@module-federation/dts-plugin 0.1.4 → 0.1.6

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.
package/dist/core.js CHANGED
@@ -61,16 +61,15 @@ var import_typescript2 = __toESM(require("typescript"));
61
61
  var import_path4 = __toESM(require("path"));
62
62
 
63
63
  // packages/dts-plugin/src/core/lib/DTSManager.ts
64
- var import_ansi_colors3 = __toESM(require("ansi-colors"));
64
+ var import_ansi_colors2 = __toESM(require("ansi-colors"));
65
65
  var import_path3 = __toESM(require("path"));
66
66
  var import_promises = require("fs/promises");
67
67
  var import_fs = __toESM(require("fs"));
68
- var import_sdk2 = require("@module-federation/sdk");
68
+ var import_sdk4 = require("@module-federation/sdk");
69
69
  var import_lodash = __toESM(require("lodash.clonedeepwith"));
70
70
 
71
71
  // packages/dts-plugin/src/core/lib/archiveHandler.ts
72
72
  var import_adm_zip = __toESM(require("adm-zip"));
73
- var import_ansi_colors2 = __toESM(require("ansi-colors"));
74
73
  var import_axios = __toESM(require("axios"));
75
74
  var import_path2 = require("path");
76
75
 
@@ -182,6 +181,787 @@ var compileTs = (mapComponentsToExpose, tsConfig, remoteOptions) => {
182
181
  }
183
182
  };
184
183
 
