@atomic-ehr/codegen 0.0.2-canary.20251119131907.723c8fd → 0.0.2-canary.20251119144634.930498f

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.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,4 @@
1
1
  import { CanonicalManager } from '@atomic-ehr/fhir-canonical-manager';
2
- import * as FS from '@atomic-ehr/fhirschema';
3
- import { FHIRSchema, StructureDefinition, FHIRSchemaElement } from '@atomic-ehr/fhirschema';
4
2
 
5
3
  /**
6
4
  * CodeGen Logger
@@ -84,16 +82,6 @@ type Name = string & {
84
82
  type CanonicalUrl = string & {
85
83
  readonly __brand: unique symbol;
86
84
  };
87
- interface PackageMeta {
88
- name: string;
89
- version: string;
90
- }
91
- type RichFHIRSchema = Omit<FS.FHIRSchema, "package_meta" | "base" | "name" | "url"> & {
92
- package_meta: PackageMeta;
93
- name: Name;
94
- url: CanonicalUrl;
95
- base: CanonicalUrl;
96
- };
97
85
  type IdentifierBase = {
98
86
  name: Name;
99
87
  url: CanonicalUrl;
@@ -256,93 +244,18 @@ interface BindingTypeSchema {
256
244
  dependencies?: Identifier[];
257
245
  }
258
246
  type Field = RegularField | ChoiceFieldDeclaration | ChoiceFieldInstance;
259
- type TypeschemaParserOptions = {
260
- format?: "auto" | "ndjson" | "json";
261
- validate?: boolean;
262
- strict?: boolean;
263
- };
264
- type ValueSet = {
265
- resourceType: "ValueSet";
266
- package_meta?: PackageMeta;
267
- id: string;
268
- name?: string;
269
- url?: string;
270
- description?: string;
271
- compose?: ValueSetCompose;
272
- expansion?: {
273
- contains: Concept[];
274
- };
275
- experimental?: boolean;
276
- immutable?: boolean;
277
- extension?: any[];
278
- status?: string;
279
- identifier?: any[];
280
- title?: string;
281
- publisher?: string;
282
- version?: string;
283
- meta?: any;
284
- date?: string;
285
- contact?: any;
286
- };
287
247
  type ValueSetCompose = {
288
248
  include: {
289
249
  concept?: Concept[];
290
250
  system?: string;
291
- filter?: {}[];
251
+ filter?: unknown[];
292
252
  }[];
293
253
  };
294
- type CodeSystem = {
295
- resourceType: "CodeSystem";
296
- url: CanonicalUrl;
297
- concept: CodeSystemConcept[];
298
- };
299
- type CodeSystemConcept = {
300
- concept: CodeSystemConcept[];
301
- code: string;
302
- display: string;
303
- };
304
- type RichValueSet = Omit<ValueSet, "name" | "url"> & {
305
- package_meta: PackageMeta;
306
- name: Name;
307
- url: CanonicalUrl;
308
- };
309
- interface TypeschemaGeneratorOptions {
310
- verbose?: boolean;
311
- logger?: CodegenLogger;
312
- treeshake?: string[];
313
- manager?: ReturnType<typeof CanonicalManager> | null;
314
- }
315
254
 
316
- type Register = {
317
- testAppendFs(fs: FHIRSchema): void;
318
- ensureSpecializationCanonicalUrl(name: string | Name | CanonicalUrl): CanonicalUrl;
319
- resolveSd(pkg: PackageMeta, canonicalUrl: CanonicalUrl): StructureDefinition | undefined;
320
- resolveFs(pkg: PackageMeta, canonicalUrl: CanonicalUrl): RichFHIRSchema | undefined;
321
- resolveFsGenealogy(pkg: PackageMeta, canonicalUrl: CanonicalUrl): RichFHIRSchema[];
322
- resolveFsSpecializations(pkg: PackageMeta, canonicalUrl: CanonicalUrl): RichFHIRSchema[];
323
- allFs(): RichFHIRSchema[];
324
- allVs(): RichValueSet[];
325
- resolveVs(_pkg: PackageMeta, canonicalUrl: CanonicalUrl): RichValueSet | undefined;
326
- resolveAny(canonicalUrl: CanonicalUrl): any | undefined;
327
- resolveElementSnapshot(fhirSchema: RichFHIRSchema, path: string[]): FHIRSchemaElement;
328
- getAllElementKeys(elems: Record<string, FHIRSchemaElement>): string[];
329
- resolver: PackageAwareResolver;
330
- } & ReturnType<typeof CanonicalManager>;
331
- type PkgId = string;
332
- type FocusedResource = StructureDefinition | ValueSet | CodeSystem;
333
- type CanonicalResolution<T> = {
334
- deep: number;
335
- pkg: PackageMeta;
336
- pkgId: PkgId;
337
- resource: T;
338
- };
339
- type PackageIndex = {
340
- pkg: PackageMeta;
341
- canonicalResolution: Record<CanonicalUrl, CanonicalResolution<FocusedResource>[]>;
342
- fhirSchemas: Record<CanonicalUrl, RichFHIRSchema>;
343
- valueSets: Record<CanonicalUrl, RichValueSet>;
255
+ type TypeSchemaShakeRule = {
256
+ ignoreFields?: string[];
344
257
  };
345
- type PackageAwareResolver = Record<PkgId, PackageIndex>;
258
+ type TreeShake = Record<string, Record<string, TypeSchemaShakeRule>>;
346
259
 
347
260
  /**
348
261
  * New Config Schema for High-Level API
@@ -563,228 +476,6 @@ declare function isConfig(obj: unknown): obj is Config;
563
476
  */
564
477
  declare function defineConfig(config: Config): Config;
565
478
 
