@module-federation/vite 1.16.6 → 1.16.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,307 +0,0 @@
1
- import { existsSync, readFileSync, readdirSync } from "fs";
2
- import { createRequire } from "module";
3
- import * as path$1 from "node:path";
4
- import { fileURLToPath, pathToFileURL } from "url";
5
- //#region src/utils/buildPaths.ts
6
- /**
7
- * Rebase an import path for a bootstrap file that moved from root into `dir`.
8
- *
9
- * When entryFileNames places entries in a subdirectory (e.g. `static/js/`),
10
- * the bootstrap file moves there too. Paths that resolved from the HTML root
11
- * must resolve from the new directory instead.
12
- *
13
- * Cases: `/static/js/hostInit.js` → `./hostInit.js` (strip dir prefix)
14
- * `./src/main.tsx` → `../../src/main.tsx` (climb back up for each dir level)
15
- * `https://cdn.example.com` → unchanged (absolute URL)
16
- */
17
- function rebaseImport(importSrc, dir) {
18
- if (!dir) return importSrc;
19
- if (isAbsoluteUrl(importSrc)) return importSrc;
20
- const normalizedDir = dir.replace(/^\/+|\/+$/g, "");
21
- if (!normalizedDir) return importSrc;
22
- const stripDirPrefix = (src, prefix) => {
23
- if (src === prefix) return "";
24
- if (src.startsWith(prefix + "/")) return src.slice(prefix.length);
25
- };
26
- const absoluteRemainder = stripDirPrefix(importSrc, "/" + normalizedDir);
27
- if (absoluteRemainder !== void 0) {
28
- const remainder = absoluteRemainder.replace(/^\/+/, "");
29
- return remainder ? "./" + remainder : "./";
30
- }
31
- const relativeRemainder = stripDirPrefix(importSrc, normalizedDir);
32
- if (relativeRemainder !== void 0) {
33
- const remainder = relativeRemainder.replace(/^\/+/, "");
34
- return remainder ? "./" + remainder : "./";
35
- }
36
- const upLevels = normalizedDir.split("/").filter(Boolean).length;
37
- const prefix = upLevels > 0 ? "../".repeat(upLevels) : "./";
38
- if (importSrc.startsWith("./")) return prefix + importSrc.slice(2);
39
- if (importSrc.startsWith("/")) return prefix + importSrc.slice(1);
40
- return prefix + importSrc;
41
- }
42
- function normalizePathForImport(path) {
43
- return path.replace(/\\/g, "/");
44
- }
45
- const EXTERNAL_URL_RE = /^(?:[a-z]+:|\/\/)/i;
46
- function isAbsoluteUrl(src) {
47
- if (/^[a-z]:[\\/]/i.test(src)) return false;
48
- return EXTERNAL_URL_RE.test(src);
49
- }
50
- //#endregion
51
- //#region src/utils/logger.ts
52
- const MODULE_FEDERATION_LOG_PREFIX = "[Module Federation]";
53
- function formatModuleFederationMessage(message) {
54
- return `${MODULE_FEDERATION_LOG_PREFIX} ${message}`;
55
- }
56
- function createModuleFederationError(message) {
57
- return new Error(formatModuleFederationMessage(message));
58
- }
59
- function toConsoleArgs(message, rest = []) {
60
- if (typeof message === "string") return [formatModuleFederationMessage(message), ...rest];
61
- if (message === void 0) return [MODULE_FEDERATION_LOG_PREFIX, ...rest];
62
- return [
63
- MODULE_FEDERATION_LOG_PREFIX,
64
- message,
65
- ...rest
66
- ];
67
- }
68
- const moduleFederationConsole = {
69
- log(message, ...rest) {
70
- console.log(...toConsoleArgs(message, rest));
71
- },
72
- warn(message, ...rest) {
73
- console.warn(...toConsoleArgs(message, rest));
74
- },
75
- error(message, ...rest) {
76
- console.error(...toConsoleArgs(message, rest));
77
- }
78
- };
79
- moduleFederationConsole.log;
80
- const mfWarn = moduleFederationConsole.warn;
81
- const mfError = moduleFederationConsole.error;
82
- //#endregion
83
- //#region src/utils/packageUtils.ts
84
- const dependencyPresenceCache = /* @__PURE__ */ new Map();
85
- let packageDetectionCwd;
86
- function getDependencyCacheKey(cwd, dependencyName) {
87
- return `${cwd}:${dependencyName}`;
88
- }
89
- function setPackageDetectionCwd(cwd) {
90
- packageDetectionCwd = cwd;
91
- }
92
- function getPackageDetectionCwd() {
93
- return packageDetectionCwd || process.cwd();
94
- }
95
- function resolveImportPath(specifier) {
96
- const resolved = import.meta.resolve(specifier);
97
- if (!resolved.startsWith("file:")) return resolved;
98
- const filePath = fileURLToPath(resolved);
99
- if (!existsSync(filePath)) {
100
- const error = /* @__PURE__ */ new Error(`Cannot find module '${specifier}'`);
101
- error.code = "MODULE_NOT_FOUND";
102
- throw error;
103
- }
104
- return filePath;
105
- }
106
- const DEFAULT_EXPORT_CONDITIONS = [
107
- "browser",
108
- "import",
109
- "module",
110
- "default",
111
- "require"
112
- ];
113
- function resolveExportsEntry(exportsField, conditions = DEFAULT_EXPORT_CONDITIONS) {
114
- if (typeof exportsField === "string") return exportsField;
115
- if (!exportsField || typeof exportsField !== "object") return void 0;
116
- const record = exportsField;
117
- const rootExport = record["."];
118
- if (rootExport) return resolveExportsEntry(rootExport);
119
- for (const condition of conditions) {
120
- const target = resolveExportsEntry(record[condition], conditions);
121
- if (target) return target;
122
- }
123
- for (const target of Object.values(record)) {
124
- const resolved = resolveExportsEntry(target, conditions);
125
- if (resolved) return resolved;
126
- }
127
- }
128
- function getPackageExportsTarget(pkg, packageName, exportsField) {
129
- if (typeof exportsField === "string") return pkg === packageName ? exportsField : void 0;
130
- if (!exportsField || typeof exportsField !== "object") return void 0;
131
- const record = exportsField;
132
- const subpath = pkg === packageName ? "." : `.${pkg.slice(packageName.length)}`;
133
- if (subpath !== ".") return record[subpath];
134
- return record["."] ?? (!Object.keys(record).some((key) => key.startsWith(".")) ? record : void 0);
135
- }
136
- /**
137
- * Escaping rules:
138
- * Convert using the format __${mapping}__, where _ and $ are not allowed in npm package names but can be used in variable names.
139
- * @ => 1
140
- * / => 2
141
- * - => 3
142
- * . => 4
143
- */
144
- /**
145
- * Encodes a package name into a valid file name.
146
- * @param {string} name - The package name, e.g., "@scope/xx-xx.xx".
147
- * @returns {string} - The encoded file name.
148
- */
149
- function packageNameEncode(name) {
150
- if (typeof name !== "string") throw createModuleFederationError("A string package name is required");
151
- return name.replace(/@/g, "_mf_0_").replace(/\//g, "_mf_1_").replace(/-/g, "_mf_2_").replace(/\./g, "_mf_3_");
152
- }
153
- /**
154
- * Decodes an encoded file name back to the original package name.
155
- * @param {string} encoded - The encoded file name, e.g., "_mf_0_scope_mf_1_xx_mf_2_xx_mf_3_xx".
156
- * @returns {string} - The decoded package name.
157
- */
158
- function packageNameDecode(encoded) {
159
- if (typeof encoded !== "string") throw createModuleFederationError("A string encoded file name is required");
160
- return encoded.replace(/_mf_0_/g, "@").replace(/_mf_1_/g, "/").replace(/_mf_2_/g, "-").replace(/_mf_3_/g, ".");
161
- }
162
- /**
163
- * Removes any subpath from an npm package specifier and returns the package name only.
164
- * @param {string} packageString - The package specifier, e.g., "@scope/pkg/runtime" or "react/jsx-runtime".
165
- * @returns {string} - The base npm package name.
166
- */
167
- function getPackageName(packageString) {
168
- const match = packageString.match(/^(?:@[^/]+\/)?[^/]+/);
169
- return match ? match[0] : packageString;
170
- }
171
- function getPackageNameFromNodeModulePath(source) {
172
- const normalized = source.replace(/\\/g, "/");
173
- const nodeModulesIndex = normalized.lastIndexOf("/node_modules/");
174
- if (nodeModulesIndex < 0) return;
175
- const parts = normalized.slice(nodeModulesIndex + 14).split("/");
176
- if (!parts[0]) return;
177
- if (parts[0].startsWith("@")) return parts[1] ? `${parts[0]}/${parts[1]}` : void 0;
178
- return parts[0];
179
- }
180
- function getSharedCacheKey(pkg, shareItem) {
181
- return shareItem.shareConfig.singleton || !shareItem.version ? pkg : `${pkg}@${shareItem.version}`;
182
- }
183
- function getInstalledPackageJson(pkg, opts) {
184
- const cwd = opts?.cwd || getPackageDetectionCwd();
185
- const packageName = opts?.packageName || getPackageName(pkg);
186
- const tryReadPackageJson = (packageJsonPath) => {
187
- if (!existsSync(packageJsonPath)) return void 0;
188
- try {
189
- return {
190
- path: packageJsonPath,
191
- dir: path$1.dirname(packageJsonPath),
192
- packageJson: JSON.parse(readFileSync(packageJsonPath, "utf-8"))
193
- };
194
- } catch {
195
- return;
196
- }
197
- };
198
- const findPackageInPnpmStore = (startDir) => {
199
- let currentDir = startDir;
200
- const rootDir = path$1.parse(currentDir).root;
201
- while (true) {
202
- const pnpmStoreDir = path$1.join(currentDir, "node_modules", ".pnpm");
203
- if (existsSync(pnpmStoreDir)) try {
204
- for (const entry of readdirSync(pnpmStoreDir, { withFileTypes: true })) {
205
- if (!entry.isDirectory()) continue;
206
- const candidate = tryReadPackageJson(path$1.join(pnpmStoreDir, entry.name, "node_modules", packageName, "package.json"));
207
- if (candidate?.packageJson.name === packageName) return candidate;
208
- }
209
- } catch {}
210
- if (currentDir === rootDir) break;
211
- currentDir = path$1.dirname(currentDir);
212
- }
213
- };
214
- try {
215
- const projectRequire = createRequire(pathToFileURL(path$1.join(cwd, "package.json")));
216
- let resolvedPath;
217
- if (opts?.fromResolvedEntry) resolvedPath = opts.fromResolvedEntry;
218
- else try {
219
- resolvedPath = projectRequire.resolve(pkg);
220
- } catch {
221
- resolvedPath = projectRequire.resolve(packageName);
222
- }
223
- let currentDir = path$1.dirname(resolvedPath);
224
- const rootDir = path$1.parse(currentDir).root;
225
- while (true) {
226
- const packageJsonPath = path$1.join(currentDir, "package.json");
227
- if (existsSync(packageJsonPath)) {
228
- const packageJsonContent = readFileSync(packageJsonPath, "utf-8");
229
- try {
230
- const packageJson = JSON.parse(packageJsonContent);
231
- if (packageJson.name === packageName) return {
232
- path: packageJsonPath,
233
- dir: currentDir,
234
- packageJson
235
- };
236
- } catch (error) {
237
- if (!(error instanceof SyntaxError)) throw error;
238
- }
239
- }
240
- if (currentDir === rootDir) break;
241
- currentDir = path$1.dirname(currentDir);
242
- }
243
- } catch {
244
- let currentDir = cwd;
245
- const rootDir = path$1.parse(currentDir).root;
246
- while (true) {
247
- const directCandidate = tryReadPackageJson(path$1.join(currentDir, "node_modules", packageName, "package.json"));
248
- if (directCandidate?.packageJson.name === packageName) return directCandidate;
249
- if (currentDir === rootDir) break;
250
- currentDir = path$1.dirname(currentDir);
251
- }
252
- return findPackageInPnpmStore(cwd);
253
- }
254
- }
255
- function getInstalledPackageEntry(pkg, opts) {
256
- const installed = getInstalledPackageJson(pkg, opts);
257
- if (!installed) return void 0;
258
- const cwd = opts?.cwd || getPackageDetectionCwd();
259
- const packageName = opts?.packageName || getPackageName(pkg);
260
- if (pkg !== packageName && opts?.resolveSubpathWithRequire !== false) try {
261
- return createRequire(pathToFileURL(path$1.join(cwd, "package.json"))).resolve(pkg);
262
- } catch {}
263
- const packageJson = installed.packageJson;
264
- const explicitEntry = resolveExportsEntry(getPackageExportsTarget(pkg, packageName, packageJson.exports), opts?.conditions) || (typeof packageJson.module === "string" ? packageJson.module : void 0) || (typeof packageJson.main === "string" ? packageJson.main : void 0) || "index.js";
265
- return path$1.join(installed.dir, explicitEntry);
266
- }
267
- /**
268
- * Detect whether the current runtime is Vite 8+ by checking for a Vite version flag
269
- * on the plugin hook context, with Rolldown metadata kept as a compatibility fallback.
270
- */
271
- function getIsRolldown(ctx) {
272
- const viteVersion = ctx?.meta?.viteVersion;
273
- const viteMajor = Number(String(viteVersion ?? "").split(".")[0]);
274
- return Number.isFinite(viteMajor) && viteMajor >= 8 || !!ctx?.meta?.rolldownVersion;
275
- }
276
- /** Walk up from Vite `config.root` (Nuxt may point at `.nuxt` cache dirs). */
277
- function isNuxtProjectRoot(root) {
278
- let dir = root;
279
- for (let i = 0; i < 8; i++) {
280
- if (hasPackageDependency("nuxt", dir) || hasPackageDependency("nuxt-nightly", dir)) return true;
281
- const parent = path$1.dirname(dir);
282
- if (parent === dir) break;
283
- dir = parent;
284
- }
285
- return false;
286
- }
287
- function hasPackageDependency(dependencyName, cwd = packageDetectionCwd || process.cwd()) {
288
- const cacheKey = getDependencyCacheKey(cwd, dependencyName);
289
- const cached = dependencyPresenceCache.get(cacheKey);
290
- if (cached !== void 0) return cached;
291
- try {
292
- const packageJson = JSON.parse(readFileSync(path$1.join(cwd, "package.json"), "utf8"));
293
- const hasDependency = [
294
- packageJson.dependencies,
295
- packageJson.devDependencies,
296
- packageJson.peerDependencies,
297
- packageJson.optionalDependencies
298
- ].some((deps) => !!deps?.[dependencyName]);
299
- dependencyPresenceCache.set(cacheKey, hasDependency);
300
- return hasDependency;
301
- } catch {
302
- dependencyPresenceCache.set(cacheKey, false);
303
- return false;
304
- }
305
- }
306
- //#endregion
307
- export { normalizePathForImport as _, getPackageName as a, hasPackageDependency as c, packageNameEncode as d, resolveImportPath as f, mfWarn as g, mfError as h, getPackageDetectionCwd as i, isNuxtProjectRoot as l, createModuleFederationError as m, getInstalledPackageJson as n, getPackageNameFromNodeModulePath as o, setPackageDetectionCwd as p, getIsRolldown as r, getSharedCacheKey as s, getInstalledPackageEntry as t, packageNameDecode as u, rebaseImport as v };
@@ -1,309 +0,0 @@
1
- import { _ as normalizePathForImport, c as hasPackageDependency, f as resolveImportPath, h as mfError, m as createModuleFederationError } from "./packageUtils-CYnJFfPP.js";
2
- import fs from "fs";
3
- import * as path$1 from "node:path";
4
- import { normalizeOptions } from "@module-federation/sdk";
5
- import { consumeTypesAPI, generateTypesAPI, isTSProject, normalizeConsumeTypesOptions, normalizeDtsOptions, normalizeGenerateTypesOptions } from "@module-federation/dts-plugin";
6
- import { rpc } from "@module-federation/dts-plugin/core";
7
- //#region src/plugins/pluginDts.ts
8
- const DEFAULT_DEV_OPTIONS = {
9
- disableLiveReload: true,
10
- disableHotTypesReload: false,
11
- disableDynamicRemoteTypeHints: false
12
- };
13
- const DYNAMIC_HINTS_PLUGIN = "@module-federation/dts-plugin/dynamic-remote-type-hints-plugin";
14
- const getIPv4 = () => process.env["FEDERATION_IPV4"] || "127.0.0.1";
15
- const DEV_TYPES_FOLDER = ".dev-server";
16
- const DEFAULT_PUBLIC_TYPES_FOLDER = "@mf-types";
17
- const forkDevWorkerPath = resolveImportPath("@module-federation/dts-plugin/dist/fork-dev-worker.js");
18
- var DevWorker = class {
19
- worker = rpc.createRpcWorker(forkDevWorkerPath, {}, void 0, false);
20
- constructor(options) {
21
- this.worker.connect(options);
22
- }
23
- update() {
24
- this.worker.process?.send?.({
25
- type: rpc.RpcGMCallTypes.CALL,
26
- id: this.worker.id,
27
- args: [void 0, "update"]
28
- });
29
- }
30
- exit() {
31
- this.worker.terminate();
32
- }
33
- };
34
- const normalizeDevOptions = (dev) => {
35
- if (dev === false) return false;
36
- if (dev === true || typeof dev === "undefined") return { ...DEFAULT_DEV_OPTIONS };
37
- return {
38
- ...DEFAULT_DEV_OPTIONS,
39
- ...dev
40
- };
41
- };
42
- const buildDtsModuleFederationConfig = (options) => {
43
- const exposes = {};
44
- Object.entries(options.exposes).forEach(([key, value]) => {
45
- if (value.import) exposes[key] = value.import;
46
- });
47
- const remotes = {};
48
- Object.entries(options.remotes).forEach(([key, remote]) => {
49
- if (!remote.entry) return;
50
- remotes[key] = `${remote.entryGlobalName?.startsWith("http") || remote.entryGlobalName?.includes(".json") ? remote.name || key : remote.entryGlobalName || remote.name || key}@${remote.entry}`;
51
- });
52
- return {
53
- ...options,
54
- exposes,
55
- remotes
56
- };
57
- };
58
- const resolveOutputDir = (config) => {
59
- const { outDir } = config.build;
60
- if (path$1.isAbsolute(outDir)) return normalizePathForImport(path$1.relative(config.root, outDir));
61
- return outDir;
62
- };
63
- const ensureRuntimePlugin = (options, pluginId) => {
64
- if (!options.runtimePlugins.some((plugin) => {
65
- if (typeof plugin === "string") return plugin === pluginId;
66
- return plugin[0] === pluginId;
67
- })) options.runtimePlugins.push(pluginId);
68
- };
69
- const getExposeImportPaths = (options) => {
70
- return Object.values(options.exposes).map((value) => {
71
- return value.import;
72
- }).filter((value) => Boolean(value));
73
- };
74
- const usesVueSfcExposes = (options) => {
75
- return getExposeImportPaths(options).some((value) => value.endsWith(".vue"));
76
- };
77
- const resolveDtsPluginOptions = (dts, options, context) => {
78
- if (dts === false) return false;
79
- const inferredGenerateTypesDefaults = { generateAPITypes: true };
80
- if (usesVueSfcExposes(options) && hasPackageDependency("vue-tsc", context)) inferredGenerateTypesDefaults.compilerInstance = "vue-tsc";
81
- if (dts === true || typeof dts === "undefined") return { generateTypes: inferredGenerateTypesDefaults };
82
- const generateTypes = dts.generateTypes;
83
- return {
84
- ...dts,
85
- generateTypes: generateTypes === false ? false : {
86
- ...inferredGenerateTypesDefaults,
87
- ...generateTypes === true || typeof generateTypes === "undefined" ? {} : generateTypes
88
- }
89
- };
90
- };
91
- const getBasePath = (base) => {
92
- if (base.startsWith("http://") || base.startsWith("https://")) return new URL(base).pathname.replace(/\/$/, "") || "/";
93
- return base.replace(/\/$/, "") || "/";
94
- };
95
- const joinBaseAndAsset = (base, assetFileName) => {
96
- const basePath = getBasePath(base);
97
- return `${basePath === "/" ? "" : basePath}/${assetFileName}`.replace(/\/{2,}/g, "/");
98
- };
99
- const getDevDtsAssetPaths = (options) => {
100
- const { outputDir, publicTypesFolder, root, base } = options;
101
- return {
102
- apiFilePath: path$1.resolve(root, outputDir, `${DEV_TYPES_FOLDER}.d.ts`),
103
- apiRequestPath: joinBaseAndAsset(base, `${publicTypesFolder}.d.ts`),
104
- zipFilePath: path$1.resolve(root, outputDir, `${DEV_TYPES_FOLDER}.zip`),
105
- zipRequestPath: joinBaseAndAsset(base, `${publicTypesFolder}.zip`)
106
- };
107
- };
108
- const createDevDtsAssetMiddleware = (assetPaths) => {
109
- return (req, res, next) => {
110
- const requestPath = req.url?.split("?")[0];
111
- const isZipRequest = requestPath === assetPaths.zipRequestPath;
112
- const isApiRequest = requestPath === assetPaths.apiRequestPath;
113
- if (!isZipRequest && !isApiRequest) {
114
- next();
115
- return;
116
- }
117
- const filePath = isZipRequest ? assetPaths.zipFilePath : assetPaths.apiFilePath;
118
- if (!fs.existsSync(filePath)) {
119
- res.statusCode = 404;
120
- res.end();
121
- return;
122
- }
123
- res.statusCode = 200;
124
- res.setHeader("Content-Type", isZipRequest ? "application/x-gzip" : "application/typescript");
125
- if (req.method === "HEAD") {
126
- res.end();
127
- return;
128
- }
129
- const stream = fs.createReadStream(filePath);
130
- stream.on("error", () => {
131
- if (!res.headersSent) res.statusCode = 500;
132
- res.end();
133
- });
134
- res.on("close", () => {
135
- stream.destroy();
136
- });
137
- stream.pipe(res);
138
- };
139
- };
140
- const normalizeDevDtsOptions = (dts, context) => {
141
- return normalizeOptions(isTSProject(dts, context), {
142
- generateTypes: { compileInChildProcess: true },
143
- consumeTypes: { consumeAPITypes: true },
144
- extraOptions: {},
145
- displayErrorInTerminal: typeof dts === "object" && dts ? dts.displayErrorInTerminal : void 0
146
- }, "mfOptions.dts")(dts);
147
- };
148
- const logDtsError = (error, dtsOptions) => {
149
- if (dtsOptions === false) return;
150
- if (typeof dtsOptions === "object" && dtsOptions && dtsOptions.displayErrorInTerminal === false) return;
151
- mfError(error);
152
- };
153
- function pluginDts(options) {
154
- if (options.dts === false) return [];
155
- const baseDtsModuleFederationConfig = buildDtsModuleFederationConfig(options);
156
- const getDtsModuleFederationConfig = (context) => ({
157
- ...baseDtsModuleFederationConfig,
158
- dts: resolveDtsPluginOptions(options.dts, options, context)
159
- });
160
- let resolvedConfig;
161
- let devWorker;
162
- let normalizedDevOptions;
163
- let hasGeneratedBundle = false;
164
- return [{
165
- name: "module-federation-dts-dev",
166
- apply: "serve",
167
- config(config) {
168
- normalizedDevOptions = normalizeDevOptions(options.dev);
169
- if (!normalizedDevOptions) return;
170
- if (normalizedDevOptions.disableDynamicRemoteTypeHints) return;
171
- ensureRuntimePlugin(options, DYNAMIC_HINTS_PLUGIN);
172
- const define = config.define ? { ...config.define } : {};
173
- if (!("FEDERATION_IPV4" in define)) define.FEDERATION_IPV4 = JSON.stringify(getIPv4());
174
- config.define = define;
175
- },
176
- configResolved(config) {
177
- resolvedConfig = config;
178
- },
179
- configureServer(server) {
180
- if (!normalizedDevOptions || !resolvedConfig) return;
181
- const devOptions = normalizedDevOptions;
182
- if (devOptions.disableDynamicRemoteTypeHints && devOptions.disableHotTypesReload && devOptions.disableLiveReload) return;
183
- if (!options.name) throw createModuleFederationError("name is required if you want to enable dev server!");
184
- const outputDir = resolveOutputDir(resolvedConfig);
185
- const dtsModuleFederationConfig = getDtsModuleFederationConfig(resolvedConfig.root);
186
- const normalizedDtsOptions = normalizeDevDtsOptions(dtsModuleFederationConfig.dts, resolvedConfig.root);
187
- if (typeof normalizedDtsOptions !== "object") return;
188
- const normalizedGenerateTypes = normalizeOptions(Boolean(normalizedDtsOptions), { compileInChildProcess: true }, "mfOptions.dts.generateTypes")(normalizedDtsOptions.generateTypes);
189
- const remote = normalizedGenerateTypes === false ? void 0 : {
190
- implementation: normalizedDtsOptions.implementation,
191
- context: resolvedConfig.root,
192
- outputDir,
193
- moduleFederationConfig: { ...dtsModuleFederationConfig },
194
- hostRemoteTypesFolder: normalizedGenerateTypes.typesFolder || DEFAULT_PUBLIC_TYPES_FOLDER,
195
- ...normalizedGenerateTypes,
196
- typesFolder: DEV_TYPES_FOLDER
197
- };
198
- if (remote) server.middlewares.use(createDevDtsAssetMiddleware(getDevDtsAssetPaths({
199
- outputDir,
200
- publicTypesFolder: remote.hostRemoteTypesFolder || DEFAULT_PUBLIC_TYPES_FOLDER,
201
- root: resolvedConfig.root,
202
- base: resolvedConfig.base
203
- })));
204
- if (remote && !remote.tsConfigPath && normalizedDtsOptions.tsConfigPath) remote.tsConfigPath = normalizedDtsOptions.tsConfigPath;
205
- const normalizedConsumeTypes = normalizeOptions(Boolean(normalizedDtsOptions), { consumeAPITypes: true }, "mfOptions.dts.consumeTypes")(normalizedDtsOptions.consumeTypes);
206
- const host = normalizedConsumeTypes === false ? void 0 : {
207
- implementation: normalizedDtsOptions.implementation,
208
- context: resolvedConfig.root,
209
- moduleFederationConfig: dtsModuleFederationConfig,
210
- typesFolder: normalizedConsumeTypes.typesFolder || "@mf-types",
211
- abortOnError: false,
212
- ...normalizedConsumeTypes
213
- };
214
- const extraOptions = normalizedDtsOptions.extraOptions || {};
215
- if (!remote && !host && devOptions.disableLiveReload) return;
216
- const startDevWorker = async () => {
217
- let remoteTypeUrls;
218
- if (host) remoteTypeUrls = await new Promise((resolve) => {
219
- consumeTypesAPI({
220
- host,
221
- extraOptions,
222
- displayErrorInTerminal: normalizedDtsOptions.displayErrorInTerminal
223
- }, resolve);
224
- });
225
- devWorker = new DevWorker({
226
- name: options.name,
227
- remote,
228
- host: host ? {
229
- ...host,
230
- remoteTypeUrls
231
- } : void 0,
232
- extraOptions,
233
- disableLiveReload: devOptions.disableLiveReload,
234
- disableHotTypesReload: devOptions.disableHotTypesReload
235
- });
236
- const update = () => devWorker?.update();
237
- server.watcher.on("change", update);
238
- server.watcher.on("add", update);
239
- server.watcher.on("unlink", update);
240
- server.httpServer?.once("close", () => {
241
- devWorker?.exit();
242
- server.watcher.off("change", update);
243
- server.watcher.off("add", update);
244
- server.watcher.off("unlink", update);
245
- });
246
- };
247
- startDevWorker().catch((error) => {
248
- logDtsError(error, normalizedDtsOptions);
249
- });
250
- }
251
- }, {
252
- name: "module-federation-dts-build",
253
- apply: "build",
254
- configResolved(config) {
255
- resolvedConfig = config;
256
- },
257
- async generateBundle() {
258
- if (hasGeneratedBundle) return;
259
- hasGeneratedBundle = true;
260
- if (!resolvedConfig) return;
261
- let normalizedDtsOptions;
262
- try {
263
- normalizedDtsOptions = normalizeDtsOptions(getDtsModuleFederationConfig(resolvedConfig.root), resolvedConfig.root);
264
- } catch (error) {
265
- logDtsError(error, options.dts);
266
- return;
267
- }
268
- if (typeof normalizedDtsOptions !== "object") return;
269
- const context = resolvedConfig.root;
270
- const outputDir = resolveOutputDir(resolvedConfig);
271
- let consumeOptions;
272
- try {
273
- consumeOptions = normalizeConsumeTypesOptions({
274
- context,
275
- dtsOptions: normalizedDtsOptions,
276
- pluginOptions: getDtsModuleFederationConfig(resolvedConfig.root)
277
- });
278
- } catch (error) {
279
- logDtsError(error, normalizedDtsOptions);
280
- return;
281
- }
282
- if (consumeOptions?.host?.typesOnBuild) try {
283
- await consumeTypesAPI(consumeOptions);
284
- } catch (error) {
285
- logDtsError(error, normalizedDtsOptions);
286
- }
287
- let generateOptions;
288
- try {
289
- generateOptions = normalizeGenerateTypesOptions({
290
- context,
291
- outputDir,
292
- dtsOptions: normalizedDtsOptions,
293
- pluginOptions: getDtsModuleFederationConfig(resolvedConfig.root)
294
- });
295
- } catch (error) {
296
- logDtsError(error, normalizedDtsOptions);
297
- return;
298
- }
299
- if (!generateOptions) return;
300
- try {
301
- await generateTypesAPI({ dtsManagerOptions: generateOptions });
302
- } catch (error) {
303
- logDtsError(error, normalizedDtsOptions);
304
- }
305
- }
306
- }];
307
- }
308
- //#endregion
309
- export { pluginDts as default };