@module-federation/vite 1.20.5 → 1.20.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,312 @@
1
+ import { n as normalizePathForImport } from "./buildPaths-BkaQHrd2.js";
2
+ import { _ as mfError, g as createModuleFederationError, l as hasPackageDependency, p as resolveImportPath } from "./dtsConstants-DyJrx8ah.js";
3
+ import fs from "fs";
4
+ import * as path$1 from "node:path";
5
+ import { normalizeOptions } from "@module-federation/sdk";
6
+ import { consumeTypesAPI, generateTypesAPI, isTSProject, normalizeConsumeTypesOptions, normalizeDtsOptions, normalizeGenerateTypesOptions } from "@module-federation/dts-plugin";
7
+ import { rpc } from "@module-federation/dts-plugin/core";
8
+ //#region src/plugins/pluginDts.ts
9
+ const DEFAULT_DEV_OPTIONS = {
10
+ disableLiveReload: true,
11
+ disableHotTypesReload: false,
12
+ disableDynamicRemoteTypeHints: false
13
+ };
14
+ const DYNAMIC_HINTS_PLUGIN = "@module-federation/dts-plugin/dynamic-remote-type-hints-plugin";
15
+ const getIPv4 = () => process.env["FEDERATION_IPV4"] || "127.0.0.1";
16
+ const DEV_TYPES_FOLDER = ".dev-server";
17
+ const forkDevWorkerPath = (() => {
18
+ return resolveImportPath("@module-federation/dts-plugin/dist/fork-dev-worker.js");
19
+ })();
20
+ var DevWorker = class {
21
+ worker = rpc.createRpcWorker(forkDevWorkerPath, {}, void 0, false);
22
+ constructor(options) {
23
+ this.worker.connect(options);
24
+ }
25
+ update() {
26
+ this.worker.process?.send?.({
27
+ type: rpc.RpcGMCallTypes.CALL,
28
+ id: this.worker.id,
29
+ args: [void 0, "update"]
30
+ });
31
+ }
32
+ exit() {
33
+ this.worker.terminate();
34
+ }
35
+ };
36
+ const normalizeDevOptions = (dev) => {
37
+ if (dev === false) return false;
38
+ if (dev === true || typeof dev === "undefined") return { ...DEFAULT_DEV_OPTIONS };
39
+ return {
40
+ ...DEFAULT_DEV_OPTIONS,
41
+ ...dev
42
+ };
43
+ };
44
+ const buildDtsModuleFederationConfig = (options) => {
45
+ const exposes = {};
46
+ Object.entries(options.exposes).forEach(([key, value]) => {
47
+ if (value.import) exposes[key] = value.import;
48
+ });
49
+ const remotes = {};
50
+ Object.entries(options.remotes).forEach(([key, remote]) => {
51
+ if (!remote.entry) return;
52
+ const entryGlobalName = remote.entryGlobalName?.startsWith("http") || remote.entryGlobalName?.includes(".json") ? remote.name || key : remote.entryGlobalName || remote.name || key;
53
+ remotes[key] = `${entryGlobalName}@${remote.entry}`;
54
+ });
55
+ return {
56
+ ...options,
57
+ exposes,
58
+ remotes
59
+ };
60
+ };
61
+ const resolveOutputDir = (config) => {
62
+ const { outDir } = config.build;
63
+ if (path$1.isAbsolute(outDir)) return normalizePathForImport(path$1.relative(config.root, outDir));
64
+ return outDir;
65
+ };
66
+ const ensureRuntimePlugin = (options, pluginId) => {
67
+ if (!options.runtimePlugins.some((plugin) => {
68
+ if (typeof plugin === "string") return plugin === pluginId;
69
+ return plugin[0] === pluginId;
70
+ })) options.runtimePlugins.push(pluginId);
71
+ };
72
+ const getExposeImportPaths = (options) => {
73
+ return Object.values(options.exposes).map((value) => {
74
+ return value.import;
75
+ }).filter((value) => Boolean(value));
76
+ };
77
+ const usesVueSfcExposes = (options) => {
78
+ return getExposeImportPaths(options).some((value) => value.endsWith(".vue"));
79
+ };
80
+ const resolveDtsPluginOptions = (dts, options, context) => {
81
+ if (dts === false) return false;
82
+ const inferredGenerateTypesDefaults = { generateAPITypes: true };
83
+ if (usesVueSfcExposes(options) && hasPackageDependency("vue-tsc", context)) inferredGenerateTypesDefaults.compilerInstance = "vue-tsc";
84
+ if (dts === true || typeof dts === "undefined") return { generateTypes: inferredGenerateTypesDefaults };
85
+ const generateTypes = dts.generateTypes;
86
+ return {
87
+ ...dts,
88
+ generateTypes: generateTypes === false ? false : {
89
+ ...inferredGenerateTypesDefaults,
90
+ ...generateTypes === true || typeof generateTypes === "undefined" ? {} : generateTypes
91
+ }
92
+ };
93
+ };
94
+ const getBasePath = (base) => {
95
+ if (base.startsWith("http://") || base.startsWith("https://")) return new URL(base).pathname.replace(/\/$/, "") || "/";
96
+ return base.replace(/\/$/, "") || "/";
97
+ };
98
+ const joinBaseAndAsset = (base, assetFileName) => {
99
+ const basePath = getBasePath(base);
100
+ return `${basePath === "/" ? "" : basePath}/${assetFileName}`.replace(/\/{2,}/g, "/");
101
+ };
102
+ const getDevDtsAssetPaths = (options) => {
103
+ const { outputDir, publicTypesFolder, root, base } = options;
104
+ return {
105
+ apiFilePath: path$1.resolve(root, outputDir, `${DEV_TYPES_FOLDER}.d.ts`),
106
+ apiRequestPath: joinBaseAndAsset(base, `${publicTypesFolder}.d.ts`),
107
+ zipFilePath: path$1.resolve(root, outputDir, `${DEV_TYPES_FOLDER}.zip`),
108
+ zipRequestPath: joinBaseAndAsset(base, `${publicTypesFolder}.zip`)
109
+ };
110
+ };
111
+ const createDevDtsAssetMiddleware = (assetPaths) => {
112
+ return (req, res, next) => {
113
+ const requestPath = req.url?.split("?")[0];
114
+ const isZipRequest = requestPath === assetPaths.zipRequestPath;
115
+ const isApiRequest = requestPath === assetPaths.apiRequestPath;
116
+ if (!isZipRequest && !isApiRequest) {
117
+ next();
118
+ return;
119
+ }
120
+ const filePath = isZipRequest ? assetPaths.zipFilePath : assetPaths.apiFilePath;
121
+ if (!fs.existsSync(filePath)) {
122
+ res.statusCode = 404;
123
+ res.end();
124
+ return;
125
+ }
126
+ res.statusCode = 200;
127
+ res.setHeader("Content-Type", isZipRequest ? "application/x-gzip" : "application/typescript");
128
+ if (req.method === "HEAD") {
129
+ res.end();
130
+ return;
131
+ }
132
+ const stream = fs.createReadStream(filePath);
133
+ stream.on("error", () => {
134
+ if (!res.headersSent) res.statusCode = 500;
135
+ res.end();
136
+ });
137
+ res.on("close", () => {
138
+ stream.destroy();
139
+ });
140
+ stream.pipe(res);
141
+ };
142
+ };
143
+ const normalizeDevDtsOptions = (dts, context) => {
144
+ return normalizeOptions(isTSProject(dts, context), {
145
+ generateTypes: { compileInChildProcess: true },
146
+ consumeTypes: { consumeAPITypes: true },
147
+ extraOptions: {},
148
+ displayErrorInTerminal: typeof dts === "object" && dts ? dts.displayErrorInTerminal : void 0
149
+ }, "mfOptions.dts")(dts);
150
+ };
151
+ const logDtsError = (error, dtsOptions) => {
152
+ if (dtsOptions === false) return;
153
+ if (typeof dtsOptions === "object" && dtsOptions && dtsOptions.displayErrorInTerminal === false) return;
154
+ mfError(error);
155
+ };
156
+ function pluginDts(options) {
157
+ if (options.dts === false) return [];
158
+ const baseDtsModuleFederationConfig = buildDtsModuleFederationConfig(options);
159
+ const getDtsModuleFederationConfig = (context) => ({
160
+ ...baseDtsModuleFederationConfig,
161
+ dts: resolveDtsPluginOptions(options.dts, options, context)
162
+ });
163
+ let resolvedConfig;
164
+ let devWorker;
165
+ let normalizedDevOptions;
166
+ let hasGeneratedBundle = false;
167
+ return [{
168
+ name: "module-federation-dts-dev",
169
+ apply: "serve",
170
+ config(config) {
171
+ normalizedDevOptions = normalizeDevOptions(options.dev);
172
+ if (!normalizedDevOptions) return;
173
+ if (normalizedDevOptions.disableDynamicRemoteTypeHints) return;
174
+ ensureRuntimePlugin(options, DYNAMIC_HINTS_PLUGIN);
175
+ const define = config.define ? { ...config.define } : {};
176
+ if (!("FEDERATION_IPV4" in define)) define.FEDERATION_IPV4 = JSON.stringify(getIPv4());
177
+ config.define = define;
178
+ },
179
+ configResolved(config) {
180
+ resolvedConfig = config;
181
+ },
182
+ configureServer(server) {
183
+ if (!normalizedDevOptions || !resolvedConfig) return;
184
+ const devOptions = normalizedDevOptions;
185
+ if (devOptions.disableDynamicRemoteTypeHints && devOptions.disableHotTypesReload && devOptions.disableLiveReload) return;
186
+ if (!options.name) throw createModuleFederationError("name is required if you want to enable dev server!");
187
+ const outputDir = resolveOutputDir(resolvedConfig);
188
+ const dtsModuleFederationConfig = getDtsModuleFederationConfig(resolvedConfig.root);
189
+ const normalizedDtsOptions = normalizeDevDtsOptions(dtsModuleFederationConfig.dts, resolvedConfig.root);
190
+ if (typeof normalizedDtsOptions !== "object") return;
191
+ const normalizedGenerateTypes = normalizeOptions(Boolean(normalizedDtsOptions), { compileInChildProcess: true }, "mfOptions.dts.generateTypes")(normalizedDtsOptions.generateTypes);
192
+ const remote = normalizedGenerateTypes === false ? void 0 : {
193
+ implementation: normalizedDtsOptions.implementation,
194
+ context: resolvedConfig.root,
195
+ outputDir,
196
+ moduleFederationConfig: { ...dtsModuleFederationConfig },
197
+ hostRemoteTypesFolder: normalizedGenerateTypes.typesFolder || "@mf-types",
198
+ ...normalizedGenerateTypes,
199
+ typesFolder: DEV_TYPES_FOLDER
200
+ };
201
+ if (remote) server.middlewares.use(createDevDtsAssetMiddleware(getDevDtsAssetPaths({
202
+ outputDir,
203
+ publicTypesFolder: remote.hostRemoteTypesFolder || "@mf-types",
204
+ root: resolvedConfig.root,
205
+ base: resolvedConfig.base
206
+ })));
207
+ if (remote && !remote.tsConfigPath && normalizedDtsOptions.tsConfigPath) remote.tsConfigPath = normalizedDtsOptions.tsConfigPath;
208
+ const normalizedConsumeTypes = normalizeOptions(Boolean(normalizedDtsOptions), { consumeAPITypes: true }, "mfOptions.dts.consumeTypes")(normalizedDtsOptions.consumeTypes);
209
+ const host = normalizedConsumeTypes === false ? void 0 : {
210
+ implementation: normalizedDtsOptions.implementation,
211
+ context: resolvedConfig.root,
212
+ moduleFederationConfig: dtsModuleFederationConfig,
213
+ typesFolder: normalizedConsumeTypes.typesFolder || "@mf-types",
214
+ abortOnError: false,
215
+ ...normalizedConsumeTypes
216
+ };
217
+ const extraOptions = normalizedDtsOptions.extraOptions || {};
218
+ if (!remote && !host && devOptions.disableLiveReload) return;
219
+ const startDevWorker = async () => {
220
+ let remoteTypeUrls;
221
+ if (host) remoteTypeUrls = await new Promise((resolve) => {
222
+ consumeTypesAPI({
223
+ host,
224
+ extraOptions,
225
+ displayErrorInTerminal: normalizedDtsOptions.displayErrorInTerminal
226
+ }, resolve);
227
+ });
228
+ devWorker = new DevWorker({
229
+ name: options.name,
230
+ remote,
231
+ host: host ? {
232
+ ...host,
233
+ remoteTypeUrls
234
+ } : void 0,
235
+ extraOptions,
236
+ disableLiveReload: devOptions.disableLiveReload,
237
+ disableHotTypesReload: devOptions.disableHotTypesReload
238
+ });
239
+ const update = () => devWorker?.update();
240
+ server.watcher.on("change", update);
241
+ server.watcher.on("add", update);
242
+ server.watcher.on("unlink", update);
243
+ server.httpServer?.once("close", () => {
244
+ devWorker?.exit();
245
+ server.watcher.off("change", update);
246
+ server.watcher.off("add", update);
247
+ server.watcher.off("unlink", update);
248
+ });
249
+ };
250
+ startDevWorker().catch((error) => {
251
+ logDtsError(error, normalizedDtsOptions);
252
+ });
253
+ }
254
+ }, {
255
+ name: "module-federation-dts-build",
256
+ apply: "build",
257
+ configResolved(config) {
258
+ resolvedConfig = config;
259
+ },
260
+ async generateBundle() {
261
+ if (hasGeneratedBundle) return;
262
+ hasGeneratedBundle = true;
263
+ if (!resolvedConfig) return;
264
+ let normalizedDtsOptions;
265
+ try {
266
+ normalizedDtsOptions = normalizeDtsOptions(getDtsModuleFederationConfig(resolvedConfig.root), resolvedConfig.root);
267
+ } catch (error) {
268
+ logDtsError(error, options.dts);
269
+ return;
270
+ }
271
+ if (typeof normalizedDtsOptions !== "object") return;
272
+ const context = resolvedConfig.root;
273
+ const outputDir = resolveOutputDir(resolvedConfig);
274
+ let consumeOptions;
275
+ try {
276
+ consumeOptions = normalizeConsumeTypesOptions({
277
+ context,
278
+ dtsOptions: normalizedDtsOptions,
279
+ pluginOptions: getDtsModuleFederationConfig(resolvedConfig.root)
280
+ });
281
+ } catch (error) {
282
+ logDtsError(error, normalizedDtsOptions);
283
+ return;
284
+ }
285
+ if (consumeOptions?.host?.typesOnBuild) try {
286
+ await consumeTypesAPI(consumeOptions);
287
+ } catch (error) {
288
+ logDtsError(error, normalizedDtsOptions);
289
+ }
290
+ let generateOptions;
291
+ try {
292
+ generateOptions = normalizeGenerateTypesOptions({
293
+ context,
294
+ outputDir,
295
+ dtsOptions: normalizedDtsOptions,
296
+ pluginOptions: getDtsModuleFederationConfig(resolvedConfig.root)
297
+ });
298
+ } catch (error) {
299
+ logDtsError(error, normalizedDtsOptions);
300
+ return;
301
+ }
302
+ if (!generateOptions) return;
303
+ try {
304
+ await generateTypesAPI({ dtsManagerOptions: generateOptions });
305
+ } catch (error) {
306
+ logDtsError(error, normalizedDtsOptions);
307
+ }
308
+ }
309
+ }];
310
+ }
311
+ //#endregion
312
+ export { pluginDts as default };
@@ -133,7 +133,9 @@ async function nodeImport(id) {
133
133
  ));
