swagger-typescript-api 13.0.26 → 13.0.27

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.
@@ -1,5 +1,5 @@
1
- import {consola}from'consola';import f from'lodash';import*as g from'typescript';import*as at from'prettier';import*as pt from'cosmiconfig';import*as ut from'nanoid';import*as dt from'js-yaml';import*as Tt from'swagger2openapi';import*as F from'node:path';import F__default from'node:path';import*as Pt from'node:url';import Pt__default from'node:url';import*as St from'eta';import*as C from'node:fs';var jt=Object.defineProperty;var Dt=(p,e)=>{for(var t in e)jt(p,t,{get:e[t],enumerable:true});};var ee=class{config;constructor(e){this.config=e;}removeUnusedImports=e=>{let t="file.ts",s=new Ke(t,e),a=g.createLanguageService(s).organizeImports({type:"file",fileName:t},{newLineCharacter:g.sys.newLine},void 0)[0];return a?.textChanges.length?a.textChanges.reduceRight((i,{span:o,newText:n})=>`${i.slice(0,o.start)}${n}${i.slice(o.start+o.length)}`,e):e};prettierFormat=async e=>await at.format(e,this.config.prettierOptions);formatCode=async(e,{removeUnusedImports:t=true,prettierFormat:s=true}={})=>(t&&(e=this.removeUnusedImports(e)),s&&(e=await this.prettierFormat(e)),e)},Ke=class{fileName;content;compilerOptions;constructor(e,t){this.fileName=e,this.content=t;let s=g.findConfigFile(e,g.sys.fileExists);this.compilerOptions=s?g.convertCompilerOptionsFromJson(g.readConfigFile(s,g.sys.readFile).config.compilerOptions,"").options:g.getDefaultCompilerOptions();}getNewLine(){return "newLine"in g.sys?g.sys.newLine:`
2
- `}getScriptFileNames(){return [this.fileName]}getCompilationSettings(){return this.compilerOptions}getDefaultLibFileName(){return g.getDefaultLibFileName(this.getCompilationSettings())}getCurrentDirectory(){return process.cwd()}getScriptVersion(){return g.version}getScriptSnapshot(){return g.ScriptSnapshot.fromString(this.content)}readFile(e,t){return e===this.fileName?this.content:g.sys.readFile(e,t)}fileExists(e){return g.sys.fileExists(e)}};var b=class{reservedNames=[];getFallbackName;config;constructor(e,t,s){this.config=e,this.getFallbackName=s,this.reserve(t);}reserve(e){let t=f.uniq(f.compact(e));for(let s of t)this.reservedNames.indexOf(s)===-1&&this.reservedNames.push(s);}unreserve(e){this.reservedNames.filter(t=>!e.some(s=>s===t));}isReserved(e){return this.reservedNames.some(t=>t===e)}resolve(e,t,s,r=true){if(typeof t=="function"){let a=null;for(;a===null;){let i=t(e,s);if(i===void 0)return consola.warn("unable to resolve name. current reserved names: ",...this.reservedNames),null;(!r||!this.isReserved(i))&&(a=i);}return r&&this.reserve([a]),a}if(Array.isArray(e)){let a=null,i=f.uniq(f.compact(e));for(let o of i)!a&&(!r||!this.isReserved(o))&&(a=o);return a?(r&&this.reserve([a]),a):(consola.debug("trying to resolve name with using fallback name generator using variants",...e),this.resolve(e,this.getFallbackName,s))}return consola.debug("problem with reserving names. current reserved names: ",...this.reservedNames),null}};var _t=(p=0,e=1)=>Math.random()*(e-p)+p,it=(p=0,e=1)=>p===e?p:Math.round(_t(p,e));var se=class extends b{counter=1;fallbackNameCounter=1;countersByVariant=new Map;constructor(e,t){super(e,t,s=>{let r=s[it(0,s.length-1)];if(r){this.countersByVariant.has(r)||this.countersByVariant.set(r,0);let i=this.countersByVariant.get(r)+1;this.countersByVariant.set(r,i);let o=`${r}${i}`;return consola.debug("generated dirty resolved type name for component - ",o),o}let a=`${this.config.componentTypeNameResolver}${this.fallbackNameCounter++}`;return consola.debug("generated fallback type name for component - ",a),a});}};var ae={};Dt(ae,{DEFAULT_BODY_ARG_NAME:()=>Ue,FILE_PREFIX:()=>qt,HTTP_CLIENT:()=>L,PRETTIER_OPTIONS:()=>re,PROJECT_VERSION:()=>H,RESERVED_BODY_ARG_NAMES:()=>Ge,RESERVED_HEADER_ARG_NAMES:()=>We,RESERVED_PATH_ARG_NAMES:()=>Ve,RESERVED_QUERY_ARG_NAMES:()=>Be,RESERVED_REQ_PARAMS_ARG_NAMES:()=>Ut,SCHEMA_TYPES:()=>l});var ot={name:"swagger-typescript-api",version:"13.0.26",description:"Generate the API client for Fetch or Axios from an OpenAPI Specification",homepage:"https://github.com/acacode/swagger-typescript-api",bugs:"https://github.com/acacode/swagger-typescript-api/issues",repository:"github:acacode/swagger-typescript-api",license:"MIT",author:"Sergey Volkov <js2me@outlook.com>",contributors:["Sora Morimoto <sora@morimoto.io>"],type:"module",exports:{".":{import:{default:"./dist/lib.js"},require:{default:"./dist/lib.cjs"}}},main:"./dist/lib.cjs",module:"./dist/lib.js",bin:{sta:"./dist/cli.js","swagger-typescript-api":"./dist/cli.js"},files:["dist","templates"],scripts:{build:"tsup","cli:help":"node index.js -h","cli:json":"node index.js -r -d -p ./swagger-test-cli.json -n swagger-test-cli.ts","cli:yaml":"node index.js -r -d -p ./swagger-test-cli.yaml -n swagger-test-cli.ts",format:"biome format --write .","format:check":"biome format .",lint:"biome check",prepack:"tsup",test:"vitest run"},dependencies:{"@types/swagger-schema-official":"^2.0.25",citty:"^0.1.6",consola:"^3.4.2",cosmiconfig:"^9.0.0",eta:"^2.2.0","js-yaml":"^4.1.0",lodash:"^4.17.21",nanoid:"^5.1.5",prettier:"~3.5.3","swagger-schema-official":"2.0.0-bab6bed",swagger2openapi:"^7.0.8",typescript:"~5.8.2"},devDependencies:{"@biomejs/biome":"1.9.4","@changesets/changelog-github":"0.5.1","@changesets/cli":"2.28.1","@tsconfig/node18":"18.2.4","@tsconfig/strictest":"2.0.5","@types/js-yaml":"4.0.9","@types/lodash":"4.17.16","@types/node":"22.13.12","@types/swagger2openapi":"7.0.4",axios:"1.8.4","openapi-types":"12.1.3",tsup:"8.4.0",vitest:"3.0.9"},packageManager:"yarn@4.7.0",engines:{node:">=18.0.0"},publishConfig:{access:"public",registry:"https://registry.npmjs.org"}};var Ue="data",qt=`/* eslint-disable */
1
+ import {consola}from'consola';import g from'lodash';import*as d from'typescript';import*as nt from'prettier';import*as lt from'cosmiconfig';import*as yt from'nanoid';import*as Pt from'js-yaml';import*as St from'swagger2openapi';import*as E from'node:path';import E__default from'node:path';import*as Ct from'node:url';import Ct__default from'node:url';import*as Nt from'eta';import*as R from'node:fs';var _t=Object.defineProperty;var Kt=(p,e)=>{for(var t in e)_t(p,t,{get:e[t],enumerable:true});};var se=class{config;constructor(e){this.config=e;}removeUnusedImports=e=>{let t="file.ts",s=new Ue(t,e),a=d.createLanguageService(s).organizeImports({type:"file",fileName:t},{newLineCharacter:d.sys.newLine},void 0)[0];return a?.textChanges.length?a.textChanges.reduceRight((i,{span:o,newText:n})=>`${i.slice(0,o.start)}${n}${i.slice(o.start+o.length)}`,e):e};prettierFormat=async e=>await nt.format(e,this.config.prettierOptions);formatCode=async(e,{removeUnusedImports:t=true,prettierFormat:s=true}={})=>(t&&(e=this.removeUnusedImports(e)),s&&(e=await this.prettierFormat(e)),e)},Ue=class{fileName;content;compilerOptions;constructor(e,t){this.fileName=e,this.content=t;let s=d.findConfigFile(e,d.sys.fileExists);this.compilerOptions=s?d.convertCompilerOptionsFromJson(d.readConfigFile(s,d.sys.readFile).config.compilerOptions,"").options:d.getDefaultCompilerOptions();}getNewLine(){return "newLine"in d.sys?d.sys.newLine:`
2
+ `}getScriptFileNames(){return [this.fileName]}getCompilationSettings(){return this.compilerOptions}getDefaultLibFileName(){return d.getDefaultLibFileName(this.getCompilationSettings())}getCurrentDirectory(){return process.cwd()}getScriptVersion(){return d.version}getScriptSnapshot(){return d.ScriptSnapshot.fromString(this.content)}readFile(e,t){return e===this.fileName?this.content:d.sys.readFile(e,t)}fileExists(e){return d.sys.fileExists(e)}};var O=class{reservedNames=[];getFallbackName;config;constructor(e,t,s){this.config=e,this.getFallbackName=s,this.reserve(t);}reserve(e){let t=g.uniq(g.compact(e));for(let s of t)this.reservedNames.indexOf(s)===-1&&this.reservedNames.push(s);}unreserve(e){this.reservedNames.filter(t=>!e.some(s=>s===t));}isReserved(e){return this.reservedNames.some(t=>t===e)}resolve(e,t,s,r=true){if(typeof t=="function"){let a=null;for(;a===null;){let i=t(e,s);if(i===void 0)return consola.warn("unable to resolve name. current reserved names: ",...this.reservedNames),null;(!r||!this.isReserved(i))&&(a=i);}return r&&this.reserve([a]),a}if(Array.isArray(e)){let a=null,i=g.uniq(g.compact(e));for(let o of i)!a&&(!r||!this.isReserved(o))&&(a=o);return a?(r&&this.reserve([a]),a):(consola.debug("trying to resolve name with using fallback name generator using variants",...e),this.resolve(e,this.getFallbackName,s))}return consola.debug("problem with reserving names. current reserved names: ",...this.reservedNames),null}};var qt=(p=0,e=1)=>Math.random()*(e-p)+p,ot=(p=0,e=1)=>p===e?p:Math.round(qt(p,e));var ae=class extends O{counter=1;fallbackNameCounter=1;countersByVariant=new Map;constructor(e,t){super(e,t,s=>{let r=s[ot(0,s.length-1)];if(r){this.countersByVariant.has(r)||this.countersByVariant.set(r,0);let i=this.countersByVariant.get(r)+1;this.countersByVariant.set(r,i);let o=`${r}${i}`;return consola.debug("generated dirty resolved type name for component - ",o),o}let a=`${this.config.componentTypeNameResolver}${this.fallbackNameCounter++}`;return consola.debug("generated fallback type name for component - ",a),a});}};var ne={};Kt(ne,{DEFAULT_BODY_ARG_NAME:()=>We,FILE_PREFIX:()=>Gt,HTTP_CLIENT:()=>J,PRETTIER_OPTIONS:()=>ie,PROJECT_VERSION:()=>Y,RESERVED_BODY_ARG_NAMES:()=>Ve,RESERVED_HEADER_ARG_NAMES:()=>Be,RESERVED_PATH_ARG_NAMES:()=>Le,RESERVED_QUERY_ARG_NAMES:()=>He,RESERVED_REQ_PARAMS_ARG_NAMES:()=>Wt,SCHEMA_TYPES:()=>l});var mt={name:"swagger-typescript-api",version:"13.0.27",description:"Generate the API client for Fetch or Axios from an OpenAPI Specification",homepage:"https://github.com/acacode/swagger-typescript-api",bugs:"https://github.com/acacode/swagger-typescript-api/issues",repository:"github:acacode/swagger-typescript-api",license:"MIT",author:"Sergey Volkov <js2me@outlook.com>",contributors:["Sora Morimoto <sora@morimoto.io>"],type:"module",exports:{".":{import:{default:"./dist/lib.js"},require:{default:"./dist/lib.cjs"}}},main:"./dist/lib.cjs",module:"./dist/lib.js",bin:{sta:"./dist/cli.js","swagger-typescript-api":"./dist/cli.js"},files:["dist","templates"],scripts:{build:"tsup","cli:help":"node index.js -h","cli:json":"node index.js -r -d -p ./swagger-test-cli.json -n swagger-test-cli.ts","cli:yaml":"node index.js -r -d -p ./swagger-test-cli.yaml -n swagger-test-cli.ts",format:"biome format --write .","format:check":"biome format .",lint:"biome check",prepack:"tsup",test:"vitest run"},dependencies:{"@types/swagger-schema-official":"^2.0.25",citty:"^0.1.6",consola:"^3.4.2",cosmiconfig:"^9.0.0",eta:"^2.2.0","js-yaml":"^4.1.0",lodash:"^4.17.21",nanoid:"^5.1.5",prettier:"~3.5.3","swagger-schema-official":"2.0.0-bab6bed",swagger2openapi:"^7.0.8",typescript:"~5.8.2"},devDependencies:{"@biomejs/biome":"1.9.4","@changesets/changelog-github":"0.5.1","@changesets/cli":"2.28.1","@tsconfig/node18":"18.2.4","@tsconfig/strictest":"2.0.5","@types/js-yaml":"4.0.9","@types/lodash":"4.17.16","@types/node":"22.13.13","@types/swagger2openapi":"7.0.4",axios:"1.8.4","openapi-types":"12.1.3",tsup:"8.4.0",vitest:"3.0.9"},packageManager:"yarn@4.7.0",engines:{node:">=18.0.0"},publishConfig:{access:"public",registry:"https://registry.npmjs.org"}};var We="data",Gt=`/* eslint-disable */
3
3
  /* tslint:disable */
4
4
  // @ts-nocheck
5
5
  /*
@@ -11,20 +11,20 @@ import {consola}from'consola';import f from'lodash';import*as g from'typescript'
11
11
  * ---------------------------------------------------------------
12
12
  */
13
13
 
14
- `,L={FETCH:"fetch",AXIOS:"axios"},re={printWidth:120,tabWidth:2,trailingComma:"all",parser:"typescript"},H=ot.version,Ge=["data","body","reqBody"],We=["headers","headersParams"],Ve=["path","pathParams"],Be=["query","queryParams","queryArg"],Ut=["params","requestParams","reqParams","httpParams"],l={ARRAY:"array",OBJECT:"object",ENUM:"enum",REF:"$ref",PRIMITIVE:"primitive",COMPLEX:"complex",DISCRIMINATOR:"discriminator",COMPLEX_ONE_OF:"oneOf",COMPLEX_ANY_OF:"anyOf",COMPLEX_ALL_OF:"allOf",COMPLEX_NOT:"not",COMPLEX_UNKNOWN:"__unknown"};var K=(p,e)=>{if(!e)return;let t=typeof e=="function"?e(p):e,s=f.map(t,(r,a)=>r===void 0&&a).filter(r=>typeof r=="string");Object.assign(p,f.merge(p,t));for(let r of s)p[r]=void 0;};var Gt={Number:"number",String:"string",Boolean:"boolean",Any:"any",Void:"void",Unknown:"unknown",Null:"null",Undefined:"undefined",Object:"object",File:"File",Date:"Date",Type:"type",Enum:"enum",Interface:"interface",Array:"Array",Record:"Record",Intersection:"&",Union:"|"},Wt={UtilRequiredKeys:"UtilRequiredKeys"},ie=class{version=H;templates="";generateResponses=false;defaultResponseAsSuccess=false;generateRouteTypes=false;generateClient=true;generateUnionEnums=false;addReadonly=false;enumNamesAsValues=false;swaggerSchema=null;originalSchema=null;componentsMap={};convertedFromSwagger2=false;moduleNameIndex=0;moduleNameFirstTag=false;extractRequestParams=false;extractRequestBody=false;extractResponseBody=false;extractResponseError=false;extractResponses=false;extractEnums=false;fileNames={dataContracts:"data-contracts",routeTypes:"route-types",httpClient:"http-client",outOfModuleApi:"Common"};routeNameDuplicatesMap=new Map;prettierOptions={...re};hooks={onPreBuildRoutePath:e=>{},onBuildRoutePath:e=>{},onInsertPathParam:e=>{},onCreateComponent:e=>e,onPreParseSchema:(e,t,s)=>{},onParseSchema:(e,t)=>t,onCreateRoute:e=>e,onInit:(e,t)=>e,onPrepareConfig:e=>e,onCreateRequestParams:e=>{},onCreateRouteName:()=>{},onFormatTypeName:(e,t,s)=>{},onFormatRouteName:(e,t)=>{}};defaultResponseType;singleHttpClient=false;httpClientType=L.FETCH;unwrapResponseData=false;disableThrowOnError=false;sortTypes=false;sortRoutes=false;templatePaths={base:"",default:"",modular:"",original:"",custom:""};templatesToRender={api:"",dataContracts:"",dataContractJsDoc:"",interfaceDataContract:"",typeDataContract:"",enumDataContract:"",objectFieldJsDoc:"",httpClient:"",routeTypes:"",routeName:""};schemaParsers={};toJS=false;silent=false;typePrefix="";typeSuffix="";enumKeyPrefix="";enumKeySuffix="";patch=false;componentTypeNameResolver;apiClassName="Api";debug=false;anotherArrayType=false;internalTemplateOptions={addUtilRequiredKeysType:false};extraTemplates=[];input="";modular=false;output="";url="";cleanOutput=false;spec=null;fileName="Api.ts";authorizationToken;requestOptions=null;jsPrimitiveTypes=[];jsEmptyTypes=[];fixInvalidTypeNamePrefix="Type";fixInvalidEnumKeyPrefix="Value";enumKeyResolverName="Value";typeNameResolverName="ComponentType";specificArgNameResolverName="arg";successResponseStatusRange=[200,299];extractingOptions={requestBodySuffix:["Payload","Body","Input"],requestParamsSuffix:["Params"],responseBodySuffix:["Data","Result","Output"],responseErrorSuffix:["Error","Fail","Fails","ErrorData","HttpError","BadResponse"],enumSuffix:["Enum"],discriminatorMappingSuffix:["Mapping","Mapper","MapType"],discriminatorAbstractPrefix:["Base","Abstract","Discriminator","Internal","Polymorph"]};compilerTsConfig={module:g.ModuleKind.ESNext,noImplicitReturns:true,alwaysStrict:true,target:g.ScriptTarget.ESNext,declaration:true,noImplicitAny:false,sourceMap:false,removeComments:false,disableSizeLimit:true,esModuleInterop:true,emitDecoratorMetadata:true,skipLibCheck:true};customTranslator;Ts={Keyword:structuredClone(Gt),CodeGenKeyword:structuredClone(Wt),ArrayType:e=>this.anotherArrayType?this.Ts.TypeWithGeneric(this.Ts.Keyword.Array,[e]):`${this.Ts.ExpressionGroup(e)}[]`,StringValue:e=>`"${e}"`,BooleanValue:e=>`${e}`,NumberValue:e=>`${e}`,NullValue:()=>"null",UnionType:e=>f.join(f.uniq(e),` ${this.Ts.Keyword.Union} `),ExpressionGroup:e=>e?`(${e})`:"",IntersectionType:e=>f.join(f.uniq(e),` ${this.Ts.Keyword.Intersection} `),RecordType:(e,t)=>this.Ts.TypeWithGeneric(this.Ts.Keyword.Record,[e,t]),TypeField:({readonly:e,key:t,optional:s,value:r})=>f.compact([e&&"readonly ",t,s&&"?",": ",r]).join(""),InterfaceDynamicField:(e,t)=>`[key: ${e}]: ${t}`,EnumUsageKey:(e,t)=>`${e}.${t}`,EnumField:(e,t)=>`${e} = ${t}`,EnumFieldsWrapper:e=>f.map(e,({key:t,value:s})=>` ${this.Ts.EnumField(t,s)}`).join(`,
14
+ `,J={FETCH:"fetch",AXIOS:"axios"},ie={printWidth:120,tabWidth:2,trailingComma:"all",parser:"typescript"},Y=mt.version,Ve=["data","body","reqBody"],Be=["headers","headersParams"],Le=["path","pathParams"],He=["query","queryParams","queryArg"],Wt=["params","requestParams","reqParams","httpParams"],l={ARRAY:"array",OBJECT:"object",ENUM:"enum",REF:"$ref",PRIMITIVE:"primitive",COMPLEX:"complex",DISCRIMINATOR:"discriminator",COMPLEX_ONE_OF:"oneOf",COMPLEX_ANY_OF:"anyOf",COMPLEX_ALL_OF:"allOf",COMPLEX_NOT:"not",COMPLEX_UNKNOWN:"__unknown"};var U=(p,e)=>{if(!e)return;let t=typeof e=="function"?e(p):e,s=g.map(t,(r,a)=>r===void 0&&a).filter(r=>typeof r=="string");Object.assign(p,g.merge(p,t));for(let r of s)p[r]=void 0;};var Vt={Number:"number",String:"string",Boolean:"boolean",Any:"any",Void:"void",Unknown:"unknown",Null:"null",Undefined:"undefined",Object:"object",File:"File",Date:"Date",Type:"type",Enum:"enum",Interface:"interface",Array:"Array",Record:"Record",Intersection:"&",Union:"|"},Bt={UtilRequiredKeys:"UtilRequiredKeys"},oe=class{version=Y;templates="";generateResponses=false;defaultResponseAsSuccess=false;generateRouteTypes=false;generateClient=true;generateUnionEnums=false;addReadonly=false;enumNamesAsValues=false;swaggerSchema=null;originalSchema=null;componentsMap={};convertedFromSwagger2=false;moduleNameIndex=0;moduleNameFirstTag=false;extractRequestParams=false;extractRequestBody=false;extractResponseBody=false;extractResponseError=false;extractResponses=false;extractEnums=false;fileNames={dataContracts:"data-contracts",routeTypes:"route-types",httpClient:"http-client",outOfModuleApi:"Common"};routeNameDuplicatesMap=new Map;prettierOptions={...ie};hooks={onPreBuildRoutePath:e=>{},onBuildRoutePath:e=>{},onInsertPathParam:e=>{},onCreateComponent:e=>e,onPreParseSchema:(e,t,s)=>{},onParseSchema:(e,t)=>t,onCreateRoute:e=>e,onInit:(e,t)=>e,onPrepareConfig:e=>e,onCreateRequestParams:e=>{},onCreateRouteName:()=>{},onFormatTypeName:(e,t,s)=>{},onFormatRouteName:(e,t)=>{}};defaultResponseType;singleHttpClient=false;httpClientType=J.FETCH;unwrapResponseData=false;disableThrowOnError=false;sortTypes=false;sortRoutes=false;templatePaths={base:"",default:"",modular:"",original:"",custom:""};templatesToRender={api:"",dataContracts:"",dataContractJsDoc:"",interfaceDataContract:"",typeDataContract:"",enumDataContract:"",objectFieldJsDoc:"",httpClient:"",routeTypes:"",routeName:""};schemaParsers={};toJS=false;silent=false;typePrefix="";typeSuffix="";enumKeyPrefix="";enumKeySuffix="";patch=false;componentTypeNameResolver;apiClassName="Api";debug=false;anotherArrayType=false;internalTemplateOptions={addUtilRequiredKeysType:false};extraTemplates=[];input="";modular=false;output="";url="";cleanOutput=false;spec=null;fileName="Api.ts";authorizationToken;requestOptions=null;jsPrimitiveTypes=[];jsEmptyTypes=[];fixInvalidTypeNamePrefix="Type";fixInvalidEnumKeyPrefix="Value";enumKeyResolverName="Value";typeNameResolverName="ComponentType";specificArgNameResolverName="arg";successResponseStatusRange=[200,299];extractingOptions={requestBodySuffix:["Payload","Body","Input"],requestParamsSuffix:["Params"],responseBodySuffix:["Data","Result","Output"],responseErrorSuffix:["Error","Fail","Fails","ErrorData","HttpError","BadResponse"],enumSuffix:["Enum"],discriminatorMappingSuffix:["Mapping","Mapper","MapType"],discriminatorAbstractPrefix:["Base","Abstract","Discriminator","Internal","Polymorph"]};compilerTsConfig={module:d.ModuleKind.ESNext,noImplicitReturns:true,alwaysStrict:true,target:d.ScriptTarget.ESNext,declaration:true,noImplicitAny:false,sourceMap:false,removeComments:false,disableSizeLimit:true,esModuleInterop:true,emitDecoratorMetadata:true,skipLibCheck:true};customTranslator;Ts={Keyword:structuredClone(Vt),CodeGenKeyword:structuredClone(Bt),ArrayType:e=>this.anotherArrayType?this.Ts.TypeWithGeneric(this.Ts.Keyword.Array,[e]):`${this.Ts.ExpressionGroup(e)}[]`,StringValue:e=>`"${e}"`,BooleanValue:e=>`${e}`,NumberValue:e=>`${e}`,NullValue:()=>"null",UnionType:e=>g.join(g.uniq(e),` ${this.Ts.Keyword.Union} `),ExpressionGroup:e=>e?`(${e})`:"",IntersectionType:e=>g.join(g.uniq(e),` ${this.Ts.Keyword.Intersection} `),RecordType:(e,t)=>this.Ts.TypeWithGeneric(this.Ts.Keyword.Record,[e,t]),TypeField:({readonly:e,key:t,optional:s,value:r})=>g.compact([e&&"readonly ",t,s&&"?",": ",r]).join(""),InterfaceDynamicField:(e,t)=>`[key: ${e}]: ${t}`,EnumUsageKey:(e,t)=>`${e}.${t}`,EnumField:(e,t)=>`${e} = ${t}`,EnumFieldsWrapper:e=>g.map(e,({key:t,value:s})=>` ${this.Ts.EnumField(t,s)}`).join(`,
15
15
  `),ObjectWrapper:e=>`{
16
16
  ${e}
17
17
  }`,MultilineComment:(e,t)=>[...e.length===1?[`/** ${e[0]} */`]:["/**",...e.map(s=>` * ${s}`)," */"]].map(s=>`${t?t(s):s}
