@module-federation/dts-plugin 0.1.5 → 0.1.7

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