@module-federation/dts-plugin 0.0.0-perf-devtools-20260107043700 → 0.0.0-perf-website-code-usage-20260914033703

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.
Files changed (56) hide show
  1. package/dist/Action-CzhPMw2i.js +153 -0
  2. package/dist/Broker-C-uWF8l5.js +802 -0
  3. package/dist/CHANGELOG.md +297 -6
  4. package/dist/DtsWorker-SBLpkK-D.d.ts +178 -0
  5. package/dist/constant-C0QI9ddQ.d.ts +42 -0
  6. package/dist/consumeTypes-DhrUgkUW.js +241 -0
  7. package/dist/core.d.ts +3 -68
  8. package/dist/core.js +26 -2380
  9. package/dist/dynamic-remote-type-hints-plugin.d.ts +819 -3
  10. package/dist/dynamic-remote-type-hints-plugin.js +65 -187
  11. package/dist/esm/Action-DNNg2YDh.mjs +47 -0
  12. package/dist/esm/Broker-BfFUcTHm.mjs +738 -0
  13. package/dist/esm/consumeTypes-WKYNaS9i.mjs +208 -0
  14. package/dist/esm/core.mjs +5 -0
  15. package/dist/esm/dynamic-remote-type-hints-plugin.mjs +73 -0
  16. package/dist/esm/expose-rpc-B0rqtOKP.mjs +1593 -0
  17. package/dist/esm/fork-dev-worker.mjs +113 -0
  18. package/dist/esm/fork-generate-dts.mjs +14 -0
  19. package/dist/esm/index.mjs +509 -0
  20. package/dist/esm/start-broker.mjs +22 -0
  21. package/dist/esm/utils-CkPvDGOy.mjs +13 -0
  22. package/dist/expose-rpc-jaGpsAVL.js +1701 -0
  23. package/dist/fork-dev-worker.d.ts +10 -9
  24. package/dist/fork-dev-worker.js +110 -2869
  25. package/dist/fork-generate-dts.d.ts +4 -8
  26. package/dist/fork-generate-dts.js +11 -2040
  27. package/dist/iife/launch-web-client.iife.js +117 -0
  28. package/dist/index.d.ts +46 -50
  29. package/dist/index.js +493 -2978
  30. package/dist/start-broker.d.ts +41 -39
  31. package/dist/start-broker.js +17 -952
  32. package/dist/utils-7KqCZHbb.js +19 -0
  33. package/package.json +50 -30
  34. package/dist/DTSManager-b15Gfat3.d.ts +0 -53
  35. package/dist/DTSManagerOptions-QVchWb0x.d.ts +0 -32
  36. package/dist/DtsWorker-BrHsGz8C.d.ts +0 -56
  37. package/dist/core.d.mts +0 -68
  38. package/dist/dynamic-remote-type-hints-plugin.d.mts +0 -5
  39. package/dist/esm/chunk-647HGGGS.js +0 -241
  40. package/dist/esm/chunk-G65LOFTY.js +0 -24
  41. package/dist/esm/chunk-N7GTIQUA.js +0 -282
  42. package/dist/esm/chunk-RWXNVNFM.js +0 -1579
  43. package/dist/esm/chunk-WWV5RWOP.js +0 -902
  44. package/dist/esm/core.js +0 -44
  45. package/dist/esm/dynamic-remote-type-hints-plugin.js +0 -73
  46. package/dist/esm/fork-dev-worker.js +0 -145
  47. package/dist/esm/fork-generate-dts.js +0 -27
  48. package/dist/esm/index.js +0 -644
  49. package/dist/esm/start-broker.js +0 -36
  50. package/dist/fork-dev-worker.d.mts +0 -15
  51. package/dist/fork-generate-dts.d.mts +0 -10
  52. package/dist/iife/launch-web-client.js +0 -152
  53. package/dist/index.d.mts +0 -56
  54. package/dist/package.json +0 -87
  55. package/dist/start-broker.d.mts +0 -42
  56. package/dist/utils-DxGrqb9N.d.ts +0 -15