18
- `),TypeWithGeneric:(e,t)=>`${e}${t.length?`<${t.join(",")}>`:""}`,Tuple:e=>`[${e.join(", ")}]`};primitiveTypes={integer:()=>this.Ts.Keyword.Number,number:()=>this.Ts.Keyword.Number,boolean:()=>this.Ts.Keyword.Boolean,object:()=>this.Ts.Keyword.Object,file:()=>this.Ts.Keyword.File,string:{$default:this.Ts.Keyword.String,binary:()=>this.Ts.Keyword.File,file:()=>this.Ts.Keyword.File,"date-time":()=>this.Ts.Keyword.String,time:()=>this.Ts.Keyword.String,date:()=>this.Ts.Keyword.String,duration:()=>this.Ts.Keyword.String,email:()=>this.Ts.Keyword.String,"idn-email":()=>this.Ts.Keyword.String,"idn-hostname":()=>this.Ts.Keyword.String,ipv4:()=>this.Ts.Keyword.String,ipv6:()=>this.Ts.Keyword.String,uuid:()=>this.Ts.Keyword.String,uri:()=>this.Ts.Keyword.String,"uri-reference":()=>this.Ts.Keyword.String,"uri-template":()=>this.Ts.Keyword.String,"json-pointer":()=>this.Ts.Keyword.String,"relative-json-pointer":()=>this.Ts.Keyword.String,regex:()=>this.Ts.Keyword.String}};templateInfos=[{name:"api",fileName:"api"},{name:"dataContracts",fileName:"data-contracts"},{name:"dataContractJsDoc",fileName:"data-contract-jsdoc"},{name:"interfaceDataContract",fileName:"interface-data-contract"},{name:"typeDataContract",fileName:"type-data-contract"},{name:"enumDataContract",fileName:"enum-data-contract"},{name:"objectFieldJsDoc",fileName:"object-field-jsdoc"},{name:"httpClient",fileName:"http-client"},{name:"routeTypes",fileName:"route-types"},{name:"routeName",fileName:"route-name"}];templateExtensions=[".eta",".ejs"];constructor({prettierOptions:e=mt(),codeGenConstructs:t,primitiveTypeConstructs:s,constants:r,templateInfos:a,hooks:i,...o}){K(this.Ts,t),K(this.primitiveTypes,s),this.defaultResponseType=this.Ts.Keyword.Void,this.update({...o,prettierOptions:e===void 0?mt():e,hooks:f.merge(this.hooks,i||{}),constants:{...ae,...r},templateInfos:a||this.templateInfos}),this.jsPrimitiveTypes=[this.Ts.Keyword.Number,this.Ts.Keyword.String,this.Ts.Keyword.Boolean],this.jsEmptyTypes=[this.Ts.Keyword.Null,this.Ts.Keyword.Undefined],this.componentTypeNameResolver=new se(this,[]);}update=e=>{K(this,e);}},mt=()=>{let p=pt.cosmiconfigSync("prettier",{searchStrategy:"global"}).search();return p?{...p.config,parser:"typescript"}:{...re}};var oe=class{_data=[];config;constructor(e){this.config=e;}clear(){this._data=[];}createRef=e=>["#",...e].join("/");parseRef=e=>e.split("/");createComponent(e,t){let s=this.parseRef(e),r=s[s.length-1],a=s[s.length-2],i={$ref:e,typeName:r,rawTypeData:t,componentName:a,typeData:null},o=this.config.hooks.onCreateComponent(i)||i,n=this._data.findIndex(c=>c.$ref===e);return n===-1?this._data.push(o):this._data[n]=o,o}getComponents(){return this._data}filter(...e){return this._data.filter(t=>e.some(s=>t.$ref.startsWith(`#/components/${s}`)))}get(e){return this._data.find(t=>t.$ref===e)||null}};var ce=class{config;templatesWorker;schemaUtils;constructor(e){this.config=e.config,this.schemaUtils=e.schemaUtils,this.templatesWorker=e.templatesWorker;}base={[l.ENUM]:e=>this.config.generateUnionEnums?{...e,$content:e.content,content:this.config.Ts.UnionType(e.content.map(({value:t})=>t))}:{...e,$content:e.content,content:this.config.Ts.EnumFieldsWrapper(e.content)},[l.OBJECT]:e=>e.nullable?this.inline[l.OBJECT](e):{...e,$content:e.content,content:this.formatObjectContent(e.content)},[l.PRIMITIVE]:e=>({...e,$content:e.content})};inline={[l.ENUM]:e=>({...e,content:e.$ref?e.typeName:this.config.Ts.UnionType(f.compact([...e.content.map(({value:t})=>`${t}`),e.nullable&&this.config.Ts.Keyword.Null]))||this.config.Ts.Keyword.Any}),[l.OBJECT]:e=>typeof e.content=="string"?{...e,typeIdentifier:this.config.Ts.Keyword.Type,content:this.schemaUtils.safeAddNullToType(e.content)}:{...e,typeIdentifier:this.config.Ts.Keyword.Type,content:this.schemaUtils.safeAddNullToType(e,e.content.length?this.config.Ts.ObjectWrapper(this.formatObjectContent(e.content)):this.config.Ts.RecordType(this.config.Ts.Keyword.String,this.config.Ts.Keyword.Any))}};formatSchema=(e,t="base")=>{let s=f.get(e,["schemaType"])||f.get(e,["$parsed","schemaType"]);return f.get(this,[t,s])?.(e)||e};formatDescription=(e,t)=>e?e.includes(`
19
- `)?t?f._(e).split(/\n/g).map(r=>r.trim()).compact().join(" ").valueOf():e.replace(/\n$/g,""):e:"";formatObjectContent=e=>{let t=[];for(let s of e){let r=" ",a=`${r}${s.field},
18
+ `),TypeWithGeneric:(e,t)=>`${e}${t.length?`<${t.join(",")}>`:""}`,Tuple:e=>`[${e.join(", ")}]`};primitiveTypes={integer:()=>this.Ts.Keyword.Number,number:()=>this.Ts.Keyword.Number,boolean:()=>this.Ts.Keyword.Boolean,object:()=>this.Ts.Keyword.Object,file:()=>this.Ts.Keyword.File,string:{$default:this.Ts.Keyword.String,binary:()=>this.Ts.Keyword.File,file:()=>this.Ts.Keyword.File,"date-time":()=>this.Ts.Keyword.String,time:()=>this.Ts.Keyword.String,date:()=>this.Ts.Keyword.String,duration:()=>this.Ts.Keyword.String,email:()=>this.Ts.Keyword.String,"idn-email":()=>this.Ts.Keyword.String,"idn-hostname":()=>this.Ts.Keyword.String,ipv4:()=>this.Ts.Keyword.String,ipv6:()=>this.Ts.Keyword.String,uuid:()=>this.Ts.Keyword.String,uri:()=>this.Ts.Keyword.String,"uri-reference":()=>this.Ts.Keyword.String,"uri-template":()=>this.Ts.Keyword.String,"json-pointer":()=>this.Ts.Keyword.String,"relative-json-pointer":()=>this.Ts.Keyword.String,regex:()=>this.Ts.Keyword.String}};templateInfos=[{name:"api",fileName:"api"},{name:"dataContracts",fileName:"data-contracts"},{name:"dataContractJsDoc",fileName:"data-contract-jsdoc"},{name:"interfaceDataContract",fileName:"interface-data-contract"},{name:"typeDataContract",fileName:"type-data-contract"},{name:"enumDataContract",fileName:"enum-data-contract"},{name:"objectFieldJsDoc",fileName:"object-field-jsdoc"},{name:"httpClient",fileName:"http-client"},{name:"routeTypes",fileName:"route-types"},{name:"routeName",fileName:"route-name"}];templateExtensions=[".eta",".ejs"];constructor({prettierOptions:e=ht(),codeGenConstructs:t,primitiveTypeConstructs:s,constants:r,templateInfos:a,hooks:i,...o}){U(this.Ts,t),U(this.primitiveTypes,s),this.defaultResponseType=this.Ts.Keyword.Void,this.update({...o,prettierOptions:e===void 0?ht():e,hooks:g.merge(this.hooks,i||{}),constants:{...ne,...r},templateInfos:a||this.templateInfos}),this.jsPrimitiveTypes=[this.Ts.Keyword.Number,this.Ts.Keyword.String,this.Ts.Keyword.Boolean],this.jsEmptyTypes=[this.Ts.Keyword.Null,this.Ts.Keyword.Undefined],this.componentTypeNameResolver=new ae(this,[]);}update=e=>{U(this,e);}},ht=()=>{let p=lt.cosmiconfigSync("prettier",{searchStrategy:"global"}).search();return p?{...p.config,parser:"typescript"}:{...ie}};var me=class{_data=[];config;constructor(e){this.config=e;}clear(){this._data=[];}createRef=e=>["#",...e].join("/");parseRef=e=>e.split("/");createComponent(e,t){let s=this.parseRef(e),r=s[s.length-1],a=s[s.length-2],i={$ref:e,typeName:r,rawTypeData:t,componentName:a,typeData:null},o=this.config.hooks.onCreateComponent(i)||i,n=this._data.findIndex(c=>c.$ref===e);return n===-1?this._data.push(o):this._data[n]=o,o}getComponents(){return this._data}filter(...e){return this._data.filter(t=>e.some(s=>t.$ref.startsWith(`#/components/${s}`)))}get(e){return this._data.find(t=>t.$ref===e)||null}};var pe=class{config;templatesWorker;schemaUtils;constructor(e){this.config=e.config,this.schemaUtils=e.schemaUtils,this.templatesWorker=e.templatesWorker;}base={[l.ENUM]:e=>this.config.generateUnionEnums?{...e,$content:e.content,content:this.config.Ts.UnionType(e.content.map(({value:t})=>t))}:{...e,$content:e.content,content:this.config.Ts.EnumFieldsWrapper(e.content)},[l.OBJECT]:e=>e.nullable?this.inline[l.OBJECT](e):{...e,$content:e.content,content:this.formatObjectContent(e.content)},[l.PRIMITIVE]:e=>({...e,$content:e.content})};inline={[l.ENUM]:e=>({...e,content:e.$ref?e.typeName:this.config.Ts.UnionType(g.compact([...e.content.map(({value:t})=>`${t}`),e.nullable&&this.config.Ts.Keyword.Null]))||this.config.Ts.Keyword.Any}),[l.OBJECT]:e=>typeof e.content=="string"?{...e,typeIdentifier:this.config.Ts.Keyword.Type,content:this.schemaUtils.safeAddNullToType(e.content)}:{...e,typeIdentifier:this.config.Ts.Keyword.Type,content:this.schemaUtils.safeAddNullToType(e,e.content.length?this.config.Ts.ObjectWrapper(this.formatObjectContent(e.content)):this.config.Ts.RecordType(this.config.Ts.Keyword.String,this.config.Ts.Keyword.Any))}};formatSchema=(e,t="base")=>{let s=g.get(e,["schemaType"])||g.get(e,["$parsed","schemaType"]);return g.get(this,[t,s])?.(e)||e};formatDescription=(e,t)=>e?e.includes(`
19
+ `)?t?g._(e).split(/\n/g).map(r=>r.trim()).compact().join(" ").valueOf():e.replace(/\n$/g,""):e:"";formatObjectContent=e=>{let t=[];for(let s of e){let r=" ",a=`${r}${s.field},
20
20
  `,o=this.templatesWorker.renderTemplate(this.config.templatesToRender.dataContractJsDoc,{data:s}).split(`
21
21
  `).map(n=>`${r}${n}`).join(`
