@atomic-ehr/codegen 0.0.1-canary.20251006070905.fb6ed98 → 0.0.1-canary.20251006094042.7f0be72

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/cli/index.js +45 -124
  2. package/dist/index.d.ts +2130 -62
  3. package/dist/index.js +5865 -84
  4. package/dist/index.js.map +1 -0
  5. package/package.json +3 -7
  6. package/dist/api/builder.d.ts +0 -154
  7. package/dist/api/builder.js +0 -341
  8. package/dist/api/generators/base/BaseGenerator.d.ts +0 -186
  9. package/dist/api/generators/base/BaseGenerator.js +0 -565
  10. package/dist/api/generators/base/FileManager.d.ts +0 -88
  11. package/dist/api/generators/base/FileManager.js +0 -202
  12. package/dist/api/generators/base/PythonTypeMapper.d.ts +0 -16
  13. package/dist/api/generators/base/PythonTypeMapper.js +0 -71
  14. package/dist/api/generators/base/TemplateEngine.d.ts +0 -126
  15. package/dist/api/generators/base/TemplateEngine.js +0 -133
  16. package/dist/api/generators/base/TypeMapper.d.ts +0 -129
  17. package/dist/api/generators/base/TypeMapper.js +0 -153
  18. package/dist/api/generators/base/TypeScriptTypeMapper.d.ts +0 -51
  19. package/dist/api/generators/base/TypeScriptTypeMapper.js +0 -232
  20. package/dist/api/generators/base/builders/DirectoryBuilder.d.ts +0 -99
  21. package/dist/api/generators/base/builders/DirectoryBuilder.js +0 -215
  22. package/dist/api/generators/base/builders/FileBuilder.d.ts +0 -160
  23. package/dist/api/generators/base/builders/FileBuilder.js +0 -406
  24. package/dist/api/generators/base/builders/IndexBuilder.d.ts +0 -126
  25. package/dist/api/generators/base/builders/IndexBuilder.js +0 -290
  26. package/dist/api/generators/base/enhanced-errors.d.ts +0 -84
  27. package/dist/api/generators/base/enhanced-errors.js +0 -259
  28. package/dist/api/generators/base/error-handler.d.ts +0 -89
  29. package/dist/api/generators/base/error-handler.js +0 -243
  30. package/dist/api/generators/base/errors.d.ts +0 -251
  31. package/dist/api/generators/base/errors.js +0 -692
  32. package/dist/api/generators/base/index.d.ts +0 -99
  33. package/dist/api/generators/base/index.js +0 -160
  34. package/dist/api/generators/base/types.d.ts +0 -433
  35. package/dist/api/generators/base/types.js +0 -12
  36. package/dist/api/generators/types.d.ts +0 -53
  37. package/dist/api/generators/types.js +0 -4
  38. package/dist/api/generators/typescript.d.ts +0 -190
  39. package/dist/api/generators/typescript.js +0 -819
  40. package/dist/api/index.d.ts +0 -51
  41. package/dist/api/index.js +0 -50
  42. package/dist/cli/commands/generate/typescript.d.ts +0 -10
  43. package/dist/cli/commands/generate/typescript.js +0 -52
  44. package/dist/cli/commands/generate.d.ts +0 -15
  45. package/dist/cli/commands/generate.js +0 -159
  46. package/dist/cli/commands/index.d.ts +0 -29
  47. package/dist/cli/commands/index.js +0 -100
  48. package/dist/cli/commands/typeschema/generate.d.ts +0 -19
  49. package/dist/cli/commands/typeschema/generate.js +0 -124
  50. package/dist/cli/commands/typeschema.d.ts +0 -10
  51. package/dist/cli/commands/typeschema.js +0 -47
  52. package/dist/cli/index.d.ts +0 -9
  53. package/dist/cli/utils/log.d.ts +0 -10
  54. package/dist/cli/utils/log.js +0 -23
  55. package/dist/cli/utils/prompts.d.ts +0 -56
  56. package/dist/cli/utils/prompts.js +0 -202
  57. package/dist/cli/utils/spinner.d.ts +0 -110
  58. package/dist/cli/utils/spinner.js +0 -266
  59. package/dist/config.d.ts +0 -217
  60. package/dist/config.js +0 -591
  61. package/dist/logger.d.ts +0 -157
  62. package/dist/logger.js +0 -281
  63. package/dist/typeschema/cache.d.ts +0 -80
  64. package/dist/typeschema/cache.js +0 -239
  65. package/dist/typeschema/core/binding.d.ts +0 -11
  66. package/dist/typeschema/core/binding.js +0 -143
  67. package/dist/typeschema/core/field-builder.d.ts +0 -12
  68. package/dist/typeschema/core/field-builder.js +0 -123
  69. package/dist/typeschema/core/identifier.d.ts +0 -13
  70. package/dist/typeschema/core/identifier.js +0 -94
  71. package/dist/typeschema/core/nested-types.d.ts +0 -9
  72. package/dist/typeschema/core/nested-types.js +0 -94
  73. package/dist/typeschema/core/transformer.d.ts +0 -11
  74. package/dist/typeschema/core/transformer.js +0 -235
  75. package/dist/typeschema/generator.d.ts +0 -43
  76. package/dist/typeschema/generator.js +0 -264
  77. package/dist/typeschema/index.d.ts +0 -15
  78. package/dist/typeschema/index.js +0 -15
  79. package/dist/typeschema/parser.d.ts +0 -79
  80. package/dist/typeschema/parser.js +0 -274
  81. package/dist/typeschema/profile/processor.d.ts +0 -14
  82. package/dist/typeschema/profile/processor.js +0 -262
  83. package/dist/typeschema/register.d.ts +0 -21
  84. package/dist/typeschema/register.js +0 -117
  85. package/dist/typeschema/types.d.ts +0 -240
  86. package/dist/typeschema/types.js +0 -19
  87. package/dist/utils/codegen-logger.d.ts +0 -102
  88. package/dist/utils/codegen-logger.js +0 -196
  89. package/dist/utils.d.ts +0 -22
  90. package/dist/utils.js +0 -42
