-
Notifications
You must be signed in to change notification settings - Fork 217
/
KiotaBuilder.cs
2529 lines (2427 loc) · 141 KB
/
KiotaBuilder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using DotNet.Globbing;
using Kiota.Builder.Caching;
using Kiota.Builder.CodeDOM;
using Kiota.Builder.CodeRenderers;
using Kiota.Builder.Configuration;
using Kiota.Builder.EqualityComparers;
using Kiota.Builder.Exceptions;
using Kiota.Builder.Export;
using Kiota.Builder.Extensions;
using Kiota.Builder.Logging;
using Kiota.Builder.Manifest;
using Kiota.Builder.OpenApiExtensions;
using Kiota.Builder.Plugins;
using Kiota.Builder.Refiners;
using Kiota.Builder.WorkspaceManagement;
using Kiota.Builder.Writers;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.ApiManifest;
using Microsoft.OpenApi.MicrosoftExtensions;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Services;
using HttpMethod = Kiota.Builder.CodeDOM.HttpMethod;
[assembly: InternalsVisibleTo("Kiota.Builder.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100957cb48387b2a5f54f5ce39255f18f26d32a39990db27cf48737afc6bc62759ba996b8a2bfb675d4e39f3d06ecb55a178b1b4031dcb2a767e29977d88cce864a0d16bfc1b3bebb0edf9fe285f10fffc0a85f93d664fa05af07faa3aad2e545182dbf787e3fd32b56aca95df1a3c4e75dec164a3f1a4c653d971b01ffc39eb3c4")]
namespace Kiota.Builder;
public partial class KiotaBuilder
{
private readonly ILogger<KiotaBuilder> logger;
private readonly GenerationConfiguration config;
private readonly ParallelOptions parallelOptions;
private readonly HttpClient httpClient;
private OpenApiDocument? openApiDocument;
internal void SetOpenApiDocument(OpenApiDocument document) => openApiDocument = document ?? throw new ArgumentNullException(nameof(document));
public KiotaBuilder(ILogger<KiotaBuilder> logger, GenerationConfiguration config, HttpClient client, bool useKiotaConfig = false)
{
ArgumentNullException.ThrowIfNull(logger);
ArgumentNullException.ThrowIfNull(config);
ArgumentNullException.ThrowIfNull(client);
this.logger = logger;
this.config = config;
httpClient = client;
parallelOptions = new ParallelOptions
{
MaxDegreeOfParallelism = config.MaxDegreeOfParallelism,
};
var workingDirectory = Directory.GetCurrentDirectory();
workspaceManagementService = new WorkspaceManagementService(logger, client, useKiotaConfig, workingDirectory);
this.useKiotaConfig = useKiotaConfig;
openApiDocumentDownloadService = new OpenApiDocumentDownloadService(client, logger);
}
private readonly OpenApiDocumentDownloadService openApiDocumentDownloadService;
private readonly bool useKiotaConfig;
private async Task CleanOutputDirectoryAsync(CancellationToken cancellationToken)
{
if (config.CleanOutput && Directory.Exists(config.OutputPath))
{
logger.LogInformation("Cleaning output directory {Path}", config.OutputPath);
// not using Directory.Delete on the main directory because it's locked when mapped in a container
foreach (var subDir in Directory.EnumerateDirectories(config.OutputPath))
Directory.Delete(subDir, true);
await workspaceManagementService.BackupStateAsync(config.OutputPath, cancellationToken).ConfigureAwait(false);
foreach (var subFile in Directory.EnumerateFiles(config.OutputPath)
.Where(static x => !x.EndsWith(FileLogLogger.LogFileName, StringComparison.OrdinalIgnoreCase)))
File.Delete(subFile);
}
}
public async Task<OpenApiUrlTreeNode?> GetUrlTreeNodeAsync(CancellationToken cancellationToken)
{
var sw = new Stopwatch();
var inputPath = config.OpenAPIFilePath;
var (_, openApiTree, _) = await GetTreeNodeInternalAsync(inputPath, false, sw, cancellationToken).ConfigureAwait(false);
return openApiTree;
}
public OpenApiDocument? OpenApiDocument => openApiDocument;
private static string NormalizeApiManifestPath(RequestInfo request, string? baseUrl)
{
var rawValue = $"{request.UriTemplate}{(request.Method is null ? string.Empty : "#")}{request.Method?.ToUpperInvariant()}";
if (!string.IsNullOrEmpty(baseUrl) && rawValue.StartsWith(baseUrl, StringComparison.OrdinalIgnoreCase))
rawValue = rawValue[baseUrl.Length..];
if (!rawValue.StartsWith('/'))
rawValue = '/' + rawValue;
return rawValue.Split('?', StringSplitOptions.RemoveEmptyEntries)[0];
}
public async Task<Tuple<string, IEnumerable<string>>?> GetApiManifestDetailsAsync(bool skipErrorLog = false, CancellationToken cancellationToken = default)
{
try
{
logger.LogDebug("Api manifest path: {ApiManifestPath}", config.ApiManifestPath);
var pathParts = config.ApiManifestPath.Split(manifestPathSeparator, StringSplitOptions.RemoveEmptyEntries);
var manifestPath = pathParts[0];
var apiIdentifier = pathParts.Length > 1 ? pathParts[1] : string.Empty;
var manifestManagementService = new ManifestManagementService();
var documentCachingProvider = new DocumentCachingProvider(httpClient, logger);
#pragma warning disable CA2000
using var manifestFileContent = manifestPath.StartsWith("http", StringComparison.OrdinalIgnoreCase) switch
{
false => File.OpenRead(manifestPath),
true => await documentCachingProvider.GetDocumentAsync(new Uri(manifestPath), "manifests", "manifest.json", cancellationToken: cancellationToken).ConfigureAwait(false)
};
#pragma warning restore CA2000
var manifest = await manifestManagementService.DeserializeManifestDocumentAsync(manifestFileContent).ConfigureAwait(false)
?? throw new InvalidOperationException("The manifest could not be decoded");
var apiDependency = (manifest.ApiDependencies.Count, string.IsNullOrEmpty(apiIdentifier)) switch
{
(0, _) => throw new InvalidOperationException("The manifest contains no APIs"),
(1, _) => manifest.ApiDependencies.First().Value,
(_, true) => throw new InvalidOperationException("The manifest contains multiple APIs, please specify the API identifier"),
(_, false) => manifest.ApiDependencies.TryGetValue(apiIdentifier, out var apiDep) ? apiDep : throw new InvalidOperationException($"The manifest does not contain the API {apiIdentifier}")
};
if (apiDependency.ApiDescriptionUrl is null)
throw new InvalidOperationException("The manifest does not contain an API description URL");
return new Tuple<string, IEnumerable<string>>(apiDependency.ApiDescriptionUrl,
apiDependency.Requests.Select(x => NormalizeApiManifestPath(x, apiDependency.ApiDeploymentBaseUrl)).ToArray());
}
#pragma warning disable CA1031
catch (Exception ex)
#pragma warning restore CA1031
{
if (!skipErrorLog)
logger.LogCritical("error getting the API manifest: {ExceptionMessage}", ex.Message);
return null;
}
}
private async Task<(int, OpenApiUrlTreeNode?, bool)> GetTreeNodeInternalAsync(string inputPath, bool generating, Stopwatch sw, CancellationToken cancellationToken)
{
logger.LogDebug("kiota version {Version}", Generated.KiotaVersion.Current());
var stepId = 0;
if (config.ShouldGetApiManifest)
{
sw.Start();
var manifestDetails = await GetApiManifestDetailsAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
if (manifestDetails is not null)
{
inputPath = manifestDetails.Item1;
if (config.IncludePatterns.Count == 0)
config.IncludePatterns = manifestDetails.Item2.ToHashSet(StringComparer.OrdinalIgnoreCase);
}
StopLogAndReset(sw, $"step {++stepId} - getting the manifest - took");
}
sw.Start();
#pragma warning disable CA2007
await using var input = await LoadStreamAsync(inputPath, cancellationToken).ConfigureAwait(false);
#pragma warning restore CA2007
if (input.Length == 0)
return (0, null, false);
StopLogAndReset(sw, $"step {++stepId} - reading the stream - took");
// Parse OpenAPI
sw.Start();
openApiDocument = await CreateOpenApiDocumentAsync(input, generating, cancellationToken).ConfigureAwait(false);
StopLogAndReset(sw, $"step {++stepId} - parsing the document - took");
sw.Start();
UpdateConfigurationFromOpenApiDocument();
StopLogAndReset(sw, $"step {++stepId} - updating generation configuration from kiota extension - took");
OpenApiUrlTreeNode? openApiTree = null;
var shouldGenerate = !config.SkipGeneration;
if (openApiDocument != null)
{
// filter paths
sw.Start();
FilterPathsByPatterns(openApiDocument);
StopLogAndReset(sw, $"step {++stepId} - filtering API paths with patterns - took");
SetApiRootUrl();
// Should Generate
sw.Start();
shouldGenerate &= await workspaceManagementService.ShouldGenerateAsync(config, openApiDocument.HashCode, cancellationToken).ConfigureAwait(false);
StopLogAndReset(sw, $"step {++stepId} - checking whether the output should be updated - took");
if (shouldGenerate && generating)
{
modelNamespacePrefixToTrim = GetDeeperMostCommonNamespaceNameForModels(openApiDocument);
}
// OperationId cleanup in the event that we are generating plugins
if (config.IsPluginConfiguration)
{
CleanupOperationIdForPlugins(openApiDocument);
}
// Create Uri Space of API
sw.Start();
openApiTree = CreateUriSpace(openApiDocument);
StopLogAndReset(sw, $"step {++stepId} - create uri space - took");
}
return (stepId, openApiTree, shouldGenerate);
}
private void UpdateConfigurationFromOpenApiDocument()
{
if (openApiDocument == null ||
GetLanguagesInformationInternal() is not LanguagesInformation languagesInfo) return;
config.UpdateConfigurationFromLanguagesInformation(languagesInfo);
}
public async Task<LanguagesInformation?> GetLanguagesInformationAsync(CancellationToken cancellationToken)
{
await GetTreeNodeInternalAsync(config.OpenAPIFilePath, false, new Stopwatch(), cancellationToken).ConfigureAwait(false);
return GetLanguagesInformationInternal();
}
private LanguagesInformation? GetLanguagesInformationInternal()
{
if (openApiDocument == null)
return null;
if (openApiDocument.Extensions.TryGetValue(OpenApiKiotaExtension.Name, out var ext) && ext is OpenApiKiotaExtension kiotaExt)
return kiotaExt.LanguagesInformation;
return null;
}
/// <summary>
/// Generates the API plugins from the OpenAPI document
/// </summary>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>Whether the generated plugin was updated or not</returns>
public async Task<bool> GeneratePluginAsync(CancellationToken cancellationToken)
{
return await GenerateConsumerAsync(async (sw, stepId, openApiTree, CancellationToken) =>
{
if (openApiDocument is null || openApiTree is null)
throw new InvalidOperationException("The OpenAPI document and the URL tree must be loaded before generating the plugins");
// generate plugin
sw.Start();
var pluginsService = new PluginsGenerationService(openApiDocument, openApiTree, config, Directory.GetCurrentDirectory(), logger);
await pluginsService.GenerateManifestAsync(cancellationToken).ConfigureAwait(false);
StopLogAndReset(sw, $"step {++stepId} - generate plugin - took");
return stepId;
}, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Generates the code from the OpenAPI document
/// </summary>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>Whether the generated code was updated or not</returns>
public async Task<bool> GenerateClientAsync(CancellationToken cancellationToken)
{
return await GenerateConsumerAsync(async (sw, stepId, openApiTree, CancellationToken) =>
{
// Create Source Model
sw.Start();
var generatedCode = CreateSourceModel(openApiTree);
StopLogAndReset(sw, $"step {++stepId} - create source model - took");
// RefineByLanguage
sw.Start();
await ApplyLanguageRefinementAsync(config, generatedCode, cancellationToken).ConfigureAwait(false);
StopLogAndReset(sw, $"step {++stepId} - refine by language - took");
if (config.ExportPublicApi)
{
// Generate public API export
sw.Start();
var fileStream = File.Create(Path.Combine(config.OutputPath, PublicApiExportService.DomExportFileName));
await using (fileStream.ConfigureAwait(false))
{
await new PublicApiExportService(config).SerializeDomAsync(fileStream, generatedCode, cancellationToken).ConfigureAwait(false);
}
StopLogAndReset(sw, $"step {++stepId} - generated public API export - took");
}
// Write language source
sw.Start();
await CreateLanguageSourceFilesAsync(config.Language, generatedCode, cancellationToken).ConfigureAwait(false);
StopLogAndReset(sw, $"step {++stepId} - writing files - took");
return stepId;
}, cancellationToken).ConfigureAwait(false);
}
private async Task<bool> GenerateConsumerAsync(Func<Stopwatch, int, OpenApiUrlTreeNode?, CancellationToken, Task<int>> innerGenerationSteps, CancellationToken cancellationToken)
{
var sw = new Stopwatch();
// Read input stream
var inputPath = config.OpenAPIFilePath;
if (config.Operation is ConsumerOperation.Add && await workspaceManagementService.IsConsumerPresentAsync(config.ClientClassName, cancellationToken).ConfigureAwait(false))
throw new InvalidOperationException($"The client {config.ClientClassName} already exists in the workspace");
try
{
await CleanOutputDirectoryAsync(cancellationToken).ConfigureAwait(false);
// doing this verification at the beginning to give immediate feedback to the user
Directory.CreateDirectory(config.OutputPath);
}
catch (Exception ex)
{
throw new InvalidOperationException($"Could not open/create output directory {config.OutputPath}, reason: {ex.Message}", ex);
}
try
{
var (stepId, openApiTree, shouldGenerate) = await GetTreeNodeInternalAsync(inputPath, true, sw, cancellationToken).ConfigureAwait(false);
if (shouldGenerate)
{
stepId = await innerGenerationSteps(sw, stepId, openApiTree, cancellationToken).ConfigureAwait(false);
await FinalizeWorkspaceAsync(sw, stepId, openApiTree, inputPath, cancellationToken).ConfigureAwait(false);
}
else
{
logger.LogInformation("No changes detected, skipping generation");
if (config.Operation is ConsumerOperation.Add or ConsumerOperation.Edit && config.SkipGeneration)
{
await FinalizeWorkspaceAsync(sw, stepId, openApiTree, inputPath, cancellationToken).ConfigureAwait(false);
}
return false;
}
}
catch
{
await workspaceManagementService.RestoreStateAsync(config.OutputPath, cancellationToken).ConfigureAwait(false);
throw;
}
return true;
}
private async Task FinalizeWorkspaceAsync(Stopwatch sw, int stepId, OpenApiUrlTreeNode? openApiTree, string inputPath, CancellationToken cancellationToken)
{
// Write lock file
sw.Start();
using var descriptionStream = !isDescriptionFromWorkspaceCopy ? await LoadStreamAsync(inputPath, cancellationToken).ConfigureAwait(false) : Stream.Null;
await workspaceManagementService.UpdateStateFromConfigurationAsync(config, openApiDocument?.HashCode ?? string.Empty, openApiTree?.GetRequestInfo().ToDictionary(static x => x.Key, static x => x.Value) ?? [], descriptionStream, cancellationToken).ConfigureAwait(false);
StopLogAndReset(sw, $"step {++stepId} - writing lock file - took");
}
private readonly WorkspaceManagementService workspaceManagementService;
private static readonly GlobComparer globComparer = new();
[GeneratedRegex(@"([\/\\])\{[\w\d-]+\}([\/\\])?", RegexOptions.IgnoreCase | RegexOptions.Singleline, 2000)]
private static partial Regex MultiIndexSameLevelCleanupRegex();
internal static string ReplaceAllIndexesWithWildcard(string path, uint depth = 10) => depth == 0 ? path : ReplaceAllIndexesWithWildcard(MultiIndexSameLevelCleanupRegex().Replace(path, "$1{*}$2"), depth - 1); // the bound needs to be greedy to avoid replacing anything else than single path parameters
private static Dictionary<Glob, HashSet<OperationType>> GetFilterPatternsFromConfiguration(HashSet<string> configPatterns)
{
return configPatterns.Select(static x =>
{
var splat = x.Split('#', StringSplitOptions.RemoveEmptyEntries);
var glob = Glob.Parse(ReplaceAllIndexesWithWildcard(splat[0]));
var operationTypes = splat.Length > 1 ?
splat[1].Split(',', StringSplitOptions.RemoveEmptyEntries)
.Select(static y => Enum.TryParse<OperationType>(y.Trim(), true, out var op) ? op : default(OperationType?)) :
Enumerable.Empty<OperationType?>();
return (glob, operationTypes);
}).GroupBy(static x => x.glob, globComparer)
.ToDictionary(static x => x.Key,
static x => new HashSet<OperationType>(x.SelectMany(static y => y.operationTypes)
.Where(static y => y != null && y.HasValue)
.Select(static y => y!.Value)),
globComparer);
}
[GeneratedRegex(@"[^a-zA-Z0-9_]+", RegexOptions.IgnoreCase | RegexOptions.Singleline, 2000)]
private static partial Regex PluginOperationIdCleanupRegex();
internal static void CleanupOperationIdForPlugins(OpenApiDocument document)
{
if (document.Paths is null) return;
foreach (var (pathItem, operation) in document.Paths.SelectMany(static path => path.Value.Operations.Select(value => new Tuple<string, KeyValuePair<OperationType, OpenApiOperation>>(path.Key, value))))
{
if (string.IsNullOrEmpty(operation.Value.OperationId))
{
var stringBuilder = new StringBuilder();
foreach (var segment in pathItem.TrimStart('/').Split('/', StringSplitOptions.RemoveEmptyEntries))
{
if (segment.IsPathSegmentWithSingleSimpleParameter())
stringBuilder.Append("item");
else if (!string.IsNullOrEmpty(segment.Trim()))
stringBuilder.Append(segment.ToLowerInvariant());
stringBuilder.Append('_');
}
stringBuilder.Append(operation.Key.ToString().ToLowerInvariant());
operation.Value.OperationId = stringBuilder.ToString();
}
else
{
operation.Value.OperationId = PluginOperationIdCleanupRegex().Replace(operation.Value.OperationId, "_");//replace non-alphanumeric characters with _
}
}
}
internal void FilterPathsByPatterns(OpenApiDocument doc)
{
var includePatterns = GetFilterPatternsFromConfiguration(config.IncludePatterns);
var excludePatterns = GetFilterPatternsFromConfiguration(config.ExcludePatterns);
if (config.PatternsOverride.Count != 0)
{ // loading the patterns from the manifest as we don't want to take the user input one and have new operation creep in from the description being updated since last generation
includePatterns = GetFilterPatternsFromConfiguration(config.PatternsOverride);
excludePatterns = [];
}
if (includePatterns.Count == 0 && excludePatterns.Count == 0) return;
var nonOperationIncludePatterns = includePatterns.Where(static x => x.Value.Count == 0).Select(static x => x.Key).ToList();
var nonOperationExcludePatterns = excludePatterns.Where(static x => x.Value.Count == 0).Select(static x => x.Key).ToList();
var operationIncludePatterns = includePatterns.Where(static x => x.Value.Count != 0).ToList();
if (nonOperationIncludePatterns.Count != 0 || nonOperationExcludePatterns.Count != 0)
doc.Paths.Keys.Where(x => (nonOperationIncludePatterns.Count != 0 && !nonOperationIncludePatterns.Any(y => y.IsMatch(x)) ||
nonOperationExcludePatterns.Count != 0 && nonOperationExcludePatterns.Any(y => y.IsMatch(x))) &&
!operationIncludePatterns.Any(y => y.Key.IsMatch(x))) // so we don't trim paths that are going to be filtered by operation
.ToList()
.ForEach(x => doc.Paths.Remove(x));
var operationExcludePatterns = excludePatterns.Where(static x => x.Value.Count != 0).ToList();
if (operationIncludePatterns.Count != 0 || operationExcludePatterns.Count != 0)
{
foreach (var path in doc.Paths.Where(x => !nonOperationIncludePatterns.Any(y => y.IsMatch(x.Key))))
{
var pathString = path.Key;
path.Value.Operations.Keys.Where(x => operationIncludePatterns.Count != 0 && !operationIncludePatterns.Any(y => y.Key.IsMatch(pathString) && y.Value.Contains(x)))
.ToList()
.ForEach(x => path.Value.Operations.Remove(x));
}
foreach (var path in doc.Paths)
{
var pathString = path.Key;
path.Value.Operations.Keys.Where(x => operationExcludePatterns.Count != 0 && operationExcludePatterns.Any(y => y.Key.IsMatch(pathString) && y.Value.Contains(x)))
.ToList()
.ForEach(x => path.Value.Operations.Remove(x));
}
foreach (var path in doc.Paths.Where(static x => !x.Value.Operations.Any()).ToList())
doc.Paths.Remove(path.Key);
}
if (!doc.Paths.Any())
logger.LogWarning("No paths were found matching the provided patterns. Check your configuration.");
}
internal void SetApiRootUrl()
{
if (openApiDocument is not null && openApiDocument.GetAPIRootUrl(config.OpenAPIFilePath) is string candidateUrl)
{
config.ApiRootUrl = candidateUrl;
if (!config.IsPluginConfiguration)
{
logger.LogInformation("Client root URL set to {ApiRootUrl}", candidateUrl);
}
}
else
logger.LogWarning("No server url found in the OpenAPI document. The base url will need to be set when using the client.");
}
private void StopLogAndReset(Stopwatch sw, string prefix)
{
sw.Stop();
logger.LogDebug("{Prefix} {SwElapsed}", prefix, sw.Elapsed);
sw.Reset();
}
private bool isDescriptionFromWorkspaceCopy;
private async Task<Stream> LoadStreamAsync(string inputPath, CancellationToken cancellationToken)
{
var (input, isCopy) = await openApiDocumentDownloadService.LoadStreamAsync(inputPath, config, workspaceManagementService, useKiotaConfig, cancellationToken).ConfigureAwait(false);
isDescriptionFromWorkspaceCopy = isCopy;
return input;
}
internal const char ForwardSlash = '/';
internal Task<OpenApiDocument?> CreateOpenApiDocumentAsync(Stream input, bool generating = false, CancellationToken cancellationToken = default)
{
return openApiDocumentDownloadService.GetDocumentFromStreamAsync(input, config, generating, cancellationToken);
}
public static string GetDeeperMostCommonNamespaceNameForModels(OpenApiDocument document)
{
if (!(document?.Components?.Schemas?.Any() ?? false)) return string.Empty;
var distinctKeys = document.Components
.Schemas
.Keys
.Select(x => string.Join(NsNameSeparator, x.Split(NsNameSeparator, StringSplitOptions.RemoveEmptyEntries)
.SkipLast(1)))
.Where(static x => !string.IsNullOrEmpty(x))
.Distinct()
.OrderByDescending(static x => x.Count(static y => y == NsNameSeparator))
.ToArray();
if (distinctKeys.FirstOrDefault() is not string longestKey) return string.Empty;
var candidate = string.Empty;
var longestKeySegments = longestKey.Split(NsNameSeparator, StringSplitOptions.RemoveEmptyEntries);
foreach (var segment in longestKeySegments)
{
var testValue = (candidate + NsNameSeparator + segment).Trim(NsNameSeparator);
if (Array.TrueForAll(distinctKeys, x => x.StartsWith(testValue, StringComparison.OrdinalIgnoreCase)))
candidate = testValue;
else
break;
}
return candidate;
}
/// <summary>
/// Translate OpenApi PathItems into a tree structure that will define the classes
/// </summary>
/// <param name="doc">OpenAPI Document of the API to be processed</param>
/// <returns>Root node of the API URI space</returns>
public OpenApiUrlTreeNode CreateUriSpace(OpenApiDocument doc)
{
ArgumentNullException.ThrowIfNull(doc);
openApiDocument ??= doc;
var stopwatch = new Stopwatch();
stopwatch.Start();
var node = OpenApiUrlTreeNode.Create(doc, Constants.DefaultOpenApiLabel);
node.MergeIndexNodesAtSameLevel(logger);
stopwatch.Stop();
logger.LogTrace("{Timestamp}ms: Created UriSpace tree", stopwatch.ElapsedMilliseconds);
return node;
}
private CodeNamespace? rootNamespace;
private CodeNamespace? modelsNamespace;
private string? modelNamespacePrefixToTrim;
/// <summary>
/// Convert UriSpace of OpenApiPathItems into conceptual SDK Code model
/// </summary>
/// <param name="root">Root OpenApiUriSpaceNode of API to be generated</param>
/// <returns></returns>
public CodeNamespace CreateSourceModel(OpenApiUrlTreeNode? root)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
rootNamespace = CodeNamespace.InitRootNamespace();
var codeNamespace = rootNamespace.AddNamespace(config.ClientNamespaceName);
modelsNamespace = rootNamespace.AddNamespace(config.ModelsNamespaceName);
InitializeInheritanceIndex();
StopLogAndReset(stopwatch, $"{nameof(InitializeInheritanceIndex)}");
if (root != null)
{
CreateRequestBuilderClass(codeNamespace, root, root);
StopLogAndReset(stopwatch, $"{nameof(CreateRequestBuilderClass)}");
stopwatch.Start();
MapTypeDefinitions(codeNamespace);
StopLogAndReset(stopwatch, $"{nameof(MapTypeDefinitions)}");
TrimInheritedModels();
StopLogAndReset(stopwatch, $"{nameof(TrimInheritedModels)}");
CleanUpInternalState();
StopLogAndReset(stopwatch, $"{nameof(CleanUpInternalState)}");
logger.LogTrace("{Timestamp}ms: Created source model with {Count} classes", stopwatch.ElapsedMilliseconds, codeNamespace.GetChildElements(true).Count());
}
return rootNamespace;
}
/// <summary>
/// Manipulate CodeDOM for language specific issues
/// </summary>
/// <param name="config"></param>
/// <param name="generatedCode"></param>
/// <param name="token"></param>
public async Task ApplyLanguageRefinementAsync(GenerationConfiguration config, CodeNamespace generatedCode, CancellationToken token)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
await ILanguageRefiner.RefineAsync(config, generatedCode, token).ConfigureAwait(false);
stopwatch.Stop();
logger.LogDebug("{Timestamp}ms: Language refinement applied", stopwatch.ElapsedMilliseconds);
}
/// <summary>
/// Iterate through Url Space and create request builder classes for each node in the tree
/// </summary>
/// <param name="root">Root node of URI space from the OpenAPI described API</param>
/// <returns>A CodeNamespace object that contains request builder classes for the Uri Space</returns>
public async Task CreateLanguageSourceFilesAsync(GenerationLanguage language, CodeNamespace generatedCode, CancellationToken cancellationToken)
{
var languageWriter = LanguageWriter.GetLanguageWriter(language, config.OutputPath, config.ClientNamespaceName, config.UsesBackingStore, config.ExcludeBackwardCompatible);
var stopwatch = new Stopwatch();
stopwatch.Start();
var codeRenderer = CodeRenderer.GetCodeRender(config);
await codeRenderer.RenderCodeNamespaceToFilePerClassAsync(languageWriter, generatedCode, cancellationToken).ConfigureAwait(false);
stopwatch.Stop();
logger.LogTrace("{Timestamp}ms: Files written to {Path}", stopwatch.ElapsedMilliseconds, config.OutputPath);
}
private const string RequestBuilderSuffix = "RequestBuilder";
private const string ItemRequestBuilderSuffix = "ItemRequestBuilder";
private const string VoidType = "void";
private const string CoreInterfaceType = "IRequestAdapter";
private const string RequestAdapterParameterName = "requestAdapter";
private const string ConstructorMethodName = "constructor";
internal const string UntypedNodeName = "UntypedNode";
/// <summary>
/// Create a CodeClass instance that is a request builder class for the OpenApiUrlTreeNode
/// </summary>
private void CreateRequestBuilderClass(CodeNamespace currentNamespace, OpenApiUrlTreeNode currentNode, OpenApiUrlTreeNode rootNode)
{
// Determine Class Name
CodeClass codeClass;
var isApiClientClass = currentNode == rootNode;
if (isApiClientClass)
codeClass = currentNamespace.AddClass(new CodeClass
{
Name = config.ClientClassName,
Kind = CodeClassKind.RequestBuilder,
Documentation = new()
{
DescriptionTemplate = "The main entry point of the SDK, exposes the configuration and the fluent API."
},
}).First();
else
{
var targetNS = currentNode.DoesNodeBelongToItemSubnamespace() ? currentNamespace.EnsureItemNamespace() : currentNamespace;
var className = currentNode.DoesNodeBelongToItemSubnamespace() ? currentNode.GetNavigationPropertyName(config.StructuredMimeTypes, ItemRequestBuilderSuffix) : currentNode.GetNavigationPropertyName(config.StructuredMimeTypes, RequestBuilderSuffix);
codeClass = targetNS.AddClass(new CodeClass
{
Name = currentNamespace.Name.EndsWith(OpenApiUrlTreeNodeExtensions.ReservedItemNameEscaped, StringComparison.OrdinalIgnoreCase) ? className.CleanupSymbolName().Replace(OpenApiUrlTreeNodeExtensions.ReservedItemName, OpenApiUrlTreeNodeExtensions.ReservedItemNameEscaped, StringComparison.OrdinalIgnoreCase) : className.CleanupSymbolName(),
Kind = CodeClassKind.RequestBuilder,
Documentation = new()
{
DescriptionTemplate = currentNode.GetPathItemDescription(Constants.DefaultOpenApiLabel, $"Builds and executes requests for operations under {currentNode.Path}"),
},
}).First();
}
logger.LogTrace("Creating class {Class}", codeClass.Name);
// Add properties for children
foreach (var child in currentNode.Children.Select(static x => x.Value))
{
var propIdentifier = child.GetNavigationPropertyName(config.StructuredMimeTypes);
var propType = child.GetNavigationPropertyName(config.StructuredMimeTypes, child.DoesNodeBelongToItemSubnamespace() ? ItemRequestBuilderSuffix : RequestBuilderSuffix);
if (child.Segment.Equals(OpenApiUrlTreeNodeExtensions.ReservedItemName, StringComparison.OrdinalIgnoreCase) && !child.DoesNodeBelongToItemSubnamespace())
propType = propType.Replace(OpenApiUrlTreeNodeExtensions.ReservedItemName, OpenApiUrlTreeNodeExtensions.ReservedItemNameEscaped, StringComparison.OrdinalIgnoreCase);
if (child.IsPathSegmentWithSingleSimpleParameter())
{
var indexerParameterType = GetIndexerParameter(child, currentNode);
codeClass.AddIndexer(CreateIndexer($"{propIdentifier}-indexer", propType, indexerParameterType, child, currentNode));
}
else if (child.IsComplexPathMultipleParameters())
CreateMethod(propIdentifier, propType, codeClass, child);
else
{
var description = child.GetPathItemDescription(Constants.DefaultOpenApiLabel).CleanupDescription();
var prop = CreateProperty(propIdentifier, propType, kind: CodePropertyKind.RequestBuilder); // we should add the type definition here but we can't as it might not have been generated yet
if (prop is null)
{
logger.LogWarning("Property {Prop} was not created as its type couldn't be determined", propIdentifier);
continue;
}
prop.Deprecation = currentNode.GetDeprecationInformation();
if (!string.IsNullOrWhiteSpace(description))
{
prop.Documentation.DescriptionTemplate = description;
}
codeClass.AddProperty(prop);
}
}
CreateUrlManagement(codeClass, currentNode, isApiClientClass);
// Add methods for Operations
if (currentNode.HasOperations(Constants.DefaultOpenApiLabel))
{
if (!isApiClientClass) // do not generate for API client class with operations as the class won't have the rawUrl constructor.
CreateWithUrlMethod(currentNode, codeClass);
foreach (var operation in currentNode
.PathItems[Constants.DefaultOpenApiLabel]
.Operations)
CreateOperationMethods(currentNode, operation.Key, operation.Value, codeClass);
}
if (rootNamespace != null)
Parallel.ForEach(currentNode.Children.Values, parallelOptions, childNode =>
{
if (childNode.GetNodeNamespaceFromPath(config.ClientNamespaceName) is string targetNamespaceName &&
!string.IsNullOrEmpty(targetNamespaceName))
{
var targetNamespace = rootNamespace.FindOrAddNamespace(targetNamespaceName);
CreateRequestBuilderClass(targetNamespace, childNode, rootNode);
}
});
}
private static void CreateWithUrlMethod(OpenApiUrlTreeNode currentNode, CodeClass currentClass)
{
var methodToAdd = new CodeMethod
{
Name = "WithUrl",
Kind = CodeMethodKind.RawUrlBuilder,
Documentation = new()
{
DescriptionTemplate = "Returns a request builder with the provided arbitrary URL. Using this method means any other path or query parameters are ignored.",
},
Access = AccessModifier.Public,
IsAsync = false,
IsStatic = false,
ReturnType = new CodeType
{
ActionOf = false,
IsExternal = false,
IsNullable = false,
TypeDefinition = currentClass,
},
Deprecation = currentNode.GetDeprecationInformation(),
};
methodToAdd.AddParameter(new CodeParameter
{
Name = "rawUrl",
Type = new CodeType { Name = "string", IsExternal = true },
Optional = false,
Documentation = new()
{
DescriptionTemplate = "The raw URL to use for the request builder.",
},
Kind = CodeParameterKind.RawUrl,
});
currentClass.AddMethod(methodToAdd);
}
private static void CreateMethod(string propIdentifier, string propType, CodeClass codeClass, OpenApiUrlTreeNode currentNode)
{
var methodToAdd = new CodeMethod
{
Name = propIdentifier.CleanupSymbolName(),
Kind = CodeMethodKind.RequestBuilderWithParameters,
Documentation = new()
{
DescriptionTemplate = currentNode.GetPathItemDescription(Constants.DefaultOpenApiLabel, $"Builds and executes requests for operations under {currentNode.Path}"),
},
Access = AccessModifier.Public,
IsAsync = false,
IsStatic = false,
Parent = codeClass,
ReturnType = new CodeType
{
Name = propType,
ActionOf = false,
CollectionKind = CodeTypeBase.CodeTypeCollectionKind.None,
IsExternal = false,
IsNullable = false,
},
Deprecation = currentNode.GetDeprecationInformation(),
};
AddPathParametersToMethod(currentNode, methodToAdd, false);
codeClass.AddMethod(methodToAdd);
}
private static void AddPathParametersToMethod(OpenApiUrlTreeNode currentNode, CodeMethod methodToAdd, bool asOptional)
{
foreach (var parameter in currentNode.GetPathParametersForCurrentSegment())
{
var codeName = parameter.Name.SanitizeParameterNameForCodeSymbols();
var parameterType = GetPrimitiveType(parameter.Schema ?? parameter.Content.Values.FirstOrDefault()?.Schema) ??
new CodeType
{
Name = "string",
IsExternal = true,
};
parameterType.CollectionKind = parameter.Schema.IsArray() ? CodeTypeBase.CodeTypeCollectionKind.Array : default;
var mParameter = new CodeParameter
{
Name = codeName,
Optional = asOptional,
Documentation = new()
{
DescriptionTemplate = !string.IsNullOrEmpty(parameter.Description) ? parameter.Description.CleanupDescription() : $"The path parameter: {codeName}",
},
Kind = CodeParameterKind.Path,
SerializationName = parameter.Name.Equals(codeName, StringComparison.OrdinalIgnoreCase) ? string.Empty : parameter.Name.SanitizeParameterNameForUrlTemplate(),
Type = parameterType,
Deprecation = parameter.GetDeprecationInformation(),
};
// not using the content schema as RFC6570 will serialize arrays as CSVs and content expects a JSON array, we failsafe to opaque string, it could be improved by involving the serialization layers.
methodToAdd.AddParameter(mParameter);
}
}
private const string PathParametersParameterName = "pathParameters";
private void CreateUrlManagement(CodeClass currentClass, OpenApiUrlTreeNode currentNode, bool isApiClientClass)
{
var pathProperty = new CodeProperty
{
Access = AccessModifier.Private,
Name = "urlTemplate",
DefaultValue = $"\"{currentNode.GetUrlTemplate()}\"",
ReadOnly = true,
Documentation = new()
{
DescriptionTemplate = "Url template to use to build the URL for the current request builder",
},
Kind = CodePropertyKind.UrlTemplate,
Type = new CodeType
{
Name = "string",
IsNullable = false,
IsExternal = true,
},
};
currentClass.AddProperty(pathProperty);
var requestAdapterProperty = new CodeProperty
{
Name = RequestAdapterParameterName,
Documentation = new()
{
DescriptionTemplate = "The request adapter to use to execute the requests.",
},
Kind = CodePropertyKind.RequestAdapter,
Access = AccessModifier.Private,
ReadOnly = true,
Type = new CodeType
{
Name = CoreInterfaceType,
IsExternal = true,
IsNullable = false,
}
};
currentClass.AddProperty(requestAdapterProperty);
var constructor = new CodeMethod
{
Name = ConstructorMethodName,
Kind = isApiClientClass ? CodeMethodKind.ClientConstructor : CodeMethodKind.Constructor,
IsAsync = false,
IsStatic = false,
Documentation = new(new() {
{"TypeName", new CodeType {
IsExternal = false,
TypeDefinition = currentClass,
}
}
})
{
DescriptionTemplate = "Instantiates a new {TypeName} and sets the default values.",
},
Access = AccessModifier.Public,
ReturnType = new CodeType { Name = VoidType, IsExternal = true },
Parent = currentClass,
};
var pathParametersProperty = new CodeProperty
{
Name = PathParametersParameterName,
Documentation = new()
{
DescriptionTemplate = "Path parameters for the request",
},
Kind = CodePropertyKind.PathParameters,
Access = AccessModifier.Private,
ReadOnly = true,
Type = new CodeType
{
Name = "Dictionary<string, object>",
IsExternal = true,
IsNullable = false,
},
};
currentClass.AddProperty(pathParametersProperty);
if (isApiClientClass)
{
constructor.SerializerModules = ReplaceNoneSerializersByEmptySet(config.Serializers);
constructor.DeserializerModules = ReplaceNoneSerializersByEmptySet(config.Deserializers);
constructor.BaseUrl = config.ApiRootUrl ?? string.Empty;
pathParametersProperty.DefaultValue = $"new {pathParametersProperty.Type.Name}()";
}
else
{
constructor.AddParameter(new CodeParameter
{
Name = PathParametersParameterName,
Type = pathParametersProperty.Type,
Optional = false,
Documentation = (CodeDocumentation)pathParametersProperty.Documentation.Clone(),
Kind = CodeParameterKind.PathParameters,
});
AddPathParametersToMethod(currentNode, constructor, true);
}
constructor.AddParameter(new CodeParameter
{
Name = RequestAdapterParameterName,
Type = requestAdapterProperty.Type,
Optional = false,
Documentation = (CodeDocumentation)requestAdapterProperty.Documentation.Clone(),
Kind = CodeParameterKind.RequestAdapter,
});
if (isApiClientClass && config.UsesBackingStore)
{
var factoryInterfaceName = $"{BackingStoreInterface}Factory";
var backingStoreParam = new CodeParameter
{
Name = "backingStore",
Optional = true,
Documentation = new()
{
DescriptionTemplate = "The backing store to use for the models.",
},
Kind = CodeParameterKind.BackingStore,
Type = new CodeType
{
Name = factoryInterfaceName,
IsNullable = true,
}
};
constructor.AddParameter(backingStoreParam);
}
currentClass.AddMethod(constructor);
if (!isApiClientClass)
{
var overloadCtor = (CodeMethod)constructor.Clone();
overloadCtor.Kind = CodeMethodKind.RawUrlConstructor;
overloadCtor.OriginalMethod = constructor;
overloadCtor.RemoveParametersByKind(CodeParameterKind.PathParameters, CodeParameterKind.Path);
overloadCtor.AddParameter(new CodeParameter
{
Name = "rawUrl",
Type = new CodeType { Name = "string", IsExternal = true },
Optional = false,
Documentation = new()
{
DescriptionTemplate = "The raw URL to use for the request builder.",
},
Kind = CodeParameterKind.RawUrl,
});
currentClass.AddMethod(overloadCtor);
}
}
private static HashSet<string> ReplaceNoneSerializersByEmptySet(HashSet<string> serializers)
{
if (serializers.Count == 1 && serializers.Contains("none")) return [];
return serializers;
}
private static readonly Func<CodeClass, int> shortestNamespaceOrder = x => x.GetNamespaceDepth();
/// <summary>
/// Remaps definitions to custom types so they can be used later in generation or in refiners
/// </summary>
private void MapTypeDefinitions(CodeElement codeElement)
{
var unmappedTypes = GetUnmappedTypeDefinitions(codeElement).Distinct().ToArray();
var unmappedTypesWithNoName = unmappedTypes.Where(static x => string.IsNullOrEmpty(x.Name)).ToList();
unmappedTypesWithNoName.ForEach(x =>
{
logger.LogWarning("Type with empty name and parent {ParentName}", x.Parent?.Name);
});
var unmappedTypesWithName = unmappedTypes.Except(unmappedTypesWithNoName);
var unmappedRequestBuilderTypes = unmappedTypesWithName
.Where(static x =>
x.Parent is CodeProperty property && property.IsOfKind(CodePropertyKind.RequestBuilder) ||
x.Parent is CodeIndexer ||
x.Parent is CodeMethod method && method.IsOfKind(CodeMethodKind.RequestBuilderWithParameters))
.ToList();
Parallel.ForEach(unmappedRequestBuilderTypes, parallelOptions, x =>
{
var parentNS = x.Parent?.Parent?.Parent as CodeNamespace;
CodeClass[] exceptions = x.Parent?.Parent is CodeClass parentClass ? [parentClass] : [];
x.TypeDefinition = parentNS?.FindChildrenByName<CodeClass>(x.Name)
.Except(exceptions)// the property method should not reference itself as a return type.
.MinBy(shortestNamespaceOrder);
// searching down first because most request builder properties on a request builder are just sub paths on the API
if (x.TypeDefinition == null)
{
parentNS = parentNS?.Parent as CodeNamespace;
x.TypeDefinition = (parentNS
?.FindNamespaceByName($"{parentNS?.Name}.{x.Name[..^RequestBuilderSuffix.Length].ToFirstCharacterLowerCase()}".TrimEnd(NsNameSeparator))
?.FindChildrenByName<CodeClass>(x.Name))?.MinBy(shortestNamespaceOrder);
// in case of the .item namespace, going to the parent and then down to the target by convention
// this avoid getting the wrong request builder in case we have multiple request builders with the same name in the parent branch
// in both cases we always take the uppermost item (smaller numbers of segments in the namespace name)
}
});
Parallel.ForEach(unmappedTypesWithName.Where(static x => x.TypeDefinition == null).GroupBy(static x => x.Name), parallelOptions, x =>
{
if (rootNamespace?.FindChildByName<ITypeDefinition>(x.First().Name) is CodeElement definition)
foreach (var type in x)
{
type.TypeDefinition = definition;
logger.LogWarning("Mapped type {TypeName} for {ParentName} using the fallback approach.", type.Name, type.Parent?.Name);
}
});
}
private const char NsNameSeparator = '.';
private static IEnumerable<CodeType> filterUnmappedTypeDefinitions(IEnumerable<CodeTypeBase?> source) =>
source.OfType<CodeType>()
.Union(source
.OfType<CodeComposedTypeBase>()
.SelectMany(x => x.Types))
.Where(static x => !x.IsExternal && x.TypeDefinition == null);
private IEnumerable<CodeType> GetUnmappedTypeDefinitions(CodeElement codeElement)
{
var childElementsUnmappedTypes = codeElement.GetChildElements(true).SelectMany(GetUnmappedTypeDefinitions);
return codeElement switch
{
CodeMethod method => filterUnmappedTypeDefinitions(method.Parameters.Select(static x => x.Type).Union(new[] { method.ReturnType })).Union(childElementsUnmappedTypes),
CodeProperty property => filterUnmappedTypeDefinitions(new[] { property.Type }).Union(childElementsUnmappedTypes),
CodeIndexer indexer => filterUnmappedTypeDefinitions(new[] { indexer.ReturnType }).Union(childElementsUnmappedTypes),