134
134
  return importCache.get(id);
135
135
  }
136
- const isNodeServer = () => typeof globalThis.process?.versions?.node === "string";
136
+ const isNodeServer = () => {
137
+ return import.meta.env?.SSR ?? typeof globalThis.process?.versions?.node === "string";
138
+ };
137
139
  const runnerCache = /* @__PURE__ */ new Map();
138
140
  function getSortedRecordEntries(record) {
139
141
  return Object.entries(record).sort(([left], [right]) => left.localeCompare(right));
@@ -196,16 +198,17 @@ async function getOrCreateRunner(remoteOrigin, resolvedShared, fetchTimeoutMs, f
196
198
  return new ModuleRunner({
197
199
  hmr: false,
198
200
  transport: { async invoke(payload) {
199
- if (payload.data.name === "fetchModule") {
200
- const sharedExternal = await resolveSharedExternal(payload.data.data[0], resolvedShared);
201
- if (sharedExternal) return { result: sharedExternal };
202
- }
203
201
  const text = await readResponseTextBounded(await fetchWithTimeout(runnerEndpoint, {
204
202
  method: "POST",
205
203
  headers: { "Content-Type": "application/json" },
206
204
  body: JSON.stringify(payload)
207
205
  }, fetchTimeoutMs), fetchMaxBytes, runnerEndpoint);
208
- return JSON.parse(text);
206
+ const result = JSON.parse(text);
207
+ if ("error" in result && payload.data.name === "fetchModule") {
208
+ const sharedExternal = await resolveSharedExternal(payload.data.data[0], resolvedShared);
209
+ if (sharedExternal) return { result: sharedExternal };
210
+ }
211
+ return result;
209
212
  } }
210
213
  }, new ESModulesEvaluator());
211
214
  } catch {
@@ -567,7 +570,7 @@ async function fetchEsmToTempFile(url, tmpDir, visited, pending, sharedPkgMap, v
567
570
  if (!res.ok) throw new SsrEntryHttpError(url, res.status, res.statusText, getBodyPreview(code));
568
571
  const base = url.replace(/\/[^/]*$/, "/");
569
572
  const relImports = [];
570
- const relRegex = /(?:from|export\s*\*\s*from|import\s*(?:\(|\s))\s*["'`]([^"'`\s]+)["'`]/g;
573
+ const relRegex = /(?:from|export\s*\*\s*from|import\s*\(?\s*)\s*["'`]([^"'`\s]+)["'`]/g;
571
574
  let m;
572
575
  while ((m = relRegex.exec(code)) !== null) if ((m[1].startsWith("./") || m[1].startsWith("../")) && !isVitePreloadHelperSpecifier(m[1])) relImports.push(new URL(m[1], base).href);
573
576
  const subMap = /* @__PURE__ */ new Map();
@@ -603,7 +606,7 @@ async function importTempModule(filePath, versionKey) {
603
606
  }
604
607
  let warnedVmUnavailable = false;
605
608
  async function tryVmStrategy(ssrEntry, options) {
606
- const { loadViaVmStrategy, isVmStrategyAvailable } = await import("./ssrVmStrategy-DTJITp2Z.js");
609
+ const { loadViaVmStrategy, isVmStrategyAvailable } = await import("./ssrVmStrategy-B0fCaHs5.js");
607
610
  if (!await isVmStrategyAvailable()) {
608
611
  if (!warnedVmUnavailable) {
609
612
  warnedVmUnavailable = true;
@@ -1,5 +1,5 @@
1
1
  import { a as getCommonSharedSubpaths } from "./pathNormalization-DvgU8LIp.js";
2
- import { c as readResponseTextBounded, n as neutralizeBrowserPreloadHelpers, s as fetchWithTimeout, t as SsrEntryHttpError } from "./ssrEntryLoader-Ccr0zMrr.js";
2
+ import { c as readResponseTextBounded, n as neutralizeBrowserPreloadHelpers, s as fetchWithTimeout, t as SsrEntryHttpError } from "./ssrEntryLoader-0NnTjWR1.js";
3
3
  //#region src/utils/ssrVmStrategy.ts
4
4
  /**
5
5
  * vm.SourceTextModule strategy for loading remote SSR entries.
@@ -1,2 +1,2 @@
1
- import { i as ssrEntryLoaderPlugin, n as neutralizeBrowserPreloadHelpers, r as revalidate, t as SsrEntryHttpError } from "../ssrEntryLoader-Ccr0zMrr.js";
1
+ import { i as ssrEntryLoaderPlugin, n as neutralizeBrowserPreloadHelpers, r as revalidate, t as SsrEntryHttpError } from "../ssrEntryLoader-0NnTjWR1.js";
2
2
  export { SsrEntryHttpError, ssrEntryLoaderPlugin as default, neutralizeBrowserPreloadHelpers, revalidate };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@module-federation/vite",
3
- "version": "1.20.5",
3
+ "version": "1.20.7",
4
4
  "description": "Vite plugin for Module Federation",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -93,4 +93,4 @@
93
93
  "vite": "8.2.0",
94
94
  "vitest": "4.1.10"
95
95
  }
96
- }
96
+ }