184
+ // packages/dts-plugin/src/server/message/Message.ts
185
+ var Message = class {
186
+ constructor(type, kind) {
187
+ this.type = type;
188
+ this.kind = kind;
189
+ this.time = Date.now();
190
+ }
191
+ };
192
+
193
+ // packages/dts-plugin/src/server/message/API/API.ts
194
+ var API = class extends Message {
195
+ constructor(content, kind) {
196
+ super("API", kind);
197
+ const { code, payload } = content;
198
+ this.code = code;
199
+ this.payload = payload;
200
+ }
201
+ };
202
+
203
+ // packages/dts-plugin/src/server/message/API/UpdateSubscriber.ts
204
+ var UpdateSubscriberAPI = class extends API {
205
+ constructor(payload) {
206
+ super(
207
+ {
208
+ code: 0,
209
+ payload
210
+ },
211
+ "UPDATE_SUBSCRIBER" /* UPDATE_SUBSCRIBER */
212
+ );
213
+ }
214
+ };
215
+
216
+ // packages/dts-plugin/src/server/message/API/ReloadWebClient.ts
217
+ var ReloadWebClientAPI = class extends API {
218
+ constructor(payload) {
219
+ super(
220
+ {
221
+ code: 0,
222
+ payload
223
+ },
224
+ "RELOAD_WEB_CLIENT" /* RELOAD_WEB_CLIENT */
225
+ );
226
+ }
227
+ };
228
+
229
+ // packages/dts-plugin/src/server/utils/index.ts
230
+ var import_sdk2 = require("@module-federation/sdk");
231
+
232
+ // packages/dts-plugin/src/server/utils/logTransform.ts
233
+ var import_chalk = __toESM(require("chalk"));
234
+
235
+ // packages/dts-plugin/src/server/message/Log/Log.ts
236
+ var Log = class extends Message {
237
+ constructor(level, kind, ignoreVerbose = false) {
238
+ super("Log", kind);
239
+ this.ignoreVerbose = false;
240
+ this.level = level;
241
+ this.ignoreVerbose = ignoreVerbose;
242
+ }
243
+ };
244
+
245
+ // packages/dts-plugin/src/server/message/Log/BrokerExitLog.ts
246
+ var BrokerExitLog = class extends Log {
247
+ constructor() {
248
+ super("LOG" /* LOG */, "BrokerExitLog" /* BrokerExitLog */);
249
+ }
250
+ };
251
+
252
+ // packages/dts-plugin/src/server/utils/log.ts
253
+ var import_sdk = require("@module-federation/sdk");
254
+ var log4js = __toESM(require("log4js"));
255
+ var import_chalk2 = __toESM(require("chalk"));
256
+
257
+ // packages/dts-plugin/src/server/constant.ts
258
+ var DEFAULT_WEB_SOCKET_PORT = 16322;
259
+ var WEB_SOCKET_CONNECT_MAGIC_ID = "1hpzW-zo2z-o8io-gfmV1-2cb1d82";
260
+
261
+ // packages/dts-plugin/src/server/utils/log.ts
262
+ function fileLog(msg, module2, level) {
263
+ var _a, _b;
264
+ if (!((_a = process == null ? void 0 : process.env) == null ? void 0 : _a["FEDERATION_DEBUG"])) {
265
+ return;
266
+ }
267
+ log4js.configure({
268
+ appenders: {
269
+ [module2]: { type: "file", filename: ".mf/typesGenerate.log" },
270
+ default: { type: "file", filename: ".mf/typesGenerate.log" }
271
+ },
272
+ categories: {
273
+ [module2]: { appenders: [module2], level: "error" },
274
+ default: { appenders: ["default"], level: "trace" }
275
+ }
276
+ });
277
+ const logger4 = log4js.getLogger(module2);
278
+ logger4.level = "debug";
279
+ (_b = logger4[level]) == null ? void 0 : _b.call(logger4, msg);
280
+ }
281
+ function error(error2, action, from) {
282
+ const err = error2 instanceof Error ? error2 : new Error(`${action} error`);
283
+ fileLog(`[${action}] error: ${err}`, from, "fatal");
284
+ return err.toString();
285
+ }
286
+
287
+ // packages/dts-plugin/src/server/utils/index.ts
288
+ function getIdentifier(options) {
289
+ const { ip, name } = options;
290
+ return `mf ${import_sdk2.SEPARATOR}${name}${ip ? `${import_sdk2.SEPARATOR}${ip}` : ""}`;
291
+ }
292
+
293
+ // packages/dts-plugin/src/server/Publisher.ts
294
+ var Publisher = class {
295
+ constructor(ctx) {
296
+ this._name = ctx.name;
297
+ this._ip = ctx.ip;
298
+ this._remoteTypeTarPath = ctx.remoteTypeTarPath;
299
+ this._subscribers = /* @__PURE__ */ new Map();
300
+ }
301
+ get identifier() {
302
+ return getIdentifier({
303
+ name: this._name,
304
+ ip: this._ip
305
+ });
306
+ }
307
+ get name() {
308
+ return this._name;
309
+ }
310
+ get ip() {
311
+ return this._ip;
312
+ }
313
+ get remoteTypeTarPath() {
314
+ return this._remoteTypeTarPath;
315
+ }
316
+ get hasSubscribes() {
317
+ return Boolean(this._subscribers.size);
318
+ }
319
+ get subscribers() {
320
+ return this._subscribers;
321
+ }
322
+ addSubscriber(identifier, subscriber) {
323
+ fileLog(`${this.name} set subscriber: ${identifier}`, "Publisher", "info");
324
+ this._subscribers.set(identifier, subscriber);
325
+ }
326
+ removeSubscriber(identifier) {
327
+ if (this._subscribers.has(identifier)) {
328
+ fileLog(
329
+ `${this.name} removeSubscriber: ${identifier}`,
330
+ "Publisher",
331
+ "warn"
332
+ );
333
+ this._subscribers.delete(identifier);
334
+ }
335
+ }
336
+ notifySubscriber(subscriberIdentifier, options) {
337
+ const subscriber = this._subscribers.get(subscriberIdentifier);
338
+ if (!subscriber) {
339
+ fileLog(
340
+ `[notifySubscriber] ${this.name} notifySubscriber: ${subscriberIdentifier}, does not exits`,
341
+ "Publisher",
342
+ "error"
343
+ );
344
+ return;
345
+ }
346
+ const api = new UpdateSubscriberAPI(options);
347
+ subscriber.send(JSON.stringify(api));
348
+ fileLog(
349
+ `[notifySubscriber] ${this.name} notifySubscriber: ${JSON.stringify(
350
+ subscriberIdentifier
351
+ )}, message: ${JSON.stringify(api)}`,
352
+ "Publisher",
353
+ "info"
354
+ );
355
+ }
356
+ notifySubscribers(options) {
357
+ const api = new UpdateSubscriberAPI(options);
358
+ this.broadcast(api);
359
+ }
360
+ broadcast(message) {
361
+ if (this.hasSubscribes) {
362
+ this._subscribers.forEach((subscriber, key) => {
363
+ fileLog(
364
+ `[BroadCast] ${this.name} notifySubscriber: ${key}, PID: ${process.pid}, message: ${JSON.stringify(message)}`,
365
+ "Publisher",
366
+ "info"
367
+ );
368
+ subscriber.send(JSON.stringify(message));
369
+ });
370
+ } else {
371
+ fileLog(
372
+ `[BroadCast] ${this.name}'s subscribe is empty`,
373
+ "Publisher",
374
+ "warn"
375
+ );
376
+ }
377
+ }
378
+ close() {
379
+ this._subscribers.forEach((_subscriber, identifier) => {
380
+ fileLog(
381
+ `[BroadCast] close ${this.name} remove: ${identifier}`,
382
+ "Publisher",
383
+ "warn"
384
+ );
385
+ this.removeSubscriber(identifier);
386
+ });
387
+ }
388
+ };
389
+
390
+ // packages/dts-plugin/src/server/DevServer.ts
391
+ var import_isomorphic_ws2 = __toESM(require("isomorphic-ws"));
392
+
393
+ // packages/dts-plugin/src/server/broker/Broker.ts
394
+ var import_http = require("http");
395
+ var import_isomorphic_ws = __toESM(require("isomorphic-ws"));
396
+ var import_node_schedule = __toESM(require("node-schedule"));
397
+ var import_url = require("url");
398
+ var _Broker = class _Broker {
399
+ constructor() {
400
+ // 1.5h
401
+ this._publisherMap = /* @__PURE__ */ new Map();
402
+ this._webClientMap = /* @__PURE__ */ new Map();
403
+ this._tmpSubscriberShelter = /* @__PURE__ */ new Map();
404
+ this._scheduleJob = null;
405
+ this._setSchedule();
406
+ this._startWsServer();
407
+ this._stopWhenSIGTERMOrSIGINT();
408
+ this._handleUnexpectedExit();
409
+ }
410
+ get hasPublishers() {
411
+ return Boolean(this._publisherMap.size);
412
+ }
413
+ async _startWsServer() {
414
+ const wsHandler = (ws, req) => {
415
+ const { url: reqUrl = "" } = req;
416
+ const { query } = (0, import_url.parse)(reqUrl, true);
417
+ const { WEB_SOCKET_CONNECT_MAGIC_ID: WEB_SOCKET_CONNECT_MAGIC_ID2 } = query;
418
+ if (WEB_SOCKET_CONNECT_MAGIC_ID2 === _Broker.WEB_SOCKET_CONNECT_MAGIC_ID) {
419
+ ws.on("message", (message) => {
420
+ try {
421
+ const text = message.toString();
422
+ const action = JSON.parse(text);
423
+ fileLog(`${action == null ? void 0 : action.kind} action received `, "Broker", "info");
424
+ this._takeAction(action, ws);
425
+ } catch (error2) {
426
+ fileLog(`parse action message error: ${error2}`, "Broker", "error");
427
+ }
428
+ });
429
+ ws.on("error", (e) => {
430
+ fileLog(`parse action message error: ${e}`, "Broker", "error");
431
+ });
432
+ } else {
433
+ ws.send("Invalid CONNECT ID.");
434
+ fileLog("Invalid CONNECT ID.", "Broker", "warn");
435
+ ws.close();
436
+ }
437
+ };
438
+ const server = (0, import_http.createServer)();
439
+ this._webSocketServer = new import_isomorphic_ws.default.Server({ noServer: true });
440
+ this._webSocketServer.on("error", (err) => {
441
+ fileLog(`ws error:
442
+ ${err.message}
443
+ ${err.stack}`, "Broker", "error");
444
+ });
445
+ this._webSocketServer.on("listening", () => {
446
+ fileLog(
447
+ `WebSocket server is listening on port ${_Broker.DEFAULT_WEB_SOCKET_PORT}`,
448
+ "Broker",
449
+ "info"
450
+ );
451
+ });
452
+ this._webSocketServer.on("connection", wsHandler);
453
+ this._webSocketServer.on("close", (code) => {
454
+ fileLog(`WebSocket Server Close with Code ${code}`, "Broker", "warn");
455
+ this._webSocketServer && this._webSocketServer.close();
456
+ this._webSocketServer = void 0;
457
+ });
458
+ server.on("upgrade", (req, socket, head) => {
459
+ var _a;
460
+ if (req.url) {
461
+ const { pathname } = (0, import_url.parse)(req.url);
462
+ if (pathname === "/") {
463
+ (_a = this._webSocketServer) == null ? void 0 : _a.handleUpgrade(req, socket, head, (ws) => {
464
+ var _a2;
465
+ (_a2 = this._webSocketServer) == null ? void 0 : _a2.emit("connection", ws, req);
466
+ });
467
+ }
468
+ }
469
+ });
470
+ server.listen(_Broker.DEFAULT_WEB_SOCKET_PORT);
471
+ }
472
+ async _takeAction(action, client) {
473
+ const { kind, payload } = action;
474
+ if (kind === "ADD_PUBLISHER" /* ADD_PUBLISHER */) {
475
+ await this._addPublisher(payload, client);
476
+ }
477
+ if (kind === "UPDATE_PUBLISHER" /* UPDATE_PUBLISHER */) {
478
+ await this._updatePublisher(
479
+ payload,
480
+ client
481
+ );
482
+ }
483
+ if (kind === "ADD_SUBSCRIBER" /* ADD_SUBSCRIBER */) {
484
+ await this._addSubscriber(payload, client);
485
+ }
486
+ if (kind === "EXIT_SUBSCRIBER" /* EXIT_SUBSCRIBER */) {
487
+ await this._removeSubscriber(
488
+ payload,
489
+ client
490
+ );
491
+ }
492
+ if (kind === "EXIT_PUBLISHER" /* EXIT_PUBLISHER */) {
493
+ await this._removePublisher(payload, client);
494
+ }
495
+ if (kind === "ADD_WEB_CLIENT" /* ADD_WEB_CLIENT */) {
496
+ await this._addWebClient(payload, client);
497
+ }
498
+ if (kind === "NOTIFY_WEB_CLIENT" /* NOTIFY_WEB_CLIENT */) {
499
+ await this._notifyWebClient(
500
+ payload,
501
+ client
502
+ );
503
+ }
504
+ }
505
+ async _addPublisher(context, client) {
506
+ const { name, ip, remoteTypeTarPath } = context ?? {};
507
+ const identifier = getIdentifier({ name, ip });
508
+ if (this._publisherMap.has(identifier)) {
509
+ fileLog(
510
+ `[${"ADD_PUBLISHER" /* ADD_PUBLISHER */}] ${identifier} has been added, this action will be ignored`,
511
+ "Broker",
512
+ "warn"
513
+ );
514
+ return;
515
+ }
516
+ try {
517
+ const publisher = new Publisher({ name, ip, remoteTypeTarPath });
518
+ this._publisherMap.set(identifier, publisher);
519
+ fileLog(
520
+ `[${"ADD_PUBLISHER" /* ADD_PUBLISHER */}] ${identifier} Adding Publisher Succeed`,
521
+ "Broker",
522
+ "info"
523
+ );
524
+ const tmpSubScribers = this._getTmpSubScribers(identifier);
525
+ if (tmpSubScribers) {
526
+ fileLog(
527
+ `[${"ADD_PUBLISHER" /* ADD_PUBLISHER */}] consumeTmpSubscriber set ${publisher.name}\u2019s subscribers `,
528
+ "Broker",
529
+ "info"
530
+ );
531
+ this._consumeTmpSubScribers(publisher, tmpSubScribers);
532
+ this._clearTmpSubScriberRelation(identifier);
533
+ }
534
+ } catch (err) {
535
+ const msg = error(err, "ADD_PUBLISHER" /* ADD_PUBLISHER */, "Broker");
536
+ client.send(msg);
537
+ client.close();
538
+ }
539
+ }
540
+ async _updatePublisher(context, client) {
541
+ const {
542
+ name,
543
+ updateMode,
544
+ updateKind,
545
+ updateSourcePaths,
546
+ remoteTypeTarPath,
547
+ ip
548
+ } = context ?? {};
549
+ const identifier = getIdentifier({ name, ip });
550
+ if (!this._publisherMap.has(identifier)) {
551
+ fileLog(
552
+ `[${"UPDATE_PUBLISHER" /* UPDATE_PUBLISHER */}] ${identifier} has not been started, this action will be ignored
553
+ this._publisherMap: ${JSON.stringify(this._publisherMap.entries())}
554
+ `,
555
+ "Broker",
556
+ "warn"
557
+ );
558
+ return;
559
+ }
560
+ try {
561
+ const publisher = this._publisherMap.get(identifier);
562
+ fileLog(
563
+ // eslint-disable-next-line max-len
564
+ `[${"UPDATE_PUBLISHER" /* UPDATE_PUBLISHER */}] ${identifier} update, and notify subscribers to update`,
565
+ "Broker",
566
+ "info"
567
+ );
568
+ if (publisher) {
569
+ publisher.notifySubscribers({
570
+ remoteTypeTarPath,
571
+ name,
572
+ updateMode,
573
+ updateKind,
574
+ updateSourcePaths: updateSourcePaths || []
575
+ });
576
+ }
577
+ } catch (err) {
578
+ const msg = error(err, "UPDATE_PUBLISHER" /* UPDATE_PUBLISHER */, "Broker");
579
+ client.send(msg);
580
+ client.close();
581
+ }
582
+ }
583
+ // app1 consumes provider1,provider2. Dependencies at this time: publishers: [provider1, provider2], subscriberName: app1
584
+ // provider1 is app1's remote
585
+ async _addSubscriber(context, client) {
586
+ const { publishers, name: subscriberName } = context ?? {};
587
+ publishers.forEach((publisher) => {
588
+ const { name, ip } = publisher;
589
+ const identifier = getIdentifier({ name, ip });
590
+ if (!this._publisherMap.has(identifier)) {
591
+ fileLog(
592
+ `[${"ADD_SUBSCRIBER" /* ADD_SUBSCRIBER */}]: ${identifier} has not been started, ${subscriberName} will add the relation to tmp shelter`,
593
+ "Broker",
594
+ "warn"
595
+ );
596
+ this._addTmpSubScriberRelation(
597
+ {
598
+ name: getIdentifier({
599
+ name: context.name,
600
+ ip: context.ip
601
+ }),
602
+ client
603
+ },
604
+ publisher
605
+ );
606
+ return;
607
+ }
608
+ try {
609
+ const registeredPublisher = this._publisherMap.get(identifier);
610
+ if (registeredPublisher) {
611
+ registeredPublisher.addSubscriber(
612
+ getIdentifier({
613
+ name: subscriberName,
614
+ ip: context.ip
615
+ }),
616
+ client
617
+ );
618
+ fileLog(
619
+ // eslint-disable-next-line @ies/eden/max-calls-in-template
620
+ `[${"ADD_SUBSCRIBER" /* ADD_SUBSCRIBER */}]: ${identifier} has been started, Adding Subscriber ${subscriberName} Succeed, this.__publisherMap are: ${JSON.stringify(
621
+ Array.from(this._publisherMap.entries())
622
+ )}`,
623
+ "Broker",
624
+ "info"
625
+ );
626
+ registeredPublisher.notifySubscriber(
627
+ getIdentifier({
628
+ name: subscriberName,
629
+ ip: context.ip
630
+ }),
631
+ {
632
+ updateKind: "UPDATE_TYPE" /* UPDATE_TYPE */,
633
+ updateMode: "PASSIVE" /* PASSIVE */,
634
+ updateSourcePaths: [registeredPublisher.name],
635
+ remoteTypeTarPath: registeredPublisher.remoteTypeTarPath,
636
+ name: registeredPublisher.name
637
+ }
638
+ );
639
+ fileLog(
640
+ // eslint-disable-next-line @ies/eden/max-calls-in-template
641
+ `[${"ADD_SUBSCRIBER" /* ADD_SUBSCRIBER */}]: notifySubscriber Subscriber ${subscriberName}, updateMode: "PASSIVE", updateSourcePaths: ${registeredPublisher.name}`,
642
+ "Broker",
643
+ "info"
644
+ );
645
+ }
646
+ } catch (err) {
647
+ const msg = error(err, "ADD_SUBSCRIBER" /* ADD_SUBSCRIBER */, "Broker");
648
+ client.send(msg);
649
+ client.close();
650
+ }
651
+ });
652
+ }
653
+ // Trigger while consumer exit
654
+ async _removeSubscriber(context, client) {
655
+ const { publishers } = context ?? {};
656
+ const subscriberIdentifier = getIdentifier({
657
+ name: context == null ? void 0 : context.name,
658
+ ip: context == null ? void 0 : context.ip
659
+ });
660
+ publishers.forEach((publisher) => {
661
+ const { name, ip } = publisher;
662
+ const identifier = getIdentifier({
663
+ name,
664
+ ip
665
+ });
666
+ const registeredPublisher = this._publisherMap.get(identifier);
667
+ if (!registeredPublisher) {
668
+ fileLog(
669
+ `[${"EXIT_SUBSCRIBER" /* EXIT_SUBSCRIBER */}], ${identifier} does not exit `,
670
+ "Broker",
671
+ "warn"
672
+ );
673
+ return;
674
+ }
675
+ try {
676
+ fileLog(
677
+ `[${"EXIT_SUBSCRIBER" /* EXIT_SUBSCRIBER */}], ${identifier} will exit `,
678
+ "Broker",
679
+ "INFO"
680
+ );
681
+ registeredPublisher.removeSubscriber(subscriberIdentifier);
682
+ this._clearTmpSubScriberRelation(identifier);
683
+ if (!registeredPublisher.hasSubscribes) {
684
+ this._publisherMap.delete(identifier);
685
+ }
686
+ if (!this.hasPublishers) {
687
+ this.exit();
688
+ }
689
+ } catch (err) {
690
+ const msg = error(err, "EXIT_SUBSCRIBER" /* EXIT_SUBSCRIBER */, "Broker");
691
+ client.send(msg);
692
+ client.close();
693
+ }
694
+ });
695
+ }
696
+ async _removePublisher(context, client) {
697
+ const { name, ip } = context ?? {};
698
+ const identifier = getIdentifier({
699
+ name,
700
+ ip
701
+ });
702
+ const publisher = this._publisherMap.get(identifier);
703
+ if (!publisher) {
704
+ fileLog(
705
+ `[${"EXIT_PUBLISHER" /* EXIT_PUBLISHER */}]: ${identifier}} has not been added, this action will be ingored`,
706
+ "Broker",
707
+ "warn"
708
+ );
709
+ return;
710
+ }
711
+ try {
712
+ const { subscribers } = publisher;
713
+ subscribers.forEach((subscriber, subscriberIdentifier) => {
714
+ this._addTmpSubScriberRelation(
715
+ {
716
+ name: subscriberIdentifier,
717
+ client: subscriber
718
+ },
719
+ { name: publisher.name, ip: publisher.ip }
720
+ );
721
+ fileLog(
722
+ // eslint-disable-next-line max-len
723
+ `[${"EXIT_PUBLISHER" /* EXIT_PUBLISHER */}]: ${identifier} is removing , subscriber: ${subscriberIdentifier} will be add tmpSubScriberRelation`,
724
+ "Broker",
725
+ "info"
726
+ );
727
+ });
728
+ this._publisherMap.delete(identifier);
729
+ fileLog(
730
+ `[${"EXIT_PUBLISHER" /* EXIT_PUBLISHER */}]: ${identifier} is removed `,
731
+ "Broker",
732
+ "info"
733
+ );
734
+ if (!this.hasPublishers) {
735
+ fileLog(
736
+ `[${"EXIT_PUBLISHER" /* EXIT_PUBLISHER */}]: _publisherMap is empty, all server will exit `,
737
+ "Broker",
738
+ "warn"
739
+ );
740
+ this.exit();
741
+ }
742
+ } catch (err) {
743
+ const msg = error(err, "EXIT_PUBLISHER" /* EXIT_PUBLISHER */, "Broker");
744
+ client.send(msg);
745
+ client.close();
746
+ }
747
+ }
748
+ async _addWebClient(context, client) {
749
+ const { name } = context ?? {};
750
+ const identifier = getIdentifier({
751
+ name
752
+ });
753
+ if (this._webClientMap.has(identifier)) {
754
+ fileLog(
755
+ `${identifier}} has been added, this action will override prev WebClient`,
756
+ "Broker",
757
+ "warn"
758
+ );
759
+ }
760
+ try {
761
+ this._webClientMap.set(identifier, client);
762
+ fileLog(`${identifier} adding WebClient Succeed`, "Broker", "info");
763
+ } catch (err) {
764
+ const msg = error(err, "ADD_WEB_CLIENT" /* ADD_WEB_CLIENT */, "Broker");
765
+ client.send(msg);
766
+ client.close();
767
+ }
768
+ }
769
+ async _notifyWebClient(context, client) {
770
+ const { name, updateMode } = context ?? {};
771
+ const identifier = getIdentifier({
772
+ name
773
+ });
774
+ const webClient = this._webClientMap.get(identifier);
775
+ if (!webClient) {
776
+ fileLog(
777
+ `[${"NOTIFY_WEB_CLIENT" /* NOTIFY_WEB_CLIENT */}] ${identifier} has not been added, this action will be ignored`,
778
+ "Broker",
779
+ "warn"
780
+ );
781
+ return;
782
+ }
783
+ try {
784
+ const api = new ReloadWebClientAPI({ name, updateMode });
785
+ webClient.send(JSON.stringify(api));
786
+ fileLog(
787
+ `[${"NOTIFY_WEB_CLIENT" /* NOTIFY_WEB_CLIENT */}] Notify ${name} WebClient Succeed`,
788
+ "Broker",
789
+ "info"
790
+ );
791
+ } catch (err) {
792
+ const msg = error(err, "NOTIFY_WEB_CLIENT" /* NOTIFY_WEB_CLIENT */, "Broker");
793
+ client.send(msg);
794
+ client.close();
795
+ }
796
+ }
797
+ // app1 consumes provider1, and provider1 not launch. this._tmpSubscriberShelter at this time: {provider1: Map{subscribers: Map{app1: app1+ip+client'}, timestamp: 'xx'} }
798
+ _addTmpSubScriberRelation(subscriber, publisher) {
799
+ const publisherIdentifier = getIdentifier({
800
+ name: publisher.name,
801
+ ip: publisher.ip
802
+ });
803
+ const subscriberIdentifier = subscriber.name;
804
+ const shelter = this._tmpSubscriberShelter.get(publisherIdentifier);
805
+ if (!shelter) {
806
+ const map = /* @__PURE__ */ new Map();
807
+ map.set(subscriberIdentifier, subscriber);
808
+ this._tmpSubscriberShelter.set(publisherIdentifier, {
809
+ subscribers: map,
810
+ timestamp: Date.now()
811
+ });
812
+ fileLog(
813
+ `[AddTmpSubscriberRelation] ${publisherIdentifier}'s subscriber has ${subscriberIdentifier} `,
814
+ "Broker",
815
+ "info"
816
+ );
817
+ return;
818
+ }
819
+ const tmpSubScriberShelterSubscriber = shelter.subscribers.get(subscriberIdentifier);
820
+ if (tmpSubScriberShelterSubscriber) {
821
+ fileLog(
822
+ `[AddTmpSubscriberRelation] ${publisherIdentifier} and ${subscriberIdentifier} relation has been added`,
823
+ "Broker",
824
+ "warn"
825
+ );
826
+ shelter.subscribers.set(subscriberIdentifier, subscriber);
827
+ shelter.timestamp = Date.now();
828
+ } else {
829
+ fileLog(
830
+ // eslint-disable-next-line max-len
831
+ `AddTmpSubscriberLog ${publisherIdentifier}'s shelter has been added, update shelter.subscribers ${subscriberIdentifier}`,
832
+ "Broker",
833
+ "warn"
834
+ );
835
+ shelter.subscribers.set(subscriberIdentifier, subscriber);
836
+ }
837
+ }
838
+ _getTmpSubScribers(publisherIdentifier) {
839
+ var _a;
840
+ return (_a = this._tmpSubscriberShelter.get(publisherIdentifier)) == null ? void 0 : _a.subscribers;
841
+ }
842
+ // after adding publisher, it will change the temp subscriber to regular subscriber
843
+ _consumeTmpSubScribers(publisher, tmpSubScribers) {
844
+ tmpSubScribers.forEach((tmpSubScriber, identifier) => {
845
+ fileLog(
846
+ `notifyTmpSubScribers ${publisher.name} will be add a subscriber: ${identifier} `,
847
+ "Broker",
848
+ "warn"
849
+ );
850
+ publisher.addSubscriber(identifier, tmpSubScriber.client);
851
+ publisher.notifySubscriber(identifier, {
852
+ updateKind: "UPDATE_TYPE" /* UPDATE_TYPE */,
853
+ updateMode: "PASSIVE" /* PASSIVE */,
854
+ updateSourcePaths: [publisher.name],
855
+ remoteTypeTarPath: publisher.remoteTypeTarPath,
856
+ name: publisher.name
857
+ });
858
+ });
859
+ }
860
+ _clearTmpSubScriberRelation(identifier) {
861
+ this._tmpSubscriberShelter.delete(identifier);
862
+ }
863
+ _clearTmpSubScriberRelations() {
864
+ this._tmpSubscriberShelter.clear();
865
+ }
866
+ _disconnect() {
867
+ this._publisherMap.forEach((publisher) => {
868
+ publisher.close();
869
+ });
870
+ }
871
+ // Every day on 0/6/9/12/15//18, Publishers that have not been connected within 1.5 hours will be cleared regularly.
872
+ // If process.env.FEDERATION_SERVER_TEST is set, it will be read at a specified time.
873
+ _setSchedule() {
874
+ const rule = new import_node_schedule.default.RecurrenceRule();
875
+ if (Number(process.env["FEDERATION_SERVER_TEST"])) {
876
+ const interval = Number(process.env["FEDERATION_SERVER_TEST"]) / 1e3;
877
+ const second = [];
878
+ for (let i = 0; i < 60; i = i + interval) {
879
+ second.push(i);
880
+ }
881
+ rule.second = second;
882
+ } else {
883
+ rule.second = 0;
884
+ rule.hour = [0, 3, 6, 9, 12, 15, 18];
885
+ rule.minute = 0;
886
+ }
887
+ const serverTest = Number(process.env["FEDERATION_SERVER_TEST"]);
888
+ this._scheduleJob = import_node_schedule.default.scheduleJob(rule, () => {
889
+ this._tmpSubscriberShelter.forEach((tmpSubscriber, identifier) => {
890
+ fileLog(
891
+ ` _clearTmpSubScriberRelation ${identifier}, ${Date.now() - tmpSubscriber.timestamp >= (process.env["GARFISH_MODULE_SERVER_TEST"] ? serverTest : _Broker.DEFAULT_WAITING_TIME)}`,
892
+ "Broker",
893
+ "info"
894
+ );
895
+ if (Date.now() - tmpSubscriber.timestamp >= (process.env["FEDERATION_SERVER_TEST"] ? serverTest : _Broker.DEFAULT_WAITING_TIME)) {
896
+ this._clearTmpSubScriberRelation(identifier);
897
+ }
898
+ });
899
+ });
900
+ }
901
+ _clearSchedule() {
902
+ if (!this._scheduleJob) {
903
+ return;
904
+ }
905
+ this._scheduleJob.cancel();
906
+ this._scheduleJob = null;
907
+ }
908
+ _stopWhenSIGTERMOrSIGINT() {
909
+ process.on("SIGTERM", () => {
910
+ this.exit();
911
+ });
912
+ process.on("SIGINT", () => {
913
+ this.exit();
914
+ });
915
+ }
916
+ _handleUnexpectedExit() {
917
+ process.on("unhandledRejection", (error2) => {
918
+ console.error("Unhandled Rejection Error: ", error2);
919
+ fileLog(`Unhandled Rejection Error: ${error2}`, "Broker", "fatal");
920
+ process.exit(1);
921
+ });
922
+ process.on("uncaughtException", (error2) => {
923
+ console.error("Unhandled Exception Error: ", error2);
924
+ fileLog(`Unhandled Rejection Error: ${error2}`, "Broker", "fatal");
925
+ process.exit(1);
926
+ });
927
+ }
928
+ async start() {
929
+ }
930
+ exit() {
931
+ const brokerExitLog = new BrokerExitLog();
932
+ this.broadcast(JSON.stringify(brokerExitLog));
933
+ this._disconnect();
934
+ this._clearSchedule();
935
+ this._clearTmpSubScriberRelations();
936
+ this._webSocketServer && this._webSocketServer.close();
937
+ this._secureWebSocketServer && this._secureWebSocketServer.close();
938
+ process.exit(0);
939
+ }
940
+ broadcast(message) {
941
+ var _a, _b;
942
+ fileLog(
943
+ `[broadcast] exit info : ${JSON.stringify(message)}`,
944
+ "Broker",
945
+ "warn"
946
+ );
947
+ (_a = this._webSocketServer) == null ? void 0 : _a.clients.forEach((client) => {
948
+ client.send(JSON.stringify(message));
949
+ });
950
+ (_b = this._secureWebSocketServer) == null ? void 0 : _b.clients.forEach((client) => {
951
+ client.send(JSON.stringify(message));
952
+ });
953
+ }
954
+ };
955
+ _Broker.WEB_SOCKET_CONNECT_MAGIC_ID = WEB_SOCKET_CONNECT_MAGIC_ID;
956
+ _Broker.DEFAULT_WEB_SOCKET_PORT = DEFAULT_WEB_SOCKET_PORT;
957
+ _Broker.DEFAULT_SECURE_WEB_SOCKET_PORT = 16324;
958
+ _Broker.DEFAULT_WAITING_TIME = 1.5 * 60 * 60 * 1e3;
959
+ var Broker = _Broker;
960
+
961
+ // packages/dts-plugin/src/server/createKoaServer.ts
962
+ var import_fs_extra = __toESM(require("fs-extra"));
963
+ var import_koa = __toESM(require("koa"));
964
+
185
965
  // packages/dts-plugin/src/core/lib/archiveHandler.ts
