@module-federation/dts-plugin 0.1.2 → 0.1.3

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.
@@ -0,0 +1,831 @@
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, (error) => {
49
+ if (error) {
50
+ reject(error);
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, error;
63
+ try {
64
+ value = await fn(...message.args);
65
+ } catch (fnError) {
66
+ error = fnError;
67
+ }
68
+ try {
69
+ if (error) {
70
+ await sendMessage({
71
+ type: "mf_reject" /* REJECT */,
72
+ id: message.id,
73
+ error
74
+ });
75
+ } else {
76
+ await sendMessage({
77
+ type: "mf_resolve" /* RESOLVE */,
78
+ id: message.id,
79
+ value
80
+ });
81
+ }
82
+ } catch (sendError) {
83
+ if (error) {
84
+ if (error instanceof Error) {
85
+ console.error(error);
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_colors3 = __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_sdk2 = require("@module-federation/sdk");
210
+ var import_lodash = __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_ansi_colors2 = __toESM(require("ansi-colors"));
215
+ var import_axios = __toESM(require("axios"));
216
+ var import_path3 = require("path");
217
+
218
+ // packages/dts-plugin/src/core/lib/typeScriptCompiler.ts
219
+ var import_ansi_colors = __toESM(require("ansi-colors"));
220
+ var import_path2 = require("path");
221
+ var import_typescript2 = __toESM(require("typescript"));
222
+ var import_third_party_dts_extractor = require("@module-federation/third-party-dts-extractor");
223
+ var STARTS_WITH_SLASH = /^\//;
224
+ var DEFINITION_FILE_EXTENSION = ".d.ts";
225
+ var reportCompileDiagnostic = (diagnostic) => {
226
+ const { line } = diagnostic.file.getLineAndCharacterOfPosition(
227
+ diagnostic.start
228
+ );
229
+ console.error(
230
+ import_ansi_colors.default.red(
231
+ `TS Error ${diagnostic.code}':' ${import_typescript2.default.flattenDiagnosticMessageText(
232
+ diagnostic.messageText,
233
+ import_typescript2.default.sys.newLine
234
+ )}`
235
+ )
236
+ );
237
+ console.error(
238
+ import_ansi_colors.default.red(
239
+ ` at ${diagnostic.file.fileName}:${line + 1} typescript.sys.newLine`
240
+ )
241
+ );
242
+ };
243
+ var retrieveMfTypesPath = (tsConfig, remoteOptions) => (0, import_path2.normalize)(tsConfig.outDir.replace(remoteOptions.compiledTypesFolder, ""));
244
+ var retrieveOriginalOutDir = (tsConfig, remoteOptions) => (0, import_path2.normalize)(
245
+ tsConfig.outDir.replace(remoteOptions.compiledTypesFolder, "").replace(remoteOptions.typesFolder, "")
246
+ );
247
+ var retrieveMfAPITypesPath = (tsConfig, remoteOptions) => (0, import_path2.join)(
248
+ retrieveOriginalOutDir(tsConfig, remoteOptions),
249
+ `${remoteOptions.typesFolder}.d.ts`
250
+ );
251
+ var createHost = (mapComponentsToExpose, tsConfig, remoteOptions, cb) => {
252
+ const host = import_typescript2.default.createCompilerHost(tsConfig);
253
+ const originalWriteFile = host.writeFile;
254
+ const mapExposeToEntry = Object.fromEntries(
255
+ Object.entries(mapComponentsToExpose).map((entry) => entry.reverse())
256
+ );
257
+ const mfTypePath = retrieveMfTypesPath(tsConfig, remoteOptions);
258
+ host.writeFile = (filepath, text, writeOrderByteMark, onError, sourceFiles, data) => {
259
+ originalWriteFile(
260
+ filepath,
261
+ text,
262
+ writeOrderByteMark,
263
+ onError,
264
+ sourceFiles,
265
+ data
266
+ );
267
+ for (const sourceFile of sourceFiles || []) {
268
+ const sourceEntry = mapExposeToEntry[sourceFile.fileName];
269
+ if (sourceEntry) {
270
+ const mfeTypeEntry = (0, import_path2.join)(
271
+ mfTypePath,
272
+ `${sourceEntry}${DEFINITION_FILE_EXTENSION}`
273
+ );
274
+ const mfeTypeEntryDirectory = (0, import_path2.dirname)(mfeTypeEntry);
275
+ const relativePathToOutput = (0, import_path2.relative)(mfeTypeEntryDirectory, filepath).replace(DEFINITION_FILE_EXTENSION, "").replace(STARTS_WITH_SLASH, "");
276
+ originalWriteFile(
277
+ mfeTypeEntry,
278
+ `export * from './${relativePathToOutput}';
279
+ export { default } from './${relativePathToOutput}';`,
280
+ writeOrderByteMark
281
+ );
282
+ }
283
+ }
284
+ cb(text);
285
+ };
286
+ return host;
287
+ };
288
+ var createVueTscProgram = (programOptions) => {
289
+ const vueTypescript = require("vue-tsc");
290
+ return vueTypescript.createProgram(programOptions);
291
+ };
292
+ var createProgram = (remoteOptions, programOptions) => {
293
+ switch (remoteOptions.compilerInstance) {
294
+ case "vue-tsc":
295
+ return createVueTscProgram(programOptions);
296
+ case "tsc":
297
+ default:
298
+ return import_typescript2.default.createProgram(programOptions);
299
+ }
300
+ };
301
+ var compileTs = (mapComponentsToExpose, tsConfig, remoteOptions) => {
302
+ const mfTypePath = retrieveMfTypesPath(tsConfig, remoteOptions);
303
+ const thirdPartyExtractor = new import_third_party_dts_extractor.ThirdPartyExtractor(
304
+ (0, import_path2.resolve)(mfTypePath, "node_modules"),
305
+ remoteOptions.context
306
+ );
307
+ const cb = remoteOptions.extractThirdParty ? thirdPartyExtractor.collectPkgs.bind(thirdPartyExtractor) : () => void 0;
308
+ const tsHost = createHost(mapComponentsToExpose, tsConfig, remoteOptions, cb);
309
+ const filesToCompile = [
310
+ ...Object.values(mapComponentsToExpose),
311
+ ...remoteOptions.additionalFilesToCompile
312
+ ];
313
+ const programOptions = {
314
+ rootNames: filesToCompile,
315
+ host: tsHost,
316
+ options: tsConfig
317
+ };
318
+ const tsProgram = createProgram(remoteOptions, programOptions);
319
+ const { diagnostics = [] } = tsProgram.emit();
320
+ diagnostics.forEach(reportCompileDiagnostic);
321
+ if (remoteOptions.extractThirdParty) {
322
+ thirdPartyExtractor.copyDts();
323
+ }
324
+ };
325
+
326
+ // packages/dts-plugin/src/core/lib/archiveHandler.ts
327
+ var retrieveTypesZipPath = (mfTypesPath, remoteOptions) => (0, import_path3.join)(
328
+ mfTypesPath.replace(remoteOptions.typesFolder, ""),
329
+ `${remoteOptions.typesFolder}.zip`
330
+ );
331
+ var createTypesArchive = async (tsConfig, remoteOptions) => {
332
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
333
+ const zip = new import_adm_zip.default();
334
+ zip.addLocalFolder(mfTypesPath);
335
+ return zip.writeZipPromise(retrieveTypesZipPath(mfTypesPath, remoteOptions));
336
+ };
337
+ var downloadErrorLogger = (destinationFolder, fileToDownload) => (reason) => {
338
+ throw {
339
+ ...reason,
340
+ message: `Network error: Unable to download federated mocks for '${destinationFolder}' from '${fileToDownload}' because '${reason.message}'`
341
+ };
342
+ };
343
+ var retrieveTypesArchiveDestinationPath = (hostOptions, destinationFolder) => {
344
+ return (0, import_path3.resolve)(
345
+ hostOptions.context,
346
+ hostOptions.typesFolder,
347
+ destinationFolder
348
+ );
349
+ };
350
+ var downloadTypesArchive = (hostOptions) => {
351
+ let retries = 0;
352
+ return async ([destinationFolder, fileToDownload]) => {
353
+ const destinationPath = retrieveTypesArchiveDestinationPath(
354
+ hostOptions,
355
+ destinationFolder
356
+ );
357
+ while (retries++ < hostOptions.maxRetries) {
358
+ try {
359
+ const url = replaceLocalhost(fileToDownload);
360
+ const response = await import_axios.default.get(url, { responseType: "arraybuffer" }).catch(downloadErrorLogger(destinationFolder, url));
361
+ const zip = new import_adm_zip.default(Buffer.from(response.data));
362
+ zip.extractAllTo(destinationPath, true);
363
+ return [destinationFolder, destinationPath];
364
+ } catch (error) {
365
+ if (isDebugMode()) {
366
+ console.error(
367
+ import_ansi_colors2.default.red(
368
+ `Error during types archive download: ${(error == null ? void 0 : error.message) || "unknown error"}`
369
+ )
370
+ );
371
+ }
372
+ if (retries >= hostOptions.maxRetries) {
373
+ if (hostOptions.abortOnError !== false) {
374
+ throw error;
375
+ }
376
+ return void 0;
377
+ }
378
+ }
379
+ }
380
+ };
381
+ };
382
+
383
+ // packages/dts-plugin/src/core/configurations/hostPlugin.ts
384
+ var import_sdk = require("@module-federation/sdk");
385
+ var import_managers2 = require("@module-federation/managers");
386
+ var defaultOptions2 = {
387
+ typesFolder: "@mf-types",
388
+ remoteTypesFolder: "@mf-types",
389
+ deleteTypesFolder: true,
390
+ maxRetries: 3,
391
+ implementation: "",
392
+ context: process.cwd(),
393
+ abortOnError: true,
394
+ consumeAPITypes: false
395
+ };
396
+ var buildZipUrl = (hostOptions, url) => {
397
+ const remoteUrl = new URL(url);
398
+ if (remoteUrl.href.includes(import_sdk.MANIFEST_EXT)) {
399
+ return void 0;
400
+ }
401
+ const pathnameWithoutEntry = remoteUrl.pathname.split("/").slice(0, -1).join("/");
402
+ remoteUrl.pathname = `${pathnameWithoutEntry}/${hostOptions.remoteTypesFolder}.zip`;
403
+ return remoteUrl.href;
404
+ };
405
+ var buildApiTypeUrl = (zipUrl) => {
406
+ if (!zipUrl) {
407
+ return void 0;
408
+ }
409
+ return zipUrl.replace(".zip", ".d.ts");
410
+ };
411
+ var retrieveRemoteInfo = (options) => {
412
+ const { hostOptions, remoteAlias, remote } = options;
413
+ const parsedInfo = (0, import_sdk.parseEntry)(remote, void 0, "@");
414
+ const url = "entry" in parsedInfo ? parsedInfo.entry : parsedInfo.name === remote ? remote : "";
415
+ const zipUrl = url ? buildZipUrl(hostOptions, url) : "";
416
+ return {
417
+ name: parsedInfo.name || remoteAlias,
418
+ url,
419
+ zipUrl,
420
+ apiTypeUrl: buildApiTypeUrl(zipUrl),
421
+ alias: remoteAlias
422
+ };
423
+ };
424
+ var resolveRemotes = (hostOptions) => {
425
+ const parsedOptions = import_managers2.utils.parseOptions(
426
+ hostOptions.moduleFederationConfig.remotes || {},
427
+ (item, key) => ({
428
+ remote: Array.isArray(item) ? item[0] : item,
429
+ key
430
+ }),
431
+ (item, key) => ({
432
+ remote: Array.isArray(item.external) ? item.external[0] : item.external,
433
+ key
434
+ })
435
+ );
436
+ return parsedOptions.reduce(
437
+ (accumulator, item) => {
438
+ const { key, remote } = item[1];
439
+ accumulator[key] = retrieveRemoteInfo({
440
+ hostOptions,
441
+ remoteAlias: key,
442
+ remote
443
+ });
444
+ return accumulator;
445
+ },
446
+ {}
447
+ );
448
+ };
449
+ var retrieveHostConfig = (options) => {
450
+ validateOptions(options);
451
+ const hostOptions = { ...defaultOptions2, ...options };
452
+ const mapRemotesToDownload = resolveRemotes(hostOptions);
453
+ return {
454
+ hostOptions,
455
+ mapRemotesToDownload
456
+ };
457
+ };
458
+
459
+ // packages/dts-plugin/src/core/constant.ts
460
+ var REMOTE_ALIAS_IDENTIFIER = "REMOTE_ALIAS_IDENTIFIER";
461
+ var REMOTE_API_TYPES_FILE_NAME = "apis.d.ts";
462
+ var HOST_API_TYPES_FILE_NAME = "index.d.ts";
463
+
464
+ // packages/dts-plugin/src/core/lib/DTSManager.ts
465
+ var import_axios2 = __toESM(require("axios"));
466
+ var DTSManager = class {
467
+ constructor(options) {
468
+ this.options = (0, import_lodash.default)(options, (_value, key) => {
469
+ if (key === "manifest") {
470
+ return false;
471
+ }
472
+ });
473
+ this.runtimePkgs = [
474
+ "@module-federation/runtime",
475
+ "@module-federation/runtime-tools"
476
+ ];
477
+ this.loadedRemoteAPIAlias = [];
478
+ this.remoteAliasMap = {};
479
+ this.extraOptions = (options == null ? void 0 : options.extraOptions) || {};
480
+ }
481
+ generateAPITypes(mapComponentsToExpose) {
482
+ const exposePaths = /* @__PURE__ */ new Set();
483
+ const packageType = Object.keys(mapComponentsToExpose).reduce(
484
+ (sum, exposeKey) => {
485
+ const exposePath = import_path4.default.join(REMOTE_ALIAS_IDENTIFIER, exposeKey);
486
+ exposePaths.add(`'${exposePath}'`);
487
+ const curType = `T extends '${exposePath}' ? typeof import('${exposePath}') :`;
488
+ sum = curType + sum;
489
+ return sum;
490
+ },
491
+ "any;"
492
+ );
493
+ const exposePathKeys = [...exposePaths].join(" | ");
494
+ return `
495
+ export type RemoteKeys = ${exposePathKeys};
496
+ type PackageType<T> = ${packageType}`;
497
+ }
498
+ async extractRemoteTypes(options) {
499
+ const { remoteOptions, tsConfig } = options;
500
+ if (!remoteOptions.extractRemoteTypes) {
501
+ return;
502
+ }
503
+ let hasRemotes = false;
504
+ const remotes = remoteOptions.moduleFederationConfig.remotes;
505
+ if (remotes) {
506
+ if (Array.isArray(remotes)) {
507
+ hasRemotes = Boolean(remotes.length);
508
+ } else if (typeof remotes === "object") {
509
+ hasRemotes = Boolean(Object.keys(remotes).length);
510
+ }
511
+ }
512
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
513
+ if (hasRemotes) {
514
+ const tempHostOptions = {
515
+ moduleFederationConfig: remoteOptions.moduleFederationConfig,
516
+ typesFolder: import_path4.default.join(mfTypesPath, "node_modules"),
517
+ remoteTypesFolder: (remoteOptions == null ? void 0 : remoteOptions.hostRemoteTypesFolder) || remoteOptions.typesFolder,
518
+ deleteTypesFolder: true,
519
+ context: remoteOptions.context,
520
+ implementation: remoteOptions.implementation,
521
+ abortOnError: false
522
+ };
523
+ await this.consumeArchiveTypes(tempHostOptions);
524
+ }
525
+ }
526
+ async generateTypes() {
527
+ var _a;
528
+ try {
529
+ const { options } = this;
530
+ if (!options.remote) {
531
+ throw new Error(
532
+ "options.remote is required if you want to generateTypes"
533
+ );
534
+ }
535
+ const { remoteOptions, tsConfig, mapComponentsToExpose } = retrieveRemoteConfig(options.remote);
536
+ if (!Object.keys(mapComponentsToExpose).length) {
537
+ return;
538
+ }
539
+ this.extractRemoteTypes({
540
+ remoteOptions,
541
+ tsConfig,
542
+ mapComponentsToExpose
543
+ });
544
+ compileTs(mapComponentsToExpose, tsConfig, remoteOptions);
545
+ await createTypesArchive(tsConfig, remoteOptions);
546
+ let apiTypesPath = "";
547
+ if (remoteOptions.generateAPITypes) {
548
+ const apiTypes = this.generateAPITypes(mapComponentsToExpose);
549
+ apiTypesPath = retrieveMfAPITypesPath(tsConfig, remoteOptions);
550
+ import_fs2.default.writeFileSync(apiTypesPath, apiTypes);
551
+ }
552
+ if (remoteOptions.deleteTypesFolder) {
553
+ await (0, import_promises.rm)(retrieveMfTypesPath(tsConfig, remoteOptions), {
554
+ recursive: true,
555
+ force: true
556
+ });
557
+ }
558
+ console.log(import_ansi_colors3.default.green("Federated types created correctly"));
559
+ } catch (error) {
560
+ if (((_a = this.options.remote) == null ? void 0 : _a.abortOnError) === false) {
561
+ console.error(
562
+ import_ansi_colors3.default.red(`Unable to compile federated types, ${error}`)
563
+ );
564
+ } else {
565
+ throw error;
566
+ }
567
+ }
568
+ }
569
+ async requestRemoteManifest(remoteInfo) {
570
+ try {
571
+ if (!remoteInfo.url.includes(import_sdk2.MANIFEST_EXT)) {
572
+ return remoteInfo;
573
+ }
574
+ const url = replaceLocalhost(remoteInfo.url);
575
+ const res = await (0, import_axios2.default)({
576
+ method: "get",
577
+ url
578
+ });
579
+ const manifestJson = res.data;
580
+ if (!manifestJson.metaData.types.zip) {
581
+ throw new Error(`Can not get ${remoteInfo.name}'s types archive url!`);
582
+ }
583
+ const addProtocol = (u) => {
584
+ if (u.startsWith("//")) {
585
+ return `https:${u}`;
586
+ }
587
+ return u;
588
+ };
589
+ const publicPath = "publicPath" in manifestJson.metaData ? manifestJson.metaData.publicPath : new Function(manifestJson.metaData.getPublicPath)();
590
+ remoteInfo.zipUrl = new URL(
591
+ import_path4.default.join(addProtocol(publicPath), manifestJson.metaData.types.zip)
592
+ ).href;
593
+ if (!manifestJson.metaData.types.api) {
594
+ console.warn(`Can not get ${remoteInfo.name}'s api types url!`);
595
+ remoteInfo.apiTypeUrl = "";
596
+ return remoteInfo;
597
+ }
598
+ remoteInfo.apiTypeUrl = new URL(
599
+ import_path4.default.join(addProtocol(publicPath), manifestJson.metaData.types.api)
600
+ ).href;
601
+ return remoteInfo;
602
+ } catch (_err) {
603
+ console.error(_err);
604
+ return remoteInfo;
605
+ }
606
+ }
607
+ async consumeTargetRemotes(hostOptions, remoteInfo) {
608
+ if (!remoteInfo.zipUrl) {
609
+ throw new Error(`Can not get ${remoteInfo.name}'s types archive url!`);
610
+ }
611
+ const typesDownloader = downloadTypesArchive(hostOptions);
612
+ return typesDownloader([remoteInfo.alias, remoteInfo.zipUrl]);
613
+ }
614
+ async downloadAPITypes(remoteInfo, destinationPath) {
615
+ const { apiTypeUrl } = remoteInfo;
616
+ if (!apiTypeUrl) {
617
+ return;
618
+ }
619
+ try {
620
+ const url = replaceLocalhost(apiTypeUrl);
621
+ const res = await import_axios2.default.get(url);
622
+ let apiTypeFile = res.data;
623
+ apiTypeFile = apiTypeFile.replaceAll(
624
+ REMOTE_ALIAS_IDENTIFIER,
625
+ remoteInfo.alias
626
+ );
627
+ const filePath = import_path4.default.join(destinationPath, REMOTE_API_TYPES_FILE_NAME);
628
+ import_fs2.default.writeFileSync(filePath, apiTypeFile);
629
+ this.loadedRemoteAPIAlias.push(remoteInfo.alias);
630
+ } catch (err) {
631
+ console.error(
632
+ import_ansi_colors3.default.red(
633
+ `Unable to download "${remoteInfo.name}" api types, ${err}`
634
+ )
635
+ );
636
+ }
637
+ }
638
+ consumeAPITypes(hostOptions) {
639
+ if (!this.loadedRemoteAPIAlias.length) {
640
+ return;
641
+ }
642
+ const packageTypes = [];
643
+ const remoteKeys = [];
644
+ const importTypeStr = this.loadedRemoteAPIAlias.map((alias, index) => {
645
+ const remoteKey = `RemoteKeys_${index}`;
646
+ const packageType = `PackageType_${index}`;
647
+ packageTypes.push(`T extends ${remoteKey} ? ${packageType}<T>`);
648
+ remoteKeys.push(remoteKey);
649
+ return `import type { PackageType as ${packageType},RemoteKeys as ${remoteKey} } from './${alias}/apis.d.ts';`;
650
+ }).join("\n");
651
+ const remoteKeysStr = `type RemoteKeys = ${remoteKeys.join(" | ")};`;
652
+ const packageTypesStr = `type PackageType<T, Y=any> = ${[
653
+ ...packageTypes,
654
+ "Y"
655
+ ].join(" :\n")} ;`;
656
+ const pkgsDeclareStr = this.runtimePkgs.map((pkg) => {
657
+ return `declare module "${pkg}" {
658
+ ${remoteKeysStr}
659
+ ${packageTypesStr}
660
+ export function loadRemote<T extends RemoteKeys,Y>(packageName: T): Promise<PackageType<T, Y>>;
661
+ export function loadRemote<T extends string,Y>(packageName: T): Promise<PackageType<T, Y>>;
662
+ }`;
663
+ }).join("\n");
664
+ const fileStr = `${importTypeStr}
665
+ ${pkgsDeclareStr}
666
+ `;
667
+ import_fs2.default.writeFileSync(
668
+ import_path4.default.join(
669
+ hostOptions.context,
670
+ hostOptions.typesFolder,
671
+ HOST_API_TYPES_FILE_NAME
672
+ ),
673
+ fileStr
674
+ );
675
+ }
676
+ async consumeArchiveTypes(options) {
677
+ const { hostOptions, mapRemotesToDownload } = retrieveHostConfig(options);
678
+ if (hostOptions.deleteTypesFolder) {
679
+ await (0, import_promises.rm)(hostOptions.typesFolder, {
680
+ recursive: true,
681
+ force: true
682
+ }).catch(
683
+ (error) => console.error(
684
+ import_ansi_colors3.default.red(`Unable to remove types folder, ${error}`)
685
+ )
686
+ );
687
+ }
688
+ const downloadPromises = Object.entries(mapRemotesToDownload).map(
689
+ async (item) => {
690
+ const remoteInfo = item[1];
691
+ if (!this.remoteAliasMap[remoteInfo.alias]) {
692
+ const requiredRemoteInfo = await this.requestRemoteManifest(remoteInfo);
693
+ this.remoteAliasMap[remoteInfo.alias] = requiredRemoteInfo;
694
+ }
695
+ return this.consumeTargetRemotes(
696
+ hostOptions,
697
+ this.remoteAliasMap[remoteInfo.alias]
698
+ );
699
+ }
700
+ );
701
+ const downloadPromisesResult = await Promise.allSettled(downloadPromises);
702
+ return {
703
+ hostOptions,
704
+ downloadPromisesResult
705
+ };
706
+ }
707
+ async consumeTypes() {
708
+ var _a;
709
+ try {
710
+ const { options } = this;
711
+ if (!options.host) {
712
+ throw new Error("options.host is required if you want to consumeTypes");
713
+ }
714
+ const { mapRemotesToDownload } = retrieveHostConfig(options.host);
715
+ if (!Object.keys(mapRemotesToDownload).length) {
716
+ return;
717
+ }
718
+ const { downloadPromisesResult, hostOptions } = await this.consumeArchiveTypes(options.host);
719
+ if (hostOptions.consumeAPITypes) {
720
+ await Promise.all(
721
+ downloadPromisesResult.map(async (item) => {
722
+ if (item.status === "rejected" || !item.value) {
723
+ return;
724
+ }
725
+ const [alias, destinationPath] = item.value;
726
+ const remoteInfo = this.remoteAliasMap[alias];
727
+ if (!remoteInfo) {
728
+ return;
729
+ }
730
+ await this.downloadAPITypes(remoteInfo, destinationPath);
731
+ })
732
+ );
733
+ this.consumeAPITypes(hostOptions);
734
+ }
735
+ console.log(import_ansi_colors3.default.green("Federated types extraction completed"));
736
+ } catch (err) {
737
+ if (((_a = this.options.host) == null ? void 0 : _a.abortOnError) === false) {
738
+ console.error(
739
+ import_ansi_colors3.default.red(`Unable to consume federated types, ${err}`)
740
+ );
741
+ } else {
742
+ throw err;
743
+ }
744
+ }
745
+ }
746
+ async updateTypes(options) {
747
+ var _a, _b, _c;
748
+ const { remoteName, updateMode } = options;
749
+ const hostName = (_c = (_b = (_a = this.options) == null ? void 0 : _a.host) == null ? void 0 : _b.moduleFederationConfig) == null ? void 0 : _c.name;
750
+ if (updateMode === "POSITIVE" /* POSITIVE */ && remoteName === hostName) {
751
+ if (!this.options.remote) {
752
+ return;
753
+ }
754
+ this.generateTypes();
755
+ } else {
756
+ const { remoteAliasMap } = this;
757
+ if (!this.options.host) {
758
+ return;
759
+ }
760
+ const { hostOptions, mapRemotesToDownload } = retrieveHostConfig(
761
+ this.options.host
762
+ );
763
+ const loadedRemoteInfo = Object.values(remoteAliasMap).find(
764
+ (i) => i.name === remoteName
765
+ );
766
+ if (!loadedRemoteInfo) {
767
+ const remoteInfo = Object.values(mapRemotesToDownload).find((item) => {
768
+ return item.name === remoteName;
769
+ });
770
+ if (remoteInfo) {
771
+ if (!this.remoteAliasMap[remoteInfo.alias]) {
772
+ const requiredRemoteInfo = await this.requestRemoteManifest(remoteInfo);
773
+ this.remoteAliasMap[remoteInfo.alias] = requiredRemoteInfo;
774
+ }
775
+ await this.consumeTargetRemotes(
776
+ hostOptions,
777
+ this.remoteAliasMap[remoteInfo.alias]
778
+ );
779
+ }
780
+ } else {
781
+ await this.consumeTargetRemotes(hostOptions, loadedRemoteInfo);
782
+ }
783
+ }
784
+ }
785
+ };
786
+
787
+ // packages/dts-plugin/src/core/lib/utils.ts
788
+ var import_ansi_colors4 = __toESM(require("ansi-colors"));
789
+ function getDTSManagerConstructor(implementation) {
790
+ if (implementation) {
791
+ const NewConstructor = require(implementation);
792
+ return NewConstructor.default ? NewConstructor.default : NewConstructor;
793
+ }
794
+ return DTSManager;
795
+ }
796
+ var validateOptions = (options) => {
797
+ if (!options.moduleFederationConfig) {
798
+ throw new Error("moduleFederationConfig is required");
799
+ }
800
+ };
801
+ function replaceLocalhost(url) {
802
+ return url.replace("localhost", "127.0.0.1");
803
+ }
804
+ function isDebugMode() {
805
+ return Boolean(process.env["FEDERATION_DEBUG"]);
806
+ }
807
+
808
+ // packages/dts-plugin/src/core/lib/generateTypes.ts
809
+ async function generateTypes(options) {
810
+ var _a;
811
+ const DTSManagerConstructor = getDTSManagerConstructor(
812
+ (_a = options.remote) == null ? void 0 : _a.implementation
813
+ );
814
+ const dtsManager = new DTSManagerConstructor(options);
815
+ return dtsManager.generateTypes();
816
+ }
817
+
818
+ // packages/dts-plugin/src/core/lib/forkGenerateDts.ts
819
+ async function forkGenerateDts(options) {
820
+ return generateTypes(options);
821
+ }
822
+ process.on("message", (message) => {
823
+ if (message.type === "mf_exit" /* EXIT */) {
824
+ process.exit(0);
825
+ }
826
+ });
827
+ exposeRpc(forkGenerateDts);
828
+ // Annotate the CommonJS export names for ESM import in node:
829
+ 0 && (module.exports = {
830
+ forkGenerateDts
831
+ });