@atomic-ehr/codegen 0.0.2 → 0.0.3-canary.20251124124513.ba9446c

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,236 +476,26 @@ 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
- interface WriterOptions {
479
+ type FileSystemWriterOptions = {
789
480
  outputDir: string;
481
+ inMemoryOnly?: boolean;
482
+ logger?: CodegenLogger;
483
+ };
484
+ type WriterOptions = FileSystemWriterOptions & {
790
485
  tabSize: number;
791
486
  withDebugComment?: boolean;
792
487
  commentLinePrefix: string;
793
488
  generateProfile?: boolean;
794
- logger?: CodegenLogger;
795
- }
489
+ };
490
+
491
+ type TypeScriptOptions = {
492
+ /** openResourceTypeSet -- for resource families (Resource, DomainResource) use open set for resourceType field.
493
+ *
494
+ * - when openResourceTypeSet is false: `type Resource = { resourceType: "Resource" | "DomainResource" | "Patient" }`
495
+ * - when openResourceTypeSet is true: `type Resource = { resourceType: "Resource" | "DomainResource" | "Patient" | string }`
496
+ */
497
+ openResourceTypeSet: boolean;
498
+ } & WriterOptions;
796
499
 
797
500
  /**
798
501
  * High-Level API Builder
@@ -821,7 +524,7 @@ interface APIBuilderOptions {
821
524
  /**
822
525
  * Progress callback for long-running operations
823
526
  */
824
- type ProgressCallback$1 = (phase: string, current: number, total: number, message?: string) => void;
527
+ type ProgressCallback = (phase: string, current: number, total: number, message?: string) => void;
825
528
  /**
826
529
  * Generation result information
827
530
  */