package/dist/index.d.ts CHANGED
@@ -1,82 +1,2150 @@
1
+ import { CanonicalManager } from '@atomic-ehr/fhir-canonical-manager';
2
+ import * as FS from '@atomic-ehr/fhirschema';
3
+ import { FHIRSchema, StructureDefinition } from '@atomic-ehr/fhirschema';
4
+
1
5
  /**
2
- * Main entry point for the @atomic-ehr/codegen library
6
+ * New Config Schema for High-Level API
3
7
  *
4
- * ## Overview
8
+ * Simple configuration system compatible ONLY with the new high-level APIBuilder.
9
+ * All legacy config functionality has been removed.
10
+ */
11
+ /**
12
+ * TypeScript generator configuration options
13
+ */
14
+ interface TypeScriptGeneratorConfig {
15
+ moduleFormat?: "esm" | "cjs";
16
+ generateIndex?: boolean;
17
+ includeDocuments?: boolean;
18
+ namingConvention?: "PascalCase" | "camelCase";
19
+ strictMode?: boolean;
20
+ includeProfiles?: boolean;
21
+ includeExtensions?: boolean;
22
+ includeCodeSystems?: boolean;
23
+ includeOperations?: boolean;
24
+ /** Generate individual TypeScript files for value sets (default: false) */
25
+ generateValueSets?: boolean;
26
+ /** Include helper validation functions in value set files (default: false) */
27
+ includeValueSetHelpers?: boolean;
28
+ /** Which binding strengths to generate value sets for (default: ['required']) */
29
+ valueSetStrengths?: ("required" | "preferred" | "extensible" | "example")[];
30
+ /** Directory name for value set files (relative to outputDir) (default: 'valuesets') */
31
+ valueSetDirectory?: string;
32
+ /** Value set generation mode (default: 'required-only') */
33
+ valueSetMode?: "all" | "required-only" | "custom";
34
+ fhirVersion?: "R4" | "R5";
35
+ resourceTypes?: string[];
36
+ maxDepth?: number;
37
+ profileOptions?: {
38
+ generateKind?: "interface" | "type" | "both";
39
+ includeConstraints?: boolean;
40
+ includeDocumentation?: boolean;
41
+ strictMode?: boolean;
42
+ subfolder?: string;
43
+ };
44
+ generateBuilders?: boolean;
45
+ builderOptions?: {
46
+ includeValidation?: boolean;
47
+ includeFactoryMethods?: boolean;
48
+ includeInterfaces?: boolean;
49
+ generateNestedBuilders?: boolean;
50
+ includeHelperMethods?: boolean;
51
+ supportPartialBuild?: boolean;
52
+ includeJSDoc?: boolean;
53
+ generateFactories?: boolean;
54
+ includeTypeGuards?: boolean;
55
+ handleChoiceTypes?: boolean;
56
+ generateArrayHelpers?: boolean;
57
+ };
58
+ validatorOptions?: {
59
+ includeCardinality?: boolean;
60
+ includeTypes?: boolean;
61
+ includeConstraints?: boolean;
62
+ includeInvariants?: boolean;
63
+ validateRequired?: boolean;
64
+ allowAdditional?: boolean;
65
+ strictValidation?: boolean;
66
+ collectMetrics?: boolean;
67
+ generateAssertions?: boolean;
68
+ generatePartialValidators?: boolean;
69
+ optimizePerformance?: boolean;
70
+ includeJSDoc?: boolean;
71
+ generateCompositeValidators?: boolean;
72
+ };
73
+ guardOptions?: {
74
+ includeRuntimeValidation?: boolean;
75
+ includeErrorMessages?: boolean;
76
+ treeShakeable?: boolean;
77
+ targetTSVersion?: "3.8" | "4.0" | "4.5" | "5.0";
78
+ strictGuards?: boolean;
79
+ includeNullChecks?: boolean;
80
+ verbose?: boolean;
81
+ };
82
+ }
83
+ /**
84
+ * TypeSchema Configuration
85
+ * Controls TypeSchema generation and caching behavior
86
+ */
87
+ interface TypeSchemaConfig {
88
+ /** Enable persistent caching of generated TypeSchemas */
89
+ enablePersistence?: boolean;
90
+ /** Directory to store cached TypeSchemas (relative to outputDir) */
91
+ cacheDir?: string;
92
+ /** Maximum age of cached schemas in milliseconds before regeneration */
93
+ maxAge?: number;
94
+ /** Whether to validate cached schemas before reuse */
95
+ validateCached?: boolean;
96
+ /** Force regeneration of schemas even if cached */
97
+ forceRegenerate?: boolean;
98
+ /** Share cache across multiple codegen runs */
99
+ shareCache?: boolean;
100
+ /** Cache key prefix for namespacing */
101
+ cacheKeyPrefix?: string;
102
+ /** Only generate TypeSchemas for specific ResourceTypes (treeshaking) */
103
+ treeshake?: string[];
104
+ /** Generate single TypeSchema file instead of multiple files */
105
+ singleFile?: boolean;
106
+ /** Profile packages configuration */
107
+ profiles?: {
108
+ /** Auto-detect profiles in packages */
109
+ autoDetect?: boolean;
110
+ };
111
+ }
112
+ /**
113
+ * Main configuration schema for the new high-level API
114
+ */
115
+ interface Config {
116
+ outputDir?: string;
117
+ verbose?: boolean;
118
+ overwrite?: boolean;
119
+ validate?: boolean;
120
+ cache?: boolean;
121
+ typescript?: TypeScriptGeneratorConfig;
122
+ typeSchema?: TypeSchemaConfig;
123
+ packages?: string[];
124
+ files?: string[];
125
+ $schema?: string;
126
+ }
127
+ /**
128
+ * Default configuration values
129
+ */
130
+ declare const DEFAULT_CONFIG: Required<Config>;
131
+ /**
132
+ * Configuration file names to search for
133
+ */
134
+ declare const CONFIG_FILE_NAMES: string[];
135
+ /**
136
+ * Validation error interface
137
+ */
138
+ interface ConfigValidationError {
139
+ path: string;
140
+ message: string;
141
+ value?: unknown;
142
+ }
143
+ /**
144
+ * Configuration validation result
145
+ */
146
+ interface ConfigValidationResult {
147
+ valid: boolean;
148
+ errors: ConfigValidationError[];
149
+ warnings: string[];
150
+ config?: Config;
151
+ }
152
+ /**
153
+ * Simple configuration validator
154
+ */
155
+ declare class ConfigValidator {
156
+ /**
157
+ * Validate a configuration object
158
+ */
159
+ validate(config: unknown): ConfigValidationResult;
160
+ private validateTypeScriptConfig;
161
+ private validateValidatorOptions;
162
+ private validateGuardOptions;
163
+ private validateProfileOptions;
164
+ private validateTypeSchemaConfig;
165
+ }
166
+ /**
167
+ * Configuration loader with autoloading capabilities
168
+ */
169
+ declare class ConfigLoader {
170
+ private validator;
171
+ /**
172
+ * Auto-load configuration from the current working directory
173
+ */
174
+ autoload(workingDir?: string): Promise<Config>;
175
+ /**
176
+ * Load configuration from a specific file
177
+ */
178
+ loadFromFile(filePath: string): Promise<Config>;
179
+ /**
180
+ * Find configuration file in the given directory
181
+ */
182
+ private findConfigFile;
183
+ /**
184
+ * Merge user config with defaults
185
+ */
186
+ private mergeWithDefaults;
187
+ }
188
+ /**
189
+ * Global config loader instance
190
+ */
191
+ declare const configLoader: ConfigLoader;
192
+ /**
193
+ * Convenience function to auto-load configuration
194
+ */
195
+ declare function loadConfig(workingDir?: string): Promise<Config>;
196
+ /**
197
+ * Type guard to check if an object is a valid Config
198
+ */
199
+ declare function isConfig(obj: unknown): obj is Config;
200
+ /**
201
+ * Define configuration with type safety and IntelliSense support.
202
+ * Similar to Vite's defineConfig function pattern.
5
203
  *
6
- * atomic-codegen is a comprehensive code generation toolkit for FHIR healthcare standards,
7
- * designed with TypeSchema as the intermediate format for maximum flexibility and type safety.
204
+ * @example
205
+ * ```typescript
206
+ * import { defineConfig } from "@atomic-ehr/codegen";
8
207
  *
9
- * ## Key Features
208
+ * export default defineConfig({
209
+ * outputDir: "./generated",
210
+ * packages: [
211
+ * "hl7.fhir.r4.core@4.0.1",
212
+ * "hl7.fhir.us.core@6.1.0"
213
+ * ],
214
+ * typescript: {
215
+ * generateIndex: true,
216
+ * strictMode: true
217
+ * }
218
+ * });
219
+ * ```
220
+ */
221
+ declare function defineConfig(config: Config): Config;
222
+
223
+ /**
224
+ * CodeGen Logger
10
225
  *
11
- * - **🔥 FHIR R4/R5 Support**: Complete FHIR resource and profile generation
12
- * - **🇺🇸 US Core Profiles**: Built-in support for US healthcare implementation guides
13
- * - **📋 TypeSchema Integration**: Uses TypeSchema as universal intermediate format
14
- * - **🎯 Type Safety**: Full TypeScript support with runtime validation
15
- * - **⚡ Performance**: Built with Bun for maximum speed
16
- * - **🏗️ Extensible**: Plugin architecture for custom generators
226
+ * Clean, colorful logging designed for code generation tools
227
+ */
228
+ interface LogOptions {
229
+ prefix?: string;
230
+ timestamp?: boolean;
231
+ verbose?: boolean;
232
+ }
233
+ /**
234
+ * Simple code generation logger with pretty colors and clean formatting
235
+ */
236
+ declare class CodegenLogger {
237
+ private options;
238
+ constructor(options?: LogOptions);
239
+ private formatMessage;
240
+ /**
241
+ * Success message with checkmark
242
+ */
243
+ success(message: string): void;
244
+ /**
245
+ * Error message with X mark
246
+ */
247
+ error(message: string, error?: Error): void;
248
+ /**
249
+ * Warning message with warning sign
250
+ */
251
+ warn(message: string): void;
252
+ /**
253
+ * Info message with info icon
254
+ */
255
+ info(message: string): void;
256
+ /**
257
+ * Debug message (only shows in verbose mode)
258
+ */
259
+ debug(message: string): void;
260
+ /**
261
+ * Step message with rocket
262
+ */
263
+ step(message: string): void;
264
+ /**
265
+ * Progress message with clock
266
+ */
267
+ progress(message: string): void;
268
+ /**
269
+ * Plain message (no icon, just colored text)
270
+ */
271
+ plain(message: string, color?: (str: string) => string): void;
272
+ /**
273
+ * Dimmed/gray text for less important info
274
+ */
275
+ dim(message: string): void;
276
+ /**
277
+ * Create a child logger with a prefix
278
+ */
279
+ child(prefix: string): CodegenLogger;
280
+ /**
281
+ * Update options
282
+ */
283
+ configure(options: Partial<LogOptions>): void;
284
+ }
285
+
286
+ type Name = string & {
287
+ readonly __brand: unique symbol;
288
+ };
289
+ type CanonicalUrl = string & {
290
+ readonly __brand: unique symbol;
291
+ };
292
+ interface PackageMeta {
293
+ name: string;
294
+ version: string;
295
+ }
296
+ type RichFHIRSchema = Omit<FS.FHIRSchema, "package_meta" | "base" | "name" | "url"> & {
297
+ package_meta: PackageMeta;
298
+ name: Name;
299
+ url: CanonicalUrl;
300
+ base: CanonicalUrl;
301
+ };
302
+ type IdentifierBase = {
303
+ name: Name;
304
+ url: CanonicalUrl;
305
+ package: string;
306
+ version: string;
307
+ };
308
+ type PrimitiveIdentifier = {
309
+ kind: "primitive-type";
310
+ } & IdentifierBase;
311
+ type ComplexTypeIdentifier = {
312
+ kind: "complex-type";
313
+ } & IdentifierBase;
314
+ type ResourceIdentifier = {
315
+ kind: "resource";
316
+ } & IdentifierBase;
317
+ type ValueSetIdentifier = {
318
+ kind: "value-set";
319
+ } & IdentifierBase;
320
+ type NestedIdentifier = {
321
+ kind: "nested";
322
+ } & IdentifierBase;
323
+ type BindingIdentifier = {
324
+ kind: "binding";
325
+ } & IdentifierBase;
326
+ type ProfileIdentifier = {
327
+ kind: "profile";
328
+ } & IdentifierBase;
329
+ type LogicalIdentifier = {
330
+ kind: "logical";
331
+ } & IdentifierBase;
332
+ type Identifier = PrimitiveIdentifier | ComplexTypeIdentifier | ResourceIdentifier | NestedIdentifier | BindingIdentifier | ValueSetIdentifier | ProfileIdentifier | LogicalIdentifier;
333
+ type TypeSchema = RegularTypeSchema | PrimitiveTypeSchema | ValueSetTypeSchema | BindingTypeSchema | ProfileTypeSchema;
334
+ interface PrimitiveTypeSchema {
335
+ identifier: PrimitiveIdentifier;
336
+ description?: string;
337
+ base: Identifier;
338
+ dependencies?: Identifier[];
339
+ }
340
+ interface NestedType {
341
+ identifier: NestedIdentifier;
342
+ base: Identifier;
343
+ fields: Record<string, Field>;
344
+ }
345
+ interface ProfileTypeSchema {
346
+ identifier: ProfileIdentifier;
347
+ base: Identifier;
348
+ description?: string;
349
+ fields?: Record<string, Field>;
350
+ constraints?: Record<string, ProfileConstraint>;
351
+ extensions?: ProfileExtension[];
352
+ validation?: ValidationRule[];
353
+ dependencies?: Identifier[];
354
+ metadata?: ProfileMetadata;
355
+ nested?: NestedType[];
356
+ }
357
+ interface ProfileConstraint {
358
+ min?: number;
359
+ max?: string;
360
+ mustSupport?: boolean;
361
+ fixedValue?: any;
362
+ patternValue?: any;
363
+ binding?: {
364
+ strength: "required" | "extensible" | "preferred" | "example";
365
+ valueSet: string;
366
+ };
367
+ types?: Array<{
368
+ code: string;
369
+ profile?: string[];
370
+ targetProfile?: string[];
371
+ }>;
372
+ slicing?: {
373
+ discriminator: any[];
374
+ rules: string;
375
+ ordered?: boolean;
376
+ };
377
+ }
378
+ interface ProfileExtension {
379
+ path: string;
380
+ profile: string | string[];
381
+ min?: number;
382
+ max?: string;
383
+ mustSupport?: boolean;
384
+ }
385
+ interface ValidationRule {
386
+ path: string;
387
+ key: string;
388
+ severity: "error" | "warning" | "information";
389
+ human: string;
390
+ expression?: string;
391
+ }
392
+ interface ProfileMetadata {
393
+ publisher?: string;
394
+ contact?: any[];
395
+ copyright?: string;
396
+ purpose?: string;
397
+ experimental?: boolean;
398
+ date?: string;
399
+ jurisdiction?: any[];
400
+ package?: string;
401
+ }
402
+ interface RegularTypeSchema {
403
+ identifier: Identifier;
404
+ base?: Identifier;
405
+ description?: string;
406
+ fields?: {
407
+ [k: string]: Field;
408
+ };
409
+ nested?: NestedType[];
410
+ dependencies?: Identifier[];
411
+ }
412
+ interface RegularField {
413
+ type: Identifier;
414
+ reference?: Identifier[];
415
+ required?: boolean;
416
+ excluded?: boolean;
417
+ array?: boolean;
418
+ binding?: BindingIdentifier;
419
+ enum?: string[];
420
+ min?: number;
421
+ max?: number;
422
+ }
423
+ interface ChoiceFieldDeclaration {
424
+ choices: string[];
425
+ required?: boolean;
426
+ excluded?: boolean;
427
+ array?: boolean;
428
+ min?: number;
429
+ max?: number;
430
+ }
431
+ interface ChoiceFieldInstance {
432
+ choiceOf: string;
433
+ type: Identifier;
434
+ required?: boolean;
435
+ excluded?: boolean;
436
+ array?: boolean;
437
+ reference?: Identifier[];
438
+ binding?: BindingIdentifier;
439
+ enum?: string[];
440
+ min?: number;
441
+ max?: number;
442
+ }
443
+ type Concept = {
444
+ code: string;
445
+ display?: string;
446
+ system?: string;
447
+ };
448
+ interface ValueSetTypeSchema {
449
+ identifier: ValueSetIdentifier;
450
+ description?: string;
451
+ concept?: Concept[];
452
+ compose?: ValueSetCompose;
453
+ }
454
+ interface BindingTypeSchema {
455
+ identifier: BindingIdentifier;
456
+ description?: string;
457
+ type?: Identifier;
458
+ strength?: string;
459
+ enum?: string[];
460
+ valueset?: ValueSetIdentifier;
461
+ dependencies?: Identifier[];
462
+ }
463
+ type Field = RegularField | ChoiceFieldDeclaration | ChoiceFieldInstance;
464
+ interface TypeschemaGeneratorOptions {
465
+ verbose?: boolean;
466
+ logger?: CodegenLogger;
467
+ treeshake?: string[];
468
+ manager?: ReturnType<typeof CanonicalManager> | null;
469
+ }
470
+ type TypeschemaParserOptions = {
471
+ format?: "auto" | "ndjson" | "json";
472
+ validate?: boolean;
473
+ strict?: boolean;
474
+ };
475
+ type ValueSet = {
476
+ resourceType: "ValueSet";
477
+ id: string;
478
+ name?: string;
479
+ url?: string;
480
+ description?: string;
481
+ compose?: ValueSetCompose;
482
+ expansion?: {
483
+ contains: Concept[];
484
+ };
485
+ experimental?: boolean;
486
+ immutable?: boolean;
487
+ extension?: any[];
488
+ status?: string;
489
+ identifier?: any[];
490
+ title?: string;
491
+ publisher?: string;
492
+ version?: string;
493
+ meta?: any;
494
+ date?: string;
495
+ contact?: any;
496
+ };
497
+ type ValueSetCompose = {
498
+ include: {
499
+ concept?: Concept[];
500
+ system?: string;
501
+ filter?: {}[];
502
+ }[];
503
+ };
504
+ type RichValueSet = Omit<ValueSet, "name" | "url"> & {
505
+ package_meta: PackageMeta;
506
+ name?: Name;
507
+ url?: CanonicalUrl;
508
+ };
509
+
510
+ /**
511
+ * TypeSchema Cache System
17
512
  *
18
- * ## Quick Start
513
+ * Caching system for TypeSchema documents with both in-memory and persistent file-based storage.
514
+ */
515
+
516
+ /**
517
+ * TypeSchema Cache with optional persistent storage
518
+ */
519
+ declare class TypeSchemaCache {
520
+ private cache;
521
+ private config;
522
+ private cacheDir?;
523
+ constructor(config?: TypeSchemaConfig);
524
+ /**
525
+ * Store a schema in the cache
526
+ */
527
+ set(schema: TypeSchema): Promise<void>;
528
+ /**
529
+ * Retrieve a schema by identifier
530
+ */
531
+ get(identifier: Identifier): TypeSchema | null;
532
+ /**
533
+ * Retrieve a schema by URL
534
+ */
535
+ getByUrl(url: string): TypeSchema | null;
536
+ /**
537
+ * Check if a schema exists in cache
538
+ */
539
+ has(identifier: Identifier): boolean;
540
+ /**
541
+ * Check if a schema exists by URL
542
+ */
543
+ hasByUrl(url: string): boolean;
544
+ /**
545
+ * Delete a schema from cache
546
+ */
547
+ delete(identifier: Identifier): boolean;
548
+ /**
549
+ * Delete a schema by URL
550
+ */
551
+ deleteByUrl(url: string): boolean;
552
+ /**
553
+ * Get schemas by package
554
+ */
555
+ getByPackage(packageName: string): TypeSchema[];
556
+ /**
557
+ * Get schemas by kind
558
+ */
559
+ getByKind(kind: string): TypeSchema[];
560
+ /**
561
+ * Store multiple schemas
562
+ */
563
+ setMany(schemas: TypeSchema[]): void;
564
+ /**
565
+ * Clear all cached schemas
566
+ */
567
+ clear(): void;
568
+ /**
569
+ * Generate cache key for identifier
570
+ */
571
+ private generateKey;
572
+ /**
573
+ * Initialize cache directory if persistence is enabled
574
+ */
575
+ initialize(): Promise<void>;
576
+ /**
577
+ * Load all cached schemas from disk
578
+ */
579
+ private loadFromDisk;
580
+ /**
581
+ * Persist a schema to disk
582
+ */
583
+ private persistSchema;
584
+ /**
585
+ * Clear cache directory
586
+ */
587
+ clearDisk(): Promise<void>;
588
+ }
589
+
590
+ type Register = {
591
+ appendFs(fs: FHIRSchema): void;
592
+ ensureCanonicalUrl(name: string | Name | CanonicalUrl): CanonicalUrl;
593
+ resolveSd(canonicalUrl: CanonicalUrl): StructureDefinition | undefined;
594
+ resolveFs(canonicalUrl: CanonicalUrl): RichFHIRSchema | undefined;
595
+ resolveFsGenealogy(canonicalUrl: CanonicalUrl): RichFHIRSchema[];
596
+ allSd(): StructureDefinition[];
597
+ allFs(): RichFHIRSchema[];
598
+ allVs(): RichValueSet[];
599
+ resolveVs(canonicalUrl: CanonicalUrl): RichValueSet | undefined;
600
+ complexTypeDict(): Record<string, RichFHIRSchema>;
601
+ resolveAny(canonicalUrl: CanonicalUrl): any | undefined;
602
+ } & ReturnType<typeof CanonicalManager>;
603
+
604
+ /**
605
+ * TypeSchema Generator
19
606
  *
20
- * ```typescript
21
- * import { APIBuilder } from '@atomic-ehr/codegen';
607
+ * Generates TypeSchema documents from FHIR packages using fhrischema.
608
+ * Provides high-level API for converting FHIR Structure Definitions to TypeSchema format.
609
+ */
610
+
611
+ /**
612
+ * TypeSchema Generator class
22
613
  *
23
- * // High-level API for common workflows
24
- * const api = new APIBuilder();
614
+ * Main class for generating TypeSchema documents from FHIR packages.
615
+ * Leverages fhrischema for FHIR parsing and canonical manager for dependency resolution.
616
+ */
617
+ declare class TypeSchemaGenerator {
618
+ private manager;
619
+ private options;
620
+ private cacheConfig?;
621
+ private cache?;
622
+ private logger;
623
+ constructor(options?: TypeschemaGeneratorOptions, cacheConfig?: TypeSchemaConfig);
624
+ private initializeCache;
625
+ registerFromPackageMetas(packageMetas: PackageMeta[]): Promise<Register>;
626
+ generateFhirSchemas(structureDefinitions: StructureDefinition[]): FHIRSchema[];
627
+ generateValueSetSchemas(valueSets: any[], _packageInfo: PackageMeta): Promise<TypeSchema[]>;
628
+ generateFromPackage(packageName: string, packageVersion?: string): Promise<TypeSchema[]>;
629
+ /**
630
+ * Apply treeshaking to StructureDefinitions before FHIR schema transformation
631
+ * This is more efficient and includes smart reference handling
632
+ */
633
+ private applyStructureDefinitionTreeshaking;
634
+ private extractStructureDefinitionDependenciesWithReferences;
635
+ private extractResourceNameFromUrl;
636
+ }
637
+
638
+ /**
639
+ * TypeSchema Parser
25
640
  *
26
- * // Generate FHIR types from packages
27
- * await api
28
- * .fromFHIRPackages(['hl7.fhir.r4.core@4.0.1', 'hl7.fhir.us.core@6.1.0'])
29
- * .typescript('./src/types/fhir')
30
- * .withValidation()
31
- * .generate();
32
- * ```
641
+ * Parser for reading and manipulating TypeSchema documents from various formats.
642
+ * Supports both NDJSON and JSON formats with automatic format detection.
643
+ */
644
+
645
+ /**
646
+ * TypeSchema Parser class
33
647
  *
34
- * ## Architecture
648
+ * Provides functionality to read, parse, and manipulate TypeSchema documents
649
+ * from files or strings in various formats.
650
+ */
651
+ declare class TypeSchemaParser {
652
+ private options;
653
+ constructor(options?: TypeschemaParserOptions);
654
+ /**
655
+ * Parse TypeSchema from file
656
+ */
657
+ parseFromFile(filePath: string): Promise<TypeSchema[]>;
658
+ /**
659
+ * Parse TypeSchema from string content
660
+ */
661
+ parseFromString(content: string, format?: "ndjson" | "json"): Promise<TypeSchema[]>;
662
+ /**
663
+ * Parse multiple TypeSchema files
664
+ */
665
+ parseFromFiles(filePaths: string[]): Promise<TypeSchema[]>;
666
+ /**
667
+ * Parse a single TypeSchema object
668
+ */
669
+ parseSchema(schemaData: any): TypeSchema;
670
+ /**
671
+ * Find schemas by identifier
672
+ */
673
+ findByIdentifier(schemas: TypeSchema[], identifier: Partial<Identifier>): TypeSchema[];
674
+ /**
675
+ * Find schema by URL
676
+ */
677
+ findByUrl(schemas: TypeSchema[], url: string): TypeSchema | undefined;
678
+ /**
679
+ * Find schemas by kind
680
+ */
681
+ findByKind(schemas: TypeSchema[], kind: Identifier["kind"]): TypeSchema[];
682
+ /**
683
+ * Find schemas by package
684
+ */
685
+ findByPackage(schemas: TypeSchema[], packageName: string): TypeSchema[];
686
+ /**
687
+ * Get all dependencies from a schema
688
+ */
689
+ /**
690
+ * Resolve schema dependencies
691
+ */
692
+ /**
693
+ * Detect format from content or filename
694
+ */
695
+ private detectFormat;
696
+ /**
697
+ * Parse NDJSON format
698
+ */
699
+ private parseNDJSON;
700
+ /**
701
+ * Parse JSON format
702
+ */
703
+ private parseJSON;
704
+ /**
705
+ * Validate schemas
706
+ */
707
+ private validateSchemas;
708
+ /**
709
+ * Validate identifier structure
710
+ */
711
+ private isValidIdentifier;
712
+ /**
713
+ * Check if identifier matches criteria
714
+ */
715
+ private matchesIdentifier;
716
+ }
717
+
718
+ /**
719
+ * High-Level API Builder
35
720
  *
36
- * The library follows a three-stage architecture:
721
+ * Provides a fluent, chainable API for common codegen use cases with pre-built generators.
722
+ * This builder pattern allows users to configure generation in a declarative way.
723
+ */
724
+
725
+ /**
726
+ * Configuration options for the API builder
727
+ */
728
+ interface APIBuilderOptions {
729
+ outputDir?: string;
730
+ verbose?: boolean;
731
+ overwrite?: boolean;
732
+ validate?: boolean;
733
+ cache?: boolean;
734
+ typeSchemaConfig?: TypeSchemaConfig;
735
+ logger?: CodegenLogger;
736
+ manager?: ReturnType<typeof CanonicalManager> | null;
737
+ }
738
+ /**
739
+ * Progress callback for long-running operations
740
+ */
741
+ type ProgressCallback$1 = (phase: string, current: number, total: number, message?: string) => void;
742
+ /**
743
+ * Generation result information
744
+ */
745
+ interface GenerationResult {
746
+ success: boolean;
747
+ outputDir: string;
748
+ filesGenerated: string[];
749
+ errors: string[];
750
+ warnings: string[];
751
+ duration: number;
752
+ }
753
+ /**
754
+ * High-Level API Builder class
37
755
  *
38
- * 1. **Input**: FHIR packages, JSON Schema, or custom schemas
39
- * 2. **TypeSchema**: Universal intermediate representation
40
- * 3. **Output**: TypeScript, Python, Go, or custom target languages
756
+ * Provides a fluent interface for configuring and executing code generation
757
+ * from FHIR packages or TypeSchema documents.
758
+ */
759
+ declare class APIBuilder {
760
+ private schemas;
761
+ private options;
762
+ private generators;
763
+ private progressCallback?;
764
+ private cache?;
765
+ private pendingOperations;
766
+ private typeSchemaGenerator?;
767
+ private logger;
768
+ private typeSchemaConfig?;
769
+ constructor(options?: APIBuilderOptions);
770
+ /**
771
+ * Load TypeSchema from a FHIR package
772
+ */
773
+ fromPackage(packageName: string, version?: string): APIBuilder;
774
+ /**
775
+ * Load TypeSchema from files
776
+ */
777
+ fromFiles(...filePaths: string[]): APIBuilder;
778
+ /**
779
+ * Load TypeSchema from TypeSchema objects
780
+ */
781
+ fromSchemas(schemas: TypeSchema[]): APIBuilder;
782
+ /**
783
+ * Configure TypeScript generation
784
+ */
785
+ typescript(options?: {
786
+ moduleFormat?: "esm" | "cjs";
787
+ generateIndex?: boolean;
788
+ includeDocuments?: boolean;
789
+ namingConvention?: "PascalCase" | "camelCase";
790
+ includeExtensions?: boolean;
791
+ includeProfiles?: boolean;
792
+ generateValueSets?: boolean;
793
+ includeValueSetHelpers?: boolean;
794
+ valueSetStrengths?: ("required" | "preferred" | "extensible" | "example")[];
795
+ valueSetMode?: "all" | "required-only" | "custom";
796
+ valueSetDirectory?: string;
797
+ }): APIBuilder;
798
+ /**
799
+ * Set a progress callback for monitoring generation
800
+ */
801
+ onProgress(callback: ProgressCallback$1): APIBuilder;
802
+ /**
803
+ * Set the output directory for all generators
804
+ */
805
+ outputTo(directory: string): APIBuilder;
806
+ /**
807
+ * Enable/disable verbose logging
808
+ */
809
+ verbose(enabled?: boolean): APIBuilder;
810
+ /**
811
+ * Enable/disable validation
812
+ */
813
+ validate(enabled?: boolean): APIBuilder;
814
+ /**
815
+ * Execute the generation process
816
+ */
817
+ generate(): Promise<GenerationResult>;
818
+ /**
819
+ * Generate and return the results without writing to files
820
+ */
821
+ build(): Promise<{
822
+ typescript?: {
823
+ content: string;
824
+ filename: string;
825
+ }[];
826
+ }>;
827
+ /**
828
+ * Clear all configuration and start fresh
829
+ */
830
+ reset(): APIBuilder;
831
+ /**
832
+ * Get loaded schemas (for inspection)
833
+ */
834
+ getSchemas(): TypeSchema[];
835
+ /**
836
+ * Get configured generators (for inspection)
837
+ */
838
+ getGenerators(): string[];
839
+ private loadFromPackage;
840
+ private loadFromFiles;
841
+ private resolveSchemas;
842
+ private validateSchemas;
843
+ private executeGenerators;
844
+ private reportProgress;
845
+ }
846
+ /**
847
+ * Create a new API builder instance
848
+ */
849
+ declare function createAPI(options?: APIBuilderOptions): APIBuilder;
850
+ /**
851
+ * Create an API builder instance from a configuration object
852
+ */
853
+ declare function createAPIFromConfig(config: Config): APIBuilder;
854
+ /**
855
+ * Convenience function for quick TypeScript generation from a package
856
+ */
857
+ declare function generateTypesFromPackage(packageName: string, outputDir: string, options?: {
858
+ version?: string;
859
+ verbose?: boolean;
860
+ validate?: boolean;
861
+ }): Promise<GenerationResult>;
862
+ /**
863
+ * Convenience function for quick TypeScript generation from files
864
+ */
865
+ declare function generateTypesFromFiles(inputFiles: string[], outputDir: string, options?: {
866
+ verbose?: boolean;
867
+ validate?: boolean;
868
+ }): Promise<GenerationResult>;
869
+
870
+ /**
871
+ * Core types and interfaces for the base generator system
41
872
  *
42
- * ## Examples
873
+ * This module provides the foundational type definitions that all generators
874
+ * build upon, ensuring consistency and type safety across the system.
875
+ */
876
+
877
+ /**
878
+ * Base configuration options that all generators must support
879
+ * These options provide the minimum required configuration for any generator
880
+ */
881
+ interface BaseGeneratorOptions {
882
+ /** Output directory where generated files will be written */
883
+ outputDir: string;
884
+ /** Logger instance for tracking generation progress and errors */
885
+ logger?: CodegenLogger;
886
+ /** Whether to overwrite existing files (default: true) */
887
+ overwrite?: boolean;
888
+ /** Whether to validate schemas and generated content (default: true) */
889
+ validate?: boolean;
890
+ /** Enable detailed logging for debugging (default: false) */
891
+ verbose?: boolean;
892
+ /** Enable beginner-friendly error messages and guidance (default: false) */
893
+ beginnerMode?: boolean;
894
+ /** Format for error output: console, json, or structured (default: 'console') */
895
+ errorFormat?: "console" | "json" | "structured";
896
+ }
897
+ /**
898
+ * Language-specific type representation
899
+ * This interface standardizes how FHIR types are mapped to target languages
900
+ */
901
+ interface LanguageType {
902
+ /** The type string in the target language (e.g., "string", "number", "Patient") */
903
+ name: string;
904
+ /** Whether this is a primitive type that doesn't need imports */
905
+ isPrimitive: boolean;
906
+ /** Import path if this type needs to be imported from another module */
907
+ importPath?: string;
908
+ /** Generic parameters if this is a generic type (e.g., ["T", "K"] for Map<T,K>) */
909
+ generics?: string[];
910
+ /** Whether this type is nullable/optional in the target language */
911
+ nullable?: boolean;
912
+ /** Additional metadata specific to the target language */
913
+ metadata?: Record<string, unknown>;
914
+ }
915
+ /**
916
+ * Generated file metadata and content
917
+ * Represents a single generated file with all its associated information
918
+ */
919
+ interface GeneratedFile {
920
+ /** Full file system path where the file was/will be written */
921
+ path: string;
922
+ /** Filename only (without directory path) */
923
+ filename: string;
924
+ /** The generated content of the file */
925
+ content: string;
926
+ /** List of symbols exported from this file */
927
+ exports: string[];
928
+ /** File size in bytes */
929
+ size: number;
930
+ /** When this file was generated */
931
+ timestamp: Date;
932
+ /** Additional metadata about the generation process */
933
+ metadata?: {
934
+ /** Time taken to generate this file in milliseconds */
935
+ generationTime?: number;
936
+ /** Number of schemas processed for this file */
937
+ schemaCount?: number;
938
+ /** Template used to generate this file */
939
+ templateName?: string;
940
+ /** Any warnings generated during processing */
941
+ warnings?: string[];
942
+ };
943
+ }
944
+ /**
945
+ * Template context provided to template engines
946
+ * Contains all the data needed to render templates for code generation
947
+ */
948
+ interface TemplateContext {
949
+ /** The schema being processed */
950
+ schema: TypeSchema;
951
+ /** Type mapper for the target language */
952
+ typeMapper: TypeMapper;
953
+ /** Current file being generated */
954
+ filename: string;
955
+ /** Target language name (e.g., "TypeScript", "Python") */
956
+ language: string;
957
+ /** Generation timestamp in ISO format */
958
+ timestamp: string;
959
+ /** Import map for the current file */
960
+ imports?: Map<string, string>;
961
+ /** Export set for the current file */
962
+ exports?: Set<string>;
963
+ /** Additional context data that templates can use */
964
+ [key: string]: unknown;
965
+ }
966
+ /**
967
+ * File builder context passed to lifecycle hooks
968
+ * Provides access to file generation state during the build process
969
+ */
970
+ interface FileContext {
971
+ /** Name of the file being generated */
972
+ filename: string;
973
+ /** Current file content */
974
+ content: string;
975
+ /** Map of imports (symbol name -> import path) */
976
+ imports: Map<string, string>;
977
+ /** Set of exported symbols */
978
+ exports: Set<string>;
979
+ /** Additional metadata about the file */
980
+ metadata: Record<string, unknown>;
981
+ /** The schema that generated this file (if applicable) */
982
+ schema?: TypeSchema;
983
+ /** Template name used to generate this file (if applicable) */
984
+ templateName?: string;
985
+ }
986
+ /**
987
+ * Statistics about file operations
988
+ * Used for performance monitoring and optimization
989
+ */
990
+ interface FileStats {
991
+ /** File size in bytes */
992
+ size: number;
993
+ /** Time taken to generate content in milliseconds */
994
+ generationTime: number;
995
+ /** Time taken to write to disk in milliseconds */
996
+ writeTime: number;
997
+ /** Memory used during generation in bytes */
998
+ memoryUsed?: number;
999
+ /** Number of template renders performed */
1000
+ templateRenders?: number;
1001
+ }
1002
+ /**
1003
+ * Progress callback signature for monitoring generation
1004
+ * Allows consumers to track progress of long-running operations
1005
+ */
1006
+ type ProgressCallback = (
1007
+ /** Current phase of generation */
1008
+ phase: "validation" | "generation" | "writing" | "complete",
1009
+ /** Current item number being processed */
1010
+ current: number,
1011
+ /** Total number of items to process */
1012
+ total: number,
1013
+ /** Optional message describing current operation */
1014
+ message?: string,
1015
+ /** Schema being processed (if applicable) */
1016
+ schema?: TypeSchema) => void;
1017
+ /**
1018
+ * Lifecycle hook signatures for file operations
1019
+ * These hooks allow customization of the file generation process
1020
+ */
1021
+ /** Hook called before saving a file - can modify content or abort save */
1022
+ type BeforeSaveHook = (context: FileContext) => void | Promise<void>;
1023
+ /** Hook called after successfully saving a file */
1024
+ type AfterSaveHook = (filePath: string, stats: FileStats) => void | Promise<void>;
1025
+ /** Hook called when an error occurs during file operations */
1026
+ type ErrorHook = (error: Error, context: FileContext) => void | Promise<void>;
1027
+ /**
1028
+ * File builder configuration options
1029
+ * Controls how files are generated and processed
1030
+ */
1031
+ interface FileBuilderOptions {
1032
+ /** Template name to use for content generation */
1033
+ template?: string;
1034
+ /** Strategy for resolving import paths */
1035
+ importStrategy?: "auto" | "manual" | "none";
1036
+ /** Level of content validation to perform */
1037
+ validation?: "strict" | "loose" | "none";
1038
+ /** Enable pretty printing of generated content */
1039
+ prettify?: boolean;
1040
+ /** Custom formatting options */
1041
+ formatting?: {
1042
+ /** Number of spaces for indentation (default: 2) */
1043
+ indentSize?: number;
1044
+ /** Use tabs instead of spaces (default: false) */
1045
+ useTabs?: boolean;
1046
+ /** Maximum line length before wrapping (default: 100) */
1047
+ maxLineLength?: number;
1048
+ };
1049
+ /** File encoding (default: 'utf-8') */
1050
+ encoding?: BufferEncoding;
1051
+ }
1052
+ /**
1053
+ * Abstract base class for type mapping between FHIR and target languages
1054
+ * Each language-specific generator must implement this interface
1055
+ */
1056
+ declare abstract class TypeMapper {
1057
+ /**
1058
+ * Map a FHIR primitive type to the target language
1059
+ * @param fhirType - FHIR primitive type name (e.g., "string", "integer")
1060
+ * @returns Language-specific type representation
1061
+ */
1062
+ abstract mapPrimitive(fhirType: string): LanguageType;
1063
+ /**
1064
+ * Map a FHIR reference to the target language
1065
+ * @param targets - Array of possible reference targets
1066
+ * @returns Language-specific reference type
1067
+ */
1068
+ abstract mapReference(targets: Identifier[]): LanguageType;
1069
+ /**
1070
+ * Map an array type in the target language
1071
+ * @param elementType - The element type name
1072
+ * @returns Language-specific array type
1073
+ */
1074
+ abstract mapArray(elementType: string): LanguageType;
1075
+ /**
1076
+ * Map optional/nullable types
1077
+ * @param type - The base type
1078
+ * @param required - Whether the field is required
1079
+ * @returns Language-specific optional type
1080
+ */
1081
+ abstract mapOptional(type: string, required: boolean): LanguageType;
1082
+ /**
1083
+ * Map enumerated values to the target language
1084
+ * @param values - Array of possible values
1085
+ * @param name - Optional name for the enum type
1086
+ * @returns Language-specific enum type
1087
+ */
1088
+ abstract mapEnum(values: string[], name?: string): LanguageType;
1089
+ /**
1090
+ * Format a FHIR type name according to target language conventions
1091
+ * @param name - FHIR type name
1092
+ * @returns Formatted type name
1093
+ */
1094
+ abstract formatTypeName(name: string): string;
1095
+ /**
1096
+ * Format a field name according to target language conventions
1097
+ * @param name - FHIR field name
1098
+ * @returns Formatted field name
1099
+ */
1100
+ abstract formatFieldName(name: string): string;
1101
+ /**
1102
+ * Format a filename according to target language conventions
1103
+ * @param name - Base filename
1104
+ * @returns Formatted filename (without extension)
1105
+ */
1106
+ abstract formatFileName(name: string): string;
1107
+ /**
1108
+ * Map a complete TypeSchema identifier to target language type
1109
+ * @param identifier - FHIR type identifier
1110
+ * @returns Language-specific type representation
1111
+ */
1112
+ abstract mapType(identifier: Identifier): LanguageType;
1113
+ /**
1114
+ * Get import statement format for the target language
1115
+ * @param symbols - Symbols to import
1116
+ * @param from - Module to import from
1117
+ * @returns Formatted import statement
1118
+ */
1119
+ formatImport?(symbols: string[], from: string): string;
1120
+ /**
1121
+ * Get export statement format for the target language
1122
+ * @param symbols - Symbols to export
1123
+ * @returns Formatted export statement
1124
+ */
1125
+ formatExport?(symbols: string[]): string;
1126
+ }
1127
+ /**
1128
+ * Template engine interface
1129
+ * Abstraction for different template engines (Handlebars, etc.)
1130
+ */
1131
+ interface TemplateEngine {
1132
+ /**
1133
+ * Render a template with the given context
1134
+ * @param templateName - Name of the template to render
1135
+ * @param context - Data to pass to the template
1136
+ * @returns Rendered content
1137
+ */
1138
+ render(templateName: string, context: Record<string, unknown>): string;
1139
+ /**
1140
+ * Register a template
1141
+ * @param name - Template name
1142
+ * @param template - Template content or compiled template
1143
+ */
1144
+ registerTemplate(name: string, template: string | ((...args: any[]) => any)): void;
1145
+ /**
1146
+ * Register a helper function
1147
+ * @param name - Helper name
1148
+ * @param helper - Helper function
1149
+ */
1150
+ registerHelper(name: string, helper: (...args: any[]) => any): void;
1151
+ /**
1152
+ * Check if a template exists
1153
+ * @param name - Template name
1154
+ * @returns True if template exists
1155
+ */
1156
+ hasTemplate(name: string): boolean;
1157
+ /**
1158
+ * Get list of available templates
1159
+ * @returns Array of template names
1160
+ */
1161
+ getAvailableTemplates(): string[];
1162
+ }
1163
+ /**
1164
+ * Generator capabilities interface
1165
+ * Describes what a generator can do - used for introspection
1166
+ */
1167
+ interface GeneratorCapabilities {
1168
+ /** Programming language this generator targets */
1169
+ language: string;
1170
+ /** File extensions this generator produces */
1171
+ fileExtensions: string[];
1172
+ /** Whether this generator supports templates */
1173
+ supportsTemplates: boolean;
1174
+ /** Whether this generator supports custom type mapping */
1175
+ supportsCustomTypeMapping: boolean;
1176
+ /** Whether this generator supports incremental generation */
1177
+ supportsIncrementalGeneration: boolean;
1178
+ /** Whether this generator supports validation */
1179
+ supportsValidation: boolean;
1180
+ /** Supported schema kinds */
1181
+ supportedSchemaKinds: Array<"resource" | "complex-type" | "profile" | "primitive-type" | "logical">;
1182
+ /** Version of the generator */
1183
+ version: string;
1184
+ /** Additional metadata about capabilities */
1185
+ metadata?: Record<string, unknown>;
1186
+ }
1187
+
1188
+ /**
1189
+ * Core file management system with batching and performance optimizations
43
1190
  *
44
- * ### FHIR Patient with US Core Extensions
1191
+ * This replaces scattered writeFile calls with a comprehensive file management
1192
+ * system that provides better error handling, performance, and maintainability.
1193
+ */
1194
+
1195
+ interface FileManagerOptions {
1196
+ outputDir: string;
1197
+ logger: CodegenLogger;
1198
+ overwrite?: boolean;
1199
+ batchSize?: number;
1200
+ }
1201
+ interface WriteFileResult {
1202
+ path: string;
1203
+ size: number;
1204
+ writeTime: number;
1205
+ }
1206
+ /**
1207
+ * High-performance file manager with batching and error recovery
45
1208
  *
46
- * ```typescript
47
- * import { USCorePatient, USCoreRaceExtension } from './types/fhir';
48
- *
49
- * const patient: USCorePatient = {
50
- * resourceType: 'Patient',
51
- * identifier: [{ value: 'MRN-123' }],
52
- * name: [{ family: 'Johnson', given: ['Maria'] }],
53
- * gender: 'female',
54
- * extension: [{
55
- * url: 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-race',
56
- * extension: [{ url: 'text', valueString: 'Hispanic or Latino' }]
57
- * } as USCoreRaceExtension]
58
- * };
59
- * ```
1209
+ * Features:
1210
+ * - Automatic directory creation
1211
+ * - Batch operations for better performance
1212
+ * - Comprehensive error handling with recovery suggestions
1213
+ * - Import path resolution
1214
+ * - File existence checks
1215
+ */
1216
+ declare class FileManager {
1217
+ private readonly options;
1218
+ private readonly logger;
1219
+ constructor(options: FileManagerOptions);
1220
+ /**
1221
+ * Write a file with automatic directory creation
1222
+ * @param relativePath Path relative to output directory
1223
+ * @param content File content
1224
+ * @param options Write options
1225
+ */
1226
+ writeFile(relativePath: string, content: string, options?: {
1227
+ encoding?: BufferEncoding;
1228
+ overwrite?: boolean;
1229
+ }): Promise<WriteFileResult>;
1230
+ /**
1231
+ * Write multiple files in batch for better performance
1232
+ * @param files Map of relative path to content
1233
+ */
1234
+ writeBatch(files: Map<string, string>): Promise<WriteFileResult[]>;
1235
+ /**
1236
+ * Ensure directory exists, creating parent directories as needed
1237
+ * @param dirPath Full directory path
1238
+ */
1239
+ ensureDirectory(dirPath: string): Promise<void>;
1240
+ /**
1241
+ * Clean directory by removing all contents
1242
+ * @param relativePath Path relative to output directory
1243
+ */
1244
+ cleanDirectory(relativePath?: string): Promise<void>;
1245
+ /**
1246
+ * Get relative import path between two files
1247
+ * @param fromFile Source file path
1248
+ * @param toFile Target file path
1249
+ */
1250
+ getRelativeImportPath(fromFile: string, toFile: string): string;
1251
+ /**
1252
+ * Check if a file would be overwritten
1253
+ * @param relativePath Path relative to output directory
1254
+ */
1255
+ wouldOverwrite(relativePath: string): Promise<boolean>;
1256
+ /**
1257
+ * Get file statistics
1258
+ * @param relativePath Path relative to output directory
1259
+ */
1260
+ getFileStats(relativePath: string): Promise<FileStats | null>;
1261
+ /**
1262
+ * Get output directory
1263
+ */
1264
+ getOutputDirectory(): string;
1265
+ /**
1266
+ * Set batch size for operations
1267
+ * @param size Batch size
1268
+ */
1269
+ setBatchSize(size: number): void;
1270
+ /**
1271
+ * Get current batch size
1272
+ */
1273
+ getBatchSize(): number;
1274
+ }
1275
+
1276
+ /**
1277
+ * Index file builder for automated exports
60
1278
  *
61
- * ### Runtime Validation
1279
+ * Automatically generates index files that export all types and functions
1280
+ * from a directory, with support for grouping and namespaces.
1281
+ */
1282
+
1283
+ interface IndexBuilderConfig {
1284
+ directory: string;
1285
+ fileManager: FileManager;
1286
+ templateEngine?: TemplateEngine;
1287
+ logger: CodegenLogger;
1288
+ }
1289
+ /**
1290
+ * Builder for index files with intelligent export management
62
1291
  *
63
- * ```typescript
64
- * import { isUSCorePatient, validateFHIRResource } from './types/fhir/guards';
1292
+ * Features:
1293
+ * - Automatic export detection
1294
+ * - Namespace support
1295
+ * - Export grouping
1296
+ * - Custom headers
1297
+ * - Template support
1298
+ */
1299
+ declare class IndexBuilder {
1300
+ private readonly config;
1301
+ private readonly exports;
1302
+ private readonly namespaces;
1303
+ private readonly reExports;
1304
+ private header;
1305
+ private footer;
1306
+ private groupingFunction?;
1307
+ private sortFunction?;
1308
+ constructor(config: IndexBuilderConfig);
1309
+ /**
1310
+ * Add exports from a specific file
1311
+ * @param exportNames Export names
1312
+ * @param fromPath Path to file (without extension)
1313
+ */
1314
+ withExports(exportNames: string[], fromPath: string): IndexBuilder;
1315
+ /**
1316
+ * Add a single export
1317
+ * @param exportName Export name
1318
+ * @param fromPath Path to file
1319
+ */
1320
+ withExport(exportName: string, fromPath: string): IndexBuilder;
1321
+ /**
1322
+ * Add namespace exports
1323
+ * @param namespaces Map of namespace to path
1324
+ */
1325
+ withNamespaces(namespaces: Record<string, string>): IndexBuilder;
1326
+ /**
1327
+ * Add namespace export
1328
+ * @param namespace Namespace name
1329
+ * @param path Path to export as namespace
1330
+ */
1331
+ withNamespace(namespace: string, path: string): IndexBuilder;
1332
+ /**
1333
+ * Re-export all from paths
1334
+ * @param paths Paths to re-export all from
1335
+ */
1336
+ withReExports(paths: string[]): IndexBuilder;
1337
+ /**
1338
+ * Add re-export
1339
+ * @param path Path to re-export all from
1340
+ */
1341
+ withReExport(path: string): IndexBuilder;
1342
+ /**
1343
+ * Set header content
1344
+ * @param header Header content
1345
+ */
1346
+ withHeader(header: string): IndexBuilder;
1347
+ /**
1348
+ * Set footer content
1349
+ * @param footer Footer content
1350
+ */
1351
+ withFooter(footer: string): IndexBuilder;
1352
+ /**
1353
+ * Group exports by function
1354
+ * @param fn Function that returns group name for export
1355
+ */
1356
+ groupBy(fn: (exportName: string) => string): IndexBuilder;
1357
+ /**
1358
+ * Sort exports by function
1359
+ * @param fn Sort function for [exportName, fromPath] tuples
1360
+ */
1361
+ sortBy(fn: (a: [string, string], b: [string, string]) => number): IndexBuilder;
1362
+ /**
1363
+ * Auto-discover exports from directory
1364
+ * @param filePattern Pattern to match files (e.g., "*.ts")
1365
+ */
1366
+ autoDiscover(_filePattern?: string): Promise<IndexBuilder>;
1367
+ /**
1368
+ * Save the index file
1369
+ */
1370
+ save(): Promise<string>;
1371
+ /**
1372
+ * Build content without saving (for preview)
1373
+ */
1374
+ build(): string;
1375
+ /**
1376
+ * Generate the index file content
1377
+ */
1378
+ private generateContent;
1379
+ /**
1380
+ * Generate simple exports without grouping
1381
+ */
1382
+ private generateSimpleExports;
1383
+ /**
1384
+ * Generate grouped exports
1385
+ */
1386
+ private generateGroupedExports;
1387
+ /**
1388
+ * Get current exports (for testing/debugging)
1389
+ */
1390
+ getExports(): Map<string, string>;
1391
+ /**
1392
+ * Get current namespaces (for testing/debugging)
1393
+ */
1394
+ getNamespaces(): Map<string, string>;
1395
+ /**
1396
+ * Get current re-exports (for testing/debugging)
1397
+ */
1398
+ getReExports(): Map<string, string>;
1399
+ }
1400
+
1401
+ /**
1402
+ * Fluent file builder with lifecycle hooks and validation
65
1403
  *
66
- * if (isUSCorePatient(someData)) {
67
- * // TypeScript knows this is a USCorePatient
68
- * const validation = await validateFHIRResource(someData);
69
- * if (validation.valid) {
70
- * console.log('Valid US Core Patient!');
71
- * }
72
- * }
73
- * ```
1404
+ * This provides a clean, chainable API for building files with imports,
1405
+ * exports, content generation, and lifecycle hooks for customization.
1406
+ */
1407
+
1408
+ interface FileBuilderConfig {
1409
+ filename: string;
1410
+ fileManager: FileManager;
1411
+ templateEngine?: TemplateEngine;
1412
+ typeMapper: TypeMapper;
1413
+ logger: CodegenLogger;
1414
+ }
1415
+ /**
1416
+ * Fluent builder for creating files with lifecycle hooks
1417
+ *
1418
+ * Features:
1419
+ * - Fluent API for content building
1420
+ * - Template integration
1421
+ * - Import/export management
1422
+ * - Lifecycle hooks (before/after save, error handling)
1423
+ * - Content validation
1424
+ * - Automatic import path resolution
1425
+ */
1426
+ declare class FileBuilder {
1427
+ private readonly config;
1428
+ private content;
1429
+ private readonly imports;
1430
+ private readonly exports;
1431
+ private readonly metadata;
1432
+ private beforeSaveHooks;
1433
+ private afterSaveHooks;
1434
+ private errorHooks;
1435
+ private options;
1436
+ constructor(config: FileBuilderConfig);
1437
+ /**
1438
+ * Set content directly
1439
+ * @param content File content
1440
+ */
1441
+ withContent(content: string | (() => string)): FileBuilder;
1442
+ /**
1443
+ * Generate content from template
1444
+ * @param templateName Template to use
1445
+ * @param context Template context
1446
+ */
1447
+ withTemplate(templateName: string, context: Record<string, unknown>): FileBuilder;
1448
+ /**
1449
+ * Append content to existing content
1450
+ * @param content Content to append
1451
+ */
1452
+ appendContent(content: string): FileBuilder;
1453
+ /**
1454
+ * Prepend content to existing content
1455
+ * @param content Content to prepend
1456
+ */
1457
+ prependContent(content: string): FileBuilder;
1458
+ /**
1459
+ * Set all imports at once
1460
+ * @param imports Map of symbol name to import path
1461
+ */
1462
+ withImports(imports: Map<string, string>): FileBuilder;
1463
+ /**
1464
+ * Add a single import
1465
+ * @param symbol Symbol to import
1466
+ * @param from Import path
1467
+ */
1468
+ addImport(symbol: string, from: string): FileBuilder;
1469
+ /**
1470
+ * Add multiple imports from the same path
1471
+ * @param symbols Symbols to import
1472
+ * @param from Import path
1473
+ */
1474
+ addImports(symbols: string[], from: string): FileBuilder;
1475
+ /**
1476
+ * Set all exports at once
1477
+ * @param exports Array of export names
1478
+ */
1479
+ withExports(exports: string[]): FileBuilder;
1480
+ /**
1481
+ * Add a single export
1482
+ * @param name Export name
1483
+ */
1484
+ addExport(name: string): FileBuilder;
1485
+ /**
1486
+ * Add multiple exports
1487
+ * @param names Export names
1488
+ */
1489
+ addExports(names: string[]): FileBuilder;
1490
+ /**
1491
+ * Set metadata for the file
1492
+ * @param key Metadata key
1493
+ * @param value Metadata value
1494
+ */
1495
+ withMetadata(key: string, value: unknown): FileBuilder;
1496
+ /**
1497
+ * Set file builder options
1498
+ * @param options Options to set
1499
+ */
1500
+ withOptions(options: Partial<FileBuilderOptions>): FileBuilder;
1501
+ /**
1502
+ * Add hook to run before saving
1503
+ * @param hook Hook function
1504
+ */
1505
+ onBeforeSave(hook: BeforeSaveHook): FileBuilder;
1506
+ /**
1507
+ * Add hook to run after successful save
1508
+ * @param hook Hook function
1509
+ */
1510
+ onAfterSave(hook: AfterSaveHook): FileBuilder;
1511
+ /**
1512
+ * Add hook to run when error occurs
1513
+ * @param hook Hook function
1514
+ */
1515
+ onError(hook: ErrorHook): FileBuilder;
1516
+ /**
1517
+ * Build final content without saving
1518
+ * @returns File context with final content
1519
+ */
1520
+ build(): FileContext;
1521
+ /**
1522
+ * Save the file
1523
+ * @returns Promise resolving to file path
1524
+ */
1525
+ save(): Promise<string>;
1526
+ /**
1527
+ * Build final content with imports and exports
1528
+ */
1529
+ private buildFinalContent;
1530
+ /**
1531
+ * Generate import statements
1532
+ */
1533
+ private generateImportStatements;
1534
+ /**
1535
+ * Generate export statements
1536
+ */
1537
+ private generateExportStatements;
1538
+ /**
1539
+ * Prettify content (basic implementation)
1540
+ */
1541
+ private prettifyContent;
1542
+ /**
1543
+ * Validate generated content
1544
+ */
1545
+ private validateContent;
1546
+ /**
1547
+ * Get current content (for testing/debugging)
1548
+ */
1549
+ getContent(): string;
1550
+ /**
1551
+ * Get current imports (for testing/debugging)
1552
+ */
1553
+ getImports(): Map<string, string>;
1554
+ /**
1555
+ * Get current exports (for testing/debugging)
1556
+ */
1557
+ getExports(): Set<string>;
1558
+ }
1559
+
1560
+ /**
1561
+ * Directory builder for batch file operations
1562
+ *
1563
+ * Provides a fluent API for managing entire directories of files,
1564
+ * including subdirectories, index files, and batch operations.
1565
+ */
1566
+
1567
+ interface DirectoryBuilderConfig {
1568
+ path: string;
1569
+ fileManager: FileManager;
1570
+ logger: CodegenLogger;
1571
+ }
1572
+ /**
1573
+ * Fluent builder for directory operations
1574
+ *
1575
+ * Features:
1576
+ * - Subdirectory management
1577
+ * - Batch file operations
1578
+ * - Index file generation
1579
+ * - Directory cleaning
1580
+ * - File listing for preview
1581
+ */
1582
+ declare class DirectoryBuilder {
1583
+ private readonly config;
1584
+ private readonly files;
1585
+ private readonly subdirectories;
1586
+ private indexBuilder?;
1587
+ private shouldClean;
1588
+ constructor(config: DirectoryBuilderConfig);
1589
+ /**
1590
+ * Add a subdirectory
1591
+ * @param name Subdirectory name
1592
+ */
1593
+ withSubdirectory(name: string): DirectoryBuilder;
1594
+ /**
1595
+ * Add files to this directory
1596
+ * @param files Map of filename to FileBuilder
1597
+ */
1598
+ withFiles(files: Record<string, FileBuilder>): DirectoryBuilder;
1599
+ /**
1600
+ * Add a single file
1601
+ * @param filename File name
1602
+ * @param builder File builder
1603
+ */
1604
+ withFile(filename: string, builder: FileBuilder): DirectoryBuilder;
1605
+ /**
1606
+ * Set index builder for this directory
1607
+ * @param builder Index builder
1608
+ */
1609
+ withIndex(builder: IndexBuilder): DirectoryBuilder;
1610
+ /**
1611
+ * Clean directory before creating files
1612
+ */
1613
+ clean(): DirectoryBuilder;
1614
+ /**
1615
+ * Ensure directory exists
1616
+ */
1617
+ ensure(): Promise<DirectoryBuilder>;
1618
+ /**
1619
+ * Save all files in this directory
1620
+ */
1621
+ save(): Promise<string[]>;
1622
+ /**
1623
+ * Get all files that would be generated (for preview)
1624
+ */
1625
+ getFileList(): string[];
1626
+ /**
1627
+ * Get statistics about this directory
1628
+ */
1629
+ getStats(): {
1630
+ fileCount: number;
1631
+ subdirectoryCount: number;
1632
+ hasIndex: boolean;
1633
+ totalFiles: number;
1634
+ };
1635
+ /**
1636
+ * Check if directory would overwrite existing files
1637
+ */
1638
+ wouldOverwrite(): Promise<string[]>;
1639
+ /**
1640
+ * Get the path of this directory
1641
+ */
1642
+ getPath(): string;
1643
+ /**
1644
+ * Get all file builders (for testing/debugging)
1645
+ */
1646
+ getFiles(): Map<string, FileBuilder>;
1647
+ /**
1648
+ * Get all subdirectories (for testing/debugging)
1649
+ */
1650
+ getSubdirectories(): Map<string, DirectoryBuilder>;
1651
+ /**
1652
+ * Get index builder (for testing/debugging)
1653
+ */
1654
+ getIndexBuilder(): IndexBuilder | undefined;
1655
+ }
1656
+
1657
+ /**
1658
+ * Centralized error handling and reporting system
1659
+ *
1660
+ * This module provides a comprehensive error handling solution that:
1661
+ * - Handles both generator-specific and unknown errors gracefully
1662
+ * - Provides rich, context-aware error reporting
1663
+ * - Supports multiple output formats (console, JSON, structured)
1664
+ * - Includes batch error handling for multiple failures
1665
+ * - Offers smart error recovery suggestions
1666
+ */
1667
+
1668
+ interface ErrorHandlerOptions {
1669
+ logger: CodegenLogger;
1670
+ verbose?: boolean;
1671
+ beginnerMode?: boolean;
1672
+ outputFormat?: "console" | "json" | "structured";
1673
+ }
1674
+ /**
1675
+ * Centralized error handler with smart reporting
1676
+ */
1677
+ declare class ErrorHandler {
1678
+ private options;
1679
+ constructor(options: ErrorHandlerOptions);
1680
+ /**
1681
+ * Handle a single error with appropriate reporting
1682
+ */
1683
+ handleError(error: Error, context?: {
1684
+ schema?: TypeSchema;
1685
+ filename?: string;
1686
+ }): void;
1687
+ /**
1688
+ * Handle multiple errors in batch
1689
+ */
1690
+ handleBatchErrors(errors: Error[]): void;
1691
+ /**
1692
+ * Handle generator-specific errors with rich context
1693
+ */
1694
+ private handleGeneratorError;
1695
+ /**
1696
+ * Handle unknown errors gracefully
1697
+ */
1698
+ private handleUnknownError;
1699
+ /**
1700
+ * Report error to console with formatting
1701
+ */
1702
+ private reportErrorToConsole;
1703
+ /**
1704
+ * Report error as JSON for programmatic consumption
1705
+ */
1706
+ private reportErrorAsJson;
1707
+ /**
1708
+ * Report error in structured format
1709
+ */
1710
+ private reportErrorStructured;
1711
+ /**
1712
+ * Report multiple errors efficiently
1713
+ */
1714
+ private reportBatchErrors;
1715
+ /**
1716
+ * Get common suggestions across similar errors
1717
+ */
1718
+ private getCommonSuggestions;
1719
+ /**
1720
+ * Get recovery actions for an error
1721
+ */
1722
+ private getRecoveryActions;
1723
+ }
1724
+ /**
1725
+ * Error boundary for catching and handling all generator errors
1726
+ */
1727
+ declare class GeneratorErrorBoundary {
1728
+ private errorHandler;
1729
+ constructor(errorHandler: ErrorHandler);
1730
+ /**
1731
+ * Wrap an async operation with error boundary
1732
+ */
1733
+ withErrorBoundary<T>(operation: () => Promise<T>, context?: {
1734
+ schema?: TypeSchema;
1735
+ filename?: string;
1736
+ operationName?: string;
1737
+ }): Promise<T>;
1738
+ /**
1739
+ * Wrap a batch operation with error boundary
1740
+ */
1741
+ withBatchErrorBoundary<T>(operations: Array<() => Promise<T>>, _context?: {
1742
+ operationName?: string;
1743
+ }): Promise<T[]>;
1744
+ }
1745
+
1746
+ /**
1747
+ * Abstract base generator class with comprehensive functionality
1748
+ *
1749
+ * Provides common functionality for all generators including:
1750
+ * - Schema validation and processing
1751
+ * - File management with fluent API
1752
+ * - Template processing
1753
+ * - Error handling and recovery
1754
+ * - Progress monitoring
1755
+ * - Performance optimization
1756
+ */
1757
+ declare abstract class BaseGenerator<TOptions extends BaseGeneratorOptions = BaseGeneratorOptions, TResult extends GeneratedFile[] = GeneratedFile[]> {
1758
+ /** Validated and merged options */
1759
+ protected options: Required<TOptions>;
1760
+ /** Logger instance for this generator */
1761
+ protected readonly logger: CodegenLogger;
1762
+ /** File manager for all file operations */
1763
+ protected readonly fileManager: FileManager;
1764
+ /** Template engine for content generation (optional) */
1765
+ protected readonly templateEngine?: TemplateEngine;
1766
+ /** Language-specific type mapper */
1767
+ protected readonly typeMapper: TypeMapper;
1768
+ /** Enhanced error handler for comprehensive error reporting */
1769
+ protected readonly errorHandler: ErrorHandler;
1770
+ /** Error boundary for catching and handling all generator errors */
1771
+ protected readonly errorBoundary: GeneratorErrorBoundary;
1772
+ /** Progress callback if provided */
1773
+ private progressCallback?;
1774
+ /** Generated files tracking */
1775
+ private generatedFiles;
1776
+ /** Generation start time for performance metrics */
1777
+ private generationStartTime;
1778
+ /** Cache for expensive operations */
1779
+ private readonly cache;
1780
+ constructor(options: TOptions);
1781
+ /**
1782
+ * Get the name of the target language (e.g., "TypeScript", "Python", "Rust")
1783
+ */
1784
+ protected abstract getLanguageName(): string;
1785
+ /**
1786
+ * Get the file extension for the target language (e.g., ".ts", ".py", ".rs")
1787
+ */
1788
+ protected abstract getFileExtension(): string;
1789
+ /**
1790
+ * Create a language-specific type mapper
1791
+ */
1792
+ protected abstract createTypeMapper(): TypeMapper;
1793
+ /**
1794
+ * Generate content for a single schema
1795
+ * @param schema - The TypeSchema to generate code for
1796
+ * @param context - Additional context for generation
1797
+ */
1798
+ protected abstract generateSchemaContent(schema: TypeSchema, context: TemplateContext): Promise<string>;
1799
+ /**
1800
+ * Validate generated content before writing
1801
+ * @param content - The generated content
1802
+ * @param context - The generation context
1803
+ */
1804
+ protected abstract validateContent(content: string, context: TemplateContext): Promise<void>;
1805
+ /**
1806
+ * Filter and sort schemas with language-specific logic
1807
+ * @param schemas - Input schemas
1808
+ */
1809
+ protected abstract filterAndSortSchemas(schemas: TypeSchema[]): TypeSchema[];
1810
+ /**
1811
+ * Get generator capabilities - can be overridden for introspection
1812
+ */
1813
+ getCapabilities(): GeneratorCapabilities;
1814
+ /**
1815
+ * Create file manager instance - can be overridden for custom file handling
1816
+ */
1817
+ protected createFileManager(): FileManager;
1818
+ /**
1819
+ * Create template engine instance - can be overridden for custom templates
1820
+ * Returns undefined if template engine is not needed
1821
+ */
1822
+ protected createTemplateEngine(): TemplateEngine | undefined;
1823
+ /**
1824
+ * Generate code from TypeSchema documents
1825
+ * This is the main method that orchestrates the entire generation process
1826
+ * @param schemas - Array of TypeSchema documents
1827
+ */
1828
+ generate(schemas: TypeSchema[]): Promise<TResult>;
1829
+ /**
1830
+ * Generate and return content without writing files (useful for testing)
1831
+ * @param schemas - Array of TypeSchema documents
1832
+ */
1833
+ build(schemas: TypeSchema[]): Promise<TResult>;
1834
+ /**
1835
+ * Create a file builder for fluent file generation
1836
+ * @param filename - Name of the file to create
1837
+ */
1838
+ file(filename: string): FileBuilder;
1839
+ /**
1840
+ * Create a directory builder for batch operations
1841
+ * @param path - Directory path relative to output directory
1842
+ */
1843
+ directory(path: string): DirectoryBuilder;
1844
+ /**
1845
+ * Create an index file builder
1846
+ * @param directory - Directory to create index for
1847
+ */
1848
+ index(directory?: string): IndexBuilder;
1849
+ /**
1850
+ * Set progress callback for monitoring generation
1851
+ * @param callback - Progress callback function
1852
+ */
1853
+ onProgress(callback: ProgressCallback): this;
1854
+ /**
1855
+ * Validate generator configuration
1856
+ */
1857
+ private validateConfiguration;
1858
+ /**
1859
+ * Merge options with defaults
1860
+ */
1861
+ private mergeWithDefaults;
1862
+ /**
1863
+ * Validate schemas before processing
1864
+ */
1865
+ private validateSchemas;
1866
+ /**
1867
+ * Validate individual schema
1868
+ */
1869
+ protected validateSchema(schema: TypeSchema): Promise<void>;
1870
+ /**
1871
+ * Detect circular references in schema dependencies
1872
+ */
1873
+ private detectCircularReferences;
1874
+ /**
1875
+ * Generate files from processed schemas
1876
+ */
1877
+ private generateFiles;
1878
+ /**
1879
+ * Generate a single file from a schema
1880
+ */
1881
+ private generateFileForSchema;
1882
+ /**
1883
+ * Ensure filename has correct extension
1884
+ */
1885
+ private ensureFileExtension;
1886
+ /**
1887
+ * Extract exported symbols from generated content
1888
+ * Can be overridden by language-specific implementations
1889
+ */
1890
+ protected extractExports(content: string): string[];
1891
+ /**
1892
+ * Report progress to callback if provided
1893
+ */
1894
+ protected reportProgress(phase: "validation" | "generation" | "writing" | "complete", current: number, total: number, message?: string, schema?: TypeSchema): void;
1895
+ /**
1896
+ * Run post-generation hooks
1897
+ * Can be overridden to add custom post-processing
1898
+ */
1899
+ protected runPostGenerationHooks(): Promise<void>;
1900
+ /**
1901
+ * Get cached value or compute and cache it
1902
+ */
1903
+ protected getCachedOrCompute<T>(key: string, computeFn: () => T | Promise<T>): T | Promise<T>;
1904
+ /**
1905
+ * Clear internal cache
1906
+ */
1907
+ protected clearCache(): void;
1908
+ /**
1909
+ * Get generation statistics
1910
+ */
1911
+ getGenerationStats(): {
1912
+ filesGenerated: number;
1913
+ totalSize: number;
1914
+ averageFileSize: number;
1915
+ generationTime: number;
1916
+ averageTimePerFile: number;
1917
+ cacheHitRate: number;
1918
+ };
1919
+ }
1920
+
1921
+ /**
1922
+ * Abstract base class for language-specific type mapping
1923
+ *
1924
+ * This provides the interface that all language generators must implement
1925
+ * to convert FHIR TypeSchema types into their target language types.
1926
+ */
1927
+
1928
+ /**
1929
+ * Configuration for type mapping behavior
1930
+ */
1931
+ interface TypeMapperOptions {
1932
+ /** Whether to generate nullable types (e.g., T | null) */
1933
+ generateNullable?: boolean;
1934
+ /** Whether to use strict type checking */
1935
+ strictTypes?: boolean;
1936
+ /** Custom type mappings */
1937
+ customMappings?: Record<string, string>;
1938
+ /** Whether to generate array types or use generic collections */
1939
+ preferArraySyntax?: boolean;
1940
+ /** Naming convention strategy */
1941
+ namingConvention?: "camelCase" | "PascalCase" | "snake_case" | "kebab-case";
1942
+ }
1943
+
1944
+ /**
1945
+ * TypeScript-specific type mapper implementation
1946
+ */
1947
+
1948
+ /**
1949
+ * TypeScript-specific options
1950
+ */
1951
+ interface TypeScriptTypeMapperOptions extends TypeMapperOptions {
1952
+ /** Whether to use 'unknown' or 'any' for unmapped types */
1953
+ preferUnknown?: boolean;
1954
+ /** Whether to generate branded types for primitives */
1955
+ useBrandedTypes?: boolean;
1956
+ /** Whether to use 'undefined' or 'null' for optional types */
1957
+ preferUndefined?: boolean;
1958
+ /** Module format for imports */
1959
+ moduleFormat?: "esm" | "commonjs";
1960
+ }
1961
+
1962
+ /**
1963
+ * Modern TypeScript Generator built on BaseGenerator
1964
+ *
1965
+ * This is the new, clean implementation that replaces the monolithic typescript.ts generator.
1966
+ * Built using the BaseGenerator architecture with TypeMapper, TemplateEngine, and FileManager.
1967
+ */
1968
+
1969
+ /**
1970
+ * TypeScript-specific generator options
1971
+ */
1972
+ interface TypeScriptGeneratorOptions extends BaseGeneratorOptions {
1973
+ /** Module format for imports/exports */
1974
+ moduleFormat?: "esm" | "cjs";
1975
+ /** Whether to generate index files */
1976
+ generateIndex?: boolean;
1977
+ /** Include JSDoc documentation */
1978
+ includeDocuments?: boolean;
1979
+ /** Naming convention for types */
1980
+ namingConvention?: "PascalCase" | "camelCase";
1981
+ /** Include FHIR extensions */
1982
+ includeExtensions?: boolean;
1983
+ /** Include FHIR profiles */
1984
+ includeProfiles?: boolean;
1985
+ /** Generate value set files (default: false) */
1986
+ generateValueSets?: boolean;
1987
+ /** Include helper validation functions (default: false) */
1988
+ includeValueSetHelpers?: boolean;
1989
+ /**
1990
+ * Which binding strengths to generate value sets for
1991
+ * Only used when valueSetMode is 'custom'
1992
+ * @default ['required']
1993
+ */
1994
+ valueSetStrengths?: ("required" | "preferred" | "extensible" | "example")[];
1995
+ /**
1996
+ * Directory name for value set files (relative to outputDir)
1997
+ * @default 'valuesets'
1998
+ */
1999
+ valueSetDirectory?: string;
2000
+ /**
2001
+ * Value set generation mode
2002
+ * - 'all': Generate for all binding strengths with enums
2003
+ * - 'required-only': Generate only for required bindings (safe default)
2004
+ * - 'custom': Use valueSetStrengths array to control
2005
+ * @default 'required-only'
2006
+ */
2007
+ valueSetMode?: "all" | "required-only" | "custom";
2008
+ /** Type mapper options */
2009
+ typeMapperOptions?: TypeScriptTypeMapperOptions;
2010
+ }
2011
+ /**
2012
+ * Result of generating a single TypeScript file
2013
+ */
2014
+ interface GeneratedTypeScript {
2015
+ content: string;
2016
+ imports: Map<string, string>;
2017
+ exports: string[];
2018
+ filename: string;
2019
+ }
2020
+ /**
2021
+ * Modern TypeScript Generator
74
2022
  *
75
- * @packageDocumentation
76
- * @module @atomic-ehr/codegen
77
- * @version 0.0.1
78
- * @author Atomic EHR Team
79
- * @since 0.0.1
2023
+ * Generates clean, type-safe TypeScript interfaces from FHIR TypeSchema documents.
2024
+ * Uses the new BaseGenerator architecture for maintainability and extensibility.
80
2025
  */
