@module-federation/dts-plugin 0.1.19 → 0.1.21

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