@module-federation/dts-plugin 0.1.4 → 0.1.6

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