81
- export * from "./api/index";
82
- export * from "./config";
2026
+ declare class TypeScriptGenerator extends BaseGenerator<TypeScriptGeneratorOptions, GeneratedFile[]> {
2027
+ private readonly resourceTypes;
2028
+ private collectedValueSets;
2029
+ private get tsOptions();
2030
+ protected getLanguageName(): string;
2031
+ protected getFileExtension(): string;
2032
+ protected createTypeMapper(): TypeMapper;
2033
+ protected generateSchemaContent(schema: TypeSchema, _context: TemplateContext): Promise<string>;
2034
+ protected filterAndSortSchemas(schemas: TypeSchema[]): TypeSchema[];
2035
+ protected validateContent(content: string, context: TemplateContext): Promise<void>;
2036
+ /**
2037
+ * Transform multiple schemas into TypeScript
2038
+ */
2039
+ transformSchemas(schemas: TypeSchema[]): Promise<GeneratedTypeScript[]>;
2040
+ /**
2041
+ * Transform a single schema into TypeScript
2042
+ */
2043
+ transformSchema(schema: TypeSchema): Promise<GeneratedTypeScript | undefined>;
2044
+ /**
2045
+ * Check if a binding schema should generate a value set file
2046
+ */
2047
+ private shouldGenerateValueSet;
2048
+ /**
2049
+ * Collect value sets from schemas that should generate value set files
2050
+ */
2051
+ private collectValueSets;
2052
+ /**
2053
+ * Check if a field binding should use a value set type
2054
+ */
2055
+ private shouldUseValueSetType;
2056
+ /**
2057
+ * Get the TypeScript type name for a binding
2058
+ */
2059
+ private getValueSetTypeName;
2060
+ /**
2061
+ * Check if a field has enum values that should be inlined
2062
+ */
2063
+ private shouldUseInlineEnum;
2064
+ /**
2065
+ * Generate inline enum type from field enum values
2066
+ */
2067
+ private generateInlineEnumType;
2068
+ private shouldSkipSchema;
2069
+ private getFilenameForSchema;
2070
+ private extractImportsFromContent;
2071
+ private extractExportsFromContent;
2072
+ /**
2073
+ * Generate special Reference interface with generics
2074
+ */
2075
+ private generateReferenceInterface;
2076
+ /**
2077
+ * Generate TypeScript interface directly without templates
2078
+ */
2079
+ private generateTypeScriptInterface;
2080
+ /**
2081
+ * Collect import dependencies from a field
2082
+ */
2083
+ private collectFieldImports;
2084
+ /**
2085
+ * Extract resource types from reference field constraints
2086
+ */
2087
+ private extractReferenceTypes;
2088
+ /**
2089
+ * Generate nested type interface
2090
+ */
2091
+ private generateNestedTypeInterface;
2092
+ /**
2093
+ * Capitalize first letter of string
2094
+ */
2095
+ private capitalizeFirst;
2096
+ /**
2097
+ * Generate field lines (handles polymorphic fields by expanding them)
2098
+ */
2099
+ private generateFieldLines;
2100
+ /**
2101
+ * Generate a single field line
2102
+ */
2103
+ private generateFieldLine;
2104
+ /**
2105
+ * Extract exported symbols from TypeScript content
2106
+ */
2107
+ protected extractExports(content: string): string[];
2108
+ /**
2109
+ * Set output directory for compatibility with API builder
2110
+ */
2111
+ setOutputDir(directory: string): void;
2112
+ /**
2113
+ * Update generator options for compatibility with API builder
2114
+ */
2115
+ setOptions(options: Partial<TypeScriptGeneratorOptions>): void;
2116
+ /**
2117
+ * Get current options for compatibility with API builder
2118
+ */
2119
+ getOptions(): TypeScriptGeneratorOptions;
2120
+ /**
2121
+ * Override generate to clean directory first
2122
+ */
2123
+ generate(schemas: TypeSchema[]): Promise<GeneratedFile[]>;
2124
+ /**
2125
+ * Run post-generation hooks - generate utility files
2126
+ */
2127
+ protected runPostGenerationHooks(): Promise<void>;
2128
+ /**
2129
+ * Generate utilities.ts file with ResourceType union
2130
+ */
2131
+ private generateUtilitiesFile;
2132
+ /**
2133
+ * Generate a complete value set TypeScript file
2134
+ */
2135
+ private generateValueSetFile;
2136
+ /**
2137
+ * Create valuesets directory and generate all value set files
2138
+ */
2139
+ private generateValueSetFiles;
2140
+ /**
2141
+ * Generate index.ts file that re-exports all value sets
2142
+ */
2143
+ private generateValueSetIndexFile;
2144
+ /**
2145
+ * Generate main types/index.ts file that exports all types and value sets
2146
+ */
2147
+ private generateMainIndexFile;
2148
+ }
2149
+
2150
+ 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, createAPI, createAPIFromConfig, defineConfig, generateTypesFromFiles, generateTypesFromPackage, isConfig, loadConfig };