@atomic-ehr/codegen 0.0.4-canary.20251218111944.d18e50d → 0.0.4-canary.20251222144228.ac2a1d7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/index.js +9 -9
- package/dist/index.d.ts +2 -1
- package/dist/index.js +17 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import T from'picocolors';import
|
|
2
|
+
import T from'picocolors';import ei from'yargs';import {hideBin}from'yargs/helpers';import*as k from'fs';import k__default,{existsSync}from'fs';import*as w from'path';import w__default,{dirname,resolve}from'path';import*as V from'fs/promises';import {mkdir,writeFile,readFile}from'fs/promises';import {CanonicalManager}from'@atomic-ehr/fhir-canonical-manager';import ne from'assert';import {fileURLToPath}from'url';import*as Tt from'yaml';import*as Lt from'@atomic-ehr/fhirschema';import {isStructureDefinition}from'@atomic-ehr/fhirschema';var Ze=i=>{switch(i.toUpperCase()){case "DEBUG":return 0;case "INFO":return 1;case "WARN":return 2;case "ERROR":return 3;case "SILENT":return 4;default:throw new Error(`Invalid log level: ${i}`)}},J=class i{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,r){let o=this.options.timestamp?`${T.gray(new Date().toLocaleTimeString())} `:"",n=this.options.prefix?`${T.cyan(`[${this.options.prefix}]`)} `:"";return `${o}${r(e)} ${n}${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;(i.consoleLevelsMap[e]||console.log)(t);}success(e){this.tryWriteToConsole(1,this.formatMessage("",e,T.green));}error(e,t){if(this.isSuppressed(3)||!this.shouldLog(3))return;console.error(this.formatMessage("X",e,T.red));let r=this.options.level===0;t&&r&&(console.error(T.red(` ${t.message}`)),t.stack&&console.error(T.gray(t.stack)));}warn(e){this.tryWriteToConsole(2,this.formatMessage("!",e,T.yellow));}dry_warn(e){this.dryWarnSet.has(e)||(this.warn(e),this.dryWarnSet.add(e));}info(e){this.tryWriteToConsole(1,this.formatMessage("i",e,T.blue));}debug(e){this.shouldLog(0)&&this.tryWriteToConsole(0,this.formatMessage("\u{1F41B}",e,T.magenta));}step(e){this.tryWriteToConsole(1,this.formatMessage("\u{1F680}",e,T.cyan));}progress(e){this.tryWriteToConsole(1,this.formatMessage("\u23F3",e,T.blue));}plain(e,t=r=>r){let r=this.options.timestamp?`${T.gray(new Date().toLocaleTimeString())} `:"",o=this.options.prefix?`${T.cyan(`[${this.options.prefix}]`)} `:"";this.tryWriteToConsole(1,`${r}${o}${t(e)}`);}dim(e){this.plain(e,T.gray);}child(e){return new i({...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;}},A=new J;function Ee(i){A.success(i);}function F(i,e){A.error(i,e);}function et(i){A.warn(i);}function Ne(i){A.info(i);}function tt(i){A.step(i);}function Xt(i){A.dim(i);}function rt(i){A.configure(i);}function M(i={}){return new J(i)}function it(i){console.log(),console.log(T.cyan(T.bold(`\u2501\u2501\u2501 ${i} \u2501\u2501\u2501`)));}function nt(i,e,t){let r=i;e&&(r+=` ${T.gray(`(${e}ms)`)}`),Ee(r),t&&Object.entries(t).forEach(([o,n])=>{Xt(` ${o}: ${n}`);});}function K(i,e="\u2022"){i.forEach(t=>{console.log(T.gray(` ${e} ${t}`));});}var ce=i=>i.split(/(?<=[a-z])(?=[A-Z])|[-_.\s]/).filter(Boolean),ot=i=>ce(i).map(e=>e.toLowerCase()).join("-"),st=i=>{if(i.length===0)throw new Error("Empty string");return i[0]?.toUpperCase()+i.substring(1).toLowerCase()},le=i=>{if(i.length===0)throw new Error("Empty string");let[e,...t]=ce(i);return [e?.toLowerCase(),...t.map(st)].join("")},P=i=>ce(i).map(st).join(""),$=i=>ce(i).map(e=>e.toLowerCase()).join("_"),E=i=>!i||i.length===0?i:i.charAt(0).toUpperCase()+i.slice(1),Y=i=>i.map(e=>E(e));var at=i=>`<${i.identifier.url}> from ${i.identifier.package}#${i.identifier.version}`;var De=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||k.existsSync(e)||k.mkdirSync(e,{recursive:true});}onDiskOpenFile(e){return this.opts.inMemoryOnly?-1:k.openSync(e,"w")}onDiskCloseFile(e){this.opts.inMemoryOnly||(k.fsyncSync(e),k.closeSync(e));}onDiskWrite(e,t){this.opts.inMemoryOnly||k.writeSync(e,t);}cd(e,t){let r=this.currentDir;this.currentDir=e.startsWith("/")?w.join(this.opts.outputDir,e):w.join(this.currentDir??this.opts.outputDir,e),this.onDiskMkDir(this.currentDir),this.logger()?.debug(`cd '${this.currentDir}'`),t(),this.currentDir=r;}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 r=w.normalize(`${this.currentDir}/${e}`);try{let o=this.onDiskOpenFile(r);this.logger()?.debug(`cat > '${r}'`),this.currentFile={descriptor:o,relPath:r},this.writtenFilesBuffer[this.currentFile.relPath]={relPath:r,absPath:w.resolve(r),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:r})=>({relPath:e,absPath:t,content:r.join()})).sort((e,t)=>e.relPath.localeCompare(t.relPath))}},B=class extends De{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 r of t)this.line(this.opts.commentLinePrefix,r);}debugComment(...e){this.opts.withDebugComment&&(e=e.map(t=>typeof t=="string"?t:JSON.stringify(t,null,2)),this.comment(...e));}disclaimer(){return ["WARNING: This file is autogenerated by @atomic-ehr/codegen.","GitHub: https://github.com/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,r){this.line(`${e.filter(Boolean).join(" ")} {`),this.indent(),t(),this.deindent(),this.line(`}${r?.filter(Boolean).join(" ")??""}`);}squareBlock(e,t,r){this.line(`${e.filter(Boolean).join(" ")} [`),this.indent(),t(),this.deindent(),this.line(`]${r?.filter(Boolean).join(" ")??""}`);}};var pe=(i,e=true)=>{let t=i.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),t};var v=i=>`${i.name}#${i.version}`,de=i=>`${i.name}@${i.version}`;var Oe=(i,e)=>(e||(e={name:"undefined",version:"undefined"}),{...i,package_meta:i.package_meta||e,name:i.name,url:i.url,base:i.base}),Z=i=>i?.kind==="primitive-type",N=i=>i?.kind==="nested",at=i=>i?.kind==="complex-type",ct=i=>i?.kind==="profile";var _=i=>i?.identifier.kind==="resource"||i?.identifier.kind==="complex-type"||i?.identifier.kind==="logical",lt=i=>i?.identifier.kind==="complex-type",D=i=>i?.identifier.kind==="resource",pt=i=>i?.identifier.kind==="primitive-type",j=i=>i?.identifier.kind==="logical",ue=i=>i?.identifier.kind==="profile";function dt(i){return i?.identifier.kind==="binding"}function ut(i){return i?.identifier.kind==="value-set"}var G=i=>i?i.choices===void 0:false,I=i=>i?i.choices!==void 0:false,Le=i=>i?i.choiceOf!==void 0:false,gt=(i,e)=>{if(!i.url)throw new Error("ValueSet must have a URL");if(!i.name)throw new Error("ValueSet must have a name");return {...i,package_meta:i.package_meta||e,name:i.name,url:i.url}};var ft={"!":"Not","<=":"LessOrEqual",">=":"GreaterOrEqual","<":"Less",">":"Greater","=":"Equal","-":"Dash","+":"Plus","*":"Asterisk","/":"Slash","%":"Percent","&":"And","|":"Or","^":"Xor","~":"Tilde","?":"Question",".":"Dot"};function Xt(i){return i.split("-").map(e=>E(e)).join("-")}function Qt(i){let e=i;for(let t in ft)e=e.replaceAll(t,ft[t]??"");return e}function Zt(i){let e=Number(i[0]);return Number.isInteger(e)&&!Number.isNaN(e)?`_${i}`:i}function mt(i){let e=Xt(i);return e=Zt(e),e=Qt(e),e=E(e),e}function O(i){return E(le(i.replaceAll(".","-")))}var er={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"},tr=["Reference","Expression"],rr=i=>i.required?["required"]:[],ir=i=>{let e=bt(St(i.identifier));return E(e)},nr=i=>i.base?`: ${i.base.name}`:"",or=(i,e=true)=>{if(!i)return;let t=i.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),O(t)},St=i=>{if(i.kind==="nested"){let e=i.url,t=or(e,false);if(!t)return "";let[r,o]=t.split("#"),n=Y((o??"").split(".")).join("");return O([r,n].join(""))}return O(i.name)},sr=i=>tr.includes(i),bt=i=>sr(i)?`Resource${i}`:i,ge=class extends B{enums={};constructor(e){super({tabSize:4,withDebugComment:false,commentLinePrefix:"//",...e});}async generate(e){let t=e.collectComplexTypes(),r=e.collectResources(),o=Array.from(new Set(r.map(n=>O(n.identifier.package))));this.generateAllFiles(t,r,o),this.copyStaticFiles();}generateAllFiles(e,t,r){this.generateUsingFile(r),this.generateBaseTypes(e),this.generateResources(t),this.generateEnumFiles(r),this.generateResourceDictionaries(t,r),this.generateHelperFile();}generateType(e,t){let r=ir(e),o=nr(e);this.curlyBlock(["public","class",r,o],()=>{this.generateFields(e,t),this.generateNestedTypes(e,t),this.line(),this.includeHelperMethods();}),this.line();}generateFields(e,t){if(!e.fields)return;let r=Object.entries(e.fields).sort(([o],[n])=>o.localeCompare(n));for(let[o,n]of r)this.generateField(o,n,t);}generateNestedTypes(e,t){if(!(!("nested"in e)||!e.nested)){this.line();for(let r of e.nested)this.generateType(r,t);}}generateField(e,t,r){try{if(I(t))return;let o=this.buildFieldDeclaration(e,t,r);this.line(...o);}catch(o){this.logger()?.error(`Error processing field ${e}: ${o.message}`);}}buildFieldDeclaration(e,t,r){let o=this.determineFieldType(e,t,r),n=rr(t),s=w(e);return ["public",...n,o,s,"{ get; set; }"].filter(Boolean)}determineFieldType(e,t,r){let o=this.getBaseTypeName(t);"enum"in t&&t.enum&&(o=this.registerAndGetEnumType(e,t,r)),o=bt(o);let n="",s=t.required?"":"?",c=t.array?"[]":"";return `${n}${o}${c}${s}`}getBaseTypeName(e){if("type"in e){let t=e.type.name.toString();return e.type.kind==="nested"?t=St(e.type):e.type.kind==="primitive-type"&&(t=er[e.type.name]??"string"),t}return ""}registerAndGetEnumType(e,t,r){let n=`${O(t.binding?.name??e)}Enum`;return this.enums[r]||(this.enums[r]={}),t.enum&&(this.enums[r][n]=t.enum),n}includeHelperMethods(){this.line("public override string ToString() => "),this.line(" JsonSerializer.Serialize(this, Helper.JsonSerializerOptions);"),this.line();}generateUsingFile(e){this.cd("/",async()=>{this.cat("Usings.cs",()=>{this.generateDisclaimer(),this.generateGlobalUsings(e);});});}generateGlobalUsings(e){let t=["CSharpSDK","System.Text.Json","System.Text.Json.Serialization",this.opts.targetNamespace,...e.map(r=>`${this.opts.targetNamespace}.${r}`)];for(let r of t)this.lineSM("global","using",r);}generateBaseTypes(e){this.cd("/",async()=>{this.cat("base.cs",()=>{this.generateDisclaimer(),this.line(),this.lineSM("namespace",this.opts.targetNamespace);for(let t of e){let r=O(t.identifier.package);this.generateType(t,r);}});});}generateResources(e){for(let t of e)this.generateResourceFile(t);}generateResourceFile(e){let t=O(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[r,o]of Object.entries(t))this.generateEnum(r,o);}generateEnum(e,t){this.curlyBlock(["public","enum",e],()=>{for(let r of t)this.line(`[Description("${r}")]`),this.line(`${mt(r)},`);}),this.line();}generateResourceDictionaries(e,t){this.cd("/",async()=>{for(let r of t){let o=e.filter(n=>O(n.identifier.package)===r);if(o.length===0)return;this.cat(`${r}ResourceDictionary.cs`,()=>{this.generateDisclaimer(),this.line(),this.lineSM(`namespace ${this.opts.targetNamespace}`),this.generateResourceDictionaryClass(r,o);});}});}generateResourceDictionaryClass(e,t){this.curlyBlock(["public","static","class","ResourceDictionary"],()=>{this.curlyBlock(["public static readonly Dictionary<Type, string> Map = new()"],()=>{for(let r of t){let o=r.identifier.name;this.line(`{ typeof(${e}.${o}), "${o}" },`);}}),this.lineSM();});}copyStaticFiles(){if(!this.opts.staticSourceDir)return;let e=P__default.resolve(this.opts.staticSourceDir);R__default.cpSync(e,this.opts.outputDir,{recursive:true});}generateHelperFile(){let e="src/api/writer-generator/csharp/Helper.cs",t=P__default.join(this.opts.outputDir,"Helper.cs");R__default.copyFileSync(e,t);}};var z=i=>{let e={};for(let t of i){let r=t.identifier.package;e[r]||(e[r]=[]),e[r].push(t);}for(let[t,r]of Object.entries(e)){let o={};for(let s of r)o[JSON.stringify(s.identifier)]=s;let n=Object.values(o);n.sort((s,c)=>s.identifier.name.localeCompare(c.identifier.name)),e[t]=n;}return e},ar=i=>{let e={};for(let r of i)e[r.identifier.name]=r;let t={};for(let r of i){let o=r.identifier.name,n=r.base?.name;t[o]||(t[o]=[]),n&&e[n]&&t[o].push(n);}return t},cr=i=>{let e=[],t={},r={},o=n=>{if(r[n])throw new Error(`Graph has cycles ${n}`);if(!t[n]){r[n]=true;for(let s of i[n]??[])o(s);r[n]=false,t[n]=true,e.push(n);}};for(let n in i)t[n]||o(n);return e},Tt=i=>{let e=ar(i);return cr(e).map(r=>i.find(o=>o.identifier.name===r)).filter(Boolean)},lr=i=>{let e=i.filter(n=>D(n)||j(n)),t=[];for(let n of e)n.base&&t.push({parent:n.base,child:n.identifier});let r=[...t],o=n=>{let s=t.filter(a=>a.parent.name===n.name).map(a=>a.child),c=[];for(let a of s)c.push(...o(a));return [...s,...c]};for(let n of t){let s=o(n.child);for(let c of s)t.some(a=>a.parent.name===n.parent.name&&a.child.name===c.name)||r.push({parent:n.parent,child:c});}return r},me=(i,{resolutionTree:e,logger:t})=>{let r={},o=u=>{let g=u.identifier.url,S=u.identifier.package;if(r[g]||(r[g]={}),r[g][u.identifier.package]&&S!=="shared"){let C=JSON.stringify(u.identifier,void 0,2),b=JSON.stringify(r[g][S]?.identifier,void 0,2);if(C!==b)throw new Error(`Duplicate schema: ${C} and ${b}`);return}r[g][S]=u;};for(let u of i)o(u);let n=lr(i),s=u=>r[u.url]?.[u.package],c=(u,g)=>{if(e){let S=e[u]?.[g]?.[0];if(S)return r[g]?.[S.pkg.name]}return r[g]?.[u]},a=u=>n.filter(g=>g.parent.name===u.name).map(g=>g.child),l=u=>{let g=[],S=u;for(;S;){g.push(S);let C=S.base;if(C===void 0)break;let b=s(C);if(!b){t?.warn(`Failed to resolve base type: ${g.map(x=>`${x.identifier.url} (${x.identifier.kind})`).join(", ")}`);return}S=b;}return g},p=u=>{let g=l(u);if(g===void 0)throw new Error(`Failed to resolve base type: ${u.identifier.url} (${u.identifier.kind})`);return g},m=u=>{let g=p(u).find(S=>S.identifier.kind!=="profile");if(!g)throw new Error(`No non-constraint schema found in hierarchy for: ${u.identifier.name}`);return g};return {_schemaIndex:r,_relations:n,collectComplexTypes:()=>i.filter(lt),collectResources:()=>i.filter(D),collectLogicalModels:()=>i.filter(j),collectProfiles:()=>i.filter(ue),resolve:s,resolveByUrl:c,resourceChildren:a,tryHierarchy:l,hierarchy:p,findLastSpecialization:m,findLastSpecializationByIdentifier:u=>{let g=s(u);return g?m(g).identifier:u},flatProfile:u=>{let g=p(u),S=g.filter(L=>L.identifier.kind==="profile"),C=g.find(L=>L.identifier.kind!=="profile");if(!C)throw new Error(`No non-constraint schema found in hierarchy for ${u.identifier.name}`);let b={};for(let L of S.slice().reverse()){let se=L;if(se.fields)for(let[ae,Qe]of Object.entries(se.fields))b[ae]?b[ae]={...b[ae],...Qe}:b[ae]={...Qe};}let x={};for(let L of S.flatMap(se=>se.dependencies??[]))x[L.url]=L;let U=Object.values(x);return {...u,base:C.identifier,fields:b,dependencies:U}},isWithMetaField:u=>{let g=l(u);return g?g.filter(_).some(S=>S.fields?.meta!==void 0):false},exportTree:async u=>{let g={};for(let[C,b]of Object.entries(z(i))){g[C]={"primitive-type":{},"complex-type":{},resource:{},"value-set":{},nested:{},binding:{},profile:{},logical:{}};for(let x of b)g[C][x.identifier.kind][x.identifier.url]={};}let S=u.endsWith(".yaml")?Ct.stringify(g):JSON.stringify(g,void 0,2);await V.mkdir(P.dirname(u),{recursive:true}),await V.writeFile(u,S);}}};var dr={boolean:"bool",instant:"str",time:"str",date:"str",dateTime:"str",decimal:"float",integer:"int",unsignedInt:"int",positiveInt:"PositiveInt",integer64:"int",base64Binary:"str",uri:"str",url:"str",canonical:"str",oid:"str",uuid:"str",string:"str",code:"str",markdown:"str",id:"str",xhtml:"str"},Me={snake_case:$,PascalCase:w,camelCase:le},ur=new Set(["False","None","True","and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","List"]),xt=100,gr=i=>ur.has(i)?`${i}_`:i,fr=i=>i==="Resource"||i==="Element"?["BaseModel"]:[],mr=(i,e=true)=>{if(!i)return;let t=i.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),$(t)},he=i=>{if(i.kind==="nested"){let e=i.url,t=mr(e,false);if(!t)return "";let[r,o]=t.split("#"),n=Y((o??"").split(".")).join("");return w([r,n].join(""))}return w(i.name)},Ft=i=>{let e=P.dirname(fileURLToPath(import.meta.url));return __filename.endsWith("dist/index.js")?P.resolve(e,"..","assets","api","writer-generator","python",i):P.resolve(e,"../../..","assets","api","writer-generator","python",i)},ye=class extends B{nameFormatFunction;tsIndex;constructor(e){super(e),this.nameFormatFunction=this.getFieldFormatFunction(e.fieldFormat);}async generate(e){this.tsIndex=e;let t={groupedComplexTypes:z(e.collectComplexTypes()),groupedResources:z(e.collectResources())};this.generateRootPackages(t),this.generateSDKPackages(t);}generateRootPackages(e){this.generateRootInitFile(e),R__default.cpSync(Ft("requirements.txt"),P.resolve(this.opts.outputDir,"requirements.txt"));}generateSDKPackages(e){this.generateComplexTypesPackages(e.groupedComplexTypes),this.generateResourcePackages(e);}generateComplexTypesPackages(e){for(let[t,r]of Object.entries(e))this.cd(`/${$(t)}`,()=>{this.generateBasePy(r);});}generateResourcePackages(e){for(let[t,r]of Object.entries(e.groupedResources))this.cd(`/${$(t)}`,()=>{this.generateResourcePackageContent(t,r,e.groupedComplexTypes[t]||[]);});}generateResourcePackageContent(e,t,r){let o=this.pyFhirPackageByName(e);this.generateResourcePackageInit(o,t,r),this.generateResourceFamilies(t);for(let n of t)this.generateResourceModule(n);}generateRootInitFile(e){this.cd("/",()=>{this.cat("__init__.py",()=>{this.generateDisclaimer();let t=this.collectAndImportAllModels(e);this.generateModelRebuilds(t);});});}collectAndImportAllModels(e){let t=[];for(let r of Object.keys(e.groupedResources)){let o=this.pyFhirPackageByName(r);t.push(...this.importComplexTypes(o,e.groupedComplexTypes[r])),t.push(...this.importResources(o,false,e.groupedResources[r]));}return this.line(),t}generateModelRebuilds(e){for(let t of e.sort())this.line(`${t}.model_rebuild()`);}generateBasePy(e){this.cat("base.py",()=>{this.generateDisclaimer(),this.generateDefaultImports(),this.line(),this.generateComplexTypes(e),this.line();});}generateComplexTypes(e){for(let t of Tt(e))this.generateNestedTypes(t),this.line(),this.generateType(t);}generateResourcePackageInit(e,t,r){this.cat("__init__.py",()=>{this.generateDisclaimer(),this.importComplexTypes(e,r);let o=this.importResources(e,true,t);this.line(),this.generateExportsDeclaration(r,o);});}importComplexTypes(e,t){if(!t||t.length===0)return [];let r=t.map(o=>o.identifier.name).sort();return this.pyImportFrom(`${e}.base`,...r),this.line(),r}buildImportLine(e,t){let r="";for(;e.length>0&&r.length<t;){let o=e.shift();if(!o)throw new Error("Unexpected empty entity");r.length>0&&(r+=", "),r+=o;}return e.length>0&&(r+=", \\"),r}importResources(e,t,r){if(!r||r.length===0)return [];let o=[];for(let n of r){let s=this.importOneResource(n,e);!t&&!n.fields||o.push(...s);}return o}importOneResource(e,t){let r=`${t}.${$(e.identifier.name)}`,o=this.collectResourceImportNames(e);this.pyImportFrom(r,...o);let n=[...o];if(this.shouldImportResourceFamily(e)){let s=`${e.identifier.name}Family`;this.pyImportFrom(`${t}.resource_families`,s);}return n}collectResourceImportNames(e){let t=[he(e.identifier)];for(let r of e.nested??[]){let o=he(r.identifier);t.push(o);}return t}shouldImportResourceFamily(e){return ne(this.tsIndex!==void 0),e.identifier.kind==="resource"&&this.tsIndex.resourceChildren(e.identifier).length>0}generateExportsDeclaration(e,t){this.squareBlock(["__all__","="],()=>{let r=[...(e||[]).map(o=>o.identifier.name),...t].sort();for(let o of r)this.line(`'${o}',`);});}generateResourceModule(e){this.cat(`${$(e.identifier.name)}.py`,()=>{this.generateDisclaimer(),this.generateDefaultImports(),this.line(),this.generateDependenciesImports(e),this.line(),this.generateNestedTypes(e),this.line(),this.generateType(e);});}generateType(e){let t=he(e.identifier),r=this.getSuperClasses(e);this.line(`class ${t}(${r.join(", ")}):`),this.indentBlock(()=>{this.generateClassBody(e);}),this.line();}getSuperClasses(e){return [...e.base?[e.base.name]:[],...fr(e.identifier.name)]}generateClassBody(e){if(this.generateModelConfig(),!e.fields){this.line("pass");return}e.identifier.kind==="resource"&&this.generateResourceTypeField(e),this.generateFields(e),e.identifier.kind==="resource"&&this.generateResourceMethods(e);}generateModelConfig(){let e=this.opts.allowExtraFields?"allow":"forbid";this.line(`model_config = ConfigDict(validate_by_name=True, serialize_by_alias=True, extra="${e}")`);}generateResourceTypeField(e){this.line(`${this.nameFormatFunction("resourceType")}: str = Field(`),this.indentBlock(()=>{this.line(`default='${e.identifier.name}',`),this.line("alias='resourceType',"),this.line("serialization_alias='resourceType',"),this.line("frozen=True,"),this.line(`pattern='${e.identifier.name}'`);}),this.line(")");}generateFields(e){let t=Object.entries(e.fields??[]).sort(([r],[o])=>r.localeCompare(o));for(let[r,o]of t){if("choices"in o&&o.choices)continue;let n=this.buildFieldInfo(r,o);this.line(`${n.name}: ${n.type}${n.defaultValue}`);}}buildFieldInfo(e,t){let r=gr(this.nameFormatFunction(e)),o=this.determineFieldType(t),n=this.getFieldDefaultValue(t,e);return {name:r,type:o,defaultValue:n}}determineFieldType(e){let t=e?this.getBaseFieldType(e):"";return "enum"in e&&e.enum&&(t=`Literal[${e.enum.map(o=>`"${o}"`).join(", ")}]`),e.array&&(t=`PyList[${t}]`),e.required||(t=`${t} | None`),t}getBaseFieldType(e){return "type"in e&&e.type.kind==="resource"?`${e.type.name}Family`:"type"in e&&e.type.kind==="nested"?he(e.type):"type"in e&&e.type.kind==="primitive-type"?dr[e.type.name]??"str":"type"in e?e.type.name:""}getFieldDefaultValue(e,t){let r=`alias="${t}", serialization_alias="${t}"`;return e.required?` = Field(${r})`:` = Field(None, ${r})`}generateResourceMethods(e){let t=e.identifier.name.toString();this.line(),this.line("def to_json(self, indent: int | None = None) -> str:"),this.line(" return self.model_dump_json(exclude_unset=True, exclude_none=True, indent=indent)"),this.line(),this.line("@classmethod"),this.line(`def from_json(cls, json: str) -> ${t}:`),this.line(" return cls.model_validate_json(json)");}generateNestedTypes(e){if(e.nested){this.line();for(let t of e.nested)this.generateType(t);}}generateDefaultImports(){this.pyImportFrom("__future__","annotations"),this.pyImportFrom("pydantic","BaseModel","ConfigDict","Field","PositiveInt"),this.pyImportFrom("typing","List as PyList","Literal");}generateDependenciesImports(e){!e.dependencies||e.dependencies.length===0||(this.importComplexTypeDependencies(e.dependencies),this.importResourceDependencies(e.dependencies));}importComplexTypeDependencies(e){let t=e.filter(o=>o.kind==="complex-type"),r=this.groupDependenciesByPackage(t);for(let[o,n]of Object.entries(r))this.pyImportFrom(o,...n.sort());}importResourceDependencies(e){let t=e.filter(r=>r.kind==="resource");for(let r of t){this.pyImportType(r);let o=`${w(r.name)}Family`,n=`${this.pyFhirPackage(r)}.resource_families`;this.pyImportFrom(n,o);}}groupDependenciesByPackage(e){let t={};for(let r of e){let o=this.pyPackage(r);t[o]||(t[o]=[]),t[o].push(r.name);}return t}pyImportFrom(e,...t){let r=`from ${e} import ${t.join(", ")}`;this.shouldUseSingleLineImport(r,t)?this.line(r):this.writeMultiLineImport(e,t);}shouldUseSingleLineImport(e,t){return e.length<=xt||t.length===1}writeMultiLineImport(e,t){this.line(`from ${e} import (\\`),this.indentBlock(()=>{let r=[...t];for(;r.length>0;){let o=this.buildImportLine(r,xt);this.line(o);}}),this.line(")");}pyImportType(e){this.pyImportFrom(this.pyPackage(e),w(e.name));}generateResourceFamilies(e){ne(this.tsIndex!==void 0);let t=Object.keys(z(e)).map(n=>`${this.opts.rootPackageName}.${n.replaceAll(".","_")}`),r={};for(let n of this.tsIndex.collectResources()){let s=this.tsIndex.resourceChildren(n.identifier).map(c=>c.name);if(s.length>0){let c=`${n.identifier.name}Family`;r[c]=s;}}let o=Object.keys(r);o.length!==0&&this.buildResourceFamiliesFile(t,r,o);}buildResourceFamiliesFile(e,t,r){this.cat("resource_families.py",()=>{this.generateDisclaimer(),this.includeResourceFamilyValidator(),this.line(),this.generateFamilyDefinitions(e,t),this.generateFamilyExports(r);});}includeResourceFamilyValidator(){let e=R__default.readFileSync(Ft("resource_family_validator.py"),"utf-8");this.line(e);}generateFamilyDefinitions(e,t){this.line(`packages = [${e.map(r=>`'${r}'`).join(", ")}]`),this.line();for(let[r,o]of Object.entries(t))this.generateFamilyDefinition(r,o);}generateFamilyDefinition(e,t){let r=`${e}_resources`;this.line(`${r} = [${t.map(o=>`'${o}'`).join(", ")}]`),this.line(),this.line(`def validate_and_downcast_${e}(v: Any) -> Any:`),this.line(` return validate_and_downcast(v, packages, ${r})`),this.line(),this.line(`type ${e} = Annotated[Any, BeforeValidator(validate_and_downcast_${e})]`),this.line();}generateFamilyExports(e){this.line(`__all__ = [${e.map(t=>`'${t}'`).join(", ")}]`);}buildPyPackageName(e){return (e?[$(e)]:[""]).join(".")}pyFhirPackage(e){return this.pyFhirPackageByName(e.package)}pyFhirPackageByName(e){return [this.opts.rootPackageName,this.buildPyPackageName(e)].join(".")}pyPackage(e){return e.kind==="complex-type"?`${this.pyFhirPackage(e)}.base`:e.kind==="resource"?[this.pyFhirPackage(e),$(e.name)].join("."):this.pyFhirPackage(e)}getFieldFormatFunction(e){return Me[e]?Me[e]:(this.logger()?.warn(`Unknown field format '${e}'. Defaulting to SnakeCase.`),this.logger()?.warn(`Supported formats: ${Object.keys(Me).join(", ")}`),$)}};function Be(i){let e=i.split("|")[0];return e||i}function hr(i){return i.split("|")[1]}function yr(i){return i.derivation==="constraint"?"profile":i.kind==="primitive-type"?"primitive-type":i.kind==="complex-type"?"complex-type":i.kind==="resource"?"resource":i.kind==="logical"?"logical":"resource"}function W(i){return {kind:yr(i),package:i.package_meta.name,version:i.package_meta.version,name:i.name,url:i.url}}var Sr=i=>{let e=i.split("/"),t=e[e.length-1];return t&&t.length>0?t.split(/[-_]/).map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join(""):i};function Se(i,e,t){let r=Be(t),o=Sr(r),n={package_meta:{name:"missing_valuesets",version:hr(r)||"0.0.0"},id:t},s=i.resolveVs(e,r)||n,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:r}}function be(i,e,t){let r=e.join("."),[o,n,s]=t?[{name:"shared",version:"1.0.0"},t,`urn:fhir:binding:${t}`]:[i.package_meta,`${i.name}.${r}_binding`,`${i.url}#${r}_binding`];return {kind:"binding",package:o.name,version:o.version,name:n,url:s}}function ve(i,e,t,r){let o={};if(e.derivation==="constraint"){let a=i.resolveFsSpecializations(e.package_meta,e.url).map(l=>_e(i,l,r)).filter(l=>l!==void 0).flat();for(let l of a.reverse())o[l.identifier.name]=l.identifier.url;}let n=t.join("."),s=o[n]??`${e.url}#${n}`;return {kind:"nested",package:e.package_meta.name,version:e.package_meta.version,name:n,url:s}}function It(i,e,t){let r=[];for(let[o,n]of Object.entries(t)){let s=[...e,o];ee(n)&&r.push([s,n]),n.elements&&r.push(...It(i,s,n.elements));}return r}function br(i,e,t,r,o){let n={};for(let[s,c]of Object.entries(r)){let a=[...t,s],l=i.resolveElementSnapshot(e,a);ee(l)?n[s]=Te(i,e,a,l,o):n[s]=Ce(i,e,a,l,o);}return n}function _e(i,e,t){if(!e.elements)return;let r=It(e,[],e.elements).filter(([n,s])=>s.elements&&Object.keys(s.elements).length>0),o=[];for(let[n,s]of r){let c=ve(i,e,n,t),a;s.type==="BackboneElement"||!s.type?a="BackboneElement":a=s.type;let l=i.ensureSpecializationCanonicalUrl(a),p=i.resolveFs(e.package_meta,l);if(!p)throw new Error(`Could not resolve base type ${a}`);let m={kind:"complex-type",package:p.package_meta.name,version:p.package_meta.version,name:a,url:l},y=br(i,e,n,s.elements??{},t),d={identifier:c,base:m,fields:y};o.push(d);}return o.sort((n,s)=>n.identifier.url.localeCompare(s.identifier.url)),o.length===0?void 0:o}function Pt(i){let e=[];for(let t of i){t.base&&e.push(t.base);for(let r of Object.values(t.fields||{}))"type"in r&&r.type&&e.push(r.type),"binding"in r&&r.binding&&e.push(r.binding);}return e}function wt(i,e,t){let r=t[t.length-1];if(!r)throw new Error(`Internal error: fieldName is missing for path ${t.join("/")}`);let o=t.slice(0,-1),n=i.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(n).has(r)}function $t(i,e,t){let r=t[t.length-1];if(!r)throw new Error(`Internal error: fieldName is missing for path ${t.join("/")}`);let o=t.slice(0,-1),n=i.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(n).has(r)}var vr=(i,e,t)=>{if(t.refers)return t.refers.map(r=>{let o=i.ensureSpecializationCanonicalUrl(r),n=i.resolveFs(e.package_meta,o);if(!n)throw new Error(`Failed to resolve fs for ${o}`);return W(n)})};function je(i,e,t,r,o){if(r.elementReference){let n=r.elementReference.slice(1).filter((s,c)=>c%2===1);return ve(i,e,n,o)}else if(r.type){let n=i.ensureSpecializationCanonicalUrl(r.type),s=i.resolveFs(e.package_meta,n);if(!s)throw new Error(`Could not resolve field type: '${r.type}' (from '${e.url}' in '${v(e.package_meta)}')`);return W(s)}else {if(r.choices)return;if(e.derivation==="constraint")return;throw o?.error(`Can't recognize element type '${e.url}' (${e.derivation}) at '${t.join(".")}': ${JSON.stringify(r,void 0,2)}`),new Error("Unrecognized element type")}}var Ce=(i,e,t,r,o)=>{let n,s;r.binding&&(n=be(e,t,r.binding.bindingName),r.binding.strength==="required"&&r.type==="code"&&(s=Ve(i,e,r,o)));let c=je(i,e,t,r,o);return c||o?.warn(`Field type not found for '${e.url}#${t.join(".")}' (${e.derivation})`),{type:c,required:wt(i,e,t),excluded:$t(i,e,t),reference:vr(i,e,r),array:r.array||false,min:r.min,max:r.max,choices:r.choices,choiceOf:r.choiceOf,binding:n,enum:s}};function ee(i){let e=i.type==="BackboneElement",t=i.type==="Element"&&i.elements!==void 0&&Object.keys(i.elements).length>0,r=i.type===void 0&&i.choiceOf===void 0&&i.elements!==void 0&&Object.keys(i.elements).length>0;return e||t||r}function Te(i,e,t,r,o){return {type:ve(i,e,t,o),array:r.array||false,required:wt(i,e,t),excluded:$t(i,e,t)}}function Ue(i,e,t,r){let o=Be(t)||t,n=i.resolveVs(e,o);if(n)return Tr(i,n)}function Tr(i,e,t){if(e.expansion?.contains)return e.expansion.contains.filter(o=>o.code!==void 0).map(o=>(ne(o.code),{code:o.code,display:o.display,system:o.system}));let r=[];if(e.compose?.include){for(let o of e.compose.include)if(o.concept)for(let n of o.concept)r.push({system:o.system,code:n.code,display:n.display});else if(o.system&&!o.filter)try{let n=i.resolveAny(o.system);if(n?.concept){let s=(c,a)=>{for(let l of c)r.push({system:a,code:l.code,display:l.display}),l.concept&&s(l.concept,a);};s(n.concept,o.system);}}catch{}}return r.length>0?r:void 0}var Et=100;function Ve(i,e,t,r){if(!t.binding)return;let o=t.binding.strength,n=t.binding.valueSet;if(!n||!(o==="required"||o==="extensible"&&(t.type==="code"||t.type==="Coding")||o==="preferred"&&(t.type==="code"||t.type==="Coding")))return;let c=Ue(i,e.package_meta,n);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>Et){r?.dry_warn(`Value set ${n} has ${a.length} which is more than ${Et} codes, which may cause issues with code generation.`);return}return a.length>0?a:void 0}function kr(i,e,t,r,o){if(!r.binding?.valueSet)return;let n=be(e,t,r.binding.bindingName),s=je(i,e,t,r,o),c=Se(i,e.package_meta,r.binding.valueSet),a=[];s&&a.push(s),a.push(c);let l=Ve(i,e,r,o);return {identifier:n,type:s,valueset:c,strength:r.binding.strength,enum:l,dependencies:a}}function Nt(i,e,t){let r=new Set;if(!e.elements)return [];let o=[];function n(a,l){for(let[p,m]of Object.entries(a)){let y=[...l,p],d=y.join(".");if(!r.has(d)){if(r.add(d),m.binding){let f=kr(i,e,y,m,t);f&&o.push(f);}m.elements&&n(m.elements,y);}}}n(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 Rr(i,e,t,r,o){if(!r)return;let n={};for(let s of i.getAllElementKeys(r)){let c=[...t,s],a=i.resolveElementSnapshot(e,c);ee(a)?n[s]=Te(i,e,c,a,o):n[s]=Ce(i,e,c,a,o);}return n}function xr(i){let e=[];for(let t of Object.values(i))"type"in t&&t.type&&e.push(t.type),"binding"in t&&t.binding&&e.push(t.binding);return e}function Fr(i,e){return !!(i.base==="Extension"||i.base==="http://hl7.org/fhir/StructureDefinition/Extension"||i.url?.includes("/extension/")||i.url?.includes("-extension")||i.name?.toLowerCase().includes("extension")||i.type==="Extension")}async function ke(i,e,t){if(!e.url)throw new Error("ValueSet URL is required");let r=Se(i,e.package_meta,e.url),o=Ue(i,e.package_meta,e.url);return {identifier:r,description:e.description,concept:o,compose:o?void 0:e.compose}}function Ae(i,e,t,r){let o=[];e&&o.push(e),t&&o.push(...xr(t)),r&&o.push(...Pt(r));let n={};for(let a of o)a.url!==i.url&&(n[a.url]=a);let s=new Set(r?.map(a=>a.identifier.url)),c=Object.values(n).filter(a=>ct(i)||!N(a)?true:!s.has(a.url)).sort((a,l)=>a.url.localeCompare(l.url));return c.length>0?c:void 0}function Ir(i,e,t){let r=W(e),o;if(e.base&&e.type!=="Element"){let p=i.resolveFs(e.package_meta,i.ensureSpecializationCanonicalUrl(e.base));if(!p)throw new Error(`Base resource not found '${e.base}' for <${e.url}> from ${v(e.package_meta)}`);o=W(p);}let n=Rr(i,e,[],e.elements,t),s=_e(i,e,t),c=Ae(r,o,n,s),a={identifier:r,base:o,fields:n,nested:s,description:e.description,dependencies:c},l=Nt(i,e,t);return [a,...l]}async function Re(i,e,t){let r=Ir(i,e,t);if(Fr(e,W(e))){let o=r[0];if(!o)throw new Error("Expected schema to be defined");o.metadata={isExtension:true};}return r}var He=i=>i!==null&&typeof i=="object"&&i.resourceType==="CodeSystem";var xe=i=>i!==null&&typeof i=="object"&&i.resourceType==="ValueSet";var Pr=async(i,e)=>{let r=(await i.packageJson(e.name)).dependencies;return r!==void 0?Object.entries(r).map(([o,n])=>({name:o,version:n})):[]},Lt=i=>({pkg:i,canonicalResolution:{},fhirSchemas:{},valueSets:{}}),Mt=async(i,e,t,r,o)=>{let n=v(e);if(o?.info(`${" ".repeat(t*2)}+ ${n}`),r[n])return r[n];let s=Lt(e);for(let a of await i.search({package:e})){let l=a.url;if(!l||!(isStructureDefinition(a)||xe(a)||He(a)))continue;let p=l;s.canonicalResolution[p]&&o?.dry_warn(`Duplicate canonical URL: ${p} at ${n}.`),s.canonicalResolution[p]=[{deep:t,pkg:e,pkgId:n,resource:a}];}let c=await Pr(i,e);for(let a of c){let{canonicalResolution:l}=await Mt(i,a,t+1,r,o);for(let[p,m]of Object.entries(l)){let y=p;s.canonicalResolution[y]=[...s.canonicalResolution[y]||[],...m];}}for(let a of Object.values(s.canonicalResolution))a.sort((l,p)=>l.deep-p.deep);return r[n]=s,s},Dt=(i,e,t)=>{let r=Object.values(i).flatMap(o=>o.canonicalResolution[e]);if(!r)throw new Error(`No canonical resolution found for ${e} in any package`);return r[0]?.resource},te=async(i,{logger:e,fallbackPackageForNameResolution:t,focusedPackages:r})=>{let o=r??await i.packages(),n={};for(let d of o)await Mt(i,d,0,n,e);for(let{pkg:d,canonicalResolution:f}of Object.values(n)){let h=v(d);if(!n[h])throw new Error(`Package ${h} not found`);let u=0;e?.info(`FHIR Schema conversion for '${v(d)}' begins...`);for(let[g,S]of Object.entries(f)){let C=S[0];if(!C)throw new Error("Resource not found");let b=C.resource,x=C.pkg;if(isStructureDefinition(b)){let U=Oe(Ot.translate(b),x);u++,n[h].fhirSchemas[U.url]=U;}if(xe(b)){let U=gt(b,x);n[h].valueSets[U.url]=U;}}e?.info(`FHIR Schema conversion for '${v(d)}' completed: ${u} successful`);}let s=(d,f)=>n[v(d)]?.fhirSchemas[f]||t&&n[v(t)]?.fhirSchemas[f],c=(d,f)=>n[v(d)]?.valueSets[f]||t&&n[v(t)]?.valueSets[f],a=d=>d.match(/^[a-zA-Z0-9]+$/)&&`http://hl7.org/fhir/StructureDefinition/${d}`||d,l=(d,f)=>{let h=s(d,f);if(h===void 0)throw new Error(`Failed to resolve FHIR Schema: '${f}'`);let u=[h];for(;h?.base;){let g=h.package_meta,S=a(h.base);if(h=s(g,S),h===void 0)throw new Error(`Failed to resolve FHIR Schema base for '${f}'. Problem: '${S}' from '${v(g)}'`);u.push(h);}return u};return {...i,testAppendFs(d){let f=Oe(d),h=v(f.package_meta);n[h]||(n[h]=Lt(f.package_meta)),n[h].fhirSchemas[f.url]=f;},resolveFs:s,resolveFsGenealogy:l,resolveFsSpecializations:(d,f)=>l(d,f).filter(h=>h.derivation==="specialization"),ensureSpecializationCanonicalUrl:a,resolveSd:(d,f)=>{let h=Dt(n,f);if(isStructureDefinition(h))return h},allFs:()=>Object.values(n).flatMap(d=>Object.values(d.fhirSchemas)),allVs:()=>Object.values(n).flatMap(d=>Object.values(d.valueSets)),resolveVs:c,resolveAny:d=>Dt(n,d),resolveElementSnapshot:(d,f)=>{let h=l(d.package_meta,d.url),u=wr(h,f);return $r(u)},getAllElementKeys:d=>{let f=new Set;for(let[h,u]of Object.entries(d)){f.add(h);for(let g of u?.choices||[])d[g]||f.add(g);}return Array.from(f)},resolver:n,resolutionTree:()=>{let d={};for(let[f,h]of Object.entries(n)){let u=h.pkg.name;d[u]={};for(let[g,S]of Object.entries(h.canonicalResolution)){let C=g;d[u][C]=[];for(let b of S)d[u][C].push({deep:b.deep,pkg:b.pkg});}}return d}}};var wr=(i,e)=>{let[t,...r]=e;return t===void 0?[]:i.map(o=>{if(!o.elements)return;let n=o.elements?.[t];for(let s of r)n=n?.elements?.[s];return n}).filter(o=>o!==void 0)};function $r(i){let e=i.reverse(),t=Object.assign({},...e);return t.elements=void 0,t}var re=class{manager;options;logger;constructor(e){this.options={...e},this.manager=e.manager,this.logger=e.logger||M({prefix:"TypeSchema"});}async registerFromPackageMetas(e){let t=e.map(v);return this.logger?.step(`Loading FHIR packages: ${t.join(", ")}`),await this.manager.init(),te(this.manager,{focusedPackages:e})}generateFhirSchemas(e){this.logger?.progress(`Converting ${e.length} StructureDefinitions to FHIRSchemas`);let t=[],r=0,o=0;for(let n of e)try{let s=Ot.translate(n);t.push(s),r++,this.logger?.debug(`Converted StructureDefinition: ${n.name||n.id} (${n.resourceType})`);}catch(s){o++,this.logger?.warn(`Failed to convert StructureDefinition ${n.name||n.id}: ${s instanceof Error?s.message:String(s)}`);}return this.logger?.success(`FHIR Schema conversion completed: ${r}/${e.length} successful, ${o} failed`),t}async generateValueSetSchemas(e,t){e.length>0&&this.logger?.debug(`${e.length} ValueSets available for enum extraction`);let r=await te(this.manager,{logger:this.logger}),o=[];if(e.length>0){this.logger?.progress(`Converting ${e.length} ValueSets to TypeSchema`);let n=0,s=0;for(let c of e)try{let a=await ke(r,c,t);a&&(o.push(a),n++,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: ${n}/${e.length} successful, ${s} failed`);}return o}async generateFromPackage(e,t,r){let o={name:e,version:t||"latest"},n=await this.registerFromPackageMetas([o]),s=await this.generateValueSetSchemas(n.allVs(),r);return [...(await Promise.all(n.allFs().map(async l=>await Re(n,l,r)))).flat(),...s]}};var ie="Use CodeableReference which is not provided by FHIR R4.",Er="Use Availability which is not provided by FHIR R4.",_t={"hl7.fhir.uv.extensions.r4#1.0.0":{"http://hl7.org/fhir/StructureDefinition/extended-contact-availability":Er,"http://hl7.org/fhir/StructureDefinition/immunization-procedure":ie,"http://hl7.org/fhir/StructureDefinition/specimen-additive":ie,"http://hl7.org/fhir/StructureDefinition/workflow-barrier":ie,"http://hl7.org/fhir/StructureDefinition/workflow-protectiveFactor":ie,"http://hl7.org/fhir/StructureDefinition/workflow-reason":ie},"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."}},jt=async(i,e)=>{let t=[];for(let r of i.allFs()){let o=v(r.package_meta);if(_t[o]?.[r.url]){e?.dry_warn(`Skip ${r.url} from ${o}. Reason: ${_t[o]?.[r.url]}`);continue}t.push(...await Re(i,r,e));}for(let r of i.allVs())t.push(await ke(i,r));return t};var Nr=(i,e)=>{let t={},r={};for(let o of e){let n=i.fields?.[o];if(!i.fields||!n)throw new Error(`Field ${o} not found`);if(I(n))r[o]||(r[o]={}),r[o].declaration=n.choices;else if(Le(n)){let s=n.choiceOf;r[s]||(r[s]={}),r[s].instances=[...r[s].instances??[],o];}else t[o]=n;}for(let[o,{declaration:n,instances:s}]of Object.entries(r)){let c=s??n;ne(c);for(let l of c){let p=i.fields?.[l];ne(p),t[l]=p;}let a=i.fields?.[o];ne(a),t[o]={...a,choices:c};}i.fields=t;},Dr=(i,e)=>{for(let t of e){let r=i.fields?.[t];if(!i.fields||!r)throw new Error(`Field ${t} not found`);if(i.fields){if(I(r))for(let o of r.choices)delete i.fields[o];if(Le(r)){let o=i.fields[r.choiceOf];ne(I(o)),o.choices=o.choices.filter(n=>n!==t),o.choices.length===0&&delete i.fields[r.choiceOf];}delete i.fields[t];}}},Or=(i,e,t)=>{if(i=structuredClone(i),pt(i)||ut(i)||dt(i))return i;if(e.selectFields){if(e.ignoreFields)throw new Error("Cannot use both ignoreFields and selectFields in the same rule");Nr(i,e.selectFields);}if(e.ignoreFields){if(e.selectFields)throw new Error("Cannot use both ignoreFields and selectFields in the same rule");Dr(i,e.ignoreFields);}if(i.nested){let r=new Set,o=n=>{Object.values(n.fields??{}).filter(G).filter(s=>N(s.type)).forEach(s=>{let c=s.type.url;if(!r.has(c)){r.add(c);let a=i.nested?.find(l=>l.identifier.url===c);ne(a),o(a);}});};o(i),i.nested=i.nested.filter(n=>r.has(n.identifier.url));}return i.dependencies=Ae(i.identifier,i.base,i.fields,i.nested),i},Vt=(i,e,{resolutionTree:t,logger:r})=>{let o=[];for(let[c,a]of Object.entries(e))for(let[l,p]of Object.entries(a)){let m=i.resolveByUrl(c,l);if(!m)throw new Error(`Schema not found for ${c} ${l}`);let y=Or(m,p);o.push(y);}let n=(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(_(p)){if(!p.dependencies)continue;if(p.dependencies.forEach(m=>{let y=i.resolve(m);if(!y)throw new Error(`Dependent schema ${JSON.stringify(m)} not found for ${JSON.stringify(p.identifier)}`);let d=JSON.stringify(y.identifier);a[d]||l.push(y);}),p.nested)for(let m of p.nested){if(N(m.identifier))continue;let y=JSON.stringify(m.identifier);a[y]||l.push(m);}}return n(l,a)},s=n(o,{});return me(s,{resolutionTree:t,logger:r})};var Lr={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"},Ut=i=>{let e=Lr[i];if(e===void 0)throw new Error(`Unknown primitive type ${i}`);return e},Ht=i=>nt(i),qe=i=>i.kind==="profile"?`${k(i)}_profile`:w(i.name),Mr=i=>`${qe(i)}.ts`,Fe=i=>`${Ht(i.package)}/${qe(i)}`,ze=(i,e=true)=>{if(!i)return;let t=pe(i,e);if(t)return We(t)},k=i=>{if(i.kind==="nested"){let e=i.url,t=ze(e,false);if(!t)return "";let[r,o]=t.split("#"),n=Y((o??"").split(".")).join("");return We([r,n].join(""))}return We(i.name)},Gt=new Set(["class","function","return","if","for","while","const","let","var","import","export","interface"]),Q=i=>Gt.has(i)?`"${i}"`:i.includes(" ")||i.includes("-")?`"${i}"`:i,We=i=>(Gt.has(i)&&(i=`${i}_`),i.replace(/[- ]/g,"_")),q=(i,e)=>e.startsWith('"')?`${i}[${e}]`:`${i}.${e}`,At=i=>`(${i.map(e=>`"${e}"`).join(" | ")})`,Ie=class extends B{tsImportType(e,...t){this.lineSM(`import type { ${t.join(", ")} } from "${e}"`);}generateFhirPackageIndexFile(e){this.cat("index.ts",()=>{let t=e.flatMap(r=>[{identifier:r.identifier,tsPackageName:qe(r.identifier),resourceName:k(r.identifier),nestedTypes:D(r)&&r.nested||j(r)&&r.nested?r.nested.map(o=>k(o.identifier)):[],helpers:D(r)||j(r)?[`is${k(r.identifier)}`]:[]}]).sort((r,o)=>r.resourceName.localeCompare(o.resourceName));t=Array.from(new Map(t.map(r=>[r.resourceName.toLowerCase(),r])).values()).sort((r,o)=>r.resourceName.localeCompare(o.resourceName));for(let r of t)this.debugComment(r.identifier),this.lineSM(`export type { ${[r.resourceName,...r.nestedTypes].join(", ")} } from "./${r.tsPackageName}"`),r.helpers.length>0&&this.lineSM(`export { ${r.helpers.join(", ")} } from "./${r.tsPackageName}"`);});}generateDependenciesImports(e,t){if(t.dependencies){let r=[],o=[];for(let n of t.dependencies)if(["complex-type","resource","logical"].includes(n.kind))r.push({tsPackage:`../${Fe(n)}`,name:E(n.name),dep:n});else if(N(n)){let s={...n};s.name=ze(n.url),r.push({tsPackage:`../${Fe(s)}`,name:k(n),dep:n});}else o.push(n);r.sort((n,s)=>n.name.localeCompare(s.name));for(let n of r)this.debugComment(n.dep),this.tsImportType(n.tsPackage,n.name);for(let n of o)this.debugComment("skip:",n);if(this.line(),this.withPrimitiveTypeExtension(t)&&t.identifier.name!=="Element"&&t.dependencies.find(n=>n.name==="Element")===void 0){let n="http://hl7.org/fhir/StructureDefinition/Element",s=e.resolveByUrl(t.identifier.package,n);if(!s)throw new Error(`'${n}' not found for ${t.identifier.package}.`);this.tsImportType(`../${Fe(s.identifier)}`,"Element");}}}generateComplexTypeReexports(e){let t=e.dependencies?.filter(at).map(r=>({tsPackage:`../${Fe(r)}`,name:E(r.name)}));if(t&&t.length>0){for(let r of t)this.lineSM(`export type { ${r.name} } from "${r.tsPackage}"`);this.line();}}addFieldExtension(e){let t=Q(`_${e}`);this.lineSM(`${t}?: Element`);}generateType(e,t){let r;t.identifier.name==="Reference"?r="Reference<T extends string = string>":(t.identifier.kind,r=k(t.identifier));let o;if(t.base&&(o=`extends ${ze(t.base.url)}`),this.debugComment(t.identifier),!t.fields&&!o&&!D(t)){this.lineSM(`export type ${r} = object`);return}this.curlyBlock(["export","interface",r,o],()=>{if(D(t)||j(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 n=Object.entries(t.fields).sort((s,c)=>s[0].localeCompare(c[0]));for(let[s,c]of n){if(I(c))continue;this.debugComment(s,":",c);let a=Q(s),l;c.enum?l=At(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(" | ")}>`:Z(c.type)?l=Ut(c.type.name):N(c.type)?l=k(c.type):l=c.type.name;let p=c.required?"":"?",m=c.array?"[]":"";this.lineSM(`${a}${p}: ${l}${m}`),this.withPrimitiveTypeExtension(t)&&Z(c.type)&&this.addFieldExtension(s);}});}withPrimitiveTypeExtension(e){if(!this.opts.primitiveTypeExtension||!_(e))return false;for(let t of Object.values(e.fields??{}))if(!I(t)&&Z(t.type))return true;return false}generateResourceTypePredicate(e){if(!D(e)&&!j(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 r of t.nested)this.generateType(e,r),this.line();}generateProfileType(e,t){this.debugComment("flatProfile",t);let r=k(t.identifier);this.debugComment("identifier",t.identifier),this.debugComment("base",t.base),this.curlyBlock(["export","interface",r],()=>{this.lineSM(`__profileUrl: "${t.identifier.url}"`),this.line();for(let[o,n]of Object.entries(t.fields??{})){if(I(n))continue;this.debugComment(o,n);let s=Q(o),c;if(n.enum)c=At(n.enum);else if(n.reference&&n.reference.length>0){let a=e.findLastSpecialization(t);if(!_(a))throw new Error(`Invalid specialization for ${t.identifier}`);let l=a.fields?.[o];if(l===void 0||I(l)||l.reference===void 0)throw new Error(`Invalid field declaration for ${o}`);let p=l.reference.map(y=>y.name),m=n.reference.map(y=>{let d=e.findLastSpecializationByIdentifier(y);return d.name!==y.name?`"${d.name}" /*${y.name}*/`:`'${y.name}'`}).join(" | ");p.length===1&&p[0]==="Resource"&&m!=='"Resource"'?c=`Reference<"Resource" /* ${m} */ >`:c=`Reference<${m}>`;}else if(N(n.type))c=k(n.type);else if(Z(n.type))c=Ut(n.type.name);else {if(n.type===void 0)throw new Error(`Undefined type for '${o}' field at ${st(t)}`);c=n.type.name;}this.lineSM(`${s}${n.required?"":"?"}: ${c}${n.array?"[]":""}`);}}),this.line();}generateAttachProfile(e){let t=k(e.base),r=k(e.identifier),o=Object.entries(e.fields||{}).filter(([n,s])=>s&&G(s)&&s.type!==void 0).map(([n])=>Q(n));this.curlyBlock([`export const attach_${r}_to_${t} =`,`(resource: ${t}, profile: ${r}): ${t}`,"=>"],()=>{this.curlyBlock(["return"],()=>{this.line("...resource,"),this.curlyBlock(["meta:"],()=>{this.line(`profile: ['${e.identifier.url}']`);},[","]),o.forEach(n=>{this.line(`${n}: ${q("profile",n)},`);});});}),this.line();}generateExtractProfile(e,t){let r=k(t.base),o=k(t.identifier),n=Object.entries(t.fields||{}).filter(([a,l])=>G(l)&&l.type!==void 0).map(([a])=>a),s=e.findLastSpecialization(t);if(!_(s))throw new Error(`Specialization not found for ${t.identifier.url}`);let c={};this.curlyBlock([`export const extract_${o}_from_${r} =`,`(resource: ${r}): ${o}`,"=>"],()=>{n.forEach(a=>{let l=Q(a),p=t.fields?.[a],m=s.fields?.[a];if(!G(p)||!G(m))return;p.required&&!m.required&&this.curlyBlock([`if (${q("resource",l)} === undefined)`],()=>this.lineSM(`throw new Error("'${l}' is required for ${t.identifier.url}")`));let y=p?.reference?.map(f=>f.name),d=m?.reference?.map(f=>f.name);if(y&&d&&y.length!==d.length){let f=`reference_is_valid_${l}`;this.curlyBlock(["const",f,"=","(ref?: Reference)","=>"],()=>{this.line("return !ref"),this.indentBlock(()=>{d.forEach(u=>{this.line(`|| ref.reference?.startsWith('${u}/')`);}),this.line(";");});});let h=p?.required?"":`!${q("resource",l)} || `;p.array?h+=`${q("resource",l)}.every( (ref) => ${f}(ref) )`:h+=`!${f}(${q("resource",l)})`,this.curlyBlock(["if (",h,")"],()=>{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}',`),n.forEach(a=>{let l=Q(a);c[a]?this.line(`${l}:`,`${q("resource",l)} as ${o}['${l}'],`):this.line(`${l}:`,`${q("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(ue(t)){let r=e.flatProfile(t);this.generateDependenciesImports(e,r),this.comment("CanonicalURL:",t.identifier.url),this.generateProfileType(e,r),this.generateAttachProfile(r),this.generateExtractProfile(e,r);}else throw new Error(`Profile generation not implemented for kind: ${t.identifier.kind}`)});}async generate(e){let t=[...e.collectComplexTypes(),...e.collectResources(),...e.collectLogicalModels(),...this.opts.generateProfile?e.collectProfiles().filter(o=>e.isWithMetaField(o)):[]],r=z(t);this.cd("/",()=>{for(let[o,n]of Object.entries(r)){let s=Ht(o);this.cd(s,()=>{for(let c of n)this.generateResourceModule(e,c);this.generateFhirPackageIndexFile(n);});}});}};var zt=i=>{let e=i.replace(/[^a-zA-Z0-9\-_.@#()]/g,"");return e.length===0?"unknown":e},_r=async(i,e)=>{e.info("Cleaning outputs...");try{e.info(`Clean ${i.outputDir}`),R.rmSync(i.outputDir,{recursive:!0,force:!0}),i.typeSchemaOutputDir&&(e.info(`Clean ${i.typeSchemaOutputDir}`),R.rmSync(i.typeSchemaOutputDir,{recursive:!0,force:!0})),i.exportTypeTree&&(e.info(`Clean ${i.exportTypeTree}`),R.rmSync(i.exportTypeTree,{recursive:!0,force:!0}));}catch(t){e.warn(`Error cleaning output directory: ${t instanceof Error?t.message:String(t)}`);}},jr=async(i,e,t)=>{await V.mkdir(e,{recursive:true}),t.info(`Writing TypeSchema files to ${e}/...`);let r={};for(let o of i){let n={name:o.identifier.package,version:o.identifier.version},s=zt(v(n)),c=zt(`${o.identifier.name}(${pe(o.identifier.url)})`),a=JSON.stringify(o,null,2),l=P.join(e,s,c);r[l]||(r[l]=[]),r[l]?.some(p=>p===a)||r[l].push(a);}for(let[o,n]of Object.entries(r))await Promise.all(n.map(async(s,c)=>{let a;c===0?a=`${o}.typeschema.json`:a=`${o}-${c}.typeschema.json`,await V.mkdir(P.dirname(a),{recursive:true}),await V.writeFile(a,s);}));},Vr=async(i,e,t)=>{t.info(`Writing TypeSchema files to: ${e}`),await V.mkdir(P.dirname(e),{recursive:true}),t.info(`Writing TypeSchemas to one file ${e}...`);for(let r of i){let o=JSON.stringify(r,null,2);await V.appendFile(e,`${o}
|
|
7
|
-
`);}},Ur=async(i,e,t)=>{if(e.typeSchemaOutputDir)try{P.extname(e.typeSchemaOutputDir)===".ndjson"?await Vr(i,e.typeSchemaOutputDir,t):await jr(i,e.typeSchemaOutputDir,t),t.info("Writing TypeSchema - DONE");}catch(r){if(t.error("Failed to write TypeSchema output",r instanceof Error?r:new Error(String(r))),e.throwException)throw r}},oe=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,registry:e.registry},this.typeSchemaConfig=e.typeSchemaConfig,this.logger=e.logger||M({prefix:"API",level:e.logLevel});}fromPackage(e,t){let r=de({name:e,version:t||"latest"});return this.packages.push(r),this}fromPackageRef(e){return this.packages.push(e),this}registry(e){return this.options.registry=e,this}localStructureDefinitions(e){return this.localStructurePackages.push(e),this}localTgzPackage(e){return this.localTgzArchives.push(P.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:P.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))},n=new Ie(o);return this.generators.set("typescript",n),this.logger.debug(`Configured TypeScript generator (${JSON.stringify(o,void 0,2)})`),this}python(e){let o={...{...{logger:this.logger,outputDir:this.options.outputDir,tabSize:4,withDebugComment:false,commentLinePrefix:"#"},rootPackageName:"fhir_types",fieldFormat:"snake_case"},...Object.fromEntries(Object.entries(e).filter(([s,c])=>c!==void 0))},n=new ye(o);return this.generators.set("python",n),this.logger.debug("Configured python generator"),this}csharp(e,t){let r=new ge({outputDir:P.join(this.options.outputDir,"/types"),staticSourceDir:t??void 0,targetNamespace:e,logger:new J({prefix:"C#",timestamp:true,suppressLoggingLevel:[]})});return this.generators.set("C#",r),this.logger.debug("Configured C# generator"),this}onProgress(e){return this.progressCallback=e,this}outputTo(e){this.logger.debug(`Setting output directory: ${e}`),this.options.outputDir=e;for(let t of this.generators.values())t.setOutputDir(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&&_r(this.options,this.logger),this.logger.info("Initialize Canonical Manager");let r=this.options.manager||CanonicalManager({packages:this.packages,workingDir:".codegen-cache/canonical-manager-cache",registry:this.options.registry||void 0});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 r.addLocalPackage({name:p.package.name,version:p.package.version,path:p.path,dependencies:p.dependencies?.map(m=>de(m))});for(let p of this.localTgzArchives)this.logger.info(`Registering local tgz package: ${p}`),await r.addTgzPackage({archivePath:p});let o=await r.init(),n=Object.values(o),s=await te(r,{logger:this.logger,focusedPackages:n}),c=await jt(s,this.logger);await Ur(c,this.options,this.logger);let a={resolutionTree:s.resolutionTree(),logger:this.logger},l=me(c,a);this.options.treeShake&&(l=Vt(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(r){if(this.logger.error("Code generation failed",r instanceof Error?r:new Error(String(r))),t.errors.push(r instanceof Error?r.message:String(r)),this.options.throwException)throw r}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[r,o]of this.generators.entries()){this.logger.info(`Generating ${r}...`);try{await o.generate(t);let n=o.writtenFiles();e.filesGenerated.push(...n.map(s=>s.absPath)),this.logger.info(`Generating ${r} finished successfully`);}catch(n){if(e.errors.push(`${r} generator failed: ${n instanceof Error?n.message:String(n)}`),this.options.throwException)throw n}}}};var Je={outputDir:"./generated",verbose:false,overwrite:true,validate:true,cache:true,cleanOutput:true,registry:"",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:""},we=["atomic-codegen.config.ts","atomic-codegen.config","atomic-codegen.config.json",".atomic-codegenrc","atomic-codegen.json",".atomic-codegen.json","codegen.config.json","codegen.json"],Ke=class{validate(e){let t={valid:true,errors:[],warnings:[]};if(!e||typeof e!="object")return t.valid=false,t.errors.push({path:"root",message:"Configuration must be an object",value:e}),t;let r=e;r.outputDir!==void 0&&typeof r.outputDir!="string"&&t.errors.push({path:"outputDir",message:"outputDir must be a string",value:r.outputDir});let o=["verbose","overwrite","validate","cache"];for(let n of o)r[n]!==void 0&&typeof r[n]!="boolean"&&t.errors.push({path:n,message:`${n} must be a boolean`,value:r[n]});if(r.typescript!==void 0){let n=this.validateTypeScriptConfig(r.typescript);t.errors.push(...n);}if(r.typeSchema!==void 0){let n=this.validateTypeSchemaConfig(r.typeSchema);t.errors.push(...n);}return r.packages!==void 0&&(Array.isArray(r.packages)?r.packages.forEach((n,s)=>{typeof n!="string"&&t.errors.push({path:`packages[${s}]`,message:"package name must be a string",value:n});}):t.errors.push({path:"packages",message:"packages must be an array",value:r.packages})),r.files!==void 0&&(Array.isArray(r.files)?r.files.forEach((n,s)=>{typeof n!="string"&&t.errors.push({path:`files[${s}]`,message:"file path must be a string",value:n});}):t.errors.push({path:"files",message:"files must be an array",value:r.files})),t.valid=t.errors.length===0,t.valid&&(t.config=r),t}validateTypeScriptConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript",message:"typescript config must be an object",value:e}),t;let r=e;r.moduleFormat!==void 0&&(["esm","cjs"].includes(r.moduleFormat)||t.push({path:"typescript.moduleFormat",message:'moduleFormat must be "esm" or "cjs"',value:r.moduleFormat})),r.namingConvention!==void 0&&(["PascalCase","camelCase"].includes(r.namingConvention)||t.push({path:"typescript.namingConvention",message:'namingConvention must be "PascalCase" or "camelCase"',value:r.namingConvention}));let o=["generateIndex","includeDocuments","strictMode","includeProfiles","includeExtensions","includeCodeSystems","includeOperations","generateValueSets","includeValueSetHelpers"];for(let n of o)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.${n}`,message:`${n} must be a boolean`,value:r[n]});if(r.validatorOptions!==void 0){let n=this.validateValidatorOptions(r.validatorOptions);t.push(...n);}if(r.guardOptions!==void 0){let n=this.validateGuardOptions(r.guardOptions);t.push(...n);}if(r.profileOptions!==void 0){let n=this.validateProfileOptions(r.profileOptions);t.push(...n);}return t}validateValidatorOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.validatorOptions",message:"validatorOptions must be an object",value:e}),t;let r=e,o=["includeCardinality","includeTypes","includeConstraints","includeInvariants","validateRequired","allowAdditional","strictValidation","collectMetrics","generateAssertions","generatePartialValidators","optimizePerformance","includeJSDoc","generateCompositeValidators"];for(let n of o)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.validatorOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateGuardOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.guardOptions",message:"guardOptions must be an object",value:e}),t;let r=e;r.targetTSVersion!==void 0&&(["3.8","4.0","4.5","5.0"].includes(r.targetTSVersion)||t.push({path:"typescript.guardOptions.targetTSVersion",message:'targetTSVersion must be one of: "3.8", "4.0", "4.5", "5.0"',value:r.targetTSVersion}));let o=["includeRuntimeValidation","includeErrorMessages","treeShakeable","strictGuards","includeNullChecks","verbose"];for(let n of o)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.guardOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateProfileOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.profileOptions",message:"profileOptions must be an object",value:e}),t;let r=e;r.generateKind!==void 0&&(["interface","type","both"].includes(r.generateKind)||t.push({path:"typescript.profileOptions.generateKind",message:'generateKind must be "interface", "type", or "both"',value:r.generateKind})),r.subfolder!==void 0&&typeof r.subfolder!="string"&&t.push({path:"typescript.profileOptions.subfolder",message:"subfolder must be a string",value:r.subfolder});let o=["includeConstraints","includeDocumentation","strictMode"];for(let n of o)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.profileOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateTypeSchemaConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typeSchema",message:"typeSchema config must be an object",value:e}),t;let r=e,o=["enablePersistence","validateCached","forceRegenerate","shareCache"];for(let s of o)r[s]!==void 0&&typeof r[s]!="boolean"&&t.push({path:`typeSchema.${s}`,message:`${s} must be a boolean`,value:r[s]});let n=["cacheDir","cacheKeyPrefix"];for(let s of n)r[s]!==void 0&&typeof r[s]!="string"&&t.push({path:`typeSchema.${s}`,message:`${s} must be a string`,value:r[s]});if(r.maxAge!==void 0&&(typeof r.maxAge!="number"||r.maxAge<=0)&&t.push({path:"typeSchema.maxAge",message:"maxAge must be a positive number",value:r.maxAge}),r.profiles!==void 0)if(typeof r.profiles!="object"||r.profiles===null)t.push({path:"typeSchema.profiles",message:"profiles must be an object",value:r.profiles});else {let s=r.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}},Ye=class{validator=new Ke;async autoload(e=process.cwd()){let t=await this.findConfigFile(e);return t?this.loadFromFile(t):{...Je}}async loadFromFile(e){try{let t;if(e.endsWith(".ts")||e.endsWith("")){let n=await import(resolve(e));t=n.default||n;}else {let o=await readFile(e,"utf-8");t=JSON.parse(o);}let r=this.validator.validate(t);if(!r.valid){let o=r.errors.map(n=>`${n.path}: ${n.message}`).join(`
|
|
6
|
+
`);for(let r of t)this.line(this.opts.commentLinePrefix,r);}debugComment(...e){this.opts.withDebugComment&&(e=e.map(t=>typeof t=="string"?t:JSON.stringify(t,null,2)),this.comment(...e));}disclaimer(){return ["WARNING: This file is autogenerated by @atomic-ehr/codegen.","GitHub: https://github.com/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,r){this.line(`${e.filter(Boolean).join(" ")} {`),this.indent(),t(),this.deindent(),this.line(`}${r?.filter(Boolean).join(" ")??""}`);}squareBlock(e,t,r){this.line(`${e.filter(Boolean).join(" ")} [`),this.indent(),t(),this.deindent(),this.line(`]${r?.filter(Boolean).join(" ")??""}`);}};var pe=(i,e=true)=>{let t=i.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),t};var b=i=>`${i.name}#${i.version}`,de=i=>`${i.name}@${i.version}`;var Oe=(i,e)=>(e||(e={name:"undefined",version:"undefined"}),{...i,package_meta:i.package_meta||e,name:i.name,url:i.url,base:i.base}),Z=i=>i?.kind==="primitive-type",N=i=>i?.kind==="nested",ct=i=>i?.kind==="complex-type",lt=i=>i?.kind==="profile";var _=i=>i?.identifier.kind==="resource"||i?.identifier.kind==="complex-type"||i?.identifier.kind==="logical",pt=i=>i?.identifier.kind==="complex-type",D=i=>i?.identifier.kind==="resource",dt=i=>i?.identifier.kind==="primitive-type",j=i=>i?.identifier.kind==="logical",ue=i=>i?.identifier.kind==="profile";function ut(i){return i?.identifier.kind==="binding"}function gt(i){return i?.identifier.kind==="value-set"}var G=i=>i?i.choices===void 0:false,I=i=>i?i.choices!==void 0:false,Le=i=>i?i.choiceOf!==void 0:false,ft=(i,e)=>{if(!i.url)throw new Error("ValueSet must have a URL");if(!i.name)throw new Error("ValueSet must have a name");return {...i,package_meta:i.package_meta||e,name:i.name,url:i.url}};var mt={"!":"Not","<=":"LessOrEqual",">=":"GreaterOrEqual","<":"Less",">":"Greater","=":"Equal","-":"Dash","+":"Plus","*":"Asterisk","/":"Slash","%":"Percent","&":"And","|":"Or","^":"Xor","~":"Tilde","?":"Question",".":"Dot"};function Qt(i){return i.split("-").map(e=>E(e)).join("-")}function Zt(i){let e=i;for(let t in mt)e=e.replaceAll(t,mt[t]??"");return e}function er(i){let e=Number(i[0]);return Number.isInteger(e)&&!Number.isNaN(e)?`_${i}`:i}function ht(i){let e=Qt(i);return e=er(e),e=Zt(e),e=E(e),e}function O(i){return E(le(i.replaceAll(".","-")))}var tr={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"},rr=["Reference","Expression"],ir=i=>i.required?["required"]:[],nr=i=>{let e=bt(vt(i.identifier));return E(e)},or=i=>i.base?`: ${i.base.name}`:"",sr=(i,e=true)=>{if(!i)return;let t=i.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),O(t)},vt=i=>{if(i.kind==="nested"){let e=i.url,t=sr(e,false);if(!t)return "";let[r,o]=t.split("#"),n=Y((o??"").split(".")).join("");return O([r,n].join(""))}return O(i.name)},ar=i=>rr.includes(i),bt=i=>ar(i)?`Resource${i}`:i,ge=class extends B{enums={};constructor(e){super({tabSize:4,withDebugComment:false,commentLinePrefix:"//",...e});}async generate(e){let t=e.collectComplexTypes(),r=e.collectResources(),o=Array.from(new Set(r.map(n=>O(n.identifier.package))));this.generateAllFiles(t,r,o),this.copyStaticFiles();}generateAllFiles(e,t,r){this.generateUsingFile(r),this.generateBaseTypes(e),this.generateResources(t),this.generateEnumFiles(r),this.generateResourceDictionaries(t,r),this.generateHelperFile();}generateType(e,t){let r=nr(e),o=or(e);this.curlyBlock(["public","class",r,o],()=>{this.generateFields(e,t),this.generateNestedTypes(e,t),this.line(),this.includeHelperMethods();}),this.line();}generateFields(e,t){if(!e.fields)return;let r=Object.entries(e.fields).sort(([o],[n])=>o.localeCompare(n));for(let[o,n]of r)this.generateField(o,n,t);}generateNestedTypes(e,t){if(!(!("nested"in e)||!e.nested)){this.line();for(let r of e.nested)this.generateType(r,t);}}generateField(e,t,r){try{if(I(t))return;let o=this.buildFieldDeclaration(e,t,r);this.line(...o);}catch(o){this.logger()?.error(`Error processing field ${e}: ${o.message}`);}}buildFieldDeclaration(e,t,r){let o=this.determineFieldType(e,t,r),n=ir(t),s=P(e);return ["public",...n,o,s,"{ get; set; }"].filter(Boolean)}determineFieldType(e,t,r){let o=this.getBaseTypeName(t);"enum"in t&&t.enum&&(o=this.registerAndGetEnumType(e,t,r)),o=bt(o);let n="",s=t.required?"":"?",c=t.array?"[]":"";return `${n}${o}${c}${s}`}getBaseTypeName(e){if("type"in e){let t=e.type.name.toString();return e.type.kind==="nested"?t=vt(e.type):e.type.kind==="primitive-type"&&(t=tr[e.type.name]??"string"),t}return ""}registerAndGetEnumType(e,t,r){let n=`${O(t.binding?.name??e)}Enum`;return this.enums[r]||(this.enums[r]={}),t.enum&&(this.enums[r][n]=t.enum),n}includeHelperMethods(){this.line("public override string ToString() => "),this.line(" JsonSerializer.Serialize(this, Helper.JsonSerializerOptions);"),this.line();}generateUsingFile(e){this.cd("/",async()=>{this.cat("Usings.cs",()=>{this.generateDisclaimer(),this.generateGlobalUsings(e);});});}generateGlobalUsings(e){let t=["CSharpSDK","System.Text.Json","System.Text.Json.Serialization",this.opts.targetNamespace,...e.map(r=>`${this.opts.targetNamespace}.${r}`)];for(let r of t)this.lineSM("global","using",r);}generateBaseTypes(e){this.cd("/",async()=>{this.cat("base.cs",()=>{this.generateDisclaimer(),this.line(),this.lineSM("namespace",this.opts.targetNamespace);for(let t of e){let r=O(t.identifier.package);this.generateType(t,r);}});});}generateResources(e){for(let t of e)this.generateResourceFile(t);}generateResourceFile(e){let t=O(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[r,o]of Object.entries(t))this.generateEnum(r,o);}generateEnum(e,t){this.curlyBlock(["public","enum",e],()=>{for(let r of t)this.line(`[Description("${r}")]`),this.line(`${ht(r)},`);}),this.line();}generateResourceDictionaries(e,t){this.cd("/",async()=>{for(let r of t){let o=e.filter(n=>O(n.identifier.package)===r);if(o.length===0)return;this.cat(`${r}ResourceDictionary.cs`,()=>{this.generateDisclaimer(),this.line(),this.lineSM(`namespace ${this.opts.targetNamespace}`),this.generateResourceDictionaryClass(r,o);});}});}generateResourceDictionaryClass(e,t){this.curlyBlock(["public","static","class","ResourceDictionary"],()=>{this.curlyBlock(["public static readonly Dictionary<Type, string> Map = new()"],()=>{for(let r of t){let o=r.identifier.name;this.line(`{ typeof(${e}.${o}), "${o}" },`);}}),this.lineSM();});}copyStaticFiles(){if(!this.opts.staticSourceDir)return;let e=w__default.resolve(this.opts.staticSourceDir);k__default.cpSync(e,this.opts.outputDir,{recursive:true});}generateHelperFile(){let e="src/api/writer-generator/csharp/Helper.cs",t=w__default.join(this.opts.outputDir,"Helper.cs");k__default.copyFileSync(e,t);}};var z=i=>{let e={};for(let t of i){let r=t.identifier.package;e[r]||(e[r]=[]),e[r].push(t);}for(let[t,r]of Object.entries(e)){let o={};for(let s of r)o[JSON.stringify(s.identifier)]=s;let n=Object.values(o);n.sort((s,c)=>s.identifier.name.localeCompare(c.identifier.name)),e[t]=n;}return e},cr=i=>{let e={};for(let r of i)e[r.identifier.name]=r;let t={};for(let r of i){let o=r.identifier.name,n=r.base?.name;t[o]||(t[o]=[]),n&&e[n]&&t[o].push(n);}return t},lr=i=>{let e=[],t={},r={},o=n=>{if(r[n])throw new Error(`Graph has cycles ${n}`);if(!t[n]){r[n]=true;for(let s of i[n]??[])o(s);r[n]=false,t[n]=true,e.push(n);}};for(let n in i)t[n]||o(n);return e},Rt=i=>{let e=cr(i);return lr(e).map(r=>i.find(o=>o.identifier.name===r)).filter(Boolean)},pr=i=>{let e=i.filter(n=>D(n)||j(n)),t=[];for(let n of e)n.base&&t.push({parent:n.base,child:n.identifier});let r=[...t],o=n=>{let s=t.filter(a=>a.parent.name===n.name).map(a=>a.child),c=[];for(let a of s)c.push(...o(a));return [...s,...c]};for(let n of t){let s=o(n.child);for(let c of s)t.some(a=>a.parent.name===n.parent.name&&a.child.name===c.name)||r.push({parent:n.parent,child:c});}return r},me=(i,{resolutionTree:e,logger:t})=>{let r={},o=u=>{let g=u.identifier.url,S=u.identifier.package;if(r[g]||(r[g]={}),r[g][u.identifier.package]&&S!=="shared"){let C=JSON.stringify(u.identifier,void 0,2),v=JSON.stringify(r[g][S]?.identifier,void 0,2);if(C!==v)throw new Error(`Duplicate schema: ${C} and ${v}`);return}r[g][S]=u;};for(let u of i)o(u);let n=pr(i),s=u=>r[u.url]?.[u.package],c=(u,g)=>{if(e){let S=e[u]?.[g]?.[0];if(S)return r[g]?.[S.pkg.name]}return r[g]?.[u]},a=u=>n.filter(g=>g.parent.name===u.name).map(g=>g.child),l=u=>{let g=[],S=u;for(;S;){g.push(S);let C=S.base;if(C===void 0)break;let v=s(C);if(!v){t?.warn(`Failed to resolve base type: ${g.map(x=>`${x.identifier.url} (${x.identifier.kind})`).join(", ")}`);return}S=v;}return g},p=u=>{let g=l(u);if(g===void 0)throw new Error(`Failed to resolve base type: ${u.identifier.url} (${u.identifier.kind})`);return g},m=u=>{let g=p(u).find(S=>S.identifier.kind!=="profile");if(!g)throw new Error(`No non-constraint schema found in hierarchy for: ${u.identifier.name}`);return g};return {_schemaIndex:r,_relations:n,collectComplexTypes:()=>i.filter(pt),collectResources:()=>i.filter(D),collectLogicalModels:()=>i.filter(j),collectProfiles:()=>i.filter(ue),resolve:s,resolveByUrl:c,resourceChildren:a,tryHierarchy:l,hierarchy:p,findLastSpecialization:m,findLastSpecializationByIdentifier:u=>{let g=s(u);return g?m(g).identifier:u},flatProfile:u=>{let g=p(u),S=g.filter(L=>L.identifier.kind==="profile"),C=g.find(L=>L.identifier.kind!=="profile");if(!C)throw new Error(`No non-constraint schema found in hierarchy for ${u.identifier.name}`);let v={};for(let L of S.slice().reverse()){let se=L;if(se.fields)for(let[ae,Qe]of Object.entries(se.fields))v[ae]?v[ae]={...v[ae],...Qe}:v[ae]={...Qe};}let x={};for(let L of S.flatMap(se=>se.dependencies??[]))x[L.url]=L;let U=Object.values(x);return {...u,base:C.identifier,fields:v,dependencies:U}},isWithMetaField:u=>{let g=l(u);return g?g.filter(_).some(S=>S.fields?.meta!==void 0):false},exportTree:async u=>{let g={};for(let[C,v]of Object.entries(z(i))){g[C]={"primitive-type":{},"complex-type":{},resource:{},"value-set":{},nested:{},binding:{},profile:{},logical:{}};for(let x of v)g[C][x.identifier.kind][x.identifier.url]={};}let S=u.endsWith(".yaml")?Tt.stringify(g):JSON.stringify(g,void 0,2);await V.mkdir(w.dirname(u),{recursive:true}),await V.writeFile(u,S);}}};var ur={boolean:"bool",instant:"str",time:"str",date:"str",dateTime:"str",decimal:"float",integer:"int",unsignedInt:"int",positiveInt:"PositiveInt",integer64:"int",base64Binary:"str",uri:"str",url:"str",canonical:"str",oid:"str",uuid:"str",string:"str",code:"str",markdown:"str",id:"str",xhtml:"str"},Me={snake_case:$,PascalCase:P,camelCase:le},gr=new Set(["False","None","True","and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","List"]),Ft=100,fr=i=>gr.has(i)?`${i}_`:i,mr=i=>i==="Resource"||i==="Element"?["BaseModel"]:[],hr=(i,e=true)=>{if(!i)return;let t=i.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),$(t)},he=i=>{if(i.kind==="nested"){let e=i.url,t=hr(e,false);if(!t)return "";let[r,o]=t.split("#"),n=Y((o??"").split(".")).join("");return P([r,n].join(""))}return P(i.name)},It=i=>{let e=w.dirname(fileURLToPath(import.meta.url));return __filename.endsWith("dist/index.js")?w.resolve(e,"..","assets","api","writer-generator","python",i):w.resolve(e,"../../..","assets","api","writer-generator","python",i)},ye=class extends B{nameFormatFunction;tsIndex;constructor(e){super(e),this.nameFormatFunction=this.getFieldFormatFunction(e.fieldFormat);}async generate(e){this.tsIndex=e;let t={groupedComplexTypes:z(e.collectComplexTypes()),groupedResources:z(e.collectResources())};this.generateRootPackages(t),this.generateSDKPackages(t);}generateRootPackages(e){this.generateRootInitFile(e),k__default.cpSync(It("requirements.txt"),w.resolve(this.opts.outputDir,"requirements.txt"));}generateSDKPackages(e){this.generateComplexTypesPackages(e.groupedComplexTypes),this.generateResourcePackages(e);}generateComplexTypesPackages(e){for(let[t,r]of Object.entries(e))this.cd(`/${$(t)}`,()=>{this.generateBasePy(r);});}generateResourcePackages(e){for(let[t,r]of Object.entries(e.groupedResources))this.cd(`/${$(t)}`,()=>{this.generateResourcePackageContent(t,r,e.groupedComplexTypes[t]||[]);});}generateResourcePackageContent(e,t,r){let o=this.pyFhirPackageByName(e);this.generateResourcePackageInit(o,t,r),this.generateResourceFamilies(t);for(let n of t)this.generateResourceModule(n);}generateRootInitFile(e){this.cd("/",()=>{this.cat("__init__.py",()=>{this.generateDisclaimer();let t=this.collectAndImportAllModels(e);this.generateModelRebuilds(t);});});}collectAndImportAllModels(e){let t=[];for(let r of Object.keys(e.groupedResources)){let o=this.pyFhirPackageByName(r);t.push(...this.importComplexTypes(o,e.groupedComplexTypes[r])),t.push(...this.importResources(o,false,e.groupedResources[r]));}return this.line(),t}generateModelRebuilds(e){for(let t of e.sort())this.line(`${t}.model_rebuild()`);}generateBasePy(e){this.cat("base.py",()=>{this.generateDisclaimer(),this.generateDefaultImports(),this.line(),this.generateComplexTypes(e),this.line();});}generateComplexTypes(e){for(let t of Rt(e))this.generateNestedTypes(t),this.line(),this.generateType(t);}generateResourcePackageInit(e,t,r){this.cat("__init__.py",()=>{this.generateDisclaimer(),this.importComplexTypes(e,r);let o=this.importResources(e,true,t);this.line(),this.generateExportsDeclaration(r,o);});}importComplexTypes(e,t){if(!t||t.length===0)return [];let r=t.map(o=>o.identifier.name).sort();return this.pyImportFrom(`${e}.base`,...r),this.line(),r}buildImportLine(e,t){let r="";for(;e.length>0&&r.length<t;){let o=e.shift();if(!o)throw new Error("Unexpected empty entity");r.length>0&&(r+=", "),r+=o;}return e.length>0&&(r+=", \\"),r}importResources(e,t,r){if(!r||r.length===0)return [];let o=[];for(let n of r){let s=this.importOneResource(n,e);!t&&!n.fields||o.push(...s);}return o}importOneResource(e,t){let r=`${t}.${$(e.identifier.name)}`,o=this.collectResourceImportNames(e);this.pyImportFrom(r,...o);let n=[...o];if(this.shouldImportResourceFamily(e)){let s=`${e.identifier.name}Family`;this.pyImportFrom(`${t}.resource_families`,s);}return n}collectResourceImportNames(e){let t=[he(e.identifier)];for(let r of e.nested??[]){let o=he(r.identifier);t.push(o);}return t}shouldImportResourceFamily(e){return ne(this.tsIndex!==void 0),e.identifier.kind==="resource"&&this.tsIndex.resourceChildren(e.identifier).length>0}generateExportsDeclaration(e,t){this.squareBlock(["__all__","="],()=>{let r=[...(e||[]).map(o=>o.identifier.name),...t].sort();for(let o of r)this.line(`'${o}',`);});}generateResourceModule(e){this.cat(`${$(e.identifier.name)}.py`,()=>{this.generateDisclaimer(),this.generateDefaultImports(),this.line(),this.generateDependenciesImports(e),this.line(),this.generateNestedTypes(e),this.line(),this.generateType(e);});}generateType(e){let t=he(e.identifier),r=this.getSuperClasses(e);this.line(`class ${t}(${r.join(", ")}):`),this.indentBlock(()=>{this.generateClassBody(e);}),this.line();}getSuperClasses(e){return [...e.base?[e.base.name]:[],...mr(e.identifier.name)]}generateClassBody(e){if(this.generateModelConfig(),!e.fields){this.line("pass");return}e.identifier.kind==="resource"&&this.generateResourceTypeField(e),this.generateFields(e),e.identifier.kind==="resource"&&this.generateResourceMethods(e);}generateModelConfig(){let e=this.opts.allowExtraFields?"allow":"forbid";this.line(`model_config = ConfigDict(validate_by_name=True, serialize_by_alias=True, extra="${e}")`);}generateResourceTypeField(e){this.line(`${this.nameFormatFunction("resourceType")}: str = Field(`),this.indentBlock(()=>{this.line(`default='${e.identifier.name}',`),this.line("alias='resourceType',"),this.line("serialization_alias='resourceType',"),this.line("frozen=True,"),this.line(`pattern='${e.identifier.name}'`);}),this.line(")");}generateFields(e){let t=Object.entries(e.fields??[]).sort(([r],[o])=>r.localeCompare(o));for(let[r,o]of t){if("choices"in o&&o.choices)continue;let n=this.buildFieldInfo(r,o);this.line(`${n.name}: ${n.type}${n.defaultValue}`);}}buildFieldInfo(e,t){let r=fr(this.nameFormatFunction(e)),o=this.determineFieldType(t),n=this.getFieldDefaultValue(t,e);return {name:r,type:o,defaultValue:n}}determineFieldType(e){let t=e?this.getBaseFieldType(e):"";return "enum"in e&&e.enum&&(t=`Literal[${e.enum.map(o=>`"${o}"`).join(", ")}]`),e.array&&(t=`PyList[${t}]`),e.required||(t=`${t} | None`),t}getBaseFieldType(e){return "type"in e&&e.type.kind==="resource"?`${e.type.name}Family`:"type"in e&&e.type.kind==="nested"?he(e.type):"type"in e&&e.type.kind==="primitive-type"?ur[e.type.name]??"str":"type"in e?e.type.name:""}getFieldDefaultValue(e,t){let r=`alias="${t}", serialization_alias="${t}"`;return e.required?` = Field(${r})`:` = Field(None, ${r})`}generateResourceMethods(e){let t=e.identifier.name.toString();this.line(),this.line("def to_json(self, indent: int | None = None) -> str:"),this.line(" return self.model_dump_json(exclude_unset=True, exclude_none=True, indent=indent)"),this.line(),this.line("@classmethod"),this.line(`def from_json(cls, json: str) -> ${t}:`),this.line(" return cls.model_validate_json(json)");}generateNestedTypes(e){if(e.nested){this.line();for(let t of e.nested)this.generateType(t);}}generateDefaultImports(){this.pyImportFrom("__future__","annotations"),this.pyImportFrom("pydantic","BaseModel","ConfigDict","Field","PositiveInt"),this.pyImportFrom("typing","List as PyList","Literal");}generateDependenciesImports(e){!e.dependencies||e.dependencies.length===0||(this.importComplexTypeDependencies(e.dependencies),this.importResourceDependencies(e.dependencies));}importComplexTypeDependencies(e){let t=e.filter(o=>o.kind==="complex-type"),r=this.groupDependenciesByPackage(t);for(let[o,n]of Object.entries(r))this.pyImportFrom(o,...n.sort());}importResourceDependencies(e){let t=e.filter(r=>r.kind==="resource");for(let r of t){this.pyImportType(r);let o=`${P(r.name)}Family`,n=`${this.pyFhirPackage(r)}.resource_families`;this.pyImportFrom(n,o);}}groupDependenciesByPackage(e){let t={};for(let r of e){let o=this.pyPackage(r);t[o]||(t[o]=[]),t[o].push(r.name);}return t}pyImportFrom(e,...t){let r=`from ${e} import ${t.join(", ")}`;this.shouldUseSingleLineImport(r,t)?this.line(r):this.writeMultiLineImport(e,t);}shouldUseSingleLineImport(e,t){return e.length<=Ft||t.length===1}writeMultiLineImport(e,t){this.line(`from ${e} import (\\`),this.indentBlock(()=>{let r=[...t];for(;r.length>0;){let o=this.buildImportLine(r,Ft);this.line(o);}}),this.line(")");}pyImportType(e){this.pyImportFrom(this.pyPackage(e),P(e.name));}generateResourceFamilies(e){ne(this.tsIndex!==void 0);let t=Object.keys(z(e)).map(n=>`${this.opts.rootPackageName}.${n.replaceAll(".","_")}`),r={};for(let n of this.tsIndex.collectResources()){let s=this.tsIndex.resourceChildren(n.identifier).map(c=>c.name);if(s.length>0){let c=`${n.identifier.name}Family`;r[c]=s;}}let o=Object.keys(r);o.length!==0&&this.buildResourceFamiliesFile(t,r,o);}buildResourceFamiliesFile(e,t,r){this.cat("resource_families.py",()=>{this.generateDisclaimer(),this.includeResourceFamilyValidator(),this.line(),this.generateFamilyDefinitions(e,t),this.generateFamilyExports(r);});}includeResourceFamilyValidator(){let e=k__default.readFileSync(It("resource_family_validator.py"),"utf-8");this.line(e);}generateFamilyDefinitions(e,t){this.line(`packages = [${e.map(r=>`'${r}'`).join(", ")}]`),this.line();for(let[r,o]of Object.entries(t))this.generateFamilyDefinition(r,o);}generateFamilyDefinition(e,t){let r=`${e}_resources`;this.line(`${r} = [${t.map(o=>`'${o}'`).join(", ")}]`),this.line(),this.line(`def validate_and_downcast_${e}(v: Any) -> Any:`),this.line(` return validate_and_downcast(v, packages, ${r})`),this.line(),this.line(`type ${e} = Annotated[Any, BeforeValidator(validate_and_downcast_${e})]`),this.line();}generateFamilyExports(e){this.line(`__all__ = [${e.map(t=>`'${t}'`).join(", ")}]`);}buildPyPackageName(e){return (e?[$(e)]:[""]).join(".")}pyFhirPackage(e){return this.pyFhirPackageByName(e.package)}pyFhirPackageByName(e){return [this.opts.rootPackageName,this.buildPyPackageName(e)].join(".")}pyPackage(e){return e.kind==="complex-type"?`${this.pyFhirPackage(e)}.base`:e.kind==="resource"?[this.pyFhirPackage(e),$(e.name)].join("."):this.pyFhirPackage(e)}getFieldFormatFunction(e){return Me[e]?Me[e]:(this.logger()?.warn(`Unknown field format '${e}'. Defaulting to SnakeCase.`),this.logger()?.warn(`Supported formats: ${Object.keys(Me).join(", ")}`),$)}};function Be(i){let e=i.split("|")[0];return e||i}function yr(i){return i.split("|")[1]}function Sr(i){return i.derivation==="constraint"?"profile":i.kind==="primitive-type"?"primitive-type":i.kind==="complex-type"?"complex-type":i.kind==="resource"?"resource":i.kind==="logical"?"logical":"resource"}function W(i){return {kind:Sr(i),package:i.package_meta.name,version:i.package_meta.version,name:i.name,url:i.url}}var vr=i=>{let e=i.split("/"),t=e[e.length-1];return t&&t.length>0?t.split(/[-_]/).map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join(""):i};function Se(i,e,t){let r=Be(t),o=vr(r),n={package_meta:{name:"missing_valuesets",version:yr(r)||"0.0.0"},id:t},s=i.resolveVs(e,r)||n,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:r}}function ve(i,e,t){let r=e.join("."),[o,n,s]=t?[{name:"shared",version:"1.0.0"},t,`urn:fhir:binding:${t}`]:[i.package_meta,`${i.name}.${r}_binding`,`${i.url}#${r}_binding`];return {kind:"binding",package:o.name,version:o.version,name:n,url:s}}function be(i,e,t,r){let o={};if(e.derivation==="constraint"){let a=i.resolveFsSpecializations(e.package_meta,e.url).map(l=>_e(i,l,r)).filter(l=>l!==void 0).flat();for(let l of a.reverse())o[l.identifier.name]=l.identifier.url;}let n=t.join("."),s=o[n]??`${e.url}#${n}`;return {kind:"nested",package:e.package_meta.name,version:e.package_meta.version,name:n,url:s}}function wt(i,e,t){let r=[];for(let[o,n]of Object.entries(t)){let s=[...e,o];ee(n)&&r.push([s,n]),n.elements&&r.push(...wt(i,s,n.elements));}return r}function br(i,e,t,r,o){let n={};for(let[s,c]of Object.entries(r)){let a=[...t,s],l=i.resolveElementSnapshot(e,a);ee(l)?n[s]=Te(i,e,a,l,o):n[s]=Ce(i,e,a,l,o);}return n}function _e(i,e,t){if(!e.elements)return;let r=wt(e,[],e.elements).filter(([n,s])=>s.elements&&Object.keys(s.elements).length>0),o=[];for(let[n,s]of r){let c=be(i,e,n,t),a;s.type==="BackboneElement"||!s.type?a="BackboneElement":a=s.type;let l=i.ensureSpecializationCanonicalUrl(a),p=i.resolveFs(e.package_meta,l);if(!p)throw new Error(`Could not resolve base type ${a}`);let m={kind:"complex-type",package:p.package_meta.name,version:p.package_meta.version,name:a,url:l},y=br(i,e,n,s.elements??{},t),d={identifier:c,base:m,fields:y};o.push(d);}return o.sort((n,s)=>n.identifier.url.localeCompare(s.identifier.url)),o.length===0?void 0:o}function Pt(i){let e=[];for(let t of i){t.base&&e.push(t.base);for(let r of Object.values(t.fields||{}))"type"in r&&r.type&&e.push(r.type),"binding"in r&&r.binding&&e.push(r.binding);}return e}function $t(i,e,t){let r=t[t.length-1];if(!r)throw new Error(`Internal error: fieldName is missing for path ${t.join("/")}`);let o=t.slice(0,-1),n=i.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(n).has(r)}function Et(i,e,t){let r=t[t.length-1];if(!r)throw new Error(`Internal error: fieldName is missing for path ${t.join("/")}`);let o=t.slice(0,-1),n=i.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(n).has(r)}var Cr=(i,e,t)=>{if(t.refers)return t.refers.map(r=>{let o=i.ensureSpecializationCanonicalUrl(r),n=i.resolveFs(e.package_meta,o);if(!n)throw new Error(`Failed to resolve fs for ${o}`);return W(n)})};function je(i,e,t,r,o){if(r.elementReference){let n=r.elementReference.slice(1).filter((s,c)=>c%2===1);return be(i,e,n,o)}else if(r.type){let n=i.ensureSpecializationCanonicalUrl(r.type),s=i.resolveFs(e.package_meta,n);if(!s)throw new Error(`Could not resolve field type: '${r.type}' (from '${e.url}' in '${b(e.package_meta)}')`);return W(s)}else {if(r.choices)return;if(e.derivation==="constraint")return;throw o?.error(`Can't recognize element type '${e.url}' (${e.derivation}) at '${t.join(".")}': ${JSON.stringify(r,void 0,2)}`),new Error("Unrecognized element type")}}var Ce=(i,e,t,r,o)=>{let n,s;r.binding&&(n=ve(e,t,r.binding.bindingName),r.binding.strength==="required"&&r.type==="code"&&(s=Ve(i,e,r,o)));let c=je(i,e,t,r,o);return c||o?.warn(`Field type not found for '${e.url}#${t.join(".")}' (${e.derivation})`),{type:c,required:$t(i,e,t),excluded:Et(i,e,t),reference:Cr(i,e,r),array:r.array||false,min:r.min,max:r.max,choices:r.choices,choiceOf:r.choiceOf,binding:n,enum:s}};function ee(i){let e=i.type==="BackboneElement",t=i.type==="Element"&&i.elements!==void 0&&Object.keys(i.elements).length>0,r=i.type===void 0&&i.choiceOf===void 0&&i.elements!==void 0&&Object.keys(i.elements).length>0;return e||t||r}function Te(i,e,t,r,o){return {type:be(i,e,t,o),array:r.array||false,required:$t(i,e,t),excluded:Et(i,e,t)}}function Ue(i,e,t,r){let o=Be(t)||t,n=i.resolveVs(e,o);if(n)return Rr(i,n)}function Rr(i,e,t){if(e.expansion?.contains)return e.expansion.contains.filter(o=>o.code!==void 0).map(o=>(ne(o.code),{code:o.code,display:o.display,system:o.system}));let r=[];if(e.compose?.include){for(let o of e.compose.include)if(o.concept)for(let n of o.concept)r.push({system:o.system,code:n.code,display:n.display});else if(o.system&&!o.filter)try{let n=i.resolveAny(o.system);if(n?.concept){let s=(c,a)=>{for(let l of c)r.push({system:a,code:l.code,display:l.display}),l.concept&&s(l.concept,a);};s(n.concept,o.system);}}catch{}}return r.length>0?r:void 0}var Nt=100;function Ve(i,e,t,r){if(!t.binding)return;let o=t.binding.strength,n=t.binding.valueSet;if(!n||!(o==="required"||o==="extensible"&&(t.type==="code"||t.type==="Coding")||o==="preferred"&&(t.type==="code"||t.type==="Coding")))return;let c=Ue(i,e.package_meta,n);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>Nt){r?.dry_warn(`Value set ${n} has ${a.length} which is more than ${Nt} codes, which may cause issues with code generation.`);return}return a.length>0?a:void 0}function kr(i,e,t,r,o){if(!r.binding?.valueSet)return;let n=ve(e,t,r.binding.bindingName),s=je(i,e,t,r,o),c=Se(i,e.package_meta,r.binding.valueSet),a=[];s&&a.push(s),a.push(c);let l=Ve(i,e,r,o);return {identifier:n,type:s,valueset:c,strength:r.binding.strength,enum:l,dependencies:a}}function Dt(i,e,t){let r=new Set;if(!e.elements)return [];let o=[];function n(a,l){for(let[p,m]of Object.entries(a)){let y=[...l,p],d=y.join(".");if(!r.has(d)){if(r.add(d),m.binding){let f=kr(i,e,y,m,t);f&&o.push(f);}m.elements&&n(m.elements,y);}}}n(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 xr(i,e,t,r,o){if(!r)return;let n={};for(let s of i.getAllElementKeys(r)){let c=[...t,s],a=i.resolveElementSnapshot(e,c);ee(a)?n[s]=Te(i,e,c,a,o):n[s]=Ce(i,e,c,a,o);}return n}function Fr(i){let e=[];for(let t of Object.values(i))"type"in t&&t.type&&e.push(t.type),"binding"in t&&t.binding&&e.push(t.binding);return e}function Ir(i,e){return !!(i.base==="Extension"||i.base==="http://hl7.org/fhir/StructureDefinition/Extension"||i.url?.includes("/extension/")||i.url?.includes("-extension")||i.name?.toLowerCase().includes("extension")||i.type==="Extension")}async function Re(i,e,t){if(!e.url)throw new Error("ValueSet URL is required");let r=Se(i,e.package_meta,e.url),o=Ue(i,e.package_meta,e.url);return {identifier:r,description:e.description,concept:o,compose:o?void 0:e.compose}}function Ae(i,e,t,r){let o=[];e&&o.push(e),t&&o.push(...Fr(t)),r&&o.push(...Pt(r));let n={};for(let a of o)a.url!==i.url&&(n[a.url]=a);let s=new Set(r?.map(a=>a.identifier.url)),c=Object.values(n).filter(a=>lt(i)||!N(a)?true:!s.has(a.url)).sort((a,l)=>a.url.localeCompare(l.url));return c.length>0?c:void 0}function wr(i,e,t){let r=W(e),o;if(e.base&&e.type!=="Element"){let p=i.resolveFs(e.package_meta,i.ensureSpecializationCanonicalUrl(e.base));if(!p)throw new Error(`Base resource not found '${e.base}' for <${e.url}> from ${b(e.package_meta)}`);o=W(p);}let n=xr(i,e,[],e.elements,t),s=_e(i,e,t),c=Ae(r,o,n,s),a={identifier:r,base:o,fields:n,nested:s,description:e.description,dependencies:c},l=Dt(i,e,t);return [a,...l]}async function ke(i,e,t){let r=wr(i,e,t);if(Ir(e,W(e))){let o=r[0];if(!o)throw new Error("Expected schema to be defined");o.metadata={isExtension:true};}return r}var He=i=>i!==null&&typeof i=="object"&&i.resourceType==="CodeSystem";var xe=i=>i!==null&&typeof i=="object"&&i.resourceType==="ValueSet";var Pr=async(i,e)=>{let r=(await i.packageJson(e.name)).dependencies;return r!==void 0?Object.entries(r).map(([o,n])=>({name:o,version:n})):[]},Mt=i=>({pkg:i,canonicalResolution:{},fhirSchemas:{},valueSets:{}}),Bt=async(i,e,t,r,o)=>{let n=b(e);if(o?.info(`${" ".repeat(t*2)}+ ${n}`),r[n])return r[n];let s=Mt(e);for(let a of await i.search({package:e})){let l=a.url;if(!l||!(isStructureDefinition(a)||xe(a)||He(a)))continue;let p=l;s.canonicalResolution[p]&&o?.dry_warn(`Duplicate canonical URL: ${p} at ${n}.`),s.canonicalResolution[p]=[{deep:t,pkg:e,pkgId:n,resource:a}];}let c=await Pr(i,e);for(let a of c){let{canonicalResolution:l}=await Bt(i,a,t+1,r,o);for(let[p,m]of Object.entries(l)){let y=p;s.canonicalResolution[y]=[...s.canonicalResolution[y]||[],...m];}}for(let a of Object.values(s.canonicalResolution))a.sort((l,p)=>l.deep-p.deep);return r[n]=s,s},Ot=(i,e,t)=>{let r=Object.values(i).flatMap(o=>o.canonicalResolution[e]);if(!r)throw new Error(`No canonical resolution found for ${e} in any package`);return r[0]?.resource},te=async(i,{logger:e,fallbackPackageForNameResolution:t,focusedPackages:r})=>{let o=r??await i.packages(),n={};for(let d of o)await Bt(i,d,0,n,e);for(let{pkg:d,canonicalResolution:f}of Object.values(n)){let h=b(d);if(!n[h])throw new Error(`Package ${h} not found`);let u=0;e?.info(`FHIR Schema conversion for '${b(d)}' begins...`);for(let[g,S]of Object.entries(f)){let C=S[0];if(!C)throw new Error("Resource not found");let v=C.resource,x=C.pkg;if(isStructureDefinition(v)){let U=Oe(Lt.translate(v),x);u++,n[h].fhirSchemas[U.url]=U;}if(xe(v)){let U=ft(v,x);n[h].valueSets[U.url]=U;}}e?.info(`FHIR Schema conversion for '${b(d)}' completed: ${u} successful`);}let s=(d,f)=>n[b(d)]?.fhirSchemas[f]||t&&n[b(t)]?.fhirSchemas[f],c=(d,f)=>n[b(d)]?.valueSets[f]||t&&n[b(t)]?.valueSets[f],a=d=>d.match(/^[a-zA-Z0-9]+$/)&&`http://hl7.org/fhir/StructureDefinition/${d}`||d,l=(d,f)=>{let h=s(d,f);if(h===void 0)throw new Error(`Failed to resolve FHIR Schema: '${f}'`);let u=[h];for(;h?.base;){let g=h.package_meta,S=a(h.base);if(h=s(g,S),h===void 0)throw new Error(`Failed to resolve FHIR Schema base for '${f}'. Problem: '${S}' from '${b(g)}'`);u.push(h);}return u};return {...i,testAppendFs(d){let f=Oe(d),h=b(f.package_meta);n[h]||(n[h]=Mt(f.package_meta)),n[h].fhirSchemas[f.url]=f;},resolveFs:s,resolveFsGenealogy:l,resolveFsSpecializations:(d,f)=>l(d,f).filter(h=>h.derivation==="specialization"),ensureSpecializationCanonicalUrl:a,resolveSd:(d,f)=>{let h=Ot(n,f);if(isStructureDefinition(h))return h},allFs:()=>Object.values(n).flatMap(d=>Object.values(d.fhirSchemas)),allVs:()=>Object.values(n).flatMap(d=>Object.values(d.valueSets)),resolveVs:c,resolveAny:d=>Ot(n,d),resolveElementSnapshot:(d,f)=>{let h=l(d.package_meta,d.url),u=$r(h,f);return Er(u)},getAllElementKeys:d=>{let f=new Set;for(let[h,u]of Object.entries(d)){f.add(h);for(let g of u?.choices||[])d[g]||f.add(g);}return Array.from(f)},resolver:n,resolutionTree:()=>{let d={};for(let[f,h]of Object.entries(n)){let u=h.pkg.name;d[u]={};for(let[g,S]of Object.entries(h.canonicalResolution)){let C=g;d[u][C]=[];for(let v of S)d[u][C].push({deep:v.deep,pkg:v.pkg});}}return d}}};var $r=(i,e)=>{let[t,...r]=e;return t===void 0?[]:i.map(o=>{if(!o.elements)return;let n=o.elements?.[t];for(let s of r)n=n?.elements?.[s];return n}).filter(o=>o!==void 0)};function Er(i){let e=i.reverse(),t=Object.assign({},...e);return t.elements=void 0,t}var re=class{manager;options;logger;constructor(e){this.options={...e},this.manager=e.manager,this.logger=e.logger||M({prefix:"TypeSchema"});}async registerFromPackageMetas(e){let t=e.map(b);return this.logger?.step(`Loading FHIR packages: ${t.join(", ")}`),await this.manager.init(),te(this.manager,{focusedPackages:e})}generateFhirSchemas(e){this.logger?.progress(`Converting ${e.length} StructureDefinitions to FHIRSchemas`);let t=[],r=0,o=0;for(let n of e)try{let s=Lt.translate(n);t.push(s),r++,this.logger?.debug(`Converted StructureDefinition: ${n.name||n.id} (${n.resourceType})`);}catch(s){o++,this.logger?.warn(`Failed to convert StructureDefinition ${n.name||n.id}: ${s instanceof Error?s.message:String(s)}`);}return this.logger?.success(`FHIR Schema conversion completed: ${r}/${e.length} successful, ${o} failed`),t}async generateValueSetSchemas(e,t){e.length>0&&this.logger?.debug(`${e.length} ValueSets available for enum extraction`);let r=await te(this.manager,{logger:this.logger}),o=[];if(e.length>0){this.logger?.progress(`Converting ${e.length} ValueSets to TypeSchema`);let n=0,s=0;for(let c of e)try{let a=await Re(r,c,t);a&&(o.push(a),n++,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: ${n}/${e.length} successful, ${s} failed`);}return o}async generateFromPackage(e,t,r){let o={name:e,version:t||"latest"},n=await this.registerFromPackageMetas([o]),s=await this.generateValueSetSchemas(n.allVs(),r);return [...(await Promise.all(n.allFs().map(async l=>await ke(n,l,r)))).flat(),...s]}};var ie="Use CodeableReference which is not provided by FHIR R4.",Nr="Use Availability which is not provided by FHIR R4.",jt={"hl7.fhir.uv.extensions.r4#1.0.0":{"http://hl7.org/fhir/StructureDefinition/extended-contact-availability":Nr,"http://hl7.org/fhir/StructureDefinition/immunization-procedure":ie,"http://hl7.org/fhir/StructureDefinition/specimen-additive":ie,"http://hl7.org/fhir/StructureDefinition/workflow-barrier":ie,"http://hl7.org/fhir/StructureDefinition/workflow-protectiveFactor":ie,"http://hl7.org/fhir/StructureDefinition/workflow-reason":ie},"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."}},Vt=async(i,e)=>{let t=[];for(let r of i.allFs()){let o=b(r.package_meta);if(jt[o]?.[r.url]){e?.dry_warn(`Skip ${r.url} from ${o}. Reason: ${jt[o]?.[r.url]}`);continue}t.push(...await ke(i,r,e));}for(let r of i.allVs())t.push(await Re(i,r));return t};var Dr=(i,e)=>{let t={},r={};for(let o of e){let n=i.fields?.[o];if(!i.fields||!n)throw new Error(`Field ${o} not found`);if(I(n))r[o]||(r[o]={}),r[o].declaration=n.choices;else if(Le(n)){let s=n.choiceOf;r[s]||(r[s]={}),r[s].instances=[...r[s].instances??[],o];}else t[o]=n;}for(let[o,{declaration:n,instances:s}]of Object.entries(r)){let c=s??n;ne(c);for(let l of c){let p=i.fields?.[l];ne(p),t[l]=p;}let a=i.fields?.[o];ne(a),t[o]={...a,choices:c};}i.fields=t;},Or=(i,e)=>{for(let t of e){let r=i.fields?.[t];if(!i.fields||!r)throw new Error(`Field ${t} not found`);if(i.fields){if(I(r))for(let o of r.choices)delete i.fields[o];if(Le(r)){let o=i.fields[r.choiceOf];ne(I(o)),o.choices=o.choices.filter(n=>n!==t),o.choices.length===0&&delete i.fields[r.choiceOf];}delete i.fields[t];}}},Lr=(i,e,t)=>{if(i=structuredClone(i),dt(i)||gt(i)||ut(i))return i;if(e.selectFields){if(e.ignoreFields)throw new Error("Cannot use both ignoreFields and selectFields in the same rule");Dr(i,e.selectFields);}if(e.ignoreFields){if(e.selectFields)throw new Error("Cannot use both ignoreFields and selectFields in the same rule");Or(i,e.ignoreFields);}if(i.nested){let r=new Set,o=n=>{Object.values(n.fields??{}).filter(G).filter(s=>N(s.type)).forEach(s=>{let c=s.type.url;if(!r.has(c)){r.add(c);let a=i.nested?.find(l=>l.identifier.url===c);ne(a),o(a);}});};o(i),i.nested=i.nested.filter(n=>r.has(n.identifier.url));}return i.dependencies=Ae(i.identifier,i.base,i.fields,i.nested),i},Ut=(i,e,{resolutionTree:t,logger:r})=>{let o=[];for(let[c,a]of Object.entries(e))for(let[l,p]of Object.entries(a)){let m=i.resolveByUrl(c,l);if(!m)throw new Error(`Schema not found for ${c} ${l}`);let y=Lr(m,p);o.push(y);}let n=(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(_(p)){if(!p.dependencies)continue;if(p.dependencies.forEach(m=>{let y=i.resolve(m);if(!y)throw new Error(`Dependent schema ${JSON.stringify(m)} not found for ${JSON.stringify(p.identifier)}`);let d=JSON.stringify(y.identifier);a[d]||l.push(y);}),p.nested)for(let m of p.nested){if(N(m.identifier))continue;let y=JSON.stringify(m.identifier);a[y]||l.push(m);}}return n(l,a)},s=n(o,{});return me(s,{resolutionTree:t,logger:r})};var Mr={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"},At=i=>{let e=Mr[i];if(e===void 0)throw new Error(`Unknown primitive type ${i}`);return e},Gt=i=>ot(i),qe=i=>i.kind==="profile"?`${R(i)}_profile`:P(i.name),Br=i=>`${qe(i)}.ts`,Fe=i=>`${Gt(i.package)}/${qe(i)}`,ze=(i,e=true)=>{if(!i)return;let t=pe(i,e);if(t)return We(t)},R=i=>{if(i.kind==="nested"){let e=i.url,t=ze(e,false);if(!t)return "";let[r,o]=t.split("#"),n=Y((o??"").split(".")).join("");return We([r,n].join(""))}return We(i.name)},zt=new Set(["class","function","return","if","for","while","const","let","var","import","export","interface"]),Q=i=>zt.has(i)?`"${i}"`:i.includes(" ")||i.includes("-")?`"${i}"`:i,We=i=>(zt.has(i)&&(i=`${i}_`),i.replace(/[- ]/g,"_")),q=(i,e)=>e.startsWith('"')?`${i}[${e}]`:`${i}.${e}`,Ht=i=>`(${i.map(e=>`"${e}"`).join(" | ")})`,Ie=class extends B{tsImportType(e,...t){this.lineSM(`import type { ${t.join(", ")} } from "${e}"`);}generateFhirPackageIndexFile(e){this.cat("index.ts",()=>{let t=e.flatMap(r=>[{identifier:r.identifier,tsPackageName:qe(r.identifier),resourceName:R(r.identifier),nestedTypes:D(r)&&r.nested||j(r)&&r.nested?r.nested.map(o=>R(o.identifier)):[],helpers:D(r)||j(r)?[`is${R(r.identifier)}`]:[]}]).sort((r,o)=>r.resourceName.localeCompare(o.resourceName));t=Array.from(new Map(t.map(r=>[r.resourceName.toLowerCase(),r])).values()).sort((r,o)=>r.resourceName.localeCompare(o.resourceName));for(let r of t)this.debugComment(r.identifier),this.lineSM(`export type { ${[r.resourceName,...r.nestedTypes].join(", ")} } from "./${r.tsPackageName}"`),r.helpers.length>0&&this.lineSM(`export { ${r.helpers.join(", ")} } from "./${r.tsPackageName}"`);});}generateDependenciesImports(e,t){if(t.dependencies){let r=[],o=[];for(let n of t.dependencies)if(["complex-type","resource","logical"].includes(n.kind))r.push({tsPackage:`../${Fe(n)}`,name:E(n.name),dep:n});else if(N(n)){let s={...n};s.name=ze(n.url),r.push({tsPackage:`../${Fe(s)}`,name:R(n),dep:n});}else o.push(n);r.sort((n,s)=>n.name.localeCompare(s.name));for(let n of r)this.debugComment(n.dep),this.tsImportType(n.tsPackage,n.name);for(let n of o)this.debugComment("skip:",n);if(this.line(),this.withPrimitiveTypeExtension(t)&&t.identifier.name!=="Element"&&t.dependencies.find(n=>n.name==="Element")===void 0){let n="http://hl7.org/fhir/StructureDefinition/Element",s=e.resolveByUrl(t.identifier.package,n);if(!s)throw new Error(`'${n}' not found for ${t.identifier.package}.`);this.tsImportType(`../${Fe(s.identifier)}`,"Element");}}}generateComplexTypeReexports(e){let t=e.dependencies?.filter(ct).map(r=>({tsPackage:`../${Fe(r)}`,name:E(r.name)}));if(t&&t.length>0){for(let r of t)this.lineSM(`export type { ${r.name} } from "${r.tsPackage}"`);this.line();}}addFieldExtension(e){let t=Q(`_${e}`);this.lineSM(`${t}?: Element`);}generateType(e,t){let r;t.identifier.name==="Reference"?r="Reference<T extends string = string>":(t.identifier.kind,r=R(t.identifier));let o;if(t.base&&(o=`extends ${ze(t.base.url)}`),this.debugComment(t.identifier),!t.fields&&!o&&!D(t)){this.lineSM(`export type ${r} = object`);return}this.curlyBlock(["export","interface",r,o],()=>{if(D(t)||j(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 n=Object.entries(t.fields).sort((s,c)=>s[0].localeCompare(c[0]));for(let[s,c]of n){if(I(c))continue;this.debugComment(s,":",c);let a=Q(s),l;c.enum?l=Ht(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(" | ")}>`:Z(c.type)?l=At(c.type.name):N(c.type)?l=R(c.type):l=c.type.name;let p=c.required?"":"?",m=c.array?"[]":"";this.lineSM(`${a}${p}: ${l}${m}`),this.withPrimitiveTypeExtension(t)&&Z(c.type)&&this.addFieldExtension(s);}});}withPrimitiveTypeExtension(e){if(!this.opts.primitiveTypeExtension||!_(e))return false;for(let t of Object.values(e.fields??{}))if(!I(t)&&Z(t.type))return true;return false}generateResourceTypePredicate(e){if(!D(e)&&!j(e))return;let t=R(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 r of t.nested)this.generateType(e,r),this.line();}generateProfileType(e,t){this.debugComment("flatProfile",t);let r=R(t.identifier);this.debugComment("identifier",t.identifier),this.debugComment("base",t.base),this.curlyBlock(["export","interface",r],()=>{this.lineSM(`__profileUrl: "${t.identifier.url}"`),this.line();for(let[o,n]of Object.entries(t.fields??{})){if(I(n))continue;this.debugComment(o,n);let s=Q(o),c;if(n.enum)c=Ht(n.enum);else if(n.reference&&n.reference.length>0){let a=e.findLastSpecialization(t);if(!_(a))throw new Error(`Invalid specialization for ${t.identifier}`);let l=a.fields?.[o];if(l===void 0||I(l)||l.reference===void 0)throw new Error(`Invalid field declaration for ${o}`);let p=l.reference.map(y=>y.name),m=n.reference.map(y=>{let d=e.findLastSpecializationByIdentifier(y);return d.name!==y.name?`"${d.name}" /*${y.name}*/`:`'${y.name}'`}).join(" | ");p.length===1&&p[0]==="Resource"&&m!=='"Resource"'?c=`Reference<"Resource" /* ${m} */ >`:c=`Reference<${m}>`;}else if(N(n.type))c=R(n.type);else if(Z(n.type))c=At(n.type.name);else {if(n.type===void 0)throw new Error(`Undefined type for '${o}' field at ${at(t)}`);c=n.type.name;}this.lineSM(`${s}${n.required?"":"?"}: ${c}${n.array?"[]":""}`);}}),this.line();}generateAttachProfile(e){let t=R(e.base),r=R(e.identifier),o=Object.entries(e.fields||{}).filter(([n,s])=>s&&G(s)&&s.type!==void 0).map(([n])=>Q(n));this.curlyBlock([`export const attach_${r}_to_${t} =`,`(resource: ${t}, profile: ${r}): ${t}`,"=>"],()=>{this.curlyBlock(["return"],()=>{this.line("...resource,"),this.curlyBlock(["meta:"],()=>{this.line(`profile: ['${e.identifier.url}']`);},[","]),o.forEach(n=>{this.line(`${n}: ${q("profile",n)},`);});});}),this.line();}generateExtractProfile(e,t){let r=R(t.base),o=R(t.identifier),n=Object.entries(t.fields||{}).filter(([a,l])=>G(l)&&l.type!==void 0).map(([a])=>a),s=e.findLastSpecialization(t);if(!_(s))throw new Error(`Specialization not found for ${t.identifier.url}`);let c={};this.curlyBlock([`export const extract_${o}_from_${r} =`,`(resource: ${r}): ${o}`,"=>"],()=>{n.forEach(a=>{let l=Q(a),p=t.fields?.[a],m=s.fields?.[a];if(!G(p)||!G(m))return;p.required&&!m.required&&this.curlyBlock([`if (${q("resource",l)} === undefined)`],()=>this.lineSM(`throw new Error("'${l}' is required for ${t.identifier.url}")`));let y=p?.reference?.map(f=>f.name),d=m?.reference?.map(f=>f.name);if(y&&d&&y.length!==d.length){let f=`reference_is_valid_${l}`;this.curlyBlock(["const",f,"=","(ref?: Reference)","=>"],()=>{this.line("return !ref"),this.indentBlock(()=>{d.forEach(u=>{this.line(`|| ref.reference?.startsWith('${u}/')`);}),this.line(";");});});let h=p?.required?"":`!${q("resource",l)} || `;p.array?h+=`${q("resource",l)}.every( (ref) => ${f}(ref) )`:h+=`!${f}(${q("resource",l)})`,this.curlyBlock(["if (",h,")"],()=>{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}',`),n.forEach(a=>{let l=Q(a);c[a]?this.line(`${l}:`,`${q("resource",l)} as ${o}['${l}'],`):this.line(`${l}:`,`${q("resource",l)},`);});});});}generateResourceModule(e,t){this.cat(`${Br(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(ue(t)){let r=e.flatProfile(t);this.generateDependenciesImports(e,r),this.comment("CanonicalURL:",t.identifier.url),this.generateProfileType(e,r),this.generateAttachProfile(r),this.generateExtractProfile(e,r);}else throw new Error(`Profile generation not implemented for kind: ${t.identifier.kind}`)});}async generate(e){let t=[...e.collectComplexTypes(),...e.collectResources(),...e.collectLogicalModels(),...this.opts.generateProfile?e.collectProfiles().filter(o=>e.isWithMetaField(o)):[]],r=z(t);this.cd("/",()=>{for(let[o,n]of Object.entries(r)){let s=Gt(o);this.cd(s,()=>{for(let c of n)this.generateResourceModule(e,c);this.generateFhirPackageIndexFile(n);});}});}};var Wt=i=>{let e=i.replace(/[^a-zA-Z0-9\-_.@#()]/g,"");return e.length===0?"unknown":e},jr=async(i,e)=>{e.info("Cleaning outputs...");try{e.info(`Clean ${i.outputDir}`),k.rmSync(i.outputDir,{recursive:!0,force:!0}),i.typeSchemaOutputDir&&(e.info(`Clean ${i.typeSchemaOutputDir}`),k.rmSync(i.typeSchemaOutputDir,{recursive:!0,force:!0})),i.exportTypeTree&&(e.info(`Clean ${i.exportTypeTree}`),k.rmSync(i.exportTypeTree,{recursive:!0,force:!0}));}catch(t){e.warn(`Error cleaning output directory: ${t instanceof Error?t.message:String(t)}`);}},Vr=async(i,e,t)=>{await V.mkdir(e,{recursive:true}),t.info(`Writing TypeSchema files to ${e}/...`);let r={};for(let o of i){let n={name:o.identifier.package,version:o.identifier.version},s=Wt(b(n)),c=Wt(`${o.identifier.name}(${pe(o.identifier.url)})`),a=JSON.stringify(o,null,2),l=w.join(e,s,c);r[l]||(r[l]=[]),r[l]?.some(p=>p===a)||r[l].push(a);}for(let[o,n]of Object.entries(r))await Promise.all(n.map(async(s,c)=>{let a;c===0?a=`${o}.typeschema.json`:a=`${o}-${c}.typeschema.json`,await V.mkdir(w.dirname(a),{recursive:true}),await V.writeFile(a,s);}));},Ur=async(i,e,t)=>{t.info(`Writing TypeSchema files to: ${e}`),await V.mkdir(w.dirname(e),{recursive:true}),t.info(`Writing TypeSchemas to one file ${e}...`);for(let r of i){let o=JSON.stringify(r,null,2);await V.appendFile(e,`${o}
|
|
7
|
+
`);}},Ar=async(i,e,t)=>{if(e.typeSchemaOutputDir)try{w.extname(e.typeSchemaOutputDir)===".ndjson"?await Ur(i,e.typeSchemaOutputDir,t):await Vr(i,e.typeSchemaOutputDir,t),t.info("Writing TypeSchema - DONE");}catch(r){if(t.error("Failed to write TypeSchema output",r instanceof Error?r:new Error(String(r))),e.throwException)throw r}},oe=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,registry:e.registry},this.typeSchemaConfig=e.typeSchemaConfig,this.logger=e.logger||M({prefix:"API",level:e.logLevel});}fromPackage(e,t){let r=de({name:e,version:t||"latest"});return this.packages.push(r),this}fromPackageRef(e){return this.packages.push(e),this}registry(e){return this.options.registry=e,this}localStructureDefinitions(e){return this.localStructurePackages.push(e),this}localTgzPackage(e){return this.localTgzArchives.push(w.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:w.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))},n=new Ie(o);return this.generators.set("typescript",n),this.logger.debug(`Configured TypeScript generator (${JSON.stringify(o,void 0,2)})`),this}python(e){let o={...{...{logger:this.logger,outputDir:this.options.outputDir,tabSize:4,withDebugComment:false,commentLinePrefix:"#"},rootPackageName:"fhir_types",fieldFormat:"snake_case"},...Object.fromEntries(Object.entries(e).filter(([s,c])=>c!==void 0))},n=new ye(o);return this.generators.set("python",n),this.logger.debug("Configured python generator"),this}csharp(e,t){let r=new ge({outputDir:w.join(this.options.outputDir,"/types"),staticSourceDir:t??void 0,targetNamespace:e,logger:new J({prefix:"C#",timestamp:true,suppressLoggingLevel:[]})});return this.generators.set("C#",r),this.logger.debug("Configured C# generator"),this}onProgress(e){return this.progressCallback=e,this}outputTo(e){this.logger.debug(`Setting output directory: ${e}`),this.options.outputDir=e;for(let t of this.generators.values())t.setOutputDir(e);return this}setLogLevel(e){return this.logger?.setLevel(typeof e=="string"?Ze(e):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&&jr(this.options,this.logger),this.logger.info("Initialize Canonical Manager");let r=this.options.manager||CanonicalManager({packages:this.packages,workingDir:".codegen-cache/canonical-manager-cache",registry:this.options.registry||void 0});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 r.addLocalPackage({name:p.package.name,version:p.package.version,path:p.path,dependencies:p.dependencies?.map(m=>de(m))});for(let p of this.localTgzArchives)this.logger.info(`Registering local tgz package: ${p}`),await r.addTgzPackage({archivePath:p});let o=await r.init(),n=Object.values(o),s=await te(r,{logger:this.logger,focusedPackages:n}),c=await Vt(s,this.logger);await Ar(c,this.options,this.logger);let a={resolutionTree:s.resolutionTree(),logger:this.logger},l=me(c,a);this.options.treeShake&&(l=Ut(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(r){if(this.logger.error("Code generation failed",r instanceof Error?r:new Error(String(r))),t.errors.push(r instanceof Error?r.message:String(r)),this.options.throwException)throw r}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[r,o]of this.generators.entries()){this.logger.info(`Generating ${r}...`);try{await o.generate(t);let n=o.writtenFiles();e.filesGenerated.push(...n.map(s=>s.absPath)),this.logger.info(`Generating ${r} finished successfully`);}catch(n){if(e.errors.push(`${r} generator failed: ${n instanceof Error?n.message:String(n)}`),this.options.throwException)throw n}}}};var Je={outputDir:"./generated",verbose:false,overwrite:true,validate:true,cache:true,cleanOutput:true,registry:"",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:""},Pe=["atomic-codegen.config.ts","atomic-codegen.config","atomic-codegen.config.json",".atomic-codegenrc","atomic-codegen.json",".atomic-codegen.json","codegen.config.json","codegen.json"],Ke=class{validate(e){let t={valid:true,errors:[],warnings:[]};if(!e||typeof e!="object")return t.valid=false,t.errors.push({path:"root",message:"Configuration must be an object",value:e}),t;let r=e;r.outputDir!==void 0&&typeof r.outputDir!="string"&&t.errors.push({path:"outputDir",message:"outputDir must be a string",value:r.outputDir});let o=["verbose","overwrite","validate","cache"];for(let n of o)r[n]!==void 0&&typeof r[n]!="boolean"&&t.errors.push({path:n,message:`${n} must be a boolean`,value:r[n]});if(r.typescript!==void 0){let n=this.validateTypeScriptConfig(r.typescript);t.errors.push(...n);}if(r.typeSchema!==void 0){let n=this.validateTypeSchemaConfig(r.typeSchema);t.errors.push(...n);}return r.packages!==void 0&&(Array.isArray(r.packages)?r.packages.forEach((n,s)=>{typeof n!="string"&&t.errors.push({path:`packages[${s}]`,message:"package name must be a string",value:n});}):t.errors.push({path:"packages",message:"packages must be an array",value:r.packages})),r.files!==void 0&&(Array.isArray(r.files)?r.files.forEach((n,s)=>{typeof n!="string"&&t.errors.push({path:`files[${s}]`,message:"file path must be a string",value:n});}):t.errors.push({path:"files",message:"files must be an array",value:r.files})),t.valid=t.errors.length===0,t.valid&&(t.config=r),t}validateTypeScriptConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript",message:"typescript config must be an object",value:e}),t;let r=e;r.moduleFormat!==void 0&&(["esm","cjs"].includes(r.moduleFormat)||t.push({path:"typescript.moduleFormat",message:'moduleFormat must be "esm" or "cjs"',value:r.moduleFormat})),r.namingConvention!==void 0&&(["PascalCase","camelCase"].includes(r.namingConvention)||t.push({path:"typescript.namingConvention",message:'namingConvention must be "PascalCase" or "camelCase"',value:r.namingConvention}));let o=["generateIndex","includeDocuments","strictMode","includeProfiles","includeExtensions","includeCodeSystems","includeOperations","generateValueSets","includeValueSetHelpers"];for(let n of o)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.${n}`,message:`${n} must be a boolean`,value:r[n]});if(r.validatorOptions!==void 0){let n=this.validateValidatorOptions(r.validatorOptions);t.push(...n);}if(r.guardOptions!==void 0){let n=this.validateGuardOptions(r.guardOptions);t.push(...n);}if(r.profileOptions!==void 0){let n=this.validateProfileOptions(r.profileOptions);t.push(...n);}return t}validateValidatorOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.validatorOptions",message:"validatorOptions must be an object",value:e}),t;let r=e,o=["includeCardinality","includeTypes","includeConstraints","includeInvariants","validateRequired","allowAdditional","strictValidation","collectMetrics","generateAssertions","generatePartialValidators","optimizePerformance","includeJSDoc","generateCompositeValidators"];for(let n of o)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.validatorOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateGuardOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.guardOptions",message:"guardOptions must be an object",value:e}),t;let r=e;r.targetTSVersion!==void 0&&(["3.8","4.0","4.5","5.0"].includes(r.targetTSVersion)||t.push({path:"typescript.guardOptions.targetTSVersion",message:'targetTSVersion must be one of: "3.8", "4.0", "4.5", "5.0"',value:r.targetTSVersion}));let o=["includeRuntimeValidation","includeErrorMessages","treeShakeable","strictGuards","includeNullChecks","verbose"];for(let n of o)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.guardOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateProfileOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.profileOptions",message:"profileOptions must be an object",value:e}),t;let r=e;r.generateKind!==void 0&&(["interface","type","both"].includes(r.generateKind)||t.push({path:"typescript.profileOptions.generateKind",message:'generateKind must be "interface", "type", or "both"',value:r.generateKind})),r.subfolder!==void 0&&typeof r.subfolder!="string"&&t.push({path:"typescript.profileOptions.subfolder",message:"subfolder must be a string",value:r.subfolder});let o=["includeConstraints","includeDocumentation","strictMode"];for(let n of o)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.profileOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateTypeSchemaConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typeSchema",message:"typeSchema config must be an object",value:e}),t;let r=e,o=["enablePersistence","validateCached","forceRegenerate","shareCache"];for(let s of o)r[s]!==void 0&&typeof r[s]!="boolean"&&t.push({path:`typeSchema.${s}`,message:`${s} must be a boolean`,value:r[s]});let n=["cacheDir","cacheKeyPrefix"];for(let s of n)r[s]!==void 0&&typeof r[s]!="string"&&t.push({path:`typeSchema.${s}`,message:`${s} must be a string`,value:r[s]});if(r.maxAge!==void 0&&(typeof r.maxAge!="number"||r.maxAge<=0)&&t.push({path:"typeSchema.maxAge",message:"maxAge must be a positive number",value:r.maxAge}),r.profiles!==void 0)if(typeof r.profiles!="object"||r.profiles===null)t.push({path:"typeSchema.profiles",message:"profiles must be an object",value:r.profiles});else {let s=r.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}},Ye=class{validator=new Ke;async autoload(e=process.cwd()){let t=await this.findConfigFile(e);return t?this.loadFromFile(t):{...Je}}async loadFromFile(e){try{let t;if(e.endsWith(".ts")||e.endsWith("")){let n=await import(resolve(e));t=n.default||n;}else {let o=await readFile(e,"utf-8");t=JSON.parse(o);}let r=this.validator.validate(t);if(!r.valid){let o=r.errors.map(n=>`${n.path}: ${n.message}`).join(`
|
|
8
8
|
`);throw new Error(`Configuration validation failed:
|
|
9
|
-
${o}`)}if(!r.config)throw new Error("Invalid configuration");return this.mergeWithDefaults(r.config)}catch(t){throw t instanceof Error?new Error(`Failed to load config from ${e}: ${t.message}`):t}}async findConfigFile(e){for(let t of
|
|
9
|
+
${o}`)}if(!r.config)throw new Error("Invalid configuration");return this.mergeWithDefaults(r.config)}catch(t){throw t instanceof Error?new Error(`Failed to load config from ${e}: ${t.message}`):t}}async findConfigFile(e){for(let t of Pe){let r=resolve(e,t);if(existsSync(r))return r}return null}mergeWithDefaults(e){return {...Je,...e,typescript:{...Je.typescript,...e.typescript}}}},Wr=new Ye;async function $e(i){return Wr.autoload(i)}var Jt={command:"generate",describe:"Generate code based on configuration file settings",builder:i=>i.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 i=>{if(i._.length>1){let s=i._.slice(1).join(" ");F(`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
|
|
17
|
+
Create an atomic-codegen.config.ts file to get started.`),process.exit(1);}let e=process.cwd(),t=await Kr(e);if(!t){let s=Pe.map(c=>` - ${c}`).join(`
|
|
18
18
|
`);F(`No configuration file found. Please create one of the following files in your project root:
|
|
19
19
|
${s}
|
|
20
20
|
|
|
@@ -27,13 +27,13 @@ export default defineConfig({
|
|
|
27
27
|
typescript: {
|
|
28
28
|
generateIndex: true
|
|
29
29
|
}
|
|
30
|
-
});`),process.exit(1);}let r=await $e(e),o=i.verbose??r.verbose??false,n=M({prefix:"Generate"});try{
|
|
31
|
-
`),await writeFile(p,m,"utf-8");let y=Date.now()-c;if(
|
|
30
|
+
});`),process.exit(1);}let r=await $e(e),o=i.verbose??r.verbose??false,n=M({prefix:"Generate"});try{tt("Starting generation from config"),o&&(n.info(`Config file: ${t}`),n.info(`Output directory: ${r.outputDir||"./generated"}`),n.info(`Packages: ${r.packages?.length||0}`),n.info(`Files: ${r.files?.length||0}`),n.info(`TypeScript generation: ${r.typescript?"enabled":"disabled"}`));let s=new oe({outputDir:r.outputDir||"./generated",overwrite:r.overwrite??!0,cache:r.cache??!0,typeSchemaConfig:r.typeSchema,logger:n});if(r.packages&&r.packages.length>0){n.info(`Loading packages from config: ${r.packages.join(", ")}`);for(let a of r.packages){let[l,p]=a.includes("@")?a.split("@"):[a,void 0];s.fromPackage(l,p);}}else throw r.files&&r.files.length>0?(n.info(`Loading files from config: ${r.files.join(", ")}`),new Error("Not Implemented")):new Error("No data source specified in config. Please configure 'packages' or 'files' in your config file.");if(r.typescript)throw new Error("Not Implemented");if(!r.typescript)throw new Error("No generators configured. Please enable 'typescript' in your config file.");o&&s.onProgress((a,l,p,m)=>{let y=Math.round(l/p*100);n.progress(`[${a}] ${y}% - ${m||"Processing..."}`);}),n.step("Executing generation...");let c=await s.generate();if(c.success){if(Ee(`Generated ${c.filesGenerated.length} files in ${c.duration.toFixed(2)}ms`),n.dim(`Output directory: ${c.outputDir}`),c.warnings.length>0)for(let a of c.warnings)et(a);}else {F(`Generation failed with ${c.errors.length} errors`);for(let a of c.errors)n.dim(` ${a}`);process.exit(1);}}catch(s){F("Generation failed with unexpected error",s instanceof Error?s:new Error(String(s))),process.exit(1);}}};async function Kr(i){for(let e of Pe){let t=resolve(i,e);if(existsSync(t))return t}return null}var Kt={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"},registry:{alias:"r",type:"string",describe:"Custom FHIR package registry URL (default: https://fs.get-ig.org/pkgs/)"}},handler:async i=>{let e=M({prefix:"TypeSchema"});try{let t=await $e(process.cwd());e.step("Generating TypeSchema from FHIR packages"),e.info(`Packages: ${i.packages.join(", ")}`),e.info(`Output: ${i.output}`);let r=i.singleFile!==void 0?i.singleFile:t.typeSchema?.singleFile??!1,o=r?"ndjson":i.format;e.debug(`Format: ${o}${r&&i.format==="json"?" (forced from json due to singleFile)":""}`);let n=i.treeshake&&i.treeshake.length>0?i.treeshake:t.typeSchema?.treeshake;n&&n.length>0&&e.info(`Treeshaking enabled for ResourceTypes: ${n.join(", ")}`),r&&e.info("Single file output enabled (NDJSON format)");let s=i.registry||t.registry;s&&e.info(`Using custom registry: ${s}`);let c=Date.now(),a=new re({treeshake:n,registry:s,manager:CanonicalManager({packages:[],workingDir:".codegen-cache/canonical-manager-cache",registry:s})}),l=[];for(let d of i.packages){let[f,h]=d.includes("@")?d.split("@"):[d,void 0];e.progress(`Processing package: ${f}${h?`@${h}`:""}`);let u=await a.generateFromPackage(f,h,e);l.push(...u);}if(l.length===0)throw new Error("No schemas were generated from the specified packages");let p=i.output;if(!p)throw new Error("Output format not specified");await mkdir(dirname(p),{recursive:!0});let m;o==="json"?m=JSON.stringify(l,null,2):m=l.map(d=>JSON.stringify(d)).join(`
|
|
31
|
+
`),await writeFile(p,m,"utf-8");let y=Date.now()-c;if(nt(`Generated ${l.length} TypeSchema definitions`,y,{schemas:l.length}),e.dim(`Output: ${p}`),i.verbose){e.debug("Generated schemas:");let d=l.map(f=>`${f.identifier?.name||"Unknown"} (${f.identifier?.kind||"unknown"})`);K(d);}}catch(t){e.error("Failed to generate TypeSchema",t instanceof Error?t:new Error(String(t))),process.exit(1);}}};var Yt={command:"typeschema [subcommand]",describe:"TypeSchema operations - generate, validate and merge schemas",builder:i=>i.command(Kt).help().example("$0 typeschema generate hl7.fhir.r4.core@4.0.1","Generate TypeSchema from FHIR R4 core package"),handler:i=>{if(!i.subcommand&&i._.length===1){Ne("Available typeschema subcommands:"),K(["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:`),K(["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}i.subcommand&&!["generate","validate","merge"].includes(i.subcommand)&&(F(`Unknown typeschema subcommand: ${i.subcommand}
|
|
34
34
|
`),Ne("Available typeschema subcommands:"),K(["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
|
|
35
|
+
Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),process.exit(1));}};function ri(i){return i?{debug:0,info:1,warn:2,error:3,silent:4}[i.toLowerCase()]:void 0}async function ii(i){let e=ri(i.logLevel);e===void 0&&(i.debug||i.verbose?e=0:e=1),rt({timestamp:i.debug,level:e});}function ni(){return ei(hideBin(process.argv)).scriptName("atomic-codegen").usage("$0 <command> [options]").middleware(ii).command(Yt).command(Jt).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(i=>{i._.length===0&&(it("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((i,e,t)=>{e?F(e.message,e):F(i),F(`
|
|
39
|
-
Use --help for usage information`),process.exit(1);}).wrap(Math.min(120,process.stdout.columns||80))}async function Xe(){await
|
|
39
|
+
Use --help for usage information`),process.exit(1);}).wrap(Math.min(120,process.stdout.columns||80))}async function Xe(){await ni().parseAsync();}import.meta.main&&Xe().catch(i=>{i("Unexpected error:",i),process.exit(1);});Xe().catch(i=>{console.error("CLI Error:",i instanceof Error?i.message:i),process.exit(1);});
|
package/dist/index.d.ts
CHANGED
|
@@ -12,6 +12,7 @@ declare enum LogLevel {
|
|
|
12
12
|
ERROR = 3,
|
|
13
13
|
SILENT = 4
|
|
14
14
|
}
|
|
15
|
+
type LogLevelString = keyof typeof LogLevel;
|
|
15
16
|
interface LogOptions {
|
|
16
17
|
prefix?: string;
|
|
17
18
|
timestamp?: boolean;
|
|
@@ -642,7 +643,7 @@ declare class APIBuilder {
|
|
|
642
643
|
* Set the output directory for all generators
|
|
643
644
|
*/
|
|
644
645
|
outputTo(directory: string): APIBuilder;
|
|
645
|
-
setLogLevel(level: LogLevel): APIBuilder;
|
|
646
|
+
setLogLevel(level: LogLevel | LogLevelString): APIBuilder;
|
|
646
647
|
throwException(enabled?: boolean): APIBuilder;
|
|
647
648
|
cleanOutput(enabled?: boolean): APIBuilder;
|
|
648
649
|
writeTypeTree(filename: string): this;
|
package/dist/index.js
CHANGED
|
@@ -21,6 +21,22 @@ var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
|
|
|
21
21
|
LogLevel2[LogLevel2["SILENT"] = 4] = "SILENT";
|
|
22
22
|
return LogLevel2;
|
|
23
23
|
})(LogLevel || {});
|
|
24
|
+
var parseLogLevel = (level) => {
|
|
25
|
+
switch (level.toUpperCase()) {
|
|
26
|
+
case "DEBUG":
|
|
27
|
+
return 0 /* DEBUG */;
|
|
28
|
+
case "INFO":
|
|
29
|
+
return 1 /* INFO */;
|
|
30
|
+
case "WARN":
|
|
31
|
+
return 2 /* WARN */;
|
|
32
|
+
case "ERROR":
|
|
33
|
+
return 3 /* ERROR */;
|
|
34
|
+
case "SILENT":
|
|
35
|
+
return 4 /* SILENT */;
|
|
36
|
+
default:
|
|
37
|
+
throw new Error(`Invalid log level: ${level}`);
|
|
38
|
+
}
|
|
39
|
+
};
|
|
24
40
|
var CodegenLogger = class _CodegenLogger {
|
|
25
41
|
options;
|
|
26
42
|
dryWarnSet = /* @__PURE__ */ new Set();
|
|
@@ -3043,7 +3059,7 @@ var APIBuilder = class {
|
|
|
3043
3059
|
return this;
|
|
3044
3060
|
}
|
|
3045
3061
|
setLogLevel(level) {
|
|
3046
|
-
this.logger?.setLevel(level);
|
|
3062
|
+
this.logger?.setLevel(typeof level === "string" ? parseLogLevel(level) : level);
|
|
3047
3063
|
return this;
|
|
3048
3064
|
}
|
|
3049
3065
|
throwException(enabled = true) {
|