@module-federation/dts-plugin 0.0.0-chore-bump-node-22-20260710161714

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,783 @@
1
+ const require_Action = require('./Action-CzhPMw2i.js');
2
+ let fs = require("fs");
3
+ fs = require_Action.__toESM(fs);
4
+ let url = require("url");
5
+ let path = require("path");
6
+ path = require_Action.__toESM(path);
7
+ let _module_federation_sdk = require("@module-federation/sdk");
8
+ let net = require("net");
9
+ net = require_Action.__toESM(net);
10
+ let os = require("os");
11
+ os = require_Action.__toESM(os);
12
+ let isomorphic_ws = require("isomorphic-ws");
13
+ isomorphic_ws = require_Action.__toESM(isomorphic_ws);
14
+ let http = require("http");
15
+ let node_schedule = require("node-schedule");
16
+ node_schedule = require_Action.__toESM(node_schedule);
17
+
18
+ //#region src/server/message/API/API.ts
19
+ let APIKind = /* @__PURE__ */ function(APIKind) {
20
+ APIKind["UPDATE_SUBSCRIBER"] = "UPDATE_SUBSCRIBER";
21
+ APIKind["RELOAD_WEB_CLIENT"] = "RELOAD_WEB_CLIENT";
22
+ APIKind["FETCH_TYPES"] = "FETCH_TYPES";
23
+ return APIKind;
24
+ }({});
25
+ var API = class extends require_Action.Message {
26
+ constructor(content, kind) {
27
+ super("API", kind);
28
+ const { code, payload } = content;
29
+ this.code = code;
30
+ this.payload = payload;
31
+ }
32
+ };
33
+
34
+ //#endregion
35
+ //#region src/server/message/API/UpdateSubscriber.ts
36
+ var UpdateSubscriberAPI = class extends API {
37
+ constructor(payload) {
38
+ super({
39
+ code: 0,
40
+ payload
41
+ }, APIKind.UPDATE_SUBSCRIBER);
42
+ }
43
+ };
44
+
45
+ //#endregion
46
+ //#region src/server/message/API/ReloadWebClient.ts
47
+ var ReloadWebClientAPI = class extends API {
48
+ constructor(payload) {
49
+ super({
50
+ code: 0,
51
+ payload
52
+ }, APIKind.RELOAD_WEB_CLIENT);
53
+ }
54
+ };
55
+
56
+ //#endregion
57
+ //#region src/server/message/API/FetchTypes.ts
58
+ var FetchTypesAPI = class extends API {
59
+ constructor(payload) {
60
+ super({
61
+ code: 0,
62
+ payload
63
+ }, APIKind.FETCH_TYPES);
64
+ }
65
+ };
66
+
67
+ //#endregion
68
+ //#region src/server/message/Log/Log.ts
69
+ let LogLevel = /* @__PURE__ */ function(LogLevel) {
70
+ LogLevel["LOG"] = "LOG";
71
+ LogLevel["WARN"] = "WARN";
72
+ LogLevel["ERROR"] = "ERROR";
73
+ return LogLevel;
74
+ }({});
75
+ let LogKind = /* @__PURE__ */ function(LogKind) {
76
+ LogKind["BrokerExitLog"] = "BrokerExitLog";
77
+ LogKind["PublisherRegisteredLog"] = "PublisherRegisteredLog";
78
+ return LogKind;
79
+ }({});
80
+ var Log = class extends require_Action.Message {
81
+ constructor(level, kind, ignoreVerbose = false) {
82
+ super("Log", kind);
83
+ this.ignoreVerbose = false;
84
+ this.level = level;
85
+ this.ignoreVerbose = ignoreVerbose;
86
+ }
87
+ };
88
+
89
+ //#endregion
90
+ //#region src/server/message/Log/BrokerExitLog.ts
91
+ var BrokerExitLog = class extends Log {
92
+ constructor() {
93
+ super(LogLevel.LOG, LogKind.BrokerExitLog);
94
+ }
95
+ };
96
+
97
+ //#endregion
98
+ //#region src/server/utils/log.ts
99
+ const logger = (0, _module_federation_sdk.createLogger)(`[ ${require_Action.MF_SERVER_IDENTIFIER} ]`);
100
+ function fileLog(msg, module, level) {
101
+ if (!process?.env?.["FEDERATION_DEBUG"]) return;
102
+ try {
103
+ const logDir = ".mf";
104
+ const logFile = path.join(logDir, "typesGenerate.log");
105
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
106
+ if (!fs.existsSync(logDir)) fs.mkdirSync(logDir, { recursive: true });
107
+ fs.appendFileSync(logFile, `[${timestamp}] [${level.toUpperCase()}] ${module} - ${msg}\n`);
108
+ } catch {}
109
+ }
110
+ function error(error, action, from) {
111
+ const err = error instanceof Error ? error : /* @__PURE__ */ new Error(`${action} error`);
112
+ fileLog(`[${action}] error: ${err}`, from, "fatal");
113
+ return err.toString();
114
+ }
115
+
116
+ //#endregion
117
+ //#region src/server/utils/getIPV4.ts
118
+ const localIpv4 = "127.0.0.1";
119
+ const getIpv4Interfaces = () => {
120
+ try {
121
+ const interfaces = os.default.networkInterfaces();
122
+ const ipv4Interfaces = [];
123
+ Object.values(interfaces).forEach((detail) => {
124
+ detail?.forEach((detail) => {
125
+ const familyV4Value = typeof detail.family === "string" ? "IPv4" : 4;
126
+ if (detail.family === familyV4Value && detail.address !== localIpv4) ipv4Interfaces.push(detail);
127
+ });
128
+ });
129
+ return ipv4Interfaces;
130
+ } catch (_err) {
131
+ return [];
132
+ }
133
+ };
134
+ const getIPV4 = () => {
135
+ return (getIpv4Interfaces()[0] || { address: localIpv4 }).address;
136
+ };
137
+
138
+ //#endregion
139
+ //#region src/server/utils/index.ts
140
+ function getIdentifier(options) {
141
+ const { ip, name } = options;
142
+ return `mf ${_module_federation_sdk.SEPARATOR}${name}${ip ? `${_module_federation_sdk.SEPARATOR}${ip}` : ""}`;
143
+ }
144
+ function fib(n) {
145
+ let i = 2;
146
+ const res = [
147
+ 0,
148
+ 1,
149
+ 1
150
+ ];
151
+ while (i <= n) {
152
+ res[i] = res[i - 1] + res[i - 2];
153
+ i++;
154
+ }
155
+ return res[n];
156
+ }
157
+ function getFreePort() {
158
+ return new Promise((resolve, reject) => {
159
+ const server = net.default.createServer();
160
+ server.unref();
161
+ server.on("error", reject);
162
+ server.listen(0, () => {
163
+ const { port } = server.address();
164
+ server.close(() => {
165
+ resolve(port);
166
+ });
167
+ });
168
+ });
169
+ }
170
+
171
+ //#endregion
172
+ //#region src/server/Publisher.ts
173
+ var Publisher = class {
174
+ constructor(ctx) {
175
+ this._name = ctx.name;
176
+ this._ip = ctx.ip;
177
+ this._remoteTypeTarPath = ctx.remoteTypeTarPath;
178
+ this._subscribers = /* @__PURE__ */ new Map();
179
+ this._ws = ctx.ws;
180
+ this.dynamicRemoteMap = /* @__PURE__ */ new Map();
181
+ }
182
+ get identifier() {
183
+ return getIdentifier({
184
+ name: this._name,
185
+ ip: this._ip
186
+ });
187
+ }
188
+ get name() {
189
+ return this._name;
190
+ }
191
+ get ip() {
192
+ return this._ip;
193
+ }
194
+ get remoteTypeTarPath() {
195
+ return this._remoteTypeTarPath;
196
+ }
197
+ get hasSubscribes() {
198
+ return Boolean(this._subscribers.size);
199
+ }
200
+ get subscribers() {
201
+ return this._subscribers;
202
+ }
203
+ addSubscriber(identifier, subscriber) {
204
+ fileLog(`${this.name} set subscriber: ${identifier}`, "Publisher", "info");
205
+ this._subscribers.set(identifier, subscriber);
206
+ }
207
+ removeSubscriber(identifier) {
208
+ if (this._subscribers.has(identifier)) {
209
+ fileLog(`${this.name} removeSubscriber: ${identifier}`, "Publisher", "warn");
210
+ this._subscribers.delete(identifier);
211
+ }
212
+ }
213
+ notifySubscriber(subscriberIdentifier, options) {
214
+ const subscriber = this._subscribers.get(subscriberIdentifier);
215
+ if (!subscriber) {
216
+ fileLog(`[notifySubscriber] ${this.name} notifySubscriber: ${subscriberIdentifier}, does not exits`, "Publisher", "error");
217
+ return;
218
+ }
219
+ const api = new UpdateSubscriberAPI(options);
220
+ subscriber.send(JSON.stringify(api));
221
+ fileLog(`[notifySubscriber] ${this.name} notifySubscriber: ${JSON.stringify(subscriberIdentifier)}, message: ${JSON.stringify(api)}`, "Publisher", "info");
222
+ }
223
+ fetchRemoteTypes(options) {
224
+ fileLog(`[fetchRemoteTypes] ${this.name} fetchRemoteTypes, options: ${JSON.stringify(options)}, ws: ${Boolean(this._ws)}`, "Publisher", "info");
225
+ if (!this._ws) return;
226
+ const api = new FetchTypesAPI(options);
227
+ this._ws.send(JSON.stringify(api));
228
+ }
229
+ notifySubscribers(options) {
230
+ const api = new UpdateSubscriberAPI(options);
231
+ this.broadcast(api);
232
+ }
233
+ broadcast(message) {
234
+ if (this.hasSubscribes) this._subscribers.forEach((subscriber, key) => {
235
+ fileLog(`[BroadCast] ${this.name} notifySubscriber: ${key}, PID: ${process.pid}, message: ${JSON.stringify(message)}`, "Publisher", "info");
236
+ subscriber.send(JSON.stringify(message));
237
+ });
238
+ else fileLog(`[BroadCast] ${this.name}'s subscribe is empty`, "Publisher", "warn");
239
+ }
240
+ close() {
241
+ this._ws = void 0;
242
+ this._subscribers.forEach((_subscriber, identifier) => {
243
+ fileLog(`[BroadCast] close ${this.name} remove: ${identifier}`, "Publisher", "warn");
244
+ this.removeSubscriber(identifier);
245
+ });
246
+ }
247
+ };
248
+
249
+ //#endregion
250
+ //#region src/server/message/Action/Update.ts
251
+ let UpdateKind = /* @__PURE__ */ function(UpdateKind) {
252
+ UpdateKind["UPDATE_TYPE"] = "UPDATE_TYPE";
253
+ UpdateKind["RELOAD_PAGE"] = "RELOAD_PAGE";
254
+ return UpdateKind;
255
+ }({});
256
+
257
+ //#endregion
258
+ //#region src/server/broker/Broker.ts
259
+ var Broker = class Broker {
260
+ static {
261
+ this.WEB_SOCKET_CONNECT_MAGIC_ID = require_Action.WEB_SOCKET_CONNECT_MAGIC_ID;
262
+ }
263
+ static {
264
+ this.DEFAULT_WEB_SOCKET_PORT = require_Action.DEFAULT_WEB_SOCKET_PORT;
265
+ }
266
+ static {
267
+ this.DEFAULT_SECURE_WEB_SOCKET_PORT = 16324;
268
+ }
269
+ static {
270
+ this.DEFAULT_WAITING_TIME = 1.5 * 60 * 60 * 1e3;
271
+ }
272
+ constructor() {
273
+ this._publisherMap = /* @__PURE__ */ new Map();
274
+ this._webClientMap = /* @__PURE__ */ new Map();
275
+ this._tmpSubscriberShelter = /* @__PURE__ */ new Map();
276
+ this._scheduleJob = null;
277
+ this._setSchedule();
278
+ this._startWsServer();
279
+ this._stopWhenSIGTERMOrSIGINT();
280
+ this._handleUnexpectedExit();
281
+ }
282
+ get hasPublishers() {
283
+ return Boolean(this._publisherMap.size);
284
+ }
285
+ async _startWsServer() {
286
+ const wsHandler = (ws, req) => {
287
+ const { url: reqUrl = "" } = req;
288
+ const { query } = (0, url.parse)(reqUrl, true);
289
+ const { WEB_SOCKET_CONNECT_MAGIC_ID } = query;
290
+ if (WEB_SOCKET_CONNECT_MAGIC_ID === Broker.WEB_SOCKET_CONNECT_MAGIC_ID) {
291
+ ws.on("message", (message) => {
292
+ try {
293
+ const text = message.toString();
294
+ const action = JSON.parse(text);
295
+ fileLog(`${action?.kind} action received `, "Broker", "info");
296
+ this._takeAction(action, ws);
297
+ } catch (error) {
298
+ fileLog(`parse action message error: ${error}`, "Broker", "error");
299
+ }
300
+ });
301
+ ws.on("error", (e) => {
302
+ fileLog(`parse action message error: ${e}`, "Broker", "error");
303
+ });
304
+ } else {
305
+ ws.send("Invalid CONNECT ID.");
306
+ fileLog("Invalid CONNECT ID.", "Broker", "warn");
307
+ ws.close();
308
+ }
309
+ };
310
+ const server = (0, http.createServer)();
311
+ this._webSocketServer = new isomorphic_ws.default.Server({ noServer: true });
312
+ this._webSocketServer.on("error", (err) => {
313
+ fileLog(`ws error: \n${err.message}\n ${err.stack}`, "Broker", "error");
314
+ });
315
+ this._webSocketServer.on("listening", () => {
316
+ fileLog(`WebSocket server is listening on port ${Broker.DEFAULT_WEB_SOCKET_PORT}`, "Broker", "info");
317
+ });
318
+ this._webSocketServer.on("connection", wsHandler);
319
+ this._webSocketServer.on("close", (code) => {
320
+ fileLog(`WebSocket Server Close with Code ${code}`, "Broker", "warn");
321
+ this._webSocketServer && this._webSocketServer.close();
322
+ this._webSocketServer = void 0;
323
+ });
324
+ server.on("upgrade", (req, socket, head) => {
325
+ if (req.url) {
326
+ const { pathname } = (0, url.parse)(req.url);
327
+ if (pathname === "/") this._webSocketServer?.handleUpgrade(req, socket, head, (ws) => {
328
+ this._webSocketServer?.emit("connection", ws, req);
329
+ });
330
+ }
331
+ });
332
+ server.listen(Broker.DEFAULT_WEB_SOCKET_PORT);
333
+ }
334
+ async _takeAction(action, client) {
335
+ const { kind, payload } = action;
336
+ if (kind === require_Action.ActionKind.ADD_PUBLISHER) await this._addPublisher(payload, client);
337
+ if (kind === require_Action.ActionKind.UPDATE_PUBLISHER) await this._updatePublisher(payload, client);
338
+ if (kind === require_Action.ActionKind.ADD_SUBSCRIBER) await this._addSubscriber(payload, client);
339
+ if (kind === require_Action.ActionKind.EXIT_SUBSCRIBER) await this._removeSubscriber(payload, client);
340
+ if (kind === require_Action.ActionKind.EXIT_PUBLISHER) await this._removePublisher(payload, client);
341
+ if (kind === require_Action.ActionKind.ADD_WEB_CLIENT) await this._addWebClient(payload, client);
342
+ if (kind === require_Action.ActionKind.NOTIFY_WEB_CLIENT) await this._notifyWebClient(payload, client);
343
+ if (kind === require_Action.ActionKind.FETCH_TYPES) await this._fetchTypes(payload, client);
344
+ if (kind === require_Action.ActionKind.ADD_DYNAMIC_REMOTE) this._addDynamicRemote(payload);
345
+ }
346
+ async _addPublisher(context, client) {
347
+ const { name, ip, remoteTypeTarPath } = context ?? {};
348
+ const identifier = getIdentifier({
349
+ name,
350
+ ip
351
+ });
352
+ if (this._publisherMap.has(identifier)) {
353
+ fileLog(`[${require_Action.ActionKind.ADD_PUBLISHER}] ${identifier} has been added, this action will be ignored`, "Broker", "warn");
354
+ return;
355
+ }
356
+ try {
357
+ const publisher = new Publisher({
358
+ name,
359
+ ip,
360
+ remoteTypeTarPath,
361
+ ws: client
362
+ });
363
+ this._publisherMap.set(identifier, publisher);
364
+ fileLog(`[${require_Action.ActionKind.ADD_PUBLISHER}] ${identifier} Adding Publisher Succeed`, "Broker", "info");
365
+ const tmpSubScribers = this._getTmpSubScribers(identifier);
366
+ if (tmpSubScribers) {
367
+ fileLog(`[${require_Action.ActionKind.ADD_PUBLISHER}] consumeTmpSubscriber set ${publisher.name}’s subscribers `, "Broker", "info");
368
+ this._consumeTmpSubScribers(publisher, tmpSubScribers);
369
+ this._clearTmpSubScriberRelation(identifier);
370
+ }
371
+ } catch (err) {
372
+ const msg = error(err, require_Action.ActionKind.ADD_PUBLISHER, "Broker");
373
+ client.send(msg);
374
+ client.close();
375
+ }
376
+ }
377
+ async _updatePublisher(context, client) {
378
+ const { name, updateMode, updateKind, updateSourcePaths, remoteTypeTarPath, ip } = context ?? {};
379
+ const identifier = getIdentifier({
380
+ name,
381
+ ip
382
+ });
383
+ if (!this._publisherMap.has(identifier)) {
384
+ fileLog(`[${require_Action.ActionKind.UPDATE_PUBLISHER}] ${identifier} has not been started, this action will be ignored
385
+ this._publisherMap: ${JSON.stringify(this._publisherMap.entries())}
386
+ `, "Broker", "warn");
387
+ return;
388
+ }
389
+ try {
390
+ const publisher = this._publisherMap.get(identifier);
391
+ fileLog(`[${require_Action.ActionKind.UPDATE_PUBLISHER}] ${identifier} update, and notify subscribers to update`, "Broker", "info");
392
+ if (publisher) {
393
+ publisher.notifySubscribers({
394
+ remoteTypeTarPath,
395
+ name,
396
+ updateMode,
397
+ updateKind,
398
+ updateSourcePaths: updateSourcePaths || []
399
+ });
400
+ this._publisherMap.forEach((p) => {
401
+ if (p.name === publisher.name) return;
402
+ const dynamicRemoteInfo = p.dynamicRemoteMap.get(identifier);
403
+ if (dynamicRemoteInfo) {
404
+ fileLog(`dynamicRemoteInfo: ${JSON.stringify(dynamicRemoteInfo)}, identifier:${identifier} publish: ${p.name}`, "Broker", "info");
405
+ p.fetchRemoteTypes({
406
+ remoteInfo: dynamicRemoteInfo,
407
+ once: false
408
+ });
409
+ }
410
+ });
411
+ }
412
+ } catch (err) {
413
+ const msg = error(err, require_Action.ActionKind.UPDATE_PUBLISHER, "Broker");
414
+ client.send(msg);
415
+ client.close();
416
+ }
417
+ }
418
+ async _fetchTypes(context, _client) {
419
+ const { name, ip, remoteInfo } = context ?? {};
420
+ const identifier = getIdentifier({
421
+ name,
422
+ ip
423
+ });
424
+ try {
425
+ const publisher = this._publisherMap.get(identifier);
426
+ fileLog(`[${require_Action.ActionKind.FETCH_TYPES}] ${identifier} fetch types`, "Broker", "info");
427
+ if (publisher) publisher.fetchRemoteTypes({
428
+ remoteInfo,
429
+ once: true
430
+ });
431
+ } catch (err) {
432
+ fileLog(`[${require_Action.ActionKind.FETCH_TYPES}] ${identifier} fetch types fail , error info: ${err}`, "Broker", "error");
433
+ }
434
+ }
435
+ _addDynamicRemote(context) {
436
+ const { name, ip, remoteInfo, remoteIp } = context ?? {};
437
+ const identifier = getIdentifier({
438
+ name,
439
+ ip
440
+ });
441
+ const publisher = this._publisherMap.get(identifier);
442
+ const remoteId = getIdentifier({
443
+ name: remoteInfo.name,
444
+ ip: remoteIp
445
+ });
446
+ fileLog(`[${require_Action.ActionKind.ADD_DYNAMIC_REMOTE}] identifier:${identifier},publisher: ${publisher.name}, remoteId:${remoteId}`, "Broker", "error");
447
+ if (!publisher || publisher.dynamicRemoteMap.has(remoteId)) return;
448
+ publisher.dynamicRemoteMap.set(remoteId, remoteInfo);
449
+ }
450
+ async _addSubscriber(context, client) {
451
+ const { publishers, name: subscriberName } = context ?? {};
452
+ publishers.forEach((publisher) => {
453
+ const { name, ip } = publisher;
454
+ const identifier = getIdentifier({
455
+ name,
456
+ ip
457
+ });
458
+ if (!this._publisherMap.has(identifier)) {
459
+ fileLog(`[${require_Action.ActionKind.ADD_SUBSCRIBER}]: ${identifier} has not been started, ${subscriberName} will add the relation to tmp shelter`, "Broker", "warn");
460
+ this._addTmpSubScriberRelation({
461
+ name: getIdentifier({
462
+ name: context.name,
463
+ ip: context.ip
464
+ }),
465
+ client
466
+ }, publisher);
467
+ return;
468
+ }
469
+ try {
470
+ const registeredPublisher = this._publisherMap.get(identifier);
471
+ if (registeredPublisher) {
472
+ registeredPublisher.addSubscriber(getIdentifier({
473
+ name: subscriberName,
474
+ ip: context.ip
475
+ }), client);
476
+ fileLog(`[${require_Action.ActionKind.ADD_SUBSCRIBER}]: ${identifier} has been started, Adding Subscriber ${subscriberName} Succeed, this.__publisherMap are: ${JSON.stringify(Array.from(this._publisherMap.entries()))}`, "Broker", "info");
477
+ registeredPublisher.notifySubscriber(getIdentifier({
478
+ name: subscriberName,
479
+ ip: context.ip
480
+ }), {
481
+ updateKind: UpdateKind.UPDATE_TYPE,
482
+ updateMode: require_Action.UpdateMode.PASSIVE,
483
+ updateSourcePaths: [registeredPublisher.name],
484
+ remoteTypeTarPath: registeredPublisher.remoteTypeTarPath,
485
+ name: registeredPublisher.name
486
+ });
487
+ fileLog(`[${require_Action.ActionKind.ADD_SUBSCRIBER}]: notifySubscriber Subscriber ${subscriberName}, updateMode: "PASSIVE", updateSourcePaths: ${registeredPublisher.name}`, "Broker", "info");
488
+ }
489
+ } catch (err) {
490
+ const msg = error(err, require_Action.ActionKind.ADD_SUBSCRIBER, "Broker");
491
+ client.send(msg);
492
+ client.close();
493
+ }
494
+ });
495
+ }
496
+ async _removeSubscriber(context, client) {
497
+ const { publishers } = context ?? {};
498
+ const subscriberIdentifier = getIdentifier({
499
+ name: context?.name,
500
+ ip: context?.ip
501
+ });
502
+ publishers.forEach((publisher) => {
503
+ const { name, ip } = publisher;
504
+ const identifier = getIdentifier({
505
+ name,
506
+ ip
507
+ });
508
+ const registeredPublisher = this._publisherMap.get(identifier);
509
+ if (!registeredPublisher) {
510
+ fileLog(`[${require_Action.ActionKind.EXIT_SUBSCRIBER}], ${identifier} does not exit `, "Broker", "warn");
511
+ return;
512
+ }
513
+ try {
514
+ fileLog(`[${require_Action.ActionKind.EXIT_SUBSCRIBER}], ${identifier} will exit `, "Broker", "INFO");
515
+ registeredPublisher.removeSubscriber(subscriberIdentifier);
516
+ this._clearTmpSubScriberRelation(identifier);
517
+ if (!registeredPublisher.hasSubscribes) this._publisherMap.delete(identifier);
518
+ if (!this.hasPublishers) this.exit();
519
+ } catch (err) {
520
+ const msg = error(err, require_Action.ActionKind.EXIT_SUBSCRIBER, "Broker");
521
+ client.send(msg);
522
+ client.close();
523
+ }
524
+ });
525
+ }
526
+ async _removePublisher(context, client) {
527
+ const { name, ip } = context ?? {};
528
+ const identifier = getIdentifier({
529
+ name,
530
+ ip
531
+ });
532
+ const publisher = this._publisherMap.get(identifier);
533
+ if (!publisher) {
534
+ fileLog(`[${require_Action.ActionKind.EXIT_PUBLISHER}]: ${identifier}} has not been added, this action will be ingored`, "Broker", "warn");
535
+ return;
536
+ }
537
+ try {
538
+ const { subscribers } = publisher;
539
+ subscribers.forEach((subscriber, subscriberIdentifier) => {
540
+ this._addTmpSubScriberRelation({
541
+ name: subscriberIdentifier,
542
+ client: subscriber
543
+ }, {
544
+ name: publisher.name,
545
+ ip: publisher.ip
546
+ });
547
+ fileLog(`[${require_Action.ActionKind.EXIT_PUBLISHER}]: ${identifier} is removing , subscriber: ${subscriberIdentifier} will be add tmpSubScriberRelation`, "Broker", "info");
548
+ });
549
+ this._publisherMap.delete(identifier);
550
+ fileLog(`[${require_Action.ActionKind.EXIT_PUBLISHER}]: ${identifier} is removed `, "Broker", "info");
551
+ if (!this.hasPublishers) {
552
+ fileLog(`[${require_Action.ActionKind.EXIT_PUBLISHER}]: _publisherMap is empty, all server will exit `, "Broker", "warn");
553
+ this.exit();
554
+ }
555
+ } catch (err) {
556
+ const msg = error(err, require_Action.ActionKind.EXIT_PUBLISHER, "Broker");
557
+ client.send(msg);
558
+ client.close();
559
+ }
560
+ }
561
+ async _addWebClient(context, client) {
562
+ const { name } = context ?? {};
563
+ const identifier = getIdentifier({ name });
564
+ if (this._webClientMap.has(identifier)) fileLog(`${identifier}} has been added, this action will override prev WebClient`, "Broker", "warn");
565
+ try {
566
+ this._webClientMap.set(identifier, client);
567
+ fileLog(`${identifier} adding WebClient Succeed`, "Broker", "info");
568
+ } catch (err) {
569
+ const msg = error(err, require_Action.ActionKind.ADD_WEB_CLIENT, "Broker");
570
+ client.send(msg);
571
+ client.close();
572
+ }
573
+ }
574
+ async _notifyWebClient(context, client) {
575
+ const { name, updateMode } = context ?? {};
576
+ const identifier = getIdentifier({ name });
577
+ const webClient = this._webClientMap.get(identifier);
578
+ if (!webClient) {
579
+ fileLog(`[${require_Action.ActionKind.NOTIFY_WEB_CLIENT}] ${identifier} has not been added, this action will be ignored`, "Broker", "warn");
580
+ return;
581
+ }
582
+ try {
583
+ const api = new ReloadWebClientAPI({
584
+ name,
585
+ updateMode
586
+ });
587
+ webClient.send(JSON.stringify(api));
588
+ fileLog(`[${require_Action.ActionKind.NOTIFY_WEB_CLIENT}] Notify ${name} WebClient Succeed`, "Broker", "info");
589
+ } catch (err) {
590
+ const msg = error(err, require_Action.ActionKind.NOTIFY_WEB_CLIENT, "Broker");
591
+ client.send(msg);
592
+ client.close();
593
+ }
594
+ }
595
+ _addTmpSubScriberRelation(subscriber, publisher) {
596
+ const publisherIdentifier = getIdentifier({
597
+ name: publisher.name,
598
+ ip: publisher.ip
599
+ });
600
+ const subscriberIdentifier = subscriber.name;
601
+ const shelter = this._tmpSubscriberShelter.get(publisherIdentifier);
602
+ if (!shelter) {
603
+ const map = /* @__PURE__ */ new Map();
604
+ map.set(subscriberIdentifier, subscriber);
605
+ this._tmpSubscriberShelter.set(publisherIdentifier, {
606
+ subscribers: map,
607
+ timestamp: Date.now()
608
+ });
609
+ fileLog(`[AddTmpSubscriberRelation] ${publisherIdentifier}'s subscriber has ${subscriberIdentifier} `, "Broker", "info");
610
+ return;
611
+ }
612
+ if (shelter.subscribers.get(subscriberIdentifier)) {
613
+ fileLog(`[AddTmpSubscriberRelation] ${publisherIdentifier} and ${subscriberIdentifier} relation has been added`, "Broker", "warn");
614
+ shelter.subscribers.set(subscriberIdentifier, subscriber);
615
+ shelter.timestamp = Date.now();
616
+ } else {
617
+ fileLog(`AddTmpSubscriberLog ${publisherIdentifier}'s shelter has been added, update shelter.subscribers ${subscriberIdentifier}`, "Broker", "warn");
618
+ shelter.subscribers.set(subscriberIdentifier, subscriber);
619
+ }
620
+ }
621
+ _getTmpSubScribers(publisherIdentifier) {
622
+ return this._tmpSubscriberShelter.get(publisherIdentifier)?.subscribers;
623
+ }
624
+ _consumeTmpSubScribers(publisher, tmpSubScribers) {
625
+ tmpSubScribers.forEach((tmpSubScriber, identifier) => {
626
+ fileLog(`notifyTmpSubScribers ${publisher.name} will be add a subscriber: ${identifier} `, "Broker", "warn");
627
+ publisher.addSubscriber(identifier, tmpSubScriber.client);
628
+ publisher.notifySubscriber(identifier, {
629
+ updateKind: UpdateKind.UPDATE_TYPE,
630
+ updateMode: require_Action.UpdateMode.PASSIVE,
631
+ updateSourcePaths: [publisher.name],
632
+ remoteTypeTarPath: publisher.remoteTypeTarPath,
633
+ name: publisher.name
634
+ });
635
+ });
636
+ }
637
+ _clearTmpSubScriberRelation(identifier) {
638
+ this._tmpSubscriberShelter.delete(identifier);
639
+ }
640
+ _clearTmpSubScriberRelations() {
641
+ this._tmpSubscriberShelter.clear();
642
+ }
643
+ _disconnect() {
644
+ this._publisherMap.forEach((publisher) => {
645
+ publisher.close();
646
+ });
647
+ }
648
+ _setSchedule() {
649
+ const rule = new node_schedule.default.RecurrenceRule();
650
+ if (Number(process.env["FEDERATION_SERVER_TEST"])) {
651
+ const interval = Number(process.env["FEDERATION_SERVER_TEST"]) / 1e3;
652
+ const second = [];
653
+ for (let i = 0; i < 60; i = i + interval) second.push(i);
654
+ rule.second = second;
655
+ } else {
656
+ rule.second = 0;
657
+ rule.hour = [
658
+ 0,
659
+ 3,
660
+ 6,
661
+ 9,
662
+ 12,
663
+ 15,
664
+ 18
665
+ ];
666
+ rule.minute = 0;
667
+ }
668
+ const serverTest = Number(process.env["FEDERATION_SERVER_TEST"]);
669
+ this._scheduleJob = node_schedule.default.scheduleJob(rule, () => {
670
+ this._tmpSubscriberShelter.forEach((tmpSubscriber, identifier) => {
671
+ fileLog(` _clearTmpSubScriberRelation ${identifier}, ${Date.now() - tmpSubscriber.timestamp >= (process.env["GARFISH_MODULE_SERVER_TEST"] ? serverTest : Broker.DEFAULT_WAITING_TIME)}`, "Broker", "info");
672
+ if (Date.now() - tmpSubscriber.timestamp >= (process.env["FEDERATION_SERVER_TEST"] ? serverTest : Broker.DEFAULT_WAITING_TIME)) this._clearTmpSubScriberRelation(identifier);
673
+ });
674
+ });
675
+ }
676
+ _clearSchedule() {
677
+ if (!this._scheduleJob) return;
678
+ this._scheduleJob.cancel();
679
+ this._scheduleJob = null;
680
+ }
681
+ _stopWhenSIGTERMOrSIGINT() {
682
+ process.on("SIGTERM", () => {
683
+ this.exit();
684
+ });
685
+ process.on("SIGINT", () => {
686
+ this.exit();
687
+ });
688
+ }
689
+ _handleUnexpectedExit() {
690
+ process.on("unhandledRejection", (error) => {
691
+ console.error("Unhandled Rejection Error: ", error);
692
+ fileLog(`Unhandled Rejection Error: ${error}`, "Broker", "fatal");
693
+ process.exit(1);
694
+ });
695
+ process.on("uncaughtException", (error) => {
696
+ console.error("Unhandled Exception Error: ", error);
697
+ fileLog(`Unhandled Rejection Error: ${error}`, "Broker", "fatal");
698
+ process.exit(1);
699
+ });
700
+ }
701
+ async start() {}
702
+ exit() {
703
+ const brokerExitLog = new BrokerExitLog();
704
+ this.broadcast(JSON.stringify(brokerExitLog));
705
+ this._disconnect();
706
+ this._clearSchedule();
707
+ this._clearTmpSubScriberRelations();
708
+ this._webSocketServer && this._webSocketServer.close();
709
+ this._secureWebSocketServer && this._secureWebSocketServer.close();
710
+ process.exit(0);
711
+ }
712
+ broadcast(message) {
713
+ fileLog(`[broadcast] exit info : ${JSON.stringify(message)}`, "Broker", "warn");
714
+ this._webSocketServer?.clients.forEach((client) => {
715
+ client.send(JSON.stringify(message));
716
+ });
717
+ this._secureWebSocketServer?.clients.forEach((client) => {
718
+ client.send(JSON.stringify(message));
719
+ });
720
+ }
721
+ };
722
+
723
+ //#endregion
724
+ Object.defineProperty(exports, 'APIKind', {
725
+ enumerable: true,
726
+ get: function () {
727
+ return APIKind;
728
+ }
729
+ });
730
+ Object.defineProperty(exports, 'Broker', {
731
+ enumerable: true,
732
+ get: function () {
733
+ return Broker;
734
+ }
735
+ });
736
+ Object.defineProperty(exports, 'LogKind', {
737
+ enumerable: true,
738
+ get: function () {
739
+ return LogKind;
740
+ }
741
+ });
742
+ Object.defineProperty(exports, 'UpdateKind', {
743
+ enumerable: true,
744
+ get: function () {
745
+ return UpdateKind;
746
+ }
747
+ });
748
+ Object.defineProperty(exports, 'fib', {
749
+ enumerable: true,
750
+ get: function () {
751
+ return fib;
752
+ }
753
+ });
754
+ Object.defineProperty(exports, 'fileLog', {
755
+ enumerable: true,
756
+ get: function () {
757
+ return fileLog;
758
+ }
759
+ });
760
+ Object.defineProperty(exports, 'getFreePort', {
761
+ enumerable: true,
762
+ get: function () {
763
+ return getFreePort;
764
+ }
765
+ });
766
+ Object.defineProperty(exports, 'getIPV4', {
767
+ enumerable: true,
768
+ get: function () {
769
+ return getIPV4;
770
+ }
771
+ });
772
+ Object.defineProperty(exports, 'getIdentifier', {
773
+ enumerable: true,
774
+ get: function () {
775
+ return getIdentifier;
776
+ }
777
+ });
778
+ Object.defineProperty(exports, 'logger', {
779
+ enumerable: true,
780
+ get: function () {
781
+ return logger;
782
+ }
783
+ });