@module-federation/dts-plugin 2.0.0 → 2.1.0

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