@module-federation/dts-plugin 0.1.19 → 0.1.21

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 (35) hide show
  1. package/dist/CHANGELOG.md +27 -0
  2. package/dist/{DtsWorker-d731dc2b.d.ts → DtsWorker-7113d2b0.d.ts} +6 -3
  3. package/dist/core.d.mts +85 -0
  4. package/dist/core.d.ts +5 -5
  5. package/dist/core.js +1105 -1008
  6. package/dist/dynamic-remote-type-hints-plugin.d.mts +5 -0
  7. package/dist/dynamic-remote-type-hints-plugin.d.ts +5 -0
  8. package/dist/dynamic-remote-type-hints-plugin.js +198 -0
  9. package/dist/esm/chunk-55BKSNZ4.js +2372 -0
  10. package/dist/esm/chunk-G7ONFBMA.js +24 -0
  11. package/dist/esm/chunk-MQRIERJP.js +236 -0
  12. package/dist/esm/core.js +44 -0
  13. package/dist/esm/dynamic-remote-type-hints-plugin.js +73 -0
  14. package/dist/esm/fork-dev-worker.js +141 -0
  15. package/dist/esm/fork-generate-dts.js +26 -0
  16. package/dist/esm/index.js +406 -0
  17. package/dist/esm/start-broker.js +36 -0
  18. package/dist/fork-dev-worker.d.ts +15 -0
  19. package/dist/fork-dev-worker.js +2543 -0
  20. package/dist/{forkGenerateDts.d.ts → fork-generate-dts.d.mts} +1 -1
  21. package/dist/fork-generate-dts.d.ts +9 -0
  22. package/dist/fork-generate-dts.js +1902 -0
  23. package/dist/iife/launch-web-client.js +91 -42
  24. package/dist/index.d.mts +10 -0
  25. package/dist/index.js +1287 -1181
  26. package/dist/package.json +11 -2
  27. package/dist/{startBroker.d.ts → start-broker.d.mts} +2 -0
  28. package/dist/start-broker.d.ts +42 -0
  29. package/dist/start-broker.js +1273 -0
  30. package/package.json +14 -5
  31. package/dist/forkDevWorker.js +0 -2523
  32. package/dist/forkGenerateDts.js +0 -1618
  33. package/dist/launch-web-client.d.ts +0 -2
  34. package/dist/startBroker.js +0 -902
  35. /package/dist/{forkDevWorker.d.ts → fork-dev-worker.d.mts} +0 -0
