@module-federation/native-federation-typescript 0.1.0 → 0.1.2

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 (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +82 -34
  3. package/dist/CHANGELOG.md +336 -0
  4. package/dist/DTSManagerOptions-3369791f.d.ts +9 -0
  5. package/dist/HostOptions-cf22e0ab.d.ts +23 -0
  6. package/dist/README.md +214 -0
  7. package/dist/chunk-2NC7LVYZ.js +864 -0
  8. package/dist/chunk-CF5CH54A.mjs +864 -0
  9. package/dist/chunk-JLWFNRJL.js +179 -0
  10. package/dist/chunk-QYHGZU7D.mjs +244 -0
  11. package/dist/chunk-VHQW5BQS.js +244 -0
  12. package/dist/chunk-VKKLMSMI.mjs +179 -0
  13. package/dist/esbuild.d.mts +9 -0
  14. package/dist/esbuild.d.ts +6 -3
  15. package/dist/esbuild.js +14 -1
  16. package/dist/esbuild.mjs +14 -1
  17. package/dist/helpers.d.mts +160 -0
  18. package/dist/helpers.d.ts +160 -0
  19. package/dist/helpers.js +40 -0
  20. package/dist/helpers.mjs +40 -0
  21. package/dist/index.d.mts +16 -0
  22. package/dist/index.d.ts +13 -4
  23. package/dist/index.js +10 -1
  24. package/dist/index.mjs +10 -1
  25. package/dist/lib/forkGenerateDts.d.mts +9 -0
  26. package/dist/lib/forkGenerateDts.d.ts +9 -0
  27. package/dist/lib/forkGenerateDts.js +18 -0
  28. package/dist/lib/forkGenerateDts.mjs +18 -0
  29. package/dist/package.json +103 -0
  30. package/dist/rolldown.d.mts +9 -0
  31. package/dist/rolldown.d.ts +9 -0
  32. package/dist/rolldown.js +14 -0
  33. package/dist/rolldown.mjs +14 -0
  34. package/dist/rollup.d.mts +9 -0
  35. package/dist/rollup.d.ts +6 -3
  36. package/dist/rollup.js +14 -1
  37. package/dist/rollup.mjs +14 -1
  38. package/dist/rspack.d.mts +9 -0
  39. package/dist/rspack.d.ts +6 -3
  40. package/dist/rspack.js +14 -1
  41. package/dist/rspack.mjs +14 -1
  42. package/dist/vite.d.mts +9 -0
  43. package/dist/vite.d.ts +6 -3
  44. package/dist/vite.js +14 -1
  45. package/dist/vite.mjs +14 -1
  46. package/dist/webpack.d.mts +9 -0
  47. package/dist/webpack.d.ts +6 -3
  48. package/dist/webpack.js +14 -1
  49. package/dist/webpack.mjs +14 -1
  50. package/package.json +50 -5
  51. package/CHANGELOG.md +0 -28
  52. package/dist/RemoteOptions-ce85caac.d.ts +0 -17
  53. package/dist/chunk-HJB2AKNY.mjs +0 -682
  54. package/dist/chunk-WNKHVVXS.js +0 -682
@@ -0,0 +1,864 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
+ }) : x)(function(x) {
5
+ if (typeof require !== "undefined")
6
+ return require.apply(this, arguments);
7
+ throw Error('Dynamic require of "' + x + '" is not supported');
8
+ });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+
14
+ // packages/native-federation-typescript/src/lib/typeScriptCompiler.ts
15
+ import ansiColors from "ansi-colors";
16
+ import { dirname, join, normalize, relative, resolve } from "path";
17
+ import typescript from "typescript";
18
+ import { ThirdPartyExtractor } from "@module-federation/third-party-dts-extractor";
19
+ var STARTS_WITH_SLASH = /^\//;
20
+ var DEFINITION_FILE_EXTENSION = ".d.ts";
21
+ var reportCompileDiagnostic = (diagnostic) => {
22
+ const { line } = diagnostic.file.getLineAndCharacterOfPosition(
23
+ diagnostic.start
24
+ );
25
+ console.error(
26
+ ansiColors.red(
27
+ `TS Error ${diagnostic.code}':' ${typescript.flattenDiagnosticMessageText(
28
+ diagnostic.messageText,
29
+ typescript.sys.newLine
30
+ )}`
31
+ )
32
+ );
33
+ console.error(
34
+ ansiColors.red(
35
+ ` at ${diagnostic.file.fileName}:${line + 1} typescript.sys.newLine`
36
+ )
37
+ );
38
+ };
39
+ var retrieveMfTypesPath = (tsConfig, remoteOptions) => normalize(tsConfig.outDir.replace(remoteOptions.compiledTypesFolder, ""));
40
+ var retrieveOriginalOutDir = (tsConfig, remoteOptions) => normalize(
41
+ tsConfig.outDir.replace(remoteOptions.compiledTypesFolder, "").replace(remoteOptions.typesFolder, "")
42
+ );
43
+ var retrieveMfAPITypesPath = (tsConfig, remoteOptions) => join(
44
+ retrieveOriginalOutDir(tsConfig, remoteOptions),
45
+ `${remoteOptions.typesFolder}.d.ts`
46
+ );
47
+ var createHost = (mapComponentsToExpose, tsConfig, remoteOptions, cb) => {
48
+ const host = typescript.createCompilerHost(tsConfig);
49
+ const originalWriteFile = host.writeFile;
50
+ const mapExposeToEntry = Object.fromEntries(
51
+ Object.entries(mapComponentsToExpose).map((entry) => entry.reverse())
52
+ );
53
+ const mfTypePath = retrieveMfTypesPath(tsConfig, remoteOptions);
54
+ host.writeFile = (filepath, text, writeOrderByteMark, onError, sourceFiles, data) => {
55
+ originalWriteFile(
56
+ filepath,
57
+ text,
58
+ writeOrderByteMark,
59
+ onError,
60
+ sourceFiles,
61
+ data
62
+ );
63
+ for (const sourceFile of sourceFiles || []) {
64
+ const sourceEntry = mapExposeToEntry[sourceFile.fileName];
65
+ if (sourceEntry) {
66
+ const mfeTypeEntry = join(
67
+ mfTypePath,
68
+ `${sourceEntry}${DEFINITION_FILE_EXTENSION}`
69
+ );
70
+ const mfeTypeEntryDirectory = dirname(mfeTypeEntry);
71
+ const relativePathToOutput = relative(mfeTypeEntryDirectory, filepath).replace(DEFINITION_FILE_EXTENSION, "").replace(STARTS_WITH_SLASH, "");
72
+ originalWriteFile(
73
+ mfeTypeEntry,
74
+ `export * from './${relativePathToOutput}';
75
+ export { default } from './${relativePathToOutput}';`,
76
+ writeOrderByteMark
77
+ );
78
+ }
79
+ }
80
+ cb(text);
81
+ };
82
+ return host;
83
+ };
84
+ var createVueTscProgram = (programOptions) => {
85
+ const vueTypescript = __require("vue-tsc");
86
+ return vueTypescript.createProgram(programOptions);
87
+ };
88
+ var createProgram = (remoteOptions, programOptions) => {
89
+ switch (remoteOptions.compilerInstance) {
90
+ case "vue-tsc":
91
+ return createVueTscProgram(programOptions);
92
+ case "tsc":
93
+ default:
94
+ return typescript.createProgram(programOptions);
95
+ }
96
+ };
97
+ var compileTs = (mapComponentsToExpose, tsConfig, remoteOptions) => {
98
+ const mfTypePath = retrieveMfTypesPath(tsConfig, remoteOptions);
99
+ const thirdPartyExtractor = new ThirdPartyExtractor(
100
+ resolve(mfTypePath, "node_modules"),
101
+ remoteOptions.context
102
+ );
103
+ const cb = remoteOptions.extractThirdParty ? thirdPartyExtractor.collectPkgs.bind(thirdPartyExtractor) : () => void 0;
104
+ const tsHost = createHost(mapComponentsToExpose, tsConfig, remoteOptions, cb);
105
+ const filesToCompile = [
106
+ ...Object.values(mapComponentsToExpose),
107
+ ...remoteOptions.additionalFilesToCompile
108
+ ];
109
+ const programOptions = {
110
+ rootNames: filesToCompile,
111
+ host: tsHost,
112
+ options: tsConfig
113
+ };
114
+ const tsProgram = createProgram(remoteOptions, programOptions);
115
+ const { diagnostics = [] } = tsProgram.emit();
116
+ diagnostics.forEach(reportCompileDiagnostic);
117
+ if (remoteOptions.extractThirdParty) {
118
+ thirdPartyExtractor.copyDts();
119
+ }
120
+ };
121
+
122
+ // packages/native-federation-typescript/src/lib/archiveHandler.ts
123
+ import AdmZip from "adm-zip";
124
+ import ansiColors4 from "ansi-colors";
125
+ import axios2 from "axios";
126
+ import { resolve as resolve3, join as join3 } from "path";
127
+
128
+ // packages/native-federation-typescript/src/lib/utils.ts
129
+ import path2 from "path";
130
+
131
+ // packages/native-federation-typescript/src/configurations/remotePlugin.ts
132
+ import { existsSync } from "fs";
133
+ import { dirname as dirname2, join as join2, resolve as resolve2, extname } from "path";
134
+ import { utils } from "@module-federation/managers";
135
+ import typescript2 from "typescript";
136
+ var defaultOptions = {
137
+ tsConfigPath: "./tsconfig.json",
138
+ typesFolder: "@mf-types",
139
+ compiledTypesFolder: "compiled-types",
140
+ hostRemoteTypesFolder: "@mf-types",
141
+ deleteTypesFolder: true,
142
+ additionalFilesToCompile: [],
143
+ compilerInstance: "tsc",
144
+ compileInChildProcess: false,
145
+ implementation: "",
146
+ generateAPITypes: false,
147
+ context: process.cwd(),
148
+ abortOnError: true,
149
+ extractRemoteTypes: false,
150
+ extractThirdParty: false
151
+ };
152
+ var readTsConfig = ({
153
+ tsConfigPath,
154
+ typesFolder,
155
+ compiledTypesFolder,
156
+ context
157
+ }) => {
158
+ const resolvedTsConfigPath = resolve2(context, tsConfigPath);
159
+ const readResult = typescript2.readConfigFile(
160
+ resolvedTsConfigPath,
161
+ typescript2.sys.readFile
162
+ );
163
+ if (readResult.error) {
164
+ throw new Error(readResult.error.messageText.toString());
165
+ }
166
+ const configContent = typescript2.parseJsonConfigFileContent(
167
+ readResult.config,
168
+ typescript2.sys,
169
+ dirname2(resolvedTsConfigPath)
170
+ );
171
+ const outDir = resolve2(
172
+ context,
173
+ configContent.options.outDir || "dist",
174
+ typesFolder,
175
+ compiledTypesFolder
176
+ );
177
+ return {
178
+ ...configContent.options,
179
+ emitDeclarationOnly: true,
180
+ noEmit: false,
181
+ declaration: true,
182
+ outDir
183
+ };
184
+ };
185
+ var TS_EXTENSIONS = ["ts", "tsx", "vue", "svelte"];
186
+ var resolveWithExtension = (exposedPath, context) => {
187
+ if (extname(exposedPath)) {
188
+ return resolve2(context, exposedPath);
189
+ }
190
+ for (const extension of TS_EXTENSIONS) {
191
+ const exposedPathWithExtension = resolve2(
192
+ context,
193
+ `${exposedPath}.${extension}`
194
+ );
195
+ if (existsSync(exposedPathWithExtension)) {
196
+ return exposedPathWithExtension;
197
+ }
198
+ }
199
+ return void 0;
200
+ };
201
+ var resolveExposes = (remoteOptions) => {
202
+ const parsedOptions = utils.parseOptions(
203
+ remoteOptions.moduleFederationConfig.exposes || {},
204
+ (item, key) => ({
205
+ exposePath: Array.isArray(item) ? item[0] : item,
206
+ key
207
+ }),
208
+ (item, key) => ({
209
+ exposePath: Array.isArray(item.import) ? item.import[0] : item.import[0],
210
+ key
211
+ })
212
+ );
213
+ return parsedOptions.reduce(
214
+ (accumulator, item) => {
215
+ const { exposePath, key } = item[1];
216
+ accumulator[key] = resolveWithExtension(exposePath, remoteOptions.context) || resolveWithExtension(
217
+ join2(exposePath, "index"),
218
+ remoteOptions.context
219
+ ) || exposePath;
220
+ return accumulator;
221
+ },
222
+ {}
223
+ );
224
+ };
225
+ var retrieveRemoteConfig = (options) => {
226
+ validateOptions(options);
227
+ const remoteOptions = {
228
+ ...defaultOptions,
229
+ ...options
230
+ };
231
+ const mapComponentsToExpose = resolveExposes(remoteOptions);
232
+ const tsConfig = readTsConfig(remoteOptions);
233
+ return {
234
+ tsConfig,
235
+ mapComponentsToExpose,
236
+ remoteOptions
237
+ };
238
+ };
239
+
240
+ // packages/native-federation-typescript/src/lib/DTSManager.ts
241
+ import ansiColors2 from "ansi-colors";
242
+ import path from "path";
243
+ import { rm } from "fs/promises";
244
+ import fs from "fs";
245
+ import { MANIFEST_EXT as MANIFEST_EXT2 } from "@module-federation/sdk";
246
+ import cloneDeepWith from "lodash.clonedeepwith";
247
+
248
+ // packages/native-federation-typescript/src/configurations/hostPlugin.ts
249
+ import { MANIFEST_EXT, parseEntry } from "@module-federation/sdk";
250
+ import { utils as utils2 } from "@module-federation/managers";
251
+ var defaultOptions2 = {
252
+ typesFolder: "@mf-types",
253
+ remoteTypesFolder: "@mf-types",
254
+ deleteTypesFolder: true,
255
+ maxRetries: 3,
256
+ implementation: "",
257
+ context: process.cwd(),
258
+ abortOnError: true,
259
+ consumeAPITypes: false
260
+ };
261
+ var buildZipUrl = (hostOptions, url) => {
262
+ const remoteUrl = new URL(url);
263
+ if (remoteUrl.href.includes(MANIFEST_EXT)) {
264
+ return void 0;
265
+ }
266
+ const pathnameWithoutEntry = remoteUrl.pathname.split("/").slice(0, -1).join("/");
267
+ remoteUrl.pathname = `${pathnameWithoutEntry}/${hostOptions.remoteTypesFolder}.zip`;
268
+ return remoteUrl.href;
269
+ };
270
+ var buildApiTypeUrl = (zipUrl) => {
271
+ if (!zipUrl) {
272
+ return void 0;
273
+ }
274
+ return zipUrl.replace(".zip", ".d.ts");
275
+ };
276
+ var retrieveRemoteInfo = (options) => {
277
+ const { hostOptions, remoteAlias, remote } = options;
278
+ const parsedInfo = parseEntry(remote, void 0, "@");
279
+ const url = "entry" in parsedInfo ? parsedInfo.entry : parsedInfo.name === remote ? remote : "";
280
+ const zipUrl = url ? buildZipUrl(hostOptions, url) : "";
281
+ return {
282
+ name: parsedInfo.name || remoteAlias,
283
+ url,
284
+ zipUrl,
285
+ apiTypeUrl: buildApiTypeUrl(zipUrl),
286
+ alias: remoteAlias
287
+ };
288
+ };
289
+ var resolveRemotes = (hostOptions) => {
290
+ const parsedOptions = utils2.parseOptions(
291
+ hostOptions.moduleFederationConfig.remotes || {},
292
+ (item, key) => ({
293
+ remote: Array.isArray(item) ? item[0] : item,
294
+ key
295
+ }),
296
+ (item, key) => ({
297
+ remote: Array.isArray(item.external) ? item.external[0] : item.external,
298
+ key
299
+ })
300
+ );
301
+ return parsedOptions.reduce(
302
+ (accumulator, item) => {
303
+ const { key, remote } = item[1];
304
+ accumulator[key] = retrieveRemoteInfo({
305
+ hostOptions,
306
+ remoteAlias: key,
307
+ remote
308
+ });
309
+ return accumulator;
310
+ },
311
+ {}
312
+ );
313
+ };
314
+ var retrieveHostConfig = (options) => {
315
+ validateOptions(options);
316
+ const hostOptions = { ...defaultOptions2, ...options };
317
+ const mapRemotesToDownload = resolveRemotes(hostOptions);
318
+ return {
319
+ hostOptions,
320
+ mapRemotesToDownload
321
+ };
322
+ };
323
+
324
+ // packages/native-federation-typescript/src/constant.ts
325
+ var REMOTE_ALIAS_IDENTIFIER = "REMOTE_ALIAS_IDENTIFIER";
326
+ var REMOTE_API_TYPES_FILE_NAME = "apis.d.ts";
327
+ var HOST_API_TYPES_FILE_NAME = "index.d.ts";
328
+ var UpdateMode = /* @__PURE__ */ ((UpdateMode2) => {
329
+ UpdateMode2["POSITIVE"] = "POSITIVE";
330
+ UpdateMode2["PASSIVE"] = "PASSIVE";
331
+ return UpdateMode2;
332
+ })(UpdateMode || {});
333
+
334
+ // packages/native-federation-typescript/src/lib/DTSManager.ts
335
+ import axios from "axios";
336
+ var DTSManager = class {
337
+ constructor(options) {
338
+ this.options = cloneDeepWith(options, (_value, key) => {
339
+ if (key === "manifest") {
340
+ return false;
341
+ }
342
+ });
343
+ this.runtimePkgs = [
344
+ "@module-federation/runtime",
345
+ "@module-federation/runtime-tools"
346
+ ];
347
+ this.loadedRemoteAPIAlias = [];
348
+ this.remoteAliasMap = {};
349
+ this.extraOptions = (options == null ? void 0 : options.extraOptions) || {};
350
+ }
351
+ generateAPITypes(mapComponentsToExpose) {
352
+ const exposePaths = /* @__PURE__ */ new Set();
353
+ const packageType = Object.keys(mapComponentsToExpose).reduce(
354
+ (sum, exposeKey) => {
355
+ const exposePath = path.join(REMOTE_ALIAS_IDENTIFIER, exposeKey);
356
+ exposePaths.add(`'${exposePath}'`);
357
+ const curType = `T extends '${exposePath}' ? typeof import('${exposePath}') :`;
358
+ sum = curType + sum;
359
+ return sum;
360
+ },
361
+ "any;"
362
+ );
363
+ const exposePathKeys = [...exposePaths].join(" | ");
364
+ return `
365
+ export type RemoteKeys = ${exposePathKeys};
366
+ type PackageType<T> = ${packageType}`;
367
+ }
368
+ async extractRemoteTypes(options) {
369
+ const { remoteOptions, tsConfig } = options;
370
+ if (!remoteOptions.extractRemoteTypes) {
371
+ return;
372
+ }
373
+ let hasRemotes = false;
374
+ const remotes = remoteOptions.moduleFederationConfig.remotes;
375
+ if (remotes) {
376
+ if (Array.isArray(remotes)) {
377
+ hasRemotes = Boolean(remotes.length);
378
+ } else if (typeof remotes === "object") {
379
+ hasRemotes = Boolean(Object.keys(remotes).length);
380
+ }
381
+ }
382
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
383
+ if (hasRemotes) {
384
+ const tempHostOptions = {
385
+ moduleFederationConfig: remoteOptions.moduleFederationConfig,
386
+ typesFolder: path.join(mfTypesPath, "node_modules"),
387
+ remoteTypesFolder: (remoteOptions == null ? void 0 : remoteOptions.hostRemoteTypesFolder) || remoteOptions.typesFolder,
388
+ deleteTypesFolder: true,
389
+ context: remoteOptions.context,
390
+ implementation: remoteOptions.implementation,
391
+ abortOnError: false
392
+ };
393
+ await this.consumeArchiveTypes(tempHostOptions);
394
+ }
395
+ }
396
+ async generateTypes() {
397
+ var _a;
398
+ try {
399
+ const { options } = this;
400
+ if (!options.remote) {
401
+ throw new Error(
402
+ "options.remote is required if you want to generateTypes"
403
+ );
404
+ }
405
+ const { remoteOptions, tsConfig, mapComponentsToExpose } = retrieveRemoteConfig(options.remote);
406
+ if (!Object.keys(mapComponentsToExpose).length) {
407
+ return;
408
+ }
409
+ this.extractRemoteTypes({
410
+ remoteOptions,
411
+ tsConfig,
412
+ mapComponentsToExpose
413
+ });
414
+ compileTs(mapComponentsToExpose, tsConfig, remoteOptions);
415
+ await createTypesArchive(tsConfig, remoteOptions);
416
+ let apiTypesPath = "";
417
+ if (remoteOptions.generateAPITypes) {
418
+ const apiTypes = this.generateAPITypes(mapComponentsToExpose);
419
+ apiTypesPath = retrieveMfAPITypesPath(tsConfig, remoteOptions);
420
+ fs.writeFileSync(apiTypesPath, apiTypes);
421
+ }
422
+ if (remoteOptions.deleteTypesFolder) {
423
+ await rm(retrieveMfTypesPath(tsConfig, remoteOptions), {
424
+ recursive: true,
425
+ force: true
426
+ });
427
+ }
428
+ console.log(ansiColors2.green("Federated types created correctly"));
429
+ } catch (error) {
430
+ if (((_a = this.options.remote) == null ? void 0 : _a.abortOnError) === false) {
431
+ console.error(
432
+ ansiColors2.red(`Unable to compile federated types, ${error}`)
433
+ );
434
+ } else {
435
+ throw error;
436
+ }
437
+ }
438
+ }
439
+ async requestRemoteManifest(remoteInfo) {
440
+ try {
441
+ if (!remoteInfo.url.includes(MANIFEST_EXT2)) {
442
+ return remoteInfo;
443
+ }
444
+ const url = replaceLocalhost(remoteInfo.url);
445
+ const res = await axios({
446
+ method: "get",
447
+ url
448
+ });
449
+ const manifestJson = res.data;
450
+ if (!manifestJson.metaData.types.zip) {
451
+ throw new Error(`Can not get ${remoteInfo.name}'s types archive url!`);
452
+ }
453
+ const addProtocol = (u) => {
454
+ if (u.startsWith("//")) {
455
+ return `https:${u}`;
456
+ }
457
+ return u;
458
+ };
459
+ const publicPath = "publicPath" in manifestJson.metaData ? manifestJson.metaData.publicPath : new Function(manifestJson.metaData.getPublicPath)();
460
+ remoteInfo.zipUrl = new URL(
461
+ path.join(addProtocol(publicPath), manifestJson.metaData.types.zip)
462
+ ).href;
463
+ if (!manifestJson.metaData.types.api) {
464
+ console.warn(`Can not get ${remoteInfo.name}'s api types url!`);
465
+ remoteInfo.apiTypeUrl = "";
466
+ return remoteInfo;
467
+ }
468
+ remoteInfo.apiTypeUrl = new URL(
469
+ path.join(addProtocol(publicPath), manifestJson.metaData.types.api)
470
+ ).href;
471
+ return remoteInfo;
472
+ } catch (_err) {
473
+ console.error(_err);
474
+ return remoteInfo;
475
+ }
476
+ }
477
+ async consumeTargetRemotes(hostOptions, remoteInfo) {
478
+ if (!remoteInfo.zipUrl) {
479
+ throw new Error(`Can not get ${remoteInfo.name}'s types archive url!`);
480
+ }
481
+ const typesDownloader = downloadTypesArchive(hostOptions);
482
+ return typesDownloader([remoteInfo.alias, remoteInfo.zipUrl]);
483
+ }
484
+ async downloadAPITypes(remoteInfo, destinationPath) {
485
+ const { apiTypeUrl } = remoteInfo;
486
+ if (!apiTypeUrl) {
487
+ return;
488
+ }
489
+ try {
490
+ const url = replaceLocalhost(apiTypeUrl);
491
+ const res = await axios.get(url);
492
+ let apiTypeFile = res.data;
493
+ apiTypeFile = apiTypeFile.replaceAll(
494
+ REMOTE_ALIAS_IDENTIFIER,
495
+ remoteInfo.alias
496
+ );
497
+ const filePath = path.join(destinationPath, REMOTE_API_TYPES_FILE_NAME);
498
+ fs.writeFileSync(filePath, apiTypeFile);
499
+ this.loadedRemoteAPIAlias.push(remoteInfo.alias);
500
+ } catch (err) {
501
+ console.error(
502
+ ansiColors2.red(
503
+ `Unable to download "${remoteInfo.name}" api types, ${err}`
504
+ )
505
+ );
506
+ }
507
+ }
508
+ consumeAPITypes(hostOptions) {
509
+ if (!this.loadedRemoteAPIAlias.length) {
510
+ return;
511
+ }
512
+ const packageTypes = [];
513
+ const remoteKeys = [];
514
+ const importTypeStr = this.loadedRemoteAPIAlias.map((alias, index) => {
515
+ const remoteKey = `RemoteKeys_${index}`;
516
+ const packageType = `PackageType_${index}`;
517
+ packageTypes.push(`T extends ${remoteKey} ? ${packageType}<T>`);
518
+ remoteKeys.push(remoteKey);
519
+ return `import type { PackageType as ${packageType},RemoteKeys as ${remoteKey} } from './${alias}/apis.d.ts';`;
520
+ }).join("\n");
521
+ const remoteKeysStr = `type RemoteKeys = ${remoteKeys.join(" | ")};`;
522
+ const packageTypesStr = `type PackageType<T, Y=any> = ${[
523
+ ...packageTypes,
524
+ "Y"
525
+ ].join(" :\n")} ;`;
526
+ const pkgsDeclareStr = this.runtimePkgs.map((pkg) => {
527
+ return `declare module "${pkg}" {
528
+ ${remoteKeysStr}
529
+ ${packageTypesStr}
530
+ export function loadRemote<T extends RemoteKeys,Y>(packageName: T): Promise<PackageType<T, Y>>;
531
+ export function loadRemote<T extends string,Y>(packageName: T): Promise<PackageType<T, Y>>;
532
+ }`;
533
+ }).join("\n");
534
+ const fileStr = `${importTypeStr}
535
+ ${pkgsDeclareStr}
536
+ `;
537
+ fs.writeFileSync(
538
+ path.join(
539
+ hostOptions.context,
540
+ hostOptions.typesFolder,
541
+ HOST_API_TYPES_FILE_NAME
542
+ ),
543
+ fileStr
544
+ );
545
+ }
546
+ async consumeArchiveTypes(options) {
547
+ const { hostOptions, mapRemotesToDownload } = retrieveHostConfig(options);
548
+ if (hostOptions.deleteTypesFolder) {
549
+ await rm(hostOptions.typesFolder, {
550
+ recursive: true,
551
+ force: true
552
+ }).catch(
553
+ (error) => console.error(
554
+ ansiColors2.red(`Unable to remove types folder, ${error}`)
555
+ )
556
+ );
557
+ }
558
+ const downloadPromises = Object.entries(mapRemotesToDownload).map(
559
+ async (item) => {
560
+ const remoteInfo = item[1];
561
+ if (!this.remoteAliasMap[remoteInfo.alias]) {
562
+ const requiredRemoteInfo = await this.requestRemoteManifest(remoteInfo);
563
+ this.remoteAliasMap[remoteInfo.alias] = requiredRemoteInfo;
564
+ }
565
+ return this.consumeTargetRemotes(
566
+ hostOptions,
567
+ this.remoteAliasMap[remoteInfo.alias]
568
+ );
569
+ }
570
+ );
571
+ const downloadPromisesResult = await Promise.allSettled(downloadPromises);
572
+ return {
573
+ hostOptions,
574
+ downloadPromisesResult
575
+ };
576
+ }
577
+ async consumeTypes() {
578
+ var _a;
579
+ try {
580
+ const { options } = this;
581
+ if (!options.host) {
582
+ throw new Error("options.host is required if you want to consumeTypes");
583
+ }
584
+ const { mapRemotesToDownload } = retrieveHostConfig(options.host);
585
+ if (!Object.keys(mapRemotesToDownload).length) {
586
+ return;
587
+ }
588
+ const { downloadPromisesResult, hostOptions } = await this.consumeArchiveTypes(options.host);
589
+ if (hostOptions.consumeAPITypes) {
590
+ await Promise.all(
591
+ downloadPromisesResult.map(async (item) => {
592
+ if (item.status === "rejected" || !item.value) {
593
+ return;
594
+ }
595
+ const [alias, destinationPath] = item.value;
596
+ const remoteInfo = this.remoteAliasMap[alias];
597
+ if (!remoteInfo) {
598
+ return;
599
+ }
600
+ await this.downloadAPITypes(remoteInfo, destinationPath);
601
+ })
602
+ );
603
+ this.consumeAPITypes(hostOptions);
604
+ }
605
+ console.log(ansiColors2.green("Federated types extraction completed"));
606
+ } catch (err) {
607
+ if (((_a = this.options.host) == null ? void 0 : _a.abortOnError) === false) {
608
+ console.error(
609
+ ansiColors2.red(`Unable to consume federated types, ${err}`)
610
+ );
611
+ } else {
612
+ throw err;
613
+ }
614
+ }
615
+ }
616
+ async updateTypes(options) {
617
+ var _a, _b, _c;
618
+ const { remoteName, updateMode } = options;
619
+ const hostName = (_c = (_b = (_a = this.options) == null ? void 0 : _a.host) == null ? void 0 : _b.moduleFederationConfig) == null ? void 0 : _c.name;
620
+ if (updateMode === "POSITIVE" /* POSITIVE */ && remoteName === hostName) {
621
+ if (!this.options.remote) {
622
+ return;
623
+ }
624
+ this.generateTypes();
625
+ } else {
626
+ const { remoteAliasMap } = this;
627
+ if (!this.options.host) {
628
+ return;
629
+ }
630
+ const { hostOptions, mapRemotesToDownload } = retrieveHostConfig(
631
+ this.options.host
632
+ );
633
+ const loadedRemoteInfo = Object.values(remoteAliasMap).find(
634
+ (i) => i.name === remoteName
635
+ );
636
+ if (!loadedRemoteInfo) {
637
+ const remoteInfo = Object.values(mapRemotesToDownload).find((item) => {
638
+ return item.name === remoteName;
639
+ });
640
+ if (remoteInfo) {
641
+ if (!this.remoteAliasMap[remoteInfo.alias]) {
642
+ const requiredRemoteInfo = await this.requestRemoteManifest(remoteInfo);
643
+ this.remoteAliasMap[remoteInfo.alias] = requiredRemoteInfo;
644
+ }
645
+ await this.consumeTargetRemotes(
646
+ hostOptions,
647
+ this.remoteAliasMap[remoteInfo.alias]
648
+ );
649
+ }
650
+ } else {
651
+ await this.consumeTargetRemotes(hostOptions, loadedRemoteInfo);
652
+ }
653
+ }
654
+ }
655
+ };
656
+
657
+ // packages/native-federation-typescript/src/lib/utils.ts
658
+ import ansiColors3 from "ansi-colors";
659
+ function getDTSManagerConstructor(implementation) {
660
+ if (implementation) {
661
+ const NewConstructor = __require(implementation);
662
+ return NewConstructor.default ? NewConstructor.default : NewConstructor;
663
+ }
664
+ return DTSManager;
665
+ }
666
+ var validateOptions = (options) => {
667
+ if (!options.moduleFederationConfig) {
668
+ throw new Error("moduleFederationConfig is required");
669
+ }
670
+ };
671
+ function retrieveTypesAssetsInfo(options) {
672
+ let apiTypesPath = "";
673
+ let zipTypesPath = "";
674
+ try {
675
+ const { tsConfig, remoteOptions, mapComponentsToExpose } = retrieveRemoteConfig(options);
676
+ if (!Object.keys(mapComponentsToExpose).length) {
677
+ return {
678
+ apiTypesPath,
679
+ zipTypesPath,
680
+ zipName: "",
681
+ apiFileName: ""
682
+ };
683
+ }
684
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
685
+ zipTypesPath = retrieveTypesZipPath(mfTypesPath, remoteOptions);
686
+ if (remoteOptions.generateAPITypes) {
687
+ apiTypesPath = retrieveMfAPITypesPath(tsConfig, remoteOptions);
688
+ }
689
+ return {
690
+ apiTypesPath,
691
+ zipTypesPath,
692
+ zipName: path2.basename(zipTypesPath),
693
+ apiFileName: path2.basename(apiTypesPath)
694
+ };
695
+ } catch (err) {
696
+ console.error(ansiColors3.red(`Unable to compile federated types, ${err}`));
697
+ return {
698
+ apiTypesPath: "",
699
+ zipTypesPath: "",
700
+ zipName: "",
701
+ apiFileName: ""
702
+ };
703
+ }
704
+ }
705
+ function replaceLocalhost(url) {
706
+ return url.replace("localhost", "127.0.0.1");
707
+ }
708
+ function isDebugMode() {
709
+ return Boolean(process.env.FEDERATION_DEBUG);
710
+ }
711
+
712
+ // packages/native-federation-typescript/src/lib/archiveHandler.ts
713
+ var retrieveTypesZipPath = (mfTypesPath, remoteOptions) => join3(
714
+ mfTypesPath.replace(remoteOptions.typesFolder, ""),
715
+ `${remoteOptions.typesFolder}.zip`
716
+ );
717
+ var createTypesArchive = async (tsConfig, remoteOptions) => {
718
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
719
+ const zip = new AdmZip();
720
+ zip.addLocalFolder(mfTypesPath);
721
+ return zip.writeZipPromise(retrieveTypesZipPath(mfTypesPath, remoteOptions));
722
+ };
723
+ var downloadErrorLogger = (destinationFolder, fileToDownload) => (reason) => {
724
+ throw {
725
+ ...reason,
726
+ message: `Network error: Unable to download federated mocks for '${destinationFolder}' from '${fileToDownload}' because '${reason.message}'`
727
+ };
728
+ };
729
+ var retrieveTypesArchiveDestinationPath = (hostOptions, destinationFolder) => {
730
+ return resolve3(
731
+ hostOptions.context,
732
+ hostOptions.typesFolder,
733
+ destinationFolder
734
+ );
735
+ };
736
+ var downloadTypesArchive = (hostOptions) => {
737
+ let retries = 0;
738
+ return async ([destinationFolder, fileToDownload]) => {
739
+ const destinationPath = retrieveTypesArchiveDestinationPath(
740
+ hostOptions,
741
+ destinationFolder
742
+ );
743
+ while (retries++ < hostOptions.maxRetries) {
744
+ try {
745
+ const url = replaceLocalhost(fileToDownload);
746
+ const response = await axios2.get(url, { responseType: "arraybuffer" }).catch(downloadErrorLogger(destinationFolder, url));
747
+ const zip = new AdmZip(Buffer.from(response.data));
748
+ zip.extractAllTo(destinationPath, true);
749
+ return [destinationFolder, destinationPath];
750
+ } catch (error) {
751
+ if (isDebugMode()) {
752
+ console.error(
753
+ ansiColors4.red(
754
+ `Error during types archive download: ${(error == null ? void 0 : error.message) || "unknown error"}`
755
+ )
756
+ );
757
+ }
758
+ if (retries >= hostOptions.maxRetries) {
759
+ if (hostOptions.abortOnError !== false) {
760
+ throw error;
761
+ }
762
+ return void 0;
763
+ }
764
+ }
765
+ }
766
+ };
767
+ };
768
+
769
+ // packages/native-federation-typescript/src/lib/generateTypes.ts
770
+ async function generateTypes(options) {
771
+ var _a;
772
+ const DTSManagerConstructor = getDTSManagerConstructor(
773
+ (_a = options.remote) == null ? void 0 : _a.implementation
774
+ );
775
+ const dtsManager = new DTSManagerConstructor(options);
776
+ return dtsManager.generateTypes();
777
+ }
778
+
779
+ // packages/native-federation-typescript/src/rpc/types.ts
780
+ var RpcGMCallTypes = /* @__PURE__ */ ((RpcGMCallTypes2) => {
781
+ RpcGMCallTypes2["CALL"] = "mf_call";
782
+ RpcGMCallTypes2["RESOLVE"] = "mf_resolve";
783
+ RpcGMCallTypes2["REJECT"] = "mf_reject";
784
+ RpcGMCallTypes2["EXIT"] = "mf_exit";
785
+ return RpcGMCallTypes2;
786
+ })(RpcGMCallTypes || {});
787
+
788
+ // packages/native-federation-typescript/src/rpc/expose-rpc.ts
789
+ import process2 from "process";
790
+ function exposeRpc(fn) {
791
+ const sendMessage = (message) => new Promise((resolve4, reject) => {
792
+ if (!process2.send) {
793
+ reject(new Error(`Process ${process2.pid} doesn't have IPC channels`));
794
+ } else if (!process2.connected) {
795
+ reject(
796
+ new Error(`Process ${process2.pid} doesn't have open IPC channels`)
797
+ );
798
+ } else {
799
+ process2.send(message, void 0, void 0, (error) => {
800
+ if (error) {
801
+ reject(error);
802
+ } else {
803
+ resolve4(void 0);
804
+ }
805
+ });
806
+ }
807
+ });
808
+ const handleMessage = async (message) => {
809
+ if (message.type === "mf_call" /* CALL */) {
810
+ if (!process2.send) {
811
+ return;
812
+ }
813
+ let value, error;
814
+ try {
815
+ value = await fn(...message.args);
816
+ } catch (fnError) {
817
+ error = fnError;
818
+ }
819
+ try {
820
+ if (error) {
821
+ await sendMessage({
822
+ type: "mf_reject" /* REJECT */,
823
+ id: message.id,
824
+ error
825
+ });
826
+ } else {
827
+ await sendMessage({
828
+ type: "mf_resolve" /* RESOLVE */,
829
+ id: message.id,
830
+ value
831
+ });
832
+ }
833
+ } catch (sendError) {
834
+ if (error) {
835
+ if (error instanceof Error) {
836
+ console.error(error);
837
+ }
838
+ }
839
+ console.error(sendError);
840
+ }
841
+ }
842
+ };
843
+ process2.on("message", handleMessage);
844
+ }
845
+
846
+ export {
847
+ __export,
848
+ retrieveMfTypesPath,
849
+ retrieveOriginalOutDir,
850
+ retrieveTypesZipPath,
851
+ retrieveHostConfig,
852
+ REMOTE_ALIAS_IDENTIFIER,
853
+ REMOTE_API_TYPES_FILE_NAME,
854
+ HOST_API_TYPES_FILE_NAME,
855
+ UpdateMode,
856
+ DTSManager,
857
+ getDTSManagerConstructor,
858
+ validateOptions,
859
+ retrieveTypesAssetsInfo,
860
+ retrieveRemoteConfig,
861
+ generateTypes,
862
+ RpcGMCallTypes,
863
+ exposeRpc
864
+ };