@module-federation/dts-plugin 0.0.0-feat-support-bridge-react-router-v7-20251015102312

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