@@ -843,9 +546,6 @@ declare class APIBuilder {
843
546
  private schemas;
844
547
  private options;
845
548
  private generators;
846
- private cache?;
847
- private pendingOperations;
848
- private typeSchemaGenerator?;
849
549
  private logger;
850
550
  private packages;
851
551
  progressCallback: any;
@@ -853,27 +553,13 @@ declare class APIBuilder {
853
553
  constructor(options?: APIBuilderOptions);
854
554
  fromPackage(packageName: string, version?: string): APIBuilder;
855
555
  fromPackageRef(packageRef: string): APIBuilder;
856
- fromFiles(...filePaths: string[]): APIBuilder;
857
556
  fromSchemas(schemas: TypeSchema[]): APIBuilder;
858
- typescriptDepricated(options?: {
859
- moduleFormat?: "esm" | "cjs";
860
- generateIndex?: boolean;
861
- includeDocuments?: boolean;
862
- namingConvention?: "PascalCase" | "camelCase";
863
- includeExtensions?: boolean;
864
- includeProfiles?: boolean;
865
- generateValueSets?: boolean;
866
- includeValueSetHelpers?: boolean;
867
- valueSetStrengths?: ("required" | "preferred" | "extensible" | "example")[];
868
- valueSetMode?: "all" | "required-only" | "custom";
869
- valueSetDirectory?: string;
870
- }): APIBuilder;
871
- typescript(opts: Partial<WriterOptions>): this;
557
+ typescript(userOpts: Partial<TypeScriptOptions>): this;
872
558
  csharp(namespace: string, staticSourceDir?: string | undefined): APIBuilder;
873
559
  /**
874
560
  * Set a progress callback for monitoring generation
875
561
  */
876
- onProgress(callback: ProgressCallback$1): APIBuilder;
562
+ onProgress(callback: ProgressCallback): APIBuilder;
877
563
  /**
878
564
  * Set the output directory for all generators
879
565
  */
@@ -885,15 +571,6 @@ declare class APIBuilder {
885
571
  treeShake(tree: TreeShake): this;
886
572
  writeTypeSchemas(target: string): this;
887
573
  generate(): Promise<GenerationResult>;
888
- /**
889
- * Generate and return the results without writing to files
890
- */
891
- build(): Promise<{
892
- typescript?: {
893
- content: string;
894
- filename: string;
895
- }[];
896
- }>;
897
574
  /**
898
575
  * Clear all configuration and start fresh
899
576
  */
@@ -906,1296 +583,13 @@ declare class APIBuilder {
906
583
  * Get configured generators (for inspection)
907
584
  */
908
585
  getGenerators(): string[];
909
- private loadFromFiles;
910
586
  private executeGenerators;
911
587
  }
912
- /**
913
- * Create an API builder instance from a configuration object
914
- */
915
- declare function createAPIFromConfig(config: Config): APIBuilder;
916
-
917
- /**
918
- * Core types and interfaces for the base generator system
919
- *
920
- * This module provides the foundational type definitions that all generators
921
- * build upon, ensuring consistency and type safety across the system.
922
- */
923
-
924
- /**
925
- * Base configuration options that all generators must support
926
- * These options provide the minimum required configuration for any generator
927
- */
928
- interface BaseGeneratorOptions {
929
- /** Output directory where generated files will be written */
930
- outputDir: string;
931
- /** Logger instance for tracking generation progress and errors */
932
- logger?: CodegenLogger;
933
- /** Whether to overwrite existing files (default: true) */
934
- overwrite?: boolean;
935
- /** Whether to validate schemas and generated content (default: true) */
936
- validate?: boolean;
937
- /** Enable detailed logging for debugging (default: false) */
938
- verbose?: boolean;
939
- /** Enable beginner-friendly error messages and guidance (default: false) */
940
- beginnerMode?: boolean;
941
- /** Format for error output: console, json, or structured (default: 'console') */
942
- errorFormat?: "console" | "json" | "structured";
943
- }
944
- /**
945
- * Language-specific type representation
946
- * This interface standardizes how FHIR types are mapped to target languages
947
- */
948
- interface LanguageType {
949
- /** The type string in the target language (e.g., "string", "number", "Patient") */
950
- name: string;
951
- /** Whether this is a primitive type that doesn't need imports */
952
- isPrimitive: boolean;
953
- /** Import path if this type needs to be imported from another module */
954
- importPath?: string;
955
- /** Generic parameters if this is a generic type (e.g., ["T", "K"] for Map<T,K>) */
956
- generics?: string[];
957
- /** Whether this type is nullable/optional in the target language */
958
- nullable?: boolean;
959
- /** Additional metadata specific to the target language */
960
- metadata?: Record<string, unknown>;
961
- }
962
- /**
963
- * Generated file metadata and content
964
- * Represents a single generated file with all its associated information
965
- */
966
- interface GeneratedFile {
967
- /** Full file system path where the file was/will be written */
968
- path: string;
969
- /** Filename only (without directory path) */
970
- filename: string;
971
- /** The generated content of the file */
972
- content: string;
973
- /** List of symbols exported from this file */
974
- exports: string[];
975
- /** File size in bytes */
976
- size: number;
977
- /** When this file was generated */
978
- timestamp: Date;
979
- /** Additional metadata about the generation process */
980
- metadata?: {
981
- /** Time taken to generate this file in milliseconds */
982
- generationTime?: number;
983
- /** Number of schemas processed for this file */
984
- schemaCount?: number;
985
- /** Template used to generate this file */
986
- templateName?: string;
987
- /** Any warnings generated during processing */
988
- warnings?: string[];
989
- };
990
- }
991
- /**
992
- * Template context provided to template engines
993
- * Contains all the data needed to render templates for code generation
994
- */
995
- interface TemplateContext {
996
- /** The schema being processed */
997
- schema: TypeSchema;
998
- /** Type mapper for the target language */
999
- typeMapper: TypeMapper;
1000
- /** Current file being generated */
1001
- filename: string;
1002
- /** Target language name (e.g., "TypeScript", "Python") */
1003
- language: string;
1004
- /** Generation timestamp in ISO format */
1005
- timestamp: string;
1006
- /** Import map for the current file */
1007
- imports?: Map<string, string>;
1008
- /** Export set for the current file */
1009
- exports?: Set<string>;
1010
- /** Additional context data that templates can use */
1011
- [key: string]: unknown;
1012
- }
1013
- /**
1014
- * File builder context passed to lifecycle hooks
1015
- * Provides access to file generation state during the build process
1016
- */
1017
- interface FileContext {
1018
- /** Name of the file being generated */
1019
- filename: string;
1020
- /** Current file content */
1021
- content: string;
1022
- /** Map of imports (symbol name -> import path) */
1023
- imports: Map<string, string>;
1024
- /** Set of exported symbols */
1025
- exports: Set<string>;
1026
- /** Additional metadata about the file */
1027
- metadata: Record<string, unknown>;
1028
- /** The schema that generated this file (if applicable) */
1029
- schema?: TypeSchema;
1030
- /** Template name used to generate this file (if applicable) */
1031
- templateName?: string;
1032
- }
1033
- /**
1034
- * Statistics about file operations
1035
- * Used for performance monitoring and optimization
1036
- */
1037
- interface FileStats {
1038
- /** File size in bytes */
1039
- size: number;
1040
- /** Time taken to generate content in milliseconds */
1041
- generationTime: number;
1042
- /** Time taken to write to disk in milliseconds */
1043
- writeTime: number;
1044
- /** Memory used during generation in bytes */
1045
- memoryUsed?: number;
1046
- /** Number of template renders performed */
1047
- templateRenders?: number;
1048
- }
1049
- /**
1050
- * Progress callback signature for monitoring generation
1051
- * Allows consumers to track progress of long-running operations
1052
- */
1053
- type ProgressCallback = (
1054
- /** Current phase of generation */
1055
- phase: "validation" | "generation" | "writing" | "complete",
1056
- /** Current item number being processed */
1057
- current: number,
1058
- /** Total number of items to process */
1059
- total: number,
1060
- /** Optional message describing current operation */
1061
- message?: string,
1062
- /** Schema being processed (if applicable) */
1063
- schema?: TypeSchema) => void;
1064
- /**
1065
- * Lifecycle hook signatures for file operations
1066
- * These hooks allow customization of the file generation process
1067
- */
1068
- /** Hook called before saving a file - can modify content or abort save */
1069
- type BeforeSaveHook = (context: FileContext) => void | Promise<void>;
1070
- /** Hook called after successfully saving a file */
1071
- type AfterSaveHook = (filePath: string, stats: FileStats) => void | Promise<void>;
1072
- /** Hook called when an error occurs during file operations */
1073
- type ErrorHook = (error: Error, context: FileContext) => void | Promise<void>;
1074
- /**
1075
- * File builder configuration options
1076
- * Controls how files are generated and processed
1077
- */
1078
- interface FileBuilderOptions {
1079
- /** Template name to use for content generation */
1080
- template?: string;
1081
- /** Strategy for resolving import paths */
1082
- importStrategy?: "auto" | "manual" | "none";
1083
- /** Level of content validation to perform */
1084
- validation?: "strict" | "loose" | "none";
1085
- /** Enable pretty printing of generated content */
1086
- prettify?: boolean;
1087
- /** Custom formatting options */
1088
- formatting?: {
1089
- /** Number of spaces for indentation (default: 2) */
1090
- indentSize?: number;
1091
- /** Use tabs instead of spaces (default: false) */
1092
- useTabs?: boolean;
1093
- /** Maximum line length before wrapping (default: 100) */
1094
- maxLineLength?: number;
1095
- };
1096
- /** File encoding (default: 'utf-8') */
1097
- encoding?: BufferEncoding;
1098
- }
1099
- /**
1100
- * Abstract base class for type mapping between FHIR and target languages
1101
- * Each language-specific generator must implement this interface
1102
- */
1103
- declare abstract class TypeMapper {
1104
- /**
1105
- * Map a FHIR primitive type to the target language
1106
- * @param fhirType - FHIR primitive type name (e.g., "string", "integer")
1107
- * @returns Language-specific type representation
1108
- */
1109
- abstract mapPrimitive(fhirType: string): LanguageType;
1110
- /**
1111
- * Map a FHIR reference to the target language
1112
- * @param targets - Array of possible reference targets
1113
- * @returns Language-specific reference type
1114
- */
1115
- abstract mapReference(targets: Identifier[]): LanguageType;
1116
- /**
1117
- * Map an array type in the target language
1118
- * @param elementType - The element type name
1119
- * @returns Language-specific array type
1120
- */
1121
- abstract mapArray(elementType: string): LanguageType;
1122
- /**
1123
- * Map optional/nullable types
1124
- * @param type - The base type
1125
- * @param required - Whether the field is required
1126
- * @returns Language-specific optional type
1127
- */
1128
- abstract mapOptional(type: string, required: boolean): LanguageType;
1129
- /**
1130
- * Map enumerated values to the target language
1131
- * @param values - Array of possible values
1132
- * @param name - Optional name for the enum type
1133
- * @returns Language-specific enum type
1134
- */
1135
- abstract mapEnum(values: string[], name?: string): LanguageType;
1136
- /**
1137
- * Format a FHIR type name according to target language conventions
1138
- * @param name - FHIR type name
1139
- * @returns Formatted type name
1140
- */
1141
- abstract formatTypeName(name: string): string;
1142
- /**
1143
- * Format a field name according to target language conventions
1144
- * @param name - FHIR field name
1145
- * @returns Formatted field name
1146
- */
1147
- abstract formatFieldName(name: string): string;
1148
- /**
1149
- * Format a filename according to target language conventions
1150
- * @param name - Base filename
1151
- * @returns Formatted filename (without extension)
1152
- */
1153
- abstract formatFileName(name: string): string;
1154
- /**
1155
- * Map a complete TypeSchema identifier to target language type
1156
- * @param identifier - FHIR type identifier
1157
- * @returns Language-specific type representation
1158
- */
1159
- abstract mapType(identifier: Identifier): LanguageType;
1160
- /**
1161
- * Get import statement format for the target language
1162
- * @param symbols - Symbols to import
1163
- * @param from - Module to import from
1164
- * @returns Formatted import statement
1165
- */
1166
- formatImport?(symbols: string[], from: string): string;
1167
- /**
1168
- * Get export statement format for the target language
1169
- * @param symbols - Symbols to export
1170
- * @returns Formatted export statement
1171
- */
1172
- formatExport?(symbols: string[]): string;
1173
- }
1174
- /**
1175
- * Template engine interface
1176
- * Abstraction for different template engines (Handlebars, etc.)
1177
- */
1178
- interface TemplateEngine {
1179
- /**
1180
- * Render a template with the given context
1181
- * @param templateName - Name of the template to render
1182
- * @param context - Data to pass to the template
1183
- * @returns Rendered content
1184
- */
1185
- render(templateName: string, context: Record<string, unknown>): string;
1186
- /**
1187
- * Register a template
1188
- * @param name - Template name
1189
- * @param template - Template content or compiled template
1190
- */
1191
- registerTemplate(name: string, template: string | ((...args: any[]) => any)): void;
1192
- /**
1193
- * Register a helper function
1194
- * @param name - Helper name
1195
- * @param helper - Helper function
1196
- */
1197
- registerHelper(name: string, helper: (...args: any[]) => any): void;
1198
- /**
1199
- * Check if a template exists
1200
- * @param name - Template name
1201
- * @returns True if template exists
1202
- */
1203
- hasTemplate(name: string): boolean;
1204
- /**
1205
- * Get list of available templates
1206
- * @returns Array of template names
1207
- */
1208
- getAvailableTemplates(): string[];
1209
- }
1210
- /**
1211
- * Generator capabilities interface
1212
- * Describes what a generator can do - used for introspection
1213
- */
1214
- interface GeneratorCapabilities {
1215
- /** Programming language this generator targets */
1216
- language: string;
1217
- /** File extensions this generator produces */
1218
- fileExtensions: string[];
1219
- /** Whether this generator supports templates */
1220
- supportsTemplates: boolean;
1221
- /** Whether this generator supports custom type mapping */
1222
- supportsCustomTypeMapping: boolean;
1223
- /** Whether this generator supports incremental generation */
1224
- supportsIncrementalGeneration: boolean;
1225
- /** Whether this generator supports validation */
1226
- supportsValidation: boolean;
1227
- /** Supported schema kinds */
1228
- supportedSchemaKinds: Array<"resource" | "complex-type" | "profile" | "primitive-type" | "logical">;
1229
- /** Version of the generator */
1230
- version: string;
1231
- /** Additional metadata about capabilities */
1232
- metadata?: Record<string, unknown>;
1233
- }
1234
-
1235
- /**
1236
- * Core file management system with batching and performance optimizations
1237
- *
1238
- * This replaces scattered writeFile calls with a comprehensive file management
1239
- * system that provides better error handling, performance, and maintainability.
1240
- */
1241
588
 
1242
- interface FileManagerOptions {
589
+ type CSharpGeneratorOptions = WriterOptions & {
1243
590
  outputDir: string;
1244
- logger: CodegenLogger;
1245
- overwrite?: boolean;
1246
- batchSize?: number;
1247
- }
1248
- interface WriteFileResult {
1249
- path: string;
1250
- size: number;
1251
- writeTime: number;
1252
- }
1253
- /**
1254
- * High-performance file manager with batching and error recovery
1255
- *
1256
- * Features:
1257
- * - Automatic directory creation
1258
- * - Batch operations for better performance
1259
- * - Comprehensive error handling with recovery suggestions
1260
- * - Import path resolution
1261
- * - File existence checks
1262
- */
1263
- declare class FileManager {
1264
- private readonly options;
1265
- private readonly logger;
1266
- constructor(options: FileManagerOptions);
1267
- /**
1268
- * Write a file with automatic directory creation
1269
- * @param relativePath Path relative to output directory
1270
- * @param content File content
1271
- * @param options Write options
1272
- */
1273
- writeFile(relativePath: string, content: string, options?: {
1274
- encoding?: BufferEncoding;
1275
- overwrite?: boolean;
1276
- }): Promise<WriteFileResult>;
1277
- /**
1278
- * Write multiple files in batch for better performance
1279
- * @param files Map of relative path to content
1280
- */
1281
- writeBatch(files: Map<string, string>): Promise<WriteFileResult[]>;
1282
- /**
1283
- * Ensure directory exists, creating parent directories as needed
1284
- * @param dirPath Full directory path
1285
- */
1286
- ensureDirectory(dirPath: string): Promise<void>;
1287
- /**
1288
- * Clean directory by removing all contents
1289
- * @param relativePath Path relative to output directory
1290
- */
1291
- cleanDirectory(relativePath?: string): Promise<void>;
1292
- /**
1293
- * Get relative import path between two files
1294
- * @param fromFile Source file path
1295
- * @param toFile Target file path
1296
- */
1297
- getRelativeImportPath(fromFile: string, toFile: string): string;
1298
- /**
1299
- * Check if a file would be overwritten
1300
- * @param relativePath Path relative to output directory
1301
- */
1302
- wouldOverwrite(relativePath: string): Promise<boolean>;
1303
- /**
1304
- * Get file statistics
1305
- * @param relativePath Path relative to output directory
1306
- */
1307
- getFileStats(relativePath: string): Promise<FileStats | null>;
1308
- /**
1309
- * Get output directory
1310
- */
1311
- getOutputDirectory(): string;
1312
- /**
1313
- * Set batch size for operations
1314
- * @param size Batch size
1315
- */
1316
- setBatchSize(size: number): void;
1317
- /**
1318
- * Get current batch size
1319
- */
1320
- getBatchSize(): number;
1321
- }
1322
-
1323
- /**
1324
- * Index file builder for automated exports
1325
- *
1326
- * Automatically generates index files that export all types and functions
1327
- * from a directory, with support for grouping and namespaces.
1328
- */
1329
-
1330
- interface IndexBuilderConfig {
1331
- directory: string;
1332
- fileManager: FileManager;
1333
- templateEngine?: TemplateEngine;
1334
- logger: CodegenLogger;
1335
- }
1336
- /**
1337
- * Builder for index files with intelligent export management
1338
- *
1339
- * Features:
1340
- * - Automatic export detection
1341
- * - Namespace support
1342
- * - Export grouping
1343
- * - Custom headers
1344
- * - Template support
1345
- */
1346
- declare class IndexBuilder {
1347
- private readonly config;
1348
- private readonly exports;
1349
- private readonly namespaces;
1350
- private readonly reExports;
1351
- private header;
1352
- private footer;
1353
- private groupingFunction?;
1354
- private sortFunction?;
1355
- constructor(config: IndexBuilderConfig);
1356
- /**
1357
- * Add exports from a specific file
1358
- * @param exportNames Export names
1359
- * @param fromPath Path to file (without extension)
1360
- */
1361
- withExports(exportNames: string[], fromPath: string): IndexBuilder;
1362
- /**
1363
- * Add a single export
1364
- * @param exportName Export name
1365
- * @param fromPath Path to file
1366
- */
1367
- withExport(exportName: string, fromPath: string): IndexBuilder;
1368
- /**
1369
- * Add namespace exports
1370
- * @param namespaces Map of namespace to path
1371
- */
1372
- withNamespaces(namespaces: Record<string, string>): IndexBuilder;
1373
- /**
1374
- * Add namespace export
1375
- * @param namespace Namespace name
1376
- * @param path Path to export as namespace
1377
- */
1378
- withNamespace(namespace: string, path: string): IndexBuilder;
1379
- /**
1380
- * Re-export all from paths
1381
- * @param paths Paths to re-export all from
1382
- */
1383
- withReExports(paths: string[]): IndexBuilder;
1384
- /**
1385
- * Add re-export
1386
- * @param path Path to re-export all from
1387
- */
1388
- withReExport(path: string): IndexBuilder;
1389
- /**
1390
- * Set header content
1391
- * @param header Header content
1392
- */
1393
- withHeader(header: string): IndexBuilder;
1394
- /**
1395
- * Set footer content
1396
- * @param footer Footer content
1397
- */
1398
- withFooter(footer: string): IndexBuilder;
1399
- /**
1400
- * Group exports by function
1401
- * @param fn Function that returns group name for export
1402
- */
1403
- groupBy(fn: (exportName: string) => string): IndexBuilder;
1404
- /**
1405
- * Sort exports by function
1406
- * @param fn Sort function for [exportName, fromPath] tuples
1407
- */
1408
- sortBy(fn: (a: [string, string], b: [string, string]) => number): IndexBuilder;
1409
- /**
1410
- * Auto-discover exports from directory
1411
- * @param filePattern Pattern to match files (e.g., "*.ts")
1412
- */
1413
- autoDiscover(_filePattern?: string): Promise<IndexBuilder>;
1414
- /**
1415
- * Save the index file
1416
- */
1417
- save(): Promise<string>;
1418
- /**
1419
- * Build content without saving (for preview)
1420
- */
1421
- build(): string;
1422
- /**
1423
- * Generate the index file content
1424
- */
1425
- private generateContent;
1426
- /**
1427
- * Generate simple exports without grouping
1428
- */
1429
- private generateSimpleExports;
1430
- /**
1431
- * Generate grouped exports
1432
- */
1433
- private generateGroupedExports;
1434
- /**
1435
- * Get current exports (for testing/debugging)
1436
- */
1437
- getExports(): Map<string, string>;
1438
- /**
1439
- * Get current namespaces (for testing/debugging)
1440
- */
1441
- getNamespaces(): Map<string, string>;
1442
- /**
1443
- * Get current re-exports (for testing/debugging)
1444
- */
1445
- getReExports(): Map<string, string>;
1446
- }
1447
-
1448
- /**
1449
- * Fluent file builder with lifecycle hooks and validation
1450
- *
1451
- * This provides a clean, chainable API for building files with imports,
1452
- * exports, content generation, and lifecycle hooks for customization.
1453
- */
1454
-
1455
- interface FileBuilderConfig {
1456
- filename: string;
1457
- fileManager: FileManager;
1458
- templateEngine?: TemplateEngine;
1459
- typeMapper: TypeMapper;
1460
- logger: CodegenLogger;
1461
- }
1462
- /**
1463
- * Fluent builder for creating files with lifecycle hooks
1464
- *
1465
- * Features:
1466
- * - Fluent API for content building
1467
- * - Template integration
1468
- * - Import/export management
1469
- * - Lifecycle hooks (before/after save, error handling)
1470
- * - Content validation
1471
- * - Automatic import path resolution
1472
- */
1473
- declare class FileBuilder {
1474
- private readonly config;
1475
- private content;
1476
- private readonly imports;
1477
- private readonly exports;
1478
- private readonly metadata;
1479
- private beforeSaveHooks;
1480
- private afterSaveHooks;
1481
- private errorHooks;
1482
- private options;
1483
- constructor(config: FileBuilderConfig);
1484
- /**
1485
- * Set content directly
1486
- * @param content File content
1487
- */
1488
- withContent(content: string | (() => string)): FileBuilder;
1489
- /**
1490
- * Generate content from template
1491
- * @param templateName Template to use
1492
- * @param context Template context
1493
- */
1494
- withTemplate(templateName: string, context: Record<string, unknown>): FileBuilder;
1495
- /**
1496
- * Append content to existing content
1497
- * @param content Content to append
1498
- */
1499
- appendContent(content: string): FileBuilder;
1500
- /**
1501
- * Prepend content to existing content
1502
- * @param content Content to prepend
1503
- */
1504
- prependContent(content: string): FileBuilder;
1505
- /**
1506
- * Set all imports at once
1507
- * @param imports Map of symbol name to import path
1508
- */
1509
- withImports(imports: Map<string, string>): FileBuilder;
1510
- /**
1511
- * Add a single import
1512
- * @param symbol Symbol to import
1513
- * @param from Import path
1514
- */
1515
- addImport(symbol: string, from: string): FileBuilder;
1516
- /**
1517
- * Add multiple imports from the same path
1518
- * @param symbols Symbols to import
1519
- * @param from Import path
1520
- */
1521
- addImports(symbols: string[], from: string): FileBuilder;
1522
- /**
1523
- * Set all exports at once
1524
- * @param exports Array of export names
1525
- */
1526
- withExports(exports: string[]): FileBuilder;
1527
- /**
1528
- * Add a single export
1529
- * @param name Export name
1530
- */
1531
- addExport(name: string): FileBuilder;
1532
- /**
1533
- * Add multiple exports
1534
- * @param names Export names
1535
- */
1536
- addExports(names: string[]): FileBuilder;
1537
- /**
1538
- * Set metadata for the file
1539
- * @param key Metadata key
1540
- * @param value Metadata value
1541
- */
1542
- withMetadata(key: string, value: unknown): FileBuilder;
1543
- /**
1544
- * Set file builder options
1545
- * @param options Options to set
1546
- */
1547
- withOptions(options: Partial<FileBuilderOptions>): FileBuilder;
1548
- /**
1549
- * Add hook to run before saving
1550
- * @param hook Hook function
1551
- */
1552
- onBeforeSave(hook: BeforeSaveHook): FileBuilder;
1553
- /**
1554
- * Add hook to run after successful save
1555
- * @param hook Hook function
1556
- */
1557
- onAfterSave(hook: AfterSaveHook): FileBuilder;
1558
- /**
1559
- * Add hook to run when error occurs
1560
- * @param hook Hook function
1561
- */
1562
- onError(hook: ErrorHook): FileBuilder;
1563
- /**
1564
- * Build final content without saving
1565
- * @returns File context with final content
1566
- */
1567
- build(): FileContext;
1568
- /**
1569
- * Save the file
1570
- * @returns Promise resolving to file path
1571
- */
1572
- save(): Promise<string>;
1573
- /**
1574
- * Build final content with imports and exports
1575
- */
1576
- private buildFinalContent;
1577
- /**
1578
- * Generate import statements
1579
- */
1580
- private generateImportStatements;
1581
- /**
1582
- * Generate export statements
1583
- */
1584
- private generateExportStatements;
1585
- /**
1586
- * Prettify content (basic implementation)
1587
- */
1588
- private prettifyContent;
1589
- /**
1590
- * Validate generated content
1591
- */
1592
- private validateContent;
1593
- /**
1594
- * Get current content (for testing/debugging)
1595
- */
1596
- getContent(): string;
1597
- /**
1598
- * Get current imports (for testing/debugging)
1599
- */
1600
- getImports(): Map<string, string>;
1601
- /**
1602
- * Get current exports (for testing/debugging)
1603
- */
1604
- getExports(): Set<string>;
1605
- }
1606
-
1607
- /**
1608
- * Directory builder for batch file operations
1609
- *
1610
- * Provides a fluent API for managing entire directories of files,
1611
- * including subdirectories, index files, and batch operations.
1612
- */
1613
-
1614
- interface DirectoryBuilderConfig {
1615
- path: string;
1616
- fileManager: FileManager;
1617
- logger: CodegenLogger;
1618
- }
1619
- /**
1620
- * Fluent builder for directory operations
1621
- *
1622
- * Features:
1623
- * - Subdirectory management
1624
- * - Batch file operations
1625
- * - Index file generation
1626
- * - Directory cleaning
1627
- * - File listing for preview
1628
- */
1629
- declare class DirectoryBuilder {
1630
- private readonly config;
1631
- private readonly files;
1632
- private readonly subdirectories;
1633
- private indexBuilder?;
1634
- private shouldClean;
1635
- constructor(config: DirectoryBuilderConfig);
1636
- /**
1637
- * Add a subdirectory
1638
- * @param name Subdirectory name
1639
- */
1640
- withSubdirectory(name: string): DirectoryBuilder;
1641
- /**
1642
- * Add files to this directory
1643
- * @param files Map of filename to FileBuilder
1644
- */
1645
- withFiles(files: Record<string, FileBuilder>): DirectoryBuilder;
1646
- /**
1647
- * Add a single file
1648
- * @param filename File name
1649
- * @param builder File builder
1650
- */
1651
- withFile(filename: string, builder: FileBuilder): DirectoryBuilder;
1652
- /**
1653
- * Set index builder for this directory
1654
- * @param builder Index builder
1655
- */
1656
- withIndex(builder: IndexBuilder): DirectoryBuilder;
1657
- /**
1658
- * Clean directory before creating files
1659
- */
1660
- clean(): DirectoryBuilder;
1661
- /**
1662
- * Ensure directory exists
1663
- */
1664
- ensure(): Promise<DirectoryBuilder>;
1665
- /**
1666
- * Save all files in this directory
1667
- */
1668
- save(): Promise<string[]>;
1669
- /**
1670
- * Get all files that would be generated (for preview)
1671
- */
1672
- getFileList(): string[];
1673
- /**
1674
- * Get statistics about this directory
1675
- */
1676
- getStats(): {
1677
- fileCount: number;
1678
- subdirectoryCount: number;
1679
- hasIndex: boolean;
1680
- totalFiles: number;
1681
- };
1682
- /**
1683
- * Check if directory would overwrite existing files
1684
- */
1685
- wouldOverwrite(): Promise<string[]>;
1686
- /**
1687
- * Get the path of this directory
1688
- */
1689
- getPath(): string;
1690
- /**
1691
- * Get all file builders (for testing/debugging)
1692
- */
1693
- getFiles(): Map<string, FileBuilder>;
1694
- /**
1695
- * Get all subdirectories (for testing/debugging)
1696
- */
1697
- getSubdirectories(): Map<string, DirectoryBuilder>;
1698
- /**
1699
- * Get index builder (for testing/debugging)
1700
- */
1701
- getIndexBuilder(): IndexBuilder | undefined;
1702
- }
1703
-
1704
- /**
1705
- * Centralized error handling and reporting system
1706
- *
1707
- * This module provides a comprehensive error handling solution that:
1708
- * - Handles both generator-specific and unknown errors gracefully
1709
- * - Provides rich, context-aware error reporting
1710
- * - Supports multiple output formats (console, JSON, structured)
1711
- * - Includes batch error handling for multiple failures
1712
- * - Offers smart error recovery suggestions
1713
- */
1714
-
1715
- interface ErrorHandlerOptions {
1716
- logger: CodegenLogger;
1717
- verbose?: boolean;
1718
- beginnerMode?: boolean;
1719
- outputFormat?: "this.options.logger" | "json" | "structured";
1720
- }
1721
- /**
1722
- * Centralized error handler with smart reporting
1723
- */
1724
- declare class ErrorHandler {
1725
- private options;
1726
- constructor(options: ErrorHandlerOptions);
1727
- /**
1728
- * Handle a single error with appropriate reporting
1729
- */
1730
- handleError(error: Error, context?: {
1731
- schema?: TypeSchema;
1732
- filename?: string;
1733
- }): void;
1734
- /**
1735
- * Handle multiple errors in batch
1736
- */
1737
- handleBatchErrors(errors: Error[]): void;
1738
- /**
1739
- * Handle generator-specific errors with rich context
1740
- */
1741
- private handleGeneratorError;
1742
- /**
1743
- * Handle unknown errors gracefully
1744
- */
1745
- private handleUnknownError;
1746
- /**
1747
- * Report error to console with formatting
1748
- */
1749
- private reportErrorToConsole;
1750
- /**
1751
- * Report error as JSON for programmatic consumption
1752
- */
1753
- private reportErrorAsJson;
1754
- /**
1755
- * Report error in structured format
1756
- */
1757
- private reportErrorStructured;
1758
- /**
1759
- * Report multiple errors efficiently
1760
- */
1761
- private reportBatchErrors;
1762
- /**
1763
- * Get common suggestions across similar errors
1764
- */
1765
- private getCommonSuggestions;
1766
- /**
1767
- * Get recovery actions for an error
1768
- */
1769
- private getRecoveryActions;
1770
- }
1771
- /**
1772
- * Error boundary for catching and handling all generator errors
1773
- */
1774
- declare class GeneratorErrorBoundary {
1775
- private errorHandler;
1776
- constructor(errorHandler: ErrorHandler);
1777
- /**
1778
- * Wrap an async operation with error boundary
1779
- */
1780
- withErrorBoundary<T>(operation: () => Promise<T>, context?: {
1781
- schema?: TypeSchema;
1782
- filename?: string;
1783
- operationName?: string;
1784
- }): Promise<T>;
1785
- /**
1786
- * Wrap a batch operation with error boundary
1787
- */
1788
- withBatchErrorBoundary<T>(operations: Array<() => Promise<T>>, _context?: {
1789
- operationName?: string;
1790
- }): Promise<T[]>;
1791
- }
1792
-
1793
- type GeneratorInput = {
1794
- schemas: TypeSchema[];
1795
- index: TypeSchemaIndex;
591
+ staticSourceDir?: string;
592
+ targetNamespace: string;
1796
593
  };
1797
- /**
1798
- * Abstract base generator class with comprehensive functionality
1799
- *
1800
- * Provides common functionality for all generators including:
1801
- * - Schema validation and processing
1802
- * - File management with fluent API
1803
- * - Template processing
1804
- * - Error handling and recovery
1805
- * - Progress monitoring
1806
- * - Performance optimization
1807
- */
1808
- declare abstract class BaseGenerator<TOptions extends BaseGeneratorOptions = BaseGeneratorOptions, TResult extends GeneratedFile[] = GeneratedFile[]> {
1809
- /** Validated and merged options */
1810
- protected options: Required<TOptions>;
1811
- /** Logger instance for this generator */
1812
- protected readonly logger: CodegenLogger;
1813
- /** File manager for all file operations */
1814
- protected readonly fileManager: FileManager;
1815
- /** Template engine for content generation (optional) */
1816
- protected readonly templateEngine?: TemplateEngine;
1817
- /** Language-specific type mapper */
1818
- protected readonly typeMapper: TypeMapper;
1819
- /** Enhanced error handler for comprehensive error reporting */
1820
- protected readonly errorHandler: ErrorHandler;
1821
- /** Error boundary for catching and handling all generator errors */
1822
- protected readonly errorBoundary: GeneratorErrorBoundary;
1823
- /** Progress callback if provided */
1824
- private progressCallback?;
1825
- /** Generated files tracking */
1826
- private generatedFiles;
1827
- /** Generation start time for performance metrics */
1828
- private generationStartTime;
1829
- /** Cache for expensive operations */
1830
- private readonly cache;
1831
- constructor(options: TOptions);
1832
- /**
1833
- * Get the name of the target language (e.g., "TypeScript", "Python", "Rust")
1834
- */
1835
- protected abstract getLanguageName(): string;
1836
- /**
1837
- * Get the file extension for the target language (e.g., ".ts", ".py", ".rs")
1838
- */
1839
- protected abstract getFileExtension(): string;
1840
- /**
1841
- * Create a language-specific type mapper
1842
- */
1843
- protected abstract createTypeMapper(): TypeMapper;
1844
- /**
1845
- * Generate content for a single schema
1846
- * @param schema - The TypeSchema to generate code for
1847
- * @param context - Additional context for generation
1848
- */
1849
- protected abstract generateSchemaContent(schema: TypeSchema, context: TemplateContext): Promise<string>;
1850
- /**
1851
- * Validate generated content before writing
1852
- * @param content - The generated content
1853
- * @param context - The generation context
1854
- */
1855
- protected abstract validateContent(content: string, context: TemplateContext): Promise<void>;
1856
- /**
1857
- * Filter and sort schemas with language-specific logic
1858
- * @param schemas - Input schemas
1859
- */
1860
- protected abstract filterAndSortSchemas(schemas: TypeSchema[]): TypeSchema[];
1861
- /**
1862
- * Get generator capabilities - can be overridden for introspection
1863
- */
1864
- getCapabilities(): GeneratorCapabilities;
1865
- /**
1866
- * Create file manager instance - can be overridden for custom file handling
1867
- */
1868
- protected createFileManager(): FileManager;
1869
- /**
1870
- * Create template engine instance - can be overridden for custom templates
1871
- * Returns undefined if template engine is not needed
1872
- */
1873
- protected createTemplateEngine(): TemplateEngine | undefined;
1874
- /**
1875
- * Generate code from TypeSchema documents
1876
- * This is the main method that orchestrates the entire generation process
1877
- * @param schemas - Array of TypeSchema documents
1878
- */
1879
- generate({ schemas }: GeneratorInput): Promise<TResult>;
1880
- /**
1881
- * Generate and return content without writing files (useful for testing)
1882
- * @param schemas - Array of TypeSchema documents
1883
- */
1884
- build(schemas: TypeSchema[]): Promise<TResult>;
1885
- /**
1886
- * Create a file builder for fluent file generation
1887
- * @param filename - Name of the file to create
1888
- */
1889
- file(filename: string): FileBuilder;
1890
- /**
1891
- * Create a directory builder for batch operations
1892
- * @param path - Directory path relative to output directory
1893
- */
1894
- directory(path: string): DirectoryBuilder;
1895
- /**
1896
- * Create an index file builder
1897
- * @param directory - Directory to create index for
1898
- */
1899
- index(directory?: string): IndexBuilder;
1900
- /**
1901
- * Set progress callback for monitoring generation
1902
- * @param callback - Progress callback function
1903
- */
1904
- onProgress(callback: ProgressCallback): this;
1905
- /**
1906
- * Validate generator configuration
1907
- */
1908
- private validateConfiguration;
1909
- /**
1910
- * Merge options with defaults
1911
- */
1912
- private mergeWithDefaults;
1913
- /**
1914
- * Validate schemas before processing
1915
- */
1916
- private validateSchemas;
1917
- /**
1918
- * Validate individual schema
1919
- */
1920
- protected validateSchema(schema: TypeSchema): Promise<void>;
1921
- /**
1922
- * Detect circular references in schema dependencies
1923
- */
1924
- private detectCircularReferences;
1925
- /**
1926
- * Generate files from processed schemas
1927
- */
1928
- private generateFiles;
1929
- /**
1930
- * Generate a single file from a schema
1931
- */
1932
- private generateFileForSchema;
1933
- /**
1934
- * Ensure filename has correct extension
1935
- */
1936
- private ensureFileExtension;
1937
- /**
1938
- * Extract exported symbols from generated content
1939
- * Can be overridden by language-specific implementations
1940
- */
1941
- protected extractExports(content: string): string[];
1942
- /**
1943
- * Report progress to callback if provided
1944
- */
1945
- protected reportProgress(phase: "validation" | "generation" | "writing" | "complete", current: number, total: number, message?: string, schema?: TypeSchema): void;
1946
- /**
1947
- * Run post-generation hooks
1948
- * Can be overridden to add custom post-processing
1949
- */
1950
- protected runPostGenerationHooks(): Promise<void>;
1951
- /**
1952
- * Get cached value or compute and cache it
1953
- */
1954
- protected getCachedOrCompute<T>(key: string, computeFn: () => T | Promise<T>): T | Promise<T>;
1955
- /**
1956
- * Clear internal cache
1957
- */
1958
- protected clearCache(): void;
1959
- /**
1960
- * Get generation statistics
1961
- */
1962
- getGenerationStats(): {
1963
- filesGenerated: number;
1964
- totalSize: number;
1965
- averageFileSize: number;
1966
- generationTime: number;
1967
- averageTimePerFile: number;
1968
- cacheHitRate: number;
1969
- };
1970
- }
1971
-
1972
- /**
1973
- * Abstract base class for language-specific type mapping
1974
- *
1975
- * This provides the interface that all language generators must implement
1976
- * to convert FHIR TypeSchema types into their target language types.
1977
- */
1978
-
1979
- /**
1980
- * Configuration for type mapping behavior
1981
- */
1982
- interface TypeMapperOptions {
1983
- /** Whether to generate nullable types (e.g., T | null) */
1984
- generateNullable?: boolean;
1985
- /** Whether to use strict type checking */
1986
- strictTypes?: boolean;
1987
- /** Custom type mappings */
1988
- customMappings?: Record<string, string>;
1989
- /** Whether to generate array types or use generic collections */
1990
- preferArraySyntax?: boolean;
1991
- /** Naming convention strategy */
1992
- namingConvention?: "camelCase" | "PascalCase" | "snake_case" | "kebab-case";
1993
- }
1994
-
1995
- /**
1996
- * TypeScript-specific type mapper implementation
1997
- */
1998
-
1999
- /**
2000
- * TypeScript-specific options
2001
- */
2002
- interface TypeScriptTypeMapperOptions extends TypeMapperOptions {
2003
- /** Whether to use 'unknown' or 'any' for unmapped types */
2004
- preferUnknown?: boolean;
2005
- /** Whether to generate branded types for primitives */
2006
- useBrandedTypes?: boolean;
2007
- /** Whether to use 'undefined' or 'null' for optional types */
2008
- preferUndefined?: boolean;
2009
- /** Module format for imports */
2010
- moduleFormat?: "esm" | "commonjs";
2011
- }
2012
-
2013
- /**
2014
- * Modern TypeScript Generator built on BaseGenerator
2015
- *
2016
- * This is the new, clean implementation that replaces the monolithic typescript.ts generator.
2017
- * Built using the BaseGenerator architecture with TypeMapper, TemplateEngine, and FileManager.
2018
- */
2019
-
2020
- /**
2021
- * TypeScript-specific generator options
2022
- */
2023
- interface TypeScriptGeneratorOptions extends BaseGeneratorOptions {
2024
- /** Module format for imports/exports */
2025
- moduleFormat?: "esm" | "cjs";
2026
- /** Whether to generate index files */
2027
- generateIndex?: boolean;
2028
- /** Include JSDoc documentation */
2029
- includeDocuments?: boolean;
2030
- /** Naming convention for types */
2031
- namingConvention?: "PascalCase" | "camelCase";
2032
- /** Include FHIR extensions */
2033
- includeExtensions?: boolean;
2034
- /** Include FHIR profiles */
2035
- includeProfiles?: boolean;
2036
- /** Generate value set files (default: false) */
2037
- generateValueSets?: boolean;
2038
- /** Include helper validation functions (default: false) */
2039
- includeValueSetHelpers?: boolean;
2040
- /**
2041
- * Which binding strengths to generate value sets for
2042
- * Only used when valueSetMode is 'custom'
2043
- * @default ['required']
2044
- */
2045
- valueSetStrengths?: ("required" | "preferred" | "extensible" | "example")[];
2046
- /**
2047
- * Directory name for value set files (relative to outputDir)
2048
- * @default 'valuesets'
2049
- */
2050
- valueSetDirectory?: string;
2051
- /**
2052
- * Value set generation mode
2053
- * - 'all': Generate for all binding strengths with enums
2054
- * - 'required-only': Generate only for required bindings (safe default)
2055
- * - 'custom': Use valueSetStrengths array to control
2056
- * @default 'required-only'
2057
- */
2058
- valueSetMode?: "all" | "required-only" | "custom";
2059
- /** Type mapper options */
2060
- typeMapperOptions?: TypeScriptTypeMapperOptions;
2061
- }
2062
- /**
2063
- * Result of generating a single TypeScript file
2064
- */
2065
- interface GeneratedTypeScript {
2066
- content: string;
2067
- imports: Map<string, string>;
2068
- exports: string[];
2069
- filename: string;
2070
- }
2071
- /**
2072
- * Modern TypeScript Generator
2073
- *
2074
- * Generates clean, type-safe TypeScript interfaces from FHIR TypeSchema documents.
2075
- * Uses the new BaseGenerator architecture for maintainability and extensibility.
2076
- */
2077
- declare class TypeScriptGenerator extends BaseGenerator<TypeScriptGeneratorOptions, GeneratedFile[]> {
2078
- private readonly resourceTypes;
2079
- private collectedValueSets;
2080
- private get tsOptions();
2081
- protected getLanguageName(): string;
2082
- protected getFileExtension(): string;
2083
- protected createTypeMapper(): TypeMapper;
2084
- protected generateSchemaContent(schema: TypeSchema, _context: TemplateContext): Promise<string>;
2085
- protected filterAndSortSchemas(schemas: TypeSchema[]): TypeSchema[];
2086
- protected validateContent(content: string, context: TemplateContext): Promise<void>;
2087
- /**
2088
- * Transform multiple schemas into TypeScript
2089
- */
2090
- transformSchemas(schemas: TypeSchema[]): Promise<GeneratedTypeScript[]>;
2091
- /**
2092
- * Transform a single schema into TypeScript
2093
- */
2094
- transformSchema(schema: TypeSchema): Promise<GeneratedTypeScript | undefined>;
2095
- /**
2096
- * Check if a binding schema should generate a value set file
2097
- */
2098
- private shouldGenerateValueSet;
2099
- /**
2100
- * Collect value sets from schemas that should generate value set files
2101
- */
2102
- private collectValueSets;
2103
- /**
2104
- * Check if a field binding should use a value set type
2105
- */
2106
- private shouldUseValueSetType;
2107
- /**
2108
- * Get the TypeScript type name for a binding
2109
- */
2110
- private getValueSetTypeName;
2111
- /**
2112
- * Check if a field has enum values that should be inlined
2113
- */
2114
- private shouldUseInlineEnum;
2115
- /**
2116
- * Generate inline enum type from field enum values
2117
- */
2118
- private generateInlineEnumType;
2119
- private shouldSkipSchema;
2120
- private getFilenameForSchema;
2121
- private extractImportsFromContent;
2122
- private extractExportsFromContent;
2123
- /**
2124
- * Generate special Reference interface with generics
2125
- */
2126
- private generateReferenceInterface;
2127
- /**
2128
- * Generate TypeScript interface directly without templates
2129
- */
2130
- private generateTypeScriptInterface;
2131
- /**
2132
- * Collect import dependencies from a field
2133
- */
2134
- private collectFieldImports;
2135
- /**
2136
- * Extract resource types from reference field constraints
2137
- */
2138
- private extractReferenceTypes;
2139
- /**
2140
- * Generate nested type interface
2141
- */
2142
- private generateNestedTypeInterface;
2143
- /**
2144
- * Capitalize first letter of string
2145
- */
2146
- private capitalizeFirst;
2147
- /**
2148
- * Generate field lines (handles polymorphic fields by expanding them)
2149
- */
2150
- private generateFieldLines;
2151
- /**
2152
- * Generate a single field line
2153
- */
2154
- private generateFieldLine;
2155
- /**
2156
- * Extract exported symbols from TypeScript content
2157
- */
2158
- protected extractExports(content: string): string[];
2159
- /**
2160
- * Set output directory for compatibility with API builder
2161
- */
2162
- setOutputDir(directory: string): void;
2163
- /**
2164
- * Update generator options for compatibility with API builder
2165
- */
2166
- setOptions(options: Partial<TypeScriptGeneratorOptions>): void;
2167
- /**
2168
- * Get current options for compatibility with API builder
2169
- */
2170
- getOptions(): TypeScriptGeneratorOptions;
2171
- /**
2172
- * Override generate to clean directory first
2173
- */
2174
- generate(input: GeneratorInput): Promise<GeneratedFile[]>;
2175
- /**
2176
- * Run post-generation hooks - generate utility files
2177
- */
2178
- protected runPostGenerationHooks(): Promise<void>;
2179
- /**
2180
- * Generate utilities.ts file with ResourceType union
2181
- */
2182
- private generateUtilitiesFile;
2183
- /**
2184
- * Generate a complete value set TypeScript file
2185
- */
2186
- private generateValueSetFile;
2187
- /**
2188
- * Create valuesets directory and generate all value set files
2189
- */
2190
- private generateValueSetFiles;
2191
- /**
2192
- * Generate index.ts file that re-exports all value sets
2193
- */
2194
- private generateValueSetIndexFile;
2195
- /**
2196
- * Generate main types/index.ts file that exports all types and value sets
2197
- */
2198
- private generateMainIndexFile;
2199
- }
2200
594
 
2201
- 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 };
595
+ 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 };