@atomic-ehr/codegen 0.0.4-canary.20251211114058.39d4b3a → 0.0.4-canary.20251216132615.27719de

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/README.md CHANGED
@@ -122,25 +122,47 @@ Actual examples of type generation and usage can be found here: [examples/typesc
122
122
 
123
123
  - `demo.ts` - a simple script that creates resources and demonstrates how to work with profiles
124
124
  - `generate.ts` - script to generate types
125
+ - [`examples/local-structure-package.ts`](examples/local-structure-package.ts) - demonstrates loading local profiles, installing dependencies, and tree shaking the output
126
+ - [`examples/local-package-folder/generate.ts`](examples/local-package-folder/generate.ts) - demonstrates pointing the builder at an existing FHIR package folder without publishing it
125
127
 
126
- ### Generate Types for a Custom Profile (Draft)
128
+ ### Load Local StructureDefinitions, Local Packages & TGZ Archives
129
+
130
+ Use the new `localPackage` helper to point the builder at an on-disk FHIR package folder (for example, an unpublished implementation guide). If you only have loose StructureDefinition JSON files, group them under a folder and pass it to `localStructureDefinitions`. Canonical Manager handles copying, indexing, and dependency installation in both scenarios, so the API builder only needs to describe where the files live and what upstream packages they depend on.
127
131
 
128
132
  ```typescript
129
- import { APIBuilder } from '@atomic-ehr/codegen';
133
+ import { APIBuilder } from "@atomic-ehr/codegen";
130
134
 
131
135
  const builder = new APIBuilder();
132
136
 
133
- // Load custom profile
134
137
  await builder
135
- .fromProfile('./profiles/my-patient-profile.json')
136
- .withBaseProfile('http://hl7.org/fhir/StructureDefinition/Patient')
137
- .typescript({
138
- outputDir: './generated/profiles',
139
- includeValidators: true,
138
+ .localPackage({
139
+ package: { name: "example.folder.structures", version: "0.0.1" },
140
+ path: "./packages/example-ig/package",
141
+ dependencies: [{ name: "hl7.fhir.r4.core", version: "4.0.1" }],
140
142
  })
143
+ .localStructureDefinitions({
144
+ package: { name: "example.local.structures", version: "0.0.1" },
145
+ path: "./custom-profiles",
146
+ dependencies: [{ name: "hl7.fhir.r4.core", version: "4.0.1" }],
147
+ })
148
+ .localTgzPackage("./packages/my-custom-ig.tgz")
149
+ .typescript({ generateIndex: true })
150
+ .treeShake({
151
+ "example.local.structures#0.0.1": {
152
+ "http://example.org/fhir/StructureDefinition/ExampleNotebook": {},
153
+ },
154
+ "hl7.fhir.r4.core#4.0.1": {
155
+ "http://hl7.org/fhir/StructureDefinition/Patient": {},
156
+ },
157
+ })
158
+ .outputTo("./generated/local-profiles")
141
159
  .generate();
142
160
  ```
143
161
 
162
+ The example above points Canonical Manager at `./custom-profiles`, installs the HL7 R4 core dependency automatically, and then limits generation to the custom `ExampleNotebook` logical model plus the standard R4 `Patient` resource via tree shaking. The `localTgzPackage` helper registers `.tgz` artifacts that Canonical Manager already knows how to unpack.
163
+
164
+ `localPackage` is ideal when you already have an extracted Implementation Guide on disk (for example, after running `fhirpack` or `npm pack`). The helper copies that folder into Canonical Manager's cache, synthesizes an index if necessary, and makes the package available to the rest of the pipeline without publishing it anywhere.
165
+
144
166
  ### Generate with Custom Templates (Draft)
145
167
 
146
168
  ```typescript
package/dist/cli/index.js CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import x from'picocolors';import Pr from'yargs';import {hideBin}from'yargs/helpers';import*as T from'fs';import T__default,{existsSync}from'fs';import*as E from'path';import E__default,{dirname,resolve}from'path';import*as L from'fs/promises';import {mkdir,writeFile,readFile}from'fs/promises';import {CanonicalManager}from'@atomic-ehr/fhir-canonical-manager';import*as gt from'@atomic-ehr/fhirschema';import {isStructureDefinition}from'@atomic-ehr/fhirschema';import*as Tt from'yaml';import nr from'assert';var _=class r{options;dryWarnSet=new Set;constructor(e={}){this.options={timestamp:false,level:1,...e};}shouldLog(e){let t=this.options.level??1;return e>=t}static consoleLevelsMap={1:console.log,2:console.warn,3:console.error,0:console.log,4:()=>{}};formatMessage(e,t,n){let o=this.options.timestamp?`${x.gray(new Date().toLocaleTimeString())} `:"",i=this.options.prefix?`${x.cyan(`[${this.options.prefix}]`)} `:"";return `${o}${n(e)} ${i}${t}`}isSuppressed(e){return this.options.suppressLoggingLevel==="all"||this.options.suppressLoggingLevel?.includes(e)||false}tryWriteToConsole(e,t){if(this.isSuppressed(e)||!this.shouldLog(e))return;(r.consoleLevelsMap[e]||console.log)(t);}success(e){this.tryWriteToConsole(1,this.formatMessage("",e,x.green));}error(e,t){if(this.isSuppressed(3)||!this.shouldLog(3))return;console.error(this.formatMessage("X",e,x.red));let n=this.options.level===0;t&&n&&(console.error(x.red(` ${t.message}`)),t.stack&&console.error(x.gray(t.stack)));}warn(e){this.tryWriteToConsole(2,this.formatMessage("!",e,x.yellow));}dry_warn(e){this.dryWarnSet.has(e)||(this.warn(e),this.dryWarnSet.add(e));}info(e){this.tryWriteToConsole(1,this.formatMessage("i",e,x.blue));}debug(e){this.shouldLog(0)&&this.tryWriteToConsole(0,this.formatMessage("\u{1F41B}",e,x.magenta));}step(e){this.tryWriteToConsole(1,this.formatMessage("\u{1F680}",e,x.cyan));}progress(e){this.tryWriteToConsole(1,this.formatMessage("\u23F3",e,x.blue));}plain(e,t=n=>n){let n=this.options.timestamp?`${x.gray(new Date().toLocaleTimeString())} `:"",o=this.options.prefix?`${x.cyan(`[${this.options.prefix}]`)} `:"";this.tryWriteToConsole(1,`${n}${o}${t(e)}`);}dim(e){this.plain(e,x.gray);}child(e){return new r({...this.options,prefix:this.options.prefix?`${this.options.prefix}:${e}`:e})}configure(e){this.options={...this.options,...e};}getLevel(){return this.options.level??1}setLevel(e){this.options.level=e;}},B=new _;function ve(r){B.success(r);}function I(r,e){B.error(r,e);}function ze(r){B.warn(r);}function xe(r){B.info(r);}function We(r){B.step(r);}function Vt(r){B.dim(r);}function qe(r){B.configure(r);}function N(r={}){return new _(r)}function Je(r){console.log(),console.log(x.cyan(x.bold(`\u2501\u2501\u2501 ${r} \u2501\u2501\u2501`)));}function Ke(r,e,t){let n=r;e&&(n+=` ${x.gray(`(${e}ms)`)}`),ve(n),t&&Object.entries(t).forEach(([o,i])=>{Vt(` ${o}: ${i}`);});}function G(r,e="\u2022"){r.forEach(t=>{console.log(x.gray(` ${e} ${t}`));});}var ke=r=>r.split(/(?<=[a-z])(?=[A-Z])|[-_.\s]/).filter(Boolean),Qe=r=>ke(r).map(e=>e.toLowerCase()).join("-"),Xe=r=>{if(r.length===0)throw new Error("Empty string");return r[0]?.toUpperCase()+r.substring(1).toLowerCase()},Ye=r=>{if(r.length===0)throw new Error("Empty string");let[e,...t]=ke(r);return [e?.toLowerCase(),...t.map(Xe)].join("")},re=r=>ke(r).map(Xe).join("");var F=r=>!r||r.length===0?r:r.charAt(0).toUpperCase()+r.slice(1),ne=r=>r.map(e=>F(e));var Ze=r=>`<${r.identifier.url}> from ${r.identifier.package}#${r.identifier.version}`;var Te=class{opts;currentDir;currentFile;writtenFilesBuffer={};constructor(e){this.opts=e;}setOutputDir(e){if(this.currentDir)throw new Error("Can't change output dir while writing");this.opts.outputDir=e;}logger(){return this.opts.logger}onDiskMkDir(e){this.opts.inMemoryOnly||T.existsSync(e)||T.mkdirSync(e,{recursive:true});}onDiskOpenFile(e){return this.opts.inMemoryOnly?-1:T.openSync(e,"w")}onDiskCloseFile(e){this.opts.inMemoryOnly||(T.fsyncSync(e),T.closeSync(e));}onDiskWrite(e,t){this.opts.inMemoryOnly||T.writeSync(e,t);}cd(e,t){let n=this.currentDir;this.currentDir=e.startsWith("/")?E.join(this.opts.outputDir,e):E.join(this.currentDir??this.opts.outputDir,e),this.onDiskMkDir(this.currentDir),this.logger()?.debug(`cd '${this.currentDir}'`),t(),this.currentDir=n;}cat(e,t){if(this.currentFile)throw new Error("Can't open file when another file is open");if(e.includes("/"))throw new Error(`Change file path separatly: ${e}`);let n=E.normalize(`${this.currentDir}/${e}`);try{let o=this.onDiskOpenFile(n);this.logger()?.debug(`cat > '${n}'`),this.currentFile={descriptor:o,relPath:n},this.writtenFilesBuffer[this.currentFile.relPath]={relPath:n,absPath:E.resolve(n),tokens:[]},t();}finally{this.currentFile&&this.onDiskCloseFile(this.currentFile.descriptor),this.currentFile=void 0;}}write(e){if(!this.currentFile)throw new Error("No file opened");this.onDiskWrite(this.currentFile.descriptor,e);let t=this.writtenFilesBuffer[this.currentFile.relPath];if(!t)throw new Error("No buffer found");t.tokens.push(e);}writtenFiles(){return Object.values(this.writtenFilesBuffer).map(({relPath:e,absPath:t,tokens:n})=>({relPath:e,absPath:t,content:n.join()})).sort((e,t)=>e.relPath.localeCompare(t.relPath))}},z=class extends Te{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(`
2
+ import k from'picocolors';import Er from'yargs';import {hideBin}from'yargs/helpers';import*as T from'fs';import T__default,{existsSync}from'fs';import*as F from'path';import F__default,{dirname,resolve}from'path';import*as L from'fs/promises';import {mkdir,writeFile,readFile}from'fs/promises';import {CanonicalManager}from'@atomic-ehr/fhir-canonical-manager';import*as gt from'@atomic-ehr/fhirschema';import {isStructureDefinition}from'@atomic-ehr/fhirschema';import*as Tt from'yaml';import nr from'assert';var _=class r{options;dryWarnSet=new Set;constructor(e={}){this.options={timestamp:false,level:1,...e};}shouldLog(e){let t=this.options.level??1;return e>=t}static consoleLevelsMap={1:console.log,2:console.warn,3:console.error,0:console.log,4:()=>{}};formatMessage(e,t,n){let o=this.options.timestamp?`${k.gray(new Date().toLocaleTimeString())} `:"",i=this.options.prefix?`${k.cyan(`[${this.options.prefix}]`)} `:"";return `${o}${n(e)} ${i}${t}`}isSuppressed(e){return this.options.suppressLoggingLevel==="all"||this.options.suppressLoggingLevel?.includes(e)||false}tryWriteToConsole(e,t){if(this.isSuppressed(e)||!this.shouldLog(e))return;(r.consoleLevelsMap[e]||console.log)(t);}success(e){this.tryWriteToConsole(1,this.formatMessage("",e,k.green));}error(e,t){if(this.isSuppressed(3)||!this.shouldLog(3))return;console.error(this.formatMessage("X",e,k.red));let n=this.options.level===0;t&&n&&(console.error(k.red(` ${t.message}`)),t.stack&&console.error(k.gray(t.stack)));}warn(e){this.tryWriteToConsole(2,this.formatMessage("!",e,k.yellow));}dry_warn(e){this.dryWarnSet.has(e)||(this.warn(e),this.dryWarnSet.add(e));}info(e){this.tryWriteToConsole(1,this.formatMessage("i",e,k.blue));}debug(e){this.shouldLog(0)&&this.tryWriteToConsole(0,this.formatMessage("\u{1F41B}",e,k.magenta));}step(e){this.tryWriteToConsole(1,this.formatMessage("\u{1F680}",e,k.cyan));}progress(e){this.tryWriteToConsole(1,this.formatMessage("\u23F3",e,k.blue));}plain(e,t=n=>n){let n=this.options.timestamp?`${k.gray(new Date().toLocaleTimeString())} `:"",o=this.options.prefix?`${k.cyan(`[${this.options.prefix}]`)} `:"";this.tryWriteToConsole(1,`${n}${o}${t(e)}`);}dim(e){this.plain(e,k.gray);}child(e){return new r({...this.options,prefix:this.options.prefix?`${this.options.prefix}:${e}`:e})}configure(e){this.options={...this.options,...e};}getLevel(){return this.options.level??1}setLevel(e){this.options.level=e;}},B=new _;function ke(r){B.success(r);}function I(r,e){B.error(r,e);}function ze(r){B.warn(r);}function xe(r){B.info(r);}function We(r){B.step(r);}function Vt(r){B.dim(r);}function qe(r){B.configure(r);}function N(r={}){return new _(r)}function Je(r){console.log(),console.log(k.cyan(k.bold(`\u2501\u2501\u2501 ${r} \u2501\u2501\u2501`)));}function Ke(r,e,t){let n=r;e&&(n+=` ${k.gray(`(${e}ms)`)}`),ke(n),t&&Object.entries(t).forEach(([o,i])=>{Vt(` ${o}: ${i}`);});}function G(r,e="\u2022"){r.forEach(t=>{console.log(k.gray(` ${e} ${t}`));});}var Te=r=>r.split(/(?<=[a-z])(?=[A-Z])|[-_.\s]/).filter(Boolean),Qe=r=>Te(r).map(e=>e.toLowerCase()).join("-"),Xe=r=>{if(r.length===0)throw new Error("Empty string");return r[0]?.toUpperCase()+r.substring(1).toLowerCase()},Ye=r=>{if(r.length===0)throw new Error("Empty string");let[e,...t]=Te(r);return [e?.toLowerCase(),...t.map(Xe)].join("")},re=r=>Te(r).map(Xe).join("");var w=r=>!r||r.length===0?r:r.charAt(0).toUpperCase()+r.slice(1),ne=r=>r.map(e=>w(e));var Ze=r=>`<${r.identifier.url}> from ${r.identifier.package}#${r.identifier.version}`;var Re=class{opts;currentDir;currentFile;writtenFilesBuffer={};constructor(e){this.opts=e;}setOutputDir(e){if(this.currentDir)throw new Error("Can't change output dir while writing");this.opts.outputDir=e;}logger(){return this.opts.logger}onDiskMkDir(e){this.opts.inMemoryOnly||T.existsSync(e)||T.mkdirSync(e,{recursive:true});}onDiskOpenFile(e){return this.opts.inMemoryOnly?-1:T.openSync(e,"w")}onDiskCloseFile(e){this.opts.inMemoryOnly||(T.fsyncSync(e),T.closeSync(e));}onDiskWrite(e,t){this.opts.inMemoryOnly||T.writeSync(e,t);}cd(e,t){let n=this.currentDir;this.currentDir=e.startsWith("/")?F.join(this.opts.outputDir,e):F.join(this.currentDir??this.opts.outputDir,e),this.onDiskMkDir(this.currentDir),this.logger()?.debug(`cd '${this.currentDir}'`),t(),this.currentDir=n;}cat(e,t){if(this.currentFile)throw new Error("Can't open file when another file is open");if(e.includes("/"))throw new Error(`Change file path separatly: ${e}`);let n=F.normalize(`${this.currentDir}/${e}`);try{let o=this.onDiskOpenFile(n);this.logger()?.debug(`cat > '${n}'`),this.currentFile={descriptor:o,relPath:n},this.writtenFilesBuffer[this.currentFile.relPath]={relPath:n,absPath:F.resolve(n),tokens:[]},t();}finally{this.currentFile&&this.onDiskCloseFile(this.currentFile.descriptor),this.currentFile=void 0;}}write(e){if(!this.currentFile)throw new Error("No file opened");this.onDiskWrite(this.currentFile.descriptor,e);let t=this.writtenFilesBuffer[this.currentFile.relPath];if(!t)throw new Error("No buffer found");t.tokens.push(e);}writtenFiles(){return Object.values(this.writtenFilesBuffer).map(({relPath:e,absPath:t,tokens:n})=>({relPath:e,absPath:t,content:n.join()})).sort((e,t)=>e.relPath.localeCompare(t.relPath))}},z=class extends Re{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(`
3
3
  `):(this.writeIndent(),this.write(`${e.join(" ")}
4
4
  `));}lineSM(...e){this.writeIndent(),this.write(`${e.join(" ")};
5
5
  `);}comment(...e){let t=e.join(" ").split(`
6
- `);for(let n of t)this.line(this.opts.commentLinePrefix,n);}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/atomic-ehr/codegen","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,n){this.line(`${e.filter(Boolean).join(" ")} {`),this.indent(),t(),this.deindent(),this.line(`}${n?.filter(Boolean).join(" ")??""}`);}squareBlock(e,t,n){this.line(`${e.filter(Boolean).join(" ")} [`),this.indent(),t(),this.deindent(),this.line(`]${n?.filter(Boolean).join(" ")??""}`);}};var ie=(r,e=true)=>{let t=r.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),t};var C=r=>`${r.name}#${r.version}`,Re=r=>`${r.name}@${r.version}`;var Ie=(r,e)=>(e||(e={name:"undefined",version:"undefined"}),{...r,package_meta:r.package_meta||e,name:r.name,url:r.url,base:r.base}),q=r=>r?.kind==="primitive-type",O=r=>r?.kind==="nested",et=r=>r?.kind==="complex-type",tt=r=>r?.kind==="profile";var j=r=>r?.identifier.kind==="resource"||r?.identifier.kind==="complex-type"||r?.identifier.kind==="logical",rt=r=>r?.identifier.kind==="complex-type",w=r=>r?.identifier.kind==="resource",nt=r=>r?.identifier.kind==="primitive-type",D=r=>r?.identifier.kind==="logical",oe=r=>r?.identifier.kind==="profile";function it(r){return r?.identifier.kind==="binding"}function ot(r){return r?.identifier.kind==="value-set"}var J=r=>r?r.choices===void 0:false,U=r=>r?r.choices!==void 0:false,st=(r,e)=>{if(!r.url)throw new Error("ValueSet must have a URL");if(!r.name)throw new Error("ValueSet must have a name");return {...r,package_meta:r.package_meta||e,name:r.name,url:r.url}};var at={"!":"Not","<=":"LessOrEqual",">=":"GreaterOrEqual","<":"Less",">":"Greater","=":"Equal","-":"Dash","+":"Plus","*":"Asterisk","/":"Slash","%":"Percent","&":"And","|":"Or","^":"Xor","~":"Tilde","?":"Question",".":"Dot"};function jt(r){return r.split("-").map(e=>F(e)).join("-")}function Ut(r){let e=r;for(let t in at)e=e.replaceAll(t,at[t]??"");return e}function Ht(r){let e=Number(r[0]);return Number.isInteger(e)&&!Number.isNaN(e)?`_${r}`:r}function ct(r){let e=jt(r);return e=Ht(e),e=Ut(e),e=F(e),e}function $(r){return F(Ye(r.replaceAll(".","-")))}var At={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"},_t=["Reference","Expression"],Gt=r=>r.required?["required"]:[],zt=r=>{let e=ut(dt(r.identifier));return F(e)},Wt=r=>r.base?`: ${r.base.name}`:"",qt=(r,e=true)=>{if(!r)return;let t=r.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),$(t)},dt=r=>{if(r.kind==="nested"){let e=r.url,t=qt(e,false);if(!t)return "";let[n,o]=t.split("#"),i=ne((o??"").split(".")).join("");return $([n,i].join(""))}return $(r.name)},Jt=r=>_t.includes(r),ut=r=>Jt(r)?`Resource${r}`:r,se=class extends z{enums={};constructor(e){super({tabSize:4,withDebugComment:false,commentLinePrefix:"//",...e});}async generate(e){let t=e.collectComplexTypes(),n=e.collectResources(),o=Array.from(new Set(n.map(i=>$(i.identifier.package))));this.generateAllFiles(t,n,o),this.copyStaticFiles();}generateAllFiles(e,t,n){this.generateUsingFile(n),this.generateBaseTypes(e),this.generateResources(t),this.generateEnumFiles(n),this.generateResourceDictionaries(t,n),this.generateHelperFile();}generateType(e,t){let n=zt(e),o=Wt(e);this.curlyBlock(["public","class",n,o],()=>{this.generateFields(e,t),this.generateNestedTypes(e,t),this.line(),this.includeHelperMethods();}),this.line();}generateFields(e,t){if(!e.fields)return;let n=Object.entries(e.fields).sort(([o],[i])=>o.localeCompare(i));for(let[o,i]of n)this.generateField(o,i,t);}generateNestedTypes(e,t){if(!(!("nested"in e)||!e.nested)){this.line();for(let n of e.nested)this.generateType(n,t);}}generateField(e,t,n){try{if(U(t))return;let o=this.buildFieldDeclaration(e,t,n);this.line(...o);}catch(o){this.logger()?.error(`Error processing field ${e}: ${o.message}`);}}buildFieldDeclaration(e,t,n){let o=this.determineFieldType(e,t,n),i=Gt(t),s=re(e);return ["public",...i,o,s,"{ get; set; }"].filter(Boolean)}determineFieldType(e,t,n){let o=this.getBaseTypeName(t);"enum"in t&&t.enum&&(o=this.registerAndGetEnumType(e,t,n)),o=ut(o);let i="",s=t.required?"":"?",c=t.array?"[]":"";return `${i}${o}${c}${s}`}getBaseTypeName(e){if("type"in e){let t=e.type.name.toString();return e.type.kind==="nested"?t=dt(e.type):e.type.kind==="primitive-type"&&(t=At[e.type.name]??"string"),t}return ""}registerAndGetEnumType(e,t,n){let i=`${$(t.binding?.name??e)}Enum`;return this.enums[n]||(this.enums[n]={}),t.enum&&(this.enums[n][i]=t.enum),i}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.opts.targetNamespace,...e.map(n=>`${this.opts.targetNamespace}.${n}`)];for(let n of t)this.lineSM("global","using",n);}generateBaseTypes(e){this.cd("/",async()=>{this.cat("base.cs",()=>{this.generateDisclaimer(),this.line(),this.lineSM("namespace",this.opts.targetNamespace);for(let t of e){let n=$(t.identifier.package);this.generateType(t,n);}});});}generateResources(e){for(let t of e)this.generateResourceFile(t);}generateResourceFile(e){let t=$(e.identifier.package);this.cd(`/${t}`,async()=>{this.cat(`${e.identifier.name}.cs`,()=>{this.generateDisclaimer(),this.line(),this.lineSM("namespace",`${this.opts.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.opts.targetNamespace}.${e}`);for(let[n,o]of Object.entries(t))this.generateEnum(n,o);}generateEnum(e,t){this.curlyBlock(["public","enum",e],()=>{for(let n of t)this.line(`[Description("${n}")]`),this.line(`${ct(n)},`);}),this.line();}generateResourceDictionaries(e,t){this.cd("/",async()=>{for(let n of t){let o=e.filter(i=>$(i.identifier.package)===n);if(o.length===0)return;this.cat(`${n}ResourceDictionary.cs`,()=>{this.generateDisclaimer(),this.line(),this.lineSM(`namespace ${this.opts.targetNamespace}`),this.generateResourceDictionaryClass(n,o);});}});}generateResourceDictionaryClass(e,t){this.curlyBlock(["public","static","class","ResourceDictionary"],()=>{this.curlyBlock(["public static readonly Dictionary<Type, string> Map = new()"],()=>{for(let n of t){let o=n.identifier.name;this.line(`{ typeof(${e}.${o}), "${o}" },`);}}),this.lineSM();});}copyStaticFiles(){if(!this.opts.staticSourceDir)return;let e=E__default.resolve(this.opts.staticSourceDir);T__default.cpSync(e,this.opts.outputDir,{recursive:true});}generateHelperFile(){let e="src/api/writer-generator/csharp/Helper.cs",t=E__default.join(this.opts.outputDir,"Helper.cs");T__default.copyFileSync(e,t);}};var Fe=r=>r!==null&&typeof r=="object"&&r.resourceType==="CodeSystem";var ae=r=>r!==null&&typeof r=="object"&&r.resourceType==="ValueSet";var Kt=async(r,e)=>{let n=(await r.packageJson(e.name)).dependencies;return n!==void 0?Object.entries(n).map(([o,i])=>({name:o,version:i})):[]},mt=r=>({pkg:r,canonicalResolution:{},fhirSchemas:{},valueSets:{}}),ht=async(r,e,t,n,o)=>{let i=C(e);if(o?.info(`${" ".repeat(t*2)}+ ${i}`),n[i])return n[i];let s=mt(e);for(let a of await r.search({package:e})){let l=a.url;if(!l||!(isStructureDefinition(a)||ae(a)||Fe(a)))continue;let d=l;s.canonicalResolution[d]&&o?.dry_warn(`Duplicate canonical URL: ${d} at ${i}.`),s.canonicalResolution[d]=[{deep:t,pkg:e,pkgId:i,resource:a}];}let c=await Kt(r,e);for(let a of c){let{canonicalResolution:l}=await ht(r,a,t+1,n,o);for(let[d,h]of Object.entries(l)){let m=d;s.canonicalResolution[m]=[...s.canonicalResolution[m]||[],...h];}}for(let a of Object.values(s.canonicalResolution))a.sort((l,d)=>l.deep-d.deep);return n[i]=s,s},ft=(r,e,t)=>{let n=Object.values(r).flatMap(o=>o.canonicalResolution[e]);if(!n)throw new Error(`No canonical resolution found for ${e} in any package`);return n[0]?.resource},K=async(r,{logger:e,fallbackPackageForNameResolution:t,focusedPackages:n})=>{let o=n??await r.packages(),i={};for(let p of o)await ht(r,p,0,i,e);for(let{pkg:p,canonicalResolution:g}of Object.values(i)){let y=C(p);if(!i[y])throw new Error(`Package ${y} not found`);let u=0;e?.info(`FHIR Schema conversion for '${C(p)}' begins...`);for(let[f,S]of Object.entries(g)){let v=S[0];if(!v)throw new Error("Resource not found");let b=v.resource,R=v.pkg;if(isStructureDefinition(b)){let M=Ie(gt.translate(b),R);u++,i[y].fhirSchemas[M.url]=M;}if(ae(b)){let M=st(b,R);i[y].valueSets[M.url]=M;}}e?.info(`FHIR Schema conversion for '${C(p)}' completed: ${u} successful`);}let s=(p,g)=>i[C(p)]?.fhirSchemas[g]||t&&i[C(t)]?.fhirSchemas[g],c=(p,g)=>i[C(p)]?.valueSets[g]||t&&i[C(t)]?.valueSets[g],a=p=>p.match(/^[a-zA-Z0-9]+$/)&&`http://hl7.org/fhir/StructureDefinition/${p}`||p,l=(p,g)=>{let y=s(p,g);if(y===void 0)throw new Error(`Failed to resolve FHIR Schema: '${g}'`);let u=[y];for(;y?.base;){let f=y.package_meta,S=a(y.base);if(y=s(f,S),y===void 0)throw new Error(`Failed to resolve FHIR Schema base for '${g}'. Problem: '${S}' from '${C(f)}'`);u.push(y);}return u};return {...r,testAppendFs(p){let g=Ie(p),y=C(g.package_meta);i[y]||(i[y]=mt(g.package_meta)),i[y].fhirSchemas[g.url]=g;},resolveFs:s,resolveFsGenealogy:l,resolveFsSpecializations:(p,g)=>l(p,g).filter(y=>y.derivation==="specialization"),ensureSpecializationCanonicalUrl:a,resolveSd:(p,g)=>{let y=ft(i,g);if(isStructureDefinition(y))return y},allFs:()=>Object.values(i).flatMap(p=>Object.values(p.fhirSchemas)),allVs:()=>Object.values(i).flatMap(p=>Object.values(p.valueSets)),resolveVs:c,resolveAny:p=>ft(i,p),resolveElementSnapshot:(p,g)=>{let y=l(p.package_meta,p.url),u=Qt(y,g);return Xt(u)},getAllElementKeys:p=>{let g=new Set;for(let[y,u]of Object.entries(p)){g.add(y);for(let f of u?.choices||[])p[f]||g.add(f);}return Array.from(g)},resolver:i,resolutionTree:()=>{let p={};for(let[g,y]of Object.entries(i)){let u=y.pkg.name;p[u]={};for(let[f,S]of Object.entries(y.canonicalResolution)){let v=f;p[u][v]=[];for(let b of S)p[u][v].push({deep:b.deep,pkg:b.pkg});}}return p}}};var Qt=(r,e)=>{let[t,...n]=e;return t===void 0?[]:r.map(o=>{if(!o.elements)return;let i=o.elements?.[t];for(let s of n)i=i?.elements?.[s];return i}).filter(o=>o!==void 0)};function Xt(r){let e=r.reverse(),t=Object.assign({},...e);return t.elements=void 0,t}function $e(r){let e=r.split("|")[0];return e||r}function Yt(r){return r.split("|")[1]}function Zt(r){return r.derivation==="constraint"?"profile":r.kind==="primitive-type"?"primitive-type":r.kind==="complex-type"?"complex-type":r.kind==="resource"?"resource":r.kind==="logical"?"logical":"resource"}function H(r){return {kind:Zt(r),package:r.package_meta.name,version:r.package_meta.version,name:r.name,url:r.url}}var er=r=>{let e=r.split("/"),t=e[e.length-1];return t&&t.length>0?t.split(/[-_]/).map(n=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join(""):r};function ce(r,e,t){let n=$e(t),o=er(n),i={package_meta:{name:"missing_valuesets",version:Yt(n)||"0.0.0"},id:t},s=r.resolveVs(e,n)||i,c=s?.id&&!/^[a-zA-Z0-9_-]{20,}$/.test(s.id)?s.id:o;return {kind:"value-set",package:s.package_meta.name,version:s.package_meta.version,name:c,url:n}}function le(r,e,t){let n=e.join("."),[o,i,s]=t?[{name:"shared",version:"1.0.0"},t,`urn:fhir:binding:${t}`]:[r.package_meta,`${r.name}.${n}_binding`,`${r.url}#${n}_binding`];return {kind:"binding",package:o.name,version:o.version,name:i,url:s}}function pe(r,e,t,n){let o={};if(e.derivation==="constraint"){let a=r.resolveFsSpecializations(e.package_meta,e.url).map(l=>Ee(r,l,n)).filter(l=>l!==void 0).flat();for(let l of a.reverse())o[l.identifier.name]=l.identifier.url;}let i=t.join("."),s=o[i]??`${e.url}#${i}`;return {kind:"nested",package:e.package_meta.name,version:e.package_meta.version,name:i,url:s}}function yt(r,e,t){let n=[];for(let[o,i]of Object.entries(t)){let s=[...e,o];Q(i)&&n.push([s,i]),i.elements&&n.push(...yt(r,s,i.elements));}return n}function tr(r,e,t,n,o){let i={};for(let[s,c]of Object.entries(n)){let a=[...t,s],l=r.resolveElementSnapshot(e,a);Q(l)?i[s]=ue(r,e,a,l,o):i[s]=de(r,e,a,l,o);}return i}function Ee(r,e,t){if(!e.elements)return;let n=yt(e,[],e.elements).filter(([i,s])=>s.elements&&Object.keys(s.elements).length>0),o=[];for(let[i,s]of n){let c=pe(r,e,i,t),a;s.type==="BackboneElement"||!s.type?a="BackboneElement":a=s.type;let l=r.ensureSpecializationCanonicalUrl(a),d=r.resolveFs(e.package_meta,l);if(!d)throw new Error(`Could not resolve base type ${a}`);let h={kind:"complex-type",package:d.package_meta.name,version:d.package_meta.version,name:a,url:l},m=tr(r,e,i,s.elements??{},t),p={identifier:c,base:h,fields:m};o.push(p);}return o.sort((i,s)=>i.identifier.url.localeCompare(s.identifier.url)),o.length===0?void 0:o}function St(r){let e=[];for(let t of r){t.base&&e.push(t.base);for(let n of Object.values(t.fields||{}))"type"in n&&n.type&&e.push(n.type),"binding"in n&&n.binding&&e.push(n.binding);}return e}function bt(r,e,t){let n=t[t.length-1];if(!n)throw new Error(`Internal error: fieldName is missing for path ${t.join("/")}`);let o=t.slice(0,-1),i=r.resolveFsGenealogy(e.package_meta,e.url).flatMap(s=>{if(o.length===0)return s.required||[];if(!s.elements)return [];let c=s;for(let a of o)c=c?.elements?.[a];return c?.required||[]});return new Set(i).has(n)}function Ct(r,e,t){let n=t[t.length-1];if(!n)throw new Error(`Internal error: fieldName is missing for path ${t.join("/")}`);let o=t.slice(0,-1),i=r.resolveFsGenealogy(e.package_meta,e.url).flatMap(s=>{if(o.length===0)return s.excluded||[];if(!s.elements)return [];let c=s;for(let a of o)c=c?.elements?.[a];return c?.excluded||[]});return new Set(i).has(n)}var rr=(r,e,t)=>{if(t.refers)return t.refers.map(n=>{let o=r.ensureSpecializationCanonicalUrl(n),i=r.resolveFs(e.package_meta,o);if(!i)throw new Error(`Failed to resolve fs for ${o}`);return H(i)})};function Pe(r,e,t,n,o){if(n.elementReference){let i=n.elementReference.slice(1).filter((s,c)=>c%2===1);return pe(r,e,i,o)}else if(n.type){let i=r.ensureSpecializationCanonicalUrl(n.type),s=r.resolveFs(e.package_meta,i);if(!s)throw new Error(`Could not resolve field type: '${n.type}' (from '${e.url}' in '${C(e.package_meta)}')`);return H(s)}else {if(n.choices)return;if(e.derivation==="constraint")return;throw o?.error(`Can't recognize element type '${e.url}' (${e.derivation}) at '${t.join(".")}': ${JSON.stringify(n,void 0,2)}`),new Error("Unrecognized element type")}}var de=(r,e,t,n,o)=>{let i,s;n.binding&&(i=le(e,t,n.binding.bindingName),n.binding.strength==="required"&&n.type==="code"&&(s=Ne(r,e,n,o)));let c=Pe(r,e,t,n,o);return c||o?.warn(`Field type not found for '${e.url}#${t.join(".")}' (${e.derivation})`),{type:c,required:bt(r,e,t),excluded:Ct(r,e,t),reference:rr(r,e,n),array:n.array||false,min:n.min,max:n.max,choices:n.choices,choiceOf:n.choiceOf,binding:i,enum:s}};function Q(r){let e=r.type==="BackboneElement",t=r.type==="Element"&&r.elements!==void 0&&Object.keys(r.elements).length>0,n=r.type===void 0&&r.choiceOf===void 0&&r.elements!==void 0&&Object.keys(r.elements).length>0;return e||t||n}function ue(r,e,t,n,o){return {type:pe(r,e,t,o),array:n.array||false,required:bt(r,e,t),excluded:Ct(r,e,t)}}function Oe(r,e,t,n){let o=$e(t)||t,i=r.resolveVs(e,o);if(i)return ir(r,i)}function ir(r,e,t){if(e.expansion?.contains)return e.expansion.contains.filter(o=>o.code!==void 0).map(o=>(nr(o.code),{code:o.code,display:o.display,system:o.system}));let n=[];if(e.compose?.include){for(let o of e.compose.include)if(o.concept)for(let i of o.concept)n.push({system:o.system,code:i.code,display:i.display});else if(o.system&&!o.filter)try{let i=r.resolveAny(o.system);if(i?.concept){let s=(c,a)=>{for(let l of c)n.push({system:a,code:l.code,display:l.display}),l.concept&&s(l.concept,a);};s(i.concept,o.system);}}catch{}}return n.length>0?n:void 0}var vt=100;function Ne(r,e,t,n){if(!t.binding)return;let o=t.binding.strength,i=t.binding.valueSet;if(!i||!(o==="required"||o==="extensible"&&(t.type==="code"||t.type==="Coding")||o==="preferred"&&(t.type==="code"||t.type==="Coding")))return;let c=Oe(r,e.package_meta,i);if(!c||c.length===0)return;let a=c.map(l=>l.code).filter(l=>l&&typeof l=="string"&&l.trim().length>0);if(a.length>vt){n?.dry_warn(`Value set ${i} has ${a.length} which is more than ${vt} codes, which may cause issues with code generation.`);return}return a.length>0?a:void 0}function or(r,e,t,n,o){if(!n.binding?.valueSet)return;let i=le(e,t,n.binding.bindingName),s=Pe(r,e,t,n,o),c=ce(r,e.package_meta,n.binding.valueSet),a=[];s&&a.push(s),a.push(c);let l=Ne(r,e,n,o);return {identifier:i,type:s,valueset:c,strength:n.binding.strength,enum:l,dependencies:a}}function xt(r,e,t){let n=new Set;if(!e.elements)return [];let o=[];function i(a,l){for(let[d,h]of Object.entries(a)){let m=[...l,d],p=m.join(".");if(!n.has(p)){if(n.add(p),h.binding){let g=or(r,e,m,h,t);g&&o.push(g);}h.elements&&i(h.elements,m);}}}i(e.elements,[]),o.sort((a,l)=>a.identifier.name.localeCompare(l.identifier.name));let s=[],c=new Set;for(let a of o)c.has(a.identifier.url)||(c.add(a.identifier.url),s.push(a));return s}function sr(r,e,t,n,o){if(!n)return;let i={};for(let s of r.getAllElementKeys(n)){let c=[...t,s],a=r.resolveElementSnapshot(e,c);Q(a)?i[s]=ue(r,e,c,a,o):i[s]=de(r,e,c,a,o);}return i}function ar(r){let e=[];for(let t of Object.values(r))"type"in t&&t.type&&e.push(t.type),"binding"in t&&t.binding&&e.push(t.binding);return e}function cr(r,e){return !!(r.base==="Extension"||r.base==="http://hl7.org/fhir/StructureDefinition/Extension"||r.url?.includes("/extension/")||r.url?.includes("-extension")||r.name?.toLowerCase().includes("extension")||r.type==="Extension")}async function fe(r,e,t){if(!e.url)throw new Error("ValueSet URL is required");let n=ce(r,e.package_meta,e.url),o=Oe(r,e.package_meta,e.url);return {identifier:n,description:e.description,concept:o,compose:o?void 0:e.compose}}function De(r,e,t,n){let o=[];e&&o.push(e),t&&o.push(...ar(t)),n&&o.push(...St(n));let i={};for(let a of o)a.url!==r.url&&(i[a.url]=a);let s=new Set(n?.map(a=>a.identifier.url)),c=Object.values(i).filter(a=>tt(r)||!O(a)?true:!s.has(a.url)).sort((a,l)=>a.url.localeCompare(l.url));return c.length>0?c:void 0}function lr(r,e,t){let n=H(e),o;if(e.base&&e.type!=="Element"){let d=r.resolveFs(e.package_meta,r.ensureSpecializationCanonicalUrl(e.base));if(!d)throw new Error(`Base resource not found '${e.base}' for <${e.url}> from ${C(e.package_meta)}`);o=H(d);}let i=sr(r,e,[],e.elements,t),s=Ee(r,e,t),c=De(n,o,i,s),a={identifier:n,base:o,fields:i,nested:s,description:e.description,dependencies:c},l=xt(r,e,t);return [a,...l]}async function ge(r,e,t){let n=lr(r,e,t);if(cr(e,H(e))){let o=n[0];if(!o)throw new Error("Expected schema to be defined");o.metadata={isExtension:true};}return n}var Le=r=>{let e={};for(let t of r){let n=t.identifier.package;e[n]||(e[n]=[]),e[n].push(t);}for(let[t,n]of Object.entries(e)){let o={};for(let s of n)o[JSON.stringify(s.identifier)]=s;let i=Object.values(o);i.sort((s,c)=>s.identifier.name.localeCompare(c.identifier.name)),e[t]=i;}return e},pr=(r,e,t)=>{if(r=structuredClone(r),nt(r)||ot(r)||it(r))return r;for(let n of e.ignoreFields??[]){if(r.fields&&!r.fields[n])throw new Error(`Field ${n} not found`);r.fields&&delete r.fields[n];}return r.dependencies=De(r.identifier,r.base,r.fields,r.nested),r},Rt=(r,e,{resolutionTree:t,logger:n})=>{let o=[];for(let[c,a]of Object.entries(e))for(let[l,d]of Object.entries(a)){let h=r.resolveByUrl(c,l);if(!h)throw new Error(`Schema not found for ${c} ${l}`);let m=pr(h,d);o.push(m);}let i=(c,a)=>{if(c.length===0)return Object.values(a);for(let d of c)a[JSON.stringify(d.identifier)]=d;let l=[];for(let d of c)if(j(d)){if(!d.dependencies)continue;if(d.dependencies.forEach(h=>{let m=r.resolve(h);if(!m)throw new Error(`Schema not found for ${h}`);let p=JSON.stringify(m.identifier);a[p]||l.push(m);}),d.nested)for(let h of d.nested){if(O(h.identifier))continue;let m=JSON.stringify(h.identifier);a[m]||l.push(h);}}return i(l,a)},s=i(o,{});return Me(s,{resolutionTree:t,logger:n})},dr=r=>{let e=r.filter(i=>w(i)||D(i)),t=[];for(let i of e)i.base&&t.push({parent:i.base,child:i.identifier});let n=[...t],o=i=>{let s=t.filter(a=>a.parent.name===i.name).map(a=>a.child),c=[];for(let a of s)c.push(...o(a));return [...s,...c]};for(let i of t){let s=o(i.child);for(let c of s)t.some(a=>a.parent.name===i.parent.name&&a.child.name===c.name)||n.push({parent:i.parent,child:c});}return n},Me=(r,{resolutionTree:e,logger:t})=>{let n={},o=u=>{let f=u.identifier.url,S=u.identifier.package;if(n[f]||(n[f]={}),n[f][u.identifier.package]&&S!=="shared"){let v=JSON.stringify(u.identifier,void 0,2),b=JSON.stringify(n[f][S]?.identifier,void 0,2);if(v!==b)throw new Error(`Duplicate schema: ${v} and ${b}`);return}n[f][S]=u;};for(let u of r)o(u);let i=dr(r),s=u=>n[u.url]?.[u.package],c=(u,f)=>{if(e){let S=e[u]?.[f]?.[0];if(S)return n[f]?.[S.pkg.name]}return n[f]?.[u]},a=u=>i.filter(f=>f.parent.name===u.name).map(f=>f.child),l=u=>{let f=[],S=u;for(;S;){f.push(S);let v=S.base;if(v===void 0)break;let b=s(v);if(!b){t?.warn(`Failed to resolve base type: ${f.map(R=>`${R.identifier.url} (${R.identifier.kind})`).join(", ")}`);return}S=b;}return f},d=u=>{let f=l(u);if(f===void 0)throw new Error(`Failed to resolve base type: ${u.identifier.url} (${u.identifier.kind})`);return f},h=u=>{let f=d(u).find(S=>S.identifier.kind!=="profile");if(!f)throw new Error(`No non-constraint schema found in hierarchy for: ${u.identifier.name}`);return f};return {_schemaIndex:n,_relations:i,collectComplexTypes:()=>r.filter(rt),collectResources:()=>r.filter(w),collectLogicalModels:()=>r.filter(D),collectProfiles:()=>r.filter(oe),resolve:s,resolveByUrl:c,resourceChildren:a,tryHierarchy:l,hierarchy:d,findLastSpecialization:h,findLastSpecializationByIdentifier:u=>{let f=s(u);return f?h(f).identifier:u},flatProfile:u=>{let f=d(u),S=f.filter(P=>P.identifier.kind==="profile"),v=f.find(P=>P.identifier.kind!=="profile");if(!v)throw new Error(`No non-constraint schema found in hierarchy for ${u.identifier.name}`);let b={};for(let P of S.slice().reverse()){let ee=P;if(ee.fields)for(let[te,Ge]of Object.entries(ee.fields))b[te]?b[te]={...b[te],...Ge}:b[te]={...Ge};}let R={};for(let P of S.flatMap(ee=>ee.dependencies??[]))R[P.url]=P;let M=Object.values(R);return {...u,base:v.identifier,fields:b,dependencies:M}},isWithMetaField:u=>{let f=l(u);return f?f.filter(j).some(S=>S.fields?.meta!==void 0):false},exportTree:async u=>{let f={};for(let[v,b]of Object.entries(Le(r))){f[v]={"primitive-type":{},"complex-type":{},resource:{},"value-set":{},nested:{},binding:{},profile:{},logical:{}};for(let R of b)f[v][R.identifier.kind][R.identifier.url]={};}let S=u.endsWith(".yaml")?Tt.stringify(f):JSON.stringify(f,void 0,2);await L.mkdir(E.dirname(u),{recursive:true}),await L.writeFile(u,S);}}};var X=class{manager;options;logger;constructor(e={}){this.options={...e},this.manager=e.manager||CanonicalManager({packages:[],workingDir:"tmp/fhir"}),this.logger=e.logger||N({prefix:"TypeSchema"});}async registerFromPackageMetas(e){let t=e.map(C);return this.logger?.step(`Loading FHIR packages: ${t.join(", ")}`),await this.manager.init(),K(this.manager,{focusedPackages:e})}generateFhirSchemas(e){this.logger?.progress(`Converting ${e.length} StructureDefinitions to FHIRSchemas`);let t=[],n=0,o=0;for(let i of e)try{let s=gt.translate(i);t.push(s),n++,this.logger?.debug(`Converted StructureDefinition: ${i.name||i.id} (${i.resourceType})`);}catch(s){o++,this.logger?.warn(`Failed to convert StructureDefinition ${i.name||i.id}: ${s instanceof Error?s.message:String(s)}`);}return this.logger?.success(`FHIR Schema conversion completed: ${n}/${e.length} successful, ${o} failed`),t}async generateValueSetSchemas(e,t){e.length>0&&this.logger?.debug(`${e.length} ValueSets available for enum extraction`);let n=await K(this.manager,{logger:this.logger}),o=[];if(e.length>0){this.logger?.progress(`Converting ${e.length} ValueSets to TypeSchema`);let i=0,s=0;for(let c of e)try{let a=await fe(n,c,t);a&&(o.push(a),i++,this.logger?.debug(`Converted ValueSet: ${c.name||c.id}`));}catch(a){s++,this.logger?.warn(`Failed to convert ValueSet ${c.name||c.id}: ${a instanceof Error?a.message:String(a)}`);}this.logger?.success(`ValueSet conversion completed: ${i}/${e.length} successful, ${s} failed`);}return o}async generateFromPackage(e,t,n){let o={name:e,version:t||"latest"},i=await this.registerFromPackageMetas([o]),s=await this.generateValueSetSchemas(i.allVs(),n);return [...(await Promise.all(i.allFs().map(async l=>await ge(i,l,n)))).flat(),...s]}};var Y="Use CodeableReference which is not provided by FHIR R4.",fr="Use Availability which is not provided by FHIR R4.",Ft={"hl7.fhir.uv.extensions.r4#1.0.0":{"http://hl7.org/fhir/StructureDefinition/extended-contact-availability":fr,"http://hl7.org/fhir/StructureDefinition/immunization-procedure":Y,"http://hl7.org/fhir/StructureDefinition/specimen-additive":Y,"http://hl7.org/fhir/StructureDefinition/workflow-barrier":Y,"http://hl7.org/fhir/StructureDefinition/workflow-protectiveFactor":Y,"http://hl7.org/fhir/StructureDefinition/workflow-reason":Y},"hl7.fhir.r5.core#5.0.0":{"http://hl7.org/fhir/StructureDefinition/shareablecodesystem":"FIXME: CodeSystem.concept.concept defined by ElementReference. FHIR Schema generator output broken value in it, so we just skip it for now."}},wt=async(r,e)=>{let t=[];for(let n of r.allFs()){let o=C(n.package_meta);if(Ft[o]?.[n.url]){e?.dry_warn(`Skip ${n.url} from ${o}. Reason: ${Ft[o]?.[n.url]}`);continue}t.push(...await ge(r,n,e));}for(let n of r.allVs())t.push(await fe(r,n));return t};var gr={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"},$t=r=>{let e=gr[r];if(e===void 0)throw new Error(`Unknown primitive type ${r}`);return e},Pt=r=>Qe(r),je=r=>r.kind==="profile"?`${k(r)}_profile`:re(r.name),mr=r=>`${je(r)}.ts`,he=r=>`${Pt(r.package)}/${je(r)}`,Be=(r,e=true)=>{if(!r)return;let t=ie(r,e);if(t)return Ve(t)},k=r=>{if(r.kind==="nested"){let e=r.url,t=Be(e,false);if(!t)return "";let[n,o]=t.split("#"),i=ne((o??"").split(".")).join("");return Ve([n,i].join(""))}return Ve(r.name)},Nt=new Set(["class","function","return","if","for","while","const","let","var","import","export","interface"]),W=r=>Nt.has(r)?`"${r}"`:r.includes(" ")||r.includes("-")?`"${r}"`:r,Ve=r=>(Nt.has(r)&&(r=`${r}_`),r.replace(/[- ]/g,"_")),A=(r,e)=>e.startsWith('"')?`${r}[${e}]`:`${r}.${e}`,Et=r=>`(${r.map(e=>`"${e}"`).join(" | ")})`,ye=class extends z{tsImportType(e,...t){this.lineSM(`import type { ${t.join(", ")} } from "${e}"`);}generateFhirPackageIndexFile(e){this.cat("index.ts",()=>{let t=e.flatMap(n=>[{identifier:n.identifier,tsPackageName:je(n.identifier),resourceName:k(n.identifier),nestedTypes:w(n)&&n.nested||D(n)&&n.nested?n.nested.map(o=>k(o.identifier)):[],helpers:w(n)||D(n)?[`is${k(n.identifier)}`]:[]}]).sort((n,o)=>n.resourceName.localeCompare(o.resourceName));t=Array.from(new Map(t.map(n=>[n.resourceName.toLowerCase(),n])).values()).sort((n,o)=>n.resourceName.localeCompare(o.resourceName));for(let n of t)this.debugComment(n.identifier),this.lineSM(`export type { ${[n.resourceName,...n.nestedTypes].join(", ")} } from "./${n.tsPackageName}"`),n.helpers.length>0&&this.lineSM(`export { ${n.helpers.join(", ")} } from "./${n.tsPackageName}"`);});}generateDependenciesImports(e,t){if(t.dependencies){let n=[],o=[];for(let i of t.dependencies)if(["complex-type","resource","logical"].includes(i.kind))n.push({tsPackage:`../${he(i)}`,name:F(i.name),dep:i});else if(O(i)){let s={...i};s.name=Be(i.url),n.push({tsPackage:`../${he(s)}`,name:k(i),dep:i});}else o.push(i);n.sort((i,s)=>i.name.localeCompare(s.name));for(let i of n)this.debugComment(i.dep),this.tsImportType(i.tsPackage,i.name);for(let i of o)this.debugComment("skip:",i);if(this.line(),this.withPrimitiveTypeExtension(t)&&t.identifier.name!=="Element"&&t.dependencies.find(i=>i.name==="Element")===void 0){let i="http://hl7.org/fhir/StructureDefinition/Element",s=e.resolveByUrl(t.identifier.package,i);if(!s)throw new Error(`'${i}' not found for ${t.identifier.package}.`);this.tsImportType(`../${he(s.identifier)}`,"Element");}}}generateComplexTypeReexports(e){let t=e.dependencies?.filter(et).map(n=>({tsPackage:`../${he(n)}`,name:F(n.name)}));if(t&&t.length>0){for(let n of t)this.lineSM(`export type { ${n.name} } from "${n.tsPackage}"`);this.line();}}addFieldExtension(e){let t=W(`_${e}`);this.lineSM(`${t}?: Element`);}generateType(e,t){let n;t.identifier.name==="Reference"?n="Reference<T extends string = string>":(t.identifier.kind,n=k(t.identifier));let o;if(t.base&&(o=`extends ${Be(t.base.url)}`),this.debugComment(t.identifier),!t.fields&&!o&&!w(t)){this.lineSM(`export type ${n} = object`);return}this.curlyBlock(["export","interface",n,o],()=>{if(w(t)||D(t)){let s=[t.identifier];s.push(...e.resourceChildren(t.identifier));let c=this.opts.openResourceTypeSet&&s.length>1?" | string":"";this.lineSM(`resourceType: ${s.sort((a,l)=>a.name.localeCompare(l.name)).map(a=>`"${a.name}"`).join(" | ")}${c}`),this.line();}if(!t.fields)return;let i=Object.entries(t.fields).sort((s,c)=>s[0].localeCompare(c[0]));for(let[s,c]of i){if(U(c))continue;this.debugComment(s,":",c);let a=W(s),l;c.enum?l=Et(c.enum):t.identifier.name==="Reference"&&a==="reference"?l="`${T}/${string}`":c.reference&&c.reference.length>0?l=`Reference<${c.reference.map(p=>`"${p.name}"`).join(" | ")}>`:q(c.type)?l=$t(c.type.name):O(c.type)?l=k(c.type):l=c.type.name;let d=c.required?"":"?",h=c.array?"[]":"";this.lineSM(`${a}${d}: ${l}${h}`),this.withPrimitiveTypeExtension(t)&&q(c.type)&&this.addFieldExtension(s);}});}withPrimitiveTypeExtension(e){if(!this.opts.primitiveTypeExtension||!j(e))return false;for(let t of Object.values(e.fields??{}))if(!U(t)&&q(t.type))return true;return false}generateResourceTypePredicate(e){if(!w(e)&&!D(e))return;let t=k(e.identifier);this.curlyBlock(["export","const",`is${t}`,"=",`(resource: unknown): resource is ${t}`,"=>"],()=>{this.lineSM(`return resource !== null && typeof resource === "object" && (resource as {resourceType: string}).resourceType === "${e.identifier.name}"`);});}generateNestedTypes(e,t){if(t.nested)for(let n of t.nested)this.generateType(e,n),this.line();}generateProfileType(e,t){this.debugComment("flatProfile",t);let n=k(t.identifier);this.debugComment("identifier",t.identifier),this.debugComment("base",t.base),this.curlyBlock(["export","interface",n],()=>{this.lineSM(`__profileUrl: "${t.identifier.url}"`),this.line();for(let[o,i]of Object.entries(t.fields??{})){if(U(i))continue;this.debugComment(o,i);let s=W(o),c;if(i.enum)c=Et(i.enum);else if(i.reference&&i.reference.length>0){let a=e.findLastSpecialization(t);if(!j(a))throw new Error(`Invalid specialization for ${t.identifier}`);let l=a.fields?.[o];if(l===void 0||U(l)||l.reference===void 0)throw new Error(`Invalid field declaration for ${o}`);let d=l.reference.map(m=>m.name),h=i.reference.map(m=>{let p=e.findLastSpecializationByIdentifier(m);return p.name!==m.name?`"${p.name}" /*${m.name}*/`:`'${m.name}'`}).join(" | ");d.length===1&&d[0]==="Resource"&&h!=='"Resource"'?c=`Reference<"Resource" /* ${h} */ >`:c=`Reference<${h}>`;}else if(O(i.type))c=k(i.type);else if(q(i.type))c=$t(i.type.name);else {if(i.type===void 0)throw new Error(`Undefined type for '${o}' field at ${Ze(t)}`);c=i.type.name;}this.lineSM(`${s}${i.required?"":"?"}: ${c}${i.array?"[]":""}`);}}),this.line();}generateAttachProfile(e){let t=k(e.base),n=k(e.identifier),o=Object.entries(e.fields||{}).filter(([i,s])=>s&&J(s)&&s.type!==void 0).map(([i])=>W(i));this.curlyBlock([`export const attach_${n}_to_${t} =`,`(resource: ${t}, profile: ${n}): ${t}`,"=>"],()=>{this.curlyBlock(["return"],()=>{this.line("...resource,"),this.curlyBlock(["meta:"],()=>{this.line(`profile: ['${e.identifier.url}']`);},[","]),o.forEach(i=>{this.line(`${i}: ${A("profile",i)},`);});});}),this.line();}generateExtractProfile(e,t){let n=k(t.base),o=k(t.identifier),i=Object.entries(t.fields||{}).filter(([a,l])=>J(l)&&l.type!==void 0).map(([a])=>a),s=e.findLastSpecialization(t);if(!j(s))throw new Error(`Specialization not found for ${t.identifier.url}`);let c={};this.curlyBlock([`export const extract_${o}_from_${n} =`,`(resource: ${n}): ${o}`,"=>"],()=>{i.forEach(a=>{let l=W(a),d=t.fields?.[a],h=s.fields?.[a];if(!J(d)||!J(h))return;d.required&&!h.required&&this.curlyBlock([`if (${A("resource",l)} === undefined)`],()=>this.lineSM(`throw new Error("'${l}' is required for ${t.identifier.url}")`));let m=d?.reference?.map(g=>g.name),p=h?.reference?.map(g=>g.name);if(m&&p&&m.length!==p.length){let g=`reference_is_valid_${l}`;this.curlyBlock(["const",g,"=","(ref?: Reference)","=>"],()=>{this.line("return !ref"),this.indentBlock(()=>{p.forEach(u=>{this.line(`|| ref.reference?.startsWith('${u}/')`);}),this.line(";");});});let y=d?.required?"":`!${A("resource",l)} || `;d.array?y+=`${A("resource",l)}.every( (ref) => ${g}(ref) )`:y+=`!${g}(${A("resource",l)})`,this.curlyBlock(["if (",y,")"],()=>{this.lineSM(`throw new Error("'${a}' has different references in profile and specialization")`);}),this.line(),c[a]=true;}}),this.curlyBlock(["return"],()=>{this.line(`__profileUrl: '${t.identifier.url}',`),i.forEach(a=>{let l=W(a);c[a]?this.line(`${l}:`,`${A("resource",l)} as ${o}['${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(e,t),this.generateComplexTypeReexports(t),this.generateNestedTypes(e,t),this.comment("CanonicalURL:",t.identifier.url),this.generateType(e,t),this.generateResourceTypePredicate(t);else if(oe(t)){let n=e.flatProfile(t);this.generateDependenciesImports(e,n),this.comment("CanonicalURL:",t.identifier.url),this.generateProfileType(e,n),this.generateAttachProfile(n),this.generateExtractProfile(e,n);}else throw new Error(`Profile generation not implemented for kind: ${t.identifier.kind}`)});}async generate(e){let t=[...e.collectComplexTypes(),...e.collectResources(),...e.collectLogicalModels(),...this.opts.generateProfile?e.collectProfiles().filter(o=>e.isWithMetaField(o)):[]],n=Le(t);this.cd("/",()=>{for(let[o,i]of Object.entries(n)){let s=Pt(o);this.cd(s,()=>{for(let c of i)this.generateResourceModule(e,c);this.generateFhirPackageIndexFile(i);});}});}};var Ot=r=>{let e=r.replace(/[^a-zA-Z0-9\-_.@#()]/g,"");return e.length===0?"unknown":e},yr=async(r,e)=>{e.info("Cleaning outputs...");try{e.info(`Clean ${r.outputDir}`),T.rmSync(r.outputDir,{recursive:!0,force:!0}),r.typeSchemaOutputDir&&(e.info(`Clean ${r.typeSchemaOutputDir}`),T.rmSync(r.typeSchemaOutputDir,{recursive:!0,force:!0})),r.exportTypeTree&&(e.info(`Clean ${r.exportTypeTree}`),T.rmSync(r.exportTypeTree,{recursive:!0,force:!0}));}catch(t){e.warn(`Error cleaning output directory: ${t instanceof Error?t.message:String(t)}`);}},Sr=async(r,e,t)=>{await L.mkdir(e,{recursive:true}),t.info(`Writing TypeSchema files to ${e}/...`);let n={};for(let o of r){let i={name:o.identifier.package,version:o.identifier.version},s=Ot(C(i)),c=Ot(`${o.identifier.name}(${ie(o.identifier.url)})`),a=JSON.stringify(o,null,2),l=E.join(e,s,c);n[l]||(n[l]=[]),n[l]?.some(d=>d===a)||n[l].push(a);}for(let[o,i]of Object.entries(n))await Promise.all(i.map(async(s,c)=>{let a;c===0?a=`${o}.typeschema.json`:a=`${o}-${c}.typeschema.json`,await L.mkdir(E.dirname(a),{recursive:true}),await L.writeFile(a,s);}));},br=async(r,e,t)=>{t.info(`Writing TypeSchema files to: ${e}`),await L.mkdir(E.dirname(e),{recursive:true}),t.info(`Writing TypeSchemas to one file ${e}...`);for(let n of r){let o=JSON.stringify(n,null,2);await L.appendFile(e,`${o}
7
- `);}},Cr=async(r,e,t)=>{if(e.typeSchemaOutputDir)try{E.extname(e.typeSchemaOutputDir)===".ndjson"?await br(r,e.typeSchemaOutputDir,t):await Sr(r,e.typeSchemaOutputDir,t),t.info("Writing TypeSchema - DONE");}catch(n){if(t.error("Failed to write TypeSchema output",n instanceof Error?n:new Error(String(n))),e.throwException)throw n}},Z=class{schemas=[];options;generators=new Map;logger;packages=[];progressCallback;typeSchemaConfig;constructor(e={}){this.options={outputDir:e.outputDir||"./generated",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,exportTypeTree:e.exportTypeTree,treeShake:e.treeShake},this.typeSchemaConfig=e.typeSchemaConfig,this.logger=e.logger||N({prefix:"API",level:e.logLevel});}fromPackage(e,t){let n=Re({name:e,version:t||"latest"});return this.packages.push(n),this}fromPackageRef(e){return this.packages.push(e),this}fromSchemas(e){return this.logger.debug(`Adding ${e.length} TypeSchemas to generation`),this.schemas=[...this.schemas,...e],this}typescript(e){let o={...{...{logger:this.logger,outputDir:E.join(this.options.outputDir,"/types"),tabSize:4,withDebugComment:false,commentLinePrefix:"//",generateProfile:true},openResourceTypeSet:false,primitiveTypeExtension:true},...Object.fromEntries(Object.entries(e).filter(([s,c])=>c!==void 0))},i=new ye(o);return this.generators.set("typescript",i),this.logger.debug(`Configured TypeScript generator (${JSON.stringify(o,void 0,2)})`),this}csharp(e,t){let n=new se({outputDir:E.join(this.options.outputDir,"/types"),staticSourceDir:t??void 0,targetNamespace:e,logger:new _({prefix:"C#",timestamp:true,suppressLoggingLevel:[]})});return this.generators.set("C#",n),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(e);return this}setLogLevel(e){return this.logger?.setLevel(e),this}throwException(e=true){return this.options.throwException=e,this}cleanOutput(e=true){return this.options.cleanOutput=e,this}writeTypeTree(e){return this.options.exportTypeTree=e,this}treeShake(e){return this.options.treeShake=e,this}writeTypeSchemas(e){return this.options.typeSchemaOutputDir=e,this}async generate(){let e=performance.now(),t={success:false,outputDir:this.options.outputDir,filesGenerated:[],errors:[],warnings:[],duration:0};this.logger.debug(`Starting generation with ${this.generators.size} generators`);try{this.options.cleanOutput&&yr(this.options,this.logger),this.logger.info("Initialize Canonical Manager");let n=CanonicalManager({packages:this.packages,workingDir:".codegen-cache/canonical-manager-cache"}),o=await n.init(),i=Object.values(o),s=await K(n,{logger:this.logger,focusedPackages:i}),c=await wt(s,this.logger);await Cr(c,this.options,this.logger);let a={resolutionTree:s.resolutionTree(),logger:this.logger},l=Me(c,a);this.options.treeShake&&(l=Rt(l,this.options.treeShake,a)),this.options.exportTypeTree&&await l.exportTree(this.options.exportTypeTree),this.logger.debug(`Executing ${this.generators.size} generators`),await this.executeGenerators(t,l),this.logger.info("Generation completed successfully"),t.success=t.errors.length===0,this.logger.debug(`Generation completed: ${t.filesGenerated.length} files`);}catch(n){if(this.logger.error("Code generation failed",n instanceof Error?n:new Error(String(n))),t.errors.push(n instanceof Error?n.message:String(n)),this.options.throwException)throw n}return {...t,success:t.errors.length===0,duration:performance.now()-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 executeGenerators(e,t){for(let[n,o]of this.generators.entries()){this.logger.info(`Generating ${n}...`);try{await o.generate(t);let i=o.writtenFiles();e.filesGenerated.push(...i.map(s=>s.absPath)),this.logger.info(`Generating ${n} finished successfully`);}catch(i){if(e.errors.push(`${n} generator failed: ${i instanceof Error?i.message:String(i)}`),this.options.throwException)throw i}}}};var Ue={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:""},be=["atomic-codegen.config.ts","atomic-codegen.config","atomic-codegen.config.json",".atomic-codegenrc","atomic-codegen.json",".atomic-codegen.json","codegen.config.json","codegen.json"],He=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 n=e;n.outputDir!==void 0&&typeof n.outputDir!="string"&&t.errors.push({path:"outputDir",message:"outputDir must be a string",value:n.outputDir});let o=["verbose","overwrite","validate","cache"];for(let i of o)n[i]!==void 0&&typeof n[i]!="boolean"&&t.errors.push({path:i,message:`${i} must be a boolean`,value:n[i]});if(n.typescript!==void 0){let i=this.validateTypeScriptConfig(n.typescript);t.errors.push(...i);}if(n.typeSchema!==void 0){let i=this.validateTypeSchemaConfig(n.typeSchema);t.errors.push(...i);}return n.packages!==void 0&&(Array.isArray(n.packages)?n.packages.forEach((i,s)=>{typeof i!="string"&&t.errors.push({path:`packages[${s}]`,message:"package name must be a string",value:i});}):t.errors.push({path:"packages",message:"packages must be an array",value:n.packages})),n.files!==void 0&&(Array.isArray(n.files)?n.files.forEach((i,s)=>{typeof i!="string"&&t.errors.push({path:`files[${s}]`,message:"file path must be a string",value:i});}):t.errors.push({path:"files",message:"files must be an array",value:n.files})),t.valid=t.errors.length===0,t.valid&&(t.config=n),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 n=e;n.moduleFormat!==void 0&&(["esm","cjs"].includes(n.moduleFormat)||t.push({path:"typescript.moduleFormat",message:'moduleFormat must be "esm" or "cjs"',value:n.moduleFormat})),n.namingConvention!==void 0&&(["PascalCase","camelCase"].includes(n.namingConvention)||t.push({path:"typescript.namingConvention",message:'namingConvention must be "PascalCase" or "camelCase"',value:n.namingConvention}));let o=["generateIndex","includeDocuments","strictMode","includeProfiles","includeExtensions","includeCodeSystems","includeOperations","generateValueSets","includeValueSetHelpers"];for(let i of o)n[i]!==void 0&&typeof n[i]!="boolean"&&t.push({path:`typescript.${i}`,message:`${i} must be a boolean`,value:n[i]});if(n.validatorOptions!==void 0){let i=this.validateValidatorOptions(n.validatorOptions);t.push(...i);}if(n.guardOptions!==void 0){let i=this.validateGuardOptions(n.guardOptions);t.push(...i);}if(n.profileOptions!==void 0){let i=this.validateProfileOptions(n.profileOptions);t.push(...i);}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 n=e,o=["includeCardinality","includeTypes","includeConstraints","includeInvariants","validateRequired","allowAdditional","strictValidation","collectMetrics","generateAssertions","generatePartialValidators","optimizePerformance","includeJSDoc","generateCompositeValidators"];for(let i of o)n[i]!==void 0&&typeof n[i]!="boolean"&&t.push({path:`typescript.validatorOptions.${i}`,message:`${i} must be a boolean`,value:n[i]});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 n=e;n.targetTSVersion!==void 0&&(["3.8","4.0","4.5","5.0"].includes(n.targetTSVersion)||t.push({path:"typescript.guardOptions.targetTSVersion",message:'targetTSVersion must be one of: "3.8", "4.0", "4.5", "5.0"',value:n.targetTSVersion}));let o=["includeRuntimeValidation","includeErrorMessages","treeShakeable","strictGuards","includeNullChecks","verbose"];for(let i of o)n[i]!==void 0&&typeof n[i]!="boolean"&&t.push({path:`typescript.guardOptions.${i}`,message:`${i} must be a boolean`,value:n[i]});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 n=e;n.generateKind!==void 0&&(["interface","type","both"].includes(n.generateKind)||t.push({path:"typescript.profileOptions.generateKind",message:'generateKind must be "interface", "type", or "both"',value:n.generateKind})),n.subfolder!==void 0&&typeof n.subfolder!="string"&&t.push({path:"typescript.profileOptions.subfolder",message:"subfolder must be a string",value:n.subfolder});let o=["includeConstraints","includeDocumentation","strictMode"];for(let i of o)n[i]!==void 0&&typeof n[i]!="boolean"&&t.push({path:`typescript.profileOptions.${i}`,message:`${i} must be a boolean`,value:n[i]});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 n=e,o=["enablePersistence","validateCached","forceRegenerate","shareCache"];for(let s of o)n[s]!==void 0&&typeof n[s]!="boolean"&&t.push({path:`typeSchema.${s}`,message:`${s} must be a boolean`,value:n[s]});let i=["cacheDir","cacheKeyPrefix"];for(let s of i)n[s]!==void 0&&typeof n[s]!="string"&&t.push({path:`typeSchema.${s}`,message:`${s} must be a string`,value:n[s]});if(n.maxAge!==void 0&&(typeof n.maxAge!="number"||n.maxAge<=0)&&t.push({path:"typeSchema.maxAge",message:"maxAge must be a positive number",value:n.maxAge}),n.profiles!==void 0)if(typeof n.profiles!="object"||n.profiles===null)t.push({path:"typeSchema.profiles",message:"profiles must be an object",value:n.profiles});else {let s=n.profiles;s.autoDetect!==void 0&&typeof s.autoDetect!="boolean"&&t.push({path:"typeSchema.profiles.autoDetect",message:"autoDetect must be a boolean",value:s.autoDetect});}return t}},Ae=class{validator=new He;async autoload(e=process.cwd()){let t=await this.findConfigFile(e);return t?this.loadFromFile(t):{...Ue}}async loadFromFile(e){try{let t;if(e.endsWith(".ts")||e.endsWith("")){let i=await import(resolve(e));t=i.default||i;}else {let o=await readFile(e,"utf-8");t=JSON.parse(o);}let n=this.validator.validate(t);if(!n.valid){let o=n.errors.map(i=>`${i.path}: ${i.message}`).join(`
6
+ `);for(let n of t)this.line(this.opts.commentLinePrefix,n);}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/atomic-ehr/codegen","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,n){this.line(`${e.filter(Boolean).join(" ")} {`),this.indent(),t(),this.deindent(),this.line(`}${n?.filter(Boolean).join(" ")??""}`);}squareBlock(e,t,n){this.line(`${e.filter(Boolean).join(" ")} [`),this.indent(),t(),this.deindent(),this.line(`]${n?.filter(Boolean).join(" ")??""}`);}};var ie=(r,e=true)=>{let t=r.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),t};var C=r=>`${r.name}#${r.version}`,oe=r=>`${r.name}@${r.version}`;var Ie=(r,e)=>(e||(e={name:"undefined",version:"undefined"}),{...r,package_meta:r.package_meta||e,name:r.name,url:r.url,base:r.base}),q=r=>r?.kind==="primitive-type",D=r=>r?.kind==="nested",et=r=>r?.kind==="complex-type",tt=r=>r?.kind==="profile";var j=r=>r?.identifier.kind==="resource"||r?.identifier.kind==="complex-type"||r?.identifier.kind==="logical",rt=r=>r?.identifier.kind==="complex-type",$=r=>r?.identifier.kind==="resource",nt=r=>r?.identifier.kind==="primitive-type",O=r=>r?.identifier.kind==="logical",se=r=>r?.identifier.kind==="profile";function it(r){return r?.identifier.kind==="binding"}function ot(r){return r?.identifier.kind==="value-set"}var J=r=>r?r.choices===void 0:false,U=r=>r?r.choices!==void 0:false,st=(r,e)=>{if(!r.url)throw new Error("ValueSet must have a URL");if(!r.name)throw new Error("ValueSet must have a name");return {...r,package_meta:r.package_meta||e,name:r.name,url:r.url}};var at={"!":"Not","<=":"LessOrEqual",">=":"GreaterOrEqual","<":"Less",">":"Greater","=":"Equal","-":"Dash","+":"Plus","*":"Asterisk","/":"Slash","%":"Percent","&":"And","|":"Or","^":"Xor","~":"Tilde","?":"Question",".":"Dot"};function jt(r){return r.split("-").map(e=>w(e)).join("-")}function Ut(r){let e=r;for(let t in at)e=e.replaceAll(t,at[t]??"");return e}function At(r){let e=Number(r[0]);return Number.isInteger(e)&&!Number.isNaN(e)?`_${r}`:r}function ct(r){let e=jt(r);return e=At(e),e=Ut(e),e=w(e),e}function P(r){return w(Ye(r.replaceAll(".","-")))}var Ht={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"},_t=["Reference","Expression"],Gt=r=>r.required?["required"]:[],zt=r=>{let e=ut(dt(r.identifier));return w(e)},Wt=r=>r.base?`: ${r.base.name}`:"",qt=(r,e=true)=>{if(!r)return;let t=r.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),P(t)},dt=r=>{if(r.kind==="nested"){let e=r.url,t=qt(e,false);if(!t)return "";let[n,o]=t.split("#"),i=ne((o??"").split(".")).join("");return P([n,i].join(""))}return P(r.name)},Jt=r=>_t.includes(r),ut=r=>Jt(r)?`Resource${r}`:r,ae=class extends z{enums={};constructor(e){super({tabSize:4,withDebugComment:false,commentLinePrefix:"//",...e});}async generate(e){let t=e.collectComplexTypes(),n=e.collectResources(),o=Array.from(new Set(n.map(i=>P(i.identifier.package))));this.generateAllFiles(t,n,o),this.copyStaticFiles();}generateAllFiles(e,t,n){this.generateUsingFile(n),this.generateBaseTypes(e),this.generateResources(t),this.generateEnumFiles(n),this.generateResourceDictionaries(t,n),this.generateHelperFile();}generateType(e,t){let n=zt(e),o=Wt(e);this.curlyBlock(["public","class",n,o],()=>{this.generateFields(e,t),this.generateNestedTypes(e,t),this.line(),this.includeHelperMethods();}),this.line();}generateFields(e,t){if(!e.fields)return;let n=Object.entries(e.fields).sort(([o],[i])=>o.localeCompare(i));for(let[o,i]of n)this.generateField(o,i,t);}generateNestedTypes(e,t){if(!(!("nested"in e)||!e.nested)){this.line();for(let n of e.nested)this.generateType(n,t);}}generateField(e,t,n){try{if(U(t))return;let o=this.buildFieldDeclaration(e,t,n);this.line(...o);}catch(o){this.logger()?.error(`Error processing field ${e}: ${o.message}`);}}buildFieldDeclaration(e,t,n){let o=this.determineFieldType(e,t,n),i=Gt(t),s=re(e);return ["public",...i,o,s,"{ get; set; }"].filter(Boolean)}determineFieldType(e,t,n){let o=this.getBaseTypeName(t);"enum"in t&&t.enum&&(o=this.registerAndGetEnumType(e,t,n)),o=ut(o);let i="",s=t.required?"":"?",c=t.array?"[]":"";return `${i}${o}${c}${s}`}getBaseTypeName(e){if("type"in e){let t=e.type.name.toString();return e.type.kind==="nested"?t=dt(e.type):e.type.kind==="primitive-type"&&(t=Ht[e.type.name]??"string"),t}return ""}registerAndGetEnumType(e,t,n){let i=`${P(t.binding?.name??e)}Enum`;return this.enums[n]||(this.enums[n]={}),t.enum&&(this.enums[n][i]=t.enum),i}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.opts.targetNamespace,...e.map(n=>`${this.opts.targetNamespace}.${n}`)];for(let n of t)this.lineSM("global","using",n);}generateBaseTypes(e){this.cd("/",async()=>{this.cat("base.cs",()=>{this.generateDisclaimer(),this.line(),this.lineSM("namespace",this.opts.targetNamespace);for(let t of e){let n=P(t.identifier.package);this.generateType(t,n);}});});}generateResources(e){for(let t of e)this.generateResourceFile(t);}generateResourceFile(e){let t=P(e.identifier.package);this.cd(`/${t}`,async()=>{this.cat(`${e.identifier.name}.cs`,()=>{this.generateDisclaimer(),this.line(),this.lineSM("namespace",`${this.opts.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.opts.targetNamespace}.${e}`);for(let[n,o]of Object.entries(t))this.generateEnum(n,o);}generateEnum(e,t){this.curlyBlock(["public","enum",e],()=>{for(let n of t)this.line(`[Description("${n}")]`),this.line(`${ct(n)},`);}),this.line();}generateResourceDictionaries(e,t){this.cd("/",async()=>{for(let n of t){let o=e.filter(i=>P(i.identifier.package)===n);if(o.length===0)return;this.cat(`${n}ResourceDictionary.cs`,()=>{this.generateDisclaimer(),this.line(),this.lineSM(`namespace ${this.opts.targetNamespace}`),this.generateResourceDictionaryClass(n,o);});}});}generateResourceDictionaryClass(e,t){this.curlyBlock(["public","static","class","ResourceDictionary"],()=>{this.curlyBlock(["public static readonly Dictionary<Type, string> Map = new()"],()=>{for(let n of t){let o=n.identifier.name;this.line(`{ typeof(${e}.${o}), "${o}" },`);}}),this.lineSM();});}copyStaticFiles(){if(!this.opts.staticSourceDir)return;let e=F__default.resolve(this.opts.staticSourceDir);T__default.cpSync(e,this.opts.outputDir,{recursive:true});}generateHelperFile(){let e="src/api/writer-generator/csharp/Helper.cs",t=F__default.join(this.opts.outputDir,"Helper.cs");T__default.copyFileSync(e,t);}};var Fe=r=>r!==null&&typeof r=="object"&&r.resourceType==="CodeSystem";var ce=r=>r!==null&&typeof r=="object"&&r.resourceType==="ValueSet";var Kt=async(r,e)=>{let n=(await r.packageJson(e.name)).dependencies;return n!==void 0?Object.entries(n).map(([o,i])=>({name:o,version:i})):[]},mt=r=>({pkg:r,canonicalResolution:{},fhirSchemas:{},valueSets:{}}),ht=async(r,e,t,n,o)=>{let i=C(e);if(o?.info(`${" ".repeat(t*2)}+ ${i}`),n[i])return n[i];let s=mt(e);for(let a of await r.search({package:e})){let l=a.url;if(!l||!(isStructureDefinition(a)||ce(a)||Fe(a)))continue;let p=l;s.canonicalResolution[p]&&o?.dry_warn(`Duplicate canonical URL: ${p} at ${i}.`),s.canonicalResolution[p]=[{deep:t,pkg:e,pkgId:i,resource:a}];}let c=await Kt(r,e);for(let a of c){let{canonicalResolution:l}=await ht(r,a,t+1,n,o);for(let[p,h]of Object.entries(l)){let m=p;s.canonicalResolution[m]=[...s.canonicalResolution[m]||[],...h];}}for(let a of Object.values(s.canonicalResolution))a.sort((l,p)=>l.deep-p.deep);return n[i]=s,s},ft=(r,e,t)=>{let n=Object.values(r).flatMap(o=>o.canonicalResolution[e]);if(!n)throw new Error(`No canonical resolution found for ${e} in any package`);return n[0]?.resource},K=async(r,{logger:e,fallbackPackageForNameResolution:t,focusedPackages:n})=>{let o=n??await r.packages(),i={};for(let d of o)await ht(r,d,0,i,e);for(let{pkg:d,canonicalResolution:g}of Object.values(i)){let y=C(d);if(!i[y])throw new Error(`Package ${y} not found`);let u=0;e?.info(`FHIR Schema conversion for '${C(d)}' begins...`);for(let[f,S]of Object.entries(g)){let v=S[0];if(!v)throw new Error("Resource not found");let b=v.resource,R=v.pkg;if(isStructureDefinition(b)){let M=Ie(gt.translate(b),R);u++,i[y].fhirSchemas[M.url]=M;}if(ce(b)){let M=st(b,R);i[y].valueSets[M.url]=M;}}e?.info(`FHIR Schema conversion for '${C(d)}' completed: ${u} successful`);}let s=(d,g)=>i[C(d)]?.fhirSchemas[g]||t&&i[C(t)]?.fhirSchemas[g],c=(d,g)=>i[C(d)]?.valueSets[g]||t&&i[C(t)]?.valueSets[g],a=d=>d.match(/^[a-zA-Z0-9]+$/)&&`http://hl7.org/fhir/StructureDefinition/${d}`||d,l=(d,g)=>{let y=s(d,g);if(y===void 0)throw new Error(`Failed to resolve FHIR Schema: '${g}'`);let u=[y];for(;y?.base;){let f=y.package_meta,S=a(y.base);if(y=s(f,S),y===void 0)throw new Error(`Failed to resolve FHIR Schema base for '${g}'. Problem: '${S}' from '${C(f)}'`);u.push(y);}return u};return {...r,testAppendFs(d){let g=Ie(d),y=C(g.package_meta);i[y]||(i[y]=mt(g.package_meta)),i[y].fhirSchemas[g.url]=g;},resolveFs:s,resolveFsGenealogy:l,resolveFsSpecializations:(d,g)=>l(d,g).filter(y=>y.derivation==="specialization"),ensureSpecializationCanonicalUrl:a,resolveSd:(d,g)=>{let y=ft(i,g);if(isStructureDefinition(y))return y},allFs:()=>Object.values(i).flatMap(d=>Object.values(d.fhirSchemas)),allVs:()=>Object.values(i).flatMap(d=>Object.values(d.valueSets)),resolveVs:c,resolveAny:d=>ft(i,d),resolveElementSnapshot:(d,g)=>{let y=l(d.package_meta,d.url),u=Qt(y,g);return Xt(u)},getAllElementKeys:d=>{let g=new Set;for(let[y,u]of Object.entries(d)){g.add(y);for(let f of u?.choices||[])d[f]||g.add(f);}return Array.from(g)},resolver:i,resolutionTree:()=>{let d={};for(let[g,y]of Object.entries(i)){let u=y.pkg.name;d[u]={};for(let[f,S]of Object.entries(y.canonicalResolution)){let v=f;d[u][v]=[];for(let b of S)d[u][v].push({deep:b.deep,pkg:b.pkg});}}return d}}};var Qt=(r,e)=>{let[t,...n]=e;return t===void 0?[]:r.map(o=>{if(!o.elements)return;let i=o.elements?.[t];for(let s of n)i=i?.elements?.[s];return i}).filter(o=>o!==void 0)};function Xt(r){let e=r.reverse(),t=Object.assign({},...e);return t.elements=void 0,t}function $e(r){let e=r.split("|")[0];return e||r}function Yt(r){return r.split("|")[1]}function Zt(r){return r.derivation==="constraint"?"profile":r.kind==="primitive-type"?"primitive-type":r.kind==="complex-type"?"complex-type":r.kind==="resource"?"resource":r.kind==="logical"?"logical":"resource"}function A(r){return {kind:Zt(r),package:r.package_meta.name,version:r.package_meta.version,name:r.name,url:r.url}}var er=r=>{let e=r.split("/"),t=e[e.length-1];return t&&t.length>0?t.split(/[-_]/).map(n=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join(""):r};function le(r,e,t){let n=$e(t),o=er(n),i={package_meta:{name:"missing_valuesets",version:Yt(n)||"0.0.0"},id:t},s=r.resolveVs(e,n)||i,c=s?.id&&!/^[a-zA-Z0-9_-]{20,}$/.test(s.id)?s.id:o;return {kind:"value-set",package:s.package_meta.name,version:s.package_meta.version,name:c,url:n}}function pe(r,e,t){let n=e.join("."),[o,i,s]=t?[{name:"shared",version:"1.0.0"},t,`urn:fhir:binding:${t}`]:[r.package_meta,`${r.name}.${n}_binding`,`${r.url}#${n}_binding`];return {kind:"binding",package:o.name,version:o.version,name:i,url:s}}function de(r,e,t,n){let o={};if(e.derivation==="constraint"){let a=r.resolveFsSpecializations(e.package_meta,e.url).map(l=>Pe(r,l,n)).filter(l=>l!==void 0).flat();for(let l of a.reverse())o[l.identifier.name]=l.identifier.url;}let i=t.join("."),s=o[i]??`${e.url}#${i}`;return {kind:"nested",package:e.package_meta.name,version:e.package_meta.version,name:i,url:s}}function yt(r,e,t){let n=[];for(let[o,i]of Object.entries(t)){let s=[...e,o];Q(i)&&n.push([s,i]),i.elements&&n.push(...yt(r,s,i.elements));}return n}function tr(r,e,t,n,o){let i={};for(let[s,c]of Object.entries(n)){let a=[...t,s],l=r.resolveElementSnapshot(e,a);Q(l)?i[s]=fe(r,e,a,l,o):i[s]=ue(r,e,a,l,o);}return i}function Pe(r,e,t){if(!e.elements)return;let n=yt(e,[],e.elements).filter(([i,s])=>s.elements&&Object.keys(s.elements).length>0),o=[];for(let[i,s]of n){let c=de(r,e,i,t),a;s.type==="BackboneElement"||!s.type?a="BackboneElement":a=s.type;let l=r.ensureSpecializationCanonicalUrl(a),p=r.resolveFs(e.package_meta,l);if(!p)throw new Error(`Could not resolve base type ${a}`);let h={kind:"complex-type",package:p.package_meta.name,version:p.package_meta.version,name:a,url:l},m=tr(r,e,i,s.elements??{},t),d={identifier:c,base:h,fields:m};o.push(d);}return o.sort((i,s)=>i.identifier.url.localeCompare(s.identifier.url)),o.length===0?void 0:o}function St(r){let e=[];for(let t of r){t.base&&e.push(t.base);for(let n of Object.values(t.fields||{}))"type"in n&&n.type&&e.push(n.type),"binding"in n&&n.binding&&e.push(n.binding);}return e}function bt(r,e,t){let n=t[t.length-1];if(!n)throw new Error(`Internal error: fieldName is missing for path ${t.join("/")}`);let o=t.slice(0,-1),i=r.resolveFsGenealogy(e.package_meta,e.url).flatMap(s=>{if(o.length===0)return s.required||[];if(!s.elements)return [];let c=s;for(let a of o)c=c?.elements?.[a];return c?.required||[]});return new Set(i).has(n)}function Ct(r,e,t){let n=t[t.length-1];if(!n)throw new Error(`Internal error: fieldName is missing for path ${t.join("/")}`);let o=t.slice(0,-1),i=r.resolveFsGenealogy(e.package_meta,e.url).flatMap(s=>{if(o.length===0)return s.excluded||[];if(!s.elements)return [];let c=s;for(let a of o)c=c?.elements?.[a];return c?.excluded||[]});return new Set(i).has(n)}var rr=(r,e,t)=>{if(t.refers)return t.refers.map(n=>{let o=r.ensureSpecializationCanonicalUrl(n),i=r.resolveFs(e.package_meta,o);if(!i)throw new Error(`Failed to resolve fs for ${o}`);return A(i)})};function Ee(r,e,t,n,o){if(n.elementReference){let i=n.elementReference.slice(1).filter((s,c)=>c%2===1);return de(r,e,i,o)}else if(n.type){let i=r.ensureSpecializationCanonicalUrl(n.type),s=r.resolveFs(e.package_meta,i);if(!s)throw new Error(`Could not resolve field type: '${n.type}' (from '${e.url}' in '${C(e.package_meta)}')`);return A(s)}else {if(n.choices)return;if(e.derivation==="constraint")return;throw o?.error(`Can't recognize element type '${e.url}' (${e.derivation}) at '${t.join(".")}': ${JSON.stringify(n,void 0,2)}`),new Error("Unrecognized element type")}}var ue=(r,e,t,n,o)=>{let i,s;n.binding&&(i=pe(e,t,n.binding.bindingName),n.binding.strength==="required"&&n.type==="code"&&(s=Ne(r,e,n,o)));let c=Ee(r,e,t,n,o);return c||o?.warn(`Field type not found for '${e.url}#${t.join(".")}' (${e.derivation})`),{type:c,required:bt(r,e,t),excluded:Ct(r,e,t),reference:rr(r,e,n),array:n.array||false,min:n.min,max:n.max,choices:n.choices,choiceOf:n.choiceOf,binding:i,enum:s}};function Q(r){let e=r.type==="BackboneElement",t=r.type==="Element"&&r.elements!==void 0&&Object.keys(r.elements).length>0,n=r.type===void 0&&r.choiceOf===void 0&&r.elements!==void 0&&Object.keys(r.elements).length>0;return e||t||n}function fe(r,e,t,n,o){return {type:de(r,e,t,o),array:n.array||false,required:bt(r,e,t),excluded:Ct(r,e,t)}}function De(r,e,t,n){let o=$e(t)||t,i=r.resolveVs(e,o);if(i)return ir(r,i)}function ir(r,e,t){if(e.expansion?.contains)return e.expansion.contains.filter(o=>o.code!==void 0).map(o=>(nr(o.code),{code:o.code,display:o.display,system:o.system}));let n=[];if(e.compose?.include){for(let o of e.compose.include)if(o.concept)for(let i of o.concept)n.push({system:o.system,code:i.code,display:i.display});else if(o.system&&!o.filter)try{let i=r.resolveAny(o.system);if(i?.concept){let s=(c,a)=>{for(let l of c)n.push({system:a,code:l.code,display:l.display}),l.concept&&s(l.concept,a);};s(i.concept,o.system);}}catch{}}return n.length>0?n:void 0}var vt=100;function Ne(r,e,t,n){if(!t.binding)return;let o=t.binding.strength,i=t.binding.valueSet;if(!i||!(o==="required"||o==="extensible"&&(t.type==="code"||t.type==="Coding")||o==="preferred"&&(t.type==="code"||t.type==="Coding")))return;let c=De(r,e.package_meta,i);if(!c||c.length===0)return;let a=c.map(l=>l.code).filter(l=>l&&typeof l=="string"&&l.trim().length>0);if(a.length>vt){n?.dry_warn(`Value set ${i} has ${a.length} which is more than ${vt} codes, which may cause issues with code generation.`);return}return a.length>0?a:void 0}function or(r,e,t,n,o){if(!n.binding?.valueSet)return;let i=pe(e,t,n.binding.bindingName),s=Ee(r,e,t,n,o),c=le(r,e.package_meta,n.binding.valueSet),a=[];s&&a.push(s),a.push(c);let l=Ne(r,e,n,o);return {identifier:i,type:s,valueset:c,strength:n.binding.strength,enum:l,dependencies:a}}function kt(r,e,t){let n=new Set;if(!e.elements)return [];let o=[];function i(a,l){for(let[p,h]of Object.entries(a)){let m=[...l,p],d=m.join(".");if(!n.has(d)){if(n.add(d),h.binding){let g=or(r,e,m,h,t);g&&o.push(g);}h.elements&&i(h.elements,m);}}}i(e.elements,[]),o.sort((a,l)=>a.identifier.name.localeCompare(l.identifier.name));let s=[],c=new Set;for(let a of o)c.has(a.identifier.url)||(c.add(a.identifier.url),s.push(a));return s}function sr(r,e,t,n,o){if(!n)return;let i={};for(let s of r.getAllElementKeys(n)){let c=[...t,s],a=r.resolveElementSnapshot(e,c);Q(a)?i[s]=fe(r,e,c,a,o):i[s]=ue(r,e,c,a,o);}return i}function ar(r){let e=[];for(let t of Object.values(r))"type"in t&&t.type&&e.push(t.type),"binding"in t&&t.binding&&e.push(t.binding);return e}function cr(r,e){return !!(r.base==="Extension"||r.base==="http://hl7.org/fhir/StructureDefinition/Extension"||r.url?.includes("/extension/")||r.url?.includes("-extension")||r.name?.toLowerCase().includes("extension")||r.type==="Extension")}async function ge(r,e,t){if(!e.url)throw new Error("ValueSet URL is required");let n=le(r,e.package_meta,e.url),o=De(r,e.package_meta,e.url);return {identifier:n,description:e.description,concept:o,compose:o?void 0:e.compose}}function Oe(r,e,t,n){let o=[];e&&o.push(e),t&&o.push(...ar(t)),n&&o.push(...St(n));let i={};for(let a of o)a.url!==r.url&&(i[a.url]=a);let s=new Set(n?.map(a=>a.identifier.url)),c=Object.values(i).filter(a=>tt(r)||!D(a)?true:!s.has(a.url)).sort((a,l)=>a.url.localeCompare(l.url));return c.length>0?c:void 0}function lr(r,e,t){let n=A(e),o;if(e.base&&e.type!=="Element"){let p=r.resolveFs(e.package_meta,r.ensureSpecializationCanonicalUrl(e.base));if(!p)throw new Error(`Base resource not found '${e.base}' for <${e.url}> from ${C(e.package_meta)}`);o=A(p);}let i=sr(r,e,[],e.elements,t),s=Pe(r,e,t),c=Oe(n,o,i,s),a={identifier:n,base:o,fields:i,nested:s,description:e.description,dependencies:c},l=kt(r,e,t);return [a,...l]}async function me(r,e,t){let n=lr(r,e,t);if(cr(e,A(e))){let o=n[0];if(!o)throw new Error("Expected schema to be defined");o.metadata={isExtension:true};}return n}var Le=r=>{let e={};for(let t of r){let n=t.identifier.package;e[n]||(e[n]=[]),e[n].push(t);}for(let[t,n]of Object.entries(e)){let o={};for(let s of n)o[JSON.stringify(s.identifier)]=s;let i=Object.values(o);i.sort((s,c)=>s.identifier.name.localeCompare(c.identifier.name)),e[t]=i;}return e},pr=(r,e,t)=>{if(r=structuredClone(r),nt(r)||ot(r)||it(r))return r;for(let n of e.ignoreFields??[]){if(r.fields&&!r.fields[n])throw new Error(`Field ${n} not found`);r.fields&&delete r.fields[n];}return r.dependencies=Oe(r.identifier,r.base,r.fields,r.nested),r},Rt=(r,e,{resolutionTree:t,logger:n})=>{let o=[];for(let[c,a]of Object.entries(e))for(let[l,p]of Object.entries(a)){let h=r.resolveByUrl(c,l);if(!h)throw new Error(`Schema not found for ${c} ${l}`);let m=pr(h,p);o.push(m);}let i=(c,a)=>{if(c.length===0)return Object.values(a);for(let p of c)a[JSON.stringify(p.identifier)]=p;let l=[];for(let p of c)if(j(p)){if(!p.dependencies)continue;if(p.dependencies.forEach(h=>{let m=r.resolve(h);if(!m)throw new Error(`Schema not found for ${h}`);let d=JSON.stringify(m.identifier);a[d]||l.push(m);}),p.nested)for(let h of p.nested){if(D(h.identifier))continue;let m=JSON.stringify(h.identifier);a[m]||l.push(h);}}return i(l,a)},s=i(o,{});return Me(s,{resolutionTree:t,logger:n})},dr=r=>{let e=r.filter(i=>$(i)||O(i)),t=[];for(let i of e)i.base&&t.push({parent:i.base,child:i.identifier});let n=[...t],o=i=>{let s=t.filter(a=>a.parent.name===i.name).map(a=>a.child),c=[];for(let a of s)c.push(...o(a));return [...s,...c]};for(let i of t){let s=o(i.child);for(let c of s)t.some(a=>a.parent.name===i.parent.name&&a.child.name===c.name)||n.push({parent:i.parent,child:c});}return n},Me=(r,{resolutionTree:e,logger:t})=>{let n={},o=u=>{let f=u.identifier.url,S=u.identifier.package;if(n[f]||(n[f]={}),n[f][u.identifier.package]&&S!=="shared"){let v=JSON.stringify(u.identifier,void 0,2),b=JSON.stringify(n[f][S]?.identifier,void 0,2);if(v!==b)throw new Error(`Duplicate schema: ${v} and ${b}`);return}n[f][S]=u;};for(let u of r)o(u);let i=dr(r),s=u=>n[u.url]?.[u.package],c=(u,f)=>{if(e){let S=e[u]?.[f]?.[0];if(S)return n[f]?.[S.pkg.name]}return n[f]?.[u]},a=u=>i.filter(f=>f.parent.name===u.name).map(f=>f.child),l=u=>{let f=[],S=u;for(;S;){f.push(S);let v=S.base;if(v===void 0)break;let b=s(v);if(!b){t?.warn(`Failed to resolve base type: ${f.map(R=>`${R.identifier.url} (${R.identifier.kind})`).join(", ")}`);return}S=b;}return f},p=u=>{let f=l(u);if(f===void 0)throw new Error(`Failed to resolve base type: ${u.identifier.url} (${u.identifier.kind})`);return f},h=u=>{let f=p(u).find(S=>S.identifier.kind!=="profile");if(!f)throw new Error(`No non-constraint schema found in hierarchy for: ${u.identifier.name}`);return f};return {_schemaIndex:n,_relations:i,collectComplexTypes:()=>r.filter(rt),collectResources:()=>r.filter($),collectLogicalModels:()=>r.filter(O),collectProfiles:()=>r.filter(se),resolve:s,resolveByUrl:c,resourceChildren:a,tryHierarchy:l,hierarchy:p,findLastSpecialization:h,findLastSpecializationByIdentifier:u=>{let f=s(u);return f?h(f).identifier:u},flatProfile:u=>{let f=p(u),S=f.filter(E=>E.identifier.kind==="profile"),v=f.find(E=>E.identifier.kind!=="profile");if(!v)throw new Error(`No non-constraint schema found in hierarchy for ${u.identifier.name}`);let b={};for(let E of S.slice().reverse()){let ee=E;if(ee.fields)for(let[te,Ge]of Object.entries(ee.fields))b[te]?b[te]={...b[te],...Ge}:b[te]={...Ge};}let R={};for(let E of S.flatMap(ee=>ee.dependencies??[]))R[E.url]=E;let M=Object.values(R);return {...u,base:v.identifier,fields:b,dependencies:M}},isWithMetaField:u=>{let f=l(u);return f?f.filter(j).some(S=>S.fields?.meta!==void 0):false},exportTree:async u=>{let f={};for(let[v,b]of Object.entries(Le(r))){f[v]={"primitive-type":{},"complex-type":{},resource:{},"value-set":{},nested:{},binding:{},profile:{},logical:{}};for(let R of b)f[v][R.identifier.kind][R.identifier.url]={};}let S=u.endsWith(".yaml")?Tt.stringify(f):JSON.stringify(f,void 0,2);await L.mkdir(F.dirname(u),{recursive:true}),await L.writeFile(u,S);}}};var X=class{manager;options;logger;constructor(e={}){this.options={...e},this.manager=e.manager||CanonicalManager({packages:[],workingDir:"tmp/fhir"}),this.logger=e.logger||N({prefix:"TypeSchema"});}async registerFromPackageMetas(e){let t=e.map(C);return this.logger?.step(`Loading FHIR packages: ${t.join(", ")}`),await this.manager.init(),K(this.manager,{focusedPackages:e})}generateFhirSchemas(e){this.logger?.progress(`Converting ${e.length} StructureDefinitions to FHIRSchemas`);let t=[],n=0,o=0;for(let i of e)try{let s=gt.translate(i);t.push(s),n++,this.logger?.debug(`Converted StructureDefinition: ${i.name||i.id} (${i.resourceType})`);}catch(s){o++,this.logger?.warn(`Failed to convert StructureDefinition ${i.name||i.id}: ${s instanceof Error?s.message:String(s)}`);}return this.logger?.success(`FHIR Schema conversion completed: ${n}/${e.length} successful, ${o} failed`),t}async generateValueSetSchemas(e,t){e.length>0&&this.logger?.debug(`${e.length} ValueSets available for enum extraction`);let n=await K(this.manager,{logger:this.logger}),o=[];if(e.length>0){this.logger?.progress(`Converting ${e.length} ValueSets to TypeSchema`);let i=0,s=0;for(let c of e)try{let a=await ge(n,c,t);a&&(o.push(a),i++,this.logger?.debug(`Converted ValueSet: ${c.name||c.id}`));}catch(a){s++,this.logger?.warn(`Failed to convert ValueSet ${c.name||c.id}: ${a instanceof Error?a.message:String(a)}`);}this.logger?.success(`ValueSet conversion completed: ${i}/${e.length} successful, ${s} failed`);}return o}async generateFromPackage(e,t,n){let o={name:e,version:t||"latest"},i=await this.registerFromPackageMetas([o]),s=await this.generateValueSetSchemas(i.allVs(),n);return [...(await Promise.all(i.allFs().map(async l=>await me(i,l,n)))).flat(),...s]}};var Y="Use CodeableReference which is not provided by FHIR R4.",fr="Use Availability which is not provided by FHIR R4.",Ft={"hl7.fhir.uv.extensions.r4#1.0.0":{"http://hl7.org/fhir/StructureDefinition/extended-contact-availability":fr,"http://hl7.org/fhir/StructureDefinition/immunization-procedure":Y,"http://hl7.org/fhir/StructureDefinition/specimen-additive":Y,"http://hl7.org/fhir/StructureDefinition/workflow-barrier":Y,"http://hl7.org/fhir/StructureDefinition/workflow-protectiveFactor":Y,"http://hl7.org/fhir/StructureDefinition/workflow-reason":Y},"hl7.fhir.r5.core#5.0.0":{"http://hl7.org/fhir/StructureDefinition/shareablecodesystem":"FIXME: CodeSystem.concept.concept defined by ElementReference. FHIR Schema generator output broken value in it, so we just skip it for now."}},wt=async(r,e)=>{let t=[];for(let n of r.allFs()){let o=C(n.package_meta);if(Ft[o]?.[n.url]){e?.dry_warn(`Skip ${n.url} from ${o}. Reason: ${Ft[o]?.[n.url]}`);continue}t.push(...await me(r,n,e));}for(let n of r.allVs())t.push(await ge(r,n));return t};var gr={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"},$t=r=>{let e=gr[r];if(e===void 0)throw new Error(`Unknown primitive type ${r}`);return e},Et=r=>Qe(r),je=r=>r.kind==="profile"?`${x(r)}_profile`:re(r.name),mr=r=>`${je(r)}.ts`,ye=r=>`${Et(r.package)}/${je(r)}`,Be=(r,e=true)=>{if(!r)return;let t=ie(r,e);if(t)return Ve(t)},x=r=>{if(r.kind==="nested"){let e=r.url,t=Be(e,false);if(!t)return "";let[n,o]=t.split("#"),i=ne((o??"").split(".")).join("");return Ve([n,i].join(""))}return Ve(r.name)},Nt=new Set(["class","function","return","if","for","while","const","let","var","import","export","interface"]),W=r=>Nt.has(r)?`"${r}"`:r.includes(" ")||r.includes("-")?`"${r}"`:r,Ve=r=>(Nt.has(r)&&(r=`${r}_`),r.replace(/[- ]/g,"_")),H=(r,e)=>e.startsWith('"')?`${r}[${e}]`:`${r}.${e}`,Pt=r=>`(${r.map(e=>`"${e}"`).join(" | ")})`,Se=class extends z{tsImportType(e,...t){this.lineSM(`import type { ${t.join(", ")} } from "${e}"`);}generateFhirPackageIndexFile(e){this.cat("index.ts",()=>{let t=e.flatMap(n=>[{identifier:n.identifier,tsPackageName:je(n.identifier),resourceName:x(n.identifier),nestedTypes:$(n)&&n.nested||O(n)&&n.nested?n.nested.map(o=>x(o.identifier)):[],helpers:$(n)||O(n)?[`is${x(n.identifier)}`]:[]}]).sort((n,o)=>n.resourceName.localeCompare(o.resourceName));t=Array.from(new Map(t.map(n=>[n.resourceName.toLowerCase(),n])).values()).sort((n,o)=>n.resourceName.localeCompare(o.resourceName));for(let n of t)this.debugComment(n.identifier),this.lineSM(`export type { ${[n.resourceName,...n.nestedTypes].join(", ")} } from "./${n.tsPackageName}"`),n.helpers.length>0&&this.lineSM(`export { ${n.helpers.join(", ")} } from "./${n.tsPackageName}"`);});}generateDependenciesImports(e,t){if(t.dependencies){let n=[],o=[];for(let i of t.dependencies)if(["complex-type","resource","logical"].includes(i.kind))n.push({tsPackage:`../${ye(i)}`,name:w(i.name),dep:i});else if(D(i)){let s={...i};s.name=Be(i.url),n.push({tsPackage:`../${ye(s)}`,name:x(i),dep:i});}else o.push(i);n.sort((i,s)=>i.name.localeCompare(s.name));for(let i of n)this.debugComment(i.dep),this.tsImportType(i.tsPackage,i.name);for(let i of o)this.debugComment("skip:",i);if(this.line(),this.withPrimitiveTypeExtension(t)&&t.identifier.name!=="Element"&&t.dependencies.find(i=>i.name==="Element")===void 0){let i="http://hl7.org/fhir/StructureDefinition/Element",s=e.resolveByUrl(t.identifier.package,i);if(!s)throw new Error(`'${i}' not found for ${t.identifier.package}.`);this.tsImportType(`../${ye(s.identifier)}`,"Element");}}}generateComplexTypeReexports(e){let t=e.dependencies?.filter(et).map(n=>({tsPackage:`../${ye(n)}`,name:w(n.name)}));if(t&&t.length>0){for(let n of t)this.lineSM(`export type { ${n.name} } from "${n.tsPackage}"`);this.line();}}addFieldExtension(e){let t=W(`_${e}`);this.lineSM(`${t}?: Element`);}generateType(e,t){let n;t.identifier.name==="Reference"?n="Reference<T extends string = string>":(t.identifier.kind,n=x(t.identifier));let o;if(t.base&&(o=`extends ${Be(t.base.url)}`),this.debugComment(t.identifier),!t.fields&&!o&&!$(t)){this.lineSM(`export type ${n} = object`);return}this.curlyBlock(["export","interface",n,o],()=>{if($(t)||O(t)){let s=[t.identifier];s.push(...e.resourceChildren(t.identifier));let c=this.opts.openResourceTypeSet&&s.length>1?" | string":"";this.lineSM(`resourceType: ${s.sort((a,l)=>a.name.localeCompare(l.name)).map(a=>`"${a.name}"`).join(" | ")}${c}`),this.line();}if(!t.fields)return;let i=Object.entries(t.fields).sort((s,c)=>s[0].localeCompare(c[0]));for(let[s,c]of i){if(U(c))continue;this.debugComment(s,":",c);let a=W(s),l;c.enum?l=Pt(c.enum):t.identifier.name==="Reference"&&a==="reference"?l="`${T}/${string}`":c.reference&&c.reference.length>0?l=`Reference<${c.reference.map(d=>`"${d.name}"`).join(" | ")}>`:q(c.type)?l=$t(c.type.name):D(c.type)?l=x(c.type):l=c.type.name;let p=c.required?"":"?",h=c.array?"[]":"";this.lineSM(`${a}${p}: ${l}${h}`),this.withPrimitiveTypeExtension(t)&&q(c.type)&&this.addFieldExtension(s);}});}withPrimitiveTypeExtension(e){if(!this.opts.primitiveTypeExtension||!j(e))return false;for(let t of Object.values(e.fields??{}))if(!U(t)&&q(t.type))return true;return false}generateResourceTypePredicate(e){if(!$(e)&&!O(e))return;let t=x(e.identifier);this.curlyBlock(["export","const",`is${t}`,"=",`(resource: unknown): resource is ${t}`,"=>"],()=>{this.lineSM(`return resource !== null && typeof resource === "object" && (resource as {resourceType: string}).resourceType === "${e.identifier.name}"`);});}generateNestedTypes(e,t){if(t.nested)for(let n of t.nested)this.generateType(e,n),this.line();}generateProfileType(e,t){this.debugComment("flatProfile",t);let n=x(t.identifier);this.debugComment("identifier",t.identifier),this.debugComment("base",t.base),this.curlyBlock(["export","interface",n],()=>{this.lineSM(`__profileUrl: "${t.identifier.url}"`),this.line();for(let[o,i]of Object.entries(t.fields??{})){if(U(i))continue;this.debugComment(o,i);let s=W(o),c;if(i.enum)c=Pt(i.enum);else if(i.reference&&i.reference.length>0){let a=e.findLastSpecialization(t);if(!j(a))throw new Error(`Invalid specialization for ${t.identifier}`);let l=a.fields?.[o];if(l===void 0||U(l)||l.reference===void 0)throw new Error(`Invalid field declaration for ${o}`);let p=l.reference.map(m=>m.name),h=i.reference.map(m=>{let d=e.findLastSpecializationByIdentifier(m);return d.name!==m.name?`"${d.name}" /*${m.name}*/`:`'${m.name}'`}).join(" | ");p.length===1&&p[0]==="Resource"&&h!=='"Resource"'?c=`Reference<"Resource" /* ${h} */ >`:c=`Reference<${h}>`;}else if(D(i.type))c=x(i.type);else if(q(i.type))c=$t(i.type.name);else {if(i.type===void 0)throw new Error(`Undefined type for '${o}' field at ${Ze(t)}`);c=i.type.name;}this.lineSM(`${s}${i.required?"":"?"}: ${c}${i.array?"[]":""}`);}}),this.line();}generateAttachProfile(e){let t=x(e.base),n=x(e.identifier),o=Object.entries(e.fields||{}).filter(([i,s])=>s&&J(s)&&s.type!==void 0).map(([i])=>W(i));this.curlyBlock([`export const attach_${n}_to_${t} =`,`(resource: ${t}, profile: ${n}): ${t}`,"=>"],()=>{this.curlyBlock(["return"],()=>{this.line("...resource,"),this.curlyBlock(["meta:"],()=>{this.line(`profile: ['${e.identifier.url}']`);},[","]),o.forEach(i=>{this.line(`${i}: ${H("profile",i)},`);});});}),this.line();}generateExtractProfile(e,t){let n=x(t.base),o=x(t.identifier),i=Object.entries(t.fields||{}).filter(([a,l])=>J(l)&&l.type!==void 0).map(([a])=>a),s=e.findLastSpecialization(t);if(!j(s))throw new Error(`Specialization not found for ${t.identifier.url}`);let c={};this.curlyBlock([`export const extract_${o}_from_${n} =`,`(resource: ${n}): ${o}`,"=>"],()=>{i.forEach(a=>{let l=W(a),p=t.fields?.[a],h=s.fields?.[a];if(!J(p)||!J(h))return;p.required&&!h.required&&this.curlyBlock([`if (${H("resource",l)} === undefined)`],()=>this.lineSM(`throw new Error("'${l}' is required for ${t.identifier.url}")`));let m=p?.reference?.map(g=>g.name),d=h?.reference?.map(g=>g.name);if(m&&d&&m.length!==d.length){let g=`reference_is_valid_${l}`;this.curlyBlock(["const",g,"=","(ref?: Reference)","=>"],()=>{this.line("return !ref"),this.indentBlock(()=>{d.forEach(u=>{this.line(`|| ref.reference?.startsWith('${u}/')`);}),this.line(";");});});let y=p?.required?"":`!${H("resource",l)} || `;p.array?y+=`${H("resource",l)}.every( (ref) => ${g}(ref) )`:y+=`!${g}(${H("resource",l)})`,this.curlyBlock(["if (",y,")"],()=>{this.lineSM(`throw new Error("'${a}' has different references in profile and specialization")`);}),this.line(),c[a]=true;}}),this.curlyBlock(["return"],()=>{this.line(`__profileUrl: '${t.identifier.url}',`),i.forEach(a=>{let l=W(a);c[a]?this.line(`${l}:`,`${H("resource",l)} as ${o}['${l}'],`):this.line(`${l}:`,`${H("resource",l)},`);});});});}generateResourceModule(e,t){this.cat(`${mr(t.identifier)}`,()=>{if(this.generateDisclaimer(),["complex-type","resource","logical"].includes(t.identifier.kind))this.generateDependenciesImports(e,t),this.generateComplexTypeReexports(t),this.generateNestedTypes(e,t),this.comment("CanonicalURL:",t.identifier.url),this.generateType(e,t),this.generateResourceTypePredicate(t);else if(se(t)){let n=e.flatProfile(t);this.generateDependenciesImports(e,n),this.comment("CanonicalURL:",t.identifier.url),this.generateProfileType(e,n),this.generateAttachProfile(n),this.generateExtractProfile(e,n);}else throw new Error(`Profile generation not implemented for kind: ${t.identifier.kind}`)});}async generate(e){let t=[...e.collectComplexTypes(),...e.collectResources(),...e.collectLogicalModels(),...this.opts.generateProfile?e.collectProfiles().filter(o=>e.isWithMetaField(o)):[]],n=Le(t);this.cd("/",()=>{for(let[o,i]of Object.entries(n)){let s=Et(o);this.cd(s,()=>{for(let c of i)this.generateResourceModule(e,c);this.generateFhirPackageIndexFile(i);});}});}};var Dt=r=>{let e=r.replace(/[^a-zA-Z0-9\-_.@#()]/g,"");return e.length===0?"unknown":e},yr=async(r,e)=>{e.info("Cleaning outputs...");try{e.info(`Clean ${r.outputDir}`),T.rmSync(r.outputDir,{recursive:!0,force:!0}),r.typeSchemaOutputDir&&(e.info(`Clean ${r.typeSchemaOutputDir}`),T.rmSync(r.typeSchemaOutputDir,{recursive:!0,force:!0})),r.exportTypeTree&&(e.info(`Clean ${r.exportTypeTree}`),T.rmSync(r.exportTypeTree,{recursive:!0,force:!0}));}catch(t){e.warn(`Error cleaning output directory: ${t instanceof Error?t.message:String(t)}`);}},Sr=async(r,e,t)=>{await L.mkdir(e,{recursive:true}),t.info(`Writing TypeSchema files to ${e}/...`);let n={};for(let o of r){let i={name:o.identifier.package,version:o.identifier.version},s=Dt(C(i)),c=Dt(`${o.identifier.name}(${ie(o.identifier.url)})`),a=JSON.stringify(o,null,2),l=F.join(e,s,c);n[l]||(n[l]=[]),n[l]?.some(p=>p===a)||n[l].push(a);}for(let[o,i]of Object.entries(n))await Promise.all(i.map(async(s,c)=>{let a;c===0?a=`${o}.typeschema.json`:a=`${o}-${c}.typeschema.json`,await L.mkdir(F.dirname(a),{recursive:true}),await L.writeFile(a,s);}));},br=async(r,e,t)=>{t.info(`Writing TypeSchema files to: ${e}`),await L.mkdir(F.dirname(e),{recursive:true}),t.info(`Writing TypeSchemas to one file ${e}...`);for(let n of r){let o=JSON.stringify(n,null,2);await L.appendFile(e,`${o}
7
+ `);}},Cr=async(r,e,t)=>{if(e.typeSchemaOutputDir)try{F.extname(e.typeSchemaOutputDir)===".ndjson"?await br(r,e.typeSchemaOutputDir,t):await Sr(r,e.typeSchemaOutputDir,t),t.info("Writing TypeSchema - DONE");}catch(n){if(t.error("Failed to write TypeSchema output",n instanceof Error?n:new Error(String(n))),e.throwException)throw n}},Z=class{schemas=[];options;generators=new Map;logger;packages=[];localStructurePackages=[];localTgzArchives=[];progressCallback;typeSchemaConfig;constructor(e={}){this.options={outputDir:e.outputDir||"./generated",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,exportTypeTree:e.exportTypeTree,treeShake:e.treeShake},this.typeSchemaConfig=e.typeSchemaConfig,this.logger=e.logger||N({prefix:"API",level:e.logLevel});}fromPackage(e,t){let n=oe({name:e,version:t||"latest"});return this.packages.push(n),this}fromPackageRef(e){return this.packages.push(e),this}localStructureDefinitions(e){return this.localStructurePackages.push(e),this}localTgzPackage(e){return this.localTgzArchives.push(F.resolve(e)),this}fromSchemas(e){return this.logger.debug(`Adding ${e.length} TypeSchemas to generation`),this.schemas=[...this.schemas,...e],this}typescript(e){let o={...{...{logger:this.logger,outputDir:F.join(this.options.outputDir,"/types"),tabSize:4,withDebugComment:false,commentLinePrefix:"//",generateProfile:true},openResourceTypeSet:false,primitiveTypeExtension:true},...Object.fromEntries(Object.entries(e).filter(([s,c])=>c!==void 0))},i=new Se(o);return this.generators.set("typescript",i),this.logger.debug(`Configured TypeScript generator (${JSON.stringify(o,void 0,2)})`),this}csharp(e,t){let n=new ae({outputDir:F.join(this.options.outputDir,"/types"),staticSourceDir:t??void 0,targetNamespace:e,logger:new _({prefix:"C#",timestamp:true,suppressLoggingLevel:[]})});return this.generators.set("C#",n),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(e);return this}setLogLevel(e){return this.logger?.setLevel(e),this}throwException(e=true){return this.options.throwException=e,this}cleanOutput(e=true){return this.options.cleanOutput=e,this}writeTypeTree(e){return this.options.exportTypeTree=e,this}treeShake(e){return this.options.treeShake=e,this}writeTypeSchemas(e){return this.options.typeSchemaOutputDir=e,this}async generate(){let e=performance.now(),t={success:false,outputDir:this.options.outputDir,filesGenerated:[],errors:[],warnings:[],duration:0};this.logger.debug(`Starting generation with ${this.generators.size} generators`);try{this.options.cleanOutput&&yr(this.options,this.logger),this.logger.info("Initialize Canonical Manager");let n=this.options.manager||CanonicalManager({packages:this.packages,workingDir:".codegen-cache/canonical-manager-cache"});if(this.localStructurePackages.length>0)for(let p of this.localStructurePackages)this.logger.info(`Registering local StructureDefinitions for ${p.package.name}@${p.package.version}`),await n.addLocalPackage({name:p.package.name,version:p.package.version,path:p.path,dependencies:p.dependencies?.map(h=>oe(h))});for(let p of this.localTgzArchives)this.logger.info(`Registering local tgz package: ${p}`),await n.addTgzPackage({archivePath:p});let o=await n.init(),i=Object.values(o),s=await K(n,{logger:this.logger,focusedPackages:i}),c=await wt(s,this.logger);await Cr(c,this.options,this.logger);let a={resolutionTree:s.resolutionTree(),logger:this.logger},l=Me(c,a);this.options.treeShake&&(l=Rt(l,this.options.treeShake,a)),this.options.exportTypeTree&&await l.exportTree(this.options.exportTypeTree),this.logger.debug(`Executing ${this.generators.size} generators`),await this.executeGenerators(t,l),this.logger.info("Generation completed successfully"),t.success=t.errors.length===0,this.logger.debug(`Generation completed: ${t.filesGenerated.length} files`);}catch(n){if(this.logger.error("Code generation failed",n instanceof Error?n:new Error(String(n))),t.errors.push(n instanceof Error?n.message:String(n)),this.options.throwException)throw n}return {...t,success:t.errors.length===0,duration:performance.now()-e}}reset(){return this.schemas=[],this.generators.clear(),this.progressCallback=void 0,this.packages=[],this.localStructurePackages=[],this.localTgzArchives=[],this}getSchemas(){return [...this.schemas]}getGenerators(){return Array.from(this.generators.keys())}async executeGenerators(e,t){for(let[n,o]of this.generators.entries()){this.logger.info(`Generating ${n}...`);try{await o.generate(t);let i=o.writtenFiles();e.filesGenerated.push(...i.map(s=>s.absPath)),this.logger.info(`Generating ${n} finished successfully`);}catch(i){if(e.errors.push(`${n} generator failed: ${i instanceof Error?i.message:String(i)}`),this.options.throwException)throw i}}}};var Ue={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:""},Ce=["atomic-codegen.config.ts","atomic-codegen.config","atomic-codegen.config.json",".atomic-codegenrc","atomic-codegen.json",".atomic-codegen.json","codegen.config.json","codegen.json"],Ae=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 n=e;n.outputDir!==void 0&&typeof n.outputDir!="string"&&t.errors.push({path:"outputDir",message:"outputDir must be a string",value:n.outputDir});let o=["verbose","overwrite","validate","cache"];for(let i of o)n[i]!==void 0&&typeof n[i]!="boolean"&&t.errors.push({path:i,message:`${i} must be a boolean`,value:n[i]});if(n.typescript!==void 0){let i=this.validateTypeScriptConfig(n.typescript);t.errors.push(...i);}if(n.typeSchema!==void 0){let i=this.validateTypeSchemaConfig(n.typeSchema);t.errors.push(...i);}return n.packages!==void 0&&(Array.isArray(n.packages)?n.packages.forEach((i,s)=>{typeof i!="string"&&t.errors.push({path:`packages[${s}]`,message:"package name must be a string",value:i});}):t.errors.push({path:"packages",message:"packages must be an array",value:n.packages})),n.files!==void 0&&(Array.isArray(n.files)?n.files.forEach((i,s)=>{typeof i!="string"&&t.errors.push({path:`files[${s}]`,message:"file path must be a string",value:i});}):t.errors.push({path:"files",message:"files must be an array",value:n.files})),t.valid=t.errors.length===0,t.valid&&(t.config=n),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 n=e;n.moduleFormat!==void 0&&(["esm","cjs"].includes(n.moduleFormat)||t.push({path:"typescript.moduleFormat",message:'moduleFormat must be "esm" or "cjs"',value:n.moduleFormat})),n.namingConvention!==void 0&&(["PascalCase","camelCase"].includes(n.namingConvention)||t.push({path:"typescript.namingConvention",message:'namingConvention must be "PascalCase" or "camelCase"',value:n.namingConvention}));let o=["generateIndex","includeDocuments","strictMode","includeProfiles","includeExtensions","includeCodeSystems","includeOperations","generateValueSets","includeValueSetHelpers"];for(let i of o)n[i]!==void 0&&typeof n[i]!="boolean"&&t.push({path:`typescript.${i}`,message:`${i} must be a boolean`,value:n[i]});if(n.validatorOptions!==void 0){let i=this.validateValidatorOptions(n.validatorOptions);t.push(...i);}if(n.guardOptions!==void 0){let i=this.validateGuardOptions(n.guardOptions);t.push(...i);}if(n.profileOptions!==void 0){let i=this.validateProfileOptions(n.profileOptions);t.push(...i);}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 n=e,o=["includeCardinality","includeTypes","includeConstraints","includeInvariants","validateRequired","allowAdditional","strictValidation","collectMetrics","generateAssertions","generatePartialValidators","optimizePerformance","includeJSDoc","generateCompositeValidators"];for(let i of o)n[i]!==void 0&&typeof n[i]!="boolean"&&t.push({path:`typescript.validatorOptions.${i}`,message:`${i} must be a boolean`,value:n[i]});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 n=e;n.targetTSVersion!==void 0&&(["3.8","4.0","4.5","5.0"].includes(n.targetTSVersion)||t.push({path:"typescript.guardOptions.targetTSVersion",message:'targetTSVersion must be one of: "3.8", "4.0", "4.5", "5.0"',value:n.targetTSVersion}));let o=["includeRuntimeValidation","includeErrorMessages","treeShakeable","strictGuards","includeNullChecks","verbose"];for(let i of o)n[i]!==void 0&&typeof n[i]!="boolean"&&t.push({path:`typescript.guardOptions.${i}`,message:`${i} must be a boolean`,value:n[i]});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 n=e;n.generateKind!==void 0&&(["interface","type","both"].includes(n.generateKind)||t.push({path:"typescript.profileOptions.generateKind",message:'generateKind must be "interface", "type", or "both"',value:n.generateKind})),n.subfolder!==void 0&&typeof n.subfolder!="string"&&t.push({path:"typescript.profileOptions.subfolder",message:"subfolder must be a string",value:n.subfolder});let o=["includeConstraints","includeDocumentation","strictMode"];for(let i of o)n[i]!==void 0&&typeof n[i]!="boolean"&&t.push({path:`typescript.profileOptions.${i}`,message:`${i} must be a boolean`,value:n[i]});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 n=e,o=["enablePersistence","validateCached","forceRegenerate","shareCache"];for(let s of o)n[s]!==void 0&&typeof n[s]!="boolean"&&t.push({path:`typeSchema.${s}`,message:`${s} must be a boolean`,value:n[s]});let i=["cacheDir","cacheKeyPrefix"];for(let s of i)n[s]!==void 0&&typeof n[s]!="string"&&t.push({path:`typeSchema.${s}`,message:`${s} must be a string`,value:n[s]});if(n.maxAge!==void 0&&(typeof n.maxAge!="number"||n.maxAge<=0)&&t.push({path:"typeSchema.maxAge",message:"maxAge must be a positive number",value:n.maxAge}),n.profiles!==void 0)if(typeof n.profiles!="object"||n.profiles===null)t.push({path:"typeSchema.profiles",message:"profiles must be an object",value:n.profiles});else {let s=n.profiles;s.autoDetect!==void 0&&typeof s.autoDetect!="boolean"&&t.push({path:"typeSchema.profiles.autoDetect",message:"autoDetect must be a boolean",value:s.autoDetect});}return t}},He=class{validator=new Ae;async autoload(e=process.cwd()){let t=await this.findConfigFile(e);return t?this.loadFromFile(t):{...Ue}}async loadFromFile(e){try{let t;if(e.endsWith(".ts")||e.endsWith("")){let i=await import(resolve(e));t=i.default||i;}else {let o=await readFile(e,"utf-8");t=JSON.parse(o);}let n=this.validator.validate(t);if(!n.valid){let o=n.errors.map(i=>`${i.path}: ${i.message}`).join(`
8
8
  `);throw new Error(`Configuration validation failed:
9
- ${o}`)}if(!n.config)throw new Error("Invalid configuration");return this.mergeWithDefaults(n.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 be){let n=resolve(e,t);if(existsSync(n))return n}return null}mergeWithDefaults(e){return {...Ue,...e,typescript:{...Ue.typescript,...e.typescript}}}},Tr=new Ae;async function Ce(r){return Tr.autoload(r)}var Lt={command:"generate",describe:"Generate code based on configuration file settings",builder:r=>r.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 r=>{if(r._.length>1){let s=r._.slice(1).join(" ");I(`Invalid syntax: 'atomic-codegen generate ${s}'
9
+ ${o}`)}if(!n.config)throw new Error("Invalid configuration");return this.mergeWithDefaults(n.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 Ce){let n=resolve(e,t);if(existsSync(n))return n}return null}mergeWithDefaults(e){return {...Ue,...e,typescript:{...Ue.typescript,...e.typescript}}}},Tr=new He;async function ve(r){return Tr.autoload(r)}var Lt={command:"generate",describe:"Generate code based on configuration file settings",builder:r=>r.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 r=>{if(r._.length>1){let s=r._.slice(1).join(" ");I(`Invalid syntax: 'atomic-codegen generate ${s}'
10
10
 
11
11
  The CLI has been simplified and no longer uses subcommands.
12
12
 
@@ -14,7 +14,7 @@ The CLI has been simplified and no longer uses subcommands.
14
14
  \u274C Old: atomic-codegen generate typescript
15
15
 
16
16
  All generation settings are now configured in your config file.
17
- Create an atomic-codegen.config.ts file to get started.`),process.exit(1);}let e=process.cwd(),t=await Fr(e);if(!t){let s=be.map(c=>` - ${c}`).join(`
17
+ Create an atomic-codegen.config.ts file to get started.`),process.exit(1);}let e=process.cwd(),t=await Fr(e);if(!t){let s=Ce.map(c=>` - ${c}`).join(`
18
18
  `);I(`No configuration file found. Please create one of the following files in your project root:
19
19
  ${s}
20
20
 
@@ -27,12 +27,12 @@ export default defineConfig({
27
27
  typescript: {
28
28
  generateIndex: true
29
29
  }
30
- });`),process.exit(1);}let n=await Ce(e),o=r.verbose??n.verbose??false,i=N({prefix:"Generate"});try{We("Starting generation from config"),o&&(i.info(`Config file: ${t}`),i.info(`Output directory: ${n.outputDir||"./generated"}`),i.info(`Packages: ${n.packages?.length||0}`),i.info(`Files: ${n.files?.length||0}`),i.info(`TypeScript generation: ${n.typescript?"enabled":"disabled"}`));let s=new Z({outputDir:n.outputDir||"./generated",overwrite:n.overwrite??!0,cache:n.cache??!0,typeSchemaConfig:n.typeSchema,logger:i});if(n.packages&&n.packages.length>0){i.info(`Loading packages from config: ${n.packages.join(", ")}`);for(let a of n.packages){let[l,d]=a.includes("@")?a.split("@"):[a,void 0];s.fromPackage(l,d);}}else throw n.files&&n.files.length>0?(i.info(`Loading files from config: ${n.files.join(", ")}`),new Error("Not Implemented")):new Error("No data source specified in config. Please configure 'packages' or 'files' in your config file.");if(n.typescript)throw new Error("Not Implemented");if(!n.typescript)throw new Error("No generators configured. Please enable 'typescript' in your config file.");o&&s.onProgress((a,l,d,h)=>{let m=Math.round(l/d*100);i.progress(`[${a}] ${m}% - ${h||"Processing..."}`);}),i.step("Executing generation...");let c=await s.generate();if(c.success){if(ve(`Generated ${c.filesGenerated.length} files in ${c.duration.toFixed(2)}ms`),i.dim(`Output directory: ${c.outputDir}`),c.warnings.length>0)for(let a of c.warnings)ze(a);}else {I(`Generation failed with ${c.errors.length} errors`);for(let a of c.errors)i.dim(` ${a}`);process.exit(1);}}catch(s){I("Generation failed with unexpected error",s instanceof Error?s:new Error(String(s))),process.exit(1);}}};async function Fr(r){for(let e of be){let t=resolve(r,e);if(existsSync(t))return t}return null}var Mt={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 r=>{let e=N({prefix:"TypeSchema"});try{let t=await Ce(process.cwd());e.step("Generating TypeSchema from FHIR packages"),e.info(`Packages: ${r.packages.join(", ")}`),e.info(`Output: ${r.output}`);let n=r.singleFile!==void 0?r.singleFile:t.typeSchema?.singleFile??!1,o=n?"ndjson":r.format;e.debug(`Format: ${o}${n&&r.format==="json"?" (forced from json due to singleFile)":""}`);let i=r.treeshake&&r.treeshake.length>0?r.treeshake:t.typeSchema?.treeshake;i&&i.length>0&&e.info(`Treeshaking enabled for ResourceTypes: ${i.join(", ")}`),n&&e.info("Single file output enabled (NDJSON format)");let s=Date.now(),c=new X({treeshake:i}),a=[];for(let m of r.packages){let[p,g]=m.includes("@")?m.split("@"):[m,void 0];e.progress(`Processing package: ${p}${g?`@${g}`:""}`);let y=await c.generateFromPackage(p,g,e);a.push(...y);}if(a.length===0)throw new Error("No schemas were generated from the specified packages");let l=r.output;if(!l)throw new Error("Output format not specified");await mkdir(dirname(l),{recursive:!0});let d;o==="json"?d=JSON.stringify(a,null,2):d=a.map(m=>JSON.stringify(m)).join(`
31
- `),await writeFile(l,d,"utf-8");let h=Date.now()-s;if(Ke(`Generated ${a.length} TypeSchema definitions`,h,{schemas:a.length}),e.dim(`Output: ${l}`),r.verbose){e.debug("Generated schemas:");let m=a.map(p=>`${p.identifier?.name||"Unknown"} (${p.identifier?.kind||"unknown"})`);G(m);}}catch(t){e.error("Failed to generate TypeSchema",t instanceof Error?t:new Error(String(t))),process.exit(1);}}};var Bt={command:"typeschema [subcommand]",describe:"TypeSchema operations - generate, validate and merge schemas",builder:r=>r.command(Mt).help().example("$0 typeschema generate hl7.fhir.r4.core@4.0.1","Generate TypeSchema from FHIR R4 core package"),handler:r=>{if(!r.subcommand&&r._.length===1){xe("Available typeschema subcommands:"),G(["generate Generate TypeSchema files from FHIR packages"]),console.log(`
30
+ });`),process.exit(1);}let n=await ve(e),o=r.verbose??n.verbose??false,i=N({prefix:"Generate"});try{We("Starting generation from config"),o&&(i.info(`Config file: ${t}`),i.info(`Output directory: ${n.outputDir||"./generated"}`),i.info(`Packages: ${n.packages?.length||0}`),i.info(`Files: ${n.files?.length||0}`),i.info(`TypeScript generation: ${n.typescript?"enabled":"disabled"}`));let s=new Z({outputDir:n.outputDir||"./generated",overwrite:n.overwrite??!0,cache:n.cache??!0,typeSchemaConfig:n.typeSchema,logger:i});if(n.packages&&n.packages.length>0){i.info(`Loading packages from config: ${n.packages.join(", ")}`);for(let a of n.packages){let[l,p]=a.includes("@")?a.split("@"):[a,void 0];s.fromPackage(l,p);}}else throw n.files&&n.files.length>0?(i.info(`Loading files from config: ${n.files.join(", ")}`),new Error("Not Implemented")):new Error("No data source specified in config. Please configure 'packages' or 'files' in your config file.");if(n.typescript)throw new Error("Not Implemented");if(!n.typescript)throw new Error("No generators configured. Please enable 'typescript' in your config file.");o&&s.onProgress((a,l,p,h)=>{let m=Math.round(l/p*100);i.progress(`[${a}] ${m}% - ${h||"Processing..."}`);}),i.step("Executing generation...");let c=await s.generate();if(c.success){if(ke(`Generated ${c.filesGenerated.length} files in ${c.duration.toFixed(2)}ms`),i.dim(`Output directory: ${c.outputDir}`),c.warnings.length>0)for(let a of c.warnings)ze(a);}else {I(`Generation failed with ${c.errors.length} errors`);for(let a of c.errors)i.dim(` ${a}`);process.exit(1);}}catch(s){I("Generation failed with unexpected error",s instanceof Error?s:new Error(String(s))),process.exit(1);}}};async function Fr(r){for(let e of Ce){let t=resolve(r,e);if(existsSync(t))return t}return null}var Mt={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 r=>{let e=N({prefix:"TypeSchema"});try{let t=await ve(process.cwd());e.step("Generating TypeSchema from FHIR packages"),e.info(`Packages: ${r.packages.join(", ")}`),e.info(`Output: ${r.output}`);let n=r.singleFile!==void 0?r.singleFile:t.typeSchema?.singleFile??!1,o=n?"ndjson":r.format;e.debug(`Format: ${o}${n&&r.format==="json"?" (forced from json due to singleFile)":""}`);let i=r.treeshake&&r.treeshake.length>0?r.treeshake:t.typeSchema?.treeshake;i&&i.length>0&&e.info(`Treeshaking enabled for ResourceTypes: ${i.join(", ")}`),n&&e.info("Single file output enabled (NDJSON format)");let s=Date.now(),c=new X({treeshake:i}),a=[];for(let m of r.packages){let[d,g]=m.includes("@")?m.split("@"):[m,void 0];e.progress(`Processing package: ${d}${g?`@${g}`:""}`);let y=await c.generateFromPackage(d,g,e);a.push(...y);}if(a.length===0)throw new Error("No schemas were generated from the specified packages");let l=r.output;if(!l)throw new Error("Output format not specified");await mkdir(dirname(l),{recursive:!0});let p;o==="json"?p=JSON.stringify(a,null,2):p=a.map(m=>JSON.stringify(m)).join(`
31
+ `),await writeFile(l,p,"utf-8");let h=Date.now()-s;if(Ke(`Generated ${a.length} TypeSchema definitions`,h,{schemas:a.length}),e.dim(`Output: ${l}`),r.verbose){e.debug("Generated schemas:");let m=a.map(d=>`${d.identifier?.name||"Unknown"} (${d.identifier?.kind||"unknown"})`);G(m);}}catch(t){e.error("Failed to generate TypeSchema",t instanceof Error?t:new Error(String(t))),process.exit(1);}}};var Bt={command:"typeschema [subcommand]",describe:"TypeSchema operations - generate, validate and merge schemas",builder:r=>r.command(Mt).help().example("$0 typeschema generate hl7.fhir.r4.core@4.0.1","Generate TypeSchema from FHIR R4 core package"),handler:r=>{if(!r.subcommand&&r._.length===1){xe("Available typeschema subcommands:"),G(["generate Generate TypeSchema files from FHIR packages"]),console.log(`
32
32
  Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),console.log(`
33
33
  Examples:`),G(["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}r.subcommand&&!["generate","validate","merge"].includes(r.subcommand)&&(I(`Unknown typeschema subcommand: ${r.subcommand}
34
34
  `),xe("Available typeschema subcommands:"),G(["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(`
35
- Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),process.exit(1));}};function Or(r){return r?{debug:0,info:1,warn:2,error:3,silent:4}[r.toLowerCase()]:void 0}async function Dr(r){let e=Or(r.logLevel);e===void 0&&(r.debug||r.verbose?e=0:e=1),qe({timestamp:r.debug,level:e});}function Lr(){return Pr(hideBin(process.argv)).scriptName("atomic-codegen").usage("$0 <command> [options]").middleware(Dr).command(Bt).command(Lt).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("log-level",{alias:"l",type:"string",choices:["debug","info","warn","error","silent"],description:"Set the log level (default: info)",global:true}).option("config",{alias:"c",type:"string",description:"Path to configuration file (.atomic-codegen.json by default)",global:true}).demandCommand(0).middleware(r=>{r._.length===0&&(Je("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(`
35
+ Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),process.exit(1));}};function Dr(r){return r?{debug:0,info:1,warn:2,error:3,silent:4}[r.toLowerCase()]:void 0}async function Or(r){let e=Dr(r.logLevel);e===void 0&&(r.debug||r.verbose?e=0:e=1),qe({timestamp:r.debug,level:e});}function Lr(){return Er(hideBin(process.argv)).scriptName("atomic-codegen").usage("$0 <command> [options]").middleware(Or).command(Bt).command(Lt).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("log-level",{alias:"l",type:"string",choices:["debug","info","warn","error","silent"],description:"Set the log level (default: info)",global:true}).option("config",{alias:"c",type:"string",description:"Path to configuration file (.atomic-codegen.json by default)",global:true}).demandCommand(0).middleware(r=>{r._.length===0&&(Je("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(`
36
36
  Use 'atomic-codegen <command> --help' for more information about a command.`),console.log(`
37
37
  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(`
38
38
  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((r,e,t)=>{e?I(e.message,e):I(r),I(`
package/dist/index.d.ts CHANGED
@@ -133,6 +133,10 @@ type Name = string & {
133
133
  type CanonicalUrl = string & {
134
134
  readonly __brand: unique symbol;
135
135
  };
136
+ interface PackageMeta {
137
+ name: string;
138
+ version: string;
139
+ }
136
140
  type IdentifierBase = {
137
141
  name: Name;
138
142
  url: CanonicalUrl;
@@ -582,6 +586,11 @@ interface GenerationResult {
582
586
  warnings: string[];
583
587
  duration: number;
584
588
  }
589
+ interface LocalStructureDefinitionConfig {
590
+ package: PackageMeta;
591
+ path: string;
592
+ dependencies?: PackageMeta[];
593
+ }
585
594
  /**
586
595
  * High-Level API Builder class
587
596
  *
@@ -594,11 +603,15 @@ declare class APIBuilder {
594
603
  private generators;
595
604
  private logger;
596
605
  private packages;
606
+ private localStructurePackages;
607
+ private localTgzArchives;
597
608
  progressCallback: any;
598
609
  private typeSchemaConfig?;
599
610
  constructor(options?: APIBuilderOptions);
600
611
  fromPackage(packageName: string, version?: string): APIBuilder;
601
612
  fromPackageRef(packageRef: string): APIBuilder;
613
+ localStructureDefinitions(config: LocalStructureDefinitionConfig): APIBuilder;
614
+ localTgzPackage(archivePath: string): APIBuilder;
602
615
  fromSchemas(schemas: TypeSchema[]): APIBuilder;
603
616
  typescript(userOpts: Partial<TypeScriptOptions>): this;
604
617
  csharp(namespace: string, staticSourceDir?: string | undefined): APIBuilder;
@@ -638,4 +651,4 @@ type CSharpGeneratorOptions = WriterOptions & {
638
651
  targetNamespace: string;
639
652
  };
640
653
 
641
- export { APIBuilder, type APIBuilderOptions, CONFIG_FILE_NAMES, type CSharpGeneratorOptions, type Config, ConfigLoader, type ConfigValidationError, type ConfigValidationResult, ConfigValidator, DEFAULT_CONFIG, LogLevel, type TypeSchemaConfig, type TypeScriptGeneratorConfig, type TypeScriptOptions, configLoader, defineConfig, isConfig, loadConfig };
654
+ export { APIBuilder, type APIBuilderOptions, CONFIG_FILE_NAMES, type CSharpGeneratorOptions, type Config, ConfigLoader, type ConfigValidationError, type ConfigValidationResult, ConfigValidator, DEFAULT_CONFIG, type LocalStructureDefinitionConfig, LogLevel, type TypeSchemaConfig, type TypeScriptGeneratorConfig, type TypeScriptOptions, configLoader, defineConfig, isConfig, loadConfig };
package/dist/index.js CHANGED
@@ -1560,7 +1560,7 @@ var mkTypeSchemaIndex = (schemas, { resolutionTree, logger }) => {
1560
1560
  append(schema);
1561
1561
  }
1562
1562
  const relations = resourceRelatives(schemas);
1563
- const resolve3 = (id) => index[id.url]?.[id.package];
1563
+ const resolve4 = (id) => index[id.url]?.[id.package];
1564
1564
  const resolveByUrl = (pkgName, url) => {
1565
1565
  if (resolutionTree) {
1566
1566
  const resolution = resolutionTree[pkgName]?.[url]?.[0];
@@ -1580,7 +1580,7 @@ var mkTypeSchemaIndex = (schemas, { resolutionTree, logger }) => {
1580
1580
  res.push(cur);
1581
1581
  const base = cur.base;
1582
1582
  if (base === void 0) break;
1583
- const resolved = resolve3(base);
1583
+ const resolved = resolve4(base);
1584
1584
  if (!resolved) {
1585
1585
  logger?.warn(
1586
1586
  `Failed to resolve base type: ${res.map((e) => `${e.identifier.url} (${e.identifier.kind})`).join(", ")}`
@@ -1606,7 +1606,7 @@ var mkTypeSchemaIndex = (schemas, { resolutionTree, logger }) => {
1606
1606
  return nonConstraintSchema;
1607
1607
  };
1608
1608
  const findLastSpecializationByIdentifier = (id) => {
1609
- const schema = resolve3(id);
1609
+ const schema = resolve4(id);
1610
1610
  if (!schema) return id;
1611
1611
  return findLastSpecialization(schema).identifier;
1612
1612
  };
@@ -1678,7 +1678,7 @@ var mkTypeSchemaIndex = (schemas, { resolutionTree, logger }) => {
1678
1678
  collectResources: () => schemas.filter(isResourceTypeSchema),
1679
1679
  collectLogicalModels: () => schemas.filter(isLogicalTypeSchema),
1680
1680
  collectProfiles: () => schemas.filter(isProfileTypeSchema),
1681
- resolve: resolve3,
1681
+ resolve: resolve4,
1682
1682
  resolveByUrl,
1683
1683
  resourceChildren,
1684
1684
  tryHierarchy,
@@ -2251,6 +2251,8 @@ var APIBuilder = class {
2251
2251
  generators = /* @__PURE__ */ new Map();
2252
2252
  logger;
2253
2253
  packages = [];
2254
+ localStructurePackages = [];
2255
+ localTgzArchives = [];
2254
2256
  progressCallback;
2255
2257
  typeSchemaConfig;
2256
2258
  constructor(options = {}) {
@@ -2281,6 +2283,14 @@ var APIBuilder = class {
2281
2283
  this.packages.push(packageRef);
2282
2284
  return this;
2283
2285
  }
2286
+ localStructureDefinitions(config) {
2287
+ this.localStructurePackages.push(config);
2288
+ return this;
2289
+ }
2290
+ localTgzPackage(archivePath) {
2291
+ this.localTgzArchives.push(Path4.resolve(archivePath));
2292
+ return this;
2293
+ }
2284
2294
  fromSchemas(schemas) {
2285
2295
  this.logger.debug(`Adding ${schemas.length} TypeSchemas to generation`);
2286
2296
  this.schemas = [...this.schemas, ...schemas];
@@ -2380,10 +2390,27 @@ var APIBuilder = class {
2380
2390
  try {
2381
2391
  if (this.options.cleanOutput) cleanup(this.options, this.logger);
2382
2392
  this.logger.info("Initialize Canonical Manager");
2383
- const manager = CanonicalManager({
2393
+ const manager = this.options.manager || CanonicalManager({
2384
2394
  packages: this.packages,
2385
2395
  workingDir: ".codegen-cache/canonical-manager-cache"
2386
2396
  });
2397
+ if (this.localStructurePackages.length > 0) {
2398
+ for (const config of this.localStructurePackages) {
2399
+ this.logger.info(
2400
+ `Registering local StructureDefinitions for ${config.package.name}@${config.package.version}`
2401
+ );
2402
+ await manager.addLocalPackage({
2403
+ name: config.package.name,
2404
+ version: config.package.version,
2405
+ path: config.path,
2406
+ dependencies: config.dependencies?.map((dep) => packageMetaToNpm(dep))
2407
+ });
2408
+ }
2409
+ }
2410
+ for (const archivePath of this.localTgzArchives) {
2411
+ this.logger.info(`Registering local tgz package: ${archivePath}`);
2412
+ await manager.addTgzPackage({ archivePath });
2413
+ }
2387
2414
  const ref2meta = await manager.init();
2388
2415
  const packageMetas = Object.values(ref2meta);
2389
2416
  const register = await registerFromManager(manager, {
@@ -2422,6 +2449,9 @@ var APIBuilder = class {
2422
2449
  this.schemas = [];
2423
2450
  this.generators.clear();
2424
2451
  this.progressCallback = void 0;
2452
+ this.packages = [];
2453
+ this.localStructurePackages = [];
2454
+ this.localTgzArchives = [];
2425
2455
  return this;
2426
2456
  }
2427
2457
  /**