@module-federation/dts-plugin 0.0.0-perf-devtools-20260107043700 → 0.0.0-perf-website-code-usage-20260914033703

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