@module-federation/dts-plugin 0.0.0-feat-support-bridge-react-router-v7-20251015102312

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 (40) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/dist/CHANGELOG.md +1065 -0
  4. package/dist/DTSManager-b15Gfat3.d.ts +53 -0
  5. package/dist/DTSManagerOptions-QVchWb0x.d.ts +32 -0
  6. package/dist/DtsWorker-BrHsGz8C.d.ts +56 -0
  7. package/dist/README.md +1 -0
  8. package/dist/core.d.mts +68 -0
  9. package/dist/core.d.ts +68 -0
  10. package/dist/core.js +2365 -0
  11. package/dist/dynamic-remote-type-hints-plugin.d.mts +5 -0
  12. package/dist/dynamic-remote-type-hints-plugin.d.ts +5 -0
  13. package/dist/dynamic-remote-type-hints-plugin.js +196 -0
  14. package/dist/esm/chunk-2GDMDG2O.js +282 -0
  15. package/dist/esm/chunk-647HGGGS.js +241 -0
  16. package/dist/esm/chunk-ETMHGGQH.js +1564 -0
  17. package/dist/esm/chunk-G65LOFTY.js +24 -0
  18. package/dist/esm/chunk-WWV5RWOP.js +902 -0
  19. package/dist/esm/core.js +44 -0
  20. package/dist/esm/dynamic-remote-type-hints-plugin.js +73 -0
  21. package/dist/esm/fork-dev-worker.js +145 -0
  22. package/dist/esm/fork-generate-dts.js +27 -0
  23. package/dist/esm/index.js +655 -0
  24. package/dist/esm/start-broker.js +36 -0
  25. package/dist/fork-dev-worker.d.mts +15 -0
  26. package/dist/fork-dev-worker.d.ts +15 -0
  27. package/dist/fork-dev-worker.js +2844 -0
  28. package/dist/fork-generate-dts.d.mts +10 -0
  29. package/dist/fork-generate-dts.d.ts +10 -0
  30. package/dist/fork-generate-dts.js +2015 -0
  31. package/dist/iife/launch-web-client.js +152 -0
  32. package/dist/index.d.mts +56 -0
  33. package/dist/index.d.ts +56 -0
  34. package/dist/index.js +2996 -0
  35. package/dist/package.json +87 -0
  36. package/dist/start-broker.d.mts +42 -0
  37. package/dist/start-broker.d.ts +42 -0
  38. package/dist/start-broker.js +958 -0
  39. package/dist/utils-BjKKtOcx.d.ts +16 -0
  40. package/package.json +87 -0
