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