186
966
  var retrieveTypesZipPath = (mfTypesPath, remoteOptions) => (0, import_path2.join)(
187
967
  mfTypesPath.replace(remoteOptions.typesFolder, ""),
@@ -220,17 +1000,15 @@ var downloadTypesArchive = (hostOptions) => {
220
1000
  const zip = new import_adm_zip.default(Buffer.from(response.data));
221
1001
  zip.extractAllTo(destinationPath, true);
222
1002
  return [destinationFolder, destinationPath];
223
- } catch (error) {
224
- if (isDebugMode()) {
225
- console.error(
226
- import_ansi_colors2.default.red(
227
- `Error during types archive download: ${(error == null ? void 0 : error.message) || "unknown error"}`
228
- )
229
- );
230
- }
1003
+ } catch (error2) {
1004
+ fileLog(
1005
+ `Error during types archive download: ${(error2 == null ? void 0 : error2.message) || "unknown error"}`,
1006
+ "downloadTypesArchive",
1007
+ "error"
1008
+ );
231
1009
  if (retries >= hostOptions.maxRetries) {
232
1010
  if (hostOptions.abortOnError !== false) {
233
- throw error;
1011
+ throw error2;
234
1012
  }
235
1013
  return void 0;
236
1014
  }
@@ -240,7 +1018,7 @@ var downloadTypesArchive = (hostOptions) => {
240
1018
  };
241
1019
 
242
1020
  // packages/dts-plugin/src/core/configurations/hostPlugin.ts
243
- var import_sdk = require("@module-federation/sdk");
1021
+ var import_sdk3 = require("@module-federation/sdk");
244
1022
  var import_managers = require("@module-federation/managers");
245
1023
  var defaultOptions = {
246
1024
  typesFolder: "@mf-types",
@@ -254,7 +1032,7 @@ var defaultOptions = {
254
1032
  };
255
1033
  var buildZipUrl = (hostOptions, url) => {
256
1034
  const remoteUrl = new URL(url);
257
- if (remoteUrl.href.includes(import_sdk.MANIFEST_EXT)) {
1035
+ if (remoteUrl.href.includes(import_sdk3.MANIFEST_EXT)) {
258
1036
  return void 0;
259
1037
  }
260
1038
  const pathnameWithoutEntry = remoteUrl.pathname.split("/").slice(0, -1).join("/");
@@ -269,7 +1047,7 @@ var buildApiTypeUrl = (zipUrl) => {
269
1047
  };
270
1048
  var retrieveRemoteInfo = (options) => {
271
1049
  const { hostOptions, remoteAlias, remote } = options;
272
- const parsedInfo = (0, import_sdk.parseEntry)(remote, void 0, "@");
1050
+ const parsedInfo = (0, import_sdk3.parseEntry)(remote, void 0, "@");
273
1051
  const url = "entry" in parsedInfo ? parsedInfo.entry : parsedInfo.name === remote ? remote : "";
274
1052
  const zipUrl = url ? buildZipUrl(hostOptions, url) : "";
275
1053
  return {
@@ -336,6 +1114,7 @@ var DTSManager = class {
336
1114
  });
337
1115
  this.runtimePkgs = [
338
1116
  "@module-federation/runtime",
1117
+ "@module-federation/enhanced/runtime",
339
1118
  "@module-federation/runtime-tools"
340
1119
  ];
341
1120
  this.loadedRemoteAPIAlias = [];
@@ -419,20 +1198,20 @@ var DTSManager = class {
419
1198
  force: true
420
1199
  });
421
1200
  }
422
- console.log(import_ansi_colors3.default.green("Federated types created correctly"));
423
- } catch (error) {
1201
+ console.log(import_ansi_colors2.default.green("Federated types created correctly"));
1202
+ } catch (error2) {
424
1203
  if (((_a = this.options.remote) == null ? void 0 : _a.abortOnError) === false) {
425
1204
  console.error(
426
- import_ansi_colors3.default.red(`Unable to compile federated types, ${error}`)
1205
+ import_ansi_colors2.default.red(`Unable to compile federated types, ${error2}`)
427
1206
  );
428
1207
  } else {
429
- throw error;
1208
+ throw error2;
430
1209
  }
431
1210
  }
432
1211
  }
433
1212
  async requestRemoteManifest(remoteInfo) {
434
1213
  try {
435
- if (!remoteInfo.url.includes(import_sdk2.MANIFEST_EXT)) {
1214
+ if (!remoteInfo.url.includes(import_sdk4.MANIFEST_EXT)) {
436
1215
  return remoteInfo;
437
1216
  }
438
1217
  const url = replaceLocalhost(remoteInfo.url);
@@ -464,7 +1243,11 @@ var DTSManager = class {
464
1243
  ).href;
465
1244
  return remoteInfo;
466
1245
  } catch (_err) {
467
- console.error(_err);
1246
+ fileLog(
1247
+ `fetch manifest failed, ${_err}, ${remoteInfo.name} will be ignored`,
1248
+ "requestRemoteManifest",
1249
+ "error"
1250
+ );
468
1251
  return remoteInfo;
469
1252
  }
470
1253
  }
@@ -492,10 +1275,10 @@ var DTSManager = class {
492
1275
  import_fs.default.writeFileSync(filePath, apiTypeFile);
493
1276
  this.loadedRemoteAPIAlias.push(remoteInfo.alias);
494
1277
  } catch (err) {
495
- console.error(
496
- import_ansi_colors3.default.red(
497
- `Unable to download "${remoteInfo.name}" api types, ${err}`
498
- )
1278
+ fileLog(
1279
+ `Unable to download "${remoteInfo.name}" api types, ${err}`,
1280
+ "consumeTargetRemotes",
1281
+ "error"
499
1282
  );
500
1283
  }
501
1284
  }
@@ -544,8 +1327,10 @@ var DTSManager = class {
544
1327
  recursive: true,
545
1328
  force: true
546
1329
  }).catch(
547
- (error) => console.error(
548
- import_ansi_colors3.default.red(`Unable to remove types folder, ${error}`)
1330
+ (error2) => fileLog(
1331
+ `Unable to remove types folder, ${error2}`,
1332
+ "consumeArchiveTypes",
1333
+ "error"
549
1334
  )
550
1335
  );
551
1336
  }
@@ -596,11 +1381,13 @@ var DTSManager = class {
596
1381
  );
597
1382
  this.consumeAPITypes(hostOptions);
598
1383
  }
599
- console.log(import_ansi_colors3.default.green("Federated types extraction completed"));
1384
+ console.log(import_ansi_colors2.default.green("Federated types extraction completed"));
600
1385
  } catch (err) {
601
1386
  if (((_a = this.options.host) == null ? void 0 : _a.abortOnError) === false) {
602
- console.error(
603
- import_ansi_colors3.default.red(`Unable to consume federated types, ${err}`)
1387
+ fileLog(
1388
+ `Unable to consume federated types, ${err}`,
1389
+ "consumeTypes",
1390
+ "error"
604
1391
  );
605
1392
  } else {
606
1393
  throw err;
@@ -649,7 +1436,7 @@ var DTSManager = class {
649
1436
  };
650
1437
 
651
1438
  // packages/dts-plugin/src/core/lib/utils.ts
652
- var import_ansi_colors4 = __toESM(require("ansi-colors"));
1439
+ var import_ansi_colors3 = __toESM(require("ansi-colors"));
653
1440
  function getDTSManagerConstructor(implementation) {
654
1441
  if (implementation) {
655
1442
  const NewConstructor = require(implementation);
@@ -687,7 +1474,7 @@ function retrieveTypesAssetsInfo(options) {
687
1474
  apiFileName: import_path4.default.basename(apiTypesPath)
688
1475
  };
689
1476
  } catch (err) {
690
- console.error(import_ansi_colors4.default.red(`Unable to compile federated types, ${err}`));
1477
+ console.error(import_ansi_colors3.default.red(`Unable to compile federated types, ${err}`));
691
1478
  return {
692
1479
  apiTypesPath: "",
693
1480
  zipTypesPath: "",
@@ -699,9 +1486,6 @@ function retrieveTypesAssetsInfo(options) {
699
1486
  function replaceLocalhost(url) {
700
1487
  return url.replace("localhost", "127.0.0.1");
701
1488
  }
702
- function isDebugMode() {
703
- return Boolean(process.env["FEDERATION_DEBUG"]);
704
- }
705
1489
 
706
1490
  // packages/dts-plugin/src/core/configurations/remotePlugin.ts
707
1491
  var defaultOptions2 = {
@@ -855,9 +1639,9 @@ function exposeRpc(fn) {
855
1639
  new Error(`Process ${import_process.default.pid} doesn't have open IPC channels`)
856
1640
  );
857
1641
  } else {
858
- import_process.default.send(message, void 0, void 0, (error) => {
859
- if (error) {
860
- reject(error);
1642
+ import_process.default.send(message, void 0, void 0, (error2) => {
1643
+ if (error2) {
1644
+ reject(error2);
861
1645
  } else {
862
1646
  resolve4(void 0);
863
1647
  }
@@ -869,18 +1653,18 @@ function exposeRpc(fn) {
869
1653
  if (!import_process.default.send) {
870
1654
  return;
871
1655
  }
872
- let value, error;
1656
+ let value, error2;
873
1657
  try {
874
1658
  value = await fn(...message.args);
875
1659
  } catch (fnError) {
876
- error = fnError;
1660
+ error2 = fnError;
877
1661
  }
878
1662
  try {
879
- if (error) {
1663
+ if (error2) {
880
1664
  await sendMessage({
881
1665
  type: "mf_reject" /* REJECT */,
882
1666
  id: message.id,
883
- error
1667
+ error: error2
884
1668
  });
885
1669
  } else {
886
1670
  await sendMessage({
@@ -890,9 +1674,9 @@ function exposeRpc(fn) {
890
1674
  });
891
1675
  }
892
1676
  } catch (sendError) {
893
- if (error) {
894
- if (error instanceof Error) {
895
- console.error(error);
1677
+ if (error2) {
1678
+ if (error2 instanceof Error) {
1679
+ console.error(error2);
896
1680
  }
897
1681
  }
898
1682
  console.error(sendError);
@@ -984,9 +1768,9 @@ function wrapRpc(childProcess, options) {
984
1768
  id,
985
1769
  args
986
1770
  },
987
- (error) => {
988
- if (error) {
989
- rejectSend(error);
1771
+ (error2) => {
1772
+ if (error2) {
1773
+ rejectSend(error2);
990
1774
  removeHandlers();
991
1775
  } else {
992
1776
  resolveSend(void 0);