@module-federation/dts-plugin 0.1.19 → 0.1.20

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 (35) hide show
  1. package/dist/CHANGELOG.md +13 -0
  2. package/dist/{DtsWorker-d731dc2b.d.ts → DtsWorker-7113d2b0.d.ts} +6 -3
  3. package/dist/core.d.mts +85 -0
  4. package/dist/core.d.ts +5 -5
  5. package/dist/core.js +1055 -993
  6. package/dist/dynamic-remote-type-hints-plugin.d.mts +5 -0
  7. package/dist/dynamic-remote-type-hints-plugin.d.ts +5 -0
  8. package/dist/dynamic-remote-type-hints-plugin.js +198 -0
  9. package/dist/esm/chunk-AJO6KMSF.js +2337 -0
  10. package/dist/esm/chunk-G7ONFBMA.js +24 -0
  11. package/dist/esm/chunk-MQRIERJP.js +236 -0
  12. package/dist/esm/core.js +44 -0
  13. package/dist/esm/dynamic-remote-type-hints-plugin.js +73 -0
  14. package/dist/esm/fork-dev-worker.js +141 -0
  15. package/dist/esm/fork-generate-dts.js +26 -0
  16. package/dist/esm/index.js +406 -0
  17. package/dist/esm/start-broker.js +36 -0
  18. package/dist/fork-dev-worker.d.ts +15 -0
  19. package/dist/fork-dev-worker.js +2506 -0
  20. package/dist/{forkGenerateDts.d.ts → fork-generate-dts.d.mts} +1 -1
  21. package/dist/fork-generate-dts.d.ts +9 -0
  22. package/dist/fork-generate-dts.js +1865 -0
  23. package/dist/iife/launch-web-client.js +91 -42
  24. package/dist/index.d.mts +10 -0
  25. package/dist/index.js +1242 -1171
  26. package/dist/package.json +11 -2
  27. package/dist/{startBroker.d.ts → start-broker.d.mts} +2 -0
  28. package/dist/start-broker.d.ts +42 -0
  29. package/dist/start-broker.js +1276 -0
  30. package/package.json +14 -5
  31. package/dist/forkDevWorker.js +0 -2523
  32. package/dist/forkGenerateDts.js +0 -1618
  33. package/dist/launch-web-client.d.ts +0 -2
  34. package/dist/startBroker.js +0 -902
  35. /package/dist/{forkDevWorker.d.ts → fork-dev-worker.d.mts} +0 -0
