@module-federation/dts-plugin 2.0.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/Action-CzhPMw2i.js +153 -0
  2. package/dist/Broker-DRlzScTT.js +800 -0
  3. package/dist/CHANGELOG.md +15 -0
  4. package/dist/DtsWorker-Dtem3-FM.d.ts +166 -0
  5. package/dist/constant-BwEkyidO.d.ts +42 -0
  6. package/dist/consumeTypes-AD2ig87l.js +237 -0
  7. package/dist/core.d.ts +3 -68
  8. package/dist/core.js +26 -2443
  9. package/dist/dynamic-remote-type-hints-plugin.d.ts +622 -3
  10. package/dist/dynamic-remote-type-hints-plugin.js +65 -187
  11. package/dist/esm/Action-DNNg2YDh.mjs +47 -0
  12. package/dist/esm/Broker-BU4gToNr.mjs +736 -0
  13. package/dist/esm/consumeTypes-D51rVbSt.mjs +204 -0
  14. package/dist/esm/core.mjs +5 -0
  15. package/dist/esm/dynamic-remote-type-hints-plugin.mjs +73 -0
  16. package/dist/esm/expose-rpc-DMhY1i8A.mjs +1301 -0
  17. package/dist/esm/fork-dev-worker.mjs +103 -0
  18. package/dist/esm/fork-generate-dts.mjs +14 -0
  19. package/dist/esm/index.mjs +465 -0
  20. package/dist/esm/start-broker.mjs +22 -0
  21. package/dist/esm/utils-CkPvDGOy.mjs +13 -0
  22. package/dist/expose-rpc-BLAH20uj.js +1415 -0
  23. package/dist/fork-dev-worker.d.ts +10 -9
  24. package/dist/fork-dev-worker.js +100 -2932
  25. package/dist/fork-generate-dts.d.ts +4 -8
  26. package/dist/fork-generate-dts.js +11 -2103
  27. package/dist/iife/launch-web-client.iife.js +117 -0
  28. package/dist/index.d.ts +57 -46
  29. package/dist/index.js +449 -3043
  30. package/dist/package.json +26 -11
  31. package/dist/start-broker.d.ts +41 -39
  32. package/dist/start-broker.js +17 -952
  33. package/dist/utils-7KqCZHbb.js +19 -0
  34. package/package.json +31 -16
  35. package/dist/DTSManager-b15Gfat3.d.ts +0 -53
  36. package/dist/DTSManagerOptions-QVchWb0x.d.ts +0 -32
  37. package/dist/DtsWorker-BrHsGz8C.d.ts +0 -56
  38. package/dist/core.d.mts +0 -68
  39. package/dist/dynamic-remote-type-hints-plugin.d.mts +0 -5
  40. package/dist/esm/chunk-647HGGGS.js +0 -241
  41. package/dist/esm/chunk-G65LOFTY.js +0 -24
  42. package/dist/esm/chunk-LJTUMI5K.js +0 -282
  43. package/dist/esm/chunk-MV6M4VFH.js +0 -1642
  44. package/dist/esm/chunk-WWV5RWOP.js +0 -902
  45. package/dist/esm/core.js +0 -44
  46. package/dist/esm/dynamic-remote-type-hints-plugin.js +0 -73
  47. package/dist/esm/fork-dev-worker.js +0 -145
  48. package/dist/esm/fork-generate-dts.js +0 -27
  49. package/dist/esm/index.js +0 -646
  50. package/dist/esm/start-broker.js +0 -36
  51. package/dist/fork-dev-worker.d.mts +0 -15
  52. package/dist/fork-generate-dts.d.mts +0 -10
  53. package/dist/iife/launch-web-client.js +0 -152
  54. package/dist/index.d.mts +0 -56
  55. package/dist/start-broker.d.mts +0 -42
  56. package/dist/utils-C4sQemLR.d.ts +0 -15