566
- /**
567
- * TypeSchema Cache System
568
- *
569
- * Caching system for TypeSchema documents with both in-memory and persistent file-based storage.
570
- */
571
-
572
- /**
573
- * TypeSchema Cache with optional persistent storage
574
- */
575
- declare class TypeSchemaCache {
576
- private cache;
577
- private config;
578
- private cacheDir?;
579
- constructor(config?: TypeSchemaConfig);
580
- /**
581
- * Store a schema in the cache
582
- */
583
- set(schema: TypeSchema): Promise<void>;
584
- /**
585
- * Retrieve a schema by identifier
586
- */
587
- get(identifier: Identifier): TypeSchema | null;
588
- /**
589
- * Retrieve a schema by URL
590
- */
591
- getByUrl(url: string): TypeSchema | null;
592
- /**
593
- * Check if a schema exists in cache
594
- */
595
- has(identifier: Identifier): boolean;
596
- /**
597
- * Check if a schema exists by URL
598
- */
599
- hasByUrl(url: string): boolean;
600
- /**
601
- * Delete a schema from cache
602
- */
603
- delete(identifier: Identifier): boolean;
604
- /**
605
- * Delete a schema by URL
606
- */
607
- deleteByUrl(url: string): boolean;
608
- /**
609
- * Get schemas by package
610
- */
611
- getByPackage(packageName: string): TypeSchema[];
612
- /**
613
- * Get schemas by kind
614
- */
615
- getByKind(kind: string): TypeSchema[];
616
- /**
617
- * Store multiple schemas
618
- */
619
- setMany(schemas: TypeSchema[]): void;
620
- /**
621
- * Clear all cached schemas
622
- */
623
- clear(): void;
624
- /**
625
- * Generate cache key for identifier
626
- */
627
- private generateKey;
628
- /**
629
- * Initialize cache directory if persistence is enabled
630
- */
631
- initialize(): Promise<void>;
632
- /**
633
- * Load all cached schemas from disk
634
- */
635
- private loadFromDisk;
636
- /**
637
- * Persist a schema to disk
638
- */
639
- private persistSchema;
640
- /**
641
- * Clear cache directory
642
- */
643
- clearDisk(): Promise<void>;
644
- }
645
-
646
- /**
647
- * TypeSchema Generator
648
- *
649
- * Generates TypeSchema documents from FHIR packages using fhrischema.
650
- * Provides high-level API for converting FHIR Structure Definitions to TypeSchema format.
651
- */
652
-
653
- /**
654
- * TypeSchema Generator class
655
- *
656
- * Main class for generating TypeSchema documents from FHIR packages.
657
- * Leverages fhrischema for FHIR parsing and canonical manager for dependency resolution.
658
- */
659
- declare class TypeSchemaGenerator {
660
- private manager;
661
- private options;
662
- private cacheConfig?;
663
- private cache?;
664
- private logger?;
665
- constructor(options?: TypeschemaGeneratorOptions, cacheConfig?: TypeSchemaConfig);
666
- private initializeCache;
667
- registerFromPackageMetas(packageMetas: PackageMeta[]): Promise<Register>;
668
- generateFhirSchemas(structureDefinitions: StructureDefinition[]): FHIRSchema[];
669
- generateValueSetSchemas(valueSets: RichValueSet[], logger?: CodegenLogger): Promise<TypeSchema[]>;
670
- generateFromPackage(packageName: string, packageVersion: string | undefined, logger?: CodegenLogger): Promise<TypeSchema[]>;
671
- /**
672
- * Apply treeshaking to StructureDefinitions before FHIR schema transformation
673
- * This is more efficient and includes smart reference handling
674
- */
675
- private applyStructureDefinitionTreeshaking;
676
- private extractStructureDefinitionDependenciesWithReferences;
677
- private extractResourceNameFromUrl;
678
- }
679
-
680
- /**
681
- * TypeSchema Parser
682
- *
683
- * Parser for reading and manipulating TypeSchema documents from various formats.
684
- * Supports both NDJSON and JSON formats with automatic format detection.
685
- */
686
-
687
- /**
688
- * TypeSchema Parser class
689
- *
690
- * Provides functionality to read, parse, and manipulate TypeSchema documents
691
- * from files or strings in various formats.
692
- */
693
- declare class TypeSchemaParser {
694
- private options;
695
- constructor(options?: TypeschemaParserOptions);
696
- /**
697
- * Parse TypeSchema from file
698
- */
699
- parseFromFile(filePath: string): Promise<TypeSchema[]>;
700
- /**
701
- * Parse TypeSchema from string content
702
- */
703
- parseFromString(content: string, format?: "ndjson" | "json"): Promise<TypeSchema[]>;
704
- /**
705
- * Parse multiple TypeSchema files
706
- */
707
- parseFromFiles(filePaths: string[]): Promise<TypeSchema[]>;
708
- /**
709
- * Parse a single TypeSchema object
710
- */
711
- parseSchema(schemaData: any): TypeSchema;
712
- /**
713
- * Find schemas by identifier
714
- */
715
- findByIdentifier(schemas: TypeSchema[], identifier: Partial<Identifier>): TypeSchema[];
716
- /**
717
- * Find schema by URL
718
- */
719
- findByUrl(schemas: TypeSchema[], url: string): TypeSchema | undefined;
720
- /**
721
- * Find schemas by kind
722
- */
723
- findByKind(schemas: TypeSchema[], kind: Identifier["kind"]): TypeSchema[];
724
- /**
725
- * Find schemas by package
726
- */
727
- findByPackage(schemas: TypeSchema[], packageName: string): TypeSchema[];
728
- /**
729
- * Get all dependencies from a schema
730
- */
731
- /**
732
- * Resolve schema dependencies
733
- */
734
- /**
735
- * Detect format from content or filename
736
- */
737
- private detectFormat;
738
- /**
739
- * Parse NDJSON format
740
- */
741
- private parseNDJSON;
742
- /**
743
- * Parse JSON format
744
- */
745
- private parseJSON;
746
- /**
747
- * Validate schemas
748
- */
749
- private validateSchemas;
750
- /**
751
- * Validate identifier structure
752
- */
753
- private isValidIdentifier;
754
- /**
755
- * Check if identifier matches criteria
756
- */
757
- private matchesIdentifier;
758
- }
759
-
760
- type TypeSchemaShakeRule = {
761
- ignoreFields?: string[];
762
- };
763
- type TreeShake = Record<string, Record<string, TypeSchemaShakeRule>>;
764
- interface TypeRelation {
765
- parent: Identifier;
766
- child: Identifier;
767
- }
768
- type PackageName = string;
769
- type TypeSchemaIndex = {
770
- _schemaIndex: Record<CanonicalUrl, Record<PackageName, TypeSchema>>;
771
- _relations: TypeRelation[];
772
- collectComplexTypes: () => RegularTypeSchema[];
773
- collectResources: () => RegularTypeSchema[];
774
- collectLogicalModels: () => RegularTypeSchema[];
775
- collectProfiles: () => ProfileTypeSchema[];
776
- resolve: (id: Identifier) => TypeSchema | undefined;
777
- resolveByUrl: (pkgName: PackageName, url: CanonicalUrl) => TypeSchema | undefined;
778
- resourceChildren: (id: Identifier) => Identifier[];
779
- tryHierarchy: (schema: TypeSchema) => TypeSchema[] | undefined;
780
- hierarchy: (schema: TypeSchema) => TypeSchema[];
781
- findLastSpecialization: (schema: TypeSchema) => TypeSchema;
782
- findLastSpecializationByIdentifier: (id: Identifier) => Identifier;
783
- flatProfile: (schema: ProfileTypeSchema) => ProfileTypeSchema;
784
- isWithMetaField: (profile: ProfileTypeSchema) => boolean;
785
- exportTree: (filename: string) => Promise<void>;
786
- };
787
-
788
479
  type WriterOptions = {
789
480
  outputDir: string;
790
481
  tabSize: number;
@@ -830,7 +521,7 @@ interface APIBuilderOptions {
830
521
  /**
831
522
  * Progress callback for long-running operations
832
523
  */
833
- type ProgressCallback$1 = (phase: string, current: number, total: number, message?: string) => void;
524
+ type ProgressCallback = (phase: string, current: number, total: number, message?: string) => void;
834
525
  /**
835
526
  * Generation result information
836
527
  */
@@ -852,7 +543,6 @@ declare class APIBuilder {
852
543
  private schemas;
853
544
  private options;
854
545
  private generators;
855
- private cache?;
856
546
  private pendingOperations;
857
547
  private typeSchemaGenerator?;
858
548
  private logger;
@@ -864,25 +554,12 @@ declare class APIBuilder {
864
554
  fromPackageRef(packageRef: string): APIBuilder;
865
555
  fromFiles(...filePaths: string[]): APIBuilder;
866
556
  fromSchemas(schemas: TypeSchema[]): APIBuilder;
867
- typescriptDepricated(options?: {
868
- moduleFormat?: "esm" | "cjs";
869
- generateIndex?: boolean;
870
- includeDocuments?: boolean;
871
- namingConvention?: "PascalCase" | "camelCase";
872
- includeExtensions?: boolean;
873
- includeProfiles?: boolean;
874
- generateValueSets?: boolean;
875
- includeValueSetHelpers?: boolean;
876
- valueSetStrengths?: ("required" | "preferred" | "extensible" | "example")[];
877
- valueSetMode?: "all" | "required-only" | "custom";
878
- valueSetDirectory?: string;
879
- }): APIBuilder;
880
557
  typescript(userOpts: Partial<TypeScriptOptions>): this;
881
558
  csharp(namespace: string, staticSourceDir?: string | undefined): APIBuilder;
882
559
  /**
883
560
  * Set a progress callback for monitoring generation
884
561
  */
885
- onProgress(callback: ProgressCallback$1): APIBuilder;
562
+ onProgress(callback: ProgressCallback): APIBuilder;
886
563
  /**
887
564
  * Set the output directory for all generators
888
565
  */
@@ -918,1293 +595,11 @@ declare class APIBuilder {
918
595
  private loadFromFiles;
919
596
  private executeGenerators;
920
597
  }
921
- /**
922
- * Create an API builder instance from a configuration object
923
- */
924
- declare function createAPIFromConfig(config: Config): APIBuilder;
925
-
926
- /**
927
- * Core types and interfaces for the base generator system
928
- *
929
- * This module provides the foundational type definitions that all generators
930
- * build upon, ensuring consistency and type safety across the system.
931
- */
932
-
933
- /**
934
- * Base configuration options that all generators must support
935
- * These options provide the minimum required configuration for any generator
936
- */
937
- interface BaseGeneratorOptions {
938
- /** Output directory where generated files will be written */
939
- outputDir: string;
940
- /** Logger instance for tracking generation progress and errors */
941
- logger?: CodegenLogger;
942
- /** Whether to overwrite existing files (default: true) */
943
- overwrite?: boolean;
944
- /** Whether to validate schemas and generated content (default: true) */
945
- validate?: boolean;
946
- /** Enable detailed logging for debugging (default: false) */
947
- verbose?: boolean;
948
- /** Enable beginner-friendly error messages and guidance (default: false) */
949
- beginnerMode?: boolean;
950
- /** Format for error output: console, json, or structured (default: 'console') */
951
- errorFormat?: "console" | "json" | "structured";
952
- }
953
- /**
954
- * Language-specific type representation
955
- * This interface standardizes how FHIR types are mapped to target languages
956
- */
957
- interface LanguageType {
958
- /** The type string in the target language (e.g., "string", "number", "Patient") */
959
- name: string;
960
- /** Whether this is a primitive type that doesn't need imports */
961
- isPrimitive: boolean;
962
- /** Import path if this type needs to be imported from another module */
963
- importPath?: string;
964
- /** Generic parameters if this is a generic type (e.g., ["T", "K"] for Map<T,K>) */
965
- generics?: string[];
966
- /** Whether this type is nullable/optional in the target language */
967
- nullable?: boolean;
968
- /** Additional metadata specific to the target language */
969
- metadata?: Record<string, unknown>;
970
- }
971
- /**
972
- * Generated file metadata and content
973
- * Represents a single generated file with all its associated information
974
- */
975
- interface GeneratedFile {
976
- /** Full file system path where the file was/will be written */
977
- path: string;
978
- /** Filename only (without directory path) */
979
- filename: string;
980
- /** The generated content of the file */
981
- content: string;
982
- /** List of symbols exported from this file */
983
- exports: string[];
984
- /** File size in bytes */
985
- size: number;
986
- /** When this file was generated */
987
- timestamp: Date;
988
- /** Additional metadata about the generation process */
989
- metadata?: {
990
- /** Time taken to generate this file in milliseconds */
991
- generationTime?: number;
992
- /** Number of schemas processed for this file */
993
- schemaCount?: number;
994
- /** Template used to generate this file */
995
- templateName?: string;
996
- /** Any warnings generated during processing */
997
- warnings?: string[];
998
- };
999
- }
1000
- /**
1001
- * Template context provided to template engines
1002
- * Contains all the data needed to render templates for code generation
1003
- */
1004
- interface TemplateContext {
1005
- /** The schema being processed */
1006
- schema: TypeSchema;
1007
- /** Type mapper for the target language */
1008
- typeMapper: TypeMapper;
1009
- /** Current file being generated */
1010
- filename: string;
1011
- /** Target language name (e.g., "TypeScript", "Python") */
1012
- language: string;
1013
- /** Generation timestamp in ISO format */
1014
- timestamp: string;
1015
- /** Import map for the current file */
1016
- imports?: Map<string, string>;
1017
- /** Export set for the current file */
1018
- exports?: Set<string>;
1019
- /** Additional context data that templates can use */
1020
- [key: string]: unknown;
1021
- }
1022
- /**
1023
- * File builder context passed to lifecycle hooks
1024
- * Provides access to file generation state during the build process
1025
- */
1026
- interface FileContext {
1027
- /** Name of the file being generated */
1028
- filename: string;
1029
- /** Current file content */
1030
- content: string;
1031
- /** Map of imports (symbol name -> import path) */
1032
- imports: Map<string, string>;
1033
- /** Set of exported symbols */
1034
- exports: Set<string>;
1035
- /** Additional metadata about the file */
1036
- metadata: Record<string, unknown>;
1037
- /** The schema that generated this file (if applicable) */
1038
- schema?: TypeSchema;
1039
- /** Template name used to generate this file (if applicable) */
1040
- templateName?: string;
1041
- }
1042
- /**
1043
- * Statistics about file operations
1044
- * Used for performance monitoring and optimization
1045
- */
1046
- interface FileStats {
1047
- /** File size in bytes */
1048
- size: number;
1049
- /** Time taken to generate content in milliseconds */
1050
- generationTime: number;
1051
- /** Time taken to write to disk in milliseconds */
1052
- writeTime: number;
1053
- /** Memory used during generation in bytes */
1054
- memoryUsed?: number;
1055
- /** Number of template renders performed */
1056
- templateRenders?: number;
1057
- }
1058
- /**
1059
- * Progress callback signature for monitoring generation
1060
- * Allows consumers to track progress of long-running operations
1061
- */
1062
- type ProgressCallback = (
1063
- /** Current phase of generation */
1064
- phase: "validation" | "generation" | "writing" | "complete",
1065
- /** Current item number being processed */
1066
- current: number,
1067
- /** Total number of items to process */
1068
- total: number,
1069
- /** Optional message describing current operation */
1070
- message?: string,
1071
- /** Schema being processed (if applicable) */
1072
- schema?: TypeSchema) => void;
1073
- /**
1074
- * Lifecycle hook signatures for file operations
1075
- * These hooks allow customization of the file generation process
1076
- */
1077
- /** Hook called before saving a file - can modify content or abort save */
1078
- type BeforeSaveHook = (context: FileContext) => void | Promise<void>;
1079
- /** Hook called after successfully saving a file */
1080
- type AfterSaveHook = (filePath: string, stats: FileStats) => void | Promise<void>;
1081
- /** Hook called when an error occurs during file operations */
1082
- type ErrorHook = (error: Error, context: FileContext) => void | Promise<void>;
1083
- /**
1084
- * File builder configuration options
1085
- * Controls how files are generated and processed
1086
- */
1087
- interface FileBuilderOptions {
1088
- /** Template name to use for content generation */
1089
- template?: string;
1090
- /** Strategy for resolving import paths */
1091
- importStrategy?: "auto" | "manual" | "none";
1092
- /** Level of content validation to perform */
1093
- validation?: "strict" | "loose" | "none";
1094
- /** Enable pretty printing of generated content */
1095
- prettify?: boolean;
1096
- /** Custom formatting options */
1097
- formatting?: {
1098
- /** Number of spaces for indentation (default: 2) */
1099
- indentSize?: number;
1100
- /** Use tabs instead of spaces (default: false) */
1101
- useTabs?: boolean;
1102
- /** Maximum line length before wrapping (default: 100) */
1103
- maxLineLength?: number;
1104
- };
1105
- /** File encoding (default: 'utf-8') */
1106
- encoding?: BufferEncoding;
1107
- }
1108
- /**
1109
- * Abstract base class for type mapping between FHIR and target languages
1110
- * Each language-specific generator must implement this interface
1111
- */
1112
- declare abstract class TypeMapper {
1113
- /**
1114
- * Map a FHIR primitive type to the target language
1115
- * @param fhirType - FHIR primitive type name (e.g., "string", "integer")
1116
- * @returns Language-specific type representation
1117
- */
1118
- abstract mapPrimitive(fhirType: string): LanguageType;
1119
- /**
1120
- * Map a FHIR reference to the target language
1121
- * @param targets - Array of possible reference targets
1122
- * @returns Language-specific reference type
1123
- */
1124
- abstract mapReference(targets: Identifier[]): LanguageType;
1125
- /**
1126
- * Map an array type in the target language
1127
- * @param elementType - The element type name
1128
- * @returns Language-specific array type
1129
- */
1130
- abstract mapArray(elementType: string): LanguageType;
1131
- /**
1132
- * Map optional/nullable types
1133
- * @param type - The base type
1134
- * @param required - Whether the field is required
1135
- * @returns Language-specific optional type
1136
- */
1137
- abstract mapOptional(type: string, required: boolean): LanguageType;
1138
- /**
1139
- * Map enumerated values to the target language
1140
- * @param values - Array of possible values
1141
- * @param name - Optional name for the enum type
1142
- * @returns Language-specific enum type
1143
- */
1144
- abstract mapEnum(values: string[], name?: string): LanguageType;
1145
- /**
1146
- * Format a FHIR type name according to target language conventions
1147
- * @param name - FHIR type name
1148
- * @returns Formatted type name
1149
- */
1150
- abstract formatTypeName(name: string): string;
1151
- /**
1152
- * Format a field name according to target language conventions
1153
- * @param name - FHIR field name
1154
- * @returns Formatted field name
1155
- */
1156
- abstract formatFieldName(name: string): string;
1157
- /**
1158
- * Format a filename according to target language conventions
1159
- * @param name - Base filename
1160
- * @returns Formatted filename (without extension)
1161
- */
1162
- abstract formatFileName(name: string): string;
1163
- /**
1164
- * Map a complete TypeSchema identifier to target language type
1165
- * @param identifier - FHIR type identifier
1166
- * @returns Language-specific type representation
1167
- */
1168
- abstract mapType(identifier: Identifier): LanguageType;
1169
- /**
1170
- * Get import statement format for the target language
1171
- * @param symbols - Symbols to import
1172
- * @param from - Module to import from
1173
- * @returns Formatted import statement
1174
- */
1175
- formatImport?(symbols: string[], from: string): string;
1176
- /**
1177
- * Get export statement format for the target language
1178
- * @param symbols - Symbols to export
1179
- * @returns Formatted export statement
1180
- */
1181
- formatExport?(symbols: string[]): string;
1182
- }
1183
- /**
1184
- * Template engine interface
1185
- * Abstraction for different template engines (Handlebars, etc.)
1186
- */
1187
- interface TemplateEngine {
1188
- /**
1189
- * Render a template with the given context
1190
- * @param templateName - Name of the template to render
1191
- * @param context - Data to pass to the template
1192
- * @returns Rendered content
1193
- */
1194
- render(templateName: string, context: Record<string, unknown>): string;
1195
- /**
1196
- * Register a template
1197
- * @param name - Template name
1198
- * @param template - Template content or compiled template
1199
- */
1200
- registerTemplate(name: string, template: string | ((...args: any[]) => any)): void;
1201
- /**
1202
- * Register a helper function
1203
- * @param name - Helper name
1204
- * @param helper - Helper function
1205
- */
1206
- registerHelper(name: string, helper: (...args: any[]) => any): void;
1207
- /**
1208
- * Check if a template exists
1209
- * @param name - Template name
1210
- * @returns True if template exists
1211
- */
1212
- hasTemplate(name: string): boolean;
1213
- /**
1214
- * Get list of available templates
1215
- * @returns Array of template names
1216
- */
1217
- getAvailableTemplates(): string[];
1218
- }
1219
- /**
1220
- * Generator capabilities interface
1221
- * Describes what a generator can do - used for introspection
1222
- */
1223
- interface GeneratorCapabilities {
1224
- /** Programming language this generator targets */
1225
- language: string;
1226
- /** File extensions this generator produces */
1227
- fileExtensions: string[];
1228
- /** Whether this generator supports templates */
1229
- supportsTemplates: boolean;
1230
- /** Whether this generator supports custom type mapping */
1231
- supportsCustomTypeMapping: boolean;
1232
- /** Whether this generator supports incremental generation */
1233
- supportsIncrementalGeneration: boolean;
1234
- /** Whether this generator supports validation */
1235
- supportsValidation: boolean;
1236
- /** Supported schema kinds */
1237
- supportedSchemaKinds: Array<"resource" | "complex-type" | "profile" | "primitive-type" | "logical">;
1238
- /** Version of the generator */
1239
- version: string;
1240
- /** Additional metadata about capabilities */
1241
- metadata?: Record<string, unknown>;
1242
- }
1243
-
1244
- /**
1245
- * Core file management system with batching and performance optimizations
1246
- *
1247
- * This replaces scattered writeFile calls with a comprehensive file management
1248
- * system that provides better error handling, performance, and maintainability.
1249
- */
1250
598
 
1251
- interface FileManagerOptions {
599
+ type CSharpGeneratorOptions = WriterOptions & {
1252
600
  outputDir: string;
1253
- logger: CodegenLogger;
1254
- overwrite?: boolean;
1255
- batchSize?: number;
1256
- }
1257
- interface WriteFileResult {
1258
- path: string;
1259
- size: number;
1260
- writeTime: number;
1261
- }
1262
- /**
1263
- * High-performance file manager with batching and error recovery
1264
- *
1265
- * Features:
1266
- * - Automatic directory creation
1267
- * - Batch operations for better performance
1268
- * - Comprehensive error handling with recovery suggestions
1269
- * - Import path resolution
1270
- * - File existence checks
1271
- */
1272
- declare class FileManager {
1273
- private readonly options;
1274
- private readonly logger;
1275
- constructor(options: FileManagerOptions);
1276
- /**
1277
- * Write a file with automatic directory creation
1278
- * @param relativePath Path relative to output directory
1279
- * @param content File content
1280
- * @param options Write options
1281
- */
1282
- writeFile(relativePath: string, content: string, options?: {
1283
- encoding?: BufferEncoding;
1284
- overwrite?: boolean;
1285
- }): Promise<WriteFileResult>;
1286
- /**
1287
- * Write multiple files in batch for better performance
1288
- * @param files Map of relative path to content
1289
- */
1290
- writeBatch(files: Map<string, string>): Promise<WriteFileResult[]>;
1291
- /**
1292
- * Ensure directory exists, creating parent directories as needed
1293
- * @param dirPath Full directory path
1294
- */
1295
- ensureDirectory(dirPath: string): Promise<void>;
1296
- /**
1297
- * Clean directory by removing all contents
1298
- * @param relativePath Path relative to output directory
1299
- */
1300
- cleanDirectory(relativePath?: string): Promise<void>;
1301
- /**
1302
- * Get relative import path between two files
1303
- * @param fromFile Source file path
1304
- * @param toFile Target file path
1305
- */
1306
- getRelativeImportPath(fromFile: string, toFile: string): string;
1307
- /**
1308
- * Check if a file would be overwritten
1309
- * @param relativePath Path relative to output directory
1310
- */
1311
- wouldOverwrite(relativePath: string): Promise<boolean>;
1312
- /**
1313
- * Get file statistics
1314
- * @param relativePath Path relative to output directory
1315
- */
1316
- getFileStats(relativePath: string): Promise<FileStats | null>;
1317
- /**
1318
- * Get output directory
1319
- */
1320
- getOutputDirectory(): string;
1321
- /**
1322
- * Set batch size for operations
1323
- * @param size Batch size
1324
- */
1325
- setBatchSize(size: number): void;
1326
- /**
1327
- * Get current batch size
1328
- */
1329
- getBatchSize(): number;
1330
- }
1331
-
1332
- /**
1333
- * Index file builder for automated exports
1334
- *
1335
- * Automatically generates index files that export all types and functions
1336
- * from a directory, with support for grouping and namespaces.
1337
- */
1338
-
1339
- interface IndexBuilderConfig {
1340
- directory: string;
1341
- fileManager: FileManager;
1342
- templateEngine?: TemplateEngine;
1343
- logger: CodegenLogger;
1344
- }
1345
- /**
1346
- * Builder for index files with intelligent export management
1347
- *
1348
- * Features:
1349
- * - Automatic export detection
1350
- * - Namespace support
1351
- * - Export grouping
1352
- * - Custom headers
1353
- * - Template support
1354
- */
1355
- declare class IndexBuilder {
1356
- private readonly config;
1357
- private readonly exports;
1358
- private readonly namespaces;
1359
- private readonly reExports;
1360
- private header;
1361
- private footer;
1362
- private groupingFunction?;
1363
- private sortFunction?;
1364
- constructor(config: IndexBuilderConfig);
1365
- /**
1366
- * Add exports from a specific file
1367
- * @param exportNames Export names
1368
- * @param fromPath Path to file (without extension)
1369
- */
1370
- withExports(exportNames: string[], fromPath: string): IndexBuilder;
1371
- /**
1372
- * Add a single export
1373
- * @param exportName Export name
1374
- * @param fromPath Path to file
1375
- */
1376
- withExport(exportName: string, fromPath: string): IndexBuilder;
1377
- /**
1378
- * Add namespace exports
1379
- * @param namespaces Map of namespace to path
1380
- */
1381
- withNamespaces(namespaces: Record<string, string>): IndexBuilder;
1382
- /**
1383
- * Add namespace export
1384
- * @param namespace Namespace name
1385
- * @param path Path to export as namespace
1386
- */
1387
- withNamespace(namespace: string, path: string): IndexBuilder;
1388
- /**
1389
- * Re-export all from paths
1390
- * @param paths Paths to re-export all from
1391
- */
1392
- withReExports(paths: string[]): IndexBuilder;
1393
- /**
1394
- * Add re-export
1395
- * @param path Path to re-export all from
1396
- */
1397
- withReExport(path: string): IndexBuilder;
1398
- /**
1399
- * Set header content
1400
- * @param header Header content
1401
- */
1402
- withHeader(header: string): IndexBuilder;
1403
- /**
1404
- * Set footer content
1405
- * @param footer Footer content
1406
- */
1407
- withFooter(footer: string): IndexBuilder;
1408
- /**
1409
- * Group exports by function
1410
- * @param fn Function that returns group name for export
1411
- */
1412
- groupBy(fn: (exportName: string) => string): IndexBuilder;
1413
- /**
1414
- * Sort exports by function
1415
- * @param fn Sort function for [exportName, fromPath] tuples
1416
- */
1417
- sortBy(fn: (a: [string, string], b: [string, string]) => number): IndexBuilder;
1418
- /**
1419
- * Auto-discover exports from directory
1420
- * @param filePattern Pattern to match files (e.g., "*.ts")
1421
- */
1422
- autoDiscover(_filePattern?: string): Promise<IndexBuilder>;
1423
- /**
1424
- * Save the index file
1425
- */
1426
- save(): Promise<string>;
1427
- /**
1428
- * Build content without saving (for preview)
1429
- */
1430
- build(): string;
1431
- /**
1432
- * Generate the index file content
1433
- */
1434
- private generateContent;
1435
- /**
1436
- * Generate simple exports without grouping
1437
- */
1438
- private generateSimpleExports;
1439
- /**
1440
- * Generate grouped exports
1441
- */
1442
- private generateGroupedExports;
1443
- /**
1444
- * Get current exports (for testing/debugging)
1445
- */
1446
- getExports(): Map<string, string>;
1447
- /**
1448
- * Get current namespaces (for testing/debugging)
1449
- */
1450
- getNamespaces(): Map<string, string>;
1451
- /**
1452
- * Get current re-exports (for testing/debugging)
1453
- */
1454
- getReExports(): Map<string, string>;
1455
- }
1456
-
1457
- /**
1458
- * Fluent file builder with lifecycle hooks and validation
1459
- *
1460
- * This provides a clean, chainable API for building files with imports,
1461
- * exports, content generation, and lifecycle hooks for customization.
1462
- */
1463
-
1464
- interface FileBuilderConfig {
1465
- filename: string;
1466
- fileManager: FileManager;
1467
- templateEngine?: TemplateEngine;
1468
- typeMapper: TypeMapper;
1469
- logger: CodegenLogger;
1470
- }
1471
- /**
1472
- * Fluent builder for creating files with lifecycle hooks
1473
- *
1474
- * Features:
1475
- * - Fluent API for content building
1476
- * - Template integration
1477
- * - Import/export management
1478
- * - Lifecycle hooks (before/after save, error handling)
1479
- * - Content validation
1480
- * - Automatic import path resolution
1481
- */
1482
- declare class FileBuilder {
1483
- private readonly config;
1484
- private content;
1485
- private readonly imports;
1486
- private readonly exports;
1487
- private readonly metadata;
1488
- private beforeSaveHooks;
1489
- private afterSaveHooks;
1490
- private errorHooks;
1491
- private options;
1492
- constructor(config: FileBuilderConfig);
1493
- /**
1494
- * Set content directly
1495
- * @param content File content
1496
- */
1497
- withContent(content: string | (() => string)): FileBuilder;
1498
- /**
1499
- * Generate content from template
1500
- * @param templateName Template to use
1501
- * @param context Template context
1502
- */
1503
- withTemplate(templateName: string, context: Record<string, unknown>): FileBuilder;
1504
- /**
1505
- * Append content to existing content
1506
- * @param content Content to append
1507
- */
1508
- appendContent(content: string): FileBuilder;
1509
- /**
1510
- * Prepend content to existing content
1511
- * @param content Content to prepend
1512
- */
1513
- prependContent(content: string): FileBuilder;
1514
- /**
1515
- * Set all imports at once
1516
- * @param imports Map of symbol name to import path
1517
- */
1518
- withImports(imports: Map<string, string>): FileBuilder;
1519
- /**
1520
- * Add a single import
1521
- * @param symbol Symbol to import
1522
- * @param from Import path
1523
- */
1524
- addImport(symbol: string, from: string): FileBuilder;
1525
- /**
1526
- * Add multiple imports from the same path
1527
- * @param symbols Symbols to import
1528
- * @param from Import path
1529
- */
1530
- addImports(symbols: string[], from: string): FileBuilder;
1531
- /**
1532
- * Set all exports at once
1533
- * @param exports Array of export names
1534
- */
1535
- withExports(exports: string[]): FileBuilder;
1536
- /**
1537
- * Add a single export
1538
- * @param name Export name
1539
- */
1540
- addExport(name: string): FileBuilder;
1541
- /**
1542
- * Add multiple exports
1543
- * @param names Export names
1544
- */
1545
- addExports(names: string[]): FileBuilder;
1546
- /**
1547
- * Set metadata for the file
1548
- * @param key Metadata key
1549
- * @param value Metadata value
1550
- */
1551
- withMetadata(key: string, value: unknown): FileBuilder;
1552
- /**
1553
- * Set file builder options
1554
- * @param options Options to set
1555
- */
1556
- withOptions(options: Partial<FileBuilderOptions>): FileBuilder;
1557
- /**
1558
- * Add hook to run before saving
1559
- * @param hook Hook function
1560
- */
1561
- onBeforeSave(hook: BeforeSaveHook): FileBuilder;
1562
- /**
1563
- * Add hook to run after successful save
1564
- * @param hook Hook function
1565
- */
1566
- onAfterSave(hook: AfterSaveHook): FileBuilder;
1567
- /**
1568
- * Add hook to run when error occurs
1569
- * @param hook Hook function
1570
- */
1571
- onError(hook: ErrorHook): FileBuilder;
1572
- /**
1573
- * Build final content without saving
1574
- * @returns File context with final content
1575
- */
1576
- build(): FileContext;
1577
- /**
1578
- * Save the file
1579
- * @returns Promise resolving to file path
1580
- */
1581
- save(): Promise<string>;
1582
- /**
1583
- * Build final content with imports and exports
1584
- */
1585
- private buildFinalContent;
1586
- /**
1587
- * Generate import statements
1588
- */
1589
- private generateImportStatements;
1590
- /**
1591
- * Generate export statements
1592
- */
1593
- private generateExportStatements;
1594
- /**
1595
- * Prettify content (basic implementation)
1596
- */
1597
- private prettifyContent;
1598
- /**
1599
- * Validate generated content
1600
- */
1601
- private validateContent;
1602
- /**
1603
- * Get current content (for testing/debugging)
1604
- */
1605
- getContent(): string;
1606
- /**
1607
- * Get current imports (for testing/debugging)
1608
- */
1609
- getImports(): Map<string, string>;
1610
- /**
1611
- * Get current exports (for testing/debugging)
1612
- */
1613
- getExports(): Set<string>;
1614
- }
1615
-
1616
- /**
1617
- * Directory builder for batch file operations
1618
- *
1619
- * Provides a fluent API for managing entire directories of files,
1620
- * including subdirectories, index files, and batch operations.
1621
- */
1622
-
1623
- interface DirectoryBuilderConfig {
1624
- path: string;
1625
- fileManager: FileManager;
1626
- logger: CodegenLogger;
1627
- }
1628
- /**
1629
- * Fluent builder for directory operations
1630
- *
1631
- * Features:
1632
- * - Subdirectory management
1633
- * - Batch file operations
1634
- * - Index file generation
1635
- * - Directory cleaning
1636
- * - File listing for preview
1637
- */
1638
- declare class DirectoryBuilder {
1639
- private readonly config;
1640
- private readonly files;
1641
- private readonly subdirectories;
1642
- private indexBuilder?;
1643
- private shouldClean;
1644
- constructor(config: DirectoryBuilderConfig);
1645
- /**
1646
- * Add a subdirectory
1647
- * @param name Subdirectory name
1648
- */
1649
- withSubdirectory(name: string): DirectoryBuilder;
1650
- /**
1651
- * Add files to this directory
1652
- * @param files Map of filename to FileBuilder
1653
- */
1654
- withFiles(files: Record<string, FileBuilder>): DirectoryBuilder;
1655
- /**
1656
- * Add a single file
1657
- * @param filename File name
1658
- * @param builder File builder
1659
- */
1660
- withFile(filename: string, builder: FileBuilder): DirectoryBuilder;
1661
- /**
1662
- * Set index builder for this directory
1663
- * @param builder Index builder
1664
- */
1665
- withIndex(builder: IndexBuilder): DirectoryBuilder;
1666
- /**
1667
- * Clean directory before creating files
1668
- */
1669
- clean(): DirectoryBuilder;
1670
- /**
1671
- * Ensure directory exists
1672
- */
1673
- ensure(): Promise<DirectoryBuilder>;
1674
- /**
1675
- * Save all files in this directory
1676
- */
1677
- save(): Promise<string[]>;
1678
- /**
1679
- * Get all files that would be generated (for preview)
1680
- */
1681
- getFileList(): string[];
1682
- /**
1683
- * Get statistics about this directory
1684
- */
1685
- getStats(): {
1686
- fileCount: number;
1687
- subdirectoryCount: number;
1688
- hasIndex: boolean;
1689
- totalFiles: number;
1690
- };
1691
- /**
1692
- * Check if directory would overwrite existing files
1693
- */
1694
- wouldOverwrite(): Promise<string[]>;
1695
- /**
1696
- * Get the path of this directory
1697
- */
1698
- getPath(): string;
1699
- /**
1700
- * Get all file builders (for testing/debugging)
1701
- */
1702
- getFiles(): Map<string, FileBuilder>;
1703
- /**
1704
- * Get all subdirectories (for testing/debugging)
1705
- */
1706
- getSubdirectories(): Map<string, DirectoryBuilder>;
1707
- /**
1708
- * Get index builder (for testing/debugging)
1709
- */
1710
- getIndexBuilder(): IndexBuilder | undefined;
1711
- }
1712
-
1713
- /**
1714
- * Centralized error handling and reporting system
1715
- *
1716
- * This module provides a comprehensive error handling solution that:
1717
- * - Handles both generator-specific and unknown errors gracefully
1718
- * - Provides rich, context-aware error reporting
1719
- * - Supports multiple output formats (console, JSON, structured)
1720
- * - Includes batch error handling for multiple failures
1721
- * - Offers smart error recovery suggestions
1722
- */
1723
-
1724
- interface ErrorHandlerOptions {
1725
- logger: CodegenLogger;
1726
- verbose?: boolean;
1727
- beginnerMode?: boolean;
1728
- outputFormat?: "this.options.logger" | "json" | "structured";
1729
- }
1730
- /**
1731
- * Centralized error handler with smart reporting
1732
- */
1733
- declare class ErrorHandler {
1734
- private options;
1735
- constructor(options: ErrorHandlerOptions);
1736
- /**
1737
- * Handle a single error with appropriate reporting
1738
- */
1739
- handleError(error: Error, context?: {
1740
- schema?: TypeSchema;
1741
- filename?: string;
1742
- }): void;
1743
- /**
1744
- * Handle multiple errors in batch
1745
- */
1746
- handleBatchErrors(errors: Error[]): void;
1747
- /**
1748
- * Handle generator-specific errors with rich context
1749
- */
1750
- private handleGeneratorError;
1751
- /**
1752
- * Handle unknown errors gracefully
1753
- */
1754
- private handleUnknownError;
1755
- /**
1756
- * Report error to console with formatting
1757
- */
1758
- private reportErrorToConsole;
1759
- /**
1760
- * Report error as JSON for programmatic consumption
1761
- */
1762
- private reportErrorAsJson;
1763
- /**
1764
- * Report error in structured format
1765
- */
1766
- private reportErrorStructured;
1767
- /**
1768
- * Report multiple errors efficiently
1769
- */
1770
- private reportBatchErrors;
1771
- /**
1772
- * Get common suggestions across similar errors
1773
- */
1774
- private getCommonSuggestions;
1775
- /**
1776
- * Get recovery actions for an error
1777
- */
1778
- private getRecoveryActions;
1779
- }
1780
- /**
1781
- * Error boundary for catching and handling all generator errors
1782
- */
1783
- declare class GeneratorErrorBoundary {
1784
- private errorHandler;
1785
- constructor(errorHandler: ErrorHandler);
1786
- /**
1787
- * Wrap an async operation with error boundary
1788
- */
1789
- withErrorBoundary<T>(operation: () => Promise<T>, context?: {
1790
- schema?: TypeSchema;
1791
- filename?: string;
1792
- operationName?: string;
1793
- }): Promise<T>;
1794
- /**
1795
- * Wrap a batch operation with error boundary
1796
- */
1797
- withBatchErrorBoundary<T>(operations: Array<() => Promise<T>>, _context?: {
1798
- operationName?: string;
1799
- }): Promise<T[]>;
1800
- }
1801
-
1802
- type GeneratorInput = {
1803
- schemas: TypeSchema[];
1804
- index: TypeSchemaIndex;
601
+ staticSourceDir?: string;
602
+ targetNamespace: string;
1805
603
  };
1806
- /**
1807
- * Abstract base generator class with comprehensive functionality
1808
- *
1809
- * Provides common functionality for all generators including:
1810
- * - Schema validation and processing
1811
- * - File management with fluent API
1812
- * - Template processing
1813
- * - Error handling and recovery
1814
- * - Progress monitoring
1815
- * - Performance optimization
1816
- */
1817
- declare abstract class BaseGenerator<TOptions extends BaseGeneratorOptions = BaseGeneratorOptions, TResult extends GeneratedFile[] = GeneratedFile[]> {
1818
- /** Validated and merged options */
1819
- protected options: Required<TOptions>;
1820
- /** Logger instance for this generator */
1821
- protected readonly logger: CodegenLogger;
1822
- /** File manager for all file operations */
1823
- protected readonly fileManager: FileManager;
1824
- /** Template engine for content generation (optional) */
1825
- protected readonly templateEngine?: TemplateEngine;
1826
- /** Language-specific type mapper */
1827
- protected readonly typeMapper: TypeMapper;
1828
- /** Enhanced error handler for comprehensive error reporting */
1829
- protected readonly errorHandler: ErrorHandler;
1830
- /** Error boundary for catching and handling all generator errors */
1831
- protected readonly errorBoundary: GeneratorErrorBoundary;
1832
- /** Progress callback if provided */
1833
- private progressCallback?;
1834
- /** Generated files tracking */
1835
- private generatedFiles;
1836
- /** Generation start time for performance metrics */
1837
- private generationStartTime;
1838
- /** Cache for expensive operations */
1839
- private readonly cache;
1840
- constructor(options: TOptions);
1841
- /**
1842
- * Get the name of the target language (e.g., "TypeScript", "Python", "Rust")
1843
- */
1844
- protected abstract getLanguageName(): string;
1845
- /**
1846
- * Get the file extension for the target language (e.g., ".ts", ".py", ".rs")
1847
- */
1848
- protected abstract getFileExtension(): string;
1849
- /**
1850
- * Create a language-specific type mapper
1851
- */
1852
- protected abstract createTypeMapper(): TypeMapper;
1853
- /**
1854
- * Generate content for a single schema
1855
- * @param schema - The TypeSchema to generate code for
1856
- * @param context - Additional context for generation
1857
- */
1858
- protected abstract generateSchemaContent(schema: TypeSchema, context: TemplateContext): Promise<string>;
1859
- /**
1860
- * Validate generated content before writing
1861
- * @param content - The generated content
1862
- * @param context - The generation context
1863
- */
1864
- protected abstract validateContent(content: string, context: TemplateContext): Promise<void>;
1865
- /**
1866
- * Filter and sort schemas with language-specific logic
1867
- * @param schemas - Input schemas
1868
- */
1869
- protected abstract filterAndSortSchemas(schemas: TypeSchema[]): TypeSchema[];
1870
- /**
1871
- * Get generator capabilities - can be overridden for introspection
1872
- */
1873
- getCapabilities(): GeneratorCapabilities;
1874
- /**
1875
- * Create file manager instance - can be overridden for custom file handling
1876
- */
1877
- protected createFileManager(): FileManager;
1878
- /**
1879
- * Create template engine instance - can be overridden for custom templates
1880
- * Returns undefined if template engine is not needed
1881
- */
1882
- protected createTemplateEngine(): TemplateEngine | undefined;
1883
- /**
1884
- * Generate code from TypeSchema documents
1885
- * This is the main method that orchestrates the entire generation process
1886
- * @param schemas - Array of TypeSchema documents
1887
- */
1888
- generate({ schemas }: GeneratorInput): Promise<TResult>;
1889
- /**
1890
- * Generate and return content without writing files (useful for testing)
1891
- * @param schemas - Array of TypeSchema documents
1892
- */
1893
- build(schemas: TypeSchema[]): Promise<TResult>;
1894
- /**
1895
- * Create a file builder for fluent file generation
1896
- * @param filename - Name of the file to create
1897
- */
1898
- file(filename: string): FileBuilder;
1899
- /**
1900
- * Create a directory builder for batch operations
1901
- * @param path - Directory path relative to output directory
1902
- */
1903
- directory(path: string): DirectoryBuilder;
1904
- /**
1905
- * Create an index file builder
1906
- * @param directory - Directory to create index for
1907
- */
1908
- index(directory?: string): IndexBuilder;
1909
- /**
1910
- * Set progress callback for monitoring generation
1911
- * @param callback - Progress callback function
1912
- */
1913
- onProgress(callback: ProgressCallback): this;
1914
- /**
1915
- * Validate generator configuration
1916
- */
1917
- private validateConfiguration;
1918
- /**
1919
- * Merge options with defaults
1920
- */
1921
- private mergeWithDefaults;
1922
- /**
1923
- * Validate schemas before processing
1924
- */
1925
- private validateSchemas;
1926
- /**
1927
- * Validate individual schema
1928
- */
1929
- protected validateSchema(schema: TypeSchema): Promise<void>;
1930
- /**
1931
- * Detect circular references in schema dependencies
1932
- */
1933
- private detectCircularReferences;
1934
- /**
1935
- * Generate files from processed schemas
1936
- */
1937
- private generateFiles;
1938
- /**
1939
- * Generate a single file from a schema
1940
- */
1941
- private generateFileForSchema;
1942
- /**
1943
- * Ensure filename has correct extension
1944
- */
1945
- private ensureFileExtension;
1946
- /**
1947
- * Extract exported symbols from generated content
1948
- * Can be overridden by language-specific implementations
1949
- */
1950
- protected extractExports(content: string): string[];
1951
- /**
1952
- * Report progress to callback if provided
1953
- */
1954
- protected reportProgress(phase: "validation" | "generation" | "writing" | "complete", current: number, total: number, message?: string, schema?: TypeSchema): void;
1955
- /**
1956
- * Run post-generation hooks
1957
- * Can be overridden to add custom post-processing
1958
- */
1959
- protected runPostGenerationHooks(): Promise<void>;
1960
- /**
1961
- * Get cached value or compute and cache it
1962
- */
1963
- protected getCachedOrCompute<T>(key: string, computeFn: () => T | Promise<T>): T | Promise<T>;
1964
- /**
1965
- * Clear internal cache
1966
- */
1967
- protected clearCache(): void;
1968
- /**
1969
- * Get generation statistics
1970
- */
1971
- getGenerationStats(): {
1972
- filesGenerated: number;
1973
- totalSize: number;
1974
- averageFileSize: number;
1975
- generationTime: number;
1976
- averageTimePerFile: number;
1977
- cacheHitRate: number;
1978
- };
1979
- }
1980
-
1981
- /**
1982
- * Abstract base class for language-specific type mapping
1983
- *
1984
- * This provides the interface that all language generators must implement
1985
- * to convert FHIR TypeSchema types into their target language types.
1986
- */
1987
-
1988
- /**
1989
- * Configuration for type mapping behavior
1990
- */
1991
- interface TypeMapperOptions {
1992
- /** Whether to generate nullable types (e.g., T | null) */
1993
- generateNullable?: boolean;
1994
- /** Whether to use strict type checking */
1995
- strictTypes?: boolean;
1996
- /** Custom type mappings */
1997
- customMappings?: Record<string, string>;
1998
- /** Whether to generate array types or use generic collections */
1999
- preferArraySyntax?: boolean;
2000
- /** Naming convention strategy */
2001
- namingConvention?: "camelCase" | "PascalCase" | "snake_case" | "kebab-case";
2002
- }
2003
-
2004
- /**
2005
- * TypeScript-specific type mapper implementation
2006
- */
2007
-
2008
- /**
2009
- * TypeScript-specific options
2010
- */
2011
- interface TypeScriptTypeMapperOptions extends TypeMapperOptions {
2012
- /** Whether to use 'unknown' or 'any' for unmapped types */
2013
- preferUnknown?: boolean;
2014
- /** Whether to generate branded types for primitives */
2015
- useBrandedTypes?: boolean;
2016
- /** Whether to use 'undefined' or 'null' for optional types */
2017
- preferUndefined?: boolean;
2018
- /** Module format for imports */
2019
- moduleFormat?: "esm" | "commonjs";
2020
- }
2021
-
2022
- /**
2023
- * Modern TypeScript Generator built on BaseGenerator
2024
- *
2025
- * This is the new, clean implementation that replaces the monolithic typescript.ts generator.
2026
- * Built using the BaseGenerator architecture with TypeMapper, TemplateEngine, and FileManager.
2027
- */
2028
-
2029
- /**
2030
- * TypeScript-specific generator options
2031
- */
2032
- interface TypeScriptGeneratorOptions extends BaseGeneratorOptions {
2033
- /** Module format for imports/exports */
2034
- moduleFormat?: "esm" | "cjs";
2035
- /** Whether to generate index files */
2036
- generateIndex?: boolean;
2037
- /** Include JSDoc documentation */
2038
- includeDocuments?: boolean;
2039
- /** Naming convention for types */
2040
- namingConvention?: "PascalCase" | "camelCase";
2041
- /** Include FHIR extensions */
2042
- includeExtensions?: boolean;
2043
- /** Include FHIR profiles */
2044
- includeProfiles?: boolean;
2045
- /** Generate value set files (default: false) */
2046
- generateValueSets?: boolean;
2047
- /** Include helper validation functions (default: false) */
2048
- includeValueSetHelpers?: boolean;
2049
- /**
2050
- * Which binding strengths to generate value sets for
2051
- * Only used when valueSetMode is 'custom'
2052
- * @default ['required']
2053
- */
2054
- valueSetStrengths?: ("required" | "preferred" | "extensible" | "example")[];
2055
- /**
2056
- * Directory name for value set files (relative to outputDir)
2057
- * @default 'valuesets'
2058
- */
2059
- valueSetDirectory?: string;
2060
- /**
2061
- * Value set generation mode
2062
- * - 'all': Generate for all binding strengths with enums
2063
- * - 'required-only': Generate only for required bindings (safe default)
2064
- * - 'custom': Use valueSetStrengths array to control
2065
- * @default 'required-only'
2066
- */
2067
- valueSetMode?: "all" | "required-only" | "custom";
2068
- /** Type mapper options */
2069
- typeMapperOptions?: TypeScriptTypeMapperOptions;
2070
- }
2071
- /**
2072
- * Result of generating a single TypeScript file
2073
- */
2074
- interface GeneratedTypeScript {
2075
- content: string;
2076
- imports: Map<string, string>;
2077
- exports: string[];
2078
- filename: string;
2079
- }
2080
- /**
2081
- * Modern TypeScript Generator
2082
- *
2083
- * Generates clean, type-safe TypeScript interfaces from FHIR TypeSchema documents.
2084
- * Uses the new BaseGenerator architecture for maintainability and extensibility.
2085
- */
2086
- declare class TypeScriptGenerator extends BaseGenerator<TypeScriptGeneratorOptions, GeneratedFile[]> {
2087
- private readonly resourceTypes;
2088
- private collectedValueSets;
2089
- private get tsOptions();
2090
- protected getLanguageName(): string;
2091
- protected getFileExtension(): string;
2092
- protected createTypeMapper(): TypeMapper;
2093
- protected generateSchemaContent(schema: TypeSchema, _context: TemplateContext): Promise<string>;
2094
- protected filterAndSortSchemas(schemas: TypeSchema[]): TypeSchema[];
2095
- protected validateContent(content: string, context: TemplateContext): Promise<void>;
2096
- /**
2097
- * Transform multiple schemas into TypeScript
2098
- */
2099
- transformSchemas(schemas: TypeSchema[]): Promise<GeneratedTypeScript[]>;
2100
- /**
2101
- * Transform a single schema into TypeScript
2102
- */
2103
- transformSchema(schema: TypeSchema): Promise<GeneratedTypeScript | undefined>;
2104
- /**
2105
- * Check if a binding schema should generate a value set file
2106
- */
2107
- private shouldGenerateValueSet;
2108
- /**
2109
- * Collect value sets from schemas that should generate value set files
2110
- */
2111
- private collectValueSets;
2112
- /**
2113
- * Check if a field binding should use a value set type
2114
- */
2115
- private shouldUseValueSetType;
2116
- /**
2117
- * Get the TypeScript type name for a binding
2118
- */
2119
- private getValueSetTypeName;
2120
- /**
2121
- * Check if a field has enum values that should be inlined
2122
- */
2123
- private shouldUseInlineEnum;
2124
- /**
2125
- * Generate inline enum type from field enum values
2126
- */
2127
- private generateInlineEnumType;
2128
- private shouldSkipSchema;
2129
- private getFilenameForSchema;
2130
- private extractImportsFromContent;
2131
- private extractExportsFromContent;
2132
- /**
2133
- * Generate special Reference interface with generics
2134
- */
2135
- private generateReferenceInterface;
2136
- /**
2137
- * Generate TypeScript interface directly without templates
2138
- */
2139
- private generateTypeScriptInterface;
2140
- /**
2141
- * Collect import dependencies from a field
2142
- */
2143
- private collectFieldImports;
2144
- /**
2145
- * Extract resource types from reference field constraints
2146
- */
2147
- private extractReferenceTypes;
2148
- /**
2149
- * Generate nested type interface
2150
- */
2151
- private generateNestedTypeInterface;
2152
- /**
2153
- * Capitalize first letter of string
2154
- */
2155
- private capitalizeFirst;
2156
- /**
2157
- * Generate field lines (handles polymorphic fields by expanding them)
2158
- */
2159
- private generateFieldLines;
2160
- /**
2161
- * Generate a single field line
2162
- */
2163
- private generateFieldLine;
2164
- /**
2165
- * Extract exported symbols from TypeScript content
2166
- */
2167
- protected extractExports(content: string): string[];
2168
- /**
2169
- * Set output directory for compatibility with API builder
2170
- */
2171
- setOutputDir(directory: string): void;
2172
- /**
2173
- * Update generator options for compatibility with API builder
2174
- */
2175
- setOptions(options: Partial<TypeScriptGeneratorOptions>): void;
2176
- /**
2177
- * Get current options for compatibility with API builder
2178
- */
2179
- getOptions(): TypeScriptGeneratorOptions;
2180
- /**
2181
- * Override generate to clean directory first
2182
- */
2183
- generate(input: GeneratorInput): Promise<GeneratedFile[]>;
2184
- /**
2185
- * Run post-generation hooks - generate utility files
2186
- */
2187
- protected runPostGenerationHooks(): Promise<void>;
2188
- /**
2189
- * Generate utilities.ts file with ResourceType union
2190
- */
2191
- private generateUtilitiesFile;
2192
- /**
2193
- * Generate a complete value set TypeScript file
2194
- */
2195
- private generateValueSetFile;
2196
- /**
2197
- * Create valuesets directory and generate all value set files
2198
- */
2199
- private generateValueSetFiles;
2200
- /**
2201
- * Generate index.ts file that re-exports all value sets
2202
- */
2203
- private generateValueSetIndexFile;
2204
- /**
2205
- * Generate main types/index.ts file that exports all types and value sets
2206
- */
2207
- private generateMainIndexFile;
2208
- }
2209
604
 
2210
- export { APIBuilder, type APIBuilderOptions, CONFIG_FILE_NAMES, type Config, ConfigLoader, type ConfigValidationError, type ConfigValidationResult, ConfigValidator, DEFAULT_CONFIG, type GeneratedFile, type GenerationResult, type PackageMeta as PackageInfo, type ProgressCallback$1 as ProgressCallback, type TypeSchema, TypeSchemaCache, type TypeSchemaConfig, type Field as TypeSchemaField, TypeSchemaGenerator, type Identifier as TypeSchemaIdentifier, TypeSchemaParser, TypeScriptGenerator, type TypeScriptGeneratorConfig, type TypeScriptGeneratorOptions, configLoader, createAPIFromConfig, defineConfig, isConfig, loadConfig };
605
+ export { APIBuilder, type APIBuilderOptions, CONFIG_FILE_NAMES, type CSharpGeneratorOptions, type Config, ConfigLoader, type ConfigValidationError, type ConfigValidationResult, ConfigValidator, DEFAULT_CONFIG, type TypeSchemaConfig, type TypeScriptGeneratorConfig, type TypeScriptOptions, configLoader, defineConfig, isConfig, loadConfig };