@@ -0,0 +1,1276 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __spreadValues = (a, b) => {
13
+ for (var prop in b || (b = {}))
14
+ if (__hasOwnProp.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ if (__getOwnPropSymbols)
17
+ for (var prop of __getOwnPropSymbols(b)) {
18
+ if (__propIsEnum.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
20
+ }
21
+ return a;
22
+ };
23
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
25
+ var __export = (target, all) => {
26
+ for (var name in all)
27
+ __defProp(target, name, { get: all[name], enumerable: true });
28
+ };
29
+ var __copyProps = (to, from, except, desc) => {
30
+ if (from && typeof from === "object" || typeof from === "function") {
31
+ for (let key of __getOwnPropNames(from))
32
+ if (!__hasOwnProp.call(to, key) && key !== except)
33
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
34
+ }
35
+ return to;
36
+ };
37
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
38
+ // If the importer is in node compatibility mode or this is not an ESM
39
+ // file that has been converted to a CommonJS file using a Babel-
40
+ // compatible transform (i.e. "__esModule" has not been set), then set
41
+ // "default" to the CommonJS "module.exports" for node compatibility.
42
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
43
+ mod
44
+ ));
45
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
46
+ var __publicField = (obj, key, value) => {
47
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
48
+ return value;
49
+ };
50
+ var __async = (__this, __arguments, generator) => {
51
+ return new Promise((resolve, reject) => {
52
+ var fulfilled = (value) => {
53
+ try {
54
+ step(generator.next(value));
55
+ } catch (e) {
56
+ reject(e);
57
+ }
58
+ };
59
+ var rejected = (value) => {
60
+ try {
61
+ step(generator.throw(value));
62
+ } catch (e) {
63
+ reject(e);
64
+ }
65
+ };
66
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
67
+ step((generator = generator.apply(__this, __arguments)).next());
68
+ });
69
+ };
70
+
71
+ // packages/dts-plugin/src/server/broker/startBroker.ts
72
+ var startBroker_exports = {};
73
+ __export(startBroker_exports, {
74
+ getBroker: () => getBroker
75
+ });
76
+ module.exports = __toCommonJS(startBroker_exports);
77
+
78
+ // packages/dts-plugin/src/server/broker/Broker.ts
79
+ var import_http = require("http");
80
+
81
+ // packages/dts-plugin/src/core/configurations/remotePlugin.ts
82
+ var import_managers2 = require("@module-federation/managers");
83
+ var import_typescript2 = __toESM(require("typescript"));
84
+
85
+ // packages/dts-plugin/src/core/lib/DTSManager.ts
86
+ var import_ansi_colors2 = __toESM(require("ansi-colors"));
87
+ var import_sdk4 = require("@module-federation/sdk");
88
+ var import_lodash = __toESM(require("lodash.clonedeepwith"));
89
+ var import_third_party_dts_extractor2 = require("@module-federation/third-party-dts-extractor");
90
+
91
+ // packages/dts-plugin/src/core/lib/archiveHandler.ts
92
+ var import_adm_zip = __toESM(require("adm-zip"));
93
+ var import_axios = __toESM(require("axios"));
94
+
95
+ // packages/dts-plugin/src/core/lib/typeScriptCompiler.ts
96
+ var import_ansi_colors = __toESM(require("ansi-colors"));
97
+ var import_typescript = __toESM(require("typescript"));
98
+ var import_third_party_dts_extractor = require("@module-federation/third-party-dts-extractor");
99
+
100
+ // packages/dts-plugin/src/server/message/Message.ts
101
+ var _Message = class _Message {
102
+ constructor(type, kind) {
103
+ __publicField(this, "type");
104
+ __publicField(this, "kind");
105
+ __publicField(this, "time");
106
+ this.type = type;
107
+ this.kind = kind;
108
+ this.time = Date.now();
109
+ }
110
+ };
111
+ __name(_Message, "Message");
112
+ var Message = _Message;
113
+
114
+ // packages/dts-plugin/src/server/message/API/API.ts
115
+ var APIKind;
116
+ (function(APIKind2) {
117
+ APIKind2["UPDATE_SUBSCRIBER"] = "UPDATE_SUBSCRIBER";
118
+ APIKind2["RELOAD_WEB_CLIENT"] = "RELOAD_WEB_CLIENT";
119
+ APIKind2["FETCH_TYPES"] = "FETCH_TYPES";
120
+ })(APIKind || (APIKind = {}));
121
+ var _API = class _API extends Message {
122
+ constructor(content, kind) {
123
+ super("API", kind);
124
+ __publicField(this, "code");
125
+ __publicField(this, "payload");
126
+ const { code, payload } = content;
127
+ this.code = code;
128
+ this.payload = payload;
129
+ }
130
+ };
131
+ __name(_API, "API");
132
+ var API = _API;
133
+
134
+ // packages/dts-plugin/src/server/message/API/UpdateSubscriber.ts
135
+ var _UpdateSubscriberAPI = class _UpdateSubscriberAPI extends API {
136
+ constructor(payload) {
137
+ super({
138
+ code: 0,
139
+ payload
140
+ }, APIKind.UPDATE_SUBSCRIBER);
141
+ }
142
+ };
143
+ __name(_UpdateSubscriberAPI, "UpdateSubscriberAPI");
144
+ var UpdateSubscriberAPI = _UpdateSubscriberAPI;
145
+
146
+ // packages/dts-plugin/src/server/message/API/ReloadWebClient.ts
147
+ var _ReloadWebClientAPI = class _ReloadWebClientAPI extends API {
148
+ constructor(payload) {
149
+ super({
150
+ code: 0,
151
+ payload
152
+ }, APIKind.RELOAD_WEB_CLIENT);
153
+ }
154
+ };
155
+ __name(_ReloadWebClientAPI, "ReloadWebClientAPI");
156
+ var ReloadWebClientAPI = _ReloadWebClientAPI;
157
+
158
+ // packages/dts-plugin/src/server/message/API/FetchTypes.ts
159
+ var _FetchTypesAPI = class _FetchTypesAPI extends API {
160
+ constructor(payload) {
161
+ super({
162
+ code: 0,
163
+ payload
164
+ }, APIKind.FETCH_TYPES);
165
+ }
166
+ };
167
+ __name(_FetchTypesAPI, "FetchTypesAPI");
168
+ var FetchTypesAPI = _FetchTypesAPI;
169
+
170
+ // packages/dts-plugin/src/server/utils/index.ts
171
+ var import_sdk2 = require("@module-federation/sdk");
172
+
173
+ // packages/dts-plugin/src/server/utils/logTransform.ts
174
+ var import_chalk = __toESM(require("chalk"));
175
+
176
+ // packages/dts-plugin/src/server/message/Log/Log.ts
177
+ var LogLevel;
178
+ (function(LogLevel2) {
179
+ LogLevel2["LOG"] = "LOG";
180
+ LogLevel2["WARN"] = "WARN";
181
+ LogLevel2["ERROR"] = "ERROR";
182
+ })(LogLevel || (LogLevel = {}));
183
+ var LogKind;
184
+ (function(LogKind2) {
185
+ LogKind2["BrokerExitLog"] = "BrokerExitLog";
186
+ LogKind2["PublisherRegisteredLog"] = "PublisherRegisteredLog";
187
+ })(LogKind || (LogKind = {}));
188
+ var _Log = class _Log extends Message {
189
+ constructor(level, kind, ignoreVerbose = false) {
190
+ super("Log", kind);
191
+ __publicField(this, "level");
192
+ __publicField(this, "ignoreVerbose", false);
193
+ this.level = level;
194
+ this.ignoreVerbose = ignoreVerbose;
195
+ }
196
+ };
197
+ __name(_Log, "Log");
198
+ var Log = _Log;
199
+
200
+ // packages/dts-plugin/src/server/message/Log/BrokerExitLog.ts
201
+ var _BrokerExitLog = class _BrokerExitLog extends Log {
202
+ constructor() {
203
+ super(LogLevel.LOG, LogKind.BrokerExitLog);
204
+ }
205
+ };
206
+ __name(_BrokerExitLog, "BrokerExitLog");
207
+ var BrokerExitLog = _BrokerExitLog;
208
+
209
+ // packages/dts-plugin/src/server/utils/log.ts
210
+ var import_sdk = require("@module-federation/sdk");
211
+ var log4js = __toESM(require("log4js"));
212
+ var import_chalk2 = __toESM(require("chalk"));
213
+
214
+ // packages/dts-plugin/src/server/constant.ts
215
+ var DEFAULT_WEB_SOCKET_PORT = 16322;
216
+ var WEB_SOCKET_CONNECT_MAGIC_ID = "1hpzW-zo2z-o8io-gfmV1-2cb1d82";
217
+
218
+ // packages/dts-plugin/src/server/utils/log.ts
219
+ function fileLog(msg, module2, level) {
220
+ var _a2, _b;
221
+ if (!((_a2 = process == null ? void 0 : process.env) == null ? void 0 : _a2["FEDERATION_DEBUG"])) {
222
+ return;
223
+ }
224
+ log4js.configure({
225
+ appenders: {
226
+ [module2]: {
227
+ type: "file",
228
+ filename: ".mf/typesGenerate.log"
229
+ },
230
+ default: {
231
+ type: "file",
232
+ filename: ".mf/typesGenerate.log"
233
+ }
234
+ },
235
+ categories: {
236
+ [module2]: {
237
+ appenders: [
238
+ module2
239
+ ],
240
+ level: "error"
241
+ },
242
+ default: {
243
+ appenders: [
244
+ "default"
245
+ ],
246
+ level: "trace"
247
+ }
248
+ }
249
+ });
250
+ const logger4 = log4js.getLogger(module2);
251
+ logger4.level = "debug";
252
+ (_b = logger4[level]) == null ? void 0 : _b.call(logger4, msg);
253
+ }
254
+ __name(fileLog, "fileLog");
255
+ function error(error2, action, from) {
256
+ const err = error2 instanceof Error ? error2 : new Error(`${action} error`);
257
+ fileLog(`[${action}] error: ${err}`, from, "fatal");
258
+ return err.toString();
259
+ }
260
+ __name(error, "error");
261
+
262
+ // packages/dts-plugin/src/server/utils/index.ts
263
+ function getIdentifier(options) {
264
+ const { ip, name } = options;
265
+ return `mf ${import_sdk2.SEPARATOR}${name}${ip ? `${import_sdk2.SEPARATOR}${ip}` : ""}`;
266
+ }
267
+ __name(getIdentifier, "getIdentifier");
268
+
269
+ // packages/dts-plugin/src/server/Publisher.ts
270
+ var _Publisher = class _Publisher {
271
+ constructor(ctx) {
272
+ __publicField(this, "_ip");
273
+ __publicField(this, "_name");
274
+ __publicField(this, "_remoteTypeTarPath");
275
+ __publicField(this, "_subscribers");
276
+ __publicField(this, "_ws");
277
+ __publicField(this, "dynamicRemoteMap");
278
+ this._name = ctx.name;
279
+ this._ip = ctx.ip;
280
+ this._remoteTypeTarPath = ctx.remoteTypeTarPath;
281
+ this._subscribers = /* @__PURE__ */ new Map();
282
+ this._ws = ctx.ws;
283
+ this.dynamicRemoteMap = /* @__PURE__ */ new Map();
284
+ }
285
+ get identifier() {
286
+ return getIdentifier({
287
+ name: this._name,
288
+ ip: this._ip
289
+ });
290
+ }
291
+ get name() {
292
+ return this._name;
293
+ }
294
+ get ip() {
295
+ return this._ip;
296
+ }
297
+ get remoteTypeTarPath() {
298
+ return this._remoteTypeTarPath;
299
+ }
300
+ get hasSubscribes() {
301
+ return Boolean(this._subscribers.size);
302
+ }
303
+ get subscribers() {
304
+ return this._subscribers;
305
+ }
306
+ addSubscriber(identifier, subscriber) {
307
+ fileLog(`${this.name} set subscriber: ${identifier}`, "Publisher", "info");
308
+ this._subscribers.set(identifier, subscriber);
309
+ }
310
+ removeSubscriber(identifier) {
311
+ if (this._subscribers.has(identifier)) {
312
+ fileLog(`${this.name} removeSubscriber: ${identifier}`, "Publisher", "warn");
313
+ this._subscribers.delete(identifier);
314
+ }
315
+ }
316
+ notifySubscriber(subscriberIdentifier, options) {
317
+ const subscriber = this._subscribers.get(subscriberIdentifier);
318
+ if (!subscriber) {
319
+ fileLog(`[notifySubscriber] ${this.name} notifySubscriber: ${subscriberIdentifier}, does not exits`, "Publisher", "error");
320
+ return;
321
+ }
322
+ const api = new UpdateSubscriberAPI(options);
323
+ subscriber.send(JSON.stringify(api));
324
+ fileLog(`[notifySubscriber] ${this.name} notifySubscriber: ${JSON.stringify(subscriberIdentifier)}, message: ${JSON.stringify(api)}`, "Publisher", "info");
325
+ }
326
+ fetchRemoteTypes(options) {
327
+ fileLog(`[fetchRemoteTypes] ${this.name} fetchRemoteTypes, options: ${JSON.stringify(options)}, ws: ${Boolean(this._ws)}`, "Publisher", "info");
328
+ if (!this._ws) {
329
+ return;
330
+ }
331
+ const api = new FetchTypesAPI(options);
332
+ this._ws.send(JSON.stringify(api));
333
+ }
334
+ notifySubscribers(options) {
335
+ const api = new UpdateSubscriberAPI(options);
336
+ this.broadcast(api);
337
+ }
338
+ broadcast(message) {
339
+ if (this.hasSubscribes) {
340
+ this._subscribers.forEach((subscriber, key) => {
341
+ fileLog(`[BroadCast] ${this.name} notifySubscriber: ${key}, PID: ${process.pid}, message: ${JSON.stringify(message)}`, "Publisher", "info");
342
+ subscriber.send(JSON.stringify(message));
343
+ });
344
+ } else {
345
+ fileLog(`[BroadCast] ${this.name}'s subscribe is empty`, "Publisher", "warn");
346
+ }
347
+ }
348
+ close() {
349
+ this._ws = void 0;
350
+ this._subscribers.forEach((_subscriber, identifier) => {
351
+ fileLog(`[BroadCast] close ${this.name} remove: ${identifier}`, "Publisher", "warn");
352
+ this.removeSubscriber(identifier);
353
+ });
354
+ }
355
+ };
356
+ __name(_Publisher, "Publisher");
357
+ var Publisher = _Publisher;
358
+
359
+ // packages/dts-plugin/src/server/DevServer.ts
360
+ var import_isomorphic_ws = __toESM(require("isomorphic-ws"));
361
+
362
+ // packages/dts-plugin/src/server/message/Action/Action.ts
363
+ var ActionKind;
364
+ (function(ActionKind2) {
365
+ ActionKind2["ADD_SUBSCRIBER"] = "ADD_SUBSCRIBER";
366
+ ActionKind2["EXIT_SUBSCRIBER"] = "EXIT_SUBSCRIBER";
367
+ ActionKind2["ADD_PUBLISHER"] = "ADD_PUBLISHER";
368
+ ActionKind2["UPDATE_PUBLISHER"] = "UPDATE_PUBLISHER";
369
+ ActionKind2["NOTIFY_SUBSCRIBER"] = "NOTIFY_SUBSCRIBER";
370
+ ActionKind2["EXIT_PUBLISHER"] = "EXIT_PUBLISHER";
371
+ ActionKind2["ADD_WEB_CLIENT"] = "ADD_WEB_CLIENT";
372
+ ActionKind2["NOTIFY_WEB_CLIENT"] = "NOTIFY_WEB_CLIENT";
373
+ ActionKind2["FETCH_TYPES"] = "FETCH_TYPES";
374
+ ActionKind2["ADD_DYNAMIC_REMOTE"] = "ADD_DYNAMIC_REMOTE";
375
+ })(ActionKind || (ActionKind = {}));
376
+
377
+ // packages/dts-plugin/src/server/message/Action/Update.ts
378
+ var UpdateKind;
379
+ (function(UpdateKind2) {
380
+ UpdateKind2["UPDATE_TYPE"] = "UPDATE_TYPE";
381
+ UpdateKind2["RELOAD_PAGE"] = "RELOAD_PAGE";
382
+ })(UpdateKind || (UpdateKind = {}));
383
+
384
+ // packages/dts-plugin/src/core/constant.ts
385
+ var UpdateMode;
386
+ (function(UpdateMode2) {
387
+ UpdateMode2["POSITIVE"] = "POSITIVE";
388
+ UpdateMode2["PASSIVE"] = "PASSIVE";
389
+ })(UpdateMode || (UpdateMode = {}));
390
+
391
+ // packages/dts-plugin/src/server/createKoaServer.ts
392
+ var import_fs_extra = __toESM(require("fs-extra"));
393
+ var import_koa = __toESM(require("koa"));
394
+
395
+ // packages/dts-plugin/src/core/configurations/hostPlugin.ts
396
+ var import_sdk3 = require("@module-federation/sdk");
397
+ var import_managers = require("@module-federation/managers");
398
+ var defaultOptions = {
399
+ typesFolder: "@mf-types",
400
+ remoteTypesFolder: "@mf-types",
401
+ deleteTypesFolder: true,
402
+ maxRetries: 3,
403
+ implementation: "",
404
+ context: process.cwd(),
405
+ abortOnError: true,
406
+ consumeAPITypes: false
407
+ };
408
+
409
+ // packages/dts-plugin/src/core/lib/DTSManager.ts
410
+ var import_axios2 = __toESM(require("axios"));
411
+
412
+ // packages/dts-plugin/src/core/lib/utils.ts
413
+ var import_ansi_colors3 = __toESM(require("ansi-colors"));
414
+
415
+ // packages/dts-plugin/src/core/configurations/remotePlugin.ts
416
+ var defaultOptions2 = {
417
+ tsConfigPath: "./tsconfig.json",
418
+ typesFolder: "@mf-types",
419
+ compiledTypesFolder: "compiled-types",
420
+ hostRemoteTypesFolder: "@mf-types",
421
+ deleteTypesFolder: true,
422
+ additionalFilesToCompile: [],
423
+ compilerInstance: "tsc",
424
+ compileInChildProcess: false,
425
+ implementation: "",
426
+ generateAPITypes: false,
427
+ context: process.cwd(),
428
+ abortOnError: true,
429
+ extractRemoteTypes: false,
430
+ extractThirdParty: false
431
+ };
432
+
433
+ // packages/dts-plugin/src/core/lib/DtsWorker.ts
434
+ var import_lodash2 = __toESM(require("lodash.clonedeepwith"));
435
+
436
+ // packages/dts-plugin/src/core/rpc/index.ts
437
+ var rpc_exports = {};
438
+ __export(rpc_exports, {
439
+ RpcExitError: () => RpcExitError,
440
+ RpcGMCallTypes: () => RpcGMCallTypes,
441
+ createRpcWorker: () => createRpcWorker,
442
+ exposeRpc: () => exposeRpc,
443
+ getRpcWorkerData: () => getRpcWorkerData,
444
+ wrapRpc: () => wrapRpc
445
+ });
446
+
447
+ // packages/dts-plugin/src/core/rpc/expose-rpc.ts
448
+ var import_process = __toESM(require("process"));
449
+
450
+ // packages/dts-plugin/src/core/rpc/types.ts
451
+ var RpcGMCallTypes;
452
+ (function(RpcGMCallTypes2) {
453
+ RpcGMCallTypes2["CALL"] = "mf_call";
454
+ RpcGMCallTypes2["RESOLVE"] = "mf_resolve";
455
+ RpcGMCallTypes2["REJECT"] = "mf_reject";
456
+ RpcGMCallTypes2["EXIT"] = "mf_exit";
457
+ })(RpcGMCallTypes || (RpcGMCallTypes = {}));
458
+
459
+ // packages/dts-plugin/src/core/rpc/expose-rpc.ts
460
+ function exposeRpc(fn) {
461
+ const sendMessage = /* @__PURE__ */ __name((message) => new Promise((resolve, reject) => {
462
+ if (!import_process.default.send) {
463
+ reject(new Error(`Process ${import_process.default.pid} doesn't have IPC channels`));
464
+ } else if (!import_process.default.connected) {
465
+ reject(new Error(`Process ${import_process.default.pid} doesn't have open IPC channels`));
466
+ } else {
467
+ import_process.default.send(message, void 0, void 0, (error2) => {
468
+ if (error2) {
469
+ reject(error2);
470
+ } else {
471
+ resolve(void 0);
472
+ }
473
+ });
474
+ }
475
+ }), "sendMessage");
476
+ const handleMessage = /* @__PURE__ */ __name((message) => __async(this, null, function* () {
477
+ if (message.type === RpcGMCallTypes.CALL) {
478
+ if (!import_process.default.send) {
479
+ return;
480
+ }
481
+ let value, error2;
482
+ try {
483
+ value = yield fn(...message.args);
484
+ } catch (fnError) {
485
+ error2 = fnError;
486
+ }
487
+ try {
488
+ if (error2) {
489
+ yield sendMessage({
490
+ type: RpcGMCallTypes.REJECT,
491
+ id: message.id,
492
+ error: error2
493
+ });
494
+ } else {
495
+ yield sendMessage({
496
+ type: RpcGMCallTypes.RESOLVE,
497
+ id: message.id,
498
+ value
499
+ });
500
+ }
501
+ } catch (sendError) {
502
+ if (error2) {
503
+ if (error2 instanceof Error) {
504
+ console.error(error2);
505
+ }
506
+ }
507
+ console.error(sendError);
508
+ }
509
+ }
510
+ }), "handleMessage");
511
+ import_process.default.on("message", handleMessage);
512
+ }
513
+ __name(exposeRpc, "exposeRpc");
514
+
515
+ // packages/dts-plugin/src/core/rpc/rpc-error.ts
516
+ var _a;
517
+ var RpcExitError = (_a = class extends Error {
518
+ constructor(message, code, signal) {
519
+ super(message);
520
+ __publicField(this, "code");
521
+ __publicField(this, "signal");
522
+ this.code = code;
523
+ this.signal = signal;
524
+ this.name = "RpcExitError";
525
+ }
526
+ }, __name(_a, "RpcExitError"), _a);
527
+
528
+ // packages/dts-plugin/src/core/rpc/wrap-rpc.ts
529
+ function createControlledPromise() {
530
+ let resolve = /* @__PURE__ */ __name(() => void 0, "resolve");
531
+ let reject = /* @__PURE__ */ __name(() => void 0, "reject");
532
+ const promise = new Promise((aResolve, aReject) => {
533
+ resolve = aResolve;
534
+ reject = aReject;
535
+ });
536
+ return {
537
+ promise,
538
+ resolve,
539
+ reject
540
+ };
541
+ }
542
+ __name(createControlledPromise, "createControlledPromise");
543
+ function wrapRpc(childProcess, options) {
544
+ return (...args) => __async(this, null, function* () {
545
+ if (!childProcess.send) {
546
+ throw new Error(`Process ${childProcess.pid} doesn't have IPC channels`);
547
+ } else if (!childProcess.connected) {
548
+ throw new Error(`Process ${childProcess.pid} doesn't have open IPC channels`);
549
+ }
550
+ const { id, once } = options;
551
+ const { promise: resultPromise, resolve: resolveResult, reject: rejectResult } = createControlledPromise();
552
+ const { promise: sendPromise, resolve: resolveSend, reject: rejectSend } = createControlledPromise();
553
+ const handleMessage = /* @__PURE__ */ __name((message) => {
554
+ if ((message == null ? void 0 : message.id) === id) {
555
+ if (message.type === RpcGMCallTypes.RESOLVE) {
556
+ resolveResult(message.value);
557
+ } else if (message.type === RpcGMCallTypes.REJECT) {
558
+ rejectResult(message.error);
559
+ }
560
+ }
561
+ if (once && (childProcess == null ? void 0 : childProcess.kill)) {
562
+ childProcess.kill("SIGTERM");
563
+ }
564
+ }, "handleMessage");
565
+ const handleClose = /* @__PURE__ */ __name((code, signal) => {
566
+ rejectResult(new RpcExitError(code ? `Process ${childProcess.pid} exited with code ${code}${signal ? ` [${signal}]` : ""}` : `Process ${childProcess.pid} exited${signal ? ` [${signal}]` : ""}`, code, signal));
567
+ removeHandlers();
568
+ }, "handleClose");
569
+ const removeHandlers = /* @__PURE__ */ __name(() => {
570
+ childProcess.off("message", handleMessage);
571
+ childProcess.off("close", handleClose);
572
+ }, "removeHandlers");
573
+ if (once) {
574
+ childProcess.once("message", handleMessage);
575
+ } else {
576
+ childProcess.on("message", handleMessage);
577
+ }
578
+ childProcess.on("close", handleClose);
579
+ childProcess.send({
580
+ type: RpcGMCallTypes.CALL,
581
+ id,
582
+ args
583
+ }, (error2) => {
584
+ if (error2) {
585
+ rejectSend(error2);
586
+ removeHandlers();
587
+ } else {
588
+ resolveSend(void 0);
589
+ }
590
+ });
591
+ return sendPromise.then(() => resultPromise);
592
+ });
593
+ }
594
+ __name(wrapRpc, "wrapRpc");
595
+
596
+ // packages/dts-plugin/src/core/rpc/rpc-worker.ts
597
+ var child_process = __toESM(require("child_process"));
598
+ var process3 = __toESM(require("process"));
599
+ var import_crypto = require("crypto");
600
+ var FEDERATION_WORKER_DATA_ENV_KEY = "VMOK_WORKER_DATA_ENV";
601
+ function createRpcWorker(modulePath, data, memoryLimit, once) {
602
+ const options = {
603
+ env: __spreadProps(__spreadValues({}, process3.env), {
604
+ [FEDERATION_WORKER_DATA_ENV_KEY]: JSON.stringify(data || {})
605
+ }),
606
+ stdio: [
607
+ "inherit",
608
+ "inherit",
609
+ "inherit",
610
+ "ipc"
611
+ ],
612
+ serialization: "advanced"
613
+ };
614
+ if (memoryLimit) {
615
+ options.execArgv = [
616
+ `--max-old-space-size=${memoryLimit}`
617
+ ];
618
+ }
619
+ let childProcess, remoteMethod;
620
+ const id = (0, import_crypto.randomUUID)();
621
+ const worker = {
622
+ connect(...args) {
623
+ if (childProcess && !childProcess.connected) {
624
+ childProcess.send({
625
+ type: RpcGMCallTypes.EXIT,
626
+ id
627
+ });
628
+ childProcess = void 0;
629
+ remoteMethod = void 0;
630
+ }
631
+ if (!(childProcess == null ? void 0 : childProcess.connected)) {
632
+ childProcess = child_process.fork(modulePath, options);
633
+ remoteMethod = wrapRpc(childProcess, {
634
+ id,
635
+ once
636
+ });
637
+ }
638
+ if (!remoteMethod) {
639
+ return Promise.reject(new Error("Worker is not connected - cannot perform RPC."));
640
+ }
641
+ return remoteMethod(...args);
642
+ },
643
+ terminate() {
644
+ var _a2;
645
+ (_a2 = childProcess == null ? void 0 : childProcess.send) == null ? void 0 : _a2.call(childProcess, {
646
+ type: RpcGMCallTypes.EXIT,
647
+ id
648
+ });
649
+ childProcess = void 0;
650
+ remoteMethod = void 0;
651
+ },
652
+ get connected() {
653
+ return Boolean(childProcess == null ? void 0 : childProcess.connected);
654
+ },
655
+ get process() {
656
+ return childProcess;
657
+ },
658
+ get id() {
659
+ return id;
660
+ }
661
+ };
662
+ return worker;
663
+ }
664
+ __name(createRpcWorker, "createRpcWorker");
665
+ function getRpcWorkerData() {
666
+ return JSON.parse(process3.env[FEDERATION_WORKER_DATA_ENV_KEY] || "{}");
667
+ }
668
+ __name(getRpcWorkerData, "getRpcWorkerData");
669
+
670
+ // packages/dts-plugin/src/server/broker/Broker.ts
671
+ var import_isomorphic_ws2 = __toESM(require("isomorphic-ws"));
672
+ var import_node_schedule = __toESM(require("node-schedule"));
673
+ var import_url = require("url");
674
+ var _Broker = class _Broker {
675
+ constructor() {
676
+ __publicField(this, "_publisherMap", /* @__PURE__ */ new Map());
677
+ __publicField(this, "_webClientMap", /* @__PURE__ */ new Map());
678
+ __publicField(this, "_webSocketServer");
679
+ __publicField(this, "_secureWebSocketServer");
680
+ __publicField(this, "_tmpSubscriberShelter", /* @__PURE__ */ new Map());
681
+ __publicField(this, "_scheduleJob", null);
682
+ this._setSchedule();
683
+ this._startWsServer();
684
+ this._stopWhenSIGTERMOrSIGINT();
685
+ this._handleUnexpectedExit();
686
+ }
687
+ get hasPublishers() {
688
+ return Boolean(this._publisherMap.size);
689
+ }
690
+ _startWsServer() {
691
+ return __async(this, null, function* () {
692
+ const wsHandler = /* @__PURE__ */ __name((ws, req) => {
693
+ const { url: reqUrl = "" } = req;
694
+ const { query } = (0, import_url.parse)(reqUrl, true);
695
+ const { WEB_SOCKET_CONNECT_MAGIC_ID: WEB_SOCKET_CONNECT_MAGIC_ID2 } = query;
696
+ if (WEB_SOCKET_CONNECT_MAGIC_ID2 === _Broker.WEB_SOCKET_CONNECT_MAGIC_ID) {
697
+ ws.on("message", (message) => {
698
+ try {
699
+ const text = message.toString();
700
+ const action = JSON.parse(text);
701
+ fileLog(`${action == null ? void 0 : action.kind} action received `, "Broker", "info");
702
+ this._takeAction(action, ws);
703
+ } catch (error2) {
704
+ fileLog(`parse action message error: ${error2}`, "Broker", "error");
705
+ }
706
+ });
707
+ ws.on("error", (e) => {
708
+ fileLog(`parse action message error: ${e}`, "Broker", "error");
709
+ });
710
+ } else {
711
+ ws.send("Invalid CONNECT ID.");
712
+ fileLog("Invalid CONNECT ID.", "Broker", "warn");
713
+ ws.close();
714
+ }
715
+ }, "wsHandler");
716
+ const server = (0, import_http.createServer)();
717
+ this._webSocketServer = new import_isomorphic_ws2.default.Server({
718
+ noServer: true
719
+ });
720
+ this._webSocketServer.on("error", (err) => {
721
+ fileLog(`ws error:
722
+ ${err.message}
723
+ ${err.stack}`, "Broker", "error");
724
+ });
725
+ this._webSocketServer.on("listening", () => {
726
+ fileLog(`WebSocket server is listening on port ${_Broker.DEFAULT_WEB_SOCKET_PORT}`, "Broker", "info");
727
+ });
728
+ this._webSocketServer.on("connection", wsHandler);
729
+ this._webSocketServer.on("close", (code) => {
730
+ fileLog(`WebSocket Server Close with Code ${code}`, "Broker", "warn");
731
+ this._webSocketServer && this._webSocketServer.close();
732
+ this._webSocketServer = void 0;
733
+ });
734
+ server.on("upgrade", (req, socket, head) => {
735
+ var _a2;
736
+ if (req.url) {
737
+ const { pathname } = (0, import_url.parse)(req.url);
738
+ if (pathname === "/") {
739
+ (_a2 = this._webSocketServer) == null ? void 0 : _a2.handleUpgrade(req, socket, head, (ws) => {
740
+ var _a3;
741
+ (_a3 = this._webSocketServer) == null ? void 0 : _a3.emit("connection", ws, req);
742
+ });
743
+ }
744
+ }
745
+ });
746
+ server.listen(_Broker.DEFAULT_WEB_SOCKET_PORT);
747
+ });
748
+ }
749
+ _takeAction(action, client) {
750
+ return __async(this, null, function* () {
751
+ const { kind, payload } = action;
752
+ if (kind === ActionKind.ADD_PUBLISHER) {
753
+ yield this._addPublisher(payload, client);
754
+ }
755
+ if (kind === ActionKind.UPDATE_PUBLISHER) {
756
+ yield this._updatePublisher(payload, client);
757
+ }
758
+ if (kind === ActionKind.ADD_SUBSCRIBER) {
759
+ yield this._addSubscriber(payload, client);
760
+ }
761
+ if (kind === ActionKind.EXIT_SUBSCRIBER) {
762
+ yield this._removeSubscriber(payload, client);
763
+ }
764
+ if (kind === ActionKind.EXIT_PUBLISHER) {
765
+ yield this._removePublisher(payload, client);
766
+ }
767
+ if (kind === ActionKind.ADD_WEB_CLIENT) {
768
+ yield this._addWebClient(payload, client);
769
+ }
770
+ if (kind === ActionKind.NOTIFY_WEB_CLIENT) {
771
+ yield this._notifyWebClient(payload, client);
772
+ }
773
+ if (kind === ActionKind.FETCH_TYPES) {
774
+ yield this._fetchTypes(payload, client);
775
+ }
776
+ if (kind === ActionKind.ADD_DYNAMIC_REMOTE) {
777
+ this._addDynamicRemote(payload);
778
+ }
779
+ });
780
+ }
781
+ _addPublisher(context, client) {
782
+ return __async(this, null, function* () {
783
+ const { name, ip, remoteTypeTarPath } = context != null ? context : {};
784
+ const identifier = getIdentifier({
785
+ name,
786
+ ip
787
+ });
788
+ if (this._publisherMap.has(identifier)) {
789
+ fileLog(`[${ActionKind.ADD_PUBLISHER}] ${identifier} has been added, this action will be ignored`, "Broker", "warn");
790
+ return;
791
+ }
792
+ try {
793
+ const publisher = new Publisher({
794
+ name,
795
+ ip,
796
+ remoteTypeTarPath,
797
+ ws: client
798
+ });
799
+ this._publisherMap.set(identifier, publisher);
800
+ fileLog(`[${ActionKind.ADD_PUBLISHER}] ${identifier} Adding Publisher Succeed`, "Broker", "info");
801
+ const tmpSubScribers = this._getTmpSubScribers(identifier);
802
+ if (tmpSubScribers) {
803
+ fileLog(`[${ActionKind.ADD_PUBLISHER}] consumeTmpSubscriber set ${publisher.name}\u2019s subscribers `, "Broker", "info");
804
+ this._consumeTmpSubScribers(publisher, tmpSubScribers);
805
+ this._clearTmpSubScriberRelation(identifier);
806
+ }
807
+ } catch (err) {
808
+ const msg = error(err, ActionKind.ADD_PUBLISHER, "Broker");
809
+ client.send(msg);
810
+ client.close();
811
+ }
812
+ });
813
+ }
814
+ _updatePublisher(context, client) {
815
+ return __async(this, null, function* () {
816
+ const { name, updateMode, updateKind, updateSourcePaths, remoteTypeTarPath, ip } = context != null ? context : {};
817
+ const identifier = getIdentifier({
818
+ name,
819
+ ip
820
+ });
821
+ if (!this._publisherMap.has(identifier)) {
822
+ fileLog(`[${ActionKind.UPDATE_PUBLISHER}] ${identifier} has not been started, this action will be ignored
823
+ this._publisherMap: ${JSON.stringify(this._publisherMap.entries())}
824
+ `, "Broker", "warn");
825
+ return;
826
+ }
827
+ try {
828
+ const publisher = this._publisherMap.get(identifier);
829
+ fileLog(
830
+ // eslint-disable-next-line max-len
831
+ `[${ActionKind.UPDATE_PUBLISHER}] ${identifier} update, and notify subscribers to update`,
832
+ "Broker",
833
+ "info"
834
+ );
835
+ if (publisher) {
836
+ publisher.notifySubscribers({
837
+ remoteTypeTarPath,
838
+ name,
839
+ updateMode,
840
+ updateKind,
841
+ updateSourcePaths: updateSourcePaths || []
842
+ });
843
+ this._publisherMap.forEach((p) => {
844
+ if (p.name === publisher.name) {
845
+ return;
846
+ }
847
+ const dynamicRemoteInfo = p.dynamicRemoteMap.get(identifier);
848
+ if (dynamicRemoteInfo) {
849
+ fileLog(
850
+ // eslint-disable-next-line max-len
851
+ `dynamicRemoteInfo: ${JSON.stringify(dynamicRemoteInfo)}, identifier:${identifier} publish: ${p.name}`,
852
+ "Broker",
853
+ "info"
854
+ );
855
+ p.fetchRemoteTypes({
856
+ remoteInfo: dynamicRemoteInfo,
857
+ once: false
858
+ });
859
+ }
860
+ });
861
+ }
862
+ } catch (err) {
863
+ const msg = error(err, ActionKind.UPDATE_PUBLISHER, "Broker");
864
+ client.send(msg);
865
+ client.close();
866
+ }
867
+ });
868
+ }
869
+ _fetchTypes(context, _client) {
870
+ return __async(this, null, function* () {
871
+ const { name, ip, remoteInfo } = context != null ? context : {};
872
+ const identifier = getIdentifier({
873
+ name,
874
+ ip
875
+ });
876
+ try {
877
+ const publisher = this._publisherMap.get(identifier);
878
+ fileLog(`[${ActionKind.FETCH_TYPES}] ${identifier} fetch types`, "Broker", "info");
879
+ if (publisher) {
880
+ publisher.fetchRemoteTypes({
881
+ remoteInfo,
882
+ once: true
883
+ });
884
+ }
885
+ } catch (err) {
886
+ fileLog(`[${ActionKind.FETCH_TYPES}] ${identifier} fetch types fail , error info: ${err}`, "Broker", "error");
887
+ }
888
+ });
889
+ }
890
+ _addDynamicRemote(context) {
891
+ const { name, ip, remoteInfo, remoteIp } = context != null ? context : {};
892
+ const identifier = getIdentifier({
893
+ name,
894
+ ip
895
+ });
896
+ const publisher = this._publisherMap.get(identifier);
897
+ const remoteId = getIdentifier({
898
+ name: remoteInfo.name,
899
+ ip: remoteIp
900
+ });
901
+ fileLog(`[${ActionKind.ADD_DYNAMIC_REMOTE}] identifier:${identifier},publisher: ${publisher.name}, remoteId:${remoteId}`, "Broker", "error");
902
+ if (!publisher || publisher.dynamicRemoteMap.has(remoteId)) {
903
+ return;
904
+ }
905
+ publisher.dynamicRemoteMap.set(remoteId, remoteInfo);
906
+ }
907
+ // app1 consumes provider1,provider2. Dependencies at this time: publishers: [provider1, provider2], subscriberName: app1
908
+ // provider1 is app1's remote
909
+ _addSubscriber(context, client) {
910
+ return __async(this, null, function* () {
911
+ const { publishers, name: subscriberName } = context != null ? context : {};
912
+ publishers.forEach((publisher) => {
913
+ const { name, ip } = publisher;
914
+ const identifier = getIdentifier({
915
+ name,
916
+ ip
917
+ });
918
+ if (!this._publisherMap.has(identifier)) {
919
+ fileLog(`[${ActionKind.ADD_SUBSCRIBER}]: ${identifier} has not been started, ${subscriberName} will add the relation to tmp shelter`, "Broker", "warn");
920
+ this._addTmpSubScriberRelation({
921
+ name: getIdentifier({
922
+ name: context.name,
923
+ ip: context.ip
924
+ }),
925
+ client
926
+ }, publisher);
927
+ return;
928
+ }
929
+ try {
930
+ const registeredPublisher = this._publisherMap.get(identifier);
931
+ if (registeredPublisher) {
932
+ registeredPublisher.addSubscriber(getIdentifier({
933
+ name: subscriberName,
934
+ ip: context.ip
935
+ }), client);
936
+ fileLog(
937
+ // eslint-disable-next-line @ies/eden/max-calls-in-template
938
+ `[${ActionKind.ADD_SUBSCRIBER}]: ${identifier} has been started, Adding Subscriber ${subscriberName} Succeed, this.__publisherMap are: ${JSON.stringify(Array.from(this._publisherMap.entries()))}`,
939
+ "Broker",
940
+ "info"
941
+ );
942
+ registeredPublisher.notifySubscriber(getIdentifier({
943
+ name: subscriberName,
944
+ ip: context.ip
945
+ }), {
946
+ updateKind: UpdateKind.UPDATE_TYPE,
947
+ updateMode: UpdateMode.PASSIVE,
948
+ updateSourcePaths: [
949
+ registeredPublisher.name
950
+ ],
951
+ remoteTypeTarPath: registeredPublisher.remoteTypeTarPath,
952
+ name: registeredPublisher.name
953
+ });
954
+ fileLog(
955
+ // eslint-disable-next-line @ies/eden/max-calls-in-template
956
+ `[${ActionKind.ADD_SUBSCRIBER}]: notifySubscriber Subscriber ${subscriberName}, updateMode: "PASSIVE", updateSourcePaths: ${registeredPublisher.name}`,
957
+ "Broker",
958
+ "info"
959
+ );
960
+ }
961
+ } catch (err) {
962
+ const msg = error(err, ActionKind.ADD_SUBSCRIBER, "Broker");
963
+ client.send(msg);
964
+ client.close();
965
+ }
966
+ });
967
+ });
968
+ }
969
+ // Trigger while consumer exit
970
+ _removeSubscriber(context, client) {
971
+ return __async(this, null, function* () {
972
+ const { publishers } = context != null ? context : {};
973
+ const subscriberIdentifier = getIdentifier({
974
+ name: context == null ? void 0 : context.name,
975
+ ip: context == null ? void 0 : context.ip
976
+ });
977
+ publishers.forEach((publisher) => {
978
+ const { name, ip } = publisher;
979
+ const identifier = getIdentifier({
980
+ name,
981
+ ip
982
+ });
983
+ const registeredPublisher = this._publisherMap.get(identifier);
984
+ if (!registeredPublisher) {
985
+ fileLog(`[${ActionKind.EXIT_SUBSCRIBER}], ${identifier} does not exit `, "Broker", "warn");
986
+ return;
987
+ }
988
+ try {
989
+ fileLog(`[${ActionKind.EXIT_SUBSCRIBER}], ${identifier} will exit `, "Broker", "INFO");
990
+ registeredPublisher.removeSubscriber(subscriberIdentifier);
991
+ this._clearTmpSubScriberRelation(identifier);
992
+ if (!registeredPublisher.hasSubscribes) {
993
+ this._publisherMap.delete(identifier);
994
+ }
995
+ if (!this.hasPublishers) {
996
+ this.exit();
997
+ }
998
+ } catch (err) {
999
+ const msg = error(err, ActionKind.EXIT_SUBSCRIBER, "Broker");
1000
+ client.send(msg);
1001
+ client.close();
1002
+ }
1003
+ });
1004
+ });
1005
+ }
1006
+ _removePublisher(context, client) {
1007
+ return __async(this, null, function* () {
1008
+ const { name, ip } = context != null ? context : {};
1009
+ const identifier = getIdentifier({
1010
+ name,
1011
+ ip
1012
+ });
1013
+ const publisher = this._publisherMap.get(identifier);
1014
+ if (!publisher) {
1015
+ fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier}} has not been added, this action will be ingored`, "Broker", "warn");
1016
+ return;
1017
+ }
1018
+ try {
1019
+ const { subscribers } = publisher;
1020
+ subscribers.forEach((subscriber, subscriberIdentifier) => {
1021
+ this._addTmpSubScriberRelation({
1022
+ name: subscriberIdentifier,
1023
+ client: subscriber
1024
+ }, {
1025
+ name: publisher.name,
1026
+ ip: publisher.ip
1027
+ });
1028
+ fileLog(
1029
+ // eslint-disable-next-line max-len
1030
+ `[${ActionKind.EXIT_PUBLISHER}]: ${identifier} is removing , subscriber: ${subscriberIdentifier} will be add tmpSubScriberRelation`,
1031
+ "Broker",
1032
+ "info"
1033
+ );
1034
+ });
1035
+ this._publisherMap.delete(identifier);
1036
+ fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier} is removed `, "Broker", "info");
1037
+ if (!this.hasPublishers) {
1038
+ fileLog(`[${ActionKind.EXIT_PUBLISHER}]: _publisherMap is empty, all server will exit `, "Broker", "warn");
1039
+ this.exit();
1040
+ }
1041
+ } catch (err) {
1042
+ const msg = error(err, ActionKind.EXIT_PUBLISHER, "Broker");
1043
+ client.send(msg);
1044
+ client.close();
1045
+ }
1046
+ });
1047
+ }
1048
+ _addWebClient(context, client) {
1049
+ return __async(this, null, function* () {
1050
+ const { name } = context != null ? context : {};
1051
+ const identifier = getIdentifier({
1052
+ name
1053
+ });
1054
+ if (this._webClientMap.has(identifier)) {
1055
+ fileLog(`${identifier}} has been added, this action will override prev WebClient`, "Broker", "warn");
1056
+ }
1057
+ try {
1058
+ this._webClientMap.set(identifier, client);
1059
+ fileLog(`${identifier} adding WebClient Succeed`, "Broker", "info");
1060
+ } catch (err) {
1061
+ const msg = error(err, ActionKind.ADD_WEB_CLIENT, "Broker");
1062
+ client.send(msg);
1063
+ client.close();
1064
+ }
1065
+ });
1066
+ }
1067
+ _notifyWebClient(context, client) {
1068
+ return __async(this, null, function* () {
1069
+ const { name, updateMode } = context != null ? context : {};
1070
+ const identifier = getIdentifier({
1071
+ name
1072
+ });
1073
+ const webClient = this._webClientMap.get(identifier);
1074
+ if (!webClient) {
1075
+ fileLog(`[${ActionKind.NOTIFY_WEB_CLIENT}] ${identifier} has not been added, this action will be ignored`, "Broker", "warn");
1076
+ return;
1077
+ }
1078
+ try {
1079
+ const api = new ReloadWebClientAPI({
1080
+ name,
1081
+ updateMode
1082
+ });
1083
+ webClient.send(JSON.stringify(api));
1084
+ fileLog(`[${ActionKind.NOTIFY_WEB_CLIENT}] Notify ${name} WebClient Succeed`, "Broker", "info");
1085
+ } catch (err) {
1086
+ const msg = error(err, ActionKind.NOTIFY_WEB_CLIENT, "Broker");
1087
+ client.send(msg);
1088
+ client.close();
1089
+ }
1090
+ });
1091
+ }
1092
+ // app1 consumes provider1, and provider1 not launch. this._tmpSubscriberShelter at this time: {provider1: Map{subscribers: Map{app1: app1+ip+client'}, timestamp: 'xx'} }
1093
+ _addTmpSubScriberRelation(subscriber, publisher) {
1094
+ const publisherIdentifier = getIdentifier({
1095
+ name: publisher.name,
1096
+ ip: publisher.ip
1097
+ });
1098
+ const subscriberIdentifier = subscriber.name;
1099
+ const shelter = this._tmpSubscriberShelter.get(publisherIdentifier);
1100
+ if (!shelter) {
1101
+ const map = /* @__PURE__ */ new Map();
1102
+ map.set(subscriberIdentifier, subscriber);
1103
+ this._tmpSubscriberShelter.set(publisherIdentifier, {
1104
+ subscribers: map,
1105
+ timestamp: Date.now()
1106
+ });
1107
+ fileLog(`[AddTmpSubscriberRelation] ${publisherIdentifier}'s subscriber has ${subscriberIdentifier} `, "Broker", "info");
1108
+ return;
1109
+ }
1110
+ const tmpSubScriberShelterSubscriber = shelter.subscribers.get(subscriberIdentifier);
1111
+ if (tmpSubScriberShelterSubscriber) {
1112
+ fileLog(`[AddTmpSubscriberRelation] ${publisherIdentifier} and ${subscriberIdentifier} relation has been added`, "Broker", "warn");
1113
+ shelter.subscribers.set(subscriberIdentifier, subscriber);
1114
+ shelter.timestamp = Date.now();
1115
+ } else {
1116
+ fileLog(
1117
+ // eslint-disable-next-line max-len
1118
+ `AddTmpSubscriberLog ${publisherIdentifier}'s shelter has been added, update shelter.subscribers ${subscriberIdentifier}`,
1119
+ "Broker",
1120
+ "warn"
1121
+ );
1122
+ shelter.subscribers.set(subscriberIdentifier, subscriber);
1123
+ }
1124
+ }
1125
+ _getTmpSubScribers(publisherIdentifier) {
1126
+ var _a2;
1127
+ return (_a2 = this._tmpSubscriberShelter.get(publisherIdentifier)) == null ? void 0 : _a2.subscribers;
1128
+ }
1129
+ // after adding publisher, it will change the temp subscriber to regular subscriber
1130
+ _consumeTmpSubScribers(publisher, tmpSubScribers) {
1131
+ tmpSubScribers.forEach((tmpSubScriber, identifier) => {
1132
+ fileLog(`notifyTmpSubScribers ${publisher.name} will be add a subscriber: ${identifier} `, "Broker", "warn");
1133
+ publisher.addSubscriber(identifier, tmpSubScriber.client);
1134
+ publisher.notifySubscriber(identifier, {
1135
+ updateKind: UpdateKind.UPDATE_TYPE,
1136
+ updateMode: UpdateMode.PASSIVE,
1137
+ updateSourcePaths: [
1138
+ publisher.name
1139
+ ],
1140
+ remoteTypeTarPath: publisher.remoteTypeTarPath,
1141
+ name: publisher.name
1142
+ });
1143
+ });
1144
+ }
1145
+ _clearTmpSubScriberRelation(identifier) {
1146
+ this._tmpSubscriberShelter.delete(identifier);
1147
+ }
1148
+ _clearTmpSubScriberRelations() {
1149
+ this._tmpSubscriberShelter.clear();
1150
+ }
1151
+ _disconnect() {
1152
+ this._publisherMap.forEach((publisher) => {
1153
+ publisher.close();
1154
+ });
1155
+ }
1156
+ // Every day on 0/6/9/12/15//18, Publishers that have not been connected within 1.5 hours will be cleared regularly.
1157
+ // If process.env.FEDERATION_SERVER_TEST is set, it will be read at a specified time.
1158
+ _setSchedule() {
1159
+ const rule = new import_node_schedule.default.RecurrenceRule();
1160
+ if (Number(process.env["FEDERATION_SERVER_TEST"])) {
1161
+ const interval = Number(process.env["FEDERATION_SERVER_TEST"]) / 1e3;
1162
+ const second = [];
1163
+ for (let i = 0; i < 60; i = i + interval) {
1164
+ second.push(i);
1165
+ }
1166
+ rule.second = second;
1167
+ } else {
1168
+ rule.second = 0;
1169
+ rule.hour = [
1170
+ 0,
1171
+ 3,
1172
+ 6,
1173
+ 9,
1174
+ 12,
1175
+ 15,
1176
+ 18
1177
+ ];
1178
+ rule.minute = 0;
1179
+ }
1180
+ const serverTest = Number(process.env["FEDERATION_SERVER_TEST"]);
1181
+ this._scheduleJob = import_node_schedule.default.scheduleJob(rule, () => {
1182
+ this._tmpSubscriberShelter.forEach((tmpSubscriber, identifier) => {
1183
+ fileLog(` _clearTmpSubScriberRelation ${identifier}, ${Date.now() - tmpSubscriber.timestamp >= (process.env["GARFISH_MODULE_SERVER_TEST"] ? serverTest : _Broker.DEFAULT_WAITING_TIME)}`, "Broker", "info");
1184
+ if (Date.now() - tmpSubscriber.timestamp >= (process.env["FEDERATION_SERVER_TEST"] ? serverTest : _Broker.DEFAULT_WAITING_TIME)) {
1185
+ this._clearTmpSubScriberRelation(identifier);
1186
+ }
1187
+ });
1188
+ });
1189
+ }
1190
+ _clearSchedule() {
1191
+ if (!this._scheduleJob) {
1192
+ return;
1193
+ }
1194
+ this._scheduleJob.cancel();
1195
+ this._scheduleJob = null;
1196
+ }
1197
+ _stopWhenSIGTERMOrSIGINT() {
1198
+ process.on("SIGTERM", () => {
1199
+ this.exit();
1200
+ });
1201
+ process.on("SIGINT", () => {
1202
+ this.exit();
1203
+ });
1204
+ }
1205
+ _handleUnexpectedExit() {
1206
+ process.on("unhandledRejection", (error2) => {
1207
+ console.error("Unhandled Rejection Error: ", error2);
1208
+ fileLog(`Unhandled Rejection Error: ${error2}`, "Broker", "fatal");
1209
+ process.exit(1);
1210
+ });
1211
+ process.on("uncaughtException", (error2) => {
1212
+ console.error("Unhandled Exception Error: ", error2);
1213
+ fileLog(`Unhandled Rejection Error: ${error2}`, "Broker", "fatal");
1214
+ process.exit(1);
1215
+ });
1216
+ }
1217
+ start() {
1218
+ return __async(this, null, function* () {
1219
+ });
1220
+ }
1221
+ exit() {
1222
+ const brokerExitLog = new BrokerExitLog();
1223
+ this.broadcast(JSON.stringify(brokerExitLog));
1224
+ this._disconnect();
1225
+ this._clearSchedule();
1226
+ this._clearTmpSubScriberRelations();
1227
+ this._webSocketServer && this._webSocketServer.close();
1228
+ this._secureWebSocketServer && this._secureWebSocketServer.close();
1229
+ process.exit(0);
1230
+ }
1231
+ broadcast(message) {
1232
+ var _a2, _b;
1233
+ fileLog(`[broadcast] exit info : ${JSON.stringify(message)}`, "Broker", "warn");
1234
+ (_a2 = this._webSocketServer) == null ? void 0 : _a2.clients.forEach((client) => {
1235
+ client.send(JSON.stringify(message));
1236
+ });
1237
+ (_b = this._secureWebSocketServer) == null ? void 0 : _b.clients.forEach((client) => {
1238
+ client.send(JSON.stringify(message));
1239
+ });
1240
+ }
1241
+ };
1242
+ __name(_Broker, "Broker");
1243
+ __publicField(_Broker, "WEB_SOCKET_CONNECT_MAGIC_ID", WEB_SOCKET_CONNECT_MAGIC_ID);
1244
+ __publicField(_Broker, "DEFAULT_WEB_SOCKET_PORT", DEFAULT_WEB_SOCKET_PORT);
1245
+ __publicField(_Broker, "DEFAULT_SECURE_WEB_SOCKET_PORT", 16324);
1246
+ __publicField(_Broker, "DEFAULT_WAITING_TIME", 1.5 * 60 * 60 * 1e3);
1247
+ var Broker = _Broker;
1248
+
1249
+ // packages/dts-plugin/src/server/broker/startBroker.ts
1250
+ var broker;
1251
+ function getBroker() {
1252
+ return broker;
1253
+ }
1254
+ __name(getBroker, "getBroker");
1255
+ function startBroker() {
1256
+ return __async(this, null, function* () {
1257
+ var _a2;
1258
+ if (getBroker()) {
1259
+ return;
1260
+ }
1261
+ broker = new Broker();
1262
+ yield broker.start();
1263
+ (_a2 = process.send) == null ? void 0 : _a2.call(process, "ready");
1264
+ });
1265
+ }
1266
+ __name(startBroker, "startBroker");
1267
+ process.on("message", (message) => {
1268
+ if (message === "start") {
1269
+ fileLog(`startBroker... ${process.pid}`, "StartBroker", "info");
1270
+ startBroker();
1271
+ }
1272
+ });
1273
+ // Annotate the CommonJS export names for ESM import in node:
1274
+ 0 && (module.exports = {
1275
+ getBroker
1276
+ });