@atomic-ehr/codegen 0.0.1-canary.20251010120059.024c867 → 0.0.1-canary.20251010120621.05ce13f
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 +1 -1
- package/dist/index.js +0 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -38,7 +38,7 @@ ${i}`:r}filterAndSortSchemas(e){return this.collectedValueSets=this.collectValue
|
|
|
38
38
|
`):(this.writeIndent(),this.write(`${e.join(" ")}
|
|
39
39
|
`));}lineSM(...e){this.writeIndent(),this.write(`${e.join(" ")};
|
|
40
40
|
`);}comment(...e){let t=e.join(" ").split(`
|
|
41
|
-
`);for(let r of t)this.line(this.opts.commentLinePrefix,r);}debugComment(...e){this.opts.withDebugComment&&(e=e.map(t=>typeof t=="string"?t:JSON.stringify(t,null,2)),this.comment(...e));}disclaimer(){return ["WARNING: This file is autogenerated by @atomic-ehr/codegen.","GitHub: https://github.com/orgs/atomic-ehr/repositories","Any manual changes made to this file may be overwritten."]}generateDisclaimer(){this.disclaimer().forEach(e=>this.comment(e)),this.line();}indentBlock(e){this.indent(),e(),this.deindent();}curlyBlock(e,t,r){this.line(`${e.filter(Boolean).join(" ")} {`),this.indent(),t(),this.deindent(),this.line(`}${r?.filter(Boolean).join(" ")??""}`);}squareBlock(e,t,r){this.line(`${e.filter(Boolean).join(" ")} [`),this.indent(),t(),this.deindent(),this.line(`]${r?.filter(Boolean).join(" ")??""}`);}};var Sr={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"},Bt=s=>{let e=Sr[s];if(e===void 0)throw new Error(`Unknown primitive type ${s}`);return e},vr=s=>H(s),Lt=s=>s.kind==="profile"?`${x(s)}_profile`:z(s.name),xr=s=>`${Lt(s)}.ts`,Qe=(s,e=true)=>{if(!s)return;let t=s.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),xe(t)},x=s=>{if(s.kind==="nested"){let e=s.url,t=Qe(e,false);if(!t)return "";let[r,i]=t.split("#"),n=Dt((i??"").split(".")).join("");return xe([r,n].join(""))}return xe(s.name)},O=s=>xe(s),xe=s=>(new Set(["abstract","any","as","async","await","boolean","bigint","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","extern","false","finally","for","function","from","get","goto","if","implements","import","in","infer","instanceof","interface","keyof","let","module","namespace","never","new","null","number","object","of","override","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","this","throw","true","try","type","typeof","unknown","var","void","while"]).has(s)&&(s=`${s}_`),s.replace(/[- ]/g,"_")),we=class extends ve{tsImportType(e,...t){this.lineSM(`import type { ${t.join(", ")} } from "${e}"`);}generateFhirPackageIndexFile(e){this.cat("index.ts",()=>{let t=e.map(r=>({identifier:r.identifier,tsPackageName:Lt(r.identifier),resourceName:x(r.identifier)})).sort((r,i)=>r.resourceName.localeCompare(i.resourceName));t=Array.from(new Map(t.map(r=>[r.resourceName.toLowerCase(),r])).values()).sort((r,i)=>r.resourceName.localeCompare(i.resourceName));for(let r of t)this.debugComment(r.identifier),this.lineSM(`export type { ${r.resourceName} } from "./${r.tsPackageName}"`);});}generateDependenciesImports(e){if(e.dependencies){let t=[],r=[];for(let i of e.dependencies)["complex-type","resource","logical"].includes(i.kind)?t.push({tsPackage:`../${H(i.package)}/${z(i.name)}`,name:Se(i.name)}):M(i)?t.push({tsPackage:`../${H(i.package)}/${z(Qe(i.url)??"")}`,name:x(i)}):r.push(i);t.sort((i,n)=>i.name.localeCompare(n.name));for(let i of t)this.tsImportType(i.tsPackage,i.name);for(let i of r)this.debugComment("skip:",i);this.line();}}generateComplexTypeReexports(e){let t=e.dependencies?.filter(r=>["complex-type"].includes(r.kind)).map(r=>({tsPackage:`../${H(r.package)}/${z(r.name)}`,name:Se(r.name)}));if(t&&t.length>0){for(let r of t)this.lineSM(`export type { ${r.name} } from "${r.tsPackage}"`);this.line();}}addFieldExtension(e,t){t.type.kind==="primitive-type"&&this.lineSM(`_${O(e)}?: Element`);}generateType(e,t){let r;t.identifier.name==="Reference"?r="Reference<T extends string = string>":(t.identifier.kind,r=x(t.identifier));let i;t.base&&(i=`extends ${Qe(t.base.url)}`),this.debugComment(t.identifier),this.curlyBlock(["export","interface",r,i],()=>{if(B(t)){let o=[t.identifier];o.push(...e.resourceChildren(t.identifier)),this.lineSM(`resourceType: ${o.map(a=>`"${a.name}"`).join(" | ")}`),this.line();}if(!t.fields)return;let n=Object.entries(t.fields).sort((o,a)=>o[0].localeCompare(a[0]));for(let[o,a]of n){if(ee(a)||a.type===void 0)continue;this.debugComment(o,":",a);let c=O(o),l;a.enum?l=a.enum.map(p=>`"${p}"`).join(" | "):t.identifier.name==="Reference"&&c==="reference"?l="`${T}/${string}`":a.reference&&a.reference.length>0?l=`Reference<${a.reference.map(g=>`"${g.name}"`).join(" | ")}>`:De(a.type)?l=Bt(a.type.name):M(a.type)?l=x(a.type):l=a.type.name;let d=a.required?"":"?",u=a.array?"[]":"";this.lineSM(`${c}${d}: ${l}${u}`),["resource","complex-type"].includes(t.identifier.kind)&&this.addFieldExtension(o,a);}});}generateNestedTypes(e,t){if(t.nested)for(let r of t.nested)this.generateType(e,r),this.line();}generateProfileType(e,t){let r=x(t.identifier);this.debugComment("identifier",t.identifier),this.debugComment("base",t.base),this.curlyBlock(["export","interface",r],()=>{this.lineSM(`__profileUrl: "${t.identifier.url}"`),this.line();for(let[i,n]of Object.entries(t.fields??{})){if(ee(n))continue;this.debugComment(i,n);let o=O(i),a;if(n.enum)a=n.enum.map(c=>`'${c}'`).join(" | ");else if(n.reference&&n.reference.length>0){let c=e.findLastSpecialization(t);if(!D(c))throw new Error(`Invalid specialization for ${t.identifier}`);let l=c.fields?.[i];if(l===void 0||ee(l)||l.reference===void 0)throw new Error(`Invalid field declaration for ${i}`);let d=l.reference.map(p=>p.name),u=n.reference.map(p=>{let g=e.findLastSpecializationByIdentifier(p);return g.name!==p.name?`"${g.name}" /*${p.name}*/`:`'${p.name}'`}).join(" | ");d.length===1&&d[0]==="Resource"&&u!=='"Resource"'?a=`Reference<"Resource" /* ${u} */ >`:a=`Reference<${u}>`;}else M(n.type)?a=x(n.type):De(n.type)?a=Bt(n.type.name):a=n.type.name;this.lineSM(`${o}${n.required?"":"?"}: ${a}${n.array?"[]":""}`);}}),this.line();}generateAttachProfile(e){let t=x(e.base),r=x(e.identifier),i=Object.entries(e.fields||{}).filter(([n,o])=>o&&L(o)&&o.type!==void 0).map(([n])=>O(n));this.curlyBlock([`export const attach_${r}_to_${t} =`,`(resource: ${t}, profile: ${r}): ${t}`,"=>"],()=>{this.curlyBlock(["return"],()=>{this.line("...resource,"),this.curlyBlock(["meta:"],()=>{this.line(`profile: ['${e.identifier.url}']`);},[","]),i.forEach(n=>{this.line(`${n}:`,`profile.${n},`);});});}),this.line();}generateExtractProfile(e,t){let r=x(t.base),i=x(t.identifier),n=Object.entries(t.fields||{}).filter(([c,l])=>L(l)&&l.type!==void 0).map(([c])=>c),o=e.findLastSpecialization(t);if(!D(o))throw new Error(`Specialization not found for ${t.identifier.url}`);let a={};this.curlyBlock([`export const extract_${i}_from_${r} =`,`(resource: ${r}): ${i}`,"=>"],()=>{n.forEach(c=>{let l=O(c),d=t.fields?.[c],u=o.fields?.[c];if(!L(d)||!L(u))return;d.required&&!u.required&&this.curlyBlock([`if (resource.${l} === undefined)`],()=>this.lineSM(`throw new Error("'${l}' is required for ${t.identifier.url}")`));let p=d?.reference?.map(f=>f.name),g=u?.reference?.map(f=>f.name);if(p&&g&&p.length!==g.length){let f=`reference_is_valid_${l}`;this.curlyBlock(["const",f,"=","(ref?: Reference)","=>"],()=>{this.line("return !ref"),this.indentBlock(()=>{g.forEach(b=>{this.line(`|| ref.reference?.startsWith('${b}/')`);}),this.line(";");});});let h=d?.required?"":`!resource.${l} || `;d.array?h+=`resource.${l}.every( (ref) => ${f}(ref) )`:h+=`!${f}(resource.${l})`,this.curlyBlock(["if (",h,")"],()=>{this.lineSM(`throw new Error("'${c}' has different references in profile and specialization")`);}),this.line(),a[c]=true;}}),this.curlyBlock(["return"],()=>{this.line(`__profileUrl: '${t.identifier.url}',`),n.forEach(c=>{let l=O(c);a[c]?this.line(`${l}:`,`resource.${l} as ${i}['${l}'],`):this.line(`${l}:`,`resource.${l},`);});});});}generateResourceModule(e,t){this.cat(`${xr(t.identifier)}`,()=>{if(this.generateDisclaimer(),["complex-type","resource","logical"].includes(t.identifier.kind))this.generateDependenciesImports(t),this.generateComplexTypeReexports(t),this.generateNestedTypes(e,t),this.comment("CanonicalURL:",t.identifier.url),this.generateType(e,t);else if(X(t)){let r=e.flatProfile(t);this.generateDependenciesImports(r),this.comment("CanonicalURL:",t.identifier.url),this.generateProfileType(e,r),this.generateAttachProfile(r),this.generateExtractProfile(e,r);}else throw new Error(`Profile generation not implemented for kind: ${t.identifier.kind}`)});}generate(e){let t=[...e.collectComplexTypes(),...e.collectResources(),...e.collectProfiles().filter(i=>e.isWithMetaField(i))],r=Tt(t);this.cd("/",()=>{for(let[i,n]of Object.entries(r)){let o=vr(i);this.cd(o,()=>{for(let a of n)this.generateResourceModule(e,a);this.generateFhirPackageIndexFile(n);});}});}};var Cr=s=>{let e=()=>s.writtenFiles().map(t=>({path:q.normalize(q.join(s.opts.outputDir,t)),filename:t.replace(/^.*[\\/]/,""),content:"",exports:[],size:0,timestamp:new Date}));return {generate:async t=>{let r=Ct(t);return s.generate(r),e()},setOutputDir:t=>s.opts.outputDir=t,build:async t=>e()}},_=class{schemas=[];options;generators=new Map;cache;pendingOperations=[];typeSchemaGenerator;logger;packages=[];progressCallback;typeSchemaConfig;constructor(e={}){this.options={outputDir:e.outputDir||"./generated",verbose:e.verbose??false,overwrite:e.overwrite??true,cache:e.cache??true,cleanOutput:e.cleanOutput??true,typeSchemaConfig:e.typeSchemaConfig,manager:e.manager||null,throwException:e.throwException||false},this.typeSchemaConfig=e.typeSchemaConfig,this.logger=e.logger||w({verbose:this.options.verbose,prefix:"API"}),this.options.cache&&(this.cache=new F(this.typeSchemaConfig));}fromPackage(e,t){return this.packages.push(ot({name:e,version:t||"latest"})),this}fromFiles(...e){this.logger.debug(`Loading from ${e.length} TypeSchema files`);let t=this.loadFromFiles(e);return this.pendingOperations.push(t),this}fromSchemas(e){return this.logger.debug(`Adding ${e.length} TypeSchemas to generation`),this.schemas=[...this.schemas,...e],this}typescript(e={}){let t=`${this.options.outputDir}/types`,r=new U({outputDir:t,moduleFormat:e.moduleFormat||"esm",generateIndex:e.generateIndex??true,includeDocuments:e.includeDocuments??true,namingConvention:e.namingConvention||"PascalCase",includeExtensions:e.includeExtensions??false,includeProfiles:e.includeProfiles??false,generateValueSets:e.generateValueSets??false,includeValueSetHelpers:e.includeValueSetHelpers??false,valueSetStrengths:e.valueSetStrengths??["required"],logger:this.logger.child("TS"),valueSetMode:e.valueSetMode??"required-only",valueSetDirectory:e.valueSetDirectory??"valuesets",verbose:this.options.verbose,validate:true,overwrite:this.options.overwrite});return this.generators.set("typescript",r),this.logger.debug(`Configured TypeScript generator (${e.moduleFormat||"esm"})`),this}typescript2(e){let t={outputDir:q.join(this.options.outputDir,"/types"),tabSize:4,withDebugComment:false,commentLinePrefix:"//"},r={logger:this.logger,...t,...e},i=Cr(new we(r));return this.generators.set("typescript2",i),this.logger.debug(`Configured TypeScript2 generator (${JSON.stringify(r,void 0,2)})`),this}onProgress(e){return this.progressCallback=e,this}outputTo(e){this.logger.debug(`Setting output directory: ${e}`),this.options.outputDir=e;for(let t of this.generators.values())t.setOutputDir&&t.setOutputDir(e);return this}verbose(e=true){return this.options.verbose=e,this.logger?.configure({verbose:e}),this}throwException(e=true){return this.options.throwException=e,this}cleanOutput(e=true){return this.options.cleanOutput=e,this}async generate(){let e=performance.now(),t={success:false,outputDir:this.options.outputDir,filesGenerated:[],errors:[],warnings:[],duration:0};if(this.logger.debug(`Starting generation with ${this.generators.size} generators`),this.options.cleanOutput){this.logger.info(`Cleaning output directory: ${this.options.outputDir}`);try{T.rmSync(this.options.outputDir,{recursive:!0,force:!0}),T.mkdirSync(this.options.outputDir,{recursive:!0});}catch(r){this.logger.warn(`Error cleaning output directory: ${r instanceof Error?r.message:String(r)}`);}}try{this.logger.info("Initialize Canonical Manager");let r=CanonicalManager({packages:this.packages,workingDir:"tmp/fhir"});await r.init();let i=await j(r,this.logger),n=await wt(i,this.logger);this.logger.debug(`Executing ${this.generators.size} generators`),await this.executeGenerators(t,n),this.logger.info("Generation completed successfully"),t.success=t.errors.length===0,this.logger.debug(`Generation completed: ${t.filesGenerated.length} files`);}catch(r){this.logger.error("Code generation failed",r instanceof Error?r:new Error(String(r))),t.errors.push(r instanceof Error?r.message:String(r));}return {...t,success:t.errors.length===0,duration:performance.now()-e}}async build(){let e={};for(let[t,r]of this.generators.entries())r.build&&(e[t]=await r.build(this.schemas));return e}reset(){return this.schemas=[],this.generators.clear(),this.progressCallback=void 0,this}getSchemas(){return [...this.schemas]}getGenerators(){return Array.from(this.generators.keys())}async loadFromFiles(e){this.typeSchemaGenerator||(this.typeSchemaGenerator=new k({verbose:this.options.verbose,logger:this.logger.child("Schema"),treeshake:this.typeSchemaConfig?.treeshake},this.typeSchemaConfig));let r=await new N({format:"auto"}).parseFromFiles(e);this.schemas=[...this.schemas,...r],this.cache&&this.cache.setMany(r);}async executeGenerators(e,t){for(let[r,i]of this.generators.entries()){this.logger.info(`Generating ${r}...`);try{let n=await i.generate(t);e.filesGenerated.push(...n.map(o=>o.path||o.filename)),this.logger.info(`Generating ${r} finished successfully`);}catch(n){if(e.errors.push(`${r} generator failed: ${n instanceof Error?n.message:String(n)}`),this.options.throwException)throw n}}}};var Xe={outputDir:"./generated",verbose:false,overwrite:true,validate:true,cache:true,cleanOutput:true,typescript:{moduleFormat:"esm",generateIndex:true,includeDocuments:false,namingConvention:"PascalCase",strictMode:true,includeProfiles:true,includeExtensions:false,includeCodeSystems:false,includeOperations:false,generateValueSets:false,valueSetDirectory:"valuesets",valueSetMode:"required-only",valueSetStrengths:["required"],includeValueSetHelpers:false,fhirVersion:"R4",resourceTypes:[],maxDepth:10,profileOptions:{generateKind:"interface",includeConstraints:true,includeDocumentation:true,strictMode:false,subfolder:"profiles"},generateBuilders:false,builderOptions:{includeValidation:true,includeFactoryMethods:true,includeInterfaces:true,generateNestedBuilders:true,includeHelperMethods:true,supportPartialBuild:true,includeJSDoc:true,generateFactories:true,includeTypeGuards:true,handleChoiceTypes:true,generateArrayHelpers:true},validatorOptions:{includeCardinality:true,includeTypes:true,includeConstraints:true,includeInvariants:false,validateRequired:true,allowAdditional:false,strictValidation:false,collectMetrics:false,generateAssertions:true,generatePartialValidators:true,optimizePerformance:true,includeJSDoc:true,generateCompositeValidators:true},guardOptions:{includeRuntimeValidation:true,includeErrorMessages:true,treeShakeable:true,targetTSVersion:"5.0",strictGuards:false,includeNullChecks:true,verbose:false}},typeSchema:{enablePersistence:true,cacheDir:".typeschema-cache",maxAge:1440*60*1e3,validateCached:true,forceRegenerate:false,shareCache:true,cacheKeyPrefix:"",treeshake:[],singleFile:false,profiles:{autoDetect:true}},packages:[],files:[],$schema:""},Ce=["atomic-codegen.config.ts","atomic-codegen.config","atomic-codegen.config.json",".atomic-codegenrc","atomic-codegen.json",".atomic-codegen.json","codegen.config.json","codegen.json"],et=class{validate(e){let t={valid:true,errors:[],warnings:[]};if(!e||typeof e!="object")return t.valid=false,t.errors.push({path:"root",message:"Configuration must be an object",value:e}),t;let r=e;r.outputDir!==void 0&&typeof r.outputDir!="string"&&t.errors.push({path:"outputDir",message:"outputDir must be a string",value:r.outputDir});let i=["verbose","overwrite","validate","cache"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.errors.push({path:n,message:`${n} must be a boolean`,value:r[n]});if(r.typescript!==void 0){let n=this.validateTypeScriptConfig(r.typescript);t.errors.push(...n);}if(r.typeSchema!==void 0){let n=this.validateTypeSchemaConfig(r.typeSchema);t.errors.push(...n);}return r.packages!==void 0&&(Array.isArray(r.packages)?r.packages.forEach((n,o)=>{typeof n!="string"&&t.errors.push({path:`packages[${o}]`,message:"package name must be a string",value:n});}):t.errors.push({path:"packages",message:"packages must be an array",value:r.packages})),r.files!==void 0&&(Array.isArray(r.files)?r.files.forEach((n,o)=>{typeof n!="string"&&t.errors.push({path:`files[${o}]`,message:"file path must be a string",value:n});}):t.errors.push({path:"files",message:"files must be an array",value:r.files})),t.valid=t.errors.length===0,t.valid&&(t.config=r),t}validateTypeScriptConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript",message:"typescript config must be an object",value:e}),t;let r=e;r.moduleFormat!==void 0&&(["esm","cjs"].includes(r.moduleFormat)||t.push({path:"typescript.moduleFormat",message:'moduleFormat must be "esm" or "cjs"',value:r.moduleFormat})),r.namingConvention!==void 0&&(["PascalCase","camelCase"].includes(r.namingConvention)||t.push({path:"typescript.namingConvention",message:'namingConvention must be "PascalCase" or "camelCase"',value:r.namingConvention}));let i=["generateIndex","includeDocuments","strictMode","includeProfiles","includeExtensions","includeCodeSystems","includeOperations","generateValueSets","includeValueSetHelpers"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.${n}`,message:`${n} must be a boolean`,value:r[n]});if(r.validatorOptions!==void 0){let n=this.validateValidatorOptions(r.validatorOptions);t.push(...n);}if(r.guardOptions!==void 0){let n=this.validateGuardOptions(r.guardOptions);t.push(...n);}if(r.profileOptions!==void 0){let n=this.validateProfileOptions(r.profileOptions);t.push(...n);}return t}validateValidatorOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.validatorOptions",message:"validatorOptions must be an object",value:e}),t;let r=e,i=["includeCardinality","includeTypes","includeConstraints","includeInvariants","validateRequired","allowAdditional","strictValidation","collectMetrics","generateAssertions","generatePartialValidators","optimizePerformance","includeJSDoc","generateCompositeValidators"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.validatorOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateGuardOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.guardOptions",message:"guardOptions must be an object",value:e}),t;let r=e;r.targetTSVersion!==void 0&&(["3.8","4.0","4.5","5.0"].includes(r.targetTSVersion)||t.push({path:"typescript.guardOptions.targetTSVersion",message:'targetTSVersion must be one of: "3.8", "4.0", "4.5", "5.0"',value:r.targetTSVersion}));let i=["includeRuntimeValidation","includeErrorMessages","treeShakeable","strictGuards","includeNullChecks","verbose"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.guardOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateProfileOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.profileOptions",message:"profileOptions must be an object",value:e}),t;let r=e;r.generateKind!==void 0&&(["interface","type","both"].includes(r.generateKind)||t.push({path:"typescript.profileOptions.generateKind",message:'generateKind must be "interface", "type", or "both"',value:r.generateKind})),r.subfolder!==void 0&&typeof r.subfolder!="string"&&t.push({path:"typescript.profileOptions.subfolder",message:"subfolder must be a string",value:r.subfolder});let i=["includeConstraints","includeDocumentation","strictMode"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.profileOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateTypeSchemaConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typeSchema",message:"typeSchema config must be an object",value:e}),t;let r=e,i=["enablePersistence","validateCached","forceRegenerate","shareCache"];for(let o of i)r[o]!==void 0&&typeof r[o]!="boolean"&&t.push({path:`typeSchema.${o}`,message:`${o} must be a boolean`,value:r[o]});let n=["cacheDir","cacheKeyPrefix"];for(let o of n)r[o]!==void 0&&typeof r[o]!="string"&&t.push({path:`typeSchema.${o}`,message:`${o} must be a string`,value:r[o]});if(r.maxAge!==void 0&&(typeof r.maxAge!="number"||r.maxAge<=0)&&t.push({path:"typeSchema.maxAge",message:"maxAge must be a positive number",value:r.maxAge}),r.profiles!==void 0)if(typeof r.profiles!="object"||r.profiles===null)t.push({path:"typeSchema.profiles",message:"profiles must be an object",value:r.profiles});else {let o=r.profiles;o.autoDetect!==void 0&&typeof o.autoDetect!="boolean"&&t.push({path:"typeSchema.profiles.autoDetect",message:"autoDetect must be a boolean",value:o.autoDetect});}return t}},tt=class{validator=new et;async autoload(e=process.cwd()){let t=await this.findConfigFile(e);return t?this.loadFromFile(t):{...Xe}}async loadFromFile(e){try{let t;if(e.endsWith(".ts")||e.endsWith("")){let n=await import(resolve(e));t=n.default||n;}else {let i=await readFile(e,"utf-8");t=JSON.parse(i);}let r=this.validator.validate(t);if(!r.valid){let i=r.errors.map(n=>`${n.path}: ${n.message}`).join(`
|
|
41
|
+
`);for(let r of t)this.line(this.opts.commentLinePrefix,r);}debugComment(...e){this.opts.withDebugComment&&(e=e.map(t=>typeof t=="string"?t:JSON.stringify(t,null,2)),this.comment(...e));}disclaimer(){return ["WARNING: This file is autogenerated by @atomic-ehr/codegen.","GitHub: https://github.com/orgs/atomic-ehr/repositories","Any manual changes made to this file may be overwritten."]}generateDisclaimer(){this.disclaimer().forEach(e=>this.comment(e)),this.line();}indentBlock(e){this.indent(),e(),this.deindent();}curlyBlock(e,t,r){this.line(`${e.filter(Boolean).join(" ")} {`),this.indent(),t(),this.deindent(),this.line(`}${r?.filter(Boolean).join(" ")??""}`);}squareBlock(e,t,r){this.line(`${e.filter(Boolean).join(" ")} [`),this.indent(),t(),this.deindent(),this.line(`]${r?.filter(Boolean).join(" ")??""}`);}};var Sr={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"},Bt=s=>{let e=Sr[s];if(e===void 0)throw new Error(`Unknown primitive type ${s}`);return e},vr=s=>H(s),Lt=s=>s.kind==="profile"?`${x(s)}_profile`:z(s.name),xr=s=>`${Lt(s)}.ts`,Qe=(s,e=true)=>{if(!s)return;let t=s.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),xe(t)},x=s=>{if(s.kind==="nested"){let e=s.url,t=Qe(e,false);if(!t)return "";let[r,i]=t.split("#"),n=Dt((i??"").split(".")).join("");return xe([r,n].join(""))}return xe(s.name)},O=s=>xe(s),xe=s=>(new Set(["abstract","any","as","async","await","boolean","bigint","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","extern","false","finally","for","function","from","get","goto","if","implements","import","in","infer","instanceof","interface","keyof","let","module","namespace","never","new","null","number","object","of","override","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","this","throw","true","try","type","typeof","unknown","var","void","while"]).has(s)&&(s=`${s}_`),s.replace(/[- ]/g,"_")),we=class extends ve{tsImportType(e,...t){this.lineSM(`import type { ${t.join(", ")} } from "${e}"`);}generateFhirPackageIndexFile(e){this.cat("index.ts",()=>{let t=e.map(r=>({identifier:r.identifier,tsPackageName:Lt(r.identifier),resourceName:x(r.identifier)})).sort((r,i)=>r.resourceName.localeCompare(i.resourceName));t=Array.from(new Map(t.map(r=>[r.resourceName.toLowerCase(),r])).values()).sort((r,i)=>r.resourceName.localeCompare(i.resourceName));for(let r of t)this.debugComment(r.identifier),this.lineSM(`export type { ${r.resourceName} } from "./${r.tsPackageName}"`);});}generateDependenciesImports(e){if(e.dependencies){let t=[],r=[];for(let i of e.dependencies)["complex-type","resource","logical"].includes(i.kind)?t.push({tsPackage:`../${H(i.package)}/${z(i.name)}`,name:Se(i.name)}):M(i)?t.push({tsPackage:`../${H(i.package)}/${z(Qe(i.url)??"")}`,name:x(i)}):r.push(i);t.sort((i,n)=>i.name.localeCompare(n.name));for(let i of t)this.tsImportType(i.tsPackage,i.name);for(let i of r)this.debugComment("skip:",i);this.line();}}generateComplexTypeReexports(e){let t=e.dependencies?.filter(r=>["complex-type"].includes(r.kind)).map(r=>({tsPackage:`../${H(r.package)}/${z(r.name)}`,name:Se(r.name)}));if(t&&t.length>0){for(let r of t)this.lineSM(`export type { ${r.name} } from "${r.tsPackage}"`);this.line();}}addFieldExtension(e,t){t.type.kind==="primitive-type"&&this.lineSM(`_${O(e)}?: Element`);}generateType(e,t){let r;t.identifier.name==="Reference"?r="Reference<T extends string = string>":(t.identifier.kind,r=x(t.identifier));let i;t.base&&(i=`extends ${Qe(t.base.url)}`),this.debugComment(t.identifier),this.curlyBlock(["export","interface",r,i],()=>{if(B(t)){let o=[t.identifier];o.push(...e.resourceChildren(t.identifier)),this.lineSM(`resourceType: ${o.map(a=>`"${a.name}"`).join(" | ")}`),this.line();}if(!t.fields)return;let n=Object.entries(t.fields).sort((o,a)=>o[0].localeCompare(a[0]));for(let[o,a]of n){if(ee(a))continue;this.debugComment(o,":",a);let c=O(o),l;a.enum?l=a.enum.map(p=>`"${p}"`).join(" | "):t.identifier.name==="Reference"&&c==="reference"?l="`${T}/${string}`":a.reference&&a.reference.length>0?l=`Reference<${a.reference.map(g=>`"${g.name}"`).join(" | ")}>`:De(a.type)?l=Bt(a.type.name):M(a.type)?l=x(a.type):l=a.type.name;let d=a.required?"":"?",u=a.array?"[]":"";this.lineSM(`${c}${d}: ${l}${u}`),["resource","complex-type"].includes(t.identifier.kind)&&this.addFieldExtension(o,a);}});}generateNestedTypes(e,t){if(t.nested)for(let r of t.nested)this.generateType(e,r),this.line();}generateProfileType(e,t){let r=x(t.identifier);this.debugComment("identifier",t.identifier),this.debugComment("base",t.base),this.curlyBlock(["export","interface",r],()=>{this.lineSM(`__profileUrl: "${t.identifier.url}"`),this.line();for(let[i,n]of Object.entries(t.fields??{})){if(ee(n))continue;this.debugComment(i,n);let o=O(i),a;if(n.enum)a=n.enum.map(c=>`'${c}'`).join(" | ");else if(n.reference&&n.reference.length>0){let c=e.findLastSpecialization(t);if(!D(c))throw new Error(`Invalid specialization for ${t.identifier}`);let l=c.fields?.[i];if(l===void 0||ee(l)||l.reference===void 0)throw new Error(`Invalid field declaration for ${i}`);let d=l.reference.map(p=>p.name),u=n.reference.map(p=>{let g=e.findLastSpecializationByIdentifier(p);return g.name!==p.name?`"${g.name}" /*${p.name}*/`:`'${p.name}'`}).join(" | ");d.length===1&&d[0]==="Resource"&&u!=='"Resource"'?a=`Reference<"Resource" /* ${u} */ >`:a=`Reference<${u}>`;}else M(n.type)?a=x(n.type):De(n.type)?a=Bt(n.type.name):a=n.type.name;this.lineSM(`${o}${n.required?"":"?"}: ${a}${n.array?"[]":""}`);}}),this.line();}generateAttachProfile(e){let t=x(e.base),r=x(e.identifier),i=Object.entries(e.fields||{}).filter(([n,o])=>o&&L(o)&&o.type!==void 0).map(([n])=>O(n));this.curlyBlock([`export const attach_${r}_to_${t} =`,`(resource: ${t}, profile: ${r}): ${t}`,"=>"],()=>{this.curlyBlock(["return"],()=>{this.line("...resource,"),this.curlyBlock(["meta:"],()=>{this.line(`profile: ['${e.identifier.url}']`);},[","]),i.forEach(n=>{this.line(`${n}:`,`profile.${n},`);});});}),this.line();}generateExtractProfile(e,t){let r=x(t.base),i=x(t.identifier),n=Object.entries(t.fields||{}).filter(([c,l])=>L(l)&&l.type!==void 0).map(([c])=>c),o=e.findLastSpecialization(t);if(!D(o))throw new Error(`Specialization not found for ${t.identifier.url}`);let a={};this.curlyBlock([`export const extract_${i}_from_${r} =`,`(resource: ${r}): ${i}`,"=>"],()=>{n.forEach(c=>{let l=O(c),d=t.fields?.[c],u=o.fields?.[c];if(!L(d)||!L(u))return;d.required&&!u.required&&this.curlyBlock([`if (resource.${l} === undefined)`],()=>this.lineSM(`throw new Error("'${l}' is required for ${t.identifier.url}")`));let p=d?.reference?.map(f=>f.name),g=u?.reference?.map(f=>f.name);if(p&&g&&p.length!==g.length){let f=`reference_is_valid_${l}`;this.curlyBlock(["const",f,"=","(ref?: Reference)","=>"],()=>{this.line("return !ref"),this.indentBlock(()=>{g.forEach(b=>{this.line(`|| ref.reference?.startsWith('${b}/')`);}),this.line(";");});});let h=d?.required?"":`!resource.${l} || `;d.array?h+=`resource.${l}.every( (ref) => ${f}(ref) )`:h+=`!${f}(resource.${l})`,this.curlyBlock(["if (",h,")"],()=>{this.lineSM(`throw new Error("'${c}' has different references in profile and specialization")`);}),this.line(),a[c]=true;}}),this.curlyBlock(["return"],()=>{this.line(`__profileUrl: '${t.identifier.url}',`),n.forEach(c=>{let l=O(c);a[c]?this.line(`${l}:`,`resource.${l} as ${i}['${l}'],`):this.line(`${l}:`,`resource.${l},`);});});});}generateResourceModule(e,t){this.cat(`${xr(t.identifier)}`,()=>{if(this.generateDisclaimer(),["complex-type","resource","logical"].includes(t.identifier.kind))this.generateDependenciesImports(t),this.generateComplexTypeReexports(t),this.generateNestedTypes(e,t),this.comment("CanonicalURL:",t.identifier.url),this.generateType(e,t);else if(X(t)){let r=e.flatProfile(t);this.generateDependenciesImports(r),this.comment("CanonicalURL:",t.identifier.url),this.generateProfileType(e,r),this.generateAttachProfile(r),this.generateExtractProfile(e,r);}else throw new Error(`Profile generation not implemented for kind: ${t.identifier.kind}`)});}generate(e){let t=[...e.collectComplexTypes(),...e.collectResources(),...e.collectProfiles().filter(i=>e.isWithMetaField(i))],r=Tt(t);this.cd("/",()=>{for(let[i,n]of Object.entries(r)){let o=vr(i);this.cd(o,()=>{for(let a of n)this.generateResourceModule(e,a);this.generateFhirPackageIndexFile(n);});}});}};var Cr=s=>{let e=()=>s.writtenFiles().map(t=>({path:q.normalize(q.join(s.opts.outputDir,t)),filename:t.replace(/^.*[\\/]/,""),content:"",exports:[],size:0,timestamp:new Date}));return {generate:async t=>{let r=Ct(t);return s.generate(r),e()},setOutputDir:t=>s.opts.outputDir=t,build:async t=>e()}},_=class{schemas=[];options;generators=new Map;cache;pendingOperations=[];typeSchemaGenerator;logger;packages=[];progressCallback;typeSchemaConfig;constructor(e={}){this.options={outputDir:e.outputDir||"./generated",verbose:e.verbose??false,overwrite:e.overwrite??true,cache:e.cache??true,cleanOutput:e.cleanOutput??true,typeSchemaConfig:e.typeSchemaConfig,manager:e.manager||null,throwException:e.throwException||false},this.typeSchemaConfig=e.typeSchemaConfig,this.logger=e.logger||w({verbose:this.options.verbose,prefix:"API"}),this.options.cache&&(this.cache=new F(this.typeSchemaConfig));}fromPackage(e,t){return this.packages.push(ot({name:e,version:t||"latest"})),this}fromFiles(...e){this.logger.debug(`Loading from ${e.length} TypeSchema files`);let t=this.loadFromFiles(e);return this.pendingOperations.push(t),this}fromSchemas(e){return this.logger.debug(`Adding ${e.length} TypeSchemas to generation`),this.schemas=[...this.schemas,...e],this}typescript(e={}){let t=`${this.options.outputDir}/types`,r=new U({outputDir:t,moduleFormat:e.moduleFormat||"esm",generateIndex:e.generateIndex??true,includeDocuments:e.includeDocuments??true,namingConvention:e.namingConvention||"PascalCase",includeExtensions:e.includeExtensions??false,includeProfiles:e.includeProfiles??false,generateValueSets:e.generateValueSets??false,includeValueSetHelpers:e.includeValueSetHelpers??false,valueSetStrengths:e.valueSetStrengths??["required"],logger:this.logger.child("TS"),valueSetMode:e.valueSetMode??"required-only",valueSetDirectory:e.valueSetDirectory??"valuesets",verbose:this.options.verbose,validate:true,overwrite:this.options.overwrite});return this.generators.set("typescript",r),this.logger.debug(`Configured TypeScript generator (${e.moduleFormat||"esm"})`),this}typescript2(e){let t={outputDir:q.join(this.options.outputDir,"/types"),tabSize:4,withDebugComment:false,commentLinePrefix:"//"},r={logger:this.logger,...t,...e},i=Cr(new we(r));return this.generators.set("typescript2",i),this.logger.debug(`Configured TypeScript2 generator (${JSON.stringify(r,void 0,2)})`),this}onProgress(e){return this.progressCallback=e,this}outputTo(e){this.logger.debug(`Setting output directory: ${e}`),this.options.outputDir=e;for(let t of this.generators.values())t.setOutputDir&&t.setOutputDir(e);return this}verbose(e=true){return this.options.verbose=e,this.logger?.configure({verbose:e}),this}throwException(e=true){return this.options.throwException=e,this}cleanOutput(e=true){return this.options.cleanOutput=e,this}async generate(){let e=performance.now(),t={success:false,outputDir:this.options.outputDir,filesGenerated:[],errors:[],warnings:[],duration:0};if(this.logger.debug(`Starting generation with ${this.generators.size} generators`),this.options.cleanOutput){this.logger.info(`Cleaning output directory: ${this.options.outputDir}`);try{T.rmSync(this.options.outputDir,{recursive:!0,force:!0}),T.mkdirSync(this.options.outputDir,{recursive:!0});}catch(r){this.logger.warn(`Error cleaning output directory: ${r instanceof Error?r.message:String(r)}`);}}try{this.logger.info("Initialize Canonical Manager");let r=CanonicalManager({packages:this.packages,workingDir:"tmp/fhir"});await r.init();let i=await j(r,this.logger),n=await wt(i,this.logger);this.logger.debug(`Executing ${this.generators.size} generators`),await this.executeGenerators(t,n),this.logger.info("Generation completed successfully"),t.success=t.errors.length===0,this.logger.debug(`Generation completed: ${t.filesGenerated.length} files`);}catch(r){this.logger.error("Code generation failed",r instanceof Error?r:new Error(String(r))),t.errors.push(r instanceof Error?r.message:String(r));}return {...t,success:t.errors.length===0,duration:performance.now()-e}}async build(){let e={};for(let[t,r]of this.generators.entries())r.build&&(e[t]=await r.build(this.schemas));return e}reset(){return this.schemas=[],this.generators.clear(),this.progressCallback=void 0,this}getSchemas(){return [...this.schemas]}getGenerators(){return Array.from(this.generators.keys())}async loadFromFiles(e){this.typeSchemaGenerator||(this.typeSchemaGenerator=new k({verbose:this.options.verbose,logger:this.logger.child("Schema"),treeshake:this.typeSchemaConfig?.treeshake},this.typeSchemaConfig));let r=await new N({format:"auto"}).parseFromFiles(e);this.schemas=[...this.schemas,...r],this.cache&&this.cache.setMany(r);}async executeGenerators(e,t){for(let[r,i]of this.generators.entries()){this.logger.info(`Generating ${r}...`);try{let n=await i.generate(t);e.filesGenerated.push(...n.map(o=>o.path||o.filename)),this.logger.info(`Generating ${r} finished successfully`);}catch(n){if(e.errors.push(`${r} generator failed: ${n instanceof Error?n.message:String(n)}`),this.options.throwException)throw n}}}};var Xe={outputDir:"./generated",verbose:false,overwrite:true,validate:true,cache:true,cleanOutput:true,typescript:{moduleFormat:"esm",generateIndex:true,includeDocuments:false,namingConvention:"PascalCase",strictMode:true,includeProfiles:true,includeExtensions:false,includeCodeSystems:false,includeOperations:false,generateValueSets:false,valueSetDirectory:"valuesets",valueSetMode:"required-only",valueSetStrengths:["required"],includeValueSetHelpers:false,fhirVersion:"R4",resourceTypes:[],maxDepth:10,profileOptions:{generateKind:"interface",includeConstraints:true,includeDocumentation:true,strictMode:false,subfolder:"profiles"},generateBuilders:false,builderOptions:{includeValidation:true,includeFactoryMethods:true,includeInterfaces:true,generateNestedBuilders:true,includeHelperMethods:true,supportPartialBuild:true,includeJSDoc:true,generateFactories:true,includeTypeGuards:true,handleChoiceTypes:true,generateArrayHelpers:true},validatorOptions:{includeCardinality:true,includeTypes:true,includeConstraints:true,includeInvariants:false,validateRequired:true,allowAdditional:false,strictValidation:false,collectMetrics:false,generateAssertions:true,generatePartialValidators:true,optimizePerformance:true,includeJSDoc:true,generateCompositeValidators:true},guardOptions:{includeRuntimeValidation:true,includeErrorMessages:true,treeShakeable:true,targetTSVersion:"5.0",strictGuards:false,includeNullChecks:true,verbose:false}},typeSchema:{enablePersistence:true,cacheDir:".typeschema-cache",maxAge:1440*60*1e3,validateCached:true,forceRegenerate:false,shareCache:true,cacheKeyPrefix:"",treeshake:[],singleFile:false,profiles:{autoDetect:true}},packages:[],files:[],$schema:""},Ce=["atomic-codegen.config.ts","atomic-codegen.config","atomic-codegen.config.json",".atomic-codegenrc","atomic-codegen.json",".atomic-codegen.json","codegen.config.json","codegen.json"],et=class{validate(e){let t={valid:true,errors:[],warnings:[]};if(!e||typeof e!="object")return t.valid=false,t.errors.push({path:"root",message:"Configuration must be an object",value:e}),t;let r=e;r.outputDir!==void 0&&typeof r.outputDir!="string"&&t.errors.push({path:"outputDir",message:"outputDir must be a string",value:r.outputDir});let i=["verbose","overwrite","validate","cache"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.errors.push({path:n,message:`${n} must be a boolean`,value:r[n]});if(r.typescript!==void 0){let n=this.validateTypeScriptConfig(r.typescript);t.errors.push(...n);}if(r.typeSchema!==void 0){let n=this.validateTypeSchemaConfig(r.typeSchema);t.errors.push(...n);}return r.packages!==void 0&&(Array.isArray(r.packages)?r.packages.forEach((n,o)=>{typeof n!="string"&&t.errors.push({path:`packages[${o}]`,message:"package name must be a string",value:n});}):t.errors.push({path:"packages",message:"packages must be an array",value:r.packages})),r.files!==void 0&&(Array.isArray(r.files)?r.files.forEach((n,o)=>{typeof n!="string"&&t.errors.push({path:`files[${o}]`,message:"file path must be a string",value:n});}):t.errors.push({path:"files",message:"files must be an array",value:r.files})),t.valid=t.errors.length===0,t.valid&&(t.config=r),t}validateTypeScriptConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript",message:"typescript config must be an object",value:e}),t;let r=e;r.moduleFormat!==void 0&&(["esm","cjs"].includes(r.moduleFormat)||t.push({path:"typescript.moduleFormat",message:'moduleFormat must be "esm" or "cjs"',value:r.moduleFormat})),r.namingConvention!==void 0&&(["PascalCase","camelCase"].includes(r.namingConvention)||t.push({path:"typescript.namingConvention",message:'namingConvention must be "PascalCase" or "camelCase"',value:r.namingConvention}));let i=["generateIndex","includeDocuments","strictMode","includeProfiles","includeExtensions","includeCodeSystems","includeOperations","generateValueSets","includeValueSetHelpers"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.${n}`,message:`${n} must be a boolean`,value:r[n]});if(r.validatorOptions!==void 0){let n=this.validateValidatorOptions(r.validatorOptions);t.push(...n);}if(r.guardOptions!==void 0){let n=this.validateGuardOptions(r.guardOptions);t.push(...n);}if(r.profileOptions!==void 0){let n=this.validateProfileOptions(r.profileOptions);t.push(...n);}return t}validateValidatorOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.validatorOptions",message:"validatorOptions must be an object",value:e}),t;let r=e,i=["includeCardinality","includeTypes","includeConstraints","includeInvariants","validateRequired","allowAdditional","strictValidation","collectMetrics","generateAssertions","generatePartialValidators","optimizePerformance","includeJSDoc","generateCompositeValidators"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.validatorOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateGuardOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.guardOptions",message:"guardOptions must be an object",value:e}),t;let r=e;r.targetTSVersion!==void 0&&(["3.8","4.0","4.5","5.0"].includes(r.targetTSVersion)||t.push({path:"typescript.guardOptions.targetTSVersion",message:'targetTSVersion must be one of: "3.8", "4.0", "4.5", "5.0"',value:r.targetTSVersion}));let i=["includeRuntimeValidation","includeErrorMessages","treeShakeable","strictGuards","includeNullChecks","verbose"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.guardOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateProfileOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.profileOptions",message:"profileOptions must be an object",value:e}),t;let r=e;r.generateKind!==void 0&&(["interface","type","both"].includes(r.generateKind)||t.push({path:"typescript.profileOptions.generateKind",message:'generateKind must be "interface", "type", or "both"',value:r.generateKind})),r.subfolder!==void 0&&typeof r.subfolder!="string"&&t.push({path:"typescript.profileOptions.subfolder",message:"subfolder must be a string",value:r.subfolder});let i=["includeConstraints","includeDocumentation","strictMode"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.profileOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateTypeSchemaConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typeSchema",message:"typeSchema config must be an object",value:e}),t;let r=e,i=["enablePersistence","validateCached","forceRegenerate","shareCache"];for(let o of i)r[o]!==void 0&&typeof r[o]!="boolean"&&t.push({path:`typeSchema.${o}`,message:`${o} must be a boolean`,value:r[o]});let n=["cacheDir","cacheKeyPrefix"];for(let o of n)r[o]!==void 0&&typeof r[o]!="string"&&t.push({path:`typeSchema.${o}`,message:`${o} must be a string`,value:r[o]});if(r.maxAge!==void 0&&(typeof r.maxAge!="number"||r.maxAge<=0)&&t.push({path:"typeSchema.maxAge",message:"maxAge must be a positive number",value:r.maxAge}),r.profiles!==void 0)if(typeof r.profiles!="object"||r.profiles===null)t.push({path:"typeSchema.profiles",message:"profiles must be an object",value:r.profiles});else {let o=r.profiles;o.autoDetect!==void 0&&typeof o.autoDetect!="boolean"&&t.push({path:"typeSchema.profiles.autoDetect",message:"autoDetect must be a boolean",value:o.autoDetect});}return t}},tt=class{validator=new et;async autoload(e=process.cwd()){let t=await this.findConfigFile(e);return t?this.loadFromFile(t):{...Xe}}async loadFromFile(e){try{let t;if(e.endsWith(".ts")||e.endsWith("")){let n=await import(resolve(e));t=n.default||n;}else {let i=await readFile(e,"utf-8");t=JSON.parse(i);}let r=this.validator.validate(t);if(!r.valid){let i=r.errors.map(n=>`${n.path}: ${n.message}`).join(`
|
|
42
42
|
`);throw new Error(`Configuration validation failed:
|
|
43
43
|
${i}`)}return this.mergeWithDefaults(r.config)}catch(t){throw t instanceof Error?new Error(`Failed to load config from ${e}: ${t.message}`):t}}async findConfigFile(e){for(let t of Ce){let r=resolve(e,t);if(existsSync(r))return r}return null}mergeWithDefaults(e){return {...Xe,...e,typescript:{...Xe.typescript,...e.typescript}}}},$r=new tt;async function Fe(s){return $r.autoload(s)}var Vt={command:"generate",describe:"Generate code based on configuration file settings",builder:s=>s.option("verbose",{alias:"v",type:"boolean",default:false,description:"Enable verbose output"}).example("$0 generate","Generate code using settings from config file").example("$0 generate --verbose","Generate with verbose output"),handler:async s=>{if(s._.length>1){let o=s._.slice(1).join(" ");S(`Invalid syntax: 'atomic-codegen generate ${o}'
|
|
44
44
|
|
package/dist/index.js
CHANGED
|
@@ -5414,7 +5414,6 @@ var TypeScript = class extends Writer {
|
|
|
5414
5414
|
const fields = Object.entries(schema.fields).sort((a, b) => a[0].localeCompare(b[0]));
|
|
5415
5415
|
for (const [fieldName, field] of fields) {
|
|
5416
5416
|
if (isChoiceDeclarationField(field)) continue;
|
|
5417
|
-
if (field.type === void 0) continue;
|
|
5418
5417
|
this.debugComment(fieldName, ":", field);
|
|
5419
5418
|
const tsName = tsFieldName(fieldName);
|
|
5420
5419
|
let tsType;
|