@@ -0,0 +1,2543 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __spreadValues = (a, b) => {
13
+ for (var prop in b || (b = {}))
14
+ if (__hasOwnProp.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ if (__getOwnPropSymbols)
17
+ for (var prop of __getOwnPropSymbols(b)) {
18
+ if (__propIsEnum.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
20
+ }
21
+ return a;
22
+ };
23
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
25
+ var __export = (target, all) => {
26
+ for (var name in all)
27
+ __defProp(target, name, { get: all[name], enumerable: true });
28
+ };
29
+ var __copyProps = (to, from, except, desc) => {
30
+ if (from && typeof from === "object" || typeof from === "function") {
31
+ for (let key of __getOwnPropNames(from))
32
+ if (!__hasOwnProp.call(to, key) && key !== except)
33
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
34
+ }
35
+ return to;
36
+ };
37
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
38
+ // If the importer is in node compatibility mode or this is not an ESM
39
+ // file that has been converted to a CommonJS file using a Babel-
40
+ // compatible transform (i.e. "__esModule" has not been set), then set
41
+ // "default" to the CommonJS "module.exports" for node compatibility.
42
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
43
+ mod
44
+ ));
45
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
46
+ var __publicField = (obj, key, value) => {
47
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
48
+ return value;
49
+ };
50
+ var __async = (__this, __arguments, generator) => {
51
+ return new Promise((resolve4, reject) => {
52
+ var fulfilled = (value) => {
53
+ try {
54
+ step(generator.next(value));
55
+ } catch (e) {
56
+ reject(e);
57
+ }
58
+ };
59
+ var rejected = (value) => {
60
+ try {
61
+ step(generator.throw(value));
62
+ } catch (e) {
63
+ reject(e);
64
+ }
65
+ };
66
+ var step = (x) => x.done ? resolve4(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
67
+ step((generator = generator.apply(__this, __arguments)).next());
68
+ });
69
+ };
70
+
71
+ // packages/dts-plugin/src/dev-worker/forkDevWorker.ts
72
+ var forkDevWorker_exports = {};
73
+ __export(forkDevWorker_exports, {
74
+ forkDevWorker: () => forkDevWorker
75
+ });
76
+ module.exports = __toCommonJS(forkDevWorker_exports);
77
+
78
+ // packages/dts-plugin/src/core/configurations/remotePlugin.ts
79
+ var import_fs2 = require("fs");
80
+ var import_path5 = require("path");
81
+ var import_managers2 = require("@module-federation/managers");
82
+ var import_typescript2 = __toESM(require("typescript"));
83
+
84
+ // packages/dts-plugin/src/core/lib/utils.ts
85
+ var import_axios = __toESM(require("axios"));
86
+ var import_http2 = __toESM(require("http"));
87
+ var import_https = __toESM(require("https"));
88
+ var import_ansi_colors3 = __toESM(require("ansi-colors"));
89
+
90
+ // packages/dts-plugin/src/core/lib/DTSManager.ts
91
+ var import_ansi_colors2 = __toESM(require("ansi-colors"));
92
+ var import_path4 = __toESM(require("path"));
93
+ var import_promises2 = require("fs/promises");
94
+ var import_fs = __toESM(require("fs"));
95
+ var import_sdk4 = require("@module-federation/sdk");
96
+ var import_lodash = __toESM(require("lodash.clonedeepwith"));
97
+ var import_third_party_dts_extractor2 = require("@module-federation/third-party-dts-extractor");
98
+
99
+ // packages/dts-plugin/src/core/lib/archiveHandler.ts
100
+ var import_adm_zip = __toESM(require("adm-zip"));
101
+ var import_path3 = require("path");
102
+ var import_promises = require("fs/promises");
103
+
104
+ // packages/dts-plugin/src/core/lib/typeScriptCompiler.ts
105
+ var import_ansi_colors = __toESM(require("ansi-colors"));
106
+ var import_path = require("path");
107
+ var import_typescript = __toESM(require("typescript"));
108
+ var import_third_party_dts_extractor = require("@module-federation/third-party-dts-extractor");
109
+ var STARTS_WITH_SLASH = /^\//;
110
+ var DEFINITION_FILE_EXTENSION = ".d.ts";
111
+ var reportCompileDiagnostic = /* @__PURE__ */ __name((diagnostic) => {
112
+ const { line } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
113
+ console.error(import_ansi_colors.default.red(`TS Error ${diagnostic.code}':' ${import_typescript.default.flattenDiagnosticMessageText(diagnostic.messageText, import_typescript.default.sys.newLine)}`));
114
+ console.error(import_ansi_colors.default.red(` at ${diagnostic.file.fileName}:${line + 1} typescript.sys.newLine`));
115
+ }, "reportCompileDiagnostic");
116
+ var retrieveMfTypesPath = /* @__PURE__ */ __name((tsConfig, remoteOptions) => (0, import_path.normalize)(tsConfig.outDir.replace(remoteOptions.compiledTypesFolder, "")), "retrieveMfTypesPath");
117
+ var retrieveOriginalOutDir = /* @__PURE__ */ __name((tsConfig, remoteOptions) => (0, import_path.normalize)(tsConfig.outDir.replace(remoteOptions.compiledTypesFolder, "").replace(remoteOptions.typesFolder, "")), "retrieveOriginalOutDir");
118
+ var retrieveMfAPITypesPath = /* @__PURE__ */ __name((tsConfig, remoteOptions) => (0, import_path.join)(retrieveOriginalOutDir(tsConfig, remoteOptions), `${remoteOptions.typesFolder}.d.ts`), "retrieveMfAPITypesPath");
119
+ var createHost = /* @__PURE__ */ __name((mapComponentsToExpose, tsConfig, remoteOptions, cb) => {
120
+ const host = import_typescript.default.createCompilerHost(tsConfig);
121
+ const originalWriteFile = host.writeFile;
122
+ const mapExposeToEntry = Object.fromEntries(Object.entries(mapComponentsToExpose).map(([exposed, filename]) => [
123
+ (0, import_path.normalize)(filename),
124
+ exposed
125
+ ]));
126
+ const mfTypePath = retrieveMfTypesPath(tsConfig, remoteOptions);
127
+ host.writeFile = (filepath, text, writeOrderByteMark, onError, sourceFiles, data) => {
128
+ originalWriteFile(filepath, text, writeOrderByteMark, onError, sourceFiles, data);
129
+ for (const sourceFile of sourceFiles || []) {
130
+ let sourceEntry = mapExposeToEntry[(0, import_path.normalize)(sourceFile.fileName)];
131
+ if (sourceEntry === ".") {
132
+ sourceEntry = "index";
133
+ }
134
+ if (sourceEntry) {
135
+ const mfeTypeEntry = (0, import_path.join)(mfTypePath, `${sourceEntry}${DEFINITION_FILE_EXTENSION}`);
136
+ const mfeTypeEntryDirectory = (0, import_path.dirname)(mfeTypeEntry);
137
+ const relativePathToOutput = (0, import_path.relative)(mfeTypeEntryDirectory, filepath).replace(DEFINITION_FILE_EXTENSION, "").replace(STARTS_WITH_SLASH, "").split(import_path.sep).join("/");
138
+ originalWriteFile(mfeTypeEntry, `export * from './${relativePathToOutput}';
139
+ export { default } from './${relativePathToOutput}';`, writeOrderByteMark);
140
+ }
141
+ }
142
+ cb(text);
143
+ };
144
+ return host;
145
+ }, "createHost");
146
+ var createVueTscProgram = /* @__PURE__ */ __name((programOptions) => {
147
+ const vueTypescript = require("vue-tsc");
148
+ return vueTypescript.createProgram(programOptions);
149
+ }, "createVueTscProgram");
150
+ var createProgram = /* @__PURE__ */ __name((remoteOptions, programOptions) => {
151
+ switch (remoteOptions.compilerInstance) {
152
+ case "vue-tsc":
153
+ return createVueTscProgram(programOptions);
154
+ case "tsc":
155
+ default:
156
+ return import_typescript.default.createProgram(programOptions);
157
+ }
158
+ }, "createProgram");
159
+ var compileTs = /* @__PURE__ */ __name((mapComponentsToExpose, tsConfig, remoteOptions) => {
160
+ const mfTypePath = retrieveMfTypesPath(tsConfig, remoteOptions);
161
+ const thirdPartyExtractor = new import_third_party_dts_extractor.ThirdPartyExtractor((0, import_path.resolve)(mfTypePath, "node_modules"), remoteOptions.context);
162
+ const cb = remoteOptions.extractThirdParty ? thirdPartyExtractor.collectPkgs.bind(thirdPartyExtractor) : () => void 0;
163
+ const tsHost = createHost(mapComponentsToExpose, tsConfig, remoteOptions, cb);
164
+ const filesToCompile = [
165
+ ...Object.values(mapComponentsToExpose),
166
+ ...remoteOptions.additionalFilesToCompile
167
+ ];
168
+ const programOptions = {
169
+ rootNames: filesToCompile,
170
+ host: tsHost,
171
+ options: tsConfig
172
+ };
173
+ const tsProgram = createProgram(remoteOptions, programOptions);
174
+ const { diagnostics = [] } = tsProgram.emit();
175
+ diagnostics.forEach(reportCompileDiagnostic);
176
+ if (remoteOptions.extractThirdParty) {
177
+ thirdPartyExtractor.copyDts();
178
+ }
179
+ }, "compileTs");
180
+
181
+ // packages/dts-plugin/src/server/message/Message.ts
182
+ var _Message = class _Message {
183
+ constructor(type, kind) {
184
+ __publicField(this, "type");
185
+ __publicField(this, "kind");
186
+ __publicField(this, "time");
187
+ this.type = type;
188
+ this.kind = kind;
189
+ this.time = Date.now();
190
+ }
191
+ };
192
+ __name(_Message, "Message");
193
+ var Message = _Message;
194
+
195
+ // packages/dts-plugin/src/server/message/API/API.ts
196
+ var APIKind;
197
+ (function(APIKind2) {
198
+ APIKind2["UPDATE_SUBSCRIBER"] = "UPDATE_SUBSCRIBER";
199
+ APIKind2["RELOAD_WEB_CLIENT"] = "RELOAD_WEB_CLIENT";
200
+ APIKind2["FETCH_TYPES"] = "FETCH_TYPES";
201
+ })(APIKind || (APIKind = {}));
202
+ var _API = class _API extends Message {
203
+ constructor(content, kind) {
204
+ super("API", kind);
205
+ __publicField(this, "code");
206
+ __publicField(this, "payload");
207
+ const { code, payload } = content;
208
+ this.code = code;
209
+ this.payload = payload;
210
+ }
211
+ };
212
+ __name(_API, "API");
213
+ var API = _API;
214
+
215
+ // packages/dts-plugin/src/server/message/API/UpdateSubscriber.ts
216
+ var _UpdateSubscriberAPI = class _UpdateSubscriberAPI extends API {
217
+ constructor(payload) {
218
+ super({
219
+ code: 0,
220
+ payload
221
+ }, APIKind.UPDATE_SUBSCRIBER);
222
+ }
223
+ };
224
+ __name(_UpdateSubscriberAPI, "UpdateSubscriberAPI");
225
+ var UpdateSubscriberAPI = _UpdateSubscriberAPI;
226
+
227
+ // packages/dts-plugin/src/server/message/API/ReloadWebClient.ts
228
+ var _ReloadWebClientAPI = class _ReloadWebClientAPI extends API {
229
+ constructor(payload) {
230
+ super({
231
+ code: 0,
232
+ payload
233
+ }, APIKind.RELOAD_WEB_CLIENT);
234
+ }
235
+ };
236
+ __name(_ReloadWebClientAPI, "ReloadWebClientAPI");
237
+ var ReloadWebClientAPI = _ReloadWebClientAPI;
238
+
239
+ // packages/dts-plugin/src/server/message/API/FetchTypes.ts
240
+ var _FetchTypesAPI = class _FetchTypesAPI extends API {
241
+ constructor(payload) {
242
+ super({
243
+ code: 0,
244
+ payload
245
+ }, APIKind.FETCH_TYPES);
246
+ }
247
+ };
248
+ __name(_FetchTypesAPI, "FetchTypesAPI");
249
+ var FetchTypesAPI = _FetchTypesAPI;
250
+
251
+ // packages/dts-plugin/src/server/utils/index.ts
252
+ var import_net = __toESM(require("net"));
253
+ var import_sdk2 = require("@module-federation/sdk");
254
+
255
+ // packages/dts-plugin/src/server/utils/logTransform.ts
256
+ var import_chalk = __toESM(require("chalk"));
257
+
258
+ // packages/dts-plugin/src/server/message/Log/Log.ts
259
+ var LogLevel;
260
+ (function(LogLevel2) {
261
+ LogLevel2["LOG"] = "LOG";
262
+ LogLevel2["WARN"] = "WARN";
263
+ LogLevel2["ERROR"] = "ERROR";
264
+ })(LogLevel || (LogLevel = {}));
265
+ var LogKind;
266
+ (function(LogKind2) {
267
+ LogKind2["BrokerExitLog"] = "BrokerExitLog";
268
+ LogKind2["PublisherRegisteredLog"] = "PublisherRegisteredLog";
269
+ })(LogKind || (LogKind = {}));
270
+ var _Log = class _Log extends Message {
271
+ constructor(level, kind, ignoreVerbose = false) {
272
+ super("Log", kind);
273
+ __publicField(this, "level");
274
+ __publicField(this, "ignoreVerbose", false);
275
+ this.level = level;
276
+ this.ignoreVerbose = ignoreVerbose;
277
+ }
278
+ };
279
+ __name(_Log, "Log");
280
+ var Log = _Log;
281
+
282
+ // packages/dts-plugin/src/server/message/Log/BrokerExitLog.ts
283
+ var _BrokerExitLog = class _BrokerExitLog extends Log {
284
+ constructor() {
285
+ super(LogLevel.LOG, LogKind.BrokerExitLog);
286
+ }
287
+ };
288
+ __name(_BrokerExitLog, "BrokerExitLog");
289
+ var BrokerExitLog = _BrokerExitLog;
290
+
291
+ // packages/dts-plugin/src/server/utils/log.ts
292
+ var import_sdk = require("@module-federation/sdk");
293
+ var log4js = __toESM(require("log4js"));
294
+ var import_chalk2 = __toESM(require("chalk"));
295
+
296
+ // packages/dts-plugin/src/server/constant.ts
297
+ var DEFAULT_WEB_SOCKET_PORT = 16322;
298
+ var WEB_SOCKET_CONNECT_MAGIC_ID = "1hpzW-zo2z-o8io-gfmV1-2cb1d82";
299
+ var MF_SERVER_IDENTIFIER = "Module Federation Dev Server";
300
+ var DEFAULT_TAR_NAME = "@mf-types.zip";
301
+
302
+ // packages/dts-plugin/src/server/utils/log.ts
303
+ function fileLog(msg, module2, level) {
304
+ var _a3, _b;
305
+ if (!((_a3 = process == null ? void 0 : process.env) == null ? void 0 : _a3["FEDERATION_DEBUG"])) {
306
+ return;
307
+ }
308
+ log4js.configure({
309
+ appenders: {
310
+ [module2]: {
311
+ type: "file",
312
+ filename: ".mf/typesGenerate.log"
313
+ },
314
+ default: {
315
+ type: "file",
316
+ filename: ".mf/typesGenerate.log"
317
+ }
318
+ },
319
+ categories: {
320
+ [module2]: {
321
+ appenders: [
322
+ module2
323
+ ],
324
+ level: "error"
325
+ },
326
+ default: {
327
+ appenders: [
328
+ "default"
329
+ ],
330
+ level: "trace"
331
+ }
332
+ }
333
+ });
334
+ const logger4 = log4js.getLogger(module2);
335
+ logger4.level = "debug";
336
+ (_b = logger4[level]) == null ? void 0 : _b.call(logger4, msg);
337
+ }
338
+ __name(fileLog, "fileLog");
339
+ function error(error2, action, from) {
340
+ const err = error2 instanceof Error ? error2 : new Error(`${action} error`);
341
+ fileLog(`[${action}] error: ${err}`, from, "fatal");
342
+ return err.toString();
343
+ }
344
+ __name(error, "error");
345
+
346
+ // packages/dts-plugin/src/server/utils/getIPV4.ts
347
+ var import_os = __toESM(require("os"));
348
+ var localIpv4 = "127.0.0.1";
349
+ var getIpv4Interfaces = /* @__PURE__ */ __name(() => {
350
+ try {
351
+ const interfaces = import_os.default.networkInterfaces();
352
+ const ipv4Interfaces = [];
353
+ Object.values(interfaces).forEach((detail) => {
354
+ detail == null ? void 0 : detail.forEach((detail2) => {
355
+ const familyV4Value = typeof detail2.family === "string" ? "IPv4" : 4;
356
+ if (detail2.family === familyV4Value && detail2.address !== localIpv4) {
357
+ ipv4Interfaces.push(detail2);
358
+ }
359
+ });
360
+ });
361
+ return ipv4Interfaces;
362
+ } catch (_err) {
363
+ return [];
364
+ }
365
+ }, "getIpv4Interfaces");
366
+ var getIPV4 = /* @__PURE__ */ __name(() => {
367
+ const ipv4Interfaces = getIpv4Interfaces();
368
+ const ipv4Interface = ipv4Interfaces[0] || {
369
+ address: localIpv4
370
+ };
371
+ return ipv4Interface.address;
372
+ }, "getIPV4");
373
+
374
+ // packages/dts-plugin/src/server/utils/index.ts
375
+ function getIdentifier(options) {
376
+ const { ip, name } = options;
377
+ return `mf ${import_sdk2.SEPARATOR}${name}${ip ? `${import_sdk2.SEPARATOR}${ip}` : ""}`;
378
+ }
379
+ __name(getIdentifier, "getIdentifier");
380
+ function fib(n) {
381
+ let i = 2;
382
+ const res = [
383
+ 0,
384
+ 1,
385
+ 1
386
+ ];
387
+ while (i <= n) {
388
+ res[i] = res[i - 1] + res[i - 2];
389
+ i++;
390
+ }
391
+ return res[n];
392
+ }
393
+ __name(fib, "fib");
394
+ function getFreePort() {
395
+ return new Promise((resolve4, reject) => {
396
+ const server = import_net.default.createServer();
397
+ server.unref();
398
+ server.on("error", reject);
399
+ server.listen(0, () => {
400
+ const { port } = server.address();
401
+ server.close(() => {
402
+ resolve4(port);
403
+ });
404
+ });
405
+ });
406
+ }
407
+ __name(getFreePort, "getFreePort");
408
+
409
+ // packages/dts-plugin/src/server/Publisher.ts
410
+ var _Publisher = class _Publisher {
411
+ constructor(ctx) {
412
+ __publicField(this, "_ip");
413
+ __publicField(this, "_name");
414
+ __publicField(this, "_remoteTypeTarPath");
415
+ __publicField(this, "_subscribers");
416
+ __publicField(this, "_ws");
417
+ __publicField(this, "dynamicRemoteMap");
418
+ this._name = ctx.name;
419
+ this._ip = ctx.ip;
420
+ this._remoteTypeTarPath = ctx.remoteTypeTarPath;
421
+ this._subscribers = /* @__PURE__ */ new Map();
422
+ this._ws = ctx.ws;
423
+ this.dynamicRemoteMap = /* @__PURE__ */ new Map();
424
+ }
425
+ get identifier() {
426
+ return getIdentifier({
427
+ name: this._name,
428
+ ip: this._ip
429
+ });
430
+ }
431
+ get name() {
432
+ return this._name;
433
+ }
434
+ get ip() {
435
+ return this._ip;
436
+ }
437
+ get remoteTypeTarPath() {
438
+ return this._remoteTypeTarPath;
439
+ }
440
+ get hasSubscribes() {
441
+ return Boolean(this._subscribers.size);
442
+ }
443
+ get subscribers() {
444
+ return this._subscribers;
445
+ }
446
+ addSubscriber(identifier, subscriber) {
447
+ fileLog(`${this.name} set subscriber: ${identifier}`, "Publisher", "info");
448
+ this._subscribers.set(identifier, subscriber);
449
+ }
450
+ removeSubscriber(identifier) {
451
+ if (this._subscribers.has(identifier)) {
452
+ fileLog(`${this.name} removeSubscriber: ${identifier}`, "Publisher", "warn");
453
+ this._subscribers.delete(identifier);
454
+ }
455
+ }
456
+ notifySubscriber(subscriberIdentifier, options) {
457
+ const subscriber = this._subscribers.get(subscriberIdentifier);
458
+ if (!subscriber) {
459
+ fileLog(`[notifySubscriber] ${this.name} notifySubscriber: ${subscriberIdentifier}, does not exits`, "Publisher", "error");
460
+ return;
461
+ }
462
+ const api = new UpdateSubscriberAPI(options);
463
+ subscriber.send(JSON.stringify(api));
464
+ fileLog(`[notifySubscriber] ${this.name} notifySubscriber: ${JSON.stringify(subscriberIdentifier)}, message: ${JSON.stringify(api)}`, "Publisher", "info");
465
+ }
466
+ fetchRemoteTypes(options) {
467
+ fileLog(`[fetchRemoteTypes] ${this.name} fetchRemoteTypes, options: ${JSON.stringify(options)}, ws: ${Boolean(this._ws)}`, "Publisher", "info");
468
+ if (!this._ws) {
469
+ return;
470
+ }
471
+ const api = new FetchTypesAPI(options);
472
+ this._ws.send(JSON.stringify(api));
473
+ }
474
+ notifySubscribers(options) {
475
+ const api = new UpdateSubscriberAPI(options);
476
+ this.broadcast(api);
477
+ }
478
+ broadcast(message) {
479
+ if (this.hasSubscribes) {
480
+ this._subscribers.forEach((subscriber, key) => {
481
+ fileLog(`[BroadCast] ${this.name} notifySubscriber: ${key}, PID: ${process.pid}, message: ${JSON.stringify(message)}`, "Publisher", "info");
482
+ subscriber.send(JSON.stringify(message));
483
+ });
484
+ } else {
485
+ fileLog(`[BroadCast] ${this.name}'s subscribe is empty`, "Publisher", "warn");
486
+ }
487
+ }
488
+ close() {
489
+ this._ws = void 0;
490
+ this._subscribers.forEach((_subscriber, identifier) => {
491
+ fileLog(`[BroadCast] close ${this.name} remove: ${identifier}`, "Publisher", "warn");
492
+ this.removeSubscriber(identifier);
493
+ });
494
+ }
495
+ };
496
+ __name(_Publisher, "Publisher");
497
+ var Publisher = _Publisher;
498
+
499
+ // packages/dts-plugin/src/server/DevServer.ts
500
+ var import_isomorphic_ws2 = __toESM(require("isomorphic-ws"));
501
+
502
+ // packages/dts-plugin/src/server/broker/Broker.ts
503
+ var import_http = require("http");
504
+ var import_isomorphic_ws = __toESM(require("isomorphic-ws"));
505
+ var import_node_schedule = __toESM(require("node-schedule"));
506
+ var import_url = require("url");
507
+
508
+ // packages/dts-plugin/src/server/message/Action/Action.ts
509
+ var ActionKind;
510
+ (function(ActionKind2) {
511
+ ActionKind2["ADD_SUBSCRIBER"] = "ADD_SUBSCRIBER";
512
+ ActionKind2["EXIT_SUBSCRIBER"] = "EXIT_SUBSCRIBER";
513
+ ActionKind2["ADD_PUBLISHER"] = "ADD_PUBLISHER";
514
+ ActionKind2["UPDATE_PUBLISHER"] = "UPDATE_PUBLISHER";
515
+ ActionKind2["NOTIFY_SUBSCRIBER"] = "NOTIFY_SUBSCRIBER";
516
+ ActionKind2["EXIT_PUBLISHER"] = "EXIT_PUBLISHER";
517
+ ActionKind2["ADD_WEB_CLIENT"] = "ADD_WEB_CLIENT";
518
+ ActionKind2["NOTIFY_WEB_CLIENT"] = "NOTIFY_WEB_CLIENT";
519
+ ActionKind2["FETCH_TYPES"] = "FETCH_TYPES";
520
+ ActionKind2["ADD_DYNAMIC_REMOTE"] = "ADD_DYNAMIC_REMOTE";
521
+ })(ActionKind || (ActionKind = {}));
522
+ var _Action = class _Action extends Message {
523
+ constructor(content, kind) {
524
+ super("Action", kind);
525
+ __publicField(this, "payload");
526
+ const { payload } = content;
527
+ this.payload = payload;
528
+ }
529
+ };
530
+ __name(_Action, "Action");
531
+ var Action = _Action;
532
+
533
+ // packages/dts-plugin/src/server/message/Action/Update.ts
534
+ var UpdateKind;
535
+ (function(UpdateKind2) {
536
+ UpdateKind2["UPDATE_TYPE"] = "UPDATE_TYPE";
537
+ UpdateKind2["RELOAD_PAGE"] = "RELOAD_PAGE";
538
+ })(UpdateKind || (UpdateKind = {}));
539
+
540
+ // packages/dts-plugin/src/server/message/Action/AddPublisher.ts
541
+ var _AddPublisherAction = class _AddPublisherAction extends Action {
542
+ constructor(payload) {
543
+ super({
544
+ payload
545
+ }, ActionKind.ADD_PUBLISHER);
546
+ }
547
+ };
548
+ __name(_AddPublisherAction, "AddPublisherAction");
549
+ var AddPublisherAction = _AddPublisherAction;
550
+
551
+ // packages/dts-plugin/src/server/message/Action/AddSubscriber.ts
552
+ var _AddSubscriberAction = class _AddSubscriberAction extends Action {
553
+ constructor(payload) {
554
+ super({
555
+ payload
556
+ }, ActionKind.ADD_SUBSCRIBER);
557
+ }
558
+ };
559
+ __name(_AddSubscriberAction, "AddSubscriberAction");
560
+ var AddSubscriberAction = _AddSubscriberAction;
561
+
562
+ // packages/dts-plugin/src/server/message/Action/ExitSubscriber.ts
563
+ var _ExitSubscriberAction = class _ExitSubscriberAction extends Action {
564
+ constructor(payload) {
565
+ super({
566
+ payload
567
+ }, ActionKind.EXIT_SUBSCRIBER);
568
+ }
569
+ };
570
+ __name(_ExitSubscriberAction, "ExitSubscriberAction");
571
+ var ExitSubscriberAction = _ExitSubscriberAction;
572
+
573
+ // packages/dts-plugin/src/server/message/Action/ExitPublisher.ts
574
+ var _ExitPublisherAction = class _ExitPublisherAction extends Action {
575
+ constructor(payload) {
576
+ super({
577
+ payload
578
+ }, ActionKind.EXIT_PUBLISHER);
579
+ }
580
+ };
581
+ __name(_ExitPublisherAction, "ExitPublisherAction");
582
+ var ExitPublisherAction = _ExitPublisherAction;
583
+
584
+ // packages/dts-plugin/src/server/message/Action/NotifyWebClient.ts
585
+ var _NotifyWebClientAction = class _NotifyWebClientAction extends Action {
586
+ constructor(payload) {
587
+ super({
588
+ payload
589
+ }, ActionKind.NOTIFY_WEB_CLIENT);
590
+ }
591
+ };
592
+ __name(_NotifyWebClientAction, "NotifyWebClientAction");
593
+ var NotifyWebClientAction = _NotifyWebClientAction;
594
+
595
+ // packages/dts-plugin/src/server/message/Action/UpdatePublisher.ts
596
+ var _UpdatePublisherAction = class _UpdatePublisherAction extends Action {
597
+ constructor(payload) {
598
+ super({
599
+ payload
600
+ }, ActionKind.UPDATE_PUBLISHER);
601
+ }
602
+ };
603
+ __name(_UpdatePublisherAction, "UpdatePublisherAction");
604
+ var UpdatePublisherAction = _UpdatePublisherAction;
605
+
606
+ // packages/dts-plugin/src/core/constant.ts
607
+ var REMOTE_ALIAS_IDENTIFIER = "REMOTE_ALIAS_IDENTIFIER";
608
+ var REMOTE_API_TYPES_FILE_NAME = "apis.d.ts";
609
+ var HOST_API_TYPES_FILE_NAME = "index.d.ts";
610
+ var UpdateMode;
611
+ (function(UpdateMode2) {
612
+ UpdateMode2["POSITIVE"] = "POSITIVE";
613
+ UpdateMode2["PASSIVE"] = "PASSIVE";
614
+ })(UpdateMode || (UpdateMode = {}));
615
+
616
+ // packages/dts-plugin/src/server/broker/Broker.ts
617
+ var _Broker = class _Broker {
618
+ constructor() {
619
+ __publicField(this, "_publisherMap", /* @__PURE__ */ new Map());
620
+ __publicField(this, "_webClientMap", /* @__PURE__ */ new Map());
621
+ __publicField(this, "_webSocketServer");
622
+ __publicField(this, "_secureWebSocketServer");
623
+ __publicField(this, "_tmpSubscriberShelter", /* @__PURE__ */ new Map());
624
+ __publicField(this, "_scheduleJob", null);
625
+ this._setSchedule();
626
+ this._startWsServer();
627
+ this._stopWhenSIGTERMOrSIGINT();
628
+ this._handleUnexpectedExit();
629
+ }
630
+ get hasPublishers() {
631
+ return Boolean(this._publisherMap.size);
632
+ }
633
+ _startWsServer() {
634
+ return __async(this, null, function* () {
635
+ const wsHandler = /* @__PURE__ */ __name((ws, req) => {
636
+ const { url: reqUrl = "" } = req;
637
+ const { query } = (0, import_url.parse)(reqUrl, true);
638
+ const { WEB_SOCKET_CONNECT_MAGIC_ID: WEB_SOCKET_CONNECT_MAGIC_ID2 } = query;
639
+ if (WEB_SOCKET_CONNECT_MAGIC_ID2 === _Broker.WEB_SOCKET_CONNECT_MAGIC_ID) {
640
+ ws.on("message", (message) => {
641
+ try {
642
+ const text = message.toString();
643
+ const action = JSON.parse(text);
644
+ fileLog(`${action == null ? void 0 : action.kind} action received `, "Broker", "info");
645
+ this._takeAction(action, ws);
646
+ } catch (error2) {
647
+ fileLog(`parse action message error: ${error2}`, "Broker", "error");
648
+ }
649
+ });
650
+ ws.on("error", (e) => {
651
+ fileLog(`parse action message error: ${e}`, "Broker", "error");
652
+ });
653
+ } else {
654
+ ws.send("Invalid CONNECT ID.");
655
+ fileLog("Invalid CONNECT ID.", "Broker", "warn");
656
+ ws.close();
657
+ }
658
+ }, "wsHandler");
659
+ const server = (0, import_http.createServer)();
660
+ this._webSocketServer = new import_isomorphic_ws.default.Server({
661
+ noServer: true
662
+ });
663
+ this._webSocketServer.on("error", (err) => {
664
+ fileLog(`ws error:
665
+ ${err.message}
666
+ ${err.stack}`, "Broker", "error");
667
+ });
668
+ this._webSocketServer.on("listening", () => {
669
+ fileLog(`WebSocket server is listening on port ${_Broker.DEFAULT_WEB_SOCKET_PORT}`, "Broker", "info");
670
+ });
671
+ this._webSocketServer.on("connection", wsHandler);
672
+ this._webSocketServer.on("close", (code) => {
673
+ fileLog(`WebSocket Server Close with Code ${code}`, "Broker", "warn");
674
+ this._webSocketServer && this._webSocketServer.close();
675
+ this._webSocketServer = void 0;
676
+ });
677
+ server.on("upgrade", (req, socket, head) => {
678
+ var _a3;
679
+ if (req.url) {
680
+ const { pathname } = (0, import_url.parse)(req.url);
681
+ if (pathname === "/") {
682
+ (_a3 = this._webSocketServer) == null ? void 0 : _a3.handleUpgrade(req, socket, head, (ws) => {
683
+ var _a4;
684
+ (_a4 = this._webSocketServer) == null ? void 0 : _a4.emit("connection", ws, req);
685
+ });
686
+ }
687
+ }
688
+ });
689
+ server.listen(_Broker.DEFAULT_WEB_SOCKET_PORT);
690
+ });
691
+ }
692
+ _takeAction(action, client) {
693
+ return __async(this, null, function* () {
694
+ const { kind, payload } = action;
695
+ if (kind === ActionKind.ADD_PUBLISHER) {
696
+ yield this._addPublisher(payload, client);
697
+ }
698
+ if (kind === ActionKind.UPDATE_PUBLISHER) {
699
+ yield this._updatePublisher(payload, client);
700
+ }
701
+ if (kind === ActionKind.ADD_SUBSCRIBER) {
702
+ yield this._addSubscriber(payload, client);
703
+ }
704
+ if (kind === ActionKind.EXIT_SUBSCRIBER) {
705
+ yield this._removeSubscriber(payload, client);
706
+ }
707
+ if (kind === ActionKind.EXIT_PUBLISHER) {
708
+ yield this._removePublisher(payload, client);
709
+ }
710
+ if (kind === ActionKind.ADD_WEB_CLIENT) {
711
+ yield this._addWebClient(payload, client);
712
+ }
713
+ if (kind === ActionKind.NOTIFY_WEB_CLIENT) {
714
+ yield this._notifyWebClient(payload, client);
715
+ }
716
+ if (kind === ActionKind.FETCH_TYPES) {
717
+ yield this._fetchTypes(payload, client);
718
+ }
719
+ if (kind === ActionKind.ADD_DYNAMIC_REMOTE) {
720
+ this._addDynamicRemote(payload);
721
+ }
722
+ });
723
+ }
724
+ _addPublisher(context, client) {
725
+ return __async(this, null, function* () {
726
+ const { name, ip, remoteTypeTarPath } = context != null ? context : {};
727
+ const identifier = getIdentifier({
728
+ name,
729
+ ip
730
+ });
731
+ if (this._publisherMap.has(identifier)) {
732
+ fileLog(`[${ActionKind.ADD_PUBLISHER}] ${identifier} has been added, this action will be ignored`, "Broker", "warn");
733
+ return;
734
+ }
735
+ try {
736
+ const publisher = new Publisher({
737
+ name,
738
+ ip,
739
+ remoteTypeTarPath,
740
+ ws: client
741
+ });
742
+ this._publisherMap.set(identifier, publisher);
743
+ fileLog(`[${ActionKind.ADD_PUBLISHER}] ${identifier} Adding Publisher Succeed`, "Broker", "info");
744
+ const tmpSubScribers = this._getTmpSubScribers(identifier);
745
+ if (tmpSubScribers) {
746
+ fileLog(`[${ActionKind.ADD_PUBLISHER}] consumeTmpSubscriber set ${publisher.name}\u2019s subscribers `, "Broker", "info");
747
+ this._consumeTmpSubScribers(publisher, tmpSubScribers);
748
+ this._clearTmpSubScriberRelation(identifier);
749
+ }
750
+ } catch (err) {
751
+ const msg = error(err, ActionKind.ADD_PUBLISHER, "Broker");
752
+ client.send(msg);
753
+ client.close();
754
+ }
755
+ });
756
+ }
757
+ _updatePublisher(context, client) {
758
+ return __async(this, null, function* () {
759
+ const { name, updateMode, updateKind, updateSourcePaths, remoteTypeTarPath, ip } = context != null ? context : {};
760
+ const identifier = getIdentifier({
761
+ name,
762
+ ip
763
+ });
764
+ if (!this._publisherMap.has(identifier)) {
765
+ fileLog(`[${ActionKind.UPDATE_PUBLISHER}] ${identifier} has not been started, this action will be ignored
766
+ this._publisherMap: ${JSON.stringify(this._publisherMap.entries())}
767
+ `, "Broker", "warn");
768
+ return;
769
+ }
770
+ try {
771
+ const publisher = this._publisherMap.get(identifier);
772
+ fileLog(
773
+ // eslint-disable-next-line max-len
774
+ `[${ActionKind.UPDATE_PUBLISHER}] ${identifier} update, and notify subscribers to update`,
775
+ "Broker",
776
+ "info"
777
+ );
778
+ if (publisher) {
779
+ publisher.notifySubscribers({
780
+ remoteTypeTarPath,
781
+ name,
782
+ updateMode,
783
+ updateKind,
784
+ updateSourcePaths: updateSourcePaths || []
785
+ });
786
+ this._publisherMap.forEach((p) => {
787
+ if (p.name === publisher.name) {
788
+ return;
789
+ }
790
+ const dynamicRemoteInfo = p.dynamicRemoteMap.get(identifier);
791
+ if (dynamicRemoteInfo) {
792
+ fileLog(
793
+ // eslint-disable-next-line max-len
794
+ `dynamicRemoteInfo: ${JSON.stringify(dynamicRemoteInfo)}, identifier:${identifier} publish: ${p.name}`,
795
+ "Broker",
796
+ "info"
797
+ );
798
+ p.fetchRemoteTypes({
799
+ remoteInfo: dynamicRemoteInfo,
800
+ once: false
801
+ });
802
+ }
803
+ });
804
+ }
805
+ } catch (err) {
806
+ const msg = error(err, ActionKind.UPDATE_PUBLISHER, "Broker");
807
+ client.send(msg);
808
+ client.close();
809
+ }
810
+ });
811
+ }
812
+ _fetchTypes(context, _client) {
813
+ return __async(this, null, function* () {
814
+ const { name, ip, remoteInfo } = context != null ? context : {};
815
+ const identifier = getIdentifier({
816
+ name,
817
+ ip
818
+ });
819
+ try {
820
+ const publisher = this._publisherMap.get(identifier);
821
+ fileLog(`[${ActionKind.FETCH_TYPES}] ${identifier} fetch types`, "Broker", "info");
822
+ if (publisher) {
823
+ publisher.fetchRemoteTypes({
824
+ remoteInfo,
825
+ once: true
826
+ });
827
+ }
828
+ } catch (err) {
829
+ fileLog(`[${ActionKind.FETCH_TYPES}] ${identifier} fetch types fail , error info: ${err}`, "Broker", "error");
830
+ }
831
+ });
832
+ }
833
+ _addDynamicRemote(context) {
834
+ const { name, ip, remoteInfo, remoteIp } = context != null ? context : {};
835
+ const identifier = getIdentifier({
836
+ name,
837
+ ip
838
+ });
839
+ const publisher = this._publisherMap.get(identifier);
840
+ const remoteId = getIdentifier({
841
+ name: remoteInfo.name,
842
+ ip: remoteIp
843
+ });
844
+ fileLog(`[${ActionKind.ADD_DYNAMIC_REMOTE}] identifier:${identifier},publisher: ${publisher.name}, remoteId:${remoteId}`, "Broker", "error");
845
+ if (!publisher || publisher.dynamicRemoteMap.has(remoteId)) {
846
+ return;
847
+ }
848
+ publisher.dynamicRemoteMap.set(remoteId, remoteInfo);
849
+ }
850
+ // app1 consumes provider1,provider2. Dependencies at this time: publishers: [provider1, provider2], subscriberName: app1
851
+ // provider1 is app1's remote
852
+ _addSubscriber(context, client) {
853
+ return __async(this, null, function* () {
854
+ const { publishers, name: subscriberName } = context != null ? context : {};
855
+ publishers.forEach((publisher) => {
856
+ const { name, ip } = publisher;
857
+ const identifier = getIdentifier({
858
+ name,
859
+ ip
860
+ });
861
+ if (!this._publisherMap.has(identifier)) {
862
+ fileLog(`[${ActionKind.ADD_SUBSCRIBER}]: ${identifier} has not been started, ${subscriberName} will add the relation to tmp shelter`, "Broker", "warn");
863
+ this._addTmpSubScriberRelation({
864
+ name: getIdentifier({
865
+ name: context.name,
866
+ ip: context.ip
867
+ }),
868
+ client
869
+ }, publisher);
870
+ return;
871
+ }
872
+ try {
873
+ const registeredPublisher = this._publisherMap.get(identifier);
874
+ if (registeredPublisher) {
875
+ registeredPublisher.addSubscriber(getIdentifier({
876
+ name: subscriberName,
877
+ ip: context.ip
878
+ }), client);
879
+ fileLog(
880
+ // eslint-disable-next-line @ies/eden/max-calls-in-template
881
+ `[${ActionKind.ADD_SUBSCRIBER}]: ${identifier} has been started, Adding Subscriber ${subscriberName} Succeed, this.__publisherMap are: ${JSON.stringify(Array.from(this._publisherMap.entries()))}`,
882
+ "Broker",
883
+ "info"
884
+ );
885
+ registeredPublisher.notifySubscriber(getIdentifier({
886
+ name: subscriberName,
887
+ ip: context.ip
888
+ }), {
889
+ updateKind: UpdateKind.UPDATE_TYPE,
890
+ updateMode: UpdateMode.PASSIVE,
891
+ updateSourcePaths: [
892
+ registeredPublisher.name
893
+ ],
894
+ remoteTypeTarPath: registeredPublisher.remoteTypeTarPath,
895
+ name: registeredPublisher.name
896
+ });
897
+ fileLog(
898
+ // eslint-disable-next-line @ies/eden/max-calls-in-template
899
+ `[${ActionKind.ADD_SUBSCRIBER}]: notifySubscriber Subscriber ${subscriberName}, updateMode: "PASSIVE", updateSourcePaths: ${registeredPublisher.name}`,
900
+ "Broker",
901
+ "info"
902
+ );
903
+ }
904
+ } catch (err) {
905
+ const msg = error(err, ActionKind.ADD_SUBSCRIBER, "Broker");
906
+ client.send(msg);
907
+ client.close();
908
+ }
909
+ });
910
+ });
911
+ }
912
+ // Trigger while consumer exit
913
+ _removeSubscriber(context, client) {
914
+ return __async(this, null, function* () {
915
+ const { publishers } = context != null ? context : {};
916
+ const subscriberIdentifier = getIdentifier({
917
+ name: context == null ? void 0 : context.name,
918
+ ip: context == null ? void 0 : context.ip
919
+ });
920
+ publishers.forEach((publisher) => {
921
+ const { name, ip } = publisher;
922
+ const identifier = getIdentifier({
923
+ name,
924
+ ip
925
+ });
926
+ const registeredPublisher = this._publisherMap.get(identifier);
927
+ if (!registeredPublisher) {
928
+ fileLog(`[${ActionKind.EXIT_SUBSCRIBER}], ${identifier} does not exit `, "Broker", "warn");
929
+ return;
930
+ }
931
+ try {
932
+ fileLog(`[${ActionKind.EXIT_SUBSCRIBER}], ${identifier} will exit `, "Broker", "INFO");
933
+ registeredPublisher.removeSubscriber(subscriberIdentifier);
934
+ this._clearTmpSubScriberRelation(identifier);
935
+ if (!registeredPublisher.hasSubscribes) {
936
+ this._publisherMap.delete(identifier);
937
+ }
938
+ if (!this.hasPublishers) {
939
+ this.exit();
940
+ }
941
+ } catch (err) {
942
+ const msg = error(err, ActionKind.EXIT_SUBSCRIBER, "Broker");
943
+ client.send(msg);
944
+ client.close();
945
+ }
946
+ });
947
+ });
948
+ }
949
+ _removePublisher(context, client) {
950
+ return __async(this, null, function* () {
951
+ const { name, ip } = context != null ? context : {};
952
+ const identifier = getIdentifier({
953
+ name,
954
+ ip
955
+ });
956
+ const publisher = this._publisherMap.get(identifier);
957
+ if (!publisher) {
958
+ fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier}} has not been added, this action will be ingored`, "Broker", "warn");
959
+ return;
960
+ }
961
+ try {
962
+ const { subscribers } = publisher;
963
+ subscribers.forEach((subscriber, subscriberIdentifier) => {
964
+ this._addTmpSubScriberRelation({
965
+ name: subscriberIdentifier,
966
+ client: subscriber
967
+ }, {
968
+ name: publisher.name,
969
+ ip: publisher.ip
970
+ });
971
+ fileLog(
972
+ // eslint-disable-next-line max-len
973
+ `[${ActionKind.EXIT_PUBLISHER}]: ${identifier} is removing , subscriber: ${subscriberIdentifier} will be add tmpSubScriberRelation`,
974
+ "Broker",
975
+ "info"
976
+ );
977
+ });
978
+ this._publisherMap.delete(identifier);
979
+ fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier} is removed `, "Broker", "info");
980
+ if (!this.hasPublishers) {
981
+ fileLog(`[${ActionKind.EXIT_PUBLISHER}]: _publisherMap is empty, all server will exit `, "Broker", "warn");
982
+ this.exit();
983
+ }
984
+ } catch (err) {
985
+ const msg = error(err, ActionKind.EXIT_PUBLISHER, "Broker");
986
+ client.send(msg);
987
+ client.close();
988
+ }
989
+ });
990
+ }
991
+ _addWebClient(context, client) {
992
+ return __async(this, null, function* () {
993
+ const { name } = context != null ? context : {};
994
+ const identifier = getIdentifier({
995
+ name
996
+ });
997
+ if (this._webClientMap.has(identifier)) {
998
+ fileLog(`${identifier}} has been added, this action will override prev WebClient`, "Broker", "warn");
999
+ }
1000
+ try {
1001
+ this._webClientMap.set(identifier, client);
1002
+ fileLog(`${identifier} adding WebClient Succeed`, "Broker", "info");
1003
+ } catch (err) {
1004
+ const msg = error(err, ActionKind.ADD_WEB_CLIENT, "Broker");
1005
+ client.send(msg);
1006
+ client.close();
1007
+ }
1008
+ });
1009
+ }
1010
+ _notifyWebClient(context, client) {
1011
+ return __async(this, null, function* () {
1012
+ const { name, updateMode } = context != null ? context : {};
1013
+ const identifier = getIdentifier({
1014
+ name
1015
+ });
1016
+ const webClient = this._webClientMap.get(identifier);
1017
+ if (!webClient) {
1018
+ fileLog(`[${ActionKind.NOTIFY_WEB_CLIENT}] ${identifier} has not been added, this action will be ignored`, "Broker", "warn");
1019
+ return;
1020
+ }
1021
+ try {
1022
+ const api = new ReloadWebClientAPI({
1023
+ name,
1024
+ updateMode
1025
+ });
1026
+ webClient.send(JSON.stringify(api));
1027
+ fileLog(`[${ActionKind.NOTIFY_WEB_CLIENT}] Notify ${name} WebClient Succeed`, "Broker", "info");
1028
+ } catch (err) {
1029
+ const msg = error(err, ActionKind.NOTIFY_WEB_CLIENT, "Broker");
1030
+ client.send(msg);
1031
+ client.close();
1032
+ }
1033
+ });
1034
+ }
1035
+ // app1 consumes provider1, and provider1 not launch. this._tmpSubscriberShelter at this time: {provider1: Map{subscribers: Map{app1: app1+ip+client'}, timestamp: 'xx'} }
1036
+ _addTmpSubScriberRelation(subscriber, publisher) {
1037
+ const publisherIdentifier = getIdentifier({
1038
+ name: publisher.name,
1039
+ ip: publisher.ip
1040
+ });
1041
+ const subscriberIdentifier = subscriber.name;
1042
+ const shelter = this._tmpSubscriberShelter.get(publisherIdentifier);
1043
+ if (!shelter) {
1044
+ const map = /* @__PURE__ */ new Map();
1045
+ map.set(subscriberIdentifier, subscriber);
1046
+ this._tmpSubscriberShelter.set(publisherIdentifier, {
1047
+ subscribers: map,
1048
+ timestamp: Date.now()
1049
+ });
1050
+ fileLog(`[AddTmpSubscriberRelation] ${publisherIdentifier}'s subscriber has ${subscriberIdentifier} `, "Broker", "info");
1051
+ return;
1052
+ }
1053
+ const tmpSubScriberShelterSubscriber = shelter.subscribers.get(subscriberIdentifier);
1054
+ if (tmpSubScriberShelterSubscriber) {
1055
+ fileLog(`[AddTmpSubscriberRelation] ${publisherIdentifier} and ${subscriberIdentifier} relation has been added`, "Broker", "warn");
1056
+ shelter.subscribers.set(subscriberIdentifier, subscriber);
1057
+ shelter.timestamp = Date.now();
1058
+ } else {
1059
+ fileLog(
1060
+ // eslint-disable-next-line max-len
1061
+ `AddTmpSubscriberLog ${publisherIdentifier}'s shelter has been added, update shelter.subscribers ${subscriberIdentifier}`,
1062
+ "Broker",
1063
+ "warn"
1064
+ );
1065
+ shelter.subscribers.set(subscriberIdentifier, subscriber);
1066
+ }
1067
+ }
1068
+ _getTmpSubScribers(publisherIdentifier) {
1069
+ var _a3;
1070
+ return (_a3 = this._tmpSubscriberShelter.get(publisherIdentifier)) == null ? void 0 : _a3.subscribers;
1071
+ }
1072
+ // after adding publisher, it will change the temp subscriber to regular subscriber
1073
+ _consumeTmpSubScribers(publisher, tmpSubScribers) {
1074
+ tmpSubScribers.forEach((tmpSubScriber, identifier) => {
1075
+ fileLog(`notifyTmpSubScribers ${publisher.name} will be add a subscriber: ${identifier} `, "Broker", "warn");
1076
+ publisher.addSubscriber(identifier, tmpSubScriber.client);
1077
+ publisher.notifySubscriber(identifier, {
1078
+ updateKind: UpdateKind.UPDATE_TYPE,
1079
+ updateMode: UpdateMode.PASSIVE,
1080
+ updateSourcePaths: [
1081
+ publisher.name
1082
+ ],
1083
+ remoteTypeTarPath: publisher.remoteTypeTarPath,
1084
+ name: publisher.name
1085
+ });
1086
+ });
1087
+ }
1088
+ _clearTmpSubScriberRelation(identifier) {
1089
+ this._tmpSubscriberShelter.delete(identifier);
1090
+ }
1091
+ _clearTmpSubScriberRelations() {
1092
+ this._tmpSubscriberShelter.clear();
1093
+ }
1094
+ _disconnect() {
1095
+ this._publisherMap.forEach((publisher) => {
1096
+ publisher.close();
1097
+ });
1098
+ }
1099
+ // Every day on 0/6/9/12/15//18, Publishers that have not been connected within 1.5 hours will be cleared regularly.
1100
+ // If process.env.FEDERATION_SERVER_TEST is set, it will be read at a specified time.
1101
+ _setSchedule() {
1102
+ const rule = new import_node_schedule.default.RecurrenceRule();
1103
+ if (Number(process.env["FEDERATION_SERVER_TEST"])) {
1104
+ const interval = Number(process.env["FEDERATION_SERVER_TEST"]) / 1e3;
1105
+ const second = [];
1106
+ for (let i = 0; i < 60; i = i + interval) {
1107
+ second.push(i);
1108
+ }
1109
+ rule.second = second;
1110
+ } else {
1111
+ rule.second = 0;
1112
+ rule.hour = [
1113
+ 0,
1114
+ 3,
1115
+ 6,
1116
+ 9,
1117
+ 12,
1118
+ 15,
1119
+ 18
1120
+ ];
1121
+ rule.minute = 0;
1122
+ }
1123
+ const serverTest = Number(process.env["FEDERATION_SERVER_TEST"]);
1124
+ this._scheduleJob = import_node_schedule.default.scheduleJob(rule, () => {
1125
+ this._tmpSubscriberShelter.forEach((tmpSubscriber, identifier) => {
1126
+ fileLog(` _clearTmpSubScriberRelation ${identifier}, ${Date.now() - tmpSubscriber.timestamp >= (process.env["GARFISH_MODULE_SERVER_TEST"] ? serverTest : _Broker.DEFAULT_WAITING_TIME)}`, "Broker", "info");
1127
+ if (Date.now() - tmpSubscriber.timestamp >= (process.env["FEDERATION_SERVER_TEST"] ? serverTest : _Broker.DEFAULT_WAITING_TIME)) {
1128
+ this._clearTmpSubScriberRelation(identifier);
1129
+ }
1130
+ });
1131
+ });
1132
+ }
1133
+ _clearSchedule() {
1134
+ if (!this._scheduleJob) {
1135
+ return;
1136
+ }
1137
+ this._scheduleJob.cancel();
1138
+ this._scheduleJob = null;
1139
+ }
1140
+ _stopWhenSIGTERMOrSIGINT() {
1141
+ process.on("SIGTERM", () => {
1142
+ this.exit();
1143
+ });
1144
+ process.on("SIGINT", () => {
1145
+ this.exit();
1146
+ });
1147
+ }
1148
+ _handleUnexpectedExit() {
1149
+ process.on("unhandledRejection", (error2) => {
1150
+ console.error("Unhandled Rejection Error: ", error2);
1151
+ fileLog(`Unhandled Rejection Error: ${error2}`, "Broker", "fatal");
1152
+ process.exit(1);
1153
+ });
1154
+ process.on("uncaughtException", (error2) => {
1155
+ console.error("Unhandled Exception Error: ", error2);
1156
+ fileLog(`Unhandled Rejection Error: ${error2}`, "Broker", "fatal");
1157
+ process.exit(1);
1158
+ });
1159
+ }
1160
+ start() {
1161
+ return __async(this, null, function* () {
1162
+ });
1163
+ }
1164
+ exit() {
1165
+ const brokerExitLog = new BrokerExitLog();
1166
+ this.broadcast(JSON.stringify(brokerExitLog));
1167
+ this._disconnect();
1168
+ this._clearSchedule();
1169
+ this._clearTmpSubScriberRelations();
1170
+ this._webSocketServer && this._webSocketServer.close();
1171
+ this._secureWebSocketServer && this._secureWebSocketServer.close();
1172
+ process.exit(0);
1173
+ }
1174
+ broadcast(message) {
1175
+ var _a3, _b;
1176
+ fileLog(`[broadcast] exit info : ${JSON.stringify(message)}`, "Broker", "warn");
1177
+ (_a3 = this._webSocketServer) == null ? void 0 : _a3.clients.forEach((client) => {
1178
+ client.send(JSON.stringify(message));
1179
+ });
1180
+ (_b = this._secureWebSocketServer) == null ? void 0 : _b.clients.forEach((client) => {
1181
+ client.send(JSON.stringify(message));
1182
+ });
1183
+ }
1184
+ };
1185
+ __name(_Broker, "Broker");
1186
+ __publicField(_Broker, "WEB_SOCKET_CONNECT_MAGIC_ID", WEB_SOCKET_CONNECT_MAGIC_ID);
1187
+ __publicField(_Broker, "DEFAULT_WEB_SOCKET_PORT", DEFAULT_WEB_SOCKET_PORT);
1188
+ __publicField(_Broker, "DEFAULT_SECURE_WEB_SOCKET_PORT", 16324);
1189
+ __publicField(_Broker, "DEFAULT_WAITING_TIME", 1.5 * 60 * 60 * 1e3);
1190
+ var Broker = _Broker;
1191
+
1192
+ // packages/dts-plugin/src/server/broker/createBroker.ts
1193
+ var import_child_process = require("child_process");
1194
+ var import_path2 = __toESM(require("path"));
1195
+ function createBroker() {
1196
+ const startBrokerPath = import_path2.default.resolve(__dirname, "./start-broker.js");
1197
+ const sub = (0, import_child_process.fork)(startBrokerPath, [], {
1198
+ detached: true,
1199
+ stdio: "ignore",
1200
+ env: process.env
1201
+ });
1202
+ sub.send("start");
1203
+ sub.unref();
1204
+ return sub;
1205
+ }
1206
+ __name(createBroker, "createBroker");
1207
+
1208
+ // packages/dts-plugin/src/server/DevServer.ts
1209
+ var _ModuleFederationDevServer = class _ModuleFederationDevServer {
1210
+ constructor(ctx) {
1211
+ __publicField(this, "_remotes");
1212
+ __publicField(this, "_ip");
1213
+ __publicField(this, "_name");
1214
+ __publicField(this, "_remoteTypeTarPath");
1215
+ __publicField(this, "_publishWebSocket", null);
1216
+ __publicField(this, "_subscriberWebsocketMap", {});
1217
+ __publicField(this, "_reconnect", true);
1218
+ __publicField(this, "_reconnectTimes", 0);
1219
+ __publicField(this, "_isConnected", false);
1220
+ __publicField(this, "_isReconnecting", false);
1221
+ __publicField(this, "_updateCallback", /* @__PURE__ */ __name(() => Promise.resolve(void 0), "_updateCallback"));
1222
+ const { name, remotes, remoteTypeTarPath, updateCallback: updateCallback2 } = ctx;
1223
+ this._ip = getIPV4();
1224
+ this._name = name;
1225
+ this._remotes = remotes;
1226
+ this._remoteTypeTarPath = remoteTypeTarPath;
1227
+ this._updateCallback = updateCallback2;
1228
+ this._stopWhenSIGTERMOrSIGINT();
1229
+ this._handleUnexpectedExit();
1230
+ this._connectPublishToServer();
1231
+ }
1232
+ _connectPublishToServer() {
1233
+ if (!this._reconnect) {
1234
+ return;
1235
+ }
1236
+ fileLog(`Publisher:${this._name} Trying to connect to ws://${this._ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}...`, MF_SERVER_IDENTIFIER, "info");
1237
+ this._publishWebSocket = new import_isomorphic_ws2.default(`ws://${this._ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}?WEB_SOCKET_CONNECT_MAGIC_ID=${Broker.WEB_SOCKET_CONNECT_MAGIC_ID}`);
1238
+ this._publishWebSocket.on("open", () => {
1239
+ var _a3;
1240
+ fileLog(`Current pid: ${process.pid}, publisher:${this._name} connected to ws://${this._ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}, starting service...`, MF_SERVER_IDENTIFIER, "info");
1241
+ this._isConnected = true;
1242
+ const startGarfishModule = new AddPublisherAction({
1243
+ name: this._name,
1244
+ ip: this._ip,
1245
+ remoteTypeTarPath: this._remoteTypeTarPath
1246
+ });
1247
+ (_a3 = this._publishWebSocket) == null ? void 0 : _a3.send(JSON.stringify(startGarfishModule));
1248
+ this._connectSubscribers();
1249
+ });
1250
+ this._publishWebSocket.on("message", (message) => __async(this, null, function* () {
1251
+ var _a3, _b;
1252
+ try {
1253
+ const parsedMessage = JSON.parse(message.toString());
1254
+ if (parsedMessage.type === "Log") {
1255
+ if (parsedMessage.kind === LogKind.BrokerExitLog) {
1256
+ fileLog(`Receive broker exit signal, ${this._name} service will exit...`, MF_SERVER_IDENTIFIER, "warn");
1257
+ this._exit();
1258
+ }
1259
+ }
1260
+ if (parsedMessage.type === "API") {
1261
+ if (parsedMessage.kind === APIKind.FETCH_TYPES) {
1262
+ const { payload: { remoteInfo } } = parsedMessage;
1263
+ fileLog(`${this._name} Receive broker FETCH_TYPES, payload as follows: ${JSON.stringify(remoteInfo, null, 2)}.`, MF_SERVER_IDENTIFIER, "info");
1264
+ yield this.fetchDynamicRemoteTypes({
1265
+ remoteInfo
1266
+ });
1267
+ }
1268
+ }
1269
+ } catch (err) {
1270
+ console.error(err);
1271
+ const exitPublisher = new ExitPublisherAction({
1272
+ name: this._name,
1273
+ ip: this._ip
1274
+ });
1275
+ const exitSubscriber = new ExitSubscriberAction({
1276
+ name: this._name,
1277
+ ip: this._ip,
1278
+ publishers: this._remotes.map((remote) => ({
1279
+ name: remote.name,
1280
+ ip: remote.ip
1281
+ }))
1282
+ });
1283
+ (_a3 = this._publishWebSocket) == null ? void 0 : _a3.send(JSON.stringify(exitPublisher));
1284
+ (_b = this._publishWebSocket) == null ? void 0 : _b.send(JSON.stringify(exitSubscriber));
1285
+ fileLog("Parse messages error, ModuleFederationDevServer will exit...", MF_SERVER_IDENTIFIER, "fatal");
1286
+ this._exit();
1287
+ }
1288
+ }));
1289
+ this._publishWebSocket.on("close", (code) => {
1290
+ fileLog(`Connection closed with code ${code}.`, MF_SERVER_IDENTIFIER, "warn");
1291
+ this._publishWebSocket && this._publishWebSocket.close();
1292
+ this._publishWebSocket = null;
1293
+ if (!this._reconnect) {
1294
+ return;
1295
+ }
1296
+ const reconnectTime = fib(++this._reconnectTimes);
1297
+ fileLog(`start reconnecting to server after ${reconnectTime}s.`, MF_SERVER_IDENTIFIER, "info");
1298
+ setTimeout(() => this._connectPublishToServer(), reconnectTime * 1e3);
1299
+ });
1300
+ this._publishWebSocket.on("error", this._tryCreateBackgroundBroker.bind(this));
1301
+ }
1302
+ // Associate the remotes(Subscriber) to the Broker
1303
+ _connectSubscriberToServer(remote) {
1304
+ const { name, ip } = remote;
1305
+ fileLog(`remote module:${name} trying to connect to ws://${ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}...`, MF_SERVER_IDENTIFIER, "info");
1306
+ const identifier = getIdentifier({
1307
+ name,
1308
+ ip
1309
+ });
1310
+ this._subscriberWebsocketMap[identifier] = new import_isomorphic_ws2.default(`ws://${ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}?WEB_SOCKET_CONNECT_MAGIC_ID=${Broker.WEB_SOCKET_CONNECT_MAGIC_ID}`);
1311
+ this._subscriberWebsocketMap[identifier].on("open", () => {
1312
+ fileLog(`Current pid: ${process.pid} remote module: ${name} connected to ws://${ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}, starting service...`, MF_SERVER_IDENTIFIER, "info");
1313
+ const addSubscriber = new AddSubscriberAction({
1314
+ name: this._name,
1315
+ ip: this._ip,
1316
+ publishers: [
1317
+ {
1318
+ name,
1319
+ ip
1320
+ }
1321
+ ]
1322
+ });
1323
+ this._subscriberWebsocketMap[identifier].send(JSON.stringify(addSubscriber));
1324
+ });
1325
+ this._subscriberWebsocketMap[identifier].on("message", (message) => __async(this, null, function* () {
1326
+ try {
1327
+ const parsedMessage = JSON.parse(message.toString());
1328
+ if (parsedMessage.type === "Log") {
1329
+ if (parsedMessage.kind === LogKind.BrokerExitLog) {
1330
+ fileLog(`${identifier}'s Server exit, thus ${identifier} will no longer has reload ability.`, MF_SERVER_IDENTIFIER, "warn");
1331
+ this._exit();
1332
+ }
1333
+ }
1334
+ if (parsedMessage.type === "API") {
1335
+ if (parsedMessage.kind === APIKind.UPDATE_SUBSCRIBER) {
1336
+ const { payload: { updateKind, updateSourcePaths, name: subscribeName, remoteTypeTarPath, updateMode } } = parsedMessage;
1337
+ yield this._updateSubscriber({
1338
+ remoteTypeTarPath,
1339
+ name: subscribeName,
1340
+ updateKind,
1341
+ updateMode,
1342
+ updateSourcePaths
1343
+ });
1344
+ }
1345
+ }
1346
+ } catch (err) {
1347
+ console.error(err);
1348
+ const exitSubscriber = new ExitSubscriberAction({
1349
+ name: this._name,
1350
+ ip: this._ip,
1351
+ publishers: [
1352
+ {
1353
+ name,
1354
+ ip
1355
+ }
1356
+ ]
1357
+ });
1358
+ this._subscriberWebsocketMap[identifier].send(JSON.stringify(exitSubscriber));
1359
+ fileLog(`${identifier} exit,
1360
+ error: ${err instanceof Error ? err.toString() : JSON.stringify(err)}
1361
+ `, MF_SERVER_IDENTIFIER, "warn");
1362
+ }
1363
+ }));
1364
+ this._subscriberWebsocketMap[identifier].on("close", (code) => {
1365
+ fileLog(`Connection closed with code ${code}.`, MF_SERVER_IDENTIFIER, "warn");
1366
+ this._subscriberWebsocketMap[identifier] && this._subscriberWebsocketMap[identifier].close();
1367
+ delete this._subscriberWebsocketMap[identifier];
1368
+ });
1369
+ }
1370
+ _connectSubscribers() {
1371
+ this._remotes.forEach((remote) => {
1372
+ this._connectSubscriberToServer(remote);
1373
+ });
1374
+ }
1375
+ // app1 consumes provider1. And the function will be triggered when provider1 code change.
1376
+ _updateSubscriber(options) {
1377
+ return __async(this, null, function* () {
1378
+ var _a3;
1379
+ const { updateMode, updateKind, updateSourcePaths, name, remoteTypeTarPath, remoteInfo } = options;
1380
+ fileLog(
1381
+ // eslint-disable-next-line max-len
1382
+ `[_updateSubscriber] run, options: ${JSON.stringify(options, null, 2)}`,
1383
+ MF_SERVER_IDENTIFIER,
1384
+ "warn"
1385
+ );
1386
+ if (updateMode === UpdateMode.PASSIVE && updateSourcePaths.includes(this._name)) {
1387
+ fileLog(
1388
+ // eslint-disable-next-line max-len
1389
+ `[_updateSubscriber] run, updateSourcePaths:${updateSourcePaths} includes ${this._name}, update ignore!`,
1390
+ MF_SERVER_IDENTIFIER,
1391
+ "warn"
1392
+ );
1393
+ return;
1394
+ }
1395
+ if (updateSourcePaths.slice(-1)[0] === this._name) {
1396
+ fileLog(`[_updateSubscriber] run, updateSourcePaths:${updateSourcePaths} ends is ${this._name}, update ignore!`, MF_SERVER_IDENTIFIER, "warn");
1397
+ return;
1398
+ }
1399
+ fileLog(
1400
+ // eslint-disable-next-line max-len
1401
+ `[_updateSubscriber] run, updateSourcePaths:${updateSourcePaths}, current module:${this._name}, update start...`,
1402
+ MF_SERVER_IDENTIFIER,
1403
+ "info"
1404
+ );
1405
+ yield this._updateCallback({
1406
+ name,
1407
+ updateMode,
1408
+ updateKind,
1409
+ updateSourcePaths,
1410
+ remoteTypeTarPath,
1411
+ remoteInfo
1412
+ });
1413
+ const newUpdateSourcePaths = updateSourcePaths.concat(this._name);
1414
+ const updatePublisher = new UpdatePublisherAction({
1415
+ name: this._name,
1416
+ ip: this._ip,
1417
+ updateMode: UpdateMode.PASSIVE,
1418
+ updateKind,
1419
+ updateSourcePaths: newUpdateSourcePaths,
1420
+ remoteTypeTarPath: this._remoteTypeTarPath
1421
+ });
1422
+ fileLog(
1423
+ // eslint-disable-next-line max-len
1424
+ `[_updateSubscriber] run, updateSourcePaths:${newUpdateSourcePaths}, update publisher ${this._name} start...`,
1425
+ MF_SERVER_IDENTIFIER,
1426
+ "info"
1427
+ );
1428
+ (_a3 = this._publishWebSocket) == null ? void 0 : _a3.send(JSON.stringify(updatePublisher));
1429
+ });
1430
+ }
1431
+ _tryCreateBackgroundBroker(err) {
1432
+ if (!((err == null ? void 0 : err.code) === "ECONNREFUSED" && err.port === Broker.DEFAULT_WEB_SOCKET_PORT)) {
1433
+ fileLog(`websocket error: ${err.stack}`, MF_SERVER_IDENTIFIER, "fatal");
1434
+ return;
1435
+ }
1436
+ fileLog(`Failed to connect to ws://${this._ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}...`, MF_SERVER_IDENTIFIER, "fatal");
1437
+ this._isReconnecting = true;
1438
+ setTimeout(() => {
1439
+ this._isReconnecting = false;
1440
+ if (this._reconnect === false) {
1441
+ return;
1442
+ }
1443
+ fileLog("Creating new background broker...", MF_SERVER_IDENTIFIER, "warn");
1444
+ const broker = createBroker();
1445
+ broker.on("message", (message) => {
1446
+ if (message === "ready") {
1447
+ fileLog("background broker started.", MF_SERVER_IDENTIFIER, "info");
1448
+ this._reconnectTimes = 1;
1449
+ if (process.send) {
1450
+ process.send("ready");
1451
+ }
1452
+ }
1453
+ });
1454
+ }, Math.ceil(100 * Math.random()));
1455
+ }
1456
+ _stopWhenSIGTERMOrSIGINT() {
1457
+ process.on("SIGTERM", () => {
1458
+ fileLog(`Process(${process.pid}) SIGTERM, ModuleFederationDevServer will exit...`, MF_SERVER_IDENTIFIER, "warn");
1459
+ this._exit();
1460
+ });
1461
+ process.on("SIGINT", () => {
1462
+ fileLog(`Process(${process.pid}) SIGINT, ModuleFederationDevServer will exit...`, MF_SERVER_IDENTIFIER, "warn");
1463
+ this._exit();
1464
+ });
1465
+ }
1466
+ _handleUnexpectedExit() {
1467
+ process.on("unhandledRejection", (error2) => {
1468
+ if (this._isReconnecting) {
1469
+ return;
1470
+ }
1471
+ console.error("Unhandled Rejection Error: ", error2);
1472
+ fileLog(`Process(${process.pid}) unhandledRejection, garfishModuleServer will exit...`, MF_SERVER_IDENTIFIER, "error");
1473
+ this._exit();
1474
+ });
1475
+ process.on("uncaughtException", (error2) => {
1476
+ if (this._isReconnecting) {
1477
+ return;
1478
+ }
1479
+ console.error("Unhandled Exception Error: ", error2);
1480
+ fileLog(`Process(${process.pid}) uncaughtException, garfishModuleServer will exit...`, MF_SERVER_IDENTIFIER, "error");
1481
+ this._exit();
1482
+ });
1483
+ }
1484
+ _exit() {
1485
+ this._reconnect = false;
1486
+ if (this._publishWebSocket) {
1487
+ const exitPublisher = new ExitPublisherAction({
1488
+ name: this._name,
1489
+ ip: this._ip
1490
+ });
1491
+ this._publishWebSocket.send(JSON.stringify(exitPublisher));
1492
+ this._publishWebSocket.on("message", (message) => {
1493
+ const parsedMessage = JSON.parse(message.toString());
1494
+ fileLog(`[${parsedMessage.kind}]: ${JSON.stringify(parsedMessage)}`, MF_SERVER_IDENTIFIER, "info");
1495
+ });
1496
+ }
1497
+ if (this._publishWebSocket) {
1498
+ this._publishWebSocket.close();
1499
+ this._publishWebSocket = null;
1500
+ }
1501
+ process.exit(0);
1502
+ }
1503
+ exit() {
1504
+ this._exit();
1505
+ }
1506
+ update(options) {
1507
+ if (!this._publishWebSocket || !this._isConnected) {
1508
+ return;
1509
+ }
1510
+ const { updateKind, updateMode, updateSourcePaths } = options;
1511
+ fileLog(`update run, ${this._name} module update, updateKind: ${updateKind}, updateMode: ${updateMode}, updateSourcePaths: ${updateSourcePaths}`, MF_SERVER_IDENTIFIER, "info");
1512
+ if (updateKind === UpdateKind.RELOAD_PAGE) {
1513
+ const notifyWebClient = new NotifyWebClientAction({
1514
+ name: this._name,
1515
+ updateMode
1516
+ });
1517
+ this._publishWebSocket.send(JSON.stringify(notifyWebClient));
1518
+ return;
1519
+ }
1520
+ const updatePublisher = new UpdatePublisherAction({
1521
+ name: this._name,
1522
+ ip: this._ip,
1523
+ updateMode,
1524
+ updateKind,
1525
+ updateSourcePaths: [
1526
+ this._name
1527
+ ],
1528
+ remoteTypeTarPath: this._remoteTypeTarPath
1529
+ });
1530
+ this._publishWebSocket.send(JSON.stringify(updatePublisher));
1531
+ }
1532
+ fetchDynamicRemoteTypes(options) {
1533
+ return __async(this, null, function* () {
1534
+ const { remoteInfo, once } = options;
1535
+ const updateMode = UpdateMode.PASSIVE;
1536
+ const updateKind = UpdateKind.UPDATE_TYPE;
1537
+ fileLog(`fetchDynamicRemoteTypes: remoteInfo: ${JSON.stringify(remoteInfo)}`, MF_SERVER_IDENTIFIER, "info");
1538
+ yield this._updateCallback({
1539
+ name: this._name,
1540
+ updateMode,
1541
+ updateKind,
1542
+ updateSourcePaths: [],
1543
+ remoteTypeTarPath: "",
1544
+ remoteInfo,
1545
+ once
1546
+ });
1547
+ const updatePublisher = new UpdatePublisherAction({
1548
+ name: this._name,
1549
+ ip: this._ip,
1550
+ updateMode,
1551
+ updateKind,
1552
+ updateSourcePaths: [
1553
+ this._name
1554
+ ],
1555
+ remoteTypeTarPath: this._remoteTypeTarPath
1556
+ });
1557
+ this._publishWebSocket.send(JSON.stringify(updatePublisher));
1558
+ });
1559
+ }
1560
+ };
1561
+ __name(_ModuleFederationDevServer, "ModuleFederationDevServer");
1562
+ var ModuleFederationDevServer = _ModuleFederationDevServer;
1563
+
1564
+ // packages/dts-plugin/src/server/createKoaServer.ts
1565
+ var import_fs_extra = __toESM(require("fs-extra"));
1566
+ var import_koa = __toESM(require("koa"));
1567
+ function createKoaServer(options) {
1568
+ return __async(this, null, function* () {
1569
+ const { typeTarPath } = options;
1570
+ const freeport = yield getFreePort();
1571
+ const app = new import_koa.default();
1572
+ app.use((ctx, next) => __async(this, null, function* () {
1573
+ if (ctx.path === `/${DEFAULT_TAR_NAME}`) {
1574
+ ctx.status = 200;
1575
+ ctx.body = import_fs_extra.default.createReadStream(typeTarPath);
1576
+ ctx.response.type = "application/x-gzip";
1577
+ } else {
1578
+ yield next();
1579
+ }
1580
+ }));
1581
+ app.listen(freeport);
1582
+ return {
1583
+ server: app,
1584
+ serverAddress: `http://${getIPV4()}:${freeport}`
1585
+ };
1586
+ });
1587
+ }
1588
+ __name(createKoaServer, "createKoaServer");
1589
+
1590
+ // packages/dts-plugin/src/core/lib/archiveHandler.ts
1591
+ var retrieveTypesZipPath = /* @__PURE__ */ __name((mfTypesPath, remoteOptions) => (0, import_path3.join)(mfTypesPath.replace(remoteOptions.typesFolder, ""), `${remoteOptions.typesFolder}.zip`), "retrieveTypesZipPath");
1592
+ var createTypesArchive = /* @__PURE__ */ __name((tsConfig, remoteOptions) => __async(void 0, null, function* () {
1593
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
1594
+ const zip = new import_adm_zip.default();
1595
+ zip.addLocalFolder(mfTypesPath);
1596
+ return zip.writeZipPromise(retrieveTypesZipPath(mfTypesPath, remoteOptions));
1597
+ }), "createTypesArchive");
1598
+ var downloadErrorLogger = /* @__PURE__ */ __name((destinationFolder, fileToDownload) => (reason) => {
1599
+ throw __spreadProps(__spreadValues({}, reason), {
1600
+ message: `Network error: Unable to download federated mocks for '${destinationFolder}' from '${fileToDownload}' because '${reason.message}'`
1601
+ });
1602
+ }, "downloadErrorLogger");
1603
+ var retrieveTypesArchiveDestinationPath = /* @__PURE__ */ __name((hostOptions, destinationFolder) => {
1604
+ return (0, import_path3.resolve)(hostOptions.context, hostOptions.typesFolder, destinationFolder);
1605
+ }, "retrieveTypesArchiveDestinationPath");
1606
+ var downloadTypesArchive = /* @__PURE__ */ __name((hostOptions) => {
1607
+ let retries = 0;
1608
+ return (_0) => __async(void 0, [_0], function* ([destinationFolder, fileToDownload]) {
1609
+ const destinationPath = retrieveTypesArchiveDestinationPath(hostOptions, destinationFolder);
1610
+ while (retries++ < hostOptions.maxRetries) {
1611
+ try {
1612
+ const url = fileToDownload;
1613
+ const response = yield axiosGet(url, {
1614
+ responseType: "arraybuffer"
1615
+ }).catch(downloadErrorLogger(destinationFolder, url));
1616
+ try {
1617
+ if (hostOptions.deleteTypesFolder) {
1618
+ yield (0, import_promises.rm)(destinationPath, {
1619
+ recursive: true,
1620
+ force: true
1621
+ });
1622
+ }
1623
+ } catch (error2) {
1624
+ fileLog(`Unable to remove types folder, ${error2}`, "downloadTypesArchive", "error");
1625
+ }
1626
+ const zip = new import_adm_zip.default(Buffer.from(response.data));
1627
+ zip.extractAllTo(destinationPath, true);
1628
+ return [
1629
+ destinationFolder,
1630
+ destinationPath
1631
+ ];
1632
+ } catch (error2) {
1633
+ fileLog(`Error during types archive download: ${(error2 == null ? void 0 : error2.message) || "unknown error"}`, "downloadTypesArchive", "error");
1634
+ if (retries >= hostOptions.maxRetries) {
1635
+ if (hostOptions.abortOnError !== false) {
1636
+ throw error2;
1637
+ }
1638
+ return void 0;
1639
+ }
1640
+ }
1641
+ }
1642
+ });
1643
+ }, "downloadTypesArchive");
1644
+
1645
+ // packages/dts-plugin/src/core/configurations/hostPlugin.ts
1646
+ var import_sdk3 = require("@module-federation/sdk");
1647
+ var import_managers = require("@module-federation/managers");
1648
+ var defaultOptions = {
1649
+ typesFolder: "@mf-types",
1650
+ remoteTypesFolder: "@mf-types",
1651
+ deleteTypesFolder: true,
1652
+ maxRetries: 3,
1653
+ implementation: "",
1654
+ context: process.cwd(),
1655
+ abortOnError: true,
1656
+ consumeAPITypes: false
1657
+ };
1658
+ var buildZipUrl = /* @__PURE__ */ __name((hostOptions, url) => {
1659
+ const remoteUrl = new URL(url, "file:");
1660
+ const pathnameWithoutEntry = remoteUrl.pathname.split("/").slice(0, -1).join("/");
1661
+ remoteUrl.pathname = `${pathnameWithoutEntry}/${hostOptions.remoteTypesFolder}.zip`;
1662
+ return remoteUrl.protocol === "file:" ? remoteUrl.pathname : remoteUrl.href;
1663
+ }, "buildZipUrl");
1664
+ var buildApiTypeUrl = /* @__PURE__ */ __name((zipUrl) => {
1665
+ if (!zipUrl) {
1666
+ return void 0;
1667
+ }
1668
+ return zipUrl.replace(".zip", ".d.ts");
1669
+ }, "buildApiTypeUrl");
1670
+ var retrieveRemoteInfo = /* @__PURE__ */ __name((options) => {
1671
+ const { hostOptions, remoteAlias, remote } = options;
1672
+ let decodedRemote = remote;
1673
+ if (decodedRemote.startsWith(import_sdk3.ENCODE_NAME_PREFIX)) {
1674
+ decodedRemote = (0, import_sdk3.decodeName)(decodedRemote, import_sdk3.ENCODE_NAME_PREFIX);
1675
+ }
1676
+ const parsedInfo = (0, import_sdk3.parseEntry)(decodedRemote, void 0, "@");
1677
+ const url = "entry" in parsedInfo ? parsedInfo.entry : parsedInfo.name === decodedRemote ? decodedRemote : "";
1678
+ const zipUrl = url ? buildZipUrl(hostOptions, url) : "";
1679
+ return {
1680
+ name: parsedInfo.name || remoteAlias,
1681
+ url,
1682
+ zipUrl,
1683
+ apiTypeUrl: buildApiTypeUrl(zipUrl),
1684
+ alias: remoteAlias
1685
+ };
1686
+ }, "retrieveRemoteInfo");
1687
+ var resolveRemotes = /* @__PURE__ */ __name((hostOptions) => {
1688
+ const parsedOptions = import_managers.utils.parseOptions(hostOptions.moduleFederationConfig.remotes || {}, (item, key) => ({
1689
+ remote: Array.isArray(item) ? item[0] : item,
1690
+ key
1691
+ }), (item, key) => ({
1692
+ remote: Array.isArray(item.external) ? item.external[0] : item.external,
1693
+ key
1694
+ }));
1695
+ return parsedOptions.reduce((accumulator, item) => {
1696
+ const { key, remote } = item[1];
1697
+ accumulator[key] = retrieveRemoteInfo({
1698
+ hostOptions,
1699
+ remoteAlias: key,
1700
+ remote
1701
+ });
1702
+ return accumulator;
1703
+ }, {});
1704
+ }, "resolveRemotes");
1705
+ var retrieveHostConfig = /* @__PURE__ */ __name((options) => {
1706
+ validateOptions(options);
1707
+ const hostOptions = __spreadValues(__spreadValues({}, defaultOptions), options);
1708
+ const mapRemotesToDownload = resolveRemotes(hostOptions);
1709
+ return {
1710
+ hostOptions,
1711
+ mapRemotesToDownload
1712
+ };
1713
+ }, "retrieveHostConfig");
1714
+
1715
+ // packages/dts-plugin/src/core/lib/DTSManager.ts
1716
+ var _a;
1717
+ var DTSManager = (_a = class {
1718
+ constructor(options) {
1719
+ __publicField(this, "options");
1720
+ __publicField(this, "runtimePkgs");
1721
+ __publicField(this, "remoteAliasMap");
1722
+ __publicField(this, "loadedRemoteAPIAlias");
1723
+ __publicField(this, "extraOptions");
1724
+ __publicField(this, "updatedRemoteInfos");
1725
+ this.options = (0, import_lodash.default)(options, (_value, key) => {
1726
+ if (key === "manifest") {
1727
+ return false;
1728
+ }
1729
+ });
1730
+ this.runtimePkgs = [
1731
+ "@module-federation/runtime",
1732
+ "@module-federation/enhanced/runtime",
1733
+ "@module-federation/runtime-tools"
1734
+ ];
1735
+ this.loadedRemoteAPIAlias = /* @__PURE__ */ new Set();
1736
+ this.remoteAliasMap = {};
1737
+ this.extraOptions = (options == null ? void 0 : options.extraOptions) || {};
1738
+ this.updatedRemoteInfos = {};
1739
+ }
1740
+ generateAPITypes(mapComponentsToExpose) {
1741
+ const exposePaths = /* @__PURE__ */ new Set();
1742
+ const packageType = Object.keys(mapComponentsToExpose).reduce((sum, exposeKey) => {
1743
+ const exposePath = import_path4.default.join(REMOTE_ALIAS_IDENTIFIER, exposeKey).split(import_path4.default.sep).join("/");
1744
+ exposePaths.add(`'${exposePath}'`);
1745
+ const curType = `T extends '${exposePath}' ? typeof import('${exposePath}') :`;
1746
+ sum = curType + sum;
1747
+ return sum;
1748
+ }, "any;");
1749
+ const exposePathKeys = [
1750
+ ...exposePaths
1751
+ ].join(" | ");
1752
+ return `
1753
+ export type RemoteKeys = ${exposePathKeys};
1754
+ type PackageType<T> = ${packageType}`;
1755
+ }
1756
+ extractRemoteTypes(options) {
1757
+ return __async(this, null, function* () {
1758
+ const { remoteOptions, tsConfig } = options;
1759
+ if (!remoteOptions.extractRemoteTypes) {
1760
+ return;
1761
+ }
1762
+ let hasRemotes = false;
1763
+ const remotes = remoteOptions.moduleFederationConfig.remotes;
1764
+ if (remotes) {
1765
+ if (Array.isArray(remotes)) {
1766
+ hasRemotes = Boolean(remotes.length);
1767
+ } else if (typeof remotes === "object") {
1768
+ hasRemotes = Boolean(Object.keys(remotes).length);
1769
+ }
1770
+ }
1771
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
1772
+ if (hasRemotes) {
1773
+ const tempHostOptions = {
1774
+ moduleFederationConfig: remoteOptions.moduleFederationConfig,
1775
+ typesFolder: import_path4.default.join(mfTypesPath, "node_modules"),
1776
+ remoteTypesFolder: (remoteOptions == null ? void 0 : remoteOptions.hostRemoteTypesFolder) || remoteOptions.typesFolder,
1777
+ deleteTypesFolder: true,
1778
+ context: remoteOptions.context,
1779
+ implementation: remoteOptions.implementation,
1780
+ abortOnError: false
1781
+ };
1782
+ yield this.consumeArchiveTypes(tempHostOptions);
1783
+ }
1784
+ });
1785
+ }
1786
+ generateTypes() {
1787
+ return __async(this, null, function* () {
1788
+ var _a3;
1789
+ try {
1790
+ const { options } = this;
1791
+ if (!options.remote) {
1792
+ throw new Error("options.remote is required if you want to generateTypes");
1793
+ }
1794
+ const { remoteOptions, tsConfig, mapComponentsToExpose } = retrieveRemoteConfig(options.remote);
1795
+ if (!Object.keys(mapComponentsToExpose).length) {
1796
+ return;
1797
+ }
1798
+ this.extractRemoteTypes({
1799
+ remoteOptions,
1800
+ tsConfig,
1801
+ mapComponentsToExpose
1802
+ });
1803
+ compileTs(mapComponentsToExpose, tsConfig, remoteOptions);
1804
+ yield createTypesArchive(tsConfig, remoteOptions);
1805
+ let apiTypesPath = "";
1806
+ if (remoteOptions.generateAPITypes) {
1807
+ const apiTypes = this.generateAPITypes(mapComponentsToExpose);
1808
+ apiTypesPath = retrieveMfAPITypesPath(tsConfig, remoteOptions);
1809
+ import_fs.default.writeFileSync(apiTypesPath, apiTypes);
1810
+ }
1811
+ try {
1812
+ if (remoteOptions.deleteTypesFolder) {
1813
+ yield (0, import_promises2.rm)(retrieveMfTypesPath(tsConfig, remoteOptions), {
1814
+ recursive: true,
1815
+ force: true
1816
+ });
1817
+ }
1818
+ } catch (err) {
1819
+ if (isDebugMode()) {
1820
+ console.error(err);
1821
+ }
1822
+ }
1823
+ console.log(import_ansi_colors2.default.green("Federated types created correctly"));
1824
+ } catch (error2) {
1825
+ if (((_a3 = this.options.remote) == null ? void 0 : _a3.abortOnError) === false) {
1826
+ console.error(import_ansi_colors2.default.red(`Unable to compile federated types, ${error2}`));
1827
+ } else {
1828
+ throw error2;
1829
+ }
1830
+ }
1831
+ });
1832
+ }
1833
+ requestRemoteManifest(remoteInfo) {
1834
+ return __async(this, null, function* () {
1835
+ try {
1836
+ if (!remoteInfo.url.includes(import_sdk4.MANIFEST_EXT)) {
1837
+ return remoteInfo;
1838
+ }
1839
+ const url = remoteInfo.url;
1840
+ const res = yield axiosGet(url);
1841
+ const manifestJson = res.data;
1842
+ if (!manifestJson.metaData.types.zip) {
1843
+ throw new Error(`Can not get ${remoteInfo.name}'s types archive url!`);
1844
+ }
1845
+ const addProtocol = /* @__PURE__ */ __name((u) => {
1846
+ if (u.startsWith("//")) {
1847
+ return `https:${u}`;
1848
+ }
1849
+ return u;
1850
+ }, "addProtocol");
1851
+ let publicPath = "publicPath" in manifestJson.metaData ? manifestJson.metaData.publicPath : new Function(manifestJson.metaData.getPublicPath)();
1852
+ if (publicPath === "auto") {
1853
+ publicPath = (0, import_sdk4.inferAutoPublicPath)(remoteInfo.url);
1854
+ }
1855
+ remoteInfo.zipUrl = new URL(import_path4.default.join(addProtocol(publicPath), manifestJson.metaData.types.zip)).href;
1856
+ if (!manifestJson.metaData.types.api) {
1857
+ console.warn(`Can not get ${remoteInfo.name}'s api types url!`);
1858
+ remoteInfo.apiTypeUrl = "";
1859
+ return remoteInfo;
1860
+ }
1861
+ remoteInfo.apiTypeUrl = new URL(import_path4.default.join(addProtocol(publicPath), manifestJson.metaData.types.api)).href;
1862
+ return remoteInfo;
1863
+ } catch (_err) {
1864
+ fileLog(`fetch manifest failed, ${_err}, ${remoteInfo.name} will be ignored`, "requestRemoteManifest", "error");
1865
+ return remoteInfo;
1866
+ }
1867
+ });
1868
+ }
1869
+ consumeTargetRemotes(hostOptions, remoteInfo) {
1870
+ return __async(this, null, function* () {
1871
+ if (!remoteInfo.zipUrl) {
1872
+ throw new Error(`Can not get ${remoteInfo.name}'s types archive url!`);
1873
+ }
1874
+ const typesDownloader = downloadTypesArchive(hostOptions);
1875
+ return typesDownloader([
1876
+ remoteInfo.alias,
1877
+ remoteInfo.zipUrl
1878
+ ]);
1879
+ });
1880
+ }
1881
+ downloadAPITypes(remoteInfo, destinationPath) {
1882
+ return __async(this, null, function* () {
1883
+ const { apiTypeUrl } = remoteInfo;
1884
+ if (!apiTypeUrl) {
1885
+ return;
1886
+ }
1887
+ try {
1888
+ const url = apiTypeUrl;
1889
+ const res = yield axiosGet(url);
1890
+ let apiTypeFile = res.data;
1891
+ apiTypeFile = apiTypeFile.replaceAll(REMOTE_ALIAS_IDENTIFIER, remoteInfo.alias);
1892
+ const filePath = import_path4.default.join(destinationPath, REMOTE_API_TYPES_FILE_NAME);
1893
+ import_fs.default.writeFileSync(filePath, apiTypeFile);
1894
+ this.loadedRemoteAPIAlias.add(remoteInfo.alias);
1895
+ } catch (err) {
1896
+ fileLog(`Unable to download "${remoteInfo.name}" api types, ${err}`, "consumeTargetRemotes", "error");
1897
+ }
1898
+ });
1899
+ }
1900
+ consumeAPITypes(hostOptions) {
1901
+ const apiTypeFileName = import_path4.default.join(hostOptions.context, hostOptions.typesFolder, HOST_API_TYPES_FILE_NAME);
1902
+ try {
1903
+ const existedFile = import_fs.default.readFileSync(apiTypeFileName, "utf-8");
1904
+ const existedImports = new import_third_party_dts_extractor2.ThirdPartyExtractor("").collectTypeImports(existedFile);
1905
+ existedImports.forEach((existedImport) => {
1906
+ const alias = existedImport.split("./").slice(1).join("./").replace("/apis.d.ts", "");
1907
+ this.loadedRemoteAPIAlias.add(alias);
1908
+ });
1909
+ } catch (err) {
1910
+ }
1911
+ if (!this.loadedRemoteAPIAlias.size) {
1912
+ return;
1913
+ }
1914
+ const packageTypes = [];
1915
+ const remoteKeys = [];
1916
+ const importTypeStr = [
1917
+ ...this.loadedRemoteAPIAlias
1918
+ ].sort().map((alias, index) => {
1919
+ const remoteKey = `RemoteKeys_${index}`;
1920
+ const packageType = `PackageType_${index}`;
1921
+ packageTypes.push(`T extends ${remoteKey} ? ${packageType}<T>`);
1922
+ remoteKeys.push(remoteKey);
1923
+ return `import type { PackageType as ${packageType},RemoteKeys as ${remoteKey} } from './${alias}/apis.d.ts';`;
1924
+ }).join("\n");
1925
+ const remoteKeysStr = `type RemoteKeys = ${remoteKeys.join(" | ")};`;
1926
+ const packageTypesStr = `type PackageType<T, Y=any> = ${[
1927
+ ...packageTypes,
1928
+ "Y"
1929
+ ].join(" :\n")} ;`;
1930
+ const pkgsDeclareStr = this.runtimePkgs.map((pkg) => {
1931
+ return `declare module "${pkg}" {
1932
+ ${remoteKeysStr}
1933
+ ${packageTypesStr}
1934
+ export function loadRemote<T extends RemoteKeys,Y>(packageName: T): Promise<PackageType<T, Y>>;
1935
+ export function loadRemote<T extends string,Y>(packageName: T): Promise<PackageType<T, Y>>;
1936
+ }`;
1937
+ }).join("\n");
1938
+ const fileStr = `${importTypeStr}
1939
+ ${pkgsDeclareStr}
1940
+ `;
1941
+ import_fs.default.writeFileSync(import_path4.default.join(hostOptions.context, hostOptions.typesFolder, HOST_API_TYPES_FILE_NAME), fileStr);
1942
+ }
1943
+ consumeArchiveTypes(options) {
1944
+ return __async(this, null, function* () {
1945
+ const { hostOptions, mapRemotesToDownload } = retrieveHostConfig(options);
1946
+ const downloadPromises = Object.entries(mapRemotesToDownload).map((item) => __async(this, null, function* () {
1947
+ const remoteInfo = item[1];
1948
+ if (!this.remoteAliasMap[remoteInfo.alias]) {
1949
+ const requiredRemoteInfo = yield this.requestRemoteManifest(remoteInfo);
1950
+ this.remoteAliasMap[remoteInfo.alias] = requiredRemoteInfo;
1951
+ }
1952
+ return this.consumeTargetRemotes(hostOptions, this.remoteAliasMap[remoteInfo.alias]);
1953
+ }));
1954
+ const downloadPromisesResult = yield Promise.allSettled(downloadPromises);
1955
+ return {
1956
+ hostOptions,
1957
+ downloadPromisesResult
1958
+ };
1959
+ });
1960
+ }
1961
+ consumeTypes() {
1962
+ return __async(this, null, function* () {
1963
+ var _a3;
1964
+ try {
1965
+ const { options } = this;
1966
+ if (!options.host) {
1967
+ throw new Error("options.host is required if you want to consumeTypes");
1968
+ }
1969
+ const { mapRemotesToDownload } = retrieveHostConfig(options.host);
1970
+ if (!Object.keys(mapRemotesToDownload).length) {
1971
+ return;
1972
+ }
1973
+ const { downloadPromisesResult, hostOptions } = yield this.consumeArchiveTypes(options.host);
1974
+ if (hostOptions.consumeAPITypes) {
1975
+ yield Promise.all(downloadPromisesResult.map((item) => __async(this, null, function* () {
1976
+ if (item.status === "rejected" || !item.value) {
1977
+ return;
1978
+ }
1979
+ const [alias, destinationPath] = item.value;
1980
+ const remoteInfo = this.remoteAliasMap[alias];
1981
+ if (!remoteInfo) {
1982
+ return;
1983
+ }
1984
+ yield this.downloadAPITypes(remoteInfo, destinationPath);
1985
+ })));
1986
+ this.consumeAPITypes(hostOptions);
1987
+ }
1988
+ console.log(import_ansi_colors2.default.green("Federated types extraction completed"));
1989
+ } catch (err) {
1990
+ if (((_a3 = this.options.host) == null ? void 0 : _a3.abortOnError) === false) {
1991
+ fileLog(`Unable to consume federated types, ${err}`, "consumeTypes", "error");
1992
+ } else {
1993
+ throw err;
1994
+ }
1995
+ }
1996
+ });
1997
+ }
1998
+ updateTypes(options) {
1999
+ return __async(this, null, function* () {
2000
+ var _a3, _b, _c;
2001
+ try {
2002
+ const { remoteName, updateMode, remoteInfo: updatedRemoteInfo, once } = options;
2003
+ const hostName = (_c = (_b = (_a3 = this.options) == null ? void 0 : _a3.host) == null ? void 0 : _b.moduleFederationConfig) == null ? void 0 : _c.name;
2004
+ fileLog(`updateTypes options:, ${JSON.stringify(options, null, 2)}`, "consumeTypes", "info");
2005
+ if (updateMode === UpdateMode.POSITIVE && remoteName === hostName) {
2006
+ if (!this.options.remote) {
2007
+ return;
2008
+ }
2009
+ this.generateTypes();
2010
+ } else {
2011
+ const { remoteAliasMap } = this;
2012
+ if (!this.options.host) {
2013
+ return;
2014
+ }
2015
+ const { hostOptions, mapRemotesToDownload } = retrieveHostConfig(this.options.host);
2016
+ const loadedRemoteInfo = Object.values(remoteAliasMap).find((i) => i.name === remoteName);
2017
+ if (!loadedRemoteInfo) {
2018
+ const remoteInfo = Object.values(mapRemotesToDownload).find((item) => {
2019
+ return item.name === remoteName;
2020
+ });
2021
+ if (remoteInfo) {
2022
+ if (!this.remoteAliasMap[remoteInfo.alias]) {
2023
+ const requiredRemoteInfo = yield this.requestRemoteManifest(remoteInfo);
2024
+ this.remoteAliasMap[remoteInfo.alias] = requiredRemoteInfo;
2025
+ }
2026
+ yield this.consumeTargetRemotes(hostOptions, this.remoteAliasMap[remoteInfo.alias]);
2027
+ } else if (updatedRemoteInfo) {
2028
+ const consumeDynamicRemoteTypes = /* @__PURE__ */ __name(() => __async(this, null, function* () {
2029
+ const [_destinationFolder, destinationPath] = yield this.consumeTargetRemotes(hostOptions, this.updatedRemoteInfos[updatedRemoteInfo.name]);
2030
+ yield this.downloadAPITypes(this.updatedRemoteInfos[updatedRemoteInfo.name], destinationPath);
2031
+ this.consumeAPITypes(hostOptions);
2032
+ }), "consumeDynamicRemoteTypes");
2033
+ if (!this.updatedRemoteInfos[updatedRemoteInfo.name]) {
2034
+ const parsedRemoteInfo = retrieveRemoteInfo({
2035
+ hostOptions,
2036
+ remoteAlias: updatedRemoteInfo.alias || updatedRemoteInfo.name,
2037
+ remote: updatedRemoteInfo.url
2038
+ });
2039
+ fileLog(`start request manifest`, "consumeTypes", "info");
2040
+ this.updatedRemoteInfos[updatedRemoteInfo.name] = yield this.requestRemoteManifest(parsedRemoteInfo);
2041
+ fileLog(`end request manifest, this.updatedRemoteInfos[updatedRemoteInfo.name]: ${JSON.stringify(this.updatedRemoteInfos[updatedRemoteInfo.name], null, 2)}`, "consumeTypes", "info");
2042
+ yield consumeDynamicRemoteTypes();
2043
+ }
2044
+ if (!once && this.updatedRemoteInfos[updatedRemoteInfo.name]) {
2045
+ yield consumeDynamicRemoteTypes();
2046
+ }
2047
+ }
2048
+ } else {
2049
+ yield this.consumeTargetRemotes(hostOptions, loadedRemoteInfo);
2050
+ }
2051
+ }
2052
+ } catch (err) {
2053
+ fileLog(`updateTypes fail, ${err}`, "updateTypes", "error");
2054
+ }
2055
+ });
2056
+ }
2057
+ }, __name(_a, "DTSManager"), _a);
2058
+
2059
+ // packages/dts-plugin/src/core/lib/utils.ts
2060
+ function getDTSManagerConstructor(implementation) {
2061
+ if (implementation) {
2062
+ const NewConstructor = require(implementation);
2063
+ return NewConstructor.default ? NewConstructor.default : NewConstructor;
2064
+ }
2065
+ return DTSManager;
2066
+ }
2067
+ __name(getDTSManagerConstructor, "getDTSManagerConstructor");
2068
+ var validateOptions = /* @__PURE__ */ __name((options) => {
2069
+ if (!options.moduleFederationConfig) {
2070
+ throw new Error("moduleFederationConfig is required");
2071
+ }
2072
+ }, "validateOptions");
2073
+ function isDebugMode() {
2074
+ return Boolean(process.env["FEDERATION_DEBUG"]);
2075
+ }
2076
+ __name(isDebugMode, "isDebugMode");
2077
+ function axiosGet(url, config) {
2078
+ return __async(this, null, function* () {
2079
+ const httpAgent = new import_http2.default.Agent({
2080
+ family: 4
2081
+ });
2082
+ const httpsAgent = new import_https.default.Agent({
2083
+ family: 4
2084
+ });
2085
+ return import_axios.default.get(url, __spreadValues({
2086
+ httpAgent,
2087
+ httpsAgent
2088
+ }, config));
2089
+ });
2090
+ }
2091
+ __name(axiosGet, "axiosGet");
2092
+
2093
+ // packages/dts-plugin/src/core/configurations/remotePlugin.ts
2094
+ var defaultOptions2 = {
2095
+ tsConfigPath: "./tsconfig.json",
2096
+ typesFolder: "@mf-types",
2097
+ compiledTypesFolder: "compiled-types",
2098
+ hostRemoteTypesFolder: "@mf-types",
2099
+ deleteTypesFolder: true,
2100
+ additionalFilesToCompile: [],
2101
+ compilerInstance: "tsc",
2102
+ compileInChildProcess: false,
2103
+ implementation: "",
2104
+ generateAPITypes: false,
2105
+ context: process.cwd(),
2106
+ abortOnError: true,
2107
+ extractRemoteTypes: false,
2108
+ extractThirdParty: false
2109
+ };
2110
+ var readTsConfig = /* @__PURE__ */ __name(({ tsConfigPath, typesFolder, compiledTypesFolder, context }) => {
2111
+ const resolvedTsConfigPath = (0, import_path5.resolve)(context, tsConfigPath);
2112
+ const readResult = import_typescript2.default.readConfigFile(resolvedTsConfigPath, import_typescript2.default.sys.readFile);
2113
+ if (readResult.error) {
2114
+ throw new Error(readResult.error.messageText.toString());
2115
+ }
2116
+ const configContent = import_typescript2.default.parseJsonConfigFileContent(readResult.config, import_typescript2.default.sys, (0, import_path5.dirname)(resolvedTsConfigPath));
2117
+ const outDir = (0, import_path5.resolve)(context, configContent.options.outDir || "dist", typesFolder, compiledTypesFolder);
2118
+ return __spreadProps(__spreadValues({}, configContent.options), {
2119
+ emitDeclarationOnly: true,
2120
+ noEmit: false,
2121
+ declaration: true,
2122
+ outDir
2123
+ });
2124
+ }, "readTsConfig");
2125
+ var TS_EXTENSIONS = [
2126
+ "ts",
2127
+ "tsx",
2128
+ "vue",
2129
+ "svelte"
2130
+ ];
2131
+ var resolveWithExtension = /* @__PURE__ */ __name((exposedPath, context) => {
2132
+ if ((0, import_path5.extname)(exposedPath)) {
2133
+ return (0, import_path5.resolve)(context, exposedPath);
2134
+ }
2135
+ for (const extension of TS_EXTENSIONS) {
2136
+ const exposedPathWithExtension = (0, import_path5.resolve)(context, `${exposedPath}.${extension}`);
2137
+ if ((0, import_fs2.existsSync)(exposedPathWithExtension)) {
2138
+ return exposedPathWithExtension;
2139
+ }
2140
+ }
2141
+ return void 0;
2142
+ }, "resolveWithExtension");
2143
+ var resolveExposes = /* @__PURE__ */ __name((remoteOptions) => {
2144
+ const parsedOptions = import_managers2.utils.parseOptions(remoteOptions.moduleFederationConfig.exposes || {}, (item, key) => ({
2145
+ exposePath: Array.isArray(item) ? item[0] : item,
2146
+ key
2147
+ }), (item, key) => ({
2148
+ exposePath: Array.isArray(item.import) ? item.import[0] : item.import[0],
2149
+ key
2150
+ }));
2151
+ return parsedOptions.reduce((accumulator, item) => {
2152
+ const { exposePath, key } = item[1];
2153
+ accumulator[key] = resolveWithExtension(exposePath, remoteOptions.context) || resolveWithExtension((0, import_path5.join)(exposePath, "index"), remoteOptions.context) || exposePath;
2154
+ return accumulator;
2155
+ }, {});
2156
+ }, "resolveExposes");
2157
+ var retrieveRemoteConfig = /* @__PURE__ */ __name((options) => {
2158
+ validateOptions(options);
2159
+ const remoteOptions = __spreadValues(__spreadValues({}, defaultOptions2), options);
2160
+ const mapComponentsToExpose = resolveExposes(remoteOptions);
2161
+ const tsConfig = readTsConfig(remoteOptions);
2162
+ return {
2163
+ tsConfig,
2164
+ mapComponentsToExpose,
2165
+ remoteOptions
2166
+ };
2167
+ }, "retrieveRemoteConfig");
2168
+
2169
+ // packages/dts-plugin/src/core/lib/DtsWorker.ts
2170
+ var import_lodash2 = __toESM(require("lodash.clonedeepwith"));
2171
+
2172
+ // packages/dts-plugin/src/core/rpc/index.ts
2173
+ var rpc_exports = {};
2174
+ __export(rpc_exports, {
2175
+ RpcExitError: () => RpcExitError,
2176
+ RpcGMCallTypes: () => RpcGMCallTypes,
2177
+ createRpcWorker: () => createRpcWorker,
2178
+ exposeRpc: () => exposeRpc,
2179
+ getRpcWorkerData: () => getRpcWorkerData,
2180
+ wrapRpc: () => wrapRpc
2181
+ });
2182
+
2183
+ // packages/dts-plugin/src/core/rpc/expose-rpc.ts
2184
+ var import_process = __toESM(require("process"));
2185
+
2186
+ // packages/dts-plugin/src/core/rpc/types.ts
2187
+ var RpcGMCallTypes;
2188
+ (function(RpcGMCallTypes2) {
2189
+ RpcGMCallTypes2["CALL"] = "mf_call";
2190
+ RpcGMCallTypes2["RESOLVE"] = "mf_resolve";
2191
+ RpcGMCallTypes2["REJECT"] = "mf_reject";
2192
+ RpcGMCallTypes2["EXIT"] = "mf_exit";
2193
+ })(RpcGMCallTypes || (RpcGMCallTypes = {}));
2194
+
2195
+ // packages/dts-plugin/src/core/rpc/expose-rpc.ts
2196
+ function exposeRpc(fn) {
2197
+ const sendMessage = /* @__PURE__ */ __name((message) => new Promise((resolve4, reject) => {
2198
+ if (!import_process.default.send) {
2199
+ reject(new Error(`Process ${import_process.default.pid} doesn't have IPC channels`));
2200
+ } else if (!import_process.default.connected) {
2201
+ reject(new Error(`Process ${import_process.default.pid} doesn't have open IPC channels`));
2202
+ } else {
2203
+ import_process.default.send(message, void 0, void 0, (error2) => {
2204
+ if (error2) {
2205
+ reject(error2);
2206
+ } else {
2207
+ resolve4(void 0);
2208
+ }
2209
+ });
2210
+ }
2211
+ }), "sendMessage");
2212
+ const handleMessage = /* @__PURE__ */ __name((message) => __async(this, null, function* () {
2213
+ if (message.type === RpcGMCallTypes.CALL) {
2214
+ if (!import_process.default.send) {
2215
+ return;
2216
+ }
2217
+ let value, error2;
2218
+ try {
2219
+ value = yield fn(...message.args);
2220
+ } catch (fnError) {
2221
+ error2 = fnError;
2222
+ }
2223
+ try {
2224
+ if (error2) {
2225
+ yield sendMessage({
2226
+ type: RpcGMCallTypes.REJECT,
2227
+ id: message.id,
2228
+ error: error2
2229
+ });
2230
+ } else {
2231
+ yield sendMessage({
2232
+ type: RpcGMCallTypes.RESOLVE,
2233
+ id: message.id,
2234
+ value
2235
+ });
2236
+ }
2237
+ } catch (sendError) {
2238
+ if (error2) {
2239
+ if (error2 instanceof Error) {
2240
+ console.error(error2);
2241
+ }
2242
+ }
2243
+ console.error(sendError);
2244
+ }
2245
+ }
2246
+ }), "handleMessage");
2247
+ import_process.default.on("message", handleMessage);
2248
+ }
2249
+ __name(exposeRpc, "exposeRpc");
2250
+
2251
+ // packages/dts-plugin/src/core/rpc/rpc-error.ts
2252
+ var _a2;
2253
+ var RpcExitError = (_a2 = class extends Error {
2254
+ constructor(message, code, signal) {
2255
+ super(message);
2256
+ __publicField(this, "code");
2257
+ __publicField(this, "signal");
2258
+ this.code = code;
2259
+ this.signal = signal;
2260
+ this.name = "RpcExitError";
2261
+ }
2262
+ }, __name(_a2, "RpcExitError"), _a2);
2263
+
2264
+ // packages/dts-plugin/src/core/rpc/wrap-rpc.ts
2265
+ function createControlledPromise() {
2266
+ let resolve4 = /* @__PURE__ */ __name(() => void 0, "resolve");
2267
+ let reject = /* @__PURE__ */ __name(() => void 0, "reject");
2268
+ const promise = new Promise((aResolve, aReject) => {
2269
+ resolve4 = aResolve;
2270
+ reject = aReject;
2271
+ });
2272
+ return {
2273
+ promise,
2274
+ resolve: resolve4,
2275
+ reject
2276
+ };
2277
+ }
2278
+ __name(createControlledPromise, "createControlledPromise");
2279
+ function wrapRpc(childProcess, options) {
2280
+ return (...args) => __async(this, null, function* () {
2281
+ if (!childProcess.send) {
2282
+ throw new Error(`Process ${childProcess.pid} doesn't have IPC channels`);
2283
+ } else if (!childProcess.connected) {
2284
+ throw new Error(`Process ${childProcess.pid} doesn't have open IPC channels`);
2285
+ }
2286
+ const { id, once } = options;
2287
+ const { promise: resultPromise, resolve: resolveResult, reject: rejectResult } = createControlledPromise();
2288
+ const { promise: sendPromise, resolve: resolveSend, reject: rejectSend } = createControlledPromise();
2289
+ const handleMessage = /* @__PURE__ */ __name((message) => {
2290
+ if ((message == null ? void 0 : message.id) === id) {
2291
+ if (message.type === RpcGMCallTypes.RESOLVE) {
2292
+ resolveResult(message.value);
2293
+ } else if (message.type === RpcGMCallTypes.REJECT) {
2294
+ rejectResult(message.error);
2295
+ }
2296
+ }
2297
+ if (once && (childProcess == null ? void 0 : childProcess.kill)) {
2298
+ childProcess.kill("SIGTERM");
2299
+ }
2300
+ }, "handleMessage");
2301
+ const handleClose = /* @__PURE__ */ __name((code, signal) => {
2302
+ rejectResult(new RpcExitError(code ? `Process ${childProcess.pid} exited with code ${code}${signal ? ` [${signal}]` : ""}` : `Process ${childProcess.pid} exited${signal ? ` [${signal}]` : ""}`, code, signal));
2303
+ removeHandlers();
2304
+ }, "handleClose");
2305
+ const removeHandlers = /* @__PURE__ */ __name(() => {
2306
+ childProcess.off("message", handleMessage);
2307
+ childProcess.off("close", handleClose);
2308
+ }, "removeHandlers");
2309
+ if (once) {
2310
+ childProcess.once("message", handleMessage);
2311
+ } else {
2312
+ childProcess.on("message", handleMessage);
2313
+ }
2314
+ childProcess.on("close", handleClose);
2315
+ childProcess.send({
2316
+ type: RpcGMCallTypes.CALL,
2317
+ id,
2318
+ args
2319
+ }, (error2) => {
2320
+ if (error2) {
2321
+ rejectSend(error2);
2322
+ removeHandlers();
2323
+ } else {
2324
+ resolveSend(void 0);
2325
+ }
2326
+ });
2327
+ return sendPromise.then(() => resultPromise);
2328
+ });
2329
+ }
2330
+ __name(wrapRpc, "wrapRpc");
2331
+
2332
+ // packages/dts-plugin/src/core/rpc/rpc-worker.ts
2333
+ var child_process = __toESM(require("child_process"));
2334
+ var process3 = __toESM(require("process"));
2335
+ var import_crypto = require("crypto");
2336
+ var FEDERATION_WORKER_DATA_ENV_KEY = "VMOK_WORKER_DATA_ENV";
2337
+ function createRpcWorker(modulePath, data, memoryLimit, once) {
2338
+ const options = {
2339
+ env: __spreadProps(__spreadValues({}, process3.env), {
2340
+ [FEDERATION_WORKER_DATA_ENV_KEY]: JSON.stringify(data || {})
2341
+ }),
2342
+ stdio: [
2343
+ "inherit",
2344
+ "inherit",
2345
+ "inherit",
2346
+ "ipc"
2347
+ ],
2348
+ serialization: "advanced"
2349
+ };
2350
+ if (memoryLimit) {
2351
+ options.execArgv = [
2352
+ `--max-old-space-size=${memoryLimit}`
2353
+ ];
2354
+ }
2355
+ let childProcess, remoteMethod;
2356
+ const id = (0, import_crypto.randomUUID)();
2357
+ const worker = {
2358
+ connect(...args) {
2359
+ if (childProcess && !childProcess.connected) {
2360
+ childProcess.send({
2361
+ type: RpcGMCallTypes.EXIT,
2362
+ id
2363
+ });
2364
+ childProcess = void 0;
2365
+ remoteMethod = void 0;
2366
+ }
2367
+ if (!(childProcess == null ? void 0 : childProcess.connected)) {
2368
+ childProcess = child_process.fork(modulePath, options);
2369
+ remoteMethod = wrapRpc(childProcess, {
2370
+ id,
2371
+ once
2372
+ });
2373
+ }
2374
+ if (!remoteMethod) {
2375
+ return Promise.reject(new Error("Worker is not connected - cannot perform RPC."));
2376
+ }
2377
+ return remoteMethod(...args);
2378
+ },
2379
+ terminate() {
2380
+ var _a3;
2381
+ (_a3 = childProcess == null ? void 0 : childProcess.send) == null ? void 0 : _a3.call(childProcess, {
2382
+ type: RpcGMCallTypes.EXIT,
2383
+ id
2384
+ });
2385
+ childProcess = void 0;
2386
+ remoteMethod = void 0;
2387
+ },
2388
+ get connected() {
2389
+ return Boolean(childProcess == null ? void 0 : childProcess.connected);
2390
+ },
2391
+ get process() {
2392
+ return childProcess;
2393
+ },
2394
+ get id() {
2395
+ return id;
2396
+ }
2397
+ };
2398
+ return worker;
2399
+ }
2400
+ __name(createRpcWorker, "createRpcWorker");
2401
+ function getRpcWorkerData() {
2402
+ return JSON.parse(process3.env[FEDERATION_WORKER_DATA_ENV_KEY] || "{}");
2403
+ }
2404
+ __name(getRpcWorkerData, "getRpcWorkerData");
2405
+
2406
+ // packages/dts-plugin/src/dev-worker/forkDevWorker.ts
2407
+ var import_sdk5 = require("@module-federation/sdk");
2408
+
2409
+ // packages/dts-plugin/src/dev-worker/utils.ts
2410
+ var DEFAULT_LOCAL_IPS = [
2411
+ "localhost",
2412
+ "127.0.0.1"
2413
+ ];
2414
+ function getIpFromEntry(entry, ipv4) {
2415
+ let ip;
2416
+ entry.replace(/https?:\/\/([0-9|.]+|localhost):/, (str, matched) => {
2417
+ ip = matched;
2418
+ return str;
2419
+ });
2420
+ if (ip) {
2421
+ return DEFAULT_LOCAL_IPS.includes(ip) ? ipv4 : ip;
2422
+ }
2423
+ }
2424
+ __name(getIpFromEntry, "getIpFromEntry");
2425
+
2426
+ // packages/dts-plugin/src/dev-worker/forkDevWorker.ts
2427
+ var typesManager;
2428
+ var serverAddress;
2429
+ var moduleServer;
2430
+ var cacheOptions;
2431
+ function getLocalRemoteNames(options, encodeNameIdentifier) {
2432
+ if (!options) {
2433
+ return [];
2434
+ }
2435
+ const { mapRemotesToDownload } = retrieveHostConfig(options);
2436
+ return Object.keys(mapRemotesToDownload).reduce((sum, remoteModuleName) => {
2437
+ const remoteInfo = mapRemotesToDownload[remoteModuleName];
2438
+ const name = encodeNameIdentifier ? (0, import_sdk5.decodeName)(remoteInfo.name, encodeNameIdentifier) : remoteInfo.name;
2439
+ const ip = getIpFromEntry(remoteInfo.url, getIPV4());
2440
+ if (!ip) {
2441
+ return sum;
2442
+ }
2443
+ sum.push({
2444
+ name,
2445
+ entry: remoteInfo.url,
2446
+ ip
2447
+ });
2448
+ return sum;
2449
+ }, []);
2450
+ }
2451
+ __name(getLocalRemoteNames, "getLocalRemoteNames");
2452
+ function updateCallback(_0) {
2453
+ return __async(this, arguments, function* ({ updateMode, name, remoteTypeTarPath, remoteInfo, once }) {
2454
+ const { disableHotTypesReload, disableLiveReload } = cacheOptions || {};
2455
+ fileLog(`sync remote module ${name}, types to ${cacheOptions == null ? void 0 : cacheOptions.name},typesManager.updateTypes run`, "forkDevWorker", "info");
2456
+ if (!disableLiveReload && moduleServer) {
2457
+ moduleServer.update({
2458
+ updateKind: UpdateKind.RELOAD_PAGE,
2459
+ updateMode: UpdateMode.PASSIVE
2460
+ });
2461
+ }
2462
+ if (!disableHotTypesReload && typesManager) {
2463
+ yield typesManager.updateTypes({
2464
+ updateMode,
2465
+ remoteName: name,
2466
+ remoteTarPath: remoteTypeTarPath,
2467
+ remoteInfo,
2468
+ once
2469
+ });
2470
+ }
2471
+ });
2472
+ }
2473
+ __name(updateCallback, "updateCallback");
2474
+ function forkDevWorker(options, action) {
2475
+ return __async(this, null, function* () {
2476
+ if (!typesManager) {
2477
+ const { name, remote, host, extraOptions } = options;
2478
+ const DTSManagerConstructor = getDTSManagerConstructor(remote == null ? void 0 : remote.implementation);
2479
+ typesManager = new DTSManagerConstructor({
2480
+ remote,
2481
+ host,
2482
+ extraOptions
2483
+ });
2484
+ if (!options.disableHotTypesReload && remote) {
2485
+ const { remoteOptions, tsConfig } = retrieveRemoteConfig(remote);
2486
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
2487
+ const mfTypesZipPath = retrieveTypesZipPath(mfTypesPath, remoteOptions);
2488
+ yield Promise.all([
2489
+ createKoaServer({
2490
+ typeTarPath: mfTypesZipPath
2491
+ }).then((res) => {
2492
+ serverAddress = res.serverAddress;
2493
+ }),
2494
+ typesManager.generateTypes()
2495
+ ]).catch((err) => {
2496
+ fileLog(`${name} module generateTypes done, localServerAddress: ${JSON.stringify(err)}`, "forkDevWorker", "error");
2497
+ });
2498
+ fileLog(`${name} module generateTypes done, localServerAddress: ${serverAddress}`, "forkDevWorker", "info");
2499
+ }
2500
+ moduleServer = new ModuleFederationDevServer({
2501
+ name,
2502
+ remotes: getLocalRemoteNames(host, extraOptions == null ? void 0 : extraOptions["encodeNameIdentifier"]),
2503
+ updateCallback,
2504
+ remoteTypeTarPath: `${serverAddress}/${DEFAULT_TAR_NAME}`
2505
+ });
2506
+ cacheOptions = options;
2507
+ }
2508
+ if (action === "update" && cacheOptions) {
2509
+ fileLog(`remoteModule ${cacheOptions.name} receive devWorker update, start typesManager.updateTypes `, "forkDevWorker", "info");
2510
+ if (!cacheOptions.disableLiveReload) {
2511
+ moduleServer == null ? void 0 : moduleServer.update({
2512
+ updateKind: UpdateKind.RELOAD_PAGE,
2513
+ updateMode: UpdateMode.POSITIVE
2514
+ });
2515
+ }
2516
+ if (!cacheOptions.disableHotTypesReload) {
2517
+ typesManager == null ? void 0 : typesManager.updateTypes({
2518
+ updateMode: UpdateMode.POSITIVE,
2519
+ remoteName: cacheOptions.name
2520
+ }).then(() => {
2521
+ moduleServer == null ? void 0 : moduleServer.update({
2522
+ updateKind: UpdateKind.UPDATE_TYPE,
2523
+ updateMode: UpdateMode.POSITIVE
2524
+ });
2525
+ });
2526
+ }
2527
+ }
2528
+ });
2529
+ }
2530
+ __name(forkDevWorker, "forkDevWorker");
2531
+ process.on("message", (message) => {
2532
+ fileLog(`ChildProcess(${process.pid}), message: ${JSON.stringify(message)} `, "forkDevWorker", "info");
2533
+ if (message.type === rpc_exports.RpcGMCallTypes.EXIT) {
2534
+ fileLog(`ChildProcess(${process.pid}) SIGTERM, Federation DevServer will exit...`, "forkDevWorker", "error");
2535
+ moduleServer.exit();
2536
+ process.exit(0);
2537
+ }
2538
+ });
2539
+ rpc_exports.exposeRpc(forkDevWorker);
2540
+ // Annotate the CommonJS export names for ESM import in node:
2541
+ 0 && (module.exports = {
2542
+ forkDevWorker
2543
+ });