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