22
- `);o?t.push(`${o}${a}`):t.push(`${a}`);}return t.join("")}};var me=p=>(e,t)=>e[p]>t[p]?1:e[p]<t[p]?-1:0;var y=class{schema;typeName;schemaPath;schemaParser;schemaParserFabric;typeNameFormatter;schemaComponentsMap;schemaUtils;config;schemaFormatters;constructor(e,t,s=null,r=[]){this.schemaParser=e,this.schemaParserFabric=e.schemaParserFabric,this.schema=t,this.typeName=s,this.typeNameFormatter=e.typeNameFormatter,this.schemaPath=r,this.schemaComponentsMap=this.schemaParser.schemaComponentsMap,this.schemaUtils=this.schemaParser.schemaUtils,this.config=this.schemaParser.config,this.schemaFormatters=this.schemaParser.schemaFormatters;}parse(){throw new Error("not implemented")}buildTypeNameFromPath=()=>this.schemaUtils.buildTypeNameFromPath(this.schemaPath)};var pe=class extends y{parse(){let e,{type:t,description:s,items:r}=this.schema||{};if(Array.isArray(r)&&t===l.ARRAY){let a=[];for(let i of r)a.push(this.schemaParserFabric.createSchemaParser({schema:i,schemaPath:this.schemaPath}).getInlineParseContent());e=this.config.Ts.Tuple(a);}else {let a=this.schemaParserFabric.createSchemaParser({schema:r,schemaPath:this.schemaPath}).getInlineParseContent();e=this.config.Ts.ArrayType(a);}return {...typeof this.schema=="object"?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:true,schemaType:l.PRIMITIVE,type:l.PRIMITIVE,typeIdentifier:this.config.Ts.Keyword.Type,name:this.typeName,description:this.schemaFormatters.formatDescription(s),content:this.schemaUtils.safeAddNullToType(this.schema,e)}}};var he=class extends y{parse(){let e=this.schemaUtils.getComplexType(this.schema),t=f.omit(f.clone(this.schema),f.keys(this.schemaParser._complexSchemaParsers)),s=this.schemaParser._complexSchemaParsers[e](this.schema);return {...typeof this.schema=="object"?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:true,schemaType:l.COMPLEX,type:l.PRIMITIVE,typeIdentifier:this.config.Ts.Keyword.Type,name:this.typeName,description:this.schemaFormatters.formatDescription(this.schema.description||f.compact(f.map(this.schema[e],"description"))[0]||""),content:this.config.Ts.IntersectionType(f.compact([this.config.Ts.ExpressionGroup(s),this.schemaUtils.getInternalSchemaType(t)===l.OBJECT&&this.config.Ts.ExpressionGroup(this.schemaParserFabric.createSchemaParser({schema:t,schemaPath:this.schemaPath}).getInlineParseContent())]))||this.config.Ts.Keyword.Any}}};var le=class extends y{parse(){let e=this.config.Ts,{discriminator:t,...s}=this.schema;if(!t.mapping)return this.schemaParserFabric.createSchemaParser({schema:s,typeName:this.typeName,schemaPath:this.schemaPath}).parseSchema();let r=false,a=this.createAbstractSchemaStruct(),i=this.createDiscriminatorSchema({skipMappingType:r,abstractSchemaStruct:a}),o=e.IntersectionType([a?.content,i?.content].filter(Boolean));return {...typeof this.schema=="object"?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:true,schemaType:l.COMPLEX,type:l.PRIMITIVE,typeIdentifier:e.Keyword.Type,name:this.typeName,description:this.schemaFormatters.formatDescription(this.schema.description),content:o}}createDiscriminatorSchema=({skipMappingType:e,abstractSchemaStruct:t})=>{let s=this.config.Ts,r=this.schemaComponentsMap.createRef(["components","schemas",this.typeName]),{discriminator:a}=this.schema,i=f.entries(a.mapping),o=!e&&!!(t?.typeName&&i.length),n=[],c,h=this.createMappingPropertySchemaEnumKeys({abstractSchemaStruct:t,discPropertyName:a.propertyName});if(o){let d=`${t.typeName}_${a.propertyName}`,T=this.schemaUtils.resolveTypeName(d,{suffixes:this.config.extractingOptions.discriminatorMappingSuffix,resolver:this.config.extractingOptions.discriminatorMappingNameResolver}),N=s.IntersectionType([s.ObjectWrapper(s.TypeField({key:s.StringValue(a.propertyName),value:"Key"})),"Type"]),E=this.schemaParserFabric.createParsedComponent({typeName:T,schema:{type:"object",properties:{},genericArgs:[{name:"Key"},{name:"Type"}],internal:true}});E.typeData.content=N,c=this.typeNameFormatter.format(E.typeName);}let m=(d,T)=>{let N=this.schemaParserFabric.createSchemaParser({schema:d,schemaPath:this.schemaPath}).getInlineParseContent(),E=h[T]||s.StringValue(T);return o?s.TypeWithGeneric(c,[E,N]):s.ExpressionGroup(s.IntersectionType([s.ObjectWrapper(s.TypeField({key:a.propertyName,value:E})),N]))};for(let[d,T]of i){let N=typeof T=="string"?{$ref:T}:T;this.mutateMappingDependentSchema({discPropertyName:a.propertyName,abstractSchemaStruct:t,mappingSchema:N,refPath:r,mappingPropertySchemaEnumKeysMap:h}),n.push(m(N,d));}return e?null:{content:s.ExpressionGroup(s.UnionType(n))}};createMappingPropertySchemaEnumKeys=({abstractSchemaStruct:e,discPropertyName:t})=>{let s=this.config.Ts,r={},a=f.get(e?.component?.rawTypeData,["properties",t]);return this.schemaUtils.isRefSchema(a)&&(a=this.schemaUtils.getSchemaRefType(a)),a?.rawTypeData?.$parsed?.type===l.ENUM&&(r=f.reduce(a.rawTypeData.$parsed.enum,(i,o,n)=>{let c=a.rawTypeData.$parsed.content[n].key;return i[o]=s.EnumUsageKey(a.rawTypeData.$parsed.typeName,c),i},{})),r};mutateMappingDependentSchema=({discPropertyName:e,abstractSchemaStruct:t,mappingSchema:s,refPath:r,mappingPropertySchemaEnumKeysMap:a})=>{let i=f.keys(this.schemaParser._complexSchemaParsers);if(s.$ref&&t?.component?.$ref){let o=this.schemaUtils.getSchemaRefType(s)?.rawTypeData;if(o)for(let n of i)Array.isArray(o[n])&&(o[n]=o[n].map(c=>{if(c.$ref===r)return {...c,$ref:t.component.$ref};if(this.schemaUtils.getInternalSchemaType(c)===l.OBJECT)for(let h in c.properties){let m=c.properties[h];h===e&&this.schemaUtils.getInternalSchemaType(m)===l.ENUM&&m.enum.length===1&&a[m.enum[0]]&&(c.properties[h]=this.schemaParserFabric.createSchema({content:a[m.enum[0]]}));}return c}));}};createAbstractSchemaStruct=()=>{let{discriminator:e,...t}=this.schema,s=f.keys(this.schemaParser._complexSchemaParsers),r=f.omit(structuredClone(t),s),a=this.schemaParserFabric.getInlineParseContent(structuredClone(r))===this.config.Ts.Keyword.Any;if(!f.keys(r).length||a)return null;let o=this.schemaUtils.resolveTypeName(this.typeName,{prefixes:this.config.extractingOptions.discriminatorAbstractPrefix,resolver:this.config.extractingOptions.discriminatorAbstractResolver}),n=this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components","schemas",o]),{...r,internal:true}),c=this.schemaParserFabric.createSchemaParser({schema:n,schemaPath:this.schemaPath}).getInlineParseContent();return {typeName:o,component:n,content:c}};createComplexSchemaStruct=()=>{let e=this.config.Ts,t=this.schemaUtils.getComplexType(this.schema);return t===l.COMPLEX_UNKNOWN?null:{content:e.ExpressionGroup(this.schemaParser._complexSchemaParsers[t](this.schema))}}};var fe=class extends b{counter=1;constructor(e,t){super(e,t,s=>{let r=s[0]&&`${s[0]}${this.counter++}`||`${this.config.enumKeyResolverName}${this.counter++}`;return consola.debug("generated fallback type name for enum key - ",r),r});}};var ue=class extends y{enumKeyResolver;constructor(...e){super(...e),this.enumKeyResolver=new fe(this.config,[]);}extractEnum=e=>{let t=this.schemaUtils.resolveTypeName(e,{suffixes:this.config.extractingOptions.enumSuffix,resolver:this.config.extractingOptions.enumNameResolver}),s=this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components","schemas",t]),{...this.schema});return this.schemaParserFabric.parseSchema(s)};parse(){let e=this.buildTypeNameFromPath();if(this.config.extractEnums&&!this.typeName&&e!=null)return this.extractEnum(e);let t=this.schemaUtils.getSchemaRefType(this.schema),s=t?.$ref||null;if(Array.isArray(this.schema.enum)&&(this.schema.enum=this.schema.enum.filter(n=>n!=null)),Array.isArray(this.schema.enum)&&Array.isArray(this.schema.enum[0]))return this.schemaParserFabric.parseSchema({oneOf:this.schema.enum.map(n=>({type:"array",items:n.map(c=>({type:"string",enum:[c]}))}))},this.typeName,this.schemaPath);let r=this.schemaUtils.getSchemaType(this.schema),a=this.schemaUtils.getEnumNames(this.schema),i=null,o=n=>n===null?this.config.Ts.NullValue(n):r.includes(this.schemaUtils.getSchemaType({type:"number"}))?this.config.Ts.NumberValue(n):r.includes(this.schemaUtils.getSchemaType({type:"boolean"}))?this.config.Ts.BooleanValue(n):this.config.Ts.StringValue(n);return Array.isArray(a)&&f.size(a)?i=a.map((n,c)=>{let h=f.get(this.schema.enum,c),m=this.formatEnumKey({key:n,value:h});return this.config.enumNamesAsValues||h===void 0?{key:m,type:this.config.Ts.Keyword.String,value:this.config.Ts.StringValue(n)}:{key:m,type:r,value:o(h)}}):i=this.schema.enum.map(n=>({key:this.formatEnumKey({value:n}),type:r,value:o(n)})),{...typeof this.schema=="object"?this.schema:{},$ref:s,typeName:this.typeName||s&&t.typeName||null,$parsedSchema:true,schemaType:l.ENUM,type:l.ENUM,keyType:r,typeIdentifier:this.config.generateUnionEnums?this.config.Ts.Keyword.Type:this.config.Ts.Keyword.Enum,name:this.typeName,description:this.schemaFormatters.formatDescription(this.schema.description),content:i}}formatEnumKey=({key:e,value:t})=>{let s;return e&&(s=this.typeNameFormatter.format(e,{type:"enum-key"})),s||(s=this.typeNameFormatter.format(`${t}`,{type:"enum-key"})),this.enumKeyResolver.resolve([s])}};var ge=class extends y{parse(){let e=this.getObjectSchemaContent(this.schema);return {...typeof this.schema=="object"?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:true,schemaType:l.OBJECT,type:l.OBJECT,typeIdentifier:this.config.Ts.Keyword.Interface,name:this.typeName,description:this.schemaFormatters.formatDescription(this.schema.description),allFieldsAreOptional:!e.some(t=>t.isRequired),content:e}}getObjectSchemaContent=e=>{let{properties:t,additionalProperties:s}=e||{},r=f.map(t,(a,i)=>{let o=this.schemaUtils.isPropertyRequired(i,a,e),n=f.get(this.schemaUtils.getSchemaRefType(a),"rawTypeData",{}),c=!!(n.nullable||a.nullable),h=this.typeNameFormatter.isValidName(i)?i:this.config.Ts.StringValue(i),m=this.schemaParserFabric.createSchemaParser({schema:a,schemaPath:[...this.schemaPath,i]}).getInlineParseContent(),u=a.readOnly;return {...a,$$raw:a,title:a.title,description:a.description||f.compact(f.map(a[this.schemaUtils.getComplexType(a)],"description"))[0]||n.description||f.compact(f.map(n[this.schemaUtils.getComplexType(n)],"description"))[0]||"",isRequired:o,isNullable:c,name:h,value:m,field:this.config.Ts.TypeField({readonly:u&&this.config.addReadonly,optional:!o,key:h,value:m})}});return s&&r.push({$$raw:{additionalProperties:s},description:"",isRequired:false,field:this.config.Ts.InterfaceDynamicField(this.config.Ts.Keyword.String,this.config.Ts.Keyword.Any)}),r}};var ye=class extends y{parse(){let e=null,{additionalProperties:t,type:s,description:r,items:a}=this.schema||{};if(s===this.config.Ts.Keyword.Object&&t){let i=typeof t=="object"?this.schemaParserFabric.createSchemaParser({schema:t,schemaPath:this.schemaPath}).getInlineParseContent():this.config.Ts.Keyword.Any;e=this.config.Ts.RecordType(this.config.Ts.Keyword.String,i);}return Array.isArray(s)&&s.length&&(e=this.schemaParser._complexSchemaParsers.oneOf({...typeof this.schema=="object"?this.schema:{},oneOf:s.map(i=>({type:i}))})),Array.isArray(a)&&s===l.ARRAY&&(e=this.config.Ts.Tuple(a.map(i=>this.schemaParserFabric.createSchemaParser({schema:i,schemaPath:this.schemaPath}).getInlineParseContent()))),{...typeof this.schema=="object"?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:true,schemaType:l.PRIMITIVE,type:l.PRIMITIVE,typeIdentifier:this.config.Ts.Keyword.Type,name:this.typeName,description:this.schemaFormatters.formatDescription(r),content:s===this.config.Ts.Keyword.Null?s:e||this.schemaUtils.getSchemaType(this.schema)}}};var de=class extends y{parse(){let e=[this.config.Ts.Keyword.Any],t=this.schema.allOf.map(a=>this.schemaParserFabric.getInlineParseContent(this.schemaUtils.makeAddRequiredToChildSchema(this.schema,a),null,this.schemaPath)),s=this.schemaUtils.filterSchemaContents(t,a=>!e.includes(a)),r=this.config.Ts.IntersectionType(s);return this.schemaUtils.safeAddNullToType(this.schema,r)}};var Te=class extends y{parse(){let e=[this.config.Ts.Keyword.Any],t=this.schema.anyOf.map(a=>this.schemaParserFabric.getInlineParseContent(this.schemaUtils.makeAddRequiredToChildSchema(this.schema,a),null,this.schemaPath)),s=this.schemaUtils.filterSchemaContents(t,a=>!e.includes(a)),r=this.config.Ts.UnionType(s);return this.schemaUtils.safeAddNullToType(this.schema,r)}};var Pe=class extends y{parse(){return this.config.Ts.Keyword.Any}};var Se=class extends y{parse(){let e=[this.config.Ts.Keyword.Any],t=this.schema.oneOf.map(a=>this.schemaParserFabric.getInlineParseContent(this.schemaUtils.makeAddRequiredToChildSchema(this.schema,a),null,this.schemaPath)),s=this.schemaUtils.filterSchemaContents(t,a=>!e.includes(a)),r=this.config.Ts.UnionType(s);return this.schemaUtils.safeAddNullToType(this.schema,r)}};var Ce=class{schemaParserFabric;config;schemaComponentsMap;typeNameFormatter;schemaFormatters;schemaUtils;templatesWorker;schemaWalker;typeName;schema;schemaPath=[];constructor(e,{typeName:t,schema:s,schemaPath:r}={}){this.schemaParserFabric=e,this.config=e.config,this.templatesWorker=e.templatesWorker,this.schemaComponentsMap=e.schemaComponentsMap,this.typeNameFormatter=e.typeNameFormatter,this.schemaWalker=e.schemaWalker,this.schemaFormatters=e.schemaFormatters,this.schemaUtils=e.schemaUtils,this.typeName=t||null,this.schema=s,this.schemaPath=[...r||[]];}_complexSchemaParsers={[l.COMPLEX_ONE_OF]:e=>{let t=this.config.schemaParsers.complexOneOf||Se;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_ALL_OF]:e=>{let t=this.config.schemaParsers.complexAllOf||de;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_ANY_OF]:e=>{let t=this.config.schemaParsers.complexAnyOf||Te;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_NOT]:e=>{let t=this.config.schemaParsers.complexNot||Pe;return new t(this,e,null,this.schemaPath).parse()}};_baseSchemaParsers={[l.ENUM]:(e,t)=>{let s=this.config.schemaParsers.enum||ue;return new s(this,e,t,this.schemaPath).parse()},[l.OBJECT]:(e,t)=>{let s=this.config.schemaParsers.object||ge;return new s(this,e,t,this.schemaPath).parse()},[l.COMPLEX]:(e,t)=>{let s=this.config.schemaParsers.complex||he;return new s(this,e,t,this.schemaPath).parse()},[l.PRIMITIVE]:(e,t)=>{let s=this.config.schemaParsers.primitive||ye;return new s(this,e,t,this.schemaPath).parse()},[l.DISCRIMINATOR]:(e,t)=>{let s=this.config.schemaParsers.discriminator||le;return new s(this,e,t,this.schemaPath).parse()},[l.ARRAY]:(e,t)=>{let s=this.config.schemaParsers.array||pe;return new s(this,e,t,this.schemaPath).parse()}};parseSchema=()=>{if(!this.schema)return this._baseSchemaParsers[l.PRIMITIVE](null,this.typeName);let e=null,t=null;if(typeof this.schema=="string")return this.schema;if(!this.schema.$parsed){if(!this.typeName&&this.schemaUtils.isRefSchema(this.schema)&&(this.typeName=this.schemaUtils.getSchemaType(this.schema)),this.schema.items&&!Array.isArray(this.schema.items)&&!this.schema.type&&(this.schema.type=l.ARRAY),Array.isArray(this.schema.enum)&&this.schema.enum.length===1&&this.schema.enum[0]==null&&(consola.debug("invalid enum schema",this.schema),this.schema={type:this.config.Ts.Keyword.Null}),"content"in this.schema&&typeof this.schema.content=="object"){let s=this.extractSchemaFromResponseStruct(this.schema),r=this.schemaParserFabric.createSchemaParser({schema:s,typeName:this.typeName,schemaPath:this.schemaPath});return this.schema.$parsed=r.parseSchema(),this.schema.$parsed}e=this.schemaUtils.getInternalSchemaType(this.schema),this.schemaPath.push(this.typeName),f.merge(this.schema,this.config.hooks.onPreParseSchema(this.schema,this.typeName,e)),t=this._baseSchemaParsers[e](this.schema,this.typeName),this.schema.$parsed=this.config.hooks.onParseSchema(this.schema,t)||t,this.config.sortTypes&&Array.isArray(this.schema.$parsed?.content)&&(this.schema.$parsed.content=this.schema.$parsed.content.sort(me("name")));}return this.schemaPath.pop(),this.schema.$parsed};getInlineParseContent=()=>{let e=this.parseSchema();return this.schemaFormatters.formatSchema(e,"inline").content};getParseContent=()=>{let e=this.parseSchema();return this.schemaFormatters.formatSchema(e,"base").content};extractSchemaFromResponseStruct=e=>{let{content:t,...s}=e,r=f.first(f.values(t)),a=f.get(r,"schema");if(a)return {...s,...f.omit(r,"schema"),...a}}};function X(p){return f.camelCase(f.lowerCase(p))}function A(p){return f.upperFirst(f.camelCase(p))}var Ne=class{config;schemaComponentsMap;typeNameFormatter;schemaWalker;constructor({config:e,schemaComponentsMap:t,typeNameFormatter:s,schemaWalker:r}){this.config=e,this.schemaComponentsMap=t,this.typeNameFormatter=s,this.schemaWalker=r;}getRequiredProperties=e=>f.uniq(e&&Array.isArray(e.required)&&e.required||[]);isRefSchema=e=>!!e?.$ref;getEnumNames=e=>e["x-enumNames"]||e.xEnumNames||e["x-enumnames"]||e["x-enum-varnames"];getSchemaRefType=e=>this.isRefSchema(e)?this.schemaComponentsMap.get(e.$ref):null;isPropertyRequired=(e,t,s)=>{if(t["x-omitempty"]===false)return true;let r=typeof t.required=="boolean"?!!t.required:Array.isArray(s.required)?s.required.includes(e):!!s.required;return this.config.convertedFromSwagger2?typeof t.nullable===this.config.Ts.Keyword.Undefined?r:!t.nullable:r};isNullMissingInType=(e,t)=>{let{nullable:s,type:r}=e||{};return (s||!!f.get(e,"x-nullable")||r===this.config.Ts.Keyword.Null)&&typeof t=="string"&&!t.includes(` ${this.config.Ts.Keyword.Null}`)&&!t.includes(`${this.config.Ts.Keyword.Null} `)};safeAddNullToType=(e,t)=>this.isNullMissingInType(e,t)?this.config.Ts.UnionType([t,this.config.Ts.Keyword.Null]):t;getSchemaPrimitiveType=e=>{let t=e||{};if(t.type)return X(t.type);if(t.enum){let s=typeof t.enum[0];return s===this.config.Ts.Keyword.Undefined?void 0:X(s)}return f.keys(t.properties).length?l.OBJECT:t.items?l.ARRAY:null};checkAndAddRequiredKeys=(e,t)=>"$$requiredKeys"in e&&e.$$requiredKeys.length?(this.config.update({internalTemplateOptions:{addUtilRequiredKeysType:true}}),this.config.Ts.TypeWithGeneric(this.config.Ts.CodeGenKeyword.UtilRequiredKeys,[t,this.config.Ts.UnionType(e.$$requiredKeys.map(this.config.Ts.StringValue))])):t;makeAddRequiredToChildSchema=(e,t)=>{if(!t)return t;let s=f.uniq([...this.getRequiredProperties(e),...this.getRequiredProperties(t)]),r=this.getSchemaRefType(t);if(r){let i=f.keys(r.rawTypeData?.properties||{}).filter(o=>s.includes(o));return i.length?{...t,$$requiredKeys:i}:t}if(t.properties){let i=f.keys(t.properties).filter(o=>s.includes(o));return i.length?{required:f.uniq([...this.getRequiredProperties(t),...i]),...t}:t}return t};filterSchemaContents=(e,t)=>f.uniq(e.filter(s=>t(s)));resolveTypeName=(e,{suffixes:t,resolver:s,prefixes:r,shouldReserve:a=true})=>s?this.config.componentTypeNameResolver.resolve([],i=>s(A(e),i)):this.config.componentTypeNameResolver.resolve([...(r||[]).map(i=>A(`${i} ${e}`)),...(t||[]).map(i=>A(`${e} ${i}`))],a);getComplexType=e=>e.oneOf?l.COMPLEX_ONE_OF:e.allOf?l.COMPLEX_ALL_OF:e.anyOf?l.COMPLEX_ANY_OF:e.not?l.COMPLEX_NOT:l.COMPLEX_UNKNOWN;getInternalSchemaType=e=>!f.isEmpty(e.enum)||!f.isEmpty(this.getEnumNames(e))?l.ENUM:e.discriminator?l.DISCRIMINATOR:e.allOf||e.oneOf||e.anyOf||e.not?l.COMPLEX:f.isEmpty(e.properties)?e.type===l.ARRAY?l.ARRAY:l.PRIMITIVE:l.OBJECT;getSchemaType=e=>{if(!e)return this.config.Ts.Keyword.Any;let t=this.getSchemaRefType(e);if(t)return this.checkAndAddRequiredKeys(e,this.safeAddNullToType(e,this.typeNameFormatter.format(t.typeName)));let s;if(this.isConstantSchema(e))s=this.formatJsValue(e.const);else {let r=this.getSchemaPrimitiveType(e);if(r==null)return this.config.Ts.Keyword.Any;let a=f.get(this.config.primitiveTypes,[r,e.format])||f.get(this.config.primitiveTypes,[r,"$default"])||this.config.primitiveTypes[r];typeof a=="function"?s=a(e,this):s=a||r;}return s?this.checkAndAddRequiredKeys(e,this.safeAddNullToType(e,s)):this.config.Ts.Keyword.Any};buildTypeNameFromPath=e=>(e=f.uniq(f.compact(e)),!e||!e[0]?null:A(f.camelCase(f.uniq([e[0],e[e.length-1]]).join("_"))));isConstantSchema(e){return "const"in e}formatJsValue=e=>{switch(typeof e){case "string":return this.config.Ts.StringValue(e);case "boolean":return this.config.Ts.BooleanValue(e);case "number":return this.config.Ts.NumberValue(e);default:return e===null?this.config.Ts.NullValue(e):this.config.Ts.Keyword.Any}}};var Re=class{config;schemaComponentsMap;typeNameFormatter;schemaFormatters;templatesWorker;schemaUtils;schemaWalker;constructor(e,t,s,r,a){this.config=e,this.schemaComponentsMap=s,this.typeNameFormatter=r,this.templatesWorker=t,this.schemaWalker=a,this.schemaUtils=new Ne(this),this.schemaFormatters=new ce(this);}createSchemaParser=({schema:e,typeName:t,schemaPath:s})=>new Ce(this,{schema:e,typeName:t,schemaPath:s});createSchema=({content:e,linkedSchema:t={},linkedComponent:s,schemaPath:r,...a})=>{let i=this.createSchemaParser({schema:s||t,schemaPath:r}),o=i.parseSchema();return o.content=e,Object.assign(o,a),s&&(s.typeData=o),i.schema};createParsedComponent=({typeName:e,schema:t,schemaPath:s})=>{let r=structuredClone(t),a=this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components","schemas",e]),r),i=this.parseSchema(r,null,s);return i.name=e,a.typeData=i,a};parseSchema=(e,t=null,s=[])=>this.createSchemaParser({schema:e,typeName:t,schemaPath:s}).parseSchema();getInlineParseContent=(e,t,s)=>this.createSchemaParser({schema:e,typeName:t,schemaPath:s}).getInlineParseContent();getParseContent=(e,t,s)=>this.createSchemaParser({schema:e,typeName:t,schemaPath:s}).getParseContent()};var Lt="abcdefghijklmnopqrstuvwxyz0123456789",gt=ut.customAlphabet(Lt,12);var we=class extends b{counter=1;constructor(e,t){super(e,t,s=>{let r=s[0]&&`${s[0]}${this.counter++}`||`${this.config.specificArgNameResolverName}${this.counter++}`;return consola.debug("generated fallback type name for specific arg - ",r),r});}};var x={JSON:"JSON",URL_ENCODED:"URL_ENCODED",FORM_DATA:"FORM_DATA",IMAGE:"IMAGE",OTHER:"OTHER",TEXT:"TEXT"},Fe=class{config;schemaParserFabric;schemaUtils;typeNameFormatter;schemaComponentsMap;templatesWorker;FORM_DATA_TYPES=[];routes=[];hasSecurityRoutes=false;hasQueryRoutes=false;hasFormDataRoutes=false;constructor(e,t,s,r,a){this.config=e,this.schemaParserFabric=t,this.schemaUtils=this.schemaParserFabric.schemaUtils,this.typeNameFormatter=a,this.schemaComponentsMap=s,this.templatesWorker=r,this.FORM_DATA_TYPES=f.uniq([this.schemaUtils.getSchemaType({type:"string",format:"file"}),this.schemaUtils.getSchemaType({type:"string",format:"binary"})]);}createRequestsMap=e=>{let t=f.get(e,"parameters");return f.reduce(e,(s,r,a)=>(a.startsWith("x-")||["parameters","$ref"].includes(a)||(s[a]={...r,parameters:f.compact(f.concat(t,r.parameters))}),s),{})};parseRouteName=e=>{let t=this.config.hooks.onPreBuildRoutePath(e)||e,s=(t||"").match(/({[\w[\\\]^`][-_.\w]*})|(:[\w[\\\]^`][-_.\w]*:?)/g),r=f.reduce(s,(c,h)=>{let m=h.replace(/\{|\}|:/g,"");return m&&(m.includes("-")&&consola.warn("wrong path param name",m),c.push({$match:h,name:f.camelCase(m),required:true,type:"string",description:"",schema:{type:"string"},in:"path"})),c},[]),a=r.reduce((c,h,m,u)=>{let d=this.config.hooks.onInsertPathParam(h.name,m,u,c)||h.name;return c.replace(h.$match,`\${${d}}`)},t||""),i=a.match(/(\{\?.*\})/g),o=[];if(i?.length){for(let h of i)a=a.replace(h,"");let c=f.uniq(i.join(",").replace(/(\{\?)|(\})|\s/g,"").split(","));for(let h of c)h.includes("-")&&consola.warn("wrong query param name",h),o.push({$match:h,name:f.camelCase(h),required:true,type:"string",description:"",schema:{type:"string"},in:"query"});}let n={originalRoute:e||"",route:a,pathParams:r,queryParams:o};return this.config.hooks.onBuildRoutePath(n)||n};getRouteParams=(e,t,s)=>{let{parameters:r}=e,a={path:[],header:[],body:[],query:[],formData:[],cookie:[]};f.each(r,i=>{let o=this.schemaParserFabric.schemaUtils.getSchemaRefType(i),n=null;if(o?.rawTypeData.in&&o.rawTypeData)a[o.rawTypeData.in]||(a[o.rawTypeData.in]=[]),n={...o.rawTypeData,...o.rawTypeData.schema||{}};else {if(!i.in)return;a[i.in]||(a[i.in]=[]),n={...i,...i.schema||{}};}if(n.in==="path"){if(!n.name)return;n.name=f.camelCase(n.name);}n&&a[n.in].push(n);});for(let i of t)a.path.some(n=>n.name===i.name)||a.path.push(i);for(let i of s)a.query.some(n=>n.name===i.name)||a.query.push(i);return a};getContentTypes=(e,t)=>f.uniq(f.compact([...t||[],...f.flatten(f.map(e,s=>s&&f.keys(s.content)))]));getContentKind=e=>e.some(t=>t.startsWith("application/json"))||e.some(t=>t.endsWith("+json"))?x.JSON:e.includes("application/x-www-form-urlencoded")?x.URL_ENCODED:e.includes("multipart/form-data")?x.FORM_DATA:e.some(t=>t.includes("image/"))?x.IMAGE:e.some(t=>t.startsWith("text/"))?x.TEXT:x.OTHER;isSuccessStatus=e=>this.config.defaultResponseAsSuccess&&e==="default"||+e>=this.config.successResponseStatusRange[0]&&+e<=this.config.successResponseStatusRange[1]||e==="2xx";getSchemaFromRequestType=e=>{let t=f.get(e,"content");if(!t)return null;for(let s in t)if(t[s]?.schema)return {...t[s].schema,dataType:s};return null};getTypeFromRequestInfo=({requestInfo:e,parsedSchemas:t,operationId:s,defaultType:r,typeName:a})=>{let i=this.getSchemaFromRequestType(e),o=this.schemaParserFabric.schemaUtils.getSchemaRefType(e);if(i){let n=this.schemaParserFabric.getInlineParseContent(i,a,[s]),c=t.find(u=>this.typeNameFormatter.format(u.name)===n),h=t.find(u=>f.isEqual(u.content,n)),m=c||h;return m?this.typeNameFormatter.format(m.name):n}if(o){let n=o.typeName.replace(s,"");if(t.find(c=>c.name===n))return this.typeNameFormatter.format(n);switch(o.componentName){case "schemas":return this.typeNameFormatter.format(o.typeName);case "responses":case "requestBodies":return this.schemaParserFabric.getInlineParseContent(this.getSchemaFromRequestType(o.rawTypeData),o.typeName||null,[s]);default:return this.schemaParserFabric.getInlineParseContent(o.rawTypeData,o.typeName||null,[s])}}return r||this.config.Ts.Keyword.Any};getRequestInfoTypes=({requestInfos:e,parsedSchemas:t,operationId:s,defaultType:r})=>f.reduce(e,(a,i,o)=>{let n=this.getContentTypes([i]);return [...a,{...i||{},contentTypes:n,contentKind:this.getContentKind(n),type:this.schemaParserFabric.schemaUtils.safeAddNullToType(i,this.getTypeFromRequestInfo({requestInfo:i,parsedSchemas:t,operationId:s,defaultType:r})),description:this.schemaParserFabric.schemaFormatters.formatDescription(i.description||"",true),status:Number.isNaN(+o)?o:+o,isSuccess:this.isSuccessStatus(o)}]},[]);getResponseBodyInfo=(e,t)=>{let{produces:s,operationId:r,responses:a}=e,i=this.getContentTypes(a,[...s||[],e["x-accepts"]]),o=this.getRequestInfoTypes({requestInfos:a,parsedSchemas:t,operationId:r,defaultType:this.config.defaultResponseType}),n=o.find(m=>m.isSuccess),c=o.filter(m=>!m.isSuccess&&m.type!==this.config.Ts.Keyword.Any),h=m=>{if(!m)return "headers: {},";let u=Object.fromEntries(Object.entries(m).map(([T,N])=>[T,this.schemaUtils.getSchemaType(N)]));return `headers: { ${Object.entries(u).map(([T,N])=>`"${T}": ${N}`).join(",")} },`};return {contentTypes:i,responses:o,success:{schema:n,type:n?.type||this.config.Ts.Keyword.Any},error:{schemas:c,type:this.config.Ts.UnionType(c.map(m=>m.type))||this.config.Ts.Keyword.Any},full:{types:this.config.Ts.UnionType(o.map(m=>`{
23
- data: ${m.type}, status: ${m.status}, statusCode: ${m.status}, statusText: "${m.description}", ${h(m.headers)} config: {} }`))||this.config.Ts.Keyword.Any}}};convertRouteParamsIntoObject=e=>e.reduce((t,s)=>!s||!s.name?t:{...t,properties:{...t.properties,[s.name]:{...s,...s.schema||{}}}},{properties:{},type:"object"});getRequestBodyInfo=(e,t,s,r)=>{let{requestBody:a,consumes:i,requestBodyName:o,operationId:n}=e,c=null,h=null,m=this.getContentTypes([a],[...i||[],e["x-contentType"]]),u=this.getContentKind(m),d=null;return this.config.extractRequestBody&&(d=this.schemaUtils.resolveTypeName(r.usage,{suffixes:this.config.extractingOptions.requestBodySuffix,resolver:this.config.extractingOptions.requestBodyNameResolver})),t.formData.length?(u=x.FORM_DATA,c=this.convertRouteParamsIntoObject(t.formData),h=this.schemaParserFabric.getInlineParseContent(c,d,[n])):u===x.FORM_DATA?(c=this.getSchemaFromRequestType(a),h=this.schemaParserFabric.getInlineParseContent(c,d,[n])):a&&(c=this.getSchemaFromRequestType(a),h=this.schemaParserFabric.schemaUtils.safeAddNullToType(a,this.getTypeFromRequestInfo({requestInfo:a,parsedSchemas:s,operationId:n,typeName:d})),this.FORM_DATA_TYPES.some(T=>h.includes(`: ${T}`))&&(u=x.FORM_DATA)),c&&!c.$ref&&this.config.extractRequestBody&&(c=this.schemaParserFabric.createParsedComponent({schema:c,typeName:d,schemaPath:[n]}),c?.typeData&&(c.typeData.isExtractedRequestBody=true),h=this.schemaParserFabric.getInlineParseContent({$ref:c.$ref})),{paramName:o||a?.name||Ue,contentTypes:m,contentKind:u,schema:c,type:h,required:a&&(typeof a.required>"u"||!!a.required)}};createRequestParamsSchema=({queryParams:e,queryObjectSchema:t,pathArgsSchemas:s,extractRequestParams:r,routeName:a})=>{if(!e||!e.length)return null;let i=s.reduce((h,m)=>(m.name&&(h[m.name]={...m,in:"path"}),h),{}),o=f.reduce(f.get(t,"properties",{}),(h,m,u)=>(u&&typeof m=="object"&&(h[u]={...m,in:"query"}),h),{}),n={...t,properties:{...o,...i}},c=this.config.hooks.onCreateRequestParams(n);if(c)return c;if(r){let h=this.schemaUtils.resolveTypeName(a.usage,{suffixes:this.config.extractingOptions.requestParamsSuffix,resolver:this.config.extractingOptions.requestParamsNameResolver}),m=this.schemaParserFabric.createParsedComponent({typeName:h,schema:n});return m.typeData&&(m.typeData.isExtractedRequestParams=true),m}return n};extractResponseBodyIfItNeeded=(e,t,s)=>{if(t.responses.length&&t.success&&t.success.schema){let r=this.schemaUtils.resolveTypeName(s.usage,{suffixes:this.config.extractingOptions.responseBodySuffix,resolver:this.config.extractingOptions.responseBodyNameResolver}),a=t.responses.indexOf(t.success.schema),i=t.success;if(i.schema&&!i.schema.$ref){let o=i.schema.contentKind,n=this.getSchemaFromRequestType(i.schema);i.schema=this.schemaParserFabric.createParsedComponent({schema:n,typeName:r,schemaPath:[e.operationId]}),i.schema.contentKind=o,i.schema.typeData&&(i.schema.typeData.isExtractedResponseBody=true),i.type=this.schemaParserFabric.getInlineParseContent({$ref:i.schema.$ref}),a>-1&&f.assign(t.responses[a],{...i.schema,type:i.type});}}};extractResponseErrorIfItNeeded=(e,t,s)=>{if(t.responses.length&&t.error.schemas&&t.error.schemas.length){let r=this.schemaUtils.resolveTypeName(s.usage,{suffixes:this.config.extractingOptions.responseErrorSuffix,resolver:this.config.extractingOptions.responseErrorNameResolver}),a=t.error.schemas.map(this.getSchemaFromRequestType).filter(Boolean);if(!a.length)return;let i=this.schemaParserFabric.parseSchema({oneOf:a,title:a.map(n=>n.title).filter(Boolean).join(" "),description:a.map(n=>n.description).filter(Boolean).join(`
24
- `)},null,[e.operationId]),o=this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components","schemas",r]),{...i});t.error.schemas=[o],o.typeData&&(o.typeData.isExtractedResponseError=true),t.error.type=this.typeNameFormatter.format(o.typeName);}};getRouteName=e=>{let{moduleName:t}=e,{routeNameDuplicatesMap:s,templatesToRender:r}=this.config,a=r.routeName,i=this.templatesWorker.renderTemplate(a,{routeInfo:e}),o=this.config.hooks.onFormatRouteName(e,i)||i,n=`${t}|${o}`;s.has(n)?(s.set(n,s.get(n)+1),consola.warn(`Module "${t}" already has method "${o}()".`,`This method has been renamed to "${o+s.get(n)}()" to solve conflict names.`)):s.set(n,1);let c=s.get(n),h={usage:o+(c>1?c:""),original:o,duplicate:c>1};return this.config.hooks.onCreateRouteName(h,e)||h};parseRouteInfo=(e,t,s,r,a)=>{let{security:i}=r,{moduleNameIndex:o,moduleNameFirstTag:n,extractRequestParams:c}=this.config,{operationId:h,requestBody:m,security:u,parameters:d,summary:T,description:N,tags:E,responses:xt,requestBodyName:rs,produces:Et,consumes:bt,...At}=t,{route:Xe,pathParams:Ot,queryParams:It}=this.parseRouteName(e),Mt=gt(),Qe=E&&E.length>0?E[0]:null,ze=n&&Qe?f.camelCase(Qe):f.camelCase(f.compact(Xe.split("/"))[o]),Ze=!!i?.length;u&&(Ze=u.length>0);let w=this.getRouteParams(t,Ot,It),Q=w.path.map(v=>({name:v.name,optional:!v.required,type:this.config.Ts.Keyword.Any,description:v.description})),$t=Q.map(v=>v.name),O=this.getResponseBodyInfo(t,a),et={...At,pathArgs:Q,operationId:h,method:s,route:e,moduleName:ze,responsesTypes:O.responses,description:N,tags:E,summary:T,responses:xt,produces:Et,requestBody:m,consumes:bt,security:u},z=this.convertRouteParamsIntoObject(w.query),De=this.convertRouteParamsIntoObject(w.path),_e=this.convertRouteParamsIntoObject(w.header),I=this.getRouteName(et),M=this.getRequestBodyInfo(t,w,a,I),vt=this.createRequestParamsSchema({queryParams:w.query,pathArgsSchemas:w.path,queryObjectSchema:z,extractRequestParams:c,routeName:I});this.config.extractResponseBody&&this.extractResponseBodyIfItNeeded(t,O,I),this.config.extractResponseError&&this.extractResponseErrorIfItNeeded(t,O,I);let Z=this.schemaUtils.resolveTypeName(I.usage,{suffixes:this.config.extractingOptions.requestParamsSuffix,resolver:this.config.extractingOptions.requestParamsNameResolver,shouldReserve:false}),tt=w.query.length?this.schemaParserFabric.getInlineParseContent(z,null,[Z]):null,st=w.path.length?this.schemaParserFabric.getInlineParseContent(De,null,[Z]):null,rt=w.header.length?this.schemaParserFabric.getInlineParseContent(_e,null,[Z]):null,V=new we(this.config,$t),B={query:tt?{name:V.resolve(Be),optional:this.schemaParserFabric.parseSchema(z,null,[I.usage]).allFieldsAreOptional,type:tt}:void 0,body:M.type?{name:V.resolve([M.paramName,...Ge]),optional:!M.required,type:M.type}:void 0,pathParams:st?{name:V.resolve(Ve),optional:this.schemaParserFabric.parseSchema(De,null,[I.usage]).allFieldsAreOptional,type:st}:void 0,headers:rt?{name:V.resolve(We),optional:this.schemaParserFabric.parseSchema(_e,null,[I.usage]).allFieldsAreOptional,type:rt}:void 0};return Q.forEach((v,kt)=>{v.type=this.schemaParserFabric.getInlineParseContent(w.path[kt].schema,null,[Z]);}),{id:Mt,namespace:ze.replace(/^(\d)/,"v$1"),routeName:I,routeParams:w,requestBodyInfo:M,responseBodyInfo:O,specificArgs:B,queryObjectSchema:z,pathObjectSchema:De,headersObjectSchema:_e,responseBodySchema:O.success.schema,requestBodySchema:M.schema,specificArgNameResolver:V,request:{contentTypes:M.contentTypes,parameters:Q,path:Xe,formData:M.contentKind===x.FORM_DATA,isQueryBody:M.contentKind===x.URL_ENCODED,security:Ze,method:s,requestParams:vt,payload:B.body,query:B.query,pathParams:B.pathParams,headers:B.headers},response:{contentTypes:O.contentTypes,type:O.success.type,errorType:O.error.type,fullTypes:O.full.types},raw:et}};attachSchema=({usageSchema:e,parsedSchemas:t})=>{this.config.routeNameDuplicatesMap.clear();let s=f.entries(e.paths);for(let[r,a]of s){let i=this.createRequestsMap(a);for(let[o,n]of Object.entries(i)){let c=this.parseRouteInfo(r,n,o,e,t),h=this.config.hooks.onCreateRoute(c);if(h!==false){let m=h||c;!this.hasSecurityRoutes&&m.security&&(this.hasSecurityRoutes=m.security),!this.hasQueryRoutes&&m.hasQuery&&(this.hasQueryRoutes=m.hasQuery),!this.hasFormDataRoutes&&m.hasFormDataParams&&(this.hasFormDataRoutes=m.hasFormDataParams),this.routes.push(m);}}}};getGroupedRoutes=()=>{let e=this.routes.reduce((s,r)=>(r.namespace?(s[r.namespace]||(s[r.namespace]=[]),s[r.namespace].push(r)):s.$outOfModule.push(r),s),{$outOfModule:[]}),t=f.reduce(e,(s,r,a)=>(a==="$outOfModule"?s.outOfModule=r:(s.combined||(s.combined=[]),s.combined.push({moduleName:a,routes:r.map(i=>{let{original:o,usage:n}=i.routeName;return r.length>1&&n!==o&&!r.some(({routeName:c,id:h})=>h!==i.id&&o===c.original)?{...i,routeName:{...i.routeName,usage:o}}:i})})),s),{});return this.config.sortRoutes&&(t.outOfModule&&(t.outOfModule=this.sortRoutes(t.outOfModule)),t.combined&&f.each(t.combined,s=>{s.routes=this.sortRoutes(s.routes);})),t};sortRoutes=e=>f.slice(e).sort((t,s)=>t.routeName.usage.localeCompare(s.routeName.usage))};var xe=class{config;swaggerSchemaResolver;schemas=new Map;caches=new Map;constructor(e,t){this.config=e,this.swaggerSchemaResolver=t;}addSchema=(e,t)=>{this.schemas.set(e,structuredClone(t));};_isLocalRef=e=>e.startsWith("#");_isRemoteRef=e=>e.startsWith("http://")||e.startsWith("https://");_getRefDataFromSchema=(e,t)=>{let s=t.replace("#","").split("/"),r=f.get(e,s);return r&&this.caches.set(t,r),r}};var Ee=class{config;constructor(e){this.config=e;}async download({url:e,authToken:t,...s}){let r={};t&&(r.headers={Authorization:t}),f.merge(r,s,this.config.requestOptions);try{return await(await fetch(e,r)).text()}catch(a){let i=`error while fetching data from URL "${e}"`;return consola.error(i,a),i}}};var be=class{config;fileSystem;request;constructor(e,t){this.config=e,this.fileSystem=t,this.request=new Ee(e);}async create(){let{spec:e,patch:t,input:s,url:r,authorizationToken:a}=this.config;if(e)return await this.convertSwaggerObject(e,{patch:t});let i=await this.fetchSwaggerSchemaFile(s,r,a),o=this.processSwaggerSchemaFile(i);return await this.convertSwaggerObject(o,{patch:t})}convertSwaggerObject(e,t){return new Promise(s=>{let r=structuredClone(e);r.info=f.merge({title:"No title",version:""},r.info),Object.hasOwn(r,"openapi")?s({usageSchema:r,originalSchema:structuredClone(r)}):(r.paths=f.merge({},r.paths),Tt.convertObj(r,{...t,warnOnly:true,refSiblings:"preserve",rbname:"requestBodyName"},(a,i)=>{let o=f.get(a,"options.openapi",f.get(i,"openapi"));if(!o&&a)throw a;this.config.update({convertedFromSwagger2:true}),s({usageSchema:o,originalSchema:r});}));})}getSwaggerSchemaByPath=e=>(consola.info(`try to get swagger by path "${e}"`),this.fileSystem.getFileContent(e));async fetchSwaggerSchemaFile(e,t,s){return this.fileSystem.pathIsExist(e)?this.getSwaggerSchemaByPath(e):(consola.info(`try to get swagger by URL "${t}"`),await this.request.download({url:t,authToken:s}))}processSwaggerSchemaFile(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return dt.load(e)}}fixSwaggerSchema({usageSchema:e,originalSchema:t}){let s=f.get(e,"paths"),r=f.get(t,"paths");f.each(s,(a,i)=>{let o=f.get(r,i);f.each(a,(n,c)=>{let h=f.get(o,c),m=f.get(n,"parameters",[]),u=f.get(h,"parameters",[]);typeof n=="object"&&(n.consumes=f.uniq(f.compact([...n.consumes||[],...h.consumes||[]])),n.produces=f.uniq(f.compact([...n.produces||[],...h.produces||[]]))),f.each(u,d=>{m.find(N=>d.in===N.in&&d.name===N.name)||m.push(d);});});});}};var Ae=class{config;fileSystem;getRenderTemplateData;constructor(e,t,s){this.config=e,this.fileSystem=t,this.getRenderTemplateData=s,this.config.debug&&(consola.level=Number.MAX_SAFE_INTEGER),this.config.silent&&(consola.level=0);}getTemplatePaths=e=>{let t=F.dirname(Pt.fileURLToPath(import.meta.url)),s=F.resolve(t,"../templates/base"),r=F.resolve(t,"../templates/default"),a=F.resolve(t,"../templates/modular"),i=e.modular?a:r,o=e.templates&&F.resolve(process.cwd(),e.templates);return {base:s,default:r,modular:a,original:i,custom:o}};cropExtension=e=>this.config.templateExtensions.reduce((t,s)=>t.endsWith(s)?t.replace(s,""):t,e);getTemplateFullPath=(e,t)=>{let s=F.resolve(e,"./",this.cropExtension(t));return this.config.templateExtensions.map(a=>`${s}${a}`).find(a=>!!this.fileSystem.pathIsExist(a))};requireFnFromTemplate=async e=>e.startsWith("./")||e.startsWith("../")?await import(F.resolve(this.config.templatePaths.custom||this.config.templatePaths.original,e)):await import(e);getTemplate=(e,t,s)=>{let{templatePaths:r}=this.config;if(s)return this.fileSystem.getFileContent(s);if(!t)return "";let a=r.custom&&this.getTemplateFullPath(r.custom,t),i=a&&this.fileSystem.getFileContent(a);if(i)return consola.info(`"${e.toLowerCase()}" template found in "${r.custom}"`),i;let o=this.getTemplateFullPath(r.base,t);o?i=this.fileSystem.getFileContent(o):r.custom?consola.warn("Code generator will use the default template:",`"${e.toLowerCase()}"`,"template not found in",`"${r.custom}"`):consola.info(`Code generator will use the default template for "${e.toLowerCase()}"`);let n=this.getTemplateFullPath(r.original,t);return n&&(i=this.fileSystem.getFileContent(n)),i};getTemplates=({templatePaths:e})=>(e.custom&&consola.info(`try to read templates from directory "${e.custom}"`),f.reduce(this.config.templateInfos,(t,{name:s,fileName:r})=>({...t,[s]:this.getTemplate(s,r)}),{}));findTemplateWithExt=e=>{let t=this.cropExtension(e);return this.config.templateExtensions.map(r=>`${t}${r}`).find(r=>this.fileSystem.pathIsExist(r))};getTemplateContent=e=>{let t=f.keys(this.config.templatePaths).find(a=>e.startsWith(`@${a}`));if(t){let a=F.resolve(e.replace(`@${t}`,f.get(this.config.templatePaths,t))),i=this.findTemplateWithExt(a);if(i)return this.fileSystem.getFileContent(i)}let s=this.config.templatePaths.custom&&this.findTemplateWithExt(F.resolve(this.config.templatePaths.custom,e));if(s)return this.fileSystem.getFileContent(s);let r=this.findTemplateWithExt(F.resolve(this.config.templatePaths.original,e));return r?this.fileSystem.getFileContent(r):""};renderTemplate=(e,t,s={})=>e?St.render(e,{...this.getRenderTemplateData(),...t},{async:false,...s,includeFile:(r,a,i={})=>this.renderTemplate(this.getTemplateContent(r),a,i)}):""};var Oe=class{config;codeFormatter;constructor(e,t){this.config=e,this.codeFormatter=t;}translate(e){throw new Error("not implemented")}};var Ie=class extends Oe{compileTSCode=e=>{let t=`${e.fileName}${e.fileExtension}`,s={},r=g.createCompilerHost(this.config.compilerTsConfig,true),a=[t],i=r.getSourceFile.bind(r);return r.getSourceFile=(o,n,c,h)=>o!==t?i(o,n,c,h):g.createSourceFile(o,e.fileContent,n,true,g.ScriptKind.TS),r.writeFile=(o,n)=>{s[o]=n;},g.createProgram(a,this.config.compilerTsConfig,r).emit(),s};translate=async e=>{let t=this.compileTSCode(e),s=`${e.fileName}${g.Extension.Js}`,r=`${e.fileName}${g.Extension.Dts}`,a=t[s],i=e.fileContent.split(`
22
+ `);o?t.push(`${o}${a}`):t.push(`${a}`);}return t.join("")}};var he=p=>(e,t)=>e[p]>t[p]?1:e[p]<t[p]?-1:0;var T=class{schema;typeName;schemaPath;schemaParser;schemaParserFabric;typeNameFormatter;schemaComponentsMap;schemaUtils;config;schemaFormatters;constructor(e,t,s=null,r=[]){this.schemaParser=e,this.schemaParserFabric=e.schemaParserFabric,this.schema=t,this.typeName=s,this.typeNameFormatter=e.typeNameFormatter,this.schemaPath=r,this.schemaComponentsMap=this.schemaParser.schemaComponentsMap,this.schemaUtils=this.schemaParser.schemaUtils,this.config=this.schemaParser.config,this.schemaFormatters=this.schemaParser.schemaFormatters;}parse(){throw new Error("not implemented")}buildTypeNameFromPath=()=>this.schemaUtils.buildTypeNameFromPath(this.schemaPath)};var le=class extends T{parse(){let e,{type:t,description:s,items:r}=this.schema||{};if(Array.isArray(r)&&t===l.ARRAY){let a=[];for(let i of r)a.push(this.schemaParserFabric.createSchemaParser({schema:i,schemaPath:this.schemaPath}).getInlineParseContent());e=this.config.Ts.Tuple(a);}else {let a=this.schemaParserFabric.createSchemaParser({schema:r,schemaPath:this.schemaPath}).getInlineParseContent();e=this.config.Ts.ArrayType(a);}return {...typeof this.schema=="object"?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:true,schemaType:l.PRIMITIVE,type:l.PRIMITIVE,typeIdentifier:this.config.Ts.Keyword.Type,name:this.typeName,description:this.schemaFormatters.formatDescription(s),content:this.schemaUtils.safeAddNullToType(this.schema,e)}}};var fe=class extends T{parse(){let e=this.schemaUtils.getComplexType(this.schema),t=g.omit(g.clone(this.schema),g.keys(this.schemaParser._complexSchemaParsers)),s=this.schemaParser._complexSchemaParsers[e](this.schema);return {...typeof this.schema=="object"?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:true,schemaType:l.COMPLEX,type:l.PRIMITIVE,typeIdentifier:this.config.Ts.Keyword.Type,name:this.typeName,description:this.schemaFormatters.formatDescription(this.schema.description||g.compact(g.map(this.schema[e],"description"))[0]||""),content:this.config.Ts.IntersectionType(g.compact([this.config.Ts.ExpressionGroup(s),this.schemaUtils.getInternalSchemaType(t)===l.OBJECT&&this.config.Ts.ExpressionGroup(this.schemaParserFabric.createSchemaParser({schema:t,schemaPath:this.schemaPath}).getInlineParseContent())]))||this.config.Ts.Keyword.Any}}};var ue=class extends T{parse(){let e=this.config.Ts,{discriminator:t,...s}=this.schema;if(!t.mapping)return this.schemaParserFabric.createSchemaParser({schema:s,typeName:this.typeName,schemaPath:this.schemaPath}).parseSchema();let r=false,a=this.createAbstractSchemaStruct(),i=this.createDiscriminatorSchema({skipMappingType:r,abstractSchemaStruct:a}),o=e.IntersectionType([a?.content,i?.content].filter(Boolean));return {...typeof this.schema=="object"?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:true,schemaType:l.COMPLEX,type:l.PRIMITIVE,typeIdentifier:e.Keyword.Type,name:this.typeName,description:this.schemaFormatters.formatDescription(this.schema.description),content:o}}createDiscriminatorSchema=({skipMappingType:e,abstractSchemaStruct:t})=>{let s=this.config.Ts,r=this.schemaComponentsMap.createRef(["components","schemas",this.typeName]),{discriminator:a}=this.schema,i=g.entries(a.mapping),o=!e&&!!(t?.typeName&&i.length),n=[],c,h=this.createMappingPropertySchemaEnumKeys({abstractSchemaStruct:t,discPropertyName:a.propertyName});if(o){let P=`${t.typeName}_${a.propertyName}`,S=this.schemaUtils.resolveTypeName(P,{suffixes:this.config.extractingOptions.discriminatorMappingSuffix,resolver:this.config.extractingOptions.discriminatorMappingNameResolver}),w=s.IntersectionType([s.ObjectWrapper(s.TypeField({key:s.StringValue(a.propertyName),value:"Key"})),"Type"]),A=this.schemaParserFabric.createParsedComponent({typeName:S,schema:{type:"object",properties:{},genericArgs:[{name:"Key"},{name:"Type"}],internal:true}});A.typeData.content=w,c=this.typeNameFormatter.format(A.typeName);}let m=(P,S)=>{let w=this.schemaParserFabric.createSchemaParser({schema:P,schemaPath:this.schemaPath}).getInlineParseContent(),A=h[S]||s.StringValue(S);return o?s.TypeWithGeneric(c,[A,w]):s.ExpressionGroup(s.IntersectionType([s.ObjectWrapper(s.TypeField({key:a.propertyName,value:A})),w]))};for(let[P,S]of i){let w=typeof S=="string"?{$ref:S}:S;this.mutateMappingDependentSchema({discPropertyName:a.propertyName,abstractSchemaStruct:t,mappingSchema:w,refPath:r,mappingPropertySchemaEnumKeysMap:h}),n.push(m(w,P));}return e?null:{content:s.ExpressionGroup(s.UnionType(n))}};createMappingPropertySchemaEnumKeys=({abstractSchemaStruct:e,discPropertyName:t})=>{let s=this.config.Ts,r={},a=g.get(e?.component?.rawTypeData,["properties",t]);return this.schemaUtils.isRefSchema(a)&&(a=this.schemaUtils.getSchemaRefType(a)),a?.rawTypeData?.$parsed?.type===l.ENUM&&(r=g.reduce(a.rawTypeData.$parsed.enum,(i,o,n)=>{let c=a.rawTypeData.$parsed.content[n].key;return i[o]=s.EnumUsageKey(a.rawTypeData.$parsed.typeName,c),i},{})),r};mutateMappingDependentSchema=({discPropertyName:e,abstractSchemaStruct:t,mappingSchema:s,refPath:r,mappingPropertySchemaEnumKeysMap:a})=>{let i=g.keys(this.schemaParser._complexSchemaParsers);if(s.$ref&&t?.component?.$ref){let o=this.schemaUtils.getSchemaRefType(s)?.rawTypeData;if(o)for(let n of i)Array.isArray(o[n])&&(o[n]=o[n].map(c=>{if(c.$ref===r)return {...c,$ref:t.component.$ref};if(this.schemaUtils.getInternalSchemaType(c)===l.OBJECT)for(let h in c.properties){let m=c.properties[h];h===e&&this.schemaUtils.getInternalSchemaType(m)===l.ENUM&&m.enum.length===1&&a[m.enum[0]]&&(c.properties[h]=this.schemaParserFabric.createSchema({content:a[m.enum[0]]}));}return c}));}};createAbstractSchemaStruct=()=>{let{discriminator:e,...t}=this.schema,s=g.keys(this.schemaParser._complexSchemaParsers),r=g.omit(structuredClone(t),s),a=this.schemaParserFabric.getInlineParseContent(structuredClone(r))===this.config.Ts.Keyword.Any;if(!g.keys(r).length||a)return null;let o=this.schemaUtils.resolveTypeName(this.typeName,{prefixes:this.config.extractingOptions.discriminatorAbstractPrefix,resolver:this.config.extractingOptions.discriminatorAbstractResolver}),n=this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components","schemas",o]),{...r,internal:true}),c=this.schemaParserFabric.createSchemaParser({schema:n,schemaPath:this.schemaPath}).getInlineParseContent();return {typeName:o,component:n,content:c}};createComplexSchemaStruct=()=>{let e=this.config.Ts,t=this.schemaUtils.getComplexType(this.schema);return t===l.COMPLEX_UNKNOWN?null:{content:e.ExpressionGroup(this.schemaParser._complexSchemaParsers[t](this.schema))}}};var ge=class extends O{counter=1;constructor(e,t){super(e,t,s=>{let r=s[0]&&`${s[0]}${this.counter++}`||`${this.config.enumKeyResolverName}${this.counter++}`;return consola.debug("generated fallback type name for enum key - ",r),r});}};var ye=class extends T{enumKeyResolver;constructor(...e){super(...e),this.enumKeyResolver=new ge(this.config,[]);}extractEnum=e=>{let t=this.schemaUtils.resolveTypeName(e,{suffixes:this.config.extractingOptions.enumSuffix,resolver:this.config.extractingOptions.enumNameResolver}),s=this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components","schemas",t]),{...this.schema});return this.schemaParserFabric.parseSchema(s)};parse(){let e=this.buildTypeNameFromPath();if(this.config.extractEnums&&!this.typeName&&e!=null)return this.extractEnum(e);let t=this.schemaUtils.getSchemaRefType(this.schema),s=t?.$ref||null;if(Array.isArray(this.schema.enum)&&(this.schema.enum=this.schema.enum.filter(n=>n!=null)),Array.isArray(this.schema.enum)&&Array.isArray(this.schema.enum[0]))return this.schemaParserFabric.parseSchema({oneOf:this.schema.enum.map(n=>({type:"array",items:n.map(c=>({type:"string",enum:[c]}))}))},this.typeName,this.schemaPath);let r=this.schemaUtils.getSchemaType(this.schema),a=this.schemaUtils.getEnumNames(this.schema),i=null,o=n=>n===null?this.config.Ts.NullValue(n):r.includes(this.schemaUtils.getSchemaType({type:"number"}))?this.config.Ts.NumberValue(n):r.includes(this.schemaUtils.getSchemaType({type:"boolean"}))?this.config.Ts.BooleanValue(n):this.config.Ts.StringValue(n);return Array.isArray(a)&&g.size(a)?i=a.map((n,c)=>{let h=g.get(this.schema.enum,c),m=this.formatEnumKey({key:n,value:h});return this.config.enumNamesAsValues||h===void 0?{key:m,type:this.config.Ts.Keyword.String,value:this.config.Ts.StringValue(n)}:{key:m,type:r,value:o(h)}}):i=this.schema.enum.map(n=>({key:this.formatEnumKey({value:n}),type:r,value:o(n)})),{...typeof this.schema=="object"?this.schema:{},$ref:s,typeName:this.typeName||s&&t.typeName||null,$parsedSchema:true,schemaType:l.ENUM,type:l.ENUM,keyType:r,typeIdentifier:this.config.generateUnionEnums?this.config.Ts.Keyword.Type:this.config.Ts.Keyword.Enum,name:this.typeName,description:this.schemaFormatters.formatDescription(this.schema.description),content:i}}formatEnumKey=({key:e,value:t})=>{let s;return e&&(s=this.typeNameFormatter.format(e,{type:"enum-key"})),s||(s=this.typeNameFormatter.format(`${t}`,{type:"enum-key"})),this.enumKeyResolver.resolve([s])}};var de=class extends T{parse(){let e=this.getObjectSchemaContent(this.schema);return {...typeof this.schema=="object"?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:true,schemaType:l.OBJECT,type:l.OBJECT,typeIdentifier:this.config.Ts.Keyword.Interface,name:this.typeName,description:this.schemaFormatters.formatDescription(this.schema.description),allFieldsAreOptional:!e.some(t=>t.isRequired),content:e}}getObjectSchemaContent=e=>{let{properties:t,additionalProperties:s}=e||{},r=g.map(t,(a,i)=>{let o=this.schemaUtils.isPropertyRequired(i,a,e),n=g.get(this.schemaUtils.getSchemaRefType(a),"rawTypeData",{}),c=!!(n.nullable||a.nullable),h=this.typeNameFormatter.isValidName(i)?i:this.config.Ts.StringValue(i),m=this.schemaParserFabric.createSchemaParser({schema:a,schemaPath:[...this.schemaPath,i]}).getInlineParseContent(),y=a.readOnly;return {...a,$$raw:a,title:a.title,description:a.description||g.compact(g.map(a[this.schemaUtils.getComplexType(a)],"description"))[0]||n.description||g.compact(g.map(n[this.schemaUtils.getComplexType(n)],"description"))[0]||"",isRequired:o,isNullable:c,name:h,value:m,field:this.config.Ts.TypeField({readonly:y&&this.config.addReadonly,optional:!o,key:h,value:m})}});return s&&r.push({$$raw:{additionalProperties:s},description:"",isRequired:false,field:this.config.Ts.InterfaceDynamicField(this.config.Ts.Keyword.String,this.config.Ts.Keyword.Any)}),r}};var Te=class extends T{parse(){let e=null,{additionalProperties:t,type:s,description:r,items:a}=this.schema||{};if(s===this.config.Ts.Keyword.Object&&t){let i=typeof t=="object"?this.schemaParserFabric.createSchemaParser({schema:t,schemaPath:this.schemaPath}).getInlineParseContent():this.config.Ts.Keyword.Any;e=this.config.Ts.RecordType(this.config.Ts.Keyword.String,i);}return Array.isArray(s)&&s.length&&(e=this.schemaParser._complexSchemaParsers.oneOf({...typeof this.schema=="object"?this.schema:{},oneOf:s.map(i=>({type:i}))})),Array.isArray(a)&&s===l.ARRAY&&(e=this.config.Ts.Tuple(a.map(i=>this.schemaParserFabric.createSchemaParser({schema:i,schemaPath:this.schemaPath}).getInlineParseContent()))),{...typeof this.schema=="object"?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:true,schemaType:l.PRIMITIVE,type:l.PRIMITIVE,typeIdentifier:this.config.Ts.Keyword.Type,name:this.typeName,description:this.schemaFormatters.formatDescription(r),content:s===this.config.Ts.Keyword.Null?s:e||this.schemaUtils.getSchemaType(this.schema)}}};var Pe=class extends T{parse(){let e=[this.config.Ts.Keyword.Any],t=this.schema.allOf.map(a=>this.schemaParserFabric.getInlineParseContent(this.schemaUtils.makeAddRequiredToChildSchema(this.schema,a),null,this.schemaPath)),s=this.schemaUtils.filterSchemaContents(t,a=>!e.includes(a)),r=this.config.Ts.IntersectionType(s);return this.schemaUtils.safeAddNullToType(this.schema,r)}};var Se=class extends T{parse(){let e=[this.config.Ts.Keyword.Any],t=this.schema.anyOf.map(a=>this.schemaParserFabric.getInlineParseContent(this.schemaUtils.makeAddRequiredToChildSchema(this.schema,a),null,this.schemaPath)),s=this.schemaUtils.filterSchemaContents(t,a=>!e.includes(a)),r=this.config.Ts.UnionType(s);return this.schemaUtils.safeAddNullToType(this.schema,r)}};var Ce=class extends T{parse(){return this.config.Ts.Keyword.Any}};var Ne=class extends T{parse(){let e=[this.config.Ts.Keyword.Any],t=this.schema.oneOf.map(a=>this.schemaParserFabric.getInlineParseContent(this.schemaUtils.makeAddRequiredToChildSchema(this.schema,a),null,this.schemaPath)),s=this.schemaUtils.filterSchemaContents(t,a=>!e.includes(a)),r=this.config.Ts.UnionType(s);return this.schemaUtils.safeAddNullToType(this.schema,r)}};var Re=class{schemaParserFabric;config;schemaComponentsMap;typeNameFormatter;schemaFormatters;schemaUtils;templatesWorker;schemaWalker;typeName;schema;schemaPath=[];constructor(e,{typeName:t,schema:s,schemaPath:r}={}){this.schemaParserFabric=e,this.config=e.config,this.templatesWorker=e.templatesWorker,this.schemaComponentsMap=e.schemaComponentsMap,this.typeNameFormatter=e.typeNameFormatter,this.schemaWalker=e.schemaWalker,this.schemaFormatters=e.schemaFormatters,this.schemaUtils=e.schemaUtils,this.typeName=t||null,this.schema=s,this.schemaPath=[...r||[]];}_complexSchemaParsers={[l.COMPLEX_ONE_OF]:e=>{let t=this.config.schemaParsers.complexOneOf||Ne;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_ALL_OF]:e=>{let t=this.config.schemaParsers.complexAllOf||Pe;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_ANY_OF]:e=>{let t=this.config.schemaParsers.complexAnyOf||Se;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_NOT]:e=>{let t=this.config.schemaParsers.complexNot||Ce;return new t(this,e,null,this.schemaPath).parse()}};_baseSchemaParsers={[l.ENUM]:(e,t)=>{let s=this.config.schemaParsers.enum||ye;return new s(this,e,t,this.schemaPath).parse()},[l.OBJECT]:(e,t)=>{let s=this.config.schemaParsers.object||de;return new s(this,e,t,this.schemaPath).parse()},[l.COMPLEX]:(e,t)=>{let s=this.config.schemaParsers.complex||fe;return new s(this,e,t,this.schemaPath).parse()},[l.PRIMITIVE]:(e,t)=>{let s=this.config.schemaParsers.primitive||Te;return new s(this,e,t,this.schemaPath).parse()},[l.DISCRIMINATOR]:(e,t)=>{let s=this.config.schemaParsers.discriminator||ue;return new s(this,e,t,this.schemaPath).parse()},[l.ARRAY]:(e,t)=>{let s=this.config.schemaParsers.array||le;return new s(this,e,t,this.schemaPath).parse()}};parseSchema=()=>{if(!this.schema)return this._baseSchemaParsers[l.PRIMITIVE](null,this.typeName);let e=null,t=null;if(typeof this.schema=="string")return this.schema;if(!this.schema.$parsed){if(!this.typeName&&this.schemaUtils.isRefSchema(this.schema)&&(this.typeName=this.schemaUtils.getSchemaType(this.schema)),this.schema.items&&!Array.isArray(this.schema.items)&&!this.schema.type&&(this.schema.type=l.ARRAY),Array.isArray(this.schema.enum)&&this.schema.enum.length===1&&this.schema.enum[0]==null&&(consola.debug("invalid enum schema",this.schema),this.schema={type:this.config.Ts.Keyword.Null}),"content"in this.schema&&typeof this.schema.content=="object"){let s=this.extractSchemaFromResponseStruct(this.schema),r=this.schemaParserFabric.createSchemaParser({schema:s,typeName:this.typeName,schemaPath:this.schemaPath});return this.schema.$parsed=r.parseSchema(),this.schema.$parsed}e=this.schemaUtils.getInternalSchemaType(this.schema),this.schemaPath.push(this.typeName),g.merge(this.schema,this.config.hooks.onPreParseSchema(this.schema,this.typeName,e)),t=this._baseSchemaParsers[e](this.schema,this.typeName),this.schema.$parsed=this.config.hooks.onParseSchema(this.schema,t)||t,this.config.sortTypes&&Array.isArray(this.schema.$parsed?.content)&&(this.schema.$parsed.content=this.schema.$parsed.content.sort(he("name")));}return this.schemaPath.pop(),this.schema.$parsed};getInlineParseContent=()=>{let e=this.parseSchema();return this.schemaFormatters.formatSchema(e,"inline").content};getParseContent=()=>{let e=this.parseSchema();return this.schemaFormatters.formatSchema(e,"base").content};extractSchemaFromResponseStruct=e=>{let{content:t,...s}=e,r=g.first(g.values(t)),a=g.get(r,"schema");if(a)return {...s,...g.omit(r,"schema"),...a}}};function z(p){return g.camelCase(g.lowerCase(p))}function I(p){return g.upperFirst(g.camelCase(p))}var we=class{config;schemaComponentsMap;typeNameFormatter;schemaWalker;constructor({config:e,schemaComponentsMap:t,typeNameFormatter:s,schemaWalker:r}){this.config=e,this.schemaComponentsMap=t,this.typeNameFormatter=s,this.schemaWalker=r;}getRequiredProperties=e=>g.uniq(e&&Array.isArray(e.required)&&e.required||[]);isRefSchema=e=>!!e?.$ref;getEnumNames=e=>e["x-enumNames"]||e.xEnumNames||e["x-enumnames"]||e["x-enum-varnames"];getSchemaRefType=e=>this.isRefSchema(e)?this.schemaComponentsMap.get(e.$ref):null;isPropertyRequired=(e,t,s)=>{if(t["x-omitempty"]===false)return true;let r=typeof t.required=="boolean"?!!t.required:Array.isArray(s.required)?s.required.includes(e):!!s.required;return this.config.convertedFromSwagger2?typeof t.nullable===this.config.Ts.Keyword.Undefined?r:!t.nullable:r};isNullMissingInType=(e,t)=>{let{nullable:s,type:r}=e||{};return (s||!!g.get(e,"x-nullable")||r===this.config.Ts.Keyword.Null)&&typeof t=="string"&&!t.includes(` ${this.config.Ts.Keyword.Null}`)&&!t.includes(`${this.config.Ts.Keyword.Null} `)};safeAddNullToType=(e,t)=>this.isNullMissingInType(e,t)?this.config.Ts.UnionType([t,this.config.Ts.Keyword.Null]):t;getSchemaPrimitiveType=e=>{let t=e||{};if(t.type)return z(t.type);if(t.enum){let s=typeof t.enum[0];return s===this.config.Ts.Keyword.Undefined?void 0:z(s)}return g.keys(t.properties).length?l.OBJECT:t.items?l.ARRAY:null};checkAndAddRequiredKeys=(e,t)=>"$$requiredKeys"in e&&e.$$requiredKeys.length?(this.config.update({internalTemplateOptions:{addUtilRequiredKeysType:true}}),this.config.Ts.TypeWithGeneric(this.config.Ts.CodeGenKeyword.UtilRequiredKeys,[t,this.config.Ts.UnionType(e.$$requiredKeys.map(this.config.Ts.StringValue))])):t;makeAddRequiredToChildSchema=(e,t)=>{if(!t)return t;let s=g.uniq([...this.getRequiredProperties(e),...this.getRequiredProperties(t)]),r=this.getSchemaRefType(t);if(r){let i=g.keys(r.rawTypeData?.properties||{}).filter(o=>s.includes(o));return i.length?{...t,$$requiredKeys:i}:t}if(t.properties){let i=g.keys(t.properties).filter(o=>s.includes(o));return i.length?{required:g.uniq([...this.getRequiredProperties(t),...i]),...t}:t}return t};filterSchemaContents=(e,t)=>g.uniq(e.filter(s=>t(s)));resolveTypeName=(e,{suffixes:t,resolver:s,prefixes:r,shouldReserve:a=true})=>s?this.config.componentTypeNameResolver.resolve([],i=>s(I(e),i)):this.config.componentTypeNameResolver.resolve([...(r||[]).map(i=>I(`${i} ${e}`)),...(t||[]).map(i=>I(`${e} ${i}`))],a);getComplexType=e=>e.oneOf?l.COMPLEX_ONE_OF:e.allOf?l.COMPLEX_ALL_OF:e.anyOf?l.COMPLEX_ANY_OF:e.not?l.COMPLEX_NOT:l.COMPLEX_UNKNOWN;getInternalSchemaType=e=>!g.isEmpty(e.enum)||!g.isEmpty(this.getEnumNames(e))?l.ENUM:e.discriminator?l.DISCRIMINATOR:e.allOf||e.oneOf||e.anyOf||e.not?l.COMPLEX:g.isEmpty(e.properties)?e.type===l.ARRAY?l.ARRAY:l.PRIMITIVE:l.OBJECT;getSchemaType=e=>{if(!e)return this.config.Ts.Keyword.Any;let t=this.getSchemaRefType(e);if(t)return this.checkAndAddRequiredKeys(e,this.safeAddNullToType(e,this.typeNameFormatter.format(t.typeName)));let s;if(this.isConstantSchema(e))s=this.formatJsValue(e.const);else {let r=this.getSchemaPrimitiveType(e);if(r==null)return this.config.Ts.Keyword.Any;let a=g.get(this.config.primitiveTypes,[r,e.format])||g.get(this.config.primitiveTypes,[r,"$default"])||this.config.primitiveTypes[r];typeof a=="function"?s=a(e,this):s=a||r;}return s?this.checkAndAddRequiredKeys(e,this.safeAddNullToType(e,s)):this.config.Ts.Keyword.Any};buildTypeNameFromPath=e=>(e=g.uniq(g.compact(e)),!e||!e[0]?null:I(g.camelCase(g.uniq([e[0],e[e.length-1]]).join("_"))));isConstantSchema(e){return "const"in e}formatJsValue=e=>{switch(typeof e){case "string":return this.config.Ts.StringValue(e);case "boolean":return this.config.Ts.BooleanValue(e);case "number":return this.config.Ts.NumberValue(e);default:return e===null?this.config.Ts.NullValue(e):this.config.Ts.Keyword.Any}}};var Fe=class{config;schemaComponentsMap;typeNameFormatter;schemaFormatters;templatesWorker;schemaUtils;schemaWalker;constructor(e,t,s,r,a){this.config=e,this.schemaComponentsMap=s,this.typeNameFormatter=r,this.templatesWorker=t,this.schemaWalker=a,this.schemaUtils=new we(this),this.schemaFormatters=new pe(this);}createSchemaParser=({schema:e,typeName:t,schemaPath:s})=>new Re(this,{schema:e,typeName:t,schemaPath:s});createSchema=({content:e,linkedSchema:t={},linkedComponent:s,schemaPath:r,...a})=>{let i=this.createSchemaParser({schema:s||t,schemaPath:r}),o=i.parseSchema();return o.content=e,Object.assign(o,a),s&&(s.typeData=o),i.schema};createParsedComponent=({typeName:e,schema:t,schemaPath:s})=>{let r=structuredClone(t),a=this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components","schemas",e]),r),i=this.parseSchema(r,null,s);return i.name=e,a.typeData=i,a};parseSchema=(e,t=null,s=[])=>this.createSchemaParser({schema:e,typeName:t,schemaPath:s}).parseSchema();getInlineParseContent=(e,t,s)=>this.createSchemaParser({schema:e,typeName:t,schemaPath:s}).getInlineParseContent();getParseContent=(e,t,s)=>this.createSchemaParser({schema:e,typeName:t,schemaPath:s}).getParseContent()};var Jt="abcdefghijklmnopqrstuvwxyz0123456789",dt=yt.customAlphabet(Jt,12);var xe=class extends O{counter=1;constructor(e,t){super(e,t,s=>{let r=s[0]&&`${s[0]}${this.counter++}`||`${this.config.specificArgNameResolverName}${this.counter++}`;return consola.debug("generated fallback type name for specific arg - ",r),r});}};var b={JSON:"JSON",URL_ENCODED:"URL_ENCODED",FORM_DATA:"FORM_DATA",IMAGE:"IMAGE",OTHER:"OTHER",TEXT:"TEXT"},Ee=class{config;schemaParserFabric;schemaUtils;typeNameFormatter;schemaComponentsMap;templatesWorker;FORM_DATA_TYPES=[];routes=[];hasSecurityRoutes=false;hasQueryRoutes=false;hasFormDataRoutes=false;constructor(e,t,s,r,a){this.config=e,this.schemaParserFabric=t,this.schemaUtils=this.schemaParserFabric.schemaUtils,this.typeNameFormatter=a,this.schemaComponentsMap=s,this.templatesWorker=r,this.FORM_DATA_TYPES=g.uniq([this.schemaUtils.getSchemaType({type:"string",format:"file"}),this.schemaUtils.getSchemaType({type:"string",format:"binary"})]);}createRequestsMap=e=>{let t=g.get(e,"parameters");return g.reduce(e,(s,r,a)=>(a.startsWith("x-")||["parameters","$ref"].includes(a)||(s[a]={...r,parameters:g.compact(g.concat(t,r.parameters))}),s),{})};parseRouteName=e=>{let t=this.config.hooks.onPreBuildRoutePath(e)||e,s=(t||"").match(/({[\w[\\\]^`][-_.\w]*})|(:[\w[\\\]^`][-_.\w]*:?)/g),r=g.reduce(s,(c,h)=>{let m=h.replace(/\{|\}|:/g,"");return m&&(m.includes("-")&&consola.warn("wrong path param name",m),c.push({$match:h,name:g.camelCase(m),required:true,type:"string",description:"",schema:{type:"string"},in:"path"})),c},[]),a=r.reduce((c,h,m,y)=>{let P=this.config.hooks.onInsertPathParam(h.name,m,y,c)||h.name;return c.replace(h.$match,`\${${P}}`)},t||""),i=a.match(/(\{\?.*\})/g),o=[];if(i?.length){for(let h of i)a=a.replace(h,"");let c=g.uniq(i.join(",").replace(/(\{\?)|(\})|\s/g,"").split(","));for(let h of c)h.includes("-")&&consola.warn("wrong query param name",h),o.push({$match:h,name:g.camelCase(h),required:true,type:"string",description:"",schema:{type:"string"},in:"query"});}let n={originalRoute:e||"",route:a,pathParams:r,queryParams:o};return this.config.hooks.onBuildRoutePath(n)||n};getRouteParams=(e,t,s)=>{let{parameters:r}=e,a={path:[],header:[],body:[],query:[],formData:[],cookie:[]};g.each(r,i=>{let o=this.schemaParserFabric.schemaUtils.getSchemaRefType(i),n=null;if(o?.rawTypeData.in&&o.rawTypeData)a[o.rawTypeData.in]||(a[o.rawTypeData.in]=[]),n={...o.rawTypeData,...o.rawTypeData.schema||{}};else {if(!i.in)return;a[i.in]||(a[i.in]=[]),n={...i,...i.schema||{}};}if(n.in==="path"){if(!n.name)return;n.name=g.camelCase(n.name);}n&&a[n.in].push(n);});for(let i of t)a.path.some(n=>n.name===i.name)||a.path.push(i);for(let i of s)a.query.some(n=>n.name===i.name)||a.query.push(i);return a};getContentTypes=(e,t)=>g.uniq(g.compact([...t||[],...g.flatten(g.map(e,s=>s&&g.keys(s.content)))]));getContentKind=e=>e.some(t=>t.startsWith("application/json"))||e.some(t=>t.endsWith("+json"))?b.JSON:e.includes("application/x-www-form-urlencoded")?b.URL_ENCODED:e.includes("multipart/form-data")?b.FORM_DATA:e.some(t=>t.includes("image/"))?b.IMAGE:e.some(t=>t.startsWith("text/"))?b.TEXT:b.OTHER;isSuccessStatus=e=>this.config.defaultResponseAsSuccess&&e==="default"||+e>=this.config.successResponseStatusRange[0]&&+e<=this.config.successResponseStatusRange[1]||e==="2xx";getSchemaFromRequestType=e=>{let t=g.get(e,"content");if(!t)return null;for(let s in t)if(t[s]?.schema)return {...t[s].schema,dataType:s};return null};getTypeFromRequestInfo=({requestInfo:e,parsedSchemas:t,operationId:s,defaultType:r,typeName:a})=>{let i=this.getSchemaFromRequestType(e),o=this.schemaParserFabric.schemaUtils.getSchemaRefType(e);if(i){let n=this.schemaParserFabric.getInlineParseContent(i,a,[s]),c=t.find(y=>this.typeNameFormatter.format(y.name)===n),h=t.find(y=>g.isEqual(y.content,n)),m=c||h;return m?this.typeNameFormatter.format(m.name):n}if(o){let n=o.typeName.replace(s,"");if(t.find(c=>c.name===n))return this.typeNameFormatter.format(n);switch(o.componentName){case "schemas":return this.typeNameFormatter.format(o.typeName);case "responses":case "requestBodies":return this.schemaParserFabric.getInlineParseContent(this.getSchemaFromRequestType(o.rawTypeData),o.typeName||null,[s]);default:return this.schemaParserFabric.getInlineParseContent(o.rawTypeData,o.typeName||null,[s])}}return r||this.config.Ts.Keyword.Any};getRequestInfoTypes=({requestInfos:e,parsedSchemas:t,operationId:s,defaultType:r})=>g.reduce(e,(a,i,o)=>{let n=this.getContentTypes([i]);return [...a,{...i||{},contentTypes:n,contentKind:this.getContentKind(n),type:this.schemaParserFabric.schemaUtils.safeAddNullToType(i,this.getTypeFromRequestInfo({requestInfo:i,parsedSchemas:t,operationId:s,defaultType:r})),description:this.schemaParserFabric.schemaFormatters.formatDescription(i.description||"",true),status:Number.isNaN(+o)?o:+o,isSuccess:this.isSuccessStatus(o)}]},[]);getResponseBodyInfo=(e,t)=>{let{produces:s,operationId:r,responses:a}=e,i=this.getContentTypes(a,[...s||[],e["x-accepts"]]),o=this.getRequestInfoTypes({requestInfos:a,parsedSchemas:t,operationId:r,defaultType:this.config.defaultResponseType}),n=o.find(m=>m.isSuccess),c=o.filter(m=>!m.isSuccess&&m.type!==this.config.Ts.Keyword.Any),h=m=>{if(!m)return "headers: {},";let y=Object.fromEntries(Object.entries(m).map(([S,w])=>[S,this.schemaUtils.getSchemaType(w)]));return `headers: { ${Object.entries(y).map(([S,w])=>`"${S}": ${w}`).join(",")} },`};return {contentTypes:i,responses:o,success:{schema:n,type:n?.type||this.config.Ts.Keyword.Any},error:{schemas:c,type:this.config.Ts.UnionType(c.map(m=>m.type))||this.config.Ts.Keyword.Any},full:{types:this.config.Ts.UnionType(o.map(m=>`{
23
+ data: ${m.type}, status: ${m.status}, statusCode: ${m.status}, statusText: "${m.description}", ${h(m.headers)} config: {} }`))||this.config.Ts.Keyword.Any}}};convertRouteParamsIntoObject=e=>e.reduce((t,s)=>!s||!s.name?t:{...t,properties:{...t.properties,[s.name]:{...s,...s.schema||{}}}},{properties:{},type:"object"});getRequestBodyInfo=(e,t,s,r)=>{let{requestBody:a,consumes:i,requestBodyName:o,operationId:n}=e,c=null,h=null,m=this.getContentTypes([a],[...i||[],e["x-contentType"]]),y=this.getContentKind(m),P=null;return this.config.extractRequestBody&&(P=this.schemaUtils.resolveTypeName(r.usage,{suffixes:this.config.extractingOptions.requestBodySuffix,resolver:this.config.extractingOptions.requestBodyNameResolver})),t.formData.length?(y=b.FORM_DATA,c=this.convertRouteParamsIntoObject(t.formData),h=this.schemaParserFabric.getInlineParseContent(c,P,[n])):y===b.FORM_DATA?(c=this.getSchemaFromRequestType(a),h=this.schemaParserFabric.getInlineParseContent(c,P,[n])):a&&(c=this.getSchemaFromRequestType(a),h=this.schemaParserFabric.schemaUtils.safeAddNullToType(a,this.getTypeFromRequestInfo({requestInfo:a,parsedSchemas:s,operationId:n,typeName:P})),this.FORM_DATA_TYPES.some(S=>h.includes(`: ${S}`))&&(y=b.FORM_DATA)),c&&!c.$ref&&this.config.extractRequestBody&&(c=this.schemaParserFabric.createParsedComponent({schema:c,typeName:P,schemaPath:[n]}),c?.typeData&&(c.typeData.isExtractedRequestBody=true),h=this.schemaParserFabric.getInlineParseContent({$ref:c.$ref})),{paramName:o||a?.name||We,contentTypes:m,contentKind:y,schema:c,type:h,required:a&&(typeof a.required>"u"||!!a.required)}};createRequestParamsSchema=({queryParams:e,queryObjectSchema:t,pathArgsSchemas:s,extractRequestParams:r,routeName:a})=>{if(!e||!e.length)return null;let i=s.reduce((h,m)=>(m.name&&(h[m.name]={...m,in:"path"}),h),{}),o=g.reduce(g.get(t,"properties",{}),(h,m,y)=>(y&&typeof m=="object"&&(h[y]={...m,in:"query"}),h),{}),n={...t,properties:{...o,...i}},c=this.config.hooks.onCreateRequestParams(n);if(c)return c;if(r){let h=this.schemaUtils.resolveTypeName(a.usage,{suffixes:this.config.extractingOptions.requestParamsSuffix,resolver:this.config.extractingOptions.requestParamsNameResolver}),m=this.schemaParserFabric.createParsedComponent({typeName:h,schema:n});return m.typeData&&(m.typeData.isExtractedRequestParams=true),m}return n};extractResponseBodyIfItNeeded=(e,t,s)=>{if(t.responses.length&&t.success&&t.success.schema){let r=this.schemaUtils.resolveTypeName(s.usage,{suffixes:this.config.extractingOptions.responseBodySuffix,resolver:this.config.extractingOptions.responseBodyNameResolver}),a=t.responses.indexOf(t.success.schema),i=t.success;if(i.schema&&!i.schema.$ref){let o=i.schema.contentKind,n=this.getSchemaFromRequestType(i.schema);i.schema=this.schemaParserFabric.createParsedComponent({schema:n,typeName:r,schemaPath:[e.operationId]}),i.schema.contentKind=o,i.schema.typeData&&(i.schema.typeData.isExtractedResponseBody=true),i.type=this.schemaParserFabric.getInlineParseContent({$ref:i.schema.$ref}),a>-1&&g.assign(t.responses[a],{...i.schema,type:i.type});}}};extractResponseErrorIfItNeeded=(e,t,s)=>{if(t.responses.length&&t.error.schemas&&t.error.schemas.length){let r=this.schemaUtils.resolveTypeName(s.usage,{suffixes:this.config.extractingOptions.responseErrorSuffix,resolver:this.config.extractingOptions.responseErrorNameResolver}),a=t.error.schemas.map(this.getSchemaFromRequestType).filter(Boolean);if(!a.length)return;let i=this.schemaParserFabric.parseSchema({oneOf:a,title:a.map(n=>n.title).filter(Boolean).join(" "),description:a.map(n=>n.description).filter(Boolean).join(`
24
+ `)},null,[e.operationId]),o=this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components","schemas",r]),{...i});t.error.schemas=[o],o.typeData&&(o.typeData.isExtractedResponseError=true),t.error.type=this.typeNameFormatter.format(o.typeName);}};getRouteName=e=>{let{moduleName:t}=e,{routeNameDuplicatesMap:s,templatesToRender:r}=this.config,a=r.routeName,i=this.templatesWorker.renderTemplate(a,{routeInfo:e}),o=this.config.hooks.onFormatRouteName(e,i)||i,n=`${t}|${o}`;s.has(n)?(s.set(n,s.get(n)+1),consola.warn(`Module "${t}" already has method "${o}()".`,`This method has been renamed to "${o+s.get(n)}()" to solve conflict names.`)):s.set(n,1);let c=s.get(n),h={usage:o+(c>1?c:""),original:o,duplicate:c>1};return this.config.hooks.onCreateRouteName(h,e)||h};parseRouteInfo=(e,t,s,r,a)=>{let{security:i}=r,{moduleNameIndex:o,moduleNameFirstTag:n,extractRequestParams:c}=this.config,{operationId:h,requestBody:m,security:y,parameters:P,summary:S,description:w,tags:A,responses:bt,requestBodyName:is,produces:At,consumes:Ot,...It}=t,{route:ze,pathParams:Mt,queryParams:$t}=this.parseRouteName(e),vt=dt(),Ze=A&&A.length>0?A[0]:null,et=n&&Ze?g.camelCase(Ze):g.camelCase(g.compact(ze.split("/"))[o]),tt=!!i?.length;y&&(tt=y.length>0);let x=this.getRouteParams(t,Mt,$t),Z=x.path.map(j=>({name:j.name,optional:!j.required,type:this.config.Ts.Keyword.Any,description:j.description})),kt=Z.map(j=>j.name),M=this.getResponseBodyInfo(t,a),st={...It,pathArgs:Z,operationId:h,method:s,route:e,moduleName:et,responsesTypes:M.responses,description:w,tags:A,summary:S,responses:bt,produces:At,requestBody:m,consumes:Ot,security:y},ee=this.convertRouteParamsIntoObject(x.query),Ke=this.convertRouteParamsIntoObject(x.path),qe=this.convertRouteParamsIntoObject(x.header),$=this.getRouteName(st),v=this.getRequestBodyInfo(t,x,a,$),jt=this.createRequestParamsSchema({queryParams:x.query,pathArgsSchemas:x.path,queryObjectSchema:ee,extractRequestParams:c,routeName:$});this.config.extractResponseBody&&this.extractResponseBodyIfItNeeded(t,M,$),this.config.extractResponseError&&this.extractResponseErrorIfItNeeded(t,M,$);let te=this.schemaUtils.resolveTypeName($.usage,{suffixes:this.config.extractingOptions.requestParamsSuffix,resolver:this.config.extractingOptions.requestParamsNameResolver,shouldReserve:false}),rt=x.query.length?this.schemaParserFabric.getInlineParseContent(ee,null,[te]):null,at=x.path.length?this.schemaParserFabric.getInlineParseContent(Ke,null,[te]):null,it=x.header.length?this.schemaParserFabric.getInlineParseContent(qe,null,[te]):null,L=new xe(this.config,kt),H={query:rt?{name:L.resolve(He),optional:this.schemaParserFabric.parseSchema(ee,null,[$.usage]).allFieldsAreOptional,type:rt}:void 0,body:v.type?{name:L.resolve([v.paramName,...Ve]),optional:!v.required,type:v.type}:void 0,pathParams:at?{name:L.resolve(Le),optional:this.schemaParserFabric.parseSchema(Ke,null,[$.usage]).allFieldsAreOptional,type:at}:void 0,headers:it?{name:L.resolve(Be),optional:this.schemaParserFabric.parseSchema(qe,null,[$.usage]).allFieldsAreOptional,type:it}:void 0};return Z.forEach((j,Dt)=>{j.type=this.schemaParserFabric.getInlineParseContent(x.path[Dt].schema,null,[te]);}),{id:vt,namespace:et.replace(/^(\d)/,"v$1"),routeName:$,routeParams:x,requestBodyInfo:v,responseBodyInfo:M,specificArgs:H,queryObjectSchema:ee,pathObjectSchema:Ke,headersObjectSchema:qe,responseBodySchema:M.success.schema,requestBodySchema:v.schema,specificArgNameResolver:L,request:{contentTypes:v.contentTypes,parameters:Z,path:ze,formData:v.contentKind===b.FORM_DATA,isQueryBody:v.contentKind===b.URL_ENCODED,security:tt,method:s,requestParams:jt,payload:H.body,query:H.query,pathParams:H.pathParams,headers:H.headers},response:{contentTypes:M.contentTypes,type:M.success.type,errorType:M.error.type,fullTypes:M.full.types},raw:st}};attachSchema=({usageSchema:e,parsedSchemas:t})=>{this.config.routeNameDuplicatesMap.clear();let s=g.entries(e.paths);for(let[r,a]of s){let i=this.createRequestsMap(a);for(let[o,n]of Object.entries(i)){let c=this.parseRouteInfo(r,n,o,e,t),h=this.config.hooks.onCreateRoute(c);if(h!==false){let m=h||c;!this.hasSecurityRoutes&&m.security&&(this.hasSecurityRoutes=m.security),!this.hasQueryRoutes&&m.hasQuery&&(this.hasQueryRoutes=m.hasQuery),!this.hasFormDataRoutes&&m.hasFormDataParams&&(this.hasFormDataRoutes=m.hasFormDataParams),this.routes.push(m);}}}};getGroupedRoutes=()=>{let e=this.routes.reduce((s,r)=>(r.namespace?(s[r.namespace]||(s[r.namespace]=[]),s[r.namespace].push(r)):s.$outOfModule.push(r),s),{$outOfModule:[]}),t=g.reduce(e,(s,r,a)=>(a==="$outOfModule"?s.outOfModule=r:(s.combined||(s.combined=[]),s.combined.push({moduleName:a,routes:r.map(i=>{let{original:o,usage:n}=i.routeName;return r.length>1&&n!==o&&!r.some(({routeName:c,id:h})=>h!==i.id&&o===c.original)?{...i,routeName:{...i.routeName,usage:o}}:i})})),s),{});return this.config.sortRoutes&&(t.outOfModule&&(t.outOfModule=this.sortRoutes(t.outOfModule)),t.combined&&g.each(t.combined,s=>{s.routes=this.sortRoutes(s.routes);})),t};sortRoutes=e=>g.slice(e).sort((t,s)=>t.routeName.usage.localeCompare(s.routeName.usage))};var be=class{config;swaggerSchemaResolver;schemas=new Map;caches=new Map;constructor(e,t){this.config=e,this.swaggerSchemaResolver=t;}addSchema=(e,t)=>{this.schemas.set(e,structuredClone(t));};_isLocalRef=e=>e.startsWith("#");_isRemoteRef=e=>e.startsWith("http://")||e.startsWith("https://");_getRefDataFromSchema=(e,t)=>{let s=t.replace("#","").split("/"),r=g.get(e,s);return r&&this.caches.set(t,r),r}};var Ae=class{config;constructor(e){this.config=e;}async download({url:e,authToken:t,...s}){let r={};t&&(r.headers={Authorization:t}),g.merge(r,s,this.config.requestOptions);try{return await(await fetch(e,r)).text()}catch(a){let i=`error while fetching data from URL "${e}"`;return consola.error(i,a),i}}};var Oe=class{config;fileSystem;request;constructor(e,t){this.config=e,this.fileSystem=t,this.request=new Ae(e);}async create(){let{spec:e,patch:t,input:s,url:r,authorizationToken:a}=this.config;if(e)return await this.convertSwaggerObject(e,{patch:t});let i=await this.fetchSwaggerSchemaFile(s,r,a),o=this.processSwaggerSchemaFile(i);return await this.convertSwaggerObject(o,{patch:t})}convertSwaggerObject(e,t){return new Promise(s=>{let r=structuredClone(e);r.info=g.merge({title:"No title",version:""},r.info),Object.hasOwn(r,"openapi")?s({usageSchema:r,originalSchema:structuredClone(r)}):(r.paths=g.merge({},r.paths),St.convertObj(r,{...t,resolveInternal:true,warnOnly:true,refSiblings:"preserve",rbname:"requestBodyName"},(a,i)=>{let o=g.get(a,"options.openapi",g.get(i,"openapi"));if(!o&&a)throw a;this.config.update({convertedFromSwagger2:true}),s({usageSchema:o,originalSchema:r});}));})}getSwaggerSchemaByPath=e=>(consola.info(`try to get swagger by path "${e}"`),this.fileSystem.getFileContent(e));async fetchSwaggerSchemaFile(e,t,s){return this.fileSystem.pathIsExist(e)?this.getSwaggerSchemaByPath(e):(consola.info(`try to get swagger by URL "${t}"`),await this.request.download({url:t,authToken:s}))}processSwaggerSchemaFile(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return Pt.load(e)}}fixSwaggerSchema({usageSchema:e,originalSchema:t}){let s=g.get(e,"paths"),r=g.get(t,"paths");g.each(s,(a,i)=>{let o=g.get(r,i);g.each(a,(n,c)=>{let h=g.get(o,c),m=g.get(n,"parameters",[]),y=g.get(h,"parameters",[]);typeof n=="object"&&(n.consumes=g.uniq(g.compact([...n.consumes||[],...h.consumes||[]])),n.produces=g.uniq(g.compact([...n.produces||[],...h.produces||[]]))),g.each(y,P=>{m.find(w=>P.in===w.in&&P.name===w.name)||m.push(P);});});});}};var Ie=class{config;fileSystem;getRenderTemplateData;constructor(e,t,s){this.config=e,this.fileSystem=t,this.getRenderTemplateData=s,this.config.debug&&(consola.level=Number.MAX_SAFE_INTEGER),this.config.silent&&(consola.level=0);}getTemplatePaths=e=>{let t=E.dirname(Ct.fileURLToPath(import.meta.url)),s=E.resolve(t,"../templates/base"),r=E.resolve(t,"../templates/default"),a=E.resolve(t,"../templates/modular"),i=e.modular?a:r,o=e.templates&&E.resolve(process.cwd(),e.templates);return {base:s,default:r,modular:a,original:i,custom:o}};cropExtension=e=>this.config.templateExtensions.reduce((t,s)=>t.endsWith(s)?t.replace(s,""):t,e);getTemplateFullPath=(e,t)=>{let s=E.resolve(e,"./",this.cropExtension(t));return this.config.templateExtensions.map(a=>`${s}${a}`).find(a=>!!this.fileSystem.pathIsExist(a))};requireFnFromTemplate=async e=>e.startsWith("./")||e.startsWith("../")?await import(E.resolve(this.config.templatePaths.custom||this.config.templatePaths.original,e)):await import(e);getTemplate=(e,t,s)=>{let{templatePaths:r}=this.config;if(s)return this.fileSystem.getFileContent(s);if(!t)return "";let a=r.custom&&this.getTemplateFullPath(r.custom,t),i=a&&this.fileSystem.getFileContent(a);if(i)return consola.info(`"${e.toLowerCase()}" template found in "${r.custom}"`),i;let o=this.getTemplateFullPath(r.base,t);o?i=this.fileSystem.getFileContent(o):r.custom?consola.warn("Code generator will use the default template:",`"${e.toLowerCase()}"`,"template not found in",`"${r.custom}"`):consola.info(`Code generator will use the default template for "${e.toLowerCase()}"`);let n=this.getTemplateFullPath(r.original,t);return n&&(i=this.fileSystem.getFileContent(n)),i};getTemplates=({templatePaths:e})=>(e.custom&&consola.info(`try to read templates from directory "${e.custom}"`),g.reduce(this.config.templateInfos,(t,{name:s,fileName:r})=>({...t,[s]:this.getTemplate(s,r)}),{}));findTemplateWithExt=e=>{let t=this.cropExtension(e);return this.config.templateExtensions.map(r=>`${t}${r}`).find(r=>this.fileSystem.pathIsExist(r))};getTemplateContent=e=>{let t=g.keys(this.config.templatePaths).find(a=>e.startsWith(`@${a}`));if(t){let a=E.resolve(e.replace(`@${t}`,g.get(this.config.templatePaths,t))),i=this.findTemplateWithExt(a);if(i)return this.fileSystem.getFileContent(i)}let s=this.config.templatePaths.custom&&this.findTemplateWithExt(E.resolve(this.config.templatePaths.custom,e));if(s)return this.fileSystem.getFileContent(s);let r=this.findTemplateWithExt(E.resolve(this.config.templatePaths.original,e));return r?this.fileSystem.getFileContent(r):""};renderTemplate=(e,t,s={})=>e?Nt.render(e,{...this.getRenderTemplateData(),...t},{async:false,...s,includeFile:(r,a,i={})=>this.renderTemplate(this.getTemplateContent(r),a,i)}):""};var Me=class{config;codeFormatter;constructor(e,t){this.config=e,this.codeFormatter=t;}translate(e){throw new Error("not implemented")}};var $e=class extends Me{compileTSCode=e=>{let t=`${e.fileName}${e.fileExtension}`,s={},r=d.createCompilerHost(this.config.compilerTsConfig,true),a=[t],i=r.getSourceFile.bind(r);return r.getSourceFile=(o,n,c,h)=>o!==t?i(o,n,c,h):d.createSourceFile(o,e.fileContent,n,true,d.ScriptKind.TS),r.writeFile=(o,n)=>{s[o]=n;},d.createProgram(a,this.config.compilerTsConfig,r).emit(),s};translate=async e=>{let t=this.compileTSCode(e),s=`${e.fileName}${d.Extension.Js}`,r=`${e.fileName}${d.Extension.Dts}`,a=t[s],i=e.fileContent.split(`
25
25
  `).filter(n=>n.startsWith("import ")),o=t[r].split(`
26
26
  `).map(n=>n.startsWith("import ")?i.shift():n).join(`
27
- `);return [{fileName:e.fileName,fileExtension:g.Extension.Js,fileContent:await this.codeFormatter.formatCode(a)},{fileName:e.fileName,fileExtension:g.Extension.Dts,fileContent:await this.codeFormatter.formatCode(o)}]}};var Me=class{formattedModelNamesMap=new Map;config;constructor(e){this.config=e;}format=(e,t={})=>{let s=t.type??"type-name",r=s==="enum-key"?this.config.enumKeyPrefix:this.config.typePrefix,a=s==="enum-key"?this.config.enumKeySuffix:this.config.typeSuffix,i=`${r}_${e}_${a}`;if(typeof e!="string")return consola.warn("wrong name of the model name",e),e;if(/^([A-Z_]{1,})$/g.test(e))return f.compact([r,e,a]).join("_");if(this.formattedModelNamesMap.has(i))return this.formattedModelNamesMap.get(i);let o=this.fixModelName(e,{type:s}),n=f.startCase(`${r}_${o}_${a}`).replace(/\s/g,""),c=this.config.hooks.onFormatTypeName(n,e,s)||n;return this.formattedModelNamesMap.set(i,c),c};isValidName=e=>/^([A-Za-z$_]{1,})$/g.test(e);fixModelName=(e,t)=>{if(!this.isValidName(e)){if(!/^[a-zA-Z_$]/g.test(e))return `${t.type==="enum-key"?this.config.fixInvalidEnumKeyPrefix:this.config.fixInvalidTypeNamePrefix} ${e}`;if(e.includes("."))return e.replace(/Exclude_keyof[A-Za-z]+/g,()=>"ExcludeKeys").replace(/%22~AND~%22/g,"And").replace(/%22~OR~%22/g,"Or").replace(/(\.?%22)|\./g,"_").replace(/__+$/,"");if(e.includes("-"))return f.startCase(e).replace(/ /g,"")}return e}};var zt=`/* eslint-disable */
27
+ `);return [{fileName:e.fileName,fileExtension:d.Extension.Js,fileContent:await this.codeFormatter.formatCode(a)},{fileName:e.fileName,fileExtension:d.Extension.Dts,fileContent:await this.codeFormatter.formatCode(o)}]}};var ve=class{formattedModelNamesMap=new Map;config;constructor(e){this.config=e;}format=(e,t={})=>{let s=t.type??"type-name",r=s==="enum-key"?this.config.enumKeyPrefix:this.config.typePrefix,a=s==="enum-key"?this.config.enumKeySuffix:this.config.typeSuffix,i=`${r}_${e}_${a}`;if(typeof e!="string")return consola.warn("wrong name of the model name",e),e;if(/^([A-Z_]{1,})$/g.test(e))return g.compact([r,e,a]).join("_");if(this.formattedModelNamesMap.has(i))return this.formattedModelNamesMap.get(i);let o=this.fixModelName(e,{type:s}),n=g.startCase(`${r}_${o}_${a}`).replace(/\s/g,""),c=this.config.hooks.onFormatTypeName(n,e,s)||n;return this.formattedModelNamesMap.set(i,c),c};isValidName=e=>/^([A-Za-z$_]{1,})$/g.test(e);fixModelName=(e,t)=>{if(!this.isValidName(e)){if(!/^[a-zA-Z_$]/g.test(e))return `${t.type==="enum-key"?this.config.fixInvalidEnumKeyPrefix:this.config.fixInvalidTypeNamePrefix} ${e}`;if(e.includes("."))return e.replace(/Exclude_keyof[A-Za-z]+/g,()=>"ExcludeKeys").replace(/%22~AND~%22/g,"And").replace(/%22~OR~%22/g,"Or").replace(/(\.?%22)|\./g,"_").replace(/__+$/,"");if(e.includes("-"))return g.startCase(e).replace(/ /g,"")}return e}};var es=`/* eslint-disable */
28
28
  /* tslint:disable */
29
29
  // @ts-nocheck
30
30
  /*
@@ -36,7 +36,7 @@ ${e}
36
36
  * ---------------------------------------------------------------
37
37
  */
38
38
 
39
- `,W=class{getFileContent=e=>C.readFileSync(e,{encoding:"utf8"});readDir=e=>C.readdirSync(e);pathIsDir=e=>{if(!e)return false;try{return C.statSync(e).isDirectory()}catch{return false}};cropExtension=e=>{let t=e.split(".");return t.length>1&&t.pop(),t.join(".")};removeDir=e=>{try{typeof C.rmSync=="function"?C.rmSync(e,{recursive:!0}):C.rmdirSync(e,{recursive:!0});}catch(t){consola.debug("failed to remove dir",t);}};createDir=e=>{try{C.mkdirSync(e,{recursive:!0});}catch(t){consola.debug("failed to create dir",t);}};cleanDir=e=>{this.removeDir(e),this.createDir(e);};pathIsExist=e=>!!e&&C.existsSync(e);createFile=({path:e,fileName:t,content:s,withPrefix:r})=>{let a=F.dirname(Pt.fileURLToPath(import.meta.url)),i=F.resolve(a,e,`./${t}`),o=`${r?zt:""}${s}`;return C.writeFileSync(i,o)}};var Zt=["schemaWalker","swaggerSchemaResolver","schemaComponentsMap","typeNameFormatter","templatesWorker","codeFormatter","schemaParserFabric","schemaRoutes","javascriptTranslator"],ve=class{config;swaggerSchemaResolver;schemaComponentsMap;typeNameFormatter;schemaParserFabric;schemaRoutes;fileSystem;codeFormatter;templatesWorker;schemaWalker;javascriptTranslator;constructor(e){this.config=new ie(e),this.fileSystem=new W,this.swaggerSchemaResolver=new be(this.config,this.fileSystem),this.schemaWalker=new xe(this.config,this.swaggerSchemaResolver),this.schemaComponentsMap=new oe(this.config),this.typeNameFormatter=new Me(this.config),this.templatesWorker=new Ae(this.config,this.fileSystem,this.getRenderTemplateData),this.codeFormatter=new ee(this.config),this.schemaParserFabric=new Re(this.config,this.templatesWorker,this.schemaComponentsMap,this.typeNameFormatter,this.schemaWalker),this.schemaRoutes=new Fe(this.config,this.schemaParserFabric,this.schemaComponentsMap,this.templatesWorker,this.typeNameFormatter),this.javascriptTranslator=new Ie(this.config,this.codeFormatter);}async start(){this.config.update({templatePaths:this.templatesWorker.getTemplatePaths(this.config)}),this.config.update({templatesToRender:this.templatesWorker.getTemplates(this.config)});let e=await this.swaggerSchemaResolver.create();this.swaggerSchemaResolver.fixSwaggerSchema(e),this.config.update({swaggerSchema:e.usageSchema,originalSchema:e.originalSchema}),this.schemaWalker.addSchema("$usage",e.usageSchema),this.schemaWalker.addSchema("$original",e.originalSchema),consola.info("start generating your typescript api"),this.config.update(this.config.hooks.onInit(this.config,this)||this.config),this.schemaComponentsMap.clear(),f.each(e.usageSchema.components,(n,c)=>f.each(n,(h,m)=>{this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components",c,m]),h);}));let s=this.schemaComponentsMap.filter(f.compact(["schemas",this.config.extractResponses&&"responses"])).map(n=>{let c=this.schemaParserFabric.parseSchema(n.rawTypeData,n.typeName);return n.typeData=c,c});this.schemaRoutes.attachSchema({usageSchema:e.usageSchema,parsedSchemas:s});let r={apiConfig:this.createApiConfig(e.usageSchema),config:this.config,modelTypes:this.collectModelTypes(),hasSecurityRoutes:this.schemaRoutes.hasSecurityRoutes,hasQueryRoutes:this.schemaRoutes.hasQueryRoutes,hasFormDataRoutes:this.schemaRoutes.hasFormDataRoutes,generateResponses:this.config.generateResponses,routes:this.schemaRoutes.getGroupedRoutes(),extraTemplates:this.config.extraTemplates,fileName:this.config.fileName,translateToJavaScript:this.config.toJS,customTranslator:this.config.customTranslator?new this.config.customTranslator:null,utils:this.getRenderTemplateData().utils},a=this.config.hooks.onPrepareConfig(r)||r;this.fileSystem.pathIsExist(this.config.output)?this.config.cleanOutput&&(consola.debug("cleaning dir",this.config.output),this.fileSystem.cleanDir(this.config.output)):(consola.debug(`path ${this.config.output} is not exist. creating dir by this path`),this.fileSystem.createDir(this.config.output));let i=await this.generateOutputFiles({configuration:a});if(this.fileSystem.pathIsDir(this.config.output))for(let n of i)this.fileSystem.createFile({path:this.config.output,fileName:`${n.fileName}${n.fileExtension}`,content:n.fileContent,withPrefix:true}),consola.success("api file",`"${n.fileName}${n.fileExtension}"`,`created in ${this.config.output}`);return {files:i,configuration:a,getTemplate:this.templatesWorker.getTemplate,renderTemplate:this.templatesWorker.renderTemplate,createFile:this.fileSystem.createFile,formatTSContent:this.codeFormatter.formatCode}}getRenderTemplateData=()=>({utils:{Ts:this.config.Ts,formatDescription:this.schemaParserFabric.schemaFormatters.formatDescription,internalCase:X,classNameCase:A,pascalCase:A,getInlineParseContent:this.schemaParserFabric.getInlineParseContent,getParseContent:this.schemaParserFabric.getParseContent,getComponentByRef:this.schemaComponentsMap.get,parseSchema:this.schemaParserFabric.parseSchema,checkAndAddNull:this.schemaParserFabric.schemaUtils.safeAddNullToType,safeAddNullToType:this.schemaParserFabric.schemaUtils.safeAddNullToType,isNeedToAddNull:this.schemaParserFabric.schemaUtils.isNullMissingInType,inlineExtraFormatters:this.schemaParserFabric.schemaFormatters.inline,formatters:this.schemaParserFabric.schemaFormatters.base,formatModelName:this.typeNameFormatter.format,fmtToJSDocLine:(e,{eol:t=true})=>` * ${e}${t?`
40
- `:""}`,NameResolver:b,_:f,require:this.templatesWorker.requireFnFromTemplate},config:this.config});collectModelTypes=()=>{let e=this.schemaComponentsMap.getComponents(),t=[],s=f.compact(["schemas",this.config.extractResponses&&"responses"]),r=()=>this.schemaComponentsMap.filter(...s).length,a=r(),i=0;for(;i<a;){t=[],i=0;for(let o of e)if(s.includes(o.componentName)){let n=this.prepareModelType(o);n&&t.push(n),i++;}a=r();}return this.config.sortTypes?t.sort(me("name")):t};prepareModelType=e=>{if(e.$prepared)return e.$prepared;e.typeData||(e.typeData=this.schemaParserFabric.parseSchema(e.rawTypeData,e.typeName));let t=e.typeData,s=this.schemaParserFabric.schemaFormatters.base[t.type]?this.schemaParserFabric.schemaFormatters.base[t.type](t):t,{typeIdentifier:r,name:a,content:i,description:o}=s,n=this.typeNameFormatter.format(a);if(n===null)return null;let c={...s,typeIdentifier:r,name:n,description:o,$content:t.content,rawContent:t.content,content:i,typeData:s};return e.$prepared=c,c};generateOutputFiles=async({configuration:e})=>{let{modular:t,templatesToRender:s}=this.config,r=t?await this.createMultipleFileInfos(s,e):await this.createSingleFileInfo(s,e);if(!f.isEmpty(e.extraTemplates))for(let a of e.extraTemplates){let i=this.templatesWorker.renderTemplate(this.fileSystem.getFileContent(a.path),e);r.push(...await this.createOutputFileInfo(e,a.name,i));}return r.filter(a=>!!a&&!!a.fileContent)};createMultipleFileInfos=async(e,t)=>{let{routes:s}=t,{fileNames:r,generateRouteTypes:a,generateClient:i}=t.config,o=[];if(s.$outOfModule){if(a){let n=this.templatesWorker.renderTemplate(e.routeTypes,{...t,route:t.routes.$outOfModule});o.push(...await this.createOutputFileInfo(t,r.outOfModuleApi,n));}if(i){let n=this.templatesWorker.renderTemplate(e.api,{...t,route:t.routes.$outOfModule});o.push(...await this.createOutputFileInfo(t,r.outOfModuleApi,n));}}if(s.combined)for(let n of s.combined){if(a){let c=this.templatesWorker.renderTemplate(e.routeTypes,{...t,route:n});o.push(...await this.createOutputFileInfo(t,A(`${n.moduleName}_Route`),c));}if(i){let c=this.templatesWorker.renderTemplate(e.api,{...t,route:n});o.push(...await this.createOutputFileInfo(t,A(n.moduleName),c));}}return [...await this.createOutputFileInfo(t,r.dataContracts,this.templatesWorker.renderTemplate(e.dataContracts,t)),...i?await this.createOutputFileInfo(t,r.httpClient,this.templatesWorker.renderTemplate(e.httpClient,t)):[],...o]};createSingleFileInfo=async(e,t)=>{let{generateRouteTypes:s,generateClient:r}=t.config;return await this.createOutputFileInfo(t,t.fileName,f.compact([this.templatesWorker.renderTemplate(e.dataContracts,t),s&&this.templatesWorker.renderTemplate(e.routeTypes,t),r&&this.templatesWorker.renderTemplate(e.httpClient,t),r&&this.templatesWorker.renderTemplate(e.api,t)]).join(`
41
- `))};createOutputFileInfo=async(e,t,s)=>{let r=this.fileSystem.cropExtension(t),a=g.Extension.Ts;return e.translateToJavaScript?(consola.debug("using js translator for",r),await this.javascriptTranslator.translate({fileName:r,fileExtension:a,fileContent:s})):e.customTranslator?(consola.debug("using custom translator for",r),await e.customTranslator.translate({fileName:r,fileExtension:a,fileContent:s})):(consola.debug("generating output for",`${r}${a}`),[{fileName:r,fileExtension:a,fileContent:await this.codeFormatter.formatCode(s)}])};createApiConfig=e=>{let{info:t,servers:s,host:r,basePath:a,externalDocs:i,tags:o}=e,n=s?.[0]||{url:""},{title:c="No title",version:h}=t||{},{url:m}=n;return {info:t||{},servers:s||[],basePath:a,host:r,externalDocs:f.merge({url:"",description:""},i),tags:f.compact(o),baseUrl:m,title:c,version:h}};injectClassInstance=(e,t)=>{this[e]=t;for(let s of Zt)s!==e&&e in this[s]&&(this[s][e]=t);}};var ke=class{cleanOutput=false;output=void 0;httpClientType=L.FETCH;modular=false;rewrite=false;silent=false;debug=false;version=H;constructor(e){this.update(e);}update=e=>{K(this,e);}};var ts=F__default.dirname(Pt__default.fileURLToPath(import.meta.url)),je=class{config;fileSystem;rootDir=F__default.resolve(ts,"../../../");paths={baseTemplates:"templates/base",httpClientTemplates:"templates/base/http-clients",moduleApiTemplates:"templates/modular",defaultApiTemplates:"templates/default"};importTemplatePrefixes=["@base","@modular","@default"];constructor(e){this.config=new ke(e),this.fileSystem=new W;}async start(){consola.info('start generating source templates ".ejs" for code generator');let e=this.getTemplates();if(this.config.output){consola.info("preparing output directory for source templates");let t=F__default.resolve(process.cwd(),this.config.output);this.fileSystem.pathIsExist(t)?this.config.cleanOutput&&this.fileSystem.cleanDir(t):this.fileSystem.createDir(t);for(let s of e){let r=this.fileSystem.cropExtension(s.name),a=F__default.resolve(t,`${r}.ejs`),i=F__default.resolve(t,`${r}.eta`),o=this.fileSystem.pathIsExist(a),n=this.fileSystem.pathIsExist(i);!o&&!n?this.fileSystem.createFile({path:t,fileName:s.name,content:s.content,withPrefix:false}):this.config.rewrite&&(o?this.fileSystem.createFile({path:t,fileName:`${r}.ejs`,content:s.content,withPrefix:false}):n&&this.fileSystem.createFile({path:t,fileName:`${r}.eta`,content:s.content,withPrefix:false}));}consola.success(`source templates has been successfully created in "${t}"`);}return {files:e,configuration:this.config,createFile:this.fileSystem.createFile}}getTemplates=()=>{let e=[],t=this.getTemplateNamesFromDir(this.paths.baseTemplates),s=this.getTemplateNamesFromDir(this.paths.httpClientTemplates),r=this.config.modular?this.paths.moduleApiTemplates:this.paths.defaultApiTemplates,a=this.getTemplateNamesFromDir(r),i=s.find(n=>n.startsWith(`${this.config.httpClientType}-`)),o="";i&&(o=this.fixTemplateContent(this.getTemplateContent(`${this.paths.httpClientTemplates}/${i}`)));for(let n of t){let c=n==="http-client.ejs"&&o||this.fixTemplateContent(this.getTemplateContent(`${this.paths.baseTemplates}/${n}`));e.push({name:n,content:c});}for(let n of a)e.push({name:n,content:this.fixTemplateContent(this.getTemplateContent(`${r}/${n}`))});return e};fixTemplateContent=e=>{let t=new RegExp(`includeFile\\("(${this.importTemplatePrefixes.map(a=>`(${a})`).join("|")})/`,"g"),s=new RegExp(`includeFile\\(\`(${this.importTemplatePrefixes.map(a=>`(${a})`).join("|")})/`,"g"),r=new RegExp(`includeFile\\('(${this.importTemplatePrefixes.map(a=>`(${a})`).join("|")})/`,"g");return e.replace(t,'includeFile("./').replace(s,"includeFile(`./").replace(r,"includeFile('./")};getTemplateNamesFromDir=e=>this.fileSystem.readDir(F__default.resolve(this.rootDir,e)).filter(t=>t.endsWith(".ejs"));getTemplateContent=e=>this.fileSystem.getFileContent(F__default.resolve(this.rootDir,e))};async function ss(p){return p.debug&&(consola.level=Number.MAX_SAFE_INTEGER),p.silent&&(consola.level=0),await new je(p).start()}async function Va(p){return p.debug&&(consola.level=Number.MAX_SAFE_INTEGER),p.silent&&(consola.level=0),await new ve(p).start()}export{ot as a,L as b,ae as c,ie as d,ke as e,ss as f,Va as g};//# sourceMappingURL=chunk-U2TAGTOU.js.map
42
- //# sourceMappingURL=chunk-U2TAGTOU.js.map
39
+ `,B=class{getFileContent=e=>R.readFileSync(e,{encoding:"utf8"});readDir=e=>R.readdirSync(e);pathIsDir=e=>{if(!e)return false;try{return R.statSync(e).isDirectory()}catch{return false}};cropExtension=e=>{let t=e.split(".");return t.length>1&&t.pop(),t.join(".")};removeDir=e=>{try{typeof R.rmSync=="function"?R.rmSync(e,{recursive:!0}):R.rmdirSync(e,{recursive:!0});}catch(t){consola.debug("failed to remove dir",t);}};createDir=e=>{try{R.mkdirSync(e,{recursive:!0});}catch(t){consola.debug("failed to create dir",t);}};cleanDir=e=>{this.removeDir(e),this.createDir(e);};pathIsExist=e=>!!e&&R.existsSync(e);createFile=({path:e,fileName:t,content:s,withPrefix:r})=>{let a=E.dirname(Ct.fileURLToPath(import.meta.url)),i=E.resolve(a,e,`./${t}`),o=`${r?es:""}${s}`;return R.writeFileSync(i,o)}};var ts=["schemaWalker","swaggerSchemaResolver","schemaComponentsMap","typeNameFormatter","templatesWorker","codeFormatter","schemaParserFabric","schemaRoutes","javascriptTranslator"],je=class{config;swaggerSchemaResolver;schemaComponentsMap;typeNameFormatter;schemaParserFabric;schemaRoutes;fileSystem;codeFormatter;templatesWorker;schemaWalker;javascriptTranslator;constructor(e){this.config=new oe(e),this.fileSystem=new B,this.swaggerSchemaResolver=new Oe(this.config,this.fileSystem),this.schemaWalker=new be(this.config,this.swaggerSchemaResolver),this.schemaComponentsMap=new me(this.config),this.typeNameFormatter=new ve(this.config),this.templatesWorker=new Ie(this.config,this.fileSystem,this.getRenderTemplateData),this.codeFormatter=new se(this.config),this.schemaParserFabric=new Fe(this.config,this.templatesWorker,this.schemaComponentsMap,this.typeNameFormatter,this.schemaWalker),this.schemaRoutes=new Ee(this.config,this.schemaParserFabric,this.schemaComponentsMap,this.templatesWorker,this.typeNameFormatter),this.javascriptTranslator=new $e(this.config,this.codeFormatter);}async start(){this.config.update({templatePaths:this.templatesWorker.getTemplatePaths(this.config)}),this.config.update({templatesToRender:this.templatesWorker.getTemplates(this.config)});let e=await this.swaggerSchemaResolver.create();this.swaggerSchemaResolver.fixSwaggerSchema(e),this.config.update({swaggerSchema:e.usageSchema,originalSchema:e.originalSchema}),this.schemaWalker.addSchema("$usage",e.usageSchema),this.schemaWalker.addSchema("$original",e.originalSchema),consola.info("start generating your typescript api"),this.config.update(this.config.hooks.onInit(this.config,this)||this.config),this.schemaComponentsMap.clear(),g.each(e.usageSchema.components,(n,c)=>g.each(n,(h,m)=>{this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components",c,m]),h);}));let s=this.schemaComponentsMap.filter(g.compact(["schemas",this.config.extractResponses&&"responses"])).map(n=>{let c=this.schemaParserFabric.parseSchema(n.rawTypeData,n.typeName);return n.typeData=c,c});this.schemaRoutes.attachSchema({usageSchema:e.usageSchema,parsedSchemas:s});let r={apiConfig:this.createApiConfig(e.usageSchema),config:this.config,modelTypes:this.collectModelTypes(),hasSecurityRoutes:this.schemaRoutes.hasSecurityRoutes,hasQueryRoutes:this.schemaRoutes.hasQueryRoutes,hasFormDataRoutes:this.schemaRoutes.hasFormDataRoutes,generateResponses:this.config.generateResponses,routes:this.schemaRoutes.getGroupedRoutes(),extraTemplates:this.config.extraTemplates,fileName:this.config.fileName,translateToJavaScript:this.config.toJS,customTranslator:this.config.customTranslator?new this.config.customTranslator:null,utils:this.getRenderTemplateData().utils},a=this.config.hooks.onPrepareConfig(r)||r;this.fileSystem.pathIsExist(this.config.output)?this.config.cleanOutput&&(consola.debug("cleaning dir",this.config.output),this.fileSystem.cleanDir(this.config.output)):(consola.debug(`path ${this.config.output} is not exist. creating dir by this path`),this.fileSystem.createDir(this.config.output));let i=await this.generateOutputFiles({configuration:a});if(this.fileSystem.pathIsDir(this.config.output))for(let n of i)this.fileSystem.createFile({path:this.config.output,fileName:`${n.fileName}${n.fileExtension}`,content:n.fileContent,withPrefix:true}),consola.success("api file",`"${n.fileName}${n.fileExtension}"`,`created in ${this.config.output}`);return {files:i,configuration:a,getTemplate:this.templatesWorker.getTemplate,renderTemplate:this.templatesWorker.renderTemplate,createFile:this.fileSystem.createFile,formatTSContent:this.codeFormatter.formatCode}}getRenderTemplateData=()=>({utils:{Ts:this.config.Ts,formatDescription:this.schemaParserFabric.schemaFormatters.formatDescription,internalCase:z,classNameCase:I,pascalCase:I,getInlineParseContent:this.schemaParserFabric.getInlineParseContent,getParseContent:this.schemaParserFabric.getParseContent,getComponentByRef:this.schemaComponentsMap.get,parseSchema:this.schemaParserFabric.parseSchema,checkAndAddNull:this.schemaParserFabric.schemaUtils.safeAddNullToType,safeAddNullToType:this.schemaParserFabric.schemaUtils.safeAddNullToType,isNeedToAddNull:this.schemaParserFabric.schemaUtils.isNullMissingInType,inlineExtraFormatters:this.schemaParserFabric.schemaFormatters.inline,formatters:this.schemaParserFabric.schemaFormatters.base,formatModelName:this.typeNameFormatter.format,fmtToJSDocLine:(e,{eol:t=true})=>` * ${e}${t?`
40
+ `:""}`,NameResolver:O,_:g,require:this.templatesWorker.requireFnFromTemplate},config:this.config});collectModelTypes=()=>{let e=this.schemaComponentsMap.getComponents(),t=[],s=g.compact(["schemas",this.config.extractResponses&&"responses"]),r=()=>this.schemaComponentsMap.filter(...s).length,a=r(),i=0;for(;i<a;){t=[],i=0;for(let o of e)if(s.includes(o.componentName)){let n=this.prepareModelType(o);n&&t.push(n),i++;}a=r();}return this.config.sortTypes?t.sort(he("name")):t};prepareModelType=e=>{if(e.$prepared)return e.$prepared;e.typeData||(e.typeData=this.schemaParserFabric.parseSchema(e.rawTypeData,e.typeName));let t=e.typeData,s=this.schemaParserFabric.schemaFormatters.base[t.type]?this.schemaParserFabric.schemaFormatters.base[t.type](t):t,{typeIdentifier:r,name:a,content:i,description:o}=s,n=this.typeNameFormatter.format(a);if(n===null)return null;let c={...s,typeIdentifier:r,name:n,description:o,$content:t.content,rawContent:t.content,content:i,typeData:s};return e.$prepared=c,c};generateOutputFiles=async({configuration:e})=>{let{modular:t,templatesToRender:s}=this.config,r=t?await this.createMultipleFileInfos(s,e):await this.createSingleFileInfo(s,e);if(!g.isEmpty(e.extraTemplates))for(let a of e.extraTemplates){let i=this.templatesWorker.renderTemplate(this.fileSystem.getFileContent(a.path),e);r.push(...await this.createOutputFileInfo(e,a.name,i));}return r.filter(a=>!!a&&!!a.fileContent)};createMultipleFileInfos=async(e,t)=>{let{routes:s}=t,{fileNames:r,generateRouteTypes:a,generateClient:i}=t.config,o=[];if(s.$outOfModule){if(a){let n=this.templatesWorker.renderTemplate(e.routeTypes,{...t,route:t.routes.$outOfModule});o.push(...await this.createOutputFileInfo(t,r.outOfModuleApi,n));}if(i){let n=this.templatesWorker.renderTemplate(e.api,{...t,route:t.routes.$outOfModule});o.push(...await this.createOutputFileInfo(t,r.outOfModuleApi,n));}}if(s.combined)for(let n of s.combined){if(a){let c=this.templatesWorker.renderTemplate(e.routeTypes,{...t,route:n});o.push(...await this.createOutputFileInfo(t,I(`${n.moduleName}_Route`),c));}if(i){let c=this.templatesWorker.renderTemplate(e.api,{...t,route:n});o.push(...await this.createOutputFileInfo(t,I(n.moduleName),c));}}return [...await this.createOutputFileInfo(t,r.dataContracts,this.templatesWorker.renderTemplate(e.dataContracts,t)),...i?await this.createOutputFileInfo(t,r.httpClient,this.templatesWorker.renderTemplate(e.httpClient,t)):[],...o]};createSingleFileInfo=async(e,t)=>{let{generateRouteTypes:s,generateClient:r}=t.config;return await this.createOutputFileInfo(t,t.fileName,g.compact([this.templatesWorker.renderTemplate(e.dataContracts,t),s&&this.templatesWorker.renderTemplate(e.routeTypes,t),r&&this.templatesWorker.renderTemplate(e.httpClient,t),r&&this.templatesWorker.renderTemplate(e.api,t)]).join(`
41
+ `))};createOutputFileInfo=async(e,t,s)=>{let r=this.fileSystem.cropExtension(t),a=d.Extension.Ts;return e.translateToJavaScript?(consola.debug("using js translator for",r),await this.javascriptTranslator.translate({fileName:r,fileExtension:a,fileContent:s})):e.customTranslator?(consola.debug("using custom translator for",r),await e.customTranslator.translate({fileName:r,fileExtension:a,fileContent:s})):(consola.debug("generating output for",`${r}${a}`),[{fileName:r,fileExtension:a,fileContent:await this.codeFormatter.formatCode(s)}])};createApiConfig=e=>{let{info:t,servers:s,host:r,basePath:a,externalDocs:i,tags:o}=e,n=s?.[0]||{url:""},{title:c="No title",version:h}=t||{},{url:m}=n;return {info:t||{},servers:s||[],basePath:a,host:r,externalDocs:g.merge({url:"",description:""},i),tags:g.compact(o),baseUrl:m,title:c,version:h}};injectClassInstance=(e,t)=>{this[e]=t;for(let s of ts)s!==e&&e in this[s]&&(this[s][e]=t);}};var De=class{cleanOutput=false;output=void 0;httpClientType=J.FETCH;modular=false;rewrite=false;silent=false;debug=false;version=Y;constructor(e){this.update(e);}update=e=>{U(this,e);}};var rs=E__default.dirname(Ct__default.fileURLToPath(import.meta.url)),_e=class{config;fileSystem;rootDir=E__default.resolve(rs,"..");paths={baseTemplates:"templates/base",httpClientTemplates:"templates/base/http-clients",moduleApiTemplates:"templates/modular",defaultApiTemplates:"templates/default"};importTemplatePrefixes=["@base","@modular","@default"];constructor(e){this.config=new De(e),this.fileSystem=new B;}async start(){consola.info('start generating source templates ".ejs" for code generator');let e=this.getTemplates();if(this.config.output){consola.info("preparing output directory for source templates");let t=E__default.resolve(process.cwd(),this.config.output);this.fileSystem.pathIsExist(t)?this.config.cleanOutput&&this.fileSystem.cleanDir(t):this.fileSystem.createDir(t);for(let s of e){let r=this.fileSystem.cropExtension(s.name),a=E__default.resolve(t,`${r}.ejs`),i=E__default.resolve(t,`${r}.eta`),o=this.fileSystem.pathIsExist(a),n=this.fileSystem.pathIsExist(i);!o&&!n?this.fileSystem.createFile({path:t,fileName:s.name,content:s.content,withPrefix:false}):this.config.rewrite&&(o?this.fileSystem.createFile({path:t,fileName:`${r}.ejs`,content:s.content,withPrefix:false}):n&&this.fileSystem.createFile({path:t,fileName:`${r}.eta`,content:s.content,withPrefix:false}));}consola.success(`source templates has been successfully created in "${t}"`);}return {files:e,configuration:this.config,createFile:this.fileSystem.createFile}}getTemplates=()=>{let e=[],t=this.getTemplateNamesFromDir(this.paths.baseTemplates),s=this.getTemplateNamesFromDir(this.paths.httpClientTemplates),r=this.config.modular?this.paths.moduleApiTemplates:this.paths.defaultApiTemplates,a=this.getTemplateNamesFromDir(r),i=s.find(n=>n.startsWith(`${this.config.httpClientType}-`)),o="";i&&(o=this.fixTemplateContent(this.getTemplateContent(`${this.paths.httpClientTemplates}/${i}`)));for(let n of t){let c=n==="http-client.ejs"&&o||this.fixTemplateContent(this.getTemplateContent(`${this.paths.baseTemplates}/${n}`));e.push({name:n,content:c});}for(let n of a)e.push({name:n,content:this.fixTemplateContent(this.getTemplateContent(`${r}/${n}`))});return e};fixTemplateContent=e=>{let t=new RegExp(`includeFile\\("(${this.importTemplatePrefixes.map(a=>`(${a})`).join("|")})/`,"g"),s=new RegExp(`includeFile\\(\`(${this.importTemplatePrefixes.map(a=>`(${a})`).join("|")})/`,"g"),r=new RegExp(`includeFile\\('(${this.importTemplatePrefixes.map(a=>`(${a})`).join("|")})/`,"g");return e.replace(t,'includeFile("./').replace(s,"includeFile(`./").replace(r,"includeFile('./")};getTemplateNamesFromDir=e=>this.fileSystem.readDir(E__default.resolve(this.rootDir,e)).filter(t=>t.endsWith(".ejs"));getTemplateContent=e=>this.fileSystem.getFileContent(E__default.resolve(this.rootDir,e))};async function as(p){return p.debug&&(consola.level=Number.MAX_SAFE_INTEGER),p.silent&&(consola.level=0),await new _e(p).start()}async function vi(p){return p.debug&&(consola.level=Number.MAX_SAFE_INTEGER),p.silent&&(consola.level=0),await new je(p).start()}export{mt as a,J as b,ne as c,oe as d,De as e,as as f,vi as g};//# sourceMappingURL=chunk-WJYL7LUK.js.map
42
+ //# sourceMappingURL=chunk-WJYL7LUK.js.map