@atomic-ehr/codegen 0.0.1-canary.20251015064414.0fcee22 → 0.0.1

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/cli/index.js CHANGED
@@ -1,21 +1,24 @@
1
1
  #!/usr/bin/env node
2
- import Wr from'yargs';import {hideBin}from'yargs/helpers';import'perf_hooks';import'ora';import v from'picocolors';import*as E from'fs';import {existsSync,mkdirSync}from'fs';import*as I from'path';import {dirname,resolve,join,relative}from'path';import*as $ from'fs/promises';import {mkdir,writeFile,readFile,readdir,stat,unlink,access,rm}from'fs/promises';import {CanonicalManager}from'@atomic-ehr/fhir-canonical-manager';import*as It from'@atomic-ehr/fhirschema';var Oe=Object.defineProperty;var Xt=Object.getOwnPropertyDescriptor;var er=Object.getOwnPropertyNames;var tr=Object.prototype.hasOwnProperty;var rr=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var ie=(s,e)=>()=>(s&&(e=s(s=0)),e);var De=(s,e)=>{for(var t in e)Oe(s,t,{get:e[t],enumerable:true});},ir=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of er(e))!tr.call(s,i)&&i!==t&&Oe(s,i,{get:()=>e[i],enumerable:!(r=Xt(e,i))||r.enumerable});return s};var Be=s=>ir(Oe({},"__esModule",{value:true}),s);var k,xe,Q,D,Te,we,X=ie(()=>{k=class extends Error{constructor(t,r,i){super(t);this.phase=r;this.context=i;this.name=this.constructor.name,this.timestamp=new Date,this.errorId=this.generateErrorId(),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor);}timestamp;errorId;generateErrorId(){return `${this.constructor.name}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}getDetailedMessage(){let t=[`\u274C ${this.constructor.name}: ${this.message}`,` Error ID: ${this.errorId}`,` Phase: ${this.phase}`,` Time: ${this.timestamp.toISOString()}`];return this.context&&Object.keys(this.context).length>0&&(t.push(""),t.push("\u{1F4CD} Context:"),Object.entries(this.context).forEach(([r,i])=>{t.push(` ${r}: ${this.formatContextValue(i)}`);})),t.join(`
3
- `)}formatContextValue(t){if(t==null)return String(t);if(typeof t=="string")return `"${t}"`;if(typeof t=="object")try{return JSON.stringify(t,null,2)}catch{return "[Object]"}return String(t)}getSeverity(){return "error"}isRecoverable(){return false}getDocumentationLinks(){return ["https://github.com/atomic-ehr/codegen/docs/troubleshooting.md",`https://github.com/atomic-ehr/codegen/docs/errors/${this.constructor.name}.md`]}},xe=class extends k{constructor(t,r,i,n){super(t,"validation",{schemaName:r.identifier?.name||"unknown",schemaKind:r.identifier?.kind||"unknown",schemaPackage:r.identifier?.package||"unknown",validationErrors:i,userContext:n});this.schema=r;this.validationErrors=i;this.userContext=n;}getSuggestions(){let t=[];t.push("Verify the schema follows the TypeSchema specification"),t.push("Check that all required fields are present and properly typed");for(let r of this.validationErrors)r.includes("identifier.name")&&(t.push("\u2728 Add a valid identifier.name field to your schema"),t.push('\u{1F4A1} Example: identifier: { name: "Patient", kind: "resource" }')),r.includes("identifier.kind")&&(t.push('\u{1F3AF} Set identifier.kind to: "resource", "complex-type", "profile", or "primitive-type"'),t.push("\u{1F4DA} Check FHIR specification for the correct kind value")),r.includes("circular")&&(t.push("\u{1F504} Remove circular references between schemas"),t.push("\u{1F4A1} Use forward declarations for recursive types"),t.push("\u{1F50D} Look for schemas that reference each other in a loop")),r.includes("fields")&&(t.push("\u{1F4DD} Check that all fields have proper type definitions"),t.push("\u{1F527} Ensure field types reference valid TypeSchema identifiers"));return this.userContext?.isBeginnerMode&&(t.push(""),t.push("\u{1F393} Beginner Tips:"),t.push("\u{1F4D6} Start with the Quick Start guide: docs/getting-started/quick-start.md"),t.push("\u{1F50D} Use --verbose flag for detailed error information"),t.push("\u{1F9EA} Test with a simple schema first to verify your setup"),this.userContext.previousSuccessfulSchemas?.length&&t.push(`\u2705 Compare with your working schema: ${this.userContext.previousSuccessfulSchemas[0]}`)),this.userContext?.isBeginnerMode||(t.push(""),t.push("\u{1F527} Advanced Debugging:"),t.push("\u{1F575}\uFE0F Enable schema validation debugging"),t.push("\u{1F4CA} Check schema statistics and complexity metrics"),t.push("\u26A1 Consider schema preprocessing if dealing with complex inheritance")),t}isRecoverable(){return this.validationErrors.every(t=>!t.includes("circular")&&!t.includes("corruption"))}},Q=class extends k{constructor(t,r,i,n){super(t,"generation",{templateName:r,contextKeys:Object.keys(i),availableTemplates:n?.availableTemplates?.length||0,debugInfo:n});this.templateName=r;this.templateContext=i;this.debugInfo=n;}getSuggestions(){let t=[];if(this.debugInfo?.availableTemplates?.length&&!this.debugInfo.availableTemplates.includes(this.templateName)){t.push(`\u274C Template '${this.templateName}' not found`),t.push("\u{1F4C2} Available templates:"),this.debugInfo.availableTemplates.forEach(i=>{t.push(` \u2022 ${i}`);});let r=this.findSimilarTemplates(this.templateName,this.debugInfo.availableTemplates);r.length>0&&(t.push("\u{1F914} Did you mean:"),r.forEach(i=>{t.push(` \u2022 ${i}`);}));}if(this.debugInfo?.missingVariables?.length){t.push("\u{1F4DD} Missing template variables:"),this.debugInfo.missingVariables.forEach(i=>{t.push(` \u2022 ${i}`);}),t.push("\u{1F4A1} Add these variables to your template context");let r=Object.keys(this.templateContext);this.debugInfo.missingVariables.forEach(i=>{let n=r.filter(o=>this.levenshteinDistance(i.toLowerCase(),o.toLowerCase())<=2);n.length>0&&t.push(` Similar to: ${n.join(", ")}`);});}if(this.debugInfo?.lineNumber&&(t.push(`\u{1F41B} Check template syntax around line ${this.debugInfo.lineNumber}`),this.debugInfo.columnNumber&&t.push(` Column: ${this.debugInfo.columnNumber}`),this.debugInfo.templateSource)){let i=this.debugInfo.templateSource.split(`
4
- `)[this.debugInfo.lineNumber-1];i&&t.push(` Code: ${i.trim()}`);}return t.push("\u{1F527} Template debugging steps:"),t.push(" \u2022 Enable template debugging: { debug: true }"),t.push(" \u2022 Verify template file exists and has correct syntax"),t.push(" \u2022 Check template variable names match context keys"),t.push(" \u2022 Ensure template engine is properly configured"),t}findSimilarTemplates(t,r){return r.filter(i=>{let n=this.levenshteinDistance(t.toLowerCase(),i.toLowerCase());return n<=2&&n>0}).slice(0,3).sort((i,n)=>this.levenshteinDistance(t.toLowerCase(),i.toLowerCase())-this.levenshteinDistance(t.toLowerCase(),n.toLowerCase()))}levenshteinDistance(t,r){let i=Array(r.length+1).fill(null).map(()=>Array(t.length+1).fill(0));for(let n=0;n<=t.length;n++)i[0][n]=n;for(let n=0;n<=r.length;n++)i[n][0]=n;for(let n=1;n<=r.length;n++)for(let o=1;o<=t.length;o++){let a=t[o-1]===r[n-1]?0:1;i[n][o]=Math.min(i[n]?.[o-1]+1,i[n-1]?.[o]+1,i[n-1]?.[o-1]+a);}return i[r.length]?.[t.length]}isRecoverable(){return true}},D=class extends k{constructor(t,r,i,n,o){super(t,"writing",{operation:r,filePath:i,originalErrorMessage:n?.message,originalErrorCode:n?.code,recoveryOptions:o});this.operation=r;this.filePath=i;this.originalError=n;this.recoveryOptions=o;}getSuggestions(){let t=[],r=this.originalError?.code;switch(this.operation){case "create":case "write":t.push("\u{1F4C1} File writing troubleshooting:"),t.push(" \u2022 Check if the output directory exists"),t.push(" \u2022 Verify write permissions for the target directory"),t.push(" \u2022 Ensure no other process has the file locked"),this.filePath.includes(" ")&&t.push(" \u2022 File path contains spaces - check path escaping"),this.recoveryOptions?.alternativePaths?.length&&(t.push("\u{1F504} Alternative output directories:"),this.recoveryOptions.alternativePaths.forEach(i=>{t.push(` \u2022 ${i}`);}));break;case "read":t.push("\u{1F4D6} File reading troubleshooting:"),t.push(" \u2022 Verify the file exists at the specified path"),t.push(" \u2022 Check file read permissions"),t.push(" \u2022 Ensure file is not corrupted");break;case "delete":t.push("\u{1F5D1}\uFE0F File deletion troubleshooting:"),t.push(" \u2022 Check if file is locked by another process"),t.push(" \u2022 Verify delete permissions for the directory"),t.push(" \u2022 Ensure file exists before attempting deletion");break}switch(r){case "EACCES":t.push("\u{1F510} Permission Error:"),t.push(" \u2022 Current user lacks necessary file permissions"),this.recoveryOptions?.permissionFix?t.push(` \u2022 Fix command: ${this.recoveryOptions.permissionFix}`):t.push(` \u2022 Try: chmod 755 "${this.filePath}"`),t.push(" \u2022 Consider running with elevated permissions"),t.push(" \u2022 Check directory ownership and permissions");break;case "ENOSPC":if(t.push("\u{1F4BE} Disk Space Error:"),t.push(" \u2022 Insufficient disk space available"),t.push(" \u2022 Free up disk space and retry"),t.push(" \u2022 Consider using a different output directory"),this.recoveryOptions?.diskSpaceRequired){let i=Math.ceil(this.recoveryOptions.diskSpaceRequired/1024/1024);t.push(` \u2022 Required space: ~${i}MB`);}break;case "ENOENT":t.push("\u{1F4C2} File Not Found:"),t.push(" \u2022 File or directory does not exist"),t.push(" \u2022 Check the file path for typos"),t.push(" \u2022 Ensure parent directories exist"),t.push(` \u2022 Create directory: mkdir -p "$(dirname "${this.filePath}")"`);break;case "EMFILE":case "ENFILE":t.push("\u{1F4CA} Too Many Open Files:"),t.push(" \u2022 System has reached file handle limit"),t.push(" \u2022 Close unused files and retry"),t.push(" \u2022 Consider processing files in smaller batches");break}return this.recoveryOptions?.canRetry&&(t.push(""),t.push("\u{1F504} Recovery Options:"),t.push(" \u2022 This operation can be retried safely"),t.push(" \u2022 Fix the underlying issue and run again")),t.push(""),t.push("\u{1F50D} General Debugging:"),t.push(" \u2022 Check system logs for more details"),t.push(" \u2022 Verify disk health if errors persist"),t.push(" \u2022 Test with a simpler file path"),t}isRecoverable(){return this.recoveryOptions?.canRetry||false}getRecoveryActions(){let t=[];switch(this.originalError?.code){case "EACCES":t.push({action:"Fix file permissions",command:`chmod 755 "${this.filePath}"`,automatic:false,riskLevel:"medium"});break;case "ENOENT":t.push({action:"Create missing directory",command:`mkdir -p "$(dirname "${this.filePath}")"`,automatic:true,riskLevel:"low"});break;case "ENOSPC":t.push({action:"Free up disk space",automatic:false,riskLevel:"low"});break}return t}},Te=class extends k{constructor(t,r,i,n,o){super(t,"initialization",{configKey:r,providedValue:i,providedType:typeof i,expectedValue:n,validOptions:o});this.configKey=r;this.providedValue=i;this.expectedValue=n;this.validOptions=o;}getSuggestions(){let t=[];switch(t.push(`\u2699\uFE0F Configuration error for '${this.configKey}'`),t.push(` Provided: ${JSON.stringify(this.providedValue)} (${typeof this.providedValue})`),this.expectedValue&&t.push(` Expected: ${this.expectedValue}`),this.validOptions?.length&&(t.push(" Valid options:"),this.validOptions.forEach(r=>{t.push(` \u2022 ${JSON.stringify(r)}`);})),t.push(""),t.push("\u{1F527} Configuration fixes:"),t.push(` \u2022 Check the '${this.configKey}' value in your configuration`),t.push(" \u2022 Refer to the configuration documentation"),t.push(" \u2022 Use TypeScript for better config validation"),t.push(" \u2022 Check for typos in configuration keys"),this.configKey){case "outputDir":t.push(" \u2022 Ensure the output directory path exists"),t.push(" \u2022 Use absolute paths for better reliability");break;case "logger":t.push(" \u2022 Provide a valid logger instance"),t.push(" \u2022 Use createLogger() from utils/codegen-logger");break;case "validation":t.push(' \u2022 Set to true, false, or "strict"');break}return t}isRecoverable(){return true}},we=class extends k{constructor(t,r){super(t,"generation",{errorCount:r.length,errorTypes:[...new Set(r.map(i=>i.constructor.name))],phases:[...new Set(r.map(i=>i.phase))]});this.errors=r;}getSuggestions(){let t=this.errors.flatMap(a=>a.getSuggestions()),r=[...new Set(t)],i=[];i.push(`\u{1F4CA} Batch operation failed with ${this.errors.length} errors:`);let n=new Map;this.errors.forEach(a=>{let c=a.constructor.name;n.has(c)||n.set(c,[]),n.get(c)?.push(a);}),i.push(""),i.push("\u{1F50D} Error breakdown:");for(let[a,c]of n)i.push(` \u2022 ${a}: ${c.length} occurrences`);i.push("\u{1F4A1} Most relevant suggestions:");let o=r.slice(0,8).map(a=>` ${a}`);return i.push(...o),i}getErrorBreakdown(){let t=[];return this.errors.forEach((r,i)=>{t.push(`${i+1}. ${r.constructor.name}: ${r.message}`),r.context?.schemaName&&t.push(` Schema: ${r.context.schemaName}`),r.context?.filename&&t.push(` File: ${r.context.filename}`),t.push("");}),t.join(`
5
- `)}isRecoverable(){return this.errors.some(t=>t.isRecoverable())}getRecoverableErrors(){return this.errors.filter(t=>t.isRecoverable())}getNonRecoverableErrors(){return this.errors.filter(t=>!t.isRecoverable())}};});var Vt={};De(Vt,{FileBuilder:()=>et});var et,jt=ie(()=>{X();et=class{config;content="";imports=new Map;exports=new Set;metadata=new Map;beforeSaveHooks=[];afterSaveHooks=[];errorHooks=[];options={template:void 0,importStrategy:"auto",validation:"strict",prettify:true,formatting:{indentSize:2,useTabs:false,maxLineLength:100},encoding:"utf-8"};constructor(e){this.config=e;}withContent(e){return this.content=typeof e=="string"?e:e(),this}withTemplate(e,t){if(!this.config.templateEngine)throw new Q(`Template engine is required for template rendering. Template: '${e}'`,e,t);this.options.template=e;try{this.content=this.config.templateEngine.render(e,{...t,imports:this.imports,exports:this.exports,filename:this.config.filename});}catch{throw new Q(`Failed to render template '${e}'`,e,t,{availableTemplates:this.config.templateEngine.getAvailableTemplates?.()||[]})}return this}appendContent(e){return this.content+=e,this}prependContent(e){return this.content=e+this.content,this}withImports(e){this.imports.clear();for(let[t,r]of e)this.imports.set(t,r);return this}addImport(e,t){return this.imports.set(e,t),this}addImports(e,t){for(let r of e)this.imports.set(r,t);return this}withExports(e){this.exports.clear();for(let t of e)this.exports.add(t);return this}addExport(e){return this.exports.add(e),this}addExports(e){for(let t of e)this.exports.add(t);return this}withMetadata(e,t){return this.metadata.set(e,t),this}withOptions(e){return this.options={...this.options,...e},this}onBeforeSave(e){return this.beforeSaveHooks.push(e),this}onAfterSave(e){return this.afterSaveHooks.push(e),this}onError(e){return this.errorHooks.push(e),this}build(){let e=this.buildFinalContent();return {filename:this.config.filename,content:e,imports:new Map(this.imports),exports:new Set(this.exports),metadata:Object.fromEntries(this.metadata),templateName:this.options.template}}async save(){let e=this.build();try{for(let i of this.beforeSaveHooks)await i(e);this.options.validation!=="none"&&await this.validateContent(e.content);let t=await this.config.fileManager.writeFile(this.config.filename,e.content,{encoding:this.options.encoding}),r={size:t.size,generationTime:0,writeTime:t.writeTime};for(let i of this.afterSaveHooks)await i(t.path,r);return this.config.logger.debug(`Saved ${this.config.filename} successfully`),t.path}catch(t){for(let r of this.errorHooks)try{await r(t instanceof Error?t:new Error(String(t)),e);}catch(i){this.config.logger.warn(`Error hook failed: ${i instanceof Error?i.message:String(i)}`);}throw t}}buildFinalContent(){let e=[];this.imports.size>0&&this.options.importStrategy!=="none"&&(e.push(this.generateImportStatements()),e.push("")),this.content&&e.push(this.content),this.exports.size>0&&!this.content.includes("export")&&(e.push(""),e.push(this.generateExportStatements()));let t=e.join(`
2
+ import Si from'yargs';import {hideBin}from'yargs/helpers';import'perf_hooks';import'ora';import h from'picocolors';import*as R from'fs';import R__default,{existsSync,mkdirSync}from'fs';import*as w from'path';import w__default,{dirname,resolve,join,relative}from'path';import*as x from'fs/promises';import {mkdir,writeFile,readFile,readdir,stat,unlink,access,rm}from'fs/promises';import {CanonicalManager}from'@atomic-ehr/fhir-canonical-manager';import*as Bt from'@atomic-ehr/fhirschema';import {isStructureDefinition}from'@atomic-ehr/fhirschema';var Be=Object.defineProperty;var dr=Object.getOwnPropertyDescriptor;var fr=Object.getOwnPropertyNames;var mr=Object.prototype.hasOwnProperty;var hr=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var oe=(s,e)=>()=>(s&&(e=s(s=0)),e);var Le=(s,e)=>{for(var t in e)Be(s,t,{get:e[t],enumerable:true});},yr=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of fr(e))!mr.call(s,i)&&i!==t&&Be(s,i,{get:()=>e[i],enumerable:!(r=dr(e,i))||r.enumerable});return s};var Ae=s=>yr(Be({},"__esModule",{value:true}),s);var v,ke,ee,O,Ce,Fe,te=oe(()=>{v=class extends Error{constructor(t,r,i){super(t);this.phase=r;this.context=i;this.name=this.constructor.name,this.timestamp=new Date,this.errorId=this.generateErrorId(),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor);}timestamp;errorId;generateErrorId(){return `${this.constructor.name}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}getDetailedMessage(){let t=[`\u274C ${this.constructor.name}: ${this.message}`,` Error ID: ${this.errorId}`,` Phase: ${this.phase}`,` Time: ${this.timestamp.toISOString()}`];return this.context&&Object.keys(this.context).length>0&&(t.push(""),t.push("\u{1F4CD} Context:"),Object.entries(this.context).forEach(([r,i])=>{t.push(` ${r}: ${this.formatContextValue(i)}`);})),t.join(`
3
+ `)}formatContextValue(t){if(t==null)return String(t);if(typeof t=="string")return `"${t}"`;if(typeof t=="object")try{return JSON.stringify(t,null,2)}catch{return "[Object]"}return String(t)}getSeverity(){return "error"}isRecoverable(){return false}getDocumentationLinks(){return ["https://github.com/atomic-ehr/codegen/docs/troubleshooting.md",`https://github.com/atomic-ehr/codegen/docs/errors/${this.constructor.name}.md`]}},ke=class extends v{constructor(t,r,i,n){super(t,"validation",{schemaName:r.identifier?.name||"unknown",schemaKind:r.identifier?.kind||"unknown",schemaPackage:r.identifier?.package||"unknown",validationErrors:i,userContext:n});this.schema=r;this.validationErrors=i;this.userContext=n;}getSuggestions(){let t=[];t.push("Verify the schema follows the TypeSchema specification"),t.push("Check that all required fields are present and properly typed");for(let r of this.validationErrors)r.includes("identifier.name")&&(t.push("\u2728 Add a valid identifier.name field to your schema"),t.push('\u{1F4A1} Example: identifier: { name: "Patient", kind: "resource" }')),r.includes("identifier.kind")&&(t.push('\u{1F3AF} Set identifier.kind to: "resource", "complex-type", "profile", or "primitive-type"'),t.push("\u{1F4DA} Check FHIR specification for the correct kind value")),r.includes("circular")&&(t.push("\u{1F504} Remove circular references between schemas"),t.push("\u{1F4A1} Use forward declarations for recursive types"),t.push("\u{1F50D} Look for schemas that reference each other in a loop")),r.includes("fields")&&(t.push("\u{1F4DD} Check that all fields have proper type definitions"),t.push("\u{1F527} Ensure field types reference valid TypeSchema identifiers"));return this.userContext?.isBeginnerMode&&(t.push(""),t.push("\u{1F393} Beginner Tips:"),t.push("\u{1F4D6} Start with the Quick Start guide: docs/getting-started/quick-start.md"),t.push("\u{1F50D} Use --verbose flag for detailed error information"),t.push("\u{1F9EA} Test with a simple schema first to verify your setup"),this.userContext.previousSuccessfulSchemas?.length&&t.push(`\u2705 Compare with your working schema: ${this.userContext.previousSuccessfulSchemas[0]}`)),this.userContext?.isBeginnerMode||(t.push(""),t.push("\u{1F527} Advanced Debugging:"),t.push("\u{1F575}\uFE0F Enable schema validation debugging"),t.push("\u{1F4CA} Check schema statistics and complexity metrics"),t.push("\u26A1 Consider schema preprocessing if dealing with complex inheritance")),t}isRecoverable(){return this.validationErrors.every(t=>!t.includes("circular")&&!t.includes("corruption"))}},ee=class extends v{constructor(t,r,i,n){super(t,"generation",{templateName:r,contextKeys:Object.keys(i),availableTemplates:n?.availableTemplates?.length||0,debugInfo:n});this.templateName=r;this.templateContext=i;this.debugInfo=n;}getSuggestions(){let t=[];if(this.debugInfo?.availableTemplates?.length&&!this.debugInfo.availableTemplates.includes(this.templateName)){t.push(`\u274C Template '${this.templateName}' not found`),t.push("\u{1F4C2} Available templates:"),this.debugInfo.availableTemplates.forEach(i=>{t.push(` \u2022 ${i}`);});let r=this.findSimilarTemplates(this.templateName,this.debugInfo.availableTemplates);r.length>0&&(t.push("\u{1F914} Did you mean:"),r.forEach(i=>{t.push(` \u2022 ${i}`);}));}if(this.debugInfo?.missingVariables?.length){t.push("\u{1F4DD} Missing template variables:"),this.debugInfo.missingVariables.forEach(i=>{t.push(` \u2022 ${i}`);}),t.push("\u{1F4A1} Add these variables to your template context");let r=Object.keys(this.templateContext);this.debugInfo.missingVariables.forEach(i=>{let n=r.filter(o=>this.levenshteinDistance(i.toLowerCase(),o.toLowerCase())<=2);n.length>0&&t.push(` Similar to: ${n.join(", ")}`);});}if(this.debugInfo?.lineNumber&&(t.push(`\u{1F41B} Check template syntax around line ${this.debugInfo.lineNumber}`),this.debugInfo.columnNumber&&t.push(` Column: ${this.debugInfo.columnNumber}`),this.debugInfo.templateSource)){let i=this.debugInfo.templateSource.split(`
4
+ `)[this.debugInfo.lineNumber-1];i&&t.push(` Code: ${i.trim()}`);}return t.push("\u{1F527} Template debugging steps:"),t.push(" \u2022 Enable template debugging: { debug: true }"),t.push(" \u2022 Verify template file exists and has correct syntax"),t.push(" \u2022 Check template variable names match context keys"),t.push(" \u2022 Ensure template engine is properly configured"),t}findSimilarTemplates(t,r){return r.filter(i=>{let n=this.levenshteinDistance(t.toLowerCase(),i.toLowerCase());return n<=2&&n>0}).slice(0,3).sort((i,n)=>this.levenshteinDistance(t.toLowerCase(),i.toLowerCase())-this.levenshteinDistance(t.toLowerCase(),n.toLowerCase()))}levenshteinDistance(t,r){let i=Array(r.length+1).fill(null).map(()=>Array(t.length+1).fill(0));for(let n=0;n<=t.length;n++)i[0][n]=n;for(let n=0;n<=r.length;n++)i[n][0]=n;for(let n=1;n<=r.length;n++)for(let o=1;o<=t.length;o++){let a=t[o-1]===r[n-1]?0:1;i[n][o]=Math.min(i[n]?.[o-1]+1,i[n-1]?.[o]+1,i[n-1]?.[o-1]+a);}return i[r.length]?.[t.length]}isRecoverable(){return true}},O=class extends v{constructor(t,r,i,n,o){super(t,"writing",{operation:r,filePath:i,originalErrorMessage:n?.message,originalErrorCode:n?.code,recoveryOptions:o});this.operation=r;this.filePath=i;this.originalError=n;this.recoveryOptions=o;}getSuggestions(){let t=[],r=this.originalError?.code;switch(this.operation){case "create":case "write":t.push("\u{1F4C1} File writing troubleshooting:"),t.push(" \u2022 Check if the output directory exists"),t.push(" \u2022 Verify write permissions for the target directory"),t.push(" \u2022 Ensure no other process has the file locked"),this.filePath.includes(" ")&&t.push(" \u2022 File path contains spaces - check path escaping"),this.recoveryOptions?.alternativePaths?.length&&(t.push("\u{1F504} Alternative output directories:"),this.recoveryOptions.alternativePaths.forEach(i=>{t.push(` \u2022 ${i}`);}));break;case "read":t.push("\u{1F4D6} File reading troubleshooting:"),t.push(" \u2022 Verify the file exists at the specified path"),t.push(" \u2022 Check file read permissions"),t.push(" \u2022 Ensure file is not corrupted");break;case "delete":t.push("\u{1F5D1}\uFE0F File deletion troubleshooting:"),t.push(" \u2022 Check if file is locked by another process"),t.push(" \u2022 Verify delete permissions for the directory"),t.push(" \u2022 Ensure file exists before attempting deletion");break}switch(r){case "EACCES":t.push("\u{1F510} Permission Error:"),t.push(" \u2022 Current user lacks necessary file permissions"),this.recoveryOptions?.permissionFix?t.push(` \u2022 Fix command: ${this.recoveryOptions.permissionFix}`):t.push(` \u2022 Try: chmod 755 "${this.filePath}"`),t.push(" \u2022 Consider running with elevated permissions"),t.push(" \u2022 Check directory ownership and permissions");break;case "ENOSPC":if(t.push("\u{1F4BE} Disk Space Error:"),t.push(" \u2022 Insufficient disk space available"),t.push(" \u2022 Free up disk space and retry"),t.push(" \u2022 Consider using a different output directory"),this.recoveryOptions?.diskSpaceRequired){let i=Math.ceil(this.recoveryOptions.diskSpaceRequired/1024/1024);t.push(` \u2022 Required space: ~${i}MB`);}break;case "ENOENT":t.push("\u{1F4C2} File Not Found:"),t.push(" \u2022 File or directory does not exist"),t.push(" \u2022 Check the file path for typos"),t.push(" \u2022 Ensure parent directories exist"),t.push(` \u2022 Create directory: mkdir -p "$(dirname "${this.filePath}")"`);break;case "EMFILE":case "ENFILE":t.push("\u{1F4CA} Too Many Open Files:"),t.push(" \u2022 System has reached file handle limit"),t.push(" \u2022 Close unused files and retry"),t.push(" \u2022 Consider processing files in smaller batches");break}return this.recoveryOptions?.canRetry&&(t.push(""),t.push("\u{1F504} Recovery Options:"),t.push(" \u2022 This operation can be retried safely"),t.push(" \u2022 Fix the underlying issue and run again")),t.push(""),t.push("\u{1F50D} General Debugging:"),t.push(" \u2022 Check system logs for more details"),t.push(" \u2022 Verify disk health if errors persist"),t.push(" \u2022 Test with a simpler file path"),t}isRecoverable(){return this.recoveryOptions?.canRetry||false}getRecoveryActions(){let t=[];switch(this.originalError?.code){case "EACCES":t.push({action:"Fix file permissions",command:`chmod 755 "${this.filePath}"`,automatic:false,riskLevel:"medium"});break;case "ENOENT":t.push({action:"Create missing directory",command:`mkdir -p "$(dirname "${this.filePath}")"`,automatic:true,riskLevel:"low"});break;case "ENOSPC":t.push({action:"Free up disk space",automatic:false,riskLevel:"low"});break}return t}},Ce=class extends v{constructor(t,r,i,n,o){super(t,"initialization",{configKey:r,providedValue:i,providedType:typeof i,expectedValue:n,validOptions:o});this.configKey=r;this.providedValue=i;this.expectedValue=n;this.validOptions=o;}getSuggestions(){let t=[];switch(t.push(`\u2699\uFE0F Configuration error for '${this.configKey}'`),t.push(` Provided: ${JSON.stringify(this.providedValue)} (${typeof this.providedValue})`),this.expectedValue&&t.push(` Expected: ${this.expectedValue}`),this.validOptions?.length&&(t.push(" Valid options:"),this.validOptions.forEach(r=>{t.push(` \u2022 ${JSON.stringify(r)}`);})),t.push(""),t.push("\u{1F527} Configuration fixes:"),t.push(` \u2022 Check the '${this.configKey}' value in your configuration`),t.push(" \u2022 Refer to the configuration documentation"),t.push(" \u2022 Use TypeScript for better config validation"),t.push(" \u2022 Check for typos in configuration keys"),this.configKey){case "outputDir":t.push(" \u2022 Ensure the output directory path exists"),t.push(" \u2022 Use absolute paths for better reliability");break;case "logger":t.push(" \u2022 Provide a valid logger instance"),t.push(" \u2022 Use createLogger() from utils/codegen-logger");break;case "validation":t.push(' \u2022 Set to true, false, or "strict"');break}return t}isRecoverable(){return true}},Fe=class extends v{constructor(t,r){super(t,"generation",{errorCount:r.length,errorTypes:[...new Set(r.map(i=>i.constructor.name))],phases:[...new Set(r.map(i=>i.phase))]});this.errors=r;}getSuggestions(){let t=this.errors.flatMap(a=>a.getSuggestions()),r=[...new Set(t)],i=[];i.push(`\u{1F4CA} Batch operation failed with ${this.errors.length} errors:`);let n=new Map;this.errors.forEach(a=>{let c=a.constructor.name;n.has(c)||n.set(c,[]),n.get(c)?.push(a);}),i.push(""),i.push("\u{1F50D} Error breakdown:");for(let[a,c]of n)i.push(` \u2022 ${a}: ${c.length} occurrences`);i.push("\u{1F4A1} Most relevant suggestions:");let o=r.slice(0,8).map(a=>` ${a}`);return i.push(...o),i}getErrorBreakdown(){let t=[];return this.errors.forEach((r,i)=>{t.push(`${i+1}. ${r.constructor.name}: ${r.message}`),r.context?.schemaName&&t.push(` Schema: ${r.context.schemaName}`),r.context?.filename&&t.push(` File: ${r.context.filename}`),t.push("");}),t.join(`
5
+ `)}isRecoverable(){return this.errors.some(t=>t.isRecoverable())}getRecoverableErrors(){return this.errors.filter(t=>t.isRecoverable())}getNonRecoverableErrors(){return this.errors.filter(t=>!t.isRecoverable())}};});var Yt={};Le(Yt,{FileBuilder:()=>st});var st,Qt=oe(()=>{te();st=class{config;content="";imports=new Map;exports=new Set;metadata=new Map;beforeSaveHooks=[];afterSaveHooks=[];errorHooks=[];options={template:void 0,importStrategy:"auto",validation:"strict",prettify:true,formatting:{indentSize:2,useTabs:false,maxLineLength:100},encoding:"utf-8"};constructor(e){this.config=e;}withContent(e){return this.content=typeof e=="string"?e:e(),this}withTemplate(e,t){if(!this.config.templateEngine)throw new ee(`Template engine is required for template rendering. Template: '${e}'`,e,t);this.options.template=e;try{this.content=this.config.templateEngine.render(e,{...t,imports:this.imports,exports:this.exports,filename:this.config.filename});}catch{throw new ee(`Failed to render template '${e}'`,e,t,{availableTemplates:this.config.templateEngine.getAvailableTemplates?.()||[]})}return this}appendContent(e){return this.content+=e,this}prependContent(e){return this.content=e+this.content,this}withImports(e){this.imports.clear();for(let[t,r]of e)this.imports.set(t,r);return this}addImport(e,t){return this.imports.set(e,t),this}addImports(e,t){for(let r of e)this.imports.set(r,t);return this}withExports(e){this.exports.clear();for(let t of e)this.exports.add(t);return this}addExport(e){return this.exports.add(e),this}addExports(e){for(let t of e)this.exports.add(t);return this}withMetadata(e,t){return this.metadata.set(e,t),this}withOptions(e){return this.options={...this.options,...e},this}onBeforeSave(e){return this.beforeSaveHooks.push(e),this}onAfterSave(e){return this.afterSaveHooks.push(e),this}onError(e){return this.errorHooks.push(e),this}build(){let e=this.buildFinalContent();return {filename:this.config.filename,content:e,imports:new Map(this.imports),exports:new Set(this.exports),metadata:Object.fromEntries(this.metadata),templateName:this.options.template}}async save(){let e=this.build();try{for(let i of this.beforeSaveHooks)await i(e);this.options.validation!=="none"&&await this.validateContent(e.content);let t=await this.config.fileManager.writeFile(this.config.filename,e.content,{encoding:this.options.encoding}),r={size:t.size,generationTime:0,writeTime:t.writeTime};for(let i of this.afterSaveHooks)await i(t.path,r);return this.config.logger.debug(`Saved ${this.config.filename} successfully`),t.path}catch(t){for(let r of this.errorHooks)try{await r(t instanceof Error?t:new Error(String(t)),e);}catch(i){this.config.logger.warn(`Error hook failed: ${i instanceof Error?i.message:String(i)}`);}throw t}}buildFinalContent(){let e=[];this.imports.size>0&&this.options.importStrategy!=="none"&&(e.push(this.generateImportStatements()),e.push("")),this.content&&e.push(this.content),this.exports.size>0&&!this.content.includes("export")&&(e.push(""),e.push(this.generateExportStatements()));let t=e.join(`
6
6
  `);return this.options.prettify&&(t=this.prettifyContent(t)),t}generateImportStatements(){let e=[],t=new Map;for(let[r,i]of this.imports){let n=this.options.importStrategy==="auto"?this.config.fileManager.getRelativeImportPath(this.config.filename,i):i;t.has(n)||t.set(n,[]),t.get(n)?.push(r);}for(let[r,i]of t)if(i.length===1)e.push(`import type { ${i[0]} } from '${r}';`);else {let n=i.sort();if(n.length<=3)e.push(`import type { ${n.join(", ")} } from '${r}';`);else {e.push("import type {");let o=" ";n.forEach((a,c)=>{let l=c===n.length-1;e.push(`${o}${a}${l?"":","}`);}),e.push(`} from '${r}';`);}}return e.join(`
7
7
  `)}generateExportStatements(){return Array.from(this.exports).sort().map(t=>`export { ${t} };`).join(`
8
8
  `)}prettifyContent(e){return e.replace(/\n{3,}/g,`
9
9
 
10
- `).replace(/\t/g,this.options.formatting?.useTabs?" ":" ".repeat(this.options.formatting?.indentSize||2)).trim()}async validateContent(e){if(this.options.validation==="none")return;let t=[],r=(e.match(/\{/g)||[]).length,i=(e.match(/\}/g)||[]).length;r!==i&&t.push(`Unmatched braces: ${r} open, ${i} close`);let n=(e.match(/\(/g)||[]).length,o=(e.match(/\)/g)||[]).length;if(n!==o&&t.push(`Unmatched parentheses: ${n} open, ${o} close`),(this.config.filename.endsWith(".ts")||this.config.filename.endsWith(".tsx"))&&e.includes("interface")&&!e.match(/interface\s+\w+\s*\{/)&&t.push("Invalid interface syntax detected"),t.length>0&&this.options.validation==="strict")throw new D(`Content validation failed for ${this.config.filename}: ${t.join(", ")}`,"write",this.config.filename);t.length>0&&this.config.logger.warn(`Validation issues in ${this.config.filename}: ${t.join(", ")}`);}getContent(){return this.content}getImports(){return new Map(this.imports)}getExports(){return new Set(this.exports)}};});var At={};De(At,{DirectoryBuilder:()=>tt});var tt,Gt=ie(()=>{tt=class s{config;files=new Map;subdirectories=new Map;indexBuilder;shouldClean=false;constructor(e){this.config=e;}withSubdirectory(e){let t=`${this.config.path}/${e}`,r=new s({path:t,fileManager:this.config.fileManager,logger:this.config.logger.child(`Dir:${e}`)});return this.subdirectories.set(e,r),r}withFiles(e){for(let[t,r]of Object.entries(e))this.files.set(t,r);return this}withFile(e,t){return this.files.set(e,t),this}withIndex(e){return this.indexBuilder=e,this}clean(){return this.shouldClean=true,this}async ensure(){return await this.config.fileManager.ensureDirectory(this.config.path),this}async save(){let e=[];this.shouldClean&&await this.config.fileManager.cleanDirectory(this.config.path),await this.ensure();let t=Array.from(this.files.entries()).map(async([r,i])=>{try{let n=await i.save();return e.push(n),n}catch(n){throw this.config.logger.error(`Failed to save file ${r}:`,n instanceof Error?n:void 0),n}});await Promise.all(t);for(let[r,i]of this.subdirectories)try{let n=await i.save();e.push(...n);}catch(n){throw this.config.logger.error(`Failed to save subdirectory ${r}:`,n instanceof Error?n:void 0),n}if(this.indexBuilder)try{let r=await this.indexBuilder.save();e.push(r);}catch(r){throw this.config.logger.error("Failed to save index file:",r instanceof Error?r:void 0),r}return this.config.logger.info(`Saved directory ${this.config.path} with ${e.length} files`),e}getFileList(){let e=[];for(let t of this.files.keys())e.push(`${this.config.path}/${t}`);for(let[t,r]of this.subdirectories){let i=r.getFileList();e.push(...i);}return this.indexBuilder&&e.push(`${this.config.path}/index.ts`),e.sort()}getStats(){let e=this.files.size;for(let t of this.subdirectories.values())e+=t.getStats().totalFiles;return this.indexBuilder&&(e+=1),{fileCount:this.files.size,subdirectoryCount:this.subdirectories.size,hasIndex:!!this.indexBuilder,totalFiles:e}}async wouldOverwrite(){let e=[];for(let t of this.files.keys()){let r=`${this.config.path}/${t}`;await this.config.fileManager.wouldOverwrite(r)&&e.push(r);}for(let t of this.subdirectories.values()){let r=await t.wouldOverwrite();e.push(...r);}if(this.indexBuilder){let t=`${this.config.path}/index.ts`;await this.config.fileManager.wouldOverwrite(t)&&e.push(t);}return e}getPath(){return this.config.path}getFiles(){return new Map(this.files)}getSubdirectories(){return new Map(this.subdirectories)}getIndexBuilder(){return this.indexBuilder}};});var Ut={};De(Ut,{IndexBuilder:()=>rt});var rt,Ht=ie(()=>{rt=class{config;exports=new Map;namespaces=new Map;reExports=new Map;header="";footer="";groupingFunction;sortFunction;constructor(e){this.config=e;}withExports(e,t){for(let r of e)this.exports.set(r,t);return this}withExport(e,t){return this.exports.set(e,t),this}withNamespaces(e){for(let[t,r]of Object.entries(e))this.namespaces.set(t,r);return this}withNamespace(e,t){return this.namespaces.set(e,t),this}withReExports(e){for(let t of e)this.reExports.set(t,t);return this}withReExport(e){return this.reExports.set(e,e),this}withHeader(e){return this.header=e,this}withFooter(e){return this.footer=e,this}groupBy(e){return this.groupingFunction=e,this}sortBy(e){return this.sortFunction=e,this}async autoDiscover(e){return this.config.logger.debug(`Auto-discovering exports in ${this.config.directory}`),this.config.logger.warn("Auto-discovery not yet implemented - manually add exports"),this}async save(){let e=this.generateContent(),t=`${this.config.directory}/index.ts`,r=await this.config.fileManager.writeFile(t,e);return this.config.logger.debug(`Generated index file: ${t}`),r.path}build(){return this.generateContent()}generateContent(){let e=[];if(this.header&&(e.push(this.header),e.push("")),this.reExports.size>0){e.push("// Re-exports");for(let r of this.reExports.values())e.push(`export * from './${r}';`);e.push("");}if(this.exports.size>0&&(this.groupingFunction?this.generateGroupedExports(e):this.generateSimpleExports(e),e.push("")),this.namespaces.size>0){e.push("// Namespace exports");let r=Array.from(this.namespaces.entries()).sort();for(let[i,n]of r)e.push(`export * as ${i} from './${n}';`);e.push("");}return this.footer&&e.push(this.footer),`${e.join(`
10
+ `).replace(/\t/g,this.options.formatting?.useTabs?" ":" ".repeat(this.options.formatting?.indentSize||2)).trim()}async validateContent(e){if(this.options.validation==="none")return;let t=[],r=(e.match(/\{/g)||[]).length,i=(e.match(/\}/g)||[]).length;r!==i&&t.push(`Unmatched braces: ${r} open, ${i} close`);let n=(e.match(/\(/g)||[]).length,o=(e.match(/\)/g)||[]).length;if(n!==o&&t.push(`Unmatched parentheses: ${n} open, ${o} close`),(this.config.filename.endsWith(".ts")||this.config.filename.endsWith(".tsx"))&&e.includes("interface")&&!e.match(/interface\s+\w+\s*\{/)&&t.push("Invalid interface syntax detected"),t.length>0&&this.options.validation==="strict")throw new O(`Content validation failed for ${this.config.filename}: ${t.join(", ")}`,"write",this.config.filename);t.length>0&&this.config.logger.warn(`Validation issues in ${this.config.filename}: ${t.join(", ")}`);}getContent(){return this.content}getImports(){return new Map(this.imports)}getExports(){return new Set(this.exports)}};});var Xt={};Le(Xt,{DirectoryBuilder:()=>ot});var ot,er=oe(()=>{ot=class s{config;files=new Map;subdirectories=new Map;indexBuilder;shouldClean=false;constructor(e){this.config=e;}withSubdirectory(e){let t=`${this.config.path}/${e}`,r=new s({path:t,fileManager:this.config.fileManager,logger:this.config.logger.child(`Dir:${e}`)});return this.subdirectories.set(e,r),r}withFiles(e){for(let[t,r]of Object.entries(e))this.files.set(t,r);return this}withFile(e,t){return this.files.set(e,t),this}withIndex(e){return this.indexBuilder=e,this}clean(){return this.shouldClean=true,this}async ensure(){return await this.config.fileManager.ensureDirectory(this.config.path),this}async save(){let e=[];this.shouldClean&&await this.config.fileManager.cleanDirectory(this.config.path),await this.ensure();let t=Array.from(this.files.entries()).map(async([r,i])=>{try{let n=await i.save();return e.push(n),n}catch(n){throw this.config.logger.error(`Failed to save file ${r}:`,n instanceof Error?n:void 0),n}});await Promise.all(t);for(let[r,i]of this.subdirectories)try{let n=await i.save();e.push(...n);}catch(n){throw this.config.logger.error(`Failed to save subdirectory ${r}:`,n instanceof Error?n:void 0),n}if(this.indexBuilder)try{let r=await this.indexBuilder.save();e.push(r);}catch(r){throw this.config.logger.error("Failed to save index file:",r instanceof Error?r:void 0),r}return this.config.logger.info(`Saved directory ${this.config.path} with ${e.length} files`),e}getFileList(){let e=[];for(let t of this.files.keys())e.push(`${this.config.path}/${t}`);for(let[t,r]of this.subdirectories){let i=r.getFileList();e.push(...i);}return this.indexBuilder&&e.push(`${this.config.path}/index.ts`),e.sort()}getStats(){let e=this.files.size;for(let t of this.subdirectories.values())e+=t.getStats().totalFiles;return this.indexBuilder&&(e+=1),{fileCount:this.files.size,subdirectoryCount:this.subdirectories.size,hasIndex:!!this.indexBuilder,totalFiles:e}}async wouldOverwrite(){let e=[];for(let t of this.files.keys()){let r=`${this.config.path}/${t}`;await this.config.fileManager.wouldOverwrite(r)&&e.push(r);}for(let t of this.subdirectories.values()){let r=await t.wouldOverwrite();e.push(...r);}if(this.indexBuilder){let t=`${this.config.path}/index.ts`;await this.config.fileManager.wouldOverwrite(t)&&e.push(t);}return e}getPath(){return this.config.path}getFiles(){return new Map(this.files)}getSubdirectories(){return new Map(this.subdirectories)}getIndexBuilder(){return this.indexBuilder}};});var tr={};Le(tr,{IndexBuilder:()=>at});var at,rr=oe(()=>{at=class{config;exports=new Map;namespaces=new Map;reExports=new Map;header="";footer="";groupingFunction;sortFunction;constructor(e){this.config=e;}withExports(e,t){for(let r of e)this.exports.set(r,t);return this}withExport(e,t){return this.exports.set(e,t),this}withNamespaces(e){for(let[t,r]of Object.entries(e))this.namespaces.set(t,r);return this}withNamespace(e,t){return this.namespaces.set(e,t),this}withReExports(e){for(let t of e)this.reExports.set(t,t);return this}withReExport(e){return this.reExports.set(e,e),this}withHeader(e){return this.header=e,this}withFooter(e){return this.footer=e,this}groupBy(e){return this.groupingFunction=e,this}sortBy(e){return this.sortFunction=e,this}async autoDiscover(e){return this.config.logger.debug(`Auto-discovering exports in ${this.config.directory}`),this.config.logger.warn("Auto-discovery not yet implemented - manually add exports"),this}async save(){let e=this.generateContent(),t=`${this.config.directory}/index.ts`,r=await this.config.fileManager.writeFile(t,e);return this.config.logger.debug(`Generated index file: ${t}`),r.path}build(){return this.generateContent()}generateContent(){let e=[];if(this.header&&(e.push(this.header),e.push("")),this.reExports.size>0){e.push("// Re-exports");for(let r of this.reExports.values())e.push(`export * from './${r}';`);e.push("");}if(this.exports.size>0&&(this.groupingFunction?this.generateGroupedExports(e):this.generateSimpleExports(e),e.push("")),this.namespaces.size>0){e.push("// Namespace exports");let r=Array.from(this.namespaces.entries()).sort();for(let[i,n]of r)e.push(`export * as ${i} from './${n}';`);e.push("");}return this.footer&&e.push(this.footer),`${e.join(`
11
11
  `).replace(/\n{3,}/g,`
12
12
 
13
13
  `).trim()}
14
- `}generateSimpleExports(e){e.push("// Exports");let t=Array.from(this.exports.entries());this.sortFunction?t=t.sort(this.sortFunction):t=t.sort(([i],[n])=>i.localeCompare(n));let r=new Map;for(let[i,n]of t)r.has(n)||r.set(n,[]),r.get(n)?.push(i);for(let[i,n]of r){let o=n.sort();o.length===1?e.push(`export type { ${o[0]} } from './${i}';`):o.length<=3?e.push(`export type { ${o.join(", ")} } from './${i}';`):(e.push("export type {"),o.forEach((a,c)=>{let l=c===o.length-1;e.push(` ${a}${l?"":","}`);}),e.push(`} from './${i}';`));}}generateGroupedExports(e){if(!this.groupingFunction)return;let t=new Map;for(let[i,n]of this.exports){let o=this.groupingFunction(i);t.has(o)||t.set(o,new Map);let a=t.get(o);a.has(n)||a.set(n,[]),a.get(n)?.push(i);}let r=Array.from(t.entries()).sort();for(let[i,n]of r){e.push(`// ${i}`);for(let[o,a]of n){let c=a.sort();c.length===1?e.push(`export type { ${c[0]} } from './${o}';`):e.push(`export type { ${c.join(", ")} } from './${o}';`);}e.push("");}}getExports(){return new Map(this.exports)}getNamespaces(){return new Map(this.namespaces)}getReExports(){return new Map(this.reExports)}};});var ne=class s{options;dryWarnSet=new Set;constructor(e={}){this.options={timestamp:false,verbose:false,...e};}static consoleLevelsMap={1:console.log,2:console.warn,3:console.error,0:console.log,4:()=>{}};formatMessage(e,t,r){let i=this.options.timestamp?`${v.gray(new Date().toLocaleTimeString())} `:"",n=this.options.prefix?`${v.cyan(`[${this.options.prefix}]`)} `:"";return `${i}${r(e)} ${n}${t}`}isSuppressed(e){return this.options.suppressLoggingLevel==="all"||this.options.suppressLoggingLevel?.includes(e)||false}tryWriteToConsole(e,t){if(this.isSuppressed(e))return;(s.consoleLevelsMap[e]||console.log)(t);}success(e){this.tryWriteToConsole(1,this.formatMessage("",e,v.green));}error(e,t){this.isSuppressed(3)||(console.error(this.formatMessage("X",e,v.red)),t&&this.options.verbose&&(console.error(v.red(` ${t.message}`)),t.stack&&console.error(v.gray(t.stack))));}warn(e){this.tryWriteToConsole(2,this.formatMessage("!",e,v.yellow));}dry_warn(e){this.dryWarnSet.has(e)||(this.warn(e),this.dryWarnSet.add(e));}info(e){this.tryWriteToConsole(1,this.formatMessage("i",e,v.blue));}debug(e){this.options.verbose&&this.tryWriteToConsole(0,this.formatMessage("\u{1F41B}",e,v.magenta));}step(e){this.tryWriteToConsole(1,this.formatMessage("\u{1F680}",e,v.cyan));}progress(e){this.tryWriteToConsole(1,this.formatMessage("\u23F3",e,v.blue));}plain(e,t=r=>r){let r=this.options.timestamp?`${v.gray(new Date().toLocaleTimeString())} `:"",i=this.options.prefix?`${v.cyan(`[${this.options.prefix}]`)} `:"";this.tryWriteToConsole(1,`${r}${i}${t(e)}`);}dim(e){this.plain(e,v.gray);}child(e){return new s({...this.options,prefix:this.options.prefix?`${this.options.prefix}:${e}`:e})}configure(e){this.options={...this.options,...e};}},L=new ne;function se(s){L.success(s);}function C(s,e){L.error(s,e);}function Le(s){L.warn(s);}function oe(s){L.info(s);}function Ve(s){L.step(s);}function ft(s){L.dim(s);}function je(s){L.configure(s);}function R(s={}){return new ne(s)}function Ae(s){console.log(),console.log(v.cyan(v.bold(`\u2501\u2501\u2501 ${s} \u2501\u2501\u2501`)));}function Ge(s,e,t){let r=s;e&&(r+=` ${v.gray(`(${e}ms)`)}`),se(r),t&&Object.entries(t).forEach(([i,n])=>{ft(` ${i}: ${n}`);});}function V(s,e="\u2022"){s.forEach(t=>{console.log(v.gray(` ${e} ${t}`));});}var ae=s=>`${s.name}#${s.version}`,ht=s=>`${s.name}@${s.version}`,Ue=(s,e)=>(e||(e={name:"undefined",version:"undefined"}),{...s,package_meta:s.package_meta||e,name:s.name,url:s.url,base:s.base}),He=s=>s?.kind==="primitive-type",U=s=>s?.kind==="nested",mt=s=>s?.kind==="profile";var _=s=>s?.identifier.kind==="resource"||s?.identifier.kind==="complex-type"||s?.identifier.kind==="logical",yt=s=>s?.identifier.kind==="complex-type",q=s=>s?.identifier.kind==="resource",St=s=>s?.identifier.kind==="logical",ce=s=>s?.identifier.kind==="profile";function ze(s){return s?.identifier.kind==="binding"}var W=s=>s?s.choices===void 0:false,le=s=>s?s.choices!==void 0:false;function _e(s){let e=s.split("|")[0];return e||s}function nr(s){return s.split("|")[1]}function sr(s){return s.derivation==="constraint"?"profile":s.kind==="primitive-type"?"primitive-type":s.kind==="complex-type"?"complex-type":(s.kind==="resource","resource")}function N(s){return {kind:sr(s),package:s.package_meta.name,version:s.package_meta.version,name:s.name,url:s.url}}var or=s=>{let e=s.split("/"),t=e[e.length-1];return t&&t.length>0?t.split(/[-_]/).map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join(""):s};function pe(s,e){let t=_e(e),r=or(t),i={package_meta:{name:"missing_valuesets",version:nr(t)||"0.0.0"},id:e},n=s.resolveVs(t)||i,o=n?.id&&!/^[a-zA-Z0-9_-]{20,}$/.test(n.id)?n.id:r;return {kind:"value-set",package:n.package_meta.name,version:n.package_meta.version,name:o,url:t}}function ue(s,e,t){let r=e.join("."),[i,n,o]=t?[{name:"shared",version:"1.0.0"},t,`urn:fhir:binding:${t}`]:[s.package_meta,`${s.name}.${r}_binding`,`${s.url}#${r}_binding`];return {kind:"binding",package:i.name,version:i.version,name:n,url:o}}function de(s,e,t,r){let i={};if(e.derivation==="constraint"){let c=s.resolveFsSpecializations(e.url).map(l=>ge(s,l,r)).filter(l=>l!==void 0).flat();for(let l of c.reverse())i[l.identifier.name]=l.identifier.url;}let n=t.join("."),o=i[n]??`${e.url}#${n}`;return {kind:"nested",package:e.package_meta.name,version:e.package_meta.version,name:n,url:o}}function bt(s,e,t){let r=[];for(let[i,n]of Object.entries(t)){let o=[...e,i];J(n)&&r.push([o,n]),n.elements&&r.push(...bt(s,o,n.elements));}return r}function ar(s,e,t,r,i){let n={};for(let[o,a]of Object.entries(r)){let c=[...t,o],l=s.resolveElementSnapshot(e,c);J(l)?n[o]=he(s,e,c,l,i):n[o]=fe(s,e,c,l,i);}return n}function ge(s,e,t){if(!e.elements)return;let r=bt(e,[],e.elements).filter(([n,o])=>o.elements&&Object.keys(o.elements).length>0),i=[];for(let[n,o]of r){let a=de(s,e,n,t),c;o.type==="BackboneElement"||!o.type?c="BackboneElement":c=o.type;let l={kind:"complex-type",package:e.package_meta.name,version:e.package_meta.version,name:c,url:s.ensureSpecializationCanonicalUrl(c)},u=ar(s,e,n,o.elements,t),g={identifier:a,base:l,fields:u};i.push(g);}return i.sort((n,o)=>n.identifier.url.localeCompare(o.identifier.url)),i.length===0?void 0:i}function qe(s){let e=[];for(let t of s){t.base&&e.push(t.base);for(let r of Object.values(t.fields||{}))"type"in r&&r.type&&e.push(r.type),"binding"in r&&r.binding&&e.push(r.binding);}return e}function vt(s,e,t){let r=t[t.length-1],i=t.slice(0,-1),n=s.resolveFsGenealogy(e.url).flatMap(o=>{if(i.length===0)return o.required||[];if(!o.elements)return [];let a=o;for(let c of i)a=a?.elements?.[c];return a?.required||[]});return new Set(n).has(r)}function xt(s,e,t){let r=t[t.length-1];if(!r)throw new Error(`Internal error: fieldName is missing for path ${t.join("/")}`);let i=t.slice(0,-1),n=s.resolveFsGenealogy(e.url).flatMap(o=>{if(i.length===0)return o.excluded||[];if(!o.elements)return [];let a=o;for(let c of i)a=a?.elements?.[c];return a?.excluded||[]});return new Set(n).has(r)}var cr=(s,e,t)=>{if(s.refers)return s.refers.map(r=>{let i=e.ensureSpecializationCanonicalUrl(r),n=e.resolveFs(i);return N(n)})};function We(s,e,t,r,i){if(r.elementReference){let n=r.elementReference.slice(1).filter((o,a)=>a%2===1);return de(s,e,n,i)}else if(r.type){let n=s.ensureSpecializationCanonicalUrl(r.type),o=s.resolveFs(n);if(!o)throw new Error(`Could not resolve field '${r.type}'`);return N(o)}else {if(r.choices)return;if(e.derivation==="constraint")return;throw i?.error(`Can't recognize element type '${e.url}' (${e.derivation}) at '${t.join(".")}': ${JSON.stringify(r,void 0,2)}`),new Error("Unrecognized element type")}}var fe=(s,e,t,r,i)=>{let n,o;return r.binding&&(n=ue(e,t,r.binding.bindingName),r.binding.strength==="required"&&r.type==="code"&&(o=Je(s,r,i))),{type:We(s,e,t,r,i),required:vt(s,e,t),excluded:xt(s,e,t),reference:cr(r,s,e.package_meta),array:r.array||false,min:r.min,max:r.max,choices:r.choices,choiceOf:r.choiceOf,binding:n,enum:o}};function J(s){let e=s.type==="BackboneElement",t=s.type==="Element"&&s.elements!==void 0&&Object.keys(s.elements).length>0,r=s.type===void 0&&s.choiceOf===void 0&&s.elements!==void 0&&Object.keys(s.elements).length>0;return e||t||r}function he(s,e,t,r,i){return {type:de(s,e,t,i),array:r.array||false,required:vt(s,e,t),excluded:xt(s,e,t)}}function Ke(s,e,t){let r=_e(e)||e,i=s.resolveVs(r);if(i)return lr(s,i)}function lr(s,e,t){if(e.expansion?.contains)return e.expansion.contains;let r=[];if(e.compose?.include){for(let i of e.compose.include)if(i.concept)for(let n of i.concept)r.push({system:i.system,code:n.code,display:n.display});else if(i.system&&!i.filter)try{let n=s.resolveAny(i.system);if(n?.concept){let o=(a,c)=>{for(let l of a)r.push({system:c,code:l.code,display:l.display}),l.concept&&o(l.concept,c);};o(n.concept,i.system);}}catch{}}return r.length>0?r:void 0}var Tt=100;function Je(s,e,t){if(!e.binding)return;let r=e.binding.strength,i=e.binding.valueSet;if(!i||!(r==="required"||r==="extensible"&&(e.type==="code"||e.type==="Coding")||r==="preferred"&&(e.type==="code"||e.type==="Coding")))return;let o=Ke(s,i);if(!o||o.length===0)return;let a=o.map(c=>c.code).filter(c=>c&&typeof c=="string"&&c.trim().length>0);if(a.length>Tt){t?.dry_warn(`Value set ${i} has ${a.length} which is more than ${Tt} codes, which may cause issues with code generation.`);return}return a.length>0?a:void 0}function pr(s,e,t,r,i){if(!r.binding?.valueSet)return;let n=ue(e,t,r.binding.bindingName),o=We(s,e,t,r,i),a=pe(s,r.binding.valueSet),c=[];o&&c.push(o),c.push(a);let l=Je(s,r,i);return {identifier:n,type:o,valueset:a,strength:r.binding.strength,enum:l,dependencies:c}}function wt(s,e,t){let r=new Set;if(!e.elements)return [];let i=[];function n(c,l){for(let[u,g]of Object.entries(c)){let m=[...l,u],p=m.join(".");if(!r.has(p)){if(r.add(p),g.binding){let h=pr(s,e,m,g,t);h&&i.push(h);}g.elements&&n(g.elements,m);}}}n(e.elements,[]),i.sort((c,l)=>c.identifier.name.localeCompare(l.identifier.name));let o=[],a=new Set;for(let c of i)a.has(c.identifier.url)||(a.add(c.identifier.url),o.push(c));return o}function Ct(s,e,t,r,i){if(!r)return;let n={};for(let o of s.getAllElementKeys(r)){let a=[...t,o],c=s.resolveElementSnapshot(e,a);J(c)?n[o]=he(s,e,a,c,i):n[o]=fe(s,e,a,c,i);}return n}function kt(s){let e=[];for(let t of Object.values(s))"type"in t&&t.type&&e.push(t.type),"binding"in t&&t.binding&&e.push(t.binding);return e}function ur(s){let e=new Set,t=[];for(let r of s){let i=r.url;e.has(i)||(e.add(i),t.push(r));}return t.sort((r,i)=>r.name.localeCompare(i.name)),t}function dr(s,e){return !!(s.base==="Extension"||s.base==="http://hl7.org/fhir/StructureDefinition/Extension"||s.url?.includes("/extension/")||s.url?.includes("-extension")||s.name?.toLowerCase().includes("extension")||s.type==="Extension")}async function me(s,e,t){if(!e.url)throw new Error("ValueSet URL is required");let r=pe(s,e.url),i=Ke(s,e.url);return {identifier:r,description:e.description,concept:i,compose:i?void 0:e.compose}}async function gr(s,e,t){try{let r=N(s),i;if(s.base&&s.base!=="Extension"){let a=s.base.includes("/")?s.base:`http://hl7.org/fhir/StructureDefinition/${s.base}`;i={kind:"complex-type",package:"hl7.fhir.r4.core",version:"4.0.1",name:s.base.split("/").pop()||s.base,url:a};}else i={kind:"complex-type",package:"hl7.fhir.r4.core",version:"4.0.1",name:"Extension",url:"http://hl7.org/fhir/StructureDefinition/Extension"};let n={identifier:r,base:i,description:s.description,dependencies:[],metadata:{isExtension:!0}};if(i&&n.dependencies.push(i),s.elements){let a=Ct(e,s,[],s.elements,t);a&&Object.keys(a).length>0&&(n.fields=a,n.dependencies.push(...kt(a)));}let o=ge(e,s,t);return o&&o.length>0&&(n.nested=o,n.dependencies.push(...qe(o))),n.dependencies=ur(n.dependencies),n.dependencies=n.dependencies.filter(a=>a.url!==r.url),n}catch(r){return console.warn(`Failed to transform extension ${s.name}: ${r}`),null}}function fr(s,e,t,r){let i=[];e&&i.push(e),t&&i.push(...kt(t)),r&&i.push(...qe(r));let n={};for(let c of i)c.url!==s.url&&(n[c.url]=c);let o=new Set(r?.map(c=>c.identifier.url)),a=Object.values(n).filter(c=>mt(s)||!U(c)?true:!o.has(c.url)).sort((c,l)=>c.url.localeCompare(l.url));return a.length>0?a:void 0}function hr(s,e,t){let r=N(e),i;if(e.base&&e.type!=="Element"){let u=s.resolveFs(s.ensureSpecializationCanonicalUrl(e.base));if(!u)throw new Error(`Base resource not found '${e.base}' for '${e.url}'`);i=N(u);}let n=Ct(s,e,[],e.elements,t),o=ge(s,e,t),a=fr(r,i,n,o),c={identifier:r,base:i,fields:n,nested:o,description:e.description,dependencies:a},l=wt(s,e,t);return [c,...l]}async function ye(s,e,t){let r=[];N(e);if(dr(e)){let n=await gr(e,s,t);return n&&r.push(n),r}return hr(s,e,t)}var M=class{cache=new Map;config;cacheDir;constructor(e){this.config={enablePersistence:true,cacheDir:".typeschema-cache",maxAge:1440*60*1e3,validateCached:true,...e},this.config.enablePersistence&&this.config.cacheDir&&(this.cacheDir=this.config.cacheDir);}async set(e){let t=this.generateKey(e.identifier);this.cache.set(t,e),this.config.enablePersistence&&this.cacheDir&&await this.persistSchema(e);}get(e){let t=this.generateKey(e);return this.cache.get(t)||null}getByUrl(e){for(let t of this.cache.values())if(t.identifier.url===e)return t;return null}has(e){let t=this.generateKey(e);return this.cache.has(t)}hasByUrl(e){for(let t of this.cache.values())if(t.identifier.url===e)return true;return false}delete(e){let t=this.generateKey(e);return this.cache.delete(t)}deleteByUrl(e){for(let[t,r]of this.cache.entries())if(r.identifier.url===e)return this.cache.delete(t);return false}getByPackage(e){let t=[];for(let r of this.cache.values())r.identifier.package===e&&t.push(r);return t}getByKind(e){let t=[];for(let r of this.cache.values())r.identifier.kind===e&&t.push(r);return t}setMany(e){for(let t of e)this.set(t);}clear(){this.cache.clear();}generateKey(e){return `${e.package}:${e.version}:${e.kind}:${e.name}`}async initialize(){this.config.enablePersistence&&this.cacheDir&&(existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:true}),await this.loadFromDisk());}async loadFromDisk(){if(!(!this.cacheDir||!existsSync(this.cacheDir)))try{let t=(await readdir(this.cacheDir)).filter(r=>r.endsWith(".typeschema.json"));for(let r of t){let i=join(this.cacheDir,r),n=await stat(i);if(this.config.maxAge&&Date.now()-n.mtimeMs>this.config.maxAge){await unlink(i);continue}try{let o=await readFile(i,"utf-8"),a=JSON.parse(o);if(this.config.validateCached&&!a.schema?.identifier)continue;let c=this.generateKey(a.schema.identifier);this.cache.set(c,a.schema);}catch(o){console.warn(`Failed to load cached schema from ${r}:`,o);}}}catch(e){console.warn("Failed to load cached schemas from disk:",e);}}async persistSchema(e){if(!this.cacheDir)return;existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:true});let t={schema:e,timestamp:Date.now(),version:e.identifier.version},r=`${e.identifier.package}-${e.identifier.version}-${e.identifier.kind}-${e.identifier.name}.typeschema.json`.replace(/[^a-zA-Z0-9.-]/g,"_"),i=join(this.cacheDir,r);try{await writeFile(i,JSON.stringify(t,null,2),"utf-8");}catch(n){console.warn(`Failed to persist schema to ${i}:`,n);}}async clearDisk(){if(!(!this.cacheDir||!existsSync(this.cacheDir)))try{let t=(await readdir(this.cacheDir)).filter(r=>r.endsWith(".typeschema.json"));for(let r of t)await unlink(join(this.cacheDir,r));}catch(e){console.warn("Failed to clear cache directory:",e);}}};var K=async(s,e)=>{let t=e?.packageNameResolver??["hl7.fhir.r5.core","hl7.cda.uv.core"],r=e?.logger,i={},n={},o=new Set(["StructureDefinition","ValueSet","CodeSystem"]);for(let d of await s.search({})){let f=d.url;if(!f||!o.has(d.resourceType))continue;let y=f,x=(await s.resolveEntry(y)).package;if(!x)throw new Error(`Can't resolve package for ${y}`);n[y]||(n[y]=[]),n[y].push(x),i[y]=d;}let a=Object.entries(n).filter(([d,f])=>f.length>1).map(([d,f])=>`${d}: ${f.map(y=>`${y.name}@${y.version}`).join(", ")}`).join(`
15
- `);r?.warn(`Duplicated canonicals: ${a}`);let c={},l={};for(let[d,f]of Object.entries(n)){let y=(await s.resolveEntry(d)).package;if(!y)throw new Error(`Can't find package for ${d}`);let x=ae(y);l[x]=y;let b=await s.resolve(d);c[x]||(c[x]={});let re=c[x];if(!re)throw new Error(`Can't find index for ${y.name}@${y.version}`);re[d]=b;}let u=[];for(let[d,f]of Object.entries(c))u.push({package_meta:l[d],index:f});let g={},m={},p={};for(let d of u){let f=d.package_meta,y=0;r?.info(`FHIR Schema conversion for '${ae(f)}' begins...`);for(let[x,b]of Object.entries(d.index)){let re=x;if(b.resourceType==="StructureDefinition"){let dt=b;g[re]=dt;let gt=Ue(It.translate(dt),f);y++,p[gt.url]=gt;}b.resourceType==="ValueSet"&&(b.package_meta||(b.package_meta=f),m[b.url]=b);}r?.success(`FHIR Schema conversion for '${ae(f)}' completed: ${y} successful`);}let h={};for(let d of Object.values(p)){if(d.derivation==="constraint")continue;let f=d.name;h[f]||(h[f]={}),h[f][d.package_meta.name]=d.url;}let S={};for(let[d,f]of Object.entries(h)){let y=d,x=Object.values(f);if(x.length===1){let b=x[0];S[y]=b;}else {for(let b of t)if(f[b]){S[y]=f[b];break}if(S[y]===void 0)throw new Error(`No canonical URL found for ${y}`)}}let w={};for(let d of Object.values(p))d.kind==="complex-type"&&(w[d.url]=d);let T=d=>{let f=p[d];if(f===void 0)throw new Error(`Failed to resolve FHIR Schema genealogy for '${d}'`);let y=[f];for(;f?.base;)if(f=p[f.base]||p[S[f.base]],y.push(f),f===void 0)throw new Error(`Failed to resolve FHIR Schema genealogy for '${d}'`);return y};return {...s,appendFs(d){let f=Ue(d);p[f.url]=f,S[f.name]=f.url;},resolveFs:d=>p[d],resolveFsGenealogy:T,resolveFsSpecializations:d=>T(d).filter(f=>f.derivation==="specialization"),ensureSpecializationCanonicalUrl:d=>S[d]||d,allSd:()=>Object.values(g),resolveSd:d=>g[d],allFs:()=>Object.values(p),allVs:()=>Object.values(m),resolveVs:d=>m[d],complexTypeDict:()=>w,resolveAny:d=>i[d],resolveElementSnapshot:(d,f)=>{let y=T(d.url),x=br(y,f);return vr(x)},getAllElementKeys:d=>{let f=new Set;for(let[y,x]of Object.entries(d)){f.add(y);for(let b of x?.choices||[])d[b]||f.add(b);}return Array.from(f)}}};var br=(s,e)=>{let[t,...r]=e;return t===void 0?[]:s.map(i=>{if(!i.elements)return;let n=i.elements?.[t];for(let o of r)n=n?.elements?.[o];return n}).filter(i=>i!==void 0)};function vr(s){let e=s.reverse().reduce((t,r)=>({...t,...r}),{});return e.elements=void 0,e}var O=class{manager;options;cacheConfig;cache;logger;constructor(e={},t){this.options={verbose:false,...e},this.manager=e.manager||CanonicalManager({packages:[],workingDir:"tmp/fhir"}),this.cacheConfig=t,this.logger=e.logger||R({verbose:this.options.verbose,prefix:"TypeSchema"});}async initializeCache(){this.cacheConfig&&!this.cache&&(this.cache=new M(this.cacheConfig),await this.cache.initialize());}async registerFromPackageMetas(e){let t=e.map(r=>`${r.name}${r.version}`);return this.logger?.step(`Loading FHIR packages: ${t.join(", ")}`),await this.manager.init(),K(this.manager)}generateFhirSchemas(e){this.logger?.progress(`Converting ${e.length} StructureDefinitions to FHIRSchemas`);let t=this.applyStructureDefinitionTreeshaking(e),r=[],i=0,n=0;for(let o of t)try{let a=It.translate(o);r.push(a),i++,this.logger?.debug(`Converted StructureDefinition: ${o.name||o.id} (${o.resourceType})`);}catch(a){n++,this.logger?.warn(`Failed to convert StructureDefinition ${o.name||o.id}: ${a instanceof Error?a.message:String(a)}`);}return this.logger?.success(`FHIR Schema conversion completed: ${i}/${t.length} successful, ${n} failed`),r}async generateValueSetSchemas(e,t){e.length>0&&this.logger?.debug(`${e.length} ValueSets available for enum extraction`);let r=await K(this.manager,{logger:this.logger}),i=[];if(e.length>0){this.logger?.progress(`Converting ${e.length} ValueSets to TypeSchema`);let n=0,o=0;for(let a of e)try{let c=await me(r,a,t);c&&(i.push(c),n++,this.logger?.debug(`Converted ValueSet: ${a.name||a.id}`));}catch(c){o++,this.logger?.warn(`Failed to convert ValueSet ${a.name||a.id}: ${c instanceof Error?c.message:String(c)}`);}this.logger?.success(`ValueSet conversion completed: ${n}/${e.length} successful, ${o} failed`);}return i}async generateFromPackage(e,t,r){if(await this.initializeCache(),this.cache&&!(this.cacheConfig?.forceRegenerate??false)){let l=this.cache.getByPackage(e);if(l.length>0)return this.logger?.info(`Using cached TypeSchemas for package: ${e} (${l.length} schemas)`),l}let i={name:e,version:t||"latest"},n=await this.registerFromPackageMetas([i]),o=await this.generateValueSetSchemas(n.allVs(),r),c=[...(await Promise.all(n.allFs().map(async l=>await ye(n,l,r)))).flat(),...o];if(this.cache)for(let l of c)await this.cache.set(l);return c}applyStructureDefinitionTreeshaking(e){let t=this.options.treeshake;if(!t||t.length===0)return e;this.logger?.info(`Applying treeshaking filter for ResourceTypes: ${t.join(", ")}`);let r=new Map,i=new Map,n=new Map;for(let u of e){let g=u.name||u.id;g&&(r.set(g,u),i.set(g,new Set),n.set(g,new Set));}for(let u of e){let g=u.name||u.id;if(!g)continue;let{realDeps:m,refTargets:p}=this.extractStructureDefinitionDependenciesWithReferences(u);i.set(g,new Set(m)),n.set(g,new Set(p));}let o=new Set;for(let u of t)r.has(u)?o.add(u):this.logger?.warn(`ResourceType '${u}' not found in structure definitions`);let a=(u,g=new Set)=>{if(g.has(u)||!i.has(u))return;g.add(u);let m=i.get(u)||new Set;for(let p of Array.from(m))r.has(p)&&(o.add(p),a(p,g));};for(let u of Array.from(o))a(u);let c=e.filter(u=>{let g=u.name||u.id;return g&&o.has(g)}),l=new Set;for(let u of e){let g=u.name||u.id;g&&!o.has(g)&&Array.from(n.values()).some(p=>p.has(g))&&l.add(g);}return l.size>0&&this.logger?.info(`Excluded reference-only targets: ${Array.from(l).join(", ")}`),this.logger?.success(`Treeshaking completed: kept ${c.length}/${e.length} structure definitions`),c}extractStructureDefinitionDependenciesWithReferences(e){let t=new Set,r=new Set;if(e.baseDefinition){let i=this.extractResourceNameFromUrl(e.baseDefinition);i&&t.add(i);}if(e.snapshot?.element||e.differential?.element){let i=e.snapshot?.element||e.differential?.element;for(let n of i)if(n.type)for(let o of n.type){if(o.code&&(t.add(o.code),o.code==="Reference"&&o.targetProfile))for(let a of o.targetProfile){let c=this.extractResourceNameFromUrl(a);c&&r.add(c);}if(o.profile)for(let a of o.profile){let c=this.extractResourceNameFromUrl(a);c&&t.add(c);}}}return {realDeps:Array.from(t),refTargets:Array.from(r)}}extractResourceNameFromUrl(e){let t=e.match(/\/([^/]+)$/);return t?t[1]??null:null}};var H=class{options;constructor(e={}){this.options={format:"auto",validate:true,strict:false,...e};}async parseFromFile(e){let t=await readFile(e,"utf-8"),r=this.options.format==="auto"?this.detectFormat(t,e):this.options.format;return this.parseFromString(t,r)}async parseFromString(e,t){let r=t||this.detectFormat(e),i;return r==="ndjson"?i=this.parseNDJSON(e):i=this.parseJSON(e),this.options.validate&&this.validateSchemas(i),i}async parseFromFiles(e){let t=[];for(let r of e){let i=await this.parseFromFile(r);t.push(...i);}return t}parseSchema(e){if(!e.identifier)throw new Error("TypeSchema must have an identifier");if(!this.isValidIdentifier(e.identifier))throw new Error("TypeSchema identifier is invalid");return e}findByIdentifier(e,t){return e.filter(r=>this.matchesIdentifier(r.identifier,t))}findByUrl(e,t){return e.find(r=>r.identifier.url===t)}findByKind(e,t){return e.filter(r=>r.identifier.kind===t)}findByPackage(e,t){return e.filter(r=>r.identifier.package===t)}detectFormat(e,t){if(t){if(t.endsWith(".ndjson"))return "ndjson";if(t.endsWith(".json"))return "json"}let r=e.trim();if(r.includes(`
14
+ `}generateSimpleExports(e){e.push("// Exports");let t=Array.from(this.exports.entries());this.sortFunction?t=t.sort(this.sortFunction):t=t.sort(([i],[n])=>i.localeCompare(n));let r=new Map;for(let[i,n]of t)r.has(n)||r.set(n,[]),r.get(n)?.push(i);for(let[i,n]of r){let o=n.sort();o.length===1?e.push(`export type { ${o[0]} } from './${i}';`):o.length<=3?e.push(`export type { ${o.join(", ")} } from './${i}';`):(e.push("export type {"),o.forEach((a,c)=>{let l=c===o.length-1;e.push(` ${a}${l?"":","}`);}),e.push(`} from './${i}';`));}}generateGroupedExports(e){if(!this.groupingFunction)return;let t=new Map;for(let[i,n]of this.exports){let o=this.groupingFunction(i);t.has(o)||t.set(o,new Map);let a=t.get(o);a.has(n)||a.set(n,[]),a.get(n)?.push(i);}let r=Array.from(t.entries()).sort();for(let[i,n]of r){e.push(`// ${i}`);for(let[o,a]of n){let c=a.sort();c.length===1?e.push(`export type { ${c[0]} } from './${o}';`):e.push(`export type { ${c.join(", ")} } from './${o}';`);}e.push("");}}getExports(){return new Map(this.exports)}getNamespaces(){return new Map(this.namespaces)}getReExports(){return new Map(this.reExports)}};});var H=class s{options;dryWarnSet=new Set;constructor(e={}){this.options={timestamp:false,verbose:false,...e};}static consoleLevelsMap={1:console.log,2:console.warn,3:console.error,0:console.log,4:()=>{}};formatMessage(e,t,r){let i=this.options.timestamp?`${h.gray(new Date().toLocaleTimeString())} `:"",n=this.options.prefix?`${h.cyan(`[${this.options.prefix}]`)} `:"";return `${i}${r(e)} ${n}${t}`}isSuppressed(e){return this.options.suppressLoggingLevel==="all"||this.options.suppressLoggingLevel?.includes(e)||false}tryWriteToConsole(e,t){if(this.isSuppressed(e))return;(s.consoleLevelsMap[e]||console.log)(t);}success(e){this.tryWriteToConsole(1,this.formatMessage("",e,h.green));}error(e,t){this.isSuppressed(3)||(console.error(this.formatMessage("X",e,h.red)),t&&this.options.verbose&&(console.error(h.red(` ${t.message}`)),t.stack&&console.error(h.gray(t.stack))));}warn(e){this.tryWriteToConsole(2,this.formatMessage("!",e,h.yellow));}dry_warn(e){this.dryWarnSet.has(e)||(this.warn(e),this.dryWarnSet.add(e));}info(e){this.tryWriteToConsole(1,this.formatMessage("i",e,h.blue));}debug(e){this.options.verbose&&this.tryWriteToConsole(0,this.formatMessage("\u{1F41B}",e,h.magenta));}step(e){this.tryWriteToConsole(1,this.formatMessage("\u{1F680}",e,h.cyan));}progress(e){this.tryWriteToConsole(1,this.formatMessage("\u23F3",e,h.blue));}plain(e,t=r=>r){let r=this.options.timestamp?`${h.gray(new Date().toLocaleTimeString())} `:"",i=this.options.prefix?`${h.cyan(`[${this.options.prefix}]`)} `:"";this.tryWriteToConsole(1,`${r}${i}${t(e)}`);}dim(e){this.plain(e,h.gray);}child(e){return new s({...this.options,prefix:this.options.prefix?`${this.options.prefix}:${e}`:e})}configure(e){this.options={...this.options,...e};}},L=new H;function ae(s){L.success(s);}function b(s,e){L.error(s,e);}function Ve(s){L.warn(s);}function ce(s){L.info(s);}function je(s){L.step(s);}function mt(s){L.dim(s);}function Ge(s){L.configure(s);}function C(s={}){return new H(s)}function He(s){console.log(),console.log(h.cyan(h.bold(`\u2501\u2501\u2501 ${s} \u2501\u2501\u2501`)));}function Ue(s,e,t){let r=s;e&&(r+=` ${h.gray(`(${e}ms)`)}`),ae(r),t&&Object.entries(t).forEach(([i,n])=>{mt(` ${i}: ${n}`);});}function A(s,e="\u2022"){s.forEach(t=>{console.log(h.gray(` ${e} ${t}`));});}var F=s=>`${s.name}#${s.version}`,ht=s=>`${s.name}@${s.version}`,_e=(s,e)=>(e||(e={name:"undefined",version:"undefined"}),{...s,package_meta:s.package_meta||e,name:s.name,url:s.url,base:s.base}),ze=s=>s?.kind==="primitive-type",U=s=>s?.kind==="nested",yt=s=>s?.kind==="profile";var J=s=>s?.identifier.kind==="resource"||s?.identifier.kind==="complex-type"||s?.identifier.kind==="logical",St=s=>s?.identifier.kind==="complex-type",K=s=>s?.identifier.kind==="resource",bt=s=>s?.identifier.kind==="logical",le=s=>s?.identifier.kind==="profile";function qe(s){return s?.identifier.kind==="binding"}var Z=s=>s?s.choices===void 0:false,_=s=>s?s.choices!==void 0:false,We=s=>s.resourceType==="ValueSet",vt=s=>s.resourceType==="CodeSystem",Tt=(s,e)=>{if(!s.url)throw new Error("ValueSet must have a URL");if(!s.name)throw new Error("ValueSet must have a name");return {...s,package_meta:s.package_meta||e,name:s.name,url:s.url}};function Je(s){let e=s.split("|")[0];return e||s}function Sr(s){return s.split("|")[1]}function br(s){return s.derivation==="constraint"?"profile":s.kind==="primitive-type"?"primitive-type":s.kind==="complex-type"?"complex-type":(s.kind==="resource","resource")}function P(s){return {kind:br(s),package:s.package_meta.name,version:s.package_meta.version,name:s.name,url:s.url}}var vr=s=>{let e=s.split("/"),t=e[e.length-1];return t&&t.length>0?t.split(/[-_]/).map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join(""):s};function pe(s,e,t){let r=Je(t),i=vr(r),n={package_meta:{name:"missing_valuesets",version:Sr(r)||"0.0.0"},id:t},o=s.resolveVs(e,r)||n,a=o?.id&&!/^[a-zA-Z0-9_-]{20,}$/.test(o.id)?o.id:i;return {kind:"value-set",package:o.package_meta.name,version:o.package_meta.version,name:a,url:r}}function ue(s,e,t){let r=e.join("."),[i,n,o]=t?[{name:"shared",version:"1.0.0"},t,`urn:fhir:binding:${t}`]:[s.package_meta,`${s.name}.${r}_binding`,`${s.url}#${r}_binding`];return {kind:"binding",package:i.name,version:i.version,name:n,url:o}}function ge(s,e,t,r){let i={};if(e.derivation==="constraint"){let c=s.resolveFsSpecializations(e.package_meta,e.url).map(l=>de(s,l,r)).filter(l=>l!==void 0).flat();for(let l of c.reverse())i[l.identifier.name]=l.identifier.url;}let n=t.join("."),o=i[n]??`${e.url}#${n}`;return {kind:"nested",package:e.package_meta.name,version:e.package_meta.version,name:n,url:o}}function xt(s,e,t){let r=[];for(let[i,n]of Object.entries(t)){let o=[...e,i];Y(n)&&r.push([o,n]),n.elements&&r.push(...xt(s,o,n.elements));}return r}function Tr(s,e,t,r,i){let n={};for(let[o,a]of Object.entries(r)){let c=[...t,o],l=s.resolveElementSnapshot(e,c);Y(l)?n[o]=me(s,e,c,l,i):n[o]=fe(s,e,c,l,i);}return n}function de(s,e,t){if(!e.elements)return;let r=xt(e,[],e.elements).filter(([n,o])=>o.elements&&Object.keys(o.elements).length>0),i=[];for(let[n,o]of r){let a=ge(s,e,n,t),c;o.type==="BackboneElement"||!o.type?c="BackboneElement":c=o.type;let l={kind:"complex-type",package:e.package_meta.name,version:e.package_meta.version,name:c,url:s.ensureSpecializationCanonicalUrl(e.package_meta,c)},d=Tr(s,e,n,o.elements,t),f={identifier:a,base:l,fields:d};i.push(f);}return i.sort((n,o)=>n.identifier.url.localeCompare(o.identifier.url)),i.length===0?void 0:i}function Ke(s){let e=[];for(let t of s){t.base&&e.push(t.base);for(let r of Object.values(t.fields||{}))"type"in r&&r.type&&e.push(r.type),"binding"in r&&r.binding&&e.push(r.binding);}return e}function wt(s,e,t){let r=t[t.length-1],i=t.slice(0,-1),n=s.resolveFsGenealogy(e.package_meta,e.url).flatMap(o=>{if(i.length===0)return o.required||[];if(!o.elements)return [];let a=o;for(let c of i)a=a?.elements?.[c];return a?.required||[]});return new Set(n).has(r)}function kt(s,e,t){let r=t[t.length-1];if(!r)throw new Error(`Internal error: fieldName is missing for path ${t.join("/")}`);let i=t.slice(0,-1),n=s.resolveFsGenealogy(e.package_meta,e.url).flatMap(o=>{if(i.length===0)return o.excluded||[];if(!o.elements)return [];let a=o;for(let c of i)a=a?.elements?.[c];return a?.excluded||[]});return new Set(n).has(r)}var xr=(s,e,t)=>{if(t.refers)return t.refers.map(r=>{let i=s.ensureSpecializationCanonicalUrl(e.package_meta,r),n=s.resolveFs(e.package_meta,i);return P(n)})};function Ze(s,e,t,r,i){if(r.elementReference){let n=r.elementReference.slice(1).filter((o,a)=>a%2===1);return ge(s,e,n,i)}else if(r.type){let n=s.ensureSpecializationCanonicalUrl(e.package_meta,r.type),o=s.resolveFs(e.package_meta,n);if(!o)throw new Error(`Could not resolve field type: '${r.type}'`);return P(o)}else {if(r.choices)return;if(e.derivation==="constraint")return;throw i?.error(`Can't recognize element type '${e.url}' (${e.derivation}) at '${t.join(".")}': ${JSON.stringify(r,void 0,2)}`),new Error("Unrecognized element type")}}var fe=(s,e,t,r,i)=>{let n,o;return r.binding&&(n=ue(e,t,r.binding.bindingName),r.binding.strength==="required"&&r.type==="code"&&(o=Ye(s,e,r,i))),{type:Ze(s,e,t,r,i),required:wt(s,e,t),excluded:kt(s,e,t),reference:xr(s,e,r),array:r.array||false,min:r.min,max:r.max,choices:r.choices,choiceOf:r.choiceOf,binding:n,enum:o}};function Y(s){let e=s.type==="BackboneElement",t=s.type==="Element"&&s.elements!==void 0&&Object.keys(s.elements).length>0,r=s.type===void 0&&s.choiceOf===void 0&&s.elements!==void 0&&Object.keys(s.elements).length>0;return e||t||r}function me(s,e,t,r,i){return {type:ge(s,e,t,i),array:r.array||false,required:wt(s,e,t),excluded:kt(s,e,t)}}function Qe(s,e,t,r){let i=Je(t)||t,n=s.resolveVs(e,i);if(n)return wr(s,n)}function wr(s,e,t){if(e.expansion?.contains)return e.expansion.contains;let r=[];if(e.compose?.include){for(let i of e.compose.include)if(i.concept)for(let n of i.concept)r.push({system:i.system,code:n.code,display:n.display});else if(i.system&&!i.filter)try{let n=s.resolveAny(i.system);if(n?.concept){let o=(a,c)=>{for(let l of a)r.push({system:c,code:l.code,display:l.display}),l.concept&&o(l.concept,c);};o(n.concept,i.system);}}catch{}}return r.length>0?r:void 0}var Ct=100;function Ye(s,e,t,r){if(!t.binding)return;let i=t.binding.strength,n=t.binding.valueSet;if(!n||!(i==="required"||i==="extensible"&&(t.type==="code"||t.type==="Coding")||i==="preferred"&&(t.type==="code"||t.type==="Coding")))return;let a=Qe(s,e.package_meta,n);if(!a||a.length===0)return;let c=a.map(l=>l.code).filter(l=>l&&typeof l=="string"&&l.trim().length>0);if(c.length>Ct){r?.dry_warn(`Value set ${n} has ${c.length} which is more than ${Ct} codes, which may cause issues with code generation.`);return}return c.length>0?c:void 0}function kr(s,e,t,r,i){if(!r.binding?.valueSet)return;let n=ue(e,t,r.binding.bindingName),o=Ze(s,e,t,r,i),a=pe(s,e.package_meta,r.binding.valueSet),c=[];o&&c.push(o),c.push(a);let l=Ye(s,e,r,i);return {identifier:n,type:o,valueset:a,strength:r.binding.strength,enum:l,dependencies:c}}function Ft(s,e,t){let r=new Set;if(!e.elements)return [];let i=[];function n(c,l){for(let[d,f]of Object.entries(c)){let g=[...l,d],p=g.join(".");if(!r.has(p)){if(r.add(p),f.binding){let u=kr(s,e,g,f,t);u&&i.push(u);}f.elements&&n(f.elements,g);}}}n(e.elements,[]),i.sort((c,l)=>c.identifier.name.localeCompare(l.identifier.name));let o=[],a=new Set;for(let c of i)a.has(c.identifier.url)||(a.add(c.identifier.url),o.push(c));return o}function $t(s,e,t,r,i){if(!r)return;let n={};for(let o of s.getAllElementKeys(r)){let a=[...t,o],c=s.resolveElementSnapshot(e,a);Y(c)?n[o]=me(s,e,a,c,i):n[o]=fe(s,e,a,c,i);}return n}function Rt(s){let e=[];for(let t of Object.values(s))"type"in t&&t.type&&e.push(t.type),"binding"in t&&t.binding&&e.push(t.binding);return e}function Cr(s){let e=new Set,t=[];for(let r of s){let i=r.url;e.has(i)||(e.add(i),t.push(r));}return t.sort((r,i)=>r.name.localeCompare(i.name)),t}function Fr(s,e){return !!(s.base==="Extension"||s.base==="http://hl7.org/fhir/StructureDefinition/Extension"||s.url?.includes("/extension/")||s.url?.includes("-extension")||s.name?.toLowerCase().includes("extension")||s.type==="Extension")}async function he(s,e,t){if(!e.url)throw new Error("ValueSet URL is required");let r=pe(s,e.package_meta,e.url),i=Qe(s,e.package_meta,e.url);return {identifier:r,description:e.description,concept:i,compose:i?void 0:e.compose}}async function $r(s,e,t){try{let r=P(s),i;if(s.base&&s.base!=="Extension"){let a=s.base.includes("/")?s.base:`http://hl7.org/fhir/StructureDefinition/${s.base}`;i={kind:"complex-type",package:"hl7.fhir.r4.core",version:"4.0.1",name:s.base.split("/").pop()||s.base,url:a};}else i={kind:"complex-type",package:"hl7.fhir.r4.core",version:"4.0.1",name:"Extension",url:"http://hl7.org/fhir/StructureDefinition/Extension"};let n={identifier:r,base:i,description:s.description,dependencies:[],metadata:{isExtension:!0}};if(i&&n.dependencies.push(i),s.elements){let a=$t(e,s,[],s.elements,t);a&&Object.keys(a).length>0&&(n.fields=a,n.dependencies.push(...Rt(a)));}let o=de(e,s,t);return o&&o.length>0&&(n.nested=o,n.dependencies.push(...Ke(o))),n.dependencies=Cr(n.dependencies),n.dependencies=n.dependencies.filter(a=>a.url!==r.url),n}catch(r){return console.warn(`Failed to transform extension ${s.name}: ${r}`),null}}function Rr(s,e,t,r){let i=[];e&&i.push(e),t&&i.push(...Rt(t)),r&&i.push(...Ke(r));let n={};for(let c of i)c.url!==s.url&&(n[c.url]=c);let o=new Set(r?.map(c=>c.identifier.url)),a=Object.values(n).filter(c=>yt(s)||!U(c)?true:!o.has(c.url)).sort((c,l)=>c.url.localeCompare(l.url));return a.length>0?a:void 0}function Ir(s,e,t){let r=P(e),i;if(e.base&&e.type!=="Element"){let d=s.resolveFs(e.package_meta,s.ensureSpecializationCanonicalUrl(e.package_meta,e.base));if(!d)throw new Error(`Base resource not found '${e.base}' for '${e.url}'`);i=P(d);}let n=$t(s,e,[],e.elements,t),o=de(s,e,t),a=Rr(r,i,n,o),c={identifier:r,base:i,fields:n,nested:o,description:e.description,dependencies:a},l=Ft(s,e,t);return [c,...l]}async function ye(s,e,t){let r=[];P(e);if(Fr(e)){let n=await $r(e,s,t);return n&&r.push(n),r}return Ir(s,e,t)}var N=class{cache=new Map;config;cacheDir;constructor(e){this.config={enablePersistence:true,cacheDir:".typeschema-cache",maxAge:1440*60*1e3,validateCached:true,...e},this.config.enablePersistence&&this.config.cacheDir&&(this.cacheDir=this.config.cacheDir);}async set(e){let t=this.generateKey(e.identifier);this.cache.set(t,e),this.config.enablePersistence&&this.cacheDir&&await this.persistSchema(e);}get(e){let t=this.generateKey(e);return this.cache.get(t)||null}getByUrl(e){for(let t of this.cache.values())if(t.identifier.url===e)return t;return null}has(e){let t=this.generateKey(e);return this.cache.has(t)}hasByUrl(e){for(let t of this.cache.values())if(t.identifier.url===e)return true;return false}delete(e){let t=this.generateKey(e);return this.cache.delete(t)}deleteByUrl(e){for(let[t,r]of this.cache.entries())if(r.identifier.url===e)return this.cache.delete(t);return false}getByPackage(e){let t=[];for(let r of this.cache.values())r.identifier.package===e&&t.push(r);return t}getByKind(e){let t=[];for(let r of this.cache.values())r.identifier.kind===e&&t.push(r);return t}setMany(e){for(let t of e)this.set(t);}clear(){this.cache.clear();}generateKey(e){return `${e.package}:${e.version}:${e.kind}:${e.name}`}async initialize(){this.config.enablePersistence&&this.cacheDir&&(existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:true}),await this.loadFromDisk());}async loadFromDisk(){if(!(!this.cacheDir||!existsSync(this.cacheDir)))try{let t=(await readdir(this.cacheDir)).filter(r=>r.endsWith(".typeschema.json"));for(let r of t){let i=join(this.cacheDir,r),n=await stat(i);if(this.config.maxAge&&Date.now()-n.mtimeMs>this.config.maxAge){await unlink(i);continue}try{let o=await readFile(i,"utf-8"),a=JSON.parse(o);if(this.config.validateCached&&!a.schema?.identifier)continue;let c=this.generateKey(a.schema.identifier);this.cache.set(c,a.schema);}catch(o){console.warn(`Failed to load cached schema from ${r}:`,o);}}}catch(e){console.warn("Failed to load cached schemas from disk:",e);}}async persistSchema(e){if(!this.cacheDir)return;existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:true});let t={schema:e,timestamp:Date.now(),version:e.identifier.version},r=`${e.identifier.package}-${e.identifier.version}-${e.identifier.kind}-${e.identifier.name}.typeschema.json`.replace(/[^a-zA-Z0-9.-]/g,"_"),i=join(this.cacheDir,r);try{await writeFile(i,JSON.stringify(t,null,2),"utf-8");}catch(n){console.warn(`Failed to persist schema to ${i}:`,n);}}async clearDisk(){if(!(!this.cacheDir||!existsSync(this.cacheDir)))try{let t=(await readdir(this.cacheDir)).filter(r=>r.endsWith(".typeschema.json"));for(let r of t)await unlink(join(this.cacheDir,r));}catch(e){console.warn("Failed to clear cache directory:",e);}}};var Mr=async(s,e)=>{let t=w.join(s,"node_modules",e.name,"package.json");return JSON.parse(await x.readFile(t,"utf8"))},Or=async(s,e)=>{let r=(await Mr(s,e)).dependencies;return r!==void 0?Object.entries(r).map(([i,n])=>({name:i,version:n})):[]},Lt=s=>({pkg:s,nameResolution:{},canonicalResolution:{},fhirSchemas:{},valueSets:{}}),At=async(s,e,t=0,r)=>{let i={},n=await Or("tmp/fhir",e);for(let a of n){let c=At(s,a,t);Object.assign(i,c);}let o=F(e);i[o]||(i[o]=Lt(e));for(let a of await s.search({package:e})){let c=a.url;if(!c||!(isStructureDefinition(a)||We(a)||vt(a)))continue;let l=c;if(!i[o].canonicalResolution[l]){i[o].canonicalResolution[l]=[];for(let[f,{canonicalResolution:g}]of Object.entries(i))if(o!==f&&g[l])for(let p of g[l])i[o].canonicalResolution[l].push({deep:p.deep+1,resource:p.resource,packageMeta:p.packageMeta});}i[o].canonicalResolution[l].push({deep:t,packageMeta:e,resource:a}),i[o].canonicalResolution[l].sort((f,g)=>f.deep-g.deep);let d=a.name;if(d&&isStructureDefinition(a)&&(a.derivation==="specialization"||a.derivation===void 0))if(!i[o].nameResolution[d])i[o].nameResolution[d]=a.url;else throw new Error(`Duplicate name ${d} in package ${o}`)}return i},Nt=(s,e,t)=>{let r=F(e);if(!s[r])throw new Error(`Package ${r} not found`);return s[r].nameResolution[t]},Mt=(s,e,t)=>{let r=Object.values(s).flatMap(i=>i.canonicalResolution[e]);if(!r)throw new Error(`No canonical resolution found for ${e} in any package`);return r.length>1&&t?.dry_warn(`Multiple canonical resolutions found for ${e} in: ${JSON.stringify(r,void 0,2)}`),r[0]?.resource},Q=async(s,{logger:e,fallbackPackageForNameResolution:t})=>{let r=await s.packages(),i={};for(let g of r)Object.assign(i,await At(s,g));for(let{pkg:g,canonicalResolution:p}of Object.values(i)){let u=F(g);if(!i[u])throw new Error(`Package ${u} not found`);let m=0;e?.info(`FHIR Schema conversion for '${F(g)}' begins...`);for(let[y,S]of Object.entries(p)){let k=S[0]?.resource;if(!k)throw new Error("Resource not found");if(isStructureDefinition(k)){let B=_e(Bt.translate(k),g);m++,i[u].fhirSchemas[B.url]=B;}if(We(k)){let B=Tt(k,g);i[u].valueSets[B.url]=B;}}e?.success(`FHIR Schema conversion for '${F(g)}' completed: ${m} successful`);}let n=(g,p)=>i[F(g)]?.fhirSchemas[p]||t&&i[F(t)]?.fhirSchemas[p],o=(g,p)=>i[F(g)]?.valueSets[p]||t&&i[F(t)]?.valueSets[p],a=(g,p)=>Nt(i,g,p)||t&&Nt(i,t,p)||p,c=(g,p)=>{let u=n(g,p);if(u===void 0)throw new Error(`Failed to resolve FHIR Schema genealogy for '${p}'`);let m=[u];for(;u?.base;){if(u=n(u.package_meta,u.base)||n(u.package_meta,a(u.package_meta,u.base)),u===void 0)throw new Error(`Failed to resolve FHIR Schema genealogy for '${p}'`);m.push(u);}return m};return {...s,unsafeAppendFs(g){let p=_e(g),u=F(p.package_meta);i[u]||(i[u]=Lt(p.package_meta)),i[u].nameResolution[p.name]=p.url,i[u].fhirSchemas[p.url]=p;},resolveFs:n,resolveFsGenealogy:c,resolveFsSpecializations:(g,p)=>c(g,p).filter(u=>u.derivation==="specialization"),ensureSpecializationCanonicalUrl:a,resolveSd:(g,p)=>{let u=Mt(i,p,e);if(isStructureDefinition(u))return u},allFs:()=>Object.values(i).flatMap(g=>Object.values(g.fhirSchemas)),allVs:()=>Object.values(i).flatMap(g=>Object.values(g.valueSets)),resolveVs:o,resolveAny:g=>Mt(i,g,e),resolveElementSnapshot:(g,p)=>{let u=c(g.package_meta,g.url),m=Dr(u,p);return Br(m)},getAllElementKeys:g=>{let p=new Set;for(let[u,m]of Object.entries(g)){p.add(u);for(let y of m?.choices||[])g[y]||p.add(y);}return Array.from(p)}}};var Dr=(s,e)=>{let[t,...r]=e;return t===void 0?[]:s.map(i=>{if(!i.elements)return;let n=i.elements?.[t];for(let o of r)n=n?.elements?.[o];return n}).filter(i=>i!==void 0)};function Br(s){let e=s.reverse(),t=Object.assign({},...e);return t.elements=void 0,t}var M=class{manager;options;cacheConfig;cache;logger;constructor(e={},t){this.options={verbose:false,...e},this.manager=e.manager||CanonicalManager({packages:[],workingDir:"tmp/fhir"}),this.cacheConfig=t,this.logger=e.logger||C({verbose:this.options.verbose,prefix:"TypeSchema"});}async initializeCache(){this.cacheConfig&&!this.cache&&(this.cache=new N(this.cacheConfig),await this.cache.initialize());}async registerFromPackageMetas(e){let t=e.map(r=>`${r.name}${r.version}`);return this.logger?.step(`Loading FHIR packages: ${t.join(", ")}`),await this.manager.init(),Q(this.manager,{})}generateFhirSchemas(e){this.logger?.progress(`Converting ${e.length} StructureDefinitions to FHIRSchemas`);let t=this.applyStructureDefinitionTreeshaking(e),r=[],i=0,n=0;for(let o of t)try{let a=Bt.translate(o);r.push(a),i++,this.logger?.debug(`Converted StructureDefinition: ${o.name||o.id} (${o.resourceType})`);}catch(a){n++,this.logger?.warn(`Failed to convert StructureDefinition ${o.name||o.id}: ${a instanceof Error?a.message:String(a)}`);}return this.logger?.success(`FHIR Schema conversion completed: ${i}/${t.length} successful, ${n} failed`),r}async generateValueSetSchemas(e,t){e.length>0&&this.logger?.debug(`${e.length} ValueSets available for enum extraction`);let r=await Q(this.manager,{logger:this.logger}),i=[];if(e.length>0){this.logger?.progress(`Converting ${e.length} ValueSets to TypeSchema`);let n=0,o=0;for(let a of e)try{let c=await he(r,a,t);c&&(i.push(c),n++,this.logger?.debug(`Converted ValueSet: ${a.name||a.id}`));}catch(c){o++,this.logger?.warn(`Failed to convert ValueSet ${a.name||a.id}: ${c instanceof Error?c.message:String(c)}`);}this.logger?.success(`ValueSet conversion completed: ${n}/${e.length} successful, ${o} failed`);}return i}async generateFromPackage(e,t,r){if(await this.initializeCache(),this.cache&&!(this.cacheConfig?.forceRegenerate??false)){let l=this.cache.getByPackage(e);if(l.length>0)return this.logger?.info(`Using cached TypeSchemas for package: ${e} (${l.length} schemas)`),l}let i={name:e,version:t||"latest"},n=await this.registerFromPackageMetas([i]),o=await this.generateValueSetSchemas(n.allVs(),r),c=[...(await Promise.all(n.allFs().map(async l=>await ye(n,l,r)))).flat(),...o];if(this.cache)for(let l of c)await this.cache.set(l);return c}applyStructureDefinitionTreeshaking(e){let t=this.options.treeshake;if(!t||t.length===0)return e;this.logger?.info(`Applying treeshaking filter for ResourceTypes: ${t.join(", ")}`);let r=new Map,i=new Map,n=new Map;for(let d of e){let f=d.name||d.id;f&&(r.set(f,d),i.set(f,new Set),n.set(f,new Set));}for(let d of e){let f=d.name||d.id;if(!f)continue;let{realDeps:g,refTargets:p}=this.extractStructureDefinitionDependenciesWithReferences(d);i.set(f,new Set(g)),n.set(f,new Set(p));}let o=new Set;for(let d of t)r.has(d)?o.add(d):this.logger?.warn(`ResourceType '${d}' not found in structure definitions`);let a=(d,f=new Set)=>{if(f.has(d)||!i.has(d))return;f.add(d);let g=i.get(d)||new Set;for(let p of Array.from(g))r.has(p)&&(o.add(p),a(p,f));};for(let d of Array.from(o))a(d);let c=e.filter(d=>{let f=d.name||d.id;return f&&o.has(f)}),l=new Set;for(let d of e){let f=d.name||d.id;f&&!o.has(f)&&Array.from(n.values()).some(p=>p.has(f))&&l.add(f);}return l.size>0&&this.logger?.info(`Excluded reference-only targets: ${Array.from(l).join(", ")}`),this.logger?.success(`Treeshaking completed: kept ${c.length}/${e.length} structure definitions`),c}extractStructureDefinitionDependenciesWithReferences(e){let t=new Set,r=new Set;if(e.baseDefinition){let i=this.extractResourceNameFromUrl(e.baseDefinition);i&&t.add(i);}if(e.snapshot?.element||e.differential?.element){let i=e.snapshot?.element||e.differential?.element;for(let n of i)if(n.type)for(let o of n.type){if(o.code&&(t.add(o.code),o.code==="Reference"&&o.targetProfile))for(let a of o.targetProfile){let c=this.extractResourceNameFromUrl(a);c&&r.add(c);}if(o.profile)for(let a of o.profile){let c=this.extractResourceNameFromUrl(a);c&&t.add(c);}}}return {realDeps:Array.from(t),refTargets:Array.from(r)}}extractResourceNameFromUrl(e){let t=e.match(/\/([^/]+)$/);return t?t[1]??null:null}};var z=class{options;constructor(e={}){this.options={format:"auto",validate:true,strict:false,...e};}async parseFromFile(e){let t=await readFile(e,"utf-8"),r=this.options.format==="auto"?this.detectFormat(t,e):this.options.format;return this.parseFromString(t,r)}async parseFromString(e,t){let r=t||this.detectFormat(e),i;return r==="ndjson"?i=this.parseNDJSON(e):i=this.parseJSON(e),this.options.validate&&this.validateSchemas(i),i}async parseFromFiles(e){let t=[];for(let r of e){let i=await this.parseFromFile(r);t.push(...i);}return t}parseSchema(e){if(!e.identifier)throw new Error("TypeSchema must have an identifier");if(!this.isValidIdentifier(e.identifier))throw new Error("TypeSchema identifier is invalid");return e}findByIdentifier(e,t){return e.filter(r=>this.matchesIdentifier(r.identifier,t))}findByUrl(e,t){return e.find(r=>r.identifier.url===t)}findByKind(e,t){return e.filter(r=>r.identifier.kind===t)}findByPackage(e,t){return e.filter(r=>r.identifier.package===t)}detectFormat(e,t){if(t){if(t.endsWith(".ndjson"))return "ndjson";if(t.endsWith(".json"))return "json"}let r=e.trim();if(r.includes(`
16
15
  `)){let i=r.split(`
17
16
  `).filter(n=>n.trim());if(i.length>1)try{return i[0]&&JSON.parse(i[0]),"ndjson"}catch{}}return "json"}parseNDJSON(e){let t=[],r=e.split(`
18
- `).filter(i=>i.trim());for(let i of r)try{let n=JSON.parse(i);t.push(this.parseSchema(n));}catch(n){if(this.options.strict)throw new Error(`Failed to parse NDJSON line: ${n}`)}return t}parseJSON(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.map(r=>this.parseSchema(r)):[this.parseSchema(t)]}catch(t){throw new Error(`Failed to parse JSON: ${t}`)}}validateSchemas(e){for(let t of e){if(!t.identifier)throw new Error("Schema missing identifier");if(!this.isValidIdentifier(t.identifier))throw new Error(`Invalid identifier in schema: ${JSON.stringify(t.identifier)}`)}}isValidIdentifier(e){return typeof e=="object"&&e!==null&&typeof e.kind=="string"&&typeof e.package=="string"&&typeof e.version=="string"&&typeof e.name=="string"&&typeof e.url=="string"}matchesIdentifier(e,t){return (!t.kind||e.kind===t.kind)&&(!t.package||e.package===t.package)&&(!t.version||e.version===t.version)&&(!t.name||e.name===t.name)&&(!t.url||e.url===t.url)}};var Pt=async(s,e)=>{let t=[];for(let r of s.allFs())t.push(...await ye(s,r,e));for(let r of s.allVs())t.push(await me(s,r));return t};var Ye=s=>s.split(/(?<=[a-z])(?=[A-Z])|[-_.\s]/).filter(Boolean),Z=s=>Ye(s).map(e=>e.toLowerCase()).join("-"),Nt=s=>{if(s.length===0)throw new Error("Empty string");return s[0]?.toUpperCase()+s.substring(1).toLowerCase()},Mt=s=>{if(s.length===0)throw new Error("Empty string");let[e,...t]=Ye(s);return [e?.toLowerCase(),...t.map(Nt)].join("")},Y=s=>Ye(s).map(Nt).join("");var ve=s=>!s||s.length===0?s:s.charAt(0).toUpperCase()+s.slice(1),Ot=s=>s.map(e=>ve(e));function be(s,e){if(s===e)return true;if(s===null||e===null||typeof s!="object"||typeof e!="object")return false;if(Array.isArray(s)&&Array.isArray(e))return s.length!==e.length?false:s.every((i,n)=>be(i,e[n]));if(Array.isArray(s)||Array.isArray(e))return false;let t=Object.keys(s),r=Object.keys(e);return t.length!==r.length?false:t.every(i=>r.includes(i)&&be(s[i],e[i]))}var Dt=s=>{let e={};for(let t of s){let r=t.identifier.package;e[r]||(e[r]=[]),e[r].push(t);}for(let[t,r]of Object.entries(e))r.sort((i,n)=>i.identifier.name.localeCompare(n.identifier.name));return e},wr=s=>{let e=s.filter(q),t=[];for(let n of e)n.base&&t.push({parent:n.base,child:n.identifier});let r=[...t],i=n=>{let o=t.filter(c=>c.parent.name===n.name).map(c=>c.child),a=[];for(let c of o)a.push(...i(c));return [...o,...a]};for(let n of t){let o=i(n.child);for(let a of o)t.some(c=>c.parent.name===n.parent.name&&c.child.name===a.name)||r.push({parent:n.parent,child:a});}return r},Bt=(s,e)=>{let t={},r=p=>{let h=p.identifier.url,S=p.identifier.package;if(t[h]||(t[h]={}),t[h][p.identifier.package]&&S!=="shared"){let w=JSON.stringify(p.identifier,void 0,2),T=JSON.stringify(t[h][S]?.identifier,void 0,2);throw new Error(`Duplicate schema: ${w} and ${T}`)}t[h][S]=p;};for(let p of s)r(p);let i=wr(s),n=p=>t[p.url]?.[p.package],o=p=>i.filter(h=>h.parent.name===p.name).map(h=>h.child),a=p=>{let h=[],S=p;for(;S;){h.push(S);let w=S.base;if(w===void 0)break;let T=n(w);if(!T){return}S=T;}return h},c=p=>{let h=a(p);if(h===void 0)throw new Error(`Failed to resolve base type: ${p.identifier.url} (${p.identifier.kind})`);return h},l=p=>{let h=c(p).find(S=>S.identifier.kind!=="profile");if(!h)throw new Error(`No non-constraint schema found in hierarchy for: ${p.identifier.name}`);return h};return {_schemaIndex:t,_relations:i,collectComplexTypes:()=>s.filter(yt),collectResources:()=>s.filter(q),collectLogicalModels:()=>s.filter(St),collectProfiles:()=>s.filter(ce),resolve:n,resourceChildren:o,tryHierarchy:a,hierarchy:c,findLastSpecialization:l,findLastSpecializationByIdentifier:p=>{let h=n(p);return h?l(h).identifier:p},flatProfile:p=>{let h=c(p),S=h.filter(P=>P.identifier.kind==="profile"),w=h.find(P=>P.identifier.kind!=="profile");if(!w)throw new Error(`No non-constraint schema found in hierarchy for ${p.identifier.name}`);let T={};for(let P of S.slice().reverse()){let d=P;if(d.fields)for(let[f,y]of Object.entries(d.fields))T[f]?T[f]={...T[f],...y}:T[f]={...y};}let G={};for(let P of S.flatMap(d=>d.dependencies??[]))G[P.url]=P;let ut=Object.values(G);return {...p,base:w.identifier,fields:T,dependencies:ut}},isWithMetaField:p=>{let h=a(p);return h?h.filter(_).some(S=>S.fields?.meta!==void 0):false}}};X();var Ce=class{constructor(e){this.options=e;}handleError(e,t){e instanceof k?this.handleGeneratorError(e,t):this.handleUnknownError(e,t);}handleBatchErrors(e){let t=e.filter(i=>i instanceof k),r=e.filter(i=>!(i instanceof k));t.length>0&&this.reportBatchErrors(t),r.forEach(i=>{this.handleUnknownError(i);});}handleGeneratorError(e,t){switch(this.options.outputFormat){case "json":this.reportErrorAsJson(e);break;case "structured":this.reportErrorStructured(e);break;default:this.reportErrorToConsole(e);}}handleUnknownError(e,t){this.options.logger.error("Unexpected error occurred:",e),this.options.verbose&&(this.options.logger.error(`
17
+ `).filter(i=>i.trim());for(let i of r)try{let n=JSON.parse(i);t.push(this.parseSchema(n));}catch(n){if(this.options.strict)throw new Error(`Failed to parse NDJSON line: ${n}`)}return t}parseJSON(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.map(r=>this.parseSchema(r)):[this.parseSchema(t)]}catch(t){throw new Error(`Failed to parse JSON: ${t}`)}}validateSchemas(e){for(let t of e){if(!t.identifier)throw new Error("Schema missing identifier");if(!this.isValidIdentifier(t.identifier))throw new Error(`Invalid identifier in schema: ${JSON.stringify(t.identifier)}`)}}isValidIdentifier(e){return typeof e=="object"&&e!==null&&typeof e.kind=="string"&&typeof e.package=="string"&&typeof e.version=="string"&&typeof e.name=="string"&&typeof e.url=="string"}matchesIdentifier(e,t){return (!t.kind||e.kind===t.kind)&&(!t.package||e.package===t.package)&&(!t.version||e.version===t.version)&&(!t.name||e.name===t.name)&&(!t.url||e.url===t.url)}};var jt=async(s,e)=>{let t=[];for(let r of s.allFs())t.push(...await ye(s,r,e));for(let r of s.allVs())t.push(await he(s,r));return t};var et=s=>s.split(/(?<=[a-z])(?=[A-Z])|[-_.\s]/).filter(Boolean),X=s=>et(s).map(e=>e.toLowerCase()).join("-"),Gt=s=>{if(s.length===0)throw new Error("Empty string");return s[0]?.toUpperCase()+s.substring(1).toLowerCase()},Te=s=>{if(s.length===0)throw new Error("Empty string");let[e,...t]=et(s);return [e?.toLowerCase(),...t.map(Gt)].join("")},V=s=>et(s).map(Gt).join("");var $=s=>!s||s.length===0?s:s.charAt(0).toUpperCase()+s.slice(1),xe=s=>s.map(e=>$(e));function ve(s,e){if(s===e)return true;if(s===null||e===null||typeof s!="object"||typeof e!="object")return false;if(Array.isArray(s)&&Array.isArray(e))return s.length!==e.length?false:s.every((i,n)=>ve(i,e[n]));if(Array.isArray(s)||Array.isArray(e))return false;let t=Object.keys(s),r=Object.keys(e);return t.length!==r.length?false:t.every(i=>r.includes(i)&&ve(s[i],e[i]))}var rt=class{opts;currentDir;currentFileDescriptor;writtenFilesSet=new Set;constructor(e){this.opts=e,this.currentDir=e.outputDir;}logger(){return this.opts.logger}cd(e,t){this.currentDir=e.startsWith("/")?w.join(this.opts.outputDir,e):w.join(this.currentDir,e),R.existsSync(this.currentDir)||R.mkdirSync(this.currentDir,{recursive:true}),this.logger()?.debug(`cd '${this.currentDir}'`),t();}cat(e,t){if(this.currentFileDescriptor)throw new Error("Can't open file in file");if(e.includes("/"))throw new Error(`Change file path separatly: ${e}`);let r=`${this.currentDir}/${e}`;try{this.currentFileDescriptor=R.openSync(r,"w"),this.writtenFilesSet.add(e),this.logger()?.debug(`cat > '${r}'`),t();}finally{this.currentFileDescriptor&&R.closeSync(this.currentFileDescriptor),this.currentFileDescriptor=void 0;}}write(e){if(!this.currentFileDescriptor)throw new Error("No file opened");R.writeSync(this.currentFileDescriptor,e);}generate(e){throw new Error("Not implemented")}writtenFiles(){return Array.from(this.writtenFilesSet)}},q=class extends rt{currentIndent=0;indent(){this.currentIndent+=this.opts.tabSize;}deindent(){this.currentIndent-=this.opts.tabSize;}writeIndent(){this.write(" ".repeat(this.currentIndent));}line(...e){e.length===0?this.write(`
18
+ `):(this.writeIndent(),this.write(`${e.join(" ")}
19
+ `));}lineSM(...e){this.writeIndent(),this.write(`${e.join(" ")};
20
+ `);}comment(...e){let t=e.join(" ").split(`
21
+ `);for(let r of t)this.line(this.opts.commentLinePrefix,r);}debugComment(...e){this.opts.withDebugComment&&(e=e.map(t=>typeof t=="string"?t:JSON.stringify(t,null,2)),this.comment(...e));}disclaimer(){return ["WARNING: This file is autogenerated by @atomic-ehr/codegen.","GitHub: https://github.com/orgs/atomic-ehr/repositories","Any manual changes made to this file may be overwritten."]}generateDisclaimer(){this.disclaimer().forEach(e=>this.comment(e)),this.line();}indentBlock(e){this.indent(),e(),this.deindent();}curlyBlock(e,t,r){this.line(`${e.filter(Boolean).join(" ")} {`),this.indent(),t(),this.deindent(),this.line(`}${r?.filter(Boolean).join(" ")??""}`);}squareBlock(e,t,r){this.line(`${e.filter(Boolean).join(" ")} [`),this.indent(),t(),this.deindent(),this.line(`]${r?.filter(Boolean).join(" ")??""}`);}};var Ht={"!":"Not","<=":"LessOrEqual",">=":"GreaterOrEqual","<":"Less",">":"Greater","=":"Equal","-":"Dash","+":"Plus","*":"Asterisk","/":"Slash","%":"Percent","&":"And","|":"Or","^":"Xor","~":"Tilde","?":"Question",".":"Dot"};function Vr(s){return s.split("-").map(e=>$(e)).join("-")}function jr(s){let e=s;for(let t in Ht)e=e.replaceAll(t,Ht[t]??"");return e}function Gr(s){let e=Number(s[0]);return Number.isInteger(e)&&!Number.isNaN(e)?`_${s}`:s}function Ut(s){let e=Vr(s);return e=Gr(e),e=jr(e),e=$(e),e}function I(s){return $(Te(s.replaceAll(".","-")))}var Hr={boolean:"bool",instant:"string",time:"string",date:"string",dateTime:"string",decimal:"decimal",integer:"int",unsignedInt:"long",positiveInt:"long",integer64:"long",base64Binary:"string",uri:"string",url:"string",canonical:"string",oid:"string",uuid:"string",string:"string",code:"string",markdown:"string",id:"string",xhtml:"string"},Ur=["Reference","Expression"],_r=s=>s.required?["required"]:[],zr=s=>{let e=Wt(qt(s.identifier));return $(e)},qr=s=>s.base?`: ${s.base.name}`:"",Wr=(s,e=true)=>{if(!s)return;let t=s.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),I(t)},qt=s=>{if(s.kind==="nested"){let e=s.url,t=Wr(e,false);if(!t)return "";let[r,i]=t.split("#"),n=xe((i??"").split(".")).join("");return I([r,n].join(""))}return I(s.name)},Jr=s=>Ur.includes(s),Wt=s=>Jr(s)?`Resource${s}`:s,we=class extends q{enums={};staticSourceDir;targetNamespace;constructor(e){super({outputDir:e.outputDir,tabSize:4,withDebugComment:false,commentLinePrefix:"//",logger:e.logger}),this.staticSourceDir=e.staticSourceDir,this.targetNamespace=e.targetNamespace;}generate(e){let t=e.collectComplexTypes(),r=e.collectResources(),i=Array.from(new Set(r.map(n=>I(n.identifier.package))));this.generateAllFiles(t,r,i),this.copyStaticFiles();}generateAllFiles(e,t,r){this.generateUsingFile(r),this.generateBaseTypes(e),this.generateResources(t),this.generateEnumFiles(r),this.generateResourceDictionaries(t,r),this.generateHelperFile();}generateType(e,t){let r=zr(e),i=qr(e);this.curlyBlock(["public","class",r,i],()=>{this.generateFields(e,t),this.generateNestedTypes(e,t),this.line(),this.includeHelperMethods();}),this.line();}generateFields(e,t){if(!e.fields)return;let r=Object.entries(e.fields).sort(([i],[n])=>i.localeCompare(n));for(let[i,n]of r)this.generateField(i,n,t);}generateNestedTypes(e,t){if(!(!("nested"in e)||!e.nested)){this.line();for(let r of e.nested)this.generateType(r,t);}}generateField(e,t,r){try{if(_(t))return;let i=this.buildFieldDeclaration(e,t,r);this.line(...i);}catch(i){this.logger()?.error(`Error processing field ${e}: ${i.message}`);}}buildFieldDeclaration(e,t,r){let i=this.determineFieldType(e,t,r),n=_r(t),o=V(e);return ["public",...n,i,o,"{ get; set; }"].filter(Boolean)}determineFieldType(e,t,r){let i=this.getBaseTypeName(t);"enum"in t&&t.enum&&(i=this.registerAndGetEnumType(e,t,r)),i=Wt(i);let n="",o=t.required?"":"?",a=t.array?"[]":"";return `${n}${i}${a}${o}`}getBaseTypeName(e){if("type"in e){let t=e.type.name.toString();return e.type.kind==="nested"?t=qt(e.type):e.type.kind==="primitive-type"&&(t=Hr[e.type.name]??"string"),t}return ""}registerAndGetEnumType(e,t,r){let n=`${I(t.binding?.name??e)}Enum`;return this.enums[r]||(this.enums[r]={}),t.enum&&(this.enums[r][n]=t.enum),n}includeHelperMethods(){this.line("public override string ToString() => "),this.line(" JsonSerializer.Serialize(this, Helper.JsonSerializerOptions);"),this.line();}generateUsingFile(e){this.cd("/",async()=>{this.cat("Usings.cs",()=>{this.generateDisclaimer(),this.generateGlobalUsings(e);});});}generateGlobalUsings(e){let t=["CSharpSDK","System.Text.Json","System.Text.Json.Serialization",this.targetNamespace,...e.map(r=>`${this.targetNamespace}.${r}`)];for(let r of t)this.lineSM("global","using",r);}generateBaseTypes(e){this.cd("/",async()=>{this.cat("base.cs",()=>{this.generateDisclaimer(),this.line(),this.lineSM("namespace",this.targetNamespace);for(let t of e){let r=I(t.identifier.package);this.generateType(t,r);}});});}generateResources(e){for(let t of e)this.generateResourceFile(t);}generateResourceFile(e){let t=I(e.identifier.package);this.cd(`/${t}`,async()=>{this.cat(`${e.identifier.name}.cs`,()=>{this.generateDisclaimer(),this.line(),this.lineSM("namespace",`${this.targetNamespace}.${t}`),this.line(),this.generateType(e,t);});});}generateEnumFiles(e){for(let t of e)this.generatePackageEnums(t);}generatePackageEnums(e){let t=this.enums[e];!t||Object.keys(t).length===0||this.cd(`/${e}`,async()=>{this.cat(`${e}Enums.cs`,()=>{this.generateDisclaimer(),this.generateEnumFileContent(e,t);});});}generateEnumFileContent(e,t){this.lineSM("using","System.ComponentModel"),this.line(),this.lineSM(`namespace ${this.targetNamespace}.${e}`);for(let[r,i]of Object.entries(t))this.generateEnum(r,i);}generateEnum(e,t){this.curlyBlock(["public","enum",e],()=>{for(let r of t)this.line(`[Description("${r}")]`),this.line(`${Ut(r)},`);}),this.line();}generateResourceDictionaries(e,t){this.cd("/",async()=>{for(let r of t){let i=e.filter(n=>I(n.identifier.package)===r);if(i.length===0)return;this.cat(`${r}ResourceDictionary.cs`,()=>{this.generateDisclaimer(),this.line(),this.lineSM(`namespace ${this.targetNamespace}`),this.generateResourceDictionaryClass(r,i);});}});}generateResourceDictionaryClass(e,t){this.curlyBlock(["public","static","class","ResourceDictionary"],()=>{this.curlyBlock(["public static readonly Dictionary<Type, string> Map = new()"],()=>{for(let r of t){let i=r.identifier.name;this.line(`{ typeof(${e}.${i}), "${i}" },`);}}),this.lineSM();});}copyStaticFiles(){if(!this.staticSourceDir)return;let e=w__default.resolve(this.staticSourceDir);R__default.cpSync(e,this.opts.outputDir,{recursive:true});}generateHelperFile(){let e="src/api/writer-generator/csharp/Helper.cs",t=w__default.join(this.opts.outputDir,"Helper.cs");R__default.copyFileSync(e,t);}};var Jt=s=>{let e={};for(let t of s){let r=t.identifier.package;e[r]||(e[r]=[]),e[r].push(t);}for(let[t,r]of Object.entries(e))r.sort((i,n)=>i.identifier.name.localeCompare(n.identifier.name));return e},Kr=s=>{let e=s.filter(K),t=[];for(let n of e)n.base&&t.push({parent:n.base,child:n.identifier});let r=[...t],i=n=>{let o=t.filter(c=>c.parent.name===n.name).map(c=>c.child),a=[];for(let c of o)a.push(...i(c));return [...o,...a]};for(let n of t){let o=i(n.child);for(let a of o)t.some(c=>c.parent.name===n.parent.name&&c.child.name===a.name)||r.push({parent:n.parent,child:a});}return r},Kt=(s,e)=>{let t={},r=p=>{let u=p.identifier.url,m=p.identifier.package;if(t[u]||(t[u]={}),t[u][p.identifier.package]&&m!=="shared"){let y=JSON.stringify(p.identifier,void 0,2),S=JSON.stringify(t[u][m]?.identifier,void 0,2);throw new Error(`Duplicate schema: ${y} and ${S}`)}t[u][m]=p;};for(let p of s)r(p);let i=Kr(s),n=p=>t[p.url]?.[p.package],o=p=>i.filter(u=>u.parent.name===p.name).map(u=>u.child),a=p=>{let u=[],m=p;for(;m;){u.push(m);let y=m.base;if(y===void 0)break;let S=n(y);if(!S){return}m=S;}return u},c=p=>{let u=a(p);if(u===void 0)throw new Error(`Failed to resolve base type: ${p.identifier.url} (${p.identifier.kind})`);return u},l=p=>{let u=c(p).find(m=>m.identifier.kind!=="profile");if(!u)throw new Error(`No non-constraint schema found in hierarchy for: ${p.identifier.name}`);return u};return {_schemaIndex:t,_relations:i,collectComplexTypes:()=>s.filter(St),collectResources:()=>s.filter(K),collectLogicalModels:()=>s.filter(bt),collectProfiles:()=>s.filter(le),resolve:n,resourceChildren:o,tryHierarchy:a,hierarchy:c,findLastSpecialization:l,findLastSpecializationByIdentifier:p=>{let u=n(p);return u?l(u).identifier:p},flatProfile:p=>{let u=c(p),m=u.filter(E=>E.identifier.kind==="profile"),y=u.find(E=>E.identifier.kind!=="profile");if(!y)throw new Error(`No non-constraint schema found in hierarchy for ${p.identifier.name}`);let S={};for(let E of m.slice().reverse()){let ne=E;if(ne.fields)for(let[se,ft]of Object.entries(ne.fields))S[se]?S[se]={...S[se],...ft}:S[se]={...ft};}let k={};for(let E of m.flatMap(ne=>ne.dependencies??[]))k[E.url]=E;let B=Object.values(k);return {...p,base:y.identifier,fields:S,dependencies:B}},isWithMetaField:p=>{let u=a(p);return u?u.filter(J).some(m=>m.fields?.meta!==void 0):false}}};te();var $e=class{constructor(e){this.options=e;}handleError(e,t){e instanceof v?this.handleGeneratorError(e,t):this.handleUnknownError(e,t);}handleBatchErrors(e){let t=e.filter(i=>i instanceof v),r=e.filter(i=>!(i instanceof v));t.length>0&&this.reportBatchErrors(t),r.forEach(i=>{this.handleUnknownError(i);});}handleGeneratorError(e,t){switch(this.options.outputFormat){case "json":this.reportErrorAsJson(e);break;case "structured":this.reportErrorStructured(e);break;default:this.reportErrorToConsole(e);}}handleUnknownError(e,t){this.options.logger.error("Unexpected error occurred:",e),this.options.verbose&&(this.options.logger.error(`
19
22
  \u{1F6A8} Unexpected Error Details:`),this.options.logger.error(` Type: ${e.constructor.name}`),this.options.logger.error(` Message: ${e.message}`),e.stack&&this.options.logger.error(` Stack: ${e.stack}`),t?.schema&&this.options.logger.error(` Schema: ${t.schema.identifier.name}`),t?.filename&&this.options.logger.error(` File: ${t.filename}`)),this.options.logger.error(`
20
23
  \u{1F4A1} General troubleshooting suggestions:`),this.options.logger.error(" \u2022 Run with --verbose flag for more details"),this.options.logger.error(" \u2022 Check your input files for corruption"),this.options.logger.error(" \u2022 Update to the latest version of atomic-codegen"),this.options.logger.error(" \u2022 Report this issue at: https://github.com/atomic-ehr/codegen/issues");}reportErrorToConsole(e){if("getFormattedMessage"in e)this.options.logger.error(e.getFormattedMessage());else {this.options.logger.error(`
21
24
  \u274C ${e.constructor.name}: ${e.message}`);let t=e.getSuggestions();t.length>0&&(this.options.logger.error(`
@@ -23,26 +26,22 @@ import Wr from'yargs';import {hideBin}from'yargs/helpers';import'perf_hooks';imp
23
26
  \u{1F50D} Debug Information:`),this.options.logger.error(JSON.stringify(e.context,null,2)));}reportErrorAsJson(e){let t={type:e.constructor.name,message:e.message,phase:e.phase,context:e.context,suggestions:e.getSuggestions(),timestamp:new Date().toISOString()};this.options.logger.error(JSON.stringify(t,null,2));}reportErrorStructured(e){let t={error:{type:e.constructor.name,message:e.message,phase:e.phase},context:e.context,suggestions:e.getSuggestions(),actions:this.getRecoveryActions(e)};this.options.logger.error("---"),this.options.logger.error("Error Report:"),this.options.logger.error(JSON.stringify(t,null,2)),this.options.logger.error("---");}reportBatchErrors(e){this.options.logger.error(`
24
27
  \u274C ${e.length} errors occurred during generation:`);let t=new Map;e.forEach(r=>{let i=r.constructor.name;t.has(i)||t.set(i,[]),t.get(i)?.push(r);});for(let[r,i]of t){this.options.logger.error(`
25
28
  \u{1F4CB} ${r} (${i.length} occurrences):`),i.forEach((o,a)=>{this.options.logger.error(` ${a+1}. ${o.message}`),o.context?.schemaName&&this.options.logger.error(` Schema: ${o.context.schemaName}`);});let n=this.getCommonSuggestions(i);n.length>0&&(this.options.logger.error(`
26
- \u{1F4A1} Common suggestions:`),n.forEach(o=>{this.options.logger.error(` \u2022 ${o}`);}));}}getCommonSuggestions(e){let t=e.flatMap(n=>n.getSuggestions()),r=new Map;t.forEach(n=>{r.set(n,(r.get(n)||0)+1);});let i=Math.ceil(e.length/2);return Array.from(r.entries()).filter(([n,o])=>o>=i).map(([n,o])=>n).slice(0,5)}getRecoveryActions(e){return "getRecoveryActions"in e?e.getRecoveryActions():[{action:"Review error message and suggestions above"},{action:"Check input files and configuration"},{action:"Try with --verbose flag for more information"}]}},ke=class{constructor(e){this.errorHandler=e;}async withErrorBoundary(e,t){try{return await e()}catch(r){throw this.errorHandler.handleError(r instanceof Error?r:new Error(String(r)),t),r}}async withBatchErrorBoundary(e,t){let r=[],i=[];for(let n of e)try{let o=await n();r.push(o);}catch(o){i.push(o instanceof Error?o:new Error(String(o)));}if(i.length>0)throw this.errorHandler.handleBatchErrors(i),new we(`${i.length} operations failed`,i.filter(n=>n instanceof k));return r}};X();X();var Fe=class{options;logger;constructor(e){this.options={overwrite:true,batchSize:10,...e},this.logger=e.logger;}async writeFile(e,t,r={}){let i=performance.now(),n=join(this.options.outputDir,e),o=r.encoding||"utf-8",a=r.overwrite??this.options.overwrite;try{if(!a)try{await access(n),this.logger.debug(`Skipping existing file: ${e}`);let u=await stat(n);return {path:n,size:u.size,writeTime:0}}catch{}await this.ensureDirectory(dirname(n)),await writeFile(n,t,o);let c=performance.now()-i,l=Buffer.byteLength(t,o);return this.logger.debug(`Written ${e} (${l} bytes, ${c.toFixed(2)}ms)`),{path:n,size:l,writeTime:c}}catch(c){throw new D(`Failed to write file '${e}': ${c}`,"write",n,c instanceof Error?c:void 0,{canRetry:true,alternativePaths:[join(process.cwd(),"backup-output",e)]})}}async writeBatch(e){this.logger.debug(`Writing batch of ${e.size} files`);let t=Array.from(e.entries()),r=[];for(let i=0;i<t.length;i+=this.options.batchSize){let o=t.slice(i,i+this.options.batchSize).map(([c,l])=>this.writeFile(c,l)),a=await Promise.all(o);r.push(...a),i+this.options.batchSize<t.length&&await new Promise(c=>setTimeout(c,10));}return r}async ensureDirectory(e){try{await mkdir(e,{recursive:!0});}catch(t){throw new D(`Failed to create directory '${e}': ${t}`,"create",e,t instanceof Error?t:void 0,{canRetry:true,permissionFix:`chmod 755 "${dirname(e)}"`})}}async cleanDirectory(e="."){let t=join(this.options.outputDir,e);try{await access(t),this.logger.debug(`Cleaning directory: ${e}`),await rm(t,{recursive:!0,force:!0});}catch(r){if(r?.code!=="ENOENT")throw new D(`Failed to clean directory '${e}': ${r}`,"delete",t,r instanceof Error?r:void 0,{canRetry:true})}}getRelativeImportPath(e,t){let r=dirname(join(this.options.outputDir,e)),i=join(this.options.outputDir,t),n=relative(r,i);return n.startsWith(".")||(n=`./${n}`),n.replace(/\.(d\.ts|ts|tsx|js|jsx)$/,"")}async wouldOverwrite(e){let t=join(this.options.outputDir,e);try{return await access(t),!0}catch{return false}}async getFileStats(e){let t=join(this.options.outputDir,e);try{return {size:(await stat(t)).size,generationTime:0,writeTime:0}}catch{return null}}getOutputDirectory(){return this.options.outputDir}setBatchSize(e){this.options.batchSize=Math.max(1,Math.min(50,e));}getBatchSize(){return this.options.batchSize}};var $e=class{options;logger;fileManager;templateEngine;typeMapper;errorHandler;errorBoundary;progressCallback;generatedFiles=[];generationStartTime=0;cache=new Map;constructor(e){let t=this.validateConfiguration(e);if(!t.isValid)throw new Te(`Invalid generator configuration: ${t.errors.join(", ")}`,"configuration",e);this.options=this.mergeWithDefaults(e),this.logger=e.logger||R({prefix:this.getLanguageName(),verbose:this.options.verbose||false}),this.fileManager=this.createFileManager(),this.templateEngine=this.createTemplateEngine(),this.typeMapper=this.createTypeMapper(),this.errorHandler=new Ce({logger:this.logger,verbose:this.options.verbose||false,beginnerMode:this.options.beginnerMode||false,outputFormat:"this.options.logger"}),this.errorBoundary=new ke(this.errorHandler),this.logger.debug(`${this.getLanguageName()} generator initialized`),t.warnings.length>0&&t.warnings.forEach(r=>{this.logger.warn(`Configuration warning: ${r}`);});}getCapabilities(){return {language:this.getLanguageName(),fileExtensions:[this.getFileExtension()],supportsTemplates:true,supportsCustomTypeMapping:true,supportsIncrementalGeneration:false,supportsValidation:true,supportedSchemaKinds:["resource","complex-type","profile","logical"],version:"1.0.0"}}createFileManager(){return new Fe({outputDir:this.options.outputDir,logger:this.logger.child("FileManager"),overwrite:this.options.overwrite})}createTemplateEngine(){}async generate(e){return this.errorBoundary.withErrorBoundary(async()=>{this.generationStartTime=performance.now(),this.generatedFiles=[],this.logger.info(`Starting ${this.getLanguageName()} generation for ${e.length} schemas`),this.reportProgress("validation",0,e.length,"Validating schemas..."),await this.validateSchemas(e),this.reportProgress("generation",0,e.length,"Processing schemas...");let t=this.filterAndSortSchemas(e);this.logger.debug(`Filtered to ${t.length} schemas for generation`),await this.generateFiles(t),await this.runPostGenerationHooks(),this.reportProgress("complete",e.length,e.length,"Generation complete");let r=performance.now()-this.generationStartTime;return this.logger.info(`Generated ${this.generatedFiles.length} files in ${r.toFixed(2)}ms (avg ${(r/this.generatedFiles.length).toFixed(2)}ms per file)`),this.generatedFiles},{operationName:"generate"})}async build(e){let t=this.fileManager.writeFile,r=new Map;this.fileManager.writeFile=async(i,n)=>{let o={path:`${this.options.outputDir}/${i}`,size:Buffer.byteLength(n,"utf-8"),writeTime:0};return r.set(i,o),o};try{let i=await this.generate(e);return i.forEach(n=>{let o=r.get(n.filename);o&&(n.path=o.path,n.size=o.size);}),i}finally{this.fileManager.writeFile=t;}}file(e){if(!this.templateEngine)throw new Error("Template engine is required for fluent file generation. Override createTemplateEngine() in your generator.");let{FileBuilder:t}=(jt(),Be(Vt));return new t({filename:this.ensureFileExtension(e),fileManager:this.fileManager,templateEngine:this.templateEngine,typeMapper:this.typeMapper,logger:this.logger.child("FileBuilder")})}directory(e){let{DirectoryBuilder:t}=(Gt(),Be(At));return new t({path:e,fileManager:this.fileManager,logger:this.logger.child("DirectoryBuilder")})}index(e="."){if(!this.templateEngine)throw new Error("Template engine is required for index file generation. Override createTemplateEngine() in your generator.");let{IndexBuilder:t}=(Ht(),Be(Ut));return new t({directory:e,fileManager:this.fileManager,templateEngine:this.templateEngine,logger:this.logger.child("IndexBuilder")})}onProgress(e){return this.progressCallback=e,this}validateConfiguration(e){let t=[],r=[],i=[];return e.outputDir||(t.push("outputDir is required"),i.push("Provide a valid output directory path")),e.outputDir&&typeof e.outputDir!="string"&&t.push("outputDir must be a string"),e.overwrite!==void 0&&typeof e.overwrite!="boolean"&&t.push("overwrite must be a boolean"),e.validate!==void 0&&typeof e.validate!="boolean"&&t.push("validate must be a boolean"),e.outputDir&&!rr("path").isAbsolute(e.outputDir)&&(r.push("Using relative path for outputDir - consider using absolute path"),i.push("Use path.resolve() to convert to absolute path")),e.validate===false&&(r.push("Validation is disabled - this may lead to invalid generated code"),i.push("Consider enabling validation for better code quality")),{isValid:t.length===0,errors:t,warnings:r,suggestions:i}}mergeWithDefaults(e){return {overwrite:true,validate:true,verbose:false,beginnerMode:false,errorFormat:"console",...e}}async validateSchemas(e){if(!this.options.validate){this.logger.debug("Schema validation disabled");return}this.logger.info(`\u{1F50D} Starting schema validation for ${e.length} schemas`),this.logger.debug("Schema validation enabled - performing comprehensive validation");let t=e.map(r=>()=>this.errorBoundary.withErrorBoundary(async()=>{await this.validateSchema(r),this.reportProgress("validation",e.indexOf(r)+1,e.length,`Validated ${r.identifier?.name||"schema"}`);},{schema:r,operationName:"validateSchema"}));await this.errorBoundary.withBatchErrorBoundary(t,{operationName:"validateSchemas"}),this.logger.debug(`Successfully validated ${e.length} schemas`);}async validateSchema(e){let t=[],r=e.identifier?.name||"unknown";if(this.logger.debug(`\u{1F50D} Validating schema: ${r} (kind: ${e.identifier?.kind})`),!e.identifier)t.push("Schema missing identifier"),this.logger.warn(`\u274C Schema missing identifier: ${JSON.stringify(e,null,2).substring(0,200)}...`);else if(e.identifier.name||t.push("Schema identifier missing name"),!e.identifier.kind)t.push("Schema identifier missing kind");else {let i=["resource","complex-type","profile","primitive-type","logical","value-set","binding","extension"];i.includes(e.identifier.kind)||t.push(`Schema identifier.kind must be one of: ${i.join(", ")}`);}if("fields"in e&&e.fields)for(let[i,n]of Object.entries(e.fields))i.trim()||t.push("Field name cannot be empty"),n||t.push(`Field '${i}' is null or undefined`);if(await this.detectCircularReferences(e)&&this.logger.warn(`\u26A0\uFE0F Circular reference detected in schema '${r}' - this may be expected for FHIR primitive types`),t.length>0)throw this.logger.error(`\u274C Schema validation failed for '${r}': ${t.join(", ")}`),this.logger.debug(`Schema details: ${JSON.stringify(e,null,2)}`),new xe(`Schema validation failed for '${e.identifier?.name||"unknown"}'`,e,t);this.logger.debug(`\u2705 Schema validation passed for '${r}'`);}async detectCircularReferences(e){let t=new Set,r=new Set;return (n=>{let o=n.identifier?.name;if(!o)return false;if(r.has(o))return true;if(t.has(o))return false;if(r.add(o),"fields"in n&&n.fields){for(let a of Object.values(n.fields))if(a?.type?.name===o)return true}return r.delete(o),t.add(o),false})(e)}async generateFiles(e){let t=e.map((r,i)=>()=>this.errorBoundary.withErrorBoundary(async()=>{let n=await this.generateFileForSchema(r,i,e.length);return this.generatedFiles.push(n),n},{schema:r,operationName:"generateFile"}));await this.errorBoundary.withBatchErrorBoundary(t,{operationName:"generateFiles"}),this.logger.debug(`Generated ${this.generatedFiles.length} files`);}async generateFileForSchema(e,t,r){let i=performance.now(),n={schema:e,typeMapper:this.typeMapper,filename:this.typeMapper.formatFileName(e.identifier?.name||"unknown"),language:this.getLanguageName(),timestamp:new Date().toISOString(),imports:new Map,exports:new Set},o=await this.generateSchemaContent(e,n);this.options.validate&&await this.validateContent(o,n);let a=n.filename+this.getFileExtension(),c=await this.fileManager.writeFile(a,o),l=performance.now()-i;return this.reportProgress("writing",t+1,r,`Generated ${a} (${c.size} bytes)`),{path:c.path,filename:a,content:o,exports:this.extractExports(o),size:c.size,timestamp:new Date,metadata:{generationTime:l,schemaCount:1,templateName:n.templateName?.toString(),warnings:[]}}}ensureFileExtension(e){let t=this.getFileExtension();return e.endsWith(t)?e:`${e}${t}`}extractExports(e){let t=[],r=/export\s*\{\s*([^}]+)\s*\}/g,i;for(;(i=r.exec(e))!==null;)if(i[1]){let o=i[1].split(",").map(a=>a.trim()).filter(Boolean);t.push(...o);}let n=/export\s+(?:const|let|var|function|class|interface|type|enum)\s+(\w+)/g;for(;(i=n.exec(e))!==null;)i[1]&&t.push(i[1]);return [...new Set(t)]}reportProgress(e,t,r,i,n){this.progressCallback&&this.progressCallback(e,t,r,i,n),i&&this.options.verbose&&this.logger.debug(`[${e}] ${i} (${t}/${r})`);}async runPostGenerationHooks(){}getCachedOrCompute(e,t){if(this.cache.has(e))return this.cache.get(e);let r=t();return r instanceof Promise?r.then(i=>(this.cache.set(e,i),i)):(this.cache.set(e,r),r)}clearCache(){this.cache.clear();}getGenerationStats(){let e=this.generatedFiles.reduce((r,i)=>r+i.size,0),t=performance.now()-this.generationStartTime;return {filesGenerated:this.generatedFiles.length,totalSize:e,averageFileSize:this.generatedFiles.length>0?e/this.generatedFiles.length:0,generationTime:t,averageTimePerFile:this.generatedFiles.length>0?t/this.generatedFiles.length:0,cacheHitRate:0}}};var Re=class{options;constructor(e={}){this.options={generateNullable:true,strictTypes:true,customMappings:{},preferArraySyntax:true,namingConvention:"PascalCase",...e};}mapType(e){if(typeof e=="string")return this.mapPrimitive(e);if(e&&typeof e=="object")switch(e.kind||e.type){case "primitive-type":return this.mapPrimitive(e.name);case "reference":return this.mapReference(e.targets||[]);case "array":{let r=this.mapType(e.element);return this.mapArray(r)}case "enum":case "coded":return this.mapEnum(e.values||[],e.name);case "complex-type":case "resource":return this.mapComplexType(e);default:return this.mapUnknownType(e)}return this.mapUnknownType(e)}mapComplexType(e){return {name:this.formatTypeName(e.name||"Unknown"),isPrimitive:false,importPath:this.calculateImportPath(e),nullable:!e.required&&this.options.generateNullable,metadata:{kind:e.kind,package:e.package}}}mapUnknownType(e){return {name:"unknown",isPrimitive:true,nullable:true,metadata:{originalType:e,warning:"unmapped_type"}}}calculateImportPath(e){return e.name?`./${this.formatFileName(e.name)}`:void 0}applyNamingConvention(e){switch(this.options.namingConvention){case "camelCase":return zt(e);case "PascalCase":return Rr(e);case "snake_case":return _t(e);case "kebab-case":return Ir(e);default:return e}}getCustomMapping(e){return this.options.customMappings[e]}shouldBeNullable(e){return !e&&this.options.generateNullable}};function zt(s){return s.replace(/[-_\s]+(.)?/g,(e,t)=>t?.toUpperCase()||"")}function Rr(s){let e=zt(s);return e.charAt(0).toUpperCase()+e.slice(1)}function _t(s){return s.replace(/([A-Z])/g,"_$1").replace(/[-\s]+/g,"_").toLowerCase().replace(/^_/,"")}function Ir(s){return _t(s).replace(/_/g,"-")}var Ie=class extends Re{tsOptions;constructor(e={}){super(e),this.tsOptions={...this.options,preferUnknown:true,useBrandedTypes:false,preferUndefined:true,moduleFormat:"esm",...e};}getLanguageName(){return "TypeScript"}mapPrimitive(e){let t=this.getCustomMapping(e);if(t)return {name:t,isPrimitive:true,nullable:false};let i={string:"string",integer:"number",decimal:"number",boolean:"boolean",dateTime:"string",date:"string",time:"string",instant:"string",uri:"string",url:"string",canonical:"string",oid:"string",uuid:"string",base64Binary:"string",code:"string",id:"string",markdown:"string",unsignedInt:"number",positiveInt:"number",xhtml:"string",json:"unknown"}[e];return i?this.tsOptions.useBrandedTypes&&e!==i?{name:`${i} & { readonly __brand: '${e}' }`,isPrimitive:false,importPath:"./brands",nullable:false,metadata:{isBranded:true,originalFhirType:e}}:{name:i,isPrimitive:true,nullable:false}:(console.warn(`Unknown FHIR primitive type: ${e}`),{name:this.tsOptions.preferUnknown?"unknown":"any",isPrimitive:true,nullable:false,metadata:{warning:"unmapped_primitive",originalType:e}})}mapReference(e){if(!e||e.length===0)return {name:"Reference",isPrimitive:false,importPath:"./Reference",generics:["unknown"],nullable:false};if(e.length===1){let r=e[0]?.name||"unknown";return {name:"Reference",isPrimitive:false,importPath:"./Reference",generics:[r==="unknown"?"unknown":`'${r}'`],nullable:false,metadata:{referencedType:r,referencedSchema:e[0]}}}return {name:"Reference",isPrimitive:false,importPath:"./Reference",generics:[e.map(r=>{let i=r.name||"unknown";return i==="unknown"?"unknown":`'${i}'`}).join(" | ")],nullable:false,metadata:{referencedTypes:e.map(r=>r.name||"unknown"),referencedSchemas:e}}}mapArray(e){return this.options.preferArraySyntax?{name:`${e.name}[]`,isPrimitive:e.isPrimitive,importPath:e.importPath,isArray:true,nullable:false,metadata:{elementType:e,arrayStyle:"suffix"}}:{name:"Array",isPrimitive:false,generics:[e.name],isArray:true,nullable:false,metadata:{elementType:e,arrayStyle:"generic"}}}mapOptional(e,t){if(t||!this.shouldBeNullable(t))return e;let r=this.tsOptions.preferUndefined?"undefined":"null";return {...e,name:`${e.name} | ${r}`,nullable:true,metadata:{...e.metadata,nullabilityType:r,wasOptional:true}}}mapEnum(e,t){let r=t?this.formatTypeName(t):"CodedValue";return {name:e.map(n=>`'${n}'`).join(" | "),isPrimitive:false,nullable:false,metadata:{enumName:r,values:e,isUnionType:true}}}formatTypeName(e){return this.applyNamingConvention(e)}formatFieldName(e){return Er(e)}formatFileName(e){return this.applyNamingConvention(e)}generateInterfaceField(e,t,r){return `${this.formatFieldName(e)}${r?"":"?"}: ${t.name};`}generateImportStatement(e){if(!(!e.importPath||e.isPrimitive))return this.tsOptions.moduleFormat==="esm"?`import type { ${e.name} } from '${e.importPath}';`:`const { ${e.name} } = require('${e.importPath}');`}getRequiredImports(e){let t=new Set;for(let r of e){let i=this.generateImportStatement(r);i&&t.add(i);}return Array.from(t).sort()}};function Er(s){return s.replace(/[-_\s]+(.)?/g,(e,t)=>t?.toUpperCase()||"")}var ee=class extends $e{resourceTypes=new Set;collectedValueSets=new Map;get tsOptions(){return this.options}getLanguageName(){return "TypeScript"}getFileExtension(){return ".ts"}createTypeMapper(){let e=this.options;return new Ie({namingConvention:(e.namingConvention??"PascalCase")==="PascalCase"?"PascalCase":"camelCase",moduleFormat:e.moduleFormat==="cjs"?"commonjs":"esm",preferUndefined:true,...e.typeMapperOptions})}async generateSchemaContent(e,t){if(this.shouldSkipSchema(e))return "";if(e.identifier.kind==="resource"&&this.resourceTypes.add(this.typeMapper.formatTypeName(e.identifier.name)),e.identifier.name==="Reference")return this.generateReferenceInterface(e);let r=this.generateTypeScriptInterface(e),i="";return "nested"in e&&e.nested&&Array.isArray(e.nested)&&(i=e.nested.map(o=>this.generateNestedTypeInterface(e.identifier.name,o)).join(`
29
+ \u{1F4A1} Common suggestions:`),n.forEach(o=>{this.options.logger.error(` \u2022 ${o}`);}));}}getCommonSuggestions(e){let t=e.flatMap(n=>n.getSuggestions()),r=new Map;t.forEach(n=>{r.set(n,(r.get(n)||0)+1);});let i=Math.ceil(e.length/2);return Array.from(r.entries()).filter(([n,o])=>o>=i).map(([n,o])=>n).slice(0,5)}getRecoveryActions(e){return "getRecoveryActions"in e?e.getRecoveryActions():[{action:"Review error message and suggestions above"},{action:"Check input files and configuration"},{action:"Try with --verbose flag for more information"}]}},Re=class{constructor(e){this.errorHandler=e;}async withErrorBoundary(e,t){try{return await e()}catch(r){throw this.errorHandler.handleError(r instanceof Error?r:new Error(String(r)),t),r}}async withBatchErrorBoundary(e,t){let r=[],i=[];for(let n of e)try{let o=await n();r.push(o);}catch(o){i.push(o instanceof Error?o:new Error(String(o)));}if(i.length>0)throw this.errorHandler.handleBatchErrors(i),new Fe(`${i.length} operations failed`,i.filter(n=>n instanceof v));return r}};te();te();var Ie=class{options;logger;constructor(e){this.options={overwrite:true,batchSize:10,...e},this.logger=e.logger;}async writeFile(e,t,r={}){let i=performance.now(),n=join(this.options.outputDir,e),o=r.encoding||"utf-8",a=r.overwrite??this.options.overwrite;try{if(!a)try{await access(n),this.logger.debug(`Skipping existing file: ${e}`);let d=await stat(n);return {path:n,size:d.size,writeTime:0}}catch{}await this.ensureDirectory(dirname(n)),await writeFile(n,t,o);let c=performance.now()-i,l=Buffer.byteLength(t,o);return this.logger.debug(`Written ${e} (${l} bytes, ${c.toFixed(2)}ms)`),{path:n,size:l,writeTime:c}}catch(c){throw new O(`Failed to write file '${e}': ${c}`,"write",n,c instanceof Error?c:void 0,{canRetry:true,alternativePaths:[join(process.cwd(),"backup-output",e)]})}}async writeBatch(e){this.logger.debug(`Writing batch of ${e.size} files`);let t=Array.from(e.entries()),r=[];for(let i=0;i<t.length;i+=this.options.batchSize){let o=t.slice(i,i+this.options.batchSize).map(([c,l])=>this.writeFile(c,l)),a=await Promise.all(o);r.push(...a),i+this.options.batchSize<t.length&&await new Promise(c=>setTimeout(c,10));}return r}async ensureDirectory(e){try{await mkdir(e,{recursive:!0});}catch(t){throw new O(`Failed to create directory '${e}': ${t}`,"create",e,t instanceof Error?t:void 0,{canRetry:true,permissionFix:`chmod 755 "${dirname(e)}"`})}}async cleanDirectory(e="."){let t=join(this.options.outputDir,e);try{await access(t),this.logger.debug(`Cleaning directory: ${e}`),await rm(t,{recursive:!0,force:!0});}catch(r){if(r?.code!=="ENOENT")throw new O(`Failed to clean directory '${e}': ${r}`,"delete",t,r instanceof Error?r:void 0,{canRetry:true})}}getRelativeImportPath(e,t){let r=dirname(join(this.options.outputDir,e)),i=join(this.options.outputDir,t),n=relative(r,i);return n.startsWith(".")||(n=`./${n}`),n.replace(/\.(d\.ts|ts|tsx|js|jsx)$/,"")}async wouldOverwrite(e){let t=join(this.options.outputDir,e);try{return await access(t),!0}catch{return false}}async getFileStats(e){let t=join(this.options.outputDir,e);try{return {size:(await stat(t)).size,generationTime:0,writeTime:0}}catch{return null}}getOutputDirectory(){return this.options.outputDir}setBatchSize(e){this.options.batchSize=Math.max(1,Math.min(50,e));}getBatchSize(){return this.options.batchSize}};var Ee=class{options;logger;fileManager;templateEngine;typeMapper;errorHandler;errorBoundary;progressCallback;generatedFiles=[];generationStartTime=0;cache=new Map;constructor(e){let t=this.validateConfiguration(e);if(!t.isValid)throw new Ce(`Invalid generator configuration: ${t.errors.join(", ")}`,"configuration",e);this.options=this.mergeWithDefaults(e),this.logger=e.logger||C({prefix:this.getLanguageName(),verbose:this.options.verbose||false}),this.fileManager=this.createFileManager(),this.templateEngine=this.createTemplateEngine(),this.typeMapper=this.createTypeMapper(),this.errorHandler=new $e({logger:this.logger,verbose:this.options.verbose||false,beginnerMode:this.options.beginnerMode||false,outputFormat:"this.options.logger"}),this.errorBoundary=new Re(this.errorHandler),this.logger.debug(`${this.getLanguageName()} generator initialized`),t.warnings.length>0&&t.warnings.forEach(r=>{this.logger.warn(`Configuration warning: ${r}`);});}getCapabilities(){return {language:this.getLanguageName(),fileExtensions:[this.getFileExtension()],supportsTemplates:true,supportsCustomTypeMapping:true,supportsIncrementalGeneration:false,supportsValidation:true,supportedSchemaKinds:["resource","complex-type","profile","logical"],version:"1.0.0"}}createFileManager(){return new Ie({outputDir:this.options.outputDir,logger:this.logger.child("FileManager"),overwrite:this.options.overwrite})}createTemplateEngine(){}async generate(e){return this.errorBoundary.withErrorBoundary(async()=>{this.generationStartTime=performance.now(),this.generatedFiles=[],this.logger.info(`Starting ${this.getLanguageName()} generation for ${e.length} schemas`),this.reportProgress("validation",0,e.length,"Validating schemas..."),await this.validateSchemas(e),this.reportProgress("generation",0,e.length,"Processing schemas...");let t=this.filterAndSortSchemas(e);this.logger.debug(`Filtered to ${t.length} schemas for generation`),await this.generateFiles(t),await this.runPostGenerationHooks(),this.reportProgress("complete",e.length,e.length,"Generation complete");let r=performance.now()-this.generationStartTime;return this.logger.info(`Generated ${this.generatedFiles.length} files in ${r.toFixed(2)}ms (avg ${(r/this.generatedFiles.length).toFixed(2)}ms per file)`),this.generatedFiles},{operationName:"generate"})}async build(e){let t=this.fileManager.writeFile,r=new Map;this.fileManager.writeFile=async(i,n)=>{let o={path:`${this.options.outputDir}/${i}`,size:Buffer.byteLength(n,"utf-8"),writeTime:0};return r.set(i,o),o};try{let i=await this.generate(e);return i.forEach(n=>{let o=r.get(n.filename);o&&(n.path=o.path,n.size=o.size);}),i}finally{this.fileManager.writeFile=t;}}file(e){if(!this.templateEngine)throw new Error("Template engine is required for fluent file generation. Override createTemplateEngine() in your generator.");let{FileBuilder:t}=(Qt(),Ae(Yt));return new t({filename:this.ensureFileExtension(e),fileManager:this.fileManager,templateEngine:this.templateEngine,typeMapper:this.typeMapper,logger:this.logger.child("FileBuilder")})}directory(e){let{DirectoryBuilder:t}=(er(),Ae(Xt));return new t({path:e,fileManager:this.fileManager,logger:this.logger.child("DirectoryBuilder")})}index(e="."){if(!this.templateEngine)throw new Error("Template engine is required for index file generation. Override createTemplateEngine() in your generator.");let{IndexBuilder:t}=(rr(),Ae(tr));return new t({directory:e,fileManager:this.fileManager,templateEngine:this.templateEngine,logger:this.logger.child("IndexBuilder")})}onProgress(e){return this.progressCallback=e,this}validateConfiguration(e){let t=[],r=[],i=[];return e.outputDir||(t.push("outputDir is required"),i.push("Provide a valid output directory path")),e.outputDir&&typeof e.outputDir!="string"&&t.push("outputDir must be a string"),e.overwrite!==void 0&&typeof e.overwrite!="boolean"&&t.push("overwrite must be a boolean"),e.validate!==void 0&&typeof e.validate!="boolean"&&t.push("validate must be a boolean"),e.outputDir&&!hr("path").isAbsolute(e.outputDir)&&(r.push("Using relative path for outputDir - consider using absolute path"),i.push("Use path.resolve() to convert to absolute path")),e.validate===false&&(r.push("Validation is disabled - this may lead to invalid generated code"),i.push("Consider enabling validation for better code quality")),{isValid:t.length===0,errors:t,warnings:r,suggestions:i}}mergeWithDefaults(e){return {overwrite:true,validate:true,verbose:false,beginnerMode:false,errorFormat:"console",...e}}async validateSchemas(e){if(!this.options.validate){this.logger.debug("Schema validation disabled");return}this.logger.info(`\u{1F50D} Starting schema validation for ${e.length} schemas`),this.logger.debug("Schema validation enabled - performing comprehensive validation");let t=e.map(r=>()=>this.errorBoundary.withErrorBoundary(async()=>{await this.validateSchema(r),this.reportProgress("validation",e.indexOf(r)+1,e.length,`Validated ${r.identifier?.name||"schema"}`);},{schema:r,operationName:"validateSchema"}));await this.errorBoundary.withBatchErrorBoundary(t,{operationName:"validateSchemas"}),this.logger.debug(`Successfully validated ${e.length} schemas`);}async validateSchema(e){let t=[],r=e.identifier?.name||"unknown";if(this.logger.debug(`\u{1F50D} Validating schema: ${r} (kind: ${e.identifier?.kind})`),!e.identifier)t.push("Schema missing identifier"),this.logger.warn(`\u274C Schema missing identifier: ${JSON.stringify(e,null,2).substring(0,200)}...`);else if(e.identifier.name||t.push("Schema identifier missing name"),!e.identifier.kind)t.push("Schema identifier missing kind");else {let i=["resource","complex-type","profile","primitive-type","logical","value-set","binding","extension"];i.includes(e.identifier.kind)||t.push(`Schema identifier.kind must be one of: ${i.join(", ")}`);}if("fields"in e&&e.fields)for(let[i,n]of Object.entries(e.fields))i.trim()||t.push("Field name cannot be empty"),n||t.push(`Field '${i}' is null or undefined`);if(await this.detectCircularReferences(e)&&this.logger.warn(`\u26A0\uFE0F Circular reference detected in schema '${r}' - this may be expected for FHIR primitive types`),t.length>0)throw this.logger.error(`\u274C Schema validation failed for '${r}': ${t.join(", ")}`),this.logger.debug(`Schema details: ${JSON.stringify(e,null,2)}`),new ke(`Schema validation failed for '${e.identifier?.name||"unknown"}'`,e,t);this.logger.debug(`\u2705 Schema validation passed for '${r}'`);}async detectCircularReferences(e){let t=new Set,r=new Set;return (n=>{let o=n.identifier?.name;if(!o)return false;if(r.has(o))return true;if(t.has(o))return false;if(r.add(o),"fields"in n&&n.fields){for(let a of Object.values(n.fields))if(a?.type?.name===o)return true}return r.delete(o),t.add(o),false})(e)}async generateFiles(e){let t=e.map((r,i)=>()=>this.errorBoundary.withErrorBoundary(async()=>{let n=await this.generateFileForSchema(r,i,e.length);return this.generatedFiles.push(n),n},{schema:r,operationName:"generateFile"}));await this.errorBoundary.withBatchErrorBoundary(t,{operationName:"generateFiles"}),this.logger.debug(`Generated ${this.generatedFiles.length} files`);}async generateFileForSchema(e,t,r){let i=performance.now(),n={schema:e,typeMapper:this.typeMapper,filename:this.typeMapper.formatFileName(e.identifier?.name||"unknown"),language:this.getLanguageName(),timestamp:new Date().toISOString(),imports:new Map,exports:new Set},o=await this.generateSchemaContent(e,n);this.options.validate&&await this.validateContent(o,n);let a=n.filename+this.getFileExtension(),c=await this.fileManager.writeFile(a,o),l=performance.now()-i;return this.reportProgress("writing",t+1,r,`Generated ${a} (${c.size} bytes)`),{path:c.path,filename:a,content:o,exports:this.extractExports(o),size:c.size,timestamp:new Date,metadata:{generationTime:l,schemaCount:1,templateName:n.templateName?.toString(),warnings:[]}}}ensureFileExtension(e){let t=this.getFileExtension();return e.endsWith(t)?e:`${e}${t}`}extractExports(e){let t=[],r=/export\s*\{\s*([^}]+)\s*\}/g,i;for(;(i=r.exec(e))!==null;)if(i[1]){let o=i[1].split(",").map(a=>a.trim()).filter(Boolean);t.push(...o);}let n=/export\s+(?:const|let|var|function|class|interface|type|enum)\s+(\w+)/g;for(;(i=n.exec(e))!==null;)i[1]&&t.push(i[1]);return [...new Set(t)]}reportProgress(e,t,r,i,n){this.progressCallback&&this.progressCallback(e,t,r,i,n),i&&this.options.verbose&&this.logger.debug(`[${e}] ${i} (${t}/${r})`);}async runPostGenerationHooks(){}getCachedOrCompute(e,t){if(this.cache.has(e))return this.cache.get(e);let r=t();return r instanceof Promise?r.then(i=>(this.cache.set(e,i),i)):(this.cache.set(e,r),r)}clearCache(){this.cache.clear();}getGenerationStats(){let e=this.generatedFiles.reduce((r,i)=>r+i.size,0),t=performance.now()-this.generationStartTime;return {filesGenerated:this.generatedFiles.length,totalSize:e,averageFileSize:this.generatedFiles.length>0?e/this.generatedFiles.length:0,generationTime:t,averageTimePerFile:this.generatedFiles.length>0?t/this.generatedFiles.length:0,cacheHitRate:0}}};var Pe=class{options;constructor(e={}){this.options={generateNullable:true,strictTypes:true,customMappings:{},preferArraySyntax:true,namingConvention:"PascalCase",...e};}mapType(e){if(typeof e=="string")return this.mapPrimitive(e);if(e&&typeof e=="object")switch(e.kind||e.type){case "primitive-type":return this.mapPrimitive(e.name);case "reference":return this.mapReference(e.targets||[]);case "array":{let r=this.mapType(e.element);return this.mapArray(r)}case "enum":case "coded":return this.mapEnum(e.values||[],e.name);case "complex-type":case "resource":return this.mapComplexType(e);default:return this.mapUnknownType(e)}return this.mapUnknownType(e)}mapComplexType(e){return {name:this.formatTypeName(e.name||"Unknown"),isPrimitive:false,importPath:this.calculateImportPath(e),nullable:!e.required&&this.options.generateNullable,metadata:{kind:e.kind,package:e.package}}}mapUnknownType(e){return {name:"unknown",isPrimitive:true,nullable:true,metadata:{originalType:e,warning:"unmapped_type"}}}calculateImportPath(e){return e.name?`./${this.formatFileName(e.name)}`:void 0}applyNamingConvention(e){switch(this.options.namingConvention){case "camelCase":return ir(e);case "PascalCase":return ei(e);case "snake_case":return nr(e);case "kebab-case":return ti(e);default:return e}}getCustomMapping(e){return this.options.customMappings[e]}shouldBeNullable(e){return !e&&this.options.generateNullable}};function ir(s){return s.replace(/[-_\s]+(.)?/g,(e,t)=>t?.toUpperCase()||"")}function ei(s){let e=ir(s);return e.charAt(0).toUpperCase()+e.slice(1)}function nr(s){return s.replace(/([A-Z])/g,"_$1").replace(/[-\s]+/g,"_").toLowerCase().replace(/^_/,"")}function ti(s){return nr(s).replace(/_/g,"-")}var Ne=class extends Pe{tsOptions;constructor(e={}){super(e),this.tsOptions={...this.options,preferUnknown:true,useBrandedTypes:false,preferUndefined:true,moduleFormat:"esm",...e};}getLanguageName(){return "TypeScript"}mapPrimitive(e){let t=this.getCustomMapping(e);if(t)return {name:t,isPrimitive:true,nullable:false};let i={string:"string",integer:"number",decimal:"number",boolean:"boolean",dateTime:"string",date:"string",time:"string",instant:"string",uri:"string",url:"string",canonical:"string",oid:"string",uuid:"string",base64Binary:"string",code:"string",id:"string",markdown:"string",unsignedInt:"number",positiveInt:"number",xhtml:"string",json:"unknown"}[e];return i?this.tsOptions.useBrandedTypes&&e!==i?{name:`${i} & { readonly __brand: '${e}' }`,isPrimitive:false,importPath:"./brands",nullable:false,metadata:{isBranded:true,originalFhirType:e}}:{name:i,isPrimitive:true,nullable:false}:(console.warn(`Unknown FHIR primitive type: ${e}`),{name:this.tsOptions.preferUnknown?"unknown":"any",isPrimitive:true,nullable:false,metadata:{warning:"unmapped_primitive",originalType:e}})}mapReference(e){if(!e||e.length===0)return {name:"Reference",isPrimitive:false,importPath:"./Reference",generics:["unknown"],nullable:false};if(e.length===1){let r=e[0]?.name||"unknown";return {name:"Reference",isPrimitive:false,importPath:"./Reference",generics:[r==="unknown"?"unknown":`'${r}'`],nullable:false,metadata:{referencedType:r,referencedSchema:e[0]}}}return {name:"Reference",isPrimitive:false,importPath:"./Reference",generics:[e.map(r=>{let i=r.name||"unknown";return i==="unknown"?"unknown":`'${i}'`}).join(" | ")],nullable:false,metadata:{referencedTypes:e.map(r=>r.name||"unknown"),referencedSchemas:e}}}mapArray(e){return this.options.preferArraySyntax?{name:`${e.name}[]`,isPrimitive:e.isPrimitive,importPath:e.importPath,isArray:true,nullable:false,metadata:{elementType:e,arrayStyle:"suffix"}}:{name:"Array",isPrimitive:false,generics:[e.name],isArray:true,nullable:false,metadata:{elementType:e,arrayStyle:"generic"}}}mapOptional(e,t){if(t||!this.shouldBeNullable(t))return e;let r=this.tsOptions.preferUndefined?"undefined":"null";return {...e,name:`${e.name} | ${r}`,nullable:true,metadata:{...e.metadata,nullabilityType:r,wasOptional:true}}}mapEnum(e,t){let r=t?this.formatTypeName(t):"CodedValue";return {name:e.map(n=>`'${n}'`).join(" | "),isPrimitive:false,nullable:false,metadata:{enumName:r,values:e,isUnionType:true}}}formatTypeName(e){return this.applyNamingConvention(e)}formatFieldName(e){return ri(e)}formatFileName(e){return this.applyNamingConvention(e)}generateInterfaceField(e,t,r){return `${this.formatFieldName(e)}${r?"":"?"}: ${t.name};`}generateImportStatement(e){if(!(!e.importPath||e.isPrimitive))return this.tsOptions.moduleFormat==="esm"?`import type { ${e.name} } from '${e.importPath}';`:`const { ${e.name} } = require('${e.importPath}');`}getRequiredImports(e){let t=new Set;for(let r of e){let i=this.generateImportStatement(r);i&&t.add(i);}return Array.from(t).sort()}};function ri(s){return s.replace(/[-_\s]+(.)?/g,(e,t)=>t?.toUpperCase()||"")}var re=class extends Ee{resourceTypes=new Set;collectedValueSets=new Map;get tsOptions(){return this.options}getLanguageName(){return "TypeScript"}getFileExtension(){return ".ts"}createTypeMapper(){let e=this.options;return new Ne({namingConvention:(e.namingConvention??"PascalCase")==="PascalCase"?"PascalCase":"camelCase",moduleFormat:e.moduleFormat==="cjs"?"commonjs":"esm",preferUndefined:true,...e.typeMapperOptions})}async generateSchemaContent(e,t){if(this.shouldSkipSchema(e))return "";if(e.identifier.kind==="resource"&&this.resourceTypes.add(this.typeMapper.formatTypeName(e.identifier.name)),e.identifier.name==="Reference")return this.generateReferenceInterface(e);let r=this.generateTypeScriptInterface(e),i="";return "nested"in e&&e.nested&&Array.isArray(e.nested)&&(i=e.nested.map(o=>this.generateNestedTypeInterface(e.identifier.name,o)).join(`
27
30
 
28
31
  `)),i?`${r}
29
32
 
30
- ${i}`:r}filterAndSortSchemas(e){return this.collectedValueSets=this.collectValueSets(e),e.filter(t=>!this.shouldSkipSchema(t))}async validateContent(e,t){let r=/export\s+(interface|class|type|enum)\s+\w+/.test(e),i=e.includes("{")&&e.includes("}");if(!r)throw new Error(`Generated content for ${t.schema.identifier.name} does not contain valid export statements`);if(!i)throw new Error(`Generated content for ${t.schema.identifier.name} has invalid syntax (missing braces)`)}async transformSchemas(e){let t=[];for(let r of e){let i=await this.transformSchema(r);i&&t.push(i);}return t}async transformSchema(e){if(this.shouldSkipSchema(e))return;let t={schema:e,typeMapper:this.typeMapper,filename:this.getFilenameForSchema(e),language:"TypeScript",timestamp:new Date().toISOString()},r=await this.generateSchemaContent(e,t);if(!r.trim())return;let i=this.extractImportsFromContent(r,e),n=this.extractExportsFromContent(r,e),o=this.getFilenameForSchema(e);return {content:r,imports:i,exports:Array.from(n),filename:o}}shouldGenerateValueSet(e){if(!ze(e)||!e.enum||!Array.isArray(e.enum)||e.enum.length===0)return false;switch(this.options.valueSetMode||"required-only"){case "all":return true;case "required-only":return e.strength==="required";case "custom":return (this.options.valueSetStrengths||["required"]).includes(e.strength);default:return e.strength==="required"}}collectValueSets(e){let t=new Map;for(let r of e)if(this.shouldGenerateValueSet(r)&&ze(r)){let i=this.typeMapper.formatTypeName(r.identifier.name);t.set(i,r);}return t}shouldUseValueSetType(e){if(!e||!this.tsOptions.generateValueSets)return false;let t=this.typeMapper.formatTypeName(e.name);return this.collectedValueSets.has(t)}getValueSetTypeName(e){return this.typeMapper.formatTypeName(e.name)}shouldUseInlineEnum(e){return !e||this.tsOptions.generateValueSets?false:e.enum&&Array.isArray(e.enum)&&e.enum.length>0}generateInlineEnumType(e){return !e.enum||!Array.isArray(e.enum)?"string":e.enum.map(r=>`'${r}'`).join(" | ")}shouldSkipSchema(e){if(e.identifier.kind==="value-set"||e.identifier.kind==="binding"||e.identifier.kind==="primitive-type")return true;if(!this.tsOptions.includeExtensions){let t=e.identifier.url;if(t?.includes("StructureDefinition/")){let r=t.split("StructureDefinition/")[1];if(r){let i=r.includes("-"),n=e.identifier.kind==="profile";if(i&&n)return true}}}return false}getFilenameForSchema(e){return `${this.typeMapper.formatFileName(e.identifier.name)}${this.getFileExtension()}`}extractImportsFromContent(e,t){let r=new Map,i=/import\s+(?:type\s+)?{\s*([^}]+)\s*}\s+from\s+['"]([^'"]+)['"];?/g,n;for(;(n=i.exec(e))!==null;){let o=n[1],a=n[2];if(!o||!a)continue;let c=o.split(",").map(l=>l.trim());for(let l of c)r.set(l,a);}return r}extractExportsFromContent(e,t){let r=new Set,i=/export\s+(?:interface|class|enum|type)\s+([A-Za-z_$][A-Za-z0-9_$]*)/g,n;for(;(n=i.exec(e))!==null;)n[1]&&r.add(n[1]);return r.add(this.typeMapper.formatTypeName(t.identifier.name)),r}generateReferenceInterface(e){let t=[],r=new Set;if("fields"in e&&e.fields)for(let[,i]of Object.entries(e.fields))this.collectFieldImports(i).forEach(o=>r.add(o));if(t.push("import type { ResourceType } from './utilities.js';"),r.size>0){let i=Array.from(r).sort();for(let n of i)t.push(`import type { ${n} } from './${n}.js';`);}if(t.push(""),this.tsOptions.includeDocuments&&e.description&&(t.push("/**"),t.push(` * ${e.description}`),e.identifier.url&&t.push(` * @see ${e.identifier.url}`),e.identifier.package&&t.push(` * @package ${e.identifier.package}`),t.push(" * @template T - The resource type being referenced"),t.push(" */")),t.push("export interface Reference<T extends ResourceType = ResourceType> {"),"fields"in e&&e.fields)for(let[i,n]of Object.entries(e.fields))if(i==="type")t.push(" type?: T;");else {let o=this.generateFieldLines(i,n);for(let a of o)a&&t.push(` ${a}`);}return t.push("}"),t.join(`
33
+ ${i}`:r}filterAndSortSchemas(e){return this.collectedValueSets=this.collectValueSets(e),e.filter(t=>!this.shouldSkipSchema(t))}async validateContent(e,t){let r=/export\s+(interface|class|type|enum)\s+\w+/.test(e),i=e.includes("{")&&e.includes("}");if(!r)throw new Error(`Generated content for ${t.schema.identifier.name} does not contain valid export statements`);if(!i)throw new Error(`Generated content for ${t.schema.identifier.name} has invalid syntax (missing braces)`)}async transformSchemas(e){let t=[];for(let r of e){let i=await this.transformSchema(r);i&&t.push(i);}return t}async transformSchema(e){if(this.shouldSkipSchema(e))return;let t={schema:e,typeMapper:this.typeMapper,filename:this.getFilenameForSchema(e),language:"TypeScript",timestamp:new Date().toISOString()},r=await this.generateSchemaContent(e,t);if(!r.trim())return;let i=this.extractImportsFromContent(r,e),n=this.extractExportsFromContent(r,e),o=this.getFilenameForSchema(e);return {content:r,imports:i,exports:Array.from(n),filename:o}}shouldGenerateValueSet(e){if(!qe(e)||!e.enum||!Array.isArray(e.enum)||e.enum.length===0)return false;switch(this.options.valueSetMode||"required-only"){case "all":return true;case "required-only":return e.strength==="required";case "custom":return (this.options.valueSetStrengths||["required"]).includes(e.strength);default:return e.strength==="required"}}collectValueSets(e){let t=new Map;for(let r of e)if(this.shouldGenerateValueSet(r)&&qe(r)){let i=this.typeMapper.formatTypeName(r.identifier.name);t.set(i,r);}return t}shouldUseValueSetType(e){if(!e||!this.tsOptions.generateValueSets)return false;let t=this.typeMapper.formatTypeName(e.name);return this.collectedValueSets.has(t)}getValueSetTypeName(e){return this.typeMapper.formatTypeName(e.name)}shouldUseInlineEnum(e){return !e||this.tsOptions.generateValueSets?false:e.enum&&Array.isArray(e.enum)&&e.enum.length>0}generateInlineEnumType(e){return !e.enum||!Array.isArray(e.enum)?"string":e.enum.map(r=>`'${r}'`).join(" | ")}shouldSkipSchema(e){if(e.identifier.kind==="value-set"||e.identifier.kind==="binding"||e.identifier.kind==="primitive-type")return true;if(!this.tsOptions.includeExtensions){let t=e.identifier.url;if(t?.includes("StructureDefinition/")){let r=t.split("StructureDefinition/")[1];if(r){let i=r.includes("-"),n=e.identifier.kind==="profile";if(i&&n)return true}}}return false}getFilenameForSchema(e){return `${this.typeMapper.formatFileName(e.identifier.name)}${this.getFileExtension()}`}extractImportsFromContent(e,t){let r=new Map,i=/import\s+(?:type\s+)?{\s*([^}]+)\s*}\s+from\s+['"]([^'"]+)['"];?/g,n;for(;(n=i.exec(e))!==null;){let o=n[1],a=n[2];if(!o||!a)continue;let c=o.split(",").map(l=>l.trim());for(let l of c)r.set(l,a);}return r}extractExportsFromContent(e,t){let r=new Set,i=/export\s+(?:interface|class|enum|type)\s+([A-Za-z_$][A-Za-z0-9_$]*)/g,n;for(;(n=i.exec(e))!==null;)n[1]&&r.add(n[1]);return r.add(this.typeMapper.formatTypeName(t.identifier.name)),r}generateReferenceInterface(e){let t=[],r=new Set;if("fields"in e&&e.fields)for(let[,i]of Object.entries(e.fields))this.collectFieldImports(i).forEach(o=>r.add(o));if(t.push("import type { ResourceType } from './utilities.js';"),r.size>0){let i=Array.from(r).sort();for(let n of i)t.push(`import type { ${n} } from './${n}.js';`);}if(t.push(""),this.tsOptions.includeDocuments&&e.description&&(t.push("/**"),t.push(` * ${e.description}`),e.identifier.url&&t.push(` * @see ${e.identifier.url}`),e.identifier.package&&t.push(` * @package ${e.identifier.package}`),t.push(" * @template T - The resource type being referenced"),t.push(" */")),t.push("export interface Reference<T extends ResourceType = ResourceType> {"),"fields"in e&&e.fields)for(let[i,n]of Object.entries(e.fields))if(i==="type")t.push(" type?: T;");else {let o=this.generateFieldLines(i,n);for(let a of o)a&&t.push(` ${a}`);}return t.push("}"),t.join(`
31
34
  `)}generateTypeScriptInterface(e){let t=[],r=this.typeMapper.formatTypeName(e.identifier.name),i=new Set,n=new Set;if("fields"in e&&e.fields)for(let[,o]of Object.entries(e.fields)){let a=this.collectFieldImports(o);for(let c of a)this.collectedValueSets.has(c)?n.add(c):i.add(c);}if("nested"in e&&e.nested&&Array.isArray(e.nested)){for(let o of e.nested)if(o.fields)for(let[,a]of Object.entries(o.fields)){let c=this.collectFieldImports(a);for(let l of c)this.collectedValueSets.has(l)?n.add(l):i.add(l);}}if(i.size>0){let o=Array.from(i).sort();for(let a of o)t.push(`import type { ${a} } from './${a}.js';`);}if(n.size>0){let a=Array.from(n).sort().join(", ");t.push(`import type { ${a} } from './valuesets/index.js';`);}if((i.size>0||n.size>0)&&t.push(""),this.tsOptions.includeDocuments&&e.description&&(t.push("/**"),t.push(` * ${e.description}`),e.identifier.url&&t.push(` * @see ${e.identifier.url}`),e.identifier.package&&t.push(` * @package ${e.identifier.package}`),t.push(" */")),t.push(`export interface ${r} {`),e.identifier.kind==="resource"&&t.push(` resourceType: '${r}';`),"fields"in e&&e.fields)for(let[o,a]of Object.entries(e.fields)){let c=this.generateFieldLines(o,a);for(let l of c)l&&t.push(` ${l}`);}return t.push("}"),t.join(`
32
35
  `)}collectFieldImports(e){let t=[];if("choices"in e&&e.choices&&Array.isArray(e.choices))return t;if(e.binding&&this.shouldUseValueSetType(e.binding)){let r=this.getValueSetTypeName(e.binding);return t.push(r),t}if("type"in e&&e.type){if(e.type.kind==="nested")return t;let r=this.typeMapper.mapType(e.type);!r.isPrimitive&&r.name!=="any"&&(["string","number","boolean","Date","object","unknown","any"].includes(r.name)||t.push(r.name));}return [...new Set(t)]}extractReferenceTypes(e){let t=[];if(!Array.isArray(e))return t;for(let r of e)if(!(!r||typeof r!="object")&&r.kind==="resource"&&r.name){let i=this.typeMapper.formatTypeName(r.name);t.push(i);}return [...new Set(t)]}generateNestedTypeInterface(e,t){let r=[],i=this.typeMapper.formatTypeName(`${e}${this.capitalizeFirst(t.identifier.name)}`);if(this.tsOptions.includeDocuments&&t.description&&(r.push("/**"),r.push(` * ${t.description}`),t.identifier.url&&r.push(` * @see ${t.identifier.url}`),r.push(" */")),r.push(`export interface ${i} {`),t.fields)for(let[n,o]of Object.entries(t.fields)){let a=this.generateFieldLines(n,o);for(let c of a)c&&r.push(` ${c}`);}return r.push("}"),r.join(`
33
- `)}capitalizeFirst(e){return e.charAt(0).toUpperCase()+e.slice(1)}generateFieldLines(e,t){if("choices"in t&&t.choices&&Array.isArray(t.choices))return [];let r=this.generateFieldLine(e,t);return r?[r]:[]}generateFieldLine(e,t){let r="any",i=false,n=false;if("type"in t&&t.type){if(t.binding&&this.shouldUseValueSetType(t.binding))r=this.getValueSetTypeName(t.binding);else if(t.binding&&this.shouldUseInlineEnum(t))r=this.generateInlineEnumType(t);else if(r=this.typeMapper.mapType(t.type).name,t.type.kind==="nested"){let l=t.type.url?.split("#")||[];if(l.length===2){let u=l[0].split("/").pop()||"",g=t.type.name;r=this.typeMapper.formatTypeName(`${u}${this.capitalizeFirst(g)}`);}else r=this.typeMapper.formatTypeName(t.type.name);}else if(r==="Reference"&&t.reference&&Array.isArray(t.reference)){let l=this.extractReferenceTypes(t.reference);l.length>0&&(l.forEach(g=>this.resourceTypes.add(g)),r=`Reference<${l.map(g=>`'${g}'`).join(" | ")}>`);}}return "required"in t&&(i=t.required),"array"in t&&(n=t.array),`${e}${i?"":"?"}: ${r}${n?"[]":""};`}extractExports(e){let t=[],r=/export\s*\{\s*([^}]+)\s*\}/g,i;for(;(i=r.exec(e))!==null;)if(i[1]){let o=i[1].split(",").map(a=>a.trim()).filter(Boolean);t.push(...o);}let n=[/export\s+interface\s+(\w+)/g,/export\s+type\s+(\w+)/g,/export\s+class\s+(\w+)/g,/export\s+enum\s+(\w+)/g,/export\s+const\s+(\w+)/g,/export\s+function\s+(\w+)/g];for(let o of n){let a;for(;(a=o.exec(e))!==null;)a[1]&&t.push(a[1]);}return [...new Set(t)]}setOutputDir(e){this.options.outputDir=e;}setOptions(e){this.options={...this.options,...e};}getOptions(){return {...this.options}}async generate(e){return await this.fileManager.cleanDirectory(),this.logger.debug("Cleaned output directory before generation"),super.generate(e)}async runPostGenerationHooks(){await super.runPostGenerationHooks(),await this.generateValueSetFiles(),await this.generateUtilitiesFile(),await this.generateMainIndexFile();}async generateUtilitiesFile(){if(this.resourceTypes.size===0){this.logger.warn("No resource types found, skipping utilities.ts generation");return}let e=[];e.push("/**"),e.push(" * FHIR Resource Type Utilities"),e.push(" * This file contains utility types for FHIR resources."),e.push(" * "),e.push(" * @generated This file is auto-generated. Do not edit manually."),e.push(" */"),e.push("");let t=Array.from(this.resourceTypes).sort();e.push("/**"),e.push(" * Union of all FHIR resource types in this package"),e.push(" */"),e.push("export type ResourceType =");for(let i=0;i<t.length;i++){let o=i===t.length-1?";":"";e.push(` | '${t[i]}'${o}`);}e.push(""),e.push("/**"),e.push(" * Helper type for creating typed References"),e.push(" * @example Reference<'Patient' | 'Practitioner'> - Reference that can point to Patient or Practitioner"),e.push(" */"),e.push("export type TypedReference<T extends ResourceType> = {"),e.push(" reference?: string;"),e.push(" type?: T;"),e.push(" identifier?: any; // Simplified for utility"),e.push(" display?: string;"),e.push("};");let r=e.join(`
36
+ `)}capitalizeFirst(e){return e.charAt(0).toUpperCase()+e.slice(1)}generateFieldLines(e,t){if("choices"in t&&t.choices&&Array.isArray(t.choices))return [];let r=this.generateFieldLine(e,t);return r?[r]:[]}generateFieldLine(e,t){let r="any",i=false,n=false;if("type"in t&&t.type){if(t.binding&&this.shouldUseValueSetType(t.binding))r=this.getValueSetTypeName(t.binding);else if(t.binding&&this.shouldUseInlineEnum(t))r=this.generateInlineEnumType(t);else if(r=this.typeMapper.mapType(t.type).name,t.type.kind==="nested"){let l=t.type.url?.split("#")||[];if(l.length===2){let d=l[0].split("/").pop()||"",f=t.type.name;r=this.typeMapper.formatTypeName(`${d}${this.capitalizeFirst(f)}`);}else r=this.typeMapper.formatTypeName(t.type.name);}else if(r==="Reference"&&t.reference&&Array.isArray(t.reference)){let l=this.extractReferenceTypes(t.reference);l.length>0&&(l.forEach(f=>this.resourceTypes.add(f)),r=`Reference<${l.map(f=>`'${f}'`).join(" | ")}>`);}}return "required"in t&&(i=t.required),"array"in t&&(n=t.array),`${e}${i?"":"?"}: ${r}${n?"[]":""};`}extractExports(e){let t=[],r=/export\s*\{\s*([^}]+)\s*\}/g,i;for(;(i=r.exec(e))!==null;)if(i[1]){let o=i[1].split(",").map(a=>a.trim()).filter(Boolean);t.push(...o);}let n=[/export\s+interface\s+(\w+)/g,/export\s+type\s+(\w+)/g,/export\s+class\s+(\w+)/g,/export\s+enum\s+(\w+)/g,/export\s+const\s+(\w+)/g,/export\s+function\s+(\w+)/g];for(let o of n){let a;for(;(a=o.exec(e))!==null;)a[1]&&t.push(a[1]);}return [...new Set(t)]}setOutputDir(e){this.options.outputDir=e;}setOptions(e){this.options={...this.options,...e};}getOptions(){return {...this.options}}async generate(e){return await this.fileManager.cleanDirectory(),this.logger.debug("Cleaned output directory before generation"),super.generate(e)}async runPostGenerationHooks(){await super.runPostGenerationHooks(),await this.generateValueSetFiles(),await this.generateUtilitiesFile(),await this.generateMainIndexFile();}async generateUtilitiesFile(){if(this.resourceTypes.size===0){this.logger.warn("No resource types found, skipping utilities.ts generation");return}let e=[];e.push("/**"),e.push(" * FHIR Resource Type Utilities"),e.push(" * This file contains utility types for FHIR resources."),e.push(" * "),e.push(" * @generated This file is auto-generated. Do not edit manually."),e.push(" */"),e.push("");let t=Array.from(this.resourceTypes).sort();e.push("/**"),e.push(" * Union of all FHIR resource types in this package"),e.push(" */"),e.push("export type ResourceType =");for(let i=0;i<t.length;i++){let o=i===t.length-1?";":"";e.push(` | '${t[i]}'${o}`);}e.push(""),e.push("/**"),e.push(" * Helper type for creating typed References"),e.push(" * @example Reference<'Patient' | 'Practitioner'> - Reference that can point to Patient or Practitioner"),e.push(" */"),e.push("export type TypedReference<T extends ResourceType> = {"),e.push(" reference?: string;"),e.push(" type?: T;"),e.push(" identifier?: any; // Simplified for utility"),e.push(" display?: string;"),e.push("};");let r=e.join(`
34
37
  `);await this.fileManager.writeFile("utilities.ts",r),this.logger.info(`Generated utilities.ts with ${this.resourceTypes.size} resource types`);}generateValueSetFile(e){let t=this.typeMapper.formatTypeName(e.identifier.name),r=e.enum?.map(n=>` '${n}'`).join(`,
35
38
  `)||"",i=[];return this.options.includeDocuments&&(i.push("/**"),i.push(` * ${e.identifier.name} value set`),e.description&&i.push(` * ${e.description}`),e.valueset?.url&&i.push(` * @see ${e.valueset.url}`),e.identifier.package&&i.push(` * @package ${e.identifier.package}`),i.push(" * @generated This file is auto-generated. Do not edit manually."),i.push(" */"),i.push("")),i.push(`export const ${t}Values = [`),r&&i.push(r),i.push("] as const;"),i.push(""),i.push(`export type ${t} = typeof ${t}Values[number];`),this.tsOptions.includeValueSetHelpers&&(i.push(""),i.push(`export const isValid${t} = (value: string): value is ${t} =>`),i.push(` ${t}Values.includes(value as ${t});`)),i.join(`
36
39
  `)}async generateValueSetFiles(){if(!(!this.tsOptions.generateValueSets||this.collectedValueSets.size===0)){for(let[e,t]of this.collectedValueSets){let r=this.generateValueSetFile(t),i=`valuesets/${e}.ts`;await this.fileManager.writeFile(i,r),this.logger.info(`Generated value set: ${i}`);}await this.generateValueSetIndexFile();}}async generateValueSetIndexFile(){let e=[];this.tsOptions.includeDocuments&&(e.push("/**"),e.push(" * FHIR Value Sets"),e.push(" * This file re-exports all generated value sets."),e.push(" * "),e.push(" * @generated This file is auto-generated. Do not edit manually."),e.push(" */"),e.push(""));let t=Array.from(this.collectedValueSets.keys()).sort();for(let i of t)e.push(`export * from './${i}.js';`);let r=e.join(`
37
40
  `);await this.fileManager.writeFile("valuesets/index.ts",r),this.logger.info(`Generated valuesets/index.ts with ${this.collectedValueSets.size} value sets`);}async generateMainIndexFile(){if(!this.options.generateIndex)return;let e=[];this.tsOptions.includeDocuments&&(e.push("/**"),e.push(" * FHIR R4 TypeScript Types"),e.push(" * Generated from FHIR StructureDefinitions"),e.push(" * "),e.push(" * @generated This file is auto-generated. Do not edit manually."),e.push(" */"),e.push("")),e.push('export * from "./utilities";'),this.tsOptions.generateValueSets&&this.collectedValueSets.size>0&&(e.push(""),e.push("// Value Sets"),e.push('export * from "./valuesets/index";'));let t=e.join(`
38
- `);await this.fileManager.writeFile("index.ts",t),this.logger.info(`Generated index.ts with type exports${this.tsOptions.generateValueSets&&this.collectedValueSets.size>0?" and value sets":""}`);}};var nt=class{opts;currentDir;currentFileDescriptor;writtenFilesSet=new Set;constructor(e){this.opts=e,this.currentDir=e.outputDir;}logger(){return this.opts.logger}cd(e,t){this.currentDir=e.startsWith("/")?I.join(this.opts.outputDir,e):I.join(this.currentDir,e),E.existsSync(this.currentDir)||E.mkdirSync(this.currentDir,{recursive:true}),this.logger()?.debug(`cd '${this.currentDir}'`),t();}cat(e,t){if(this.currentFileDescriptor)throw new Error("Can't open file in file");if(e.includes("/"))throw new Error(`Change file path separatly: ${e}`);let r=`${this.currentDir}/${e}`;try{this.currentFileDescriptor=E.openSync(r,"w"),this.writtenFilesSet.add(e),this.logger()?.debug(`cat > '${r}'`),t();}finally{this.currentFileDescriptor&&E.closeSync(this.currentFileDescriptor),this.currentFileDescriptor=void 0;}}write(e){if(!this.currentFileDescriptor)throw new Error("No file opened");E.writeSync(this.currentFileDescriptor,e);}generate(e){throw new Error("Not implemented")}writtenFiles(){return Array.from(this.writtenFilesSet)}},Ee=class extends nt{currentIndent=0;indent(){this.currentIndent+=this.opts.tabSize;}deindent(){this.currentIndent-=this.opts.tabSize;}writeIndent(){this.write(" ".repeat(this.currentIndent));}line(...e){e.length===0?this.write(`
39
- `):(this.writeIndent(),this.write(`${e.join(" ")}
40
- `));}lineSM(...e){this.writeIndent(),this.write(`${e.join(" ")};
41
- `);}comment(...e){let t=e.join(" ").split(`
42
- `);for(let r of t)this.line(this.opts.commentLinePrefix,r);}debugComment(...e){this.opts.withDebugComment&&(e=e.map(t=>typeof t=="string"?t:JSON.stringify(t,null,2)),this.comment(...e));}disclaimer(){return ["WARNING: This file is autogenerated by @atomic-ehr/codegen.","GitHub: https://github.com/orgs/atomic-ehr/repositories","Any manual changes made to this file may be overwritten."]}generateDisclaimer(){this.disclaimer().forEach(e=>this.comment(e)),this.line();}indentBlock(e){this.indent(),e(),this.deindent();}curlyBlock(e,t,r){this.line(`${e.filter(Boolean).join(" ")} {`),this.indent(),t(),this.deindent(),this.line(`}${r?.filter(Boolean).join(" ")??""}`);}squareBlock(e,t,r){this.line(`${e.filter(Boolean).join(" ")} [`),this.indent(),t(),this.deindent(),this.line(`]${r?.filter(Boolean).join(" ")??""}`);}};var Pr={boolean:"boolean",instant:"string",time:"string",date:"string",dateTime:"string",decimal:"number",integer:"number",unsignedInt:"number",positiveInt:"number",integer64:"number",base64Binary:"string",uri:"string",url:"string",canonical:"string",oid:"string",uuid:"string",string:"string",code:"string",markdown:"string",id:"string",xhtml:"string"},qt=s=>{let e=Pr[s];if(e===void 0)throw new Error(`Unknown primitive type ${s}`);return e},Nr=s=>Z(s),Wt=s=>s.kind==="profile"?`${F(s)}_profile`:Y(s.name),Mr=s=>`${Wt(s)}.ts`,st=(s,e=true)=>{if(!s)return;let t=s.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),ot(t)},F=s=>{if(s.kind==="nested"){let e=s.url,t=st(e,false);if(!t)return "";let[r,i]=t.split("#"),n=Ot((i??"").split(".")).join("");return ot([r,n].join(""))}return ot(s.name)},Jt=new Set(["class","function","return","if","for","while","const","let","var","import","export","interface"]),z=s=>Jt.has(s)?`"${s}"`:s.includes(" ")||s.includes("-")?`"${s}"`:s,ot=s=>(Jt.has(s)&&(s=`${s}_`),s.replace(/[- ]/g,"_")),A=(s,e)=>e.startsWith('"')?`${s}[${e}]`:`${s}.${e}`,Pe=class extends Ee{tsImportType(e,...t){this.lineSM(`import type { ${t.join(", ")} } from "${e}"`);}generateFhirPackageIndexFile(e){this.cat("index.ts",()=>{let t=e.map(r=>({identifier:r.identifier,tsPackageName:Wt(r.identifier),resourceName:F(r.identifier)})).sort((r,i)=>r.resourceName.localeCompare(i.resourceName));t=Array.from(new Map(t.map(r=>[r.resourceName.toLowerCase(),r])).values()).sort((r,i)=>r.resourceName.localeCompare(i.resourceName));for(let r of t)this.debugComment(r.identifier),this.lineSM(`export type { ${r.resourceName} } from "./${r.tsPackageName}"`);});}generateDependenciesImports(e){if(e.dependencies){let t=[],r=[];for(let i of e.dependencies)["complex-type","resource","logical"].includes(i.kind)?t.push({tsPackage:`../${Z(i.package)}/${Y(i.name)}`,name:ve(i.name)}):U(i)?t.push({tsPackage:`../${Z(i.package)}/${Y(st(i.url)??"")}`,name:F(i)}):r.push(i);t.sort((i,n)=>i.name.localeCompare(n.name));for(let i of t)this.tsImportType(i.tsPackage,i.name);for(let i of r)this.debugComment("skip:",i);this.line();}}generateComplexTypeReexports(e){let t=e.dependencies?.filter(r=>["complex-type"].includes(r.kind)).map(r=>({tsPackage:`../${Z(r.package)}/${Y(r.name)}`,name:ve(r.name)}));if(t&&t.length>0){for(let r of t)this.lineSM(`export type { ${r.name} } from "${r.tsPackage}"`);this.line();}}addFieldExtension(e,t){if(t.type.kind==="primitive-type"){let r=z(`_${e}`);this.lineSM(`${r}?: Element`);}}generateType(e,t){let r;t.identifier.name==="Reference"?r="Reference<T extends string = string>":(t.identifier.kind,r=F(t.identifier));let i;t.base&&(i=`extends ${st(t.base.url)}`),this.debugComment(t.identifier),this.curlyBlock(["export","interface",r,i],()=>{if(q(t)){let o=[t.identifier];o.push(...e.resourceChildren(t.identifier)),this.lineSM(`resourceType: ${o.map(a=>`"${a.name}"`).join(" | ")}`),this.line();}if(!t.fields)return;let n=Object.entries(t.fields).sort((o,a)=>o[0].localeCompare(a[0]));for(let[o,a]of n){if(le(a))continue;this.debugComment(o,":",a);let c=z(o),l;a.enum?l=a.enum.map(m=>`"${m}"`).join(" | "):t.identifier.name==="Reference"&&c==="reference"?l="`${T}/${string}`":a.reference&&a.reference.length>0?l=`Reference<${a.reference.map(p=>`"${p.name}"`).join(" | ")}>`:He(a.type)?l=qt(a.type.name):U(a.type)?l=F(a.type):l=a.type.name;let u=a.required?"":"?",g=a.array?"[]":"";this.lineSM(`${c}${u}: ${l}${g}`),["resource","complex-type"].includes(t.identifier.kind)&&this.addFieldExtension(o,a);}});}generateNestedTypes(e,t){if(t.nested)for(let r of t.nested)this.generateType(e,r),this.line();}generateProfileType(e,t){let r=F(t.identifier);this.debugComment("identifier",t.identifier),this.debugComment("base",t.base),this.curlyBlock(["export","interface",r],()=>{this.lineSM(`__profileUrl: "${t.identifier.url}"`),this.line();for(let[i,n]of Object.entries(t.fields??{})){if(le(n))continue;this.debugComment(i,n);let o=z(i),a;if(n.enum)a=n.enum.map(c=>`'${c}'`).join(" | ");else if(n.reference&&n.reference.length>0){let c=e.findLastSpecialization(t);if(!_(c))throw new Error(`Invalid specialization for ${t.identifier}`);let l=c.fields?.[i];if(l===void 0||le(l)||l.reference===void 0)throw new Error(`Invalid field declaration for ${i}`);let u=l.reference.map(m=>m.name),g=n.reference.map(m=>{let p=e.findLastSpecializationByIdentifier(m);return p.name!==m.name?`"${p.name}" /*${m.name}*/`:`'${m.name}'`}).join(" | ");u.length===1&&u[0]==="Resource"&&g!=='"Resource"'?a=`Reference<"Resource" /* ${g} */ >`:a=`Reference<${g}>`;}else U(n.type)?a=F(n.type):He(n.type)?a=qt(n.type.name):a=n.type.name;this.lineSM(`${o}${n.required?"":"?"}: ${a}${n.array?"[]":""}`);}}),this.line();}generateAttachProfile(e){let t=F(e.base),r=F(e.identifier),i=Object.entries(e.fields||{}).filter(([n,o])=>o&&W(o)&&o.type!==void 0).map(([n])=>z(n));this.curlyBlock([`export const attach_${r}_to_${t} =`,`(resource: ${t}, profile: ${r}): ${t}`,"=>"],()=>{this.curlyBlock(["return"],()=>{this.line("...resource,"),this.curlyBlock(["meta:"],()=>{this.line(`profile: ['${e.identifier.url}']`);},[","]),i.forEach(n=>{this.line(`${n}: ${A("profile",n)},`);});});}),this.line();}generateExtractProfile(e,t){let r=F(t.base),i=F(t.identifier),n=Object.entries(t.fields||{}).filter(([c,l])=>W(l)&&l.type!==void 0).map(([c])=>c),o=e.findLastSpecialization(t);if(!_(o))throw new Error(`Specialization not found for ${t.identifier.url}`);let a={};this.curlyBlock([`export const extract_${i}_from_${r} =`,`(resource: ${r}): ${i}`,"=>"],()=>{n.forEach(c=>{let l=z(c),u=t.fields?.[c],g=o.fields?.[c];if(!W(u)||!W(g))return;u.required&&!g.required&&this.curlyBlock([`if (${A("resource",l)} === undefined)`],()=>this.lineSM(`throw new Error("'${l}' is required for ${t.identifier.url}")`));let m=u?.reference?.map(h=>h.name),p=g?.reference?.map(h=>h.name);if(m&&p&&m.length!==p.length){let h=`reference_is_valid_${l}`;this.curlyBlock(["const",h,"=","(ref?: Reference)","=>"],()=>{this.line("return !ref"),this.indentBlock(()=>{p.forEach(w=>{this.line(`|| ref.reference?.startsWith('${w}/')`);}),this.line(";");});});let S=u?.required?"":`!${A("resource",l)} || `;u.array?S+=`${A("resource",l)}.every( (ref) => ${h}(ref) )`:S+=`!${h}(${A("resource",l)})`,this.curlyBlock(["if (",S,")"],()=>{this.lineSM(`throw new Error("'${c}' has different references in profile and specialization")`);}),this.line(),a[c]=true;}}),this.curlyBlock(["return"],()=>{this.line(`__profileUrl: '${t.identifier.url}',`),n.forEach(c=>{let l=z(c);a[c]?this.line(`${l}:`,`${A("resource",l)} as ${i}['${l}'],`):this.line(`${l}:`,`${A("resource",l)},`);});});});}generateResourceModule(e,t){this.cat(`${Mr(t.identifier)}`,()=>{if(this.generateDisclaimer(),["complex-type","resource","logical"].includes(t.identifier.kind))this.generateDependenciesImports(t),this.generateComplexTypeReexports(t),this.generateNestedTypes(e,t),this.comment("CanonicalURL:",t.identifier.url),this.generateType(e,t);else if(ce(t)){let r=e.flatProfile(t);this.generateDependenciesImports(r),this.comment("CanonicalURL:",t.identifier.url),this.generateProfileType(e,r),this.generateAttachProfile(r),this.generateExtractProfile(e,r);}else throw new Error(`Profile generation not implemented for kind: ${t.identifier.kind}`)});}generate(e){let t=[...e.collectComplexTypes(),...e.collectResources(),...e.collectProfiles().filter(i=>e.isWithMetaField(i))],r=Dt(t);this.cd("/",()=>{for(let[i,n]of Object.entries(r)){let o=Nr(i);this.cd(o,()=>{for(let a of n)this.generateResourceModule(e,a);this.generateFhirPackageIndexFile(n);});}});}};var Br=s=>{let e=()=>s.writtenFiles().map(t=>({path:I.normalize(I.join(s.opts.outputDir,t)),filename:t.replace(/^.*[\\/]/,""),content:"",exports:[],size:0,timestamp:new Date}));return {generate:async t=>{let r=Bt(t);return s.generate(r),e()},setOutputDir:t=>s.opts.outputDir=t,build:async t=>e()}},Lr=s=>s.replace(/[^a-zA-Z0-9]/g,""),te=class s{schemas=[];options;generators=new Map;cache;pendingOperations=[];typeSchemaGenerator;logger;packages=[];progressCallback;typeSchemaConfig;constructor(e={}){this.options={outputDir:e.outputDir||"./generated",verbose:e.verbose??false,overwrite:e.overwrite??true,cache:e.cache??true,cleanOutput:e.cleanOutput??true,typeSchemaConfig:e.typeSchemaConfig,manager:e.manager||null,throwException:e.throwException||false,typeSchemaOutputDir:e.typeSchemaOutputDir},this.typeSchemaConfig=e.typeSchemaConfig,this.logger=e.logger||R({verbose:this.options.verbose,prefix:"API"}),this.options.cache&&(this.cache=new M(this.typeSchemaConfig));}fromPackage(e,t){return this.packages.push(ht({name:e,version:t||"latest"})),this}fromFiles(...e){this.logger.debug(`Loading from ${e.length} TypeSchema files`);let t=this.loadFromFiles(e);return this.pendingOperations.push(t),this}fromSchemas(e){return this.logger.debug(`Adding ${e.length} TypeSchemas to generation`),this.schemas=[...this.schemas,...e],this}typescript(e={}){let t=`${this.options.outputDir}/types`,r=new ee({outputDir:t,moduleFormat:e.moduleFormat||"esm",generateIndex:e.generateIndex??true,includeDocuments:e.includeDocuments??true,namingConvention:e.namingConvention||"PascalCase",includeExtensions:e.includeExtensions??false,includeProfiles:e.includeProfiles??false,generateValueSets:e.generateValueSets??false,includeValueSetHelpers:e.includeValueSetHelpers??false,valueSetStrengths:e.valueSetStrengths??["required"],logger:this.logger.child("TS"),valueSetMode:e.valueSetMode??"required-only",valueSetDirectory:e.valueSetDirectory??"valuesets",verbose:this.options.verbose,validate:true,overwrite:this.options.overwrite});return this.generators.set("typescript",r),this.logger.debug(`Configured TypeScript generator (${e.moduleFormat||"esm"})`),this}typescript2(e){let t={outputDir:I.join(this.options.outputDir,"/types"),tabSize:4,withDebugComment:false,commentLinePrefix:"//"},r={logger:this.logger,...t,...e},i=Br(new Pe(r));return this.generators.set("typescript2",i),this.logger.debug(`Configured TypeScript2 generator (${JSON.stringify(r,void 0,2)})`),this}onProgress(e){return this.progressCallback=e,this}outputTo(e){this.logger.debug(`Setting output directory: ${e}`),this.options.outputDir=e;for(let t of this.generators.values())t.setOutputDir&&t.setOutputDir(e);return this}verbose(e=true){return this.options.verbose=e,this.logger?.configure({verbose:e}),this}throwException(e=true){return this.options.throwException=e,this}cleanOutput(e=true){return this.options.cleanOutput=e,this}writeTypeSchemas(e){return this.options.typeSchemaOutputDir=e,this}static async isIdenticalTo(e,t){if(!await $.exists(e))return false;let r=await $.readFile(e),i=JSON.parse(r.toString()),n=JSON.parse(t);return be(i,n)}async writeTypeSchemasToSeparateFiles(e,t){this.options.cleanOutput&&E.rmSync(t,{recursive:true,force:true}),await $.mkdir(t,{recursive:true});let r={};this.logger.info(`Writing TypeSchema files to ${t}...`);for(let i of e){let n=Mt(i.identifier.package.replaceAll("/","-")),o=Lr(i.identifier.name.toString()),a=JSON.stringify(i,null,2),c=I.join(t,n,o),l;r[c]!==void 0?(r[c]++,l=`${c}-${r[c]}.typeschema.json`):(r[c]=0,l=`${c}.typeschema.json`),!await s.isIdenticalTo(l,a)&&(await $.mkdir(I.dirname(l),{recursive:true}),await $.writeFile(l,a));}}async writeTypeSchemasToSingleFile(e,t){this.options.cleanOutput&&E.existsSync(t)&&E.rmSync(t),await $.mkdir(I.dirname(t),{recursive:true}),this.logger.info(`Writing TypeSchemas to one file ${t}...`);for(let r of e){let i=JSON.stringify(r,null,2);await $.appendFile(t,i+`
43
- `);}}async tryWriteTypeSchema(e){if(this.options.typeSchemaOutputDir)try{this.logger.info("Starting writing TypeSchema files."),I.extname(this.options.typeSchemaOutputDir)===".ndjson"?await this.writeTypeSchemasToSingleFile(e,this.options.typeSchemaOutputDir):await this.writeTypeSchemasToSeparateFiles(e,this.options.typeSchemaOutputDir),this.logger.info("Finished writing TypeSchema files.");}catch(t){if(this.options.throwException)throw t;this.logger.error("Failed to write TypeSchema output",t instanceof Error?t:new Error(String(t)));}}async generate(){let e=performance.now(),t={success:false,outputDir:this.options.outputDir,filesGenerated:[],errors:[],warnings:[],duration:0};if(this.logger.debug(`Starting generation with ${this.generators.size} generators`),this.options.cleanOutput){this.logger.info(`Cleaning output directory: ${this.options.outputDir}`);try{E.rmSync(this.options.outputDir,{recursive:!0,force:!0}),E.mkdirSync(this.options.outputDir,{recursive:!0});}catch(r){this.logger.warn(`Error cleaning output directory: ${r instanceof Error?r.message:String(r)}`);}}try{this.logger.info("Initialize Canonical Manager");let r=CanonicalManager({packages:this.packages,workingDir:"tmp/fhir"});await r.init();let i=await K(r,{logger:this.logger}),n=await Pt(i,this.logger);await this.tryWriteTypeSchema(n),this.logger.debug(`Executing ${this.generators.size} generators`),await this.executeGenerators(t,n),this.logger.info("Generation completed successfully"),t.success=t.errors.length===0,this.logger.debug(`Generation completed: ${t.filesGenerated.length} files`);}catch(r){this.logger.error("Code generation failed",r instanceof Error?r:new Error(String(r))),t.errors.push(r instanceof Error?r.message:String(r));}return {...t,success:t.errors.length===0,duration:performance.now()-e}}async build(){let e={};for(let[t,r]of this.generators.entries())r.build&&(e[t]=await r.build(this.schemas));return e}reset(){return this.schemas=[],this.generators.clear(),this.progressCallback=void 0,this}getSchemas(){return [...this.schemas]}getGenerators(){return Array.from(this.generators.keys())}async loadFromFiles(e){this.typeSchemaGenerator||(this.typeSchemaGenerator=new O({verbose:this.options.verbose,logger:this.logger.child("Schema"),treeshake:this.typeSchemaConfig?.treeshake},this.typeSchemaConfig));let r=await new H({format:"auto"}).parseFromFiles(e);this.schemas=[...this.schemas,...r],this.cache&&this.cache.setMany(r);}async executeGenerators(e,t){for(let[r,i]of this.generators.entries()){this.logger.info(`Generating ${r}...`);try{let n=await i.generate(t);e.filesGenerated.push(...n.map(o=>o.path||o.filename)),this.logger.info(`Generating ${r} finished successfully`);}catch(n){if(e.errors.push(`${r} generator failed: ${n instanceof Error?n.message:String(n)}`),this.options.throwException)throw n}}}};var at={outputDir:"./generated",verbose:false,overwrite:true,validate:true,cache:true,cleanOutput:true,typescript:{moduleFormat:"esm",generateIndex:true,includeDocuments:false,namingConvention:"PascalCase",strictMode:true,includeProfiles:true,includeExtensions:false,includeCodeSystems:false,includeOperations:false,generateValueSets:false,valueSetDirectory:"valuesets",valueSetMode:"required-only",valueSetStrengths:["required"],includeValueSetHelpers:false,fhirVersion:"R4",resourceTypes:[],maxDepth:10,profileOptions:{generateKind:"interface",includeConstraints:true,includeDocumentation:true,strictMode:false,subfolder:"profiles"},generateBuilders:false,builderOptions:{includeValidation:true,includeFactoryMethods:true,includeInterfaces:true,generateNestedBuilders:true,includeHelperMethods:true,supportPartialBuild:true,includeJSDoc:true,generateFactories:true,includeTypeGuards:true,handleChoiceTypes:true,generateArrayHelpers:true},validatorOptions:{includeCardinality:true,includeTypes:true,includeConstraints:true,includeInvariants:false,validateRequired:true,allowAdditional:false,strictValidation:false,collectMetrics:false,generateAssertions:true,generatePartialValidators:true,optimizePerformance:true,includeJSDoc:true,generateCompositeValidators:true},guardOptions:{includeRuntimeValidation:true,includeErrorMessages:true,treeShakeable:true,targetTSVersion:"5.0",strictGuards:false,includeNullChecks:true,verbose:false}},typeSchema:{enablePersistence:true,cacheDir:".typeschema-cache",maxAge:1440*60*1e3,validateCached:true,forceRegenerate:false,shareCache:true,cacheKeyPrefix:"",treeshake:[],singleFile:false,profiles:{autoDetect:true}},packages:[],files:[],$schema:""},Ne=["atomic-codegen.config.ts","atomic-codegen.config","atomic-codegen.config.json",".atomic-codegenrc","atomic-codegen.json",".atomic-codegen.json","codegen.config.json","codegen.json"],ct=class{validate(e){let t={valid:true,errors:[],warnings:[]};if(!e||typeof e!="object")return t.valid=false,t.errors.push({path:"root",message:"Configuration must be an object",value:e}),t;let r=e;r.outputDir!==void 0&&typeof r.outputDir!="string"&&t.errors.push({path:"outputDir",message:"outputDir must be a string",value:r.outputDir});let i=["verbose","overwrite","validate","cache"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.errors.push({path:n,message:`${n} must be a boolean`,value:r[n]});if(r.typescript!==void 0){let n=this.validateTypeScriptConfig(r.typescript);t.errors.push(...n);}if(r.typeSchema!==void 0){let n=this.validateTypeSchemaConfig(r.typeSchema);t.errors.push(...n);}return r.packages!==void 0&&(Array.isArray(r.packages)?r.packages.forEach((n,o)=>{typeof n!="string"&&t.errors.push({path:`packages[${o}]`,message:"package name must be a string",value:n});}):t.errors.push({path:"packages",message:"packages must be an array",value:r.packages})),r.files!==void 0&&(Array.isArray(r.files)?r.files.forEach((n,o)=>{typeof n!="string"&&t.errors.push({path:`files[${o}]`,message:"file path must be a string",value:n});}):t.errors.push({path:"files",message:"files must be an array",value:r.files})),t.valid=t.errors.length===0,t.valid&&(t.config=r),t}validateTypeScriptConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript",message:"typescript config must be an object",value:e}),t;let r=e;r.moduleFormat!==void 0&&(["esm","cjs"].includes(r.moduleFormat)||t.push({path:"typescript.moduleFormat",message:'moduleFormat must be "esm" or "cjs"',value:r.moduleFormat})),r.namingConvention!==void 0&&(["PascalCase","camelCase"].includes(r.namingConvention)||t.push({path:"typescript.namingConvention",message:'namingConvention must be "PascalCase" or "camelCase"',value:r.namingConvention}));let i=["generateIndex","includeDocuments","strictMode","includeProfiles","includeExtensions","includeCodeSystems","includeOperations","generateValueSets","includeValueSetHelpers"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.${n}`,message:`${n} must be a boolean`,value:r[n]});if(r.validatorOptions!==void 0){let n=this.validateValidatorOptions(r.validatorOptions);t.push(...n);}if(r.guardOptions!==void 0){let n=this.validateGuardOptions(r.guardOptions);t.push(...n);}if(r.profileOptions!==void 0){let n=this.validateProfileOptions(r.profileOptions);t.push(...n);}return t}validateValidatorOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.validatorOptions",message:"validatorOptions must be an object",value:e}),t;let r=e,i=["includeCardinality","includeTypes","includeConstraints","includeInvariants","validateRequired","allowAdditional","strictValidation","collectMetrics","generateAssertions","generatePartialValidators","optimizePerformance","includeJSDoc","generateCompositeValidators"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.validatorOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateGuardOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.guardOptions",message:"guardOptions must be an object",value:e}),t;let r=e;r.targetTSVersion!==void 0&&(["3.8","4.0","4.5","5.0"].includes(r.targetTSVersion)||t.push({path:"typescript.guardOptions.targetTSVersion",message:'targetTSVersion must be one of: "3.8", "4.0", "4.5", "5.0"',value:r.targetTSVersion}));let i=["includeRuntimeValidation","includeErrorMessages","treeShakeable","strictGuards","includeNullChecks","verbose"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.guardOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateProfileOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.profileOptions",message:"profileOptions must be an object",value:e}),t;let r=e;r.generateKind!==void 0&&(["interface","type","both"].includes(r.generateKind)||t.push({path:"typescript.profileOptions.generateKind",message:'generateKind must be "interface", "type", or "both"',value:r.generateKind})),r.subfolder!==void 0&&typeof r.subfolder!="string"&&t.push({path:"typescript.profileOptions.subfolder",message:"subfolder must be a string",value:r.subfolder});let i=["includeConstraints","includeDocumentation","strictMode"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.profileOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateTypeSchemaConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typeSchema",message:"typeSchema config must be an object",value:e}),t;let r=e,i=["enablePersistence","validateCached","forceRegenerate","shareCache"];for(let o of i)r[o]!==void 0&&typeof r[o]!="boolean"&&t.push({path:`typeSchema.${o}`,message:`${o} must be a boolean`,value:r[o]});let n=["cacheDir","cacheKeyPrefix"];for(let o of n)r[o]!==void 0&&typeof r[o]!="string"&&t.push({path:`typeSchema.${o}`,message:`${o} must be a string`,value:r[o]});if(r.maxAge!==void 0&&(typeof r.maxAge!="number"||r.maxAge<=0)&&t.push({path:"typeSchema.maxAge",message:"maxAge must be a positive number",value:r.maxAge}),r.profiles!==void 0)if(typeof r.profiles!="object"||r.profiles===null)t.push({path:"typeSchema.profiles",message:"profiles must be an object",value:r.profiles});else {let o=r.profiles;o.autoDetect!==void 0&&typeof o.autoDetect!="boolean"&&t.push({path:"typeSchema.profiles.autoDetect",message:"autoDetect must be a boolean",value:o.autoDetect});}return t}},lt=class{validator=new ct;async autoload(e=process.cwd()){let t=await this.findConfigFile(e);return t?this.loadFromFile(t):{...at}}async loadFromFile(e){try{let t;if(e.endsWith(".ts")||e.endsWith("")){let n=await import(resolve(e));t=n.default||n;}else {let i=await readFile(e,"utf-8");t=JSON.parse(i);}let r=this.validator.validate(t);if(!r.valid){let i=r.errors.map(n=>`${n.path}: ${n.message}`).join(`
41
+ `);await this.fileManager.writeFile("index.ts",t),this.logger.info(`Generated index.ts with type exports${this.tsOptions.generateValueSets&&this.collectedValueSets.size>0?" and value sets":""}`);}};var ii={boolean:"boolean",instant:"string",time:"string",date:"string",dateTime:"string",decimal:"number",integer:"number",unsignedInt:"number",positiveInt:"number",integer64:"number",base64Binary:"string",uri:"string",url:"string",canonical:"string",oid:"string",uuid:"string",string:"string",code:"string",markdown:"string",id:"string",xhtml:"string"},sr=s=>{let e=ii[s];if(e===void 0)throw new Error(`Unknown primitive type ${s}`);return e},ni=s=>X(s),or=s=>s.kind==="profile"?`${T(s)}_profile`:V(s.name),si=s=>`${or(s)}.ts`,ct=(s,e=true)=>{if(!s)return;let t=s.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),lt(t)},T=s=>{if(s.kind==="nested"){let e=s.url,t=ct(e,false);if(!t)return "";let[r,i]=t.split("#"),n=xe((i??"").split(".")).join("");return lt([r,n].join(""))}return lt(s.name)},ar=new Set(["class","function","return","if","for","while","const","let","var","import","export","interface"]),W=s=>ar.has(s)?`"${s}"`:s.includes(" ")||s.includes("-")?`"${s}"`:s,lt=s=>(ar.has(s)&&(s=`${s}_`),s.replace(/[- ]/g,"_")),G=(s,e)=>e.startsWith('"')?`${s}[${e}]`:`${s}.${e}`,Me=class extends q{tsImportType(e,...t){this.lineSM(`import type { ${t.join(", ")} } from "${e}"`);}generateFhirPackageIndexFile(e){this.cat("index.ts",()=>{let t=e.map(r=>({identifier:r.identifier,tsPackageName:or(r.identifier),resourceName:T(r.identifier)})).sort((r,i)=>r.resourceName.localeCompare(i.resourceName));t=Array.from(new Map(t.map(r=>[r.resourceName.toLowerCase(),r])).values()).sort((r,i)=>r.resourceName.localeCompare(i.resourceName));for(let r of t)this.debugComment(r.identifier),this.lineSM(`export type { ${r.resourceName} } from "./${r.tsPackageName}"`);});}generateDependenciesImports(e){if(e.dependencies){let t=[],r=[];for(let i of e.dependencies)["complex-type","resource","logical"].includes(i.kind)?t.push({tsPackage:`../${X(i.package)}/${V(i.name)}`,name:$(i.name)}):U(i)?t.push({tsPackage:`../${X(i.package)}/${V(ct(i.url)??"")}`,name:T(i)}):r.push(i);t.sort((i,n)=>i.name.localeCompare(n.name));for(let i of t)this.tsImportType(i.tsPackage,i.name);for(let i of r)this.debugComment("skip:",i);this.line();}}generateComplexTypeReexports(e){let t=e.dependencies?.filter(r=>["complex-type"].includes(r.kind)).map(r=>({tsPackage:`../${X(r.package)}/${V(r.name)}`,name:$(r.name)}));if(t&&t.length>0){for(let r of t)this.lineSM(`export type { ${r.name} } from "${r.tsPackage}"`);this.line();}}addFieldExtension(e,t){if(t.type.kind==="primitive-type"){let r=W(`_${e}`);this.lineSM(`${r}?: Element`);}}generateType(e,t){let r;t.identifier.name==="Reference"?r="Reference<T extends string = string>":(t.identifier.kind,r=T(t.identifier));let i;t.base&&(i=`extends ${ct(t.base.url)}`),this.debugComment(t.identifier),this.curlyBlock(["export","interface",r,i],()=>{if(K(t)){let o=[t.identifier];o.push(...e.resourceChildren(t.identifier)),this.lineSM(`resourceType: ${o.map(a=>`"${a.name}"`).join(" | ")}`),this.line();}if(!t.fields)return;let n=Object.entries(t.fields).sort((o,a)=>o[0].localeCompare(a[0]));for(let[o,a]of n){if(_(a))continue;this.debugComment(o,":",a);let c=W(o),l;a.enum?l=a.enum.map(g=>`"${g}"`).join(" | "):t.identifier.name==="Reference"&&c==="reference"?l="`${T}/${string}`":a.reference&&a.reference.length>0?l=`Reference<${a.reference.map(p=>`"${p.name}"`).join(" | ")}>`:ze(a.type)?l=sr(a.type.name):U(a.type)?l=T(a.type):l=a.type.name;let d=a.required?"":"?",f=a.array?"[]":"";this.lineSM(`${c}${d}: ${l}${f}`),["resource","complex-type"].includes(t.identifier.kind)&&this.addFieldExtension(o,a);}});}generateNestedTypes(e,t){if(t.nested)for(let r of t.nested)this.generateType(e,r),this.line();}generateProfileType(e,t){let r=T(t.identifier);this.debugComment("identifier",t.identifier),this.debugComment("base",t.base),this.curlyBlock(["export","interface",r],()=>{this.lineSM(`__profileUrl: "${t.identifier.url}"`),this.line();for(let[i,n]of Object.entries(t.fields??{})){if(_(n))continue;this.debugComment(i,n);let o=W(i),a;if(n.enum)a=n.enum.map(c=>`'${c}'`).join(" | ");else if(n.reference&&n.reference.length>0){let c=e.findLastSpecialization(t);if(!J(c))throw new Error(`Invalid specialization for ${t.identifier}`);let l=c.fields?.[i];if(l===void 0||_(l)||l.reference===void 0)throw new Error(`Invalid field declaration for ${i}`);let d=l.reference.map(g=>g.name),f=n.reference.map(g=>{let p=e.findLastSpecializationByIdentifier(g);return p.name!==g.name?`"${p.name}" /*${g.name}*/`:`'${g.name}'`}).join(" | ");d.length===1&&d[0]==="Resource"&&f!=='"Resource"'?a=`Reference<"Resource" /* ${f} */ >`:a=`Reference<${f}>`;}else U(n.type)?a=T(n.type):ze(n.type)?a=sr(n.type.name):a=n.type.name;this.lineSM(`${o}${n.required?"":"?"}: ${a}${n.array?"[]":""}`);}}),this.line();}generateAttachProfile(e){let t=T(e.base),r=T(e.identifier),i=Object.entries(e.fields||{}).filter(([n,o])=>o&&Z(o)&&o.type!==void 0).map(([n])=>W(n));this.curlyBlock([`export const attach_${r}_to_${t} =`,`(resource: ${t}, profile: ${r}): ${t}`,"=>"],()=>{this.curlyBlock(["return"],()=>{this.line("...resource,"),this.curlyBlock(["meta:"],()=>{this.line(`profile: ['${e.identifier.url}']`);},[","]),i.forEach(n=>{this.line(`${n}: ${G("profile",n)},`);});});}),this.line();}generateExtractProfile(e,t){let r=T(t.base),i=T(t.identifier),n=Object.entries(t.fields||{}).filter(([c,l])=>Z(l)&&l.type!==void 0).map(([c])=>c),o=e.findLastSpecialization(t);if(!J(o))throw new Error(`Specialization not found for ${t.identifier.url}`);let a={};this.curlyBlock([`export const extract_${i}_from_${r} =`,`(resource: ${r}): ${i}`,"=>"],()=>{n.forEach(c=>{let l=W(c),d=t.fields?.[c],f=o.fields?.[c];if(!Z(d)||!Z(f))return;d.required&&!f.required&&this.curlyBlock([`if (${G("resource",l)} === undefined)`],()=>this.lineSM(`throw new Error("'${l}' is required for ${t.identifier.url}")`));let g=d?.reference?.map(u=>u.name),p=f?.reference?.map(u=>u.name);if(g&&p&&g.length!==p.length){let u=`reference_is_valid_${l}`;this.curlyBlock(["const",u,"=","(ref?: Reference)","=>"],()=>{this.line("return !ref"),this.indentBlock(()=>{p.forEach(y=>{this.line(`|| ref.reference?.startsWith('${y}/')`);}),this.line(";");});});let m=d?.required?"":`!${G("resource",l)} || `;d.array?m+=`${G("resource",l)}.every( (ref) => ${u}(ref) )`:m+=`!${u}(${G("resource",l)})`,this.curlyBlock(["if (",m,")"],()=>{this.lineSM(`throw new Error("'${c}' has different references in profile and specialization")`);}),this.line(),a[c]=true;}}),this.curlyBlock(["return"],()=>{this.line(`__profileUrl: '${t.identifier.url}',`),n.forEach(c=>{let l=W(c);a[c]?this.line(`${l}:`,`${G("resource",l)} as ${i}['${l}'],`):this.line(`${l}:`,`${G("resource",l)},`);});});});}generateResourceModule(e,t){this.cat(`${si(t.identifier)}`,()=>{if(this.generateDisclaimer(),["complex-type","resource","logical"].includes(t.identifier.kind))this.generateDependenciesImports(t),this.generateComplexTypeReexports(t),this.generateNestedTypes(e,t),this.comment("CanonicalURL:",t.identifier.url),this.generateType(e,t);else if(le(t)){let r=e.flatProfile(t);this.generateDependenciesImports(r),this.comment("CanonicalURL:",t.identifier.url),this.generateProfileType(e,r),this.generateAttachProfile(r),this.generateExtractProfile(e,r);}else throw new Error(`Profile generation not implemented for kind: ${t.identifier.kind}`)});}generate(e){let t=[...e.collectComplexTypes(),...e.collectResources(),...e.collectProfiles().filter(i=>e.isWithMetaField(i))],r=Jt(t);this.cd("/",()=>{for(let[i,n]of Object.entries(r)){let o=ni(i);this.cd(o,()=>{for(let a of n)this.generateResourceModule(e,a);this.generateFhirPackageIndexFile(n);});}});}};var cr=s=>{let e=()=>s.writtenFiles().map(t=>({path:w.normalize(w.join(s.opts.outputDir,t)),filename:t.replace(/^.*[\\/]/,""),content:"",exports:[],size:0,timestamp:new Date}));return {generate:async t=>{let r=Kt(t);return s.generate(r),e()},setOutputDir:t=>s.opts.outputDir=t,build:async t=>e()}},ci=s=>s.replace(/[^a-zA-Z0-9]/g,""),ie=class s{schemas=[];options;generators=new Map;cache;pendingOperations=[];typeSchemaGenerator;logger;packages=[];progressCallback;typeSchemaConfig;constructor(e={}){this.options={outputDir:e.outputDir||"./generated",verbose:e.verbose??false,overwrite:e.overwrite??true,cache:e.cache??true,cleanOutput:e.cleanOutput??true,typeSchemaConfig:e.typeSchemaConfig,manager:e.manager||null,throwException:e.throwException||false,typeSchemaOutputDir:e.typeSchemaOutputDir},this.typeSchemaConfig=e.typeSchemaConfig,this.logger=e.logger||C({verbose:this.options.verbose,prefix:"API"}),this.options.cache&&(this.cache=new N(this.typeSchemaConfig));}fromPackage(e,t){return this.packages.push(ht({name:e,version:t||"latest"})),this}fromFiles(...e){this.logger.debug(`Loading from ${e.length} TypeSchema files`);let t=this.loadFromFiles(e);return this.pendingOperations.push(t),this}fromSchemas(e){return this.logger.debug(`Adding ${e.length} TypeSchemas to generation`),this.schemas=[...this.schemas,...e],this}typescript(e={}){let t=`${this.options.outputDir}/types`,r=new re({outputDir:t,moduleFormat:e.moduleFormat||"esm",generateIndex:e.generateIndex??true,includeDocuments:e.includeDocuments??true,namingConvention:e.namingConvention||"PascalCase",includeExtensions:e.includeExtensions??false,includeProfiles:e.includeProfiles??false,generateValueSets:e.generateValueSets??false,includeValueSetHelpers:e.includeValueSetHelpers??false,valueSetStrengths:e.valueSetStrengths??["required"],logger:this.logger.child("TS"),valueSetMode:e.valueSetMode??"required-only",valueSetDirectory:e.valueSetDirectory??"valuesets",verbose:this.options.verbose,validate:true,overwrite:this.options.overwrite});return this.generators.set("typescript",r),this.logger.debug(`Configured TypeScript generator (${e.moduleFormat||"esm"})`),this}typescript2(e){let t={outputDir:w.join(this.options.outputDir,"/types"),tabSize:4,withDebugComment:false,commentLinePrefix:"//"},r={logger:this.logger,...t,...e},i=cr(new Me(r));return this.generators.set("typescript2",i),this.logger.debug(`Configured TypeScript2 generator (${JSON.stringify(r,void 0,2)})`),this}csharp(e,t){let r=cr(new we({outputDir:w.join(this.options.outputDir,"/types"),staticSourceDir:t??void 0,targetNamespace:e,logger:new H({prefix:"C#",timestamp:true,verbose:true,suppressLoggingLevel:[]})}));return this.generators.set("C#",r),this.logger.debug("Configured C# generator"),this}onProgress(e){return this.progressCallback=e,this}outputTo(e){this.logger.debug(`Setting output directory: ${e}`),this.options.outputDir=e;for(let t of this.generators.values())t.setOutputDir&&t.setOutputDir(e);return this}verbose(e=true){return this.options.verbose=e,this.logger?.configure({verbose:e}),this}throwException(e=true){return this.options.throwException=e,this}cleanOutput(e=true){return this.options.cleanOutput=e,this}writeTypeSchemas(e){return this.options.typeSchemaOutputDir=e,this}static async isIdenticalTo(e,t){if(!await x.exists(e))return false;let r=await x.readFile(e),i=JSON.parse(r.toString()),n=JSON.parse(t);return ve(i,n)}async writeTypeSchemasToSeparateFiles(e,t){this.options.cleanOutput&&R.rmSync(t,{recursive:true,force:true}),await x.mkdir(t,{recursive:true});let r={};this.logger.info(`Writing TypeSchema files to ${t}...`);for(let i of e){let n=Te(i.identifier.package.replaceAll("/","-")),o=ci(i.identifier.name.toString()),a=JSON.stringify(i,null,2),c=w.join(t,n,o),l;r[c]!==void 0?(r[c]++,l=`${c}-${r[c]}.typeschema.json`):(r[c]=0,l=`${c}.typeschema.json`),!await s.isIdenticalTo(l,a)&&(await x.mkdir(w.dirname(l),{recursive:true}),await x.writeFile(l,a));}}async writeTypeSchemasToSingleFile(e,t){this.options.cleanOutput&&R.existsSync(t)&&R.rmSync(t),await x.mkdir(w.dirname(t),{recursive:true}),this.logger.info(`Writing TypeSchemas to one file ${t}...`);for(let r of e){let i=JSON.stringify(r,null,2);await x.appendFile(t,i+`
42
+ `);}}async tryWriteTypeSchema(e){if(this.options.typeSchemaOutputDir)try{this.logger.info("Starting writing TypeSchema files."),w.extname(this.options.typeSchemaOutputDir)===".ndjson"?await this.writeTypeSchemasToSingleFile(e,this.options.typeSchemaOutputDir):await this.writeTypeSchemasToSeparateFiles(e,this.options.typeSchemaOutputDir),this.logger.info("Finished writing TypeSchema files.");}catch(t){if(this.options.throwException)throw t;this.logger.error("Failed to write TypeSchema output",t instanceof Error?t:new Error(String(t)));}}async generate(){let e=performance.now(),t={success:false,outputDir:this.options.outputDir,filesGenerated:[],errors:[],warnings:[],duration:0};if(this.logger.debug(`Starting generation with ${this.generators.size} generators`),this.options.cleanOutput){this.logger.info(`Cleaning output directory: ${this.options.outputDir}`);try{R.rmSync(this.options.outputDir,{recursive:!0,force:!0}),R.mkdirSync(this.options.outputDir,{recursive:!0});}catch(r){this.logger.warn(`Error cleaning output directory: ${r instanceof Error?r.message:String(r)}`);}}try{this.logger.info("Initialize Canonical Manager");let r=CanonicalManager({packages:this.packages,workingDir:"tmp/fhir"});await r.init();let i=await Q(r,{logger:this.logger}),n=await jt(i,this.logger);await this.tryWriteTypeSchema(n),this.logger.debug(`Executing ${this.generators.size} generators`),await this.executeGenerators(t,n),this.logger.info("Generation completed successfully"),t.success=t.errors.length===0,this.logger.debug(`Generation completed: ${t.filesGenerated.length} files`);}catch(r){this.logger.error("Code generation failed",r instanceof Error?r:new Error(String(r))),t.errors.push(r instanceof Error?r.message:String(r));}return {...t,success:t.errors.length===0,duration:performance.now()-e}}async build(){let e={};for(let[t,r]of this.generators.entries())r.build&&(e[t]=await r.build(this.schemas));return e}reset(){return this.schemas=[],this.generators.clear(),this.progressCallback=void 0,this}getSchemas(){return [...this.schemas]}getGenerators(){return Array.from(this.generators.keys())}async loadFromFiles(e){this.typeSchemaGenerator||(this.typeSchemaGenerator=new M({verbose:this.options.verbose,logger:this.logger.child("Schema"),treeshake:this.typeSchemaConfig?.treeshake},this.typeSchemaConfig));let r=await new z({format:"auto"}).parseFromFiles(e);this.schemas=[...this.schemas,...r],this.cache&&this.cache.setMany(r);}async executeGenerators(e,t){for(let[r,i]of this.generators.entries()){this.logger.info(`Generating ${r}...`);try{let n=await i.generate(t);e.filesGenerated.push(...n.map(o=>o.path||o.filename)),this.logger.info(`Generating ${r} finished successfully`);}catch(n){if(e.errors.push(`${r} generator failed: ${n instanceof Error?n.message:String(n)}`),this.options.throwException)throw n}}}};var pt={outputDir:"./generated",verbose:false,overwrite:true,validate:true,cache:true,cleanOutput:true,typescript:{moduleFormat:"esm",generateIndex:true,includeDocuments:false,namingConvention:"PascalCase",strictMode:true,includeProfiles:true,includeExtensions:false,includeCodeSystems:false,includeOperations:false,generateValueSets:false,valueSetDirectory:"valuesets",valueSetMode:"required-only",valueSetStrengths:["required"],includeValueSetHelpers:false,fhirVersion:"R4",resourceTypes:[],maxDepth:10,profileOptions:{generateKind:"interface",includeConstraints:true,includeDocumentation:true,strictMode:false,subfolder:"profiles"},generateBuilders:false,builderOptions:{includeValidation:true,includeFactoryMethods:true,includeInterfaces:true,generateNestedBuilders:true,includeHelperMethods:true,supportPartialBuild:true,includeJSDoc:true,generateFactories:true,includeTypeGuards:true,handleChoiceTypes:true,generateArrayHelpers:true},validatorOptions:{includeCardinality:true,includeTypes:true,includeConstraints:true,includeInvariants:false,validateRequired:true,allowAdditional:false,strictValidation:false,collectMetrics:false,generateAssertions:true,generatePartialValidators:true,optimizePerformance:true,includeJSDoc:true,generateCompositeValidators:true},guardOptions:{includeRuntimeValidation:true,includeErrorMessages:true,treeShakeable:true,targetTSVersion:"5.0",strictGuards:false,includeNullChecks:true,verbose:false}},typeSchema:{enablePersistence:true,cacheDir:".typeschema-cache",maxAge:1440*60*1e3,validateCached:true,forceRegenerate:false,shareCache:true,cacheKeyPrefix:"",treeshake:[],singleFile:false,profiles:{autoDetect:true}},packages:[],files:[],$schema:""},Oe=["atomic-codegen.config.ts","atomic-codegen.config","atomic-codegen.config.json",".atomic-codegenrc","atomic-codegen.json",".atomic-codegen.json","codegen.config.json","codegen.json"],ut=class{validate(e){let t={valid:true,errors:[],warnings:[]};if(!e||typeof e!="object")return t.valid=false,t.errors.push({path:"root",message:"Configuration must be an object",value:e}),t;let r=e;r.outputDir!==void 0&&typeof r.outputDir!="string"&&t.errors.push({path:"outputDir",message:"outputDir must be a string",value:r.outputDir});let i=["verbose","overwrite","validate","cache"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.errors.push({path:n,message:`${n} must be a boolean`,value:r[n]});if(r.typescript!==void 0){let n=this.validateTypeScriptConfig(r.typescript);t.errors.push(...n);}if(r.typeSchema!==void 0){let n=this.validateTypeSchemaConfig(r.typeSchema);t.errors.push(...n);}return r.packages!==void 0&&(Array.isArray(r.packages)?r.packages.forEach((n,o)=>{typeof n!="string"&&t.errors.push({path:`packages[${o}]`,message:"package name must be a string",value:n});}):t.errors.push({path:"packages",message:"packages must be an array",value:r.packages})),r.files!==void 0&&(Array.isArray(r.files)?r.files.forEach((n,o)=>{typeof n!="string"&&t.errors.push({path:`files[${o}]`,message:"file path must be a string",value:n});}):t.errors.push({path:"files",message:"files must be an array",value:r.files})),t.valid=t.errors.length===0,t.valid&&(t.config=r),t}validateTypeScriptConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript",message:"typescript config must be an object",value:e}),t;let r=e;r.moduleFormat!==void 0&&(["esm","cjs"].includes(r.moduleFormat)||t.push({path:"typescript.moduleFormat",message:'moduleFormat must be "esm" or "cjs"',value:r.moduleFormat})),r.namingConvention!==void 0&&(["PascalCase","camelCase"].includes(r.namingConvention)||t.push({path:"typescript.namingConvention",message:'namingConvention must be "PascalCase" or "camelCase"',value:r.namingConvention}));let i=["generateIndex","includeDocuments","strictMode","includeProfiles","includeExtensions","includeCodeSystems","includeOperations","generateValueSets","includeValueSetHelpers"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.${n}`,message:`${n} must be a boolean`,value:r[n]});if(r.validatorOptions!==void 0){let n=this.validateValidatorOptions(r.validatorOptions);t.push(...n);}if(r.guardOptions!==void 0){let n=this.validateGuardOptions(r.guardOptions);t.push(...n);}if(r.profileOptions!==void 0){let n=this.validateProfileOptions(r.profileOptions);t.push(...n);}return t}validateValidatorOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.validatorOptions",message:"validatorOptions must be an object",value:e}),t;let r=e,i=["includeCardinality","includeTypes","includeConstraints","includeInvariants","validateRequired","allowAdditional","strictValidation","collectMetrics","generateAssertions","generatePartialValidators","optimizePerformance","includeJSDoc","generateCompositeValidators"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.validatorOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateGuardOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.guardOptions",message:"guardOptions must be an object",value:e}),t;let r=e;r.targetTSVersion!==void 0&&(["3.8","4.0","4.5","5.0"].includes(r.targetTSVersion)||t.push({path:"typescript.guardOptions.targetTSVersion",message:'targetTSVersion must be one of: "3.8", "4.0", "4.5", "5.0"',value:r.targetTSVersion}));let i=["includeRuntimeValidation","includeErrorMessages","treeShakeable","strictGuards","includeNullChecks","verbose"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.guardOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateProfileOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.profileOptions",message:"profileOptions must be an object",value:e}),t;let r=e;r.generateKind!==void 0&&(["interface","type","both"].includes(r.generateKind)||t.push({path:"typescript.profileOptions.generateKind",message:'generateKind must be "interface", "type", or "both"',value:r.generateKind})),r.subfolder!==void 0&&typeof r.subfolder!="string"&&t.push({path:"typescript.profileOptions.subfolder",message:"subfolder must be a string",value:r.subfolder});let i=["includeConstraints","includeDocumentation","strictMode"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.profileOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateTypeSchemaConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typeSchema",message:"typeSchema config must be an object",value:e}),t;let r=e,i=["enablePersistence","validateCached","forceRegenerate","shareCache"];for(let o of i)r[o]!==void 0&&typeof r[o]!="boolean"&&t.push({path:`typeSchema.${o}`,message:`${o} must be a boolean`,value:r[o]});let n=["cacheDir","cacheKeyPrefix"];for(let o of n)r[o]!==void 0&&typeof r[o]!="string"&&t.push({path:`typeSchema.${o}`,message:`${o} must be a string`,value:r[o]});if(r.maxAge!==void 0&&(typeof r.maxAge!="number"||r.maxAge<=0)&&t.push({path:"typeSchema.maxAge",message:"maxAge must be a positive number",value:r.maxAge}),r.profiles!==void 0)if(typeof r.profiles!="object"||r.profiles===null)t.push({path:"typeSchema.profiles",message:"profiles must be an object",value:r.profiles});else {let o=r.profiles;o.autoDetect!==void 0&&typeof o.autoDetect!="boolean"&&t.push({path:"typeSchema.profiles.autoDetect",message:"autoDetect must be a boolean",value:o.autoDetect});}return t}},gt=class{validator=new ut;async autoload(e=process.cwd()){let t=await this.findConfigFile(e);return t?this.loadFromFile(t):{...pt}}async loadFromFile(e){try{let t;if(e.endsWith(".ts")||e.endsWith("")){let n=await import(resolve(e));t=n.default||n;}else {let i=await readFile(e,"utf-8");t=JSON.parse(i);}let r=this.validator.validate(t);if(!r.valid){let i=r.errors.map(n=>`${n.path}: ${n.message}`).join(`
44
43
  `);throw new Error(`Configuration validation failed:
45
- ${i}`)}return this.mergeWithDefaults(r.config)}catch(t){throw t instanceof Error?new Error(`Failed to load config from ${e}: ${t.message}`):t}}async findConfigFile(e){for(let t of Ne){let r=resolve(e,t);if(existsSync(r))return r}return null}mergeWithDefaults(e){return {...at,...e,typescript:{...at.typescript,...e.typescript}}}},Ar=new lt;async function Me(s){return Ar.autoload(s)}var Zt={command:"generate",describe:"Generate code based on configuration file settings",builder:s=>s.option("verbose",{alias:"v",type:"boolean",default:false,description:"Enable verbose output"}).example("$0 generate","Generate code using settings from config file").example("$0 generate --verbose","Generate with verbose output"),handler:async s=>{if(s._.length>1){let o=s._.slice(1).join(" ");C(`Invalid syntax: 'atomic-codegen generate ${o}'
44
+ ${i}`)}return this.mergeWithDefaults(r.config)}catch(t){throw t instanceof Error?new Error(`Failed to load config from ${e}: ${t.message}`):t}}async findConfigFile(e){for(let t of Oe){let r=resolve(e,t);if(existsSync(r))return r}return null}mergeWithDefaults(e){return {...pt,...e,typescript:{...pt.typescript,...e.typescript}}}},ui=new gt;async function De(s){return ui.autoload(s)}var pr={command:"generate",describe:"Generate code based on configuration file settings",builder:s=>s.option("verbose",{alias:"v",type:"boolean",default:false,description:"Enable verbose output"}).example("$0 generate","Generate code using settings from config file").example("$0 generate --verbose","Generate with verbose output"),handler:async s=>{if(s._.length>1){let o=s._.slice(1).join(" ");b(`Invalid syntax: 'atomic-codegen generate ${o}'
46
45
 
47
46
  The CLI has been simplified and no longer uses subcommands.
48
47
 
@@ -50,8 +49,8 @@ The CLI has been simplified and no longer uses subcommands.
50
49
  \u274C Old: atomic-codegen generate typescript
51
50
 
52
51
  All generation settings are now configured in your config file.
53
- Create an atomic-codegen.config.ts file to get started.`),process.exit(1);}let e=process.cwd(),t=await Hr(e);if(!t){let o=Ne.map(a=>` - ${a}`).join(`
54
- `);C(`No configuration file found. Please create one of the following files in your project root:
52
+ Create an atomic-codegen.config.ts file to get started.`),process.exit(1);}let e=process.cwd(),t=await fi(e);if(!t){let o=Oe.map(a=>` - ${a}`).join(`
53
+ `);b(`No configuration file found. Please create one of the following files in your project root:
55
54
  ${o}
56
55
 
57
56
  Example atomic-codegen.config.ts:
@@ -63,13 +62,13 @@ export default defineConfig({
63
62
  typescript: {
64
63
  generateIndex: true
65
64
  }
66
- });`),process.exit(1);}let r=await Me(e),i=s.verbose??r.verbose??false,n=R({verbose:i,prefix:"Generate"});try{Ve("Starting generation from config"),i&&(n.info(`Config file: ${t}`),n.info(`Output directory: ${r.outputDir||"./generated"}`),n.info(`Packages: ${r.packages?.length||0}`),n.info(`Files: ${r.files?.length||0}`),n.info(`TypeScript generation: ${r.typescript?"enabled":"disabled"}`));let o=new te({outputDir:r.outputDir||"./generated",verbose:i,overwrite:r.overwrite??!0,cache:r.cache??!0,typeSchemaConfig:r.typeSchema,logger:n});if(r.packages&&r.packages.length>0){n.info(`Loading packages from config: ${r.packages.join(", ")}`);for(let c of r.packages){let[l,u]=c.includes("@")?c.split("@"):[c,void 0];o.fromPackage(l,u);}}else if(r.files&&r.files.length>0){n.info(`Loading files from config: ${r.files.join(", ")}`);for(let c of r.files)o.fromFiles(c);}else throw new Error("No data source specified in config. Please configure 'packages' or 'files' in your config file.");if(r.typescript&&(i&&(n.info("Configuring TypeScript generation from config"),n.debug(`Module format: ${r.typescript.moduleFormat||"esm"}`),n.debug(`Generate index: ${r.typescript.generateIndex??!0}`),n.debug(`Include docs: ${r.typescript.includeDocuments??!1}`),n.debug(`Naming convention: ${r.typescript.namingConvention||"PascalCase"}`)),o.typescript(r.typescript)),!r.typescript)throw new Error("No generators configured. Please enable 'typescript' in your config file.");i&&o.onProgress((c,l,u,g)=>{let m=Math.round(l/u*100);n.progress(`[${c}] ${m}% - ${g||"Processing..."}`);}),n.step("Executing generation...");let a=await o.generate();if(a.success){if(se(`Generated ${a.filesGenerated.length} files in ${a.duration.toFixed(2)}ms`),n.dim(`Output directory: ${a.outputDir}`),a.warnings.length>0)for(let c of a.warnings)Le(c);}else {C(`Generation failed with ${a.errors.length} errors`);for(let c of a.errors)n.dim(` ${c}`);process.exit(1);}}catch(o){C("Generation failed with unexpected error",o instanceof Error?o:new Error(String(o))),process.exit(1);}}};async function Hr(s){for(let e of Ne){let t=resolve(s,e);if(existsSync(t))return t}return null}var Yt={command:"generate <packages..>",describe:"Generate TypeSchema files from FHIR packages",builder:{packages:{type:"string",array:true,demandOption:true,describe:"FHIR packages to process (e.g., hl7.fhir.r4.core@4.0.1)"},output:{alias:"o",type:"string",describe:"Output file or directory",default:"./schemas.ndjson"},format:{alias:"f",type:"string",choices:["ndjson","json"],default:"ndjson",describe:"Output format for TypeSchema files"},treeshake:{alias:"t",type:"string",array:true,describe:"Only generate TypeSchemas for specific ResourceTypes (treeshaking)"},singleFile:{alias:"s",type:"boolean",default:false,describe:"Generate single TypeSchema file instead of multiple files (NDJSON format)"},verbose:{alias:"v",type:"boolean",default:false,describe:"Enable verbose output"}},handler:async s=>{let e=R({verbose:s.verbose,prefix:"TypeSchema"});try{let t=await Me(process.cwd());e.step("Generating TypeSchema from FHIR packages"),e.info(`Packages: ${s.packages.join(", ")}`),e.info(`Output: ${s.output}`);let r=s.singleFile!==void 0?s.singleFile:t.typeSchema?.singleFile??!1,i=r?"ndjson":s.format;e.debug(`Format: ${i}${r&&s.format==="json"?" (forced from json due to singleFile)":""}`);let n=s.treeshake&&s.treeshake.length>0?s.treeshake:t.typeSchema?.treeshake;n&&n.length>0&&e.info(`Treeshaking enabled for ResourceTypes: ${n.join(", ")}`),r&&e.info("Single file output enabled (NDJSON format)");let o=Date.now(),a=new O({verbose:s.verbose,treeshake:n}),c=[];for(let m of s.packages){let[p,h]=m.includes("@")?m.split("@"):[m,void 0];e.progress(`Processing package: ${p}${h?`@${h}`:""}`);let S=await a.generateFromPackage(p,h,e);c.push(...S);}if(c.length===0)throw new Error("No schemas were generated from the specified packages");let l=s.output;await mkdir(dirname(l),{recursive:!0});let u;i==="json"?u=JSON.stringify(c,null,2):u=c.map(m=>JSON.stringify(m)).join(`
67
- `),await writeFile(l,u,"utf-8");let g=Date.now()-o;if(Ge(`Generated ${c.length} TypeSchema definitions`,g,{schemas:c.length}),e.dim(`Output: ${l}`),s.verbose){e.debug("Generated schemas:");let m=c.map(p=>`${p.identifier?.name||"Unknown"} (${p.identifier?.kind||"unknown"})`);V(m);}}catch(t){e.error("Failed to generate TypeSchema",t instanceof Error?t:new Error(String(t))),process.exit(1);}}};var Qt={command:"typeschema [subcommand]",describe:"TypeSchema operations - generate, validate and merge schemas",builder:s=>s.command(Yt).help().example("$0 typeschema generate hl7.fhir.r4.core@4.0.1","Generate TypeSchema from FHIR R4 core package"),handler:s=>{if(!s.subcommand&&s._.length===1){oe("Available typeschema subcommands:"),V(["generate Generate TypeSchema files from FHIR packages"]),console.log(`
65
+ });`),process.exit(1);}let r=await De(e),i=s.verbose??r.verbose??false,n=C({verbose:i,prefix:"Generate"});try{je("Starting generation from config"),i&&(n.info(`Config file: ${t}`),n.info(`Output directory: ${r.outputDir||"./generated"}`),n.info(`Packages: ${r.packages?.length||0}`),n.info(`Files: ${r.files?.length||0}`),n.info(`TypeScript generation: ${r.typescript?"enabled":"disabled"}`));let o=new ie({outputDir:r.outputDir||"./generated",verbose:i,overwrite:r.overwrite??!0,cache:r.cache??!0,typeSchemaConfig:r.typeSchema,logger:n});if(r.packages&&r.packages.length>0){n.info(`Loading packages from config: ${r.packages.join(", ")}`);for(let c of r.packages){let[l,d]=c.includes("@")?c.split("@"):[c,void 0];o.fromPackage(l,d);}}else if(r.files&&r.files.length>0){n.info(`Loading files from config: ${r.files.join(", ")}`);for(let c of r.files)o.fromFiles(c);}else throw new Error("No data source specified in config. Please configure 'packages' or 'files' in your config file.");if(r.typescript&&(i&&(n.info("Configuring TypeScript generation from config"),n.debug(`Module format: ${r.typescript.moduleFormat||"esm"}`),n.debug(`Generate index: ${r.typescript.generateIndex??!0}`),n.debug(`Include docs: ${r.typescript.includeDocuments??!1}`),n.debug(`Naming convention: ${r.typescript.namingConvention||"PascalCase"}`)),o.typescript(r.typescript)),!r.typescript)throw new Error("No generators configured. Please enable 'typescript' in your config file.");i&&o.onProgress((c,l,d,f)=>{let g=Math.round(l/d*100);n.progress(`[${c}] ${g}% - ${f||"Processing..."}`);}),n.step("Executing generation...");let a=await o.generate();if(a.success){if(ae(`Generated ${a.filesGenerated.length} files in ${a.duration.toFixed(2)}ms`),n.dim(`Output directory: ${a.outputDir}`),a.warnings.length>0)for(let c of a.warnings)Ve(c);}else {b(`Generation failed with ${a.errors.length} errors`);for(let c of a.errors)n.dim(` ${c}`);process.exit(1);}}catch(o){b("Generation failed with unexpected error",o instanceof Error?o:new Error(String(o))),process.exit(1);}}};async function fi(s){for(let e of Oe){let t=resolve(s,e);if(existsSync(t))return t}return null}var ur={command:"generate <packages..>",describe:"Generate TypeSchema files from FHIR packages",builder:{packages:{type:"string",array:true,demandOption:true,describe:"FHIR packages to process (e.g., hl7.fhir.r4.core@4.0.1)"},output:{alias:"o",type:"string",describe:"Output file or directory",default:"./schemas.ndjson"},format:{alias:"f",type:"string",choices:["ndjson","json"],default:"ndjson",describe:"Output format for TypeSchema files"},treeshake:{alias:"t",type:"string",array:true,describe:"Only generate TypeSchemas for specific ResourceTypes (treeshaking)"},singleFile:{alias:"s",type:"boolean",default:false,describe:"Generate single TypeSchema file instead of multiple files (NDJSON format)"},verbose:{alias:"v",type:"boolean",default:false,describe:"Enable verbose output"}},handler:async s=>{let e=C({verbose:s.verbose,prefix:"TypeSchema"});try{let t=await De(process.cwd());e.step("Generating TypeSchema from FHIR packages"),e.info(`Packages: ${s.packages.join(", ")}`),e.info(`Output: ${s.output}`);let r=s.singleFile!==void 0?s.singleFile:t.typeSchema?.singleFile??!1,i=r?"ndjson":s.format;e.debug(`Format: ${i}${r&&s.format==="json"?" (forced from json due to singleFile)":""}`);let n=s.treeshake&&s.treeshake.length>0?s.treeshake:t.typeSchema?.treeshake;n&&n.length>0&&e.info(`Treeshaking enabled for ResourceTypes: ${n.join(", ")}`),r&&e.info("Single file output enabled (NDJSON format)");let o=Date.now(),a=new M({verbose:s.verbose,treeshake:n}),c=[];for(let g of s.packages){let[p,u]=g.includes("@")?g.split("@"):[g,void 0];e.progress(`Processing package: ${p}${u?`@${u}`:""}`);let m=await a.generateFromPackage(p,u,e);c.push(...m);}if(c.length===0)throw new Error("No schemas were generated from the specified packages");let l=s.output;await mkdir(dirname(l),{recursive:!0});let d;i==="json"?d=JSON.stringify(c,null,2):d=c.map(g=>JSON.stringify(g)).join(`
66
+ `),await writeFile(l,d,"utf-8");let f=Date.now()-o;if(Ue(`Generated ${c.length} TypeSchema definitions`,f,{schemas:c.length}),e.dim(`Output: ${l}`),s.verbose){e.debug("Generated schemas:");let g=c.map(p=>`${p.identifier?.name||"Unknown"} (${p.identifier?.kind||"unknown"})`);A(g);}}catch(t){e.error("Failed to generate TypeSchema",t instanceof Error?t:new Error(String(t))),process.exit(1);}}};var gr={command:"typeschema [subcommand]",describe:"TypeSchema operations - generate, validate and merge schemas",builder:s=>s.command(ur).help().example("$0 typeschema generate hl7.fhir.r4.core@4.0.1","Generate TypeSchema from FHIR R4 core package"),handler:s=>{if(!s.subcommand&&s._.length===1){ce("Available typeschema subcommands:"),A(["generate Generate TypeSchema files from FHIR packages"]),console.log(`
68
67
  Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),console.log(`
69
- Examples:`),V(["atomic-codegen typeschema generate hl7.fhir.r4.core@4.0.1 -o schemas.ndjson","atomic-codegen typeschema validate schemas.ndjson","atomic-codegen typeschema merge schema1.ndjson schema2.ndjson -o merged.ndjson"]);return}s.subcommand&&!["generate","validate","merge"].includes(s.subcommand)&&(C(`Unknown typeschema subcommand: ${s.subcommand}
70
- `),oe("Available typeschema subcommands:"),V(["generate Generate TypeSchema files from FHIR packages","validate Validate TypeSchema files for correctness and consistency","merge Merge multiple TypeSchema files into a single file"]),console.log(`
71
- Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),process.exit(1));}};async function Kr(s){je({verbose:s.verbose||s.debug,timestamp:s.debug});}function Zr(){return Wr(hideBin(process.argv)).scriptName("atomic-codegen").usage("$0 <command> [options]").middleware(Kr).command(Qt).command(Zt).option("verbose",{alias:"v",type:"boolean",description:"Enable verbose output",default:false,global:true}).option("debug",{alias:"d",type:"boolean",description:"Enable debug output with detailed logging",default:false,global:true}).option("config",{alias:"c",type:"string",description:"Path to configuration file (.atomic-codegen.json by default)",global:true}).demandCommand(0).middleware(s=>{s._.length===0&&(Ae("Welcome to Atomic Codegen!"),console.log("Available commands:"),console.log(" typeschema Generate, validate and merge TypeSchema files"),console.log(" generate Generate code based on configuration file"),console.log(`
68
+ Examples:`),A(["atomic-codegen typeschema generate hl7.fhir.r4.core@4.0.1 -o schemas.ndjson","atomic-codegen typeschema validate schemas.ndjson","atomic-codegen typeschema merge schema1.ndjson schema2.ndjson -o merged.ndjson"]);return}s.subcommand&&!["generate","validate","merge"].includes(s.subcommand)&&(b(`Unknown typeschema subcommand: ${s.subcommand}
69
+ `),ce("Available typeschema subcommands:"),A(["generate Generate TypeSchema files from FHIR packages","validate Validate TypeSchema files for correctness and consistency","merge Merge multiple TypeSchema files into a single file"]),console.log(`
70
+ Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),process.exit(1));}};async function vi(s){Ge({verbose:s.verbose||s.debug,timestamp:s.debug});}function Ti(){return Si(hideBin(process.argv)).scriptName("atomic-codegen").usage("$0 <command> [options]").middleware(vi).command(gr).command(pr).option("verbose",{alias:"v",type:"boolean",description:"Enable verbose output",default:false,global:true}).option("debug",{alias:"d",type:"boolean",description:"Enable debug output with detailed logging",default:false,global:true}).option("config",{alias:"c",type:"string",description:"Path to configuration file (.atomic-codegen.json by default)",global:true}).demandCommand(0).middleware(s=>{s._.length===0&&(He("Welcome to Atomic Codegen!"),console.log("Available commands:"),console.log(" typeschema Generate, validate and merge TypeSchema files"),console.log(" generate Generate code based on configuration file"),console.log(`
72
71
  Use 'atomic-codegen <command> --help' for more information about a command.`),console.log(`
73
72
  Quick examples:`),console.log(" atomic-codegen typeschema generate hl7.fhir.r4.core@4.0.1 -o schemas.ndjson"),console.log(" atomic-codegen generate # Uses atomic-codegen.config.ts"),console.log(`
74
- Use 'atomic-codegen --help' to see all options.`),process.exit(0));}).help().version("0.1.0").example("$0 generate","Generate code using atomic-codegen.config.ts").example("$0 generate --verbose","Generate with detailed progress output").example("$0 --config custom-config.ts generate","Use custom configuration file").example("$0 typeschema generate hl7.fhir.r4.core@4.0.1 -o schemas.ndjson","Generate TypeSchemas from FHIR package").fail((s,e,t)=>{e?C(e.message,e):C(s),C(`
75
- Use --help for usage information`),process.exit(1);}).wrap(Math.min(120,process.stdout.columns||80))}async function pt(){await Zr().parseAsync();}import.meta.main&&pt().catch(s=>{s("Unexpected error:",s),process.exit(1);});pt().catch(s=>{console.error("CLI Error:",s instanceof Error?s.message:s),process.exit(1);});
73
+ Use 'atomic-codegen --help' to see all options.`),process.exit(0));}).help().version("0.1.0").example("$0 generate","Generate code using atomic-codegen.config.ts").example("$0 generate --verbose","Generate with detailed progress output").example("$0 --config custom-config.ts generate","Use custom configuration file").example("$0 typeschema generate hl7.fhir.r4.core@4.0.1 -o schemas.ndjson","Generate TypeSchemas from FHIR package").fail((s,e,t)=>{e?b(e.message,e):b(s),b(`
74
+ Use --help for usage information`),process.exit(1);}).wrap(Math.min(120,process.stdout.columns||80))}async function dt(){await Ti().parseAsync();}import.meta.main&&dt().catch(s=>{s("Unexpected error:",s),process.exit(1);});dt().catch(s=>{console.error("CLI Error:",s instanceof Error?s.message:s),process.exit(1);});