@module-federation/dts-plugin 0.1.19 → 0.1.21

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