@module-federation/dts-plugin 0.1.5 → 0.1.7

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