swagger-typescript-api 13.0.20 → 13.0.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-KMLLDZJ4.cjs +97 -0
- package/dist/chunk-KMLLDZJ4.cjs.map +1 -0
- package/dist/chunk-M2JPSLFC.js +58 -0
- package/dist/chunk-M2JPSLFC.js.map +1 -0
- package/dist/cli.cjs +3 -3
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/lib.cjs +4 -4
- package/dist/lib.js +1 -1
- package/dist/types.d.cts +16 -36
- package/dist/types.d.ts +16 -36
- package/package.json +5 -5
- package/dist/chunk-7LVPMIGQ.js +0 -67
- package/dist/chunk-7LVPMIGQ.js.map +0 -1
- package/dist/chunk-EMN27Y3B.cjs +0 -107
- package/dist/chunk-EMN27Y3B.cjs.map +0 -1
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var consola = require('consola');
|
|
4
|
+
var u = require('lodash');
|
|
5
|
+
var d = require('typescript');
|
|
6
|
+
var rt = require('prettier');
|
|
7
|
+
var mt = require('cosmiconfig');
|
|
8
|
+
var ut = require('nanoid');
|
|
9
|
+
var gt = require('js-yaml');
|
|
10
|
+
var Tt = require('swagger2openapi');
|
|
11
|
+
var F = require('path');
|
|
12
|
+
var St = require('url');
|
|
13
|
+
var Nt = require('eta');
|
|
14
|
+
var N = require('fs');
|
|
15
|
+
|
|
16
|
+
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
17
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
18
|
+
|
|
19
|
+
function _interopNamespace(e) {
|
|
20
|
+
if (e && e.__esModule) return e;
|
|
21
|
+
var n = Object.create(null);
|
|
22
|
+
if (e) {
|
|
23
|
+
Object.keys(e).forEach(function (k) {
|
|
24
|
+
if (k !== 'default') {
|
|
25
|
+
var d = Object.getOwnPropertyDescriptor(e, k);
|
|
26
|
+
Object.defineProperty(n, k, d.get ? d : {
|
|
27
|
+
enumerable: true,
|
|
28
|
+
get: function () { return e[k]; }
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
n.default = e;
|
|
34
|
+
return Object.freeze(n);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
var u__default = /*#__PURE__*/_interopDefault(u);
|
|
38
|
+
var d__namespace = /*#__PURE__*/_interopNamespace(d);
|
|
39
|
+
var rt__namespace = /*#__PURE__*/_interopNamespace(rt);
|
|
40
|
+
var mt__namespace = /*#__PURE__*/_interopNamespace(mt);
|
|
41
|
+
var ut__namespace = /*#__PURE__*/_interopNamespace(ut);
|
|
42
|
+
var gt__namespace = /*#__PURE__*/_interopNamespace(gt);
|
|
43
|
+
var Tt__namespace = /*#__PURE__*/_interopNamespace(Tt);
|
|
44
|
+
var F__namespace = /*#__PURE__*/_interopNamespace(F);
|
|
45
|
+
var St__namespace = /*#__PURE__*/_interopNamespace(St);
|
|
46
|
+
var Nt__namespace = /*#__PURE__*/_interopNamespace(Nt);
|
|
47
|
+
var N__namespace = /*#__PURE__*/_interopNamespace(N);
|
|
48
|
+
|
|
49
|
+
var Dt=Object.defineProperty;var _t=(p,e)=>{for(var t in e)Dt(p,t,{get:e[t],enumerable:!0});};var Z=class{config;constructor({config:e}){this.config=e;}removeUnusedImports=e=>{let t="file.ts",s=new Ue(t,e),a=d__namespace.createLanguageService(s).organizeImports({type:"file",fileName:t},{newLineCharacter:d__namespace.sys.newLine})[0];return a?.textChanges.length?a.textChanges.reduceRight((i,{span:n,newText:o})=>`${i.slice(0,n.start)}${o}${i.slice(n.start+n.length)}`,e):e};prettierFormat=async e=>await rt__namespace.format(e,this.config.prettierOptions);formatCode=async(e,{removeUnusedImports:t=!0,prettierFormat:s=!0}={})=>(t&&(e=this.removeUnusedImports(e)),s&&(e=await this.prettierFormat(e)),e)},Ue=class{constructor(e,t){let s=d__namespace.findConfigFile(e,d__namespace.sys.fileExists);Object.assign(this,{fileName:e,content:t,compilerOptions:s?d__namespace.convertCompilerOptionsFromJson(d__namespace.readConfigFile(s,d__namespace.sys.readFile).config.compilerOptions).options:d__namespace.getDefaultCompilerOptions()});}getNewLine(){return "newLine"in d__namespace.sys?d__namespace.sys.newLine:`
|
|
50
|
+
`}getScriptFileNames(){return [this.fileName]}getCompilationSettings(){return this.compilerOptions}getDefaultLibFileName(){return d__namespace.getDefaultLibFileName(this.getCompilationSettings())}getCurrentDirectory(){return process.cwd()}getScriptVersion(){return d__namespace.version}getScriptSnapshot(){return d__namespace.ScriptSnapshot.fromString(this.content)}readFile(e,t){return e===this.fileName?this.content:d__namespace.sys.readFile(e,t)}fileExists(e){return d__namespace.sys.fileExists(e)}};var b=class{reservedNames=[];getFallbackName=null;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=!0){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 n of i)!a&&(!r||!this.isReserved(n))&&(a=n);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 Kt=(p=0,e=1)=>Math.random()*(e-p)+p,at=(p=0,e=1)=>p===e?p:Math.round(Kt(p,e));var te=class extends b{counter=1;fallbackNameCounter=1;countersByVariant=new Map;constructor(e,t){super(e,t,s=>{let r=s[at(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 n=`${r}${i}`;return consola.consola.debug("generated dirty resolved type name for component - ",n),n}let a=`${this.config.componentTypeNameResolver}${this.fallbackNameCounter++}`;return consola.consola.debug("generated fallback type name for component - ",a),a});}};var re={};_t(re,{DEFAULT_BODY_ARG_NAME:()=>ke,FILE_PREFIX:()=>Ut,HTTP_CLIENT:()=>L,PRETTIER_OPTIONS:()=>se,PROJECT_VERSION:()=>G,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:()=>jt,SCHEMA_TYPES:()=>l});var ot={name:"swagger-typescript-api",version:"13.0.22",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:{types:"./dist/types.d.ts",default:"./dist/lib.js"},require:{types:"./dist/types.d.cts",default:"./dist/lib.cjs"}}},main:"./dist/lib.cjs",module:"./dist/lib.js",types:"./dist/types.d.cts",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",consola:"^3.2.3",cosmiconfig:"^9.0.0",didyoumean:"^1.2.2",eta:"^2.2.0","js-yaml":"^4.1.0",lodash:"^4.17.21",nanoid:"^3.3.7",prettier:"~3.3.3","swagger-schema-official":"2.0.0-bab6bed",swagger2openapi:"^7.0.8",typescript:"~5.5.4"},devDependencies:{"@biomejs/biome":"1.8.3","@tsconfig/node18":"18.2.4","@tsconfig/strictest":"2.0.5","@types/didyoumean":"1.2.2","@types/js-yaml":"4.0.9","@types/lodash":"4.17.7","@types/node":"22.5.0","@types/swagger2openapi":"7.0.4",axios:"1.7.5",shx:"0.3.4",tsup:"8.2.4",vitest:"2.0.5"},packageManager:"yarn@4.4.1",engines:{node:">=18.0.0"},publishConfig:{access:"public",registry:"https://registry.npmjs.org"}};var ke="data",Ut=`/* eslint-disable */
|
|
51
|
+
/* tslint:disable */
|
|
52
|
+
/*
|
|
53
|
+
* ---------------------------------------------------------------
|
|
54
|
+
* ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
|
|
55
|
+
* ## ##
|
|
56
|
+
* ## AUTHOR: acacode ##
|
|
57
|
+
* ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
|
|
58
|
+
* ---------------------------------------------------------------
|
|
59
|
+
*/
|
|
60
|
+
|
|
61
|
+
`,L={FETCH:"fetch",AXIOS:"axios"},se={printWidth:120,tabWidth:2,trailingComma:"all",parser:"typescript"},G=ot.version,We=["data","body","reqBody"],Ve=["headers","headersParams"],Be=["path","pathParams"],Le=["query","queryParams","queryArg"],jt=["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(Boolean);Object.assign(p,u__default.default.merge(p,t));for(let r of s)p[r]=void 0;};var kt={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"},ae=class{version=G;templates="";generateResponses=!1;defaultResponseAsSuccess=!1;generateRouteTypes=!1;generateClient=!0;generateUnionEnums=!1;addReadonly=!1;enumNamesAsValues=!1;swaggerSchema=null;originalSchema=null;componentsMap={};convertedFromSwagger2=!1;moduleNameIndex=0;moduleNameFirstTag=!1;disableStrictSSL=!1;disableProxy=!1;extractRequestParams=!1;extractRequestBody=!1;extractResponseBody=!1;extractResponseError=!1;extractResponses=!1;extractEnums=!1;fileNames={dataContracts:"data-contracts",routeTypes:"route-types",httpClient:"http-client",outOfModuleApi:"Common"};routeNameDuplicatesMap=new Map;prettierOptions={...se};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=!1;httpClientType=L.FETCH;unwrapResponseData=!1;disableThrowOnError=!1;sortTypes=!1;sortRoutes=!1;templatePaths={base:"",default:"",modular:"",original:"",custom:""};templatesToRender={api:"",dataContracts:"",dataContractJsDoc:"",interfaceDataContract:"",typeDataContract:"",enumDataContract:"",objectFieldJsDoc:"",httpClient:"",routeTypes:"",routeName:""};schemaParsers={};toJS=!1;silent=!1;typePrefix="";typeSuffix="";enumKeyPrefix="";enumKeySuffix="";patch=!1;componentTypeNameResolver;apiClassName="Api";debug=!1;anotherArrayType=!1;internalTemplateOptions={addUtilRequiredKeysType:!1};extraTemplates=[];input="";modular=!1;output="";url="";cleanOutput=!1;spec=null;fileName="Api.ts";authorizationToken=void 0;requestOptions=null;jsPrimitiveTypes=[];jsEmptyTypes=[];fixInvalidTypeNamePrefix="Type";fixInvalidEnumKeyPrefix="Value";enumKeyResolverName="Value";typeNameResolverName="ComponentType";specificArgNameResolverName="arg";successResponseStatusRange=[200,299];extractingOptions={requestBodySuffix:["Payload","Body","Input"],requestParamsSuffix:["Params"],responseBodySuffix:["Data","Result","Output"],responseErrorSuffix:["Error","Fail","Fails","ErrorData","HttpError","BadResponse"],enumSuffix:["Enum"],discriminatorMappingSuffix:["Mapping","Mapper","MapType"],discriminatorAbstractPrefix:["Base","Abstract","Discriminator","Internal","Polymorph"]};compilerTsConfig={module:d__namespace.ModuleKind.ESNext,noImplicitReturns:!0,alwaysStrict:!0,target:d__namespace.ScriptTarget.ESNext,declaration:!0,noImplicitAny:!1,sourceMap:!1,removeComments:!1,disableSizeLimit:!0,esModuleInterop:!0,emitDecoratorMetadata:!0,skipLibCheck:!0};customTranslator;Ts={Keyword:structuredClone(kt),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:e=>"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(`,
|
|
62
|
+
`),ObjectWrapper:e=>`{
|
|
63
|
+
${e}
|
|
64
|
+
}`,MultilineComment:(e,t)=>[...e.length===1?[`/** ${e[0]} */`]:["/**",...e.map(s=>` * ${s}`)," */"]].map(s=>`${t?t(s):s}
|
|
65
|
+
`),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=ct(),codeGenConstructs:t,primitiveTypeConstructs:s,constants:r,templateInfos:a,hooks:i,...n}){U(this.Ts,t),U(this.primitiveTypes,s),this.defaultResponseType=this.Ts.Keyword.Void,this.update({...n,prettierOptions:e===void 0?ct():e,hooks:u__default.default.merge(this.hooks,i||{}),constants:{...re,...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 te(this,null,[]);}update=e=>{U(this,e);}},ct=()=>{let p=mt__namespace.cosmiconfigSync("prettier",{searchStrategy:"global"}).search();return p?{...p.config,parser:"typescript"}:{...se}};var oe=class{_data=[];config;constructor({config: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},n=this.config.hooks.onCreateComponent(i)||i,o=this._data.findIndex(c=>c.$ref===e);return o===-1?this._data.push(n):this._data[o]=n,n}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 ne=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(`
|
|
66
|
+
`)?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},
|
|
67
|
+
`,n=this.templatesWorker.renderTemplate(this.config.templatesToRender.dataContractJsDoc,{data:s}).split(`
|
|
68
|
+
`).map(o=>`${r}${o}`).join(`
|
|
69
|
+
`);n?t.push(`${n}${a}`):t.push(`${a}`);}return t.join("")}};var ce=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 me=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:!0,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=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:!0,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 pe=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=!1,a=this.createAbstractSchemaStruct(),i=this.createDiscriminatorSchema({skipMappingType:r,abstractSchemaStruct:a}),n=e.IntersectionType([a?.content,i?.content].filter(Boolean));return {...typeof this.schema=="object"?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:!0,schemaType:l.COMPLEX,type:l.PRIMITIVE,typeIdentifier:e.Keyword.Type,name:this.typeName,description:this.schemaFormatters.formatDescription(this.schema.description),content:n}}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),n=!e&&!!(t?.typeName&&i.length),o=[],c,m=this.createMappingPropertySchemaEnumKeys({abstractSchemaStruct:t,discPropertyName:a.propertyName});if(n){let g=`${t.typeName}_${a.propertyName}`,T=this.schemaUtils.resolveTypeName(g,{suffixes:this.config.extractingOptions.discriminatorMappingSuffix,resolver:this.config.extractingOptions.discriminatorMappingNameResolver}),C=s.IntersectionType([s.ObjectWrapper(s.TypeField({key:s.StringValue(a.propertyName),value:"Key"})),"Type"]),w=this.schemaParserFabric.createParsedComponent({typeName:T,schema:{type:"object",properties:{},genericArgs:[{name:"Key"},{name:"Type"}],internal:!0}});w.typeData.content=C,c=this.typeNameFormatter.format(w.typeName);}let h=(g,T)=>{let C=this.schemaParserFabric.createSchemaParser({schema:g,schemaPath:this.schemaPath}).getInlineParseContent(),w=m[T]||s.StringValue(T);return n?s.TypeWithGeneric(c,[w,C]):s.ExpressionGroup(s.IntersectionType([s.ObjectWrapper(s.TypeField({key:a.propertyName,value:w})),C]))};for(let[g,T]of i){let C=typeof T=="string"?{$ref:T}:T;this.mutateMappingDependentSchema({discPropertyName:a.propertyName,abstractSchemaStruct:t,mappingSchema:C,refPath:r,mappingPropertySchemaEnumKeysMap:m}),o.push(h(C,g));}return e?null:{content:s.ExpressionGroup(s.UnionType(o))}};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,n,o)=>{let c=a.rawTypeData.$parsed.content[o].key;return i[n]=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 n=this.schemaUtils.getSchemaRefType(s)?.rawTypeData;if(n)for(let o of i)Array.isArray(n[o])&&(n[o]=n[o].map(c=>{if(c.$ref===r)return {...c,$ref:t.component.$ref};if(this.schemaUtils.getInternalSchemaType(c)===l.OBJECT)for(let m in c.properties){let h=c.properties[m];m===e&&this.schemaUtils.getInternalSchemaType(h)===l.ENUM&&h.enum.length===1&&a[h.enum[0]]&&(c.properties[m]=this.schemaParserFabric.createSchema({content:a[h.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 n=this.schemaUtils.resolveTypeName(this.typeName,{prefixes:this.config.extractingOptions.discriminatorAbstractPrefix,resolver:this.config.extractingOptions.discriminatorAbstractResolver}),o=this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components","schemas",n]),{...r,internal:!0}),c=this.schemaParserFabric.createSchemaParser({schema:o,schemaPath:this.schemaPath}).getInlineParseContent();return {typeName:n,component:o,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 le=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 le(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(o=>o!=null)),Array.isArray(this.schema.enum)&&Array.isArray(this.schema.enum[0]))return this.schemaParserFabric.parseSchema({oneOf:this.schema.enum.map(o=>({type:"array",items:o.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,n=o=>o===null?this.config.Ts.NullValue(o):r.includes(this.schemaUtils.getSchemaType({type:"number"}))?this.config.Ts.NumberValue(o):r.includes(this.schemaUtils.getSchemaType({type:"boolean"}))?this.config.Ts.BooleanValue(o):this.config.Ts.StringValue(o);return Array.isArray(a)&&u__default.default.size(a)?i=a.map((o,c)=>{let m=u__default.default.get(this.schema.enum,c),h=this.formatEnumKey({key:o,value:m});return this.config.enumNamesAsValues||m===void 0?{key:h,type:this.config.Ts.Keyword.String,value:this.config.Ts.StringValue(o)}:{key:h,type:r,value:n(m)}}):i=this.schema.enum.map(o=>({key:this.formatEnumKey({value:o}),type:r,value:n(o)})),{...typeof this.schema=="object"?this.schema:{},$ref:s,typeName:this.typeName||s&&t.typeName||null,$parsedSchema:!0,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 fe=class extends y{parse(){let e=this.getObjectSchemaContent(this.schema);return {...typeof this.schema=="object"?this.schema:{},$schemaPath:this.schemaPath.slice(),$parsedSchema:!0,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 n=this.schemaUtils.isPropertyRequired(i,a,e),o=u__default.default.get(this.schemaUtils.getSchemaRefType(a),"rawTypeData",{}),c=!!(o.nullable||a.nullable),m=this.typeNameFormatter.isValidName(i)?i:this.config.Ts.StringValue(i),h=this.schemaParserFabric.createSchemaParser({schema:a,schemaPath:[...this.schemaPath,i]}).getInlineParseContent(),f=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]||o.description||u__default.default.compact(u__default.default.map(o[this.schemaUtils.getComplexType(o)],"description"))[0]||"",isRequired:n,isNullable:c,name:m,value:h,field:this.config.Ts.TypeField({readonly:f&&this.config.addReadonly,optional:!n,key:m,value:h})}});return s&&r.push({$$raw:{additionalProperties:s},description:"",isRequired:!1,field:this.config.Ts.InterfaceDynamicField(this.config.Ts.Keyword.String,this.config.Ts.Keyword.Any)}),r}};var de=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:!0,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 ye=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 ge=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 Te=class extends y{parse(){return this.config.Ts.Keyword.Any}};var Pe=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)}};function H(p){return u__default.default.camelCase(u__default.default.lowerCase(p))}function A(p){return u__default.default.upperFirst(u__default.default.camelCase(p))}var Se=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"]===!1)return !0;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 H(t.type);if(t.enum){let s=typeof t.enum[0];return s===this.config.Ts.Keyword.Undefined?void 0:H(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:!0}}),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(n=>s.includes(n));return i.length?{...t,$$requiredKeys:i}:t}if(t.properties){let i=u__default.default.keys(t.properties).filter(n=>s.includes(n));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=!0})=>s?this.config.componentTypeNameResolver.resolve(null,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=>!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:A(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 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||Pe;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_ALL_OF]:e=>{let t=this.config.schemaParsers.complexAllOf||ye;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_ANY_OF]:e=>{let t=this.config.schemaParsers.complexAnyOf||ge;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_NOT]:e=>{let t=this.config.schemaParsers.complexNot||Te;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||fe;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||de;return new s(this,e,t,this.schemaPath).parse()},[l.DISCRIMINATOR]:(e,t)=>{let s=this.config.schemaParsers.discriminator||pe;return new s(this,e,t,this.schemaPath).parse()},[l.ARRAY]:(e,t)=>{let s=this.config.schemaParsers.array||me;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(ce("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}}};var Ce=class{config;schemaComponentsMap;typeNameFormatter;schemaFormatters;templatesWorker;schemaUtils;schemaWalker;constructor({config:e,templatesWorker:t,schemaComponentsMap:s,typeNameFormatter:r,schemaWalker:a}){this.config=e,this.schemaComponentsMap=s,this.typeNameFormatter=r,this.templatesWorker=t,this.schemaWalker=a,this.schemaUtils=new Se(this),this.schemaFormatters=new ne(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}),n=i.parseSchema();return n.content=e,Object.assign(n,a),s&&(s.typeData=n),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",ft=ut__namespace.customAlphabet(Lt,12);var Re=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"},Ee=class{config;schemaParserFabric;schemaUtils;typeNameFormatter;schemaComponentsMap;templatesWorker;FORM_DATA_TYPES=[];routes=[];hasSecurityRoutes=!1;hasQueryRoutes=!1;hasFormDataRoutes=!1;constructor({config:e,schemaParserFabric:t,schemaComponentsMap:s,templatesWorker:r,typeNameFormatter: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(/({(([A-z]){1}([a-zA-Z0-9]-?_?\.?)+)([0-9]+)?})|(:(([A-z]){1}([a-zA-Z0-9]-?_?\.?)+)([0-9]+)?:?)/g),r=u__default.default.reduce(s,(c,m)=>{let h=m.replace(/\{|\}|:/g,"");return h&&(h.includes("-")&&consola.consola.warn("wrong path param name",h),c.push({$match:m,name:u__default.default.camelCase(h),required:!0,type:"string",description:"",schema:{type:"string"},in:"path"})),c},[]),a=r.reduce((c,m,h,f)=>{let g=this.config.hooks.onInsertPathParam(m.name,h,f,c)||m.name;return c.replace(m.$match,`\${${g}}`)},t||""),i=a.match(/(\{\?.*\})/g),n=[];if(i?.length){for(let m of i)a=a.replace(m,"");let c=u__default.default.uniq(i.join(",").replace(/(\{\?)|(\})|\s/g,"").split(","));for(let m of c)m.includes("-")&&consola.consola.warn("wrong query param name",m),n.push({$match:m,name:u__default.default.camelCase(m),required:!0,type:"string",description:"",schema:{type:"string"},in:"query"});}let o={originalRoute:e||"",route:a,pathParams:r,queryParams:n};return this.config.hooks.onBuildRoutePath(o)||o};getRouteParams=(e,t,s)=>{let{parameters:r}=e,a={path:[],header:[],body:[],query:[],formData:[],cookie:[]};u__default.default.each(r,i=>{let n=this.schemaParserFabric.schemaUtils.getSchemaRefType(i),o=null;if(n?.rawTypeData.in&&n.rawTypeData)a[n.rawTypeData.in]||(a[n.rawTypeData.in]=[]),o={...n.rawTypeData,...n.rawTypeData.schema||{}};else {if(!i.in)return;a[i.in]||(a[i.in]=[]),o={...i,...i.schema||{}};}if(o.in==="path"){if(!o.name)return;o.name=u__default.default.camelCase(o.name);}o&&a[o.in].push(o);});for(let i of t)a.path.some(o=>o.name===i.name)||a.path.push(i);for(let i of s)a.query.some(o=>o.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"))?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=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),n=this.schemaParserFabric.schemaUtils.getSchemaRefType(e);if(i){let o=this.schemaParserFabric.getInlineParseContent(i,a,[s]),c=t.find(f=>this.typeNameFormatter.format(f.name)===o),m=t.find(f=>u__default.default.isEqual(f.content,o)),h=c||m;return h?this.typeNameFormatter.format(h.name):o}if(n){let o=n.typeName.replace(s,"");if(t.find(c=>c.name===o))return this.typeNameFormatter.format(o);switch(n.componentName){case"schemas":return this.typeNameFormatter.format(n.typeName);case"responses":case"requestBodies":return this.schemaParserFabric.getInlineParseContent(this.getSchemaFromRequestType(n.rawTypeData),n.typeName||null,[s]);default:return this.schemaParserFabric.getInlineParseContent(n.rawTypeData,n.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,n)=>{let o=this.getContentTypes([i]);return [...a,{...i||{},contentTypes:o,contentKind:this.getContentKind(o),type:this.schemaParserFabric.schemaUtils.safeAddNullToType(i,this.getTypeFromRequestInfo({requestInfo:i,parsedSchemas:t,operationId:s,defaultType:r})),description:this.schemaParserFabric.schemaFormatters.formatDescription(i.description||"",!0),status:Number.isNaN(+n)?n:+n,isSuccess:this.isSuccessStatus(n)}]},[]);getResponseBodyInfo=(e,t)=>{let{produces:s,operationId:r,responses:a}=e,i=this.getContentTypes(a,[...s||[],e["x-accepts"]]),n=this.getRequestInfoTypes({requestInfos:a,parsedSchemas:t,operationId:r,defaultType:this.config.defaultResponseType}),o=n.find(h=>h.isSuccess),c=n.filter(h=>!h.isSuccess&&h.type!==this.config.Ts.Keyword.Any),m=h=>{if(!h)return "headers: {},";let f=Object.fromEntries(Object.entries(h).map(([T,C])=>[T,this.schemaUtils.getSchemaType(C)]));return `headers: { ${Object.entries(f).map(([T,C])=>`"${T}": ${C}`).join(",")} },`};return {contentTypes:i,responses:n,success:{schema:o,type:o?.type||this.config.Ts.Keyword.Any},error:{schemas:c,type:this.config.Ts.UnionType(c.map(h=>h.type))||this.config.Ts.Keyword.Any},full:{types:this.config.Ts.UnionType(n.map(h=>`{
|
|
70
|
+
data: ${h.type}, status: ${h.status}, statusCode: ${h.status}, statusText: "${h.description}", ${m(h.headers)} config: {} }`))||this.config.Ts.Keyword.Any}}};convertRouteParamsIntoObject=e=>e.reduce((t,s)=>{if(!s||!s.name)return t;let r=`${s.name}`;return r.includes(".")&&(r=u__default.default.camelCase(r)),{...t,properties:{...t.properties,[r]:{...s,...s.schema||{},$origName:s.name,name:r}}}},{properties:{},type:"object"});getRequestBodyInfo=(e,t,s,r)=>{let{requestBody:a,consumes:i,requestBodyName:n,operationId:o}=e,c=null,m=null,h=this.getContentTypes([a],[...i||[],e["x-contentType"]]),f=this.getContentKind(h),g=null;return this.config.extractRequestBody&&(g=this.schemaUtils.resolveTypeName(r.usage,{suffixes:this.config.extractingOptions.requestBodySuffix,resolver:this.config.extractingOptions.requestBodyNameResolver})),t.formData.length?(f=x.FORM_DATA,c=this.convertRouteParamsIntoObject(t.formData),m=this.schemaParserFabric.getInlineParseContent(c,g,[o])):f===x.FORM_DATA?(c=this.getSchemaFromRequestType(a),m=this.schemaParserFabric.getInlineParseContent(c,g,[o])):a&&(c=this.getSchemaFromRequestType(a),m=this.schemaParserFabric.schemaUtils.safeAddNullToType(a,this.getTypeFromRequestInfo({requestInfo:a,parsedSchemas:s,operationId:o,typeName:g})),this.FORM_DATA_TYPES.some(T=>m.includes(`: ${T}`))&&(f=x.FORM_DATA)),c&&!c.$ref&&this.config.extractRequestBody&&(c=this.schemaParserFabric.createParsedComponent({schema:c,typeName:g,schemaPath:[o]}),m=this.schemaParserFabric.getInlineParseContent({$ref:c.$ref})),{paramName:n||a?.name||ke,contentTypes:h,contentKind:f,schema:c,type:m,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((m,h)=>(h.name&&(m[h.name]={...h,in:"path"}),m),{}),n=u__default.default.reduce(u__default.default.get(t,"properties",{}),(m,h,f)=>(f&&typeof h=="object"&&(m[f]={...h,in:"query"}),m),{}),o={...t,properties:{...n,...i}},c=this.config.hooks.onCreateRequestParams(o);if(c)return c;if(r){let m=this.schemaUtils.resolveTypeName(a.usage,{suffixes:this.config.extractingOptions.requestParamsSuffix,resolver:this.config.extractingOptions.requestParamsNameResolver});return this.schemaParserFabric.createParsedComponent({typeName:m,schema:o})}return o};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 n=i.schema.contentKind,o=this.getSchemaFromRequestType(i.schema);i.schema=this.schemaParserFabric.createParsedComponent({schema:o,typeName:r,schemaPath:[e.operationId]}),i.schema.contentKind=n,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(o=>o.title).filter(Boolean).join(" "),description:a.map(o=>o.description).filter(Boolean).join(`
|
|
71
|
+
`)},null,[e.operationId]),n=this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components","schemas",r]),{...i});t.error.schemas=[n],t.error.type=this.typeNameFormatter.format(n.typeName);}};getRouteName=e=>{let{moduleName:t}=e,{routeNameDuplicatesMap:s,templatesToRender:r}=this.config,a=r.routeName,i=this.templatesWorker.renderTemplate(a,{routeInfo:e}),n=this.config.hooks.onFormatRouteName(e,i)||i,o=`${t}|${n}`;s.has(o)?(s.set(o,s.get(o)+1),consola.consola.warn(`Module "${t}" already has method "${n}()".`,`This method has been renamed to "${n+s.get(o)}()" to solve conflict names.`)):s.set(o,1);let c=s.get(o),m={usage:n+(c>1?c:""),original:n,duplicate:c>1};return this.config.hooks.onCreateRouteName(m,e)||m};parseRouteInfo=(e,t,s,r,a)=>{let{security:i}=r,{moduleNameIndex:n,moduleNameFirstTag:o,extractRequestParams:c}=this.config,{operationId:m,requestBody:h,security:f,parameters:g,summary:T,description:C,tags:w,responses:Ft,requestBodyName:as,produces:xt,consumes:wt,...bt}=t,{route:Ye,pathParams:At,queryParams:Ot}=this.parseRouteName(e),$t=ft(),Xe=w&&w.length>0?w[0]:null,ze=o&&Xe?u__default.default.camelCase(Xe):u__default.default.camelCase(u__default.default.compact(Ye.split("/"))[n]),Qe=!!i?.length;f&&(Qe=f.length>0);let E=this.getRouteParams(t,At,Ot),X=E.path.map(v=>({name:v.name,optional:!v.required,type:this.config.Ts.Keyword.Any,description:v.description})),Mt=X.map(v=>v.name),O=this.getResponseBodyInfo(t,a),Ze={...bt,pathArgs:X,operationId:m,method:s,route:e,moduleName:ze,responsesTypes:O.responses,description:C,tags:w,summary:T,responses:Ft,produces:xt,requestBody:h,consumes:wt,security:f},z=this.convertRouteParamsIntoObject(E.query),Ke=this.convertRouteParamsIntoObject(E.path),qe=this.convertRouteParamsIntoObject(E.header),$=this.getRouteName(Ze),M=this.getRequestBodyInfo(t,E,a,$),It=this.createRequestParamsSchema({queryParams:E.query,pathArgsSchemas:E.path,queryObjectSchema:z,extractRequestParams:c,routeName:$});this.config.extractResponseBody&&this.extractResponseBodyIfItNeeded(t,O,$),this.config.extractResponseError&&this.extractResponseErrorIfItNeeded(t,O,$);let Q=this.schemaUtils.resolveTypeName($.usage,{suffixes:this.config.extractingOptions.requestParamsSuffix,resolver:this.config.extractingOptions.requestParamsNameResolver,shouldReserve:!1}),et=E.query.length?this.schemaParserFabric.getInlineParseContent(z,null,[Q]):null,tt=E.path.length?this.schemaParserFabric.getInlineParseContent(Ke,null,[Q]):null,st=E.header.length?this.schemaParserFabric.getInlineParseContent(qe,null,[Q]):null,V=new Re(this.config,Mt),B={query:et?{name:V.resolve(Le),optional:this.schemaParserFabric.parseSchema(z,null,[$.usage]).allFieldsAreOptional,type:et}:void 0,body:M.type?{name:V.resolve([M.paramName,...We]),optional:!M.required,type:M.type}:void 0,pathParams:tt?{name:V.resolve(Be),optional:this.schemaParserFabric.parseSchema(Ke,null,[$.usage]).allFieldsAreOptional,type:tt}:void 0,headers:st?{name:V.resolve(Ve),optional:this.schemaParserFabric.parseSchema(qe,null,[$.usage]).allFieldsAreOptional,type:st}:void 0};return X.forEach((v,vt)=>{v.type=this.schemaParserFabric.getInlineParseContent(E.path[vt].schema,null,[Q]);}),{id:$t,namespace:ze.replace(/^(\d)/,"v$1"),routeName:$,routeParams:E,requestBodyInfo:M,responseBodyInfo:O,specificArgs:B,queryObjectSchema:z,pathObjectSchema:Ke,headersObjectSchema:qe,responseBodySchema:O.success.schema,requestBodySchema:M.schema,specificArgNameResolver:V,request:{contentTypes:M.contentTypes,parameters:X,path:Ye,formData:M.contentKind===x.FORM_DATA,isQueryBody:M.contentKind===x.URL_ENCODED,security:Qe,method:s,requestParams:It,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:Ze}};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[n,o]of Object.entries(i)){let c=this.parseRouteInfo(r,o,n,e,t),m=this.config.hooks.onCreateRoute(c);if(m!==!1){let h=m||c;!this.hasSecurityRoutes&&h.security&&(this.hasSecurityRoutes=h.security),!this.hasQueryRoutes&&h.hasQuery&&(this.hasQueryRoutes=h.hasQuery),!this.hasFormDataRoutes&&h.hasFormDataParams&&(this.hasFormDataRoutes=h.hasFormDataParams),this.routes.push(h);}}}};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:n,usage:o}=i.routeName;return r.length>1&&o!==n&&!r.some(({routeName:c,id:m})=>m!==i.id&&n===c.original)?{...i,routeName:{...i.routeName,usage:n}}: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 Fe=class{config;swaggerSchemaResolver;schemas=new Map;caches=new Map;constructor({config:e}){this.config=e;}addSchema=(e,t)=>{this.schemas.set(e,structuredClone(t));};findByRef=e=>{if(consola.consola.debug("try to resolve ref by path",e),this.caches.has(e))return this.caches.get(e);let t=Array.from(this.schemas.values());if(this._isLocalRef(e))for(let s of t){let r=this._getRefDataFromSchema(s,e);if(r)return r}else {if(this._isRemoteRef(e))return consola.consola.debug("remote refs not supported",e),null;{let[s,r]=r.split("#"),a;if(this.schemas.has(s))a=this.schemas.get(s);else {let i=r.resolve(process.cwd(),s),n=this.swaggerSchemaResolver.getSwaggerSchemaByPath(i);a=this.swaggerSchemaResolver.processSwaggerSchemaFile(n),this.schemas.set(s,a);}return this._getRefDataFromSchema(a,r)}}};_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 xe=class{config;constructor(e){this.config=e;}async download({url:e,disableStrictSSL:t,authToken:s,...r}){let a={};if(t&&!e.startsWith("http://")){let i=global[Symbol.for("undici.globalDispatcher.1")];if(!i)throw new Error("Could not find the global Undici dispatcher");let n=new i.constructor({connect:{rejectUnauthorized:!1}});global[unidiciGlobalDispatcherSymbol]=n;}s&&(a.headers={Authorization:s}),u__default.default.merge(a,r,this.config.requestOptions);try{return await(await fetch(e,a)).text()}catch(i){let n=`error while fetching data from URL "${e}"`;return consola.consola.error(n,"response"in i?i.response:i),n}}};var we=class{config;fileSystem;request;constructor({config:e,fileSystem:t}){this.config=e,this.fileSystem=t,this.request=new xe(e);}async create(){let{spec:e,patch:t,input:s,url:r,disableStrictSSL:a,disableProxy:i,authorizationToken:n}=this.config;if(this.config.spec)return await this.convertSwaggerObject(e,{patch:t});let o=await this.fetchSwaggerSchemaFile(s,r,a,i,n),c=this.processSwaggerSchemaFile(o);return await this.convertSwaggerObject(c,{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),r.openapi?s({usageSchema:r,originalSchema:structuredClone(r)}):(r.paths=u__default.default.merge({},r.paths),Tt__namespace.convertObj(r,{...t,warnOnly:!0,refSiblings:"preserve",rbname:"requestBodyName"},(a,i)=>{let n=u__default.default.get(a,"options.openapi",u__default.default.get(i,"openapi"));if(!n&&a)throw new Error(a);this.config.update({convertedFromSwagger2:!0}),s({usageSchema:n,originalSchema:r});}));})}getSwaggerSchemaByPath=e=>(consola.consola.info(`try to get swagger by path "${e}"`),this.fileSystem.getFileContent(e));async fetchSwaggerSchemaFile(e,t,s,r,a){return this.fileSystem.pathIsExist(e)?this.getSwaggerSchemaByPath(e):(consola.consola.info(`try to get swagger by URL "${t}"`),await this.request.download({url:t,disableStrictSSL:s,authToken:a,disableProxy:r}))}processSwaggerSchemaFile(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return gt__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 n=u__default.default.get(r,i);u__default.default.each(a,(o,c)=>{let m=u__default.default.get(n,c),h=u__default.default.get(o,"parameters",[]),f=u__default.default.get(m,"parameters",[]);typeof o=="object"&&(o.consumes=u__default.default.uniq(u__default.default.compact([...o.consumes||[],...m.consumes||[]])),o.produces=u__default.default.uniq(u__default.default.compact([...o.produces||[],...m.produces||[]]))),u__default.default.each(f,g=>{h.find(C=>g.in===C.in&&g.name===C.name)||h.push(g);});});});}};var Ae=class{config;fileSystem;getRenderTemplateData;constructor({config:e,fileSystem:t,getRenderTemplateData:s}){this.config=e,this.fileSystem=t,this.getRenderTemplateData=s;}getTemplatePaths=e=>{let t=F__namespace.dirname(St__namespace.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('chunk-KMLLDZJ4.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,n=e.templates&&F__namespace.resolve(process.cwd(),e.templates)||null;return {base:s,default:r,modular:a,original:i,custom:n}};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=({fileName:e,name:t,path:s})=>{let{templatePaths:r}=this.config;if(s)return this.fileSystem.getFileContent(s);if(!e)return "";let a=r.custom&&this.getTemplateFullPath(r.custom,e),i=a&&this.fileSystem.getFileContent(a);if(i)return consola.consola.info(`"${t.toLowerCase()}" template found in "${r.custom}"`),i;let n=this.getTemplateFullPath(r.base,e);n?i=this.fileSystem.getFileContent(n):r.custom?consola.consola.warn("Code generator will use the default template:",`"${t.toLowerCase()}"`,"template not found in",`"${r.custom}"`):consola.consola.info(`Code generator will use the default template for "${t.toLowerCase()}"`);let o=this.getTemplateFullPath(r.original,e);return o&&(i=this.fileSystem.getFileContent(o)),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,{fileName:s,name:r})=>({...t,[r]:this.getTemplate({fileName:s,name: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(n=>e.startsWith(`@${n}`)),s=F__namespace.resolve(e.replace(`@${t}`,this.config.templatePaths[t])),r=this.findTemplateWithExt(s);if(r)return this.fileSystem.getFileContent(r);let a=this.config.templatePaths.custom&&this.findTemplateWithExt(F__namespace.resolve(this.config.templatePaths.custom,e));if(a)return this.fileSystem.getFileContent(a);let i=this.findTemplateWithExt(F__namespace.resolve(this.config.templatePaths.original,e));return i?this.fileSystem.getFileContent(i):""};renderTemplate=(e,t,s)=>e?Nt__namespace.render(e,{...this.getRenderTemplateData(),...t},{async:!1,...s||{},includeFile:(r,a,i)=>this.renderTemplate(this.getTemplateContent(r),a,i)}):""};var Oe=class{config;codeFormatter;constructor(e){this.config=e.config,this.codeFormatter=e.codeFormatter;}translate(e){throw new Error("not implemented")}};var $e=class extends Oe{compileTSCode=e=>{let t=`${e.fileName}${e.fileExtension}`,s={},r=d__namespace.createCompilerHost(this.config.compilerTsConfig,!0),a=[t],i=r.getSourceFile.bind(r);return r.getSourceFile=(n,o,c,m)=>n!==t?i(n,o,c,m):d__namespace.createSourceFile(n,e.fileContent,o,!0,d__namespace.ScriptKind.TS),r.writeFile=(n,o)=>{s[n]=o;},d__namespace.createProgram(a,this.config.compilerTsConfig,r).emit(),s};translate=async e=>{let t=this.compileTSCode(e),s=`${e.fileName}${d__namespace.Extension.Js}`,r=`${e.fileName}${d__namespace.Extension.Dts}`,a=t[s],i=e.fileContent.split(`
|
|
72
|
+
`).filter(o=>o.startsWith("import ")),n=t[r].split(`
|
|
73
|
+
`).map(o=>o.startsWith("import ")?i.shift():o).join(`
|
|
74
|
+
`);return [{fileName:e.fileName,fileExtension:d__namespace.Extension.Js,fileContent:await this.codeFormatter.formatCode(a)},{fileName:e.fileName,fileExtension:d__namespace.Extension.Dts,fileContent:await this.codeFormatter.formatCode(n)}]}};var Me=class{formattedModelNamesMap=new Map;config;constructor({config: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 n=this.fixModelName(e,{type:s}),o=u__default.default.startCase(`${r}_${n}_${a}`).replace(/\s/g,""),c=this.config.hooks.onFormatTypeName(o,e,s)||o;return this.formattedModelNamesMap.set(i,c),c};isValidName=e=>/^([A-Za-z$_]{1,})$/g.test(e);fixModelName=(e,t)=>{let{type:s}=t||{};return this.isValidName(e)||(/^[a-zA-Z_$]/g.test(e)||(e=`${s==="enum-key"?this.config.fixInvalidEnumKeyPrefix:this.config.fixInvalidTypeNamePrefix} ${e}`),e.includes(".")&&(e=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(/__+$/,"")),e.includes("-")&&(e=u__default.default.startCase(e).replace(/ /g,""))),e}};var Qt=`/* eslint-disable */
|
|
75
|
+
/* tslint:disable */
|
|
76
|
+
/*
|
|
77
|
+
* ---------------------------------------------------------------
|
|
78
|
+
* ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
|
|
79
|
+
* ## ##
|
|
80
|
+
* ## AUTHOR: acacode ##
|
|
81
|
+
* ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
|
|
82
|
+
* ---------------------------------------------------------------
|
|
83
|
+
*/
|
|
84
|
+
|
|
85
|
+
`,W=class{getFileContent=e=>N__namespace.readFileSync(e,{encoding:"utf8"});readDir=e=>N__namespace.readdirSync(e);pathIsDir=e=>{if(!e)return !1;try{return N__namespace.statSync(e).isDirectory()}catch{return !1}};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=F__namespace.dirname(St__namespace.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('chunk-KMLLDZJ4.cjs', document.baseURI).href)))),i=F__namespace.resolve(a,e,`./${t}`),n=`${r?Qt:""}${s}`;return N__namespace.writeFileSync(i,n,u__default.default.noop)}};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 ae(e),this.fileSystem=new W(this),this.schemaWalker=new Fe(this),this.swaggerSchemaResolver=new we(this),this.schemaComponentsMap=new oe(this),this.typeNameFormatter=new Me(this),this.templatesWorker=new Ae(this),this.codeFormatter=new Z(this),this.schemaParserFabric=new Ce(this),this.schemaRoutes=new Ee(this),this.javascriptTranslator=new $e(this);}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,(o,c)=>u__default.default.each(o,(m,h)=>{this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components",c,h]),m);}));let s=this.schemaComponentsMap.filter(u__default.default.compact(["schemas",this.config.extractResponses&&"responses"])).map(o=>{let c=this.schemaParserFabric.parseSchema(o.rawTypeData,o.typeName);return o.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(this):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 o of i)this.fileSystem.createFile({path:this.config.output,fileName:`${o.fileName}${o.fileExtension}`,content:o.fileContent,withPrefix:!0}),consola.consola.success("api file",`"${o.fileName}${o.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:H,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:function(t,{eol:s=!0}){return ` * ${t}${s?`
|
|
86
|
+
`:""}`},NameResolver:b,_: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 n of e)if(s.includes(n.componentName)){let o=this.prepareModelType(n);o&&t.push(o),i++;}a=r();}return this.config.sortTypes?t.sort(ce("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:n}=s,o=this.typeNameFormatter.format(a);if(o===null)return null;let c={...s,typeIdentifier:r,name:o,description:n,$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,n=[];if(s.$outOfModule){if(a){let o=this.templatesWorker.renderTemplate(e.routeTypes,{...t,route:t.routes.$outOfModule});n.push(...await this.createOutputFileInfo(t,r.outOfModuleApi,o));}if(i){let o=this.templatesWorker.renderTemplate(e.api,{...t,route:t.routes.$outOfModule});n.push(...await this.createOutputFileInfo(t,r.outOfModuleApi,o));}}if(s.combined)for(let o of s.combined){if(a){let c=this.templatesWorker.renderTemplate(e.routeTypes,{...t,route:o});n.push(...await this.createOutputFileInfo(t,A(`${o.moduleName}_Route`),c));}if(i){let c=this.templatesWorker.renderTemplate(e.api,{...t,route:o});n.push(...await this.createOutputFileInfo(t,A(o.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)):[],...n]};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(`
|
|
87
|
+
`))};createOutputFileInfo=async(e,t,s)=>{let r=this.fileSystem.cropExtension(t),a=d__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:n}=e,o=s?.[0]||{url:""},{title:c="No title",version:m}=t||{},{url:h}=o;return {info:t||{},servers:s||[],basePath:a,host:r,externalDocs:u__default.default.merge({url:"",description:""},i),tags:u__default.default.compact(n),baseUrl:h,title:c,version:m}};injectClassInstance=(e,t)=>{this[e]=t;for(let s of Zt)s!==e&&e in this[s]&&(this[s][e]=t);}};var De=class{cleanOutput=!1;output=void 0;httpClientType=L.FETCH;modular=!1;silent=!1;version=G;rewrite=!1;constructor(e){this.update(e);}update=e=>{U(this,e);}};var ts=F__namespace.default.dirname(St__namespace.default.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('chunk-KMLLDZJ4.cjs', document.baseURI).href)))),_e=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 De(e),this.fileSystem=new W(this);}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`),n=this.fileSystem.pathIsExist(a),o=this.fileSystem.pathIsExist(i);!n&&!o?this.fileSystem.createFile({path:t,fileName:s.name,content:s.content,withPrefix:!1}):this.config.rewrite&&(n?this.fileSystem.createFile({path:t,fileName:`${r}.ejs`,content:s.content,withPrefix:!1}):o&&this.fileSystem.createFile({path:t,fileName:`${r}.eta`,content:s.content,withPrefix:!1}));}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(o=>o.startsWith(`${this.config.httpClientType}-`)),n="";i&&(n=this.fixTemplateContent(this.getTemplateContent(`${this.paths.httpClientTemplates}/${i}`)));for(let o of t){let c=o==="http-client.ejs"&&n||this.fixTemplateContent(this.getTemplateContent(`${this.paths.baseTemplates}/${o}`));e.push({name:o,content:c});}for(let o of a)e.push({name:o,content:this.fixTemplateContent(this.getTemplateContent(`${r}/${o}`))});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 await new _e(p).start()}async function za({name:p,prettier:e,...t}){return t.debug&&(consola.consola.level=Number.MAX_SAFE_INTEGER),await new ve({...t,fileName:p,prettierOptions:e}).start()}
|
|
88
|
+
|
|
89
|
+
exports.a = ot;
|
|
90
|
+
exports.b = L;
|
|
91
|
+
exports.c = re;
|
|
92
|
+
exports.d = ae;
|
|
93
|
+
exports.e = De;
|
|
94
|
+
exports.f = ss;
|
|
95
|
+
exports.g = za;
|
|
96
|
+
//# sourceMappingURL=chunk-KMLLDZJ4.cjs.map
|
|
97
|
+
//# sourceMappingURL=chunk-KMLLDZJ4.cjs.map
|