@module-federation/dts-plugin 0.1.19 → 0.1.21

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