-
Notifications
You must be signed in to change notification settings - Fork 308
Expand file tree
/
Copy pathgeneration-info.ts
More file actions
1221 lines (1193 loc) · 55.8 KB
/
generation-info.ts
File metadata and controls
1221 lines (1193 loc) · 55.8 KB
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
export type Namespace = string;
import { FernIr as DynamicFernIr } from "@fern-api/dynamic-ir-sdk";
import { FernIr } from "@fern-fern/ir-sdk";
type IntermediateRepresentation = FernIr.IntermediateRepresentation;
type TypeId = FernIr.TypeId;
type FernFilepath = FernIr.FernFilepath;
/**
* Browser-compatible path join for C# project paths.
* Joins path segments with "/" separator, filtering empty segments.
*/
function join(...segments: string[]): string {
return segments.filter(Boolean).join("/");
}
import * as ast from "../ast/index.js";
import { ClassReference } from "../ast/types/ClassReference.js";
import { Type } from "../ast/types/IType.js";
import { Collection, Primitive, Value } from "../ast/types/Type.js";
import { CSharp } from "../csharp.js";
import { type CsharpConfigSchema } from "../custom-config/index.js";
import { is, text } from "../index.js";
import { lazy } from "../utils/lazy.js";
import { camelCase, upperFirst } from "../utils/text.js";
import { MinimalGeneratorConfig, Support, TAbsoluteFilePath, TRelativeFilePath } from "./common.js";
import { Extern } from "./extern.js";
import { ModelNavigator } from "./model-navigator.js";
import { NameRegistry } from "./name-registry.js";
/**
* Central configuration and code generation context for C# SDK generation.
*
* This class serves as the single source of truth for all code generation decisions,
* consolidating names, namespaces, types, and settings into a unified graph. It eliminates
* duplication between dynamic and regular generators by providing consistent access to
* generation metadata.
*
* ## Key Responsibilities:
* - Manages namespace organization for generated C# code
* - Provides standardized naming conventions for classes, types, and identifiers
* - Lazily initializes and caches type references and configuration values
* - Serves as a navigation hub for the IR (Intermediate Representation) model
* - Coordinates between code generation utilities (CSharp, NameRegistry, etc.)
*
* ## Lazy Initialization:
* All returned values use lazy initialization for performance:
* - Parameterless functions: Evaluated once and cached on first access
* - Parameterized functions: Remain as functions, evaluated on each call
*
* ## Usage Pattern:
* ```typescript
* const generation = new Generation(ir, apiName, config, generatorConfig);
* const namespace = generation.namespaces.root; // Lazy-evaluated and cached
* const pager = generation.types.Pager(itemType); // Function, evaluated each call
* ```
*
* This object is safe to pass throughout the code generation pipeline and should be
* the primary source for all naming and type reference decisions.
*/
export class Generation {
/**
* Creates a new Generation context for C# code generation.
*
* @param intermediateRepresentation - The Fern IR containing the API definition,
* supports both static and dynamic IR formats
* @param apiName - The name of the API being generated (used for namespace/class naming)
* @param customConfig - User-provided custom configuration overrides for the generator
* @param generatorConfig - Core generator configuration including organization and workspace info
*/
constructor(
public readonly intermediateRepresentation:
| IntermediateRepresentation
| DynamicFernIr.dynamic.DynamicIntermediateRepresentation,
private readonly apiName: string,
private readonly customConfig: CsharpConfigSchema,
private readonly generatorConfig: MinimalGeneratorConfig,
private readonly support: Support = {
makeRelativeFilePath: (path) => path as TRelativeFilePath,
makeAbsoluteFilePath: (path: string) => path as TAbsoluteFilePath,
getNamespaceForTypeId: (typeId: TypeId) => "",
getDirectoryForTypeId: (typeId: TypeId) => "",
getCoreAsIsFiles: () => [],
getCoreTestAsIsFiles: () => [],
getPublicCoreAsIsFiles: () => [],
getAsyncCoreAsIsFiles: () => [],
getChildNamespaceSegments: (fernFilepath: FernFilepath) => []
}
) {
// Initialize the model navigator to traverse and query the IR
this.model = new ModelNavigator(intermediateRepresentation, this);
this.ir = is.IR.IntermediateRepresentation(intermediateRepresentation)
? intermediateRepresentation
: ({} as IntermediateRepresentation);
this.dir = is.DynamicIR.DynamicIntermediateRepresentation(intermediateRepresentation)
? intermediateRepresentation
: ({} as DynamicFernIr.dynamic.DynamicIntermediateRepresentation);
}
public readonly ir: IntermediateRepresentation;
public readonly dir: DynamicFernIr.dynamic.DynamicIntermediateRepresentation;
/**
* Utility for generating C# AST nodes and type references.
* Provides methods for creating class references, type declarations, and other C# constructs.
*/
public readonly csharp = new CSharp(this);
/**
* Registry for tracking and managing generated names to prevent collisions.
* Ensures unique naming across namespaces, classes, properties, and other identifiers.
*/
public readonly registry = new NameRegistry(this);
/**
* Navigator for traversing the IR model and querying type information.
* Provides access to types, endpoints, errors, and other IR elements.
*/
public readonly model: ModelNavigator;
/**
* Manager for external dependencies and imports.
* Tracks which external packages and types are needed by the generated code.
*/
public readonly extern = new Extern(this);
/**
* Lazily-initialized configuration settings for C# code generation.
*
* These settings control various aspects of the generated code including:
* - Namespace configuration
* - Feature flags (websockets, forward-compatible enums, etc.)
* - Type generation options (discriminated unions, additional properties)
* - Naming customization (client class names, exception classes)
* - Testing options (mock server tests)
* - Access modifiers and visibility settings
*
* All settings are derived from the custom configuration with sensible defaults.
* Each property is lazily evaluated and cached on first access.
*/
public readonly settings = lazy({
/** The root namespace for all generated C# code (e.g., "Acme.MyApi"). Defaults to Organization_ApiName in camelCase. */
namespace: () =>
this.customConfig.namespace ??
upperFirst(camelCase(`${this.generatorConfig.organization}_${this.apiName}`)),
/** List of types that should use ReadOnlyMemory<byte> instead of byte[] for binary data. Default: []. */
readOnlyMemoryTypes: () => this.customConfig["read-only-memory-types"] ?? [],
/** When true, simplifies object dictionaries in generated code for better type safety. Default: false. */
simplifyObjectDictionaries: () => this.customConfig["simplify-object-dictionaries"] ?? false,
/** When true, uses fully-qualified namespaces in generated code to avoid naming conflicts. Default: false. */
useFullyQualifiedNamespaces: () => this.customConfig["experimental-fully-qualified-namespaces"] ?? false,
/** When true, runs dotnet format on generated code for consistent formatting. Default: false. */
useDotnetFormat: () => this.customConfig["experimental-dotnet-format"] ?? false,
/** When true, enables WebSocket support in the generated SDK. Default: false. */
enableWebsockets: () => this.customConfig["experimental-enable-websockets"] ?? false,
/** @deprecated Use `generateLiterals` instead. When true, generates readonly constants instead of static properties. Default: false. */
enableReadonlyConstants: () => this.customConfig["experimental-readonly-constants"] ?? false,
/** When true, generates literal struct types for literal properties. If `experimental-readonly-constants` is also set, this takes precedence. Default: false. */
generateLiterals: () =>
this.customConfig["generate-literals"] ?? this.customConfig["experimental-readonly-constants"] ?? false,
/** When true, uses explicit nullable/optional attributes and Optional<T?> wrapper for better null handling. Default: false. */
enableExplicitNullableOptional: () => this.customConfig["experimental-explicit-nullable-optional"] ?? false,
/** When true, generates Defaults nested class and WithDefaults() method for request records with default values. Default: false. */
useDefaultRequestParameterValues: () => this.customConfig["use-default-request-parameter-values"] ?? false,
/** When true, redacts the response body in deserialization error exceptions and adds a custom ToString override to the base API exception. Default: false. */
redactResponseBodyOnError: () => this.customConfig["redact-response-body-on-error"] ?? false,
/** Temporary mapping of websocket environment configurations. Default: {}. */
temporaryWebsocketEnvironments: () => this.customConfig["temporary-websocket-environments"] ?? {},
/** Custom name for the base API exception class. Default: "" (auto-generated). */
baseApiExceptionClassName: () => this.customConfig["base-api-exception-class-name"] ?? "",
/** Custom name for the base exception class. Default: "" (auto-generated). */
baseExceptionClassName: () => this.customConfig["base-exception-class-name"] ?? "",
/** When true, generates discriminated unions with type discriminators. Default: true. */
shouldGeneratedDiscriminatedUnions: () => this.customConfig["use-discriminated-unions"] ?? true,
/** When true, generates undiscriminated unions with runtime type detection. Default: false. */
shouldGenerateUndiscriminatedUnions: () => this.customConfig["use-undiscriminated-unions"] ?? false,
/** Custom name for the exported public client class. Default: "" (uses clientClassName or computed name). */
exportedClientClassName: () => this.customConfig["exported-client-class-name"] ?? "",
/** Custom name for the internal client class. Default: "" (auto-generated from organization/workspace). */
clientClassName: () => this.customConfig["client-class-name"] ?? "",
/** When true, places core classes in the root namespace instead of {root}.Core. Default: true. */
rootNamespaceForCoreClasses: () => this.customConfig["root-namespace-for-core-classes"] ?? true,
/** Custom NuGet package identifier. Default: "" (uses root namespace). */
packageId: () => this.customConfig["package-id"] ?? "",
/** When true, generates enums that can handle unknown/future values gracefully. Default: true. */
isForwardCompatibleEnumsEnabled: () =>
this.customConfig["enable-forward-compatible-enums"] ??
this.customConfig["experimental-enable-forward-compatible-enums"] ??
true,
/** Mapping of websocket environment configurations. Default: {}. */
websocketEnvironments: () => this.customConfig["temporary-websocket-environments"] ?? {},
/** Custom name for the pagination class. Default: "" (auto-generated). */
customPagerName: () => this.customConfig["custom-pager-name"] ?? "",
/** Custom name for the environment configuration class. Default: "" (auto-generated). */
environmentClassName: () => this.customConfig["environment-class-name"] ?? "",
/** When true, generates dedicated error type classes for API errors. Default: true. */
generateErrorTypes: () => this.customConfig["generate-error-types"] ?? true,
/** When true, inlines path parameters in method signatures instead of using a request object. Default: true. */
shouldInlinePathParameters: () => this.customConfig["inline-path-parameters"] ?? true,
/** When true, includes exception handler infrastructure for custom error handling. Default: false. */
includeExceptionHandler: () => this.customConfig["include-exception-handler"] ?? false,
/** Custom name for the exception interceptor class. Default: {PackageName}ExceptionInterceptor. */
exceptionInterceptorClassName: () => this.customConfig["exception-interceptor-class-name"] ?? "",
/** When true, generates mock server tests for the SDK. Default: true. Also accepts enable-wire-tests as an alias. */
shouldGenerateMockServerTests: () =>
this.customConfig["generate-mock-server-tests"] ?? this.customConfig["enable-wire-tests"] ?? true,
/** Access modifier for the root client class (Public or Internal). Default: Public. */
rootClientAccess: () =>
this.customConfig["root-client-class-access"] == "internal" ? ast.Access.Internal : ast.Access.Public,
/** Additional NuGet package dependencies to include in the generated project. Default: {}. */
extraDependencies: () => this.customConfig["extra-dependencies"] ?? {},
/** When true, omits Fern platform headers (X-Fern-Language, SDK name/version, User-Agent) from generated SDK requests. Default: false. */
omitFernHeaders: () => this.customConfig["omit-fern-headers"] ?? false,
/** When true, uses PascalCase for environment names (e.g., "Production" instead of "production"). Default: true. */
pascalCaseEnvironments: () => this.customConfig["pascal-case-environments"] ?? true,
/** Solution file format: "sln" generates both .sln and .slnx, "slnx" (default) generates only .slnx. */
slnFormat: () => this.customConfig["sln-format"] ?? "slnx",
/** When true, requires explicit namespace declarations instead of using file-scoped namespaces. Default: false. */
explicitNamespaces: () => this.customConfig["explicit-namespaces"] === true,
/**
* Output path configuration for generated files.
* Returns normalized paths for library, test, solution, and other files.
*/
outputPath: () => {
const config = this.customConfig["output-path"];
if (config == null) {
// Default: all files go to "src" for library/test, "." for solution/other
return {
library: "src",
test: "src",
solution: ".",
other: "."
};
}
if (typeof config === "string") {
// Simple string: library and test go to that path, solution/other go to "."
return {
library: config,
test: config,
solution: ".",
other: "."
};
}
// Object: use specified paths with defaults
return {
library: config.library ?? "src",
test: config.test ?? "src",
solution: config.solution ?? ".",
other: config.other ?? "."
};
}
});
public readonly constants = {
folders: lazy({
mockServerTests: () => this.support.makeRelativeFilePath("Unit/MockServer"),
types: () => "Types",
exceptions: () => "Exceptions",
src: () => "src",
protobuf: () => "proto",
serializationTests: () => this.support.makeRelativeFilePath("Unit/Serialization"),
project: () =>
this.support.makeRelativeFilePath(
join(
this.constants.folders.sourceFiles,
this.support.makeRelativeFilePath(this.names.files.project)
)
),
sourceFiles: () => this.support.makeRelativeFilePath(this.constants.folders.src),
coreFiles: () =>
this.support.makeRelativeFilePath(
join(
this.constants.folders.project,
this.support.makeRelativeFilePath(this.constants.defaults.core)
)
),
publicCoreFiles: () =>
this.support.makeRelativeFilePath(
join(
this.constants.folders.project,
this.support.makeRelativeFilePath(this.constants.defaults.core),
this.support.makeRelativeFilePath(this.constants.defaults.publicCore)
)
),
testFiles: () =>
this.support.makeRelativeFilePath(
join(
this.constants.folders.sourceFiles,
this.support.makeRelativeFilePath(this.names.files.testProject)
)
)
}),
formatting: lazy({
indent: () => " "
}),
defaults: lazy({
core: () => "Core",
publicCore: () => "Public",
version: () => "0.0.0"
})
};
/**
* Lazily-initialized namespace paths for organizing generated C# code.
*
* This object defines the namespace hierarchy used throughout the generated SDK:
* - `root`: The top-level namespace for all generated code
* - `core`: Internal implementation details and utilities (e.g., {root}.Core)
* - `test`: Testing utilities and fixtures
* - `testUtils`: Helper methods for tests
* - `mockServerTest`: Mock server testing infrastructure
* - `publicCore`: Public core utilities exposed to SDK users
* - `webSocketsCore`: WebSocket API utilities
* - `publicCoreTest`: Tests for public core functionality
* - `asIsTestUtils`: Test utilities that preserve original casing
* - `publicCoreClasses`: Location for core classes based on rootNamespaceForCoreClasses setting
*
* Namespaces are canonicalized through the NameRegistry to avoid conflicts with generated types.
* All namespace paths are lazy-evaluated and cached on first access.
*/
public readonly namespaces = lazy({
/** The top-level root namespace for all generated SDK code (e.g., "Acme.MyApi"). */
root: (): string => this.settings.namespace,
/** Internal Core namespace for SDK implementation details and utilities ({root}.Core). */
core: (): string => `${this.namespaces.root}.Core`,
/** Pre-qualified root namespace with global:: prefix when the root segment has a type-namespace conflict. */
qualifiedRoot: (): string => this.qualifyNamespace(this.namespaces.root),
/** Pre-qualified Core namespace with global:: prefix when the root segment has a type-namespace conflict. */
qualifiedCore: (): string => this.qualifyNamespace(this.namespaces.core),
/** Test namespace for all test-related code, canonicalized to avoid conflicts ({root}.Test). */
test: (): string => this.registry.canonicalizeNamespace(`${this.namespaces.root}.Test`),
/** Test utilities namespace for helper methods and fixtures ({root}.Test.Utils). */
testUtils: (): string => `${this.namespaces.test}.Utils`,
/** Mock server test namespace for mock server testing infrastructure ({root}.Test.Unit.MockServer). */
mockServerTest: (): string => `${this.namespaces.test}.Unit.MockServer`,
/** Public Core namespace, same as root for publicly exposed core utilities. */
publicCore: (): string => this.namespaces.root,
/** WebSockets Core namespace for WebSocket APIs ({root}.Core.WebSockets). */
webSocketsCore: (): string => `${this.namespaces.core}.WebSockets`,
/** Public Core test namespace for testing public core functionality ({root}.Test.PublicCore). */
publicCoreTest: (): string => `${this.namespaces.root}.Test.PublicCore`,
/** Test utilities namespace that preserves original casing ({root}.Test.Utils). */
asIsTestUtils: (): string => `${this.namespaces.root}.Test.Utils`,
/** Namespace for public core classes; either root or core based on rootNamespaceForCoreClasses setting. */
publicCoreClasses: (): string =>
this.settings.rootNamespaceForCoreClasses ? this.namespaces.root : this.namespaces.core,
/** Implicit namespaces are namespaces that are assumed to be automatically imported into the generated code. */
implicit: (): Set<string> =>
new Set([
"System",
"System.Collections.Generic",
"System.IO",
"System.Linq",
"System.Threading",
"System.Threading.Tasks",
"System.Net.Http"
])
});
/**
* Lazily-initialized names for key generated classes and identifiers.
*
* Names are computed using naming conventions (camelCase, upperFirst) and can be
* overridden via custom configuration. All names are lazy-evaluated and cached.
*/
public readonly names = {
classes: lazy({
/** The name of the base API exception class (e.g., "AcmeWidgetsApiException"). */
baseApiException: (): string =>
this.settings.baseApiExceptionClassName || `${this.names.project.clientPrefix}ApiException`,
/** The name of the base exception class for all SDK exceptions (e.g., "AcmeWidgetsException"). */
baseException: (): string =>
this.settings.baseExceptionClassName || `${this.names.project.clientPrefix}Exception`,
/** The name of the main internal SDK client class (e.g., "AcmeWidgetsClient"). */
rootClient: (): string => this.settings.clientClassName || `${this.names.project.clientPrefix}Client`,
/** The name of the client class used in documentation snippets and examples. */
rootClientForSnippets: (): string => this.settings.exportedClientClassName || this.names.classes.rootClient,
/** The name for custom pagination classes (e.g., "AcmeWidgetsPager"), alphanumeric only. */
customPager: (): string =>
this.settings.customPagerName || `${this.names.project.packageId.replace(/[^a-zA-Z0-9]/g, "")}Pager`,
/** The name for the environment configuration class (e.g., "AcmeWidgetsEnvironment"). */
environment: (): string =>
this.settings.environmentClassName || `${this.names.project.clientPrefix}Environment`,
/** The name for the custom exception interceptor class (e.g., "AcmeWidgetsExceptionInterceptor"). */
exceptionInterceptor: (): string =>
this.settings.exceptionInterceptorClassName ||
`${this.names.project.packageId.replace(/[^a-zA-Z0-9]/g, "")}ExceptionInterceptor`
}),
project: lazy({
/** The computed client name derived from organization and workspace in camelCase (e.g., "AcmeWidgets"). */
client: () =>
upperFirst(camelCase(`${this.generatorConfig.organization}_${this.generatorConfig.workspaceName}`)),
/** The prefix used for client-related classes, customizable via config or defaults to clientName. */
clientPrefix: () =>
this.settings.exportedClientClassName || this.settings.clientClassName || this.names.project.client,
/** The NuGet package identifier for the generated SDK, defaults to root namespace if not specified. */
packageId: () => this.settings.packageId || this.namespaces.root
}),
files: lazy({
/* the name of the project */
project: () => this.namespaces.root,
/* the name of the test project */
testProject: () => `${this.namespaces.root}.Test`
}),
methods: lazy({
mockOauth: () => "MockOAuthEndpoint",
mockInferredAuth: () => "MockInferredAuthEndpoint",
getAccessTokenAsync: () => "GetAccessTokenAsync",
getAuthHeadersAsync: () => "GetAuthHeadersAsync"
}),
variables: lazy({
client: () => "client",
response: () => "response",
httpRequest: () => "httpRequest",
sendRequest: () => "sendRequest",
responseBody: () => "responseBody",
query: () => "_query",
headers: () => "_headers"
}),
parameters: lazy({
cancellationToken: () => "cancellationToken",
requestOptions: () => "options",
idempotentOptions: () => "options"
})
};
/**
* Lazily-initialized C# type references for core SDK classes and utilities.
*
* This object provides type references for all core infrastructure classes used in the
* generated SDK. These references are used throughout code generation to ensure consistent
* type usage and proper namespace imports.
*
* ## Categories of Types:
*
* ### Request/Response Handling:
* - `FormRequest`, `JsonRequest`: Request builders for different content types
* - `ClientOptions`, `RequestOptions`: Configuration objects for API calls
* - `RawClient`, `RawGrpcClient`: Low-level HTTP/gRPC clients
* - `Headers`: HTTP header management
*
* ### Client Infrastructure:
* - `RootClient`, `RootClientForSnippets`: Main SDK client classes
* - `TestClient`: Testing infrastructure
* - `WebSocketClient`: WebSocket client for managing connections
*
* ### Error Handling:
* - `BaseException`, `BaseApiException`: Exception hierarchy
* - `ExceptionInterceptor`, `ExceptionHandler`: Exception processing
*
* ### Serialization:
* - `EnumSerializer`, `StringEnumSerializer`: Enum serialization
* - `DateTimeSerializer`: DateTime handling
* - `JsonUtils`: JSON utilities
* - `OneOfSerializer`: Union type serialization
* - `CollectionItemSerializer`: Collection element serialization
* - `ProtoConverter`, `ProtoAnyMapper`: Protocol buffer conversion
*
* ### Pagination:
* - `Pager`: Base pagination interface
* - `CustomPagerClass`: Custom pagination implementation
* - `OffsetPager`: Offset-based pagination
* - `CursorPager`: Cursor-based pagination
* - `CustomPagerFactory`, `CustomPagerContext`: Pagination utilities
*
* ### Additional Properties:
* - `AdditionalProperties`: Mutable additional properties
* - `ReadOnlyAdditionalProperties`: Immutable additional properties
*
* ### Other Utilities:
* - `Version`: SDK version information
* - `ValueConvert`: Value conversion utilities
* - `FileParameter`: File upload support
* - `Constants`: SDK constants
* - `Environments`: Environment configuration
* - `Extensions`: Extension methods
* - `OAuthTokenProvider`: OAuth authentication
* - `QueryBuilder`: Query string building
* - `IStringEnum`, `StringEnum`: String-based enum support
*
* ## Usage Patterns:
*
* ### Non-Generic Types (cached):
* ```typescript
* const clientType = generation.Types.RootClient; // Returns cached ClassReference
* ```
*
* ### Generic Types (evaluated per call):
* ```typescript
* const pager = generation.Types.Pager(itemType); // Returns new ClassReference each time
* const webSocketClient = generation.Types.WebSocketClient();
* ```
*
* All type references include proper namespace information and are registered with
* the NameRegistry to ensure correct imports in generated code.
*/
public readonly Types = lazy({
Arbitrary: (name: string) => new Primitive.ArbitraryType(name, this),
HttpMethodExtensions: () =>
this.csharp.classReference({
namespace: this.namespaces.core,
origin: this.model.staticExplicit("HttpMethodExtensions")
}),
/** Core infrastructure type for building multipart/form-data requests */
FormRequest: () =>
this.csharp.classReference({
namespace: this.namespaces.core,
origin: this.model.staticExplicit("FormRequest")
}),
/** Optional<T> wrapper type for explicit undefined/null semantics */
Optional: () =>
this.csharp.classReference({
namespace: this.namespaces.core,
origin: this.model.staticExplicit("Optional")
}),
/** Configuration options for the SDK client (base URL, headers, timeout, etc.) */
ClientOptions: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("ClientOptions"),
namespace: this.namespaces.publicCoreClasses
}),
/** Low-level HTTP client wrapper for making raw API calls */
RawClient: () =>
this.csharp.classReference({
namespace: this.namespaces.core,
origin: this.model.staticExplicit("RawClient")
}),
/** Per-request configuration options (headers, timeout overrides, etc.) */
RequestOptions: () =>
this.csharp.classReference({
namespace: this.namespaces.publicCoreClasses,
origin: this.model.staticExplicit("RequestOptions")
}),
/** Interface for per-request configuration options */
RequestOptionsInterface: () =>
this.csharp.classReference({
namespace: this.namespaces.core,
origin: this.model.staticExplicit("IRequestOptions")
}),
/** Core infrastructure type for building JSON requests */
JsonRequest: () =>
this.csharp.classReference({
namespace: this.namespaces.core,
origin: this.model.staticExplicit("JsonRequest")
}),
/** SDK version metadata class */
Version: () =>
this.csharp.classReference({
namespace: this.namespaces.publicCore,
origin: this.model.staticExplicit("Version")
}),
/** Utility for converting values between different representations */
ValueConvert: () =>
this.csharp.classReference({
namespace: this.namespaces.core,
origin: this.model.staticExplicit("ValueConvert")
}),
/** Wrapper for file upload parameters in multipart requests */
FileParameter: () =>
this.csharp.classReference({
namespace: this.namespaces.publicCore,
origin: this.model.staticExplicit("FileParameter"),
multipartMethodName: "AddFileParameterPart",
multipartMethodNameForCollection: "AddFileParameterParts",
isReferenceType: true
}),
/** HTTP header management utilities */
Headers: () =>
this.csharp.classReference({
namespace: this.namespaces.core,
origin: this.model.staticExplicit("Headers")
}),
/** HTTP header value management utilities */
HeaderValue: () =>
this.csharp.classReference({
namespace: this.namespaces.core,
origin: this.model.staticExplicit("HeaderValue")
}),
/** The main SDK client class (for code generation) */
RootClient: () =>
this.csharp.classReference({
origin: this.model.staticExplicit(this.names.classes.rootClient),
namespace: this.namespaces.root
}),
/** The main SDK client class (for documentation snippets) */
RootClientForSnippets: () =>
this.csharp.classReference({
origin: this.model.staticExplicit(this.names.classes.rootClientForSnippets),
namespace: this.namespaces.root
}),
/** Base exception class for API errors (HTTP 4xx/5xx responses) */
BaseApiException: () =>
this.csharp.classReference({
origin: this.model.staticExplicit(this.names.classes.baseApiException),
namespace: this.namespaces.publicCoreClasses
}),
/** Base exception class for all SDK exceptions */
BaseException: () =>
this.csharp.classReference({
origin: this.model.staticExplicit(this.names.classes.baseException),
namespace: this.namespaces.publicCoreClasses
}),
/** Interface for intercepting and processing exceptions */
ExceptionInterceptor: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("IExceptionInterceptor"),
namespace: this.namespaces.core
}),
/** Utility for handling and transforming exceptions */
ExceptionHandler: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("ExceptionHandler"),
namespace: this.namespaces.core
}),
/** Custom exception interceptor class for SDK authors to implement */
CustomExceptionInterceptor: () =>
this.csharp.classReference({
origin: this.model.staticExplicit(this.names.classes.exceptionInterceptor),
namespace: this.namespaces.core
}),
/** Utility for mapping Protocol Buffer Any types */
ProtoAnyMapper: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("ProtoAnyMapper"),
namespace: this.namespaces.core
}),
/** SDK-wide constants */
Constants: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("Constants"),
namespace: this.namespaces.core
}),
/** JSON serializer for enum types */
EnumSerializer: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("EnumSerializer"),
namespace: this.namespaces.core
}),
/** JSON serializer for DateTime types */
DateTimeSerializer: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("DateTimeSerializer"),
namespace: this.namespaces.core
}),
/** Utility methods for JSON serialization/deserialization */
JsonUtils: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("JsonUtils"),
namespace: this.namespaces.core
}),
/** Test assertion helper for JSON comparison */
JsonAssert: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("JsonAssert"),
namespace: this.namespaces.testUtils
}),
/** Factory for creating custom pagination instances */
CustomPagerFactory: () =>
this.csharp.classReference({
origin: this.model.staticExplicit(`${this.names.classes.customPager}Factory`),
namespace: this.namespaces.core
}),
/** Context object for custom pagination state */
CustomPagerContext: () =>
this.csharp.classReference({
origin: this.model.staticExplicit(`${this.names.classes.customPager}Context`),
namespace: this.namespaces.core
}),
/** Environment configuration class (base URLs for different environments) */
Environments: () =>
this.csharp.classReference({
origin: this.model.staticExplicit(this.names.classes.environment),
namespace: this.namespaces.publicCoreClasses
}),
/** Test client for testing infrastructure */
TestClient: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("TestClient"),
namespace: this.namespaces.test
}),
/** Base class for mock server tests */
BaseMockServerTest: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("BaseMockServerTest"),
namespace: this.namespaces.mockServerTest
}),
/** Request options with idempotency key support */
IdempotentRequestOptions: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("IdempotentRequestOptions"),
namespace: this.namespaces.publicCoreClasses
}),
/** Interface for idempotent request options */
IdempotentRequestOptionsInterface: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("IIdempotentRequestOptions"),
namespace: this.namespaces.core
}),
/** Interface for string-based enum types */
IStringEnum: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("IStringEnum"),
namespace: this.namespaces.core
}),
/** WebSocket client for managing WebSocket connections */
WebSocketClient: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("WebSocketClient"),
namespace: this.namespaces.webSocketsCore
}),
/** Query string builder utility for WebSocket URLs (legacy) */
QueryBuilder: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("Query"),
namespace: this.namespaces.webSocketsCore
}),
/** High-performance query string builder with fluent API */
QueryStringBuilder: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("QueryStringBuilder"),
namespace: this.namespaces.core
}),
/** Fluent builder for constructing query strings */
QueryStringBuilderBuilder: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("QueryStringBuilder.Builder"),
namespace: this.namespaces.core
}),
/** OAuth token provider for authentication */
OAuthTokenProvider: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("OAuthTokenProvider"),
namespace: this.namespaces.core
}),
/** Inferred auth token provider for authentication */
InferredAuthTokenProvider: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("InferredAuthTokenProvider"),
namespace: this.namespaces.core
}),
/** Converter for Protocol Buffer types */
ProtoConverter: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("ProtoConverter"),
namespace: this.namespaces.core
}),
/** Low-level gRPC client wrapper */
RawGrpcClient: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("RawGrpcClient"),
namespace: this.namespaces.core
}),
/** Extension methods for common operations */
Extensions: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("Extensions"),
namespace: this.namespaces.core
}),
/** Request options for gRPC calls */
GrpcRequestOptions: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("GrpcRequestOptions"),
namespace: this.namespaces.root
}),
/** Configuration options for gRPC channels */
GrpcChannelOptions: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("GrpcChannelOptions"),
namespace: "Grpc.Net.Client"
}),
/**
* Generic string-based enum wrapper type.
* @param genericType - The specific enum type to wrap (optional)
*/
StringEnum: (genericType?: ast.Type | ast.ClassReference) =>
this.csharp.classReference({
origin: this.model.staticExplicit("StringEnum"),
namespace: this.namespaces.core,
generics: genericType ? [genericType] : undefined
}),
/**
* Generic event wrapper for WebSocket APIs.
* @param genericType - The event payload type
*/
WebSocketEvent: (genericType: ast.Type | ast.ClassReference): ast.ClassReference => {
return this.csharp.classReference({
origin: this.model.staticExplicit("Event"),
namespace: this.namespaces.webSocketsCore,
generics: [genericType]
});
},
/** Connection status enum for WebSocket connections */
ConnectionStatus: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("ConnectionStatus"),
namespace: this.namespaces.webSocketsCore
}),
/** Connected event for WebSocket connections */
WebSocketConnected: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("Connected"),
namespace: this.namespaces.webSocketsCore
}),
/** Closed event for WebSocket connections */
WebSocketClosed: () =>
this.csharp.classReference({
origin: this.model.staticExplicit("Closed"),
namespace: this.namespaces.webSocketsCore
}),
/**
* JSON serializer for string-based enum types.
* @param enumClassReference - The enum type to serialize
*/
StringEnumSerializer: (enumClassReference: ast.Type | ast.ClassReference): ast.ClassReference => {
return this.csharp.classReference({
origin: this.model.staticExplicit("StringEnumSerializer"),
namespace: this.namespaces.core,
generics: [enumClassReference]
});
},
/**
* Custom pagination class for iterating over paged results.
* @param itemType - The type of items in each page
*/
CustomPagerClass: (itemType: ast.Type | ast.ClassReference): ast.ClassReference => {
return this.csharp.classReference({
origin: this.model.staticExplicit(this.names.classes.customPager),
namespace: this.namespaces.core,
generics: [itemType]
});
},
/**
* Generic pager interface for pagination support.
* @param itemType - The type of items being paginated
*/
Pager: (itemType: ast.Type | ast.ClassReference): ast.ClassReference => {
return this.csharp.classReference({
origin: this.model.staticExplicit("Pager"),
namespace: this.namespaces.core,
generics: [itemType]
});
},
/**
* Offset-based pagination implementation.
* Supports paginating through results using numeric offsets.
*
* @param requestType - The type of the pagination request
* @param requestOptionsType - The type of request options
* @param responseType - The type of the pagination response
* @param offsetType - The type of the offset (usually int or long)
* @param stepType - The type of the step/page size (usually int)
* @param itemType - The type of items in the paginated results
*/
OffsetPager: ({
requestType,
requestOptionsType,
responseType,
offsetType,
stepType,
itemType
}: {
requestType: ast.Type;
requestOptionsType: ast.Type;
responseType: ast.Type;
offsetType: ast.Type;
stepType: ast.Type;
itemType: ast.Type;
}): ast.ClassReference => {
return this.csharp.classReference({
origin: this.model.staticExplicit("OffsetPager"),
namespace: this.namespaces.core,
generics: [requestType, requestOptionsType, responseType, offsetType, stepType, itemType]
});
},
/**
* Cursor-based pagination implementation.
* Supports paginating through results using opaque cursor tokens.
*
* @param requestType - The type of the pagination request
* @param requestOptionsType - The type of request options
* @param responseType - The type of the pagination response
* @param cursorType - The type of the cursor token (usually string)
* @param itemType - The type of items in the paginated results
*/
CursorPager: ({
requestType,
requestOptionsType,
responseType,
cursorType,
itemType
}: {
requestType: ast.Type;
requestOptionsType: ast.Type;
responseType: ast.Type;
cursorType: ast.Type;
itemType: ast.Type;
}): ast.ClassReference => {
return this.csharp.classReference({
origin: this.model.staticExplicit("CursorPager"),
namespace: this.namespaces.core,
generics: [requestType, requestOptionsType, responseType, cursorType, itemType]
});
},
/**
* Custom JSON serializer for collection items.
* Wraps items in a collection with a specific serializer implementation.
*
* @param itemType - The type of items in the collection
* @param serializer - The serializer class to use for each item
* @returns A ClassReference for CollectionItemSerializer<TItem, TSerializer>
*/
CollectionItemSerializer: (
itemType: ast.ClassReference,
serializer: ast.ClassReference
): ast.ClassReference => {
return this.csharp.classReference({
origin: this.model.staticExplicit("CollectionItemSerializer"),
namespace: this.namespaces.core,
generics: [itemType, serializer]
});
},
/**
* JSON serializer for union/OneOf types.
* Handles discriminated and undiscriminated union serialization.
*
* @param oneof - The union type to serialize
* @returns A ClassReference for OneOfSerializer<TOneOf>
*/
OneOfSerializer: (oneof: ast.Type | ast.ClassReference): ast.ClassReference => {
return this.csharp.classReference({
origin: this.model.staticExplicit("OneOfSerializer"),
namespace: this.namespaces.core,
generics: [oneof]
});
},
/**
* Mutable dictionary for additional/extra properties on objects.
* Allows setting arbitrary key-value pairs beyond defined properties.
*
* @param genericType - The value type for additional properties (defaults to object if not specified)
* @returns A ClassReference for AdditionalProperties or AdditionalProperties<T>
*/
AdditionalProperties: (genericType?: ast.Type | ast.ClassReference): ast.ClassReference => {
return this.csharp.classReference({
origin: this.model.staticExplicit("AdditionalProperties"),
namespace: this.namespaces.publicCore,
generics: genericType ? [genericType] : undefined
});
},
/**
* Immutable read-only dictionary for additional/extra properties on objects.
* Provides read-only access to arbitrary key-value pairs beyond defined properties.
*
* @param genericType - The value type for additional properties (defaults to object if not specified)
* @returns A ClassReference for ReadOnlyAdditionalProperties or ReadOnlyAdditionalProperties<T>
*/
ReadOnlyAdditionalProperties: (genericType?: ast.Type | ast.ClassReference): ast.ClassReference => {
return this.csharp.classReference({
origin: this.model.staticExplicit("ReadOnlyAdditionalProperties"),
namespace: this.namespaces.publicCore,
generics: genericType ? [genericType] : undefined
});
}
});
public Primitive = lazy({
/**
* Creates a string type.
*
* @returns A Type object representing the C# string type
*/
string: () => {
return new Primitive.String(this);
},
/**
* Creates a boolean type.
*
* @returns A Type object representing the C# bool type
*/
boolean: () => {
return new Primitive.Boolean(this);
},
/**
* Creates an integer type.
*
* @returns A Type object representing the C# int type
*/
integer: () => {
return new Primitive.Integer(this);
},
/**
* Creates a long type.
*
* @returns A Type object representing the C# long type
*/