package/dist/index.js ADDED
@@ -0,0 +1,2996 @@
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((resolve5, 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 ? resolve5(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
79
+ step((generator = generator.apply(__this, __arguments)).next());
80
+ });
81
+ };
82
+
83
+ // src/index.ts
84
+ var src_exports = {};
85
+ __export(src_exports, {
86
+ DtsPlugin: () => DtsPlugin,
87
+ consumeTypesAPI: () => consumeTypesAPI,
88
+ generateTypesAPI: () => generateTypesAPI,
89
+ isTSProject: () => isTSProject,
90
+ normalizeConsumeTypesOptions: () => normalizeConsumeTypesOptions,
91
+ normalizeDtsOptions: () => normalizeDtsOptions,
92
+ normalizeGenerateTypesOptions: () => normalizeGenerateTypesOptions
93
+ });
94
+ module.exports = __toCommonJS(src_exports);
95
+
96
+ // src/plugins/DevPlugin.ts
97
+ var import_fs_extra4 = __toESM(require("fs-extra"));
98
+ var import_path9 = __toESM(require("path"));
99
+
100
+ // src/dev-worker/createDevWorker.ts
101
+ var path5 = __toESM(require("path"));
102
+ var fse2 = __toESM(require("fs-extra"));
103
+
104
+ // src/dev-worker/DevWorker.ts
105
+ var import_path7 = __toESM(require("path"));
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_extra = 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_sdk = require("@module-federation/sdk");
145
+ var STARTS_WITH_SLASH = /^\//;
146
+ var DEFINITION_FILE_EXTENSION = ".d.ts";
147
+ var retrieveMfTypesPath = /* @__PURE__ */ __name((tsConfig, remoteOptions) => (0, import_path.normalize)(tsConfig.compilerOptions.outDir.replace(remoteOptions.compiledTypesFolder, "")), "retrieveMfTypesPath");
148
+ var retrieveOriginalOutDir = /* @__PURE__ */ __name((tsConfig, remoteOptions) => (0, import_path.normalize)(tsConfig.compilerOptions.outDir.replace(remoteOptions.compiledTypesFolder, "").replace(remoteOptions.typesFolder, "")), "retrieveOriginalOutDir");
149
+ var retrieveMfAPITypesPath = /* @__PURE__ */ __name((tsConfig, remoteOptions) => (0, import_path.join)(retrieveOriginalOutDir(tsConfig, remoteOptions), `${remoteOptions.typesFolder}.d.ts`), "retrieveMfAPITypesPath");
150
+ function writeTempTsConfig(tsConfig, context, name, cwd) {
151
+ const createHash = /* @__PURE__ */ __name((contents) => {
152
+ return import_crypto.default.createHash("md5").update(contents).digest("hex");
153
+ }, "createHash");
154
+ const hash = createHash(`${JSON.stringify(tsConfig)}${name}${Date.now()}`);
155
+ const tempTsConfigJsonPath = (0, import_path.resolve)(cwd != null ? cwd : context, "node_modules", import_sdk.TEMP_DIR, `tsconfig.${hash}.json`);
156
+ (0, import_fs_extra.ensureDirSync)((0, import_path.dirname)(tempTsConfigJsonPath));
157
+ (0, import_fs_extra.writeFileSync)(tempTsConfigJsonPath, JSON.stringify(tsConfig, null, 2));
158
+ return tempTsConfigJsonPath;
159
+ }
160
+ __name(writeTempTsConfig, "writeTempTsConfig");
161
+ var removeExt = /* @__PURE__ */ __name((f) => {
162
+ const vueExt = ".vue";
163
+ const ext = (0, import_path.extname)(f);
164
+ if (ext === vueExt) {
165
+ return f;
166
+ }
167
+ const regexPattern = new RegExp(`\\${ext}$`);
168
+ return f.replace(regexPattern, "");
169
+ }, "removeExt");
170
+ function getExposeKey(options) {
171
+ const { filePath, rootDir, outDir, mapExposeToEntry } = options;
172
+ const relativeFilePath = (0, import_path.relative)(outDir, filePath.replace(new RegExp(`\\.d.ts$`), ""));
173
+ return mapExposeToEntry[relativeFilePath];
174
+ }
175
+ __name(getExposeKey, "getExposeKey");
176
+ var processTypesFile = /* @__PURE__ */ __name((options) => __async(void 0, null, function* () {
177
+ const { outDir, filePath, rootDir, cb, mapExposeToEntry, mfTypePath } = options;
178
+ if (!(0, import_fs_extra.existsSync)(filePath)) {
179
+ return;
180
+ }
181
+ const stats = yield (0, import_promises.stat)(filePath);
182
+ if (stats.isDirectory()) {
183
+ const files = yield (0, import_promises.readdir)(filePath);
184
+ yield Promise.all(files.map((file) => processTypesFile(__spreadProps(__spreadValues({}, options), {
185
+ filePath: (0, import_path.join)(filePath, file)
186
+ }))));
187
+ } else if (filePath.endsWith(".d.ts")) {
188
+ const exposeKey = getExposeKey({
189
+ filePath,
190
+ rootDir,
191
+ outDir,
192
+ mapExposeToEntry
193
+ });
194
+ if (exposeKey) {
195
+ const sourceEntry = exposeKey === "." ? "index" : exposeKey;
196
+ const mfeTypeEntry = (0, import_path.join)(mfTypePath, `${sourceEntry}${DEFINITION_FILE_EXTENSION}`);
197
+ const mfeTypeEntryDirectory = (0, import_path.dirname)(mfeTypeEntry);
198
+ const relativePathToOutput = (0, import_path.relative)(mfeTypeEntryDirectory, filePath).replace(DEFINITION_FILE_EXTENSION, "").replace(STARTS_WITH_SLASH, "").split(import_path.sep).join("/");
199
+ (0, import_fs_extra.ensureDirSync)(mfeTypeEntryDirectory);
200
+ yield (0, import_promises.writeFile)(mfeTypeEntry, `export * from './${relativePathToOutput}';
201
+ export { default } from './${relativePathToOutput}';`);
202
+ }
203
+ const content = yield (0, import_promises.readFile)(filePath, "utf8");
204
+ cb(content);
205
+ }
206
+ }), "processTypesFile");
207
+ var compileTs = /* @__PURE__ */ __name((mapComponentsToExpose, tsConfig, remoteOptions) => __async(void 0, null, function* () {
208
+ var _a3, _b, _c, _d;
209
+ if (!Object.keys(mapComponentsToExpose).length) {
210
+ return;
211
+ }
212
+ const { compilerOptions } = tsConfig;
213
+ 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);
214
+ try {
215
+ const mfTypePath = retrieveMfTypesPath(tsConfig, remoteOptions);
216
+ const thirdPartyExtractor = new import_third_party_dts_extractor.ThirdPartyExtractor({
217
+ destDir: (0, import_path.resolve)(mfTypePath, "node_modules"),
218
+ context: remoteOptions.context,
219
+ exclude: typeof remoteOptions.extractThirdParty === "object" ? remoteOptions.extractThirdParty.exclude : void 0
220
+ });
221
+ const execPromise = import_util.default.promisify(import_child_process.exec);
222
+ const cmd = `npx ${remoteOptions.compilerInstance} --project '${tempTsConfigJsonPath}'`;
223
+ try {
224
+ yield execPromise(cmd, {
225
+ cwd: typeof remoteOptions.moduleFederationConfig.dts !== "boolean" ? (_d = (_c = remoteOptions.moduleFederationConfig.dts) == null ? void 0 : _c.cwd) != null ? _d : void 0 : void 0
226
+ });
227
+ } catch (err) {
228
+ if (compilerOptions.tsBuildInfoFile) {
229
+ try {
230
+ yield (0, import_promises.rm)(compilerOptions.tsBuildInfoFile);
231
+ } catch (e) {
232
+ }
233
+ }
234
+ throw new Error((0, import_error_codes.getShortErrorMsg)(import_error_codes.TYPE_001, import_error_codes.typeDescMap, {
235
+ cmd
236
+ }));
237
+ }
238
+ const mapExposeToEntry = Object.fromEntries(Object.entries(mapComponentsToExpose).map(([exposed, filename]) => {
239
+ const normalizedFileName = (0, import_path.normalize)(filename);
240
+ let relativeFileName = "";
241
+ if ((0, import_path.isAbsolute)(normalizedFileName)) {
242
+ relativeFileName = (0, import_path.relative)(tsConfig.compilerOptions.rootDir, normalizedFileName);
243
+ } else {
244
+ relativeFileName = (0, import_path.relative)(tsConfig.compilerOptions.rootDir, (0, import_path.resolve)(remoteOptions.context, normalizedFileName));
245
+ }
246
+ return [
247
+ removeExt(relativeFileName),
248
+ exposed
249
+ ];
250
+ }));
251
+ const cb = remoteOptions.extractThirdParty ? thirdPartyExtractor.collectPkgs.bind(thirdPartyExtractor) : () => void 0;
252
+ yield processTypesFile({
253
+ outDir: compilerOptions.outDir,
254
+ filePath: compilerOptions.outDir,
255
+ rootDir: compilerOptions.rootDir,
256
+ mfTypePath,
257
+ cb,
258
+ mapExposeToEntry
259
+ });
260
+ if (remoteOptions.extractThirdParty) {
261
+ yield thirdPartyExtractor.copyDts();
262
+ }
263
+ yield (0, import_promises.rm)(tempTsConfigJsonPath);
264
+ } catch (err) {
265
+ throw err;
266
+ }
267
+ }), "compileTs");
268
+
269
+ // src/server/message/Message.ts
270
+ var _Message = class _Message {
271
+ constructor(type, kind) {
272
+ __publicField(this, "type");
273
+ __publicField(this, "kind");
274
+ __publicField(this, "time");
275
+ this.type = type;
276
+ this.kind = kind;
277
+ this.time = Date.now();
278
+ }
279
+ };
280
+ __name(_Message, "Message");
281
+ var Message = _Message;
282
+
283
+ // src/server/message/API/API.ts
284
+ var APIKind;
285
+ (function(APIKind2) {
286
+ APIKind2["UPDATE_SUBSCRIBER"] = "UPDATE_SUBSCRIBER";
287
+ APIKind2["RELOAD_WEB_CLIENT"] = "RELOAD_WEB_CLIENT";
288
+ APIKind2["FETCH_TYPES"] = "FETCH_TYPES";
289
+ })(APIKind || (APIKind = {}));
290
+ var _API = class _API extends Message {
291
+ constructor(content, kind) {
292
+ super("API", kind);
293
+ __publicField(this, "code");
294
+ __publicField(this, "payload");
295
+ const { code, payload } = content;
296
+ this.code = code;
297
+ this.payload = payload;
298
+ }
299
+ };
300
+ __name(_API, "API");
301
+ var API = _API;
302
+
303
+ // src/server/message/API/UpdateSubscriber.ts
304
+ var _UpdateSubscriberAPI = class _UpdateSubscriberAPI extends API {
305
+ constructor(payload) {
306
+ super({
307
+ code: 0,
308
+ payload
309
+ }, APIKind.UPDATE_SUBSCRIBER);
310
+ }
311
+ };
312
+ __name(_UpdateSubscriberAPI, "UpdateSubscriberAPI");
313
+ var UpdateSubscriberAPI = _UpdateSubscriberAPI;
314
+
315
+ // src/server/message/API/ReloadWebClient.ts
316
+ var _ReloadWebClientAPI = class _ReloadWebClientAPI extends API {
317
+ constructor(payload) {
318
+ super({
319
+ code: 0,
320
+ payload
321
+ }, APIKind.RELOAD_WEB_CLIENT);
322
+ }
323
+ };
324
+ __name(_ReloadWebClientAPI, "ReloadWebClientAPI");
325
+ var ReloadWebClientAPI = _ReloadWebClientAPI;
326
+
327
+ // src/server/message/API/FetchTypes.ts
328
+ var _FetchTypesAPI = class _FetchTypesAPI extends API {
329
+ constructor(payload) {
330
+ super({
331
+ code: 0,
332
+ payload
333
+ }, APIKind.FETCH_TYPES);
334
+ }
335
+ };
336
+ __name(_FetchTypesAPI, "FetchTypesAPI");
337
+ var FetchTypesAPI = _FetchTypesAPI;
338
+
339
+ // src/server/utils/index.ts
340
+ var import_sdk3 = require("@module-federation/sdk");
341
+
342
+ // src/server/utils/logTransform.ts
343
+ var import_chalk = __toESM(require("chalk"));
344
+
345
+ // src/server/message/Log/Log.ts
346
+ var LogLevel;
347
+ (function(LogLevel2) {
348
+ LogLevel2["LOG"] = "LOG";
349
+ LogLevel2["WARN"] = "WARN";
350
+ LogLevel2["ERROR"] = "ERROR";
351
+ })(LogLevel || (LogLevel = {}));
352
+ var LogKind;
353
+ (function(LogKind2) {
354
+ LogKind2["BrokerExitLog"] = "BrokerExitLog";
355
+ LogKind2["PublisherRegisteredLog"] = "PublisherRegisteredLog";
356
+ })(LogKind || (LogKind = {}));
357
+ var _Log = class _Log extends Message {
358
+ constructor(level, kind, ignoreVerbose = false) {
359
+ super("Log", kind);
360
+ __publicField(this, "level");
361
+ __publicField(this, "ignoreVerbose", false);
362
+ this.level = level;
363
+ this.ignoreVerbose = ignoreVerbose;
364
+ }
365
+ };
366
+ __name(_Log, "Log");
367
+ var Log = _Log;
368
+
369
+ // src/server/message/Log/BrokerExitLog.ts
370
+ var _BrokerExitLog = class _BrokerExitLog extends Log {
371
+ constructor() {
372
+ super(LogLevel.LOG, LogKind.BrokerExitLog);
373
+ }
374
+ };
375
+ __name(_BrokerExitLog, "BrokerExitLog");
376
+ var BrokerExitLog = _BrokerExitLog;
377
+
378
+ // src/server/utils/log.ts
379
+ var import_sdk2 = require("@module-federation/sdk");
380
+ var log4js = __toESM(require("log4js"));
381
+
382
+ // src/server/constant.ts
383
+ var DEFAULT_WEB_SOCKET_PORT = 16322;
384
+ var WEB_SOCKET_CONNECT_MAGIC_ID = "1hpzW-zo2z-o8io-gfmV1-2cb1d82";
385
+ var MF_SERVER_IDENTIFIER = "Module Federation DTS";
386
+ var WEB_CLIENT_OPTIONS_IDENTIFIER = "__WEB_CLIENT_OPTIONS__";
387
+ var UpdateMode;
388
+ (function(UpdateMode2) {
389
+ UpdateMode2["POSITIVE"] = "POSITIVE";
390
+ UpdateMode2["PASSIVE"] = "PASSIVE";
391
+ })(UpdateMode || (UpdateMode = {}));
392
+
393
+ // src/server/utils/log.ts
394
+ var logger = (0, import_sdk2.createLogger)(`[ ${MF_SERVER_IDENTIFIER} ]`);
395
+ function fileLog(msg, module2, level) {
396
+ var _a3, _b;
397
+ if (!((_a3 = process == null ? void 0 : process.env) == null ? void 0 : _a3["FEDERATION_DEBUG"])) {
398
+ return;
399
+ }
400
+ log4js.configure({
401
+ appenders: {
402
+ [module2]: {
403
+ type: "file",
404
+ filename: ".mf/typesGenerate.log"
405
+ },
406
+ default: {
407
+ type: "file",
408
+ filename: ".mf/typesGenerate.log"
409
+ }
410
+ },
411
+ categories: {
412
+ [module2]: {
413
+ appenders: [
414
+ module2
415
+ ],
416
+ level: "error"
417
+ },
418
+ default: {
419
+ appenders: [
420
+ "default"
421
+ ],
422
+ level: "trace"
423
+ }
424
+ }
425
+ });
426
+ const logger4 = log4js.getLogger(module2);
427
+ logger4.level = "debug";
428
+ (_b = logger4[level]) == null ? void 0 : _b.call(logger4, msg);
429
+ }
430
+ __name(fileLog, "fileLog");
431
+ function error(error2, action, from) {
432
+ const err = error2 instanceof Error ? error2 : new Error(`${action} error`);
433
+ fileLog(`[${action}] error: ${err}`, from, "fatal");
434
+ return err.toString();
435
+ }
436
+ __name(error, "error");
437
+
438
+ // src/server/utils/getIPV4.ts
439
+ var import_os = __toESM(require("os"));
440
+ var localIpv4 = "127.0.0.1";
441
+ var getIpv4Interfaces = /* @__PURE__ */ __name(() => {
442
+ try {
443
+ const interfaces = import_os.default.networkInterfaces();
444
+ const ipv4Interfaces = [];
445
+ Object.values(interfaces).forEach((detail) => {
446
+ detail == null ? void 0 : detail.forEach((detail2) => {
447
+ const familyV4Value = typeof detail2.family === "string" ? "IPv4" : 4;
448
+ if (detail2.family === familyV4Value && detail2.address !== localIpv4) {
449
+ ipv4Interfaces.push(detail2);
450
+ }
451
+ });
452
+ });
453
+ return ipv4Interfaces;
454
+ } catch (_err) {
455
+ return [];
456
+ }
457
+ }, "getIpv4Interfaces");
458
+ var getIPV4 = /* @__PURE__ */ __name(() => {
459
+ const ipv4Interfaces = getIpv4Interfaces();
460
+ const ipv4Interface = ipv4Interfaces[0] || {
461
+ address: localIpv4
462
+ };
463
+ return ipv4Interface.address;
464
+ }, "getIPV4");
465
+
466
+ // src/server/utils/index.ts
467
+ function getIdentifier(options) {
468
+ const { ip, name } = options;
469
+ return `mf ${import_sdk3.SEPARATOR}${name}${ip ? `${import_sdk3.SEPARATOR}${ip}` : ""}`;
470
+ }
471
+ __name(getIdentifier, "getIdentifier");
472
+
473
+ // src/server/Publisher.ts
474
+ var _Publisher = class _Publisher {
475
+ constructor(ctx) {
476
+ __publicField(this, "_ip");
477
+ __publicField(this, "_name");
478
+ __publicField(this, "_remoteTypeTarPath");
479
+ __publicField(this, "_subscribers");
480
+ __publicField(this, "_ws");
481
+ __publicField(this, "dynamicRemoteMap");
482
+ this._name = ctx.name;
483
+ this._ip = ctx.ip;
484
+ this._remoteTypeTarPath = ctx.remoteTypeTarPath;
485
+ this._subscribers = /* @__PURE__ */ new Map();
486
+ this._ws = ctx.ws;
487
+ this.dynamicRemoteMap = /* @__PURE__ */ new Map();
488
+ }
489
+ get identifier() {
490
+ return getIdentifier({
491
+ name: this._name,
492
+ ip: this._ip
493
+ });
494
+ }
495
+ get name() {
496
+ return this._name;
497
+ }
498
+ get ip() {
499
+ return this._ip;
500
+ }
501
+ get remoteTypeTarPath() {
502
+ return this._remoteTypeTarPath;
503
+ }
504
+ get hasSubscribes() {
505
+ return Boolean(this._subscribers.size);
506
+ }
507
+ get subscribers() {
508
+ return this._subscribers;
509
+ }
510
+ addSubscriber(identifier, subscriber) {
511
+ fileLog(`${this.name} set subscriber: ${identifier}`, "Publisher", "info");
512
+ this._subscribers.set(identifier, subscriber);
513
+ }
514
+ removeSubscriber(identifier) {
515
+ if (this._subscribers.has(identifier)) {
516
+ fileLog(`${this.name} removeSubscriber: ${identifier}`, "Publisher", "warn");
517
+ this._subscribers.delete(identifier);
518
+ }
519
+ }
520
+ notifySubscriber(subscriberIdentifier, options) {
521
+ const subscriber = this._subscribers.get(subscriberIdentifier);
522
+ if (!subscriber) {
523
+ fileLog(`[notifySubscriber] ${this.name} notifySubscriber: ${subscriberIdentifier}, does not exits`, "Publisher", "error");
524
+ return;
525
+ }
526
+ const api = new UpdateSubscriberAPI(options);
527
+ subscriber.send(JSON.stringify(api));
528
+ fileLog(`[notifySubscriber] ${this.name} notifySubscriber: ${JSON.stringify(subscriberIdentifier)}, message: ${JSON.stringify(api)}`, "Publisher", "info");
529
+ }
530
+ fetchRemoteTypes(options) {
531
+ fileLog(`[fetchRemoteTypes] ${this.name} fetchRemoteTypes, options: ${JSON.stringify(options)}, ws: ${Boolean(this._ws)}`, "Publisher", "info");
532
+ if (!this._ws) {
533
+ return;
534
+ }
535
+ const api = new FetchTypesAPI(options);
536
+ this._ws.send(JSON.stringify(api));
537
+ }
538
+ notifySubscribers(options) {
539
+ const api = new UpdateSubscriberAPI(options);
540
+ this.broadcast(api);
541
+ }
542
+ broadcast(message) {
543
+ if (this.hasSubscribes) {
544
+ this._subscribers.forEach((subscriber, key) => {
545
+ fileLog(`[BroadCast] ${this.name} notifySubscriber: ${key}, PID: ${process.pid}, message: ${JSON.stringify(message)}`, "Publisher", "info");
546
+ subscriber.send(JSON.stringify(message));
547
+ });
548
+ } else {
549
+ fileLog(`[BroadCast] ${this.name}'s subscribe is empty`, "Publisher", "warn");
550
+ }
551
+ }
552
+ close() {
553
+ this._ws = void 0;
554
+ this._subscribers.forEach((_subscriber, identifier) => {
555
+ fileLog(`[BroadCast] close ${this.name} remove: ${identifier}`, "Publisher", "warn");
556
+ this.removeSubscriber(identifier);
557
+ });
558
+ }
559
+ };
560
+ __name(_Publisher, "Publisher");
561
+ var Publisher = _Publisher;
562
+
563
+ // src/server/DevServer.ts
564
+ var import_isomorphic_ws2 = __toESM(require("isomorphic-ws"));
565
+
566
+ // src/server/broker/Broker.ts
567
+ var import_http = require("http");
568
+ var import_isomorphic_ws = __toESM(require("isomorphic-ws"));
569
+ var import_node_schedule = __toESM(require("node-schedule"));
570
+ var import_url = require("url");
571
+
572
+ // src/server/message/Action/Action.ts
573
+ var ActionKind;
574
+ (function(ActionKind2) {
575
+ ActionKind2["ADD_SUBSCRIBER"] = "ADD_SUBSCRIBER";
576
+ ActionKind2["EXIT_SUBSCRIBER"] = "EXIT_SUBSCRIBER";
577
+ ActionKind2["ADD_PUBLISHER"] = "ADD_PUBLISHER";
578
+ ActionKind2["UPDATE_PUBLISHER"] = "UPDATE_PUBLISHER";
579
+ ActionKind2["NOTIFY_SUBSCRIBER"] = "NOTIFY_SUBSCRIBER";
580
+ ActionKind2["EXIT_PUBLISHER"] = "EXIT_PUBLISHER";
581
+ ActionKind2["ADD_WEB_CLIENT"] = "ADD_WEB_CLIENT";
582
+ ActionKind2["NOTIFY_WEB_CLIENT"] = "NOTIFY_WEB_CLIENT";
583
+ ActionKind2["FETCH_TYPES"] = "FETCH_TYPES";
584
+ ActionKind2["ADD_DYNAMIC_REMOTE"] = "ADD_DYNAMIC_REMOTE";
585
+ })(ActionKind || (ActionKind = {}));
586
+
587
+ // src/server/message/Action/Update.ts
588
+ var UpdateKind;
589
+ (function(UpdateKind2) {
590
+ UpdateKind2["UPDATE_TYPE"] = "UPDATE_TYPE";
591
+ UpdateKind2["RELOAD_PAGE"] = "RELOAD_PAGE";
592
+ })(UpdateKind || (UpdateKind = {}));
593
+
594
+ // src/server/broker/Broker.ts
595
+ var _Broker = class _Broker {
596
+ constructor() {
597
+ __publicField(this, "_publisherMap", /* @__PURE__ */ new Map());
598
+ __publicField(this, "_webClientMap", /* @__PURE__ */ new Map());
599
+ __publicField(this, "_webSocketServer");
600
+ __publicField(this, "_secureWebSocketServer");
601
+ __publicField(this, "_tmpSubscriberShelter", /* @__PURE__ */ new Map());
602
+ __publicField(this, "_scheduleJob", null);
603
+ this._setSchedule();
604
+ this._startWsServer();
605
+ this._stopWhenSIGTERMOrSIGINT();
606
+ this._handleUnexpectedExit();
607
+ }
608
+ get hasPublishers() {
609
+ return Boolean(this._publisherMap.size);
610
+ }
611
+ _startWsServer() {
612
+ return __async(this, null, function* () {
613
+ const wsHandler = /* @__PURE__ */ __name((ws, req) => {
614
+ const { url: reqUrl = "" } = req;
615
+ const { query } = (0, import_url.parse)(reqUrl, true);
616
+ const { WEB_SOCKET_CONNECT_MAGIC_ID: WEB_SOCKET_CONNECT_MAGIC_ID2 } = query;
617
+ if (WEB_SOCKET_CONNECT_MAGIC_ID2 === _Broker.WEB_SOCKET_CONNECT_MAGIC_ID) {
618
+ ws.on("message", (message) => {
619
+ try {
620
+ const text = message.toString();
621
+ const action = JSON.parse(text);
622
+ fileLog(`${action == null ? void 0 : action.kind} action received `, "Broker", "info");
623
+ this._takeAction(action, ws);
624
+ } catch (error2) {
625
+ fileLog(`parse action message error: ${error2}`, "Broker", "error");
626
+ }
627
+ });
628
+ ws.on("error", (e) => {
629
+ fileLog(`parse action message error: ${e}`, "Broker", "error");
630
+ });
631
+ } else {
632
+ ws.send("Invalid CONNECT ID.");
633
+ fileLog("Invalid CONNECT ID.", "Broker", "warn");
634
+ ws.close();
635
+ }
636
+ }, "wsHandler");
637
+ const server = (0, import_http.createServer)();
638
+ this._webSocketServer = new import_isomorphic_ws.default.Server({
639
+ noServer: true
640
+ });
641
+ this._webSocketServer.on("error", (err) => {
642
+ fileLog(`ws error:
643
+ ${err.message}
644
+ ${err.stack}`, "Broker", "error");
645
+ });
646
+ this._webSocketServer.on("listening", () => {
647
+ fileLog(`WebSocket server is listening on port ${_Broker.DEFAULT_WEB_SOCKET_PORT}`, "Broker", "info");
648
+ });
649
+ this._webSocketServer.on("connection", wsHandler);
650
+ this._webSocketServer.on("close", (code) => {
651
+ fileLog(`WebSocket Server Close with Code ${code}`, "Broker", "warn");
652
+ this._webSocketServer && this._webSocketServer.close();
653
+ this._webSocketServer = void 0;
654
+ });
655
+ server.on("upgrade", (req, socket, head) => {
656
+ var _a3;
657
+ if (req.url) {
658
+ const { pathname } = (0, import_url.parse)(req.url);
659
+ if (pathname === "/") {
660
+ (_a3 = this._webSocketServer) == null ? void 0 : _a3.handleUpgrade(req, socket, head, (ws) => {
661
+ var _a4;
662
+ (_a4 = this._webSocketServer) == null ? void 0 : _a4.emit("connection", ws, req);
663
+ });
664
+ }
665
+ }
666
+ });
667
+ server.listen(_Broker.DEFAULT_WEB_SOCKET_PORT);
668
+ });
669
+ }
670
+ _takeAction(action, client) {
671
+ return __async(this, null, function* () {
672
+ const { kind, payload } = action;
673
+ if (kind === ActionKind.ADD_PUBLISHER) {
674
+ yield this._addPublisher(payload, client);
675
+ }
676
+ if (kind === ActionKind.UPDATE_PUBLISHER) {
677
+ yield this._updatePublisher(payload, client);
678
+ }
679
+ if (kind === ActionKind.ADD_SUBSCRIBER) {
680
+ yield this._addSubscriber(payload, client);
681
+ }
682
+ if (kind === ActionKind.EXIT_SUBSCRIBER) {
683
+ yield this._removeSubscriber(payload, client);
684
+ }
685
+ if (kind === ActionKind.EXIT_PUBLISHER) {
686
+ yield this._removePublisher(payload, client);
687
+ }
688
+ if (kind === ActionKind.ADD_WEB_CLIENT) {
689
+ yield this._addWebClient(payload, client);
690
+ }
691
+ if (kind === ActionKind.NOTIFY_WEB_CLIENT) {
692
+ yield this._notifyWebClient(payload, client);
693
+ }
694
+ if (kind === ActionKind.FETCH_TYPES) {
695
+ yield this._fetchTypes(payload, client);
696
+ }
697
+ if (kind === ActionKind.ADD_DYNAMIC_REMOTE) {
698
+ this._addDynamicRemote(payload);
699
+ }
700
+ });
701
+ }
702
+ _addPublisher(context, client) {
703
+ return __async(this, null, function* () {
704
+ const { name, ip, remoteTypeTarPath } = context != null ? context : {};
705
+ const identifier = getIdentifier({
706
+ name,
707
+ ip
708
+ });
709
+ if (this._publisherMap.has(identifier)) {
710
+ fileLog(`[${ActionKind.ADD_PUBLISHER}] ${identifier} has been added, this action will be ignored`, "Broker", "warn");
711
+ return;
712
+ }
713
+ try {
714
+ const publisher = new Publisher({
715
+ name,
716
+ ip,
717
+ remoteTypeTarPath,
718
+ ws: client
719
+ });
720
+ this._publisherMap.set(identifier, publisher);
721
+ fileLog(`[${ActionKind.ADD_PUBLISHER}] ${identifier} Adding Publisher Succeed`, "Broker", "info");
722
+ const tmpSubScribers = this._getTmpSubScribers(identifier);
723
+ if (tmpSubScribers) {
724
+ fileLog(`[${ActionKind.ADD_PUBLISHER}] consumeTmpSubscriber set ${publisher.name}\u2019s subscribers `, "Broker", "info");
725
+ this._consumeTmpSubScribers(publisher, tmpSubScribers);
726
+ this._clearTmpSubScriberRelation(identifier);
727
+ }
728
+ } catch (err) {
729
+ const msg = error(err, ActionKind.ADD_PUBLISHER, "Broker");
730
+ client.send(msg);
731
+ client.close();
732
+ }
733
+ });
734
+ }
735
+ _updatePublisher(context, client) {
736
+ return __async(this, null, function* () {
737
+ const { name, updateMode, updateKind, updateSourcePaths, remoteTypeTarPath, ip } = context != null ? context : {};
738
+ const identifier = getIdentifier({
739
+ name,
740
+ ip
741
+ });
742
+ if (!this._publisherMap.has(identifier)) {
743
+ fileLog(`[${ActionKind.UPDATE_PUBLISHER}] ${identifier} has not been started, this action will be ignored
744
+ this._publisherMap: ${JSON.stringify(this._publisherMap.entries())}
745
+ `, "Broker", "warn");
746
+ return;
747
+ }
748
+ try {
749
+ const publisher = this._publisherMap.get(identifier);
750
+ fileLog(
751
+ // eslint-disable-next-line max-len
752
+ `[${ActionKind.UPDATE_PUBLISHER}] ${identifier} update, and notify subscribers to update`,
753
+ "Broker",
754
+ "info"
755
+ );
756
+ if (publisher) {
757
+ publisher.notifySubscribers({
758
+ remoteTypeTarPath,
759
+ name,
760
+ updateMode,
761
+ updateKind,
762
+ updateSourcePaths: updateSourcePaths || []
763
+ });
764
+ this._publisherMap.forEach((p) => {
765
+ if (p.name === publisher.name) {
766
+ return;
767
+ }
768
+ const dynamicRemoteInfo = p.dynamicRemoteMap.get(identifier);
769
+ if (dynamicRemoteInfo) {
770
+ fileLog(
771
+ // eslint-disable-next-line max-len
772
+ `dynamicRemoteInfo: ${JSON.stringify(dynamicRemoteInfo)}, identifier:${identifier} publish: ${p.name}`,
773
+ "Broker",
774
+ "info"
775
+ );
776
+ p.fetchRemoteTypes({
777
+ remoteInfo: dynamicRemoteInfo,
778
+ once: false
779
+ });
780
+ }
781
+ });
782
+ }
783
+ } catch (err) {
784
+ const msg = error(err, ActionKind.UPDATE_PUBLISHER, "Broker");
785
+ client.send(msg);
786
+ client.close();
787
+ }
788
+ });
789
+ }
790
+ _fetchTypes(context, _client) {
791
+ return __async(this, null, function* () {
792
+ const { name, ip, remoteInfo } = context != null ? context : {};
793
+ const identifier = getIdentifier({
794
+ name,
795
+ ip
796
+ });
797
+ try {
798
+ const publisher = this._publisherMap.get(identifier);
799
+ fileLog(`[${ActionKind.FETCH_TYPES}] ${identifier} fetch types`, "Broker", "info");
800
+ if (publisher) {
801
+ publisher.fetchRemoteTypes({
802
+ remoteInfo,
803
+ once: true
804
+ });
805
+ }
806
+ } catch (err) {
807
+ fileLog(`[${ActionKind.FETCH_TYPES}] ${identifier} fetch types fail , error info: ${err}`, "Broker", "error");
808
+ }
809
+ });
810
+ }
811
+ _addDynamicRemote(context) {
812
+ const { name, ip, remoteInfo, remoteIp } = context != null ? context : {};
813
+ const identifier = getIdentifier({
814
+ name,
815
+ ip
816
+ });
817
+ const publisher = this._publisherMap.get(identifier);
818
+ const remoteId = getIdentifier({
819
+ name: remoteInfo.name,
820
+ ip: remoteIp
821
+ });
822
+ fileLog(`[${ActionKind.ADD_DYNAMIC_REMOTE}] identifier:${identifier},publisher: ${publisher.name}, remoteId:${remoteId}`, "Broker", "error");
823
+ if (!publisher || publisher.dynamicRemoteMap.has(remoteId)) {
824
+ return;
825
+ }
826
+ publisher.dynamicRemoteMap.set(remoteId, remoteInfo);
827
+ }
828
+ // app1 consumes provider1,provider2. Dependencies at this time: publishers: [provider1, provider2], subscriberName: app1
829
+ // provider1 is app1's remote
830
+ _addSubscriber(context, client) {
831
+ return __async(this, null, function* () {
832
+ const { publishers, name: subscriberName } = context != null ? context : {};
833
+ publishers.forEach((publisher) => {
834
+ const { name, ip } = publisher;
835
+ const identifier = getIdentifier({
836
+ name,
837
+ ip
838
+ });
839
+ if (!this._publisherMap.has(identifier)) {
840
+ fileLog(`[${ActionKind.ADD_SUBSCRIBER}]: ${identifier} has not been started, ${subscriberName} will add the relation to tmp shelter`, "Broker", "warn");
841
+ this._addTmpSubScriberRelation({
842
+ name: getIdentifier({
843
+ name: context.name,
844
+ ip: context.ip
845
+ }),
846
+ client
847
+ }, publisher);
848
+ return;
849
+ }
850
+ try {
851
+ const registeredPublisher = this._publisherMap.get(identifier);
852
+ if (registeredPublisher) {
853
+ registeredPublisher.addSubscriber(getIdentifier({
854
+ name: subscriberName,
855
+ ip: context.ip
856
+ }), client);
857
+ fileLog(
858
+ // eslint-disable-next-line @ies/eden/max-calls-in-template
859
+ `[${ActionKind.ADD_SUBSCRIBER}]: ${identifier} has been started, Adding Subscriber ${subscriberName} Succeed, this.__publisherMap are: ${JSON.stringify(Array.from(this._publisherMap.entries()))}`,
860
+ "Broker",
861
+ "info"
862
+ );
863
+ registeredPublisher.notifySubscriber(getIdentifier({
864
+ name: subscriberName,
865
+ ip: context.ip
866
+ }), {
867
+ updateKind: UpdateKind.UPDATE_TYPE,
868
+ updateMode: UpdateMode.PASSIVE,
869
+ updateSourcePaths: [
870
+ registeredPublisher.name
871
+ ],
872
+ remoteTypeTarPath: registeredPublisher.remoteTypeTarPath,
873
+ name: registeredPublisher.name
874
+ });
875
+ fileLog(
876
+ // eslint-disable-next-line @ies/eden/max-calls-in-template
877
+ `[${ActionKind.ADD_SUBSCRIBER}]: notifySubscriber Subscriber ${subscriberName}, updateMode: "PASSIVE", updateSourcePaths: ${registeredPublisher.name}`,
878
+ "Broker",
879
+ "info"
880
+ );
881
+ }
882
+ } catch (err) {
883
+ const msg = error(err, ActionKind.ADD_SUBSCRIBER, "Broker");
884
+ client.send(msg);
885
+ client.close();
886
+ }
887
+ });
888
+ });
889
+ }
890
+ // Trigger while consumer exit
891
+ _removeSubscriber(context, client) {
892
+ return __async(this, null, function* () {
893
+ const { publishers } = context != null ? context : {};
894
+ const subscriberIdentifier = getIdentifier({
895
+ name: context == null ? void 0 : context.name,
896
+ ip: context == null ? void 0 : context.ip
897
+ });
898
+ publishers.forEach((publisher) => {
899
+ const { name, ip } = publisher;
900
+ const identifier = getIdentifier({
901
+ name,
902
+ ip
903
+ });
904
+ const registeredPublisher = this._publisherMap.get(identifier);
905
+ if (!registeredPublisher) {
906
+ fileLog(`[${ActionKind.EXIT_SUBSCRIBER}], ${identifier} does not exit `, "Broker", "warn");
907
+ return;
908
+ }
909
+ try {
910
+ fileLog(`[${ActionKind.EXIT_SUBSCRIBER}], ${identifier} will exit `, "Broker", "INFO");
911
+ registeredPublisher.removeSubscriber(subscriberIdentifier);
912
+ this._clearTmpSubScriberRelation(identifier);
913
+ if (!registeredPublisher.hasSubscribes) {
914
+ this._publisherMap.delete(identifier);
915
+ }
916
+ if (!this.hasPublishers) {
917
+ this.exit();
918
+ }
919
+ } catch (err) {
920
+ const msg = error(err, ActionKind.EXIT_SUBSCRIBER, "Broker");
921
+ client.send(msg);
922
+ client.close();
923
+ }
924
+ });
925
+ });
926
+ }
927
+ _removePublisher(context, client) {
928
+ return __async(this, null, function* () {
929
+ const { name, ip } = context != null ? context : {};
930
+ const identifier = getIdentifier({
931
+ name,
932
+ ip
933
+ });
934
+ const publisher = this._publisherMap.get(identifier);
935
+ if (!publisher) {
936
+ fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier}} has not been added, this action will be ingored`, "Broker", "warn");
937
+ return;
938
+ }
939
+ try {
940
+ const { subscribers } = publisher;
941
+ subscribers.forEach((subscriber, subscriberIdentifier) => {
942
+ this._addTmpSubScriberRelation({
943
+ name: subscriberIdentifier,
944
+ client: subscriber
945
+ }, {
946
+ name: publisher.name,
947
+ ip: publisher.ip
948
+ });
949
+ fileLog(
950
+ // eslint-disable-next-line max-len
951
+ `[${ActionKind.EXIT_PUBLISHER}]: ${identifier} is removing , subscriber: ${subscriberIdentifier} will be add tmpSubScriberRelation`,
952
+ "Broker",
953
+ "info"
954
+ );
955
+ });
956
+ this._publisherMap.delete(identifier);
957
+ fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier} is removed `, "Broker", "info");
958
+ if (!this.hasPublishers) {
959
+ fileLog(`[${ActionKind.EXIT_PUBLISHER}]: _publisherMap is empty, all server will exit `, "Broker", "warn");
960
+ this.exit();
961
+ }
962
+ } catch (err) {
963
+ const msg = error(err, ActionKind.EXIT_PUBLISHER, "Broker");
964
+ client.send(msg);
965
+ client.close();
966
+ }
967
+ });
968
+ }
969
+ _addWebClient(context, client) {
970
+ return __async(this, null, function* () {
971
+ const { name } = context != null ? context : {};
972
+ const identifier = getIdentifier({
973
+ name
974
+ });
975
+ if (this._webClientMap.has(identifier)) {
976
+ fileLog(`${identifier}} has been added, this action will override prev WebClient`, "Broker", "warn");
977
+ }
978
+ try {
979
+ this._webClientMap.set(identifier, client);
980
+ fileLog(`${identifier} adding WebClient Succeed`, "Broker", "info");
981
+ } catch (err) {
982
+ const msg = error(err, ActionKind.ADD_WEB_CLIENT, "Broker");
983
+ client.send(msg);
984
+ client.close();
985
+ }
986
+ });
987
+ }
988
+ _notifyWebClient(context, client) {
989
+ return __async(this, null, function* () {
990
+ const { name, updateMode } = context != null ? context : {};
991
+ const identifier = getIdentifier({
992
+ name
993
+ });
994
+ const webClient = this._webClientMap.get(identifier);
995
+ if (!webClient) {
996
+ fileLog(`[${ActionKind.NOTIFY_WEB_CLIENT}] ${identifier} has not been added, this action will be ignored`, "Broker", "warn");
997
+ return;
998
+ }
999
+ try {
1000
+ const api = new ReloadWebClientAPI({
1001
+ name,
1002
+ updateMode
1003
+ });
1004
+ webClient.send(JSON.stringify(api));
1005
+ fileLog(`[${ActionKind.NOTIFY_WEB_CLIENT}] Notify ${name} WebClient Succeed`, "Broker", "info");
1006
+ } catch (err) {
1007
+ const msg = error(err, ActionKind.NOTIFY_WEB_CLIENT, "Broker");
1008
+ client.send(msg);
1009
+ client.close();
1010
+ }
1011
+ });
1012
+ }
1013
+ // app1 consumes provider1, and provider1 not launch. this._tmpSubscriberShelter at this time: {provider1: Map{subscribers: Map{app1: app1+ip+client'}, timestamp: 'xx'} }
1014
+ _addTmpSubScriberRelation(subscriber, publisher) {
1015
+ const publisherIdentifier = getIdentifier({
1016
+ name: publisher.name,
1017
+ ip: publisher.ip
1018
+ });
1019
+ const subscriberIdentifier = subscriber.name;
1020
+ const shelter = this._tmpSubscriberShelter.get(publisherIdentifier);
1021
+ if (!shelter) {
1022
+ const map = /* @__PURE__ */ new Map();
1023
+ map.set(subscriberIdentifier, subscriber);
1024
+ this._tmpSubscriberShelter.set(publisherIdentifier, {
1025
+ subscribers: map,
1026
+ timestamp: Date.now()
1027
+ });
1028
+ fileLog(`[AddTmpSubscriberRelation] ${publisherIdentifier}'s subscriber has ${subscriberIdentifier} `, "Broker", "info");
1029
+ return;
1030
+ }
1031
+ const tmpSubScriberShelterSubscriber = shelter.subscribers.get(subscriberIdentifier);
1032
+ if (tmpSubScriberShelterSubscriber) {
1033
+ fileLog(`[AddTmpSubscriberRelation] ${publisherIdentifier} and ${subscriberIdentifier} relation has been added`, "Broker", "warn");
1034
+ shelter.subscribers.set(subscriberIdentifier, subscriber);
1035
+ shelter.timestamp = Date.now();
1036
+ } else {
1037
+ fileLog(
1038
+ // eslint-disable-next-line max-len
1039
+ `AddTmpSubscriberLog ${publisherIdentifier}'s shelter has been added, update shelter.subscribers ${subscriberIdentifier}`,
1040
+ "Broker",
1041
+ "warn"
1042
+ );
1043
+ shelter.subscribers.set(subscriberIdentifier, subscriber);
1044
+ }
1045
+ }
1046
+ _getTmpSubScribers(publisherIdentifier) {
1047
+ var _a3;
1048
+ return (_a3 = this._tmpSubscriberShelter.get(publisherIdentifier)) == null ? void 0 : _a3.subscribers;
1049
+ }
1050
+ // after adding publisher, it will change the temp subscriber to regular subscriber
1051
+ _consumeTmpSubScribers(publisher, tmpSubScribers) {
1052
+ tmpSubScribers.forEach((tmpSubScriber, identifier) => {
1053
+ fileLog(`notifyTmpSubScribers ${publisher.name} will be add a subscriber: ${identifier} `, "Broker", "warn");
1054
+ publisher.addSubscriber(identifier, tmpSubScriber.client);
1055
+ publisher.notifySubscriber(identifier, {
1056
+ updateKind: UpdateKind.UPDATE_TYPE,
1057
+ updateMode: UpdateMode.PASSIVE,
1058
+ updateSourcePaths: [
1059
+ publisher.name
1060
+ ],
1061
+ remoteTypeTarPath: publisher.remoteTypeTarPath,
1062
+ name: publisher.name
1063
+ });
1064
+ });
1065
+ }
1066
+ _clearTmpSubScriberRelation(identifier) {
1067
+ this._tmpSubscriberShelter.delete(identifier);
1068
+ }
1069
+ _clearTmpSubScriberRelations() {
1070
+ this._tmpSubscriberShelter.clear();
1071
+ }
1072
+ _disconnect() {
1073
+ this._publisherMap.forEach((publisher) => {
1074
+ publisher.close();
1075
+ });
1076
+ }
1077
+ // Every day on 0/6/9/12/15//18, Publishers that have not been connected within 1.5 hours will be cleared regularly.
1078
+ // If process.env.FEDERATION_SERVER_TEST is set, it will be read at a specified time.
1079
+ _setSchedule() {
1080
+ const rule = new import_node_schedule.default.RecurrenceRule();
1081
+ if (Number(process.env["FEDERATION_SERVER_TEST"])) {
1082
+ const interval = Number(process.env["FEDERATION_SERVER_TEST"]) / 1e3;
1083
+ const second = [];
1084
+ for (let i = 0; i < 60; i = i + interval) {
1085
+ second.push(i);
1086
+ }
1087
+ rule.second = second;
1088
+ } else {
1089
+ rule.second = 0;
1090
+ rule.hour = [
1091
+ 0,
1092
+ 3,
1093
+ 6,
1094
+ 9,
1095
+ 12,
1096
+ 15,
1097
+ 18
1098
+ ];
1099
+ rule.minute = 0;
1100
+ }
1101
+ const serverTest = Number(process.env["FEDERATION_SERVER_TEST"]);
1102
+ this._scheduleJob = import_node_schedule.default.scheduleJob(rule, () => {
1103
+ this._tmpSubscriberShelter.forEach((tmpSubscriber, identifier) => {
1104
+ fileLog(` _clearTmpSubScriberRelation ${identifier}, ${Date.now() - tmpSubscriber.timestamp >= (process.env["GARFISH_MODULE_SERVER_TEST"] ? serverTest : _Broker.DEFAULT_WAITING_TIME)}`, "Broker", "info");
1105
+ if (Date.now() - tmpSubscriber.timestamp >= (process.env["FEDERATION_SERVER_TEST"] ? serverTest : _Broker.DEFAULT_WAITING_TIME)) {
1106
+ this._clearTmpSubScriberRelation(identifier);
1107
+ }
1108
+ });
1109
+ });
1110
+ }
1111
+ _clearSchedule() {
1112
+ if (!this._scheduleJob) {
1113
+ return;
1114
+ }
1115
+ this._scheduleJob.cancel();
1116
+ this._scheduleJob = null;
1117
+ }
1118
+ _stopWhenSIGTERMOrSIGINT() {
1119
+ process.on("SIGTERM", () => {
1120
+ this.exit();
1121
+ });
1122
+ process.on("SIGINT", () => {
1123
+ this.exit();
1124
+ });
1125
+ }
1126
+ _handleUnexpectedExit() {
1127
+ process.on("unhandledRejection", (error2) => {
1128
+ console.error("Unhandled Rejection Error: ", error2);
1129
+ fileLog(`Unhandled Rejection Error: ${error2}`, "Broker", "fatal");
1130
+ process.exit(1);
1131
+ });
1132
+ process.on("uncaughtException", (error2) => {
1133
+ console.error("Unhandled Exception Error: ", error2);
1134
+ fileLog(`Unhandled Rejection Error: ${error2}`, "Broker", "fatal");
1135
+ process.exit(1);
1136
+ });
1137
+ }
1138
+ start() {
1139
+ return __async(this, null, function* () {
1140
+ });
1141
+ }
1142
+ exit() {
1143
+ const brokerExitLog = new BrokerExitLog();
1144
+ this.broadcast(JSON.stringify(brokerExitLog));
1145
+ this._disconnect();
1146
+ this._clearSchedule();
1147
+ this._clearTmpSubScriberRelations();
1148
+ this._webSocketServer && this._webSocketServer.close();
1149
+ this._secureWebSocketServer && this._secureWebSocketServer.close();
1150
+ process.exit(0);
1151
+ }
1152
+ broadcast(message) {
1153
+ var _a3, _b;
1154
+ fileLog(`[broadcast] exit info : ${JSON.stringify(message)}`, "Broker", "warn");
1155
+ (_a3 = this._webSocketServer) == null ? void 0 : _a3.clients.forEach((client) => {
1156
+ client.send(JSON.stringify(message));
1157
+ });
1158
+ (_b = this._secureWebSocketServer) == null ? void 0 : _b.clients.forEach((client) => {
1159
+ client.send(JSON.stringify(message));
1160
+ });
1161
+ }
1162
+ };
1163
+ __name(_Broker, "Broker");
1164
+ __publicField(_Broker, "WEB_SOCKET_CONNECT_MAGIC_ID", WEB_SOCKET_CONNECT_MAGIC_ID);
1165
+ __publicField(_Broker, "DEFAULT_WEB_SOCKET_PORT", DEFAULT_WEB_SOCKET_PORT);
1166
+ __publicField(_Broker, "DEFAULT_SECURE_WEB_SOCKET_PORT", 16324);
1167
+ __publicField(_Broker, "DEFAULT_WAITING_TIME", 1.5 * 60 * 60 * 1e3);
1168
+ var Broker = _Broker;
1169
+
1170
+ // src/server/createKoaServer.ts
1171
+ var import_fs_extra2 = __toESM(require("fs-extra"));
1172
+ var import_koa = __toESM(require("koa"));
1173
+
1174
+ // src/core/lib/archiveHandler.ts
1175
+ var retrieveTypesZipPath = /* @__PURE__ */ __name((mfTypesPath, remoteOptions) => (0, import_path2.join)(mfTypesPath.replace(remoteOptions.typesFolder, ""), `${remoteOptions.typesFolder}.zip`), "retrieveTypesZipPath");
1176
+ var createTypesArchive = /* @__PURE__ */ __name((tsConfig, remoteOptions) => __async(void 0, null, function* () {
1177
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
1178
+ const zip = new import_adm_zip.default();
1179
+ zip.addLocalFolder(mfTypesPath);
1180
+ return zip.writeZipPromise(retrieveTypesZipPath(mfTypesPath, remoteOptions));
1181
+ }), "createTypesArchive");
1182
+ var downloadErrorLogger = /* @__PURE__ */ __name((destinationFolder, fileToDownload) => (reason) => {
1183
+ throw __spreadProps(__spreadValues({}, reason), {
1184
+ message: `Network error: Unable to download federated mocks for '${destinationFolder}' from '${fileToDownload}' because '${reason.message}'`
1185
+ });
1186
+ }, "downloadErrorLogger");
1187
+ var retrieveTypesArchiveDestinationPath = /* @__PURE__ */ __name((hostOptions, destinationFolder) => {
1188
+ return (0, import_path2.resolve)(hostOptions.context, hostOptions.typesFolder, destinationFolder);
1189
+ }, "retrieveTypesArchiveDestinationPath");
1190
+ var downloadTypesArchive = /* @__PURE__ */ __name((hostOptions) => {
1191
+ let retries = 0;
1192
+ return (_0) => __async(void 0, [_0], function* ([destinationFolder, fileToDownload]) {
1193
+ var _a3;
1194
+ const destinationPath = retrieveTypesArchiveDestinationPath(hostOptions, destinationFolder);
1195
+ while (retries++ < hostOptions.maxRetries) {
1196
+ try {
1197
+ const url = new URL(fileToDownload).href;
1198
+ const response = yield axiosGet(url, {
1199
+ responseType: "arraybuffer",
1200
+ timeout: hostOptions.timeout,
1201
+ family: hostOptions.family
1202
+ }).catch(downloadErrorLogger(destinationFolder, url));
1203
+ if (typeof ((_a3 = response.headers) == null ? void 0 : _a3["content-type"]) === "string" && response.headers["content-type"].includes("text/html")) {
1204
+ throw new Error(`${url} receives invalid content-type: ${response.headers["content-type"]}`);
1205
+ }
1206
+ try {
1207
+ if (hostOptions.deleteTypesFolder) {
1208
+ yield (0, import_promises2.rm)(destinationPath, {
1209
+ recursive: true,
1210
+ force: true
1211
+ });
1212
+ }
1213
+ } catch (error2) {
1214
+ fileLog(`Unable to remove types folder, ${error2}`, "downloadTypesArchive", "error");
1215
+ }
1216
+ const zip = new import_adm_zip.default(Buffer.from(response.data));
1217
+ zip.extractAllTo(destinationPath, true);
1218
+ fileLog(`zip.extractAllTo success destinationPath: ${destinationPath}; url: ${url}`, "downloadTypesArchive", "info");
1219
+ return [
1220
+ destinationFolder,
1221
+ destinationPath
1222
+ ];
1223
+ } catch (error2) {
1224
+ fileLog(`Error during types archive download: ${(error2 == null ? void 0 : error2.message) || "unknown error"}`, "downloadTypesArchive", "error");
1225
+ if (retries >= hostOptions.maxRetries) {
1226
+ logger.error(`Failed to download types archive from "${fileToDownload}". Set FEDERATION_DEBUG=true for details.`);
1227
+ if (hostOptions.abortOnError !== false) {
1228
+ throw error2;
1229
+ }
1230
+ return void 0;
1231
+ }
1232
+ }
1233
+ }
1234
+ });
1235
+ }, "downloadTypesArchive");
1236
+
1237
+ // src/core/configurations/hostPlugin.ts
1238
+ var import_sdk4 = require("@module-federation/sdk");
1239
+ var import_managers = require("@module-federation/managers");
1240
+ var defaultOptions = {
1241
+ typesFolder: "@mf-types",
1242
+ remoteTypesFolder: "@mf-types",
1243
+ deleteTypesFolder: true,
1244
+ maxRetries: 3,
1245
+ implementation: "",
1246
+ context: process.cwd(),
1247
+ abortOnError: true,
1248
+ consumeAPITypes: false,
1249
+ runtimePkgs: [],
1250
+ remoteTypeUrls: {},
1251
+ timeout: 6e4,
1252
+ typesOnBuild: false,
1253
+ family: 4
1254
+ };
1255
+ var buildZipUrl = /* @__PURE__ */ __name((hostOptions, url) => {
1256
+ const remoteUrl = new URL(url, "file:");
1257
+ const pathnameWithoutEntry = remoteUrl.pathname.split("/").slice(0, -1).join("/");
1258
+ remoteUrl.pathname = `${pathnameWithoutEntry}/${hostOptions.remoteTypesFolder}.zip`;
1259
+ return remoteUrl.protocol === "file:" ? remoteUrl.pathname : remoteUrl.href;
1260
+ }, "buildZipUrl");
1261
+ var buildApiTypeUrl = /* @__PURE__ */ __name((zipUrl) => {
1262
+ if (!zipUrl) {
1263
+ return void 0;
1264
+ }
1265
+ return zipUrl.replace(".zip", ".d.ts");
1266
+ }, "buildApiTypeUrl");
1267
+ var retrieveRemoteInfo = /* @__PURE__ */ __name((options) => {
1268
+ const { hostOptions, remoteAlias, remote } = options;
1269
+ const { remoteTypeUrls } = hostOptions;
1270
+ let decodedRemote = remote;
1271
+ if (decodedRemote.startsWith(import_sdk4.ENCODE_NAME_PREFIX)) {
1272
+ decodedRemote = (0, import_sdk4.decodeName)(decodedRemote, import_sdk4.ENCODE_NAME_PREFIX);
1273
+ }
1274
+ const parsedInfo = (0, import_sdk4.parseEntry)(decodedRemote, void 0, "@");
1275
+ const url = "entry" in parsedInfo ? parsedInfo.entry : parsedInfo.name === decodedRemote ? decodedRemote : "";
1276
+ let zipUrl = "";
1277
+ let apiTypeUrl = "";
1278
+ const name = parsedInfo.name || remoteAlias;
1279
+ if (typeof remoteTypeUrls === "object" && remoteTypeUrls[name]) {
1280
+ zipUrl = remoteTypeUrls[name].zip;
1281
+ apiTypeUrl = remoteTypeUrls[name].api;
1282
+ }
1283
+ if (!zipUrl && url) {
1284
+ zipUrl = buildZipUrl(hostOptions, url);
1285
+ }
1286
+ if (!apiTypeUrl && zipUrl) {
1287
+ apiTypeUrl = buildApiTypeUrl(zipUrl);
1288
+ }
1289
+ return {
1290
+ name,
1291
+ url,
1292
+ zipUrl,
1293
+ apiTypeUrl,
1294
+ alias: remoteAlias
1295
+ };
1296
+ }, "retrieveRemoteInfo");
1297
+ var resolveRemotes = /* @__PURE__ */ __name((hostOptions) => {
1298
+ var _a3;
1299
+ const parsedOptions = import_managers.utils.parseOptions(hostOptions.moduleFederationConfig.remotes || {}, (item, key) => ({
1300
+ remote: Array.isArray(item) ? item[0] : item,
1301
+ key
1302
+ }), (item, key) => ({
1303
+ remote: Array.isArray(item.external) ? item.external[0] : item.external,
1304
+ key
1305
+ }));
1306
+ const remoteTypeUrls = (_a3 = hostOptions.remoteTypeUrls) != null ? _a3 : {};
1307
+ if (typeof remoteTypeUrls !== "object") {
1308
+ throw new Error("remoteTypeUrls must be consumed before resolveRemotes");
1309
+ }
1310
+ const remoteInfos = Object.keys(remoteTypeUrls).reduce((sum, remoteName) => {
1311
+ const { zip, api, alias } = remoteTypeUrls[remoteName];
1312
+ sum[alias] = {
1313
+ name: remoteName,
1314
+ url: "",
1315
+ zipUrl: zip,
1316
+ apiTypeUrl: api,
1317
+ alias: alias || remoteName
1318
+ };
1319
+ return sum;
1320
+ }, {});
1321
+ return parsedOptions.reduce((accumulator, item) => {
1322
+ const { key, remote } = item[1];
1323
+ const res = retrieveRemoteInfo({
1324
+ hostOptions,
1325
+ remoteAlias: key,
1326
+ remote
1327
+ });
1328
+ if (accumulator[key]) {
1329
+ accumulator[key] = __spreadProps(__spreadValues({}, accumulator[key]), {
1330
+ url: res.url,
1331
+ apiTypeUrl: accumulator[key].apiTypeUrl || res.apiTypeUrl
1332
+ });
1333
+ return accumulator;
1334
+ }
1335
+ accumulator[key] = res;
1336
+ return accumulator;
1337
+ }, remoteInfos);
1338
+ }, "resolveRemotes");
1339
+ var retrieveHostConfig = /* @__PURE__ */ __name((options) => {
1340
+ validateOptions(options);
1341
+ const hostOptions = __spreadValues(__spreadValues({}, defaultOptions), options);
1342
+ const mapRemotesToDownload = resolveRemotes(hostOptions);
1343
+ return {
1344
+ hostOptions,
1345
+ mapRemotesToDownload
1346
+ };
1347
+ }, "retrieveHostConfig");
1348
+
1349
+ // src/core/constant.ts
1350
+ var REMOTE_ALIAS_IDENTIFIER = "REMOTE_ALIAS_IDENTIFIER";
1351
+ var REMOTE_API_TYPES_FILE_NAME = "apis.d.ts";
1352
+ var HOST_API_TYPES_FILE_NAME = "index.d.ts";
1353
+
1354
+ // src/core/lib/DTSManager.ts
1355
+ var _a;
1356
+ var DTSManager = (_a = class {
1357
+ constructor(options) {
1358
+ __publicField(this, "options");
1359
+ __publicField(this, "runtimePkgs");
1360
+ __publicField(this, "remoteAliasMap");
1361
+ __publicField(this, "loadedRemoteAPIAlias");
1362
+ __publicField(this, "extraOptions");
1363
+ __publicField(this, "updatedRemoteInfos");
1364
+ this.options = cloneDeepOptions(options);
1365
+ this.runtimePkgs = [
1366
+ "@module-federation/runtime",
1367
+ "@module-federation/enhanced/runtime",
1368
+ "@module-federation/runtime-tools"
1369
+ ];
1370
+ this.loadedRemoteAPIAlias = /* @__PURE__ */ new Set();
1371
+ this.remoteAliasMap = {};
1372
+ this.extraOptions = (options == null ? void 0 : options.extraOptions) || {};
1373
+ this.updatedRemoteInfos = {};
1374
+ }
1375
+ generateAPITypes(mapComponentsToExpose) {
1376
+ const exposePaths = /* @__PURE__ */ new Set();
1377
+ const packageType = Object.keys(mapComponentsToExpose).reduce((sum, exposeKey) => {
1378
+ const exposePath = import_path3.default.join(REMOTE_ALIAS_IDENTIFIER, exposeKey).split(import_path3.default.sep).join("/");
1379
+ exposePaths.add(`'${exposePath}'`);
1380
+ const curType = `T extends '${exposePath}' ? typeof import('${exposePath}') :`;
1381
+ sum = curType + sum;
1382
+ return sum;
1383
+ }, "any;");
1384
+ const exposePathKeys = [
1385
+ ...exposePaths
1386
+ ].join(" | ");
1387
+ return `
1388
+ export type RemoteKeys = ${exposePathKeys};
1389
+ type PackageType<T> = ${packageType}`;
1390
+ }
1391
+ extractRemoteTypes(options) {
1392
+ return __async(this, null, function* () {
1393
+ var _a3;
1394
+ const { remoteOptions, tsConfig } = options;
1395
+ if (!remoteOptions.extractRemoteTypes) {
1396
+ return;
1397
+ }
1398
+ let hasRemotes = false;
1399
+ const remotes = remoteOptions.moduleFederationConfig.remotes;
1400
+ if (remotes) {
1401
+ if (Array.isArray(remotes)) {
1402
+ hasRemotes = Boolean(remotes.length);
1403
+ } else if (typeof remotes === "object") {
1404
+ hasRemotes = Boolean(Object.keys(remotes).length);
1405
+ }
1406
+ }
1407
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
1408
+ if (hasRemotes && this.options.host) {
1409
+ try {
1410
+ const { hostOptions } = retrieveHostConfig(this.options.host);
1411
+ const remoteTypesFolder = import_path3.default.resolve(hostOptions.context, hostOptions.typesFolder);
1412
+ const targetDir = import_path3.default.join(mfTypesPath, "node_modules");
1413
+ if (import_fs.default.existsSync(remoteTypesFolder)) {
1414
+ const targetFolder = import_path3.default.resolve(remoteOptions.context, targetDir);
1415
+ yield import_fs_extra3.default.ensureDir(targetFolder);
1416
+ yield import_fs_extra3.default.copy(remoteTypesFolder, targetFolder, {
1417
+ overwrite: true
1418
+ });
1419
+ }
1420
+ } catch (err) {
1421
+ if (((_a3 = this.options.host) == null ? void 0 : _a3.abortOnError) === false) {
1422
+ fileLog(`Unable to copy remote types, ${err}`, "extractRemoteTypes", "error");
1423
+ } else {
1424
+ throw err;
1425
+ }
1426
+ }
1427
+ }
1428
+ });
1429
+ }
1430
+ // it must execute after consumeTypes
1431
+ generateTypes() {
1432
+ return __async(this, null, function* () {
1433
+ var _a3, _b;
1434
+ try {
1435
+ const { options } = this;
1436
+ if (!options.remote) {
1437
+ throw new Error("options.remote is required if you want to generateTypes");
1438
+ }
1439
+ const { remoteOptions, tsConfig, mapComponentsToExpose } = retrieveRemoteConfig(options.remote);
1440
+ if (!Object.keys(mapComponentsToExpose).length) {
1441
+ return;
1442
+ }
1443
+ if (!((_a3 = tsConfig.files) == null ? void 0 : _a3.length)) {
1444
+ logger.info("No type files to compile, skip");
1445
+ return;
1446
+ }
1447
+ if (tsConfig.compilerOptions.tsBuildInfoFile) {
1448
+ try {
1449
+ const tsBuildInfoFile = import_path3.default.resolve(remoteOptions.context, tsConfig.compilerOptions.tsBuildInfoFile);
1450
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
1451
+ if (!import_fs.default.existsSync(mfTypesPath)) {
1452
+ import_fs.default.rmSync(tsBuildInfoFile, {
1453
+ force: true
1454
+ });
1455
+ }
1456
+ } catch (e) {
1457
+ }
1458
+ }
1459
+ yield this.extractRemoteTypes({
1460
+ remoteOptions,
1461
+ tsConfig,
1462
+ mapComponentsToExpose
1463
+ });
1464
+ yield compileTs(mapComponentsToExpose, tsConfig, remoteOptions);
1465
+ yield createTypesArchive(tsConfig, remoteOptions);
1466
+ let apiTypesPath = "";
1467
+ if (remoteOptions.generateAPITypes) {
1468
+ const apiTypes = this.generateAPITypes(mapComponentsToExpose);
1469
+ apiTypesPath = retrieveMfAPITypesPath(tsConfig, remoteOptions);
1470
+ import_fs.default.writeFileSync(apiTypesPath, apiTypes);
1471
+ }
1472
+ try {
1473
+ if (remoteOptions.deleteTypesFolder) {
1474
+ yield (0, import_promises3.rm)(retrieveMfTypesPath(tsConfig, remoteOptions), {
1475
+ recursive: true,
1476
+ force: true
1477
+ });
1478
+ }
1479
+ } catch (err) {
1480
+ if (isDebugMode()) {
1481
+ console.error(err);
1482
+ }
1483
+ }
1484
+ logger.success("Federated types created correctly");
1485
+ } catch (error2) {
1486
+ if (((_b = this.options.remote) == null ? void 0 : _b.abortOnError) === false) {
1487
+ if (this.options.displayErrorInTerminal) {
1488
+ logger.error(error2);
1489
+ }
1490
+ } else {
1491
+ throw error2;
1492
+ }
1493
+ }
1494
+ });
1495
+ }
1496
+ requestRemoteManifest(remoteInfo, hostOptions) {
1497
+ return __async(this, null, function* () {
1498
+ try {
1499
+ if (!remoteInfo.url.includes(import_sdk5.MANIFEST_EXT)) {
1500
+ return remoteInfo;
1501
+ }
1502
+ if (remoteInfo.zipUrl) {
1503
+ return remoteInfo;
1504
+ }
1505
+ const url = remoteInfo.url;
1506
+ const res = yield axiosGet(url, {
1507
+ timeout: hostOptions.timeout,
1508
+ family: hostOptions.family
1509
+ });
1510
+ const manifestJson = res.data;
1511
+ if (!manifestJson.metaData.types.zip) {
1512
+ throw new Error(`Can not get ${remoteInfo.name}'s types archive url!`);
1513
+ }
1514
+ const addProtocol = /* @__PURE__ */ __name((u) => {
1515
+ if (u.startsWith("//")) {
1516
+ return `https:${u}`;
1517
+ }
1518
+ return u;
1519
+ }, "addProtocol");
1520
+ let publicPath;
1521
+ if ("publicPath" in manifestJson.metaData) {
1522
+ publicPath = manifestJson.metaData.publicPath;
1523
+ } else {
1524
+ const getPublicPath = new Function(manifestJson.metaData.getPublicPath);
1525
+ if (manifestJson.metaData.getPublicPath.startsWith("function")) {
1526
+ publicPath = getPublicPath()();
1527
+ } else {
1528
+ publicPath = getPublicPath();
1529
+ }
1530
+ }
1531
+ if (publicPath === "auto") {
1532
+ publicPath = (0, import_sdk5.inferAutoPublicPath)(remoteInfo.url);
1533
+ }
1534
+ remoteInfo.zipUrl = new URL(import_path3.default.join(addProtocol(publicPath), manifestJson.metaData.types.zip)).href;
1535
+ if (!manifestJson.metaData.types.api) {
1536
+ console.warn(`Can not get ${remoteInfo.name}'s api types url!`);
1537
+ remoteInfo.apiTypeUrl = "";
1538
+ return remoteInfo;
1539
+ }
1540
+ remoteInfo.apiTypeUrl = new URL(import_path3.default.join(addProtocol(publicPath), manifestJson.metaData.types.api)).href;
1541
+ return remoteInfo;
1542
+ } catch (_err) {
1543
+ fileLog(`fetch manifest failed, ${_err}, ${remoteInfo.name} will be ignored`, "requestRemoteManifest", "error");
1544
+ return remoteInfo;
1545
+ }
1546
+ });
1547
+ }
1548
+ consumeTargetRemotes(hostOptions, remoteInfo) {
1549
+ return __async(this, null, function* () {
1550
+ if (!remoteInfo.zipUrl) {
1551
+ throw new Error(`Can not get ${remoteInfo.name}'s types archive url!`);
1552
+ }
1553
+ const typesDownloader = downloadTypesArchive(hostOptions);
1554
+ return typesDownloader([
1555
+ remoteInfo.alias,
1556
+ remoteInfo.zipUrl
1557
+ ]);
1558
+ });
1559
+ }
1560
+ downloadAPITypes(remoteInfo, destinationPath, hostOptions) {
1561
+ return __async(this, null, function* () {
1562
+ const { apiTypeUrl } = remoteInfo;
1563
+ if (!apiTypeUrl) {
1564
+ return;
1565
+ }
1566
+ try {
1567
+ const url = apiTypeUrl;
1568
+ const res = yield axiosGet(url, {
1569
+ timeout: hostOptions.timeout,
1570
+ family: hostOptions.family
1571
+ });
1572
+ let apiTypeFile = res.data;
1573
+ apiTypeFile = apiTypeFile.replaceAll(REMOTE_ALIAS_IDENTIFIER, remoteInfo.alias);
1574
+ const filePath = import_path3.default.join(destinationPath, REMOTE_API_TYPES_FILE_NAME);
1575
+ import_fs.default.writeFileSync(filePath, apiTypeFile);
1576
+ const existed = this.loadedRemoteAPIAlias.has(remoteInfo.alias);
1577
+ this.loadedRemoteAPIAlias.add(remoteInfo.alias);
1578
+ fileLog(`success`, "downloadAPITypes", "info");
1579
+ return existed;
1580
+ } catch (err) {
1581
+ fileLog(`Unable to download "${remoteInfo.name}" api types, ${err}`, "downloadAPITypes", "error");
1582
+ }
1583
+ });
1584
+ }
1585
+ consumeAPITypes(hostOptions) {
1586
+ const apiTypeFileName = import_path3.default.join(hostOptions.context, hostOptions.typesFolder, HOST_API_TYPES_FILE_NAME);
1587
+ try {
1588
+ const existedFile = import_fs.default.readFileSync(apiTypeFileName, "utf-8");
1589
+ const existedImports = new import_third_party_dts_extractor2.ThirdPartyExtractor({
1590
+ destDir: ""
1591
+ }).collectTypeImports(existedFile);
1592
+ existedImports.forEach((existedImport) => {
1593
+ const alias = existedImport.split("./").slice(1).join("./").replace("/apis.d.ts", "");
1594
+ this.loadedRemoteAPIAlias.add(alias);
1595
+ });
1596
+ } catch (err) {
1597
+ }
1598
+ if (!this.loadedRemoteAPIAlias.size) {
1599
+ return;
1600
+ }
1601
+ const packageTypes = [];
1602
+ const remoteKeys = [];
1603
+ const importTypeStr = [
1604
+ ...this.loadedRemoteAPIAlias
1605
+ ].sort().map((alias, index) => {
1606
+ const remoteKey = `RemoteKeys_${index}`;
1607
+ const packageType = `PackageType_${index}`;
1608
+ packageTypes.push(`T extends ${remoteKey} ? ${packageType}<T>`);
1609
+ remoteKeys.push(remoteKey);
1610
+ return `import type { PackageType as ${packageType},RemoteKeys as ${remoteKey} } from './${alias}/apis.d.ts';`;
1611
+ }).join("\n");
1612
+ const remoteKeysStr = `type RemoteKeys = ${remoteKeys.join(" | ")};`;
1613
+ const packageTypesStr = `type PackageType<T, Y=any> = ${[
1614
+ ...packageTypes,
1615
+ "Y"
1616
+ ].join(" :\n")} ;`;
1617
+ const runtimePkgs = /* @__PURE__ */ new Set();
1618
+ [
1619
+ ...this.runtimePkgs,
1620
+ ...hostOptions.runtimePkgs
1621
+ ].forEach((pkg) => {
1622
+ runtimePkgs.add(pkg);
1623
+ });
1624
+ const pkgsDeclareStr = [
1625
+ ...runtimePkgs
1626
+ ].map((pkg) => {
1627
+ return `declare module "${pkg}" {
1628
+ ${remoteKeysStr}
1629
+ ${packageTypesStr}
1630
+ export function loadRemote<T extends RemoteKeys,Y>(packageName: T): Promise<PackageType<T, Y>>;
1631
+ export function loadRemote<T extends string,Y>(packageName: T): Promise<PackageType<T, Y>>;
1632
+ }`;
1633
+ }).join("\n");
1634
+ const fileStr = `${importTypeStr}
1635
+ ${pkgsDeclareStr}
1636
+ `;
1637
+ import_fs.default.writeFileSync(import_path3.default.join(hostOptions.context, hostOptions.typesFolder, HOST_API_TYPES_FILE_NAME), fileStr);
1638
+ }
1639
+ consumeArchiveTypes(options) {
1640
+ return __async(this, null, function* () {
1641
+ const { hostOptions, mapRemotesToDownload } = retrieveHostConfig(options);
1642
+ const downloadPromises = Object.entries(mapRemotesToDownload).map((item) => __async(this, null, function* () {
1643
+ const remoteInfo = item[1];
1644
+ if (!this.remoteAliasMap[remoteInfo.alias]) {
1645
+ const requiredRemoteInfo = yield this.requestRemoteManifest(remoteInfo, hostOptions);
1646
+ this.remoteAliasMap[remoteInfo.alias] = requiredRemoteInfo;
1647
+ }
1648
+ return this.consumeTargetRemotes(hostOptions, this.remoteAliasMap[remoteInfo.alias]);
1649
+ }));
1650
+ const downloadPromisesResult = yield Promise.allSettled(downloadPromises);
1651
+ return {
1652
+ hostOptions,
1653
+ downloadPromisesResult
1654
+ };
1655
+ });
1656
+ }
1657
+ consumeTypes() {
1658
+ return __async(this, null, function* () {
1659
+ var _a3;
1660
+ try {
1661
+ const { options } = this;
1662
+ if (!options.host) {
1663
+ throw new Error("options.host is required if you want to consumeTypes");
1664
+ }
1665
+ const { mapRemotesToDownload } = retrieveHostConfig(options.host);
1666
+ if (!Object.keys(mapRemotesToDownload).length) {
1667
+ return;
1668
+ }
1669
+ const { downloadPromisesResult, hostOptions } = yield this.consumeArchiveTypes(options.host);
1670
+ if (hostOptions.consumeAPITypes) {
1671
+ yield Promise.all(downloadPromisesResult.map((item) => __async(this, null, function* () {
1672
+ if (item.status === "rejected" || !item.value) {
1673
+ return;
1674
+ }
1675
+ const [alias, destinationPath] = item.value;
1676
+ const remoteInfo = this.remoteAliasMap[alias];
1677
+ if (!remoteInfo) {
1678
+ return;
1679
+ }
1680
+ yield this.downloadAPITypes(remoteInfo, destinationPath, hostOptions);
1681
+ })));
1682
+ this.consumeAPITypes(hostOptions);
1683
+ }
1684
+ logger.success("Federated types extraction completed");
1685
+ } catch (err) {
1686
+ if (((_a3 = this.options.host) == null ? void 0 : _a3.abortOnError) === false) {
1687
+ fileLog(`Unable to consume federated types, ${err}`, "consumeTypes", "error");
1688
+ } else {
1689
+ throw err;
1690
+ }
1691
+ }
1692
+ });
1693
+ }
1694
+ updateTypes(options) {
1695
+ return __async(this, null, function* () {
1696
+ var _a3, _b, _c;
1697
+ try {
1698
+ const { remoteName, updateMode, remoteTarPath, remoteInfo: updatedRemoteInfo, once } = options;
1699
+ const hostName = (_c = (_b = (_a3 = this.options) == null ? void 0 : _a3.host) == null ? void 0 : _b.moduleFederationConfig) == null ? void 0 : _c.name;
1700
+ fileLog(`options: ${JSON.stringify(options, null, 2)};
1701
+ hostName: ${hostName}`, "updateTypes", "info");
1702
+ if (updateMode === UpdateMode.POSITIVE && remoteName === hostName) {
1703
+ if (!this.options.remote) {
1704
+ return;
1705
+ }
1706
+ yield this.generateTypes();
1707
+ } else {
1708
+ const { remoteAliasMap } = this;
1709
+ if (!this.options.host) {
1710
+ return;
1711
+ }
1712
+ const { hostOptions, mapRemotesToDownload } = retrieveHostConfig(this.options.host);
1713
+ const loadedRemoteInfo = Object.values(remoteAliasMap).find((i) => i.name === remoteName);
1714
+ const consumeTypes2 = /* @__PURE__ */ __name((requiredRemoteInfo) => __async(this, null, function* () {
1715
+ fileLog(`consumeTypes start`, "updateTypes", "info");
1716
+ if (!requiredRemoteInfo.zipUrl) {
1717
+ throw new Error(`Can not get ${requiredRemoteInfo.name}'s types archive url!`);
1718
+ }
1719
+ const [_alias, destinationPath] = yield this.consumeTargetRemotes(hostOptions, __spreadProps(__spreadValues({}, requiredRemoteInfo), {
1720
+ // use remoteTarPath first
1721
+ zipUrl: remoteTarPath || requiredRemoteInfo.zipUrl
1722
+ }));
1723
+ const addNew = yield this.downloadAPITypes(requiredRemoteInfo, destinationPath, hostOptions);
1724
+ if (addNew) {
1725
+ this.consumeAPITypes(hostOptions);
1726
+ }
1727
+ fileLog(`consumeTypes end`, "updateTypes", "info");
1728
+ }), "consumeTypes");
1729
+ fileLog(`loadedRemoteInfo: ${JSON.stringify(loadedRemoteInfo, null, 2)}`, "updateTypes", "info");
1730
+ if (!loadedRemoteInfo) {
1731
+ const remoteInfo = Object.values(mapRemotesToDownload).find((item) => {
1732
+ return item.name === remoteName;
1733
+ });
1734
+ fileLog(`remoteInfo: ${JSON.stringify(remoteInfo, null, 2)}`, "updateTypes", "info");
1735
+ if (remoteInfo) {
1736
+ if (!this.remoteAliasMap[remoteInfo.alias]) {
1737
+ const requiredRemoteInfo = yield this.requestRemoteManifest(remoteInfo, hostOptions);
1738
+ this.remoteAliasMap[remoteInfo.alias] = requiredRemoteInfo;
1739
+ }
1740
+ yield consumeTypes2(this.remoteAliasMap[remoteInfo.alias]);
1741
+ } else if (updatedRemoteInfo) {
1742
+ const consumeDynamicRemoteTypes = /* @__PURE__ */ __name(() => __async(this, null, function* () {
1743
+ yield consumeTypes2(this.updatedRemoteInfos[updatedRemoteInfo.name]);
1744
+ }), "consumeDynamicRemoteTypes");
1745
+ if (!this.updatedRemoteInfos[updatedRemoteInfo.name]) {
1746
+ const parsedRemoteInfo = retrieveRemoteInfo({
1747
+ hostOptions,
1748
+ remoteAlias: updatedRemoteInfo.alias || updatedRemoteInfo.name,
1749
+ remote: updatedRemoteInfo.url
1750
+ });
1751
+ fileLog(`start request manifest`, "consumeTypes", "info");
1752
+ this.updatedRemoteInfos[updatedRemoteInfo.name] = yield this.requestRemoteManifest(parsedRemoteInfo, hostOptions);
1753
+ fileLog(`end request manifest, this.updatedRemoteInfos[updatedRemoteInfo.name]: ${JSON.stringify(this.updatedRemoteInfos[updatedRemoteInfo.name], null, 2)}`, "updateTypes", "info");
1754
+ yield consumeDynamicRemoteTypes();
1755
+ }
1756
+ if (!once && this.updatedRemoteInfos[updatedRemoteInfo.name]) {
1757
+ yield consumeDynamicRemoteTypes();
1758
+ }
1759
+ }
1760
+ } else {
1761
+ yield consumeTypes2(loadedRemoteInfo);
1762
+ }
1763
+ }
1764
+ } catch (err) {
1765
+ fileLog(`updateTypes fail, ${err}`, "updateTypes", "error");
1766
+ }
1767
+ });
1768
+ }
1769
+ }, __name(_a, "DTSManager"), _a);
1770
+
1771
+ // src/core/lib/utils.ts
1772
+ var import_lodash = __toESM(require("lodash.clonedeepwith"));
1773
+ function getDTSManagerConstructor(implementation) {
1774
+ if (implementation) {
1775
+ const NewConstructor = require(implementation);
1776
+ return NewConstructor.default ? NewConstructor.default : NewConstructor;
1777
+ }
1778
+ return DTSManager;
1779
+ }
1780
+ __name(getDTSManagerConstructor, "getDTSManagerConstructor");
1781
+ var validateOptions = /* @__PURE__ */ __name((options) => {
1782
+ if (!options.moduleFederationConfig) {
1783
+ throw new Error("moduleFederationConfig is required");
1784
+ }
1785
+ }, "validateOptions");
1786
+ function retrieveTypesAssetsInfo(options) {
1787
+ const { moduleFederationConfig } = options;
1788
+ let apiTypesPath = "";
1789
+ let zipTypesPath = "";
1790
+ let zipPrefix = "";
1791
+ try {
1792
+ const { tsConfig, remoteOptions, mapComponentsToExpose } = retrieveRemoteConfig(options);
1793
+ if (!Object.keys(mapComponentsToExpose).length || !tsConfig.files.length) {
1794
+ return {
1795
+ zipPrefix,
1796
+ apiTypesPath,
1797
+ zipTypesPath,
1798
+ zipName: "",
1799
+ apiFileName: ""
1800
+ };
1801
+ }
1802
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
1803
+ zipTypesPath = retrieveTypesZipPath(mfTypesPath, remoteOptions);
1804
+ if (remoteOptions.generateAPITypes) {
1805
+ apiTypesPath = retrieveMfAPITypesPath(tsConfig, remoteOptions);
1806
+ }
1807
+ if (typeof moduleFederationConfig.manifest === "object" && moduleFederationConfig.manifest.filePath) {
1808
+ zipPrefix = moduleFederationConfig.manifest.filePath;
1809
+ } else if (typeof moduleFederationConfig.manifest === "object" && moduleFederationConfig.manifest.fileName) {
1810
+ zipPrefix = import_path4.default.dirname(moduleFederationConfig.manifest.fileName);
1811
+ } else if (moduleFederationConfig.filename) {
1812
+ zipPrefix = import_path4.default.dirname(moduleFederationConfig.filename);
1813
+ }
1814
+ return {
1815
+ zipPrefix,
1816
+ apiTypesPath,
1817
+ zipTypesPath,
1818
+ zipName: import_path4.default.basename(zipTypesPath),
1819
+ apiFileName: import_path4.default.basename(apiTypesPath)
1820
+ };
1821
+ } catch (err) {
1822
+ console.error(import_ansi_colors.default.red(`Unable to compile federated types, ${err}`));
1823
+ return {
1824
+ zipPrefix,
1825
+ apiTypesPath: "",
1826
+ zipTypesPath: "",
1827
+ zipName: "",
1828
+ apiFileName: ""
1829
+ };
1830
+ }
1831
+ }
1832
+ __name(retrieveTypesAssetsInfo, "retrieveTypesAssetsInfo");
1833
+ function isDebugMode() {
1834
+ return Boolean(process.env["FEDERATION_DEBUG"]) || process.env["NODE_ENV"] === "test";
1835
+ }
1836
+ __name(isDebugMode, "isDebugMode");
1837
+ var isTSProject = /* @__PURE__ */ __name((dtsOptions, context = process.cwd()) => {
1838
+ if (dtsOptions === false) {
1839
+ return false;
1840
+ }
1841
+ try {
1842
+ let filepath = "";
1843
+ if (typeof dtsOptions === "object" && dtsOptions.tsConfigPath) {
1844
+ filepath = dtsOptions.tsConfigPath;
1845
+ } else {
1846
+ filepath = import_path4.default.resolve(context, "./tsconfig.json");
1847
+ }
1848
+ if (!import_path4.default.isAbsolute(filepath)) {
1849
+ filepath = import_path4.default.resolve(context, filepath);
1850
+ }
1851
+ return import_fs2.default.existsSync(filepath);
1852
+ } catch (err) {
1853
+ return false;
1854
+ }
1855
+ }, "isTSProject");
1856
+ function cloneDeepOptions(options) {
1857
+ const excludeKeys = [
1858
+ "manifest",
1859
+ "async"
1860
+ ];
1861
+ return (0, import_lodash.default)(options, (value, key) => {
1862
+ if (typeof key === "string" && excludeKeys.includes(key)) {
1863
+ return false;
1864
+ }
1865
+ if (typeof value === "function") {
1866
+ return false;
1867
+ }
1868
+ if (key === "extractThirdParty" && Array.isArray(value)) {
1869
+ return value.map((item) => {
1870
+ return item.toString();
1871
+ });
1872
+ }
1873
+ });
1874
+ }
1875
+ __name(cloneDeepOptions, "cloneDeepOptions");
1876
+ var getEnvHeaders = /* @__PURE__ */ __name(() => {
1877
+ const headersStr = (0, import_sdk6.getProcessEnv)()["MF_ENV_HEADERS"] || "{}";
1878
+ return __spreadValues({}, JSON.parse(headersStr));
1879
+ }, "getEnvHeaders");
1880
+ function axiosGet(url, config) {
1881
+ return __async(this, null, function* () {
1882
+ var _a3, _b;
1883
+ const httpAgent = new import_http2.default.Agent({
1884
+ family: (_a3 = config == null ? void 0 : config.family) != null ? _a3 : 4
1885
+ });
1886
+ const httpsAgent = new import_https.default.Agent({
1887
+ family: (_b = config == null ? void 0 : config.family) != null ? _b : 4
1888
+ });
1889
+ return import_axios.default.get(url, __spreadProps(__spreadValues(__spreadValues({
1890
+ httpAgent,
1891
+ httpsAgent
1892
+ }, {
1893
+ headers: getEnvHeaders()
1894
+ }), config), {
1895
+ timeout: (config == null ? void 0 : config.timeout) || 6e4
1896
+ }));
1897
+ });
1898
+ }
1899
+ __name(axiosGet, "axiosGet");
1900
+
1901
+ // src/core/configurations/remotePlugin.ts
1902
+ var defaultOptions2 = {
1903
+ tsConfigPath: "./tsconfig.json",
1904
+ typesFolder: "@mf-types",
1905
+ compiledTypesFolder: "compiled-types",
1906
+ hostRemoteTypesFolder: "@mf-types",
1907
+ deleteTypesFolder: true,
1908
+ additionalFilesToCompile: [],
1909
+ compilerInstance: "tsc",
1910
+ compileInChildProcess: false,
1911
+ implementation: "",
1912
+ generateAPITypes: false,
1913
+ context: process.cwd(),
1914
+ abortOnError: true,
1915
+ extractRemoteTypes: false,
1916
+ extractThirdParty: false,
1917
+ outputDir: ""
1918
+ };
1919
+ function getEffectiveRootDir(parsedCommandLine) {
1920
+ const compilerOptions = parsedCommandLine.options;
1921
+ if (compilerOptions.rootDir) {
1922
+ return compilerOptions.rootDir;
1923
+ }
1924
+ const files = parsedCommandLine.fileNames;
1925
+ if (files.length > 0) {
1926
+ const commonRoot = files.map((file) => (0, import_path5.dirname)(file)).reduce((commonPath, fileDir) => {
1927
+ while (!fileDir.startsWith(commonPath)) {
1928
+ commonPath = (0, import_path5.dirname)(commonPath);
1929
+ }
1930
+ return commonPath;
1931
+ }, files[0]);
1932
+ return commonRoot;
1933
+ }
1934
+ throw new Error("Can not get effective rootDir, please set compilerOptions.rootDir !");
1935
+ }
1936
+ __name(getEffectiveRootDir, "getEffectiveRootDir");
1937
+ var getDependentFiles = /* @__PURE__ */ __name((rootFiles, configContent, rootDir) => {
1938
+ const program = import_typescript.default.createProgram(rootFiles, configContent.options);
1939
+ const sourceFiles = program.getSourceFiles();
1940
+ const dependentFiles = sourceFiles.map((file) => file.fileName).filter((file) => !file.endsWith(".d.ts") && file.startsWith(rootDir));
1941
+ return dependentFiles.length ? dependentFiles : rootFiles;
1942
+ }, "getDependentFiles");
1943
+ var readTsConfig = /* @__PURE__ */ __name(({ tsConfigPath, typesFolder, compiledTypesFolder, context, additionalFilesToCompile, outputDir }, mapComponentsToExpose) => {
1944
+ const resolvedTsConfigPath = (0, import_path5.resolve)(context, tsConfigPath);
1945
+ const readResult = import_typescript.default.readConfigFile(resolvedTsConfigPath, import_typescript.default.sys.readFile);
1946
+ if (readResult.error) {
1947
+ throw new Error(readResult.error.messageText.toString());
1948
+ }
1949
+ const rawTsConfigJson = readResult.config;
1950
+ const configContent = import_typescript.default.parseJsonConfigFileContent(rawTsConfigJson, import_typescript.default.sys, (0, import_path5.dirname)(resolvedTsConfigPath));
1951
+ const rootDir = getEffectiveRootDir(configContent);
1952
+ const outDir = (0, import_path5.resolve)(context, outputDir || configContent.options.outDir || "dist", typesFolder, compiledTypesFolder);
1953
+ const defaultCompilerOptions = {
1954
+ rootDir,
1955
+ emitDeclarationOnly: true,
1956
+ noEmit: false,
1957
+ declaration: true,
1958
+ outDir
1959
+ };
1960
+ rawTsConfigJson.compilerOptions = rawTsConfigJson.compilerOptions || {};
1961
+ rawTsConfigJson.compilerOptions = __spreadValues(__spreadValues({
1962
+ incremental: true,
1963
+ tsBuildInfoFile: (0, import_path5.resolve)(context, "node_modules/.cache/mf-types/.tsbuildinfo")
1964
+ }, rawTsConfigJson.compilerOptions), defaultCompilerOptions);
1965
+ const _a3 = rawTsConfigJson.compilerOptions || {}, { paths, baseUrl } = _a3, restCompilerOptions = __objRest(_a3, ["paths", "baseUrl"]);
1966
+ rawTsConfigJson.compilerOptions = restCompilerOptions;
1967
+ const outDirWithoutTypesFolder = (0, import_path5.resolve)(context, outputDir || configContent.options.outDir || "dist");
1968
+ const excludeExtensions = [
1969
+ ".mdx",
1970
+ ".md"
1971
+ ];
1972
+ const rootFiles = [
1973
+ ...Object.values(mapComponentsToExpose),
1974
+ ...additionalFilesToCompile
1975
+ ].filter((filename) => !excludeExtensions.some((ext) => filename.endsWith(ext)));
1976
+ const filesToCompile = [
1977
+ ...getDependentFiles(rootFiles, configContent, rootDir),
1978
+ ...configContent.fileNames.filter((filename) => filename.endsWith(".d.ts") && !filename.startsWith(outDirWithoutTypesFolder))
1979
+ ];
1980
+ rawTsConfigJson.include = [];
1981
+ rawTsConfigJson.files = [
1982
+ ...new Set(filesToCompile)
1983
+ ];
1984
+ rawTsConfigJson.exclude = [];
1985
+ "references" in rawTsConfigJson && delete rawTsConfigJson.references;
1986
+ rawTsConfigJson.extends = resolvedTsConfigPath;
1987
+ return rawTsConfigJson;
1988
+ }, "readTsConfig");
1989
+ var TS_EXTENSIONS = [
1990
+ "ts",
1991
+ "tsx",
1992
+ "vue",
1993
+ "svelte"
1994
+ ];
1995
+ var resolveWithExtension = /* @__PURE__ */ __name((exposedPath, context) => {
1996
+ if ((0, import_path5.extname)(exposedPath)) {
1997
+ return (0, import_path5.resolve)(context, exposedPath);
1998
+ }
1999
+ for (const extension of TS_EXTENSIONS) {
2000
+ const exposedPathWithExtension = (0, import_path5.resolve)(context, `${exposedPath}.${extension}`);
2001
+ if ((0, import_fs3.existsSync)(exposedPathWithExtension)) {
2002
+ return exposedPathWithExtension;
2003
+ }
2004
+ }
2005
+ return void 0;
2006
+ }, "resolveWithExtension");
2007
+ var resolveExposes = /* @__PURE__ */ __name((remoteOptions) => {
2008
+ const parsedOptions = import_managers2.utils.parseOptions(remoteOptions.moduleFederationConfig.exposes || {}, (item, key) => ({
2009
+ exposePath: Array.isArray(item) ? item[0] : item,
2010
+ key
2011
+ }), (item, key) => ({
2012
+ exposePath: Array.isArray(item.import) ? item.import[0] : item.import[0],
2013
+ key
2014
+ }));
2015
+ return parsedOptions.reduce((accumulator, item) => {
2016
+ const { exposePath, key } = item[1];
2017
+ accumulator[key] = resolveWithExtension(exposePath, remoteOptions.context) || resolveWithExtension((0, import_path5.join)(exposePath, "index"), remoteOptions.context) || exposePath;
2018
+ return accumulator;
2019
+ }, {});
2020
+ }, "resolveExposes");
2021
+ var retrieveRemoteConfig = /* @__PURE__ */ __name((options) => {
2022
+ validateOptions(options);
2023
+ const remoteOptions = __spreadValues(__spreadValues({}, defaultOptions2), options);
2024
+ const mapComponentsToExpose = resolveExposes(remoteOptions);
2025
+ const tsConfig = readTsConfig(remoteOptions, mapComponentsToExpose);
2026
+ if (tsConfig.compilerOptions.incremental && tsConfig.compilerOptions.tsBuildInfoFile && options.deleteTypesFolder !== true) {
2027
+ remoteOptions.deleteTypesFolder = false;
2028
+ }
2029
+ return {
2030
+ tsConfig,
2031
+ mapComponentsToExpose,
2032
+ remoteOptions
2033
+ };
2034
+ }, "retrieveRemoteConfig");
2035
+
2036
+ // src/core/lib/generateTypes.ts
2037
+ function generateTypes(options) {
2038
+ return __async(this, null, function* () {
2039
+ var _a3;
2040
+ const DTSManagerConstructor = getDTSManagerConstructor((_a3 = options.remote) == null ? void 0 : _a3.implementation);
2041
+ const dtsManager = new DTSManagerConstructor(options);
2042
+ return dtsManager.generateTypes();
2043
+ });
2044
+ }
2045
+ __name(generateTypes, "generateTypes");
2046
+
2047
+ // src/core/lib/DtsWorker.ts
2048
+ var import_path6 = __toESM(require("path"));
2049
+
2050
+ // src/core/rpc/index.ts
2051
+ var rpc_exports = {};
2052
+ __export(rpc_exports, {
2053
+ RpcExitError: () => RpcExitError,
2054
+ RpcGMCallTypes: () => RpcGMCallTypes,
2055
+ createRpcWorker: () => createRpcWorker,
2056
+ exposeRpc: () => exposeRpc,
2057
+ getRpcWorkerData: () => getRpcWorkerData,
2058
+ wrapRpc: () => wrapRpc
2059
+ });
2060
+
2061
+ // src/core/rpc/expose-rpc.ts
2062
+ var import_process = __toESM(require("process"));
2063
+
2064
+ // src/core/rpc/types.ts
2065
+ var RpcGMCallTypes;
2066
+ (function(RpcGMCallTypes2) {
2067
+ RpcGMCallTypes2["CALL"] = "mf_call";
2068
+ RpcGMCallTypes2["RESOLVE"] = "mf_resolve";
2069
+ RpcGMCallTypes2["REJECT"] = "mf_reject";
2070
+ RpcGMCallTypes2["EXIT"] = "mf_exit";
2071
+ })(RpcGMCallTypes || (RpcGMCallTypes = {}));
2072
+
2073
+ // src/core/rpc/expose-rpc.ts
2074
+ function exposeRpc(fn) {
2075
+ const sendMessage = /* @__PURE__ */ __name((message) => new Promise((resolve5, reject) => {
2076
+ if (!import_process.default.send) {
2077
+ reject(new Error(`Process ${import_process.default.pid} doesn't have IPC channels`));
2078
+ } else if (!import_process.default.connected) {
2079
+ reject(new Error(`Process ${import_process.default.pid} doesn't have open IPC channels`));
2080
+ } else {
2081
+ import_process.default.send(message, void 0, void 0, (error2) => {
2082
+ if (error2) {
2083
+ reject(error2);
2084
+ } else {
2085
+ resolve5(void 0);
2086
+ }
2087
+ });
2088
+ }
2089
+ }), "sendMessage");
2090
+ const handleMessage = /* @__PURE__ */ __name((message) => __async(this, null, function* () {
2091
+ if (message.type === RpcGMCallTypes.CALL) {
2092
+ if (!import_process.default.send) {
2093
+ return;
2094
+ }
2095
+ let value, error2;
2096
+ try {
2097
+ value = yield fn(...message.args);
2098
+ } catch (fnError) {
2099
+ error2 = fnError;
2100
+ }
2101
+ try {
2102
+ if (error2) {
2103
+ yield sendMessage({
2104
+ type: RpcGMCallTypes.REJECT,
2105
+ id: message.id,
2106
+ error: error2
2107
+ });
2108
+ } else {
2109
+ yield sendMessage({
2110
+ type: RpcGMCallTypes.RESOLVE,
2111
+ id: message.id,
2112
+ value
2113
+ });
2114
+ }
2115
+ } catch (sendError) {
2116
+ if (error2) {
2117
+ if (error2 instanceof Error) {
2118
+ console.error(error2);
2119
+ }
2120
+ }
2121
+ console.error(sendError);
2122
+ }
2123
+ }
2124
+ }), "handleMessage");
2125
+ import_process.default.on("message", handleMessage);
2126
+ }
2127
+ __name(exposeRpc, "exposeRpc");
2128
+
2129
+ // src/core/rpc/rpc-error.ts
2130
+ var _a2;
2131
+ var RpcExitError = (_a2 = class extends Error {
2132
+ constructor(message, code, signal) {
2133
+ super(message);
2134
+ __publicField(this, "code");
2135
+ __publicField(this, "signal");
2136
+ this.code = code, this.signal = signal;
2137
+ this.name = "RpcExitError";
2138
+ }
2139
+ }, __name(_a2, "RpcExitError"), _a2);
2140
+
2141
+ // src/core/rpc/wrap-rpc.ts
2142
+ function createControlledPromise() {
2143
+ let resolve5 = /* @__PURE__ */ __name(() => void 0, "resolve");
2144
+ let reject = /* @__PURE__ */ __name(() => void 0, "reject");
2145
+ const promise = new Promise((aResolve, aReject) => {
2146
+ resolve5 = aResolve;
2147
+ reject = aReject;
2148
+ });
2149
+ return {
2150
+ promise,
2151
+ resolve: resolve5,
2152
+ reject
2153
+ };
2154
+ }
2155
+ __name(createControlledPromise, "createControlledPromise");
2156
+ function wrapRpc(childProcess, options) {
2157
+ return (...args) => __async(this, null, function* () {
2158
+ if (!childProcess.send) {
2159
+ throw new Error(`Process ${childProcess.pid} doesn't have IPC channels`);
2160
+ } else if (!childProcess.connected) {
2161
+ throw new Error(`Process ${childProcess.pid} doesn't have open IPC channels`);
2162
+ }
2163
+ const { id, once } = options;
2164
+ const { promise: resultPromise, resolve: resolveResult, reject: rejectResult } = createControlledPromise();
2165
+ const { promise: sendPromise, resolve: resolveSend, reject: rejectSend } = createControlledPromise();
2166
+ const handleMessage = /* @__PURE__ */ __name((message) => {
2167
+ if ((message == null ? void 0 : message.id) === id) {
2168
+ if (message.type === RpcGMCallTypes.RESOLVE) {
2169
+ resolveResult(message.value);
2170
+ } else if (message.type === RpcGMCallTypes.REJECT) {
2171
+ rejectResult(message.error);
2172
+ }
2173
+ }
2174
+ if (once && (childProcess == null ? void 0 : childProcess.kill)) {
2175
+ childProcess.kill("SIGTERM");
2176
+ }
2177
+ }, "handleMessage");
2178
+ const handleClose = /* @__PURE__ */ __name((code, signal) => {
2179
+ rejectResult(new RpcExitError(code ? `Process ${childProcess.pid} exited with code ${code}${signal ? ` [${signal}]` : ""}` : `Process ${childProcess.pid} exited${signal ? ` [${signal}]` : ""}`, code, signal));
2180
+ removeHandlers();
2181
+ }, "handleClose");
2182
+ const removeHandlers = /* @__PURE__ */ __name(() => {
2183
+ childProcess.off("message", handleMessage);
2184
+ childProcess.off("close", handleClose);
2185
+ }, "removeHandlers");
2186
+ if (once) {
2187
+ childProcess.once("message", handleMessage);
2188
+ } else {
2189
+ childProcess.on("message", handleMessage);
2190
+ }
2191
+ childProcess.on("close", handleClose);
2192
+ childProcess.send({
2193
+ type: RpcGMCallTypes.CALL,
2194
+ id,
2195
+ args
2196
+ }, (error2) => {
2197
+ if (error2) {
2198
+ rejectSend(error2);
2199
+ removeHandlers();
2200
+ } else {
2201
+ resolveSend(void 0);
2202
+ }
2203
+ });
2204
+ return sendPromise.then(() => resultPromise);
2205
+ });
2206
+ }
2207
+ __name(wrapRpc, "wrapRpc");
2208
+
2209
+ // src/core/rpc/rpc-worker.ts
2210
+ var child_process = __toESM(require("child_process"));
2211
+ var process3 = __toESM(require("process"));
2212
+ var import_crypto2 = require("crypto");
2213
+ var FEDERATION_WORKER_DATA_ENV_KEY = "VMOK_WORKER_DATA_ENV";
2214
+ function createRpcWorker(modulePath, data, memoryLimit, once) {
2215
+ const options = {
2216
+ env: __spreadProps(__spreadValues({}, process3.env), {
2217
+ [FEDERATION_WORKER_DATA_ENV_KEY]: JSON.stringify(data || {})
2218
+ }),
2219
+ stdio: [
2220
+ "inherit",
2221
+ "inherit",
2222
+ "inherit",
2223
+ "ipc"
2224
+ ],
2225
+ serialization: "advanced"
2226
+ };
2227
+ if (memoryLimit) {
2228
+ options.execArgv = [
2229
+ `--max-old-space-size=${memoryLimit}`
2230
+ ];
2231
+ }
2232
+ let childProcess, remoteMethod;
2233
+ const id = (0, import_crypto2.randomUUID)();
2234
+ const worker = {
2235
+ connect(...args) {
2236
+ if (childProcess && !childProcess.connected) {
2237
+ childProcess.send({
2238
+ type: RpcGMCallTypes.EXIT,
2239
+ id
2240
+ });
2241
+ childProcess = void 0;
2242
+ remoteMethod = void 0;
2243
+ }
2244
+ if (!(childProcess == null ? void 0 : childProcess.connected)) {
2245
+ childProcess = child_process.fork(modulePath, options);
2246
+ remoteMethod = wrapRpc(childProcess, {
2247
+ id,
2248
+ once
2249
+ });
2250
+ }
2251
+ if (!remoteMethod) {
2252
+ return Promise.reject(new Error("Worker is not connected - cannot perform RPC."));
2253
+ }
2254
+ return remoteMethod(...args);
2255
+ },
2256
+ terminate() {
2257
+ try {
2258
+ if (childProcess.connected) {
2259
+ childProcess.send({
2260
+ type: RpcGMCallTypes.EXIT,
2261
+ id
2262
+ }, (err) => {
2263
+ if (err) {
2264
+ console.error("Error sending message:", err);
2265
+ }
2266
+ });
2267
+ }
2268
+ } catch (error2) {
2269
+ if (error2.code === "EPIPE") {
2270
+ console.error("Pipe closed before message could be sent:", error2);
2271
+ } else {
2272
+ console.error("Unexpected error:", error2);
2273
+ }
2274
+ }
2275
+ childProcess = void 0;
2276
+ remoteMethod = void 0;
2277
+ },
2278
+ get connected() {
2279
+ return Boolean(childProcess == null ? void 0 : childProcess.connected);
2280
+ },
2281
+ get process() {
2282
+ return childProcess;
2283
+ },
2284
+ get id() {
2285
+ return id;
2286
+ }
2287
+ };
2288
+ return worker;
2289
+ }
2290
+ __name(createRpcWorker, "createRpcWorker");
2291
+ function getRpcWorkerData() {
2292
+ return JSON.parse(process3.env[FEDERATION_WORKER_DATA_ENV_KEY] || "{}");
2293
+ }
2294
+ __name(getRpcWorkerData, "getRpcWorkerData");
2295
+
2296
+ // src/core/lib/DtsWorker.ts
2297
+ var _DtsWorker = class _DtsWorker {
2298
+ constructor(options) {
2299
+ __publicField(this, "rpcWorker");
2300
+ __publicField(this, "_options");
2301
+ __publicField(this, "_res");
2302
+ this._options = cloneDeepOptions(options);
2303
+ this.removeUnSerializationOptions();
2304
+ this.rpcWorker = createRpcWorker(import_path6.default.resolve(__dirname, "./fork-generate-dts.js"), {}, void 0, true);
2305
+ this._res = this.rpcWorker.connect(this._options);
2306
+ }
2307
+ removeUnSerializationOptions() {
2308
+ var _a3, _b, _c, _d, _e, _f, _g, _h;
2309
+ if ((_b = (_a3 = this._options.remote) == null ? void 0 : _a3.moduleFederationConfig) == null ? void 0 : _b.manifest) {
2310
+ (_d = (_c = this._options.remote) == null ? void 0 : _c.moduleFederationConfig) == null ? true : delete _d.manifest;
2311
+ }
2312
+ if ((_f = (_e = this._options.host) == null ? void 0 : _e.moduleFederationConfig) == null ? void 0 : _f.manifest) {
2313
+ (_h = (_g = this._options.host) == null ? void 0 : _g.moduleFederationConfig) == null ? true : delete _h.manifest;
2314
+ }
2315
+ }
2316
+ get controlledPromise() {
2317
+ const ensureChildProcessExit = /* @__PURE__ */ __name(() => {
2318
+ var _a3;
2319
+ try {
2320
+ const pid = (_a3 = this.rpcWorker.process) == null ? void 0 : _a3.pid;
2321
+ const rootPid = process.pid;
2322
+ if (pid && rootPid !== pid) {
2323
+ process.kill(pid, 0);
2324
+ }
2325
+ } catch (error2) {
2326
+ if (isDebugMode()) {
2327
+ console.error(error2);
2328
+ }
2329
+ }
2330
+ }, "ensureChildProcessExit");
2331
+ return Promise.resolve(this._res).then(() => {
2332
+ this.exit();
2333
+ ensureChildProcessExit();
2334
+ }).catch((err) => {
2335
+ if (isDebugMode()) {
2336
+ console.error(err);
2337
+ }
2338
+ ensureChildProcessExit();
2339
+ });
2340
+ }
2341
+ exit() {
2342
+ var _a3;
2343
+ try {
2344
+ (_a3 = this.rpcWorker) == null ? void 0 : _a3.terminate();
2345
+ } catch (err) {
2346
+ if (isDebugMode()) {
2347
+ console.error(err);
2348
+ }
2349
+ }
2350
+ }
2351
+ };
2352
+ __name(_DtsWorker, "DtsWorker");
2353
+ var DtsWorker = _DtsWorker;
2354
+
2355
+ // src/core/lib/generateTypesInChildProcess.ts
2356
+ function generateTypesInChildProcess(options) {
2357
+ return __async(this, null, function* () {
2358
+ const dtsWorker = new DtsWorker(options);
2359
+ return dtsWorker.controlledPromise;
2360
+ });
2361
+ }
2362
+ __name(generateTypesInChildProcess, "generateTypesInChildProcess");
2363
+
2364
+ // src/core/lib/consumeTypes.ts
2365
+ function consumeTypes(options) {
2366
+ return __async(this, null, function* () {
2367
+ var _a3;
2368
+ const DTSManagerConstructor = getDTSManagerConstructor((_a3 = options.host) == null ? void 0 : _a3.implementation);
2369
+ const dtsManager = new DTSManagerConstructor(options);
2370
+ yield dtsManager.consumeTypes();
2371
+ });
2372
+ }
2373
+ __name(consumeTypes, "consumeTypes");
2374
+
2375
+ // src/dev-worker/DevWorker.ts
2376
+ var _DevWorker = class _DevWorker {
2377
+ constructor(options) {
2378
+ __publicField(this, "_rpcWorker");
2379
+ __publicField(this, "_options");
2380
+ __publicField(this, "_res");
2381
+ this._options = cloneDeepOptions(options);
2382
+ this.removeUnSerializationOptions();
2383
+ this._rpcWorker = rpc_exports.createRpcWorker(import_path7.default.resolve(__dirname, "./fork-dev-worker.js"), {}, void 0, false);
2384
+ this._res = this._rpcWorker.connect(this._options);
2385
+ }
2386
+ // moduleFederationConfig.manifest may have un serialization options
2387
+ removeUnSerializationOptions() {
2388
+ var _a3, _b, _c, _d;
2389
+ (_b = (_a3 = this._options.host) == null ? void 0 : _a3.moduleFederationConfig) == null ? true : delete _b.manifest;
2390
+ (_d = (_c = this._options.remote) == null ? void 0 : _c.moduleFederationConfig) == null ? true : delete _d.manifest;
2391
+ }
2392
+ get controlledPromise() {
2393
+ return this._res;
2394
+ }
2395
+ update() {
2396
+ var _a3, _b;
2397
+ (_b = (_a3 = this._rpcWorker.process) == null ? void 0 : _a3.send) == null ? void 0 : _b.call(_a3, {
2398
+ type: rpc_exports.RpcGMCallTypes.CALL,
2399
+ id: this._rpcWorker.id,
2400
+ args: [
2401
+ void 0,
2402
+ "update"
2403
+ ]
2404
+ });
2405
+ }
2406
+ exit() {
2407
+ var _a3;
2408
+ (_a3 = this._rpcWorker) == null ? void 0 : _a3.terminate();
2409
+ }
2410
+ };
2411
+ __name(_DevWorker, "DevWorker");
2412
+ var DevWorker = _DevWorker;
2413
+
2414
+ // src/dev-worker/createDevWorker.ts
2415
+ function removeLogFile() {
2416
+ return __async(this, null, function* () {
2417
+ try {
2418
+ const logDir = path5.resolve(process.cwd(), ".mf/typesGenerate.log");
2419
+ yield fse2.remove(logDir);
2420
+ } catch (err) {
2421
+ console.error("removeLogFile error", "forkDevWorker", err);
2422
+ }
2423
+ });
2424
+ }
2425
+ __name(removeLogFile, "removeLogFile");
2426
+ function createDevWorker(options) {
2427
+ removeLogFile();
2428
+ return new DevWorker(__spreadValues({}, options));
2429
+ }
2430
+ __name(createDevWorker, "createDevWorker");
2431
+
2432
+ // src/plugins/DevPlugin.ts
2433
+ var import_sdk7 = require("@module-federation/sdk");
2434
+
2435
+ // src/plugins/utils.ts
2436
+ var import_path8 = __toESM(require("path"));
2437
+ function isDev() {
2438
+ return process.env["NODE_ENV"] === "development";
2439
+ }
2440
+ __name(isDev, "isDev");
2441
+ function isPrd() {
2442
+ return process.env["NODE_ENV"] === "production";
2443
+ }
2444
+ __name(isPrd, "isPrd");
2445
+ function getCompilerOutputDir(compiler) {
2446
+ try {
2447
+ return import_path8.default.relative(compiler.context, compiler.outputPath || compiler.options.output.path);
2448
+ } catch (err) {
2449
+ return "";
2450
+ }
2451
+ }
2452
+ __name(getCompilerOutputDir, "getCompilerOutputDir");
2453
+
2454
+ // src/plugins/DevPlugin.ts
2455
+ var PROCESS_EXIT_CODE;
2456
+ (function(PROCESS_EXIT_CODE2) {
2457
+ PROCESS_EXIT_CODE2[PROCESS_EXIT_CODE2["SUCCESS"] = 0] = "SUCCESS";
2458
+ PROCESS_EXIT_CODE2[PROCESS_EXIT_CODE2["FAILURE"] = 1] = "FAILURE";
2459
+ })(PROCESS_EXIT_CODE || (PROCESS_EXIT_CODE = {}));
2460
+ function ensureTempDir(filePath) {
2461
+ try {
2462
+ const dir = import_path9.default.dirname(filePath);
2463
+ import_fs_extra4.default.ensureDirSync(dir);
2464
+ } catch (_err) {
2465
+ }
2466
+ }
2467
+ __name(ensureTempDir, "ensureTempDir");
2468
+ var _DevPlugin = class _DevPlugin {
2469
+ constructor(options, dtsOptions, generateTypesPromise, fetchRemoteTypeUrlsPromise) {
2470
+ __publicField(this, "name", "MFDevPlugin");
2471
+ __publicField(this, "_options");
2472
+ __publicField(this, "_devWorker");
2473
+ __publicField(this, "dtsOptions");
2474
+ __publicField(this, "generateTypesPromise");
2475
+ __publicField(this, "fetchRemoteTypeUrlsPromise");
2476
+ this._options = options;
2477
+ this.generateTypesPromise = generateTypesPromise;
2478
+ this.dtsOptions = dtsOptions;
2479
+ this.fetchRemoteTypeUrlsPromise = fetchRemoteTypeUrlsPromise;
2480
+ }
2481
+ static ensureLiveReloadEntry(options, filePath) {
2482
+ ensureTempDir(filePath);
2483
+ const liveReloadEntry = import_fs_extra4.default.readFileSync(import_path9.default.join(__dirname, "./iife/launch-web-client.js")).toString("utf-8");
2484
+ const liveReloadEntryWithOptions = liveReloadEntry.replace(WEB_CLIENT_OPTIONS_IDENTIFIER, JSON.stringify(options));
2485
+ import_fs_extra4.default.writeFileSync(filePath, liveReloadEntryWithOptions);
2486
+ }
2487
+ _stopWhenSIGTERMOrSIGINT() {
2488
+ process.on("SIGTERM", () => {
2489
+ logger.info(`${this._options.name} Process(${process.pid}) SIGTERM, mf server will exit...`);
2490
+ this._exit(0);
2491
+ });
2492
+ process.on("SIGINT", () => {
2493
+ logger.info(`${this._options.name} Process(${process.pid}) SIGINT, mf server will exit...`);
2494
+ this._exit(0);
2495
+ });
2496
+ }
2497
+ _handleUnexpectedExit() {
2498
+ process.on("unhandledRejection", (error2) => {
2499
+ logger.error(error2);
2500
+ logger.error(`Process(${process.pid}) unhandledRejection, mf server will exit...`);
2501
+ this._exit(1);
2502
+ });
2503
+ process.on("uncaughtException", (error2) => {
2504
+ logger.error(error2);
2505
+ logger.error(`Process(${process.pid}) uncaughtException, mf server will exit...`);
2506
+ this._exit(1);
2507
+ });
2508
+ }
2509
+ _exit(exitCode = 0) {
2510
+ var _a3;
2511
+ (_a3 = this._devWorker) == null ? void 0 : _a3.exit();
2512
+ process.exit(exitCode);
2513
+ }
2514
+ _afterEmit() {
2515
+ var _a3;
2516
+ (_a3 = this._devWorker) == null ? void 0 : _a3.update();
2517
+ }
2518
+ apply(compiler) {
2519
+ var _a3;
2520
+ const { _options: { name, dev, dts } } = this;
2521
+ const normalizedDev = (0, import_sdk7.normalizeOptions)(true, {
2522
+ disableLiveReload: true,
2523
+ disableHotTypesReload: false,
2524
+ disableDynamicRemoteTypeHints: false
2525
+ }, "mfOptions.dev")(dev);
2526
+ if (!isDev() || normalizedDev === false) {
2527
+ return;
2528
+ }
2529
+ new compiler.webpack.DefinePlugin({
2530
+ FEDERATION_IPV4: JSON.stringify(getIPV4())
2531
+ }).apply(compiler);
2532
+ if (normalizedDev.disableHotTypesReload && normalizedDev.disableLiveReload && normalizedDev.disableDynamicRemoteTypeHints) {
2533
+ return;
2534
+ }
2535
+ if (!name) {
2536
+ throw new Error("name is required if you want to enable dev server!");
2537
+ }
2538
+ if (!normalizedDev.disableDynamicRemoteTypeHints) {
2539
+ if (!this._options.runtimePlugins) {
2540
+ this._options.runtimePlugins = [];
2541
+ }
2542
+ this._options.runtimePlugins.push(import_path9.default.resolve(__dirname, "dynamic-remote-type-hints-plugin.js"));
2543
+ }
2544
+ if (!normalizedDev.disableLiveReload) {
2545
+ const TEMP_DIR2 = import_path9.default.join(`${process.cwd()}/node_modules`, import_sdk7.TEMP_DIR);
2546
+ const filepath = import_path9.default.join(TEMP_DIR2, `live-reload.js`);
2547
+ if (typeof compiler.options.entry === "object") {
2548
+ _DevPlugin.ensureLiveReloadEntry({
2549
+ name
2550
+ }, filepath);
2551
+ Object.keys(compiler.options.entry).forEach((entry) => {
2552
+ const normalizedEntry = compiler.options.entry[entry];
2553
+ if (typeof normalizedEntry === "object" && Array.isArray(normalizedEntry.import)) {
2554
+ normalizedEntry.import.unshift(filepath);
2555
+ }
2556
+ });
2557
+ }
2558
+ }
2559
+ const defaultGenerateTypes = {
2560
+ compileInChildProcess: true
2561
+ };
2562
+ const defaultConsumeTypes = {
2563
+ consumeAPITypes: true
2564
+ };
2565
+ const normalizedDtsOptions = (0, import_sdk7.normalizeOptions)(isTSProject(dts, compiler.context), {
2566
+ // remote types dist(.dev-server) not be used currently, so no need to set extractThirdParty etc
2567
+ generateTypes: defaultGenerateTypes,
2568
+ consumeTypes: defaultConsumeTypes,
2569
+ extraOptions: {},
2570
+ displayErrorInTerminal: (_a3 = this.dtsOptions) == null ? void 0 : _a3.displayErrorInTerminal
2571
+ }, "mfOptions.dts")(dts);
2572
+ const normalizedGenerateTypes = (0, import_sdk7.normalizeOptions)(Boolean(normalizedDtsOptions), defaultGenerateTypes, "mfOptions.dts.generateTypes")(normalizedDtsOptions === false ? void 0 : normalizedDtsOptions.generateTypes);
2573
+ const remote = normalizedGenerateTypes === false ? void 0 : __spreadProps(__spreadValues({
2574
+ implementation: normalizedDtsOptions === false ? void 0 : normalizedDtsOptions.implementation,
2575
+ context: compiler.context,
2576
+ outputDir: getCompilerOutputDir(compiler),
2577
+ moduleFederationConfig: __spreadValues({}, this._options),
2578
+ hostRemoteTypesFolder: normalizedGenerateTypes.typesFolder || "@mf-types"
2579
+ }, normalizedGenerateTypes), {
2580
+ typesFolder: `.dev-server`
2581
+ });
2582
+ const normalizedConsumeTypes = (0, import_sdk7.normalizeOptions)(Boolean(normalizedDtsOptions), defaultConsumeTypes, "mfOptions.dts.consumeTypes")(normalizedDtsOptions === false ? void 0 : normalizedDtsOptions.consumeTypes);
2583
+ const host = normalizedConsumeTypes === false ? void 0 : __spreadValues({
2584
+ implementation: normalizedDtsOptions === false ? void 0 : normalizedDtsOptions.implementation,
2585
+ context: compiler.context,
2586
+ moduleFederationConfig: this._options,
2587
+ typesFolder: normalizedConsumeTypes.typesFolder || "@mf-types",
2588
+ abortOnError: false
2589
+ }, normalizedConsumeTypes);
2590
+ const extraOptions = normalizedDtsOptions ? normalizedDtsOptions.extraOptions || {} : {};
2591
+ if (!remote && !host && normalizedDev.disableLiveReload) {
2592
+ return;
2593
+ }
2594
+ if (remote && !(remote == null ? void 0 : remote.tsConfigPath) && typeof normalizedDtsOptions === "object" && normalizedDtsOptions.tsConfigPath) {
2595
+ remote.tsConfigPath = normalizedDtsOptions.tsConfigPath;
2596
+ }
2597
+ Promise.all([
2598
+ this.generateTypesPromise,
2599
+ this.fetchRemoteTypeUrlsPromise
2600
+ ]).then(([_, remoteTypeUrls]) => {
2601
+ this._devWorker = createDevWorker({
2602
+ name,
2603
+ remote,
2604
+ host: __spreadProps(__spreadValues({}, host), {
2605
+ remoteTypeUrls
2606
+ }),
2607
+ extraOptions,
2608
+ disableLiveReload: normalizedDev.disableHotTypesReload,
2609
+ disableHotTypesReload: normalizedDev.disableHotTypesReload
2610
+ });
2611
+ });
2612
+ this._stopWhenSIGTERMOrSIGINT();
2613
+ this._handleUnexpectedExit();
2614
+ compiler.hooks.afterEmit.tap(this.name, this._afterEmit.bind(this));
2615
+ }
2616
+ };
2617
+ __name(_DevPlugin, "DevPlugin");
2618
+ var DevPlugin = _DevPlugin;
2619
+
2620
+ // src/plugins/DtsPlugin.ts
2621
+ var import_sdk11 = require("@module-federation/sdk");
2622
+
2623
+ // src/plugins/ConsumeTypesPlugin.ts
2624
+ var import_sdk8 = require("@module-federation/sdk");
2625
+ var import_sdk9 = require("@module-federation/sdk");
2626
+ var DEFAULT_CONSUME_TYPES = {
2627
+ abortOnError: false,
2628
+ consumeAPITypes: true,
2629
+ typesOnBuild: false
2630
+ };
2631
+ var normalizeConsumeTypesOptions = /* @__PURE__ */ __name(({ context, dtsOptions, pluginOptions }) => {
2632
+ const normalizedConsumeTypes = (0, import_sdk9.normalizeOptions)(true, DEFAULT_CONSUME_TYPES, "mfOptions.dts.consumeTypes")(dtsOptions.consumeTypes);
2633
+ if (!normalizedConsumeTypes) {
2634
+ return;
2635
+ }
2636
+ const dtsManagerOptions = {
2637
+ host: __spreadValues({
2638
+ implementation: dtsOptions.implementation,
2639
+ context,
2640
+ moduleFederationConfig: pluginOptions
2641
+ }, normalizedConsumeTypes),
2642
+ extraOptions: dtsOptions.extraOptions || {},
2643
+ displayErrorInTerminal: dtsOptions.displayErrorInTerminal
2644
+ };
2645
+ validateOptions(dtsManagerOptions.host);
2646
+ return dtsManagerOptions;
2647
+ }, "normalizeConsumeTypesOptions");
2648
+ var consumeTypesAPI = /* @__PURE__ */ __name((dtsManagerOptions, cb) => __async(void 0, null, function* () {
2649
+ const fetchRemoteTypeUrlsPromise = typeof dtsManagerOptions.host.remoteTypeUrls === "function" ? dtsManagerOptions.host.remoteTypeUrls() : Promise.resolve(dtsManagerOptions.host.remoteTypeUrls);
2650
+ return fetchRemoteTypeUrlsPromise.then((remoteTypeUrls) => {
2651
+ consumeTypes(__spreadProps(__spreadValues({}, dtsManagerOptions), {
2652
+ host: __spreadProps(__spreadValues({}, dtsManagerOptions.host), {
2653
+ remoteTypeUrls
2654
+ })
2655
+ })).then(() => {
2656
+ typeof cb === "function" && cb(remoteTypeUrls);
2657
+ }).catch(() => {
2658
+ typeof cb === "function" && cb(remoteTypeUrls);
2659
+ });
2660
+ });
2661
+ }), "consumeTypesAPI");
2662
+ var _ConsumeTypesPlugin = class _ConsumeTypesPlugin {
2663
+ constructor(pluginOptions, dtsOptions, fetchRemoteTypeUrlsResolve) {
2664
+ __publicField(this, "pluginOptions");
2665
+ __publicField(this, "dtsOptions");
2666
+ __publicField(this, "callback");
2667
+ __publicField(this, "fetchRemoteTypeUrlsResolve");
2668
+ this.pluginOptions = pluginOptions;
2669
+ this.dtsOptions = dtsOptions;
2670
+ this.fetchRemoteTypeUrlsResolve = fetchRemoteTypeUrlsResolve;
2671
+ }
2672
+ apply(compiler) {
2673
+ const { dtsOptions, pluginOptions, fetchRemoteTypeUrlsResolve } = this;
2674
+ const dtsManagerOptions = normalizeConsumeTypesOptions({
2675
+ context: compiler.context,
2676
+ dtsOptions,
2677
+ pluginOptions
2678
+ });
2679
+ if (!dtsManagerOptions) {
2680
+ fetchRemoteTypeUrlsResolve(void 0);
2681
+ return;
2682
+ }
2683
+ if (isPrd() && !dtsManagerOptions.host.typesOnBuild) {
2684
+ fetchRemoteTypeUrlsResolve(void 0);
2685
+ return;
2686
+ }
2687
+ import_sdk8.infrastructureLogger.debug("start fetching remote types...");
2688
+ const promise = consumeTypesAPI(dtsManagerOptions, fetchRemoteTypeUrlsResolve);
2689
+ compiler.hooks.thisCompilation.tap("mf:generateTypes", (compilation) => {
2690
+ compilation.hooks.processAssets.tapPromise({
2691
+ name: "mf:generateTypes",
2692
+ stage: (
2693
+ // @ts-expect-error use runtime variable in case peer dep not installed , it should execute before generate types
2694
+ compilation.constructor.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER - 1
2695
+ )
2696
+ }, () => __async(this, null, function* () {
2697
+ yield promise;
2698
+ import_sdk8.infrastructureLogger.debug("fetch remote types success!");
2699
+ }));
2700
+ });
2701
+ }
2702
+ };
2703
+ __name(_ConsumeTypesPlugin, "ConsumeTypesPlugin");
2704
+ var ConsumeTypesPlugin = _ConsumeTypesPlugin;
2705
+
2706
+ // src/plugins/GenerateTypesPlugin.ts
2707
+ var import_fs4 = __toESM(require("fs"));
2708
+ var import_path10 = __toESM(require("path"));
2709
+ var import_sdk10 = require("@module-federation/sdk");
2710
+ var DEFAULT_GENERATE_TYPES = {
2711
+ generateAPITypes: true,
2712
+ compileInChildProcess: true,
2713
+ abortOnError: false,
2714
+ extractThirdParty: false,
2715
+ extractRemoteTypes: false
2716
+ };
2717
+ var normalizeGenerateTypesOptions = /* @__PURE__ */ __name(({ context, outputDir, dtsOptions, pluginOptions }) => {
2718
+ const normalizedGenerateTypes = (0, import_sdk10.normalizeOptions)(true, DEFAULT_GENERATE_TYPES, "mfOptions.dts.generateTypes")(dtsOptions.generateTypes);
2719
+ if (!normalizedGenerateTypes) {
2720
+ return;
2721
+ }
2722
+ const normalizedConsumeTypes = (0, import_sdk10.normalizeOptions)(true, {}, "mfOptions.dts.consumeTypes")(dtsOptions.consumeTypes);
2723
+ const finalOptions = {
2724
+ remote: __spreadValues({
2725
+ implementation: dtsOptions.implementation,
2726
+ context,
2727
+ outputDir,
2728
+ moduleFederationConfig: pluginOptions
2729
+ }, normalizedGenerateTypes),
2730
+ host: normalizedConsumeTypes === false ? void 0 : __spreadProps(__spreadValues({
2731
+ context,
2732
+ moduleFederationConfig: pluginOptions
2733
+ }, normalizedConsumeTypes), {
2734
+ // generateTypes only use host basic config, eg: typeFolders
2735
+ remoteTypeUrls: typeof (normalizedConsumeTypes == null ? void 0 : normalizedConsumeTypes.remoteTypeUrls) === "object" ? normalizedConsumeTypes == null ? void 0 : normalizedConsumeTypes.remoteTypeUrls : void 0
2736
+ }),
2737
+ extraOptions: dtsOptions.extraOptions || {},
2738
+ displayErrorInTerminal: dtsOptions.displayErrorInTerminal
2739
+ };
2740
+ if (dtsOptions.tsConfigPath && !finalOptions.remote.tsConfigPath) {
2741
+ finalOptions.remote.tsConfigPath = dtsOptions.tsConfigPath;
2742
+ }
2743
+ validateOptions(finalOptions.remote);
2744
+ return finalOptions;
2745
+ }, "normalizeGenerateTypesOptions");
2746
+ var getGenerateTypesFn = /* @__PURE__ */ __name((dtsManagerOptions) => {
2747
+ let fn = generateTypes;
2748
+ if (dtsManagerOptions.remote.compileInChildProcess) {
2749
+ fn = generateTypesInChildProcess;
2750
+ }
2751
+ return fn;
2752
+ }, "getGenerateTypesFn");
2753
+ var generateTypesAPI = /* @__PURE__ */ __name(({ dtsManagerOptions }) => {
2754
+ const fn = getGenerateTypesFn(dtsManagerOptions);
2755
+ return fn(dtsManagerOptions);
2756
+ }, "generateTypesAPI");
2757
+ var _GenerateTypesPlugin = class _GenerateTypesPlugin {
2758
+ constructor(pluginOptions, dtsOptions, fetchRemoteTypeUrlsPromise, callback) {
2759
+ __publicField(this, "pluginOptions");
2760
+ __publicField(this, "dtsOptions");
2761
+ __publicField(this, "fetchRemoteTypeUrlsPromise");
2762
+ __publicField(this, "callback");
2763
+ this.pluginOptions = pluginOptions;
2764
+ this.dtsOptions = dtsOptions;
2765
+ this.fetchRemoteTypeUrlsPromise = fetchRemoteTypeUrlsPromise;
2766
+ this.callback = callback;
2767
+ }
2768
+ apply(compiler) {
2769
+ const { dtsOptions, pluginOptions, fetchRemoteTypeUrlsPromise, callback } = this;
2770
+ const outputDir = getCompilerOutputDir(compiler);
2771
+ const context = compiler.context;
2772
+ const dtsManagerOptions = normalizeGenerateTypesOptions({
2773
+ context,
2774
+ outputDir,
2775
+ dtsOptions,
2776
+ pluginOptions
2777
+ });
2778
+ if (!dtsManagerOptions) {
2779
+ callback();
2780
+ return;
2781
+ }
2782
+ const isProd = !isDev();
2783
+ const emitTypesFiles = /* @__PURE__ */ __name((compilation) => __async(this, null, function* () {
2784
+ try {
2785
+ const { zipTypesPath, apiTypesPath, zipName, apiFileName } = retrieveTypesAssetsInfo(dtsManagerOptions.remote);
2786
+ if (isProd && zipName && compilation.getAsset(zipName)) {
2787
+ callback();
2788
+ return;
2789
+ }
2790
+ import_sdk10.logger.debug("start generating types...");
2791
+ yield generateTypesAPI({
2792
+ dtsManagerOptions
2793
+ });
2794
+ import_sdk10.logger.debug("generate types success!");
2795
+ const config = dtsManagerOptions.remote.moduleFederationConfig;
2796
+ let zipPrefix = "";
2797
+ if (typeof config.manifest === "object" && config.manifest.filePath) {
2798
+ zipPrefix = config.manifest.filePath;
2799
+ } else if (typeof config.manifest === "object" && config.manifest.fileName) {
2800
+ zipPrefix = import_path10.default.dirname(config.manifest.fileName);
2801
+ } else if (config.filename) {
2802
+ zipPrefix = import_path10.default.dirname(config.filename);
2803
+ }
2804
+ if (isProd) {
2805
+ const zipAssetName = import_path10.default.join(zipPrefix, zipName);
2806
+ const apiAssetName = import_path10.default.join(zipPrefix, apiFileName);
2807
+ if (zipTypesPath && !compilation.getAsset(zipAssetName) && import_fs4.default.existsSync(zipTypesPath)) {
2808
+ compilation.emitAsset(zipAssetName, new compiler.webpack.sources.RawSource(import_fs4.default.readFileSync(zipTypesPath), false));
2809
+ }
2810
+ if (apiTypesPath && !compilation.getAsset(apiAssetName) && import_fs4.default.existsSync(apiTypesPath)) {
2811
+ compilation.emitAsset(apiAssetName, new compiler.webpack.sources.RawSource(import_fs4.default.readFileSync(apiTypesPath), false));
2812
+ }
2813
+ callback();
2814
+ } else {
2815
+ const isEEXIST = /* @__PURE__ */ __name((err) => {
2816
+ return err.code == "EEXIST";
2817
+ }, "isEEXIST");
2818
+ if (zipTypesPath && import_fs4.default.existsSync(zipTypesPath)) {
2819
+ const zipContent = import_fs4.default.readFileSync(zipTypesPath);
2820
+ const zipOutputPath = import_path10.default.join(compiler.outputPath, zipPrefix, zipName);
2821
+ yield new Promise((resolve5, reject) => {
2822
+ compiler.outputFileSystem.mkdir(
2823
+ import_path10.default.dirname(zipOutputPath),
2824
+ {
2825
+ recursive: true
2826
+ },
2827
+ // @ts-ignore type fixed in https://github.com/webpack/webpack/releases/tag/v5.91.0
2828
+ (err) => {
2829
+ if (err && !isEEXIST(err)) {
2830
+ reject(err);
2831
+ } else {
2832
+ compiler.outputFileSystem.writeFile(
2833
+ zipOutputPath,
2834
+ // @ts-ignore
2835
+ zipContent,
2836
+ (writeErr) => {
2837
+ if (writeErr && !isEEXIST(writeErr)) {
2838
+ reject(writeErr);
2839
+ } else {
2840
+ resolve5();
2841
+ }
2842
+ }
2843
+ );
2844
+ }
2845
+ }
2846
+ );
2847
+ });
2848
+ }
2849
+ if (apiTypesPath && import_fs4.default.existsSync(apiTypesPath)) {
2850
+ const apiContent = import_fs4.default.readFileSync(apiTypesPath);
2851
+ const apiOutputPath = import_path10.default.join(compiler.outputPath, zipPrefix, apiFileName);
2852
+ yield new Promise((resolve5, reject) => {
2853
+ compiler.outputFileSystem.mkdir(
2854
+ import_path10.default.dirname(apiOutputPath),
2855
+ {
2856
+ recursive: true
2857
+ },
2858
+ // @ts-ignore type fixed in https://github.com/webpack/webpack/releases/tag/v5.91.0
2859
+ (err) => {
2860
+ if (err && !isEEXIST(err)) {
2861
+ reject(err);
2862
+ } else {
2863
+ compiler.outputFileSystem.writeFile(
2864
+ apiOutputPath,
2865
+ // @ts-ignore
2866
+ apiContent,
2867
+ (writeErr) => {
2868
+ if (writeErr && !isEEXIST(writeErr)) {
2869
+ reject(writeErr);
2870
+ } else {
2871
+ resolve5();
2872
+ }
2873
+ }
2874
+ );
2875
+ }
2876
+ }
2877
+ );
2878
+ });
2879
+ }
2880
+ callback();
2881
+ }
2882
+ } catch (err) {
2883
+ callback();
2884
+ if (dtsManagerOptions.displayErrorInTerminal) {
2885
+ console.error(err);
2886
+ }
2887
+ import_sdk10.logger.debug("generate types fail!");
2888
+ }
2889
+ }), "emitTypesFiles");
2890
+ compiler.hooks.thisCompilation.tap("mf:generateTypes", (compilation) => {
2891
+ compilation.hooks.processAssets.tapPromise({
2892
+ name: "mf:generateTypes",
2893
+ stage: (
2894
+ // @ts-expect-error use runtime variable in case peer dep not installed
2895
+ compilation.constructor.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER
2896
+ )
2897
+ }, () => __async(this, null, function* () {
2898
+ yield fetchRemoteTypeUrlsPromise;
2899
+ const emitTypesFilesPromise = emitTypesFiles(compilation);
2900
+ if (isProd) {
2901
+ yield emitTypesFilesPromise;
2902
+ }
2903
+ }));
2904
+ });
2905
+ }
2906
+ };
2907
+ __name(_GenerateTypesPlugin, "GenerateTypesPlugin");
2908
+ var GenerateTypesPlugin = _GenerateTypesPlugin;
2909
+
2910
+ // src/plugins/DtsPlugin.ts
2911
+ var normalizeDtsOptions = /* @__PURE__ */ __name((options, context, defaultOptions3) => {
2912
+ return (0, import_sdk11.normalizeOptions)(isTSProject(options.dts, context), {
2913
+ generateTypes: (defaultOptions3 == null ? void 0 : defaultOptions3.defaultGenerateOptions) || DEFAULT_GENERATE_TYPES,
2914
+ consumeTypes: (defaultOptions3 == null ? void 0 : defaultOptions3.defaultConsumeOptions) || DEFAULT_CONSUME_TYPES,
2915
+ extraOptions: {},
2916
+ displayErrorInTerminal: true
2917
+ }, "mfOptions.dts")(options.dts);
2918
+ }, "normalizeDtsOptions");
2919
+ var excludeDts = /* @__PURE__ */ __name((filepath) => {
2920
+ if (typeof filepath !== "string") {
2921
+ return false;
2922
+ }
2923
+ const [_p, query] = filepath.split("?");
2924
+ if (query && query.startsWith("exclude-mf-dts")) {
2925
+ return true;
2926
+ }
2927
+ return false;
2928
+ }, "excludeDts");
2929
+ var _DtsPlugin = class _DtsPlugin {
2930
+ constructor(options) {
2931
+ __publicField(this, "options");
2932
+ __publicField(this, "clonedOptions");
2933
+ this.options = options;
2934
+ this.clonedOptions = __spreadValues({}, options);
2935
+ }
2936
+ apply(compiler) {
2937
+ const { options, clonedOptions } = this;
2938
+ if (options.exposes && typeof options.exposes === "object") {
2939
+ const cleanedExposes = {};
2940
+ Object.entries(options.exposes).forEach(([key, value]) => {
2941
+ if (typeof value === "string") {
2942
+ const [filepath, _query] = value.split("?");
2943
+ if (excludeDts(value)) {
2944
+ return;
2945
+ }
2946
+ cleanedExposes[key] = filepath;
2947
+ } else {
2948
+ if (typeof value === "object" && Array.isArray(value.import) && value.import.some((v) => excludeDts(v))) {
2949
+ return;
2950
+ }
2951
+ cleanedExposes[key] = value;
2952
+ }
2953
+ });
2954
+ clonedOptions.exposes = cleanedExposes;
2955
+ }
2956
+ const normalizedDtsOptions = normalizeDtsOptions(clonedOptions, compiler.context);
2957
+ if (typeof normalizedDtsOptions !== "object") {
2958
+ return;
2959
+ }
2960
+ let fetchRemoteTypeUrlsResolve;
2961
+ const fetchRemoteTypeUrlsPromise = new Promise((resolve5) => {
2962
+ fetchRemoteTypeUrlsResolve = resolve5;
2963
+ });
2964
+ let generateTypesPromiseResolve;
2965
+ const generateTypesPromise = new Promise((resolve5) => {
2966
+ generateTypesPromiseResolve = resolve5;
2967
+ });
2968
+ new DevPlugin(clonedOptions, normalizedDtsOptions, generateTypesPromise, fetchRemoteTypeUrlsPromise).apply(compiler);
2969
+ new GenerateTypesPlugin(clonedOptions, normalizedDtsOptions, fetchRemoteTypeUrlsPromise, generateTypesPromiseResolve).apply(compiler);
2970
+ new ConsumeTypesPlugin(clonedOptions, normalizedDtsOptions, fetchRemoteTypeUrlsResolve).apply(compiler);
2971
+ }
2972
+ addRuntimePlugins() {
2973
+ const { options, clonedOptions } = this;
2974
+ if (!clonedOptions.runtimePlugins) {
2975
+ return;
2976
+ }
2977
+ if (!options.runtimePlugins) {
2978
+ options.runtimePlugins = [];
2979
+ }
2980
+ clonedOptions.runtimePlugins.forEach((plugin) => {
2981
+ options.runtimePlugins.includes(plugin) || options.runtimePlugins.push(plugin);
2982
+ });
2983
+ }
2984
+ };
2985
+ __name(_DtsPlugin, "DtsPlugin");
2986
+ var DtsPlugin = _DtsPlugin;
2987
+ // Annotate the CommonJS export names for ESM import in node:
2988
+ 0 && (module.exports = {
2989
+ DtsPlugin,
2990
+ consumeTypesAPI,
2991
+ generateTypesAPI,
2992
+ isTSProject,
2993
+ normalizeConsumeTypesOptions,
2994
+ normalizeDtsOptions,
2995
+ normalizeGenerateTypesOptions
2996
+ });