@@ -0,0 +1,1593 @@
1
+ import { a as MF_SERVER_IDENTIFIER, n as ActionKind, o as UpdateMode, r as DEFAULT_TAR_NAME, t as Action } from "./Action-DNNg2YDh.mjs";
2
+ import { a as getIdentifier, c as logger$1, i as getFreePort, l as LogKind, n as UpdateKind, o as getIPV4, r as fib, s as fileLog, t as Broker, u as APIKind } from "./Broker-BfFUcTHm.mjs";
3
+ import { createRequire } from "node:module";
4
+ import fs, { existsSync, mkdirSync, realpathSync, rmSync, writeFileSync } from "fs";
5
+ import { fileURLToPath } from "url";
6
+ import path, { dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "path";
7
+ import { cp, mkdir, readFile, readdir, rm, stat, writeFile } from "fs/promises";
8
+ import crypto from "crypto";
9
+ import { execFile, execFileSync, fork } from "child_process";
10
+ import { utils } from "@module-federation/managers";
11
+ import { ENCODE_NAME_PREFIX, MANIFEST_EXT, TEMP_DIR, decodeName, getProcessEnv, inferAutoPublicPath, parseEntry } from "@module-federation/sdk";
12
+ import { styleText } from "node:util";
13
+ import { Agent } from "undici";
14
+ import { ThirdPartyExtractor } from "@module-federation/third-party-dts-extractor";
15
+ import AdmZip from "adm-zip";
16
+ import { TYPE_001, typeDescMap } from "@module-federation/error-codes";
17
+ import { logAndReport } from "@module-federation/error-codes/node";
18
+ import util from "util";
19
+ import WebSocket from "isomorphic-ws";
20
+ import http from "http";
21
+ import { createRequire as createRequire$1 } from "module";
22
+ import process$1 from "process";
23
+
24
+ //#region \0rolldown/runtime.js
25
+ var __defProp = Object.defineProperty;
26
+ var __exportAll = (all, no_symbols) => {
27
+ let target = {};
28
+ for (var name in all) {
29
+ __defProp(target, name, {
30
+ get: all[name],
31
+ enumerable: true
32
+ });
33
+ }
34
+ if (!no_symbols) {
35
+ __defProp(target, Symbol.toStringTag, { value: "Module" });
36
+ }
37
+ return target;
38
+ };
39
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
40
+
41
+ //#endregion
42
+ //#region src/server/message/Action/AddPublisher.ts
43
+ var AddPublisherAction = class extends Action {
44
+ constructor(payload) {
45
+ super({ payload }, ActionKind.ADD_PUBLISHER);
46
+ }
47
+ };
48
+
49
+ //#endregion
50
+ //#region src/server/message/Action/AddSubscriber.ts
51
+ var AddSubscriberAction = class extends Action {
52
+ constructor(payload) {
53
+ super({ payload }, ActionKind.ADD_SUBSCRIBER);
54
+ }
55
+ };
56
+
57
+ //#endregion
58
+ //#region src/server/message/Action/ExitSubscriber.ts
59
+ var ExitSubscriberAction = class extends Action {
60
+ constructor(payload) {
61
+ super({ payload }, ActionKind.EXIT_SUBSCRIBER);
62
+ }
63
+ };
64
+
65
+ //#endregion
66
+ //#region src/server/message/Action/ExitPublisher.ts
67
+ var ExitPublisherAction = class extends Action {
68
+ constructor(payload) {
69
+ super({ payload }, ActionKind.EXIT_PUBLISHER);
70
+ }
71
+ };
72
+
73
+ //#endregion
74
+ //#region src/server/message/Action/NotifyWebClient.ts
75
+ var NotifyWebClientAction = class extends Action {
76
+ constructor(payload) {
77
+ super({ payload }, ActionKind.NOTIFY_WEB_CLIENT);
78
+ }
79
+ };
80
+
81
+ //#endregion
82
+ //#region src/server/message/Action/UpdatePublisher.ts
83
+ var UpdatePublisherAction = class extends Action {
84
+ constructor(payload) {
85
+ super({ payload }, ActionKind.UPDATE_PUBLISHER);
86
+ }
87
+ };
88
+
89
+ //#endregion
90
+ //#region src/server/broker/createBroker.ts
91
+ const __filename = fileURLToPath(import.meta.url);
92
+ const __dirname = path.dirname(__filename);
93
+ function createBroker() {
94
+ const sub = fork(path.resolve(__dirname, "./start-broker.js"), [], {
95
+ detached: true,
96
+ stdio: "ignore",
97
+ env: process.env
98
+ });
99
+ sub.send("start");
100
+ sub.unref();
101
+ return sub;
102
+ }
103
+
104
+ //#endregion
105
+ //#region src/server/DevServer.ts
106
+ var ModuleFederationDevServer = class {
107
+ constructor(ctx) {
108
+ this._publishWebSocket = null;
109
+ this._subscriberWebsocketMap = {};
110
+ this._reconnect = true;
111
+ this._reconnectTimes = 0;
112
+ this._isConnected = false;
113
+ this._isReconnecting = false;
114
+ this._updateCallback = () => Promise.resolve(void 0);
115
+ const { name, remotes, remoteTypeTarPath, updateCallback } = ctx;
116
+ this._ip = getIPV4();
117
+ this._name = name;
118
+ this._remotes = remotes;
119
+ this._remoteTypeTarPath = remoteTypeTarPath;
120
+ this._updateCallback = updateCallback;
121
+ this._stopWhenSIGTERMOrSIGINT();
122
+ this._handleUnexpectedExit();
123
+ this._connectPublishToServer();
124
+ }
125
+ _connectPublishToServer() {
126
+ if (!this._reconnect) return;
127
+ fileLog(`Publisher:${this._name} Trying to connect to ws://${this._ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}...`, MF_SERVER_IDENTIFIER, "info");
128
+ this._publishWebSocket = new WebSocket(`ws://${this._ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}?WEB_SOCKET_CONNECT_MAGIC_ID=${Broker.WEB_SOCKET_CONNECT_MAGIC_ID}`);
129
+ this._publishWebSocket.on("open", () => {
130
+ fileLog(`Current pid: ${process.pid}, publisher:${this._name} connected to ws://${this._ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}, starting service...`, MF_SERVER_IDENTIFIER, "info");
131
+ this._isConnected = true;
132
+ const addPublisherAction = new AddPublisherAction({
133
+ name: this._name,
134
+ ip: this._ip,
135
+ remoteTypeTarPath: this._remoteTypeTarPath
136
+ });
137
+ this._publishWebSocket?.send(JSON.stringify(addPublisherAction));
138
+ this._connectSubscribers();
139
+ });
140
+ this._publishWebSocket.on("message", async (message) => {
141
+ try {
142
+ const parsedMessage = JSON.parse(message.toString());
143
+ if (parsedMessage.type === "Log") {
144
+ if (parsedMessage.kind === LogKind.BrokerExitLog) {
145
+ fileLog(`Receive broker exit signal, ${this._name} service will exit...`, MF_SERVER_IDENTIFIER, "warn");
146
+ this._exit();
147
+ }
148
+ }
149
+ if (parsedMessage.type === "API") {
150
+ if (parsedMessage.kind === APIKind.FETCH_TYPES) {
151
+ const { payload: { remoteInfo } } = parsedMessage;
152
+ fileLog(`${this._name} Receive broker FETCH_TYPES, payload as follows: ${JSON.stringify(remoteInfo, null, 2)}.`, MF_SERVER_IDENTIFIER, "info");
153
+ await this.fetchDynamicRemoteTypes({ remoteInfo });
154
+ }
155
+ }
156
+ } catch (err) {
157
+ console.error(err);
158
+ const exitPublisher = new ExitPublisherAction({
159
+ name: this._name,
160
+ ip: this._ip
161
+ });
162
+ const exitSubscriber = new ExitSubscriberAction({
163
+ name: this._name,
164
+ ip: this._ip,
165
+ publishers: this._remotes.map((remote) => ({
166
+ name: remote.name,
167
+ ip: remote.ip
168
+ }))
169
+ });
170
+ this._publishWebSocket?.send(JSON.stringify(exitPublisher));
171
+ this._publishWebSocket?.send(JSON.stringify(exitSubscriber));
172
+ fileLog("Parse messages error, ModuleFederationDevServer will exit...", MF_SERVER_IDENTIFIER, "fatal");
173
+ this._exit();
174
+ }
175
+ });
176
+ this._publishWebSocket.on("close", (code) => {
177
+ fileLog(`Connection closed with code ${code}.`, MF_SERVER_IDENTIFIER, "warn");
178
+ this._publishWebSocket && this._publishWebSocket.close();
179
+ this._publishWebSocket = null;
180
+ if (!this._reconnect) return;
181
+ const reconnectTime = fib(++this._reconnectTimes);
182
+ fileLog(`start reconnecting to server after ${reconnectTime}s.`, MF_SERVER_IDENTIFIER, "info");
183
+ setTimeout(() => this._connectPublishToServer(), reconnectTime * 1e3);
184
+ });
185
+ this._publishWebSocket.on("error", this._tryCreateBackgroundBroker.bind(this));
186
+ }
187
+ _connectSubscriberToServer(remote) {
188
+ const { name, ip } = remote;
189
+ fileLog(`remote module:${name} trying to connect to ws://${ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}...`, MF_SERVER_IDENTIFIER, "info");
190
+ const identifier = getIdentifier({
191
+ name,
192
+ ip
193
+ });
194
+ this._subscriberWebsocketMap[identifier] = new WebSocket(`ws://${ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}?WEB_SOCKET_CONNECT_MAGIC_ID=${Broker.WEB_SOCKET_CONNECT_MAGIC_ID}`);
195
+ this._subscriberWebsocketMap[identifier].on("open", () => {
196
+ fileLog(`Current pid: ${process.pid} remote module: ${name} connected to ws://${ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}, starting service...`, MF_SERVER_IDENTIFIER, "info");
197
+ const addSubscriber = new AddSubscriberAction({
198
+ name: this._name,
199
+ ip: this._ip,
200
+ publishers: [{
201
+ name,
202
+ ip
203
+ }]
204
+ });
205
+ this._subscriberWebsocketMap[identifier].send(JSON.stringify(addSubscriber));
206
+ });
207
+ this._subscriberWebsocketMap[identifier].on("message", async (message) => {
208
+ try {
209
+ const parsedMessage = JSON.parse(message.toString());
210
+ if (parsedMessage.type === "Log") {
211
+ if (parsedMessage.kind === LogKind.BrokerExitLog) {
212
+ fileLog(`${identifier}'s Server exit, thus ${identifier} will no longer has reload ability.`, MF_SERVER_IDENTIFIER, "warn");
213
+ this._exit();
214
+ }
215
+ }
216
+ if (parsedMessage.type === "API") {
217
+ if (parsedMessage.kind === APIKind.UPDATE_SUBSCRIBER) {
218
+ const { payload: { updateKind, updateSourcePaths, name: subscribeName, remoteTypeTarPath, updateMode } } = parsedMessage;
219
+ await this._updateSubscriber({
220
+ remoteTypeTarPath,
221
+ name: subscribeName,
222
+ updateKind,
223
+ updateMode,
224
+ updateSourcePaths
225
+ });
226
+ }
227
+ }
228
+ } catch (err) {
229
+ console.error(err);
230
+ const exitSubscriber = new ExitSubscriberAction({
231
+ name: this._name,
232
+ ip: this._ip,
233
+ publishers: [{
234
+ name,
235
+ ip
236
+ }]
237
+ });
238
+ this._subscriberWebsocketMap[identifier].send(JSON.stringify(exitSubscriber));
239
+ fileLog(`${identifier} exit,
240
+ error: ${err instanceof Error ? err.toString() : JSON.stringify(err)}
241
+ `, MF_SERVER_IDENTIFIER, "warn");
242
+ }
243
+ });
244
+ this._subscriberWebsocketMap[identifier].on("close", (code) => {
245
+ fileLog(`Connection closed with code ${code}.`, MF_SERVER_IDENTIFIER, "warn");
246
+ this._subscriberWebsocketMap[identifier]?.close();
247
+ delete this._subscriberWebsocketMap[identifier];
248
+ });
249
+ this._subscriberWebsocketMap[identifier].on("error", (err) => {
250
+ if ("code" in err && err.code === "ETIMEDOUT") fileLog(`Can not connect ${JSON.stringify(remote)}, please make sure this remote is started locally.`, MF_SERVER_IDENTIFIER, "warn");
251
+ else console.error(err);
252
+ this._subscriberWebsocketMap[identifier]?.close();
253
+ delete this._subscriberWebsocketMap[identifier];
254
+ });
255
+ }
256
+ _connectSubscribers() {
257
+ this._remotes.forEach((remote) => {
258
+ this._connectSubscriberToServer(remote);
259
+ });
260
+ }
261
+ async _updateSubscriber(options) {
262
+ const { updateMode, updateKind, updateSourcePaths, name, remoteTypeTarPath, remoteInfo } = options;
263
+ fileLog(`[_updateSubscriber] run, options: ${JSON.stringify(options, null, 2)}`, MF_SERVER_IDENTIFIER, "warn");
264
+ if (updateMode === UpdateMode.PASSIVE && updateSourcePaths.includes(this._name)) {
265
+ fileLog(`[_updateSubscriber] run, updateSourcePaths:${updateSourcePaths} includes ${this._name}, update ignore!`, MF_SERVER_IDENTIFIER, "warn");
266
+ return;
267
+ }
268
+ if (updateSourcePaths.slice(-1)[0] === this._name) {
269
+ fileLog(`[_updateSubscriber] run, updateSourcePaths:${updateSourcePaths} ends is ${this._name}, update ignore!`, MF_SERVER_IDENTIFIER, "warn");
270
+ return;
271
+ }
272
+ fileLog(`[_updateSubscriber] run, updateSourcePaths:${updateSourcePaths}, current module:${this._name}, update start...`, MF_SERVER_IDENTIFIER, "info");
273
+ await this._updateCallback({
274
+ name,
275
+ updateMode,
276
+ updateKind,
277
+ updateSourcePaths,
278
+ remoteTypeTarPath,
279
+ remoteInfo
280
+ });
281
+ const newUpdateSourcePaths = updateSourcePaths.concat(this._name);
282
+ const updatePublisher = new UpdatePublisherAction({
283
+ name: this._name,
284
+ ip: this._ip,
285
+ updateMode: UpdateMode.PASSIVE,
286
+ updateKind,
287
+ updateSourcePaths: newUpdateSourcePaths,
288
+ remoteTypeTarPath: this._remoteTypeTarPath
289
+ });
290
+ fileLog(`[_updateSubscriber] run, updateSourcePaths:${newUpdateSourcePaths}, update publisher ${this._name} start...`, MF_SERVER_IDENTIFIER, "info");
291
+ this._publishWebSocket?.send(JSON.stringify(updatePublisher));
292
+ }
293
+ _tryCreateBackgroundBroker(err) {
294
+ if (!((err?.code === "ECONNREFUSED" || err?.code === "ETIMEDOUT") && err.port === Broker.DEFAULT_WEB_SOCKET_PORT)) {
295
+ fileLog(`websocket error: ${err.stack}`, MF_SERVER_IDENTIFIER, "fatal");
296
+ return;
297
+ }
298
+ fileLog(`Failed to connect to ws://${this._ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}...`, MF_SERVER_IDENTIFIER, "fatal");
299
+ this._isReconnecting = true;
300
+ setTimeout(() => {
301
+ this._isReconnecting = false;
302
+ if (this._reconnect === false) return;
303
+ fileLog("Creating new background broker...", MF_SERVER_IDENTIFIER, "warn");
304
+ createBroker().on("message", (message) => {
305
+ if (message === "ready") {
306
+ fileLog("background broker started.", MF_SERVER_IDENTIFIER, "info");
307
+ this._reconnectTimes = 1;
308
+ if (process.send) process.send("ready");
309
+ }
310
+ });
311
+ }, Math.ceil(100 * Math.random()));
312
+ }
313
+ _stopWhenSIGTERMOrSIGINT() {
314
+ process.on("SIGTERM", () => {
315
+ fileLog(`Process(${process.pid}) SIGTERM, ModuleFederationDevServer will exit...`, MF_SERVER_IDENTIFIER, "warn");
316
+ this._exit();
317
+ });
318
+ process.on("SIGINT", () => {
319
+ fileLog(`Process(${process.pid}) SIGINT, ModuleFederationDevServer will exit...`, MF_SERVER_IDENTIFIER, "warn");
320
+ this._exit();
321
+ });
322
+ }
323
+ _handleUnexpectedExit() {
324
+ process.on("unhandledRejection", (error) => {
325
+ if (this._isReconnecting) return;
326
+ console.error("Unhandled Rejection Error: ", error);
327
+ fileLog(`Process(${process.pid}) unhandledRejection, garfishModuleServer will exit...`, MF_SERVER_IDENTIFIER, "error");
328
+ this._exit();
329
+ });
330
+ process.on("uncaughtException", (error) => {
331
+ if (this._isReconnecting) return;
332
+ console.error("Unhandled Exception Error: ", error);
333
+ fileLog(`Process(${process.pid}) uncaughtException, garfishModuleServer will exit...`, MF_SERVER_IDENTIFIER, "error");
334
+ this._exit();
335
+ });
336
+ }
337
+ _exit() {
338
+ this._reconnect = false;
339
+ if (this._publishWebSocket) {
340
+ const exitPublisher = new ExitPublisherAction({
341
+ name: this._name,
342
+ ip: this._ip
343
+ });
344
+ this._publishWebSocket.send(JSON.stringify(exitPublisher));
345
+ this._publishWebSocket.on("message", (message) => {
346
+ const parsedMessage = JSON.parse(message.toString());
347
+ fileLog(`[${parsedMessage.kind}]: ${JSON.stringify(parsedMessage)}`, MF_SERVER_IDENTIFIER, "info");
348
+ });
349
+ }
350
+ if (this._publishWebSocket) {
351
+ this._publishWebSocket.close();
352
+ this._publishWebSocket = null;
353
+ }
354
+ process.exit(0);
355
+ }
356
+ exit() {
357
+ this._exit();
358
+ }
359
+ update(options) {
360
+ if (!this._publishWebSocket || !this._isConnected) return;
361
+ const { updateKind, updateMode, updateSourcePaths, clientName } = options;
362
+ fileLog(`update run, ${this._name} module update, updateKind: ${updateKind}, updateMode: ${updateMode}, updateSourcePaths: ${updateSourcePaths}`, MF_SERVER_IDENTIFIER, "info");
363
+ if (updateKind === UpdateKind.RELOAD_PAGE) {
364
+ const notifyWebClient = new NotifyWebClientAction({
365
+ name: clientName || this._name,
366
+ updateMode
367
+ });
368
+ this._publishWebSocket.send(JSON.stringify(notifyWebClient));
369
+ return;
370
+ }
371
+ const updatePublisher = new UpdatePublisherAction({
372
+ name: this._name,
373
+ ip: this._ip,
374
+ updateMode,
375
+ updateKind,
376
+ updateSourcePaths: [this._name],
377
+ remoteTypeTarPath: this._remoteTypeTarPath
378
+ });
379
+ this._publishWebSocket.send(JSON.stringify(updatePublisher));
380
+ }
381
+ async fetchDynamicRemoteTypes(options) {
382
+ const { remoteInfo, once } = options;
383
+ const updateMode = UpdateMode.PASSIVE;
384
+ const updateKind = UpdateKind.UPDATE_TYPE;
385
+ fileLog(`fetchDynamicRemoteTypes: remoteInfo: ${JSON.stringify(remoteInfo)}`, MF_SERVER_IDENTIFIER, "info");
386
+ await this._updateCallback({
387
+ name: this._name,
388
+ updateMode,
389
+ updateKind,
390
+ updateSourcePaths: [],
391
+ remoteTypeTarPath: "",
392
+ remoteInfo,
393
+ once
394
+ });
395
+ const updatePublisher = new UpdatePublisherAction({
396
+ name: this._name,
397
+ ip: this._ip,
398
+ updateMode,
399
+ updateKind,
400
+ updateSourcePaths: [this._name],
401
+ remoteTypeTarPath: this._remoteTypeTarPath
402
+ });
403
+ this._publishWebSocket.send(JSON.stringify(updatePublisher));
404
+ }
405
+ };
406
+
407
+ //#endregion
408
+ //#region src/server/createHttpServer.ts
409
+ async function createHttpServer(options) {
410
+ const { typeTarPath } = options;
411
+ const freeport = await getFreePort();
412
+ const server = http.createServer((req, res) => {
413
+ if ((req.url?.split("?")[0] ?? "/") === `/${DEFAULT_TAR_NAME}`) {
414
+ res.statusCode = 200;
415
+ res.setHeader("Content-Type", "application/x-gzip");
416
+ if (req.method === "HEAD") {
417
+ res.end();
418
+ return;
419
+ }
420
+ const stream = fs.createReadStream(typeTarPath);
421
+ stream.on("error", () => {
422
+ if (!res.headersSent) res.statusCode = 500;
423
+ res.end();
424
+ });
425
+ res.on("close", () => {
426
+ stream.destroy();
427
+ });
428
+ stream.pipe(res);
429
+ return;
430
+ }
431
+ res.statusCode = 404;
432
+ res.end();
433
+ });
434
+ server.listen(freeport);
435
+ return {
436
+ server,
437
+ serverAddress: `http://${getIPV4()}:${freeport}`
438
+ };
439
+ }
440
+
441
+ //#endregion
442
+ //#region src/core/lib/typeScriptResolver.ts
443
+ const parseMajorVersion = (version) => {
444
+ const major = Number.parseInt(version.split(".")[0], 10);
445
+ return Number.isNaN(major) ? 0 : major;
446
+ };
447
+ const isMissingTypeScriptPackage = (error) => typeof error === "object" && error !== null && "code" in error && error.code === "MODULE_NOT_FOUND" && "message" in error && typeof error.message === "string" && error.message.includes("typescript/package.json");
448
+ const resolveTypeScriptPackage = (context = process.cwd()) => {
449
+ const candidateContexts = [...new Set([context, process.cwd()])];
450
+ let missingTypeScriptError;
451
+ for (const candidateContext of candidateContexts) {
452
+ const requireFromContext = createRequire$1(resolve(candidateContext, "package.json"));
453
+ try {
454
+ return {
455
+ packageJsonPath: requireFromContext.resolve("typescript/package.json"),
456
+ packageJson: requireFromContext("typescript/package.json"),
457
+ requireFromContext
458
+ };
459
+ } catch (error) {
460
+ if (!isMissingTypeScriptPackage(error)) throw error;
461
+ missingTypeScriptError = error;
462
+ }
463
+ }
464
+ throw missingTypeScriptError;
465
+ };
466
+ const getTypeScriptPackageInfo = (context = process.cwd()) => {
467
+ const { packageJsonPath, packageJson } = resolveTypeScriptPackage(context);
468
+ const version = packageJson.version || "0.0.0";
469
+ const packageRoot = dirname(packageJsonPath);
470
+ const bin = typeof packageJson.bin === "string" ? packageJson.bin : packageJson.bin?.["tsc"] ?? "./bin/tsc";
471
+ return {
472
+ packageJsonPath,
473
+ packageRoot,
474
+ version,
475
+ majorVersion: parseMajorVersion(version),
476
+ tscBinPath: resolve(packageRoot, bin)
477
+ };
478
+ };
479
+ const requireTypeScript = (context = process.cwd()) => {
480
+ const { requireFromContext } = resolveTypeScriptPackage(context);
481
+ return requireFromContext("typescript");
482
+ };
483
+
484
+ //#endregion
485
+ //#region src/core/lib/typeScriptCompiler.ts
486
+ const STARTS_WITH_SLASH = /^\//;
487
+ const DEFINITION_FILE_EXTENSION = ".d.ts";
488
+ const retrieveMfTypesPath = (tsConfig, remoteOptions) => normalize(tsConfig.compilerOptions.outDir.replace(remoteOptions.compiledTypesFolder, ""));
489
+ const retrieveOriginalOutDir = (tsConfig, remoteOptions) => normalize(tsConfig.compilerOptions.outDir.replace(remoteOptions.compiledTypesFolder, "").replace(remoteOptions.typesFolder, ""));
490
+ const retrieveMfAPITypesPath = (tsConfig, remoteOptions) => join(retrieveOriginalOutDir(tsConfig, remoteOptions), `${remoteOptions.typesFolder}.d.ts`);
491
+ function writeTempTsConfig(tsConfig, context, name, cwd) {
492
+ const createHash = (contents) => {
493
+ return crypto.createHash("md5").update(contents).digest("hex");
494
+ };
495
+ const hash = createHash(`${JSON.stringify(tsConfig)}${name}${Date.now()}`);
496
+ const tempTsConfigJsonPath = resolve(cwd ?? context, "node_modules", TEMP_DIR, `tsconfig.${hash}.json`);
497
+ mkdirSync(dirname(tempTsConfigJsonPath), { recursive: true });
498
+ writeFileSync(tempTsConfigJsonPath, JSON.stringify(tsConfig, null, 2));
499
+ return tempTsConfigJsonPath;
500
+ }
501
+ const removeExt = (f) => {
502
+ const vueExt = ".vue";
503
+ const ext = extname(f);
504
+ if (ext === vueExt) return f;
505
+ const regexPattern = new RegExp(`\\${ext}$`);
506
+ return f.replace(regexPattern, "");
507
+ };
508
+ function getExposeKey(options) {
509
+ const { filePath, rootDir, outDir, mapExposeToEntry } = options;
510
+ return mapExposeToEntry[relative(outDir, filePath.replace(new RegExp(`\\.d.ts$`), ""))];
511
+ }
512
+ const processTypesFile = async (options) => {
513
+ const { outDir, filePath, rootDir, cb, mapExposeToEntry, mfTypePath } = options;
514
+ if (!existsSync(filePath)) return;
515
+ if ((await stat(filePath)).isDirectory()) {
516
+ const files = await readdir(filePath);
517
+ await Promise.all(files.map((file) => processTypesFile({
518
+ ...options,
519
+ filePath: join(filePath, file)
520
+ })));
521
+ } else if (filePath.endsWith(".d.ts")) {
522
+ const exposeKey = getExposeKey({
523
+ filePath,
524
+ rootDir,
525
+ outDir,
526
+ mapExposeToEntry
527
+ });
528
+ if (exposeKey) {
529
+ const mfeTypeEntry = join(mfTypePath, `${exposeKey === "." ? "index" : exposeKey}${DEFINITION_FILE_EXTENSION}`);
530
+ const mfeTypeEntryDirectory = dirname(mfeTypeEntry);
531
+ const relativePathToOutput = relative(mfeTypeEntryDirectory, filePath).replace(DEFINITION_FILE_EXTENSION, "").replace(STARTS_WITH_SLASH, "").split(sep).join("/");
532
+ mkdirSync(mfeTypeEntryDirectory, { recursive: true });
533
+ await writeFile(mfeTypeEntry, `export * from './${relativePathToOutput}';\nexport { default } from './${relativePathToOutput}';`);
534
+ }
535
+ cb(await readFile(filePath, "utf8"));
536
+ }
537
+ };
538
+ const getPMFromUserAgent = () => {
539
+ const userAgent = process.env["npm_config_user_agent"];
540
+ if (userAgent == null) return "null";
541
+ return userAgent.split("/")[0];
542
+ };
543
+ const resolvePackageManagerExecutable = () => {
544
+ switch (getPMFromUserAgent()) {
545
+ case "yarn": return "yarn";
546
+ default: return "npx";
547
+ }
548
+ };
549
+ const splitCommandArgs = (value) => {
550
+ const args = [];
551
+ let current = "";
552
+ let quote = null;
553
+ let escaped = false;
554
+ for (const char of value) {
555
+ if (escaped) {
556
+ current += char;
557
+ escaped = false;
558
+ continue;
559
+ }
560
+ if (char === "\\") {
561
+ escaped = true;
562
+ continue;
563
+ }
564
+ if (quote) {
565
+ if (char === quote) quote = null;
566
+ else current += char;
567
+ continue;
568
+ }
569
+ if (char === "\"" || char === "'") {
570
+ quote = char;
571
+ continue;
572
+ }
573
+ if (char.trim() === "") {
574
+ if (current) {
575
+ args.push(current);
576
+ current = "";
577
+ }
578
+ continue;
579
+ }
580
+ current += char;
581
+ }
582
+ if (current) args.push(current);
583
+ return args;
584
+ };
585
+ const formatCommandForDisplay = (executable, args) => {
586
+ const formatArg = (arg) => {
587
+ if (/[\s'"]/.test(arg)) return JSON.stringify(arg);
588
+ return arg;
589
+ };
590
+ return [executable, ...args].map(formatArg).join(" ");
591
+ };
592
+ const getTypeScriptContext$1 = (remoteOptions) => {
593
+ const dtsOptions = remoteOptions.moduleFederationConfig.dts;
594
+ return typeof dtsOptions !== "boolean" && dtsOptions?.cwd ? dtsOptions.cwd : remoteOptions.context;
595
+ };
596
+ const resolveCompilerCommand = (remoteOptions, tempTsConfigJsonPath) => {
597
+ const compilerArgs = splitCommandArgs(remoteOptions.compilerInstance);
598
+ const resolvedCompilerArgs = compilerArgs.length > 0 ? compilerArgs : [remoteOptions.compilerInstance];
599
+ if (resolvedCompilerArgs[0] === "tsc") {
600
+ const args = [
601
+ getTypeScriptPackageInfo(getTypeScriptContext$1(remoteOptions)).tscBinPath,
602
+ ...resolvedCompilerArgs.slice(1),
603
+ "--project",
604
+ tempTsConfigJsonPath
605
+ ];
606
+ return {
607
+ executable: process.execPath,
608
+ args,
609
+ displayCommand: formatCommandForDisplay(process.execPath, args),
610
+ shell: false
611
+ };
612
+ }
613
+ const executable = resolvePackageManagerExecutable();
614
+ const args = [
615
+ ...resolvedCompilerArgs,
616
+ "--project",
617
+ tempTsConfigJsonPath
618
+ ];
619
+ return {
620
+ executable,
621
+ args,
622
+ displayCommand: formatCommandForDisplay(executable, args),
623
+ shell: process.platform === "win32"
624
+ };
625
+ };
626
+ const compileTs = async (mapComponentsToExpose, tsConfig, remoteOptions) => {
627
+ if (!Object.keys(mapComponentsToExpose).length) return;
628
+ const { compilerOptions } = tsConfig;
629
+ const tempTsConfigJsonPath = writeTempTsConfig(tsConfig, remoteOptions.context, remoteOptions.moduleFederationConfig.name || "mf", typeof remoteOptions.moduleFederationConfig.dts !== "boolean" ? remoteOptions.moduleFederationConfig.dts?.cwd ?? void 0 : void 0);
630
+ logger$1.debug(`tempTsConfigJsonPath: ${tempTsConfigJsonPath}`);
631
+ try {
632
+ const mfTypePath = retrieveMfTypesPath(tsConfig, remoteOptions);
633
+ const thirdPartyExtractor = new ThirdPartyExtractor({
634
+ destDir: resolve(mfTypePath, "node_modules"),
635
+ context: remoteOptions.context,
636
+ exclude: typeof remoteOptions.extractThirdParty === "object" ? remoteOptions.extractThirdParty.exclude : void 0
637
+ });
638
+ const execPromise = util.promisify(execFile);
639
+ const compilerCommand = resolveCompilerCommand(remoteOptions, tempTsConfigJsonPath);
640
+ try {
641
+ await execPromise(compilerCommand.executable, compilerCommand.args, {
642
+ cwd: getTypeScriptContext$1(remoteOptions),
643
+ shell: compilerCommand.shell
644
+ });
645
+ } catch (err) {
646
+ if (compilerOptions.tsBuildInfoFile) try {
647
+ await rm(compilerOptions.tsBuildInfoFile);
648
+ } catch (e) {}
649
+ logAndReport(TYPE_001, typeDescMap, { cmd: compilerCommand.displayCommand }, (msg) => {
650
+ throw new Error(msg);
651
+ }, void 0);
652
+ }
653
+ const mapExposeToEntry = Object.fromEntries(Object.entries(mapComponentsToExpose).map(([exposed, filename]) => {
654
+ const normalizedFileName = normalize(filename);
655
+ let relativeFileName = "";
656
+ if (isAbsolute(normalizedFileName)) relativeFileName = relative(tsConfig.compilerOptions.rootDir, normalizedFileName);
657
+ else relativeFileName = relative(tsConfig.compilerOptions.rootDir, resolve(remoteOptions.context, normalizedFileName));
658
+ return [removeExt(relativeFileName), exposed];
659
+ }));
660
+ const cb = remoteOptions.extractThirdParty ? thirdPartyExtractor.collectPkgs.bind(thirdPartyExtractor) : () => void 0;
661
+ await processTypesFile({
662
+ outDir: compilerOptions.outDir,
663
+ filePath: compilerOptions.outDir,
664
+ rootDir: compilerOptions.rootDir,
665
+ mfTypePath,
666
+ cb,
667
+ mapExposeToEntry
668
+ });
669
+ if (remoteOptions.extractThirdParty) await thirdPartyExtractor.copyDts();
670
+ if (remoteOptions.deleteTsConfig) await rm(tempTsConfigJsonPath);
671
+ } catch (err) {
672
+ throw err;
673
+ }
674
+ };
675
+
676
+ //#endregion
677
+ //#region src/core/lib/archiveHandler.ts
678
+ const retrieveTypesZipPath = (mfTypesPath, remoteOptions) => join(mfTypesPath.replace(remoteOptions.typesFolder, ""), `${remoteOptions.typesFolder}.zip`);
679
+ const createTypesArchive = async (tsConfig, remoteOptions) => {
680
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
681
+ const zip = new AdmZip();
682
+ zip.addLocalFolder(mfTypesPath);
683
+ return zip.writeZipPromise(retrieveTypesZipPath(mfTypesPath, remoteOptions));
684
+ };
685
+ const downloadErrorLogger = (destinationFolder, fileToDownload) => (reason) => {
686
+ throw {
687
+ ...reason,
688
+ message: `Network error: Unable to download federated mocks for '${destinationFolder}' from '${fileToDownload}' because '${reason.message}'`
689
+ };
690
+ };
691
+ const retrieveTypesArchiveDestinationPath = (hostOptions, destinationFolder) => {
692
+ return resolve(hostOptions.context, hostOptions.typesFolder, destinationFolder);
693
+ };
694
+ const downloadTypesArchive = (hostOptions) => {
695
+ let retries = 0;
696
+ return async ([destinationFolder, fileToDownload]) => {
697
+ const destinationPath = retrieveTypesArchiveDestinationPath(hostOptions, destinationFolder);
698
+ while (retries++ < hostOptions.maxRetries) try {
699
+ const url = new URL(fileToDownload).href;
700
+ const response = await nativeFetch(url, {
701
+ responseType: "arraybuffer",
702
+ timeout: hostOptions.timeout,
703
+ family: hostOptions.family
704
+ }).catch(downloadErrorLogger(destinationFolder, url));
705
+ if (typeof response.headers?.["content-type"] === "string" && response.headers["content-type"].includes("text/html")) throw new Error(`${url} receives invalid content-type: ${response.headers["content-type"]}`);
706
+ try {
707
+ if (hostOptions.deleteTypesFolder) await rm(destinationPath, {
708
+ recursive: true,
709
+ force: true
710
+ });
711
+ } catch (error) {
712
+ fileLog(`Unable to remove types folder, ${error}`, "downloadTypesArchive", "error");
713
+ }
714
+ new AdmZip(Buffer.from(response.data)).extractAllTo(destinationPath, true);
715
+ fileLog(`zip.extractAllTo success destinationPath: ${destinationPath}; url: ${url}`, "downloadTypesArchive", "info");
716
+ return [destinationFolder, destinationPath];
717
+ } catch (error) {
718
+ fileLog(`Error during types archive download: ${error?.message || "unknown error"}`, "downloadTypesArchive", "error");
719
+ if (retries >= hostOptions.maxRetries) {
720
+ logger$1.error(`Failed to download types archive from "${fileToDownload}". Set FEDERATION_DEBUG=true for details.`);
721
+ if (hostOptions.abortOnError !== false) throw error;
722
+ return;
723
+ }
724
+ }
725
+ };
726
+ };
727
+
728
+ //#endregion
729
+ //#region src/core/configurations/hostPlugin.ts
730
+ const defaultOptions$1 = {
731
+ typesFolder: "@mf-types",
732
+ remoteTypesFolder: "@mf-types",
733
+ deleteTypesFolder: true,
734
+ maxRetries: 3,
735
+ implementation: "",
736
+ context: process.cwd(),
737
+ abortOnError: true,
738
+ consumeAPITypes: false,
739
+ runtimePkgs: [],
740
+ remoteTypeUrls: {},
741
+ timeout: 6e4,
742
+ typesOnBuild: false,
743
+ family: 0
744
+ };
745
+ const buildZipUrl = (hostOptions, url) => {
746
+ const remoteUrl = new URL(url, "file:");
747
+ remoteUrl.pathname = `${remoteUrl.pathname.split("/").slice(0, -1).join("/")}/${hostOptions.remoteTypesFolder}.zip`;
748
+ return remoteUrl.protocol === "file:" ? remoteUrl.pathname : remoteUrl.href;
749
+ };
750
+ const buildApiTypeUrl = (zipUrl) => {
751
+ if (!zipUrl) return;
752
+ return zipUrl.replace(".zip", ".d.ts");
753
+ };
754
+ const retrieveRemoteInfo = (options) => {
755
+ const { hostOptions, remoteAlias, remote } = options;
756
+ const { remoteTypeUrls } = hostOptions;
757
+ let decodedRemote = remote;
758
+ if (decodedRemote.startsWith(ENCODE_NAME_PREFIX)) decodedRemote = decodeName(decodedRemote, ENCODE_NAME_PREFIX);
759
+ const parsedInfo = parseEntry(decodedRemote, void 0, "@");
760
+ const url = "entry" in parsedInfo ? parsedInfo.entry : parsedInfo.name === decodedRemote ? decodedRemote : "";
761
+ let zipUrl = "";
762
+ let apiTypeUrl = "";
763
+ const name = parsedInfo.name || remoteAlias;
764
+ const remoteTypeUrl = typeof remoteTypeUrls === "object" && remoteTypeUrls[name];
765
+ if (remoteTypeUrl) {
766
+ zipUrl = remoteTypeUrl.zip;
767
+ apiTypeUrl = remoteTypeUrl.api;
768
+ }
769
+ const shouldResolveTypeUrlsByConvention = Boolean(url && !url.includes(MANIFEST_EXT));
770
+ if (!zipUrl && shouldResolveTypeUrlsByConvention) zipUrl = buildZipUrl(hostOptions, url);
771
+ if (!apiTypeUrl && zipUrl && (remoteTypeUrl || shouldResolveTypeUrlsByConvention)) apiTypeUrl = buildApiTypeUrl(zipUrl);
772
+ return {
773
+ name,
774
+ url,
775
+ zipUrl,
776
+ apiTypeUrl,
777
+ alias: remoteAlias
778
+ };
779
+ };
780
+ const resolveRemotes = (hostOptions) => {
781
+ const parsedOptions = utils.parseOptions(hostOptions.moduleFederationConfig.remotes || {}, (item, key) => ({
782
+ remote: Array.isArray(item) ? item[0] : item,
783
+ key
784
+ }), (item, key) => ({
785
+ remote: Array.isArray(item.external) ? item.external[0] : item.external,
786
+ key
787
+ }));
788
+ const remoteTypeUrls = hostOptions.remoteTypeUrls ?? {};
789
+ if (typeof remoteTypeUrls !== "object") throw new Error("remoteTypeUrls must be consumed before resolveRemotes");
790
+ const remoteInfos = Object.keys(remoteTypeUrls).reduce((sum, remoteName) => {
791
+ const { zip, api, alias } = remoteTypeUrls[remoteName];
792
+ sum[alias] = {
793
+ name: remoteName,
794
+ url: "",
795
+ zipUrl: zip,
796
+ apiTypeUrl: api,
797
+ alias: alias || remoteName
798
+ };
799
+ return sum;
800
+ }, {});
801
+ return parsedOptions.reduce((accumulator, item) => {
802
+ const { key, remote } = item[1];
803
+ const res = retrieveRemoteInfo({
804
+ hostOptions,
805
+ remoteAlias: key,
806
+ remote
807
+ });
808
+ if (accumulator[key]) {
809
+ accumulator[key] = {
810
+ ...accumulator[key],
811
+ url: res.url,
812
+ apiTypeUrl: accumulator[key].apiTypeUrl || res.apiTypeUrl
813
+ };
814
+ return accumulator;
815
+ }
816
+ accumulator[key] = res;
817
+ return accumulator;
818
+ }, remoteInfos);
819
+ };
820
+ const retrieveHostConfig = (options) => {
821
+ validateOptions(options);
822
+ const hostOptions = {
823
+ ...defaultOptions$1,
824
+ ...options
825
+ };
826
+ return {
827
+ hostOptions,
828
+ mapRemotesToDownload: resolveRemotes(hostOptions)
829
+ };
830
+ };
831
+
832
+ //#endregion
833
+ //#region src/core/constant.ts
834
+ const REMOTE_ALIAS_IDENTIFIER = "REMOTE_ALIAS_IDENTIFIER";
835
+ const REMOTE_API_TYPES_FILE_NAME = "apis.d.ts";
836
+ const HOST_API_TYPES_FILE_NAME = "index.d.ts";
837
+
838
+ //#endregion
839
+ //#region src/core/lib/DTSManager.ts
840
+ var DTSManager = class {
841
+ constructor(options) {
842
+ this.options = cloneDeepOptions(options);
843
+ this.runtimePkgs = [
844
+ "@module-federation/runtime",
845
+ "@module-federation/enhanced/runtime",
846
+ "@module-federation/runtime-tools"
847
+ ];
848
+ this.loadedRemoteAPIAlias = /* @__PURE__ */ new Set();
849
+ this.remoteAliasMap = {};
850
+ this.extraOptions = options?.extraOptions || {};
851
+ this.updatedRemoteInfos = {};
852
+ }
853
+ generateAPITypes(mapComponentsToExpose) {
854
+ const exposePaths = /* @__PURE__ */ new Set();
855
+ const packageType = Object.keys(mapComponentsToExpose).reduce((sum, exposeKey) => {
856
+ const exposePath = path.join(REMOTE_ALIAS_IDENTIFIER, exposeKey).split(path.sep).join("/");
857
+ exposePaths.add(`'${exposePath}'`);
858
+ sum = `T extends '${exposePath}' ? typeof import('${exposePath}') :` + sum;
859
+ return sum;
860
+ }, "any;");
861
+ return `
862
+ export type RemoteKeys = ${[...exposePaths].join(" | ")};
863
+ type PackageType<T> = ${packageType}`;
864
+ }
865
+ async extractRemoteTypes(options) {
866
+ const { remoteOptions, tsConfig } = options;
867
+ if (!remoteOptions.extractRemoteTypes) return;
868
+ let hasRemotes = false;
869
+ const remotes = remoteOptions.moduleFederationConfig.remotes;
870
+ if (remotes) {
871
+ if (Array.isArray(remotes)) hasRemotes = Boolean(remotes.length);
872
+ else if (typeof remotes === "object") hasRemotes = Boolean(Object.keys(remotes).length);
873
+ }
874
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
875
+ if (hasRemotes && this.options.host) try {
876
+ const { hostOptions } = retrieveHostConfig(this.options.host);
877
+ const remoteTypesFolder = path.resolve(hostOptions.context, hostOptions.typesFolder);
878
+ const targetDir = path.join(mfTypesPath, "node_modules");
879
+ if (fs.existsSync(remoteTypesFolder)) {
880
+ const targetFolder = path.resolve(remoteOptions.context, targetDir);
881
+ await mkdir(targetFolder, { recursive: true });
882
+ await cp(remoteTypesFolder, targetFolder, {
883
+ recursive: true,
884
+ force: true
885
+ });
886
+ }
887
+ } catch (err) {
888
+ if (this.options.host?.abortOnError === false) fileLog(`Unable to copy remote types, ${err}`, "extractRemoteTypes", "error");
889
+ else throw err;
890
+ }
891
+ }
892
+ async generateTypes() {
893
+ try {
894
+ const { options } = this;
895
+ if (!options.remote) throw new Error("options.remote is required if you want to generateTypes");
896
+ const { remoteOptions, tsConfig, mapComponentsToExpose } = retrieveRemoteConfig(options.remote);
897
+ if (!Object.keys(mapComponentsToExpose).length) return;
898
+ if (!tsConfig.files?.length) {
899
+ logger$1.info("No type files to compile, skip");
900
+ return;
901
+ }
902
+ if (tsConfig.compilerOptions.tsBuildInfoFile) try {
903
+ const tsBuildInfoFile = path.resolve(remoteOptions.context, tsConfig.compilerOptions.tsBuildInfoFile);
904
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
905
+ if (!fs.existsSync(mfTypesPath)) fs.rmSync(tsBuildInfoFile, { force: true });
906
+ } catch (e) {}
907
+ await this.extractRemoteTypes({
908
+ remoteOptions,
909
+ tsConfig,
910
+ mapComponentsToExpose
911
+ });
912
+ await compileTs(mapComponentsToExpose, tsConfig, remoteOptions);
913
+ await createTypesArchive(tsConfig, remoteOptions);
914
+ let apiTypesPath = "";
915
+ if (remoteOptions.generateAPITypes) {
916
+ const apiTypes = this.generateAPITypes(mapComponentsToExpose);
917
+ apiTypesPath = retrieveMfAPITypesPath(tsConfig, remoteOptions);
918
+ fs.writeFileSync(apiTypesPath, apiTypes);
919
+ }
920
+ try {
921
+ if (remoteOptions.deleteTypesFolder) await rm(retrieveMfTypesPath(tsConfig, remoteOptions), {
922
+ recursive: true,
923
+ force: true
924
+ });
925
+ } catch (err) {
926
+ if (isDebugMode()) console.error(err);
927
+ }
928
+ logger$1.success("Federated types created correctly");
929
+ } catch (error) {
930
+ if (this.options.remote?.abortOnError === false) {
931
+ if (this.options.displayErrorInTerminal) logger$1.error(error);
932
+ } else throw error;
933
+ }
934
+ }
935
+ async requestRemoteManifest(remoteInfo, hostOptions) {
936
+ try {
937
+ if (!remoteInfo.url.includes(MANIFEST_EXT)) return remoteInfo;
938
+ if (remoteInfo.zipUrl) return remoteInfo;
939
+ const url = remoteInfo.url;
940
+ const manifestJson = (await nativeFetch(url, {
941
+ timeout: hostOptions.timeout,
942
+ family: hostOptions.family
943
+ })).data;
944
+ if (!manifestJson.metaData.types.zip) throw new Error(`Can not get ${remoteInfo.name}'s types archive url!`);
945
+ const addProtocol = (u) => {
946
+ if (u.startsWith("//")) return `https:${u}`;
947
+ return u;
948
+ };
949
+ let publicPath;
950
+ if ("publicPath" in manifestJson.metaData) publicPath = manifestJson.metaData.publicPath;
951
+ else {
952
+ const getPublicPath = new Function(manifestJson.metaData.getPublicPath);
953
+ if (manifestJson.metaData.getPublicPath.startsWith("function")) publicPath = getPublicPath()();
954
+ else publicPath = getPublicPath();
955
+ }
956
+ if (publicPath === "auto") publicPath = inferAutoPublicPath(remoteInfo.url);
957
+ const normalizedPublicPath = addProtocol(publicPath).endsWith("/") ? addProtocol(publicPath) : `${addProtocol(publicPath)}/`;
958
+ remoteInfo.zipUrl = new URL(manifestJson.metaData.types.zip, normalizedPublicPath).href;
959
+ if (!manifestJson.metaData.types.api) {
960
+ console.warn(`Can not get ${remoteInfo.name}'s api types url!`);
961
+ remoteInfo.apiTypeUrl = "";
962
+ return remoteInfo;
963
+ }
964
+ remoteInfo.apiTypeUrl = new URL(manifestJson.metaData.types.api, normalizedPublicPath).href;
965
+ return remoteInfo;
966
+ } catch (_err) {
967
+ fileLog(`fetch manifest failed, ${_err}, ${remoteInfo.name} will be ignored`, "requestRemoteManifest", "error");
968
+ return remoteInfo;
969
+ }
970
+ }
971
+ async consumeTargetRemotes(hostOptions, remoteInfo) {
972
+ if (!remoteInfo.zipUrl) throw new Error(`Can not get ${remoteInfo.name}'s types archive url!`);
973
+ return downloadTypesArchive(hostOptions)([remoteInfo.alias, remoteInfo.zipUrl]);
974
+ }
975
+ async downloadAPITypes(remoteInfo, destinationPath, hostOptions) {
976
+ const { apiTypeUrl } = remoteInfo;
977
+ if (!apiTypeUrl) return;
978
+ try {
979
+ let apiTypeFile = (await nativeFetch(apiTypeUrl, {
980
+ timeout: hostOptions.timeout,
981
+ family: hostOptions.family
982
+ })).data;
983
+ apiTypeFile = apiTypeFile.replaceAll(REMOTE_ALIAS_IDENTIFIER, remoteInfo.alias);
984
+ const filePath = path.join(destinationPath, REMOTE_API_TYPES_FILE_NAME);
985
+ fs.writeFileSync(filePath, apiTypeFile);
986
+ const existed = this.loadedRemoteAPIAlias.has(remoteInfo.alias);
987
+ this.loadedRemoteAPIAlias.add(remoteInfo.alias);
988
+ fileLog(`success`, "downloadAPITypes", "info");
989
+ return existed;
990
+ } catch (err) {
991
+ fileLog(`Unable to download "${remoteInfo.name}" api types, ${err}`, "downloadAPITypes", "error");
992
+ }
993
+ }
994
+ consumeAPITypes(hostOptions) {
995
+ const apiTypeFileName = path.join(hostOptions.context, hostOptions.typesFolder, HOST_API_TYPES_FILE_NAME);
996
+ try {
997
+ const existedFile = fs.readFileSync(apiTypeFileName, "utf-8");
998
+ new ThirdPartyExtractor({ destDir: "" }).collectTypeImports(existedFile).forEach((existedImport) => {
999
+ const alias = existedImport.split("./").slice(1).join("./").replace("/apis.d.ts", "");
1000
+ this.loadedRemoteAPIAlias.add(alias);
1001
+ });
1002
+ } catch (err) {}
1003
+ if (!this.loadedRemoteAPIAlias.size) return;
1004
+ const packageTypes = [];
1005
+ const remoteKeys = [];
1006
+ const importTypeStr = [...this.loadedRemoteAPIAlias].sort().map((alias, index) => {
1007
+ const remoteKey = `RemoteKeys_${index}`;
1008
+ const packageType = `PackageType_${index}`;
1009
+ packageTypes.push(`T extends ${remoteKey} ? ${packageType}<T>`);
1010
+ remoteKeys.push(remoteKey);
1011
+ return `import type { PackageType as ${packageType},RemoteKeys as ${remoteKey} } from './${alias}/apis.d.ts';`;
1012
+ }).join("\n");
1013
+ const remoteKeysStr = `type RemoteKeys = ${remoteKeys.join(" | ")};`;
1014
+ const packageTypesStr = `type PackageType<T, Y=any> = ${[...packageTypes, "Y"].join(" :\n")} ;`;
1015
+ const runtimePkgs = /* @__PURE__ */ new Set();
1016
+ [...this.runtimePkgs, ...hostOptions.runtimePkgs].forEach((pkg) => {
1017
+ runtimePkgs.add(pkg);
1018
+ });
1019
+ const fileStr = `${importTypeStr}
1020
+ ${[...runtimePkgs].map((pkg) => {
1021
+ return `declare module "${pkg}" {
1022
+ ${remoteKeysStr}
1023
+ ${packageTypesStr}
1024
+ export function loadRemote<T extends RemoteKeys,Y>(packageName: T): Promise<PackageType<T, Y>>;
1025
+ export function loadRemote<T extends string,Y>(packageName: T): Promise<PackageType<T, Y>>;
1026
+ }`;
1027
+ }).join("\n")}
1028
+ `;
1029
+ fs.writeFileSync(path.join(hostOptions.context, hostOptions.typesFolder, HOST_API_TYPES_FILE_NAME), fileStr);
1030
+ }
1031
+ async consumeArchiveTypes(options) {
1032
+ const { hostOptions, mapRemotesToDownload } = retrieveHostConfig(options);
1033
+ const downloadPromises = Object.entries(mapRemotesToDownload).map(async (item) => {
1034
+ const remoteInfo = item[1];
1035
+ if (!this.remoteAliasMap[remoteInfo.alias]) {
1036
+ const requiredRemoteInfo = await this.requestRemoteManifest(remoteInfo, hostOptions);
1037
+ this.remoteAliasMap[remoteInfo.alias] = requiredRemoteInfo;
1038
+ }
1039
+ return this.consumeTargetRemotes(hostOptions, this.remoteAliasMap[remoteInfo.alias]);
1040
+ });
1041
+ return {
1042
+ hostOptions,
1043
+ downloadPromisesResult: await Promise.allSettled(downloadPromises)
1044
+ };
1045
+ }
1046
+ async consumeTypes() {
1047
+ try {
1048
+ const { options } = this;
1049
+ if (!options.host) throw new Error("options.host is required if you want to consumeTypes");
1050
+ const { mapRemotesToDownload } = retrieveHostConfig(options.host);
1051
+ if (!Object.keys(mapRemotesToDownload).length) return;
1052
+ const { downloadPromisesResult, hostOptions } = await this.consumeArchiveTypes(options.host);
1053
+ if (hostOptions.consumeAPITypes) {
1054
+ await Promise.all(downloadPromisesResult.map(async (item) => {
1055
+ if (item.status === "rejected" || !item.value) return;
1056
+ const [alias, destinationPath] = item.value;
1057
+ const remoteInfo = this.remoteAliasMap[alias];
1058
+ if (!remoteInfo) return;
1059
+ await this.downloadAPITypes(remoteInfo, destinationPath, hostOptions);
1060
+ }));
1061
+ this.consumeAPITypes(hostOptions);
1062
+ }
1063
+ logger$1.success("Federated types extraction completed");
1064
+ } catch (err) {
1065
+ if (this.options.host?.abortOnError === false) fileLog(`Unable to consume federated types, ${err}`, "consumeTypes", "error");
1066
+ else throw err;
1067
+ }
1068
+ }
1069
+ async updateTypes(options) {
1070
+ try {
1071
+ const { remoteName, updateMode, remoteTarPath, remoteInfo: updatedRemoteInfo, once } = options;
1072
+ const hostName = this.options?.host?.moduleFederationConfig?.name;
1073
+ fileLog(`options: ${JSON.stringify(options, null, 2)};\nhostName: ${hostName}`, "updateTypes", "info");
1074
+ if (updateMode === UpdateMode.POSITIVE && remoteName === hostName) {
1075
+ if (!this.options.remote) return;
1076
+ await this.generateTypes();
1077
+ } else {
1078
+ const { remoteAliasMap } = this;
1079
+ if (!this.options.host) return;
1080
+ const { hostOptions, mapRemotesToDownload } = retrieveHostConfig(this.options.host);
1081
+ const loadedRemoteInfo = Object.values(remoteAliasMap).find((i) => i.name === remoteName);
1082
+ const consumeTypes = async (requiredRemoteInfo) => {
1083
+ fileLog(`consumeTypes start`, "updateTypes", "info");
1084
+ if (!requiredRemoteInfo.zipUrl) throw new Error(`Can not get ${requiredRemoteInfo.name}'s types archive url!`);
1085
+ const [_alias, destinationPath] = await this.consumeTargetRemotes(hostOptions, {
1086
+ ...requiredRemoteInfo,
1087
+ zipUrl: remoteTarPath || requiredRemoteInfo.zipUrl
1088
+ });
1089
+ if (await this.downloadAPITypes(requiredRemoteInfo, destinationPath, hostOptions)) this.consumeAPITypes(hostOptions);
1090
+ fileLog(`consumeTypes end`, "updateTypes", "info");
1091
+ };
1092
+ fileLog(`loadedRemoteInfo: ${JSON.stringify(loadedRemoteInfo, null, 2)}`, "updateTypes", "info");
1093
+ if (!loadedRemoteInfo) {
1094
+ const remoteInfo = Object.values(mapRemotesToDownload).find((item) => {
1095
+ return item.name === remoteName;
1096
+ });
1097
+ fileLog(`remoteInfo: ${JSON.stringify(remoteInfo, null, 2)}`, "updateTypes", "info");
1098
+ if (remoteInfo) {
1099
+ if (!this.remoteAliasMap[remoteInfo.alias]) {
1100
+ const requiredRemoteInfo = await this.requestRemoteManifest(remoteInfo, hostOptions);
1101
+ this.remoteAliasMap[remoteInfo.alias] = requiredRemoteInfo;
1102
+ }
1103
+ await consumeTypes(this.remoteAliasMap[remoteInfo.alias]);
1104
+ } else if (updatedRemoteInfo) {
1105
+ const consumeDynamicRemoteTypes = async () => {
1106
+ await consumeTypes(this.updatedRemoteInfos[updatedRemoteInfo.name]);
1107
+ };
1108
+ if (!this.updatedRemoteInfos[updatedRemoteInfo.name]) {
1109
+ const parsedRemoteInfo = retrieveRemoteInfo({
1110
+ hostOptions,
1111
+ remoteAlias: updatedRemoteInfo.alias || updatedRemoteInfo.name,
1112
+ remote: updatedRemoteInfo.url
1113
+ });
1114
+ fileLog(`start request manifest`, "consumeTypes", "info");
1115
+ this.updatedRemoteInfos[updatedRemoteInfo.name] = await this.requestRemoteManifest(parsedRemoteInfo, hostOptions);
1116
+ fileLog(`end request manifest, this.updatedRemoteInfos[updatedRemoteInfo.name]: ${JSON.stringify(this.updatedRemoteInfos[updatedRemoteInfo.name], null, 2)}`, "updateTypes", "info");
1117
+ await consumeDynamicRemoteTypes();
1118
+ }
1119
+ if (!once && this.updatedRemoteInfos[updatedRemoteInfo.name]) await consumeDynamicRemoteTypes();
1120
+ }
1121
+ } else await consumeTypes(loadedRemoteInfo);
1122
+ }
1123
+ } catch (err) {
1124
+ fileLog(`updateTypes fail, ${err}`, "updateTypes", "error");
1125
+ }
1126
+ }
1127
+ };
1128
+
1129
+ //#endregion
1130
+ //#region src/core/lib/utils.ts
1131
+ const dispatcherCache = /* @__PURE__ */ new Map();
1132
+ function getDTSManagerConstructor(implementation) {
1133
+ if (implementation) {
1134
+ const NewConstructor = __require(implementation);
1135
+ return NewConstructor.default ? NewConstructor.default : NewConstructor;
1136
+ }
1137
+ return DTSManager;
1138
+ }
1139
+ const validateOptions = (options) => {
1140
+ if (!options.moduleFederationConfig) throw new Error("moduleFederationConfig is required");
1141
+ };
1142
+ function retrieveTypesAssetsInfo(options) {
1143
+ let apiTypesPath = "";
1144
+ let zipTypesPath = "";
1145
+ try {
1146
+ const { tsConfig, remoteOptions, mapComponentsToExpose } = retrieveRemoteConfig(options);
1147
+ if (!Object.keys(mapComponentsToExpose).length || !tsConfig.files.length) return {
1148
+ apiTypesPath,
1149
+ zipTypesPath,
1150
+ zipName: "",
1151
+ apiFileName: ""
1152
+ };
1153
+ zipTypesPath = retrieveTypesZipPath(retrieveMfTypesPath(tsConfig, remoteOptions), remoteOptions);
1154
+ if (remoteOptions.generateAPITypes) apiTypesPath = retrieveMfAPITypesPath(tsConfig, remoteOptions);
1155
+ return {
1156
+ apiTypesPath,
1157
+ zipTypesPath,
1158
+ zipName: path.basename(zipTypesPath),
1159
+ apiFileName: path.basename(apiTypesPath)
1160
+ };
1161
+ } catch (err) {
1162
+ console.error(styleText("red", `Unable to compile federated types, ${err}`));
1163
+ return {
1164
+ apiTypesPath: "",
1165
+ zipTypesPath: "",
1166
+ zipName: "",
1167
+ apiFileName: ""
1168
+ };
1169
+ }
1170
+ }
1171
+ function isDebugMode() {
1172
+ return Boolean(process.env["FEDERATION_DEBUG"]) || process.env["NODE_ENV"] === "test";
1173
+ }
1174
+ const isTSProject = (dtsOptions, context = process.cwd()) => {
1175
+ if (dtsOptions === false) return false;
1176
+ try {
1177
+ let filepath = "";
1178
+ if (typeof dtsOptions === "object" && dtsOptions.tsConfigPath) filepath = dtsOptions.tsConfigPath;
1179
+ else filepath = path.resolve(context, "./tsconfig.json");
1180
+ if (!path.isAbsolute(filepath)) filepath = path.resolve(context, filepath);
1181
+ return fs.existsSync(filepath);
1182
+ } catch (err) {
1183
+ return false;
1184
+ }
1185
+ };
1186
+ function cloneDeepOptions(options) {
1187
+ const excludeKeys = new Set(["manifest", "async"]);
1188
+ const cache = /* @__PURE__ */ new WeakMap();
1189
+ function sanitize(val, key) {
1190
+ if (key !== void 0 && excludeKeys.has(key) || typeof val === "function") return false;
1191
+ if (key === "extractThirdParty" && Array.isArray(val)) return val.map(String);
1192
+ if (Array.isArray(val)) {
1193
+ if (cache.has(val)) return cache.get(val);
1194
+ const out = [];
1195
+ cache.set(val, out);
1196
+ val.forEach((v, i) => out.push(sanitize(v, String(i))));
1197
+ return out;
1198
+ }
1199
+ if (val !== null && typeof val === "object" && Object.getPrototypeOf(val) === Object.prototype) {
1200
+ const obj = val;
1201
+ if (cache.has(obj)) return cache.get(obj);
1202
+ const out = {};
1203
+ cache.set(obj, out);
1204
+ for (const [k, v] of Object.entries(obj)) out[k] = sanitize(v, k);
1205
+ return out;
1206
+ }
1207
+ return val;
1208
+ }
1209
+ return structuredClone(sanitize(options));
1210
+ }
1211
+ const getEnvHeaders = () => {
1212
+ const headersStr = getProcessEnv()["MF_ENV_HEADERS"];
1213
+ if (!headersStr || headersStr === "undefined") return {};
1214
+ try {
1215
+ return { ...JSON.parse(headersStr) };
1216
+ } catch {
1217
+ return {};
1218
+ }
1219
+ };
1220
+ const createDispatcherFromFamily = (family) => {
1221
+ if (!family) return void 0;
1222
+ if (dispatcherCache.has(family)) return dispatcherCache.get(family);
1223
+ try {
1224
+ const dispatcher = new Agent({ connect: { family } });
1225
+ dispatcherCache.set(family, dispatcher);
1226
+ return dispatcher;
1227
+ } catch {}
1228
+ };
1229
+ const toHeaderRecord = (headers) => {
1230
+ const out = {};
1231
+ headers.forEach((value, key) => {
1232
+ out[key.toLowerCase()] = value;
1233
+ });
1234
+ return out;
1235
+ };
1236
+ async function nativeFetch(url, config) {
1237
+ const controller = new AbortController();
1238
+ const timeoutMs = config?.timeout ?? 6e4;
1239
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
1240
+ const headers = {
1241
+ ...getEnvHeaders(),
1242
+ ...config?.headers ?? {}
1243
+ };
1244
+ const dispatcher = config?.dispatcher ?? createDispatcherFromFamily(config?.family);
1245
+ try {
1246
+ const resp = await fetch(url, {
1247
+ headers,
1248
+ signal: controller.signal,
1249
+ ...dispatcher ? { dispatcher } : {},
1250
+ ...config?.agent ? { agent: config.agent } : {}
1251
+ });
1252
+ const headerRecord = toHeaderRecord(resp.headers);
1253
+ if (!resp.ok) throw new Error(`Request failed with status ${resp.status}`);
1254
+ if (config?.responseType === "arraybuffer") return {
1255
+ data: await resp.arrayBuffer(),
1256
+ headers: headerRecord,
1257
+ status: resp.status
1258
+ };
1259
+ return {
1260
+ data: (resp.headers.get("content-type") || "").includes("application/json") || url.endsWith(".json") ? await resp.json() : await resp.text(),
1261
+ headers: headerRecord,
1262
+ status: resp.status
1263
+ };
1264
+ } finally {
1265
+ clearTimeout(timeoutId);
1266
+ }
1267
+ }
1268
+
1269
+ //#endregion
1270
+ //#region src/core/configurations/remotePlugin.ts
1271
+ const defaultOptions = {
1272
+ tsConfigPath: "./tsconfig.json",
1273
+ typesFolder: "@mf-types",
1274
+ compiledTypesFolder: "compiled-types",
1275
+ hostRemoteTypesFolder: "@mf-types",
1276
+ deleteTypesFolder: true,
1277
+ additionalFilesToCompile: [],
1278
+ compilerInstance: "tsc",
1279
+ compileInChildProcess: false,
1280
+ implementation: "",
1281
+ generateAPITypes: false,
1282
+ context: process.cwd(),
1283
+ abortOnError: true,
1284
+ extractRemoteTypes: false,
1285
+ extractThirdParty: false,
1286
+ outputDir: "",
1287
+ deleteTsConfig: true
1288
+ };
1289
+ function getEffectiveRootDir(parsedCommandLine) {
1290
+ const compilerOptions = parsedCommandLine.options;
1291
+ if (compilerOptions.rootDir) return compilerOptions.rootDir;
1292
+ const files = parsedCommandLine.fileNames;
1293
+ if (files.length > 0) return files.map((file) => dirname(file)).reduce((commonPath, fileDir) => {
1294
+ while (!fileDir.startsWith(commonPath)) commonPath = dirname(commonPath);
1295
+ return commonPath;
1296
+ }, files[0]);
1297
+ if (parsedCommandLine.projectReferences.length) {
1298
+ const relativeReferences = parsedCommandLine.projectReferences.filter((reference) => !isAbsolute(reference.originalPath ?? reference.path));
1299
+ const referencesForRoot = relativeReferences.length ? relativeReferences : parsedCommandLine.projectReferences;
1300
+ return referencesForRoot.map((reference) => dirname(reference.path)).reduce((commonPath, filePath) => {
1301
+ while (!filePath.startsWith(commonPath)) commonPath = dirname(commonPath);
1302
+ return commonPath;
1303
+ }, dirname(referencesForRoot[0].path));
1304
+ }
1305
+ throw new Error("Can not get effective rootDir, please set compilerOptions.rootDir !");
1306
+ }
1307
+ const getDependentFiles = (rootFiles, configContent, rootDir, typescript) => {
1308
+ const dependentFiles = typescript.createProgram(rootFiles, configContent.options).getSourceFiles().map((file) => file.fileName).filter((file) => !file.endsWith(".d.ts") && isFileWithinRootDir(file, rootDir)).map((file) => normalizeFileToRootDir(file, rootDir));
1309
+ return dependentFiles.length ? dependentFiles : rootFiles;
1310
+ };
1311
+ const normalizeForComparison = (value) => {
1312
+ try {
1313
+ return normalize(realpathSync.native(value));
1314
+ } catch {
1315
+ return normalize(value);
1316
+ }
1317
+ };
1318
+ const isFileWithinRootDir = (file, rootDir) => {
1319
+ const normalizedFile = normalizeForComparison(file);
1320
+ const normalizedRootDir = normalizeForComparison(rootDir);
1321
+ return normalizedFile === normalizedRootDir || normalizedFile.startsWith(normalizedRootDir.endsWith(sep) ? normalizedRootDir : `${normalizedRootDir}${sep}`);
1322
+ };
1323
+ const normalizeFileToRootDir = (file, rootDir) => {
1324
+ const normalizedFile = normalizeForComparison(file);
1325
+ const normalizedRootDir = normalizeForComparison(rootDir);
1326
+ if (normalizedFile === normalizedRootDir || normalizedFile.startsWith(normalizedRootDir.endsWith(sep) ? normalizedRootDir : `${normalizedRootDir}${sep}`)) return normalize(join(rootDir, relative(normalizedRootDir, normalizedFile)));
1327
+ return normalize(file);
1328
+ };
1329
+ const getTypeScriptContext = ({ context, moduleFederationConfig }) => {
1330
+ const dtsOptions = moduleFederationConfig.dts;
1331
+ return typeof dtsOptions !== "boolean" && dtsOptions?.cwd ? dtsOptions.cwd : context;
1332
+ };
1333
+ const resolveFromConfigDir = (value, configDir) => {
1334
+ if (typeof value !== "string") return value;
1335
+ return isAbsolute(value) ? normalize(value) : resolve(configDir, value);
1336
+ };
1337
+ const normalizeCompilerOptions = (compilerOptions = {}, configDir) => {
1338
+ const normalizedOptions = { ...compilerOptions };
1339
+ for (const pathOption of [
1340
+ "rootDir",
1341
+ "outDir",
1342
+ "declarationDir",
1343
+ "tsBuildInfoFile"
1344
+ ]) if (typeof normalizedOptions[pathOption] === "string") normalizedOptions[pathOption] = resolveFromConfigDir(normalizedOptions[pathOption], configDir);
1345
+ if (normalizedOptions["moduleResolution"] === "node" || normalizedOptions["moduleResolution"] === "node10") normalizedOptions["moduleResolution"] = "bundler";
1346
+ return normalizedOptions;
1347
+ };
1348
+ const parseShowConfigOutput = (stdout, resolvedTsConfigPath) => {
1349
+ const configDir = dirname(resolvedTsConfigPath);
1350
+ const shownConfig = JSON.parse(stdout);
1351
+ const compilerOptions = normalizeCompilerOptions(shownConfig.compilerOptions, configDir);
1352
+ const fileNames = (shownConfig.files || []).map((file) => resolveFromConfigDir(file, configDir));
1353
+ const projectReferences = (shownConfig.references || []).map((reference) => ({
1354
+ ...reference,
1355
+ path: resolveFromConfigDir(reference.path, configDir),
1356
+ originalPath: reference.path
1357
+ }));
1358
+ return {
1359
+ rawTsConfigJson: {
1360
+ ...shownConfig,
1361
+ compilerOptions
1362
+ },
1363
+ configContent: {
1364
+ options: compilerOptions,
1365
+ fileNames,
1366
+ projectReferences
1367
+ }
1368
+ };
1369
+ };
1370
+ const readTsConfigWithTsc = (resolvedTsConfigPath, typeScriptContext) => {
1371
+ const typeScriptPackageInfo = getTypeScriptPackageInfo(typeScriptContext);
1372
+ return parseShowConfigOutput(execFileSync(process.execPath, [
1373
+ typeScriptPackageInfo.tscBinPath,
1374
+ "--showConfig",
1375
+ "--project",
1376
+ resolvedTsConfigPath
1377
+ ], {
1378
+ cwd: typeScriptContext,
1379
+ encoding: "utf8",
1380
+ stdio: [
1381
+ "ignore",
1382
+ "pipe",
1383
+ "pipe"
1384
+ ]
1385
+ }), resolvedTsConfigPath);
1386
+ };
1387
+ const writeListFilesTsConfig = (rootFiles, resolvedTsConfigPath, context, compilerOptions) => {
1388
+ const tempTsConfigJsonPath = resolve(context, "node_modules", TEMP_DIR, `tsconfig.list-files.${crypto.createHash("md5").update(`${JSON.stringify(rootFiles)}${resolvedTsConfigPath}${Date.now()}`).digest("hex")}.json`);
1389
+ mkdirSync(dirname(tempTsConfigJsonPath), { recursive: true });
1390
+ const listFilesConfig = compilerOptions ? {
1391
+ compilerOptions,
1392
+ files: rootFiles.map((file) => isAbsolute(file) ? file : resolve(context, file))
1393
+ } : {
1394
+ extends: resolvedTsConfigPath,
1395
+ files: rootFiles.map((file) => isAbsolute(file) ? file : resolve(context, file))
1396
+ };
1397
+ writeFileSync(tempTsConfigJsonPath, JSON.stringify(listFilesConfig, null, 2));
1398
+ return tempTsConfigJsonPath;
1399
+ };
1400
+ const formatCompilerError = (error) => {
1401
+ const readOutput = (value) => {
1402
+ if (Buffer.isBuffer(value)) return value.toString("utf8");
1403
+ return typeof value === "string" ? value : "";
1404
+ };
1405
+ if (typeof error === "object" && error !== null) {
1406
+ const processError = error;
1407
+ const stderr = readOutput(processError.stderr).trim();
1408
+ if (stderr) return stderr.split(/\r?\n/)[0];
1409
+ const stdout = readOutput(processError.stdout).trim();
1410
+ if (stdout) return stdout.split(/\r?\n/)[0];
1411
+ if (typeof processError.message === "string") return processError.message;
1412
+ }
1413
+ return String(error);
1414
+ };
1415
+ const getDependentFilesWithTsc = (rootFiles, rootDir, resolvedTsConfigPath, compilerOptions, context, typeScriptContext) => {
1416
+ if (!rootFiles.length) return [];
1417
+ const typeScriptPackageInfo = getTypeScriptPackageInfo(typeScriptContext);
1418
+ const listFilesTsConfigPath = writeListFilesTsConfig(rootFiles, resolvedTsConfigPath, context, compilerOptions);
1419
+ try {
1420
+ const dependentFiles = execFileSync(process.execPath, [
1421
+ typeScriptPackageInfo.tscBinPath,
1422
+ "--listFilesOnly",
1423
+ "--project",
1424
+ listFilesTsConfigPath
1425
+ ], {
1426
+ cwd: typeScriptContext,
1427
+ encoding: "utf8",
1428
+ stdio: [
1429
+ "ignore",
1430
+ "pipe",
1431
+ "pipe"
1432
+ ]
1433
+ }).split(/\r?\n/).map((file) => file.trim()).filter(Boolean).map((file) => isAbsolute(file) ? file : resolve(context, file)).filter((file) => !file.endsWith(".d.ts") && isFileWithinRootDir(file, rootDir)).map((file) => normalizeFileToRootDir(file, rootDir));
1434
+ return dependentFiles.length ? dependentFiles : rootFiles;
1435
+ } catch (error) {
1436
+ logger$1.warn(`Failed to collect TypeScript dependency files with "tsc --listFilesOnly"; falling back to exposed files only. ${formatCompilerError(error)}`);
1437
+ return rootFiles;
1438
+ } finally {
1439
+ rmSync(listFilesTsConfigPath, { force: true });
1440
+ }
1441
+ };
1442
+ const readTsConfig = (remoteOptions, mapComponentsToExpose) => {
1443
+ const { tsConfigPath, typesFolder, compiledTypesFolder, context, additionalFilesToCompile, outputDir } = remoteOptions;
1444
+ const resolvedTsConfigPath = resolve(context, tsConfigPath);
1445
+ const typeScriptContext = getTypeScriptContext(remoteOptions);
1446
+ const typeScriptPackageInfo = getTypeScriptPackageInfo(typeScriptContext);
1447
+ let rawTsConfigJson;
1448
+ let configContent;
1449
+ let typescript;
1450
+ if (typeScriptPackageInfo.majorVersion === 7) ({rawTsConfigJson, configContent} = readTsConfigWithTsc(resolvedTsConfigPath, typeScriptContext));
1451
+ else {
1452
+ typescript = requireTypeScript(typeScriptContext);
1453
+ const readResult = typescript.readConfigFile(resolvedTsConfigPath, typescript.sys.readFile);
1454
+ if (readResult.error) throw new Error(readResult.error.messageText.toString());
1455
+ rawTsConfigJson = readResult.config || {};
1456
+ configContent = typescript.parseJsonConfigFileContent(rawTsConfigJson, typescript.sys, dirname(resolvedTsConfigPath));
1457
+ configContent.projectReferences = configContent.projectReferences || [];
1458
+ }
1459
+ const rootDir = getEffectiveRootDir(configContent);
1460
+ const outDir = resolve(context, outputDir || configContent.options.outDir || "dist", typesFolder, compiledTypesFolder);
1461
+ const defaultCompilerOptions = {
1462
+ rootDir,
1463
+ emitDeclarationOnly: true,
1464
+ noEmit: false,
1465
+ declaration: true,
1466
+ outDir
1467
+ };
1468
+ rawTsConfigJson.compilerOptions = rawTsConfigJson.compilerOptions || {};
1469
+ rawTsConfigJson.compilerOptions = {
1470
+ incremental: true,
1471
+ tsBuildInfoFile: resolve(context, "node_modules/.cache/mf-types/.tsbuildinfo"),
1472
+ ...rawTsConfigJson.compilerOptions,
1473
+ ...defaultCompilerOptions
1474
+ };
1475
+ const { paths, baseUrl, ...restCompilerOptions } = rawTsConfigJson.compilerOptions || {};
1476
+ rawTsConfigJson.compilerOptions = restCompilerOptions;
1477
+ const outDirWithoutTypesFolder = resolve(context, outputDir || configContent.options.outDir || "dist");
1478
+ const excludeExtensions = [".mdx", ".md"];
1479
+ const rootFiles = [...Object.values(mapComponentsToExpose), ...additionalFilesToCompile].filter((filename) => !excludeExtensions.some((ext) => filename.endsWith(ext)));
1480
+ const filesToCompile = [...typescript ? getDependentFiles(rootFiles, configContent, rootDir, typescript) : getDependentFilesWithTsc(rootFiles, rootDir, resolvedTsConfigPath, configContent.options, context, typeScriptContext), ...configContent.fileNames.filter((filename) => filename.endsWith(".d.ts") && !filename.startsWith(outDirWithoutTypesFolder))];
1481
+ rawTsConfigJson.include = [];
1482
+ rawTsConfigJson.files = [...new Set(filesToCompile)];
1483
+ rawTsConfigJson.exclude = [];
1484
+ "references" in rawTsConfigJson && delete rawTsConfigJson.references;
1485
+ rawTsConfigJson.extends = resolvedTsConfigPath;
1486
+ rawTsConfigJson.compilerOptions.declarationDir = outDir;
1487
+ return rawTsConfigJson;
1488
+ };
1489
+ const TS_EXTENSIONS = [
1490
+ ".ts",
1491
+ ".tsx",
1492
+ ".vue",
1493
+ ".svelte",
1494
+ ".js",
1495
+ ".jsx"
1496
+ ];
1497
+ const resolveWithExtension = (exposedPath, context) => {
1498
+ const explicitExtension = extname(exposedPath);
1499
+ if (TS_EXTENSIONS.includes(explicitExtension)) return resolve(context, exposedPath);
1500
+ for (const extension of TS_EXTENSIONS) {
1501
+ const exposedPathWithExtension = resolve(context, `${exposedPath}${extension}`);
1502
+ if (existsSync(exposedPathWithExtension)) return exposedPathWithExtension;
1503
+ }
1504
+ };
1505
+ const resolveExposes = (remoteOptions) => {
1506
+ return utils.parseOptions(remoteOptions.moduleFederationConfig.exposes || {}, (item, key) => ({
1507
+ exposePath: Array.isArray(item) ? item[0] : item,
1508
+ key
1509
+ }), (item, key) => ({
1510
+ exposePath: Array.isArray(item.import) ? item.import[0] : item.import[0],
1511
+ key
1512
+ })).reduce((accumulator, item) => {
1513
+ const { exposePath, key } = item[1];
1514
+ accumulator[key] = resolveWithExtension(exposePath, remoteOptions.context) || resolveWithExtension(join(exposePath, "index"), remoteOptions.context) || exposePath;
1515
+ return accumulator;
1516
+ }, {});
1517
+ };
1518
+ const retrieveRemoteConfig = (options) => {
1519
+ validateOptions(options);
1520
+ const remoteOptions = {
1521
+ ...defaultOptions,
1522
+ ...options
1523
+ };
1524
+ const mapComponentsToExpose = resolveExposes(remoteOptions);
1525
+ const tsConfig = readTsConfig(remoteOptions, mapComponentsToExpose);
1526
+ if (tsConfig.compilerOptions.incremental && tsConfig.compilerOptions.tsBuildInfoFile && options.deleteTypesFolder !== true) remoteOptions.deleteTypesFolder = false;
1527
+ return {
1528
+ tsConfig,
1529
+ mapComponentsToExpose,
1530
+ remoteOptions
1531
+ };
1532
+ };
1533
+
1534
+ //#endregion
1535
+ //#region src/core/lib/generateTypes.ts
1536
+ async function generateTypes(options) {
1537
+ return new (getDTSManagerConstructor(options.remote?.implementation))(options).generateTypes();
1538
+ }
1539
+
1540
+ //#endregion
1541
+ //#region src/core/rpc/types.ts
1542
+ let RpcGMCallTypes = /* @__PURE__ */ function(RpcGMCallTypes) {
1543
+ RpcGMCallTypes["CALL"] = "mf_call";
1544
+ RpcGMCallTypes["RESOLVE"] = "mf_resolve";
1545
+ RpcGMCallTypes["REJECT"] = "mf_reject";
1546
+ RpcGMCallTypes["EXIT"] = "mf_exit";
1547
+ return RpcGMCallTypes;
1548
+ }({});
1549
+
1550
+ //#endregion
1551
+ //#region src/core/rpc/expose-rpc.ts
1552
+ function exposeRpc(fn) {
1553
+ const sendMessage = (message) => new Promise((resolve, reject) => {
1554
+ if (!process$1.send) reject(/* @__PURE__ */ new Error(`Process ${process$1.pid} doesn't have IPC channels`));
1555
+ else if (!process$1.connected) reject(/* @__PURE__ */ new Error(`Process ${process$1.pid} doesn't have open IPC channels`));
1556
+ else process$1.send(message, void 0, void 0, (error) => {
1557
+ if (error) reject(error);
1558
+ else resolve(void 0);
1559
+ });
1560
+ });
1561
+ const handleMessage = async (message) => {
1562
+ if (message.type === RpcGMCallTypes.CALL) {
1563
+ if (!process$1.send) return;
1564
+ let value, error;
1565
+ try {
1566
+ value = await fn(...message.args);
1567
+ } catch (fnError) {
1568
+ error = fnError;
1569
+ }
1570
+ try {
1571
+ if (error) await sendMessage({
1572
+ type: RpcGMCallTypes.REJECT,
1573
+ id: message.id,
1574
+ error
1575
+ });
1576
+ else await sendMessage({
1577
+ type: RpcGMCallTypes.RESOLVE,
1578
+ id: message.id,
1579
+ value
1580
+ });
1581
+ } catch (sendError) {
1582
+ if (error) {
1583
+ if (error instanceof Error) console.error(error);
1584
+ }
1585
+ console.error(sendError);
1586
+ }
1587
+ }
1588
+ };
1589
+ process$1.on("message", handleMessage);
1590
+ }
1591
+
1592
+ //#endregion
1593
+ export { retrieveMfTypesPath as _, cloneDeepOptions as a, ModuleFederationDevServer as b, isTSProject as c, DTSManager as d, HOST_API_TYPES_FILE_NAME as f, retrieveTypesZipPath as g, retrieveHostConfig as h, retrieveRemoteConfig as i, retrieveTypesAssetsInfo as l, REMOTE_API_TYPES_FILE_NAME as m, RpcGMCallTypes as n, getDTSManagerConstructor as o, REMOTE_ALIAS_IDENTIFIER as p, generateTypes as r, isDebugMode as s, exposeRpc as t, validateOptions as u, retrieveOriginalOutDir as v, __exportAll as x, createHttpServer as y };