Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

@module-federation/sdk

Package Overview
Dependencies
Maintainers
4
Versions
1202
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@module-federation/sdk - npm Package Compare versions

Comparing version
0.0.0-feat-apply-bundler-runtime-1702896801896
to
0.0.0-feat-await-dev-dts-20260324072937
+19
dist/_virtual/_rolldown/runtime.cjs
//#region \0rolldown/runtime.js
var __defProp = Object.defineProperty;
var __exportAll = (all, no_symbols) => {
let target = {};
for (var name in all) {
__defProp(target, name, {
get: all[name],
enumerable: true
});
}
if (!no_symbols) {
__defProp(target, Symbol.toStringTag, { value: "Module" });
}
return target;
};
//#endregion
exports.__exportAll = __exportAll;
//#region \0rolldown/runtime.js
var __defProp = Object.defineProperty;
var __exportAll = (all, no_symbols) => {
let target = {};
for (var name in all) {
__defProp(target, name, {
get: all[name],
enumerable: true
});
}
if (!no_symbols) {
__defProp(target, Symbol.toStringTag, { value: "Module" });
}
return target;
};
//#endregion
export { __exportAll };
//#region src/constant.ts
const FederationModuleManifest = "federation-manifest.json";
const MANIFEST_EXT = ".json";
const BROWSER_LOG_KEY = "FEDERATION_DEBUG";
const NameTransformSymbol = {
AT: "@",
HYPHEN: "-",
SLASH: "/"
};
const NameTransformMap = {
[NameTransformSymbol.AT]: "scope_",
[NameTransformSymbol.HYPHEN]: "_",
[NameTransformSymbol.SLASH]: "__"
};
const EncodedNameTransformMap = {
[NameTransformMap[NameTransformSymbol.AT]]: NameTransformSymbol.AT,
[NameTransformMap[NameTransformSymbol.HYPHEN]]: NameTransformSymbol.HYPHEN,
[NameTransformMap[NameTransformSymbol.SLASH]]: NameTransformSymbol.SLASH
};
const SEPARATOR = ":";
const ManifestFileName = "mf-manifest.json";
const StatsFileName = "mf-stats.json";
const MFModuleType = {
NPM: "npm",
APP: "app"
};
const MODULE_DEVTOOL_IDENTIFIER = "__MF_DEVTOOLS_MODULE_INFO__";
const ENCODE_NAME_PREFIX = "ENCODE_NAME_PREFIX";
const TEMP_DIR = ".federation";
const MFPrefetchCommon = {
identifier: "MFDataPrefetch",
globalKey: "__PREFETCH__",
library: "mf-data-prefetch",
exportsKey: "__PREFETCH_EXPORTS__",
fileName: "bootstrap.js"
};
let TreeShakingStatus = /* @__PURE__ */ function(TreeShakingStatus) {
/**
* Not handled by deploy server, needs to infer by the real runtime period.
*/
TreeShakingStatus[TreeShakingStatus["UNKNOWN"] = 1] = "UNKNOWN";
/**
* It means the shared has been calculated , runtime should take this shared as first choice.
*/
TreeShakingStatus[TreeShakingStatus["CALCULATED"] = 2] = "CALCULATED";
/**
* It means the shared has been calculated, and marked as no used
*/
TreeShakingStatus[TreeShakingStatus["NO_USE"] = 0] = "NO_USE";
return TreeShakingStatus;
}({});
//#endregion
exports.BROWSER_LOG_KEY = BROWSER_LOG_KEY;
exports.ENCODE_NAME_PREFIX = ENCODE_NAME_PREFIX;
exports.EncodedNameTransformMap = EncodedNameTransformMap;
exports.FederationModuleManifest = FederationModuleManifest;
exports.MANIFEST_EXT = MANIFEST_EXT;
exports.MFModuleType = MFModuleType;
exports.MFPrefetchCommon = MFPrefetchCommon;
exports.MODULE_DEVTOOL_IDENTIFIER = MODULE_DEVTOOL_IDENTIFIER;
exports.ManifestFileName = ManifestFileName;
exports.NameTransformMap = NameTransformMap;
exports.NameTransformSymbol = NameTransformSymbol;
exports.SEPARATOR = SEPARATOR;
exports.StatsFileName = StatsFileName;
exports.TEMP_DIR = TEMP_DIR;
exports.TreeShakingStatus = TreeShakingStatus;
//# sourceMappingURL=constant.cjs.map
{"version":3,"file":"constant.cjs","names":[],"sources":["../src/constant.ts"],"sourcesContent":["export const FederationModuleManifest = 'federation-manifest.json';\nexport const MANIFEST_EXT = '.json';\n\nexport const BROWSER_LOG_KEY = 'FEDERATION_DEBUG';\n\nexport const NameTransformSymbol = {\n AT: '@',\n HYPHEN: '-',\n SLASH: '/',\n} as const;\nexport const NameTransformMap = {\n [NameTransformSymbol.AT]: 'scope_',\n [NameTransformSymbol.HYPHEN]: '_',\n [NameTransformSymbol.SLASH]: '__',\n} as const;\n\nexport const EncodedNameTransformMap = {\n [NameTransformMap[NameTransformSymbol.AT]]: NameTransformSymbol.AT,\n [NameTransformMap[NameTransformSymbol.HYPHEN]]: NameTransformSymbol.HYPHEN,\n [NameTransformMap[NameTransformSymbol.SLASH]]: NameTransformSymbol.SLASH,\n};\n\nexport const SEPARATOR = ':';\n\nexport const ManifestFileName = 'mf-manifest.json';\nexport const StatsFileName = 'mf-stats.json';\n\nexport const MFModuleType = {\n NPM: 'npm',\n APP: 'app',\n};\n\nexport const MODULE_DEVTOOL_IDENTIFIER = '__MF_DEVTOOLS_MODULE_INFO__';\nexport const ENCODE_NAME_PREFIX = 'ENCODE_NAME_PREFIX';\nexport const TEMP_DIR = '.federation';\n\nexport const MFPrefetchCommon = {\n identifier: 'MFDataPrefetch',\n globalKey: '__PREFETCH__',\n library: 'mf-data-prefetch',\n exportsKey: '__PREFETCH_EXPORTS__',\n fileName: 'bootstrap.js',\n};\n\nexport const enum TreeShakingStatus {\n /**\n * Not handled by deploy server, needs to infer by the real runtime period.\n */\n UNKNOWN = 1,\n /**\n * It means the shared has been calculated , runtime should take this shared as first choice.\n */\n CALCULATED = 2,\n /**\n * It means the shared has been calculated, and marked as no used\n */\n NO_USE = 0,\n}\n"],"mappings":";;AAAA,MAAa,2BAA2B;AACxC,MAAa,eAAe;AAE5B,MAAa,kBAAkB;AAE/B,MAAa,sBAAsB;CACjC,IAAI;CACJ,QAAQ;CACR,OAAO;CACR;AACD,MAAa,mBAAmB;EAC7B,oBAAoB,KAAK;EACzB,oBAAoB,SAAS;EAC7B,oBAAoB,QAAQ;CAC9B;AAED,MAAa,0BAA0B;EACpC,iBAAiB,oBAAoB,MAAM,oBAAoB;EAC/D,iBAAiB,oBAAoB,UAAU,oBAAoB;EACnE,iBAAiB,oBAAoB,SAAS,oBAAoB;CACpE;AAED,MAAa,YAAY;AAEzB,MAAa,mBAAmB;AAChC,MAAa,gBAAgB;AAE7B,MAAa,eAAe;CAC1B,KAAK;CACL,KAAK;CACN;AAED,MAAa,4BAA4B;AACzC,MAAa,qBAAqB;AAClC,MAAa,WAAW;AAExB,MAAa,mBAAmB;CAC9B,YAAY;CACZ,WAAW;CACX,SAAS;CACT,YAAY;CACZ,UAAU;CACX;AAED,IAAkB,gEAAX;;;;AAIL;;;;AAIA;;;;AAIA"}
//#region src/constant.d.ts
declare const FederationModuleManifest = "federation-manifest.json";
declare const MANIFEST_EXT = ".json";
declare const BROWSER_LOG_KEY = "FEDERATION_DEBUG";
declare const NameTransformSymbol: {
readonly AT: "@";
readonly HYPHEN: "-";
readonly SLASH: "/";
};
declare const NameTransformMap: {
readonly "@": "scope_";
readonly "-": "_";
readonly "/": "__";
};
declare const EncodedNameTransformMap: {
scope_: "@";
_: "-";
__: "/";
};
declare const SEPARATOR = ":";
declare const ManifestFileName = "mf-manifest.json";
declare const StatsFileName = "mf-stats.json";
declare const MFModuleType: {
NPM: string;
APP: string;
};
declare const MODULE_DEVTOOL_IDENTIFIER = "__MF_DEVTOOLS_MODULE_INFO__";
declare const ENCODE_NAME_PREFIX = "ENCODE_NAME_PREFIX";
declare const TEMP_DIR = ".federation";
declare const MFPrefetchCommon: {
identifier: string;
globalKey: string;
library: string;
exportsKey: string;
fileName: string;
};
declare const enum TreeShakingStatus {
/**
* Not handled by deploy server, needs to infer by the real runtime period.
*/
UNKNOWN = 1,
/**
* It means the shared has been calculated , runtime should take this shared as first choice.
*/
CALCULATED = 2,
/**
* It means the shared has been calculated, and marked as no used
*/
NO_USE = 0
}
//#endregion
export { BROWSER_LOG_KEY, ENCODE_NAME_PREFIX, EncodedNameTransformMap, FederationModuleManifest, MANIFEST_EXT, MFModuleType, MFPrefetchCommon, MODULE_DEVTOOL_IDENTIFIER, ManifestFileName, NameTransformMap, NameTransformSymbol, SEPARATOR, StatsFileName, TEMP_DIR, TreeShakingStatus };
//# sourceMappingURL=constant.d.ts.map
//#region src/constant.ts
const FederationModuleManifest = "federation-manifest.json";
const MANIFEST_EXT = ".json";
const BROWSER_LOG_KEY = "FEDERATION_DEBUG";
const NameTransformSymbol = {
AT: "@",
HYPHEN: "-",
SLASH: "/"
};
const NameTransformMap = {
[NameTransformSymbol.AT]: "scope_",
[NameTransformSymbol.HYPHEN]: "_",
[NameTransformSymbol.SLASH]: "__"
};
const EncodedNameTransformMap = {
[NameTransformMap[NameTransformSymbol.AT]]: NameTransformSymbol.AT,
[NameTransformMap[NameTransformSymbol.HYPHEN]]: NameTransformSymbol.HYPHEN,
[NameTransformMap[NameTransformSymbol.SLASH]]: NameTransformSymbol.SLASH
};
const SEPARATOR = ":";
const ManifestFileName = "mf-manifest.json";
const StatsFileName = "mf-stats.json";
const MFModuleType = {
NPM: "npm",
APP: "app"
};
const MODULE_DEVTOOL_IDENTIFIER = "__MF_DEVTOOLS_MODULE_INFO__";
const ENCODE_NAME_PREFIX = "ENCODE_NAME_PREFIX";
const TEMP_DIR = ".federation";
const MFPrefetchCommon = {
identifier: "MFDataPrefetch",
globalKey: "__PREFETCH__",
library: "mf-data-prefetch",
exportsKey: "__PREFETCH_EXPORTS__",
fileName: "bootstrap.js"
};
let TreeShakingStatus = /* @__PURE__ */ function(TreeShakingStatus) {
/**
* Not handled by deploy server, needs to infer by the real runtime period.
*/
TreeShakingStatus[TreeShakingStatus["UNKNOWN"] = 1] = "UNKNOWN";
/**
* It means the shared has been calculated , runtime should take this shared as first choice.
*/
TreeShakingStatus[TreeShakingStatus["CALCULATED"] = 2] = "CALCULATED";
/**
* It means the shared has been calculated, and marked as no used
*/
TreeShakingStatus[TreeShakingStatus["NO_USE"] = 0] = "NO_USE";
return TreeShakingStatus;
}({});
//#endregion
export { BROWSER_LOG_KEY, ENCODE_NAME_PREFIX, EncodedNameTransformMap, FederationModuleManifest, MANIFEST_EXT, MFModuleType, MFPrefetchCommon, MODULE_DEVTOOL_IDENTIFIER, ManifestFileName, NameTransformMap, NameTransformSymbol, SEPARATOR, StatsFileName, TEMP_DIR, TreeShakingStatus };
//# sourceMappingURL=constant.js.map
{"version":3,"file":"constant.js","names":[],"sources":["../src/constant.ts"],"sourcesContent":["export const FederationModuleManifest = 'federation-manifest.json';\nexport const MANIFEST_EXT = '.json';\n\nexport const BROWSER_LOG_KEY = 'FEDERATION_DEBUG';\n\nexport const NameTransformSymbol = {\n AT: '@',\n HYPHEN: '-',\n SLASH: '/',\n} as const;\nexport const NameTransformMap = {\n [NameTransformSymbol.AT]: 'scope_',\n [NameTransformSymbol.HYPHEN]: '_',\n [NameTransformSymbol.SLASH]: '__',\n} as const;\n\nexport const EncodedNameTransformMap = {\n [NameTransformMap[NameTransformSymbol.AT]]: NameTransformSymbol.AT,\n [NameTransformMap[NameTransformSymbol.HYPHEN]]: NameTransformSymbol.HYPHEN,\n [NameTransformMap[NameTransformSymbol.SLASH]]: NameTransformSymbol.SLASH,\n};\n\nexport const SEPARATOR = ':';\n\nexport const ManifestFileName = 'mf-manifest.json';\nexport const StatsFileName = 'mf-stats.json';\n\nexport const MFModuleType = {\n NPM: 'npm',\n APP: 'app',\n};\n\nexport const MODULE_DEVTOOL_IDENTIFIER = '__MF_DEVTOOLS_MODULE_INFO__';\nexport const ENCODE_NAME_PREFIX = 'ENCODE_NAME_PREFIX';\nexport const TEMP_DIR = '.federation';\n\nexport const MFPrefetchCommon = {\n identifier: 'MFDataPrefetch',\n globalKey: '__PREFETCH__',\n library: 'mf-data-prefetch',\n exportsKey: '__PREFETCH_EXPORTS__',\n fileName: 'bootstrap.js',\n};\n\nexport const enum TreeShakingStatus {\n /**\n * Not handled by deploy server, needs to infer by the real runtime period.\n */\n UNKNOWN = 1,\n /**\n * It means the shared has been calculated , runtime should take this shared as first choice.\n */\n CALCULATED = 2,\n /**\n * It means the shared has been calculated, and marked as no used\n */\n NO_USE = 0,\n}\n"],"mappings":";AAAA,MAAa,2BAA2B;AACxC,MAAa,eAAe;AAE5B,MAAa,kBAAkB;AAE/B,MAAa,sBAAsB;CACjC,IAAI;CACJ,QAAQ;CACR,OAAO;CACR;AACD,MAAa,mBAAmB;EAC7B,oBAAoB,KAAK;EACzB,oBAAoB,SAAS;EAC7B,oBAAoB,QAAQ;CAC9B;AAED,MAAa,0BAA0B;EACpC,iBAAiB,oBAAoB,MAAM,oBAAoB;EAC/D,iBAAiB,oBAAoB,UAAU,oBAAoB;EACnE,iBAAiB,oBAAoB,SAAS,oBAAoB;CACpE;AAED,MAAa,YAAY;AAEzB,MAAa,mBAAmB;AAChC,MAAa,gBAAgB;AAE7B,MAAa,eAAe;CAC1B,KAAK;CACL,KAAK;CACN;AAED,MAAa,4BAA4B;AACzC,MAAa,qBAAqB;AAClC,MAAa,WAAW;AAExB,MAAa,mBAAmB;CAC9B,YAAY;CACZ,WAAW;CACX,SAAS;CACT,YAAY;CACZ,UAAU;CACX;AAED,IAAkB,gEAAX;;;;AAIL;;;;AAIA;;;;AAIA"}
//#region src/createModuleFederationConfig.ts
const createModuleFederationConfig = (options) => {
return options;
};
//#endregion
exports.createModuleFederationConfig = createModuleFederationConfig;
//# sourceMappingURL=createModuleFederationConfig.cjs.map
{"version":3,"file":"createModuleFederationConfig.cjs","names":[],"sources":["../src/createModuleFederationConfig.ts"],"sourcesContent":["import type { moduleFederationPlugin } from './types/plugins';\n\nexport const createModuleFederationConfig = (\n options: moduleFederationPlugin.ModuleFederationPluginOptions,\n): moduleFederationPlugin.ModuleFederationPluginOptions => {\n return options;\n};\n"],"mappings":";;AAEA,MAAa,gCACX,YACyD;AACzD,QAAO"}
import { ModuleFederationPluginOptions } from "./types/plugins/ModuleFederationPlugin.js";
//#region src/createModuleFederationConfig.d.ts
declare const createModuleFederationConfig: (options: ModuleFederationPluginOptions) => ModuleFederationPluginOptions;
//#endregion
export { createModuleFederationConfig };
//# sourceMappingURL=createModuleFederationConfig.d.ts.map
//#region src/createModuleFederationConfig.ts
const createModuleFederationConfig = (options) => {
return options;
};
//#endregion
export { createModuleFederationConfig };
//# sourceMappingURL=createModuleFederationConfig.js.map
{"version":3,"file":"createModuleFederationConfig.js","names":[],"sources":["../src/createModuleFederationConfig.ts"],"sourcesContent":["import type { moduleFederationPlugin } from './types/plugins';\n\nexport const createModuleFederationConfig = (\n options: moduleFederationPlugin.ModuleFederationPluginOptions,\n): moduleFederationPlugin.ModuleFederationPluginOptions => {\n return options;\n};\n"],"mappings":";AAEA,MAAa,gCACX,YACyD;AACzD,QAAO"}
const require_utils = require('./utils.cjs');
//#region src/dom.ts
async function safeWrapper(callback, disableWarn) {
try {
return await callback();
} catch (e) {
!disableWarn && require_utils.warn(e);
return;
}
}
function isStaticResourcesEqual(url1, url2) {
const REG_EXP = /^(https?:)?\/\//i;
return url1.replace(REG_EXP, "").replace(/\/$/, "") === url2.replace(REG_EXP, "").replace(/\/$/, "");
}
function createScript(info) {
let script = null;
let needAttach = true;
let timeout = 2e4;
let timeoutId;
const scripts = document.getElementsByTagName("script");
for (let i = 0; i < scripts.length; i++) {
const s = scripts[i];
const scriptSrc = s.getAttribute("src");
if (scriptSrc && isStaticResourcesEqual(scriptSrc, info.url)) {
script = s;
needAttach = false;
break;
}
}
if (!script) {
const attrs = info.attrs;
script = document.createElement("script");
script.type = attrs?.["type"] === "module" ? "module" : "text/javascript";
let createScriptRes = void 0;
if (info.createScriptHook) {
createScriptRes = info.createScriptHook(info.url, info.attrs);
if (createScriptRes instanceof HTMLScriptElement) script = createScriptRes;
else if (typeof createScriptRes === "object") {
if ("script" in createScriptRes && createScriptRes.script) script = createScriptRes.script;
if ("timeout" in createScriptRes && createScriptRes.timeout) timeout = createScriptRes.timeout;
}
}
if (!script.src) script.src = info.url;
if (attrs && !createScriptRes) Object.keys(attrs).forEach((name) => {
if (script) {
if (name === "async" || name === "defer") script[name] = attrs[name];
else if (!script.getAttribute(name)) script.setAttribute(name, attrs[name]);
}
});
}
let executionError = null;
const executionErrorHandler = typeof window !== "undefined" ? (evt) => {
if (evt.filename && isStaticResourcesEqual(evt.filename, info.url)) {
const err = /* @__PURE__ */ new Error(`ScriptExecutionError: Script "${info.url}" loaded but threw a runtime error during execution: ${evt.message} (${evt.filename}:${evt.lineno}:${evt.colno})`);
err.name = "ScriptExecutionError";
executionError = err;
}
} : null;
if (executionErrorHandler) window.addEventListener("error", executionErrorHandler);
const onScriptComplete = async (prev, event) => {
clearTimeout(timeoutId);
if (executionErrorHandler) window.removeEventListener("error", executionErrorHandler);
const onScriptCompleteCallback = () => {
if (event?.type === "error") {
const networkError = /* @__PURE__ */ new Error(`ScriptNetworkError: Failed to load script "${info.url}" - the script URL is unreachable or the server returned an error (network failure, 404, CORS, etc.)`);
networkError.name = "ScriptNetworkError";
info?.onErrorCallback && info?.onErrorCallback(networkError);
} else if (executionError) info?.onErrorCallback && info?.onErrorCallback(executionError);
else info?.cb && info?.cb();
};
if (script) {
script.onerror = null;
script.onload = null;
safeWrapper(() => {
const { needDeleteScript = true } = info;
if (needDeleteScript) script?.parentNode && script.parentNode.removeChild(script);
});
if (prev && typeof prev === "function") {
const result = prev(event);
if (result instanceof Promise) {
const res = await result;
onScriptCompleteCallback();
return res;
}
onScriptCompleteCallback();
return result;
}
}
onScriptCompleteCallback();
};
script.onerror = onScriptComplete.bind(null, script.onerror);
script.onload = onScriptComplete.bind(null, script.onload);
timeoutId = setTimeout(() => {
onScriptComplete(null, /* @__PURE__ */ new Error(`Remote script "${info.url}" time-outed.`));
}, timeout);
return {
script,
needAttach
};
}
function createLink(info) {
let link = null;
let needAttach = true;
const links = document.getElementsByTagName("link");
for (let i = 0; i < links.length; i++) {
const l = links[i];
const linkHref = l.getAttribute("href");
const linkRel = l.getAttribute("rel");
if (linkHref && isStaticResourcesEqual(linkHref, info.url) && linkRel === info.attrs["rel"]) {
link = l;
needAttach = false;
break;
}
}
if (!link) {
link = document.createElement("link");
link.setAttribute("href", info.url);
let createLinkRes = void 0;
const attrs = info.attrs;
if (info.createLinkHook) {
createLinkRes = info.createLinkHook(info.url, attrs);
if (createLinkRes instanceof HTMLLinkElement) link = createLinkRes;
}
if (attrs && !createLinkRes) Object.keys(attrs).forEach((name) => {
if (link && !link.getAttribute(name)) link.setAttribute(name, attrs[name]);
});
}
const onLinkComplete = (prev, event) => {
const onLinkCompleteCallback = () => {
if (event?.type === "error") info?.onErrorCallback && info?.onErrorCallback(event);
else info?.cb && info?.cb();
};
if (link) {
link.onerror = null;
link.onload = null;
safeWrapper(() => {
const { needDeleteLink = true } = info;
if (needDeleteLink) link?.parentNode && link.parentNode.removeChild(link);
});
if (prev) {
const res = prev(event);
onLinkCompleteCallback();
return res;
}
}
onLinkCompleteCallback();
};
link.onerror = onLinkComplete.bind(null, link.onerror);
link.onload = onLinkComplete.bind(null, link.onload);
return {
link,
needAttach
};
}
function loadScript(url, info) {
const { attrs = {}, createScriptHook } = info;
return new Promise((resolve, reject) => {
const { script, needAttach } = createScript({
url,
cb: resolve,
onErrorCallback: reject,
attrs: {
fetchpriority: "high",
...attrs
},
createScriptHook,
needDeleteScript: true
});
needAttach && document.head.appendChild(script);
});
}
//#endregion
exports.createLink = createLink;
exports.createScript = createScript;
exports.isStaticResourcesEqual = isStaticResourcesEqual;
exports.loadScript = loadScript;
exports.safeWrapper = safeWrapper;
//# sourceMappingURL=dom.cjs.map
{"version":3,"file":"dom.cjs","names":["warn"],"sources":["../src/dom.ts"],"sourcesContent":["import type { CreateScriptHookDom, CreateScriptHookReturnDom } from './types';\nimport { warn } from './utils';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport async function safeWrapper<T extends (...args: Array<any>) => any>(\n callback: T,\n disableWarn?: boolean,\n): Promise<ReturnType<T> | undefined> {\n try {\n const res = await callback();\n return res;\n } catch (e) {\n !disableWarn && warn(e);\n return;\n }\n}\n\nexport function isStaticResourcesEqual(url1: string, url2: string): boolean {\n const REG_EXP = /^(https?:)?\\/\\//i;\n // Transform url1 and url2 into relative paths\n const relativeUrl1 = url1.replace(REG_EXP, '').replace(/\\/$/, '');\n const relativeUrl2 = url2.replace(REG_EXP, '').replace(/\\/$/, '');\n // Check if the relative paths are identical\n return relativeUrl1 === relativeUrl2;\n}\n\nexport function createScript(info: {\n url: string;\n cb?: (value: void | PromiseLike<void>) => void;\n onErrorCallback?: (error: Error) => void;\n attrs?: Record<string, any>;\n needDeleteScript?: boolean;\n createScriptHook?: CreateScriptHookDom;\n}): { script: HTMLScriptElement; needAttach: boolean } {\n // Retrieve the existing script element by its src attribute\n let script: HTMLScriptElement | null = null;\n let needAttach = true;\n let timeout = 20000;\n let timeoutId: NodeJS.Timeout;\n const scripts = document.getElementsByTagName('script');\n\n for (let i = 0; i < scripts.length; i++) {\n const s = scripts[i];\n const scriptSrc = s.getAttribute('src');\n if (scriptSrc && isStaticResourcesEqual(scriptSrc, info.url)) {\n script = s;\n needAttach = false;\n break;\n }\n }\n\n if (!script) {\n const attrs = info.attrs;\n script = document.createElement('script');\n script.type = attrs?.['type'] === 'module' ? 'module' : 'text/javascript';\n let createScriptRes: CreateScriptHookReturnDom = undefined;\n if (info.createScriptHook) {\n createScriptRes = info.createScriptHook(info.url, info.attrs);\n\n if (createScriptRes instanceof HTMLScriptElement) {\n script = createScriptRes;\n } else if (typeof createScriptRes === 'object') {\n if ('script' in createScriptRes && createScriptRes.script) {\n script = createScriptRes.script;\n }\n if ('timeout' in createScriptRes && createScriptRes.timeout) {\n timeout = createScriptRes.timeout;\n }\n }\n }\n if (!script.src) {\n script.src = info.url;\n }\n if (attrs && !createScriptRes) {\n Object.keys(attrs).forEach((name) => {\n if (script) {\n if (name === 'async' || name === 'defer') {\n script[name] = attrs[name];\n // Attributes that do not exist are considered overridden\n } else if (!script.getAttribute(name)) {\n script.setAttribute(name, attrs[name]);\n }\n }\n });\n }\n }\n\n // Capture JS runtime errors thrown by this script's IIFE during execution.\n // The browser still fires onload even when the script throws, so without this\n // listener the execution error would silently become an uncaught global exception.\n let executionError: Error | null = null;\n const executionErrorHandler =\n typeof window !== 'undefined'\n ? (evt: ErrorEvent) => {\n if (evt.filename && isStaticResourcesEqual(evt.filename, info.url)) {\n const err = new Error(\n `ScriptExecutionError: Script \"${info.url}\" loaded but threw a runtime error during execution: ${evt.message} (${evt.filename}:${evt.lineno}:${evt.colno})`,\n );\n err.name = 'ScriptExecutionError';\n executionError = err;\n }\n }\n : null;\n if (executionErrorHandler) {\n window.addEventListener('error', executionErrorHandler);\n }\n\n const onScriptComplete = async (\n prev: OnErrorEventHandler | GlobalEventHandlers['onload'] | null,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n event: any,\n ): Promise<void> => {\n clearTimeout(timeoutId);\n if (executionErrorHandler) {\n window.removeEventListener('error', executionErrorHandler);\n }\n const onScriptCompleteCallback = () => {\n if (event?.type === 'error') {\n const networkError = new Error(\n `ScriptNetworkError: Failed to load script \"${info.url}\" - the script URL is unreachable or the server returned an error (network failure, 404, CORS, etc.)`,\n );\n networkError.name = 'ScriptNetworkError';\n info?.onErrorCallback && info?.onErrorCallback(networkError);\n } else if (executionError) {\n // Script fetched OK (onload fired) but IIFE threw during execution.\n info?.onErrorCallback && info?.onErrorCallback(executionError);\n } else {\n info?.cb && info?.cb();\n }\n };\n\n // Prevent memory leaks in IE.\n if (script) {\n script.onerror = null;\n script.onload = null;\n safeWrapper(() => {\n const { needDeleteScript = true } = info;\n if (needDeleteScript) {\n script?.parentNode && script.parentNode.removeChild(script);\n }\n });\n if (prev && typeof prev === 'function') {\n const result = (prev as any)(event);\n if (result instanceof Promise) {\n const res = await result;\n onScriptCompleteCallback();\n return res;\n }\n onScriptCompleteCallback();\n return result;\n }\n }\n onScriptCompleteCallback();\n };\n\n script.onerror = onScriptComplete.bind(null, script.onerror);\n script.onload = onScriptComplete.bind(null, script.onload);\n\n timeoutId = setTimeout(() => {\n onScriptComplete(\n null,\n new Error(`Remote script \"${info.url}\" time-outed.`),\n );\n }, timeout);\n\n return { script, needAttach };\n}\n\nexport function createLink(info: {\n url: string;\n cb?: (value: void | PromiseLike<void>) => void;\n onErrorCallback?: (error: Error) => void;\n attrs: Record<string, string>;\n needDeleteLink?: boolean;\n createLinkHook?: (\n url: string,\n attrs?: Record<string, any>,\n ) => HTMLLinkElement | void;\n}) {\n // <link rel=\"preload\" href=\"script.js\" as=\"script\">\n\n // Retrieve the existing script element by its src attribute\n let link: HTMLLinkElement | null = null;\n let needAttach = true;\n const links = document.getElementsByTagName('link');\n for (let i = 0; i < links.length; i++) {\n const l = links[i];\n const linkHref = l.getAttribute('href');\n const linkRel = l.getAttribute('rel');\n if (\n linkHref &&\n isStaticResourcesEqual(linkHref, info.url) &&\n linkRel === info.attrs['rel']\n ) {\n link = l;\n needAttach = false;\n break;\n }\n }\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('href', info.url);\n\n let createLinkRes: void | HTMLLinkElement = undefined;\n const attrs = info.attrs;\n\n if (info.createLinkHook) {\n createLinkRes = info.createLinkHook(info.url, attrs);\n if (createLinkRes instanceof HTMLLinkElement) {\n link = createLinkRes;\n }\n }\n\n if (attrs && !createLinkRes) {\n Object.keys(attrs).forEach((name) => {\n if (link && !link.getAttribute(name)) {\n link.setAttribute(name, attrs[name]);\n }\n });\n }\n }\n\n const onLinkComplete = (\n prev: OnErrorEventHandler | GlobalEventHandlers['onload'] | null,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n event: any,\n ): void => {\n const onLinkCompleteCallback = () => {\n if (event?.type === 'error') {\n info?.onErrorCallback && info?.onErrorCallback(event);\n } else {\n info?.cb && info?.cb();\n }\n };\n // Prevent memory leaks in IE.\n if (link) {\n link.onerror = null;\n link.onload = null;\n safeWrapper(() => {\n const { needDeleteLink = true } = info;\n if (needDeleteLink) {\n link?.parentNode && link.parentNode.removeChild(link);\n }\n });\n if (prev) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const res = (prev as any)(event);\n onLinkCompleteCallback();\n return res;\n }\n }\n onLinkCompleteCallback();\n };\n\n link.onerror = onLinkComplete.bind(null, link.onerror);\n link.onload = onLinkComplete.bind(null, link.onload);\n\n return { link, needAttach };\n}\n\nexport function loadScript(\n url: string,\n info: {\n attrs?: Record<string, any>;\n createScriptHook?: CreateScriptHookDom;\n },\n) {\n const { attrs = {}, createScriptHook } = info;\n return new Promise<void>((resolve, reject) => {\n const { script, needAttach } = createScript({\n url,\n cb: resolve,\n onErrorCallback: reject,\n attrs: {\n fetchpriority: 'high',\n ...attrs,\n },\n createScriptHook,\n needDeleteScript: true,\n });\n needAttach && document.head.appendChild(script);\n });\n}\n"],"mappings":"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"}
import { CreateScriptHookDom } from "./types/hooks.js";
//#region src/dom.d.ts
declare function safeWrapper<T extends (...args: Array<any>) => any>(callback: T, disableWarn?: boolean): Promise<ReturnType<T> | undefined>;
declare function isStaticResourcesEqual(url1: string, url2: string): boolean;
declare function createScript(info: {
url: string;
cb?: (value: void | PromiseLike<void>) => void;
onErrorCallback?: (error: Error) => void;
attrs?: Record<string, any>;
needDeleteScript?: boolean;
createScriptHook?: CreateScriptHookDom;
}): {
script: HTMLScriptElement;
needAttach: boolean;
};
declare function createLink(info: {
url: string;
cb?: (value: void | PromiseLike<void>) => void;
onErrorCallback?: (error: Error) => void;
attrs: Record<string, string>;
needDeleteLink?: boolean;
createLinkHook?: (url: string, attrs?: Record<string, any>) => HTMLLinkElement | void;
}): {
link: HTMLLinkElement;
needAttach: boolean;
};
declare function loadScript(url: string, info: {
attrs?: Record<string, any>;
createScriptHook?: CreateScriptHookDom;
}): Promise<void>;
//#endregion
export { createLink, createScript, isStaticResourcesEqual, loadScript, safeWrapper };
//# sourceMappingURL=dom.d.ts.map
import { warn } from "./utils.js";
//#region src/dom.ts
async function safeWrapper(callback, disableWarn) {
try {
return await callback();
} catch (e) {
!disableWarn && warn(e);
return;
}
}
function isStaticResourcesEqual(url1, url2) {
const REG_EXP = /^(https?:)?\/\//i;
return url1.replace(REG_EXP, "").replace(/\/$/, "") === url2.replace(REG_EXP, "").replace(/\/$/, "");
}
function createScript(info) {
let script = null;
let needAttach = true;
let timeout = 2e4;
let timeoutId;
const scripts = document.getElementsByTagName("script");
for (let i = 0; i < scripts.length; i++) {
const s = scripts[i];
const scriptSrc = s.getAttribute("src");
if (scriptSrc && isStaticResourcesEqual(scriptSrc, info.url)) {
script = s;
needAttach = false;
break;
}
}
if (!script) {
const attrs = info.attrs;
script = document.createElement("script");
script.type = attrs?.["type"] === "module" ? "module" : "text/javascript";
let createScriptRes = void 0;
if (info.createScriptHook) {
createScriptRes = info.createScriptHook(info.url, info.attrs);
if (createScriptRes instanceof HTMLScriptElement) script = createScriptRes;
else if (typeof createScriptRes === "object") {
if ("script" in createScriptRes && createScriptRes.script) script = createScriptRes.script;
if ("timeout" in createScriptRes && createScriptRes.timeout) timeout = createScriptRes.timeout;
}
}
if (!script.src) script.src = info.url;
if (attrs && !createScriptRes) Object.keys(attrs).forEach((name) => {
if (script) {
if (name === "async" || name === "defer") script[name] = attrs[name];
else if (!script.getAttribute(name)) script.setAttribute(name, attrs[name]);
}
});
}
let executionError = null;
const executionErrorHandler = typeof window !== "undefined" ? (evt) => {
if (evt.filename && isStaticResourcesEqual(evt.filename, info.url)) {
const err = /* @__PURE__ */ new Error(`ScriptExecutionError: Script "${info.url}" loaded but threw a runtime error during execution: ${evt.message} (${evt.filename}:${evt.lineno}:${evt.colno})`);
err.name = "ScriptExecutionError";
executionError = err;
}
} : null;
if (executionErrorHandler) window.addEventListener("error", executionErrorHandler);
const onScriptComplete = async (prev, event) => {
clearTimeout(timeoutId);
if (executionErrorHandler) window.removeEventListener("error", executionErrorHandler);
const onScriptCompleteCallback = () => {
if (event?.type === "error") {
const networkError = /* @__PURE__ */ new Error(`ScriptNetworkError: Failed to load script "${info.url}" - the script URL is unreachable or the server returned an error (network failure, 404, CORS, etc.)`);
networkError.name = "ScriptNetworkError";
info?.onErrorCallback && info?.onErrorCallback(networkError);
} else if (executionError) info?.onErrorCallback && info?.onErrorCallback(executionError);
else info?.cb && info?.cb();
};
if (script) {
script.onerror = null;
script.onload = null;
safeWrapper(() => {
const { needDeleteScript = true } = info;
if (needDeleteScript) script?.parentNode && script.parentNode.removeChild(script);
});
if (prev && typeof prev === "function") {
const result = prev(event);
if (result instanceof Promise) {
const res = await result;
onScriptCompleteCallback();
return res;
}
onScriptCompleteCallback();
return result;
}
}
onScriptCompleteCallback();
};
script.onerror = onScriptComplete.bind(null, script.onerror);
script.onload = onScriptComplete.bind(null, script.onload);
timeoutId = setTimeout(() => {
onScriptComplete(null, /* @__PURE__ */ new Error(`Remote script "${info.url}" time-outed.`));
}, timeout);
return {
script,
needAttach
};
}
function createLink(info) {
let link = null;
let needAttach = true;
const links = document.getElementsByTagName("link");
for (let i = 0; i < links.length; i++) {
const l = links[i];
const linkHref = l.getAttribute("href");
const linkRel = l.getAttribute("rel");
if (linkHref && isStaticResourcesEqual(linkHref, info.url) && linkRel === info.attrs["rel"]) {
link = l;
needAttach = false;
break;
}
}
if (!link) {
link = document.createElement("link");
link.setAttribute("href", info.url);
let createLinkRes = void 0;
const attrs = info.attrs;
if (info.createLinkHook) {
createLinkRes = info.createLinkHook(info.url, attrs);
if (createLinkRes instanceof HTMLLinkElement) link = createLinkRes;
}
if (attrs && !createLinkRes) Object.keys(attrs).forEach((name) => {
if (link && !link.getAttribute(name)) link.setAttribute(name, attrs[name]);
});
}
const onLinkComplete = (prev, event) => {
const onLinkCompleteCallback = () => {
if (event?.type === "error") info?.onErrorCallback && info?.onErrorCallback(event);
else info?.cb && info?.cb();
};
if (link) {
link.onerror = null;
link.onload = null;
safeWrapper(() => {
const { needDeleteLink = true } = info;
if (needDeleteLink) link?.parentNode && link.parentNode.removeChild(link);
});
if (prev) {
const res = prev(event);
onLinkCompleteCallback();
return res;
}
}
onLinkCompleteCallback();
};
link.onerror = onLinkComplete.bind(null, link.onerror);
link.onload = onLinkComplete.bind(null, link.onload);
return {
link,
needAttach
};
}
function loadScript(url, info) {
const { attrs = {}, createScriptHook } = info;
return new Promise((resolve, reject) => {
const { script, needAttach } = createScript({
url,
cb: resolve,
onErrorCallback: reject,
attrs: {
fetchpriority: "high",
...attrs
},
createScriptHook,
needDeleteScript: true
});
needAttach && document.head.appendChild(script);
});
}
//#endregion
export { createLink, createScript, isStaticResourcesEqual, loadScript, safeWrapper };
//# sourceMappingURL=dom.js.map
{"version":3,"file":"dom.js","names":[],"sources":["../src/dom.ts"],"sourcesContent":["import type { CreateScriptHookDom, CreateScriptHookReturnDom } from './types';\nimport { warn } from './utils';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport async function safeWrapper<T extends (...args: Array<any>) => any>(\n callback: T,\n disableWarn?: boolean,\n): Promise<ReturnType<T> | undefined> {\n try {\n const res = await callback();\n return res;\n } catch (e) {\n !disableWarn && warn(e);\n return;\n }\n}\n\nexport function isStaticResourcesEqual(url1: string, url2: string): boolean {\n const REG_EXP = /^(https?:)?\\/\\//i;\n // Transform url1 and url2 into relative paths\n const relativeUrl1 = url1.replace(REG_EXP, '').replace(/\\/$/, '');\n const relativeUrl2 = url2.replace(REG_EXP, '').replace(/\\/$/, '');\n // Check if the relative paths are identical\n return relativeUrl1 === relativeUrl2;\n}\n\nexport function createScript(info: {\n url: string;\n cb?: (value: void | PromiseLike<void>) => void;\n onErrorCallback?: (error: Error) => void;\n attrs?: Record<string, any>;\n needDeleteScript?: boolean;\n createScriptHook?: CreateScriptHookDom;\n}): { script: HTMLScriptElement; needAttach: boolean } {\n // Retrieve the existing script element by its src attribute\n let script: HTMLScriptElement | null = null;\n let needAttach = true;\n let timeout = 20000;\n let timeoutId: NodeJS.Timeout;\n const scripts = document.getElementsByTagName('script');\n\n for (let i = 0; i < scripts.length; i++) {\n const s = scripts[i];\n const scriptSrc = s.getAttribute('src');\n if (scriptSrc && isStaticResourcesEqual(scriptSrc, info.url)) {\n script = s;\n needAttach = false;\n break;\n }\n }\n\n if (!script) {\n const attrs = info.attrs;\n script = document.createElement('script');\n script.type = attrs?.['type'] === 'module' ? 'module' : 'text/javascript';\n let createScriptRes: CreateScriptHookReturnDom = undefined;\n if (info.createScriptHook) {\n createScriptRes = info.createScriptHook(info.url, info.attrs);\n\n if (createScriptRes instanceof HTMLScriptElement) {\n script = createScriptRes;\n } else if (typeof createScriptRes === 'object') {\n if ('script' in createScriptRes && createScriptRes.script) {\n script = createScriptRes.script;\n }\n if ('timeout' in createScriptRes && createScriptRes.timeout) {\n timeout = createScriptRes.timeout;\n }\n }\n }\n if (!script.src) {\n script.src = info.url;\n }\n if (attrs && !createScriptRes) {\n Object.keys(attrs).forEach((name) => {\n if (script) {\n if (name === 'async' || name === 'defer') {\n script[name] = attrs[name];\n // Attributes that do not exist are considered overridden\n } else if (!script.getAttribute(name)) {\n script.setAttribute(name, attrs[name]);\n }\n }\n });\n }\n }\n\n // Capture JS runtime errors thrown by this script's IIFE during execution.\n // The browser still fires onload even when the script throws, so without this\n // listener the execution error would silently become an uncaught global exception.\n let executionError: Error | null = null;\n const executionErrorHandler =\n typeof window !== 'undefined'\n ? (evt: ErrorEvent) => {\n if (evt.filename && isStaticResourcesEqual(evt.filename, info.url)) {\n const err = new Error(\n `ScriptExecutionError: Script \"${info.url}\" loaded but threw a runtime error during execution: ${evt.message} (${evt.filename}:${evt.lineno}:${evt.colno})`,\n );\n err.name = 'ScriptExecutionError';\n executionError = err;\n }\n }\n : null;\n if (executionErrorHandler) {\n window.addEventListener('error', executionErrorHandler);\n }\n\n const onScriptComplete = async (\n prev: OnErrorEventHandler | GlobalEventHandlers['onload'] | null,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n event: any,\n ): Promise<void> => {\n clearTimeout(timeoutId);\n if (executionErrorHandler) {\n window.removeEventListener('error', executionErrorHandler);\n }\n const onScriptCompleteCallback = () => {\n if (event?.type === 'error') {\n const networkError = new Error(\n `ScriptNetworkError: Failed to load script \"${info.url}\" - the script URL is unreachable or the server returned an error (network failure, 404, CORS, etc.)`,\n );\n networkError.name = 'ScriptNetworkError';\n info?.onErrorCallback && info?.onErrorCallback(networkError);\n } else if (executionError) {\n // Script fetched OK (onload fired) but IIFE threw during execution.\n info?.onErrorCallback && info?.onErrorCallback(executionError);\n } else {\n info?.cb && info?.cb();\n }\n };\n\n // Prevent memory leaks in IE.\n if (script) {\n script.onerror = null;\n script.onload = null;\n safeWrapper(() => {\n const { needDeleteScript = true } = info;\n if (needDeleteScript) {\n script?.parentNode && script.parentNode.removeChild(script);\n }\n });\n if (prev && typeof prev === 'function') {\n const result = (prev as any)(event);\n if (result instanceof Promise) {\n const res = await result;\n onScriptCompleteCallback();\n return res;\n }\n onScriptCompleteCallback();\n return result;\n }\n }\n onScriptCompleteCallback();\n };\n\n script.onerror = onScriptComplete.bind(null, script.onerror);\n script.onload = onScriptComplete.bind(null, script.onload);\n\n timeoutId = setTimeout(() => {\n onScriptComplete(\n null,\n new Error(`Remote script \"${info.url}\" time-outed.`),\n );\n }, timeout);\n\n return { script, needAttach };\n}\n\nexport function createLink(info: {\n url: string;\n cb?: (value: void | PromiseLike<void>) => void;\n onErrorCallback?: (error: Error) => void;\n attrs: Record<string, string>;\n needDeleteLink?: boolean;\n createLinkHook?: (\n url: string,\n attrs?: Record<string, any>,\n ) => HTMLLinkElement | void;\n}) {\n // <link rel=\"preload\" href=\"script.js\" as=\"script\">\n\n // Retrieve the existing script element by its src attribute\n let link: HTMLLinkElement | null = null;\n let needAttach = true;\n const links = document.getElementsByTagName('link');\n for (let i = 0; i < links.length; i++) {\n const l = links[i];\n const linkHref = l.getAttribute('href');\n const linkRel = l.getAttribute('rel');\n if (\n linkHref &&\n isStaticResourcesEqual(linkHref, info.url) &&\n linkRel === info.attrs['rel']\n ) {\n link = l;\n needAttach = false;\n break;\n }\n }\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('href', info.url);\n\n let createLinkRes: void | HTMLLinkElement = undefined;\n const attrs = info.attrs;\n\n if (info.createLinkHook) {\n createLinkRes = info.createLinkHook(info.url, attrs);\n if (createLinkRes instanceof HTMLLinkElement) {\n link = createLinkRes;\n }\n }\n\n if (attrs && !createLinkRes) {\n Object.keys(attrs).forEach((name) => {\n if (link && !link.getAttribute(name)) {\n link.setAttribute(name, attrs[name]);\n }\n });\n }\n }\n\n const onLinkComplete = (\n prev: OnErrorEventHandler | GlobalEventHandlers['onload'] | null,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n event: any,\n ): void => {\n const onLinkCompleteCallback = () => {\n if (event?.type === 'error') {\n info?.onErrorCallback && info?.onErrorCallback(event);\n } else {\n info?.cb && info?.cb();\n }\n };\n // Prevent memory leaks in IE.\n if (link) {\n link.onerror = null;\n link.onload = null;\n safeWrapper(() => {\n const { needDeleteLink = true } = info;\n if (needDeleteLink) {\n link?.parentNode && link.parentNode.removeChild(link);\n }\n });\n if (prev) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const res = (prev as any)(event);\n onLinkCompleteCallback();\n return res;\n }\n }\n onLinkCompleteCallback();\n };\n\n link.onerror = onLinkComplete.bind(null, link.onerror);\n link.onload = onLinkComplete.bind(null, link.onload);\n\n return { link, needAttach };\n}\n\nexport function loadScript(\n url: string,\n info: {\n attrs?: Record<string, any>;\n createScriptHook?: CreateScriptHookDom;\n },\n) {\n const { attrs = {}, createScriptHook } = info;\n return new Promise<void>((resolve, reject) => {\n const { script, needAttach } = createScript({\n url,\n cb: resolve,\n onErrorCallback: reject,\n attrs: {\n fetchpriority: 'high',\n ...attrs,\n },\n createScriptHook,\n needDeleteScript: true,\n });\n needAttach && document.head.appendChild(script);\n });\n}\n"],"mappings":"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"}
const require_constant = require('./constant.cjs');
//#region src/env.ts
const isBrowserEnvValue = typeof ENV_TARGET !== "undefined" ? ENV_TARGET === "web" : typeof window !== "undefined" && typeof window.document !== "undefined";
function isBrowserEnv() {
return isBrowserEnvValue;
}
function isReactNativeEnv() {
return typeof navigator !== "undefined" && navigator?.product === "ReactNative";
}
function isBrowserDebug() {
try {
if (isBrowserEnv() && window.localStorage) return Boolean(localStorage.getItem(require_constant.BROWSER_LOG_KEY));
} catch (error) {
return false;
}
return false;
}
function isDebugMode() {
if (typeof process !== "undefined" && process.env && process.env["FEDERATION_DEBUG"]) return Boolean(process.env["FEDERATION_DEBUG"]);
if (typeof FEDERATION_DEBUG !== "undefined" && Boolean(FEDERATION_DEBUG)) return true;
return isBrowserDebug();
}
const getProcessEnv = function() {
return typeof process !== "undefined" && process.env ? process.env : {};
};
//#endregion
exports.getProcessEnv = getProcessEnv;
exports.isBrowserEnv = isBrowserEnv;
exports.isBrowserEnvValue = isBrowserEnvValue;
exports.isDebugMode = isDebugMode;
exports.isReactNativeEnv = isReactNativeEnv;
//# sourceMappingURL=env.cjs.map
{"version":3,"file":"env.cjs","names":["BROWSER_LOG_KEY"],"sources":["../src/env.ts"],"sourcesContent":["import { BROWSER_LOG_KEY } from './constant';\n\ndeclare global {\n // eslint-disable-next-line no-var\n var FEDERATION_DEBUG: string | undefined;\n}\n\n// Declare the ENV_TARGET constant that will be defined by DefinePlugin\ndeclare const ENV_TARGET: 'web' | 'node';\n\nconst isBrowserEnvValue =\n typeof ENV_TARGET !== 'undefined'\n ? ENV_TARGET === 'web'\n : typeof window !== 'undefined' && typeof window.document !== 'undefined';\n\nfunction isBrowserEnv(): boolean {\n return isBrowserEnvValue;\n}\n\nfunction isReactNativeEnv(): boolean {\n return (\n typeof navigator !== 'undefined' && navigator?.product === 'ReactNative'\n );\n}\n\nfunction isBrowserDebug() {\n try {\n if (isBrowserEnv() && window.localStorage) {\n return Boolean(localStorage.getItem(BROWSER_LOG_KEY));\n }\n } catch (error) {\n return false;\n }\n return false;\n}\n\nfunction isDebugMode(): boolean {\n if (\n typeof process !== 'undefined' &&\n process.env &&\n process.env['FEDERATION_DEBUG']\n ) {\n return Boolean(process.env['FEDERATION_DEBUG']);\n }\n\n if (typeof FEDERATION_DEBUG !== 'undefined' && Boolean(FEDERATION_DEBUG)) {\n return true;\n }\n\n return isBrowserDebug();\n}\n\nconst getProcessEnv = function (): Record<string, string | undefined> {\n return typeof process !== 'undefined' && process.env ? process.env : {};\n};\n\nexport {\n isBrowserEnv,\n isBrowserEnvValue,\n isReactNativeEnv,\n isDebugMode,\n getProcessEnv,\n};\n"],"mappings":";;;AAUA,MAAM,oBACJ,OAAO,eAAe,cAClB,eAAe,QACf,OAAO,WAAW,eAAe,OAAO,OAAO,aAAa;AAElE,SAAS,eAAwB;AAC/B,QAAO;;AAGT,SAAS,mBAA4B;AACnC,QACE,OAAO,cAAc,eAAe,WAAW,YAAY;;AAI/D,SAAS,iBAAiB;AACxB,KAAI;AACF,MAAI,cAAc,IAAI,OAAO,aAC3B,QAAO,QAAQ,aAAa,QAAQA,iCAAgB,CAAC;UAEhD,OAAO;AACd,SAAO;;AAET,QAAO;;AAGT,SAAS,cAAuB;AAC9B,KACE,OAAO,YAAY,eACnB,QAAQ,OACR,QAAQ,IAAI,oBAEZ,QAAO,QAAQ,QAAQ,IAAI,oBAAoB;AAGjD,KAAI,OAAO,qBAAqB,eAAe,QAAQ,iBAAiB,CACtE,QAAO;AAGT,QAAO,gBAAgB;;AAGzB,MAAM,gBAAgB,WAAgD;AACpE,QAAO,OAAO,YAAY,eAAe,QAAQ,MAAM,QAAQ,MAAM,EAAE"}
//#region src/env.d.ts
declare global {
var FEDERATION_DEBUG: string | undefined;
}
declare const isBrowserEnvValue: boolean;
declare function isBrowserEnv(): boolean;
declare function isReactNativeEnv(): boolean;
declare function isDebugMode(): boolean;
declare const getProcessEnv: () => Record<string, string | undefined>;
//#endregion
export { getProcessEnv, isBrowserEnv, isBrowserEnvValue, isDebugMode, isReactNativeEnv };
//# sourceMappingURL=env.d.ts.map
import { BROWSER_LOG_KEY } from "./constant.js";
//#region src/env.ts
const isBrowserEnvValue = typeof ENV_TARGET !== "undefined" ? ENV_TARGET === "web" : typeof window !== "undefined" && typeof window.document !== "undefined";
function isBrowserEnv() {
return isBrowserEnvValue;
}
function isReactNativeEnv() {
return typeof navigator !== "undefined" && navigator?.product === "ReactNative";
}
function isBrowserDebug() {
try {
if (isBrowserEnv() && window.localStorage) return Boolean(localStorage.getItem(BROWSER_LOG_KEY));
} catch (error) {
return false;
}
return false;
}
function isDebugMode() {
if (typeof process !== "undefined" && process.env && process.env["FEDERATION_DEBUG"]) return Boolean(process.env["FEDERATION_DEBUG"]);
if (typeof FEDERATION_DEBUG !== "undefined" && Boolean(FEDERATION_DEBUG)) return true;
return isBrowserDebug();
}
const getProcessEnv = function() {
return typeof process !== "undefined" && process.env ? process.env : {};
};
//#endregion
export { getProcessEnv, isBrowserEnv, isBrowserEnvValue, isDebugMode, isReactNativeEnv };
//# sourceMappingURL=env.js.map
{"version":3,"file":"env.js","names":[],"sources":["../src/env.ts"],"sourcesContent":["import { BROWSER_LOG_KEY } from './constant';\n\ndeclare global {\n // eslint-disable-next-line no-var\n var FEDERATION_DEBUG: string | undefined;\n}\n\n// Declare the ENV_TARGET constant that will be defined by DefinePlugin\ndeclare const ENV_TARGET: 'web' | 'node';\n\nconst isBrowserEnvValue =\n typeof ENV_TARGET !== 'undefined'\n ? ENV_TARGET === 'web'\n : typeof window !== 'undefined' && typeof window.document !== 'undefined';\n\nfunction isBrowserEnv(): boolean {\n return isBrowserEnvValue;\n}\n\nfunction isReactNativeEnv(): boolean {\n return (\n typeof navigator !== 'undefined' && navigator?.product === 'ReactNative'\n );\n}\n\nfunction isBrowserDebug() {\n try {\n if (isBrowserEnv() && window.localStorage) {\n return Boolean(localStorage.getItem(BROWSER_LOG_KEY));\n }\n } catch (error) {\n return false;\n }\n return false;\n}\n\nfunction isDebugMode(): boolean {\n if (\n typeof process !== 'undefined' &&\n process.env &&\n process.env['FEDERATION_DEBUG']\n ) {\n return Boolean(process.env['FEDERATION_DEBUG']);\n }\n\n if (typeof FEDERATION_DEBUG !== 'undefined' && Boolean(FEDERATION_DEBUG)) {\n return true;\n }\n\n return isBrowserDebug();\n}\n\nconst getProcessEnv = function (): Record<string, string | undefined> {\n return typeof process !== 'undefined' && process.env ? process.env : {};\n};\n\nexport {\n isBrowserEnv,\n isBrowserEnvValue,\n isReactNativeEnv,\n isDebugMode,\n getProcessEnv,\n};\n"],"mappings":";;;AAUA,MAAM,oBACJ,OAAO,eAAe,cAClB,eAAe,QACf,OAAO,WAAW,eAAe,OAAO,OAAO,aAAa;AAElE,SAAS,eAAwB;AAC/B,QAAO;;AAGT,SAAS,mBAA4B;AACnC,QACE,OAAO,cAAc,eAAe,WAAW,YAAY;;AAI/D,SAAS,iBAAiB;AACxB,KAAI;AACF,MAAI,cAAc,IAAI,OAAO,aAC3B,QAAO,QAAQ,aAAa,QAAQ,gBAAgB,CAAC;UAEhD,OAAO;AACd,SAAO;;AAET,QAAO;;AAGT,SAAS,cAAuB;AAC9B,KACE,OAAO,YAAY,eACnB,QAAQ,OACR,QAAQ,IAAI,oBAEZ,QAAO,QAAQ,QAAQ,IAAI,oBAAoB;AAGjD,KAAI,OAAO,qBAAqB,eAAe,QAAQ,iBAAiB,CACtE,QAAO;AAGT,QAAO,gBAAgB;;AAGzB,MAAM,gBAAgB,WAAgD;AACpE,QAAO,OAAO,YAAY,eAAe,QAAQ,MAAM,QAAQ,MAAM,EAAE"}
const require_constant = require('./constant.cjs');
//#region src/generateSnapshotFromManifest.ts
const simpleJoinRemoteEntry = (rPath, rName) => {
if (!rPath) return rName;
const transformPath = (str) => {
if (str === ".") return "";
if (str.startsWith("./")) return str.replace("./", "");
if (str.startsWith("/")) {
const strWithoutSlash = str.slice(1);
if (strWithoutSlash.endsWith("/")) return strWithoutSlash.slice(0, -1);
return strWithoutSlash;
}
return str;
};
const transformedPath = transformPath(rPath);
if (!transformedPath) return rName;
if (transformedPath.endsWith("/")) return `${transformedPath}${rName}`;
return `${transformedPath}/${rName}`;
};
function inferAutoPublicPath(url) {
return url.replace(/#.*$/, "").replace(/\?.*$/, "").replace(/\/[^\/]+$/, "/");
}
function generateSnapshotFromManifest(manifest, options = {}) {
const { remotes = {}, overrides = {}, version } = options;
let remoteSnapshot;
const getPublicPath = () => {
if ("publicPath" in manifest.metaData) {
if ((manifest.metaData.publicPath === "auto" || manifest.metaData.publicPath === "") && version) return inferAutoPublicPath(version);
return manifest.metaData.publicPath;
} else return manifest.metaData.getPublicPath;
};
const overridesKeys = Object.keys(overrides);
let remotesInfo = {};
if (!Object.keys(remotes).length) remotesInfo = manifest.remotes?.reduce((res, next) => {
let matchedVersion;
const name = next.federationContainerName;
if (overridesKeys.includes(name)) matchedVersion = overrides[name];
else if ("version" in next) matchedVersion = next.version;
else matchedVersion = next.entry;
res[name] = { matchedVersion };
return res;
}, {}) || {};
Object.keys(remotes).forEach((key) => remotesInfo[key] = { matchedVersion: overridesKeys.includes(key) ? overrides[key] : remotes[key] });
const { remoteEntry: { path: remoteEntryPath, name: remoteEntryName, type: remoteEntryType }, types: remoteTypes = {
path: "",
name: "",
zip: "",
api: ""
}, buildInfo: { buildVersion }, globalName, ssrRemoteEntry } = manifest.metaData;
const { exposes } = manifest;
let basicRemoteSnapshot = {
version: version ? version : "",
buildVersion,
globalName,
remoteEntry: simpleJoinRemoteEntry(remoteEntryPath, remoteEntryName),
remoteEntryType,
remoteTypes: simpleJoinRemoteEntry(remoteTypes.path, remoteTypes.name),
remoteTypesZip: remoteTypes.zip || "",
remoteTypesAPI: remoteTypes.api || "",
remotesInfo,
shared: manifest?.shared.map((item) => ({
assets: item.assets,
sharedName: item.name,
version: item.version,
usedExports: item.referenceExports || []
})),
modules: exposes?.map((expose) => ({
moduleName: expose.name,
modulePath: expose.path,
assets: expose.assets
}))
};
if (manifest.metaData?.prefetchInterface) {
const prefetchInterface = manifest.metaData.prefetchInterface;
basicRemoteSnapshot = {
...basicRemoteSnapshot,
prefetchInterface
};
}
if (manifest.metaData?.prefetchEntry) {
const { path, name, type } = manifest.metaData.prefetchEntry;
basicRemoteSnapshot = {
...basicRemoteSnapshot,
prefetchEntry: simpleJoinRemoteEntry(path, name),
prefetchEntryType: type
};
}
if ("publicPath" in manifest.metaData) {
remoteSnapshot = {
...basicRemoteSnapshot,
publicPath: getPublicPath()
};
if (typeof manifest.metaData.ssrPublicPath === "string") remoteSnapshot.ssrPublicPath = manifest.metaData.ssrPublicPath;
} else remoteSnapshot = {
...basicRemoteSnapshot,
getPublicPath: getPublicPath()
};
if (ssrRemoteEntry) {
const fullSSRRemoteEntry = simpleJoinRemoteEntry(ssrRemoteEntry.path, ssrRemoteEntry.name);
remoteSnapshot.ssrRemoteEntry = fullSSRRemoteEntry;
remoteSnapshot.ssrRemoteEntryType = ssrRemoteEntry.type || "commonjs-module";
}
return remoteSnapshot;
}
function isManifestProvider(moduleInfo) {
if ("remoteEntry" in moduleInfo && moduleInfo.remoteEntry.includes(require_constant.MANIFEST_EXT)) return true;
else return false;
}
function getManifestFileName(manifestOptions) {
if (!manifestOptions) return {
statsFileName: require_constant.StatsFileName,
manifestFileName: require_constant.ManifestFileName
};
let filePath = typeof manifestOptions === "boolean" ? "" : manifestOptions.filePath || "";
let fileName = typeof manifestOptions === "boolean" ? "" : manifestOptions.fileName || "";
const JSON_EXT = ".json";
const addExt = (name) => {
if (name.endsWith(JSON_EXT)) return name;
return `${name}${JSON_EXT}`;
};
const insertSuffix = (name, suffix) => {
return name.replace(JSON_EXT, `${suffix}${JSON_EXT}`);
};
const manifestFileName = fileName ? addExt(fileName) : require_constant.ManifestFileName;
return {
statsFileName: simpleJoinRemoteEntry(filePath, fileName ? insertSuffix(manifestFileName, "-stats") : require_constant.StatsFileName),
manifestFileName: simpleJoinRemoteEntry(filePath, manifestFileName)
};
}
//#endregion
exports.generateSnapshotFromManifest = generateSnapshotFromManifest;
exports.getManifestFileName = getManifestFileName;
exports.inferAutoPublicPath = inferAutoPublicPath;
exports.isManifestProvider = isManifestProvider;
exports.simpleJoinRemoteEntry = simpleJoinRemoteEntry;
//# sourceMappingURL=generateSnapshotFromManifest.cjs.map
{"version":3,"file":"generateSnapshotFromManifest.cjs","names":["MANIFEST_EXT","StatsFileName","ManifestFileName"],"sources":["../src/generateSnapshotFromManifest.ts"],"sourcesContent":["import {\n Manifest,\n ProviderModuleInfo,\n ModuleInfo,\n BasicProviderModuleInfo,\n ConsumerModuleInfo,\n ManifestProvider,\n moduleFederationPlugin,\n} from './types';\nimport { MANIFEST_EXT, ManifestFileName, StatsFileName } from './constant';\n\ninterface IOptions {\n remotes?: Record<string, string>;\n overrides?: Record<string, string>;\n version?: string;\n}\n\nexport const simpleJoinRemoteEntry = (rPath: string, rName: string): string => {\n if (!rPath) {\n return rName;\n }\n const transformPath = (str: string) => {\n if (str === '.') {\n return '';\n }\n if (str.startsWith('./')) {\n return str.replace('./', '');\n }\n if (str.startsWith('/')) {\n const strWithoutSlash = str.slice(1);\n if (strWithoutSlash.endsWith('/')) {\n return strWithoutSlash.slice(0, -1);\n }\n return strWithoutSlash;\n }\n return str;\n };\n\n const transformedPath = transformPath(rPath);\n\n if (!transformedPath) {\n return rName;\n }\n\n if (transformedPath.endsWith('/')) {\n return `${transformedPath}${rName}`;\n }\n\n return `${transformedPath}/${rName}`;\n};\n\nexport function inferAutoPublicPath(url: string): string {\n return url\n .replace(/#.*$/, '')\n .replace(/\\?.*$/, '')\n .replace(/\\/[^\\/]+$/, '/');\n}\n\n// Priority: overrides > remotes\n// eslint-disable-next-line max-lines-per-function\nexport function generateSnapshotFromManifest(\n manifest: Manifest,\n options: IOptions = {},\n): ProviderModuleInfo {\n const { remotes = {}, overrides = {}, version } = options;\n let remoteSnapshot: ProviderModuleInfo;\n\n const getPublicPath = (): string => {\n if ('publicPath' in manifest.metaData) {\n if (\n (manifest.metaData.publicPath === 'auto' ||\n manifest.metaData.publicPath === '') &&\n version\n ) {\n // use same implementation as publicPath auto runtime module implements\n return inferAutoPublicPath(version);\n }\n return manifest.metaData.publicPath;\n } else {\n return manifest.metaData.getPublicPath;\n }\n };\n\n const overridesKeys = Object.keys(overrides);\n\n let remotesInfo: ConsumerModuleInfo['remotesInfo'] = {};\n\n // If remotes are not provided, only the remotes in the manifest will be read\n if (!Object.keys(remotes).length) {\n remotesInfo =\n manifest.remotes?.reduce(\n (res, next) => {\n let matchedVersion: string;\n const name = next.federationContainerName;\n // overrides have higher priority\n if (overridesKeys.includes(name)) {\n matchedVersion = overrides[name];\n } else {\n if ('version' in next) {\n matchedVersion = next.version;\n } else {\n matchedVersion = next.entry;\n }\n }\n res[name] = {\n matchedVersion,\n };\n return res;\n },\n {} as ConsumerModuleInfo['remotesInfo'],\n ) || {};\n }\n\n // If remotes (deploy scenario) are specified, they need to be traversed again\n Object.keys(remotes).forEach(\n (key) =>\n (remotesInfo[key] = {\n // overrides will override dependencies\n matchedVersion: overridesKeys.includes(key)\n ? overrides[key]\n : remotes[key],\n }),\n );\n\n const {\n remoteEntry: {\n path: remoteEntryPath,\n name: remoteEntryName,\n type: remoteEntryType,\n },\n types: remoteTypes = { path: '', name: '', zip: '', api: '' },\n buildInfo: { buildVersion },\n globalName,\n ssrRemoteEntry,\n } = manifest.metaData;\n const { exposes } = manifest;\n\n let basicRemoteSnapshot: BasicProviderModuleInfo = {\n version: version ? version : '',\n buildVersion,\n globalName,\n remoteEntry: simpleJoinRemoteEntry(remoteEntryPath, remoteEntryName),\n remoteEntryType,\n remoteTypes: simpleJoinRemoteEntry(remoteTypes.path, remoteTypes.name),\n remoteTypesZip: remoteTypes.zip || '',\n remoteTypesAPI: remoteTypes.api || '',\n remotesInfo,\n shared: manifest?.shared.map((item) => ({\n assets: item.assets,\n sharedName: item.name,\n version: item.version,\n // @ts-ignore\n usedExports: item.referenceExports || [],\n })),\n modules: exposes?.map((expose) => ({\n moduleName: expose.name,\n modulePath: expose.path,\n assets: expose.assets,\n })),\n };\n\n if (manifest.metaData?.prefetchInterface) {\n const prefetchInterface = manifest.metaData.prefetchInterface;\n\n basicRemoteSnapshot = {\n ...basicRemoteSnapshot,\n prefetchInterface,\n };\n }\n\n if (manifest.metaData?.prefetchEntry) {\n const { path, name, type } = manifest.metaData.prefetchEntry;\n\n basicRemoteSnapshot = {\n ...basicRemoteSnapshot,\n prefetchEntry: simpleJoinRemoteEntry(path, name),\n prefetchEntryType: type,\n };\n }\n\n if ('publicPath' in manifest.metaData) {\n remoteSnapshot = {\n ...basicRemoteSnapshot,\n publicPath: getPublicPath(),\n };\n if (typeof manifest.metaData.ssrPublicPath === 'string') {\n remoteSnapshot.ssrPublicPath = manifest.metaData.ssrPublicPath;\n }\n } else {\n remoteSnapshot = {\n ...basicRemoteSnapshot,\n getPublicPath: getPublicPath(),\n };\n }\n\n if (ssrRemoteEntry) {\n const fullSSRRemoteEntry = simpleJoinRemoteEntry(\n ssrRemoteEntry.path,\n ssrRemoteEntry.name,\n );\n remoteSnapshot.ssrRemoteEntry = fullSSRRemoteEntry;\n remoteSnapshot.ssrRemoteEntryType =\n ssrRemoteEntry.type || 'commonjs-module';\n }\n\n return remoteSnapshot;\n}\n\nexport function isManifestProvider(\n moduleInfo: ModuleInfo | ManifestProvider,\n): moduleInfo is ManifestProvider {\n if (\n 'remoteEntry' in moduleInfo &&\n moduleInfo.remoteEntry.includes(MANIFEST_EXT)\n ) {\n return true;\n } else {\n return false;\n }\n}\n\nexport function getManifestFileName(\n manifestOptions?: moduleFederationPlugin.ModuleFederationPluginOptions['manifest'],\n): {\n statsFileName: string;\n manifestFileName: string;\n} {\n if (!manifestOptions) {\n return {\n statsFileName: StatsFileName,\n manifestFileName: ManifestFileName,\n };\n }\n\n let filePath =\n typeof manifestOptions === 'boolean' ? '' : manifestOptions.filePath || '';\n let fileName =\n typeof manifestOptions === 'boolean' ? '' : manifestOptions.fileName || '';\n\n const JSON_EXT = '.json';\n const addExt = (name: string): string => {\n if (name.endsWith(JSON_EXT)) {\n return name;\n }\n return `${name}${JSON_EXT}`;\n };\n const insertSuffix = (name: string, suffix: string): string => {\n return name.replace(JSON_EXT, `${suffix}${JSON_EXT}`);\n };\n const manifestFileName = fileName ? addExt(fileName) : ManifestFileName;\n const statsFileName = fileName\n ? insertSuffix(manifestFileName, '-stats')\n : StatsFileName;\n\n return {\n statsFileName: simpleJoinRemoteEntry(filePath, statsFileName),\n manifestFileName: simpleJoinRemoteEntry(filePath, manifestFileName),\n };\n}\n"],"mappings":"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"}
import { Manifest } from "./types/manifest.js";
import { ManifestProvider, ModuleInfo, ProviderModuleInfo } from "./types/snapshot.js";
import { ModuleFederationPluginOptions } from "./types/plugins/ModuleFederationPlugin.js";
//#region src/generateSnapshotFromManifest.d.ts
interface IOptions {
remotes?: Record<string, string>;
overrides?: Record<string, string>;
version?: string;
}
declare const simpleJoinRemoteEntry: (rPath: string, rName: string) => string;
declare function inferAutoPublicPath(url: string): string;
declare function generateSnapshotFromManifest(manifest: Manifest, options?: IOptions): ProviderModuleInfo;
declare function isManifestProvider(moduleInfo: ModuleInfo | ManifestProvider): moduleInfo is ManifestProvider;
declare function getManifestFileName(manifestOptions?: ModuleFederationPluginOptions['manifest']): {
statsFileName: string;
manifestFileName: string;
};
//#endregion
export { generateSnapshotFromManifest, getManifestFileName, inferAutoPublicPath, isManifestProvider, simpleJoinRemoteEntry };
//# sourceMappingURL=generateSnapshotFromManifest.d.ts.map
import { MANIFEST_EXT, ManifestFileName, StatsFileName } from "./constant.js";
//#region src/generateSnapshotFromManifest.ts
const simpleJoinRemoteEntry = (rPath, rName) => {
if (!rPath) return rName;
const transformPath = (str) => {
if (str === ".") return "";
if (str.startsWith("./")) return str.replace("./", "");
if (str.startsWith("/")) {
const strWithoutSlash = str.slice(1);
if (strWithoutSlash.endsWith("/")) return strWithoutSlash.slice(0, -1);
return strWithoutSlash;
}
return str;
};
const transformedPath = transformPath(rPath);
if (!transformedPath) return rName;
if (transformedPath.endsWith("/")) return `${transformedPath}${rName}`;
return `${transformedPath}/${rName}`;
};
function inferAutoPublicPath(url) {
return url.replace(/#.*$/, "").replace(/\?.*$/, "").replace(/\/[^\/]+$/, "/");
}
function generateSnapshotFromManifest(manifest, options = {}) {
const { remotes = {}, overrides = {}, version } = options;
let remoteSnapshot;
const getPublicPath = () => {
if ("publicPath" in manifest.metaData) {
if ((manifest.metaData.publicPath === "auto" || manifest.metaData.publicPath === "") && version) return inferAutoPublicPath(version);
return manifest.metaData.publicPath;
} else return manifest.metaData.getPublicPath;
};
const overridesKeys = Object.keys(overrides);
let remotesInfo = {};
if (!Object.keys(remotes).length) remotesInfo = manifest.remotes?.reduce((res, next) => {
let matchedVersion;
const name = next.federationContainerName;
if (overridesKeys.includes(name)) matchedVersion = overrides[name];
else if ("version" in next) matchedVersion = next.version;
else matchedVersion = next.entry;
res[name] = { matchedVersion };
return res;
}, {}) || {};
Object.keys(remotes).forEach((key) => remotesInfo[key] = { matchedVersion: overridesKeys.includes(key) ? overrides[key] : remotes[key] });
const { remoteEntry: { path: remoteEntryPath, name: remoteEntryName, type: remoteEntryType }, types: remoteTypes = {
path: "",
name: "",
zip: "",
api: ""
}, buildInfo: { buildVersion }, globalName, ssrRemoteEntry } = manifest.metaData;
const { exposes } = manifest;
let basicRemoteSnapshot = {
version: version ? version : "",
buildVersion,
globalName,
remoteEntry: simpleJoinRemoteEntry(remoteEntryPath, remoteEntryName),
remoteEntryType,
remoteTypes: simpleJoinRemoteEntry(remoteTypes.path, remoteTypes.name),
remoteTypesZip: remoteTypes.zip || "",
remoteTypesAPI: remoteTypes.api || "",
remotesInfo,
shared: manifest?.shared.map((item) => ({
assets: item.assets,
sharedName: item.name,
version: item.version,
usedExports: item.referenceExports || []
})),
modules: exposes?.map((expose) => ({
moduleName: expose.name,
modulePath: expose.path,
assets: expose.assets
}))
};
if (manifest.metaData?.prefetchInterface) {
const prefetchInterface = manifest.metaData.prefetchInterface;
basicRemoteSnapshot = {
...basicRemoteSnapshot,
prefetchInterface
};
}
if (manifest.metaData?.prefetchEntry) {
const { path, name, type } = manifest.metaData.prefetchEntry;
basicRemoteSnapshot = {
...basicRemoteSnapshot,
prefetchEntry: simpleJoinRemoteEntry(path, name),
prefetchEntryType: type
};
}
if ("publicPath" in manifest.metaData) {
remoteSnapshot = {
...basicRemoteSnapshot,
publicPath: getPublicPath()
};
if (typeof manifest.metaData.ssrPublicPath === "string") remoteSnapshot.ssrPublicPath = manifest.metaData.ssrPublicPath;
} else remoteSnapshot = {
...basicRemoteSnapshot,
getPublicPath: getPublicPath()
};
if (ssrRemoteEntry) {
const fullSSRRemoteEntry = simpleJoinRemoteEntry(ssrRemoteEntry.path, ssrRemoteEntry.name);
remoteSnapshot.ssrRemoteEntry = fullSSRRemoteEntry;
remoteSnapshot.ssrRemoteEntryType = ssrRemoteEntry.type || "commonjs-module";
}
return remoteSnapshot;
}
function isManifestProvider(moduleInfo) {
if ("remoteEntry" in moduleInfo && moduleInfo.remoteEntry.includes(MANIFEST_EXT)) return true;
else return false;
}
function getManifestFileName(manifestOptions) {
if (!manifestOptions) return {
statsFileName: StatsFileName,
manifestFileName: ManifestFileName
};
let filePath = typeof manifestOptions === "boolean" ? "" : manifestOptions.filePath || "";
let fileName = typeof manifestOptions === "boolean" ? "" : manifestOptions.fileName || "";
const JSON_EXT = ".json";
const addExt = (name) => {
if (name.endsWith(JSON_EXT)) return name;
return `${name}${JSON_EXT}`;
};
const insertSuffix = (name, suffix) => {
return name.replace(JSON_EXT, `${suffix}${JSON_EXT}`);
};
const manifestFileName = fileName ? addExt(fileName) : ManifestFileName;
return {
statsFileName: simpleJoinRemoteEntry(filePath, fileName ? insertSuffix(manifestFileName, "-stats") : StatsFileName),
manifestFileName: simpleJoinRemoteEntry(filePath, manifestFileName)
};
}
//#endregion
export { generateSnapshotFromManifest, getManifestFileName, inferAutoPublicPath, isManifestProvider, simpleJoinRemoteEntry };
//# sourceMappingURL=generateSnapshotFromManifest.js.map
{"version":3,"file":"generateSnapshotFromManifest.js","names":[],"sources":["../src/generateSnapshotFromManifest.ts"],"sourcesContent":["import {\n Manifest,\n ProviderModuleInfo,\n ModuleInfo,\n BasicProviderModuleInfo,\n ConsumerModuleInfo,\n ManifestProvider,\n moduleFederationPlugin,\n} from './types';\nimport { MANIFEST_EXT, ManifestFileName, StatsFileName } from './constant';\n\ninterface IOptions {\n remotes?: Record<string, string>;\n overrides?: Record<string, string>;\n version?: string;\n}\n\nexport const simpleJoinRemoteEntry = (rPath: string, rName: string): string => {\n if (!rPath) {\n return rName;\n }\n const transformPath = (str: string) => {\n if (str === '.') {\n return '';\n }\n if (str.startsWith('./')) {\n return str.replace('./', '');\n }\n if (str.startsWith('/')) {\n const strWithoutSlash = str.slice(1);\n if (strWithoutSlash.endsWith('/')) {\n return strWithoutSlash.slice(0, -1);\n }\n return strWithoutSlash;\n }\n return str;\n };\n\n const transformedPath = transformPath(rPath);\n\n if (!transformedPath) {\n return rName;\n }\n\n if (transformedPath.endsWith('/')) {\n return `${transformedPath}${rName}`;\n }\n\n return `${transformedPath}/${rName}`;\n};\n\nexport function inferAutoPublicPath(url: string): string {\n return url\n .replace(/#.*$/, '')\n .replace(/\\?.*$/, '')\n .replace(/\\/[^\\/]+$/, '/');\n}\n\n// Priority: overrides > remotes\n// eslint-disable-next-line max-lines-per-function\nexport function generateSnapshotFromManifest(\n manifest: Manifest,\n options: IOptions = {},\n): ProviderModuleInfo {\n const { remotes = {}, overrides = {}, version } = options;\n let remoteSnapshot: ProviderModuleInfo;\n\n const getPublicPath = (): string => {\n if ('publicPath' in manifest.metaData) {\n if (\n (manifest.metaData.publicPath === 'auto' ||\n manifest.metaData.publicPath === '') &&\n version\n ) {\n // use same implementation as publicPath auto runtime module implements\n return inferAutoPublicPath(version);\n }\n return manifest.metaData.publicPath;\n } else {\n return manifest.metaData.getPublicPath;\n }\n };\n\n const overridesKeys = Object.keys(overrides);\n\n let remotesInfo: ConsumerModuleInfo['remotesInfo'] = {};\n\n // If remotes are not provided, only the remotes in the manifest will be read\n if (!Object.keys(remotes).length) {\n remotesInfo =\n manifest.remotes?.reduce(\n (res, next) => {\n let matchedVersion: string;\n const name = next.federationContainerName;\n // overrides have higher priority\n if (overridesKeys.includes(name)) {\n matchedVersion = overrides[name];\n } else {\n if ('version' in next) {\n matchedVersion = next.version;\n } else {\n matchedVersion = next.entry;\n }\n }\n res[name] = {\n matchedVersion,\n };\n return res;\n },\n {} as ConsumerModuleInfo['remotesInfo'],\n ) || {};\n }\n\n // If remotes (deploy scenario) are specified, they need to be traversed again\n Object.keys(remotes).forEach(\n (key) =>\n (remotesInfo[key] = {\n // overrides will override dependencies\n matchedVersion: overridesKeys.includes(key)\n ? overrides[key]\n : remotes[key],\n }),\n );\n\n const {\n remoteEntry: {\n path: remoteEntryPath,\n name: remoteEntryName,\n type: remoteEntryType,\n },\n types: remoteTypes = { path: '', name: '', zip: '', api: '' },\n buildInfo: { buildVersion },\n globalName,\n ssrRemoteEntry,\n } = manifest.metaData;\n const { exposes } = manifest;\n\n let basicRemoteSnapshot: BasicProviderModuleInfo = {\n version: version ? version : '',\n buildVersion,\n globalName,\n remoteEntry: simpleJoinRemoteEntry(remoteEntryPath, remoteEntryName),\n remoteEntryType,\n remoteTypes: simpleJoinRemoteEntry(remoteTypes.path, remoteTypes.name),\n remoteTypesZip: remoteTypes.zip || '',\n remoteTypesAPI: remoteTypes.api || '',\n remotesInfo,\n shared: manifest?.shared.map((item) => ({\n assets: item.assets,\n sharedName: item.name,\n version: item.version,\n // @ts-ignore\n usedExports: item.referenceExports || [],\n })),\n modules: exposes?.map((expose) => ({\n moduleName: expose.name,\n modulePath: expose.path,\n assets: expose.assets,\n })),\n };\n\n if (manifest.metaData?.prefetchInterface) {\n const prefetchInterface = manifest.metaData.prefetchInterface;\n\n basicRemoteSnapshot = {\n ...basicRemoteSnapshot,\n prefetchInterface,\n };\n }\n\n if (manifest.metaData?.prefetchEntry) {\n const { path, name, type } = manifest.metaData.prefetchEntry;\n\n basicRemoteSnapshot = {\n ...basicRemoteSnapshot,\n prefetchEntry: simpleJoinRemoteEntry(path, name),\n prefetchEntryType: type,\n };\n }\n\n if ('publicPath' in manifest.metaData) {\n remoteSnapshot = {\n ...basicRemoteSnapshot,\n publicPath: getPublicPath(),\n };\n if (typeof manifest.metaData.ssrPublicPath === 'string') {\n remoteSnapshot.ssrPublicPath = manifest.metaData.ssrPublicPath;\n }\n } else {\n remoteSnapshot = {\n ...basicRemoteSnapshot,\n getPublicPath: getPublicPath(),\n };\n }\n\n if (ssrRemoteEntry) {\n const fullSSRRemoteEntry = simpleJoinRemoteEntry(\n ssrRemoteEntry.path,\n ssrRemoteEntry.name,\n );\n remoteSnapshot.ssrRemoteEntry = fullSSRRemoteEntry;\n remoteSnapshot.ssrRemoteEntryType =\n ssrRemoteEntry.type || 'commonjs-module';\n }\n\n return remoteSnapshot;\n}\n\nexport function isManifestProvider(\n moduleInfo: ModuleInfo | ManifestProvider,\n): moduleInfo is ManifestProvider {\n if (\n 'remoteEntry' in moduleInfo &&\n moduleInfo.remoteEntry.includes(MANIFEST_EXT)\n ) {\n return true;\n } else {\n return false;\n }\n}\n\nexport function getManifestFileName(\n manifestOptions?: moduleFederationPlugin.ModuleFederationPluginOptions['manifest'],\n): {\n statsFileName: string;\n manifestFileName: string;\n} {\n if (!manifestOptions) {\n return {\n statsFileName: StatsFileName,\n manifestFileName: ManifestFileName,\n };\n }\n\n let filePath =\n typeof manifestOptions === 'boolean' ? '' : manifestOptions.filePath || '';\n let fileName =\n typeof manifestOptions === 'boolean' ? '' : manifestOptions.fileName || '';\n\n const JSON_EXT = '.json';\n const addExt = (name: string): string => {\n if (name.endsWith(JSON_EXT)) {\n return name;\n }\n return `${name}${JSON_EXT}`;\n };\n const insertSuffix = (name: string, suffix: string): string => {\n return name.replace(JSON_EXT, `${suffix}${JSON_EXT}`);\n };\n const manifestFileName = fileName ? addExt(fileName) : ManifestFileName;\n const statsFileName = fileName\n ? insertSuffix(manifestFileName, '-stats')\n : StatsFileName;\n\n return {\n statsFileName: simpleJoinRemoteEntry(filePath, statsFileName),\n manifestFileName: simpleJoinRemoteEntry(filePath, manifestFileName),\n };\n}\n"],"mappings":"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"}
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_constant = require('./constant.cjs');
const require_ContainerPlugin = require('./types/plugins/ContainerPlugin.cjs');
const require_ContainerReferencePlugin = require('./types/plugins/ContainerReferencePlugin.cjs');
const require_ModuleFederationPlugin = require('./types/plugins/ModuleFederationPlugin.cjs');
const require_SharePlugin = require('./types/plugins/SharePlugin.cjs');
const require_ConsumeSharedPlugin = require('./types/plugins/ConsumeSharedPlugin.cjs');
const require_ProvideSharedPlugin = require('./types/plugins/ProvideSharedPlugin.cjs');
const require_env = require('./env.cjs');
const require_utils = require('./utils.cjs');
const require_generateSnapshotFromManifest = require('./generateSnapshotFromManifest.cjs');
const require_logger = require('./logger.cjs');
const require_dom = require('./dom.cjs');
const require_node = require('./node.cjs');
const require_normalizeOptions = require('./normalizeOptions.cjs');
const require_createModuleFederationConfig = require('./createModuleFederationConfig.cjs');
exports.BROWSER_LOG_KEY = require_constant.BROWSER_LOG_KEY;
exports.ENCODE_NAME_PREFIX = require_constant.ENCODE_NAME_PREFIX;
exports.EncodedNameTransformMap = require_constant.EncodedNameTransformMap;
exports.FederationModuleManifest = require_constant.FederationModuleManifest;
exports.MANIFEST_EXT = require_constant.MANIFEST_EXT;
exports.MFModuleType = require_constant.MFModuleType;
exports.MFPrefetchCommon = require_constant.MFPrefetchCommon;
exports.MODULE_DEVTOOL_IDENTIFIER = require_constant.MODULE_DEVTOOL_IDENTIFIER;
exports.ManifestFileName = require_constant.ManifestFileName;
exports.NameTransformMap = require_constant.NameTransformMap;
exports.NameTransformSymbol = require_constant.NameTransformSymbol;
exports.SEPARATOR = require_constant.SEPARATOR;
exports.StatsFileName = require_constant.StatsFileName;
exports.TEMP_DIR = require_constant.TEMP_DIR;
exports.TreeShakingStatus = require_constant.TreeShakingStatus;
exports.assert = require_utils.assert;
exports.bindLoggerToCompiler = require_logger.bindLoggerToCompiler;
exports.composeKeyWithSeparator = require_utils.composeKeyWithSeparator;
Object.defineProperty(exports, 'consumeSharedPlugin', {
enumerable: true,
get: function () {
return require_ConsumeSharedPlugin.ConsumeSharedPlugin_exports;
}
});
Object.defineProperty(exports, 'containerPlugin', {
enumerable: true,
get: function () {
return require_ContainerPlugin.ContainerPlugin_exports;
}
});
Object.defineProperty(exports, 'containerReferencePlugin', {
enumerable: true,
get: function () {
return require_ContainerReferencePlugin.ContainerReferencePlugin_exports;
}
});
exports.createInfrastructureLogger = require_logger.createInfrastructureLogger;
exports.createLink = require_dom.createLink;
exports.createLogger = require_logger.createLogger;
exports.createModuleFederationConfig = require_createModuleFederationConfig.createModuleFederationConfig;
exports.createScript = require_dom.createScript;
exports.createScriptNode = require_node.createScriptNode;
exports.decodeName = require_utils.decodeName;
exports.encodeName = require_utils.encodeName;
exports.error = require_utils.error;
exports.generateExposeFilename = require_utils.generateExposeFilename;
exports.generateShareFilename = require_utils.generateShareFilename;
exports.generateSnapshotFromManifest = require_generateSnapshotFromManifest.generateSnapshotFromManifest;
exports.getManifestFileName = require_generateSnapshotFromManifest.getManifestFileName;
exports.getProcessEnv = require_env.getProcessEnv;
exports.getResourceUrl = require_utils.getResourceUrl;
exports.inferAutoPublicPath = require_generateSnapshotFromManifest.inferAutoPublicPath;
exports.infrastructureLogger = require_logger.infrastructureLogger;
exports.isBrowserEnv = require_env.isBrowserEnv;
exports.isBrowserEnvValue = require_env.isBrowserEnvValue;
exports.isDebugMode = require_env.isDebugMode;
exports.isManifestProvider = require_generateSnapshotFromManifest.isManifestProvider;
exports.isReactNativeEnv = require_env.isReactNativeEnv;
exports.isRequiredVersion = require_utils.isRequiredVersion;
exports.isStaticResourcesEqual = require_dom.isStaticResourcesEqual;
exports.loadScript = require_dom.loadScript;
exports.loadScriptNode = require_node.loadScriptNode;
exports.logger = require_logger.logger;
Object.defineProperty(exports, 'moduleFederationPlugin', {
enumerable: true,
get: function () {
return require_ModuleFederationPlugin.ModuleFederationPlugin_exports;
}
});
exports.normalizeOptions = require_normalizeOptions.normalizeOptions;
exports.parseEntry = require_utils.parseEntry;
Object.defineProperty(exports, 'provideSharedPlugin', {
enumerable: true,
get: function () {
return require_ProvideSharedPlugin.ProvideSharedPlugin_exports;
}
});
exports.safeToString = require_utils.safeToString;
exports.safeWrapper = require_dom.safeWrapper;
Object.defineProperty(exports, 'sharePlugin', {
enumerable: true,
get: function () {
return require_SharePlugin.SharePlugin_exports;
}
});
exports.simpleJoinRemoteEntry = require_generateSnapshotFromManifest.simpleJoinRemoteEntry;
exports.warn = require_utils.warn;
import { BROWSER_LOG_KEY, ENCODE_NAME_PREFIX, EncodedNameTransformMap, FederationModuleManifest, MANIFEST_EXT, MFModuleType, MFPrefetchCommon, MODULE_DEVTOOL_IDENTIFIER, ManifestFileName, NameTransformMap, NameTransformSymbol, SEPARATOR, StatsFileName, TEMP_DIR, TreeShakingStatus } from "./constant.js";
import { Module, RemoteEntryInfo, RemoteWithEntry, RemoteWithVersion } from "./types/common.js";
import { BasicStatsMetaData, ManifestModuleInfos, MetaDataTypes, RemoteEntryType, ResourceInfo, Stats, StatsAssets, StatsBuildInfo, StatsExpose, StatsMetaData, StatsMetaDataWithGetPublicPath, StatsMetaDataWithPublicPath, StatsModuleInfo, StatsRemote, StatsRemoteVal, StatsRemoteWithEntry, StatsRemoteWithVersion, StatsShared } from "./types/stats.js";
import { Manifest, ManifestExpose, ManifestRemote, ManifestRemoteCommonInfo, ManifestShared } from "./types/manifest.js";
import { BasicProviderModuleInfo, ConsumerModuleInfo, ConsumerModuleInfoWithPublicPath, GlobalModuleInfo, ManifestProvider, ModuleInfo, ProviderModuleInfo, PureConsumerModuleInfo, PureEntryProvider } from "./types/snapshot.js";
import { ModuleFederationPlugin_d_exports } from "./types/plugins/ModuleFederationPlugin.js";
import { ContainerPlugin_d_exports } from "./types/plugins/ContainerPlugin.js";
import { ContainerReferencePlugin_d_exports } from "./types/plugins/ContainerReferencePlugin.js";
import { SharePlugin_d_exports } from "./types/plugins/SharePlugin.js";
import { ConsumeSharedPlugin_d_exports } from "./types/plugins/ConsumeSharedPlugin.js";
import { ProvideSharedPlugin_d_exports } from "./types/plugins/ProvideSharedPlugin.js";
import { CreateScriptHook, CreateScriptHookDom, CreateScriptHookNode, CreateScriptHookReturn, CreateScriptHookReturnDom, CreateScriptHookReturnNode, FetchHook } from "./types/hooks.js";
import { assert, composeKeyWithSeparator, decodeName, encodeName, error, generateExposeFilename, generateShareFilename, getResourceUrl, isRequiredVersion, parseEntry, safeToString, warn } from "./utils.js";
import { generateSnapshotFromManifest, getManifestFileName, inferAutoPublicPath, isManifestProvider, simpleJoinRemoteEntry } from "./generateSnapshotFromManifest.js";
import { InfrastructureLogger, Logger, bindLoggerToCompiler, createInfrastructureLogger, createLogger, infrastructureLogger, logger } from "./logger.js";
import { getProcessEnv, isBrowserEnv, isBrowserEnvValue, isDebugMode, isReactNativeEnv } from "./env.js";
import { createLink, createScript, isStaticResourcesEqual, loadScript, safeWrapper } from "./dom.js";
import { createScriptNode, loadScriptNode } from "./node.js";
import { normalizeOptions } from "./normalizeOptions.js";
import { createModuleFederationConfig } from "./createModuleFederationConfig.js";
export { BROWSER_LOG_KEY, BasicProviderModuleInfo, BasicStatsMetaData, ConsumerModuleInfo, ConsumerModuleInfoWithPublicPath, CreateScriptHook, CreateScriptHookDom, CreateScriptHookNode, CreateScriptHookReturn, CreateScriptHookReturnDom, CreateScriptHookReturnNode, ENCODE_NAME_PREFIX, EncodedNameTransformMap, FederationModuleManifest, FetchHook, GlobalModuleInfo, type InfrastructureLogger, type Logger, MANIFEST_EXT, MFModuleType, MFPrefetchCommon, MODULE_DEVTOOL_IDENTIFIER, Manifest, ManifestExpose, ManifestFileName, ManifestModuleInfos, ManifestProvider, ManifestRemote, ManifestRemoteCommonInfo, ManifestShared, MetaDataTypes, Module, ModuleInfo, NameTransformMap, NameTransformSymbol, ProviderModuleInfo, PureConsumerModuleInfo, PureEntryProvider, RemoteEntryInfo, RemoteEntryType, RemoteWithEntry, RemoteWithVersion, ResourceInfo, SEPARATOR, Stats, StatsAssets, StatsBuildInfo, StatsExpose, StatsFileName, StatsMetaData, StatsMetaDataWithGetPublicPath, StatsMetaDataWithPublicPath, StatsModuleInfo, StatsRemote, StatsRemoteVal, StatsRemoteWithEntry, StatsRemoteWithVersion, StatsShared, TEMP_DIR, TreeShakingStatus, assert, bindLoggerToCompiler, composeKeyWithSeparator, ConsumeSharedPlugin_d_exports as consumeSharedPlugin, ContainerPlugin_d_exports as containerPlugin, ContainerReferencePlugin_d_exports as containerReferencePlugin, createInfrastructureLogger, createLink, createLogger, createModuleFederationConfig, createScript, createScriptNode, decodeName, encodeName, error, generateExposeFilename, generateShareFilename, generateSnapshotFromManifest, getManifestFileName, getProcessEnv, getResourceUrl, inferAutoPublicPath, infrastructureLogger, isBrowserEnv, isBrowserEnvValue, isDebugMode, isManifestProvider, isReactNativeEnv, isRequiredVersion, isStaticResourcesEqual, loadScript, loadScriptNode, logger, ModuleFederationPlugin_d_exports as moduleFederationPlugin, normalizeOptions, parseEntry, ProvideSharedPlugin_d_exports as provideSharedPlugin, safeToString, safeWrapper, SharePlugin_d_exports as sharePlugin, simpleJoinRemoteEntry, warn };
import { BROWSER_LOG_KEY, ENCODE_NAME_PREFIX, EncodedNameTransformMap, FederationModuleManifest, MANIFEST_EXT, MFModuleType, MFPrefetchCommon, MODULE_DEVTOOL_IDENTIFIER, ManifestFileName, NameTransformMap, NameTransformSymbol, SEPARATOR, StatsFileName, TEMP_DIR, TreeShakingStatus } from "./constant.js";
import { ContainerPlugin_exports } from "./types/plugins/ContainerPlugin.js";
import { ContainerReferencePlugin_exports } from "./types/plugins/ContainerReferencePlugin.js";
import { ModuleFederationPlugin_exports } from "./types/plugins/ModuleFederationPlugin.js";
import { SharePlugin_exports } from "./types/plugins/SharePlugin.js";
import { ConsumeSharedPlugin_exports } from "./types/plugins/ConsumeSharedPlugin.js";
import { ProvideSharedPlugin_exports } from "./types/plugins/ProvideSharedPlugin.js";
import { getProcessEnv, isBrowserEnv, isBrowserEnvValue, isDebugMode, isReactNativeEnv } from "./env.js";
import { assert, composeKeyWithSeparator, decodeName, encodeName, error, generateExposeFilename, generateShareFilename, getResourceUrl, isRequiredVersion, parseEntry, safeToString, warn } from "./utils.js";
import { generateSnapshotFromManifest, getManifestFileName, inferAutoPublicPath, isManifestProvider, simpleJoinRemoteEntry } from "./generateSnapshotFromManifest.js";
import { bindLoggerToCompiler, createInfrastructureLogger, createLogger, infrastructureLogger, logger } from "./logger.js";
import { createLink, createScript, isStaticResourcesEqual, loadScript, safeWrapper } from "./dom.js";
import { createScriptNode, loadScriptNode } from "./node.js";
import { normalizeOptions } from "./normalizeOptions.js";
import { createModuleFederationConfig } from "./createModuleFederationConfig.js";
export { BROWSER_LOG_KEY, ENCODE_NAME_PREFIX, EncodedNameTransformMap, FederationModuleManifest, MANIFEST_EXT, MFModuleType, MFPrefetchCommon, MODULE_DEVTOOL_IDENTIFIER, ManifestFileName, NameTransformMap, NameTransformSymbol, SEPARATOR, StatsFileName, TEMP_DIR, TreeShakingStatus, assert, bindLoggerToCompiler, composeKeyWithSeparator, ConsumeSharedPlugin_exports as consumeSharedPlugin, ContainerPlugin_exports as containerPlugin, ContainerReferencePlugin_exports as containerReferencePlugin, createInfrastructureLogger, createLink, createLogger, createModuleFederationConfig, createScript, createScriptNode, decodeName, encodeName, error, generateExposeFilename, generateShareFilename, generateSnapshotFromManifest, getManifestFileName, getProcessEnv, getResourceUrl, inferAutoPublicPath, infrastructureLogger, isBrowserEnv, isBrowserEnvValue, isDebugMode, isManifestProvider, isReactNativeEnv, isRequiredVersion, isStaticResourcesEqual, loadScript, loadScriptNode, logger, ModuleFederationPlugin_exports as moduleFederationPlugin, normalizeOptions, parseEntry, ProvideSharedPlugin_exports as provideSharedPlugin, safeToString, safeWrapper, SharePlugin_exports as sharePlugin, simpleJoinRemoteEntry, warn };
MIT License
Copyright (c) 2023-present zhanghang(2heal1)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
const require_env = require('./env.cjs');
//#region src/logger.ts
const PREFIX = "[ Module Federation ]";
const DEFAULT_DELEGATE = console;
const LOGGER_STACK_SKIP_TOKENS = [
"logger.ts",
"logger.js",
"captureStackTrace",
"Logger.emit",
"Logger.log",
"Logger.info",
"Logger.warn",
"Logger.error",
"Logger.debug"
];
function captureStackTrace() {
try {
const stack = (/* @__PURE__ */ new Error()).stack;
if (!stack) return;
const [, ...rawLines] = stack.split("\n");
const filtered = rawLines.filter((line) => !LOGGER_STACK_SKIP_TOKENS.some((token) => line.includes(token)));
if (!filtered.length) return;
return `Stack trace:\n${filtered.slice(0, 5).join("\n")}`;
} catch {
return;
}
}
var Logger = class {
constructor(prefix, delegate = DEFAULT_DELEGATE) {
this.prefix = prefix;
this.delegate = delegate ?? DEFAULT_DELEGATE;
}
setPrefix(prefix) {
this.prefix = prefix;
}
setDelegate(delegate) {
this.delegate = delegate ?? DEFAULT_DELEGATE;
}
emit(method, args) {
const delegate = this.delegate;
const stackTrace = require_env.isDebugMode() ? captureStackTrace() : void 0;
const enrichedArgs = stackTrace ? [...args, stackTrace] : args;
const order = (() => {
switch (method) {
case "log": return ["log", "info"];
case "info": return ["info", "log"];
case "warn": return [
"warn",
"info",
"log"
];
case "error": return [
"error",
"warn",
"log"
];
default: return ["debug", "log"];
}
})();
for (const candidate of order) {
const handler = delegate[candidate];
if (typeof handler === "function") {
handler.call(delegate, this.prefix, ...enrichedArgs);
return;
}
}
for (const candidate of order) {
const handler = DEFAULT_DELEGATE[candidate];
if (typeof handler === "function") {
handler.call(DEFAULT_DELEGATE, this.prefix, ...enrichedArgs);
return;
}
}
}
log(...args) {
this.emit("log", args);
}
warn(...args) {
this.emit("warn", args);
}
error(...args) {
this.emit("error", args);
}
success(...args) {
this.emit("info", args);
}
info(...args) {
this.emit("info", args);
}
ready(...args) {
this.emit("info", args);
}
debug(...args) {
if (require_env.isDebugMode()) this.emit("debug", args);
}
};
function createLogger(prefix) {
return new Logger(prefix);
}
function createInfrastructureLogger(prefix) {
const infrastructureLogger = new Logger(prefix);
Object.defineProperty(infrastructureLogger, "__mf_infrastructure_logger__", {
value: true,
enumerable: false,
configurable: false
});
return infrastructureLogger;
}
function bindLoggerToCompiler(loggerInstance, compiler, name) {
if (!loggerInstance.__mf_infrastructure_logger__) return;
if (!compiler?.getInfrastructureLogger) return;
try {
const infrastructureLogger = compiler.getInfrastructureLogger(name);
if (infrastructureLogger && typeof infrastructureLogger === "object" && (typeof infrastructureLogger.log === "function" || typeof infrastructureLogger.info === "function" || typeof infrastructureLogger.warn === "function" || typeof infrastructureLogger.error === "function")) loggerInstance.setDelegate(infrastructureLogger);
} catch {
loggerInstance.setDelegate(void 0);
}
}
const logger = createLogger(PREFIX);
const infrastructureLogger = createInfrastructureLogger(PREFIX);
//#endregion
exports.bindLoggerToCompiler = bindLoggerToCompiler;
exports.createInfrastructureLogger = createInfrastructureLogger;
exports.createLogger = createLogger;
exports.infrastructureLogger = infrastructureLogger;
exports.logger = logger;
//# sourceMappingURL=logger.cjs.map
{"version":3,"file":"logger.cjs","names":["isDebugMode"],"sources":["../src/logger.ts"],"sourcesContent":["import { isDebugMode } from './env';\n\nconst PREFIX = '[ Module Federation ]';\n\ntype LogMethod = 'log' | 'info' | 'warn' | 'error' | 'debug';\n\ntype LoggerDelegate = Partial<Record<LogMethod, (...args: any[]) => void>> & {\n [key: string]: ((...args: any[]) => void) | undefined;\n};\n\nconst DEFAULT_DELEGATE: LoggerDelegate = console as unknown as LoggerDelegate;\nconst LOGGER_STACK_SKIP_TOKENS = [\n 'logger.ts',\n 'logger.js',\n 'captureStackTrace',\n 'Logger.emit',\n 'Logger.log',\n 'Logger.info',\n 'Logger.warn',\n 'Logger.error',\n 'Logger.debug',\n];\n\nfunction captureStackTrace(): string | undefined {\n try {\n const stack = new Error().stack;\n if (!stack) {\n return undefined;\n }\n\n const [, ...rawLines] = stack.split('\\n');\n const filtered = rawLines.filter(\n (line) => !LOGGER_STACK_SKIP_TOKENS.some((token) => line.includes(token)),\n );\n\n if (!filtered.length) {\n return undefined;\n }\n\n const stackPreview = filtered.slice(0, 5).join('\\n');\n return `Stack trace:\\n${stackPreview}`;\n } catch {\n return undefined;\n }\n}\n\nclass Logger {\n prefix: string;\n private delegate: LoggerDelegate;\n\n constructor(prefix: string, delegate: LoggerDelegate = DEFAULT_DELEGATE) {\n this.prefix = prefix;\n this.delegate = delegate ?? DEFAULT_DELEGATE;\n }\n\n setPrefix(prefix: string) {\n this.prefix = prefix;\n }\n\n setDelegate(delegate?: LoggerDelegate) {\n this.delegate = delegate ?? DEFAULT_DELEGATE;\n }\n\n private emit(method: LogMethod, args: any[]) {\n const delegate = this.delegate;\n const debugMode = isDebugMode();\n const stackTrace = debugMode ? captureStackTrace() : undefined;\n const enrichedArgs = stackTrace ? [...args, stackTrace] : args;\n\n const order: LogMethod[] = (() => {\n switch (method) {\n case 'log':\n return ['log', 'info'];\n case 'info':\n return ['info', 'log'];\n case 'warn':\n return ['warn', 'info', 'log'];\n case 'error':\n return ['error', 'warn', 'log'];\n case 'debug':\n default:\n return ['debug', 'log'];\n }\n })();\n\n for (const candidate of order) {\n const handler = delegate[candidate];\n if (typeof handler === 'function') {\n handler.call(delegate, this.prefix, ...enrichedArgs);\n return;\n }\n }\n\n for (const candidate of order) {\n const handler = DEFAULT_DELEGATE[candidate];\n if (typeof handler === 'function') {\n handler.call(DEFAULT_DELEGATE, this.prefix, ...enrichedArgs);\n return;\n }\n }\n }\n\n log(...args: any[]) {\n this.emit('log', args);\n }\n warn(...args: any[]) {\n this.emit('warn', args);\n }\n error(...args: any[]) {\n this.emit('error', args);\n }\n\n success(...args: any[]) {\n this.emit('info', args);\n }\n info(...args: any[]) {\n this.emit('info', args);\n }\n ready(...args: any[]) {\n this.emit('info', args);\n }\n\n debug(...args: any[]) {\n if (isDebugMode()) {\n this.emit('debug', args);\n }\n }\n}\n\nfunction createLogger(prefix: string) {\n return new Logger(prefix);\n}\n\ntype InfrastructureLogger = Logger & {\n __mf_infrastructure_logger__: true;\n};\n\nfunction createInfrastructureLogger(prefix: string): InfrastructureLogger {\n const infrastructureLogger = new Logger(prefix) as InfrastructureLogger;\n Object.defineProperty(infrastructureLogger, '__mf_infrastructure_logger__', {\n value: true,\n enumerable: false,\n configurable: false,\n });\n return infrastructureLogger;\n}\n\ntype InfrastructureLoggerCapableCompiler = {\n getInfrastructureLogger?: (name: string) => unknown;\n};\n\nfunction bindLoggerToCompiler(\n loggerInstance: Logger,\n compiler: InfrastructureLoggerCapableCompiler,\n name: string,\n) {\n if (\n !(loggerInstance as Partial<InfrastructureLogger>)\n .__mf_infrastructure_logger__\n ) {\n return;\n }\n if (!compiler?.getInfrastructureLogger) {\n return;\n }\n try {\n const infrastructureLogger = compiler.getInfrastructureLogger(name);\n if (\n infrastructureLogger &&\n typeof infrastructureLogger === 'object' &&\n (typeof (infrastructureLogger as LoggerDelegate).log === 'function' ||\n typeof (infrastructureLogger as LoggerDelegate).info === 'function' ||\n typeof (infrastructureLogger as LoggerDelegate).warn === 'function' ||\n typeof (infrastructureLogger as LoggerDelegate).error === 'function')\n ) {\n loggerInstance.setDelegate(\n infrastructureLogger as unknown as LoggerDelegate,\n );\n }\n } catch {\n // If the bundler throws (older versions), fall back to default console logger.\n loggerInstance.setDelegate(undefined);\n }\n}\n\nconst logger = createLogger(PREFIX);\nconst infrastructureLogger = createInfrastructureLogger(PREFIX);\n\nexport {\n logger,\n infrastructureLogger,\n createLogger,\n createInfrastructureLogger,\n bindLoggerToCompiler,\n};\nexport type { Logger, InfrastructureLogger };\n"],"mappings":"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"}
//#region src/logger.d.ts
type LogMethod = 'log' | 'info' | 'warn' | 'error' | 'debug';
type LoggerDelegate = Partial<Record<LogMethod, (...args: any[]) => void>> & {
[key: string]: ((...args: any[]) => void) | undefined;
};
declare class Logger {
prefix: string;
private delegate;
constructor(prefix: string, delegate?: LoggerDelegate);
setPrefix(prefix: string): void;
setDelegate(delegate?: LoggerDelegate): void;
private emit;
log(...args: any[]): void;
warn(...args: any[]): void;
error(...args: any[]): void;
success(...args: any[]): void;
info(...args: any[]): void;
ready(...args: any[]): void;
debug(...args: any[]): void;
}
declare function createLogger(prefix: string): Logger;
type InfrastructureLogger = Logger & {
__mf_infrastructure_logger__: true;
};
declare function createInfrastructureLogger(prefix: string): InfrastructureLogger;
type InfrastructureLoggerCapableCompiler = {
getInfrastructureLogger?: (name: string) => unknown;
};
declare function bindLoggerToCompiler(loggerInstance: Logger, compiler: InfrastructureLoggerCapableCompiler, name: string): void;
declare const logger: Logger;
declare const infrastructureLogger: InfrastructureLogger;
//#endregion
export { type InfrastructureLogger, type Logger, bindLoggerToCompiler, createInfrastructureLogger, createLogger, infrastructureLogger, logger };
//# sourceMappingURL=logger.d.ts.map
import { isDebugMode } from "./env.js";
//#region src/logger.ts
const PREFIX = "[ Module Federation ]";
const DEFAULT_DELEGATE = console;
const LOGGER_STACK_SKIP_TOKENS = [
"logger.ts",
"logger.js",
"captureStackTrace",
"Logger.emit",
"Logger.log",
"Logger.info",
"Logger.warn",
"Logger.error",
"Logger.debug"
];
function captureStackTrace() {
try {
const stack = (/* @__PURE__ */ new Error()).stack;
if (!stack) return;
const [, ...rawLines] = stack.split("\n");
const filtered = rawLines.filter((line) => !LOGGER_STACK_SKIP_TOKENS.some((token) => line.includes(token)));
if (!filtered.length) return;
return `Stack trace:\n${filtered.slice(0, 5).join("\n")}`;
} catch {
return;
}
}
var Logger = class {
constructor(prefix, delegate = DEFAULT_DELEGATE) {
this.prefix = prefix;
this.delegate = delegate ?? DEFAULT_DELEGATE;
}
setPrefix(prefix) {
this.prefix = prefix;
}
setDelegate(delegate) {
this.delegate = delegate ?? DEFAULT_DELEGATE;
}
emit(method, args) {
const delegate = this.delegate;
const stackTrace = isDebugMode() ? captureStackTrace() : void 0;
const enrichedArgs = stackTrace ? [...args, stackTrace] : args;
const order = (() => {
switch (method) {
case "log": return ["log", "info"];
case "info": return ["info", "log"];
case "warn": return [
"warn",
"info",
"log"
];
case "error": return [
"error",
"warn",
"log"
];
default: return ["debug", "log"];
}
})();
for (const candidate of order) {
const handler = delegate[candidate];
if (typeof handler === "function") {
handler.call(delegate, this.prefix, ...enrichedArgs);
return;
}
}
for (const candidate of order) {
const handler = DEFAULT_DELEGATE[candidate];
if (typeof handler === "function") {
handler.call(DEFAULT_DELEGATE, this.prefix, ...enrichedArgs);
return;
}
}
}
log(...args) {
this.emit("log", args);
}
warn(...args) {
this.emit("warn", args);
}
error(...args) {
this.emit("error", args);
}
success(...args) {
this.emit("info", args);
}
info(...args) {
this.emit("info", args);
}
ready(...args) {
this.emit("info", args);
}
debug(...args) {
if (isDebugMode()) this.emit("debug", args);
}
};
function createLogger(prefix) {
return new Logger(prefix);
}
function createInfrastructureLogger(prefix) {
const infrastructureLogger = new Logger(prefix);
Object.defineProperty(infrastructureLogger, "__mf_infrastructure_logger__", {
value: true,
enumerable: false,
configurable: false
});
return infrastructureLogger;
}
function bindLoggerToCompiler(loggerInstance, compiler, name) {
if (!loggerInstance.__mf_infrastructure_logger__) return;
if (!compiler?.getInfrastructureLogger) return;
try {
const infrastructureLogger = compiler.getInfrastructureLogger(name);
if (infrastructureLogger && typeof infrastructureLogger === "object" && (typeof infrastructureLogger.log === "function" || typeof infrastructureLogger.info === "function" || typeof infrastructureLogger.warn === "function" || typeof infrastructureLogger.error === "function")) loggerInstance.setDelegate(infrastructureLogger);
} catch {
loggerInstance.setDelegate(void 0);
}
}
const logger = createLogger(PREFIX);
const infrastructureLogger = createInfrastructureLogger(PREFIX);
//#endregion
export { bindLoggerToCompiler, createInfrastructureLogger, createLogger, infrastructureLogger, logger };
//# sourceMappingURL=logger.js.map
{"version":3,"file":"logger.js","names":[],"sources":["../src/logger.ts"],"sourcesContent":["import { isDebugMode } from './env';\n\nconst PREFIX = '[ Module Federation ]';\n\ntype LogMethod = 'log' | 'info' | 'warn' | 'error' | 'debug';\n\ntype LoggerDelegate = Partial<Record<LogMethod, (...args: any[]) => void>> & {\n [key: string]: ((...args: any[]) => void) | undefined;\n};\n\nconst DEFAULT_DELEGATE: LoggerDelegate = console as unknown as LoggerDelegate;\nconst LOGGER_STACK_SKIP_TOKENS = [\n 'logger.ts',\n 'logger.js',\n 'captureStackTrace',\n 'Logger.emit',\n 'Logger.log',\n 'Logger.info',\n 'Logger.warn',\n 'Logger.error',\n 'Logger.debug',\n];\n\nfunction captureStackTrace(): string | undefined {\n try {\n const stack = new Error().stack;\n if (!stack) {\n return undefined;\n }\n\n const [, ...rawLines] = stack.split('\\n');\n const filtered = rawLines.filter(\n (line) => !LOGGER_STACK_SKIP_TOKENS.some((token) => line.includes(token)),\n );\n\n if (!filtered.length) {\n return undefined;\n }\n\n const stackPreview = filtered.slice(0, 5).join('\\n');\n return `Stack trace:\\n${stackPreview}`;\n } catch {\n return undefined;\n }\n}\n\nclass Logger {\n prefix: string;\n private delegate: LoggerDelegate;\n\n constructor(prefix: string, delegate: LoggerDelegate = DEFAULT_DELEGATE) {\n this.prefix = prefix;\n this.delegate = delegate ?? DEFAULT_DELEGATE;\n }\n\n setPrefix(prefix: string) {\n this.prefix = prefix;\n }\n\n setDelegate(delegate?: LoggerDelegate) {\n this.delegate = delegate ?? DEFAULT_DELEGATE;\n }\n\n private emit(method: LogMethod, args: any[]) {\n const delegate = this.delegate;\n const debugMode = isDebugMode();\n const stackTrace = debugMode ? captureStackTrace() : undefined;\n const enrichedArgs = stackTrace ? [...args, stackTrace] : args;\n\n const order: LogMethod[] = (() => {\n switch (method) {\n case 'log':\n return ['log', 'info'];\n case 'info':\n return ['info', 'log'];\n case 'warn':\n return ['warn', 'info', 'log'];\n case 'error':\n return ['error', 'warn', 'log'];\n case 'debug':\n default:\n return ['debug', 'log'];\n }\n })();\n\n for (const candidate of order) {\n const handler = delegate[candidate];\n if (typeof handler === 'function') {\n handler.call(delegate, this.prefix, ...enrichedArgs);\n return;\n }\n }\n\n for (const candidate of order) {\n const handler = DEFAULT_DELEGATE[candidate];\n if (typeof handler === 'function') {\n handler.call(DEFAULT_DELEGATE, this.prefix, ...enrichedArgs);\n return;\n }\n }\n }\n\n log(...args: any[]) {\n this.emit('log', args);\n }\n warn(...args: any[]) {\n this.emit('warn', args);\n }\n error(...args: any[]) {\n this.emit('error', args);\n }\n\n success(...args: any[]) {\n this.emit('info', args);\n }\n info(...args: any[]) {\n this.emit('info', args);\n }\n ready(...args: any[]) {\n this.emit('info', args);\n }\n\n debug(...args: any[]) {\n if (isDebugMode()) {\n this.emit('debug', args);\n }\n }\n}\n\nfunction createLogger(prefix: string) {\n return new Logger(prefix);\n}\n\ntype InfrastructureLogger = Logger & {\n __mf_infrastructure_logger__: true;\n};\n\nfunction createInfrastructureLogger(prefix: string): InfrastructureLogger {\n const infrastructureLogger = new Logger(prefix) as InfrastructureLogger;\n Object.defineProperty(infrastructureLogger, '__mf_infrastructure_logger__', {\n value: true,\n enumerable: false,\n configurable: false,\n });\n return infrastructureLogger;\n}\n\ntype InfrastructureLoggerCapableCompiler = {\n getInfrastructureLogger?: (name: string) => unknown;\n};\n\nfunction bindLoggerToCompiler(\n loggerInstance: Logger,\n compiler: InfrastructureLoggerCapableCompiler,\n name: string,\n) {\n if (\n !(loggerInstance as Partial<InfrastructureLogger>)\n .__mf_infrastructure_logger__\n ) {\n return;\n }\n if (!compiler?.getInfrastructureLogger) {\n return;\n }\n try {\n const infrastructureLogger = compiler.getInfrastructureLogger(name);\n if (\n infrastructureLogger &&\n typeof infrastructureLogger === 'object' &&\n (typeof (infrastructureLogger as LoggerDelegate).log === 'function' ||\n typeof (infrastructureLogger as LoggerDelegate).info === 'function' ||\n typeof (infrastructureLogger as LoggerDelegate).warn === 'function' ||\n typeof (infrastructureLogger as LoggerDelegate).error === 'function')\n ) {\n loggerInstance.setDelegate(\n infrastructureLogger as unknown as LoggerDelegate,\n );\n }\n } catch {\n // If the bundler throws (older versions), fall back to default console logger.\n loggerInstance.setDelegate(undefined);\n }\n}\n\nconst logger = createLogger(PREFIX);\nconst infrastructureLogger = createInfrastructureLogger(PREFIX);\n\nexport {\n logger,\n infrastructureLogger,\n createLogger,\n createInfrastructureLogger,\n bindLoggerToCompiler,\n};\nexport type { Logger, InfrastructureLogger };\n"],"mappings":"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"}
//#region src/node.ts
const sdkImportCache = /* @__PURE__ */ new Map();
function importNodeModule(name) {
if (!name) throw new Error("import specifier is required");
if (sdkImportCache.has(name)) return sdkImportCache.get(name);
const promise = new Function("name", `return import(name)`)(name).then((res) => res).catch((error) => {
console.error(`Error importing module ${name}:`, error);
sdkImportCache.delete(name);
throw error;
});
sdkImportCache.set(name, promise);
return promise;
}
const loadNodeFetch = async () => {
const fetchModule = await importNodeModule("node-fetch");
return fetchModule.default || fetchModule;
};
const lazyLoaderHookFetch = async (input, init, loaderHook) => {
const hook = (url, init) => {
return loaderHook.lifecycle.fetch.emit(url, init);
};
const res = await hook(input, init || {});
if (!res || !(res instanceof Response)) return (typeof fetch === "undefined" ? await loadNodeFetch() : fetch)(input, init || {});
return res;
};
const createScriptNode = typeof ENV_TARGET === "undefined" || ENV_TARGET !== "web" ? (url, cb, attrs, loaderHook) => {
if (loaderHook?.createScriptHook) {
const hookResult = loaderHook.createScriptHook(url);
if (hookResult && typeof hookResult === "object" && "url" in hookResult) url = hookResult.url;
}
let urlObj;
try {
urlObj = new URL(url);
} catch (e) {
console.error("Error constructing URL:", e);
cb(/* @__PURE__ */ new Error(`Invalid URL: ${e}`));
return;
}
const getFetch = async () => {
if (loaderHook?.fetch) return (input, init) => lazyLoaderHookFetch(input, init, loaderHook);
return typeof fetch === "undefined" ? loadNodeFetch() : fetch;
};
const handleScriptFetch = async (f, urlObj) => {
try {
const res = await f(urlObj.href);
const data = await res.text();
const [path, vm] = await Promise.all([importNodeModule("path"), importNodeModule("vm")]);
const scriptContext = {
exports: {},
module: { exports: {} }
};
const urlDirname = urlObj.pathname.split("/").slice(0, -1).join("/");
const filename = path.basename(urlObj.pathname);
const script = new vm.Script(`(function(exports, module, require, __dirname, __filename) {${data}\n})`, {
filename,
importModuleDynamically: vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER ?? importNodeModule
});
let requireFn;
requireFn = eval("require");
script.runInThisContext()(scriptContext.exports, scriptContext.module, requireFn, urlDirname, filename);
const exportedInterface = scriptContext.module.exports || scriptContext.exports;
if (attrs && exportedInterface && attrs["globalName"]) {
cb(void 0, exportedInterface[attrs["globalName"]] || exportedInterface);
return;
}
cb(void 0, exportedInterface);
} catch (e) {
cb(e instanceof Error ? e : /* @__PURE__ */ new Error(`Script execution error: ${e}`));
}
};
getFetch().then(async (f) => {
if (attrs?.["type"] === "esm" || attrs?.["type"] === "module") return loadModule(urlObj.href, {
fetch: f,
vm: await importNodeModule("vm")
}).then(async (module) => {
await module.evaluate();
cb(void 0, module.namespace);
}).catch((e) => {
cb(e instanceof Error ? e : /* @__PURE__ */ new Error(`Script execution error: ${e}`));
});
handleScriptFetch(f, urlObj);
}).catch((err) => {
cb(err);
});
} : (url, cb, attrs, loaderHook) => {
cb(/* @__PURE__ */ new Error("createScriptNode is disabled in non-Node.js environment"));
};
const loadScriptNode = typeof ENV_TARGET === "undefined" || ENV_TARGET !== "web" ? (url, info) => {
return new Promise((resolve, reject) => {
createScriptNode(url, (error, scriptContext) => {
if (error) reject(error);
else {
const remoteEntryKey = info?.attrs?.["globalName"] || `__FEDERATION_${info?.attrs?.["name"]}:custom__`;
resolve(globalThis[remoteEntryKey] = scriptContext);
}
}, info.attrs, info.loaderHook);
});
} : (url, info) => {
throw new Error("loadScriptNode is disabled in non-Node.js environment");
};
const esmModuleCache = /* @__PURE__ */ new Map();
async function loadModule(url, options) {
if (esmModuleCache.has(url)) return esmModuleCache.get(url);
const { fetch, vm } = options;
const code = await (await fetch(url)).text();
const module = new vm.SourceTextModule(code, { importModuleDynamically: async (specifier, script) => {
const resolvedUrl = new URL(specifier, url).href;
return loadModule(resolvedUrl, options);
} });
esmModuleCache.set(url, module);
await module.link(async (specifier) => {
const resolvedUrl = new URL(specifier, url).href;
return await loadModule(resolvedUrl, options);
});
return module;
}
//#endregion
exports.createScriptNode = createScriptNode;
exports.loadScriptNode = loadScriptNode;
//# sourceMappingURL=node.cjs.map
{"version":3,"file":"node.cjs","names":[],"sources":["../src/node.ts"],"sourcesContent":["import { CreateScriptHookNode, FetchHook } from './types';\n\n// Declare the ENV_TARGET constant that will be defined by DefinePlugin\ndeclare const ENV_TARGET: 'web' | 'node';\n\nconst sdkImportCache = new Map<string, Promise<any>>();\n\nfunction importNodeModule<T>(name: string): Promise<T> {\n if (!name) {\n throw new Error('import specifier is required');\n }\n\n // Check cache to prevent infinite recursion\n if (sdkImportCache.has(name)) {\n return sdkImportCache.get(name)!;\n }\n\n const importModule = new Function('name', `return import(name)`);\n const promise = importModule(name)\n .then((res: any) => res as T)\n .catch((error: any) => {\n console.error(`Error importing module ${name}:`, error);\n // Remove from cache on error so it can be retried\n sdkImportCache.delete(name);\n throw error;\n });\n\n // Cache the promise to prevent recursive calls\n sdkImportCache.set(name, promise);\n return promise;\n}\n\nconst loadNodeFetch = async (): Promise<typeof fetch> => {\n const fetchModule =\n await importNodeModule<typeof import('node-fetch')>('node-fetch');\n return (fetchModule.default || fetchModule) as unknown as typeof fetch;\n};\n\nconst lazyLoaderHookFetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n loaderHook?: any,\n): Promise<Response> => {\n const hook = (url: RequestInfo | URL, init: RequestInit) => {\n return loaderHook.lifecycle.fetch.emit(url, init);\n };\n\n const res = await hook(input, init || {});\n if (!res || !(res instanceof Response)) {\n const fetchFunction =\n typeof fetch === 'undefined' ? await loadNodeFetch() : fetch;\n return fetchFunction(input, init || {});\n }\n\n return res;\n};\n\nexport const createScriptNode =\n typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'\n ? (\n url: string,\n cb: (error?: Error, scriptContext?: any) => void,\n attrs?: Record<string, any>,\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n fetch?: FetchHook;\n },\n ) => {\n if (loaderHook?.createScriptHook) {\n const hookResult = loaderHook.createScriptHook(url);\n if (\n hookResult &&\n typeof hookResult === 'object' &&\n 'url' in hookResult\n ) {\n url = hookResult.url;\n }\n }\n\n let urlObj: URL;\n try {\n urlObj = new URL(url);\n } catch (e) {\n console.error('Error constructing URL:', e);\n cb(new Error(`Invalid URL: ${e}`));\n return;\n }\n\n const getFetch = async (): Promise<typeof fetch> => {\n if (loaderHook?.fetch) {\n return (input: RequestInfo | URL, init?: RequestInit) =>\n lazyLoaderHookFetch(input, init, loaderHook);\n }\n\n return typeof fetch === 'undefined' ? loadNodeFetch() : fetch;\n };\n\n const handleScriptFetch = async (f: typeof fetch, urlObj: URL) => {\n try {\n const res = await f(urlObj.href);\n const data = await res.text();\n const [path, vm] = await Promise.all([\n importNodeModule<typeof import('path')>('path'),\n importNodeModule<typeof import('vm')>('vm'),\n ]);\n\n const scriptContext = { exports: {}, module: { exports: {} } };\n const urlDirname = urlObj.pathname\n .split('/')\n .slice(0, -1)\n .join('/');\n const filename = path.basename(urlObj.pathname);\n\n const script = new vm.Script(\n `(function(exports, module, require, __dirname, __filename) {${data}\\n})`,\n {\n filename,\n importModuleDynamically:\n //@ts-ignore\n vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER ??\n importNodeModule,\n },\n );\n\n let requireFn: NodeRequire;\n if (process.env.IS_ESM_BUILD === 'true') {\n const nodeModule =\n await importNodeModule<typeof import('node:module')>(\n 'node:module',\n );\n requireFn = nodeModule.createRequire(\n urlObj.protocol === 'file:' || urlObj.protocol === 'node:'\n ? urlObj.href\n : path.join(process.cwd(), '__mf_require_base__.js'),\n );\n } else {\n requireFn = eval('require') as NodeRequire;\n }\n\n script.runInThisContext()(\n scriptContext.exports,\n scriptContext.module,\n requireFn,\n urlDirname,\n filename,\n );\n const exportedInterface: Record<string, any> =\n scriptContext.module.exports || scriptContext.exports;\n\n if (attrs && exportedInterface && attrs['globalName']) {\n const container =\n exportedInterface[attrs['globalName']] || exportedInterface;\n cb(\n undefined,\n container as keyof typeof scriptContext.module.exports,\n );\n return;\n }\n\n cb(\n undefined,\n exportedInterface as keyof typeof scriptContext.module.exports,\n );\n } catch (e) {\n cb(\n e instanceof Error\n ? e\n : new Error(`Script execution error: ${e}`),\n );\n }\n };\n\n getFetch()\n .then(async (f) => {\n if (attrs?.['type'] === 'esm' || attrs?.['type'] === 'module') {\n return loadModule(urlObj.href, {\n fetch: f,\n vm: await importNodeModule<typeof import('vm')>('vm'),\n })\n .then(async (module) => {\n await module.evaluate();\n cb(undefined, module.namespace);\n })\n .catch((e) => {\n cb(\n e instanceof Error\n ? e\n : new Error(`Script execution error: ${e}`),\n );\n });\n }\n handleScriptFetch(f, urlObj);\n })\n .catch((err) => {\n cb(err);\n });\n }\n : (\n url: string,\n cb: (error?: Error, scriptContext?: any) => void,\n attrs?: Record<string, any>,\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n fetch?: FetchHook;\n },\n ) => {\n cb(\n new Error('createScriptNode is disabled in non-Node.js environment'),\n );\n };\n\nexport const loadScriptNode =\n typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'\n ? (\n url: string,\n info: {\n attrs?: Record<string, any>;\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n };\n },\n ) => {\n return new Promise<void>((resolve, reject) => {\n createScriptNode(\n url,\n (error, scriptContext) => {\n if (error) {\n reject(error);\n } else {\n const remoteEntryKey =\n info?.attrs?.['globalName'] ||\n `__FEDERATION_${info?.attrs?.['name']}:custom__`;\n const entryExports = ((globalThis as any)[remoteEntryKey] =\n scriptContext);\n resolve(entryExports);\n }\n },\n info.attrs,\n info.loaderHook,\n );\n });\n }\n : (\n url: string,\n info: {\n attrs?: Record<string, any>;\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n };\n },\n ) => {\n throw new Error(\n 'loadScriptNode is disabled in non-Node.js environment',\n );\n };\n\nconst esmModuleCache = new Map<string, any>();\n\nasync function loadModule(\n url: string,\n options: {\n vm: any;\n fetch: any;\n },\n) {\n // Check cache to prevent infinite recursion in ESM loading\n if (esmModuleCache.has(url)) {\n return esmModuleCache.get(url)!;\n }\n\n const { fetch, vm } = options;\n const response = await fetch(url);\n const code = await response.text();\n\n const module: any = new vm.SourceTextModule(code, {\n // @ts-ignore\n importModuleDynamically: async (specifier, script) => {\n const resolvedUrl = new URL(specifier, url).href;\n return loadModule(resolvedUrl, options);\n },\n });\n\n // Cache the module before linking to prevent cycles\n esmModuleCache.set(url, module);\n\n await module.link(async (specifier: string) => {\n const resolvedUrl = new URL(specifier, url).href;\n const module = await loadModule(resolvedUrl, options);\n return module;\n });\n\n return module;\n}\n"],"mappings":"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"}
import { CreateScriptHookNode, FetchHook } from "./types/hooks.js";
//#region src/node.d.ts
declare const createScriptNode: (url: string, cb: (error?: Error, scriptContext?: any) => void, attrs?: Record<string, any>, loaderHook?: {
createScriptHook?: CreateScriptHookNode;
fetch?: FetchHook;
}) => void;
declare const loadScriptNode: (url: string, info: {
attrs?: Record<string, any>;
loaderHook?: {
createScriptHook?: CreateScriptHookNode;
};
}) => Promise<void>;
//#endregion
export { createScriptNode, loadScriptNode };
//# sourceMappingURL=node.d.ts.map
//#region src/node.ts
const sdkImportCache = /* @__PURE__ */ new Map();
function importNodeModule(name) {
if (!name) throw new Error("import specifier is required");
if (sdkImportCache.has(name)) return sdkImportCache.get(name);
const promise = new Function("name", `return import(name)`)(name).then((res) => res).catch((error) => {
console.error(`Error importing module ${name}:`, error);
sdkImportCache.delete(name);
throw error;
});
sdkImportCache.set(name, promise);
return promise;
}
const loadNodeFetch = async () => {
const fetchModule = await importNodeModule("node-fetch");
return fetchModule.default || fetchModule;
};
const lazyLoaderHookFetch = async (input, init, loaderHook) => {
const hook = (url, init) => {
return loaderHook.lifecycle.fetch.emit(url, init);
};
const res = await hook(input, init || {});
if (!res || !(res instanceof Response)) return (typeof fetch === "undefined" ? await loadNodeFetch() : fetch)(input, init || {});
return res;
};
const createScriptNode = typeof ENV_TARGET === "undefined" || ENV_TARGET !== "web" ? (url, cb, attrs, loaderHook) => {
if (loaderHook?.createScriptHook) {
const hookResult = loaderHook.createScriptHook(url);
if (hookResult && typeof hookResult === "object" && "url" in hookResult) url = hookResult.url;
}
let urlObj;
try {
urlObj = new URL(url);
} catch (e) {
console.error("Error constructing URL:", e);
cb(/* @__PURE__ */ new Error(`Invalid URL: ${e}`));
return;
}
const getFetch = async () => {
if (loaderHook?.fetch) return (input, init) => lazyLoaderHookFetch(input, init, loaderHook);
return typeof fetch === "undefined" ? loadNodeFetch() : fetch;
};
const handleScriptFetch = async (f, urlObj) => {
try {
const res = await f(urlObj.href);
const data = await res.text();
const [path, vm] = await Promise.all([importNodeModule("path"), importNodeModule("vm")]);
const scriptContext = {
exports: {},
module: { exports: {} }
};
const urlDirname = urlObj.pathname.split("/").slice(0, -1).join("/");
const filename = path.basename(urlObj.pathname);
const script = new vm.Script(`(function(exports, module, require, __dirname, __filename) {${data}\n})`, {
filename,
importModuleDynamically: vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER ?? importNodeModule
});
let requireFn;
requireFn = (await importNodeModule("node:module")).createRequire(urlObj.protocol === "file:" || urlObj.protocol === "node:" ? urlObj.href : path.join(process.cwd(), "__mf_require_base__.js"));
script.runInThisContext()(scriptContext.exports, scriptContext.module, requireFn, urlDirname, filename);
const exportedInterface = scriptContext.module.exports || scriptContext.exports;
if (attrs && exportedInterface && attrs["globalName"]) {
cb(void 0, exportedInterface[attrs["globalName"]] || exportedInterface);
return;
}
cb(void 0, exportedInterface);
} catch (e) {
cb(e instanceof Error ? e : /* @__PURE__ */ new Error(`Script execution error: ${e}`));
}
};
getFetch().then(async (f) => {
if (attrs?.["type"] === "esm" || attrs?.["type"] === "module") return loadModule(urlObj.href, {
fetch: f,
vm: await importNodeModule("vm")
}).then(async (module) => {
await module.evaluate();
cb(void 0, module.namespace);
}).catch((e) => {
cb(e instanceof Error ? e : /* @__PURE__ */ new Error(`Script execution error: ${e}`));
});
handleScriptFetch(f, urlObj);
}).catch((err) => {
cb(err);
});
} : (url, cb, attrs, loaderHook) => {
cb(/* @__PURE__ */ new Error("createScriptNode is disabled in non-Node.js environment"));
};
const loadScriptNode = typeof ENV_TARGET === "undefined" || ENV_TARGET !== "web" ? (url, info) => {
return new Promise((resolve, reject) => {
createScriptNode(url, (error, scriptContext) => {
if (error) reject(error);
else {
const remoteEntryKey = info?.attrs?.["globalName"] || `__FEDERATION_${info?.attrs?.["name"]}:custom__`;
resolve(globalThis[remoteEntryKey] = scriptContext);
}
}, info.attrs, info.loaderHook);
});
} : (url, info) => {
throw new Error("loadScriptNode is disabled in non-Node.js environment");
};
const esmModuleCache = /* @__PURE__ */ new Map();
async function loadModule(url, options) {
if (esmModuleCache.has(url)) return esmModuleCache.get(url);
const { fetch, vm } = options;
const code = await (await fetch(url)).text();
const module = new vm.SourceTextModule(code, { importModuleDynamically: async (specifier, script) => {
const resolvedUrl = new URL(specifier, url).href;
return loadModule(resolvedUrl, options);
} });
esmModuleCache.set(url, module);
await module.link(async (specifier) => {
const resolvedUrl = new URL(specifier, url).href;
return await loadModule(resolvedUrl, options);
});
return module;
}
//#endregion
export { createScriptNode, loadScriptNode };
//# sourceMappingURL=node.js.map
{"version":3,"file":"node.js","names":[],"sources":["../src/node.ts"],"sourcesContent":["import { CreateScriptHookNode, FetchHook } from './types';\n\n// Declare the ENV_TARGET constant that will be defined by DefinePlugin\ndeclare const ENV_TARGET: 'web' | 'node';\n\nconst sdkImportCache = new Map<string, Promise<any>>();\n\nfunction importNodeModule<T>(name: string): Promise<T> {\n if (!name) {\n throw new Error('import specifier is required');\n }\n\n // Check cache to prevent infinite recursion\n if (sdkImportCache.has(name)) {\n return sdkImportCache.get(name)!;\n }\n\n const importModule = new Function('name', `return import(name)`);\n const promise = importModule(name)\n .then((res: any) => res as T)\n .catch((error: any) => {\n console.error(`Error importing module ${name}:`, error);\n // Remove from cache on error so it can be retried\n sdkImportCache.delete(name);\n throw error;\n });\n\n // Cache the promise to prevent recursive calls\n sdkImportCache.set(name, promise);\n return promise;\n}\n\nconst loadNodeFetch = async (): Promise<typeof fetch> => {\n const fetchModule =\n await importNodeModule<typeof import('node-fetch')>('node-fetch');\n return (fetchModule.default || fetchModule) as unknown as typeof fetch;\n};\n\nconst lazyLoaderHookFetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n loaderHook?: any,\n): Promise<Response> => {\n const hook = (url: RequestInfo | URL, init: RequestInit) => {\n return loaderHook.lifecycle.fetch.emit(url, init);\n };\n\n const res = await hook(input, init || {});\n if (!res || !(res instanceof Response)) {\n const fetchFunction =\n typeof fetch === 'undefined' ? await loadNodeFetch() : fetch;\n return fetchFunction(input, init || {});\n }\n\n return res;\n};\n\nexport const createScriptNode =\n typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'\n ? (\n url: string,\n cb: (error?: Error, scriptContext?: any) => void,\n attrs?: Record<string, any>,\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n fetch?: FetchHook;\n },\n ) => {\n if (loaderHook?.createScriptHook) {\n const hookResult = loaderHook.createScriptHook(url);\n if (\n hookResult &&\n typeof hookResult === 'object' &&\n 'url' in hookResult\n ) {\n url = hookResult.url;\n }\n }\n\n let urlObj: URL;\n try {\n urlObj = new URL(url);\n } catch (e) {\n console.error('Error constructing URL:', e);\n cb(new Error(`Invalid URL: ${e}`));\n return;\n }\n\n const getFetch = async (): Promise<typeof fetch> => {\n if (loaderHook?.fetch) {\n return (input: RequestInfo | URL, init?: RequestInit) =>\n lazyLoaderHookFetch(input, init, loaderHook);\n }\n\n return typeof fetch === 'undefined' ? loadNodeFetch() : fetch;\n };\n\n const handleScriptFetch = async (f: typeof fetch, urlObj: URL) => {\n try {\n const res = await f(urlObj.href);\n const data = await res.text();\n const [path, vm] = await Promise.all([\n importNodeModule<typeof import('path')>('path'),\n importNodeModule<typeof import('vm')>('vm'),\n ]);\n\n const scriptContext = { exports: {}, module: { exports: {} } };\n const urlDirname = urlObj.pathname\n .split('/')\n .slice(0, -1)\n .join('/');\n const filename = path.basename(urlObj.pathname);\n\n const script = new vm.Script(\n `(function(exports, module, require, __dirname, __filename) {${data}\\n})`,\n {\n filename,\n importModuleDynamically:\n //@ts-ignore\n vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER ??\n importNodeModule,\n },\n );\n\n let requireFn: NodeRequire;\n if (process.env.IS_ESM_BUILD === 'true') {\n const nodeModule =\n await importNodeModule<typeof import('node:module')>(\n 'node:module',\n );\n requireFn = nodeModule.createRequire(\n urlObj.protocol === 'file:' || urlObj.protocol === 'node:'\n ? urlObj.href\n : path.join(process.cwd(), '__mf_require_base__.js'),\n );\n } else {\n requireFn = eval('require') as NodeRequire;\n }\n\n script.runInThisContext()(\n scriptContext.exports,\n scriptContext.module,\n requireFn,\n urlDirname,\n filename,\n );\n const exportedInterface: Record<string, any> =\n scriptContext.module.exports || scriptContext.exports;\n\n if (attrs && exportedInterface && attrs['globalName']) {\n const container =\n exportedInterface[attrs['globalName']] || exportedInterface;\n cb(\n undefined,\n container as keyof typeof scriptContext.module.exports,\n );\n return;\n }\n\n cb(\n undefined,\n exportedInterface as keyof typeof scriptContext.module.exports,\n );\n } catch (e) {\n cb(\n e instanceof Error\n ? e\n : new Error(`Script execution error: ${e}`),\n );\n }\n };\n\n getFetch()\n .then(async (f) => {\n if (attrs?.['type'] === 'esm' || attrs?.['type'] === 'module') {\n return loadModule(urlObj.href, {\n fetch: f,\n vm: await importNodeModule<typeof import('vm')>('vm'),\n })\n .then(async (module) => {\n await module.evaluate();\n cb(undefined, module.namespace);\n })\n .catch((e) => {\n cb(\n e instanceof Error\n ? e\n : new Error(`Script execution error: ${e}`),\n );\n });\n }\n handleScriptFetch(f, urlObj);\n })\n .catch((err) => {\n cb(err);\n });\n }\n : (\n url: string,\n cb: (error?: Error, scriptContext?: any) => void,\n attrs?: Record<string, any>,\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n fetch?: FetchHook;\n },\n ) => {\n cb(\n new Error('createScriptNode is disabled in non-Node.js environment'),\n );\n };\n\nexport const loadScriptNode =\n typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'\n ? (\n url: string,\n info: {\n attrs?: Record<string, any>;\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n };\n },\n ) => {\n return new Promise<void>((resolve, reject) => {\n createScriptNode(\n url,\n (error, scriptContext) => {\n if (error) {\n reject(error);\n } else {\n const remoteEntryKey =\n info?.attrs?.['globalName'] ||\n `__FEDERATION_${info?.attrs?.['name']}:custom__`;\n const entryExports = ((globalThis as any)[remoteEntryKey] =\n scriptContext);\n resolve(entryExports);\n }\n },\n info.attrs,\n info.loaderHook,\n );\n });\n }\n : (\n url: string,\n info: {\n attrs?: Record<string, any>;\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n };\n },\n ) => {\n throw new Error(\n 'loadScriptNode is disabled in non-Node.js environment',\n );\n };\n\nconst esmModuleCache = new Map<string, any>();\n\nasync function loadModule(\n url: string,\n options: {\n vm: any;\n fetch: any;\n },\n) {\n // Check cache to prevent infinite recursion in ESM loading\n if (esmModuleCache.has(url)) {\n return esmModuleCache.get(url)!;\n }\n\n const { fetch, vm } = options;\n const response = await fetch(url);\n const code = await response.text();\n\n const module: any = new vm.SourceTextModule(code, {\n // @ts-ignore\n importModuleDynamically: async (specifier, script) => {\n const resolvedUrl = new URL(specifier, url).href;\n return loadModule(resolvedUrl, options);\n },\n });\n\n // Cache the module before linking to prevent cycles\n esmModuleCache.set(url, module);\n\n await module.link(async (specifier: string) => {\n const resolvedUrl = new URL(specifier, url).href;\n const module = await loadModule(resolvedUrl, options);\n return module;\n });\n\n return module;\n}\n"],"mappings":"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"}
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
let node_path = require("node:path");
//#region src/normalize-webpack-path.ts
function getWebpackPath(compiler, options = { framework: "other" }) {
const resolveWithContext = new Function("id", "options", "return typeof require === \"undefined\" ? \"\" : require.resolve(id, options)");
try {
compiler.webpack();
return "";
} catch (err) {
const webpackPath = ((err.stack?.split("\n") || []).find((item) => item.includes("at webpack")) || "").replace(/[^\(\)]+/, "").slice(1, -1).split(":").slice(0, -2).join(":");
if (options?.framework === "nextjs") {
if (webpackPath.endsWith("webpack.js")) return webpackPath.replace("webpack.js", "index.js");
return "";
}
return resolveWithContext("webpack", { paths: [webpackPath] });
}
}
const normalizeWebpackPath = (fullPath) => {
if (fullPath === "webpack") return process.env["FEDERATION_WEBPACK_PATH"] || fullPath;
if (process.env["FEDERATION_WEBPACK_PATH"]) return (0, node_path.resolve)(process.env["FEDERATION_WEBPACK_PATH"], fullPath.replace("webpack", "../../"));
return fullPath;
};
//#endregion
exports.getWebpackPath = getWebpackPath;
exports.normalizeWebpackPath = normalizeWebpackPath;
//# sourceMappingURL=normalize-webpack-path.cjs.map
{"version":3,"file":"normalize-webpack-path.cjs","names":[],"sources":["../src/normalize-webpack-path.ts"],"sourcesContent":["import type webpack from 'webpack';\nimport { resolve } from 'node:path';\n\nexport function getWebpackPath(\n compiler: webpack.Compiler,\n options: { framework: 'nextjs' | 'other' } = { framework: 'other' },\n): string {\n const resolveWithContext = new Function(\n 'id',\n 'options',\n 'return typeof require === \"undefined\" ? \"\" : require.resolve(id, options)',\n ) as (id: string, options?: { paths?: string[] }) => string;\n\n try {\n // @ts-ignore just throw err\n compiler.webpack();\n return '';\n } catch (err) {\n const trace = (err as Error).stack?.split('\\n') || [];\n const webpackErrLocation =\n trace.find((item) => item.includes('at webpack')) || '';\n const webpackLocationWithDetail = webpackErrLocation\n .replace(/[^\\(\\)]+/, '')\n .slice(1, -1);\n const webpackPath = webpackLocationWithDetail\n .split(':')\n .slice(0, -2)\n .join(':');\n if (options?.framework === 'nextjs') {\n if (webpackPath.endsWith('webpack.js')) {\n return webpackPath.replace('webpack.js', 'index.js');\n }\n return '';\n }\n return resolveWithContext('webpack', { paths: [webpackPath] });\n }\n}\n\nexport const normalizeWebpackPath = (fullPath: string): string => {\n if (fullPath === 'webpack') {\n return process.env['FEDERATION_WEBPACK_PATH'] || fullPath;\n }\n\n if (process.env['FEDERATION_WEBPACK_PATH']) {\n return resolve(\n process.env['FEDERATION_WEBPACK_PATH'],\n fullPath.replace('webpack', '../../'),\n );\n }\n\n return fullPath;\n};\n"],"mappings":";;;;AAGA,SAAgB,eACd,UACA,UAA6C,EAAE,WAAW,SAAS,EAC3D;CACR,MAAM,qBAAqB,IAAI,SAC7B,MACA,WACA,gFACD;AAED,KAAI;AAEF,WAAS,SAAS;AAClB,SAAO;UACA,KAAK;EAOZ,MAAM,gBANS,IAAc,OAAO,MAAM,KAAK,IAAI,EAAE,EAE7C,MAAM,SAAS,KAAK,SAAS,aAAa,CAAC,IAAI,IAEpD,QAAQ,YAAY,GAAG,CACvB,MAAM,GAAG,GAAG,CAEZ,MAAM,IAAI,CACV,MAAM,GAAG,GAAG,CACZ,KAAK,IAAI;AACZ,MAAI,SAAS,cAAc,UAAU;AACnC,OAAI,YAAY,SAAS,aAAa,CACpC,QAAO,YAAY,QAAQ,cAAc,WAAW;AAEtD,UAAO;;AAET,SAAO,mBAAmB,WAAW,EAAE,OAAO,CAAC,YAAY,EAAE,CAAC;;;AAIlE,MAAa,wBAAwB,aAA6B;AAChE,KAAI,aAAa,UACf,QAAO,QAAQ,IAAI,8BAA8B;AAGnD,KAAI,QAAQ,IAAI,2BACd,+BACE,QAAQ,IAAI,4BACZ,SAAS,QAAQ,WAAW,SAAS,CACtC;AAGH,QAAO"}
import webpack from "webpack";
//#region src/normalize-webpack-path.d.ts
declare function getWebpackPath(compiler: webpack.Compiler, options?: {
framework: 'nextjs' | 'other';
}): string;
declare const normalizeWebpackPath: (fullPath: string) => string;
//#endregion
export { getWebpackPath, normalizeWebpackPath };
//# sourceMappingURL=normalize-webpack-path.d.ts.map
import { resolve } from "node:path";
//#region src/normalize-webpack-path.ts
function getWebpackPath(compiler, options = { framework: "other" }) {
const resolveWithContext = new Function("id", "options", "return typeof require === \"undefined\" ? \"\" : require.resolve(id, options)");
try {
compiler.webpack();
return "";
} catch (err) {
const webpackPath = ((err.stack?.split("\n") || []).find((item) => item.includes("at webpack")) || "").replace(/[^\(\)]+/, "").slice(1, -1).split(":").slice(0, -2).join(":");
if (options?.framework === "nextjs") {
if (webpackPath.endsWith("webpack.js")) return webpackPath.replace("webpack.js", "index.js");
return "";
}
return resolveWithContext("webpack", { paths: [webpackPath] });
}
}
const normalizeWebpackPath = (fullPath) => {
if (fullPath === "webpack") return process.env["FEDERATION_WEBPACK_PATH"] || fullPath;
if (process.env["FEDERATION_WEBPACK_PATH"]) return resolve(process.env["FEDERATION_WEBPACK_PATH"], fullPath.replace("webpack", "../../"));
return fullPath;
};
//#endregion
export { getWebpackPath, normalizeWebpackPath };
//# sourceMappingURL=normalize-webpack-path.js.map
{"version":3,"file":"normalize-webpack-path.js","names":[],"sources":["../src/normalize-webpack-path.ts"],"sourcesContent":["import type webpack from 'webpack';\nimport { resolve } from 'node:path';\n\nexport function getWebpackPath(\n compiler: webpack.Compiler,\n options: { framework: 'nextjs' | 'other' } = { framework: 'other' },\n): string {\n const resolveWithContext = new Function(\n 'id',\n 'options',\n 'return typeof require === \"undefined\" ? \"\" : require.resolve(id, options)',\n ) as (id: string, options?: { paths?: string[] }) => string;\n\n try {\n // @ts-ignore just throw err\n compiler.webpack();\n return '';\n } catch (err) {\n const trace = (err as Error).stack?.split('\\n') || [];\n const webpackErrLocation =\n trace.find((item) => item.includes('at webpack')) || '';\n const webpackLocationWithDetail = webpackErrLocation\n .replace(/[^\\(\\)]+/, '')\n .slice(1, -1);\n const webpackPath = webpackLocationWithDetail\n .split(':')\n .slice(0, -2)\n .join(':');\n if (options?.framework === 'nextjs') {\n if (webpackPath.endsWith('webpack.js')) {\n return webpackPath.replace('webpack.js', 'index.js');\n }\n return '';\n }\n return resolveWithContext('webpack', { paths: [webpackPath] });\n }\n}\n\nexport const normalizeWebpackPath = (fullPath: string): string => {\n if (fullPath === 'webpack') {\n return process.env['FEDERATION_WEBPACK_PATH'] || fullPath;\n }\n\n if (process.env['FEDERATION_WEBPACK_PATH']) {\n return resolve(\n process.env['FEDERATION_WEBPACK_PATH'],\n fullPath.replace('webpack', '../../'),\n );\n }\n\n return fullPath;\n};\n"],"mappings":";;;AAGA,SAAgB,eACd,UACA,UAA6C,EAAE,WAAW,SAAS,EAC3D;CACR,MAAM,qBAAqB,IAAI,SAC7B,MACA,WACA,gFACD;AAED,KAAI;AAEF,WAAS,SAAS;AAClB,SAAO;UACA,KAAK;EAOZ,MAAM,gBANS,IAAc,OAAO,MAAM,KAAK,IAAI,EAAE,EAE7C,MAAM,SAAS,KAAK,SAAS,aAAa,CAAC,IAAI,IAEpD,QAAQ,YAAY,GAAG,CACvB,MAAM,GAAG,GAAG,CAEZ,MAAM,IAAI,CACV,MAAM,GAAG,GAAG,CACZ,KAAK,IAAI;AACZ,MAAI,SAAS,cAAc,UAAU;AACnC,OAAI,YAAY,SAAS,aAAa,CACpC,QAAO,YAAY,QAAQ,cAAc,WAAW;AAEtD,UAAO;;AAET,SAAO,mBAAmB,WAAW,EAAE,OAAO,CAAC,YAAY,EAAE,CAAC;;;AAIlE,MAAa,wBAAwB,aAA6B;AAChE,KAAI,aAAa,UACf,QAAO,QAAQ,IAAI,8BAA8B;AAGnD,KAAI,QAAQ,IAAI,2BACd,QAAO,QACL,QAAQ,IAAI,4BACZ,SAAS,QAAQ,WAAW,SAAS,CACtC;AAGH,QAAO"}
//#region src/normalizeOptions.ts
function normalizeOptions(enableDefault, defaultOptions, key) {
return function(options) {
if (options === false) return false;
if (typeof options === "undefined") if (enableDefault) return defaultOptions;
else return false;
if (options === true) return defaultOptions;
if (options && typeof options === "object") return {
...defaultOptions,
...options
};
throw new Error(`Unexpected type for \`${key}\`, expect boolean/undefined/object, got: ${typeof options}`);
};
}
//#endregion
exports.normalizeOptions = normalizeOptions;
//# sourceMappingURL=normalizeOptions.cjs.map
{"version":3,"file":"normalizeOptions.cjs","names":[],"sources":["../src/normalizeOptions.ts"],"sourcesContent":["export function normalizeOptions<T>(\n enableDefault: boolean,\n defaultOptions: T,\n key: string,\n) {\n return function <U extends boolean | undefined | T>(options: U): T | false {\n if (options === false) {\n return false;\n }\n\n if (typeof options === 'undefined') {\n if (enableDefault) {\n return defaultOptions;\n } else {\n return false;\n }\n }\n\n if (options === true) {\n return defaultOptions;\n }\n\n if (options && typeof options === 'object') {\n return {\n ...(defaultOptions as T),\n ...options,\n };\n }\n\n throw new Error(\n `Unexpected type for \\`${key}\\`, expect boolean/undefined/object, got: ${typeof options}`,\n );\n };\n}\n"],"mappings":";;AAAA,SAAgB,iBACd,eACA,gBACA,KACA;AACA,QAAO,SAA6C,SAAuB;AACzE,MAAI,YAAY,MACd,QAAO;AAGT,MAAI,OAAO,YAAY,YACrB,KAAI,cACF,QAAO;MAEP,QAAO;AAIX,MAAI,YAAY,KACd,QAAO;AAGT,MAAI,WAAW,OAAO,YAAY,SAChC,QAAO;GACL,GAAI;GACJ,GAAG;GACJ;AAGH,QAAM,IAAI,MACR,yBAAyB,IAAI,4CAA4C,OAAO,UACjF"}
//#region src/normalizeOptions.d.ts
declare function normalizeOptions<T>(enableDefault: boolean, defaultOptions: T, key: string): <U extends boolean | undefined | T>(options: U) => T | false;
//#endregion
export { normalizeOptions };
//# sourceMappingURL=normalizeOptions.d.ts.map
//#region src/normalizeOptions.ts
function normalizeOptions(enableDefault, defaultOptions, key) {
return function(options) {
if (options === false) return false;
if (typeof options === "undefined") if (enableDefault) return defaultOptions;
else return false;
if (options === true) return defaultOptions;
if (options && typeof options === "object") return {
...defaultOptions,
...options
};
throw new Error(`Unexpected type for \`${key}\`, expect boolean/undefined/object, got: ${typeof options}`);
};
}
//#endregion
export { normalizeOptions };
//# sourceMappingURL=normalizeOptions.js.map
{"version":3,"file":"normalizeOptions.js","names":[],"sources":["../src/normalizeOptions.ts"],"sourcesContent":["export function normalizeOptions<T>(\n enableDefault: boolean,\n defaultOptions: T,\n key: string,\n) {\n return function <U extends boolean | undefined | T>(options: U): T | false {\n if (options === false) {\n return false;\n }\n\n if (typeof options === 'undefined') {\n if (enableDefault) {\n return defaultOptions;\n } else {\n return false;\n }\n }\n\n if (options === true) {\n return defaultOptions;\n }\n\n if (options && typeof options === 'object') {\n return {\n ...(defaultOptions as T),\n ...options,\n };\n }\n\n throw new Error(\n `Unexpected type for \\`${key}\\`, expect boolean/undefined/object, got: ${typeof options}`,\n );\n };\n}\n"],"mappings":";AAAA,SAAgB,iBACd,eACA,gBACA,KACA;AACA,QAAO,SAA6C,SAAuB;AACzE,MAAI,YAAY,MACd,QAAO;AAGT,MAAI,OAAO,YAAY,YACrB,KAAI,cACF,QAAO;MAEP,QAAO;AAIX,MAAI,YAAY,KACd,QAAO;AAGT,MAAI,WAAW,OAAO,YAAY,SAChC,QAAO;GACL,GAAI;GACJ,GAAG;GACJ;AAGH,QAAM,IAAI,MACR,yBAAyB,IAAI,4CAA4C,OAAO,UACjF"}
//#region src/types/common.d.ts
interface RemoteWithEntry {
name: string;
entry: string;
}
interface RemoteWithVersion {
name: string;
version: string;
}
type RemoteEntryInfo = RemoteWithEntry | RemoteWithVersion;
type Module = any;
//#endregion
export { Module, RemoteEntryInfo, RemoteWithEntry, RemoteWithVersion };
//# sourceMappingURL=common.d.ts.map
//#region src/types/hooks.d.ts
type CreateScriptHookReturnNode = {
url: string;
} | void;
type CreateScriptHookReturnDom = HTMLScriptElement | {
script?: HTMLScriptElement;
timeout?: number;
} | void;
type CreateScriptHookReturn = CreateScriptHookReturnNode | CreateScriptHookReturnDom;
type CreateScriptHookNode = (url: string, attrs?: Record<string, any> | undefined) => CreateScriptHookReturnNode;
type CreateScriptHookDom = (url: string, attrs?: Record<string, any> | undefined) => CreateScriptHookReturnDom;
type CreateScriptHook = (url: string, attrs?: Record<string, any> | undefined) => CreateScriptHookReturn;
type FetchHook = (args: [string, RequestInit]) => Promise<Response> | void | false;
//#endregion
export { CreateScriptHook, CreateScriptHookDom, CreateScriptHookNode, CreateScriptHookReturn, CreateScriptHookReturnDom, CreateScriptHookReturnNode, FetchHook };
//# sourceMappingURL=hooks.d.ts.map
import { Module, RemoteEntryInfo, RemoteWithEntry, RemoteWithVersion } from "./common.js";
import { BasicStatsMetaData, ManifestModuleInfos, MetaDataTypes, RemoteEntryType, ResourceInfo, Stats, StatsAssets, StatsBuildInfo, StatsExpose, StatsMetaData, StatsMetaDataWithGetPublicPath, StatsMetaDataWithPublicPath, StatsModuleInfo, StatsRemote, StatsRemoteVal, StatsRemoteWithEntry, StatsRemoteWithVersion, StatsShared } from "./stats.js";
import { Manifest, ManifestExpose, ManifestRemote, ManifestRemoteCommonInfo, ManifestShared } from "./manifest.js";
import { BasicProviderModuleInfo, ConsumerModuleInfo, ConsumerModuleInfoWithPublicPath, GlobalModuleInfo, ManifestProvider, ModuleInfo, ProviderModuleInfo, PureConsumerModuleInfo, PureEntryProvider } from "./snapshot.js";
import { ModuleFederationPlugin_d_exports } from "./plugins/ModuleFederationPlugin.js";
import { ContainerPlugin_d_exports } from "./plugins/ContainerPlugin.js";
import { ContainerReferencePlugin_d_exports } from "./plugins/ContainerReferencePlugin.js";
import { SharePlugin_d_exports } from "./plugins/SharePlugin.js";
import { ConsumeSharedPlugin_d_exports } from "./plugins/ConsumeSharedPlugin.js";
import { ProvideSharedPlugin_d_exports } from "./plugins/ProvideSharedPlugin.js";
import { CreateScriptHook, CreateScriptHookDom, CreateScriptHookNode, CreateScriptHookReturn, CreateScriptHookReturnDom, CreateScriptHookReturnNode, FetchHook } from "./hooks.js";
import { RemoteWithEntry, RemoteWithVersion } from "./common.js";
import { BasicStatsMetaData, RemoteEntryType, StatsAssets, StatsExpose, StatsMetaData } from "./stats.js";
//#region src/types/manifest.d.ts
interface ManifestShared {
id: string;
name: string;
version: string;
singleton: boolean;
requiredVersion: string;
hash: string;
assets: StatsAssets;
fallback?: string;
fallbackName?: string;
fallbackType?: RemoteEntryType;
}
interface ManifestRemoteCommonInfo {
federationContainerName: string;
moduleName: string;
alias: string;
}
type ManifestRemote<T = ManifestRemoteCommonInfo> = (Omit<RemoteWithEntry, 'name'> & T) | (Omit<RemoteWithVersion, 'name'> & T);
type ManifestExpose = Pick<StatsExpose, 'assets' | 'id' | 'name' | 'path'>;
interface Manifest<T = BasicStatsMetaData, K = ManifestRemoteCommonInfo> {
id: string;
name: string;
metaData: StatsMetaData<T>;
shared: ManifestShared[];
remotes: ManifestRemote<K>[];
exposes: ManifestExpose[];
}
//#endregion
export { Manifest, ManifestExpose, ManifestRemote, ManifestRemoteCommonInfo, ManifestShared };
//# sourceMappingURL=manifest.d.ts.map
const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
//#region src/types/plugins/ConsumeSharedPlugin.ts
var ConsumeSharedPlugin_exports = /* @__PURE__ */ require_runtime.__exportAll({});
//#endregion
Object.defineProperty(exports, 'ConsumeSharedPlugin_exports', {
enumerable: true,
get: function () {
return ConsumeSharedPlugin_exports;
}
});
//# sourceMappingURL=ConsumeSharedPlugin.cjs.map
{"version":3,"file":"ConsumeSharedPlugin.cjs","names":[],"sources":["../../../src/types/plugins/ConsumeSharedPlugin.ts"],"sourcesContent":["/*\n * This file was automatically generated.\n * DO NOT MODIFY BY HAND.\n * Run `pnpm generate:schema -w` to update.\n */\n\n/**\n * A module that should be consumed from share scope.\n */\nexport type ConsumesItem = string;\n\n/**\n * Advanced configuration for modules that should be consumed from share scope.\n */\nexport interface ConsumesConfig {\n /**\n * Include the fallback module directly instead behind an async request. This allows to use fallback module in initial load too. All possible shared modules need to be eager too.\n */\n eager?: boolean;\n /**\n * Fallback module if no shared module is found in share scope. Defaults to the property name.\n */\n import?: false | ConsumesItem;\n /**\n * Package name to determine required version from description file. This is only needed when package name can't be automatically determined from request.\n */\n packageName?: string;\n /**\n * Version requirement from module in share scope.\n */\n requiredVersion?: false | string;\n /**\n * Module is looked up under this key from the share scope.\n */\n shareKey?: string;\n /**\n * Share scope name.\n */\n shareScope?: string | string[];\n /**\n * Layer in which the shared module should be placed.\n */\n layer?: string;\n /**\n * Layer of the issuer.\n */\n issuerLayer?: string;\n /**\n * Import request to match on\n */\n request?: string;\n /**\n * Allow only a single version of the shared module in share scope (disabled by default).\n */\n singleton?: boolean;\n /**\n * Do not accept shared module if version is not valid (defaults to yes, if local fallback module is available and shared module is not a singleton, otherwise no, has no effect if there is no required version specified).\n */\n strictVersion?: boolean;\n /**\n * Filter consumed modules based on the request path.\n */\n exclude?: IncludeExcludeOptions;\n /**\n * Filter consumed modules based on the request path (only include matches).\n */\n include?: IncludeExcludeOptions;\n /**\n * Enable reconstructed lookup for node_modules paths for this share item\n */\n allowNodeModulesSuffixMatch?: boolean;\n /**\n * Tree shaking mode for the shared module.\n */\n treeShakingMode?: 'server-calc' | 'runtime-infer';\n}\n\n/**\n * Modules that should be consumed from share scope. Property names are used to match requested modules in this compilation. Relative requests are resolved, module requests are matched unresolved, absolute paths will match resolved requests. A trailing slash will match all requests with this prefix. In this case shareKey must also have a trailing slash.\n */\nexport interface ConsumesObject {\n [k: string]: ConsumesConfig | ConsumesItem;\n}\n\n/**\n * Modules that should be consumed from share scope. When provided, property names are used to match requested modules in this compilation.\n */\nexport type Consumes = (ConsumesItem | ConsumesObject)[] | ConsumesObject;\n\nexport interface IncludeExcludeOptions {\n request?: string | RegExp;\n /**\n * Semantic versioning range to match against the module's version.\n */\n version?: string;\n /**\n * Optional specific version string to check against the version range instead of reading package.json.\n */\n fallbackVersion?: string;\n}\n\nexport interface ConsumeSharedPluginOptions {\n consumes: Consumes;\n /**\n * Share scope name used for all consumed modules (defaults to 'default').\n */\n shareScope?: string | string[];\n /**\n * Experimental features configuration\n */\n experiments?: {\n /** Enable reconstructed lookup for node_modules paths */\n allowNodeModulesSuffixMatch?: boolean;\n };\n}\n"],"mappings":""}
declare namespace ConsumeSharedPlugin_d_exports {
export { ConsumeSharedPluginOptions, Consumes, ConsumesConfig, ConsumesItem, ConsumesObject, IncludeExcludeOptions };
}
/**
* A module that should be consumed from share scope.
*/
type ConsumesItem = string;
/**
* Advanced configuration for modules that should be consumed from share scope.
*/
interface ConsumesConfig {
/**
* Include the fallback module directly instead behind an async request. This allows to use fallback module in initial load too. All possible shared modules need to be eager too.
*/
eager?: boolean;
/**
* Fallback module if no shared module is found in share scope. Defaults to the property name.
*/
import?: false | ConsumesItem;
/**
* Package name to determine required version from description file. This is only needed when package name can't be automatically determined from request.
*/
packageName?: string;
/**
* Version requirement from module in share scope.
*/
requiredVersion?: false | string;
/**
* Module is looked up under this key from the share scope.
*/
shareKey?: string;
/**
* Share scope name.
*/
shareScope?: string | string[];
/**
* Layer in which the shared module should be placed.
*/
layer?: string;
/**
* Layer of the issuer.
*/
issuerLayer?: string;
/**
* Import request to match on
*/
request?: string;
/**
* Allow only a single version of the shared module in share scope (disabled by default).
*/
singleton?: boolean;
/**
* Do not accept shared module if version is not valid (defaults to yes, if local fallback module is available and shared module is not a singleton, otherwise no, has no effect if there is no required version specified).
*/
strictVersion?: boolean;
/**
* Filter consumed modules based on the request path.
*/
exclude?: IncludeExcludeOptions;
/**
* Filter consumed modules based on the request path (only include matches).
*/
include?: IncludeExcludeOptions;
/**
* Enable reconstructed lookup for node_modules paths for this share item
*/
allowNodeModulesSuffixMatch?: boolean;
/**
* Tree shaking mode for the shared module.
*/
treeShakingMode?: 'server-calc' | 'runtime-infer';
}
/**
* Modules that should be consumed from share scope. Property names are used to match requested modules in this compilation. Relative requests are resolved, module requests are matched unresolved, absolute paths will match resolved requests. A trailing slash will match all requests with this prefix. In this case shareKey must also have a trailing slash.
*/
interface ConsumesObject {
[k: string]: ConsumesConfig | ConsumesItem;
}
/**
* Modules that should be consumed from share scope. When provided, property names are used to match requested modules in this compilation.
*/
type Consumes = (ConsumesItem | ConsumesObject)[] | ConsumesObject;
interface IncludeExcludeOptions {
request?: string | RegExp;
/**
* Semantic versioning range to match against the module's version.
*/
version?: string;
/**
* Optional specific version string to check against the version range instead of reading package.json.
*/
fallbackVersion?: string;
}
interface ConsumeSharedPluginOptions {
consumes: Consumes;
/**
* Share scope name used for all consumed modules (defaults to 'default').
*/
shareScope?: string | string[];
/**
* Experimental features configuration
*/
experiments?: {
/** Enable reconstructed lookup for node_modules paths */allowNodeModulesSuffixMatch?: boolean;
};
}
//#endregion
export { ConsumeSharedPlugin_d_exports, IncludeExcludeOptions };
//# sourceMappingURL=ConsumeSharedPlugin.d.ts.map
import { __exportAll } from "../../_virtual/_rolldown/runtime.js";
//#region src/types/plugins/ConsumeSharedPlugin.ts
var ConsumeSharedPlugin_exports = /* @__PURE__ */ __exportAll({});
//#endregion
export { ConsumeSharedPlugin_exports };
//# sourceMappingURL=ConsumeSharedPlugin.js.map
{"version":3,"file":"ConsumeSharedPlugin.js","names":[],"sources":["../../../src/types/plugins/ConsumeSharedPlugin.ts"],"sourcesContent":["/*\n * This file was automatically generated.\n * DO NOT MODIFY BY HAND.\n * Run `pnpm generate:schema -w` to update.\n */\n\n/**\n * A module that should be consumed from share scope.\n */\nexport type ConsumesItem = string;\n\n/**\n * Advanced configuration for modules that should be consumed from share scope.\n */\nexport interface ConsumesConfig {\n /**\n * Include the fallback module directly instead behind an async request. This allows to use fallback module in initial load too. All possible shared modules need to be eager too.\n */\n eager?: boolean;\n /**\n * Fallback module if no shared module is found in share scope. Defaults to the property name.\n */\n import?: false | ConsumesItem;\n /**\n * Package name to determine required version from description file. This is only needed when package name can't be automatically determined from request.\n */\n packageName?: string;\n /**\n * Version requirement from module in share scope.\n */\n requiredVersion?: false | string;\n /**\n * Module is looked up under this key from the share scope.\n */\n shareKey?: string;\n /**\n * Share scope name.\n */\n shareScope?: string | string[];\n /**\n * Layer in which the shared module should be placed.\n */\n layer?: string;\n /**\n * Layer of the issuer.\n */\n issuerLayer?: string;\n /**\n * Import request to match on\n */\n request?: string;\n /**\n * Allow only a single version of the shared module in share scope (disabled by default).\n */\n singleton?: boolean;\n /**\n * Do not accept shared module if version is not valid (defaults to yes, if local fallback module is available and shared module is not a singleton, otherwise no, has no effect if there is no required version specified).\n */\n strictVersion?: boolean;\n /**\n * Filter consumed modules based on the request path.\n */\n exclude?: IncludeExcludeOptions;\n /**\n * Filter consumed modules based on the request path (only include matches).\n */\n include?: IncludeExcludeOptions;\n /**\n * Enable reconstructed lookup for node_modules paths for this share item\n */\n allowNodeModulesSuffixMatch?: boolean;\n /**\n * Tree shaking mode for the shared module.\n */\n treeShakingMode?: 'server-calc' | 'runtime-infer';\n}\n\n/**\n * Modules that should be consumed from share scope. Property names are used to match requested modules in this compilation. Relative requests are resolved, module requests are matched unresolved, absolute paths will match resolved requests. A trailing slash will match all requests with this prefix. In this case shareKey must also have a trailing slash.\n */\nexport interface ConsumesObject {\n [k: string]: ConsumesConfig | ConsumesItem;\n}\n\n/**\n * Modules that should be consumed from share scope. When provided, property names are used to match requested modules in this compilation.\n */\nexport type Consumes = (ConsumesItem | ConsumesObject)[] | ConsumesObject;\n\nexport interface IncludeExcludeOptions {\n request?: string | RegExp;\n /**\n * Semantic versioning range to match against the module's version.\n */\n version?: string;\n /**\n * Optional specific version string to check against the version range instead of reading package.json.\n */\n fallbackVersion?: string;\n}\n\nexport interface ConsumeSharedPluginOptions {\n consumes: Consumes;\n /**\n * Share scope name used for all consumed modules (defaults to 'default').\n */\n shareScope?: string | string[];\n /**\n * Experimental features configuration\n */\n experiments?: {\n /** Enable reconstructed lookup for node_modules paths */\n allowNodeModulesSuffixMatch?: boolean;\n };\n}\n"],"mappings":""}
const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
//#region src/types/plugins/ContainerPlugin.ts
var ContainerPlugin_exports = /* @__PURE__ */ require_runtime.__exportAll({});
//#endregion
Object.defineProperty(exports, 'ContainerPlugin_exports', {
enumerable: true,
get: function () {
return ContainerPlugin_exports;
}
});
//# sourceMappingURL=ContainerPlugin.cjs.map
{"version":3,"file":"ContainerPlugin.cjs","names":[],"sources":["../../../src/types/plugins/ContainerPlugin.ts"],"sourcesContent":["/*\n * This file was automatically generated.\n * DO NOT MODIFY BY HAND.\n * Run `pnpm generate:schema -w` to update.\n */\n\nimport type {\n Exposes,\n EntryRuntime,\n LibraryOptions,\n} from './ModuleFederationPlugin';\n\nexport interface ContainerPluginOptions {\n exposes: Exposes;\n /**\n * The filename for this container relative path inside the `output.path` directory.\n */\n filename?: string;\n library?: LibraryOptions;\n /**\n * The name for this container.\n */\n name: string;\n runtime?: EntryRuntime;\n /**\n * The name of the share scope which is shared with the host (defaults to 'default').\n */\n shareScope?: string | string[];\n /**\n * Experimental features configuration\n */\n experiments?: {\n /** Enable async startup for the container */\n asyncStartup?: boolean;\n /** After setting true, the external MF runtime will be used and the runtime provided by the consumer will be used. (Please make sure your consumer has provideExternalRuntime: true set, otherwise it will not run properly!) */\n externalRuntime?: boolean;\n /** Enable providing external runtime */\n provideExternalRuntime?: boolean;\n };\n /**\n * Enable data prefetching for container modules.\n */\n dataPrefetch?: boolean;\n /**\n * Array of runtime plugins to be applied\n */\n runtimePlugins?: (string | unknown[])[];\n}\n"],"mappings":""}
import { EntryRuntime, Exposes, LibraryOptions } from "./ModuleFederationPlugin.js";
//#region src/types/plugins/ContainerPlugin.d.ts
declare namespace ContainerPlugin_d_exports {
export { ContainerPluginOptions };
}
interface ContainerPluginOptions {
exposes: Exposes;
/**
* The filename for this container relative path inside the `output.path` directory.
*/
filename?: string;
library?: LibraryOptions;
/**
* The name for this container.
*/
name: string;
runtime?: EntryRuntime;
/**
* The name of the share scope which is shared with the host (defaults to 'default').
*/
shareScope?: string | string[];
/**
* Experimental features configuration
*/
experiments?: {
/** Enable async startup for the container */asyncStartup?: boolean; /** After setting true, the external MF runtime will be used and the runtime provided by the consumer will be used. (Please make sure your consumer has provideExternalRuntime: true set, otherwise it will not run properly!) */
externalRuntime?: boolean; /** Enable providing external runtime */
provideExternalRuntime?: boolean;
};
/**
* Enable data prefetching for container modules.
*/
dataPrefetch?: boolean;
/**
* Array of runtime plugins to be applied
*/
runtimePlugins?: (string | unknown[])[];
}
//#endregion
export { ContainerPlugin_d_exports };
//# sourceMappingURL=ContainerPlugin.d.ts.map
import { __exportAll } from "../../_virtual/_rolldown/runtime.js";
//#region src/types/plugins/ContainerPlugin.ts
var ContainerPlugin_exports = /* @__PURE__ */ __exportAll({});
//#endregion
export { ContainerPlugin_exports };
//# sourceMappingURL=ContainerPlugin.js.map
{"version":3,"file":"ContainerPlugin.js","names":[],"sources":["../../../src/types/plugins/ContainerPlugin.ts"],"sourcesContent":["/*\n * This file was automatically generated.\n * DO NOT MODIFY BY HAND.\n * Run `pnpm generate:schema -w` to update.\n */\n\nimport type {\n Exposes,\n EntryRuntime,\n LibraryOptions,\n} from './ModuleFederationPlugin';\n\nexport interface ContainerPluginOptions {\n exposes: Exposes;\n /**\n * The filename for this container relative path inside the `output.path` directory.\n */\n filename?: string;\n library?: LibraryOptions;\n /**\n * The name for this container.\n */\n name: string;\n runtime?: EntryRuntime;\n /**\n * The name of the share scope which is shared with the host (defaults to 'default').\n */\n shareScope?: string | string[];\n /**\n * Experimental features configuration\n */\n experiments?: {\n /** Enable async startup for the container */\n asyncStartup?: boolean;\n /** After setting true, the external MF runtime will be used and the runtime provided by the consumer will be used. (Please make sure your consumer has provideExternalRuntime: true set, otherwise it will not run properly!) */\n externalRuntime?: boolean;\n /** Enable providing external runtime */\n provideExternalRuntime?: boolean;\n };\n /**\n * Enable data prefetching for container modules.\n */\n dataPrefetch?: boolean;\n /**\n * Array of runtime plugins to be applied\n */\n runtimePlugins?: (string | unknown[])[];\n}\n"],"mappings":""}
const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
//#region src/types/plugins/ContainerReferencePlugin.ts
var ContainerReferencePlugin_exports = /* @__PURE__ */ require_runtime.__exportAll({});
//#endregion
Object.defineProperty(exports, 'ContainerReferencePlugin_exports', {
enumerable: true,
get: function () {
return ContainerReferencePlugin_exports;
}
});
//# sourceMappingURL=ContainerReferencePlugin.cjs.map
{"version":3,"file":"ContainerReferencePlugin.cjs","names":[],"sources":["../../../src/types/plugins/ContainerReferencePlugin.ts"],"sourcesContent":["/*\n * This file was automatically generated.\n * DO NOT MODIFY BY HAND.\n * Run `pnpm generate:schema -w` to update.\n */\n\nimport type { ExternalsType, Remotes } from './ModuleFederationPlugin';\n\nexport interface ContainerReferencePluginOptions {\n /**\n * Enable/disable asynchronous loading of runtime modules. When enabled, entry points will be wrapped in asynchronous chunks.\n */\n async?: boolean;\n /**\n * The external type of the remote containers.\n */\n remoteType: ExternalsType;\n remotes: Remotes;\n /**\n * The name of the share scope shared with all remotes (defaults to 'default').\n */\n shareScope?: string | string[];\n}\n"],"mappings":""}
import { ExternalsType, Remotes } from "./ModuleFederationPlugin.js";
//#region src/types/plugins/ContainerReferencePlugin.d.ts
declare namespace ContainerReferencePlugin_d_exports {
export { ContainerReferencePluginOptions };
}
interface ContainerReferencePluginOptions {
/**
* Enable/disable asynchronous loading of runtime modules. When enabled, entry points will be wrapped in asynchronous chunks.
*/
async?: boolean;
/**
* The external type of the remote containers.
*/
remoteType: ExternalsType;
remotes: Remotes;
/**
* The name of the share scope shared with all remotes (defaults to 'default').
*/
shareScope?: string | string[];
}
//#endregion
export { ContainerReferencePlugin_d_exports };
//# sourceMappingURL=ContainerReferencePlugin.d.ts.map
import { __exportAll } from "../../_virtual/_rolldown/runtime.js";
//#region src/types/plugins/ContainerReferencePlugin.ts
var ContainerReferencePlugin_exports = /* @__PURE__ */ __exportAll({});
//#endregion
export { ContainerReferencePlugin_exports };
//# sourceMappingURL=ContainerReferencePlugin.js.map
{"version":3,"file":"ContainerReferencePlugin.js","names":[],"sources":["../../../src/types/plugins/ContainerReferencePlugin.ts"],"sourcesContent":["/*\n * This file was automatically generated.\n * DO NOT MODIFY BY HAND.\n * Run `pnpm generate:schema -w` to update.\n */\n\nimport type { ExternalsType, Remotes } from './ModuleFederationPlugin';\n\nexport interface ContainerReferencePluginOptions {\n /**\n * Enable/disable asynchronous loading of runtime modules. When enabled, entry points will be wrapped in asynchronous chunks.\n */\n async?: boolean;\n /**\n * The external type of the remote containers.\n */\n remoteType: ExternalsType;\n remotes: Remotes;\n /**\n * The name of the share scope shared with all remotes (defaults to 'default').\n */\n shareScope?: string | string[];\n}\n"],"mappings":""}
import { ModuleFederationPlugin_d_exports } from "./ModuleFederationPlugin.js";
import { ContainerPlugin_d_exports } from "./ContainerPlugin.js";
import { ContainerReferencePlugin_d_exports } from "./ContainerReferencePlugin.js";
import { SharePlugin_d_exports } from "./SharePlugin.js";
import { ConsumeSharedPlugin_d_exports } from "./ConsumeSharedPlugin.js";
import { ProvideSharedPlugin_d_exports } from "./ProvideSharedPlugin.js";
const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
//#region src/types/plugins/ModuleFederationPlugin.ts
var ModuleFederationPlugin_exports = /* @__PURE__ */ require_runtime.__exportAll({});
//#endregion
Object.defineProperty(exports, 'ModuleFederationPlugin_exports', {
enumerable: true,
get: function () {
return ModuleFederationPlugin_exports;
}
});
//# sourceMappingURL=ModuleFederationPlugin.cjs.map
{"version":3,"file":"ModuleFederationPlugin.cjs","names":[],"sources":["../../../src/types/plugins/ModuleFederationPlugin.ts"],"sourcesContent":["import type { Stats } from '../stats';\nimport type webpack from 'webpack';\n\n// <-- BEGIN SCHEMA-GENERATED TYPES -->\n/**\n * Module that should be exposed by this container.\n */\nexport type ExposesItem = string;\n\n/**\n * Modules that should be exposed by this container.\n */\nexport type ExposesItems = ExposesItem[];\n\n/**\n * Modules that should be exposed by this container. Property names are used as public paths.\n */\nexport interface ExposesObject {\n [k: string]: ExposesConfig | ExposesItem | ExposesItems;\n}\n\n/**\n * Advanced configuration for modules that should be exposed by this container.\n */\nexport interface ExposesConfig {\n /**\n * Request to a module that should be exposed by this container.\n */\n import: ExposesItem | ExposesItems;\n /**\n * Custom chunk name for the exposed module.\n */\n name?: string;\n}\n\n/**\n * Modules that should be exposed by this container. When provided, property name is used as public name, otherwise public name is automatically inferred from request.\n */\nexport type Exposes = (ExposesItem | ExposesObject)[] | ExposesObject;\n\n/**\n * Add a container for define/require functions in the AMD module.\n */\nexport type AmdContainer = string;\n\n/**\n * Add a comment in the UMD wrapper.\n */\nexport type AuxiliaryComment = string | LibraryCustomUmdCommentObject;\n\n/**\n * Set explicit comments for `commonjs`, `commonjs2`, `amd`, and `root`.\n */\nexport interface LibraryCustomUmdCommentObject {\n /**\n * Set comment for `amd` section in UMD.\n */\n amd?: string;\n /**\n * Set comment for `commonjs` (exports) section in UMD.\n */\n commonjs?: string;\n /**\n * Set comment for `commonjs2` (module.exports) section in UMD.\n */\n commonjs2?: string;\n /**\n * Set comment for `root` (global variable) section in UMD.\n */\n root?: string;\n}\n\n/**\n * Description object for all UMD variants of the library name.\n */\nexport interface LibraryCustomUmdObject {\n /**\n * Name of the exposed AMD library in the UMD.\n */\n amd?: string;\n /**\n * Name of the exposed commonjs export in the UMD.\n */\n commonjs?: string;\n /**\n * Name of the property exposed globally by a UMD library.\n */\n root?: string[] | string;\n}\n\n/**\n * Specify which export should be exposed as library.\n */\nexport type LibraryExport = string[] | string;\n\n/**\n * The name of the library (some types allow unnamed libraries too).\n */\nexport type LibraryName = string[] | string | LibraryCustomUmdObject;\n\n/**\n * Type of library (types included by default are 'var', 'module', 'assign', 'assign-properties', 'this', 'window', 'self', 'global', 'commonjs', 'commonjs2', 'commonjs-module', 'commonjs-static', 'amd', 'amd-require', 'umd', 'umd2', 'jsonp', 'system', but others might be added by plugins).\n */\nexport type LibraryType =\n | 'var'\n | 'module'\n | 'assign'\n | 'assign-properties'\n | 'this'\n | 'window'\n | 'self'\n | 'global'\n | 'commonjs'\n | 'commonjs2'\n | 'commonjs-module'\n | 'commonjs-static'\n | 'amd'\n | 'amd-require'\n | 'umd'\n | 'umd2'\n | 'jsonp'\n | 'system'\n | string;\n\n/**\n * Options for library.\n */\nexport interface LibraryOptions {\n amdContainer?: AmdContainer;\n auxiliaryComment?: AuxiliaryComment;\n export?: LibraryExport;\n name?: LibraryName;\n type: LibraryType;\n umdNamedDefine?: UmdNamedDefine;\n}\n\n/**\n * If `output.libraryTarget` is set to umd and `output.library` is set, setting this to true will name the AMD module.\n */\nexport type UmdNamedDefine = boolean;\n\n/**\n * Specifies the default type of externals ('amd*', 'umd*', 'system' and 'jsonp' depend on output.libraryTarget set to the same value).\n */\nexport type ExternalsType =\n | 'var'\n | 'module'\n | 'assign'\n | 'this'\n | 'window'\n | 'self'\n | 'global'\n | 'commonjs'\n | 'commonjs2'\n | 'commonjs-module'\n | 'commonjs-static'\n | 'amd'\n | 'amd-require'\n | 'umd'\n | 'umd2'\n | 'jsonp'\n | 'system'\n | 'promise'\n | 'import'\n | 'module-import'\n | 'script'\n | 'node-commonjs';\n\n/**\n * Container location from which modules should be resolved and loaded at runtime.\n */\nexport type RemotesItem = string;\n\n/**\n * Container locations from which modules should be resolved and loaded at runtime.\n */\nexport type RemotesItems = RemotesItem[];\n\n/**\n * Container locations from which modules should be resolved and loaded at runtime. Property names are used as request scopes.\n */\nexport interface RemotesObject {\n [k: string]: RemotesConfig | RemotesItem | RemotesItems;\n}\n\n/**\n * Advanced configuration for container locations from which modules should be resolved and loaded at runtime.\n */\nexport interface RemotesConfig {\n /**\n * Container locations from which modules should be resolved and loaded at runtime.\n */\n external: RemotesItem | RemotesItems;\n /**\n * The name of the share scope shared with this remote.\n */\n shareScope?: string | string[];\n}\n\n/**\n * Container locations and request scopes from which modules should be resolved and loaded at runtime. When provided, property name is used as request scope, otherwise request scope is automatically inferred from container location.\n */\nexport type Remotes = (RemotesItem | RemotesObject)[] | RemotesObject;\n\n/**\n * The name of the runtime chunk. If set a runtime chunk with this name is created or an existing entrypoint is used as runtime.\n */\nexport type EntryRuntime = false | string;\n\n/**\n * A module that should be shared in the share scope.\n */\nexport type SharedItem = string;\n\n/**\n * Modules that should be shared in the share scope. Property names are used to match requested modules in this compilation. Relative requests are resolved, module requests are matched unresolved, absolute paths will match resolved requests. A trailing slash will match all requests with this prefix. In this case shareKey must also have a trailing slash.\n */\nexport interface SharedObject {\n [k: string]: SharedConfig | SharedItem;\n}\n\n/**\n * Advanced configuration for modules that should be shared in the share scope.\n */\nexport interface SharedConfig {\n /**\n * Include the provided and fallback module directly instead behind an async request. This allows to use this shared module in initial load too. All possible shared modules need to be eager too.\n */\n eager?: boolean;\n /**\n * Options for excluding specific versions or request paths of the shared module. When specified, matching modules will not be shared. Cannot be used with 'include'.\n */\n exclude?: IncludeExcludeOptions;\n /**\n * Options for including only specific versions or request paths of the shared module. When specified, only matching modules will be shared. Cannot be used with 'exclude'.\n */\n include?: IncludeExcludeOptions;\n /**\n * Provided module that should be provided to share scope. Also acts as fallback module if no shared module is found in share scope or version isn't valid. Defaults to the property name.\n */\n import?: false | SharedItem;\n /**\n * Import request to match on\n */\n request?: string;\n /**\n * Layer in which the shared module should be placed.\n */\n layer?: string;\n /**\n * Layer of the issuer.\n */\n issuerLayer?: string;\n /**\n * Package name to determine required version from description file. This is only needed when package name can't be automatically determined from request.\n */\n packageName?: string;\n /**\n * Version requirement from module in share scope.\n */\n requiredVersion?: false | string;\n /**\n * Module is looked up under this key from the share scope.\n */\n shareKey?: string;\n /**\n * Share scope name.\n */\n shareScope?: string | string[];\n /**\n * [Deprecated]: load shared strategy(defaults to 'version-first').\n */\n shareStrategy?: 'version-first' | 'loaded-first';\n /**\n * Allow only a single version of the shared module in share scope (disabled by default).\n */\n singleton?: boolean;\n /**\n * Do not accept shared module if version is not valid (defaults to yes, if local fallback module is available and shared module is not a singleton, otherwise no, has no effect if there is no required version specified).\n */\n strictVersion?: boolean;\n /**\n * Version of the provided module. Will replace lower matching versions, but not higher.\n */\n version?: false | string;\n /**\n * Enable reconstructed lookup for node_modules paths for this share item\n */\n allowNodeModulesSuffixMatch?: boolean;\n /**\n * Enable tree-shaking for the shared module or configure it.\n */\n treeShaking?: boolean | TreeShakingConfig;\n}\n\n/**\n * Modules that should be shared in the share scope. When provided, property names are used to match requested modules in this compilation.\n */\nexport type Shared = (SharedItem | SharedObject)[] | SharedObject;\n\nexport interface IncludeExcludeOptions {\n /**\n * A string (which can be a regex pattern) or a RegExp object to match the request path.\n */\n request?: string | RegExp;\n /**\n * Semantic versioning range to match against the module's version.\n */\n version?: string;\n /**\n * Semantic versioning range to match against the fallback module's version for exclusion/inclusion context where applicable.\n */\n fallbackVersion?: string;\n}\n\n/**\n * Tree-shake configuration for shared module.\n */\nexport interface TreeShakingConfig {\n /**\n * List of export names used from the shared module.\n */\n usedExports?: string[];\n /**\n * Tree-shake analysis mode.\n */\n mode?: 'server-calc' | 'runtime-infer';\n /**\n * Filename for generated treeShaking metadata.\n */\n filename?: string;\n}\n\n// <-- END SCHEMA-GENERATED TYPES -->\n\nexport interface AdditionalDataOptions {\n stats: Stats;\n compiler: webpack.Compiler;\n compilation: webpack.Compilation;\n bundler: 'webpack' | 'rspack';\n}\nexport interface PluginManifestOptions {\n filePath?: string;\n disableAssetsAnalyze?: boolean;\n fileName?: string;\n additionalData?: (\n options: AdditionalDataOptions,\n ) => Promise<void | Stats> | Stats | void;\n}\n\nexport interface PluginDevOptions {\n disableLiveReload?: boolean;\n disableHotTypesReload?: boolean;\n disableDynamicRemoteTypeHints?: boolean;\n}\n\ninterface RemoteTypeUrl {\n alias?: string;\n api: string;\n zip: string;\n}\n\nexport interface RemoteTypeUrls {\n [remoteName: string]: RemoteTypeUrl;\n}\n\nexport interface DtsHostOptions {\n typesFolder?: string;\n abortOnError?: boolean;\n remoteTypesFolder?: string;\n deleteTypesFolder?: boolean;\n maxRetries?: number;\n consumeAPITypes?: boolean;\n runtimePkgs?: string[];\n remoteTypeUrls?: (() => Promise<RemoteTypeUrls>) | RemoteTypeUrls;\n timeout?: number;\n /** The family of IP, used for network requests */\n family?: 4 | 6;\n typesOnBuild?: boolean;\n}\n\nexport interface DtsRemoteOptions {\n tsConfigPath?: string;\n typesFolder?: string;\n compiledTypesFolder?: string;\n /** Custom base output directory for generated types. When set, types will be emitted to this directory instead of the default compiler output directory. */\n outputDir?: string;\n deleteTypesFolder?: boolean;\n additionalFilesToCompile?: string[];\n compileInChildProcess?: boolean;\n compilerInstance?: 'tsc' | 'vue-tsc' | 'tspc' | string;\n generateAPITypes?: boolean;\n extractThirdParty?:\n | boolean\n | {\n exclude?: Array<string | RegExp>;\n };\n extractRemoteTypes?: boolean;\n abortOnError?: boolean;\n deleteTsConfig?: boolean;\n}\n\nexport interface PluginDtsOptions {\n generateTypes?: boolean | DtsRemoteOptions;\n consumeTypes?: boolean | DtsHostOptions;\n tsConfigPath?: string;\n extraOptions?: Record<string, any>;\n implementation?: string;\n cwd?: string;\n displayErrorInTerminal?: boolean;\n afterGenerateTypes?: () => void | Promise<void>;\n}\n\nexport type AsyncBoundaryOptions = {\n eager?: RegExp | ((module: any) => boolean);\n excludeChunk?: (chunk: any) => boolean;\n};\n\nexport interface ModuleFederationPluginOptions {\n /**\n * Modules that should be exposed by this container. When provided, property name is used as public name, otherwise public name is automatically inferred from request.\n */\n exposes?: Exposes;\n /**\n * The filename of the container as relative path inside the `output.path` directory.\n */\n filename?: string;\n /**\n * Options for library.\n */\n library?: LibraryOptions;\n /**\n * The name of the container.\n */\n name?: string;\n /**\n * The external type of the remote containers.\n */\n remoteType?: ExternalsType;\n /**\n * Container locations and request scopes from which modules should be resolved and loaded at runtime. When provided, property name is used as request scope, otherwise request scope is automatically inferred from container location.\n */\n remotes?: Remotes;\n /**\n * The name of the runtime chunk. If set a runtime chunk with this name is created or an existing entrypoint is used as runtime.\n */\n runtime?: EntryRuntime;\n /**\n * Share scope name used for all shared modules (defaults to 'default').\n */\n shareScope?: string | string[];\n /**\n * load shared strategy(defaults to 'version-first').\n */\n shareStrategy?: SharedStrategy;\n /**\n * Modules that should be shared in the share scope. When provided, property names are used to match requested modules in this compilation.\n */\n shared?: Shared;\n /**\n * Runtime plugin file paths or package name. Supports tuple [path, params].\n */\n runtimePlugins?: (string | [string, Record<string, unknown>])[];\n /**\n * Custom public path function\n */\n getPublicPath?: string;\n /**\n * Bundler runtime path\n */\n implementation?: string;\n\n manifest?: boolean | PluginManifestOptions;\n dev?: boolean | PluginDevOptions;\n dts?: boolean | PluginDtsOptions;\n virtualRuntimeEntry?: boolean;\n experiments?: {\n externalRuntime?: boolean;\n provideExternalRuntime?: boolean;\n asyncStartup?: boolean;\n /**\n * Options related to build optimizations.\n */\n optimization?: {\n /**\n * Enable optimization to skip snapshot plugin\n */\n disableSnapshot?: boolean;\n /**\n * Target environment for the build\n */\n target?: 'web' | 'node';\n };\n };\n bridge?: {\n /**\n * Enables bridge router functionality for React applications.\n * When enabled, automatically handles routing context and basename injection\n * for micro-frontend applications using react-router-dom.\n *\n * @default false\n */\n enableBridgeRouter?: boolean;\n /**\n * @deprecated Use `enableBridgeRouter: false` instead.\n *\n * Disables the default alias setting in the bridge.\n * When true, users must manually handle basename through root component props.\n *\n * Migration:\n * - `disableAlias: true` → `enableBridgeRouter: false`\n * - `disableAlias: false` → `enableBridgeRouter: true`\n *\n * @default false\n */\n disableAlias?: boolean;\n };\n /**\n * Configuration for async boundary plugin\n */\n async?: boolean | AsyncBoundaryOptions;\n\n /**\n * The directory to output the tree shaking shared fallback resources.\n */\n treeShakingDir?: string;\n\n /**\n * Whether to inject shared used exports into bundler runtime.\n */\n injectTreeShakingUsedExports?: boolean;\n treeShakingSharedExcludePlugins?: string[];\n treeShakingSharedPlugins?: string[];\n}\n\nexport type SharedStrategy = 'version-first' | 'loaded-first';\n"],"mappings":""}
import { Stats } from "../stats.js";
import webpack from "webpack";
//#region src/types/plugins/ModuleFederationPlugin.d.ts
declare namespace ModuleFederationPlugin_d_exports {
export { AdditionalDataOptions, AmdContainer, AsyncBoundaryOptions, AuxiliaryComment, DtsHostOptions, DtsRemoteOptions, EntryRuntime, Exposes, ExposesConfig, ExposesItem, ExposesItems, ExposesObject, ExternalsType, IncludeExcludeOptions, LibraryCustomUmdCommentObject, LibraryCustomUmdObject, LibraryExport, LibraryName, LibraryOptions, LibraryType, ModuleFederationPluginOptions, PluginDevOptions, PluginDtsOptions, PluginManifestOptions, RemoteTypeUrls, Remotes, RemotesConfig, RemotesItem, RemotesItems, RemotesObject, Shared, SharedConfig, SharedItem, SharedObject, SharedStrategy, TreeShakingConfig, UmdNamedDefine };
}
/**
* Module that should be exposed by this container.
*/
type ExposesItem = string;
/**
* Modules that should be exposed by this container.
*/
type ExposesItems = ExposesItem[];
/**
* Modules that should be exposed by this container. Property names are used as public paths.
*/
interface ExposesObject {
[k: string]: ExposesConfig | ExposesItem | ExposesItems;
}
/**
* Advanced configuration for modules that should be exposed by this container.
*/
interface ExposesConfig {
/**
* Request to a module that should be exposed by this container.
*/
import: ExposesItem | ExposesItems;
/**
* Custom chunk name for the exposed module.
*/
name?: string;
}
/**
* Modules that should be exposed by this container. When provided, property name is used as public name, otherwise public name is automatically inferred from request.
*/
type Exposes = (ExposesItem | ExposesObject)[] | ExposesObject;
/**
* Add a container for define/require functions in the AMD module.
*/
type AmdContainer = string;
/**
* Add a comment in the UMD wrapper.
*/
type AuxiliaryComment = string | LibraryCustomUmdCommentObject;
/**
* Set explicit comments for `commonjs`, `commonjs2`, `amd`, and `root`.
*/
interface LibraryCustomUmdCommentObject {
/**
* Set comment for `amd` section in UMD.
*/
amd?: string;
/**
* Set comment for `commonjs` (exports) section in UMD.
*/
commonjs?: string;
/**
* Set comment for `commonjs2` (module.exports) section in UMD.
*/
commonjs2?: string;
/**
* Set comment for `root` (global variable) section in UMD.
*/
root?: string;
}
/**
* Description object for all UMD variants of the library name.
*/
interface LibraryCustomUmdObject {
/**
* Name of the exposed AMD library in the UMD.
*/
amd?: string;
/**
* Name of the exposed commonjs export in the UMD.
*/
commonjs?: string;
/**
* Name of the property exposed globally by a UMD library.
*/
root?: string[] | string;
}
/**
* Specify which export should be exposed as library.
*/
type LibraryExport = string[] | string;
/**
* The name of the library (some types allow unnamed libraries too).
*/
type LibraryName = string[] | string | LibraryCustomUmdObject;
/**
* Type of library (types included by default are 'var', 'module', 'assign', 'assign-properties', 'this', 'window', 'self', 'global', 'commonjs', 'commonjs2', 'commonjs-module', 'commonjs-static', 'amd', 'amd-require', 'umd', 'umd2', 'jsonp', 'system', but others might be added by plugins).
*/
type LibraryType = 'var' | 'module' | 'assign' | 'assign-properties' | 'this' | 'window' | 'self' | 'global' | 'commonjs' | 'commonjs2' | 'commonjs-module' | 'commonjs-static' | 'amd' | 'amd-require' | 'umd' | 'umd2' | 'jsonp' | 'system' | string;
/**
* Options for library.
*/
interface LibraryOptions {
amdContainer?: AmdContainer;
auxiliaryComment?: AuxiliaryComment;
export?: LibraryExport;
name?: LibraryName;
type: LibraryType;
umdNamedDefine?: UmdNamedDefine;
}
/**
* If `output.libraryTarget` is set to umd and `output.library` is set, setting this to true will name the AMD module.
*/
type UmdNamedDefine = boolean;
/**
* Specifies the default type of externals ('amd*', 'umd*', 'system' and 'jsonp' depend on output.libraryTarget set to the same value).
*/
type ExternalsType = 'var' | 'module' | 'assign' | 'this' | 'window' | 'self' | 'global' | 'commonjs' | 'commonjs2' | 'commonjs-module' | 'commonjs-static' | 'amd' | 'amd-require' | 'umd' | 'umd2' | 'jsonp' | 'system' | 'promise' | 'import' | 'module-import' | 'script' | 'node-commonjs';
/**
* Container location from which modules should be resolved and loaded at runtime.
*/
type RemotesItem = string;
/**
* Container locations from which modules should be resolved and loaded at runtime.
*/
type RemotesItems = RemotesItem[];
/**
* Container locations from which modules should be resolved and loaded at runtime. Property names are used as request scopes.
*/
interface RemotesObject {
[k: string]: RemotesConfig | RemotesItem | RemotesItems;
}
/**
* Advanced configuration for container locations from which modules should be resolved and loaded at runtime.
*/
interface RemotesConfig {
/**
* Container locations from which modules should be resolved and loaded at runtime.
*/
external: RemotesItem | RemotesItems;
/**
* The name of the share scope shared with this remote.
*/
shareScope?: string | string[];
}
/**
* Container locations and request scopes from which modules should be resolved and loaded at runtime. When provided, property name is used as request scope, otherwise request scope is automatically inferred from container location.
*/
type Remotes = (RemotesItem | RemotesObject)[] | RemotesObject;
/**
* The name of the runtime chunk. If set a runtime chunk with this name is created or an existing entrypoint is used as runtime.
*/
type EntryRuntime = false | string;
/**
* A module that should be shared in the share scope.
*/
type SharedItem = string;
/**
* Modules that should be shared in the share scope. Property names are used to match requested modules in this compilation. Relative requests are resolved, module requests are matched unresolved, absolute paths will match resolved requests. A trailing slash will match all requests with this prefix. In this case shareKey must also have a trailing slash.
*/
interface SharedObject {
[k: string]: SharedConfig | SharedItem;
}
/**
* Advanced configuration for modules that should be shared in the share scope.
*/
interface SharedConfig {
/**
* Include the provided and fallback module directly instead behind an async request. This allows to use this shared module in initial load too. All possible shared modules need to be eager too.
*/
eager?: boolean;
/**
* Options for excluding specific versions or request paths of the shared module. When specified, matching modules will not be shared. Cannot be used with 'include'.
*/
exclude?: IncludeExcludeOptions;
/**
* Options for including only specific versions or request paths of the shared module. When specified, only matching modules will be shared. Cannot be used with 'exclude'.
*/
include?: IncludeExcludeOptions;
/**
* Provided module that should be provided to share scope. Also acts as fallback module if no shared module is found in share scope or version isn't valid. Defaults to the property name.
*/
import?: false | SharedItem;
/**
* Import request to match on
*/
request?: string;
/**
* Layer in which the shared module should be placed.
*/
layer?: string;
/**
* Layer of the issuer.
*/
issuerLayer?: string;
/**
* Package name to determine required version from description file. This is only needed when package name can't be automatically determined from request.
*/
packageName?: string;
/**
* Version requirement from module in share scope.
*/
requiredVersion?: false | string;
/**
* Module is looked up under this key from the share scope.
*/
shareKey?: string;
/**
* Share scope name.
*/
shareScope?: string | string[];
/**
* [Deprecated]: load shared strategy(defaults to 'version-first').
*/
shareStrategy?: 'version-first' | 'loaded-first';
/**
* Allow only a single version of the shared module in share scope (disabled by default).
*/
singleton?: boolean;
/**
* Do not accept shared module if version is not valid (defaults to yes, if local fallback module is available and shared module is not a singleton, otherwise no, has no effect if there is no required version specified).
*/
strictVersion?: boolean;
/**
* Version of the provided module. Will replace lower matching versions, but not higher.
*/
version?: false | string;
/**
* Enable reconstructed lookup for node_modules paths for this share item
*/
allowNodeModulesSuffixMatch?: boolean;
/**
* Enable tree-shaking for the shared module or configure it.
*/
treeShaking?: boolean | TreeShakingConfig;
}
/**
* Modules that should be shared in the share scope. When provided, property names are used to match requested modules in this compilation.
*/
type Shared = (SharedItem | SharedObject)[] | SharedObject;
interface IncludeExcludeOptions {
/**
* A string (which can be a regex pattern) or a RegExp object to match the request path.
*/
request?: string | RegExp;
/**
* Semantic versioning range to match against the module's version.
*/
version?: string;
/**
* Semantic versioning range to match against the fallback module's version for exclusion/inclusion context where applicable.
*/
fallbackVersion?: string;
}
/**
* Tree-shake configuration for shared module.
*/
interface TreeShakingConfig {
/**
* List of export names used from the shared module.
*/
usedExports?: string[];
/**
* Tree-shake analysis mode.
*/
mode?: 'server-calc' | 'runtime-infer';
/**
* Filename for generated treeShaking metadata.
*/
filename?: string;
}
interface AdditionalDataOptions {
stats: Stats;
compiler: webpack.Compiler;
compilation: webpack.Compilation;
bundler: 'webpack' | 'rspack';
}
interface PluginManifestOptions {
filePath?: string;
disableAssetsAnalyze?: boolean;
fileName?: string;
additionalData?: (options: AdditionalDataOptions) => Promise<void | Stats> | Stats | void;
}
interface PluginDevOptions {
disableLiveReload?: boolean;
disableHotTypesReload?: boolean;
disableDynamicRemoteTypeHints?: boolean;
}
interface RemoteTypeUrl {
alias?: string;
api: string;
zip: string;
}
interface RemoteTypeUrls {
[remoteName: string]: RemoteTypeUrl;
}
interface DtsHostOptions {
typesFolder?: string;
abortOnError?: boolean;
remoteTypesFolder?: string;
deleteTypesFolder?: boolean;
maxRetries?: number;
consumeAPITypes?: boolean;
runtimePkgs?: string[];
remoteTypeUrls?: (() => Promise<RemoteTypeUrls>) | RemoteTypeUrls;
timeout?: number;
/** The family of IP, used for network requests */
family?: 4 | 6;
typesOnBuild?: boolean;
}
interface DtsRemoteOptions {
tsConfigPath?: string;
typesFolder?: string;
compiledTypesFolder?: string;
/** Custom base output directory for generated types. When set, types will be emitted to this directory instead of the default compiler output directory. */
outputDir?: string;
deleteTypesFolder?: boolean;
additionalFilesToCompile?: string[];
compileInChildProcess?: boolean;
compilerInstance?: 'tsc' | 'vue-tsc' | 'tspc' | string;
generateAPITypes?: boolean;
extractThirdParty?: boolean | {
exclude?: Array<string | RegExp>;
};
extractRemoteTypes?: boolean;
abortOnError?: boolean;
deleteTsConfig?: boolean;
}
interface PluginDtsOptions {
generateTypes?: boolean | DtsRemoteOptions;
consumeTypes?: boolean | DtsHostOptions;
tsConfigPath?: string;
extraOptions?: Record<string, any>;
implementation?: string;
cwd?: string;
displayErrorInTerminal?: boolean;
afterGenerateTypes?: () => void | Promise<void>;
}
type AsyncBoundaryOptions = {
eager?: RegExp | ((module: any) => boolean);
excludeChunk?: (chunk: any) => boolean;
};
interface ModuleFederationPluginOptions {
/**
* Modules that should be exposed by this container. When provided, property name is used as public name, otherwise public name is automatically inferred from request.
*/
exposes?: Exposes;
/**
* The filename of the container as relative path inside the `output.path` directory.
*/
filename?: string;
/**
* Options for library.
*/
library?: LibraryOptions;
/**
* The name of the container.
*/
name?: string;
/**
* The external type of the remote containers.
*/
remoteType?: ExternalsType;
/**
* Container locations and request scopes from which modules should be resolved and loaded at runtime. When provided, property name is used as request scope, otherwise request scope is automatically inferred from container location.
*/
remotes?: Remotes;
/**
* The name of the runtime chunk. If set a runtime chunk with this name is created or an existing entrypoint is used as runtime.
*/
runtime?: EntryRuntime;
/**
* Share scope name used for all shared modules (defaults to 'default').
*/
shareScope?: string | string[];
/**
* load shared strategy(defaults to 'version-first').
*/
shareStrategy?: SharedStrategy;
/**
* Modules that should be shared in the share scope. When provided, property names are used to match requested modules in this compilation.
*/
shared?: Shared;
/**
* Runtime plugin file paths or package name. Supports tuple [path, params].
*/
runtimePlugins?: (string | [string, Record<string, unknown>])[];
/**
* Custom public path function
*/
getPublicPath?: string;
/**
* Bundler runtime path
*/
implementation?: string;
manifest?: boolean | PluginManifestOptions;
dev?: boolean | PluginDevOptions;
dts?: boolean | PluginDtsOptions;
virtualRuntimeEntry?: boolean;
experiments?: {
externalRuntime?: boolean;
provideExternalRuntime?: boolean;
asyncStartup?: boolean;
/**
* Options related to build optimizations.
*/
optimization?: {
/**
* Enable optimization to skip snapshot plugin
*/
disableSnapshot?: boolean;
/**
* Target environment for the build
*/
target?: 'web' | 'node';
};
};
bridge?: {
/**
* Enables bridge router functionality for React applications.
* When enabled, automatically handles routing context and basename injection
* for micro-frontend applications using react-router-dom.
*
* @default false
*/
enableBridgeRouter?: boolean;
/**
* @deprecated Use `enableBridgeRouter: false` instead.
*
* Disables the default alias setting in the bridge.
* When true, users must manually handle basename through root component props.
*
* Migration:
* - `disableAlias: true` → `enableBridgeRouter: false`
* - `disableAlias: false` → `enableBridgeRouter: true`
*
* @default false
*/
disableAlias?: boolean;
};
/**
* Configuration for async boundary plugin
*/
async?: boolean | AsyncBoundaryOptions;
/**
* The directory to output the tree shaking shared fallback resources.
*/
treeShakingDir?: string;
/**
* Whether to inject shared used exports into bundler runtime.
*/
injectTreeShakingUsedExports?: boolean;
treeShakingSharedExcludePlugins?: string[];
treeShakingSharedPlugins?: string[];
}
type SharedStrategy = 'version-first' | 'loaded-first';
//#endregion
export { EntryRuntime, Exposes, ExternalsType, LibraryOptions, ModuleFederationPluginOptions, ModuleFederationPlugin_d_exports, Remotes, Shared };
//# sourceMappingURL=ModuleFederationPlugin.d.ts.map
import { __exportAll } from "../../_virtual/_rolldown/runtime.js";
//#region src/types/plugins/ModuleFederationPlugin.ts
var ModuleFederationPlugin_exports = /* @__PURE__ */ __exportAll({});
//#endregion
export { ModuleFederationPlugin_exports };
//# sourceMappingURL=ModuleFederationPlugin.js.map
{"version":3,"file":"ModuleFederationPlugin.js","names":[],"sources":["../../../src/types/plugins/ModuleFederationPlugin.ts"],"sourcesContent":["import type { Stats } from '../stats';\nimport type webpack from 'webpack';\n\n// <-- BEGIN SCHEMA-GENERATED TYPES -->\n/**\n * Module that should be exposed by this container.\n */\nexport type ExposesItem = string;\n\n/**\n * Modules that should be exposed by this container.\n */\nexport type ExposesItems = ExposesItem[];\n\n/**\n * Modules that should be exposed by this container. Property names are used as public paths.\n */\nexport interface ExposesObject {\n [k: string]: ExposesConfig | ExposesItem | ExposesItems;\n}\n\n/**\n * Advanced configuration for modules that should be exposed by this container.\n */\nexport interface ExposesConfig {\n /**\n * Request to a module that should be exposed by this container.\n */\n import: ExposesItem | ExposesItems;\n /**\n * Custom chunk name for the exposed module.\n */\n name?: string;\n}\n\n/**\n * Modules that should be exposed by this container. When provided, property name is used as public name, otherwise public name is automatically inferred from request.\n */\nexport type Exposes = (ExposesItem | ExposesObject)[] | ExposesObject;\n\n/**\n * Add a container for define/require functions in the AMD module.\n */\nexport type AmdContainer = string;\n\n/**\n * Add a comment in the UMD wrapper.\n */\nexport type AuxiliaryComment = string | LibraryCustomUmdCommentObject;\n\n/**\n * Set explicit comments for `commonjs`, `commonjs2`, `amd`, and `root`.\n */\nexport interface LibraryCustomUmdCommentObject {\n /**\n * Set comment for `amd` section in UMD.\n */\n amd?: string;\n /**\n * Set comment for `commonjs` (exports) section in UMD.\n */\n commonjs?: string;\n /**\n * Set comment for `commonjs2` (module.exports) section in UMD.\n */\n commonjs2?: string;\n /**\n * Set comment for `root` (global variable) section in UMD.\n */\n root?: string;\n}\n\n/**\n * Description object for all UMD variants of the library name.\n */\nexport interface LibraryCustomUmdObject {\n /**\n * Name of the exposed AMD library in the UMD.\n */\n amd?: string;\n /**\n * Name of the exposed commonjs export in the UMD.\n */\n commonjs?: string;\n /**\n * Name of the property exposed globally by a UMD library.\n */\n root?: string[] | string;\n}\n\n/**\n * Specify which export should be exposed as library.\n */\nexport type LibraryExport = string[] | string;\n\n/**\n * The name of the library (some types allow unnamed libraries too).\n */\nexport type LibraryName = string[] | string | LibraryCustomUmdObject;\n\n/**\n * Type of library (types included by default are 'var', 'module', 'assign', 'assign-properties', 'this', 'window', 'self', 'global', 'commonjs', 'commonjs2', 'commonjs-module', 'commonjs-static', 'amd', 'amd-require', 'umd', 'umd2', 'jsonp', 'system', but others might be added by plugins).\n */\nexport type LibraryType =\n | 'var'\n | 'module'\n | 'assign'\n | 'assign-properties'\n | 'this'\n | 'window'\n | 'self'\n | 'global'\n | 'commonjs'\n | 'commonjs2'\n | 'commonjs-module'\n | 'commonjs-static'\n | 'amd'\n | 'amd-require'\n | 'umd'\n | 'umd2'\n | 'jsonp'\n | 'system'\n | string;\n\n/**\n * Options for library.\n */\nexport interface LibraryOptions {\n amdContainer?: AmdContainer;\n auxiliaryComment?: AuxiliaryComment;\n export?: LibraryExport;\n name?: LibraryName;\n type: LibraryType;\n umdNamedDefine?: UmdNamedDefine;\n}\n\n/**\n * If `output.libraryTarget` is set to umd and `output.library` is set, setting this to true will name the AMD module.\n */\nexport type UmdNamedDefine = boolean;\n\n/**\n * Specifies the default type of externals ('amd*', 'umd*', 'system' and 'jsonp' depend on output.libraryTarget set to the same value).\n */\nexport type ExternalsType =\n | 'var'\n | 'module'\n | 'assign'\n | 'this'\n | 'window'\n | 'self'\n | 'global'\n | 'commonjs'\n | 'commonjs2'\n | 'commonjs-module'\n | 'commonjs-static'\n | 'amd'\n | 'amd-require'\n | 'umd'\n | 'umd2'\n | 'jsonp'\n | 'system'\n | 'promise'\n | 'import'\n | 'module-import'\n | 'script'\n | 'node-commonjs';\n\n/**\n * Container location from which modules should be resolved and loaded at runtime.\n */\nexport type RemotesItem = string;\n\n/**\n * Container locations from which modules should be resolved and loaded at runtime.\n */\nexport type RemotesItems = RemotesItem[];\n\n/**\n * Container locations from which modules should be resolved and loaded at runtime. Property names are used as request scopes.\n */\nexport interface RemotesObject {\n [k: string]: RemotesConfig | RemotesItem | RemotesItems;\n}\n\n/**\n * Advanced configuration for container locations from which modules should be resolved and loaded at runtime.\n */\nexport interface RemotesConfig {\n /**\n * Container locations from which modules should be resolved and loaded at runtime.\n */\n external: RemotesItem | RemotesItems;\n /**\n * The name of the share scope shared with this remote.\n */\n shareScope?: string | string[];\n}\n\n/**\n * Container locations and request scopes from which modules should be resolved and loaded at runtime. When provided, property name is used as request scope, otherwise request scope is automatically inferred from container location.\n */\nexport type Remotes = (RemotesItem | RemotesObject)[] | RemotesObject;\n\n/**\n * The name of the runtime chunk. If set a runtime chunk with this name is created or an existing entrypoint is used as runtime.\n */\nexport type EntryRuntime = false | string;\n\n/**\n * A module that should be shared in the share scope.\n */\nexport type SharedItem = string;\n\n/**\n * Modules that should be shared in the share scope. Property names are used to match requested modules in this compilation. Relative requests are resolved, module requests are matched unresolved, absolute paths will match resolved requests. A trailing slash will match all requests with this prefix. In this case shareKey must also have a trailing slash.\n */\nexport interface SharedObject {\n [k: string]: SharedConfig | SharedItem;\n}\n\n/**\n * Advanced configuration for modules that should be shared in the share scope.\n */\nexport interface SharedConfig {\n /**\n * Include the provided and fallback module directly instead behind an async request. This allows to use this shared module in initial load too. All possible shared modules need to be eager too.\n */\n eager?: boolean;\n /**\n * Options for excluding specific versions or request paths of the shared module. When specified, matching modules will not be shared. Cannot be used with 'include'.\n */\n exclude?: IncludeExcludeOptions;\n /**\n * Options for including only specific versions or request paths of the shared module. When specified, only matching modules will be shared. Cannot be used with 'exclude'.\n */\n include?: IncludeExcludeOptions;\n /**\n * Provided module that should be provided to share scope. Also acts as fallback module if no shared module is found in share scope or version isn't valid. Defaults to the property name.\n */\n import?: false | SharedItem;\n /**\n * Import request to match on\n */\n request?: string;\n /**\n * Layer in which the shared module should be placed.\n */\n layer?: string;\n /**\n * Layer of the issuer.\n */\n issuerLayer?: string;\n /**\n * Package name to determine required version from description file. This is only needed when package name can't be automatically determined from request.\n */\n packageName?: string;\n /**\n * Version requirement from module in share scope.\n */\n requiredVersion?: false | string;\n /**\n * Module is looked up under this key from the share scope.\n */\n shareKey?: string;\n /**\n * Share scope name.\n */\n shareScope?: string | string[];\n /**\n * [Deprecated]: load shared strategy(defaults to 'version-first').\n */\n shareStrategy?: 'version-first' | 'loaded-first';\n /**\n * Allow only a single version of the shared module in share scope (disabled by default).\n */\n singleton?: boolean;\n /**\n * Do not accept shared module if version is not valid (defaults to yes, if local fallback module is available and shared module is not a singleton, otherwise no, has no effect if there is no required version specified).\n */\n strictVersion?: boolean;\n /**\n * Version of the provided module. Will replace lower matching versions, but not higher.\n */\n version?: false | string;\n /**\n * Enable reconstructed lookup for node_modules paths for this share item\n */\n allowNodeModulesSuffixMatch?: boolean;\n /**\n * Enable tree-shaking for the shared module or configure it.\n */\n treeShaking?: boolean | TreeShakingConfig;\n}\n\n/**\n * Modules that should be shared in the share scope. When provided, property names are used to match requested modules in this compilation.\n */\nexport type Shared = (SharedItem | SharedObject)[] | SharedObject;\n\nexport interface IncludeExcludeOptions {\n /**\n * A string (which can be a regex pattern) or a RegExp object to match the request path.\n */\n request?: string | RegExp;\n /**\n * Semantic versioning range to match against the module's version.\n */\n version?: string;\n /**\n * Semantic versioning range to match against the fallback module's version for exclusion/inclusion context where applicable.\n */\n fallbackVersion?: string;\n}\n\n/**\n * Tree-shake configuration for shared module.\n */\nexport interface TreeShakingConfig {\n /**\n * List of export names used from the shared module.\n */\n usedExports?: string[];\n /**\n * Tree-shake analysis mode.\n */\n mode?: 'server-calc' | 'runtime-infer';\n /**\n * Filename for generated treeShaking metadata.\n */\n filename?: string;\n}\n\n// <-- END SCHEMA-GENERATED TYPES -->\n\nexport interface AdditionalDataOptions {\n stats: Stats;\n compiler: webpack.Compiler;\n compilation: webpack.Compilation;\n bundler: 'webpack' | 'rspack';\n}\nexport interface PluginManifestOptions {\n filePath?: string;\n disableAssetsAnalyze?: boolean;\n fileName?: string;\n additionalData?: (\n options: AdditionalDataOptions,\n ) => Promise<void | Stats> | Stats | void;\n}\n\nexport interface PluginDevOptions {\n disableLiveReload?: boolean;\n disableHotTypesReload?: boolean;\n disableDynamicRemoteTypeHints?: boolean;\n}\n\ninterface RemoteTypeUrl {\n alias?: string;\n api: string;\n zip: string;\n}\n\nexport interface RemoteTypeUrls {\n [remoteName: string]: RemoteTypeUrl;\n}\n\nexport interface DtsHostOptions {\n typesFolder?: string;\n abortOnError?: boolean;\n remoteTypesFolder?: string;\n deleteTypesFolder?: boolean;\n maxRetries?: number;\n consumeAPITypes?: boolean;\n runtimePkgs?: string[];\n remoteTypeUrls?: (() => Promise<RemoteTypeUrls>) | RemoteTypeUrls;\n timeout?: number;\n /** The family of IP, used for network requests */\n family?: 4 | 6;\n typesOnBuild?: boolean;\n}\n\nexport interface DtsRemoteOptions {\n tsConfigPath?: string;\n typesFolder?: string;\n compiledTypesFolder?: string;\n /** Custom base output directory for generated types. When set, types will be emitted to this directory instead of the default compiler output directory. */\n outputDir?: string;\n deleteTypesFolder?: boolean;\n additionalFilesToCompile?: string[];\n compileInChildProcess?: boolean;\n compilerInstance?: 'tsc' | 'vue-tsc' | 'tspc' | string;\n generateAPITypes?: boolean;\n extractThirdParty?:\n | boolean\n | {\n exclude?: Array<string | RegExp>;\n };\n extractRemoteTypes?: boolean;\n abortOnError?: boolean;\n deleteTsConfig?: boolean;\n}\n\nexport interface PluginDtsOptions {\n generateTypes?: boolean | DtsRemoteOptions;\n consumeTypes?: boolean | DtsHostOptions;\n tsConfigPath?: string;\n extraOptions?: Record<string, any>;\n implementation?: string;\n cwd?: string;\n displayErrorInTerminal?: boolean;\n afterGenerateTypes?: () => void | Promise<void>;\n}\n\nexport type AsyncBoundaryOptions = {\n eager?: RegExp | ((module: any) => boolean);\n excludeChunk?: (chunk: any) => boolean;\n};\n\nexport interface ModuleFederationPluginOptions {\n /**\n * Modules that should be exposed by this container. When provided, property name is used as public name, otherwise public name is automatically inferred from request.\n */\n exposes?: Exposes;\n /**\n * The filename of the container as relative path inside the `output.path` directory.\n */\n filename?: string;\n /**\n * Options for library.\n */\n library?: LibraryOptions;\n /**\n * The name of the container.\n */\n name?: string;\n /**\n * The external type of the remote containers.\n */\n remoteType?: ExternalsType;\n /**\n * Container locations and request scopes from which modules should be resolved and loaded at runtime. When provided, property name is used as request scope, otherwise request scope is automatically inferred from container location.\n */\n remotes?: Remotes;\n /**\n * The name of the runtime chunk. If set a runtime chunk with this name is created or an existing entrypoint is used as runtime.\n */\n runtime?: EntryRuntime;\n /**\n * Share scope name used for all shared modules (defaults to 'default').\n */\n shareScope?: string | string[];\n /**\n * load shared strategy(defaults to 'version-first').\n */\n shareStrategy?: SharedStrategy;\n /**\n * Modules that should be shared in the share scope. When provided, property names are used to match requested modules in this compilation.\n */\n shared?: Shared;\n /**\n * Runtime plugin file paths or package name. Supports tuple [path, params].\n */\n runtimePlugins?: (string | [string, Record<string, unknown>])[];\n /**\n * Custom public path function\n */\n getPublicPath?: string;\n /**\n * Bundler runtime path\n */\n implementation?: string;\n\n manifest?: boolean | PluginManifestOptions;\n dev?: boolean | PluginDevOptions;\n dts?: boolean | PluginDtsOptions;\n virtualRuntimeEntry?: boolean;\n experiments?: {\n externalRuntime?: boolean;\n provideExternalRuntime?: boolean;\n asyncStartup?: boolean;\n /**\n * Options related to build optimizations.\n */\n optimization?: {\n /**\n * Enable optimization to skip snapshot plugin\n */\n disableSnapshot?: boolean;\n /**\n * Target environment for the build\n */\n target?: 'web' | 'node';\n };\n };\n bridge?: {\n /**\n * Enables bridge router functionality for React applications.\n * When enabled, automatically handles routing context and basename injection\n * for micro-frontend applications using react-router-dom.\n *\n * @default false\n */\n enableBridgeRouter?: boolean;\n /**\n * @deprecated Use `enableBridgeRouter: false` instead.\n *\n * Disables the default alias setting in the bridge.\n * When true, users must manually handle basename through root component props.\n *\n * Migration:\n * - `disableAlias: true` → `enableBridgeRouter: false`\n * - `disableAlias: false` → `enableBridgeRouter: true`\n *\n * @default false\n */\n disableAlias?: boolean;\n };\n /**\n * Configuration for async boundary plugin\n */\n async?: boolean | AsyncBoundaryOptions;\n\n /**\n * The directory to output the tree shaking shared fallback resources.\n */\n treeShakingDir?: string;\n\n /**\n * Whether to inject shared used exports into bundler runtime.\n */\n injectTreeShakingUsedExports?: boolean;\n treeShakingSharedExcludePlugins?: string[];\n treeShakingSharedPlugins?: string[];\n}\n\nexport type SharedStrategy = 'version-first' | 'loaded-first';\n"],"mappings":""}
const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
//#region src/types/plugins/ProvideSharedPlugin.ts
var ProvideSharedPlugin_exports = /* @__PURE__ */ require_runtime.__exportAll({});
//#endregion
Object.defineProperty(exports, 'ProvideSharedPlugin_exports', {
enumerable: true,
get: function () {
return ProvideSharedPlugin_exports;
}
});
//# sourceMappingURL=ProvideSharedPlugin.cjs.map
{"version":3,"file":"ProvideSharedPlugin.cjs","names":[],"sources":["../../../src/types/plugins/ProvideSharedPlugin.ts"],"sourcesContent":["/*\n * This file was automatically generated.\n * DO NOT MODIFY BY HAND.\n * Run `pnpm generate:schema -w` to update.\n */\n\nimport type { IncludeExcludeOptions } from './ConsumeSharedPlugin';\n\n/**\n * Request to a module that should be provided as shared module to the share scope (will be resolved when relative).\n */\nexport type ProvidesItem = string;\n\n/**\n * Advanced configuration for modules that should be provided as shared modules to the share scope.\n */\nexport interface ProvidesConfig {\n /**\n * Include the provided module directly instead behind an async request. This allows to use this shared module in initial load too. All possible shared modules need to be eager too.\n */\n eager?: boolean;\n /**\n * Key in the share scope under which the shared modules should be stored.\n */\n shareKey?: string;\n /**\n * Import request to match on\n */\n request?: string;\n /**\n * Share scope name.\n */\n shareScope?: string | string[];\n /**\n * Version requirement from module in share scope.\n */\n requiredVersion?: false | string;\n /**\n * Do not accept shared module if version is not valid (defaults to yes, if local fallback module is available and shared module is not a singleton, otherwise no, has no effect if there is no required version specified).\n */\n strictVersion?: boolean;\n /**\n * Allow only a single version of the shared module in share scope (disabled by default).\n */\n singleton?: boolean;\n /**\n * Layer in which the shared module should be placed.\n */\n layer?: string;\n /**\n * Layer of the issuer.\n */\n issuerLayer?: string;\n /**\n * Version of the provided module. Will replace lower matching versions, but not higher.\n */\n version?: false | string;\n /**\n * Filter for the shared module.\n */\n exclude?: IncludeExcludeOptions;\n /**\n * Options for including only certain versions or requests of the provided module. Cannot be used with 'exclude'.\n */\n include?: IncludeExcludeOptions;\n /**\n * Enable reconstructed lookup for node_modules paths for this share item\n */\n allowNodeModulesSuffixMatch?: boolean;\n /**\n * Tree shaking mode for the shared module.\n */\n treeShakingMode?: 'server-calc' | 'runtime-infer';\n}\n\n/**\n * Modules that should be provided as shared modules to the share scope. Property names are used as share keys.\n */\nexport interface ProvidesObject {\n [k: string]: ProvidesConfig | ProvidesItem;\n}\n\n/**\n * Modules that should be provided as shared modules to the share scope. When provided, property name is used to match modules, otherwise this is automatically inferred from share key.\n */\nexport type Provides = (ProvidesItem | ProvidesObject)[] | ProvidesObject;\n\nexport interface ProvideSharedPluginOptions {\n provides: Provides;\n /**\n * Share scope name used for all provided modules (defaults to 'default').\n */\n shareScope?: string | string[];\n /**\n * Experimental features configuration\n */\n experiments?: {\n /** Enable reconstructed lookup for node_modules paths */\n allowNodeModulesSuffixMatch?: boolean;\n };\n}\n"],"mappings":""}
import { IncludeExcludeOptions } from "./ConsumeSharedPlugin.js";
//#region src/types/plugins/ProvideSharedPlugin.d.ts
declare namespace ProvideSharedPlugin_d_exports {
export { ProvideSharedPluginOptions, Provides, ProvidesConfig, ProvidesItem, ProvidesObject };
}
/**
* Request to a module that should be provided as shared module to the share scope (will be resolved when relative).
*/
type ProvidesItem = string;
/**
* Advanced configuration for modules that should be provided as shared modules to the share scope.
*/
interface ProvidesConfig {
/**
* Include the provided module directly instead behind an async request. This allows to use this shared module in initial load too. All possible shared modules need to be eager too.
*/
eager?: boolean;
/**
* Key in the share scope under which the shared modules should be stored.
*/
shareKey?: string;
/**
* Import request to match on
*/
request?: string;
/**
* Share scope name.
*/
shareScope?: string | string[];
/**
* Version requirement from module in share scope.
*/
requiredVersion?: false | string;
/**
* Do not accept shared module if version is not valid (defaults to yes, if local fallback module is available and shared module is not a singleton, otherwise no, has no effect if there is no required version specified).
*/
strictVersion?: boolean;
/**
* Allow only a single version of the shared module in share scope (disabled by default).
*/
singleton?: boolean;
/**
* Layer in which the shared module should be placed.
*/
layer?: string;
/**
* Layer of the issuer.
*/
issuerLayer?: string;
/**
* Version of the provided module. Will replace lower matching versions, but not higher.
*/
version?: false | string;
/**
* Filter for the shared module.
*/
exclude?: IncludeExcludeOptions;
/**
* Options for including only certain versions or requests of the provided module. Cannot be used with 'exclude'.
*/
include?: IncludeExcludeOptions;
/**
* Enable reconstructed lookup for node_modules paths for this share item
*/
allowNodeModulesSuffixMatch?: boolean;
/**
* Tree shaking mode for the shared module.
*/
treeShakingMode?: 'server-calc' | 'runtime-infer';
}
/**
* Modules that should be provided as shared modules to the share scope. Property names are used as share keys.
*/
interface ProvidesObject {
[k: string]: ProvidesConfig | ProvidesItem;
}
/**
* Modules that should be provided as shared modules to the share scope. When provided, property name is used to match modules, otherwise this is automatically inferred from share key.
*/
type Provides = (ProvidesItem | ProvidesObject)[] | ProvidesObject;
interface ProvideSharedPluginOptions {
provides: Provides;
/**
* Share scope name used for all provided modules (defaults to 'default').
*/
shareScope?: string | string[];
/**
* Experimental features configuration
*/
experiments?: {
/** Enable reconstructed lookup for node_modules paths */allowNodeModulesSuffixMatch?: boolean;
};
}
//#endregion
export { ProvideSharedPlugin_d_exports };
//# sourceMappingURL=ProvideSharedPlugin.d.ts.map
import { __exportAll } from "../../_virtual/_rolldown/runtime.js";
//#region src/types/plugins/ProvideSharedPlugin.ts
var ProvideSharedPlugin_exports = /* @__PURE__ */ __exportAll({});
//#endregion
export { ProvideSharedPlugin_exports };
//# sourceMappingURL=ProvideSharedPlugin.js.map
{"version":3,"file":"ProvideSharedPlugin.js","names":[],"sources":["../../../src/types/plugins/ProvideSharedPlugin.ts"],"sourcesContent":["/*\n * This file was automatically generated.\n * DO NOT MODIFY BY HAND.\n * Run `pnpm generate:schema -w` to update.\n */\n\nimport type { IncludeExcludeOptions } from './ConsumeSharedPlugin';\n\n/**\n * Request to a module that should be provided as shared module to the share scope (will be resolved when relative).\n */\nexport type ProvidesItem = string;\n\n/**\n * Advanced configuration for modules that should be provided as shared modules to the share scope.\n */\nexport interface ProvidesConfig {\n /**\n * Include the provided module directly instead behind an async request. This allows to use this shared module in initial load too. All possible shared modules need to be eager too.\n */\n eager?: boolean;\n /**\n * Key in the share scope under which the shared modules should be stored.\n */\n shareKey?: string;\n /**\n * Import request to match on\n */\n request?: string;\n /**\n * Share scope name.\n */\n shareScope?: string | string[];\n /**\n * Version requirement from module in share scope.\n */\n requiredVersion?: false | string;\n /**\n * Do not accept shared module if version is not valid (defaults to yes, if local fallback module is available and shared module is not a singleton, otherwise no, has no effect if there is no required version specified).\n */\n strictVersion?: boolean;\n /**\n * Allow only a single version of the shared module in share scope (disabled by default).\n */\n singleton?: boolean;\n /**\n * Layer in which the shared module should be placed.\n */\n layer?: string;\n /**\n * Layer of the issuer.\n */\n issuerLayer?: string;\n /**\n * Version of the provided module. Will replace lower matching versions, but not higher.\n */\n version?: false | string;\n /**\n * Filter for the shared module.\n */\n exclude?: IncludeExcludeOptions;\n /**\n * Options for including only certain versions or requests of the provided module. Cannot be used with 'exclude'.\n */\n include?: IncludeExcludeOptions;\n /**\n * Enable reconstructed lookup for node_modules paths for this share item\n */\n allowNodeModulesSuffixMatch?: boolean;\n /**\n * Tree shaking mode for the shared module.\n */\n treeShakingMode?: 'server-calc' | 'runtime-infer';\n}\n\n/**\n * Modules that should be provided as shared modules to the share scope. Property names are used as share keys.\n */\nexport interface ProvidesObject {\n [k: string]: ProvidesConfig | ProvidesItem;\n}\n\n/**\n * Modules that should be provided as shared modules to the share scope. When provided, property name is used to match modules, otherwise this is automatically inferred from share key.\n */\nexport type Provides = (ProvidesItem | ProvidesObject)[] | ProvidesObject;\n\nexport interface ProvideSharedPluginOptions {\n provides: Provides;\n /**\n * Share scope name used for all provided modules (defaults to 'default').\n */\n shareScope?: string | string[];\n /**\n * Experimental features configuration\n */\n experiments?: {\n /** Enable reconstructed lookup for node_modules paths */\n allowNodeModulesSuffixMatch?: boolean;\n };\n}\n"],"mappings":""}
const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
//#region src/types/plugins/SharePlugin.ts
var SharePlugin_exports = /* @__PURE__ */ require_runtime.__exportAll({});
//#endregion
Object.defineProperty(exports, 'SharePlugin_exports', {
enumerable: true,
get: function () {
return SharePlugin_exports;
}
});
//# sourceMappingURL=SharePlugin.cjs.map
{"version":3,"file":"SharePlugin.cjs","names":[],"sources":["../../../src/types/plugins/SharePlugin.ts"],"sourcesContent":["/*\n * This file was automatically generated.\n * DO NOT MODIFY BY HAND.\n * Run `pnpm generate:schema -w` to update.\n */\n\nimport type { Shared } from './ModuleFederationPlugin';\n\nexport interface SharePluginOptions {\n /**\n * Enable/disable asynchronous loading of runtime modules. When enabled, entry points will be wrapped in asynchronous chunks.\n */\n async?: boolean;\n /**\n * Share scope name used for all shared modules (defaults to 'default').\n */\n shareScope?: string | string[];\n shared: Shared;\n /**\n * Experimental features configuration\n */\n experiments?: {\n /** Enable reconstructed lookup for node_modules paths */\n allowNodeModulesSuffixMatch?: boolean;\n };\n}\n"],"mappings":""}
import { Shared } from "./ModuleFederationPlugin.js";
//#region src/types/plugins/SharePlugin.d.ts
declare namespace SharePlugin_d_exports {
export { SharePluginOptions };
}
interface SharePluginOptions {
/**
* Enable/disable asynchronous loading of runtime modules. When enabled, entry points will be wrapped in asynchronous chunks.
*/
async?: boolean;
/**
* Share scope name used for all shared modules (defaults to 'default').
*/
shareScope?: string | string[];
shared: Shared;
/**
* Experimental features configuration
*/
experiments?: {
/** Enable reconstructed lookup for node_modules paths */allowNodeModulesSuffixMatch?: boolean;
};
}
//#endregion
export { SharePlugin_d_exports };
//# sourceMappingURL=SharePlugin.d.ts.map
import { __exportAll } from "../../_virtual/_rolldown/runtime.js";
//#region src/types/plugins/SharePlugin.ts
var SharePlugin_exports = /* @__PURE__ */ __exportAll({});
//#endregion
export { SharePlugin_exports };
//# sourceMappingURL=SharePlugin.js.map
{"version":3,"file":"SharePlugin.js","names":[],"sources":["../../../src/types/plugins/SharePlugin.ts"],"sourcesContent":["/*\n * This file was automatically generated.\n * DO NOT MODIFY BY HAND.\n * Run `pnpm generate:schema -w` to update.\n */\n\nimport type { Shared } from './ModuleFederationPlugin';\n\nexport interface SharePluginOptions {\n /**\n * Enable/disable asynchronous loading of runtime modules. When enabled, entry points will be wrapped in asynchronous chunks.\n */\n async?: boolean;\n /**\n * Share scope name used for all shared modules (defaults to 'default').\n */\n shareScope?: string | string[];\n shared: Shared;\n /**\n * Experimental features configuration\n */\n experiments?: {\n /** Enable reconstructed lookup for node_modules paths */\n allowNodeModulesSuffixMatch?: boolean;\n };\n}\n"],"mappings":""}
import { TreeShakingStatus } from "../constant.js";
import { RemoteEntryType, StatsAssets } from "./stats.js";
//#region src/types/snapshot.d.ts
interface BasicModuleInfo {
dev?: {
version?: string;
remotes?: {
[nameWithType: string]: string;
};
};
version: string;
buildVersion: string;
remoteTypes: string;
remoteTypesZip: string;
remoteTypesAPI?: string;
remotesInfo: Record<string, {
matchedVersion: string;
}>;
shared: Array<{
sharedName: string;
fallback?: string;
fallbackName?: string;
fallbackType?: RemoteEntryType;
version?: string;
assets: StatsAssets;
treeShakingStatus?: TreeShakingStatus;
secondarySharedTreeShakingEntry?: string;
secondarySharedTreeShakingName?: string;
}>;
}
interface BasicProviderModuleInfo extends BasicModuleInfo {
remoteEntry: string;
remoteEntryType: RemoteEntryType;
ssrRemoteEntry?: string;
ssrRemoteEntryType?: RemoteEntryType;
globalName: string;
modules: Array<{
moduleName: string;
modulePath?: string;
assets: StatsAssets;
}>;
prefetchInterface?: boolean;
prefetchEntry?: string;
prefetchEntryType?: RemoteEntryType;
}
interface BasicProviderModuleInfoWithPublicPath extends BasicProviderModuleInfo {
publicPath: string;
ssrPublicPath?: string;
}
interface BasicProviderModuleInfoWithGetPublicPath extends BasicProviderModuleInfo {
getPublicPath: string;
}
interface ManifestProvider {
remoteEntry: string;
ssrRemoteEntry?: string;
version?: string;
}
interface PureEntryProvider extends ManifestProvider {
globalName: string;
}
interface BasicConsumerModuleInfo extends BasicModuleInfo {
consumerList: Array<string>;
}
interface ConsumerModuleInfoWithPublicPath extends BasicConsumerModuleInfo, BasicProviderModuleInfo {
publicPath: string;
ssrPublicPath?: string;
}
interface ConsumerModuleInfoWithGetPublicPath extends BasicConsumerModuleInfo, BasicProviderModuleInfo {
getPublicPath: string;
}
type PureConsumerModuleInfo = Omit<BasicConsumerModuleInfo, 'remoteTypes'>;
type ConsumerModuleInfo = ConsumerModuleInfoWithPublicPath | ConsumerModuleInfoWithGetPublicPath;
type ProviderModuleInfo = BasicProviderModuleInfoWithPublicPath | BasicProviderModuleInfoWithGetPublicPath;
type ModuleInfo = ConsumerModuleInfo | PureConsumerModuleInfo | ProviderModuleInfo;
type GlobalModuleInfo = {
[key: string]: ModuleInfo | ManifestProvider | PureEntryProvider | undefined;
};
//#endregion
export { BasicProviderModuleInfo, ConsumerModuleInfo, ConsumerModuleInfoWithPublicPath, GlobalModuleInfo, ManifestProvider, ModuleInfo, ProviderModuleInfo, PureConsumerModuleInfo, PureEntryProvider };
//# sourceMappingURL=snapshot.d.ts.map
import { RemoteWithEntry, RemoteWithVersion } from "./common.js";
//#region src/types/stats.d.ts
type RemoteEntryType = 'var' | 'module' | 'assign' | 'assign-properties' | 'this' | 'window' | 'self' | 'global' | 'commonjs' | 'commonjs2' | 'commonjs-module' | 'commonjs-static' | 'amd' | 'amd-require' | 'umd' | 'umd2' | 'jsonp' | 'system' | string;
interface ResourceInfo {
path: string;
name: string;
type: RemoteEntryType;
}
interface StatsBuildInfo {
buildVersion: string;
buildName: string;
target?: string[];
plugins?: string[];
excludePlugins?: string[];
}
interface MetaDataTypes {
path: string;
name: string;
api: string;
zip: string;
}
interface BasicStatsMetaData {
name: string;
globalName: string;
buildInfo: StatsBuildInfo;
remoteEntry: ResourceInfo;
ssrRemoteEntry?: ResourceInfo;
prefetchInterface?: boolean;
prefetchEntry?: ResourceInfo;
types?: MetaDataTypes;
type: string;
pluginVersion?: string;
}
type StatsMetaDataWithGetPublicPath<T = BasicStatsMetaData> = T & {
getPublicPath: string;
};
type StatsMetaDataWithPublicPath<T = BasicStatsMetaData> = T & {
publicPath: string;
ssrPublicPath?: string;
};
type StatsMetaData<T = BasicStatsMetaData> = StatsMetaDataWithGetPublicPath<T> | StatsMetaDataWithPublicPath<T>;
interface StatsAssets {
js: StatsAssetsInfo;
css: StatsAssetsInfo;
}
interface StatsAssetsInfo {
sync: string[];
async: string[];
}
interface StatsShared {
id: string;
name: string;
version: string;
singleton: boolean;
requiredVersion: string;
hash: string;
assets: StatsAssets;
deps: string[];
usedIn: string[];
usedExports: string[];
fallback: string;
fallbackName: string;
fallbackType: RemoteEntryType;
}
interface StatsRemoteVal {
moduleName: string;
federationContainerName: string;
consumingFederationContainerName: string;
alias: string;
usedIn: string[];
}
type StatsRemoteWithEntry<T = StatsRemoteVal> = T & Omit<RemoteWithEntry, 'name'>;
type StatsRemoteWithVersion<T = StatsRemoteVal> = T & Omit<RemoteWithVersion, 'name'>;
type StatsRemote<T = StatsRemoteVal> = StatsRemoteWithEntry<T> | StatsRemoteWithVersion<T>;
interface StatsModuleInfo {
name: string;
file: string[];
}
interface ManifestModuleInfos {
[exposeModuleName: string]: StatsModuleInfo;
}
interface StatsExpose {
id: string;
name: string;
path?: string;
file: string;
requires: string[];
assets: StatsAssets;
}
interface Stats<T = BasicStatsMetaData, K = StatsRemoteVal> {
id: string;
name: string;
metaData: StatsMetaData<T>;
shared: StatsShared[];
remotes: StatsRemote<K>[];
exposes: StatsExpose[];
}
//#endregion
export { BasicStatsMetaData, ManifestModuleInfos, MetaDataTypes, RemoteEntryType, ResourceInfo, Stats, StatsAssets, StatsBuildInfo, StatsExpose, StatsMetaData, StatsMetaDataWithGetPublicPath, StatsMetaDataWithPublicPath, StatsModuleInfo, StatsRemote, StatsRemoteVal, StatsRemoteWithEntry, StatsRemoteWithVersion, StatsShared };
//# sourceMappingURL=stats.d.ts.map
const require_constant = require('./constant.cjs');
const require_env = require('./env.cjs');
//#region src/utils.ts
const LOG_CATEGORY = "[ Federation Runtime ]";
const parseEntry = (str, devVerOrUrl, separator = require_constant.SEPARATOR) => {
const strSplit = str.split(separator);
const devVersionOrUrl = require_env.getProcessEnv()["NODE_ENV"] === "development" && devVerOrUrl;
const defaultVersion = "*";
const isEntry = (s) => s.startsWith("http") || s.includes(require_constant.MANIFEST_EXT);
if (strSplit.length >= 2) {
let [name, ...versionOrEntryArr] = strSplit;
if (str.startsWith(separator)) {
name = strSplit.slice(0, 2).join(separator);
versionOrEntryArr = [devVersionOrUrl || strSplit.slice(2).join(separator)];
}
let versionOrEntry = devVersionOrUrl || versionOrEntryArr.join(separator);
if (isEntry(versionOrEntry)) return {
name,
entry: versionOrEntry
};
else return {
name,
version: versionOrEntry || defaultVersion
};
} else if (strSplit.length === 1) {
const [name] = strSplit;
if (devVersionOrUrl && isEntry(devVersionOrUrl)) return {
name,
entry: devVersionOrUrl
};
return {
name,
version: devVersionOrUrl || defaultVersion
};
} else throw `Invalid entry value: ${str}`;
};
const composeKeyWithSeparator = function(...args) {
if (!args.length) return "";
return args.reduce((sum, cur) => {
if (!cur) return sum;
if (!sum) return cur;
return `${sum}${require_constant.SEPARATOR}${cur}`;
}, "");
};
const encodeName = function(name, prefix = "", withExt = false) {
try {
const ext = withExt ? ".js" : "";
return `${prefix}${name.replace(new RegExp(`${require_constant.NameTransformSymbol.AT}`, "g"), require_constant.NameTransformMap[require_constant.NameTransformSymbol.AT]).replace(new RegExp(`${require_constant.NameTransformSymbol.HYPHEN}`, "g"), require_constant.NameTransformMap[require_constant.NameTransformSymbol.HYPHEN]).replace(new RegExp(`${require_constant.NameTransformSymbol.SLASH}`, "g"), require_constant.NameTransformMap[require_constant.NameTransformSymbol.SLASH])}${ext}`;
} catch (err) {
throw err;
}
};
const decodeName = function(name, prefix, withExt) {
try {
let decodedName = name;
if (prefix) {
if (!decodedName.startsWith(prefix)) return decodedName;
decodedName = decodedName.replace(new RegExp(prefix, "g"), "");
}
decodedName = decodedName.replace(new RegExp(`${require_constant.NameTransformMap[require_constant.NameTransformSymbol.AT]}`, "g"), require_constant.EncodedNameTransformMap[require_constant.NameTransformMap[require_constant.NameTransformSymbol.AT]]).replace(new RegExp(`${require_constant.NameTransformMap[require_constant.NameTransformSymbol.SLASH]}`, "g"), require_constant.EncodedNameTransformMap[require_constant.NameTransformMap[require_constant.NameTransformSymbol.SLASH]]).replace(new RegExp(`${require_constant.NameTransformMap[require_constant.NameTransformSymbol.HYPHEN]}`, "g"), require_constant.EncodedNameTransformMap[require_constant.NameTransformMap[require_constant.NameTransformSymbol.HYPHEN]]);
if (withExt) decodedName = decodedName.replace(".js", "");
return decodedName;
} catch (err) {
throw err;
}
};
const generateExposeFilename = (exposeName, withExt) => {
if (!exposeName) return "";
let expose = exposeName;
if (expose === ".") expose = "default_export";
if (expose.startsWith("./")) expose = expose.replace("./", "");
return encodeName(expose, "__federation_expose_", withExt);
};
const generateShareFilename = (pkgName, withExt) => {
if (!pkgName) return "";
return encodeName(pkgName, "__federation_shared_", withExt);
};
const getResourceUrl = (module, sourceUrl) => {
if ("getPublicPath" in module) {
let publicPath;
if (!module.getPublicPath.startsWith("function")) publicPath = new Function(module.getPublicPath)();
else publicPath = new Function("return " + module.getPublicPath)()();
return `${publicPath}${sourceUrl}`;
} else if ("publicPath" in module) {
if (!require_env.isBrowserEnv() && !require_env.isReactNativeEnv() && "ssrPublicPath" in module && typeof module.ssrPublicPath === "string") return `${module.ssrPublicPath}${sourceUrl}`;
return `${module.publicPath}${sourceUrl}`;
} else {
console.warn("Cannot get resource URL. If in debug mode, please ignore.", module, sourceUrl);
return "";
}
};
const assert = (condition, msg) => {
if (!condition) error(msg);
};
const error = (msg) => {
throw new Error(`${LOG_CATEGORY}: ${msg}`);
};
const warn = (msg) => {
console.warn(`${LOG_CATEGORY}: ${msg}`);
};
function safeToString(info) {
try {
return JSON.stringify(info, null, 2);
} catch (e) {
return "";
}
}
const VERSION_PATTERN_REGEXP = /^([\d^=v<>~]|[*xX]$)/;
function isRequiredVersion(str) {
return VERSION_PATTERN_REGEXP.test(str);
}
//#endregion
exports.assert = assert;
exports.composeKeyWithSeparator = composeKeyWithSeparator;
exports.decodeName = decodeName;
exports.encodeName = encodeName;
exports.error = error;
exports.generateExposeFilename = generateExposeFilename;
exports.generateShareFilename = generateShareFilename;
exports.getResourceUrl = getResourceUrl;
exports.isRequiredVersion = isRequiredVersion;
exports.parseEntry = parseEntry;
exports.safeToString = safeToString;
exports.warn = warn;
//# sourceMappingURL=utils.cjs.map
{"version":3,"file":"utils.cjs","names":["SEPARATOR","getProcessEnv","MANIFEST_EXT","NameTransformSymbol","NameTransformMap","EncodedNameTransformMap","isBrowserEnv","isReactNativeEnv"],"sources":["../src/utils.ts"],"sourcesContent":["import { RemoteEntryInfo, ModuleInfo } from './types';\nimport {\n NameTransformMap,\n NameTransformSymbol,\n EncodedNameTransformMap,\n SEPARATOR,\n MANIFEST_EXT,\n} from './constant';\nimport { getProcessEnv, isBrowserEnv, isReactNativeEnv } from './env';\n\nconst LOG_CATEGORY = '[ Federation Runtime ]';\n\n// entry: name:version version : 1.0.0 | ^1.2.3\n// entry: name:entry entry: https://localhost:9000/federation-manifest.json\nconst parseEntry = (\n str: string,\n devVerOrUrl?: string,\n separator = SEPARATOR,\n): RemoteEntryInfo => {\n const strSplit = str.split(separator);\n const devVersionOrUrl =\n getProcessEnv()['NODE_ENV'] === 'development' && devVerOrUrl;\n const defaultVersion = '*';\n const isEntry = (s: string) =>\n s.startsWith('http') || s.includes(MANIFEST_EXT);\n\n // Check if the string starts with a type\n if (strSplit.length >= 2) {\n let [name, ...versionOrEntryArr] = strSplit;\n // @name@manifest-url.json\n if (str.startsWith(separator)) {\n name = strSplit.slice(0, 2).join(separator);\n versionOrEntryArr = [\n devVersionOrUrl || strSplit.slice(2).join(separator),\n ];\n }\n\n let versionOrEntry = devVersionOrUrl || versionOrEntryArr.join(separator);\n\n if (isEntry(versionOrEntry)) {\n return {\n name,\n entry: versionOrEntry,\n };\n } else {\n // Apply version rule\n // devVersionOrUrl => inputVersion => defaultVersion\n return {\n name,\n version: versionOrEntry || defaultVersion,\n };\n }\n } else if (strSplit.length === 1) {\n const [name] = strSplit;\n if (devVersionOrUrl && isEntry(devVersionOrUrl)) {\n return {\n name,\n entry: devVersionOrUrl,\n };\n }\n return {\n name,\n version: devVersionOrUrl || defaultVersion,\n };\n } else {\n throw `Invalid entry value: ${str}`;\n }\n};\n\ndeclare global {\n // eslint-disable-next-line no-var\n var FEDERATION_DEBUG: string | undefined;\n}\n\nconst composeKeyWithSeparator = function (\n ...args: (string | undefined)[]\n): string {\n if (!args.length) {\n return '';\n }\n\n return args.reduce((sum, cur) => {\n if (!cur) {\n return sum;\n }\n if (!sum) {\n return cur;\n }\n\n return `${sum}${SEPARATOR}${cur}`;\n }, '') as string;\n};\n\nconst encodeName = function (\n name: string,\n prefix = '',\n withExt = false,\n): string {\n try {\n const ext = withExt ? '.js' : '';\n return `${prefix}${name\n .replace(\n new RegExp(`${NameTransformSymbol.AT}`, 'g'),\n NameTransformMap[NameTransformSymbol.AT],\n )\n .replace(\n new RegExp(`${NameTransformSymbol.HYPHEN}`, 'g'),\n NameTransformMap[NameTransformSymbol.HYPHEN],\n )\n .replace(\n new RegExp(`${NameTransformSymbol.SLASH}`, 'g'),\n NameTransformMap[NameTransformSymbol.SLASH],\n )}${ext}`;\n } catch (err) {\n throw err;\n }\n};\n\nconst decodeName = function (\n name: string,\n prefix?: string,\n withExt?: boolean,\n): string {\n try {\n let decodedName = name;\n if (prefix) {\n if (!decodedName.startsWith(prefix)) {\n return decodedName;\n }\n decodedName = decodedName.replace(new RegExp(prefix, 'g'), '');\n }\n decodedName = decodedName\n .replace(\n new RegExp(`${NameTransformMap[NameTransformSymbol.AT]}`, 'g'),\n EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.AT]],\n )\n .replace(\n new RegExp(`${NameTransformMap[NameTransformSymbol.SLASH]}`, 'g'),\n EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.SLASH]],\n )\n .replace(\n new RegExp(`${NameTransformMap[NameTransformSymbol.HYPHEN]}`, 'g'),\n EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.HYPHEN]],\n );\n if (withExt) {\n decodedName = decodedName.replace('.js', '');\n }\n return decodedName;\n } catch (err) {\n throw err;\n }\n};\n\nconst generateExposeFilename = (\n exposeName: string,\n withExt: boolean,\n): string => {\n if (!exposeName) {\n return '';\n }\n\n let expose = exposeName;\n if (expose === '.') {\n expose = 'default_export';\n }\n if (expose.startsWith('./')) {\n expose = expose.replace('./', '');\n }\n\n return encodeName(expose, '__federation_expose_', withExt);\n};\n\nconst generateShareFilename = (pkgName: string, withExt: boolean): string => {\n if (!pkgName) {\n return '';\n }\n return encodeName(pkgName, '__federation_shared_', withExt);\n};\n\nconst getResourceUrl = (module: ModuleInfo, sourceUrl: string): string => {\n if ('getPublicPath' in module) {\n let publicPath;\n\n if (!module.getPublicPath.startsWith('function')) {\n publicPath = new Function(module.getPublicPath)();\n } else {\n publicPath = new Function('return ' + module.getPublicPath)()();\n }\n\n return `${publicPath}${sourceUrl}`;\n } else if ('publicPath' in module) {\n if (\n !isBrowserEnv() &&\n !isReactNativeEnv() &&\n 'ssrPublicPath' in module &&\n typeof module.ssrPublicPath === 'string'\n ) {\n return `${module.ssrPublicPath}${sourceUrl}`;\n }\n return `${module.publicPath}${sourceUrl}`;\n } else {\n console.warn(\n 'Cannot get resource URL. If in debug mode, please ignore.',\n module,\n sourceUrl,\n );\n return '';\n }\n};\n\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nconst assert = (condition: any, msg: string): asserts condition => {\n if (!condition) {\n error(msg);\n }\n};\n\nconst error = (msg: string | Error | unknown): never => {\n throw new Error(`${LOG_CATEGORY}: ${msg}`);\n};\n\nconst warn = (msg: Parameters<typeof console.warn>[0]): void => {\n console.warn(`${LOG_CATEGORY}: ${msg}`);\n};\n\nfunction safeToString(info: any): string {\n try {\n return JSON.stringify(info, null, 2);\n } catch (e) {\n return '';\n }\n}\n\n// RegExp for version string\nconst VERSION_PATTERN_REGEXP: RegExp = /^([\\d^=v<>~]|[*xX]$)/;\n\nfunction isRequiredVersion(str: string): boolean {\n return VERSION_PATTERN_REGEXP.test(str);\n}\n\nexport {\n parseEntry,\n decodeName,\n encodeName,\n composeKeyWithSeparator,\n generateExposeFilename,\n generateShareFilename,\n getResourceUrl,\n assert,\n error,\n warn,\n safeToString,\n isRequiredVersion,\n};\n"],"mappings":"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"}
import { RemoteEntryInfo } from "./types/common.js";
import { ModuleInfo } from "./types/snapshot.js";
//#region src/utils.d.ts
declare const parseEntry: (str: string, devVerOrUrl?: string, separator?: string) => RemoteEntryInfo;
declare global {
var FEDERATION_DEBUG: string | undefined;
}
declare const composeKeyWithSeparator: (...args: (string | undefined)[]) => string;
declare const encodeName: (name: string, prefix?: string, withExt?: boolean) => string;
declare const decodeName: (name: string, prefix?: string, withExt?: boolean) => string;
declare const generateExposeFilename: (exposeName: string, withExt: boolean) => string;
declare const generateShareFilename: (pkgName: string, withExt: boolean) => string;
declare const getResourceUrl: (module: ModuleInfo, sourceUrl: string) => string;
declare const assert: (condition: any, msg: string) => asserts condition;
declare const error: (msg: string | Error | unknown) => never;
declare const warn: (msg: Parameters<typeof console.warn>[0]) => void;
declare function safeToString(info: any): string;
declare function isRequiredVersion(str: string): boolean;
//#endregion
export { assert, composeKeyWithSeparator, decodeName, encodeName, error, generateExposeFilename, generateShareFilename, getResourceUrl, isRequiredVersion, parseEntry, safeToString, warn };
//# sourceMappingURL=utils.d.ts.map
import { EncodedNameTransformMap, MANIFEST_EXT, NameTransformMap, NameTransformSymbol, SEPARATOR } from "./constant.js";
import { getProcessEnv, isBrowserEnv, isReactNativeEnv } from "./env.js";
//#region src/utils.ts
const LOG_CATEGORY = "[ Federation Runtime ]";
const parseEntry = (str, devVerOrUrl, separator = SEPARATOR) => {
const strSplit = str.split(separator);
const devVersionOrUrl = getProcessEnv()["NODE_ENV"] === "development" && devVerOrUrl;
const defaultVersion = "*";
const isEntry = (s) => s.startsWith("http") || s.includes(MANIFEST_EXT);
if (strSplit.length >= 2) {
let [name, ...versionOrEntryArr] = strSplit;
if (str.startsWith(separator)) {
name = strSplit.slice(0, 2).join(separator);
versionOrEntryArr = [devVersionOrUrl || strSplit.slice(2).join(separator)];
}
let versionOrEntry = devVersionOrUrl || versionOrEntryArr.join(separator);
if (isEntry(versionOrEntry)) return {
name,
entry: versionOrEntry
};
else return {
name,
version: versionOrEntry || defaultVersion
};
} else if (strSplit.length === 1) {
const [name] = strSplit;
if (devVersionOrUrl && isEntry(devVersionOrUrl)) return {
name,
entry: devVersionOrUrl
};
return {
name,
version: devVersionOrUrl || defaultVersion
};
} else throw `Invalid entry value: ${str}`;
};
const composeKeyWithSeparator = function(...args) {
if (!args.length) return "";
return args.reduce((sum, cur) => {
if (!cur) return sum;
if (!sum) return cur;
return `${sum}${SEPARATOR}${cur}`;
}, "");
};
const encodeName = function(name, prefix = "", withExt = false) {
try {
const ext = withExt ? ".js" : "";
return `${prefix}${name.replace(new RegExp(`${NameTransformSymbol.AT}`, "g"), NameTransformMap[NameTransformSymbol.AT]).replace(new RegExp(`${NameTransformSymbol.HYPHEN}`, "g"), NameTransformMap[NameTransformSymbol.HYPHEN]).replace(new RegExp(`${NameTransformSymbol.SLASH}`, "g"), NameTransformMap[NameTransformSymbol.SLASH])}${ext}`;
} catch (err) {
throw err;
}
};
const decodeName = function(name, prefix, withExt) {
try {
let decodedName = name;
if (prefix) {
if (!decodedName.startsWith(prefix)) return decodedName;
decodedName = decodedName.replace(new RegExp(prefix, "g"), "");
}
decodedName = decodedName.replace(new RegExp(`${NameTransformMap[NameTransformSymbol.AT]}`, "g"), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.AT]]).replace(new RegExp(`${NameTransformMap[NameTransformSymbol.SLASH]}`, "g"), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.SLASH]]).replace(new RegExp(`${NameTransformMap[NameTransformSymbol.HYPHEN]}`, "g"), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.HYPHEN]]);
if (withExt) decodedName = decodedName.replace(".js", "");
return decodedName;
} catch (err) {
throw err;
}
};
const generateExposeFilename = (exposeName, withExt) => {
if (!exposeName) return "";
let expose = exposeName;
if (expose === ".") expose = "default_export";
if (expose.startsWith("./")) expose = expose.replace("./", "");
return encodeName(expose, "__federation_expose_", withExt);
};
const generateShareFilename = (pkgName, withExt) => {
if (!pkgName) return "";
return encodeName(pkgName, "__federation_shared_", withExt);
};
const getResourceUrl = (module, sourceUrl) => {
if ("getPublicPath" in module) {
let publicPath;
if (!module.getPublicPath.startsWith("function")) publicPath = new Function(module.getPublicPath)();
else publicPath = new Function("return " + module.getPublicPath)()();
return `${publicPath}${sourceUrl}`;
} else if ("publicPath" in module) {
if (!isBrowserEnv() && !isReactNativeEnv() && "ssrPublicPath" in module && typeof module.ssrPublicPath === "string") return `${module.ssrPublicPath}${sourceUrl}`;
return `${module.publicPath}${sourceUrl}`;
} else {
console.warn("Cannot get resource URL. If in debug mode, please ignore.", module, sourceUrl);
return "";
}
};
const assert = (condition, msg) => {
if (!condition) error(msg);
};
const error = (msg) => {
throw new Error(`${LOG_CATEGORY}: ${msg}`);
};
const warn = (msg) => {
console.warn(`${LOG_CATEGORY}: ${msg}`);
};
function safeToString(info) {
try {
return JSON.stringify(info, null, 2);
} catch (e) {
return "";
}
}
const VERSION_PATTERN_REGEXP = /^([\d^=v<>~]|[*xX]$)/;
function isRequiredVersion(str) {
return VERSION_PATTERN_REGEXP.test(str);
}
//#endregion
export { assert, composeKeyWithSeparator, decodeName, encodeName, error, generateExposeFilename, generateShareFilename, getResourceUrl, isRequiredVersion, parseEntry, safeToString, warn };
//# sourceMappingURL=utils.js.map
{"version":3,"file":"utils.js","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import { RemoteEntryInfo, ModuleInfo } from './types';\nimport {\n NameTransformMap,\n NameTransformSymbol,\n EncodedNameTransformMap,\n SEPARATOR,\n MANIFEST_EXT,\n} from './constant';\nimport { getProcessEnv, isBrowserEnv, isReactNativeEnv } from './env';\n\nconst LOG_CATEGORY = '[ Federation Runtime ]';\n\n// entry: name:version version : 1.0.0 | ^1.2.3\n// entry: name:entry entry: https://localhost:9000/federation-manifest.json\nconst parseEntry = (\n str: string,\n devVerOrUrl?: string,\n separator = SEPARATOR,\n): RemoteEntryInfo => {\n const strSplit = str.split(separator);\n const devVersionOrUrl =\n getProcessEnv()['NODE_ENV'] === 'development' && devVerOrUrl;\n const defaultVersion = '*';\n const isEntry = (s: string) =>\n s.startsWith('http') || s.includes(MANIFEST_EXT);\n\n // Check if the string starts with a type\n if (strSplit.length >= 2) {\n let [name, ...versionOrEntryArr] = strSplit;\n // @name@manifest-url.json\n if (str.startsWith(separator)) {\n name = strSplit.slice(0, 2).join(separator);\n versionOrEntryArr = [\n devVersionOrUrl || strSplit.slice(2).join(separator),\n ];\n }\n\n let versionOrEntry = devVersionOrUrl || versionOrEntryArr.join(separator);\n\n if (isEntry(versionOrEntry)) {\n return {\n name,\n entry: versionOrEntry,\n };\n } else {\n // Apply version rule\n // devVersionOrUrl => inputVersion => defaultVersion\n return {\n name,\n version: versionOrEntry || defaultVersion,\n };\n }\n } else if (strSplit.length === 1) {\n const [name] = strSplit;\n if (devVersionOrUrl && isEntry(devVersionOrUrl)) {\n return {\n name,\n entry: devVersionOrUrl,\n };\n }\n return {\n name,\n version: devVersionOrUrl || defaultVersion,\n };\n } else {\n throw `Invalid entry value: ${str}`;\n }\n};\n\ndeclare global {\n // eslint-disable-next-line no-var\n var FEDERATION_DEBUG: string | undefined;\n}\n\nconst composeKeyWithSeparator = function (\n ...args: (string | undefined)[]\n): string {\n if (!args.length) {\n return '';\n }\n\n return args.reduce((sum, cur) => {\n if (!cur) {\n return sum;\n }\n if (!sum) {\n return cur;\n }\n\n return `${sum}${SEPARATOR}${cur}`;\n }, '') as string;\n};\n\nconst encodeName = function (\n name: string,\n prefix = '',\n withExt = false,\n): string {\n try {\n const ext = withExt ? '.js' : '';\n return `${prefix}${name\n .replace(\n new RegExp(`${NameTransformSymbol.AT}`, 'g'),\n NameTransformMap[NameTransformSymbol.AT],\n )\n .replace(\n new RegExp(`${NameTransformSymbol.HYPHEN}`, 'g'),\n NameTransformMap[NameTransformSymbol.HYPHEN],\n )\n .replace(\n new RegExp(`${NameTransformSymbol.SLASH}`, 'g'),\n NameTransformMap[NameTransformSymbol.SLASH],\n )}${ext}`;\n } catch (err) {\n throw err;\n }\n};\n\nconst decodeName = function (\n name: string,\n prefix?: string,\n withExt?: boolean,\n): string {\n try {\n let decodedName = name;\n if (prefix) {\n if (!decodedName.startsWith(prefix)) {\n return decodedName;\n }\n decodedName = decodedName.replace(new RegExp(prefix, 'g'), '');\n }\n decodedName = decodedName\n .replace(\n new RegExp(`${NameTransformMap[NameTransformSymbol.AT]}`, 'g'),\n EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.AT]],\n )\n .replace(\n new RegExp(`${NameTransformMap[NameTransformSymbol.SLASH]}`, 'g'),\n EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.SLASH]],\n )\n .replace(\n new RegExp(`${NameTransformMap[NameTransformSymbol.HYPHEN]}`, 'g'),\n EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.HYPHEN]],\n );\n if (withExt) {\n decodedName = decodedName.replace('.js', '');\n }\n return decodedName;\n } catch (err) {\n throw err;\n }\n};\n\nconst generateExposeFilename = (\n exposeName: string,\n withExt: boolean,\n): string => {\n if (!exposeName) {\n return '';\n }\n\n let expose = exposeName;\n if (expose === '.') {\n expose = 'default_export';\n }\n if (expose.startsWith('./')) {\n expose = expose.replace('./', '');\n }\n\n return encodeName(expose, '__federation_expose_', withExt);\n};\n\nconst generateShareFilename = (pkgName: string, withExt: boolean): string => {\n if (!pkgName) {\n return '';\n }\n return encodeName(pkgName, '__federation_shared_', withExt);\n};\n\nconst getResourceUrl = (module: ModuleInfo, sourceUrl: string): string => {\n if ('getPublicPath' in module) {\n let publicPath;\n\n if (!module.getPublicPath.startsWith('function')) {\n publicPath = new Function(module.getPublicPath)();\n } else {\n publicPath = new Function('return ' + module.getPublicPath)()();\n }\n\n return `${publicPath}${sourceUrl}`;\n } else if ('publicPath' in module) {\n if (\n !isBrowserEnv() &&\n !isReactNativeEnv() &&\n 'ssrPublicPath' in module &&\n typeof module.ssrPublicPath === 'string'\n ) {\n return `${module.ssrPublicPath}${sourceUrl}`;\n }\n return `${module.publicPath}${sourceUrl}`;\n } else {\n console.warn(\n 'Cannot get resource URL. If in debug mode, please ignore.',\n module,\n sourceUrl,\n );\n return '';\n }\n};\n\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nconst assert = (condition: any, msg: string): asserts condition => {\n if (!condition) {\n error(msg);\n }\n};\n\nconst error = (msg: string | Error | unknown): never => {\n throw new Error(`${LOG_CATEGORY}: ${msg}`);\n};\n\nconst warn = (msg: Parameters<typeof console.warn>[0]): void => {\n console.warn(`${LOG_CATEGORY}: ${msg}`);\n};\n\nfunction safeToString(info: any): string {\n try {\n return JSON.stringify(info, null, 2);\n } catch (e) {\n return '';\n }\n}\n\n// RegExp for version string\nconst VERSION_PATTERN_REGEXP: RegExp = /^([\\d^=v<>~]|[*xX]$)/;\n\nfunction isRequiredVersion(str: string): boolean {\n return VERSION_PATTERN_REGEXP.test(str);\n}\n\nexport {\n parseEntry,\n decodeName,\n encodeName,\n composeKeyWithSeparator,\n generateExposeFilename,\n generateShareFilename,\n getResourceUrl,\n assert,\n error,\n warn,\n safeToString,\n isRequiredVersion,\n};\n"],"mappings":"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"}
# `@module-federation/sdk` Documentation
- This SDK provides utilities and tools to support the implementation of Module Federation in your projects.
- It contains utility functions for parsing, encoding, and decoding module names, as well as generating filenames for exposed modules and shared packages.
- It also includes a logger for debugging and environment detection utilities.
- Additionally, it provides a function to generate a snapshot from a manifest and environment detection utilities.
## Usage
```javascript
// The SDK can be used to parse entry strings, encode and decode module names, and generate filenames for exposed modules and shared packages.
// It also includes a logger for debugging and environment detection utilities.
// Additionally, it provides a function to generate a snapshot from a manifest and environment detection utilities.
import { parseEntry, encodeName, decodeName, generateExposeFilename, generateShareFilename, createLogger, isBrowserEnv, isBrowserEnvValue, isDebugMode, getProcessEnv, generateSnapshotFromManifest } from '@module-federation/sdk';
// Parse an entry string into a RemoteEntryInfo object
parseEntry('entryString');
// Encode a module name with a prefix and optional extension
encodeName('moduleName', 'prefix');
// Decode a module name with a prefix and optional extension
decodeName('encodedModuleName', 'prefix');
// Generate a filename for an exposed module
generateExposeFilename('exposeName', true);
// Generate a filename for a shared package
generateShareFilename('packageName', true);
// Create a logger
const logger = createLogger('identifier');
// Check if the current environment is a browser
const inBrowser = isBrowserEnv();
const inBrowserStatic = isBrowserEnvValue;
// Check if the current environment is in debug mode
isDebugMode();
// Get the process environment
getProcessEnv();
// Generate a snapshot from a manifest
generateSnapshotFromManifest(manifest, options);
```
### parseEntry
- Type: `parseEntry(str: string, devVerOrUrl?: string, separator?: string) `
- Parses a string into a RemoteEntryInfo object.
### encodeName
- Type: `encodeName(name: string, prefix?: string, withExt?: boolean)`
- Encodes a name with a prefix and optional extension.
### decodeName
- Type: `decodeName(name: string, prefix?: string, withExt?: boolean)`
- Decodes a name with a prefix and optional extension.
### generateExposeFilename
- Type: `generateExposeFilename(exposeName: string, withExt: boolean)`
- Generates a filename for an expose.
### generateShareFilename
- Type: `generateShareFilename(pkgName: string, withExt: boolean)`
- Generates a filename for a shared package.
### createLogger
- Type: `createLogger(prefix: string)`
- Creates a logger for debugging.
### isBrowserEnv
- Type: `isBrowserEnv(): boolean`
- Checks if the current environment is a browser.
### isBrowserEnvValue
- Type: `isBrowserEnvValue: boolean`
- Static browser environment flag (tree-shakable when ENV_TARGET is defined).
### isDebugMode
- Type: `isDebugMode()`
- Checks if the current environment is in debug mode.
### getProcessEnv
- Type: `getProcessEnv()`
- Gets the process environment.
### generateSnapshotFromManifest
- Type: `generateSnapshotFromManifest(manifest: Manifest, options?: IOptions)`
- Generates a snapshot from a manifest.
## Testing
The SDK uses Jest for testing. The configuration can be found in `jest.config.js`. The tests are located in the **tests** directory.
+64
-12
{
"name": "@module-federation/sdk",
"version": "0.0.0-feat-apply-bundler-runtime-1702896801896",
"version": "0.0.0-feat-await-dev-dts-20260324072937",
"type": "module",
"license": "MIT",

@@ -10,2 +11,12 @@ "description": "A sdk for support module federation",

],
"files": [
"dist/",
"README.md",
"LICENSE"
],
"repository": {
"type": "git",
"url": "git+https://github.com/module-federation/core.git",
"directory": "packages/sdk"
},
"publishConfig": {

@@ -16,18 +27,59 @@ "access": "public"

"sideEffects": false,
"main": "./index.cjs.js",
"module": "./index.esm.js",
"types": "./index.cjs.d.ts",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"browser": {
"url": false
},
"exports": {
"./package.json": "./package.json",
".": {
"module": "./index.esm.js",
"import": "./index.cjs.mjs",
"default": "./index.cjs.js"
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"require": {
"types": "./dist/index.d.ts",
"default": "./dist/index.cjs"
}
},
"./normalize-webpack-path": {
"module": "./normalize-webpack-path.esm.js",
"import": "./normalize-webpack-path.cjs.mjs",
"default": "./normalize-webpack-path.cjs.js"
"import": {
"types": "./dist/normalize-webpack-path.d.ts",
"default": "./dist/normalize-webpack-path.js"
},
"require": {
"types": "./dist/normalize-webpack-path.d.ts",
"default": "./dist/normalize-webpack-path.cjs"
}
}
},
"typesVersions": {
"*": {
".": [
"./dist/index.d.ts"
],
"normalize-webpack-path": [
"./dist/normalize-webpack-path.d.ts"
]
}
},
"devDependencies": {
"@jest/globals": "29.7.0",
"webpack": "^5.0.0"
},
"peerDependencies": {
"node-fetch": "^3.3.2"
},
"peerDependenciesMeta": {
"node-fetch": {
"optional": true
}
},
"scripts": {
"build": "tsdown --config tsdown.config.ts",
"lint": "ESLINT_USE_FLAT_CONFIG=false pnpm exec eslint --ignore-pattern node_modules \"**/*.ts\" \"package.json\"",
"test": "pnpm exec jest --config jest.config.cjs --passWithNoTests",
"test:ci": "pnpm exec jest --config jest.config.cjs --passWithNoTests --ci --coverage",
"pre-release": "pnpm run test && pnpm run build"
}
}
}
-1
export * from "./src/index";
exports._default = require('./index.cjs.js').default;
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _define_property$2(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
var FederationModuleManifest = "federation-manifest.json";
var MANIFEST_EXT = ".json";
var BROWSER_LOG_KEY = "FEDERATION_DEBUG";
var BROWSER_LOG_VALUE = "1";
var NameTransformSymbol = {
AT: "@",
HYPHEN: "-",
SLASH: "/"
};
var _obj;
var NameTransformMap = (_obj = {}, _define_property$2(_obj, NameTransformSymbol.AT, "scope_"), _define_property$2(_obj, NameTransformSymbol.HYPHEN, "_"), _define_property$2(_obj, NameTransformSymbol.SLASH, "__"), _obj);
var _obj1;
var EncodedNameTransformMap = (_obj1 = {}, _define_property$2(_obj1, NameTransformMap[NameTransformSymbol.AT], NameTransformSymbol.AT), _define_property$2(_obj1, NameTransformMap[NameTransformSymbol.HYPHEN], NameTransformSymbol.HYPHEN), _define_property$2(_obj1, NameTransformMap[NameTransformSymbol.SLASH], NameTransformSymbol.SLASH), _obj1);
var SEPARATOR = ":";
function isBrowserEnv() {
return typeof window !== "undefined";
}
function isDebugMode() {
if (typeof process !== "undefined" && process.env && process.env["FEDERATION_DEBUG"]) {
return Boolean(process.env["FEDERATION_DEBUG"]);
}
return typeof FEDERATION_DEBUG !== "undefined" && Boolean(FEDERATION_DEBUG);
}
var getProcessEnv = function getProcessEnv() {
return typeof process !== "undefined" && process.env ? process.env : {};
};
function _array_like_to_array$1(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _array_without_holes(arr) {
if (Array.isArray(arr)) return _array_like_to_array$1(arr);
}
function _class_call_check(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for(var i = 0; i < props.length; i++){
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _create_class(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _define_property$1(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _iterable_to_array$1(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _non_iterable_spread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _to_consumable_array(arr) {
return _array_without_holes(arr) || _iterable_to_array$1(arr) || _unsupported_iterable_to_array$1(arr) || _non_iterable_spread();
}
function _unsupported_iterable_to_array$1(o, minLen) {
if (!o) return;
if (typeof o === "string") return _array_like_to_array$1(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$1(o, minLen);
}
function safeToString(info) {
try {
return JSON.stringify(info, null, 2);
} catch (e) {
return "";
}
}
var DEBUG_LOG = "[ FEDERATION DEBUG ]";
var Logger = /*#__PURE__*/ function() {
function Logger(identifier) {
_class_call_check(this, Logger);
_define_property$1(this, "enable", false);
_define_property$1(this, "identifier", void 0);
this.identifier = identifier || DEBUG_LOG;
if (isBrowserEnv() && localStorage.getItem(BROWSER_LOG_KEY) === BROWSER_LOG_VALUE) {
this.enable = true;
} else if (isDebugMode()) {
this.enable = true;
}
}
_create_class(Logger, [
{
key: "info",
value: function info(msg, info) {
if (this.enable) {
var argsToString = safeToString(info) || "";
if (isBrowserEnv()) {
console.info("%c ".concat(this.identifier, ": ").concat(msg, " ").concat(argsToString), "color:#3300CC");
} else {
console.info("\x1b[34m%s", "".concat(this.identifier, ": ").concat(msg, " ").concat(argsToString ? "\n".concat(argsToString) : ""));
}
}
}
},
{
key: "logOriginalInfo",
value: function logOriginalInfo() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
if (this.enable) {
if (isBrowserEnv()) {
var _console;
console.info("%c ".concat(this.identifier, ": OriginalInfo"), "color:#3300CC");
(_console = console).log.apply(_console, _to_consumable_array(args));
} else {
var _console1;
console.info("%c ".concat(this.identifier, ": OriginalInfo"), "color:#3300CC");
(_console1 = console).log.apply(_console1, _to_consumable_array(args));
}
}
}
}
]);
return Logger;
}();
function _array_like_to_array(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _array_with_holes(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterable_to_array(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterable_to_array_limit(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally{
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally{
if (_d) throw _e;
}
}
return _arr;
}
function _non_iterable_rest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _sliced_to_array(arr, i) {
return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _to_array(arr) {
return _array_with_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
if (!o) return;
if (typeof o === "string") return _array_like_to_array(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
var LOG_CATEGORY = "[ Federation Runtime ]";
// entry: name:version version : 1.0.0 | ^1.2.3
// entry: name:entry entry: https://localhost:9000/federation-manifest.json
var parseEntry = function(str, devVerOrUrl) {
var strSplit = str.split(SEPARATOR);
var devVersionOrUrl = getProcessEnv()["NODE_ENV"] === "development" && devVerOrUrl;
var defaultVersion = "*";
var isEntry = function(s) {
return s.startsWith("http") || s.endsWith(MANIFEST_EXT);
};
// Check if the string starts with a type
if (strSplit.length >= 2) {
var _strSplit = _to_array(strSplit), name = _strSplit[0], versionOrEntryArr = _strSplit.slice(1);
var versionOrEntry = devVersionOrUrl || versionOrEntryArr.join(SEPARATOR);
if (isEntry(versionOrEntry)) {
return {
name: name,
entry: versionOrEntry
};
} else {
// Apply version rule
// devVersionOrUrl => inputVersion => defaultVersion
return {
name: name,
version: versionOrEntry || defaultVersion
};
}
} else if (strSplit.length === 1) {
var _strSplit1 = _sliced_to_array(strSplit, 1), name1 = _strSplit1[0];
if (devVersionOrUrl && isEntry(devVersionOrUrl)) {
return {
name: name1,
entry: devVersionOrUrl
};
}
return {
name: name1,
version: devVersionOrUrl || defaultVersion
};
} else {
throw "Invalid entry value: ".concat(str);
}
};
var logger = new Logger();
var composeKeyWithSeparator = function composeKeyWithSeparator() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
if (!args.length) {
return "";
}
return args.reduce(function(sum, cur) {
if (!cur) {
return sum;
}
if (!sum) {
return cur;
}
return "".concat(sum).concat(SEPARATOR).concat(cur);
}, "");
};
var encodeName = function encodeName(name) {
var prefix = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "", withExt = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
try {
var ext = withExt ? ".js" : "";
return "".concat(prefix).concat(name.replace(new RegExp("".concat(NameTransformSymbol.AT), "g"), NameTransformMap[NameTransformSymbol.AT]).replace(new RegExp("".concat(NameTransformSymbol.HYPHEN), "g"), NameTransformMap[NameTransformSymbol.HYPHEN]).replace(new RegExp("".concat(NameTransformSymbol.SLASH), "g"), NameTransformMap[NameTransformSymbol.SLASH])).concat(ext);
} catch (err) {
throw err;
}
};
var decodeName = function decodeName(name, prefix, withExt) {
try {
var decodedName = name;
if (prefix) {
decodedName = decodedName.replace(new RegExp(prefix, "g"), "");
}
decodedName = decodedName.replace(new RegExp("".concat(NameTransformMap[NameTransformSymbol.AT]), "g"), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.AT]]).replace(new RegExp("".concat(NameTransformMap[NameTransformSymbol.SLASH]), "g"), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.SLASH]]).replace(new RegExp("".concat(NameTransformMap[NameTransformSymbol.HYPHEN]), "g"), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.HYPHEN]]);
if (withExt) {
decodedName = decodedName.replace(".js", "");
}
return decodedName;
} catch (err) {
throw err;
}
};
var generateExposeFilename = function(exposeName, withExt) {
if (!exposeName) {
return "";
}
var expose = exposeName;
if (expose === ".") {
expose = "default_export";
}
if (expose.startsWith("./")) {
expose = expose.replace("./", "");
}
return encodeName(expose, "__federation_expose_", withExt);
};
var generateShareFilename = function(pkgName, withExt) {
if (!pkgName) {
return "";
}
return encodeName(pkgName, "__federation_shared_", withExt);
};
var getResourceUrl = function(module, sourceUrl) {
if ("getPublicPath" in module) {
var publicPath = new Function(module.getPublicPath)();
return "".concat(publicPath).concat(sourceUrl);
} else if ("publicPath" in module) {
return "".concat(module.publicPath).concat(sourceUrl);
} else {
console.warn("Can not get resource url, if in debug mode, please ignore", module, sourceUrl);
return "";
}
};
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
var assert = function(condition, msg) {
if (!condition) {
error(msg);
}
};
var error = function(msg) {
throw new Error("".concat(LOG_CATEGORY, ": ").concat(msg));
};
var warn = function(msg) {
console.warn("".concat(LOG_CATEGORY, ": ").concat(msg));
};
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _object_spread(target) {
for(var i = 1; i < arguments.length; i++){
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function(key) {
_define_property(target, key, source[key]);
});
}
return target;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) {
symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
}
keys.push.apply(keys, symbols);
}
return keys;
}
function _object_spread_props(target, source) {
source = source != null ? source : {};
if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
var simpleJoinRemoteEntry = function(rPath, rName) {
if (!rPath) {
return rName;
}
var transformPath = function(str) {
if (str === ".") {
return "";
}
if (str.startsWith("./")) {
return str.replace("./", "");
}
if (str.startsWith("/")) {
var strWithoutSlash = str.slice(1);
if (strWithoutSlash.endsWith("/")) {
return strWithoutSlash.slice(0, -1);
}
return strWithoutSlash;
}
return str;
};
var transformedPath = transformPath(rPath);
if (!transformedPath) {
return rName;
}
if (transformedPath.endsWith("/")) {
return "".concat(transformedPath).concat(rName);
}
return "".concat(transformedPath, "/").concat(rName);
};
// Priority: overrides > remotes
// eslint-disable-next-line max-lines-per-function
function generateSnapshotFromManifest(manifest) {
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
var _manifest_metaData;
var _options_remotes = options.remotes, remotes = _options_remotes === void 0 ? {} : _options_remotes, _options_overrides = options.overrides, overrides = _options_overrides === void 0 ? {} : _options_overrides, version = options.version;
var remoteSnapshot;
var getPublicPath = function() {
if ("publicPath" in manifest.metaData) {
return manifest.metaData.publicPath;
} else {
return manifest.metaData.getPublicPath;
}
};
var overridesKeys = Object.keys(overrides);
var remotesInfo = {};
// If remotes are not provided, only the remotes in the manifest will be read
if (!Object.keys(remotes).length) {
var _manifest_remotes;
remotesInfo = ((_manifest_remotes = manifest.remotes) === null || _manifest_remotes === void 0 ? void 0 : _manifest_remotes.reduce(function(res, next) {
var matchedVersion;
var name = next.federationContainerName;
// overrides have higher priority
if (overridesKeys.includes(name)) {
matchedVersion = overrides[name];
} else {
if ("version" in next) {
matchedVersion = next.version;
} else {
matchedVersion = next.entry;
}
}
res[name] = {
matchedVersion: matchedVersion
};
return res;
}, {})) || {};
}
// If remotes (deploy scenario) are specified, they need to be traversed again
Object.keys(remotes).forEach(function(key) {
return remotesInfo[key] = {
// overrides will override dependencies
matchedVersion: overridesKeys.includes(key) ? overrides[key] : remotes[key]
};
});
var _manifest_metaData1 = manifest.metaData, _manifest_metaData_remoteEntry = _manifest_metaData1.remoteEntry, remoteEntryPath = _manifest_metaData_remoteEntry.path, remoteEntryName = _manifest_metaData_remoteEntry.name, remoteEntryType = _manifest_metaData_remoteEntry.type, remoteTypes = _manifest_metaData1.types, buildVersion = _manifest_metaData1.buildInfo.buildVersion, globalName = _manifest_metaData1.globalName;
var exposes = manifest.exposes;
var basicRemoteSnapshot = {
version: version ? version : "",
buildVersion: buildVersion,
globalName: globalName,
remoteEntry: simpleJoinRemoteEntry(remoteEntryPath, remoteEntryName),
remoteEntryType: remoteEntryType,
remoteTypes: simpleJoinRemoteEntry(remoteTypes.path, remoteTypes.name),
remotesInfo: remotesInfo,
shared: manifest === null || manifest === void 0 ? void 0 : manifest.shared.map(function(item) {
return {
assets: item.assets,
sharedName: item.name
};
}),
modules: exposes === null || exposes === void 0 ? void 0 : exposes.map(function(expose) {
return {
moduleName: expose.name,
modulePath: expose.path,
assets: expose.assets
};
})
};
if ((_manifest_metaData = manifest.metaData) === null || _manifest_metaData === void 0 ? void 0 : _manifest_metaData.prefetchEntry) {
var _manifest_metaData_prefetchEntry = manifest.metaData.prefetchEntry, path = _manifest_metaData_prefetchEntry.path, name = _manifest_metaData_prefetchEntry.name, type = _manifest_metaData_prefetchEntry.type;
basicRemoteSnapshot = _object_spread_props(_object_spread({}, basicRemoteSnapshot), {
prefetchEntry: simpleJoinRemoteEntry(path, name),
prefetchEntryType: type
});
}
if ("publicPath" in manifest.metaData) {
remoteSnapshot = _object_spread_props(_object_spread({}, basicRemoteSnapshot), {
publicPath: getPublicPath()
});
} else {
remoteSnapshot = _object_spread_props(_object_spread({}, basicRemoteSnapshot), {
getPublicPath: getPublicPath()
});
}
return remoteSnapshot;
}
function isManifestProvider(moduleInfo) {
if ("remoteEntry" in moduleInfo && moduleInfo.remoteEntry.endsWith(MANIFEST_EXT)) {
return true;
} else {
return false;
}
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _async_to_generator(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _instanceof(left, right) {
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
return !!right[Symbol.hasInstance](left);
} else {
return left instanceof right;
}
}
function _ts_generator(thisArg, body) {
var f, y, t, g, _ = {
label: 0,
sent: function() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
};
return g = {
next: verb(0),
"throw": verb(1),
"return": verb(2)
}, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
return this;
}), g;
function verb(n) {
return function(v) {
return step([
n,
v
]);
};
}
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while(_)try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [
op[0] & 2,
t.value
];
switch(op[0]){
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return {
value: op[1],
done: false
};
case 5:
_.label++;
y = op[1];
op = [
0
];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2]) _.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [
6,
e
];
y = 0;
} finally{
f = t = 0;
}
if (op[0] & 5) throw op[1];
return {
value: op[0] ? op[1] : void 0,
done: true
};
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function safeWrapper(callback, disableWarn) {
return _safeWrapper.apply(this, arguments);
}
function _safeWrapper() {
_safeWrapper = _async_to_generator(function(callback, disableWarn) {
var res, e;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
_state.trys.push([
0,
2,
,
3
]);
return [
4,
callback()
];
case 1:
res = _state.sent();
return [
2,
res
];
case 2:
e = _state.sent();
!disableWarn && warn(e);
return [
2
];
case 3:
return [
2
];
}
});
});
return _safeWrapper.apply(this, arguments);
}
function isStaticResourcesEqual(url1, url2) {
var REG_EXP = /^(https?:)?\/\//i;
// Transform url1 and url2 into relative paths
var relativeUrl1 = url1.replace(REG_EXP, "").replace(/\/$/, "");
var relativeUrl2 = url2.replace(REG_EXP, "").replace(/\/$/, "");
// Check if the relative paths are identical
return relativeUrl1 === relativeUrl2;
}
function createScript(url, cb, attrs, createScriptHook) {
// Retrieve the existing script element by its src attribute
var script = null;
var needAttach = true;
var scripts = document.getElementsByTagName("script");
for(var i = 0; i < scripts.length; i++){
var s = scripts[i];
var scriptSrc = s.getAttribute("src");
if (scriptSrc && isStaticResourcesEqual(scriptSrc, url)) {
script = s;
needAttach = false;
break;
}
}
if (!script) {
script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
if (createScriptHook) {
var createScriptRes = createScriptHook(url);
if (_instanceof(createScriptRes, HTMLScriptElement)) {
script = createScriptRes;
}
}
}
if (attrs) {
Object.keys(attrs).forEach(function(name) {
if (script) {
if (name === "async" || name === "defer") {
script[name] = attrs[name];
} else {
script.setAttribute(name, attrs[name]);
}
}
});
}
var onScriptComplete = function(prev, // eslint-disable-next-line @typescript-eslint/no-explicit-any
event) {
// Prevent memory leaks in IE.
if (script) {
script.onerror = null;
script.onload = null;
safeWrapper(function() {
(script === null || script === void 0 ? void 0 : script.parentNode) && script.parentNode.removeChild(script);
});
if (prev) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var res = prev(event);
cb();
return res;
}
}
cb();
};
script.onerror = onScriptComplete.bind(null, script.onerror);
script.onload = onScriptComplete.bind(null, script.onload);
return {
script: script,
needAttach: needAttach
};
}
function loadScript(url, info) {
var attrs = info.attrs, createScriptHook = info.createScriptHook;
return new Promise(function(resolve, _reject) {
var _createScript = createScript(url, resolve, attrs, createScriptHook), script = _createScript.script, needAttach = _createScript.needAttach;
needAttach && document.getElementsByTagName("head")[0].appendChild(script);
});
}
exports.BROWSER_LOG_KEY = BROWSER_LOG_KEY;
exports.BROWSER_LOG_VALUE = BROWSER_LOG_VALUE;
exports.EncodedNameTransformMap = EncodedNameTransformMap;
exports.FederationModuleManifest = FederationModuleManifest;
exports.Logger = Logger;
exports.MANIFEST_EXT = MANIFEST_EXT;
exports.NameTransformMap = NameTransformMap;
exports.NameTransformSymbol = NameTransformSymbol;
exports.SEPARATOR = SEPARATOR;
exports.assert = assert;
exports.composeKeyWithSeparator = composeKeyWithSeparator;
exports.createScript = createScript;
exports.decodeName = decodeName;
exports.encodeName = encodeName;
exports.error = error;
exports.generateExposeFilename = generateExposeFilename;
exports.generateShareFilename = generateShareFilename;
exports.generateSnapshotFromManifest = generateSnapshotFromManifest;
exports.getProcessEnv = getProcessEnv;
exports.getResourceUrl = getResourceUrl;
exports.isBrowserEnv = isBrowserEnv;
exports.isDebugMode = isDebugMode;
exports.isManifestProvider = isManifestProvider;
exports.isStaticResourcesEqual = isStaticResourcesEqual;
exports.loadScript = loadScript;
exports.logger = logger;
exports.parseEntry = parseEntry;
exports.safeWrapper = safeWrapper;
exports.warn = warn;
export * from './index.cjs.js';
export { _default as default } from './index.cjs.default.js';
function _define_property$2(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
var FederationModuleManifest = "federation-manifest.json";
var MANIFEST_EXT = ".json";
var BROWSER_LOG_KEY = "FEDERATION_DEBUG";
var BROWSER_LOG_VALUE = "1";
var NameTransformSymbol = {
AT: "@",
HYPHEN: "-",
SLASH: "/"
};
var _obj;
var NameTransformMap = (_obj = {}, _define_property$2(_obj, NameTransformSymbol.AT, "scope_"), _define_property$2(_obj, NameTransformSymbol.HYPHEN, "_"), _define_property$2(_obj, NameTransformSymbol.SLASH, "__"), _obj);
var _obj1;
var EncodedNameTransformMap = (_obj1 = {}, _define_property$2(_obj1, NameTransformMap[NameTransformSymbol.AT], NameTransformSymbol.AT), _define_property$2(_obj1, NameTransformMap[NameTransformSymbol.HYPHEN], NameTransformSymbol.HYPHEN), _define_property$2(_obj1, NameTransformMap[NameTransformSymbol.SLASH], NameTransformSymbol.SLASH), _obj1);
var SEPARATOR = ":";
function isBrowserEnv() {
return typeof window !== "undefined";
}
function isDebugMode() {
if (typeof process !== "undefined" && process.env && process.env["FEDERATION_DEBUG"]) {
return Boolean(process.env["FEDERATION_DEBUG"]);
}
return typeof FEDERATION_DEBUG !== "undefined" && Boolean(FEDERATION_DEBUG);
}
var getProcessEnv = function getProcessEnv() {
return typeof process !== "undefined" && process.env ? process.env : {};
};
function _array_like_to_array$1(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _array_without_holes(arr) {
if (Array.isArray(arr)) return _array_like_to_array$1(arr);
}
function _class_call_check(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for(var i = 0; i < props.length; i++){
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _create_class(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _define_property$1(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _iterable_to_array$1(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _non_iterable_spread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _to_consumable_array(arr) {
return _array_without_holes(arr) || _iterable_to_array$1(arr) || _unsupported_iterable_to_array$1(arr) || _non_iterable_spread();
}
function _unsupported_iterable_to_array$1(o, minLen) {
if (!o) return;
if (typeof o === "string") return _array_like_to_array$1(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$1(o, minLen);
}
function safeToString(info) {
try {
return JSON.stringify(info, null, 2);
} catch (e) {
return "";
}
}
var DEBUG_LOG = "[ FEDERATION DEBUG ]";
var Logger = /*#__PURE__*/ function() {
function Logger(identifier) {
_class_call_check(this, Logger);
_define_property$1(this, "enable", false);
_define_property$1(this, "identifier", void 0);
this.identifier = identifier || DEBUG_LOG;
if (isBrowserEnv() && localStorage.getItem(BROWSER_LOG_KEY) === BROWSER_LOG_VALUE) {
this.enable = true;
} else if (isDebugMode()) {
this.enable = true;
}
}
_create_class(Logger, [
{
key: "info",
value: function info(msg, info) {
if (this.enable) {
var argsToString = safeToString(info) || "";
if (isBrowserEnv()) {
console.info("%c ".concat(this.identifier, ": ").concat(msg, " ").concat(argsToString), "color:#3300CC");
} else {
console.info("\x1b[34m%s", "".concat(this.identifier, ": ").concat(msg, " ").concat(argsToString ? "\n".concat(argsToString) : ""));
}
}
}
},
{
key: "logOriginalInfo",
value: function logOriginalInfo() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
if (this.enable) {
if (isBrowserEnv()) {
var _console;
console.info("%c ".concat(this.identifier, ": OriginalInfo"), "color:#3300CC");
(_console = console).log.apply(_console, _to_consumable_array(args));
} else {
var _console1;
console.info("%c ".concat(this.identifier, ": OriginalInfo"), "color:#3300CC");
(_console1 = console).log.apply(_console1, _to_consumable_array(args));
}
}
}
}
]);
return Logger;
}();
function _array_like_to_array(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _array_with_holes(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterable_to_array(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterable_to_array_limit(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally{
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally{
if (_d) throw _e;
}
}
return _arr;
}
function _non_iterable_rest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _sliced_to_array(arr, i) {
return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _to_array(arr) {
return _array_with_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
if (!o) return;
if (typeof o === "string") return _array_like_to_array(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
var LOG_CATEGORY = "[ Federation Runtime ]";
// entry: name:version version : 1.0.0 | ^1.2.3
// entry: name:entry entry: https://localhost:9000/federation-manifest.json
var parseEntry = function(str, devVerOrUrl) {
var strSplit = str.split(SEPARATOR);
var devVersionOrUrl = getProcessEnv()["NODE_ENV"] === "development" && devVerOrUrl;
var defaultVersion = "*";
var isEntry = function(s) {
return s.startsWith("http") || s.endsWith(MANIFEST_EXT);
};
// Check if the string starts with a type
if (strSplit.length >= 2) {
var _strSplit = _to_array(strSplit), name = _strSplit[0], versionOrEntryArr = _strSplit.slice(1);
var versionOrEntry = devVersionOrUrl || versionOrEntryArr.join(SEPARATOR);
if (isEntry(versionOrEntry)) {
return {
name: name,
entry: versionOrEntry
};
} else {
// Apply version rule
// devVersionOrUrl => inputVersion => defaultVersion
return {
name: name,
version: versionOrEntry || defaultVersion
};
}
} else if (strSplit.length === 1) {
var _strSplit1 = _sliced_to_array(strSplit, 1), name1 = _strSplit1[0];
if (devVersionOrUrl && isEntry(devVersionOrUrl)) {
return {
name: name1,
entry: devVersionOrUrl
};
}
return {
name: name1,
version: devVersionOrUrl || defaultVersion
};
} else {
throw "Invalid entry value: ".concat(str);
}
};
var logger = new Logger();
var composeKeyWithSeparator = function composeKeyWithSeparator() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
if (!args.length) {
return "";
}
return args.reduce(function(sum, cur) {
if (!cur) {
return sum;
}
if (!sum) {
return cur;
}
return "".concat(sum).concat(SEPARATOR).concat(cur);
}, "");
};
var encodeName = function encodeName(name) {
var prefix = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "", withExt = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
try {
var ext = withExt ? ".js" : "";
return "".concat(prefix).concat(name.replace(new RegExp("".concat(NameTransformSymbol.AT), "g"), NameTransformMap[NameTransformSymbol.AT]).replace(new RegExp("".concat(NameTransformSymbol.HYPHEN), "g"), NameTransformMap[NameTransformSymbol.HYPHEN]).replace(new RegExp("".concat(NameTransformSymbol.SLASH), "g"), NameTransformMap[NameTransformSymbol.SLASH])).concat(ext);
} catch (err) {
throw err;
}
};
var decodeName = function decodeName(name, prefix, withExt) {
try {
var decodedName = name;
if (prefix) {
decodedName = decodedName.replace(new RegExp(prefix, "g"), "");
}
decodedName = decodedName.replace(new RegExp("".concat(NameTransformMap[NameTransformSymbol.AT]), "g"), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.AT]]).replace(new RegExp("".concat(NameTransformMap[NameTransformSymbol.SLASH]), "g"), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.SLASH]]).replace(new RegExp("".concat(NameTransformMap[NameTransformSymbol.HYPHEN]), "g"), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.HYPHEN]]);
if (withExt) {
decodedName = decodedName.replace(".js", "");
}
return decodedName;
} catch (err) {
throw err;
}
};
var generateExposeFilename = function(exposeName, withExt) {
if (!exposeName) {
return "";
}
var expose = exposeName;
if (expose === ".") {
expose = "default_export";
}
if (expose.startsWith("./")) {
expose = expose.replace("./", "");
}
return encodeName(expose, "__federation_expose_", withExt);
};
var generateShareFilename = function(pkgName, withExt) {
if (!pkgName) {
return "";
}
return encodeName(pkgName, "__federation_shared_", withExt);
};
var getResourceUrl = function(module, sourceUrl) {
if ("getPublicPath" in module) {
var publicPath = new Function(module.getPublicPath)();
return "".concat(publicPath).concat(sourceUrl);
} else if ("publicPath" in module) {
return "".concat(module.publicPath).concat(sourceUrl);
} else {
console.warn("Can not get resource url, if in debug mode, please ignore", module, sourceUrl);
return "";
}
};
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
var assert = function(condition, msg) {
if (!condition) {
error(msg);
}
};
var error = function(msg) {
throw new Error("".concat(LOG_CATEGORY, ": ").concat(msg));
};
var warn = function(msg) {
console.warn("".concat(LOG_CATEGORY, ": ").concat(msg));
};
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _object_spread(target) {
for(var i = 1; i < arguments.length; i++){
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function(key) {
_define_property(target, key, source[key]);
});
}
return target;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) {
symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
}
keys.push.apply(keys, symbols);
}
return keys;
}
function _object_spread_props(target, source) {
source = source != null ? source : {};
if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
var simpleJoinRemoteEntry = function(rPath, rName) {
if (!rPath) {
return rName;
}
var transformPath = function(str) {
if (str === ".") {
return "";
}
if (str.startsWith("./")) {
return str.replace("./", "");
}
if (str.startsWith("/")) {
var strWithoutSlash = str.slice(1);
if (strWithoutSlash.endsWith("/")) {
return strWithoutSlash.slice(0, -1);
}
return strWithoutSlash;
}
return str;
};
var transformedPath = transformPath(rPath);
if (!transformedPath) {
return rName;
}
if (transformedPath.endsWith("/")) {
return "".concat(transformedPath).concat(rName);
}
return "".concat(transformedPath, "/").concat(rName);
};
// Priority: overrides > remotes
// eslint-disable-next-line max-lines-per-function
function generateSnapshotFromManifest(manifest) {
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
var _manifest_metaData;
var _options_remotes = options.remotes, remotes = _options_remotes === void 0 ? {} : _options_remotes, _options_overrides = options.overrides, overrides = _options_overrides === void 0 ? {} : _options_overrides, version = options.version;
var remoteSnapshot;
var getPublicPath = function() {
if ("publicPath" in manifest.metaData) {
return manifest.metaData.publicPath;
} else {
return manifest.metaData.getPublicPath;
}
};
var overridesKeys = Object.keys(overrides);
var remotesInfo = {};
// If remotes are not provided, only the remotes in the manifest will be read
if (!Object.keys(remotes).length) {
var _manifest_remotes;
remotesInfo = ((_manifest_remotes = manifest.remotes) === null || _manifest_remotes === void 0 ? void 0 : _manifest_remotes.reduce(function(res, next) {
var matchedVersion;
var name = next.federationContainerName;
// overrides have higher priority
if (overridesKeys.includes(name)) {
matchedVersion = overrides[name];
} else {
if ("version" in next) {
matchedVersion = next.version;
} else {
matchedVersion = next.entry;
}
}
res[name] = {
matchedVersion: matchedVersion
};
return res;
}, {})) || {};
}
// If remotes (deploy scenario) are specified, they need to be traversed again
Object.keys(remotes).forEach(function(key) {
return remotesInfo[key] = {
// overrides will override dependencies
matchedVersion: overridesKeys.includes(key) ? overrides[key] : remotes[key]
};
});
var _manifest_metaData1 = manifest.metaData, _manifest_metaData_remoteEntry = _manifest_metaData1.remoteEntry, remoteEntryPath = _manifest_metaData_remoteEntry.path, remoteEntryName = _manifest_metaData_remoteEntry.name, remoteEntryType = _manifest_metaData_remoteEntry.type, remoteTypes = _manifest_metaData1.types, buildVersion = _manifest_metaData1.buildInfo.buildVersion, globalName = _manifest_metaData1.globalName;
var exposes = manifest.exposes;
var basicRemoteSnapshot = {
version: version ? version : "",
buildVersion: buildVersion,
globalName: globalName,
remoteEntry: simpleJoinRemoteEntry(remoteEntryPath, remoteEntryName),
remoteEntryType: remoteEntryType,
remoteTypes: simpleJoinRemoteEntry(remoteTypes.path, remoteTypes.name),
remotesInfo: remotesInfo,
shared: manifest === null || manifest === void 0 ? void 0 : manifest.shared.map(function(item) {
return {
assets: item.assets,
sharedName: item.name
};
}),
modules: exposes === null || exposes === void 0 ? void 0 : exposes.map(function(expose) {
return {
moduleName: expose.name,
modulePath: expose.path,
assets: expose.assets
};
})
};
if ((_manifest_metaData = manifest.metaData) === null || _manifest_metaData === void 0 ? void 0 : _manifest_metaData.prefetchEntry) {
var _manifest_metaData_prefetchEntry = manifest.metaData.prefetchEntry, path = _manifest_metaData_prefetchEntry.path, name = _manifest_metaData_prefetchEntry.name, type = _manifest_metaData_prefetchEntry.type;
basicRemoteSnapshot = _object_spread_props(_object_spread({}, basicRemoteSnapshot), {
prefetchEntry: simpleJoinRemoteEntry(path, name),
prefetchEntryType: type
});
}
if ("publicPath" in manifest.metaData) {
remoteSnapshot = _object_spread_props(_object_spread({}, basicRemoteSnapshot), {
publicPath: getPublicPath()
});
} else {
remoteSnapshot = _object_spread_props(_object_spread({}, basicRemoteSnapshot), {
getPublicPath: getPublicPath()
});
}
return remoteSnapshot;
}
function isManifestProvider(moduleInfo) {
if ("remoteEntry" in moduleInfo && moduleInfo.remoteEntry.endsWith(MANIFEST_EXT)) {
return true;
} else {
return false;
}
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _async_to_generator(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _instanceof(left, right) {
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
return !!right[Symbol.hasInstance](left);
} else {
return left instanceof right;
}
}
function _ts_generator(thisArg, body) {
var f, y, t, g, _ = {
label: 0,
sent: function() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
};
return g = {
next: verb(0),
"throw": verb(1),
"return": verb(2)
}, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
return this;
}), g;
function verb(n) {
return function(v) {
return step([
n,
v
]);
};
}
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while(_)try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [
op[0] & 2,
t.value
];
switch(op[0]){
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return {
value: op[1],
done: false
};
case 5:
_.label++;
y = op[1];
op = [
0
];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2]) _.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [
6,
e
];
y = 0;
} finally{
f = t = 0;
}
if (op[0] & 5) throw op[1];
return {
value: op[0] ? op[1] : void 0,
done: true
};
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function safeWrapper(callback, disableWarn) {
return _safeWrapper.apply(this, arguments);
}
function _safeWrapper() {
_safeWrapper = _async_to_generator(function(callback, disableWarn) {
var res, e;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
_state.trys.push([
0,
2,
,
3
]);
return [
4,
callback()
];
case 1:
res = _state.sent();
return [
2,
res
];
case 2:
e = _state.sent();
!disableWarn && warn(e);
return [
2
];
case 3:
return [
2
];
}
});
});
return _safeWrapper.apply(this, arguments);
}
function isStaticResourcesEqual(url1, url2) {
var REG_EXP = /^(https?:)?\/\//i;
// Transform url1 and url2 into relative paths
var relativeUrl1 = url1.replace(REG_EXP, "").replace(/\/$/, "");
var relativeUrl2 = url2.replace(REG_EXP, "").replace(/\/$/, "");
// Check if the relative paths are identical
return relativeUrl1 === relativeUrl2;
}
function createScript(url, cb, attrs, createScriptHook) {
// Retrieve the existing script element by its src attribute
var script = null;
var needAttach = true;
var scripts = document.getElementsByTagName("script");
for(var i = 0; i < scripts.length; i++){
var s = scripts[i];
var scriptSrc = s.getAttribute("src");
if (scriptSrc && isStaticResourcesEqual(scriptSrc, url)) {
script = s;
needAttach = false;
break;
}
}
if (!script) {
script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
if (createScriptHook) {
var createScriptRes = createScriptHook(url);
if (_instanceof(createScriptRes, HTMLScriptElement)) {
script = createScriptRes;
}
}
}
if (attrs) {
Object.keys(attrs).forEach(function(name) {
if (script) {
if (name === "async" || name === "defer") {
script[name] = attrs[name];
} else {
script.setAttribute(name, attrs[name]);
}
}
});
}
var onScriptComplete = function(prev, // eslint-disable-next-line @typescript-eslint/no-explicit-any
event) {
// Prevent memory leaks in IE.
if (script) {
script.onerror = null;
script.onload = null;
safeWrapper(function() {
(script === null || script === void 0 ? void 0 : script.parentNode) && script.parentNode.removeChild(script);
});
if (prev) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var res = prev(event);
cb();
return res;
}
}
cb();
};
script.onerror = onScriptComplete.bind(null, script.onerror);
script.onload = onScriptComplete.bind(null, script.onload);
return {
script: script,
needAttach: needAttach
};
}
function loadScript(url, info) {
var attrs = info.attrs, createScriptHook = info.createScriptHook;
return new Promise(function(resolve, _reject) {
var _createScript = createScript(url, resolve, attrs, createScriptHook), script = _createScript.script, needAttach = _createScript.needAttach;
needAttach && document.getElementsByTagName("head")[0].appendChild(script);
});
}
export { BROWSER_LOG_KEY, BROWSER_LOG_VALUE, EncodedNameTransformMap, FederationModuleManifest, Logger, MANIFEST_EXT, NameTransformMap, NameTransformSymbol, SEPARATOR, assert, composeKeyWithSeparator, createScript, decodeName, encodeName, error, generateExposeFilename, generateShareFilename, generateSnapshotFromManifest, getProcessEnv, getResourceUrl, isBrowserEnv, isDebugMode, isManifestProvider, isStaticResourcesEqual, loadScript, logger, parseEntry, safeWrapper, warn };
export * from "./src/normalize-webpack-path";
exports._default = require('./normalize-webpack-path.cjs.js').default;
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var path = require('path');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
function getWebpackPath(compiler) {
try {
// @ts-ignore just throw err
compiler.webpack();
return "";
} catch (err) {
var _err_stack;
var trace = ((_err_stack = err.stack) === null || _err_stack === void 0 ? void 0 : _err_stack.split("\n")) || [];
var webpackErrLocation = trace.find(function(item) {
return item.includes("at webpack");
}) || "";
var webpackLocationWithDetail = webpackErrLocation.replace(/[^\(\)]+/, "").slice(1, -1);
var webpackPath = webpackLocationWithDetail.split(":").slice(0, -2)[0];
return require.resolve("webpack", {
paths: [
webpackPath
]
});
}
}
var normalizeWebpackPath = function(fullPath) {
if (fullPath === "webpack") {
return process.env["FEDERATION_WEBPACK_PATH"] || fullPath;
}
if (process.env["FEDERATION_WEBPACK_PATH"]) {
return path__default["default"].resolve(process.env["FEDERATION_WEBPACK_PATH"], fullPath.replace("webpack", "../../"));
}
return fullPath;
};
exports.getWebpackPath = getWebpackPath;
exports.normalizeWebpackPath = normalizeWebpackPath;
export * from './normalize-webpack-path.cjs.js';
export { _default as default } from './normalize-webpack-path.cjs.default.js';
import path from 'path';
function getWebpackPath(compiler) {
try {
// @ts-ignore just throw err
compiler.webpack();
return "";
} catch (err) {
var _err_stack;
var trace = ((_err_stack = err.stack) === null || _err_stack === void 0 ? void 0 : _err_stack.split("\n")) || [];
var webpackErrLocation = trace.find(function(item) {
return item.includes("at webpack");
}) || "";
var webpackLocationWithDetail = webpackErrLocation.replace(/[^\(\)]+/, "").slice(1, -1);
var webpackPath = webpackLocationWithDetail.split(":").slice(0, -2)[0];
return require.resolve("webpack", {
paths: [
webpackPath
]
});
}
}
var normalizeWebpackPath = function(fullPath) {
if (fullPath === "webpack") {
return process.env["FEDERATION_WEBPACK_PATH"] || fullPath;
}
if (process.env["FEDERATION_WEBPACK_PATH"]) {
return path.resolve(process.env["FEDERATION_WEBPACK_PATH"], fullPath.replace("webpack", "../../"));
}
return fullPath;
};
export { getWebpackPath, normalizeWebpackPath };
export declare const FederationModuleManifest = "federation-manifest.json";
export declare const MANIFEST_EXT = ".json";
export declare const BROWSER_LOG_KEY = "FEDERATION_DEBUG";
export declare const BROWSER_LOG_VALUE = "1";
export declare const NameTransformSymbol: {
AT: string;
HYPHEN: string;
SLASH: string;
};
export declare const NameTransformMap: {
[x: string]: string;
};
export declare const EncodedNameTransformMap: {
[x: string]: string;
};
export declare const SEPARATOR = ":";
export declare function safeWrapper<T extends (...args: Array<any>) => any>(callback: T, disableWarn?: boolean): Promise<ReturnType<T> | undefined>;
export declare function isStaticResourcesEqual(url1: string, url2: string): boolean;
export declare function createScript(url: string, cb: (value: void | PromiseLike<void>) => void, attrs?: Record<string, any>, createScriptHook?: (url: string) => HTMLScriptElement | void): {
script: HTMLScriptElement;
needAttach: boolean;
};
export declare function loadScript(url: string, info: {
attrs?: Record<string, any>;
createScriptHook?: (url: string) => HTMLScriptElement | void;
}): Promise<void>;
declare global {
var FEDERATION_DEBUG: string | undefined;
}
declare function isBrowserEnv(): boolean;
declare function isDebugMode(): boolean;
declare const getProcessEnv: () => Record<string, string | undefined>;
export { isBrowserEnv, isDebugMode, getProcessEnv };
import { Manifest, ProviderModuleInfo, ModuleInfo, ManifestProvider } from './types';
interface IOptions {
remotes?: Record<string, string>;
overrides?: Record<string, string>;
version?: string;
}
export declare const simpleJoinRemoteEntry: (rPath: string, rName: string) => string;
export declare function generateSnapshotFromManifest(manifest: Manifest, options?: IOptions): ProviderModuleInfo;
export declare function isManifestProvider(moduleInfo: ModuleInfo | ManifestProvider): moduleInfo is ManifestProvider;
export {};
export * from './constant';
export * from './types';
export * from './utils';
export { generateSnapshotFromManifest, isManifestProvider, } from './generateSnapshotFromManifest';
export * from './logger';
export * from './env';
export * from './dom';
declare class Logger {
enable: boolean;
identifier: string;
constructor(identifier?: string);
info(msg: string, info?: any): void;
logOriginalInfo(...args: unknown[]): void;
}
export { Logger };
import type webpack from 'webpack';
export declare function getWebpackPath(compiler: webpack.Compiler): string;
export declare const normalizeWebpackPath: (fullPath: string) => string;
export interface RemoteWithEntry {
name: string;
entry: string;
}
export interface RemoteWithVersion {
name: string;
version: string;
}
export type RemoteEntryInfo = RemoteWithEntry | RemoteWithVersion;
export type Module = any;
export * from './common';
export * from './manifest';
export * from './stats';
export * from './snapshot';
import { StatsMetaData, StatsAssets, StatsExpose, BasicStatsMetaData } from './stats';
import { RemoteWithEntry, RemoteWithVersion } from './common';
export interface ManifestShared {
id: string;
name: string;
version: string;
singleton: boolean;
requiredVersion: string;
hash: string;
assets: StatsAssets;
}
export interface ManifestRemoteCommonInfo {
federationContainerName: string;
moduleName: string;
alias: string;
}
export type ManifestRemote<T = ManifestRemoteCommonInfo> = (Omit<RemoteWithEntry, 'name'> & T) | (Omit<RemoteWithVersion, 'name'> & T);
export type ManifestExpose = Pick<StatsExpose, 'assets' | 'id' | 'name' | 'path'>;
export interface Manifest<T = BasicStatsMetaData, K = ManifestRemoteCommonInfo> {
id: string;
name: string;
metaData: StatsMetaData<T>;
shared: ManifestShared[];
remotes: ManifestRemote<K>[];
exposes: ManifestExpose[];
}
import { RemoteEntryType, StatsAssets } from './stats';
interface BasicModuleInfo {
dev?: {
version?: string;
remotes?: {
[nameWithType: string]: string;
};
};
version: string;
buildVersion: string;
remoteTypes: string;
remotesInfo: Record<string, {
matchedVersion: string;
}>;
shared: Array<{
sharedName: string;
assets: StatsAssets;
}>;
}
export interface BasicProviderModuleInfo extends BasicModuleInfo {
remoteEntry: string;
remoteEntryType: RemoteEntryType;
remoteManifest?: string;
globalName: string;
modules: Array<{
moduleName: string;
modulePath?: string;
assets: StatsAssets;
}>;
prefetchEntry?: string;
prefetchEntryType?: RemoteEntryType;
}
interface BasicProviderModuleInfoWithPublicPath extends BasicProviderModuleInfo {
publicPath: string;
}
interface BasicProviderModuleInfoWithGetPublicPath extends BasicProviderModuleInfo {
getPublicPath: string;
}
export interface ManifestProvider {
remoteEntry: string;
version?: string;
}
export interface PureEntryProvider extends ManifestProvider {
globalName: string;
}
interface BasicConsumerModuleInfo extends BasicModuleInfo {
consumerList: Array<string>;
}
export interface ConsumerModuleInfoWithPublicPath extends BasicConsumerModuleInfo, BasicProviderModuleInfo {
publicPath: string;
}
interface ConsumerModuleInfoWithGetPublicPath extends BasicConsumerModuleInfo, BasicProviderModuleInfo {
getPublicPath: string;
}
export type PureConsumerModuleInfo = Omit<BasicConsumerModuleInfo, 'remoteTypes'>;
export type ConsumerModuleInfo = ConsumerModuleInfoWithPublicPath | ConsumerModuleInfoWithGetPublicPath;
export type ProviderModuleInfo = BasicProviderModuleInfoWithPublicPath | BasicProviderModuleInfoWithGetPublicPath;
export type ModuleInfo = ConsumerModuleInfo | PureConsumerModuleInfo | ProviderModuleInfo;
export type GlobalModuleInfo = {
[key: string]: ModuleInfo | ManifestProvider | PureEntryProvider | undefined;
};
export {};
import type { RemoteWithEntry, RemoteWithVersion } from './common';
export type RemoteEntryType = 'esm' | 'global';
interface ResourceInfo {
path: string;
name: string;
type: RemoteEntryType;
}
export interface StatsBuildInfo {
buildVersion: string;
buildName: string;
}
export interface BasicStatsMetaData {
name: string;
globalName: string;
buildInfo: StatsBuildInfo;
remoteEntry: ResourceInfo;
prefetchEntry: ResourceInfo;
types: Omit<ResourceInfo, 'type'>;
}
type StatsMetaDataWithGetPublicPath<T = BasicStatsMetaData> = T & {
getPublicPath: string;
};
type StatsMetaDataWithPublicPath<T = BasicStatsMetaData> = T & {
publicPath: string;
};
export type StatsMetaData<T = BasicStatsMetaData> = StatsMetaDataWithGetPublicPath<T> | StatsMetaDataWithPublicPath<T>;
export interface StatsAssets {
js: StatsAssetsInfo;
css: StatsAssetsInfo;
}
interface StatsAssetsInfo {
sync: string[];
async: string[];
}
export interface StatsShared {
id: string;
name: string;
version: string;
singleton: boolean;
requiredVersion: string;
hash: string;
assets: StatsAssets;
deps: string[];
usedIn: string[];
}
export interface StatsRemoteVal {
moduleName: string;
federationContainerName: string;
consumingFederationContainerName: string;
alias: string;
usedIn: string[];
}
export type StatsRemoteWithEntry<T = StatsRemoteVal> = T & Omit<RemoteWithEntry, 'name'>;
export type StatsRemoteWithVersion<T = StatsRemoteVal> = T & Omit<RemoteWithVersion, 'name'>;
export type StatsRemote<T = StatsRemoteVal> = StatsRemoteWithEntry<T> | StatsRemoteWithVersion<T>;
export interface StatsModuleInfo {
name: string;
file: string;
}
export interface ManifestModuleInfos {
[exposeModuleName: string]: StatsModuleInfo;
}
export interface StatsExpose {
id: string;
name: string;
path?: string;
file: string;
requires: string[];
assets: StatsAssets;
}
export interface Stats<T = BasicStatsMetaData, K = StatsRemoteVal> {
id: string;
name: string;
metaData: StatsMetaData<T>;
shared: StatsShared[];
remotes: StatsRemote<K>[];
exposes: StatsExpose[];
}
export {};
import { RemoteEntryInfo, ModuleInfo } from './types';
import { Logger } from './logger';
declare const parseEntry: (str: string, devVerOrUrl?: string) => RemoteEntryInfo;
declare global {
var FEDERATION_DEBUG: string | undefined;
}
declare const logger: Logger;
declare const composeKeyWithSeparator: (...args: (string | undefined)[]) => string;
declare const encodeName: (name: string, prefix?: string, withExt?: boolean) => string;
declare const decodeName: (name: string, prefix?: string, withExt?: boolean) => string;
declare const generateExposeFilename: (exposeName: string, withExt: boolean) => string;
declare const generateShareFilename: (pkgName: string, withExt: boolean) => string;
declare const getResourceUrl: (module: ModuleInfo, sourceUrl: string) => string;
declare const assert: (condition: any, msg: string) => asserts condition;
declare const error: (msg: string | Error | unknown) => never;
declare const warn: (msg: Parameters<typeof console.warn>[0]) => void;
export { parseEntry, logger, decodeName, encodeName, composeKeyWithSeparator, generateExposeFilename, generateShareFilename, getResourceUrl, assert, error, warn, };