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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # swagger-typescript-api
2
2
 
3
+ ## 13.0.27
4
+
5
+ ### Patch Changes
6
+
7
+ - [#1113](https://github.com/acacode/swagger-typescript-api/pull/1113) [`bdb3277`](https://github.com/acacode/swagger-typescript-api/commit/bdb3277302e566bbe182bd13c3ff22f07bd14aa6) Thanks [@smorimoto](https://github.com/smorimoto)! - Add `shims` option in tsup configuration and update `rootDir` path in templates generation process.
8
+
9
+ - [#1051](https://github.com/acacode/swagger-typescript-api/pull/1051) [`1fe8e24`](https://github.com/acacode/swagger-typescript-api/commit/1fe8e249993642a3fe5cc8da47ef4288421f9774) Thanks [@yepninja](https://github.com/yepninja)! - Resolve internal references in Swagger v2 to OpenAPI v3 conversion by adding `resolveInternal` option and enhancing type definitions for request payloads.
10
+
11
+ - [#1118](https://github.com/acacode/swagger-typescript-api/pull/1118) [`00f8995`](https://github.com/acacode/swagger-typescript-api/commit/00f8995f621521e2c0b66ca1660cb3d839f81bc8) Thanks [@smorimoto](https://github.com/smorimoto)! - Fix default value for `no-client` option in `generateCommand` to `false`.
12
+
13
+ - [#1113](https://github.com/acacode/swagger-typescript-api/pull/1113) [`28d43b4`](https://github.com/acacode/swagger-typescript-api/commit/28d43b49604f6fa00155a4e4ac95322d5ca86713) Thanks [@smorimoto](https://github.com/smorimoto)! - Add `required` property to output path in `generateTemplatesCommand`.
14
+
15
+ - [#1069](https://github.com/acacode/swagger-typescript-api/pull/1069) [`c06af2e`](https://github.com/acacode/swagger-typescript-api/commit/c06af2e3cf9b03aa37e3652d5312975bb1292d28) Thanks [@yangdan8](https://github.com/yangdan8)! - Fix documentation and type definition to align with actual implementation by renaming `name` to `fileName`.
16
+
3
17
  ## 13.0.26
4
18
 
5
19
  ### Patch Changes
package/README.md CHANGED
@@ -84,7 +84,7 @@ import { generateApi, generateTemplates } from "swagger-typescript-api";
84
84
 
85
85
  /* NOTE: all fields are optional expect one of `input`, `url`, `spec` */
86
86
  generateApi({
87
- name: "MySuperbApi.ts",
87
+ fileName: "MySuperbApi.ts",
88
88
  // set to `false` to prevent the tool from writing to disk
89
89
  output: path.resolve(process.cwd(), "./src/__generated__"),
90
90
  url: "http://api.com/swagger.json",
@@ -1,5 +1,5 @@
1
- 'use strict';var consola=require('consola'),f=require('lodash'),g=require('typescript'),at=require('prettier'),pt=require('cosmiconfig'),ut=require('nanoid'),dt=require('js-yaml'),Tt=require('swagger2openapi'),F=require('path'),Pt=require('url'),St=require('eta'),C=require('fs');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var f__default=/*#__PURE__*/_interopDefault(f);var g__namespace=/*#__PURE__*/_interopNamespace(g);var at__namespace=/*#__PURE__*/_interopNamespace(at);var pt__namespace=/*#__PURE__*/_interopNamespace(pt);var ut__namespace=/*#__PURE__*/_interopNamespace(ut);var dt__namespace=/*#__PURE__*/_interopNamespace(dt);var Tt__namespace=/*#__PURE__*/_interopNamespace(Tt);var F__namespace=/*#__PURE__*/_interopNamespace(F);var Pt__namespace=/*#__PURE__*/_interopNamespace(Pt);var St__namespace=/*#__PURE__*/_interopNamespace(St);var C__namespace=/*#__PURE__*/_interopNamespace(C);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__namespace.createLanguageService(s).organizeImports({type:"file",fileName:t},{newLineCharacter:g__namespace.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__namespace.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__namespace.findConfigFile(e,g__namespace.sys.fileExists);this.compilerOptions=s?g__namespace.convertCompilerOptionsFromJson(g__namespace.readConfigFile(s,g__namespace.sys.readFile).config.compilerOptions,"").options:g__namespace.getDefaultCompilerOptions();}getNewLine(){return "newLine"in g__namespace.sys?g__namespace.sys.newLine:`
2
- `}getScriptFileNames(){return [this.fileName]}getCompilationSettings(){return this.compilerOptions}getDefaultLibFileName(){return g__namespace.getDefaultLibFileName(this.getCompilationSettings())}getCurrentDirectory(){return process.cwd()}getScriptVersion(){return g__namespace.version}getScriptSnapshot(){return g__namespace.ScriptSnapshot.fromString(this.content)}readFile(e,t){return e===this.fileName?this.content:g__namespace.sys.readFile(e,t)}fileExists(e){return g__namespace.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__default.default.uniq(f__default.default.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.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__default.default.uniq(f__default.default.compact(e));for(let o of i)!a&&(!r||!this.isReserved(o))&&(a=o);return a?(r&&this.reserve([a]),a):(consola.consola.debug("trying to resolve name with using fallback name generator using variants",...e),this.resolve(e,this.getFallbackName,s))}return consola.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.consola.debug("generated dirty resolved type name for component - ",o),o}let a=`${this.config.componentTypeNameResolver}${this.fallbackNameCounter++}`;return consola.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
+ 'use strict';var consola=require('consola'),u=require('lodash'),y=require('typescript'),it=require('prettier'),ht=require('cosmiconfig'),gt=require('nanoid'),Tt=require('js-yaml'),Pt=require('swagger2openapi'),x=require('path'),St=require('url'),Ct=require('eta'),N=require('fs');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var u__default=/*#__PURE__*/_interopDefault(u);var y__namespace=/*#__PURE__*/_interopNamespace(y);var it__namespace=/*#__PURE__*/_interopNamespace(it);var ht__namespace=/*#__PURE__*/_interopNamespace(ht);var gt__namespace=/*#__PURE__*/_interopNamespace(gt);var Tt__namespace=/*#__PURE__*/_interopNamespace(Tt);var Pt__namespace=/*#__PURE__*/_interopNamespace(Pt);var x__namespace=/*#__PURE__*/_interopNamespace(x);var St__namespace=/*#__PURE__*/_interopNamespace(St);var Ct__namespace=/*#__PURE__*/_interopNamespace(Ct);var N__namespace=/*#__PURE__*/_interopNamespace(N);var Dt=Object.defineProperty;var _t=(p,e)=>{for(var t in e)Dt(p,t,{get:e[t],enumerable:true});};var Kt=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href,f=Kt();var te=class{config;constructor(e){this.config=e;}removeUnusedImports=e=>{let t="file.ts",s=new Ue(t,e),a=y__namespace.createLanguageService(s).organizeImports({type:"file",fileName:t},{newLineCharacter:y__namespace.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 it__namespace.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=y__namespace.findConfigFile(e,y__namespace.sys.fileExists);this.compilerOptions=s?y__namespace.convertCompilerOptionsFromJson(y__namespace.readConfigFile(s,y__namespace.sys.readFile).config.compilerOptions,"").options:y__namespace.getDefaultCompilerOptions();}getNewLine(){return "newLine"in y__namespace.sys?y__namespace.sys.newLine:`
2
+ `}getScriptFileNames(){return [this.fileName]}getCompilationSettings(){return this.compilerOptions}getDefaultLibFileName(){return y__namespace.getDefaultLibFileName(this.getCompilationSettings())}getCurrentDirectory(){return process.cwd()}getScriptVersion(){return y__namespace.version}getScriptSnapshot(){return y__namespace.ScriptSnapshot.fromString(this.content)}readFile(e,t){return e===this.fileName?this.content:y__namespace.sys.readFile(e,t)}fileExists(e){return y__namespace.sys.fileExists(e)}};var A=class{reservedNames=[];getFallbackName;config;constructor(e,t,s){this.config=e,this.getFallbackName=s,this.reserve(t);}reserve(e){let t=u__default.default.uniq(u__default.default.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.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=u__default.default.uniq(u__default.default.compact(e));for(let o of i)!a&&(!r||!this.isReserved(o))&&(a=o);return a?(r&&this.reserve([a]),a):(consola.consola.debug("trying to resolve name with using fallback name generator using variants",...e),this.resolve(e,this.getFallbackName,s))}return consola.consola.debug("problem with reserving names. current reserved names: ",...this.reservedNames),null}};var Ut=(p=0,e=1)=>Math.random()*(e-p)+p,nt=(p=0,e=1)=>p===e?p:Math.round(Ut(p,e));var re=class extends A{counter=1;fallbackNameCounter=1;countersByVariant=new Map;constructor(e,t){super(e,t,s=>{let r=s[nt(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.consola.debug("generated dirty resolved type name for component - ",o),o}let a=`${this.config.componentTypeNameResolver}${this.fallbackNameCounter++}`;return consola.consola.debug("generated fallback type name for component - ",a),a});}};var ie={};_t(ie,{DEFAULT_BODY_ARG_NAME:()=>Ge,FILE_PREFIX:()=>Gt,HTTP_CLIENT:()=>H,PRETTIER_OPTIONS:()=>ae,PROJECT_VERSION:()=>J,RESERVED_BODY_ARG_NAMES:()=>We,RESERVED_HEADER_ARG_NAMES:()=>Ve,RESERVED_PATH_ARG_NAMES:()=>Be,RESERVED_QUERY_ARG_NAMES:()=>Le,RESERVED_REQ_PARAMS_ARG_NAMES:()=>Wt,SCHEMA_TYPES:()=>l});var ct={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 Ge="data",Gt=`/* eslint-disable */
3
3
  /* tslint:disable */
4
4
  // @ts-nocheck
5
5
  /*
@@ -11,20 +11,20 @@
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__default.default.map(t,(r,a)=>r===void 0&&a).filter(r=>typeof r=="string");Object.assign(p,f__default.default.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__namespace.ModuleKind.ESNext,noImplicitReturns:true,alwaysStrict:true,target:g__namespace.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__default.default.join(f__default.default.uniq(e),` ${this.Ts.Keyword.Union} `),ExpressionGroup:e=>e?`(${e})`:"",IntersectionType:e=>f__default.default.join(f__default.default.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__default.default.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__default.default.map(e,({key:t,value:s})=>` ${this.Ts.EnumField(t,s)}`).join(`,
14
+ `,H={FETCH:"fetch",AXIOS:"axios"},ae={printWidth:120,tabWidth:2,trailingComma:"all",parser:"typescript"},J=ct.version,We=["data","body","reqBody"],Ve=["headers","headersParams"],Be=["path","pathParams"],Le=["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=u__default.default.map(t,(r,a)=>r===void 0&&a).filter(r=>typeof r=="string");Object.assign(p,u__default.default.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"},ne=class{version=J;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={...ae};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=H.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:y__namespace.ModuleKind.ESNext,noImplicitReturns:true,alwaysStrict:true,target:y__namespace.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=>u__default.default.join(u__default.default.uniq(e),` ${this.Ts.Keyword.Union} `),ExpressionGroup:e=>e?`(${e})`:"",IntersectionType:e=>u__default.default.join(u__default.default.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})=>u__default.default.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=>u__default.default.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__default.default.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__namespace.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__default.default.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__default.default.get(e,["schemaType"])||f__default.default.get(e,["$parsed","schemaType"]);return f__default.default.get(this,[t,s])?.(e)||e};formatDescription=(e,t)=>e?e.includes(`
19
- `)?t?f__default.default._(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=pt(),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?pt():e,hooks:u__default.default.merge(this.hooks,i||{}),constants:{...ie,...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 re(this,[]);}update=e=>{U(this,e);}},pt=()=>{let p=ht__namespace.cosmiconfigSync("prettier",{searchStrategy:"global"}).search();return p?{...p.config,parser:"typescript"}:{...ae}};var ce=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 me=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(u__default.default.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=u__default.default.get(e,["schemaType"])||u__default.default.get(e,["$parsed","schemaType"]);return u__default.default.get(this,[t,s])?.(e)||e};formatDescription=(e,t)=>e?e.includes(`
19
+ `)?t?u__default.default._(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__default.default.omit(f__default.default.clone(this.schema),f__default.default.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__default.default.compact(f__default.default.map(this.schema[e],"description"))[0]||""),content:this.config.Ts.IntersectionType(f__default.default.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__default.default.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__default.default.get(e?.component?.rawTypeData,["properties",t]);return this.schemaUtils.isRefSchema(a)&&(a=this.schemaUtils.getSchemaRefType(a)),a?.rawTypeData?.$parsed?.type===l.ENUM&&(r=f__default.default.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__default.default.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__default.default.keys(this.schemaParser._complexSchemaParsers),r=f__default.default.omit(structuredClone(t),s),a=this.schemaParserFabric.getInlineParseContent(structuredClone(r))===this.config.Ts.Keyword.Any;if(!f__default.default.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.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__default.default.size(a)?i=a.map((n,c)=>{let h=f__default.default.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__default.default.map(t,(a,i)=>{let o=this.schemaUtils.isPropertyRequired(i,a,e),n=f__default.default.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__default.default.compact(f__default.default.map(a[this.schemaUtils.getComplexType(a)],"description"))[0]||n.description||f__default.default.compact(f__default.default.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.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__default.default.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__default.default.first(f__default.default.values(t)),a=f__default.default.get(r,"schema");if(a)return {...s,...f__default.default.omit(r,"schema"),...a}}};function X(p){return f__default.default.camelCase(f__default.default.lowerCase(p))}function A(p){return f__default.default.upperFirst(f__default.default.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__default.default.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__default.default.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__default.default.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__default.default.uniq([...this.getRequiredProperties(e),...this.getRequiredProperties(t)]),r=this.getSchemaRefType(t);if(r){let i=f__default.default.keys(r.rawTypeData?.properties||{}).filter(o=>s.includes(o));return i.length?{...t,$$requiredKeys:i}:t}if(t.properties){let i=f__default.default.keys(t.properties).filter(o=>s.includes(o));return i.length?{required:f__default.default.uniq([...this.getRequiredProperties(t),...i]),...t}:t}return t};filterSchemaContents=(e,t)=>f__default.default.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__default.default.isEmpty(e.enum)||!f__default.default.isEmpty(this.getEnumNames(e))?l.ENUM:e.discriminator?l.DISCRIMINATOR:e.allOf||e.oneOf||e.anyOf||e.not?l.COMPLEX:f__default.default.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__default.default.get(this.config.primitiveTypes,[r,e.format])||f__default.default.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__default.default.uniq(f__default.default.compact(e)),!e||!e[0]?null:A(f__default.default.camelCase(f__default.default.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__namespace.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.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__default.default.uniq([this.schemaUtils.getSchemaType({type:"string",format:"file"}),this.schemaUtils.getSchemaType({type:"string",format:"binary"})]);}createRequestsMap=e=>{let t=f__default.default.get(e,"parameters");return f__default.default.reduce(e,(s,r,a)=>(a.startsWith("x-")||["parameters","$ref"].includes(a)||(s[a]={...r,parameters:f__default.default.compact(f__default.default.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__default.default.reduce(s,(c,h)=>{let m=h.replace(/\{|\}|:/g,"");return m&&(m.includes("-")&&consola.consola.warn("wrong path param name",m),c.push({$match:h,name:f__default.default.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__default.default.uniq(i.join(",").replace(/(\{\?)|(\})|\s/g,"").split(","));for(let h of c)h.includes("-")&&consola.consola.warn("wrong query param name",h),o.push({$match:h,name:f__default.default.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__default.default.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__default.default.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__default.default.uniq(f__default.default.compact([...t||[],...f__default.default.flatten(f__default.default.map(e,s=>s&&f__default.default.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__default.default.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__default.default.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__default.default.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__default.default.reduce(f__default.default.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__default.default.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.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__default.default.camelCase(Qe):f__default.default.camelCase(f__default.default.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__default.default.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__default.default.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__default.default.each(t.combined,s=>{s.routes=this.sortRoutes(s.routes);})),t};sortRoutes=e=>f__default.default.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__default.default.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__default.default.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.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__default.default.merge({title:"No title",version:""},r.info),Object.hasOwn(r,"openapi")?s({usageSchema:r,originalSchema:structuredClone(r)}):(r.paths=f__default.default.merge({},r.paths),Tt__namespace.convertObj(r,{...t,warnOnly:true,refSiblings:"preserve",rbname:"requestBodyName"},(a,i)=>{let o=f__default.default.get(a,"options.openapi",f__default.default.get(i,"openapi"));if(!o&&a)throw a;this.config.update({convertedFromSwagger2:true}),s({usageSchema:o,originalSchema:r});}));})}getSwaggerSchemaByPath=e=>(consola.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.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__namespace.load(e)}}fixSwaggerSchema({usageSchema:e,originalSchema:t}){let s=f__default.default.get(e,"paths"),r=f__default.default.get(t,"paths");f__default.default.each(s,(a,i)=>{let o=f__default.default.get(r,i);f__default.default.each(a,(n,c)=>{let h=f__default.default.get(o,c),m=f__default.default.get(n,"parameters",[]),u=f__default.default.get(h,"parameters",[]);typeof n=="object"&&(n.consumes=f__default.default.uniq(f__default.default.compact([...n.consumes||[],...h.consumes||[]])),n.produces=f__default.default.uniq(f__default.default.compact([...n.produces||[],...h.produces||[]]))),f__default.default.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.consola.level=Number.MAX_SAFE_INTEGER),this.config.silent&&(consola.consola.level=0);}getTemplatePaths=e=>{let t=F__namespace.dirname(Pt__namespace.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-LI5RQUAL.cjs', document.baseURI).href)))),s=F__namespace.resolve(t,"../templates/base"),r=F__namespace.resolve(t,"../templates/default"),a=F__namespace.resolve(t,"../templates/modular"),i=e.modular?a:r,o=e.templates&&F__namespace.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__namespace.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__namespace.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.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.consola.warn("Code generator will use the default template:",`"${e.toLowerCase()}"`,"template not found in",`"${r.custom}"`):consola.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.consola.info(`try to read templates from directory "${e.custom}"`),f__default.default.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__default.default.keys(this.config.templatePaths).find(a=>e.startsWith(`@${a}`));if(t){let a=F__namespace.resolve(e.replace(`@${t}`,f__default.default.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__namespace.resolve(this.config.templatePaths.custom,e));if(s)return this.fileSystem.getFileContent(s);let r=this.findTemplateWithExt(F__namespace.resolve(this.config.templatePaths.original,e));return r?this.fileSystem.getFileContent(r):""};renderTemplate=(e,t,s={})=>e?St__namespace.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__namespace.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__namespace.createSourceFile(o,e.fileContent,n,true,g__namespace.ScriptKind.TS),r.writeFile=(o,n)=>{s[o]=n;},g__namespace.createProgram(a,this.config.compilerTsConfig,r).emit(),s};translate=async e=>{let t=this.compileTSCode(e),s=`${e.fileName}${g__namespace.Extension.Js}`,r=`${e.fileName}${g__namespace.Extension.Dts}`,a=t[s],i=e.fileContent.split(`
22
+ `);o?t.push(`${o}${a}`):t.push(`${a}`);}return t.join("")}};var pe=p=>(e,t)=>e[p]>t[p]?1:e[p]<t[p]?-1:0;var d=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 he=class extends d{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 le=class extends d{parse(){let e=this.schemaUtils.getComplexType(this.schema),t=u__default.default.omit(u__default.default.clone(this.schema),u__default.default.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||u__default.default.compact(u__default.default.map(this.schema[e],"description"))[0]||""),content:this.config.Ts.IntersectionType(u__default.default.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 fe=class extends d{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=u__default.default.entries(a.mapping),o=!e&&!!(t?.typeName&&i.length),n=[],c,h=this.createMappingPropertySchemaEnumKeys({abstractSchemaStruct:t,discPropertyName:a.propertyName});if(o){let T=`${t.typeName}_${a.propertyName}`,P=this.schemaUtils.resolveTypeName(T,{suffixes:this.config.extractingOptions.discriminatorMappingSuffix,resolver:this.config.extractingOptions.discriminatorMappingNameResolver}),R=s.IntersectionType([s.ObjectWrapper(s.TypeField({key:s.StringValue(a.propertyName),value:"Key"})),"Type"]),b=this.schemaParserFabric.createParsedComponent({typeName:P,schema:{type:"object",properties:{},genericArgs:[{name:"Key"},{name:"Type"}],internal:true}});b.typeData.content=R,c=this.typeNameFormatter.format(b.typeName);}let m=(T,P)=>{let R=this.schemaParserFabric.createSchemaParser({schema:T,schemaPath:this.schemaPath}).getInlineParseContent(),b=h[P]||s.StringValue(P);return o?s.TypeWithGeneric(c,[b,R]):s.ExpressionGroup(s.IntersectionType([s.ObjectWrapper(s.TypeField({key:a.propertyName,value:b})),R]))};for(let[T,P]of i){let R=typeof P=="string"?{$ref:P}:P;this.mutateMappingDependentSchema({discPropertyName:a.propertyName,abstractSchemaStruct:t,mappingSchema:R,refPath:r,mappingPropertySchemaEnumKeysMap:h}),n.push(m(R,T));}return e?null:{content:s.ExpressionGroup(s.UnionType(n))}};createMappingPropertySchemaEnumKeys=({abstractSchemaStruct:e,discPropertyName:t})=>{let s=this.config.Ts,r={},a=u__default.default.get(e?.component?.rawTypeData,["properties",t]);return this.schemaUtils.isRefSchema(a)&&(a=this.schemaUtils.getSchemaRefType(a)),a?.rawTypeData?.$parsed?.type===l.ENUM&&(r=u__default.default.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=u__default.default.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=u__default.default.keys(this.schemaParser._complexSchemaParsers),r=u__default.default.omit(structuredClone(t),s),a=this.schemaParserFabric.getInlineParseContent(structuredClone(r))===this.config.Ts.Keyword.Any;if(!u__default.default.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 ue=class extends A{counter=1;constructor(e,t){super(e,t,s=>{let r=s[0]&&`${s[0]}${this.counter++}`||`${this.config.enumKeyResolverName}${this.counter++}`;return consola.consola.debug("generated fallback type name for enum key - ",r),r});}};var ge=class extends d{enumKeyResolver;constructor(...e){super(...e),this.enumKeyResolver=new ue(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)&&u__default.default.size(a)?i=a.map((n,c)=>{let h=u__default.default.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 ye=class extends d{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=u__default.default.map(t,(a,i)=>{let o=this.schemaUtils.isPropertyRequired(i,a,e),n=u__default.default.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(),g=a.readOnly;return {...a,$$raw:a,title:a.title,description:a.description||u__default.default.compact(u__default.default.map(a[this.schemaUtils.getComplexType(a)],"description"))[0]||n.description||u__default.default.compact(u__default.default.map(n[this.schemaUtils.getComplexType(n)],"description"))[0]||"",isRequired:o,isNullable:c,name:h,value:m,field:this.config.Ts.TypeField({readonly:g&&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 de=class extends d{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 Te=class extends d{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 Pe=class extends d{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 Se=class extends d{parse(){return this.config.Ts.Keyword.Any}};var Ce=class extends d{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 Ne=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||Ce;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_ALL_OF]:e=>{let t=this.config.schemaParsers.complexAllOf||Te;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_ANY_OF]:e=>{let t=this.config.schemaParsers.complexAnyOf||Pe;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_NOT]:e=>{let t=this.config.schemaParsers.complexNot||Se;return new t(this,e,null,this.schemaPath).parse()}};_baseSchemaParsers={[l.ENUM]:(e,t)=>{let s=this.config.schemaParsers.enum||ge;return new s(this,e,t,this.schemaPath).parse()},[l.OBJECT]:(e,t)=>{let s=this.config.schemaParsers.object||ye;return new s(this,e,t,this.schemaPath).parse()},[l.COMPLEX]:(e,t)=>{let s=this.config.schemaParsers.complex||le;return new s(this,e,t,this.schemaPath).parse()},[l.PRIMITIVE]:(e,t)=>{let s=this.config.schemaParsers.primitive||de;return new s(this,e,t,this.schemaPath).parse()},[l.DISCRIMINATOR]:(e,t)=>{let s=this.config.schemaParsers.discriminator||fe;return new s(this,e,t,this.schemaPath).parse()},[l.ARRAY]:(e,t)=>{let s=this.config.schemaParsers.array||he;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.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),u__default.default.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(pe("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=u__default.default.first(u__default.default.values(t)),a=u__default.default.get(r,"schema");if(a)return {...s,...u__default.default.omit(r,"schema"),...a}}};function Q(p){return u__default.default.camelCase(u__default.default.lowerCase(p))}function O(p){return u__default.default.upperFirst(u__default.default.camelCase(p))}var Re=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=>u__default.default.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||!!u__default.default.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 Q(t.type);if(t.enum){let s=typeof t.enum[0];return s===this.config.Ts.Keyword.Undefined?void 0:Q(s)}return u__default.default.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=u__default.default.uniq([...this.getRequiredProperties(e),...this.getRequiredProperties(t)]),r=this.getSchemaRefType(t);if(r){let i=u__default.default.keys(r.rawTypeData?.properties||{}).filter(o=>s.includes(o));return i.length?{...t,$$requiredKeys:i}:t}if(t.properties){let i=u__default.default.keys(t.properties).filter(o=>s.includes(o));return i.length?{required:u__default.default.uniq([...this.getRequiredProperties(t),...i]),...t}:t}return t};filterSchemaContents=(e,t)=>u__default.default.uniq(e.filter(s=>t(s)));resolveTypeName=(e,{suffixes:t,resolver:s,prefixes:r,shouldReserve:a=true})=>s?this.config.componentTypeNameResolver.resolve([],i=>s(O(e),i)):this.config.componentTypeNameResolver.resolve([...(r||[]).map(i=>O(`${i} ${e}`)),...(t||[]).map(i=>O(`${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=>!u__default.default.isEmpty(e.enum)||!u__default.default.isEmpty(this.getEnumNames(e))?l.ENUM:e.discriminator?l.DISCRIMINATOR:e.allOf||e.oneOf||e.anyOf||e.not?l.COMPLEX:u__default.default.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=u__default.default.get(this.config.primitiveTypes,[r,e.format])||u__default.default.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=u__default.default.uniq(u__default.default.compact(e)),!e||!e[0]?null:O(u__default.default.camelCase(u__default.default.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 we=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 Re(this),this.schemaFormatters=new me(this);}createSchemaParser=({schema:e,typeName:t,schemaPath:s})=>new Ne(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",yt=gt__namespace.customAlphabet(Jt,12);var Fe=class extends A{counter=1;constructor(e,t){super(e,t,s=>{let r=s[0]&&`${s[0]}${this.counter++}`||`${this.config.specificArgNameResolverName}${this.counter++}`;return consola.consola.debug("generated fallback type name for specific arg - ",r),r});}};var E={JSON:"JSON",URL_ENCODED:"URL_ENCODED",FORM_DATA:"FORM_DATA",IMAGE:"IMAGE",OTHER:"OTHER",TEXT:"TEXT"},xe=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=u__default.default.uniq([this.schemaUtils.getSchemaType({type:"string",format:"file"}),this.schemaUtils.getSchemaType({type:"string",format:"binary"})]);}createRequestsMap=e=>{let t=u__default.default.get(e,"parameters");return u__default.default.reduce(e,(s,r,a)=>(a.startsWith("x-")||["parameters","$ref"].includes(a)||(s[a]={...r,parameters:u__default.default.compact(u__default.default.concat(t,r.parameters))}),s),{})};parseRouteName=e=>{let t=this.config.hooks.onPreBuildRoutePath(e)||e,s=(t||"").match(/({[\w[\\\]^`][-_.\w]*})|(:[\w[\\\]^`][-_.\w]*:?)/g),r=u__default.default.reduce(s,(c,h)=>{let m=h.replace(/\{|\}|:/g,"");return m&&(m.includes("-")&&consola.consola.warn("wrong path param name",m),c.push({$match:h,name:u__default.default.camelCase(m),required:true,type:"string",description:"",schema:{type:"string"},in:"path"})),c},[]),a=r.reduce((c,h,m,g)=>{let T=this.config.hooks.onInsertPathParam(h.name,m,g,c)||h.name;return c.replace(h.$match,`\${${T}}`)},t||""),i=a.match(/(\{\?.*\})/g),o=[];if(i?.length){for(let h of i)a=a.replace(h,"");let c=u__default.default.uniq(i.join(",").replace(/(\{\?)|(\})|\s/g,"").split(","));for(let h of c)h.includes("-")&&consola.consola.warn("wrong query param name",h),o.push({$match:h,name:u__default.default.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:[]};u__default.default.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=u__default.default.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)=>u__default.default.uniq(u__default.default.compact([...t||[],...u__default.default.flatten(u__default.default.map(e,s=>s&&u__default.default.keys(s.content)))]));getContentKind=e=>e.some(t=>t.startsWith("application/json"))||e.some(t=>t.endsWith("+json"))?E.JSON:e.includes("application/x-www-form-urlencoded")?E.URL_ENCODED:e.includes("multipart/form-data")?E.FORM_DATA:e.some(t=>t.includes("image/"))?E.IMAGE:e.some(t=>t.startsWith("text/"))?E.TEXT:E.OTHER;isSuccessStatus=e=>this.config.defaultResponseAsSuccess&&e==="default"||+e>=this.config.successResponseStatusRange[0]&&+e<=this.config.successResponseStatusRange[1]||e==="2xx";getSchemaFromRequestType=e=>{let t=u__default.default.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(g=>this.typeNameFormatter.format(g.name)===n),h=t.find(g=>u__default.default.isEqual(g.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})=>u__default.default.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 g=Object.fromEntries(Object.entries(m).map(([P,R])=>[P,this.schemaUtils.getSchemaType(R)]));return `headers: { ${Object.entries(g).map(([P,R])=>`"${P}": ${R}`).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"]]),g=this.getContentKind(m),T=null;return this.config.extractRequestBody&&(T=this.schemaUtils.resolveTypeName(r.usage,{suffixes:this.config.extractingOptions.requestBodySuffix,resolver:this.config.extractingOptions.requestBodyNameResolver})),t.formData.length?(g=E.FORM_DATA,c=this.convertRouteParamsIntoObject(t.formData),h=this.schemaParserFabric.getInlineParseContent(c,T,[n])):g===E.FORM_DATA?(c=this.getSchemaFromRequestType(a),h=this.schemaParserFabric.getInlineParseContent(c,T,[n])):a&&(c=this.getSchemaFromRequestType(a),h=this.schemaParserFabric.schemaUtils.safeAddNullToType(a,this.getTypeFromRequestInfo({requestInfo:a,parsedSchemas:s,operationId:n,typeName:T})),this.FORM_DATA_TYPES.some(P=>h.includes(`: ${P}`))&&(g=E.FORM_DATA)),c&&!c.$ref&&this.config.extractRequestBody&&(c=this.schemaParserFabric.createParsedComponent({schema:c,typeName:T,schemaPath:[n]}),c?.typeData&&(c.typeData.isExtractedRequestBody=true),h=this.schemaParserFabric.getInlineParseContent({$ref:c.$ref})),{paramName:o||a?.name||Ge,contentTypes:m,contentKind:g,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=u__default.default.reduce(u__default.default.get(t,"properties",{}),(h,m,g)=>(g&&typeof m=="object"&&(h[g]={...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&&u__default.default.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.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:g,parameters:T,summary:P,description:R,tags:b,responses:Et,requestBodyName:is,produces:bt,consumes:At,...Ot}=t,{route:Qe,pathParams:It,queryParams:$t}=this.parseRouteName(e),Mt=yt(),ze=b&&b.length>0?b[0]:null,Ze=n&&ze?u__default.default.camelCase(ze):u__default.default.camelCase(u__default.default.compact(Qe.split("/"))[o]),et=!!i?.length;g&&(et=g.length>0);let F=this.getRouteParams(t,It,$t),z=F.path.map(k=>({name:k.name,optional:!k.required,type:this.config.Ts.Keyword.Any,description:k.description})),vt=z.map(k=>k.name),I=this.getResponseBodyInfo(t,a),tt={...Ot,pathArgs:z,operationId:h,method:s,route:e,moduleName:Ze,responsesTypes:I.responses,description:R,tags:b,summary:P,responses:Et,produces:bt,requestBody:m,consumes:At,security:g},Z=this.convertRouteParamsIntoObject(F.query),_e=this.convertRouteParamsIntoObject(F.path),Ke=this.convertRouteParamsIntoObject(F.header),$=this.getRouteName(tt),M=this.getRequestBodyInfo(t,F,a,$),kt=this.createRequestParamsSchema({queryParams:F.query,pathArgsSchemas:F.path,queryObjectSchema:Z,extractRequestParams:c,routeName:$});this.config.extractResponseBody&&this.extractResponseBodyIfItNeeded(t,I,$),this.config.extractResponseError&&this.extractResponseErrorIfItNeeded(t,I,$);let ee=this.schemaUtils.resolveTypeName($.usage,{suffixes:this.config.extractingOptions.requestParamsSuffix,resolver:this.config.extractingOptions.requestParamsNameResolver,shouldReserve:false}),st=F.query.length?this.schemaParserFabric.getInlineParseContent(Z,null,[ee]):null,rt=F.path.length?this.schemaParserFabric.getInlineParseContent(_e,null,[ee]):null,at=F.header.length?this.schemaParserFabric.getInlineParseContent(Ke,null,[ee]):null,B=new Fe(this.config,vt),L={query:st?{name:B.resolve(Le),optional:this.schemaParserFabric.parseSchema(Z,null,[$.usage]).allFieldsAreOptional,type:st}:void 0,body:M.type?{name:B.resolve([M.paramName,...We]),optional:!M.required,type:M.type}:void 0,pathParams:rt?{name:B.resolve(Be),optional:this.schemaParserFabric.parseSchema(_e,null,[$.usage]).allFieldsAreOptional,type:rt}:void 0,headers:at?{name:B.resolve(Ve),optional:this.schemaParserFabric.parseSchema(Ke,null,[$.usage]).allFieldsAreOptional,type:at}:void 0};return z.forEach((k,jt)=>{k.type=this.schemaParserFabric.getInlineParseContent(F.path[jt].schema,null,[ee]);}),{id:Mt,namespace:Ze.replace(/^(\d)/,"v$1"),routeName:$,routeParams:F,requestBodyInfo:M,responseBodyInfo:I,specificArgs:L,queryObjectSchema:Z,pathObjectSchema:_e,headersObjectSchema:Ke,responseBodySchema:I.success.schema,requestBodySchema:M.schema,specificArgNameResolver:B,request:{contentTypes:M.contentTypes,parameters:z,path:Qe,formData:M.contentKind===E.FORM_DATA,isQueryBody:M.contentKind===E.URL_ENCODED,security:et,method:s,requestParams:kt,payload:L.body,query:L.query,pathParams:L.pathParams,headers:L.headers},response:{contentTypes:I.contentTypes,type:I.success.type,errorType:I.error.type,fullTypes:I.full.types},raw:tt}};attachSchema=({usageSchema:e,parsedSchemas:t})=>{this.config.routeNameDuplicatesMap.clear();let s=u__default.default.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=u__default.default.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&&u__default.default.each(t.combined,s=>{s.routes=this.sortRoutes(s.routes);})),t};sortRoutes=e=>u__default.default.slice(e).sort((t,s)=>t.routeName.usage.localeCompare(s.routeName.usage))};var Ee=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=u__default.default.get(e,s);return r&&this.caches.set(t,r),r}};var be=class{config;constructor(e){this.config=e;}async download({url:e,authToken:t,...s}){let r={};t&&(r.headers={Authorization:t}),u__default.default.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.consola.error(i,a),i}}};var Ae=class{config;fileSystem;request;constructor(e,t){this.config=e,this.fileSystem=t,this.request=new be(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=u__default.default.merge({title:"No title",version:""},r.info),Object.hasOwn(r,"openapi")?s({usageSchema:r,originalSchema:structuredClone(r)}):(r.paths=u__default.default.merge({},r.paths),Pt__namespace.convertObj(r,{...t,resolveInternal:true,warnOnly:true,refSiblings:"preserve",rbname:"requestBodyName"},(a,i)=>{let o=u__default.default.get(a,"options.openapi",u__default.default.get(i,"openapi"));if(!o&&a)throw a;this.config.update({convertedFromSwagger2:true}),s({usageSchema:o,originalSchema:r});}));})}getSwaggerSchemaByPath=e=>(consola.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.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 Tt__namespace.load(e)}}fixSwaggerSchema({usageSchema:e,originalSchema:t}){let s=u__default.default.get(e,"paths"),r=u__default.default.get(t,"paths");u__default.default.each(s,(a,i)=>{let o=u__default.default.get(r,i);u__default.default.each(a,(n,c)=>{let h=u__default.default.get(o,c),m=u__default.default.get(n,"parameters",[]),g=u__default.default.get(h,"parameters",[]);typeof n=="object"&&(n.consumes=u__default.default.uniq(u__default.default.compact([...n.consumes||[],...h.consumes||[]])),n.produces=u__default.default.uniq(u__default.default.compact([...n.produces||[],...h.produces||[]]))),u__default.default.each(g,T=>{m.find(R=>T.in===R.in&&T.name===R.name)||m.push(T);});});});}};var Oe=class{config;fileSystem;getRenderTemplateData;constructor(e,t,s){this.config=e,this.fileSystem=t,this.getRenderTemplateData=s,this.config.debug&&(consola.consola.level=Number.MAX_SAFE_INTEGER),this.config.silent&&(consola.consola.level=0);}getTemplatePaths=e=>{let t=x__namespace.dirname(St__namespace.fileURLToPath(f)),s=x__namespace.resolve(t,"../templates/base"),r=x__namespace.resolve(t,"../templates/default"),a=x__namespace.resolve(t,"../templates/modular"),i=e.modular?a:r,o=e.templates&&x__namespace.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=x__namespace.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(x__namespace.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.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.consola.warn("Code generator will use the default template:",`"${e.toLowerCase()}"`,"template not found in",`"${r.custom}"`):consola.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.consola.info(`try to read templates from directory "${e.custom}"`),u__default.default.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=u__default.default.keys(this.config.templatePaths).find(a=>e.startsWith(`@${a}`));if(t){let a=x__namespace.resolve(e.replace(`@${t}`,u__default.default.get(this.config.templatePaths,t))),i=this.findTemplateWithExt(a);if(i)return this.fileSystem.getFileContent(i)}let s=this.config.templatePaths.custom&&this.findTemplateWithExt(x__namespace.resolve(this.config.templatePaths.custom,e));if(s)return this.fileSystem.getFileContent(s);let r=this.findTemplateWithExt(x__namespace.resolve(this.config.templatePaths.original,e));return r?this.fileSystem.getFileContent(r):""};renderTemplate=(e,t,s={})=>e?Ct__namespace.render(e,{...this.getRenderTemplateData(),...t},{async:false,...s,includeFile:(r,a,i={})=>this.renderTemplate(this.getTemplateContent(r),a,i)}):""};var Ie=class{config;codeFormatter;constructor(e,t){this.config=e,this.codeFormatter=t;}translate(e){throw new Error("not implemented")}};var $e=class extends Ie{compileTSCode=e=>{let t=`${e.fileName}${e.fileExtension}`,s={},r=y__namespace.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):y__namespace.createSourceFile(o,e.fileContent,n,true,y__namespace.ScriptKind.TS),r.writeFile=(o,n)=>{s[o]=n;},y__namespace.createProgram(a,this.config.compilerTsConfig,r).emit(),s};translate=async e=>{let t=this.compileTSCode(e),s=`${e.fileName}${y__namespace.Extension.Js}`,r=`${e.fileName}${y__namespace.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__namespace.Extension.Js,fileContent:await this.codeFormatter.formatCode(a)},{fileName:e.fileName,fileExtension:g__namespace.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.consola.warn("wrong name of the model name",e),e;if(/^([A-Z_]{1,})$/g.test(e))return f__default.default.compact([r,e,a]).join("_");if(this.formattedModelNamesMap.has(i))return this.formattedModelNamesMap.get(i);let o=this.fixModelName(e,{type:s}),n=f__default.default.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__default.default.startCase(e).replace(/ /g,"")}return e}};var zt=`/* eslint-disable */
27
+ `);return [{fileName:e.fileName,fileExtension:y__namespace.Extension.Js,fileContent:await this.codeFormatter.formatCode(a)},{fileName:e.fileName,fileExtension:y__namespace.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.consola.warn("wrong name of the model name",e),e;if(/^([A-Z_]{1,})$/g.test(e))return u__default.default.compact([r,e,a]).join("_");if(this.formattedModelNamesMap.has(i))return this.formattedModelNamesMap.get(i);let o=this.fixModelName(e,{type:s}),n=u__default.default.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 u__default.default.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__namespace.readFileSync(e,{encoding:"utf8"});readDir=e=>C__namespace.readdirSync(e);pathIsDir=e=>{if(!e)return false;try{return C__namespace.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__namespace.rmSync=="function"?C__namespace.rmSync(e,{recursive:!0}):C__namespace.rmdirSync(e,{recursive:!0});}catch(t){consola.consola.debug("failed to remove dir",t);}};createDir=e=>{try{C__namespace.mkdirSync(e,{recursive:!0});}catch(t){consola.consola.debug("failed to create dir",t);}};cleanDir=e=>{this.removeDir(e),this.createDir(e);};pathIsExist=e=>!!e&&C__namespace.existsSync(e);createFile=({path:e,fileName:t,content:s,withPrefix:r})=>{let a=F__namespace.dirname(Pt__namespace.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-LI5RQUAL.cjs', document.baseURI).href)))),i=F__namespace.resolve(a,e,`./${t}`),o=`${r?zt:""}${s}`;return C__namespace.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.consola.info("start generating your typescript api"),this.config.update(this.config.hooks.onInit(this.config,this)||this.config),this.schemaComponentsMap.clear(),f__default.default.each(e.usageSchema.components,(n,c)=>f__default.default.each(n,(h,m)=>{this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components",c,m]),h);}));let s=this.schemaComponentsMap.filter(f__default.default.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.consola.debug("cleaning dir",this.config.output),this.fileSystem.cleanDir(this.config.output)):(consola.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.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__default.default,require:this.templatesWorker.requireFnFromTemplate},config:this.config});collectModelTypes=()=>{let e=this.schemaComponentsMap.getComponents(),t=[],s=f__default.default.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__default.default.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__default.default.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__namespace.Extension.Ts;return e.translateToJavaScript?(consola.consola.debug("using js translator for",r),await this.javascriptTranslator.translate({fileName:r,fileExtension:a,fileContent:s})):e.customTranslator?(consola.consola.debug("using custom translator for",r),await e.customTranslator.translate({fileName:r,fileExtension:a,fileContent:s})):(consola.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__default.default.merge({url:"",description:""},i),tags:f__default.default.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__namespace.default.dirname(Pt__namespace.default.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-LI5RQUAL.cjs', document.baseURI).href)))),je=class{config;fileSystem;rootDir=F__namespace.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.consola.info('start generating source templates ".ejs" for code generator');let e=this.getTemplates();if(this.config.output){consola.consola.info("preparing output directory for source templates");let t=F__namespace.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__namespace.default.resolve(t,`${r}.ejs`),i=F__namespace.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.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__namespace.default.resolve(this.rootDir,e)).filter(t=>t.endsWith(".ejs"));getTemplateContent=e=>this.fileSystem.getFileContent(F__namespace.default.resolve(this.rootDir,e))};async function ss(p){return p.debug&&(consola.consola.level=Number.MAX_SAFE_INTEGER),p.silent&&(consola.consola.level=0),await new je(p).start()}async function Va(p){return p.debug&&(consola.consola.level=Number.MAX_SAFE_INTEGER),p.silent&&(consola.consola.level=0),await new ve(p).start()}exports.a=ot;exports.b=L;exports.c=ae;exports.d=ie;exports.e=ke;exports.f=ss;exports.g=Va;//# sourceMappingURL=chunk-LI5RQUAL.cjs.map
42
- //# sourceMappingURL=chunk-LI5RQUAL.cjs.map
39
+ `,V=class{getFileContent=e=>N__namespace.readFileSync(e,{encoding:"utf8"});readDir=e=>N__namespace.readdirSync(e);pathIsDir=e=>{if(!e)return false;try{return N__namespace.statSync(e).isDirectory()}catch{return false}};cropExtension=e=>{let t=e.split(".");return t.length>1&&t.pop(),t.join(".")};removeDir=e=>{try{typeof N__namespace.rmSync=="function"?N__namespace.rmSync(e,{recursive:!0}):N__namespace.rmdirSync(e,{recursive:!0});}catch(t){consola.consola.debug("failed to remove dir",t);}};createDir=e=>{try{N__namespace.mkdirSync(e,{recursive:!0});}catch(t){consola.consola.debug("failed to create dir",t);}};cleanDir=e=>{this.removeDir(e),this.createDir(e);};pathIsExist=e=>!!e&&N__namespace.existsSync(e);createFile=({path:e,fileName:t,content:s,withPrefix:r})=>{let a=x__namespace.dirname(St__namespace.fileURLToPath(f)),i=x__namespace.resolve(a,e,`./${t}`),o=`${r?es:""}${s}`;return N__namespace.writeFileSync(i,o)}};var ts=["schemaWalker","swaggerSchemaResolver","schemaComponentsMap","typeNameFormatter","templatesWorker","codeFormatter","schemaParserFabric","schemaRoutes","javascriptTranslator"],ke=class{config;swaggerSchemaResolver;schemaComponentsMap;typeNameFormatter;schemaParserFabric;schemaRoutes;fileSystem;codeFormatter;templatesWorker;schemaWalker;javascriptTranslator;constructor(e){this.config=new ne(e),this.fileSystem=new V,this.swaggerSchemaResolver=new Ae(this.config,this.fileSystem),this.schemaWalker=new Ee(this.config,this.swaggerSchemaResolver),this.schemaComponentsMap=new ce(this.config),this.typeNameFormatter=new Me(this.config),this.templatesWorker=new Oe(this.config,this.fileSystem,this.getRenderTemplateData),this.codeFormatter=new te(this.config),this.schemaParserFabric=new we(this.config,this.templatesWorker,this.schemaComponentsMap,this.typeNameFormatter,this.schemaWalker),this.schemaRoutes=new xe(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.consola.info("start generating your typescript api"),this.config.update(this.config.hooks.onInit(this.config,this)||this.config),this.schemaComponentsMap.clear(),u__default.default.each(e.usageSchema.components,(n,c)=>u__default.default.each(n,(h,m)=>{this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components",c,m]),h);}));let s=this.schemaComponentsMap.filter(u__default.default.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.consola.debug("cleaning dir",this.config.output),this.fileSystem.cleanDir(this.config.output)):(consola.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.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:Q,classNameCase:O,pascalCase:O,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:A,_:u__default.default,require:this.templatesWorker.requireFnFromTemplate},config:this.config});collectModelTypes=()=>{let e=this.schemaComponentsMap.getComponents(),t=[],s=u__default.default.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(pe("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(!u__default.default.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,O(`${n.moduleName}_Route`),c));}if(i){let c=this.templatesWorker.renderTemplate(e.api,{...t,route:n});o.push(...await this.createOutputFileInfo(t,O(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,u__default.default.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=y__namespace.Extension.Ts;return e.translateToJavaScript?(consola.consola.debug("using js translator for",r),await this.javascriptTranslator.translate({fileName:r,fileExtension:a,fileContent:s})):e.customTranslator?(consola.consola.debug("using custom translator for",r),await e.customTranslator.translate({fileName:r,fileExtension:a,fileContent:s})):(consola.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:u__default.default.merge({url:"",description:""},i),tags:u__default.default.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 je=class{cleanOutput=false;output=void 0;httpClientType=H.FETCH;modular=false;rewrite=false;silent=false;debug=false;version=J;constructor(e){this.update(e);}update=e=>{U(this,e);}};var rs=x__namespace.default.dirname(St__namespace.default.fileURLToPath(f)),De=class{config;fileSystem;rootDir=x__namespace.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 je(e),this.fileSystem=new V;}async start(){consola.consola.info('start generating source templates ".ejs" for code generator');let e=this.getTemplates();if(this.config.output){consola.consola.info("preparing output directory for source templates");let t=x__namespace.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=x__namespace.default.resolve(t,`${r}.ejs`),i=x__namespace.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.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(x__namespace.default.resolve(this.rootDir,e)).filter(t=>t.endsWith(".ejs"));getTemplateContent=e=>this.fileSystem.getFileContent(x__namespace.default.resolve(this.rootDir,e))};async function as(p){return p.debug&&(consola.consola.level=Number.MAX_SAFE_INTEGER),p.silent&&(consola.consola.level=0),await new De(p).start()}async function ki(p){return p.debug&&(consola.consola.level=Number.MAX_SAFE_INTEGER),p.silent&&(consola.consola.level=0),await new ke(p).start()}exports.a=ct;exports.b=H;exports.c=ie;exports.d=ne;exports.e=je;exports.f=as;exports.g=ki;//# sourceMappingURL=chunk-NP4SPLZD.cjs.map
42
+ //# sourceMappingURL=chunk-NP4SPLZD.cjs.map