package/dist/core.js CHANGED
@@ -1,2445 +1,28 @@
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 __objRest = (source, exclude) => {
26
- var target = {};
27
- for (var prop in source)
28
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
29
- target[prop] = source[prop];
30
- if (source != null && __getOwnPropSymbols)
31
- for (var prop of __getOwnPropSymbols(source)) {
32
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
33
- target[prop] = source[prop];
34
- }
35
- return target;
36
- };
37
- var __export = (target, all) => {
38
- for (var name in all)
39
- __defProp(target, name, { get: all[name], enumerable: true });
40
- };
41
- var __copyProps = (to, from, except, desc) => {
42
- if (from && typeof from === "object" || typeof from === "function") {
43
- for (let key of __getOwnPropNames(from))
44
- if (!__hasOwnProp.call(to, key) && key !== except)
45
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ require('./Broker-DRlzScTT.js');
3
+ const require_expose_rpc = require('./expose-rpc-BLAH20uj.js');
4
+ const require_consumeTypes = require('./consumeTypes-AD2ig87l.js');
5
+
6
+ exports.DTSManager = require_expose_rpc.DTSManager;
7
+ exports.DtsWorker = require_consumeTypes.DtsWorker;
8
+ exports.HOST_API_TYPES_FILE_NAME = require_expose_rpc.HOST_API_TYPES_FILE_NAME;
9
+ exports.REMOTE_ALIAS_IDENTIFIER = require_expose_rpc.REMOTE_ALIAS_IDENTIFIER;
10
+ exports.REMOTE_API_TYPES_FILE_NAME = require_expose_rpc.REMOTE_API_TYPES_FILE_NAME;
11
+ exports.consumeTypes = require_consumeTypes.consumeTypes;
12
+ exports.generateTypes = require_expose_rpc.generateTypes;
13
+ exports.generateTypesInChildProcess = require_consumeTypes.generateTypesInChildProcess;
14
+ exports.getDTSManagerConstructor = require_expose_rpc.getDTSManagerConstructor;
15
+ exports.isTSProject = require_expose_rpc.isTSProject;
16
+ exports.retrieveHostConfig = require_expose_rpc.retrieveHostConfig;
17
+ exports.retrieveMfTypesPath = require_expose_rpc.retrieveMfTypesPath;
18
+ exports.retrieveOriginalOutDir = require_expose_rpc.retrieveOriginalOutDir;
19
+ exports.retrieveRemoteConfig = require_expose_rpc.retrieveRemoteConfig;
20
+ exports.retrieveTypesAssetsInfo = require_expose_rpc.retrieveTypesAssetsInfo;
21
+ exports.retrieveTypesZipPath = require_expose_rpc.retrieveTypesZipPath;
22
+ Object.defineProperty(exports, 'rpc', {
23
+ enumerable: true,
24
+ get: function () {
25
+ return require_consumeTypes.rpc_exports;
46
26
  }
47
- return to;
48
- };
49
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
50
- // If the importer is in node compatibility mode or this is not an ESM
51
- // file that has been converted to a CommonJS file using a Babel-
52
- // compatible transform (i.e. "__esModule" has not been set), then set
53
- // "default" to the CommonJS "module.exports" for node compatibility.
54
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
55
- mod
56
- ));
57
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
58
- var __publicField = (obj, key, value) => {
59
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
60
- return value;
61
- };
62
- var __async = (__this, __arguments, generator) => {
63
- return new Promise((resolve4, reject) => {
64
- var fulfilled = (value) => {
65
- try {
66
- step(generator.next(value));
67
- } catch (e) {
68
- reject(e);
69
- }
70
- };
71
- var rejected = (value) => {
72
- try {
73
- step(generator.throw(value));
74
- } catch (e) {
75
- reject(e);
76
- }
77
- };
78
- var step = (x) => x.done ? resolve4(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
79
- step((generator = generator.apply(__this, __arguments)).next());
80
- });
81
- };
82
-
83
- // src/core/index.ts
84
- var core_exports = {};
85
- __export(core_exports, {
86
- DTSManager: () => DTSManager,
87
- DtsWorker: () => DtsWorker,
88
- HOST_API_TYPES_FILE_NAME: () => HOST_API_TYPES_FILE_NAME,
89
- REMOTE_ALIAS_IDENTIFIER: () => REMOTE_ALIAS_IDENTIFIER,
90
- REMOTE_API_TYPES_FILE_NAME: () => REMOTE_API_TYPES_FILE_NAME,
91
- consumeTypes: () => consumeTypes,
92
- generateTypes: () => generateTypes,
93
- generateTypesInChildProcess: () => generateTypesInChildProcess,
94
- getDTSManagerConstructor: () => getDTSManagerConstructor,
95
- isTSProject: () => isTSProject,
96
- retrieveHostConfig: () => retrieveHostConfig,
97
- retrieveMfTypesPath: () => retrieveMfTypesPath,
98
- retrieveOriginalOutDir: () => retrieveOriginalOutDir,
99
- retrieveRemoteConfig: () => retrieveRemoteConfig,
100
- retrieveTypesAssetsInfo: () => retrieveTypesAssetsInfo,
101
- retrieveTypesZipPath: () => retrieveTypesZipPath,
102
- rpc: () => rpc_exports,
103
- validateOptions: () => validateOptions
104
- });
105
- module.exports = __toCommonJS(core_exports);
106
-
107
- // src/core/configurations/remotePlugin.ts
108
- var import_fs3 = require("fs");
109
- var import_path5 = require("path");
110
- var import_managers2 = require("@module-federation/managers");
111
- var import_typescript = __toESM(require("typescript"));
112
-
113
- // src/core/lib/utils.ts
114
- var import_fs2 = __toESM(require("fs"));
115
- var import_path4 = __toESM(require("path"));
116
- var import_axios = __toESM(require("axios"));
117
- var import_http2 = __toESM(require("http"));
118
- var import_https = __toESM(require("https"));
119
- var import_sdk6 = require("@module-federation/sdk");
120
- var import_ansi_colors = __toESM(require("ansi-colors"));
121
-
122
- // src/core/lib/DTSManager.ts
123
- var import_path3 = __toESM(require("path"));
124
- var import_promises3 = require("fs/promises");
125
- var import_fs = __toESM(require("fs"));
126
- var import_fs_extra3 = __toESM(require("fs-extra"));
127
- var import_sdk5 = require("@module-federation/sdk");
128
- var import_third_party_dts_extractor2 = require("@module-federation/third-party-dts-extractor");
129
-
130
- // src/core/lib/archiveHandler.ts
131
- var import_adm_zip = __toESM(require("adm-zip"));
132
- var import_path2 = require("path");
133
- var import_promises2 = require("fs/promises");
134
-
135
- // src/core/lib/typeScriptCompiler.ts
136
- var import_fs_extra2 = require("fs-extra");
137
- var import_crypto = __toESM(require("crypto"));
138
- var import_promises = require("fs/promises");
139
- var import_path = require("path");
140
- var import_error_codes = require("@module-federation/error-codes");
141
- var import_third_party_dts_extractor = require("@module-federation/third-party-dts-extractor");
142
- var import_child_process = require("child_process");
143
- var import_util = __toESM(require("util"));
144
- var import_sdk3 = require("@module-federation/sdk");
145
-
146
- // src/server/message/Message.ts
147
- var _Message = class _Message {
148
- constructor(type, kind) {
149
- __publicField(this, "type");
150
- __publicField(this, "kind");
151
- __publicField(this, "time");
152
- this.type = type;
153
- this.kind = kind;
154
- this.time = Date.now();
155
- }
156
- };
157
- __name(_Message, "Message");
158
- var Message = _Message;
159
-
160
- // src/server/message/API/API.ts
161
- var APIKind;
162
- (function(APIKind2) {
163
- APIKind2["UPDATE_SUBSCRIBER"] = "UPDATE_SUBSCRIBER";
164
- APIKind2["RELOAD_WEB_CLIENT"] = "RELOAD_WEB_CLIENT";
165
- APIKind2["FETCH_TYPES"] = "FETCH_TYPES";
166
- })(APIKind || (APIKind = {}));
167
- var _API = class _API extends Message {
168
- constructor(content, kind) {
169
- super("API", kind);
170
- __publicField(this, "code");
171
- __publicField(this, "payload");
172
- const { code, payload } = content;
173
- this.code = code;
174
- this.payload = payload;
175
- }
176
- };
177
- __name(_API, "API");
178
- var API = _API;
179
-
180
- // src/server/message/API/UpdateSubscriber.ts
181
- var _UpdateSubscriberAPI = class _UpdateSubscriberAPI extends API {
182
- constructor(payload) {
183
- super({
184
- code: 0,
185
- payload
186
- }, APIKind.UPDATE_SUBSCRIBER);
187
- }
188
- };
189
- __name(_UpdateSubscriberAPI, "UpdateSubscriberAPI");
190
- var UpdateSubscriberAPI = _UpdateSubscriberAPI;
191
-
192
- // src/server/message/API/ReloadWebClient.ts
193
- var _ReloadWebClientAPI = class _ReloadWebClientAPI extends API {
194
- constructor(payload) {
195
- super({
196
- code: 0,
197
- payload
198
- }, APIKind.RELOAD_WEB_CLIENT);
199
- }
200
- };
201
- __name(_ReloadWebClientAPI, "ReloadWebClientAPI");
202
- var ReloadWebClientAPI = _ReloadWebClientAPI;
203
-
204
- // src/server/message/API/FetchTypes.ts
205
- var _FetchTypesAPI = class _FetchTypesAPI extends API {
206
- constructor(payload) {
207
- super({
208
- code: 0,
209
- payload
210
- }, APIKind.FETCH_TYPES);
211
- }
212
- };
213
- __name(_FetchTypesAPI, "FetchTypesAPI");
214
- var FetchTypesAPI = _FetchTypesAPI;
215
-
216
- // src/server/utils/index.ts
217
- var import_sdk2 = require("@module-federation/sdk");
218
-
219
- // src/server/utils/logTransform.ts
220
- var import_chalk = __toESM(require("chalk"));
221
-
222
- // src/server/message/Log/Log.ts
223
- var LogLevel;
224
- (function(LogLevel2) {
225
- LogLevel2["LOG"] = "LOG";
226
- LogLevel2["WARN"] = "WARN";
227
- LogLevel2["ERROR"] = "ERROR";
228
- })(LogLevel || (LogLevel = {}));
229
- var LogKind;
230
- (function(LogKind2) {
231
- LogKind2["BrokerExitLog"] = "BrokerExitLog";
232
- LogKind2["PublisherRegisteredLog"] = "PublisherRegisteredLog";
233
- })(LogKind || (LogKind = {}));
234
- var _Log = class _Log extends Message {
235
- constructor(level, kind, ignoreVerbose = false) {
236
- super("Log", kind);
237
- __publicField(this, "level");
238
- __publicField(this, "ignoreVerbose", false);
239
- this.level = level;
240
- this.ignoreVerbose = ignoreVerbose;
241
- }
242
- };
243
- __name(_Log, "Log");
244
- var Log = _Log;
245
-
246
- // src/server/message/Log/BrokerExitLog.ts
247
- var _BrokerExitLog = class _BrokerExitLog extends Log {
248
- constructor() {
249
- super(LogLevel.LOG, LogKind.BrokerExitLog);
250
- }
251
- };
252
- __name(_BrokerExitLog, "BrokerExitLog");
253
- var BrokerExitLog = _BrokerExitLog;
254
-
255
- // src/server/utils/log.ts
256
- var import_sdk = require("@module-federation/sdk");
257
- var log4js = __toESM(require("log4js"));
258
-
259
- // src/server/constant.ts
260
- var DEFAULT_WEB_SOCKET_PORT = 16322;
261
- var WEB_SOCKET_CONNECT_MAGIC_ID = "1hpzW-zo2z-o8io-gfmV1-2cb1d82";
262
- var MF_SERVER_IDENTIFIER = "Module Federation DTS";
263
- var UpdateMode;
264
- (function(UpdateMode2) {
265
- UpdateMode2["POSITIVE"] = "POSITIVE";
266
- UpdateMode2["PASSIVE"] = "PASSIVE";
267
- })(UpdateMode || (UpdateMode = {}));
268
-
269
- // src/server/utils/log.ts
270
- var logger = (0, import_sdk.createLogger)(`[ ${MF_SERVER_IDENTIFIER} ]`);
271
- function fileLog(msg, module2, level) {
272
- var _a3, _b;
273
- if (!((_a3 = process == null ? void 0 : process.env) == null ? void 0 : _a3["FEDERATION_DEBUG"])) {
274
- return;
275
- }
276
- log4js.configure({
277
- appenders: {
278
- [module2]: {
279
- type: "file",
280
- filename: ".mf/typesGenerate.log"
281
- },
282
- default: {
283
- type: "file",
284
- filename: ".mf/typesGenerate.log"
285
- }
286
- },
287
- categories: {
288
- [module2]: {
289
- appenders: [
290
- module2
291
- ],
292
- level: "error"
293
- },
294
- default: {
295
- appenders: [
296
- "default"
297
- ],
298
- level: "trace"
299
- }
300
- }
301
- });
302
- const logger4 = log4js.getLogger(module2);
303
- logger4.level = "debug";
304
- (_b = logger4[level]) == null ? void 0 : _b.call(logger4, msg);
305
- }
306
- __name(fileLog, "fileLog");
307
- function error(error2, action, from) {
308
- const err = error2 instanceof Error ? error2 : new Error(`${action} error`);
309
- fileLog(`[${action}] error: ${err}`, from, "fatal");
310
- return err.toString();
311
- }
312
- __name(error, "error");
313
-
314
- // src/server/utils/index.ts
315
- function getIdentifier(options) {
316
- const { ip, name } = options;
317
- return `mf ${import_sdk2.SEPARATOR}${name}${ip ? `${import_sdk2.SEPARATOR}${ip}` : ""}`;
318
- }
319
- __name(getIdentifier, "getIdentifier");
320
-
321
- // src/server/Publisher.ts
322
- var _Publisher = class _Publisher {
323
- constructor(ctx) {
324
- __publicField(this, "_ip");
325
- __publicField(this, "_name");
326
- __publicField(this, "_remoteTypeTarPath");
327
- __publicField(this, "_subscribers");
328
- __publicField(this, "_ws");
329
- __publicField(this, "dynamicRemoteMap");
330
- this._name = ctx.name;
331
- this._ip = ctx.ip;
332
- this._remoteTypeTarPath = ctx.remoteTypeTarPath;
333
- this._subscribers = /* @__PURE__ */ new Map();
334
- this._ws = ctx.ws;
335
- this.dynamicRemoteMap = /* @__PURE__ */ new Map();
336
- }
337
- get identifier() {
338
- return getIdentifier({
339
- name: this._name,
340
- ip: this._ip
341
- });
342
- }
343
- get name() {
344
- return this._name;
345
- }
346
- get ip() {
347
- return this._ip;
348
- }
349
- get remoteTypeTarPath() {
350
- return this._remoteTypeTarPath;
351
- }
352
- get hasSubscribes() {
353
- return Boolean(this._subscribers.size);
354
- }
355
- get subscribers() {
356
- return this._subscribers;
357
- }
358
- addSubscriber(identifier, subscriber) {
359
- fileLog(`${this.name} set subscriber: ${identifier}`, "Publisher", "info");
360
- this._subscribers.set(identifier, subscriber);
361
- }
362
- removeSubscriber(identifier) {
363
- if (this._subscribers.has(identifier)) {
364
- fileLog(`${this.name} removeSubscriber: ${identifier}`, "Publisher", "warn");
365
- this._subscribers.delete(identifier);
366
- }
367
- }
368
- notifySubscriber(subscriberIdentifier, options) {
369
- const subscriber = this._subscribers.get(subscriberIdentifier);
370
- if (!subscriber) {
371
- fileLog(`[notifySubscriber] ${this.name} notifySubscriber: ${subscriberIdentifier}, does not exits`, "Publisher", "error");
372
- return;
373
- }
374
- const api = new UpdateSubscriberAPI(options);
375
- subscriber.send(JSON.stringify(api));
376
- fileLog(`[notifySubscriber] ${this.name} notifySubscriber: ${JSON.stringify(subscriberIdentifier)}, message: ${JSON.stringify(api)}`, "Publisher", "info");
377
- }
378
- fetchRemoteTypes(options) {
379
- fileLog(`[fetchRemoteTypes] ${this.name} fetchRemoteTypes, options: ${JSON.stringify(options)}, ws: ${Boolean(this._ws)}`, "Publisher", "info");
380
- if (!this._ws) {
381
- return;
382
- }
383
- const api = new FetchTypesAPI(options);
384
- this._ws.send(JSON.stringify(api));
385
- }
386
- notifySubscribers(options) {
387
- const api = new UpdateSubscriberAPI(options);
388
- this.broadcast(api);
389
- }
390
- broadcast(message) {
391
- if (this.hasSubscribes) {
392
- this._subscribers.forEach((subscriber, key) => {
393
- fileLog(`[BroadCast] ${this.name} notifySubscriber: ${key}, PID: ${process.pid}, message: ${JSON.stringify(message)}`, "Publisher", "info");
394
- subscriber.send(JSON.stringify(message));
395
- });
396
- } else {
397
- fileLog(`[BroadCast] ${this.name}'s subscribe is empty`, "Publisher", "warn");
398
- }
399
- }
400
- close() {
401
- this._ws = void 0;
402
- this._subscribers.forEach((_subscriber, identifier) => {
403
- fileLog(`[BroadCast] close ${this.name} remove: ${identifier}`, "Publisher", "warn");
404
- this.removeSubscriber(identifier);
405
- });
406
- }
407
- };
408
- __name(_Publisher, "Publisher");
409
- var Publisher = _Publisher;
410
-
411
- // src/server/DevServer.ts
412
- var import_isomorphic_ws2 = __toESM(require("isomorphic-ws"));
413
-
414
- // src/server/broker/Broker.ts
415
- var import_http = require("http");
416
- var import_isomorphic_ws = __toESM(require("isomorphic-ws"));
417
- var import_node_schedule = __toESM(require("node-schedule"));
418
- var import_url = require("url");
419
-
420
- // src/server/message/Action/Action.ts
421
- var ActionKind;
422
- (function(ActionKind2) {
423
- ActionKind2["ADD_SUBSCRIBER"] = "ADD_SUBSCRIBER";
424
- ActionKind2["EXIT_SUBSCRIBER"] = "EXIT_SUBSCRIBER";
425
- ActionKind2["ADD_PUBLISHER"] = "ADD_PUBLISHER";
426
- ActionKind2["UPDATE_PUBLISHER"] = "UPDATE_PUBLISHER";
427
- ActionKind2["NOTIFY_SUBSCRIBER"] = "NOTIFY_SUBSCRIBER";
428
- ActionKind2["EXIT_PUBLISHER"] = "EXIT_PUBLISHER";
429
- ActionKind2["ADD_WEB_CLIENT"] = "ADD_WEB_CLIENT";
430
- ActionKind2["NOTIFY_WEB_CLIENT"] = "NOTIFY_WEB_CLIENT";
431
- ActionKind2["FETCH_TYPES"] = "FETCH_TYPES";
432
- ActionKind2["ADD_DYNAMIC_REMOTE"] = "ADD_DYNAMIC_REMOTE";
433
- })(ActionKind || (ActionKind = {}));
434
-
435
- // src/server/message/Action/Update.ts
436
- var UpdateKind;
437
- (function(UpdateKind2) {
438
- UpdateKind2["UPDATE_TYPE"] = "UPDATE_TYPE";
439
- UpdateKind2["RELOAD_PAGE"] = "RELOAD_PAGE";
440
- })(UpdateKind || (UpdateKind = {}));
441
-
442
- // src/server/broker/Broker.ts
443
- var _Broker = class _Broker {
444
- constructor() {
445
- __publicField(this, "_publisherMap", /* @__PURE__ */ new Map());
446
- __publicField(this, "_webClientMap", /* @__PURE__ */ new Map());
447
- __publicField(this, "_webSocketServer");
448
- __publicField(this, "_secureWebSocketServer");
449
- __publicField(this, "_tmpSubscriberShelter", /* @__PURE__ */ new Map());
450
- __publicField(this, "_scheduleJob", null);
451
- this._setSchedule();
452
- this._startWsServer();
453
- this._stopWhenSIGTERMOrSIGINT();
454
- this._handleUnexpectedExit();
455
- }
456
- get hasPublishers() {
457
- return Boolean(this._publisherMap.size);
458
- }
459
- _startWsServer() {
460
- return __async(this, null, function* () {
461
- const wsHandler = /* @__PURE__ */ __name((ws, req) => {
462
- const { url: reqUrl = "" } = req;
463
- const { query } = (0, import_url.parse)(reqUrl, true);
464
- const { WEB_SOCKET_CONNECT_MAGIC_ID: WEB_SOCKET_CONNECT_MAGIC_ID2 } = query;
465
- if (WEB_SOCKET_CONNECT_MAGIC_ID2 === _Broker.WEB_SOCKET_CONNECT_MAGIC_ID) {
466
- ws.on("message", (message) => {
467
- try {
468
- const text = message.toString();
469
- const action = JSON.parse(text);
470
- fileLog(`${action == null ? void 0 : action.kind} action received `, "Broker", "info");
471
- this._takeAction(action, ws);
472
- } catch (error2) {
473
- fileLog(`parse action message error: ${error2}`, "Broker", "error");
474
- }
475
- });
476
- ws.on("error", (e) => {
477
- fileLog(`parse action message error: ${e}`, "Broker", "error");
478
- });
479
- } else {
480
- ws.send("Invalid CONNECT ID.");
481
- fileLog("Invalid CONNECT ID.", "Broker", "warn");
482
- ws.close();
483
- }
484
- }, "wsHandler");
485
- const server = (0, import_http.createServer)();
486
- this._webSocketServer = new import_isomorphic_ws.default.Server({
487
- noServer: true
488
- });
489
- this._webSocketServer.on("error", (err) => {
490
- fileLog(`ws error:
491
- ${err.message}
492
- ${err.stack}`, "Broker", "error");
493
- });
494
- this._webSocketServer.on("listening", () => {
495
- fileLog(`WebSocket server is listening on port ${_Broker.DEFAULT_WEB_SOCKET_PORT}`, "Broker", "info");
496
- });
497
- this._webSocketServer.on("connection", wsHandler);
498
- this._webSocketServer.on("close", (code) => {
499
- fileLog(`WebSocket Server Close with Code ${code}`, "Broker", "warn");
500
- this._webSocketServer && this._webSocketServer.close();
501
- this._webSocketServer = void 0;
502
- });
503
- server.on("upgrade", (req, socket, head) => {
504
- var _a3;
505
- if (req.url) {
506
- const { pathname } = (0, import_url.parse)(req.url);
507
- if (pathname === "/") {
508
- (_a3 = this._webSocketServer) == null ? void 0 : _a3.handleUpgrade(req, socket, head, (ws) => {
509
- var _a4;
510
- (_a4 = this._webSocketServer) == null ? void 0 : _a4.emit("connection", ws, req);
511
- });
512
- }
513
- }
514
- });
515
- server.listen(_Broker.DEFAULT_WEB_SOCKET_PORT);
516
- });
517
- }
518
- _takeAction(action, client) {
519
- return __async(this, null, function* () {
520
- const { kind, payload } = action;
521
- if (kind === ActionKind.ADD_PUBLISHER) {
522
- yield this._addPublisher(payload, client);
523
- }
524
- if (kind === ActionKind.UPDATE_PUBLISHER) {
525
- yield this._updatePublisher(payload, client);
526
- }
527
- if (kind === ActionKind.ADD_SUBSCRIBER) {
528
- yield this._addSubscriber(payload, client);
529
- }
530
- if (kind === ActionKind.EXIT_SUBSCRIBER) {
531
- yield this._removeSubscriber(payload, client);
532
- }
533
- if (kind === ActionKind.EXIT_PUBLISHER) {
534
- yield this._removePublisher(payload, client);
535
- }
536
- if (kind === ActionKind.ADD_WEB_CLIENT) {
537
- yield this._addWebClient(payload, client);
538
- }
539
- if (kind === ActionKind.NOTIFY_WEB_CLIENT) {
540
- yield this._notifyWebClient(payload, client);
541
- }
542
- if (kind === ActionKind.FETCH_TYPES) {
543
- yield this._fetchTypes(payload, client);
544
- }
545
- if (kind === ActionKind.ADD_DYNAMIC_REMOTE) {
546
- this._addDynamicRemote(payload);
547
- }
548
- });
549
- }
550
- _addPublisher(context, client) {
551
- return __async(this, null, function* () {
552
- const { name, ip, remoteTypeTarPath } = context != null ? context : {};
553
- const identifier = getIdentifier({
554
- name,
555
- ip
556
- });
557
- if (this._publisherMap.has(identifier)) {
558
- fileLog(`[${ActionKind.ADD_PUBLISHER}] ${identifier} has been added, this action will be ignored`, "Broker", "warn");
559
- return;
560
- }
561
- try {
562
- const publisher = new Publisher({
563
- name,
564
- ip,
565
- remoteTypeTarPath,
566
- ws: client
567
- });
568
- this._publisherMap.set(identifier, publisher);
569
- fileLog(`[${ActionKind.ADD_PUBLISHER}] ${identifier} Adding Publisher Succeed`, "Broker", "info");
570
- const tmpSubScribers = this._getTmpSubScribers(identifier);
571
- if (tmpSubScribers) {
572
- fileLog(`[${ActionKind.ADD_PUBLISHER}] consumeTmpSubscriber set ${publisher.name}\u2019s subscribers `, "Broker", "info");
573
- this._consumeTmpSubScribers(publisher, tmpSubScribers);
574
- this._clearTmpSubScriberRelation(identifier);
575
- }
576
- } catch (err) {
577
- const msg = error(err, ActionKind.ADD_PUBLISHER, "Broker");
578
- client.send(msg);
579
- client.close();
580
- }
581
- });
582
- }
583
- _updatePublisher(context, client) {
584
- return __async(this, null, function* () {
585
- const { name, updateMode, updateKind, updateSourcePaths, remoteTypeTarPath, ip } = context != null ? context : {};
586
- const identifier = getIdentifier({
587
- name,
588
- ip
589
- });
590
- if (!this._publisherMap.has(identifier)) {
591
- fileLog(`[${ActionKind.UPDATE_PUBLISHER}] ${identifier} has not been started, this action will be ignored
592
- this._publisherMap: ${JSON.stringify(this._publisherMap.entries())}
593
- `, "Broker", "warn");
594
- return;
595
- }
596
- try {
597
- const publisher = this._publisherMap.get(identifier);
598
- fileLog(
599
- // eslint-disable-next-line max-len
600
- `[${ActionKind.UPDATE_PUBLISHER}] ${identifier} update, and notify subscribers to update`,
601
- "Broker",
602
- "info"
603
- );
604
- if (publisher) {
605
- publisher.notifySubscribers({
606
- remoteTypeTarPath,
607
- name,
608
- updateMode,
609
- updateKind,
610
- updateSourcePaths: updateSourcePaths || []
611
- });
612
- this._publisherMap.forEach((p) => {
613
- if (p.name === publisher.name) {
614
- return;
615
- }
616
- const dynamicRemoteInfo = p.dynamicRemoteMap.get(identifier);
617
- if (dynamicRemoteInfo) {
618
- fileLog(
619
- // eslint-disable-next-line max-len
620
- `dynamicRemoteInfo: ${JSON.stringify(dynamicRemoteInfo)}, identifier:${identifier} publish: ${p.name}`,
621
- "Broker",
622
- "info"
623
- );
624
- p.fetchRemoteTypes({
625
- remoteInfo: dynamicRemoteInfo,
626
- once: false
627
- });
628
- }
629
- });
630
- }
631
- } catch (err) {
632
- const msg = error(err, ActionKind.UPDATE_PUBLISHER, "Broker");
633
- client.send(msg);
634
- client.close();
635
- }
636
- });
637
- }
638
- _fetchTypes(context, _client) {
639
- return __async(this, null, function* () {
640
- const { name, ip, remoteInfo } = context != null ? context : {};
641
- const identifier = getIdentifier({
642
- name,
643
- ip
644
- });
645
- try {
646
- const publisher = this._publisherMap.get(identifier);
647
- fileLog(`[${ActionKind.FETCH_TYPES}] ${identifier} fetch types`, "Broker", "info");
648
- if (publisher) {
649
- publisher.fetchRemoteTypes({
650
- remoteInfo,
651
- once: true
652
- });
653
- }
654
- } catch (err) {
655
- fileLog(`[${ActionKind.FETCH_TYPES}] ${identifier} fetch types fail , error info: ${err}`, "Broker", "error");
656
- }
657
- });
658
- }
659
- _addDynamicRemote(context) {
660
- const { name, ip, remoteInfo, remoteIp } = context != null ? context : {};
661
- const identifier = getIdentifier({
662
- name,
663
- ip
664
- });
665
- const publisher = this._publisherMap.get(identifier);
666
- const remoteId = getIdentifier({
667
- name: remoteInfo.name,
668
- ip: remoteIp
669
- });
670
- fileLog(`[${ActionKind.ADD_DYNAMIC_REMOTE}] identifier:${identifier},publisher: ${publisher.name}, remoteId:${remoteId}`, "Broker", "error");
671
- if (!publisher || publisher.dynamicRemoteMap.has(remoteId)) {
672
- return;
673
- }
674
- publisher.dynamicRemoteMap.set(remoteId, remoteInfo);
675
- }
676
- // app1 consumes provider1,provider2. Dependencies at this time: publishers: [provider1, provider2], subscriberName: app1
677
- // provider1 is app1's remote
678
- _addSubscriber(context, client) {
679
- return __async(this, null, function* () {
680
- const { publishers, name: subscriberName } = context != null ? context : {};
681
- publishers.forEach((publisher) => {
682
- const { name, ip } = publisher;
683
- const identifier = getIdentifier({
684
- name,
685
- ip
686
- });
687
- if (!this._publisherMap.has(identifier)) {
688
- fileLog(`[${ActionKind.ADD_SUBSCRIBER}]: ${identifier} has not been started, ${subscriberName} will add the relation to tmp shelter`, "Broker", "warn");
689
- this._addTmpSubScriberRelation({
690
- name: getIdentifier({
691
- name: context.name,
692
- ip: context.ip
693
- }),
694
- client
695
- }, publisher);
696
- return;
697
- }
698
- try {
699
- const registeredPublisher = this._publisherMap.get(identifier);
700
- if (registeredPublisher) {
701
- registeredPublisher.addSubscriber(getIdentifier({
702
- name: subscriberName,
703
- ip: context.ip
704
- }), client);
705
- fileLog(
706
- // eslint-disable-next-line @ies/eden/max-calls-in-template
707
- `[${ActionKind.ADD_SUBSCRIBER}]: ${identifier} has been started, Adding Subscriber ${subscriberName} Succeed, this.__publisherMap are: ${JSON.stringify(Array.from(this._publisherMap.entries()))}`,
708
- "Broker",
709
- "info"
710
- );
711
- registeredPublisher.notifySubscriber(getIdentifier({
712
- name: subscriberName,
713
- ip: context.ip
714
- }), {
715
- updateKind: UpdateKind.UPDATE_TYPE,
716
- updateMode: UpdateMode.PASSIVE,
717
- updateSourcePaths: [
718
- registeredPublisher.name
719
- ],
720
- remoteTypeTarPath: registeredPublisher.remoteTypeTarPath,
721
- name: registeredPublisher.name
722
- });
723
- fileLog(
724
- // eslint-disable-next-line @ies/eden/max-calls-in-template
725
- `[${ActionKind.ADD_SUBSCRIBER}]: notifySubscriber Subscriber ${subscriberName}, updateMode: "PASSIVE", updateSourcePaths: ${registeredPublisher.name}`,
726
- "Broker",
727
- "info"
728
- );
729
- }
730
- } catch (err) {
731
- const msg = error(err, ActionKind.ADD_SUBSCRIBER, "Broker");
732
- client.send(msg);
733
- client.close();
734
- }
735
- });
736
- });
737
- }
738
- // Trigger while consumer exit
739
- _removeSubscriber(context, client) {
740
- return __async(this, null, function* () {
741
- const { publishers } = context != null ? context : {};
742
- const subscriberIdentifier = getIdentifier({
743
- name: context == null ? void 0 : context.name,
744
- ip: context == null ? void 0 : context.ip
745
- });
746
- publishers.forEach((publisher) => {
747
- const { name, ip } = publisher;
748
- const identifier = getIdentifier({
749
- name,
750
- ip
751
- });
752
- const registeredPublisher = this._publisherMap.get(identifier);
753
- if (!registeredPublisher) {
754
- fileLog(`[${ActionKind.EXIT_SUBSCRIBER}], ${identifier} does not exit `, "Broker", "warn");
755
- return;
756
- }
757
- try {
758
- fileLog(`[${ActionKind.EXIT_SUBSCRIBER}], ${identifier} will exit `, "Broker", "INFO");
759
- registeredPublisher.removeSubscriber(subscriberIdentifier);
760
- this._clearTmpSubScriberRelation(identifier);
761
- if (!registeredPublisher.hasSubscribes) {
762
- this._publisherMap.delete(identifier);
763
- }
764
- if (!this.hasPublishers) {
765
- this.exit();
766
- }
767
- } catch (err) {
768
- const msg = error(err, ActionKind.EXIT_SUBSCRIBER, "Broker");
769
- client.send(msg);
770
- client.close();
771
- }
772
- });
773
- });
774
- }
775
- _removePublisher(context, client) {
776
- return __async(this, null, function* () {
777
- const { name, ip } = context != null ? context : {};
778
- const identifier = getIdentifier({
779
- name,
780
- ip
781
- });
782
- const publisher = this._publisherMap.get(identifier);
783
- if (!publisher) {
784
- fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier}} has not been added, this action will be ingored`, "Broker", "warn");
785
- return;
786
- }
787
- try {
788
- const { subscribers } = publisher;
789
- subscribers.forEach((subscriber, subscriberIdentifier) => {
790
- this._addTmpSubScriberRelation({
791
- name: subscriberIdentifier,
792
- client: subscriber
793
- }, {
794
- name: publisher.name,
795
- ip: publisher.ip
796
- });
797
- fileLog(
798
- // eslint-disable-next-line max-len
799
- `[${ActionKind.EXIT_PUBLISHER}]: ${identifier} is removing , subscriber: ${subscriberIdentifier} will be add tmpSubScriberRelation`,
800
- "Broker",
801
- "info"
802
- );
803
- });
804
- this._publisherMap.delete(identifier);
805
- fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier} is removed `, "Broker", "info");
806
- if (!this.hasPublishers) {
807
- fileLog(`[${ActionKind.EXIT_PUBLISHER}]: _publisherMap is empty, all server will exit `, "Broker", "warn");
808
- this.exit();
809
- }
810
- } catch (err) {
811
- const msg = error(err, ActionKind.EXIT_PUBLISHER, "Broker");
812
- client.send(msg);
813
- client.close();
814
- }
815
- });
816
- }
817
- _addWebClient(context, client) {
818
- return __async(this, null, function* () {
819
- const { name } = context != null ? context : {};
820
- const identifier = getIdentifier({
821
- name
822
- });
823
- if (this._webClientMap.has(identifier)) {
824
- fileLog(`${identifier}} has been added, this action will override prev WebClient`, "Broker", "warn");
825
- }
826
- try {
827
- this._webClientMap.set(identifier, client);
828
- fileLog(`${identifier} adding WebClient Succeed`, "Broker", "info");
829
- } catch (err) {
830
- const msg = error(err, ActionKind.ADD_WEB_CLIENT, "Broker");
831
- client.send(msg);
832
- client.close();
833
- }
834
- });
835
- }
836
- _notifyWebClient(context, client) {
837
- return __async(this, null, function* () {
838
- const { name, updateMode } = context != null ? context : {};
839
- const identifier = getIdentifier({
840
- name
841
- });
842
- const webClient = this._webClientMap.get(identifier);
843
- if (!webClient) {
844
- fileLog(`[${ActionKind.NOTIFY_WEB_CLIENT}] ${identifier} has not been added, this action will be ignored`, "Broker", "warn");
845
- return;
846
- }
847
- try {
848
- const api = new ReloadWebClientAPI({
849
- name,
850
- updateMode
851
- });
852
- webClient.send(JSON.stringify(api));
853
- fileLog(`[${ActionKind.NOTIFY_WEB_CLIENT}] Notify ${name} WebClient Succeed`, "Broker", "info");
854
- } catch (err) {
855
- const msg = error(err, ActionKind.NOTIFY_WEB_CLIENT, "Broker");
856
- client.send(msg);
857
- client.close();
858
- }
859
- });
860
- }
861
- // app1 consumes provider1, and provider1 not launch. this._tmpSubscriberShelter at this time: {provider1: Map{subscribers: Map{app1: app1+ip+client'}, timestamp: 'xx'} }
862
- _addTmpSubScriberRelation(subscriber, publisher) {
863
- const publisherIdentifier = getIdentifier({
864
- name: publisher.name,
865
- ip: publisher.ip
866
- });
867
- const subscriberIdentifier = subscriber.name;
868
- const shelter = this._tmpSubscriberShelter.get(publisherIdentifier);
869
- if (!shelter) {
870
- const map = /* @__PURE__ */ new Map();
871
- map.set(subscriberIdentifier, subscriber);
872
- this._tmpSubscriberShelter.set(publisherIdentifier, {
873
- subscribers: map,
874
- timestamp: Date.now()
875
- });
876
- fileLog(`[AddTmpSubscriberRelation] ${publisherIdentifier}'s subscriber has ${subscriberIdentifier} `, "Broker", "info");
877
- return;
878
- }
879
- const tmpSubScriberShelterSubscriber = shelter.subscribers.get(subscriberIdentifier);
880
- if (tmpSubScriberShelterSubscriber) {
881
- fileLog(`[AddTmpSubscriberRelation] ${publisherIdentifier} and ${subscriberIdentifier} relation has been added`, "Broker", "warn");
882
- shelter.subscribers.set(subscriberIdentifier, subscriber);
883
- shelter.timestamp = Date.now();
884
- } else {
885
- fileLog(
886
- // eslint-disable-next-line max-len
887
- `AddTmpSubscriberLog ${publisherIdentifier}'s shelter has been added, update shelter.subscribers ${subscriberIdentifier}`,
888
- "Broker",
889
- "warn"
890
- );
891
- shelter.subscribers.set(subscriberIdentifier, subscriber);
892
- }
893
- }
894
- _getTmpSubScribers(publisherIdentifier) {
895
- var _a3;
896
- return (_a3 = this._tmpSubscriberShelter.get(publisherIdentifier)) == null ? void 0 : _a3.subscribers;
897
- }
898
- // after adding publisher, it will change the temp subscriber to regular subscriber
899
- _consumeTmpSubScribers(publisher, tmpSubScribers) {
900
- tmpSubScribers.forEach((tmpSubScriber, identifier) => {
901
- fileLog(`notifyTmpSubScribers ${publisher.name} will be add a subscriber: ${identifier} `, "Broker", "warn");
902
- publisher.addSubscriber(identifier, tmpSubScriber.client);
903
- publisher.notifySubscriber(identifier, {
904
- updateKind: UpdateKind.UPDATE_TYPE,
905
- updateMode: UpdateMode.PASSIVE,
906
- updateSourcePaths: [
907
- publisher.name
908
- ],
909
- remoteTypeTarPath: publisher.remoteTypeTarPath,
910
- name: publisher.name
911
- });
912
- });
913
- }
914
- _clearTmpSubScriberRelation(identifier) {
915
- this._tmpSubscriberShelter.delete(identifier);
916
- }
917
- _clearTmpSubScriberRelations() {
918
- this._tmpSubscriberShelter.clear();
919
- }
920
- _disconnect() {
921
- this._publisherMap.forEach((publisher) => {
922
- publisher.close();
923
- });
924
- }
925
- // Every day on 0/6/9/12/15//18, Publishers that have not been connected within 1.5 hours will be cleared regularly.
926
- // If process.env.FEDERATION_SERVER_TEST is set, it will be read at a specified time.
927
- _setSchedule() {
928
- const rule = new import_node_schedule.default.RecurrenceRule();
929
- if (Number(process.env["FEDERATION_SERVER_TEST"])) {
930
- const interval = Number(process.env["FEDERATION_SERVER_TEST"]) / 1e3;
931
- const second = [];
932
- for (let i = 0; i < 60; i = i + interval) {
933
- second.push(i);
934
- }
935
- rule.second = second;
936
- } else {
937
- rule.second = 0;
938
- rule.hour = [
939
- 0,
940
- 3,
941
- 6,
942
- 9,
943
- 12,
944
- 15,
945
- 18
946
- ];
947
- rule.minute = 0;
948
- }
949
- const serverTest = Number(process.env["FEDERATION_SERVER_TEST"]);
950
- this._scheduleJob = import_node_schedule.default.scheduleJob(rule, () => {
951
- this._tmpSubscriberShelter.forEach((tmpSubscriber, identifier) => {
952
- fileLog(` _clearTmpSubScriberRelation ${identifier}, ${Date.now() - tmpSubscriber.timestamp >= (process.env["GARFISH_MODULE_SERVER_TEST"] ? serverTest : _Broker.DEFAULT_WAITING_TIME)}`, "Broker", "info");
953
- if (Date.now() - tmpSubscriber.timestamp >= (process.env["FEDERATION_SERVER_TEST"] ? serverTest : _Broker.DEFAULT_WAITING_TIME)) {
954
- this._clearTmpSubScriberRelation(identifier);
955
- }
956
- });
957
- });
958
- }
959
- _clearSchedule() {
960
- if (!this._scheduleJob) {
961
- return;
962
- }
963
- this._scheduleJob.cancel();
964
- this._scheduleJob = null;
965
- }
966
- _stopWhenSIGTERMOrSIGINT() {
967
- process.on("SIGTERM", () => {
968
- this.exit();
969
- });
970
- process.on("SIGINT", () => {
971
- this.exit();
972
- });
973
- }
974
- _handleUnexpectedExit() {
975
- process.on("unhandledRejection", (error2) => {
976
- console.error("Unhandled Rejection Error: ", error2);
977
- fileLog(`Unhandled Rejection Error: ${error2}`, "Broker", "fatal");
978
- process.exit(1);
979
- });
980
- process.on("uncaughtException", (error2) => {
981
- console.error("Unhandled Exception Error: ", error2);
982
- fileLog(`Unhandled Rejection Error: ${error2}`, "Broker", "fatal");
983
- process.exit(1);
984
- });
985
- }
986
- start() {
987
- return __async(this, null, function* () {
988
- });
989
- }
990
- exit() {
991
- const brokerExitLog = new BrokerExitLog();
992
- this.broadcast(JSON.stringify(brokerExitLog));
993
- this._disconnect();
994
- this._clearSchedule();
995
- this._clearTmpSubScriberRelations();
996
- this._webSocketServer && this._webSocketServer.close();
997
- this._secureWebSocketServer && this._secureWebSocketServer.close();
998
- process.exit(0);
999
- }
1000
- broadcast(message) {
1001
- var _a3, _b;
1002
- fileLog(`[broadcast] exit info : ${JSON.stringify(message)}`, "Broker", "warn");
1003
- (_a3 = this._webSocketServer) == null ? void 0 : _a3.clients.forEach((client) => {
1004
- client.send(JSON.stringify(message));
1005
- });
1006
- (_b = this._secureWebSocketServer) == null ? void 0 : _b.clients.forEach((client) => {
1007
- client.send(JSON.stringify(message));
1008
- });
1009
- }
1010
- };
1011
- __name(_Broker, "Broker");
1012
- __publicField(_Broker, "WEB_SOCKET_CONNECT_MAGIC_ID", WEB_SOCKET_CONNECT_MAGIC_ID);
1013
- __publicField(_Broker, "DEFAULT_WEB_SOCKET_PORT", DEFAULT_WEB_SOCKET_PORT);
1014
- __publicField(_Broker, "DEFAULT_SECURE_WEB_SOCKET_PORT", 16324);
1015
- __publicField(_Broker, "DEFAULT_WAITING_TIME", 1.5 * 60 * 60 * 1e3);
1016
- var Broker = _Broker;
1017
-
1018
- // src/server/createKoaServer.ts
1019
- var import_fs_extra = __toESM(require("fs-extra"));
1020
- var import_koa = __toESM(require("koa"));
1021
-
1022
- // src/core/lib/typeScriptCompiler.ts
1023
- var STARTS_WITH_SLASH = /^\//;
1024
- var DEFINITION_FILE_EXTENSION = ".d.ts";
1025
- var retrieveMfTypesPath = /* @__PURE__ */ __name((tsConfig, remoteOptions) => (0, import_path.normalize)(tsConfig.compilerOptions.outDir.replace(remoteOptions.compiledTypesFolder, "")), "retrieveMfTypesPath");
1026
- var retrieveOriginalOutDir = /* @__PURE__ */ __name((tsConfig, remoteOptions) => (0, import_path.normalize)(tsConfig.compilerOptions.outDir.replace(remoteOptions.compiledTypesFolder, "").replace(remoteOptions.typesFolder, "")), "retrieveOriginalOutDir");
1027
- var retrieveMfAPITypesPath = /* @__PURE__ */ __name((tsConfig, remoteOptions) => (0, import_path.join)(retrieveOriginalOutDir(tsConfig, remoteOptions), `${remoteOptions.typesFolder}.d.ts`), "retrieveMfAPITypesPath");
1028
- function writeTempTsConfig(tsConfig, context, name, cwd) {
1029
- const createHash = /* @__PURE__ */ __name((contents) => {
1030
- return import_crypto.default.createHash("md5").update(contents).digest("hex");
1031
- }, "createHash");
1032
- const hash = createHash(`${JSON.stringify(tsConfig)}${name}${Date.now()}`);
1033
- const tempTsConfigJsonPath = (0, import_path.resolve)(cwd != null ? cwd : context, "node_modules", import_sdk3.TEMP_DIR, `tsconfig.${hash}.json`);
1034
- (0, import_fs_extra2.ensureDirSync)((0, import_path.dirname)(tempTsConfigJsonPath));
1035
- (0, import_fs_extra2.writeFileSync)(tempTsConfigJsonPath, JSON.stringify(tsConfig, null, 2));
1036
- return tempTsConfigJsonPath;
1037
- }
1038
- __name(writeTempTsConfig, "writeTempTsConfig");
1039
- var removeExt = /* @__PURE__ */ __name((f) => {
1040
- const vueExt = ".vue";
1041
- const ext = (0, import_path.extname)(f);
1042
- if (ext === vueExt) {
1043
- return f;
1044
- }
1045
- const regexPattern = new RegExp(`\\${ext}$`);
1046
- return f.replace(regexPattern, "");
1047
- }, "removeExt");
1048
- function getExposeKey(options) {
1049
- const { filePath, rootDir, outDir, mapExposeToEntry } = options;
1050
- const relativeFilePath = (0, import_path.relative)(outDir, filePath.replace(new RegExp(`\\.d.ts$`), ""));
1051
- return mapExposeToEntry[relativeFilePath];
1052
- }
1053
- __name(getExposeKey, "getExposeKey");
1054
- var processTypesFile = /* @__PURE__ */ __name((options) => __async(void 0, null, function* () {
1055
- const { outDir, filePath, rootDir, cb, mapExposeToEntry, mfTypePath } = options;
1056
- if (!(0, import_fs_extra2.existsSync)(filePath)) {
1057
- return;
1058
- }
1059
- const stats = yield (0, import_promises.stat)(filePath);
1060
- if (stats.isDirectory()) {
1061
- const files = yield (0, import_promises.readdir)(filePath);
1062
- yield Promise.all(files.map((file) => processTypesFile(__spreadProps(__spreadValues({}, options), {
1063
- filePath: (0, import_path.join)(filePath, file)
1064
- }))));
1065
- } else if (filePath.endsWith(".d.ts")) {
1066
- const exposeKey = getExposeKey({
1067
- filePath,
1068
- rootDir,
1069
- outDir,
1070
- mapExposeToEntry
1071
- });
1072
- if (exposeKey) {
1073
- const sourceEntry = exposeKey === "." ? "index" : exposeKey;
1074
- const mfeTypeEntry = (0, import_path.join)(mfTypePath, `${sourceEntry}${DEFINITION_FILE_EXTENSION}`);
1075
- const mfeTypeEntryDirectory = (0, import_path.dirname)(mfeTypeEntry);
1076
- const relativePathToOutput = (0, import_path.relative)(mfeTypeEntryDirectory, filePath).replace(DEFINITION_FILE_EXTENSION, "").replace(STARTS_WITH_SLASH, "").split(import_path.sep).join("/");
1077
- (0, import_fs_extra2.ensureDirSync)(mfeTypeEntryDirectory);
1078
- yield (0, import_promises.writeFile)(mfeTypeEntry, `export * from './${relativePathToOutput}';
1079
- export { default } from './${relativePathToOutput}';`);
1080
- }
1081
- const content = yield (0, import_promises.readFile)(filePath, "utf8");
1082
- cb(content);
1083
- }
1084
- }), "processTypesFile");
1085
- var getPMFromUserAgent = /* @__PURE__ */ __name(() => {
1086
- const userAgent = process.env["npm_config_user_agent"];
1087
- if (userAgent == null) {
1088
- return "null";
1089
- }
1090
- const name = userAgent.split("/")[0];
1091
- return name;
1092
- }, "getPMFromUserAgent");
1093
- var resolvePackageManagerExecutable = /* @__PURE__ */ __name(() => {
1094
- const pm = getPMFromUserAgent();
1095
- switch (pm) {
1096
- case "yarn":
1097
- return "yarn";
1098
- case "npm":
1099
- case "pnpm":
1100
- default:
1101
- return "npx";
1102
- }
1103
- }, "resolvePackageManagerExecutable");
1104
- var splitCommandArgs = /* @__PURE__ */ __name((value) => {
1105
- const args = [];
1106
- let current = "";
1107
- let quote = null;
1108
- let escaped = false;
1109
- for (const char of value) {
1110
- if (escaped) {
1111
- current += char;
1112
- escaped = false;
1113
- continue;
1114
- }
1115
- if (char === "\\") {
1116
- escaped = true;
1117
- continue;
1118
- }
1119
- if (quote) {
1120
- if (char === quote) {
1121
- quote = null;
1122
- } else {
1123
- current += char;
1124
- }
1125
- continue;
1126
- }
1127
- if (char === '"' || char === "'") {
1128
- quote = char;
1129
- continue;
1130
- }
1131
- if (char.trim() === "") {
1132
- if (current) {
1133
- args.push(current);
1134
- current = "";
1135
- }
1136
- continue;
1137
- }
1138
- current += char;
1139
- }
1140
- if (current) {
1141
- args.push(current);
1142
- }
1143
- return args;
1144
- }, "splitCommandArgs");
1145
- var formatCommandForDisplay = /* @__PURE__ */ __name((executable, args) => {
1146
- const formatArg = /* @__PURE__ */ __name((arg) => {
1147
- if (/[\s'"]/.test(arg)) {
1148
- return JSON.stringify(arg);
1149
- }
1150
- return arg;
1151
- }, "formatArg");
1152
- return [
1153
- executable,
1154
- ...args
1155
- ].map(formatArg).join(" ");
1156
- }, "formatCommandForDisplay");
1157
- var compileTs = /* @__PURE__ */ __name((mapComponentsToExpose, tsConfig, remoteOptions) => __async(void 0, null, function* () {
1158
- var _a3, _b, _c, _d;
1159
- if (!Object.keys(mapComponentsToExpose).length) {
1160
- return;
1161
- }
1162
- const { compilerOptions } = tsConfig;
1163
- const tempTsConfigJsonPath = writeTempTsConfig(tsConfig, remoteOptions.context, remoteOptions.moduleFederationConfig.name || "mf", typeof remoteOptions.moduleFederationConfig.dts !== "boolean" ? (_b = (_a3 = remoteOptions.moduleFederationConfig.dts) == null ? void 0 : _a3.cwd) != null ? _b : void 0 : void 0);
1164
- logger.debug(`tempTsConfigJsonPath: ${tempTsConfigJsonPath}`);
1165
- try {
1166
- const mfTypePath = retrieveMfTypesPath(tsConfig, remoteOptions);
1167
- const thirdPartyExtractor = new import_third_party_dts_extractor.ThirdPartyExtractor({
1168
- destDir: (0, import_path.resolve)(mfTypePath, "node_modules"),
1169
- context: remoteOptions.context,
1170
- exclude: typeof remoteOptions.extractThirdParty === "object" ? remoteOptions.extractThirdParty.exclude : void 0
1171
- });
1172
- const execPromise = import_util.default.promisify(import_child_process.execFile);
1173
- const pmExecutable = resolvePackageManagerExecutable();
1174
- const compilerArgs = splitCommandArgs(remoteOptions.compilerInstance);
1175
- const resolvedCompilerArgs = compilerArgs.length > 0 ? compilerArgs : [
1176
- remoteOptions.compilerInstance
1177
- ];
1178
- const cmdArgs = [
1179
- ...resolvedCompilerArgs,
1180
- "--project",
1181
- tempTsConfigJsonPath
1182
- ];
1183
- const cmd = formatCommandForDisplay(pmExecutable, cmdArgs);
1184
- try {
1185
- yield execPromise(pmExecutable, cmdArgs, {
1186
- cwd: typeof remoteOptions.moduleFederationConfig.dts !== "boolean" ? (_d = (_c = remoteOptions.moduleFederationConfig.dts) == null ? void 0 : _c.cwd) != null ? _d : void 0 : void 0,
1187
- shell: process.platform === "win32"
1188
- });
1189
- } catch (err) {
1190
- if (compilerOptions.tsBuildInfoFile) {
1191
- try {
1192
- yield (0, import_promises.rm)(compilerOptions.tsBuildInfoFile);
1193
- } catch (e) {
1194
- }
1195
- }
1196
- throw new Error((0, import_error_codes.getShortErrorMsg)(import_error_codes.TYPE_001, import_error_codes.typeDescMap, {
1197
- cmd
1198
- }));
1199
- }
1200
- const mapExposeToEntry = Object.fromEntries(Object.entries(mapComponentsToExpose).map(([exposed, filename]) => {
1201
- const normalizedFileName = (0, import_path.normalize)(filename);
1202
- let relativeFileName = "";
1203
- if ((0, import_path.isAbsolute)(normalizedFileName)) {
1204
- relativeFileName = (0, import_path.relative)(tsConfig.compilerOptions.rootDir, normalizedFileName);
1205
- } else {
1206
- relativeFileName = (0, import_path.relative)(tsConfig.compilerOptions.rootDir, (0, import_path.resolve)(remoteOptions.context, normalizedFileName));
1207
- }
1208
- return [
1209
- removeExt(relativeFileName),
1210
- exposed
1211
- ];
1212
- }));
1213
- const cb = remoteOptions.extractThirdParty ? thirdPartyExtractor.collectPkgs.bind(thirdPartyExtractor) : () => void 0;
1214
- yield processTypesFile({
1215
- outDir: compilerOptions.outDir,
1216
- filePath: compilerOptions.outDir,
1217
- rootDir: compilerOptions.rootDir,
1218
- mfTypePath,
1219
- cb,
1220
- mapExposeToEntry
1221
- });
1222
- if (remoteOptions.extractThirdParty) {
1223
- yield thirdPartyExtractor.copyDts();
1224
- }
1225
- if (remoteOptions.deleteTsConfig) {
1226
- yield (0, import_promises.rm)(tempTsConfigJsonPath);
1227
- }
1228
- } catch (err) {
1229
- throw err;
1230
- }
1231
- }), "compileTs");
1232
-
1233
- // src/core/lib/archiveHandler.ts
1234
- var retrieveTypesZipPath = /* @__PURE__ */ __name((mfTypesPath, remoteOptions) => (0, import_path2.join)(mfTypesPath.replace(remoteOptions.typesFolder, ""), `${remoteOptions.typesFolder}.zip`), "retrieveTypesZipPath");
1235
- var createTypesArchive = /* @__PURE__ */ __name((tsConfig, remoteOptions) => __async(void 0, null, function* () {
1236
- const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
1237
- const zip = new import_adm_zip.default();
1238
- zip.addLocalFolder(mfTypesPath);
1239
- return zip.writeZipPromise(retrieveTypesZipPath(mfTypesPath, remoteOptions));
1240
- }), "createTypesArchive");
1241
- var downloadErrorLogger = /* @__PURE__ */ __name((destinationFolder, fileToDownload) => (reason) => {
1242
- throw __spreadProps(__spreadValues({}, reason), {
1243
- message: `Network error: Unable to download federated mocks for '${destinationFolder}' from '${fileToDownload}' because '${reason.message}'`
1244
- });
1245
- }, "downloadErrorLogger");
1246
- var retrieveTypesArchiveDestinationPath = /* @__PURE__ */ __name((hostOptions, destinationFolder) => {
1247
- return (0, import_path2.resolve)(hostOptions.context, hostOptions.typesFolder, destinationFolder);
1248
- }, "retrieveTypesArchiveDestinationPath");
1249
- var downloadTypesArchive = /* @__PURE__ */ __name((hostOptions) => {
1250
- let retries = 0;
1251
- return (_0) => __async(void 0, [_0], function* ([destinationFolder, fileToDownload]) {
1252
- var _a3;
1253
- const destinationPath = retrieveTypesArchiveDestinationPath(hostOptions, destinationFolder);
1254
- while (retries++ < hostOptions.maxRetries) {
1255
- try {
1256
- const url = new URL(fileToDownload).href;
1257
- const response = yield axiosGet(url, {
1258
- responseType: "arraybuffer",
1259
- timeout: hostOptions.timeout,
1260
- family: hostOptions.family
1261
- }).catch(downloadErrorLogger(destinationFolder, url));
1262
- if (typeof ((_a3 = response.headers) == null ? void 0 : _a3["content-type"]) === "string" && response.headers["content-type"].includes("text/html")) {
1263
- throw new Error(`${url} receives invalid content-type: ${response.headers["content-type"]}`);
1264
- }
1265
- try {
1266
- if (hostOptions.deleteTypesFolder) {
1267
- yield (0, import_promises2.rm)(destinationPath, {
1268
- recursive: true,
1269
- force: true
1270
- });
1271
- }
1272
- } catch (error2) {
1273
- fileLog(`Unable to remove types folder, ${error2}`, "downloadTypesArchive", "error");
1274
- }
1275
- const zip = new import_adm_zip.default(Buffer.from(response.data));
1276
- zip.extractAllTo(destinationPath, true);
1277
- fileLog(`zip.extractAllTo success destinationPath: ${destinationPath}; url: ${url}`, "downloadTypesArchive", "info");
1278
- return [
1279
- destinationFolder,
1280
- destinationPath
1281
- ];
1282
- } catch (error2) {
1283
- fileLog(`Error during types archive download: ${(error2 == null ? void 0 : error2.message) || "unknown error"}`, "downloadTypesArchive", "error");
1284
- if (retries >= hostOptions.maxRetries) {
1285
- logger.error(`Failed to download types archive from "${fileToDownload}". Set FEDERATION_DEBUG=true for details.`);
1286
- if (hostOptions.abortOnError !== false) {
1287
- throw error2;
1288
- }
1289
- return void 0;
1290
- }
1291
- }
1292
- }
1293
- });
1294
- }, "downloadTypesArchive");
1295
-
1296
- // src/core/configurations/hostPlugin.ts
1297
- var import_sdk4 = require("@module-federation/sdk");
1298
- var import_managers = require("@module-federation/managers");
1299
- var defaultOptions = {
1300
- typesFolder: "@mf-types",
1301
- remoteTypesFolder: "@mf-types",
1302
- deleteTypesFolder: true,
1303
- maxRetries: 3,
1304
- implementation: "",
1305
- context: process.cwd(),
1306
- abortOnError: true,
1307
- consumeAPITypes: false,
1308
- runtimePkgs: [],
1309
- remoteTypeUrls: {},
1310
- timeout: 6e4,
1311
- typesOnBuild: false,
1312
- family: 4
1313
- };
1314
- var buildZipUrl = /* @__PURE__ */ __name((hostOptions, url) => {
1315
- const remoteUrl = new URL(url, "file:");
1316
- const pathnameWithoutEntry = remoteUrl.pathname.split("/").slice(0, -1).join("/");
1317
- remoteUrl.pathname = `${pathnameWithoutEntry}/${hostOptions.remoteTypesFolder}.zip`;
1318
- return remoteUrl.protocol === "file:" ? remoteUrl.pathname : remoteUrl.href;
1319
- }, "buildZipUrl");
1320
- var buildApiTypeUrl = /* @__PURE__ */ __name((zipUrl) => {
1321
- if (!zipUrl) {
1322
- return void 0;
1323
- }
1324
- return zipUrl.replace(".zip", ".d.ts");
1325
- }, "buildApiTypeUrl");
1326
- var retrieveRemoteInfo = /* @__PURE__ */ __name((options) => {
1327
- const { hostOptions, remoteAlias, remote } = options;
1328
- const { remoteTypeUrls } = hostOptions;
1329
- let decodedRemote = remote;
1330
- if (decodedRemote.startsWith(import_sdk4.ENCODE_NAME_PREFIX)) {
1331
- decodedRemote = (0, import_sdk4.decodeName)(decodedRemote, import_sdk4.ENCODE_NAME_PREFIX);
1332
- }
1333
- const parsedInfo = (0, import_sdk4.parseEntry)(decodedRemote, void 0, "@");
1334
- const url = "entry" in parsedInfo ? parsedInfo.entry : parsedInfo.name === decodedRemote ? decodedRemote : "";
1335
- let zipUrl = "";
1336
- let apiTypeUrl = "";
1337
- const name = parsedInfo.name || remoteAlias;
1338
- if (typeof remoteTypeUrls === "object" && remoteTypeUrls[name]) {
1339
- zipUrl = remoteTypeUrls[name].zip;
1340
- apiTypeUrl = remoteTypeUrls[name].api;
1341
- }
1342
- if (!zipUrl && url) {
1343
- zipUrl = buildZipUrl(hostOptions, url);
1344
- }
1345
- if (!apiTypeUrl && zipUrl) {
1346
- apiTypeUrl = buildApiTypeUrl(zipUrl);
1347
- }
1348
- return {
1349
- name,
1350
- url,
1351
- zipUrl,
1352
- apiTypeUrl,
1353
- alias: remoteAlias
1354
- };
1355
- }, "retrieveRemoteInfo");
1356
- var resolveRemotes = /* @__PURE__ */ __name((hostOptions) => {
1357
- var _a3;
1358
- const parsedOptions = import_managers.utils.parseOptions(hostOptions.moduleFederationConfig.remotes || {}, (item, key) => ({
1359
- remote: Array.isArray(item) ? item[0] : item,
1360
- key
1361
- }), (item, key) => ({
1362
- remote: Array.isArray(item.external) ? item.external[0] : item.external,
1363
- key
1364
- }));
1365
- const remoteTypeUrls = (_a3 = hostOptions.remoteTypeUrls) != null ? _a3 : {};
1366
- if (typeof remoteTypeUrls !== "object") {
1367
- throw new Error("remoteTypeUrls must be consumed before resolveRemotes");
1368
- }
1369
- const remoteInfos = Object.keys(remoteTypeUrls).reduce((sum, remoteName) => {
1370
- const { zip, api, alias } = remoteTypeUrls[remoteName];
1371
- sum[alias] = {
1372
- name: remoteName,
1373
- url: "",
1374
- zipUrl: zip,
1375
- apiTypeUrl: api,
1376
- alias: alias || remoteName
1377
- };
1378
- return sum;
1379
- }, {});
1380
- return parsedOptions.reduce((accumulator, item) => {
1381
- const { key, remote } = item[1];
1382
- const res = retrieveRemoteInfo({
1383
- hostOptions,
1384
- remoteAlias: key,
1385
- remote
1386
- });
1387
- if (accumulator[key]) {
1388
- accumulator[key] = __spreadProps(__spreadValues({}, accumulator[key]), {
1389
- url: res.url,
1390
- apiTypeUrl: accumulator[key].apiTypeUrl || res.apiTypeUrl
1391
- });
1392
- return accumulator;
1393
- }
1394
- accumulator[key] = res;
1395
- return accumulator;
1396
- }, remoteInfos);
1397
- }, "resolveRemotes");
1398
- var retrieveHostConfig = /* @__PURE__ */ __name((options) => {
1399
- validateOptions(options);
1400
- const hostOptions = __spreadValues(__spreadValues({}, defaultOptions), options);
1401
- const mapRemotesToDownload = resolveRemotes(hostOptions);
1402
- return {
1403
- hostOptions,
1404
- mapRemotesToDownload
1405
- };
1406
- }, "retrieveHostConfig");
1407
-
1408
- // src/core/constant.ts
1409
- var REMOTE_ALIAS_IDENTIFIER = "REMOTE_ALIAS_IDENTIFIER";
1410
- var REMOTE_API_TYPES_FILE_NAME = "apis.d.ts";
1411
- var HOST_API_TYPES_FILE_NAME = "index.d.ts";
1412
-
1413
- // src/core/lib/DTSManager.ts
1414
- var _a;
1415
- var DTSManager = (_a = class {
1416
- constructor(options) {
1417
- __publicField(this, "options");
1418
- __publicField(this, "runtimePkgs");
1419
- __publicField(this, "remoteAliasMap");
1420
- __publicField(this, "loadedRemoteAPIAlias");
1421
- __publicField(this, "extraOptions");
1422
- __publicField(this, "updatedRemoteInfos");
1423
- this.options = cloneDeepOptions(options);
1424
- this.runtimePkgs = [
1425
- "@module-federation/runtime",
1426
- "@module-federation/enhanced/runtime",
1427
- "@module-federation/runtime-tools"
1428
- ];
1429
- this.loadedRemoteAPIAlias = /* @__PURE__ */ new Set();
1430
- this.remoteAliasMap = {};
1431
- this.extraOptions = (options == null ? void 0 : options.extraOptions) || {};
1432
- this.updatedRemoteInfos = {};
1433
- }
1434
- generateAPITypes(mapComponentsToExpose) {
1435
- const exposePaths = /* @__PURE__ */ new Set();
1436
- const packageType = Object.keys(mapComponentsToExpose).reduce((sum, exposeKey) => {
1437
- const exposePath = import_path3.default.join(REMOTE_ALIAS_IDENTIFIER, exposeKey).split(import_path3.default.sep).join("/");
1438
- exposePaths.add(`'${exposePath}'`);
1439
- const curType = `T extends '${exposePath}' ? typeof import('${exposePath}') :`;
1440
- sum = curType + sum;
1441
- return sum;
1442
- }, "any;");
1443
- const exposePathKeys = [
1444
- ...exposePaths
1445
- ].join(" | ");
1446
- return `
1447
- export type RemoteKeys = ${exposePathKeys};
1448
- type PackageType<T> = ${packageType}`;
1449
- }
1450
- extractRemoteTypes(options) {
1451
- return __async(this, null, function* () {
1452
- var _a3;
1453
- const { remoteOptions, tsConfig } = options;
1454
- if (!remoteOptions.extractRemoteTypes) {
1455
- return;
1456
- }
1457
- let hasRemotes = false;
1458
- const remotes = remoteOptions.moduleFederationConfig.remotes;
1459
- if (remotes) {
1460
- if (Array.isArray(remotes)) {
1461
- hasRemotes = Boolean(remotes.length);
1462
- } else if (typeof remotes === "object") {
1463
- hasRemotes = Boolean(Object.keys(remotes).length);
1464
- }
1465
- }
1466
- const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
1467
- if (hasRemotes && this.options.host) {
1468
- try {
1469
- const { hostOptions } = retrieveHostConfig(this.options.host);
1470
- const remoteTypesFolder = import_path3.default.resolve(hostOptions.context, hostOptions.typesFolder);
1471
- const targetDir = import_path3.default.join(mfTypesPath, "node_modules");
1472
- if (import_fs.default.existsSync(remoteTypesFolder)) {
1473
- const targetFolder = import_path3.default.resolve(remoteOptions.context, targetDir);
1474
- yield import_fs_extra3.default.ensureDir(targetFolder);
1475
- yield import_fs_extra3.default.copy(remoteTypesFolder, targetFolder, {
1476
- overwrite: true
1477
- });
1478
- }
1479
- } catch (err) {
1480
- if (((_a3 = this.options.host) == null ? void 0 : _a3.abortOnError) === false) {
1481
- fileLog(`Unable to copy remote types, ${err}`, "extractRemoteTypes", "error");
1482
- } else {
1483
- throw err;
1484
- }
1485
- }
1486
- }
1487
- });
1488
- }
1489
- // it must execute after consumeTypes
1490
- generateTypes() {
1491
- return __async(this, null, function* () {
1492
- var _a3, _b;
1493
- try {
1494
- const { options } = this;
1495
- if (!options.remote) {
1496
- throw new Error("options.remote is required if you want to generateTypes");
1497
- }
1498
- const { remoteOptions, tsConfig, mapComponentsToExpose } = retrieveRemoteConfig(options.remote);
1499
- if (!Object.keys(mapComponentsToExpose).length) {
1500
- return;
1501
- }
1502
- if (!((_a3 = tsConfig.files) == null ? void 0 : _a3.length)) {
1503
- logger.info("No type files to compile, skip");
1504
- return;
1505
- }
1506
- if (tsConfig.compilerOptions.tsBuildInfoFile) {
1507
- try {
1508
- const tsBuildInfoFile = import_path3.default.resolve(remoteOptions.context, tsConfig.compilerOptions.tsBuildInfoFile);
1509
- const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
1510
- if (!import_fs.default.existsSync(mfTypesPath)) {
1511
- import_fs.default.rmSync(tsBuildInfoFile, {
1512
- force: true
1513
- });
1514
- }
1515
- } catch (e) {
1516
- }
1517
- }
1518
- yield this.extractRemoteTypes({
1519
- remoteOptions,
1520
- tsConfig,
1521
- mapComponentsToExpose
1522
- });
1523
- yield compileTs(mapComponentsToExpose, tsConfig, remoteOptions);
1524
- yield createTypesArchive(tsConfig, remoteOptions);
1525
- let apiTypesPath = "";
1526
- if (remoteOptions.generateAPITypes) {
1527
- const apiTypes = this.generateAPITypes(mapComponentsToExpose);
1528
- apiTypesPath = retrieveMfAPITypesPath(tsConfig, remoteOptions);
1529
- import_fs.default.writeFileSync(apiTypesPath, apiTypes);
1530
- }
1531
- try {
1532
- if (remoteOptions.deleteTypesFolder) {
1533
- yield (0, import_promises3.rm)(retrieveMfTypesPath(tsConfig, remoteOptions), {
1534
- recursive: true,
1535
- force: true
1536
- });
1537
- }
1538
- } catch (err) {
1539
- if (isDebugMode()) {
1540
- console.error(err);
1541
- }
1542
- }
1543
- logger.success("Federated types created correctly");
1544
- } catch (error2) {
1545
- if (((_b = this.options.remote) == null ? void 0 : _b.abortOnError) === false) {
1546
- if (this.options.displayErrorInTerminal) {
1547
- logger.error(error2);
1548
- }
1549
- } else {
1550
- throw error2;
1551
- }
1552
- }
1553
- });
1554
- }
1555
- requestRemoteManifest(remoteInfo, hostOptions) {
1556
- return __async(this, null, function* () {
1557
- try {
1558
- if (!remoteInfo.url.includes(import_sdk5.MANIFEST_EXT)) {
1559
- return remoteInfo;
1560
- }
1561
- if (remoteInfo.zipUrl) {
1562
- return remoteInfo;
1563
- }
1564
- const url = remoteInfo.url;
1565
- const res = yield axiosGet(url, {
1566
- timeout: hostOptions.timeout,
1567
- family: hostOptions.family
1568
- });
1569
- const manifestJson = res.data;
1570
- if (!manifestJson.metaData.types.zip) {
1571
- throw new Error(`Can not get ${remoteInfo.name}'s types archive url!`);
1572
- }
1573
- const addProtocol = /* @__PURE__ */ __name((u) => {
1574
- if (u.startsWith("//")) {
1575
- return `https:${u}`;
1576
- }
1577
- return u;
1578
- }, "addProtocol");
1579
- let publicPath;
1580
- if ("publicPath" in manifestJson.metaData) {
1581
- publicPath = manifestJson.metaData.publicPath;
1582
- } else {
1583
- const getPublicPath = new Function(manifestJson.metaData.getPublicPath);
1584
- if (manifestJson.metaData.getPublicPath.startsWith("function")) {
1585
- publicPath = getPublicPath()();
1586
- } else {
1587
- publicPath = getPublicPath();
1588
- }
1589
- }
1590
- if (publicPath === "auto") {
1591
- publicPath = (0, import_sdk5.inferAutoPublicPath)(remoteInfo.url);
1592
- }
1593
- remoteInfo.zipUrl = new URL(import_path3.default.join(addProtocol(publicPath), manifestJson.metaData.types.zip)).href;
1594
- if (!manifestJson.metaData.types.api) {
1595
- console.warn(`Can not get ${remoteInfo.name}'s api types url!`);
1596
- remoteInfo.apiTypeUrl = "";
1597
- return remoteInfo;
1598
- }
1599
- remoteInfo.apiTypeUrl = new URL(import_path3.default.join(addProtocol(publicPath), manifestJson.metaData.types.api)).href;
1600
- return remoteInfo;
1601
- } catch (_err) {
1602
- fileLog(`fetch manifest failed, ${_err}, ${remoteInfo.name} will be ignored`, "requestRemoteManifest", "error");
1603
- return remoteInfo;
1604
- }
1605
- });
1606
- }
1607
- consumeTargetRemotes(hostOptions, remoteInfo) {
1608
- return __async(this, null, function* () {
1609
- if (!remoteInfo.zipUrl) {
1610
- throw new Error(`Can not get ${remoteInfo.name}'s types archive url!`);
1611
- }
1612
- const typesDownloader = downloadTypesArchive(hostOptions);
1613
- return typesDownloader([
1614
- remoteInfo.alias,
1615
- remoteInfo.zipUrl
1616
- ]);
1617
- });
1618
- }
1619
- downloadAPITypes(remoteInfo, destinationPath, hostOptions) {
1620
- return __async(this, null, function* () {
1621
- const { apiTypeUrl } = remoteInfo;
1622
- if (!apiTypeUrl) {
1623
- return;
1624
- }
1625
- try {
1626
- const url = apiTypeUrl;
1627
- const res = yield axiosGet(url, {
1628
- timeout: hostOptions.timeout,
1629
- family: hostOptions.family
1630
- });
1631
- let apiTypeFile = res.data;
1632
- apiTypeFile = apiTypeFile.replaceAll(REMOTE_ALIAS_IDENTIFIER, remoteInfo.alias);
1633
- const filePath = import_path3.default.join(destinationPath, REMOTE_API_TYPES_FILE_NAME);
1634
- import_fs.default.writeFileSync(filePath, apiTypeFile);
1635
- const existed = this.loadedRemoteAPIAlias.has(remoteInfo.alias);
1636
- this.loadedRemoteAPIAlias.add(remoteInfo.alias);
1637
- fileLog(`success`, "downloadAPITypes", "info");
1638
- return existed;
1639
- } catch (err) {
1640
- fileLog(`Unable to download "${remoteInfo.name}" api types, ${err}`, "downloadAPITypes", "error");
1641
- }
1642
- });
1643
- }
1644
- consumeAPITypes(hostOptions) {
1645
- const apiTypeFileName = import_path3.default.join(hostOptions.context, hostOptions.typesFolder, HOST_API_TYPES_FILE_NAME);
1646
- try {
1647
- const existedFile = import_fs.default.readFileSync(apiTypeFileName, "utf-8");
1648
- const existedImports = new import_third_party_dts_extractor2.ThirdPartyExtractor({
1649
- destDir: ""
1650
- }).collectTypeImports(existedFile);
1651
- existedImports.forEach((existedImport) => {
1652
- const alias = existedImport.split("./").slice(1).join("./").replace("/apis.d.ts", "");
1653
- this.loadedRemoteAPIAlias.add(alias);
1654
- });
1655
- } catch (err) {
1656
- }
1657
- if (!this.loadedRemoteAPIAlias.size) {
1658
- return;
1659
- }
1660
- const packageTypes = [];
1661
- const remoteKeys = [];
1662
- const importTypeStr = [
1663
- ...this.loadedRemoteAPIAlias
1664
- ].sort().map((alias, index) => {
1665
- const remoteKey = `RemoteKeys_${index}`;
1666
- const packageType = `PackageType_${index}`;
1667
- packageTypes.push(`T extends ${remoteKey} ? ${packageType}<T>`);
1668
- remoteKeys.push(remoteKey);
1669
- return `import type { PackageType as ${packageType},RemoteKeys as ${remoteKey} } from './${alias}/apis.d.ts';`;
1670
- }).join("\n");
1671
- const remoteKeysStr = `type RemoteKeys = ${remoteKeys.join(" | ")};`;
1672
- const packageTypesStr = `type PackageType<T, Y=any> = ${[
1673
- ...packageTypes,
1674
- "Y"
1675
- ].join(" :\n")} ;`;
1676
- const runtimePkgs = /* @__PURE__ */ new Set();
1677
- [
1678
- ...this.runtimePkgs,
1679
- ...hostOptions.runtimePkgs
1680
- ].forEach((pkg) => {
1681
- runtimePkgs.add(pkg);
1682
- });
1683
- const pkgsDeclareStr = [
1684
- ...runtimePkgs
1685
- ].map((pkg) => {
1686
- return `declare module "${pkg}" {
1687
- ${remoteKeysStr}
1688
- ${packageTypesStr}
1689
- export function loadRemote<T extends RemoteKeys,Y>(packageName: T): Promise<PackageType<T, Y>>;
1690
- export function loadRemote<T extends string,Y>(packageName: T): Promise<PackageType<T, Y>>;
1691
- }`;
1692
- }).join("\n");
1693
- const fileStr = `${importTypeStr}
1694
- ${pkgsDeclareStr}
1695
- `;
1696
- import_fs.default.writeFileSync(import_path3.default.join(hostOptions.context, hostOptions.typesFolder, HOST_API_TYPES_FILE_NAME), fileStr);
1697
- }
1698
- consumeArchiveTypes(options) {
1699
- return __async(this, null, function* () {
1700
- const { hostOptions, mapRemotesToDownload } = retrieveHostConfig(options);
1701
- const downloadPromises = Object.entries(mapRemotesToDownload).map((item) => __async(this, null, function* () {
1702
- const remoteInfo = item[1];
1703
- if (!this.remoteAliasMap[remoteInfo.alias]) {
1704
- const requiredRemoteInfo = yield this.requestRemoteManifest(remoteInfo, hostOptions);
1705
- this.remoteAliasMap[remoteInfo.alias] = requiredRemoteInfo;
1706
- }
1707
- return this.consumeTargetRemotes(hostOptions, this.remoteAliasMap[remoteInfo.alias]);
1708
- }));
1709
- const downloadPromisesResult = yield Promise.allSettled(downloadPromises);
1710
- return {
1711
- hostOptions,
1712
- downloadPromisesResult
1713
- };
1714
- });
1715
- }
1716
- consumeTypes() {
1717
- return __async(this, null, function* () {
1718
- var _a3;
1719
- try {
1720
- const { options } = this;
1721
- if (!options.host) {
1722
- throw new Error("options.host is required if you want to consumeTypes");
1723
- }
1724
- const { mapRemotesToDownload } = retrieveHostConfig(options.host);
1725
- if (!Object.keys(mapRemotesToDownload).length) {
1726
- return;
1727
- }
1728
- const { downloadPromisesResult, hostOptions } = yield this.consumeArchiveTypes(options.host);
1729
- if (hostOptions.consumeAPITypes) {
1730
- yield Promise.all(downloadPromisesResult.map((item) => __async(this, null, function* () {
1731
- if (item.status === "rejected" || !item.value) {
1732
- return;
1733
- }
1734
- const [alias, destinationPath] = item.value;
1735
- const remoteInfo = this.remoteAliasMap[alias];
1736
- if (!remoteInfo) {
1737
- return;
1738
- }
1739
- yield this.downloadAPITypes(remoteInfo, destinationPath, hostOptions);
1740
- })));
1741
- this.consumeAPITypes(hostOptions);
1742
- }
1743
- logger.success("Federated types extraction completed");
1744
- } catch (err) {
1745
- if (((_a3 = this.options.host) == null ? void 0 : _a3.abortOnError) === false) {
1746
- fileLog(`Unable to consume federated types, ${err}`, "consumeTypes", "error");
1747
- } else {
1748
- throw err;
1749
- }
1750
- }
1751
- });
1752
- }
1753
- updateTypes(options) {
1754
- return __async(this, null, function* () {
1755
- var _a3, _b, _c;
1756
- try {
1757
- const { remoteName, updateMode, remoteTarPath, remoteInfo: updatedRemoteInfo, once } = options;
1758
- const hostName = (_c = (_b = (_a3 = this.options) == null ? void 0 : _a3.host) == null ? void 0 : _b.moduleFederationConfig) == null ? void 0 : _c.name;
1759
- fileLog(`options: ${JSON.stringify(options, null, 2)};
1760
- hostName: ${hostName}`, "updateTypes", "info");
1761
- if (updateMode === UpdateMode.POSITIVE && remoteName === hostName) {
1762
- if (!this.options.remote) {
1763
- return;
1764
- }
1765
- yield this.generateTypes();
1766
- } else {
1767
- const { remoteAliasMap } = this;
1768
- if (!this.options.host) {
1769
- return;
1770
- }
1771
- const { hostOptions, mapRemotesToDownload } = retrieveHostConfig(this.options.host);
1772
- const loadedRemoteInfo = Object.values(remoteAliasMap).find((i) => i.name === remoteName);
1773
- const consumeTypes2 = /* @__PURE__ */ __name((requiredRemoteInfo) => __async(this, null, function* () {
1774
- fileLog(`consumeTypes start`, "updateTypes", "info");
1775
- if (!requiredRemoteInfo.zipUrl) {
1776
- throw new Error(`Can not get ${requiredRemoteInfo.name}'s types archive url!`);
1777
- }
1778
- const [_alias, destinationPath] = yield this.consumeTargetRemotes(hostOptions, __spreadProps(__spreadValues({}, requiredRemoteInfo), {
1779
- // use remoteTarPath first
1780
- zipUrl: remoteTarPath || requiredRemoteInfo.zipUrl
1781
- }));
1782
- const addNew = yield this.downloadAPITypes(requiredRemoteInfo, destinationPath, hostOptions);
1783
- if (addNew) {
1784
- this.consumeAPITypes(hostOptions);
1785
- }
1786
- fileLog(`consumeTypes end`, "updateTypes", "info");
1787
- }), "consumeTypes");
1788
- fileLog(`loadedRemoteInfo: ${JSON.stringify(loadedRemoteInfo, null, 2)}`, "updateTypes", "info");
1789
- if (!loadedRemoteInfo) {
1790
- const remoteInfo = Object.values(mapRemotesToDownload).find((item) => {
1791
- return item.name === remoteName;
1792
- });
1793
- fileLog(`remoteInfo: ${JSON.stringify(remoteInfo, null, 2)}`, "updateTypes", "info");
1794
- if (remoteInfo) {
1795
- if (!this.remoteAliasMap[remoteInfo.alias]) {
1796
- const requiredRemoteInfo = yield this.requestRemoteManifest(remoteInfo, hostOptions);
1797
- this.remoteAliasMap[remoteInfo.alias] = requiredRemoteInfo;
1798
- }
1799
- yield consumeTypes2(this.remoteAliasMap[remoteInfo.alias]);
1800
- } else if (updatedRemoteInfo) {
1801
- const consumeDynamicRemoteTypes = /* @__PURE__ */ __name(() => __async(this, null, function* () {
1802
- yield consumeTypes2(this.updatedRemoteInfos[updatedRemoteInfo.name]);
1803
- }), "consumeDynamicRemoteTypes");
1804
- if (!this.updatedRemoteInfos[updatedRemoteInfo.name]) {
1805
- const parsedRemoteInfo = retrieveRemoteInfo({
1806
- hostOptions,
1807
- remoteAlias: updatedRemoteInfo.alias || updatedRemoteInfo.name,
1808
- remote: updatedRemoteInfo.url
1809
- });
1810
- fileLog(`start request manifest`, "consumeTypes", "info");
1811
- this.updatedRemoteInfos[updatedRemoteInfo.name] = yield this.requestRemoteManifest(parsedRemoteInfo, hostOptions);
1812
- fileLog(`end request manifest, this.updatedRemoteInfos[updatedRemoteInfo.name]: ${JSON.stringify(this.updatedRemoteInfos[updatedRemoteInfo.name], null, 2)}`, "updateTypes", "info");
1813
- yield consumeDynamicRemoteTypes();
1814
- }
1815
- if (!once && this.updatedRemoteInfos[updatedRemoteInfo.name]) {
1816
- yield consumeDynamicRemoteTypes();
1817
- }
1818
- }
1819
- } else {
1820
- yield consumeTypes2(loadedRemoteInfo);
1821
- }
1822
- }
1823
- } catch (err) {
1824
- fileLog(`updateTypes fail, ${err}`, "updateTypes", "error");
1825
- }
1826
- });
1827
- }
1828
- }, __name(_a, "DTSManager"), _a);
1829
-
1830
- // src/core/lib/utils.ts
1831
- var import_lodash = __toESM(require("lodash.clonedeepwith"));
1832
- function getDTSManagerConstructor(implementation) {
1833
- if (implementation) {
1834
- const NewConstructor = require(implementation);
1835
- return NewConstructor.default ? NewConstructor.default : NewConstructor;
1836
- }
1837
- return DTSManager;
1838
- }
1839
- __name(getDTSManagerConstructor, "getDTSManagerConstructor");
1840
- var validateOptions = /* @__PURE__ */ __name((options) => {
1841
- if (!options.moduleFederationConfig) {
1842
- throw new Error("moduleFederationConfig is required");
1843
- }
1844
- }, "validateOptions");
1845
- function retrieveTypesAssetsInfo(options) {
1846
- let apiTypesPath = "";
1847
- let zipTypesPath = "";
1848
- try {
1849
- const { tsConfig, remoteOptions, mapComponentsToExpose } = retrieveRemoteConfig(options);
1850
- if (!Object.keys(mapComponentsToExpose).length || !tsConfig.files.length) {
1851
- return {
1852
- apiTypesPath,
1853
- zipTypesPath,
1854
- zipName: "",
1855
- apiFileName: ""
1856
- };
1857
- }
1858
- const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
1859
- zipTypesPath = retrieveTypesZipPath(mfTypesPath, remoteOptions);
1860
- if (remoteOptions.generateAPITypes) {
1861
- apiTypesPath = retrieveMfAPITypesPath(tsConfig, remoteOptions);
1862
- }
1863
- return {
1864
- apiTypesPath,
1865
- zipTypesPath,
1866
- zipName: import_path4.default.basename(zipTypesPath),
1867
- apiFileName: import_path4.default.basename(apiTypesPath)
1868
- };
1869
- } catch (err) {
1870
- console.error(import_ansi_colors.default.red(`Unable to compile federated types, ${err}`));
1871
- return {
1872
- apiTypesPath: "",
1873
- zipTypesPath: "",
1874
- zipName: "",
1875
- apiFileName: ""
1876
- };
1877
- }
1878
- }
1879
- __name(retrieveTypesAssetsInfo, "retrieveTypesAssetsInfo");
1880
- function isDebugMode() {
1881
- return Boolean(process.env["FEDERATION_DEBUG"]) || process.env["NODE_ENV"] === "test";
1882
- }
1883
- __name(isDebugMode, "isDebugMode");
1884
- var isTSProject = /* @__PURE__ */ __name((dtsOptions, context = process.cwd()) => {
1885
- if (dtsOptions === false) {
1886
- return false;
1887
- }
1888
- try {
1889
- let filepath = "";
1890
- if (typeof dtsOptions === "object" && dtsOptions.tsConfigPath) {
1891
- filepath = dtsOptions.tsConfigPath;
1892
- } else {
1893
- filepath = import_path4.default.resolve(context, "./tsconfig.json");
1894
- }
1895
- if (!import_path4.default.isAbsolute(filepath)) {
1896
- filepath = import_path4.default.resolve(context, filepath);
1897
- }
1898
- return import_fs2.default.existsSync(filepath);
1899
- } catch (err) {
1900
- return false;
1901
- }
1902
- }, "isTSProject");
1903
- function cloneDeepOptions(options) {
1904
- const excludeKeys = [
1905
- "manifest",
1906
- "async"
1907
- ];
1908
- return (0, import_lodash.default)(options, (value, key) => {
1909
- if (typeof key === "string" && excludeKeys.includes(key)) {
1910
- return false;
1911
- }
1912
- if (typeof value === "function") {
1913
- return false;
1914
- }
1915
- if (key === "extractThirdParty" && Array.isArray(value)) {
1916
- return value.map((item) => {
1917
- return item.toString();
1918
- });
1919
- }
1920
- });
1921
- }
1922
- __name(cloneDeepOptions, "cloneDeepOptions");
1923
- var getEnvHeaders = /* @__PURE__ */ __name(() => {
1924
- const headersStr = (0, import_sdk6.getProcessEnv)()["MF_ENV_HEADERS"] || "{}";
1925
- return __spreadValues({}, JSON.parse(headersStr));
1926
- }, "getEnvHeaders");
1927
- function axiosGet(url, config) {
1928
- return __async(this, null, function* () {
1929
- var _a3, _b;
1930
- const httpAgent = new import_http2.default.Agent({
1931
- family: (_a3 = config == null ? void 0 : config.family) != null ? _a3 : 4
1932
- });
1933
- const httpsAgent = new import_https.default.Agent({
1934
- family: (_b = config == null ? void 0 : config.family) != null ? _b : 4
1935
- });
1936
- return import_axios.default.get(url, __spreadProps(__spreadValues(__spreadValues({
1937
- httpAgent,
1938
- httpsAgent
1939
- }, {
1940
- headers: getEnvHeaders()
1941
- }), config), {
1942
- timeout: (config == null ? void 0 : config.timeout) || 6e4
1943
- }));
1944
- });
1945
- }
1946
- __name(axiosGet, "axiosGet");
1947
-
1948
- // src/core/configurations/remotePlugin.ts
1949
- var defaultOptions2 = {
1950
- tsConfigPath: "./tsconfig.json",
1951
- typesFolder: "@mf-types",
1952
- compiledTypesFolder: "compiled-types",
1953
- hostRemoteTypesFolder: "@mf-types",
1954
- deleteTypesFolder: true,
1955
- additionalFilesToCompile: [],
1956
- compilerInstance: "tsc",
1957
- compileInChildProcess: false,
1958
- implementation: "",
1959
- generateAPITypes: false,
1960
- context: process.cwd(),
1961
- abortOnError: true,
1962
- extractRemoteTypes: false,
1963
- extractThirdParty: false,
1964
- outputDir: "",
1965
- deleteTsConfig: true
1966
- };
1967
- function getEffectiveRootDir(parsedCommandLine) {
1968
- const compilerOptions = parsedCommandLine.options;
1969
- if (compilerOptions.rootDir) {
1970
- return compilerOptions.rootDir;
1971
- }
1972
- const files = parsedCommandLine.fileNames;
1973
- if (files.length > 0) {
1974
- const commonRoot = files.map((file) => (0, import_path5.dirname)(file)).reduce((commonPath, fileDir) => {
1975
- while (!fileDir.startsWith(commonPath)) {
1976
- commonPath = (0, import_path5.dirname)(commonPath);
1977
- }
1978
- return commonPath;
1979
- }, files[0]);
1980
- return commonRoot;
1981
- }
1982
- throw new Error("Can not get effective rootDir, please set compilerOptions.rootDir !");
1983
- }
1984
- __name(getEffectiveRootDir, "getEffectiveRootDir");
1985
- var getDependentFiles = /* @__PURE__ */ __name((rootFiles, configContent, rootDir) => {
1986
- const program = import_typescript.default.createProgram(rootFiles, configContent.options);
1987
- const sourceFiles = program.getSourceFiles();
1988
- const dependentFiles = sourceFiles.map((file) => file.fileName).filter((file) => !file.endsWith(".d.ts") && file.startsWith(rootDir));
1989
- return dependentFiles.length ? dependentFiles : rootFiles;
1990
- }, "getDependentFiles");
1991
- var readTsConfig = /* @__PURE__ */ __name(({ tsConfigPath, typesFolder, compiledTypesFolder, context, additionalFilesToCompile, outputDir }, mapComponentsToExpose) => {
1992
- const resolvedTsConfigPath = (0, import_path5.resolve)(context, tsConfigPath);
1993
- const readResult = import_typescript.default.readConfigFile(resolvedTsConfigPath, import_typescript.default.sys.readFile);
1994
- if (readResult.error) {
1995
- throw new Error(readResult.error.messageText.toString());
1996
- }
1997
- const rawTsConfigJson = readResult.config;
1998
- const configContent = import_typescript.default.parseJsonConfigFileContent(rawTsConfigJson, import_typescript.default.sys, (0, import_path5.dirname)(resolvedTsConfigPath));
1999
- const rootDir = getEffectiveRootDir(configContent);
2000
- const outDir = (0, import_path5.resolve)(context, outputDir || configContent.options.outDir || "dist", typesFolder, compiledTypesFolder);
2001
- const defaultCompilerOptions = {
2002
- rootDir,
2003
- emitDeclarationOnly: true,
2004
- noEmit: false,
2005
- declaration: true,
2006
- outDir
2007
- };
2008
- rawTsConfigJson.compilerOptions = rawTsConfigJson.compilerOptions || {};
2009
- rawTsConfigJson.compilerOptions = __spreadValues(__spreadValues({
2010
- incremental: true,
2011
- tsBuildInfoFile: (0, import_path5.resolve)(context, "node_modules/.cache/mf-types/.tsbuildinfo")
2012
- }, rawTsConfigJson.compilerOptions), defaultCompilerOptions);
2013
- const _a3 = rawTsConfigJson.compilerOptions || {}, { paths, baseUrl } = _a3, restCompilerOptions = __objRest(_a3, ["paths", "baseUrl"]);
2014
- rawTsConfigJson.compilerOptions = restCompilerOptions;
2015
- const outDirWithoutTypesFolder = (0, import_path5.resolve)(context, outputDir || configContent.options.outDir || "dist");
2016
- const excludeExtensions = [
2017
- ".mdx",
2018
- ".md"
2019
- ];
2020
- const rootFiles = [
2021
- ...Object.values(mapComponentsToExpose),
2022
- ...additionalFilesToCompile
2023
- ].filter((filename) => !excludeExtensions.some((ext) => filename.endsWith(ext)));
2024
- const filesToCompile = [
2025
- ...getDependentFiles(rootFiles, configContent, rootDir),
2026
- ...configContent.fileNames.filter((filename) => filename.endsWith(".d.ts") && !filename.startsWith(outDirWithoutTypesFolder))
2027
- ];
2028
- rawTsConfigJson.include = [];
2029
- rawTsConfigJson.files = [
2030
- ...new Set(filesToCompile)
2031
- ];
2032
- rawTsConfigJson.exclude = [];
2033
- "references" in rawTsConfigJson && delete rawTsConfigJson.references;
2034
- rawTsConfigJson.extends = resolvedTsConfigPath;
2035
- if (rawTsConfigJson.compilerOptions.declarationDir) {
2036
- delete rawTsConfigJson.compilerOptions.declarationDir;
2037
- }
2038
- return rawTsConfigJson;
2039
- }, "readTsConfig");
2040
- var TS_EXTENSIONS = [
2041
- "ts",
2042
- "tsx",
2043
- "vue",
2044
- "svelte"
2045
- ];
2046
- var resolveWithExtension = /* @__PURE__ */ __name((exposedPath, context) => {
2047
- if ((0, import_path5.extname)(exposedPath)) {
2048
- return (0, import_path5.resolve)(context, exposedPath);
2049
- }
2050
- for (const extension of TS_EXTENSIONS) {
2051
- const exposedPathWithExtension = (0, import_path5.resolve)(context, `${exposedPath}.${extension}`);
2052
- if ((0, import_fs3.existsSync)(exposedPathWithExtension)) {
2053
- return exposedPathWithExtension;
2054
- }
2055
- }
2056
- return void 0;
2057
- }, "resolveWithExtension");
2058
- var resolveExposes = /* @__PURE__ */ __name((remoteOptions) => {
2059
- const parsedOptions = import_managers2.utils.parseOptions(remoteOptions.moduleFederationConfig.exposes || {}, (item, key) => ({
2060
- exposePath: Array.isArray(item) ? item[0] : item,
2061
- key
2062
- }), (item, key) => ({
2063
- exposePath: Array.isArray(item.import) ? item.import[0] : item.import[0],
2064
- key
2065
- }));
2066
- return parsedOptions.reduce((accumulator, item) => {
2067
- const { exposePath, key } = item[1];
2068
- accumulator[key] = resolveWithExtension(exposePath, remoteOptions.context) || resolveWithExtension((0, import_path5.join)(exposePath, "index"), remoteOptions.context) || exposePath;
2069
- return accumulator;
2070
- }, {});
2071
- }, "resolveExposes");
2072
- var retrieveRemoteConfig = /* @__PURE__ */ __name((options) => {
2073
- validateOptions(options);
2074
- const remoteOptions = __spreadValues(__spreadValues({}, defaultOptions2), options);
2075
- const mapComponentsToExpose = resolveExposes(remoteOptions);
2076
- const tsConfig = readTsConfig(remoteOptions, mapComponentsToExpose);
2077
- if (tsConfig.compilerOptions.incremental && tsConfig.compilerOptions.tsBuildInfoFile && options.deleteTypesFolder !== true) {
2078
- remoteOptions.deleteTypesFolder = false;
2079
- }
2080
- return {
2081
- tsConfig,
2082
- mapComponentsToExpose,
2083
- remoteOptions
2084
- };
2085
- }, "retrieveRemoteConfig");
2086
-
2087
- // src/core/lib/generateTypes.ts
2088
- function generateTypes(options) {
2089
- return __async(this, null, function* () {
2090
- var _a3;
2091
- const DTSManagerConstructor = getDTSManagerConstructor((_a3 = options.remote) == null ? void 0 : _a3.implementation);
2092
- const dtsManager = new DTSManagerConstructor(options);
2093
- return dtsManager.generateTypes();
2094
- });
2095
- }
2096
- __name(generateTypes, "generateTypes");
2097
-
2098
- // src/core/lib/DtsWorker.ts
2099
- var import_path6 = __toESM(require("path"));
2100
-
2101
- // src/core/rpc/index.ts
2102
- var rpc_exports = {};
2103
- __export(rpc_exports, {
2104
- RpcExitError: () => RpcExitError,
2105
- RpcGMCallTypes: () => RpcGMCallTypes,
2106
- createRpcWorker: () => createRpcWorker,
2107
- exposeRpc: () => exposeRpc,
2108
- getRpcWorkerData: () => getRpcWorkerData,
2109
- wrapRpc: () => wrapRpc
2110
- });
2111
-
2112
- // src/core/rpc/expose-rpc.ts
2113
- var import_process = __toESM(require("process"));
2114
-
2115
- // src/core/rpc/types.ts
2116
- var RpcGMCallTypes;
2117
- (function(RpcGMCallTypes2) {
2118
- RpcGMCallTypes2["CALL"] = "mf_call";
2119
- RpcGMCallTypes2["RESOLVE"] = "mf_resolve";
2120
- RpcGMCallTypes2["REJECT"] = "mf_reject";
2121
- RpcGMCallTypes2["EXIT"] = "mf_exit";
2122
- })(RpcGMCallTypes || (RpcGMCallTypes = {}));
2123
-
2124
- // src/core/rpc/expose-rpc.ts
2125
- function exposeRpc(fn) {
2126
- const sendMessage = /* @__PURE__ */ __name((message) => new Promise((resolve4, reject) => {
2127
- if (!import_process.default.send) {
2128
- reject(new Error(`Process ${import_process.default.pid} doesn't have IPC channels`));
2129
- } else if (!import_process.default.connected) {
2130
- reject(new Error(`Process ${import_process.default.pid} doesn't have open IPC channels`));
2131
- } else {
2132
- import_process.default.send(message, void 0, void 0, (error2) => {
2133
- if (error2) {
2134
- reject(error2);
2135
- } else {
2136
- resolve4(void 0);
2137
- }
2138
- });
2139
- }
2140
- }), "sendMessage");
2141
- const handleMessage = /* @__PURE__ */ __name((message) => __async(this, null, function* () {
2142
- if (message.type === RpcGMCallTypes.CALL) {
2143
- if (!import_process.default.send) {
2144
- return;
2145
- }
2146
- let value, error2;
2147
- try {
2148
- value = yield fn(...message.args);
2149
- } catch (fnError) {
2150
- error2 = fnError;
2151
- }
2152
- try {
2153
- if (error2) {
2154
- yield sendMessage({
2155
- type: RpcGMCallTypes.REJECT,
2156
- id: message.id,
2157
- error: error2
2158
- });
2159
- } else {
2160
- yield sendMessage({
2161
- type: RpcGMCallTypes.RESOLVE,
2162
- id: message.id,
2163
- value
2164
- });
2165
- }
2166
- } catch (sendError) {
2167
- if (error2) {
2168
- if (error2 instanceof Error) {
2169
- console.error(error2);
2170
- }
2171
- }
2172
- console.error(sendError);
2173
- }
2174
- }
2175
- }), "handleMessage");
2176
- import_process.default.on("message", handleMessage);
2177
- }
2178
- __name(exposeRpc, "exposeRpc");
2179
-
2180
- // src/core/rpc/rpc-error.ts
2181
- var _a2;
2182
- var RpcExitError = (_a2 = class extends Error {
2183
- constructor(message, code, signal) {
2184
- super(message);
2185
- __publicField(this, "code");
2186
- __publicField(this, "signal");
2187
- this.code = code, this.signal = signal;
2188
- this.name = "RpcExitError";
2189
- }
2190
- }, __name(_a2, "RpcExitError"), _a2);
2191
-
2192
- // src/core/rpc/wrap-rpc.ts
2193
- function createControlledPromise() {
2194
- let resolve4 = /* @__PURE__ */ __name(() => void 0, "resolve");
2195
- let reject = /* @__PURE__ */ __name(() => void 0, "reject");
2196
- const promise = new Promise((aResolve, aReject) => {
2197
- resolve4 = aResolve;
2198
- reject = aReject;
2199
- });
2200
- return {
2201
- promise,
2202
- resolve: resolve4,
2203
- reject
2204
- };
2205
- }
2206
- __name(createControlledPromise, "createControlledPromise");
2207
- function wrapRpc(childProcess, options) {
2208
- return (...args) => __async(this, null, function* () {
2209
- if (!childProcess.send) {
2210
- throw new Error(`Process ${childProcess.pid} doesn't have IPC channels`);
2211
- } else if (!childProcess.connected) {
2212
- throw new Error(`Process ${childProcess.pid} doesn't have open IPC channels`);
2213
- }
2214
- const { id, once } = options;
2215
- const { promise: resultPromise, resolve: resolveResult, reject: rejectResult } = createControlledPromise();
2216
- const { promise: sendPromise, resolve: resolveSend, reject: rejectSend } = createControlledPromise();
2217
- const handleMessage = /* @__PURE__ */ __name((message) => {
2218
- if ((message == null ? void 0 : message.id) === id) {
2219
- if (message.type === RpcGMCallTypes.RESOLVE) {
2220
- resolveResult(message.value);
2221
- } else if (message.type === RpcGMCallTypes.REJECT) {
2222
- rejectResult(message.error);
2223
- }
2224
- }
2225
- if (once && (childProcess == null ? void 0 : childProcess.kill)) {
2226
- childProcess.kill("SIGTERM");
2227
- }
2228
- }, "handleMessage");
2229
- const handleClose = /* @__PURE__ */ __name((code, signal) => {
2230
- rejectResult(new RpcExitError(code ? `Process ${childProcess.pid} exited with code ${code}${signal ? ` [${signal}]` : ""}` : `Process ${childProcess.pid} exited${signal ? ` [${signal}]` : ""}`, code, signal));
2231
- removeHandlers();
2232
- }, "handleClose");
2233
- const removeHandlers = /* @__PURE__ */ __name(() => {
2234
- childProcess.off("message", handleMessage);
2235
- childProcess.off("close", handleClose);
2236
- }, "removeHandlers");
2237
- if (once) {
2238
- childProcess.once("message", handleMessage);
2239
- } else {
2240
- childProcess.on("message", handleMessage);
2241
- }
2242
- childProcess.on("close", handleClose);
2243
- childProcess.send({
2244
- type: RpcGMCallTypes.CALL,
2245
- id,
2246
- args
2247
- }, (error2) => {
2248
- if (error2) {
2249
- rejectSend(error2);
2250
- removeHandlers();
2251
- } else {
2252
- resolveSend(void 0);
2253
- }
2254
- });
2255
- return sendPromise.then(() => resultPromise);
2256
- });
2257
- }
2258
- __name(wrapRpc, "wrapRpc");
2259
-
2260
- // src/core/rpc/rpc-worker.ts
2261
- var child_process = __toESM(require("child_process"));
2262
- var process3 = __toESM(require("process"));
2263
- var import_crypto2 = require("crypto");
2264
- var FEDERATION_WORKER_DATA_ENV_KEY = "VMOK_WORKER_DATA_ENV";
2265
- function createRpcWorker(modulePath, data, memoryLimit, once) {
2266
- const options = {
2267
- env: __spreadProps(__spreadValues({}, process3.env), {
2268
- [FEDERATION_WORKER_DATA_ENV_KEY]: JSON.stringify(data || {})
2269
- }),
2270
- stdio: [
2271
- "inherit",
2272
- "inherit",
2273
- "inherit",
2274
- "ipc"
2275
- ],
2276
- serialization: "advanced"
2277
- };
2278
- if (memoryLimit) {
2279
- options.execArgv = [
2280
- `--max-old-space-size=${memoryLimit}`
2281
- ];
2282
- }
2283
- let childProcess, remoteMethod;
2284
- const id = (0, import_crypto2.randomUUID)();
2285
- const worker = {
2286
- connect(...args) {
2287
- if (childProcess && !childProcess.connected) {
2288
- childProcess.send({
2289
- type: RpcGMCallTypes.EXIT,
2290
- id
2291
- });
2292
- childProcess = void 0;
2293
- remoteMethod = void 0;
2294
- }
2295
- if (!(childProcess == null ? void 0 : childProcess.connected)) {
2296
- childProcess = child_process.fork(modulePath, options);
2297
- remoteMethod = wrapRpc(childProcess, {
2298
- id,
2299
- once
2300
- });
2301
- }
2302
- if (!remoteMethod) {
2303
- return Promise.reject(new Error("Worker is not connected - cannot perform RPC."));
2304
- }
2305
- return remoteMethod(...args);
2306
- },
2307
- terminate() {
2308
- try {
2309
- if (childProcess.connected) {
2310
- childProcess.send({
2311
- type: RpcGMCallTypes.EXIT,
2312
- id
2313
- }, (err) => {
2314
- if (err) {
2315
- console.error("Error sending message:", err);
2316
- }
2317
- });
2318
- }
2319
- } catch (error2) {
2320
- if (error2.code === "EPIPE") {
2321
- console.error("Pipe closed before message could be sent:", error2);
2322
- } else {
2323
- console.error("Unexpected error:", error2);
2324
- }
2325
- }
2326
- childProcess = void 0;
2327
- remoteMethod = void 0;
2328
- },
2329
- get connected() {
2330
- return Boolean(childProcess == null ? void 0 : childProcess.connected);
2331
- },
2332
- get process() {
2333
- return childProcess;
2334
- },
2335
- get id() {
2336
- return id;
2337
- }
2338
- };
2339
- return worker;
2340
- }
2341
- __name(createRpcWorker, "createRpcWorker");
2342
- function getRpcWorkerData() {
2343
- return JSON.parse(process3.env[FEDERATION_WORKER_DATA_ENV_KEY] || "{}");
2344
- }
2345
- __name(getRpcWorkerData, "getRpcWorkerData");
2346
-
2347
- // src/core/lib/DtsWorker.ts
2348
- var _DtsWorker = class _DtsWorker {
2349
- constructor(options) {
2350
- __publicField(this, "rpcWorker");
2351
- __publicField(this, "_options");
2352
- __publicField(this, "_res");
2353
- this._options = cloneDeepOptions(options);
2354
- this.removeUnSerializationOptions();
2355
- this.rpcWorker = createRpcWorker(import_path6.default.resolve(__dirname, "./fork-generate-dts.js"), {}, void 0, true);
2356
- this._res = this.rpcWorker.connect(this._options);
2357
- }
2358
- removeUnSerializationOptions() {
2359
- var _a3, _b, _c, _d, _e, _f, _g, _h;
2360
- if ((_b = (_a3 = this._options.remote) == null ? void 0 : _a3.moduleFederationConfig) == null ? void 0 : _b.manifest) {
2361
- (_d = (_c = this._options.remote) == null ? void 0 : _c.moduleFederationConfig) == null ? true : delete _d.manifest;
2362
- }
2363
- if ((_f = (_e = this._options.host) == null ? void 0 : _e.moduleFederationConfig) == null ? void 0 : _f.manifest) {
2364
- (_h = (_g = this._options.host) == null ? void 0 : _g.moduleFederationConfig) == null ? true : delete _h.manifest;
2365
- }
2366
- }
2367
- get controlledPromise() {
2368
- const ensureChildProcessExit = /* @__PURE__ */ __name(() => {
2369
- var _a3;
2370
- try {
2371
- const pid = (_a3 = this.rpcWorker.process) == null ? void 0 : _a3.pid;
2372
- const rootPid = process.pid;
2373
- if (pid && rootPid !== pid) {
2374
- process.kill(pid, 0);
2375
- }
2376
- } catch (error2) {
2377
- if (isDebugMode()) {
2378
- console.error(error2);
2379
- }
2380
- }
2381
- }, "ensureChildProcessExit");
2382
- return Promise.resolve(this._res).then(() => {
2383
- this.exit();
2384
- ensureChildProcessExit();
2385
- }).catch((err) => {
2386
- if (isDebugMode()) {
2387
- console.error(err);
2388
- }
2389
- ensureChildProcessExit();
2390
- });
2391
- }
2392
- exit() {
2393
- var _a3;
2394
- try {
2395
- (_a3 = this.rpcWorker) == null ? void 0 : _a3.terminate();
2396
- } catch (err) {
2397
- if (isDebugMode()) {
2398
- console.error(err);
2399
- }
2400
- }
2401
- }
2402
- };
2403
- __name(_DtsWorker, "DtsWorker");
2404
- var DtsWorker = _DtsWorker;
2405
-
2406
- // src/core/lib/generateTypesInChildProcess.ts
2407
- function generateTypesInChildProcess(options) {
2408
- return __async(this, null, function* () {
2409
- const dtsWorker = new DtsWorker(options);
2410
- return dtsWorker.controlledPromise;
2411
- });
2412
- }
2413
- __name(generateTypesInChildProcess, "generateTypesInChildProcess");
2414
-
2415
- // src/core/lib/consumeTypes.ts
2416
- function consumeTypes(options) {
2417
- return __async(this, null, function* () {
2418
- var _a3;
2419
- const DTSManagerConstructor = getDTSManagerConstructor((_a3 = options.host) == null ? void 0 : _a3.implementation);
2420
- const dtsManager = new DTSManagerConstructor(options);
2421
- yield dtsManager.consumeTypes();
2422
- });
2423
- }
2424
- __name(consumeTypes, "consumeTypes");
2425
- // Annotate the CommonJS export names for ESM import in node:
2426
- 0 && (module.exports = {
2427
- DTSManager,
2428
- DtsWorker,
2429
- HOST_API_TYPES_FILE_NAME,
2430
- REMOTE_ALIAS_IDENTIFIER,
2431
- REMOTE_API_TYPES_FILE_NAME,
2432
- consumeTypes,
2433
- generateTypes,
2434
- generateTypesInChildProcess,
2435
- getDTSManagerConstructor,
2436
- isTSProject,
2437
- retrieveHostConfig,
2438
- retrieveMfTypesPath,
2439
- retrieveOriginalOutDir,
2440
- retrieveRemoteConfig,
2441
- retrieveTypesAssetsInfo,
2442
- retrieveTypesZipPath,
2443
- rpc,
2444
- validateOptions
2445
27
  });
28
+ exports.validateOptions = require_expose_rpc.validateOptions;