swagger-typescript-api 13.0.14 → 13.0.15

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.
@@ -45,7 +45,7 @@ var ft__namespace = /*#__PURE__*/_interopNamespace(ft);
45
45
  var v__default = /*#__PURE__*/_interopDefault(v);
46
46
 
47
47
  var Ft=Object.defineProperty;var wt=(m,e)=>{for(var t in e)Ft(m,t,{get:e[t],enumerable:!0});};var re=class{config;constructor({config:e}){this.config=e;}removeUnusedImports=e=>{let t="file.ts",s=new ke(t,e),i=N__default.default.createLanguageService(s).organizeImports({type:"file",fileName:t},{newLineCharacter:N__default.default.sys.newLine})[0];return i?.textChanges.length?p__default.default.reduceRight(i.textChanges,(a,{span:n,newText:o})=>`${a.slice(0,n.start)}${o}${a.slice(n.start+n.length)}`,e):e};prettierFormat=async e=>await At__default.default.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)},ke=class{constructor(e,t){let s=N__default.default.findConfigFile(e,N__default.default.sys.fileExists);Object.assign(this,{fileName:e,content:t,compilerOptions:s?N__default.default.convertCompilerOptionsFromJson(N__default.default.readConfigFile(s,N__default.default.sys.readFile).config.compilerOptions).options:N__default.default.getDefaultCompilerOptions()});}getNewLine(){return "newLine"in N__default.default.sys?N__default.default.sys.newLine:`
48
- `}getScriptFileNames(){return [this.fileName]}getCompilationSettings(){return this.compilerOptions}getDefaultLibFileName(){return N__default.default.getDefaultLibFileName(this.getCompilationSettings())}getCurrentDirectory(){return process.cwd()}getScriptVersion(){return N__default.default.version}getScriptSnapshot(){return N__default.default.ScriptSnapshot.fromString(this.content)}readFile(e,t){return e===this.fileName?this.content:N__default.default.sys.readFile(e,t)}fileExists(e){return N__default.default.sys.fileExists(e)}};var w=class{reservedNames=[];getFallbackName=null;config;logger;constructor(e,t,s,r){this.config=e,this.logger=t,this.getFallbackName=r,this.reserve(s);}reserve(e){let t=p__default.default.uniq(p__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 p__default.default.some(this.reservedNames,t=>t===e)}resolve(e,t,s,r=!0){if(typeof t=="function"){let i=null;for(;i===null;){let a=t(e,s);if(a===void 0)return this.logger.warn("unable to resolve name. current reserved names: ",this.reservedNames),null;(!r||!this.isReserved(a))&&(i=a);}return r&&this.reserve([i]),i}else if(Array.isArray(e)){let i=null,a=p__default.default.uniq(p__default.default.compact(e));return p__default.default.forEach(a,n=>{!i&&(!r||!this.isReserved(n))&&(i=n);}),i?(r&&this.reserve([i]),i):(this.logger.debug("trying to resolve name with using fallback name generator using variants",e),this.resolve(e,this.getFallbackName,s))}return this.logger.debug("problem with reserving names. current reserved names: ",this.reservedNames),null}};var Ot=(m=0,e=1)=>Math.random()*(e-m)+m,tt=(m=0,e=1)=>m===e?m:Math.round(Ot(m,e));var ie=class extends w{counter=1;fallbackNameCounter=1;countersByVariant=new Map;constructor(e,t,s){super(e,t,s,r=>{let i=r[tt(0,r.length-1)];if(i){this.countersByVariant.has(i)||this.countersByVariant.set(i,0);let n=this.countersByVariant.get(i)+1;this.countersByVariant.set(i,n);let o=`${i}${n}`;return this.logger.debug("generated dirty resolved type name for component - ",o),o}let a=`${this.config.componentTypeNameResolver}${this.fallbackNameCounter++}`;return this.logger.debug("generated fallback type name for component - ",a),a});}};var oe={};wt(oe,{DEFAULT_BODY_ARG_NAME:()=>We,FILE_PREFIX:()=>Mt,HTTP_CLIENT:()=>Y,PRETTIER_OPTIONS:()=>ae,PROJECT_VERSION:()=>X,RESERVED_BODY_ARG_NAMES:()=>Le,RESERVED_HEADER_ARG_NAMES:()=>Be,RESERVED_PATH_ARG_NAMES:()=>Ve,RESERVED_QUERY_ARG_NAMES:()=>Ge,RESERVED_REQ_PARAMS_ARG_NAMES:()=>It,SCHEMA_TYPES:()=>l});var st={name:"swagger-typescript-api",version:"13.0.14",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",ci:"biome ci .","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 .",test:"vitest run"},dependencies:{"@types/swagger-schema-official":"^2.0.25",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","node-emoji":"^2.1.3",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.0.0","@types/swagger2openapi":"7.0.4",axios:"1.7.2",shx:"0.3.4",tsup:"8.2.3",vitest:"2.0.4"},packageManager:"yarn@4.3.1",engines:{node:">=18.0.0"},publishConfig:{access:"public",registry:"https://registry.npmjs.org"}};var We="data",Mt=`/* eslint-disable */
48
+ `}getScriptFileNames(){return [this.fileName]}getCompilationSettings(){return this.compilerOptions}getDefaultLibFileName(){return N__default.default.getDefaultLibFileName(this.getCompilationSettings())}getCurrentDirectory(){return process.cwd()}getScriptVersion(){return N__default.default.version}getScriptSnapshot(){return N__default.default.ScriptSnapshot.fromString(this.content)}readFile(e,t){return e===this.fileName?this.content:N__default.default.sys.readFile(e,t)}fileExists(e){return N__default.default.sys.fileExists(e)}};var w=class{reservedNames=[];getFallbackName=null;config;logger;constructor(e,t,s,r){this.config=e,this.logger=t,this.getFallbackName=r,this.reserve(s);}reserve(e){let t=p__default.default.uniq(p__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 p__default.default.some(this.reservedNames,t=>t===e)}resolve(e,t,s,r=!0){if(typeof t=="function"){let i=null;for(;i===null;){let a=t(e,s);if(a===void 0)return this.logger.warn("unable to resolve name. current reserved names: ",this.reservedNames),null;(!r||!this.isReserved(a))&&(i=a);}return r&&this.reserve([i]),i}else if(Array.isArray(e)){let i=null,a=p__default.default.uniq(p__default.default.compact(e));return p__default.default.forEach(a,n=>{!i&&(!r||!this.isReserved(n))&&(i=n);}),i?(r&&this.reserve([i]),i):(this.logger.debug("trying to resolve name with using fallback name generator using variants",e),this.resolve(e,this.getFallbackName,s))}return this.logger.debug("problem with reserving names. current reserved names: ",this.reservedNames),null}};var Ot=(m=0,e=1)=>Math.random()*(e-m)+m,tt=(m=0,e=1)=>m===e?m:Math.round(Ot(m,e));var ie=class extends w{counter=1;fallbackNameCounter=1;countersByVariant=new Map;constructor(e,t,s){super(e,t,s,r=>{let i=r[tt(0,r.length-1)];if(i){this.countersByVariant.has(i)||this.countersByVariant.set(i,0);let n=this.countersByVariant.get(i)+1;this.countersByVariant.set(i,n);let o=`${i}${n}`;return this.logger.debug("generated dirty resolved type name for component - ",o),o}let a=`${this.config.componentTypeNameResolver}${this.fallbackNameCounter++}`;return this.logger.debug("generated fallback type name for component - ",a),a});}};var oe={};wt(oe,{DEFAULT_BODY_ARG_NAME:()=>We,FILE_PREFIX:()=>Mt,HTTP_CLIENT:()=>Y,PRETTIER_OPTIONS:()=>ae,PROJECT_VERSION:()=>X,RESERVED_BODY_ARG_NAMES:()=>Le,RESERVED_HEADER_ARG_NAMES:()=>Be,RESERVED_PATH_ARG_NAMES:()=>Ve,RESERVED_QUERY_ARG_NAMES:()=>Ge,RESERVED_REQ_PARAMS_ARG_NAMES:()=>It,SCHEMA_TYPES:()=>l});var st={name:"swagger-typescript-api",version:"13.0.15",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",prepublishOnly:"pnpm build",test:"vitest run"},dependencies:{"@types/swagger-schema-official":"^2.0.25",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","node-emoji":"^2.1.3",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.0.2","@types/swagger2openapi":"7.0.4",axios:"1.7.2",shx:"0.3.4",tsup:"8.2.3",vitest:"2.0.5"},packageManager:"pnpm@9.6.0",engines:{node:">=18.0.0"},publishConfig:{access:"public",provenance:!0,registry:"https://registry.npmjs.org"}};var We="data",Mt=`/* eslint-disable */
49
49
  /* tslint:disable */
50
50
  /*
51
51
  * ---------------------------------------------------------------
@@ -67,7 +67,7 @@ ${e}
67
67
  `);n?t.push(`${n}${i}`):t.push(`${i}`);}return t.join("")}};var he=m=>(e,t)=>e[m]>t[m]?1:e[m]<t[m]?-1:0;var d=class{schema;typeName;schemaPath;logger;schemaParser;schemaParserFabric;typeNameFormatter;schemaComponentsMap;schemaUtils;config;schemaFormatters;constructor(e,t,s=null,r=[]){this.schemaParser=e,this.schemaParserFabric=e.schemaParserFabric,this.logger=e.logger,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 d{parse(){let e,{type:t,description:s,items:r}=this.schema||{};if(p__default.default.isArray(r)&&t===l.ARRAY){let i=[];for(let a of r)i.push(this.schemaParserFabric.createSchemaParser({schema:a,schemaPath:this.schemaPath}).getInlineParseContent());e=this.config.Ts.Tuple(i);}else {let i=this.schemaParserFabric.createSchemaParser({schema:r,schemaPath:this.schemaPath}).getInlineParseContent();e=this.config.Ts.ArrayType(i);}return {...p__default.default.isObject(this.schema)?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 le=class extends d{parse(){let e=this.schemaUtils.getComplexType(this.schema),t=p__default.default.omit(p__default.default.clone(this.schema),p__default.default.keys(this.schemaParser._complexSchemaParsers)),s=this.schemaParser._complexSchemaParsers[e](this.schema);return {...p__default.default.isObject(this.schema)?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||p__default.default.compact(p__default.default.map(this.schema[e],"description"))[0]||""),content:this.config.Ts.IntersectionType(p__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 ue=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=!1,i=this.createAbstractSchemaStruct(),a=this.createDiscriminatorSchema({skipMappingType:r,abstractSchemaStruct:i}),n=e.IntersectionType([i?.content,a?.content].filter(Boolean));return {...p__default.default.isObject(this.schema)?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:i}=this.schema,a=p__default.default.entries(i.mapping),n=!e&&!!(t?.typeName&&a.length),o=[],c,u=this.createMappingPropertySchemaEnumKeys({abstractSchemaStruct:t,discPropertyName:i.propertyName});if(n){let T=`${t.typeName}_${i.propertyName}`,P=this.schemaUtils.resolveTypeName(T,{suffixes:this.config.extractingOptions.discriminatorMappingSuffix,resolver:this.config.extractingOptions.discriminatorMappingNameResolver}),S=s.IntersectionType([s.ObjectWrapper(s.TypeField({key:s.StringValue(i.propertyName),value:"Key"})),"Type"]),F=this.schemaParserFabric.createParsedComponent({typeName:P,schema:{type:"object",properties:{},genericArgs:[{name:"Key"},{name:"Type"}],internal:!0}});F.typeData.content=S,c=this.typeNameFormatter.format(F.typeName);}let h=(T,P)=>{let S=this.schemaParserFabric.createSchemaParser({schema:T,schemaPath:this.schemaPath}).getInlineParseContent(),F=u[P]||s.StringValue(P);return n?s.TypeWithGeneric(c,[F,S]):s.ExpressionGroup(s.IntersectionType([s.ObjectWrapper(s.TypeField({key:i.propertyName,value:F})),S]))};for(let[T,P]of a){let S=typeof P=="string"?{$ref:P}:P;this.mutateMappingDependentSchema({discPropertyName:i.propertyName,abstractSchemaStruct:t,mappingSchema:S,refPath:r,mappingPropertySchemaEnumKeysMap:u}),o.push(h(S,T));}return e?null:{content:s.ExpressionGroup(s.UnionType(o))}};createMappingPropertySchemaEnumKeys=({abstractSchemaStruct:e,discPropertyName:t})=>{let s=this.config.Ts,r={},i=p__default.default.get(e?.component?.rawTypeData,["properties",t]);return this.schemaUtils.isRefSchema(i)&&(i=this.schemaUtils.getSchemaRefType(i)),i?.rawTypeData?.$parsed?.type===l.ENUM&&(r=p__default.default.reduce(i.rawTypeData.$parsed.enum,(a,n,o)=>{let c=i.rawTypeData.$parsed.content[o].key;return a[n]=s.EnumUsageKey(i.rawTypeData.$parsed.typeName,c),a},{})),r};mutateMappingDependentSchema=({discPropertyName:e,abstractSchemaStruct:t,mappingSchema:s,refPath:r,mappingPropertySchemaEnumKeysMap:i})=>{let a=p__default.default.keys(this.schemaParser._complexSchemaParsers);if(s.$ref&&t?.component?.$ref){let n=this.schemaUtils.getSchemaRefType(s)?.rawTypeData;n&&a.forEach(o=>{p__default.default.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 u in c.properties){let h=c.properties[u];u===e&&this.schemaUtils.getInternalSchemaType(h)===l.ENUM&&h.enum.length===1&&i[h.enum[0]]&&(c.properties[u]=this.schemaParserFabric.createSchema({content:i[h.enum[0]]}));}return c}));});}};createAbstractSchemaStruct=()=>{let{discriminator:e,...t}=this.schema,s=p__default.default.keys(this.schemaParser._complexSchemaParsers),r=p__default.default.omit(p__default.default.clone(t),s),i=this.schemaParserFabric.getInlineParseContent(p__default.default.cloneDeep(r))===this.config.Ts.Keyword.Any;if(!p__default.default.keys(r).length||i)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 fe=class extends w{counter=1;constructor(e,t,s){super(e,t,s,r=>{let i=r[0]&&`${r[0]}${this.counter++}`||`${this.config.enumKeyResolverName}${this.counter++}`;return this.logger.debug("generated fallback type name for enum key - ",i),i});}};var ge=class extends d{enumKeyResolver;constructor(...e){super(...e),this.enumKeyResolver=new fe(this.config,this.logger,[]);}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),i=this.schemaUtils.getEnumNames(this.schema),a=null,n=o=>o===null?this.config.Ts.NullValue(o):p__default.default.includes(r,this.schemaUtils.getSchemaType({type:"number"}))?this.config.Ts.NumberValue(o):p__default.default.includes(r,this.schemaUtils.getSchemaType({type:"boolean"}))?this.config.Ts.BooleanValue(o):this.config.Ts.StringValue(o);return p__default.default.isArray(i)&&p__default.default.size(i)?a=p__default.default.map(i,(o,c)=>{let u=p__default.default.get(this.schema.enum,c),h=this.formatEnumKey({key:o,value:u});return this.config.enumNamesAsValues||p__default.default.isUndefined(u)?{key:h,type:this.config.Ts.Keyword.String,value:this.config.Ts.StringValue(o)}:{key:h,type:r,value:n(u)}}):a=p__default.default.map(this.schema.enum,o=>({key:this.formatEnumKey({value:o}),type:r,value:n(o)})),{...p__default.default.isObject(this.schema)?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:a}}formatEnumKey=({key:e,value:t})=>{let s;return e&&(s=this.typeNameFormatter.format(e,{type:"enum-key"})),s||(s=this.typeNameFormatter.format(`${t}`,{type:"enum-key"})),this.enumKeyResolver.resolve([s])}};var de=class extends d{parse(){let e=this.getObjectSchemaContent(this.schema);return {...p__default.default.isObject(this.schema)?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:!p__default.default.some(p__default.default.values(e),t=>t.isRequired),content:e}}getObjectSchemaContent=e=>{let{properties:t,additionalProperties:s}=e||{},r=p__default.default.map(t,(i,a)=>{let n=this.schemaUtils.isPropertyRequired(a,i,e),o=p__default.default.get(this.schemaUtils.getSchemaRefType(i),"rawTypeData",{}),c=!!(o.nullable||i.nullable),u=this.typeNameFormatter.isValidName(a)?a:this.config.Ts.StringValue(a),h=this.schemaParserFabric.createSchemaParser({schema:i,schemaPath:[...this.schemaPath,a]}).getInlineParseContent(),f=i.readOnly;return {...i,$$raw:i,title:i.title,description:i.description||p__default.default.compact(p__default.default.map(i[this.schemaUtils.getComplexType(i)],"description"))[0]||o.description||p__default.default.compact(p__default.default.map(o[this.schemaUtils.getComplexType(o)],"description"))[0]||"",isRequired:n,isNullable:c,name:u,value:h,field:this.config.Ts.TypeField({readonly:f&&this.config.addReadonly,optional:!n,key:u,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 ye=class extends d{parse(){let e=null,{additionalProperties:t,type:s,description:r,items:i}=this.schema||{};if(s===this.config.Ts.Keyword.Object&&t){let a=p__default.default.isObject(t)?this.schemaParserFabric.createSchemaParser({schema:t,schemaPath:this.schemaPath}).getInlineParseContent():this.config.Ts.Keyword.Any;e=this.config.Ts.RecordType(this.config.Ts.Keyword.String,a);}return p__default.default.isArray(s)&&s.length&&(e=this.schemaParser._complexSchemaParsers.oneOf({...p__default.default.isObject(this.schema)?this.schema:{},oneOf:s.map(a=>({type:a}))})),p__default.default.isArray(i)&&s===l.ARRAY&&(e=this.config.Ts.Tuple(i.map(a=>this.schemaParserFabric.createSchemaParser({schema:a,schemaPath:this.schemaPath}).getInlineParseContent()))),{...p__default.default.isObject(this.schema)?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 Te=class extends d{parse(){let e=[this.config.Ts.Keyword.Any],t=p__default.default.map(this.schema.allOf,i=>this.schemaParserFabric.getInlineParseContent(this.schemaUtils.makeAddRequiredToChildSchema(this.schema,i),null,this.schemaPath)),s=this.schemaUtils.filterSchemaContents(t,i=>!e.includes(i)),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=p__default.default.map(this.schema.anyOf,i=>this.schemaParserFabric.getInlineParseContent(this.schemaUtils.makeAddRequiredToChildSchema(this.schema,i),null,this.schemaPath)),s=this.schemaUtils.filterSchemaContents(t,i=>!e.includes(i)),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 Ne=class extends d{parse(){let e=[this.config.Ts.Keyword.Any],t=p__default.default.map(this.schema.oneOf,i=>this.schemaParserFabric.getInlineParseContent(this.schemaUtils.makeAddRequiredToChildSchema(this.schema,i),null,this.schemaPath)),s=this.schemaUtils.filterSchemaContents(t,i=>!e.includes(i)),r=this.config.Ts.UnionType(s);return this.schemaUtils.safeAddNullToType(this.schema,r)}};function Q(m){return p__default.default.camelCase(p__default.default.lowerCase(m))}function b(m){return p__default.default.upperFirst(p__default.default.camelCase(m))}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=>p__default.default.uniq(e&&p__default.default.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=p__default.default.isBoolean(t.required)?!!t.required:p__default.default.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||!!p__default.default.get(e,"x-nullable")||r===this.config.Ts.Keyword.Null)&&p__default.default.isString(t)&&!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 p__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=p__default.default.uniq([...this.getRequiredProperties(e),...this.getRequiredProperties(t)]),r=this.getSchemaRefType(t);if(r){let a=p__default.default.keys(r.rawTypeData?.properties||{}).filter(n=>s.includes(n));return a.length?{...t,$$requiredKeys:a}:t}else if(t.properties){let a=p__default.default.keys(t.properties).filter(n=>s.includes(n));return a.length?{required:p__default.default.uniq([...this.getRequiredProperties(t),...a]),...t}:t}return t};filterSchemaContents=(e,t)=>p__default.default.uniq(p__default.default.filter(e,s=>t(s)));resolveTypeName=(e,{suffixes:t,resolver:s,prefixes:r,shouldReserve:i=!0})=>s?this.config.componentTypeNameResolver.resolve(null,a=>s(b(e),a)):this.config.componentTypeNameResolver.resolve([...(r||[]).map(a=>b(`${a} ${e}`)),...(t||[]).map(a=>b(`${e} ${a}`))],i);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=>!p__default.default.isEmpty(e.enum)||!p__default.default.isEmpty(this.getEnumNames(e))?l.ENUM:e.discriminator?l.DISCRIMINATOR:e.allOf||e.oneOf||e.anyOf||e.not?l.COMPLEX:p__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 i=p__default.default.get(this.config.primitiveTypes,[r,e.format])||p__default.default.get(this.config.primitiveTypes,[r,"$default"])||this.config.primitiveTypes[r];p__default.default.isFunction(i)?s=i(e,this):s=i||r;}return s?this.checkAndAddRequiredKeys(e,this.safeAddNullToType(e,s)):this.config.Ts.Keyword.Any};buildTypeNameFromPath=e=>(e=p__default.default.uniq(p__default.default.compact(e)),!e||!e[0]?null:b(p__default.default.camelCase(p__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 Ce=class{schemaParserFabric;config;logger;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.logger=e.logger,this.templatesWorker=e.templatesWorker,this.schemaComponentsMap=e.schemaComponentsMap,this.typeNameFormatter=e.typeNameFormatter,this.schemaWalker=e.schemaWalker,this.schemaFormatters=e.schemaFormatters,this.schemaUtils=e.schemaUtils,this.typeName=t||null,this.schema=s,this.schemaPath=[...r||[]];}_complexSchemaParsers={[l.COMPLEX_ONE_OF]:e=>{let t=this.config.schemaParsers.complexOneOf||Ne;return new t(this,e,null,this.schemaPath).parse()},[l.COMPLEX_ALL_OF]:e=>{let t=this.config.schemaParsers.complexAllOf||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||de;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||ye;return new s(this,e,t,this.schemaPath).parse()},[l.DISCRIMINATOR]:(e,t)=>{let s=this.config.schemaParsers.discriminator||ue;return new s(this,e,t,this.schemaPath).parse()},[l.ARRAY]:(e,t)=>{let s=this.config.schemaParsers.array||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&&(this.logger.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),p__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(he("name")));}return this.schemaPath.pop(),this.schema.$parsed};getInlineParseContent=()=>{let e=this.parseSchema();return this.schemaFormatters.formatSchema(e,"inline").content};getParseContent=()=>{let e=this.parseSchema();return this.schemaFormatters.formatSchema(e,"base").content};extractSchemaFromResponseStruct=e=>{let{content:t,...s}=e,r=p__default.default.first(p__default.default.values(t)),i=p__default.default.get(r,"schema");if(i)return {...s,...p__default.default.omit(r,"schema"),...i}}};var Ee=class{config;logger;schemaComponentsMap;typeNameFormatter;schemaFormatters;templatesWorker;schemaUtils;schemaWalker;constructor({config:e,logger:t,templatesWorker:s,schemaComponentsMap:r,typeNameFormatter:i,schemaWalker:a}){this.config=e,this.logger=t,this.schemaComponentsMap=r,this.typeNameFormatter=i,this.templatesWorker=s,this.schemaWalker=a,this.schemaUtils=new Re(this),this.schemaFormatters=new me(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,...i})=>{let a=this.createSchemaParser({schema:s||t,schemaPath:r}),n=a.parseSchema();return n.content=e,Object.assign(n,i),s&&(s.typeData=n),a.schema};createParsedComponent=({typeName:e,schema:t,schemaPath:s})=>{let r=p__default.default.cloneDeep(t),i=this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components","schemas",e]),r),a=this.parseSchema(r,null,s);return a.name=e,i.typeData=a,i};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 Wt="abcdefghijklmnopqrstuvwxyz0123456789",ht=nanoid.customAlphabet(Wt,12);var xe=class extends w{counter=1;constructor(e,t,s){super(e,t,s,r=>{let i=r[0]&&`${r[0]}${this.counter++}`||`${this.config.specificArgNameResolverName}${this.counter++}`;return this.logger.debug("generated fallback type name for specific arg - ",i),i});}};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;logger;templatesWorker;FORM_DATA_TYPES=[];routes=[];hasSecurityRoutes=!1;hasQueryRoutes=!1;hasFormDataRoutes=!1;constructor({config:e,schemaParserFabric:t,schemaComponentsMap:s,logger:r,templatesWorker:i,typeNameFormatter:a}){this.config=e,this.schemaParserFabric=t,this.schemaUtils=this.schemaParserFabric.schemaUtils,this.typeNameFormatter=a,this.schemaComponentsMap=s,this.logger=r,this.templatesWorker=i,this.FORM_DATA_TYPES=p__default.default.uniq([this.schemaUtils.getSchemaType({type:"string",format:"file"}),this.schemaUtils.getSchemaType({type:"string",format:"binary"})]);}createRequestsMap=e=>{let t=p__default.default.get(e,"parameters");return p__default.default.reduce(e,(s,r,i)=>(p__default.default.startsWith(i,"x-")||["parameters","$ref"].includes(i)||(s[i]={...r,parameters:p__default.default.compact(p__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=p__default.default.reduce(s,(c,u)=>{let h=p__default.default.replace(u,/\{|\}|:/g,"");return h&&(p__default.default.includes(h,"-")&&this.logger.warn("wrong path param name",h),c.push({$match:u,name:p__default.default.camelCase(h),required:!0,type:"string",description:"",schema:{type:"string"},in:"path"})),c},[]),i=p__default.default.reduce(r,(c,u,h,f)=>{let T=this.config.hooks.onInsertPathParam(u.name,h,f,c)||u.name;return p__default.default.replace(c,u.$match,`\${${T}}`)},t||""),a=i.match(/(\{\?.*\})/g),n=[];a?.length&&(a.forEach(c=>{i=i.replace(c,"");}),p__default.default.uniq(a.join(",").replace(/(\{\?)|(\})|\s/g,"").split(",")).forEach(c=>{p__default.default.includes(c,"-")&&this.logger.warn("wrong query param name",c),n.push({$match:c,name:p__default.default.camelCase(c),required:!0,type:"string",description:"",schema:{type:"string"},in:"query"});}));let o={originalRoute:e||"",route:i,pathParams:r,queryParams:n};return this.config.hooks.onBuildRoutePath(o)||o};getRouteParams=(e,t,s)=>{let{parameters:r}=e,i={path:[],header:[],body:[],query:[],formData:[],cookie:[]};return p__default.default.each(r,a=>{let n=this.schemaParserFabric.schemaUtils.getSchemaRefType(a),o=null;if(n?.rawTypeData.in&&n.rawTypeData)i[n.rawTypeData.in]||(i[n.rawTypeData.in]=[]),o={...n.rawTypeData,...n.rawTypeData.schema||{}};else {if(!a.in)return;i[a.in]||(i[a.in]=[]),o={...a,...a.schema||{}};}if(o.in==="path"){if(!o.name)return;o.name=p__default.default.camelCase(o.name);}o&&i[o.in].push(o);}),p__default.default.each(t,a=>{p__default.default.some(i.path,o=>o.name===a.name)||i.path.push(a);}),p__default.default.each(s,a=>{p__default.default.some(i.query,o=>o.name===a.name)||i.query.push(a);}),i};getContentTypes=(e,t)=>p__default.default.uniq(p__default.default.compact([...t||[],...p__default.default.flatten(p__default.default.map(e,s=>s&&p__default.default.keys(s.content)))]));getContentKind=e=>p__default.default.some(e,t=>p__default.default.startsWith(t,"application/json"))||p__default.default.some(e,t=>p__default.default.endsWith(t,"+json"))?x.JSON:e.includes("application/x-www-form-urlencoded")?x.URL_ENCODED:e.includes("multipart/form-data")?x.FORM_DATA:p__default.default.some(e,t=>p__default.default.includes(t,"image/"))?x.IMAGE:p__default.default.some(e,t=>p__default.default.startsWith(t,"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=p__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:i})=>{let a=this.getSchemaFromRequestType(e),n=this.schemaParserFabric.schemaUtils.getSchemaRefType(e);if(a){let o=this.schemaParserFabric.getInlineParseContent(a,i,[s]),c=p__default.default.find(t,f=>this.typeNameFormatter.format(f.name)===o),u=p__default.default.find(t,f=>p__default.default.isEqual(f.content,o)),h=c||u;return h?this.typeNameFormatter.format(h.name):o}if(n){let o=p__default.default.replace(n.typeName,s,"");if(p__default.default.find(t,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})=>p__default.default.reduce(e,(i,a,n)=>{let o=this.getContentTypes([a]);return [...i,{...a||{},contentTypes:o,contentKind:this.getContentKind(o),type:this.schemaParserFabric.schemaUtils.safeAddNullToType(a,this.getTypeFromRequestInfo({requestInfo:a,parsedSchemas:t,operationId:s,defaultType:r})),description:this.schemaParserFabric.schemaFormatters.formatDescription(a.description||"",!0),status:p__default.default.isNaN(+n)?n:+n,isSuccess:this.isSuccessStatus(n)}]},[]);getResponseBodyInfo=(e,t)=>{let{produces:s,operationId:r,responses:i}=e,a=this.getContentTypes(i,[...s||[],e["x-accepts"]]),n=this.getRequestInfoTypes({requestInfos:i,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),u=h=>{if(!h)return "headers: {},";let f=Object.fromEntries(Object.entries(h).map(([P,S])=>[P,this.schemaUtils.getSchemaType(S)]));return `headers: { ${Object.entries(f).map(([P,S])=>`"${P}": ${S}`).join(",")} },`};return {contentTypes:a,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=>`{
68
68
  data: ${h.type}, status: ${h.status}, statusCode: ${h.status}, statusText: "${h.description}", ${u(h.headers)} config: {} }`))||this.config.Ts.Keyword.Any}}};convertRouteParamsIntoObject=e=>p__default.default.reduce(e,(t,s)=>{if(!s||!s.name)return t;let r=`${s.name}`;return r.includes(".")&&(r=p__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:i,consumes:a,requestBodyName:n,operationId:o}=e,c=null,u=null,h=this.getContentTypes([i],[...a||[],e["x-contentType"]]),f=this.getContentKind(h),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?(f=x.FORM_DATA,c=this.convertRouteParamsIntoObject(t.formData),u=this.schemaParserFabric.getInlineParseContent(c,T,[o])):f===x.FORM_DATA?(c=this.getSchemaFromRequestType(i),u=this.schemaParserFabric.getInlineParseContent(c,T,[o])):i&&(c=this.getSchemaFromRequestType(i),u=this.schemaParserFabric.schemaUtils.safeAddNullToType(i,this.getTypeFromRequestInfo({requestInfo:i,parsedSchemas:s,operationId:o,typeName:T})),this.FORM_DATA_TYPES.some(P=>p__default.default.includes(u,`: ${P}`))&&(f=x.FORM_DATA)),c&&!c.$ref&&this.config.extractRequestBody&&(c=this.schemaParserFabric.createParsedComponent({schema:c,typeName:T,schemaPath:[o]}),u=this.schemaParserFabric.getInlineParseContent({$ref:c.$ref})),{paramName:n||i?.name||We,contentTypes:h,contentKind:f,schema:c,type:u,required:i&&(typeof i.required>"u"||!!i.required)}};createRequestParamsSchema=({queryParams:e,queryObjectSchema:t,pathArgsSchemas:s,extractRequestParams:r,routeName:i})=>{if(!e||!e.length)return null;let a=p__default.default.reduce(s,(u,h)=>(h.name&&(u[h.name]={...h,in:"path"}),u),{}),n=p__default.default.reduce(p__default.default.get(t,"properties",{}),(u,h,f)=>(f&&p__default.default.isObject(h)&&(u[f]={...h,in:"query"}),u),{}),o={...t,properties:{...n,...a}},c=this.config.hooks.onCreateRequestParams(o);if(c)return c;if(r){let u=this.schemaUtils.resolveTypeName(i.usage,{suffixes:this.config.extractingOptions.requestParamsSuffix,resolver:this.config.extractingOptions.requestParamsNameResolver});return this.schemaParserFabric.createParsedComponent({typeName:u,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}),i=t.responses.indexOf(t.success.schema),a=t.success;if(a.schema&&!a.schema.$ref){let n=a.schema.contentKind,o=this.getSchemaFromRequestType(a.schema);a.schema=this.schemaParserFabric.createParsedComponent({schema:o,typeName:r,schemaPath:[e.operationId]}),a.schema.contentKind=n,a.type=this.schemaParserFabric.getInlineParseContent({$ref:a.schema.$ref}),i>-1&&p__default.default.assign(t.responses[i],{...a.schema,type:a.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}),i=t.error.schemas.map(this.getSchemaFromRequestType).filter(Boolean);if(!i.length)return;let a=this.schemaParserFabric.parseSchema({oneOf:i,title:i.map(o=>o.title).filter(Boolean).join(" "),description:i.map(o=>o.description).filter(Boolean).join(`
69
69
  `)},null,[e.operationId]),n=this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components","schemas",r]),{...a});t.error.schemas=[n],t.error.type=this.typeNameFormatter.format(n.typeName);}};getRouteName=e=>{let{moduleName:t}=e,{routeNameDuplicatesMap:s,templatesToRender:r}=this.config,i=r.routeName,a=this.templatesWorker.renderTemplate(i,{routeInfo:e}),n=this.config.hooks.onFormatRouteName(e,a)||a,o=`${t}|${n}`;s.has(o)?(s.set(o,s.get(o)+1),this.logger.warn(`Module "${t}" already has method "${n}()"`,`
70
- This method has been renamed to "${n+s.get(o)}()" to solve conflict names.`)):s.set(o,1);let c=s.get(o),u={usage:n+(c>1?c:""),original:n,duplicate:c>1};return this.config.hooks.onCreateRouteName(u,e)||u};parseRouteInfo=(e,t,s,r,i)=>{let{security:a}=r,{moduleNameIndex:n,moduleNameFirstTag:o,extractRequestParams:c}=this.config,{operationId:u,requestBody:h,security:f,parameters:T,summary:P,description:S,tags:F,responses:dt,requestBodyName:ss,produces:yt,consumes:Tt,...Pt}=t,{route:Je,pathParams:St,queryParams:Nt}=this.parseRouteName(e),Rt=ht(),He=F&&F.length>0?F[0]:null,Ye=o&&He?p__default.default.camelCase(He):p__default.default.camelCase(p__default.default.compact(p__default.default.split(Je,"/"))[n]),Xe=!!a?.length;f&&(Xe=f.length>0);let R=this.getRouteParams(t,St,Nt),ee=R.path.map(k=>({name:k.name,optional:!k.required,type:this.config.Ts.Keyword.Any,description:k.description})),Ct=ee.map(k=>k.name),O=this.getResponseBodyInfo(t,i),ze={...Pt,pathArgs:ee,operationId:u,method:s,route:e,moduleName:Ye,responsesTypes:O.responses,description:S,tags:F,summary:P,responses:dt,produces:yt,requestBody:h,consumes:Tt,security:f},te=this.convertRouteParamsIntoObject(R.query),Ue=this.convertRouteParamsIntoObject(R.path),je=this.convertRouteParamsIntoObject(R.header),$=this.getRouteName(ze),M=this.getRequestBodyInfo(t,R,i,$),Et=this.createRequestParamsSchema({queryParams:R.query,pathArgsSchemas:R.path,queryObjectSchema:te,extractRequestParams:c,routeName:$});this.config.extractResponseBody&&this.extractResponseBodyIfItNeeded(t,O,$),this.config.extractResponseError&&this.extractResponseErrorIfItNeeded(t,O,$);let se=this.schemaUtils.resolveTypeName($.usage,{suffixes:this.config.extractingOptions.requestParamsSuffix,resolver:this.config.extractingOptions.requestParamsNameResolver,shouldReserve:!1}),Qe=R.query.length?this.schemaParserFabric.getInlineParseContent(te,null,[se]):null,Ze=R.path.length?this.schemaParserFabric.getInlineParseContent(Ue,null,[se]):null,et=R.header.length?this.schemaParserFabric.getInlineParseContent(je,null,[se]):null,J=new xe(this.config,this.logger,Ct),H={query:Qe?{name:J.resolve(Ge),optional:this.schemaParserFabric.parseSchema(te,null,[$.usage]).allFieldsAreOptional,type:Qe}:void 0,body:M.type?{name:J.resolve([M.paramName,...Le]),optional:!M.required,type:M.type}:void 0,pathParams:Ze?{name:J.resolve(Ve),optional:this.schemaParserFabric.parseSchema(Ue,null,[$.usage]).allFieldsAreOptional,type:Ze}:void 0,headers:et?{name:J.resolve(Be),optional:this.schemaParserFabric.parseSchema(je,null,[$.usage]).allFieldsAreOptional,type:et}:void 0};return ee.forEach((k,xt)=>{k.type=this.schemaParserFabric.getInlineParseContent(R.path[xt].schema,null,[se]);}),{id:Rt,namespace:p__default.default.replace(Ye,/^(\d)/,"v$1"),routeName:$,routeParams:R,requestBodyInfo:M,responseBodyInfo:O,specificArgs:H,queryObjectSchema:te,pathObjectSchema:Ue,headersObjectSchema:je,responseBodySchema:O.success.schema,requestBodySchema:M.schema,specificArgNameResolver:J,request:{contentTypes:M.contentTypes,parameters:ee,path:Je,formData:M.contentKind===x.FORM_DATA,isQueryBody:M.contentKind===x.URL_ENCODED,security:Xe,method:s,requestParams:Et,payload:H.body,query:H.query,pathParams:H.pathParams,headers:H.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=p__default.default.entries(e.paths);p__default.default.forEach(s,([r,i])=>{let a=this.createRequestsMap(i);p__default.default.forEach(a,(n,o)=>{let c=this.parseRouteInfo(r,n,o,e,t),u=this.config.hooks.onCreateRoute(c);if(u!==!1){let h=u||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=p__default.default.reduce(e,(s,r,i)=>(i==="$outOfModule"?s.outOfModule=r:(s.combined||(s.combined=[]),s.combined.push({moduleName:i,routes:p__default.default.map(r,a=>{let{original:n,usage:o}=a.routeName;return r.length>1&&o!==n&&!p__default.default.some(r,({routeName:c,id:u})=>u!==a.id&&n===c.original)?{...a,routeName:{...a.routeName,usage:n}}:a})})),s),{});return this.config.sortRoutes&&(t.outOfModule&&(t.outOfModule=this.sortRoutes(t.outOfModule)),t.combined&&p__default.default.each(t.combined,s=>{s.routes=this.sortRoutes(s.routes);})),t};sortRoutes=e=>p__default.default.slice(e).sort((t,s)=>t.routeName.usage.localeCompare(s.routeName.usage))};var we=class{logger;config;swaggerSchemaResolver;schemas=new Map;caches=new Map;constructor({config:e,logger:t}){this.logger=t,this.config=e;}addSchema=(e,t)=>{this.schemas.set(e,p__default.default.cloneDeep(t));};findByRef=e=>{if(this.logger.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 this.logger.debug("remote refs not supported",e),null;{let[s,r]=r.split("#"),i;if(this.schemas.has(s))i=this.schemas.get(s);else {let a=r.resolve(process.cwd(),s),n=this.swaggerSchemaResolver.getSwaggerSchemaByPath(a);i=this.swaggerSchemaResolver.processSwaggerSchemaFile(n),this.schemas.set(s,i);}return this._getRefDataFromSchema(i,r)}}};_isLocalRef=e=>e.startsWith("#");_isRemoteRef=e=>e.startsWith("http://")||e.startsWith("https://");_getRefDataFromSchema=(e,t)=>{let s=t.replace("#","").split("/"),r=p__default.default.get(e,s);return r&&this.caches.set(t,r),r}};var be=class{config;logger;constructor(e,t){this.config=e,this.logger=t;}async download({url:e,disableStrictSSL:t,authToken:s,...r}){let i={};if(t&&!p__default.default.startsWith(e,"http://")){let a=global[Symbol.for("undici.globalDispatcher.1")];if(!a)throw new Error("Could not find the global Undici dispatcher");let n=new a.constructor({connect:{rejectUnauthorized:!1}});global[unidiciGlobalDispatcherSymbol]=n;}s&&(i.headers={Authorization:s}),p__default.default.merge(i,r,this.config.requestOptions);try{return await(await fetch(e,i)).text()}catch(a){let n=`error while fetching data from URL "${e}"`;return this.logger.error(n,"response"in a?a.response:a),n}}};var Ae=class{config;logger;fileSystem;request;constructor({config:e,logger:t,fileSystem:s}){this.config=e,this.logger=t,this.fileSystem=s,this.request=new be(e,t);}async create(){let{spec:e,patch:t,input:s,url:r,disableStrictSSL:i,disableProxy:a,authorizationToken:n}=this.config;if(this.config.spec)return await this.convertSwaggerObject(e,{patch:t});let o=await this.fetchSwaggerSchemaFile(s,r,i,a,n),c=this.processSwaggerSchemaFile(o);return await this.convertSwaggerObject(c,{patch:t})}convertSwaggerObject(e,t){return new Promise(s=>{let r=p__default.default.cloneDeep(e);r.info=p__default.default.merge({title:"No title",version:""},r.info),r.openapi?s({usageSchema:r,originalSchema:p__default.default.cloneDeep(r)}):(r.paths=p__default.default.merge({},r.paths),Bt__default.default.convertObj(r,{...t,warnOnly:!0,refSiblings:"preserve",rbname:"requestBodyName"},(i,a)=>{let n=p__default.default.get(i,"options.openapi",p__default.default.get(a,"openapi"));if(!n&&i)throw new Error(i);this.config.update({convertedFromSwagger2:!0}),s({usageSchema:n,originalSchema:r});}));})}getSwaggerSchemaByPath=e=>(this.logger.log(`try to get swagger by path "${e}"`),this.fileSystem.getFileContent(e));async fetchSwaggerSchemaFile(e,t,s,r,i){return this.fileSystem.pathIsExist(e)?this.getSwaggerSchemaByPath(e):(this.logger.log(`try to get swagger by URL "${t}"`),await this.request.download({url:t,disableStrictSSL:s,authToken:i,disableProxy:r}))}processSwaggerSchemaFile(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return Lt__default.default.load(e)}}fixSwaggerSchema({usageSchema:e,originalSchema:t}){let s=p__default.default.get(e,"paths"),r=p__default.default.get(t,"paths");p__default.default.each(s,(i,a)=>{let n=p__default.default.get(r,a);p__default.default.each(i,(o,c)=>{let u=p__default.default.get(n,c),h=p__default.default.get(o,"parameters",[]),f=p__default.default.get(u,"parameters",[]);typeof o=="object"&&(o.consumes=p__default.default.uniq(p__default.default.compact([...o.consumes||[],...u.consumes||[]])),o.produces=p__default.default.uniq(p__default.default.compact([...o.produces||[],...u.produces||[]]))),p__default.default.each(f,T=>{p__default.default.find(h,S=>T.in===S.in&&T.name===S.name)||h.push(T);});});});}};var Oe=class{config;logger;fileSystem;getRenderTemplateData;constructor({config:e,logger:t,fileSystem:s,getRenderTemplateData:r}){this.config=e,this.logger=t,this.fileSystem=s,this.getRenderTemplateData=r;}getTemplatePaths=e=>{let t=L__default.default.dirname(Vt__default.default.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('chunk-PZ627X5P.cjs', document.baseURI).href)))),s=L.resolve(t,"../templates/base"),r=L.resolve(t,"../templates/default"),i=L.resolve(t,"../templates/modular"),a=e.modular?i:r,n=e.templates&&L.resolve(process.cwd(),e.templates)||null;return {base:s,default:r,modular:i,original:a,custom:n}};cropExtension=e=>this.config.templateExtensions.reduce((t,s)=>p__default.default.endsWith(t,s)?t.replace(s,""):t,e);getTemplateFullPath=(e,t)=>{let s=L.resolve(e,"./",this.cropExtension(t));return this.config.templateExtensions.map(i=>`${s}${i}`).find(i=>!!this.fileSystem.pathIsExist(i))};requireFnFromTemplate=async e=>p__default.default.startsWith(e,"./")||p__default.default.startsWith(e,"../")?await import(L__default.default.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 i=r.custom&&this.getTemplateFullPath(r.custom,e),a=i&&this.fileSystem.getFileContent(i);if(a)return this.logger.log(`"${p__default.default.lowerCase(t)}" template found in "${r.custom}"`),a;let n=this.getTemplateFullPath(r.base,e);n?a=this.fileSystem.getFileContent(n):r.custom?this.logger.warn(`"${p__default.default.lowerCase(t)}" template not found in "${r.custom}"`,`
70
+ This method has been renamed to "${n+s.get(o)}()" to solve conflict names.`)):s.set(o,1);let c=s.get(o),u={usage:n+(c>1?c:""),original:n,duplicate:c>1};return this.config.hooks.onCreateRouteName(u,e)||u};parseRouteInfo=(e,t,s,r,i)=>{let{security:a}=r,{moduleNameIndex:n,moduleNameFirstTag:o,extractRequestParams:c}=this.config,{operationId:u,requestBody:h,security:f,parameters:T,summary:P,description:S,tags:F,responses:dt,requestBodyName:ss,produces:yt,consumes:Tt,...Pt}=t,{route:Je,pathParams:St,queryParams:Nt}=this.parseRouteName(e),Rt=ht(),He=F&&F.length>0?F[0]:null,Ye=o&&He?p__default.default.camelCase(He):p__default.default.camelCase(p__default.default.compact(p__default.default.split(Je,"/"))[n]),Xe=!!a?.length;f&&(Xe=f.length>0);let R=this.getRouteParams(t,St,Nt),ee=R.path.map(k=>({name:k.name,optional:!k.required,type:this.config.Ts.Keyword.Any,description:k.description})),Ct=ee.map(k=>k.name),O=this.getResponseBodyInfo(t,i),ze={...Pt,pathArgs:ee,operationId:u,method:s,route:e,moduleName:Ye,responsesTypes:O.responses,description:S,tags:F,summary:P,responses:dt,produces:yt,requestBody:h,consumes:Tt,security:f},te=this.convertRouteParamsIntoObject(R.query),Ue=this.convertRouteParamsIntoObject(R.path),je=this.convertRouteParamsIntoObject(R.header),$=this.getRouteName(ze),M=this.getRequestBodyInfo(t,R,i,$),Et=this.createRequestParamsSchema({queryParams:R.query,pathArgsSchemas:R.path,queryObjectSchema:te,extractRequestParams:c,routeName:$});this.config.extractResponseBody&&this.extractResponseBodyIfItNeeded(t,O,$),this.config.extractResponseError&&this.extractResponseErrorIfItNeeded(t,O,$);let se=this.schemaUtils.resolveTypeName($.usage,{suffixes:this.config.extractingOptions.requestParamsSuffix,resolver:this.config.extractingOptions.requestParamsNameResolver,shouldReserve:!1}),Qe=R.query.length?this.schemaParserFabric.getInlineParseContent(te,null,[se]):null,Ze=R.path.length?this.schemaParserFabric.getInlineParseContent(Ue,null,[se]):null,et=R.header.length?this.schemaParserFabric.getInlineParseContent(je,null,[se]):null,J=new xe(this.config,this.logger,Ct),H={query:Qe?{name:J.resolve(Ge),optional:this.schemaParserFabric.parseSchema(te,null,[$.usage]).allFieldsAreOptional,type:Qe}:void 0,body:M.type?{name:J.resolve([M.paramName,...Le]),optional:!M.required,type:M.type}:void 0,pathParams:Ze?{name:J.resolve(Ve),optional:this.schemaParserFabric.parseSchema(Ue,null,[$.usage]).allFieldsAreOptional,type:Ze}:void 0,headers:et?{name:J.resolve(Be),optional:this.schemaParserFabric.parseSchema(je,null,[$.usage]).allFieldsAreOptional,type:et}:void 0};return ee.forEach((k,xt)=>{k.type=this.schemaParserFabric.getInlineParseContent(R.path[xt].schema,null,[se]);}),{id:Rt,namespace:p__default.default.replace(Ye,/^(\d)/,"v$1"),routeName:$,routeParams:R,requestBodyInfo:M,responseBodyInfo:O,specificArgs:H,queryObjectSchema:te,pathObjectSchema:Ue,headersObjectSchema:je,responseBodySchema:O.success.schema,requestBodySchema:M.schema,specificArgNameResolver:J,request:{contentTypes:M.contentTypes,parameters:ee,path:Je,formData:M.contentKind===x.FORM_DATA,isQueryBody:M.contentKind===x.URL_ENCODED,security:Xe,method:s,requestParams:Et,payload:H.body,query:H.query,pathParams:H.pathParams,headers:H.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=p__default.default.entries(e.paths);p__default.default.forEach(s,([r,i])=>{let a=this.createRequestsMap(i);p__default.default.forEach(a,(n,o)=>{let c=this.parseRouteInfo(r,n,o,e,t),u=this.config.hooks.onCreateRoute(c);if(u!==!1){let h=u||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=p__default.default.reduce(e,(s,r,i)=>(i==="$outOfModule"?s.outOfModule=r:(s.combined||(s.combined=[]),s.combined.push({moduleName:i,routes:p__default.default.map(r,a=>{let{original:n,usage:o}=a.routeName;return r.length>1&&o!==n&&!p__default.default.some(r,({routeName:c,id:u})=>u!==a.id&&n===c.original)?{...a,routeName:{...a.routeName,usage:n}}:a})})),s),{});return this.config.sortRoutes&&(t.outOfModule&&(t.outOfModule=this.sortRoutes(t.outOfModule)),t.combined&&p__default.default.each(t.combined,s=>{s.routes=this.sortRoutes(s.routes);})),t};sortRoutes=e=>p__default.default.slice(e).sort((t,s)=>t.routeName.usage.localeCompare(s.routeName.usage))};var we=class{logger;config;swaggerSchemaResolver;schemas=new Map;caches=new Map;constructor({config:e,logger:t}){this.logger=t,this.config=e;}addSchema=(e,t)=>{this.schemas.set(e,p__default.default.cloneDeep(t));};findByRef=e=>{if(this.logger.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 this.logger.debug("remote refs not supported",e),null;{let[s,r]=r.split("#"),i;if(this.schemas.has(s))i=this.schemas.get(s);else {let a=r.resolve(process.cwd(),s),n=this.swaggerSchemaResolver.getSwaggerSchemaByPath(a);i=this.swaggerSchemaResolver.processSwaggerSchemaFile(n),this.schemas.set(s,i);}return this._getRefDataFromSchema(i,r)}}};_isLocalRef=e=>e.startsWith("#");_isRemoteRef=e=>e.startsWith("http://")||e.startsWith("https://");_getRefDataFromSchema=(e,t)=>{let s=t.replace("#","").split("/"),r=p__default.default.get(e,s);return r&&this.caches.set(t,r),r}};var be=class{config;logger;constructor(e,t){this.config=e,this.logger=t;}async download({url:e,disableStrictSSL:t,authToken:s,...r}){let i={};if(t&&!p__default.default.startsWith(e,"http://")){let a=global[Symbol.for("undici.globalDispatcher.1")];if(!a)throw new Error("Could not find the global Undici dispatcher");let n=new a.constructor({connect:{rejectUnauthorized:!1}});global[unidiciGlobalDispatcherSymbol]=n;}s&&(i.headers={Authorization:s}),p__default.default.merge(i,r,this.config.requestOptions);try{return await(await fetch(e,i)).text()}catch(a){let n=`error while fetching data from URL "${e}"`;return this.logger.error(n,"response"in a?a.response:a),n}}};var Ae=class{config;logger;fileSystem;request;constructor({config:e,logger:t,fileSystem:s}){this.config=e,this.logger=t,this.fileSystem=s,this.request=new be(e,t);}async create(){let{spec:e,patch:t,input:s,url:r,disableStrictSSL:i,disableProxy:a,authorizationToken:n}=this.config;if(this.config.spec)return await this.convertSwaggerObject(e,{patch:t});let o=await this.fetchSwaggerSchemaFile(s,r,i,a,n),c=this.processSwaggerSchemaFile(o);return await this.convertSwaggerObject(c,{patch:t})}convertSwaggerObject(e,t){return new Promise(s=>{let r=p__default.default.cloneDeep(e);r.info=p__default.default.merge({title:"No title",version:""},r.info),r.openapi?s({usageSchema:r,originalSchema:p__default.default.cloneDeep(r)}):(r.paths=p__default.default.merge({},r.paths),Bt__default.default.convertObj(r,{...t,warnOnly:!0,refSiblings:"preserve",rbname:"requestBodyName"},(i,a)=>{let n=p__default.default.get(i,"options.openapi",p__default.default.get(a,"openapi"));if(!n&&i)throw new Error(i);this.config.update({convertedFromSwagger2:!0}),s({usageSchema:n,originalSchema:r});}));})}getSwaggerSchemaByPath=e=>(this.logger.log(`try to get swagger by path "${e}"`),this.fileSystem.getFileContent(e));async fetchSwaggerSchemaFile(e,t,s,r,i){return this.fileSystem.pathIsExist(e)?this.getSwaggerSchemaByPath(e):(this.logger.log(`try to get swagger by URL "${t}"`),await this.request.download({url:t,disableStrictSSL:s,authToken:i,disableProxy:r}))}processSwaggerSchemaFile(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return Lt__default.default.load(e)}}fixSwaggerSchema({usageSchema:e,originalSchema:t}){let s=p__default.default.get(e,"paths"),r=p__default.default.get(t,"paths");p__default.default.each(s,(i,a)=>{let n=p__default.default.get(r,a);p__default.default.each(i,(o,c)=>{let u=p__default.default.get(n,c),h=p__default.default.get(o,"parameters",[]),f=p__default.default.get(u,"parameters",[]);typeof o=="object"&&(o.consumes=p__default.default.uniq(p__default.default.compact([...o.consumes||[],...u.consumes||[]])),o.produces=p__default.default.uniq(p__default.default.compact([...o.produces||[],...u.produces||[]]))),p__default.default.each(f,T=>{p__default.default.find(h,S=>T.in===S.in&&T.name===S.name)||h.push(T);});});});}};var Oe=class{config;logger;fileSystem;getRenderTemplateData;constructor({config:e,logger:t,fileSystem:s,getRenderTemplateData:r}){this.config=e,this.logger=t,this.fileSystem=s,this.getRenderTemplateData=r;}getTemplatePaths=e=>{let t=L__default.default.dirname(Vt__default.default.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('chunk-HJEBGORP.cjs', document.baseURI).href)))),s=L.resolve(t,"../templates/base"),r=L.resolve(t,"../templates/default"),i=L.resolve(t,"../templates/modular"),a=e.modular?i:r,n=e.templates&&L.resolve(process.cwd(),e.templates)||null;return {base:s,default:r,modular:i,original:a,custom:n}};cropExtension=e=>this.config.templateExtensions.reduce((t,s)=>p__default.default.endsWith(t,s)?t.replace(s,""):t,e);getTemplateFullPath=(e,t)=>{let s=L.resolve(e,"./",this.cropExtension(t));return this.config.templateExtensions.map(i=>`${s}${i}`).find(i=>!!this.fileSystem.pathIsExist(i))};requireFnFromTemplate=async e=>p__default.default.startsWith(e,"./")||p__default.default.startsWith(e,"../")?await import(L__default.default.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 i=r.custom&&this.getTemplateFullPath(r.custom,e),a=i&&this.fileSystem.getFileContent(i);if(a)return this.logger.log(`"${p__default.default.lowerCase(t)}" template found in "${r.custom}"`),a;let n=this.getTemplateFullPath(r.base,e);n?a=this.fileSystem.getFileContent(n):r.custom?this.logger.warn(`"${p__default.default.lowerCase(t)}" template not found in "${r.custom}"`,`
71
71
  Code generator will use the default template`):this.logger.log(`Code generator will use the default template for "${p__default.default.lowerCase(t)}"`);let o=this.getTemplateFullPath(r.original,e);return o&&(a=this.fileSystem.getFileContent(o)),a};getTemplates=({templatePaths:e})=>(e.custom&&this.logger.log(`try to read templates from directory "${e.custom}"`),p__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=p__default.default.keys(this.config.templatePaths).find(n=>p__default.default.startsWith(e,`@${n}`)),s=L.resolve(p__default.default.replace(e,`@${t}`,this.config.templatePaths[t])),r=this.findTemplateWithExt(s);if(r)return this.fileSystem.getFileContent(r);let i=this.config.templatePaths.custom&&this.findTemplateWithExt(L.resolve(this.config.templatePaths.custom,e));if(i)return this.fileSystem.getFileContent(i);let a=this.findTemplateWithExt(L.resolve(this.config.templatePaths.original,e));return a?this.fileSystem.getFileContent(a):""};renderTemplate=(e,t,s)=>e?ft__namespace.render(e,{...this.getRenderTemplateData(),...t},{async:!1,...s||{},includeFile:(r,i,a)=>this.renderTemplate(this.getTemplateContent(r),i,a)}):""};var $e=class{logger;config;codeFormatter;constructor(e){this.logger=e.logger,this.config=e.config,this.codeFormatter=e.codeFormatter;}translate(e){throw new Error("not implemented")}};var Me=class extends $e{compileTSCode=e=>{let t=`${e.fileName}${e.fileExtension}`,s={},r=N__default.default.createCompilerHost(this.config.compilerTsConfig,!0),i=[t],a=r.getSourceFile.bind(r);return r.getSourceFile=(n,o,c,u)=>n!==t?a(n,o,c,u):N__default.default.createSourceFile(n,e.fileContent,o,!0,N__default.default.ScriptKind.TS),r.writeFile=(n,o)=>{s[n]=o;},N__default.default.createProgram(i,this.config.compilerTsConfig,r).emit(),s};translate=async e=>{let t=this.compileTSCode(e),s=`${e.fileName}${N__default.default.Extension.Js}`,r=`${e.fileName}${N__default.default.Extension.Dts}`,i=t[s],a=e.fileContent.split(`
72
72
  `).filter(o=>o.startsWith("import ")),n=t[r].split(`
73
73
  `).map(o=>o.startsWith("import ")?a.shift():o).join(`
@@ -89,9 +89,9 @@ ${r} ${i.replace(/\n/,"")}`:i));};log=(...e)=>this.createLogMessage({type:"log
89
89
  * ---------------------------------------------------------------
90
90
  */
91
91
 
92
- `,G=class{logger;constructor({logger:e=new j("file-system")}={}){this.logger=e;}getFileContent=e=>v__default.default.readFileSync(e,{encoding:"utf8"});readDir=e=>v__default.default.readdirSync(e);pathIsDir=e=>{if(!e)return !1;try{return v__default.default.statSync(e).isDirectory()}catch{return !1}};cropExtension=e=>{let t=p__default.default.split(e,".");return t.length>1&&t.pop(),t.join(".")};removeDir=e=>{try{typeof v__default.default.rmSync=="function"?v__default.default.rmSync(e,{recursive:!0}):v__default.default.rmdirSync(e,{recursive:!0});}catch(t){this.logger.debug("failed to remove dir",t);}};createDir=e=>{try{v__default.default.mkdirSync(e,{recursive:!0});}catch(t){this.logger.debug("failed to create dir",t);}};cleanDir=e=>{this.removeDir(e),this.createDir(e);};pathIsExist=e=>!!e&&v__default.default.existsSync(e);createFile=({path:e,fileName:t,content:s,withPrefix:r})=>{let i=L.dirname(Vt__default.default.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('chunk-PZ627X5P.cjs', document.baseURI).href)))),a=L.resolve(i,e,`./${t}`),n=`${r?Xt:""}${s}`;return v__default.default.writeFileSync(a,n,p__default.default.noop)}};var Qt=["schemaWalker","swaggerSchemaResolver","schemaComponentsMap","typeNameFormatter","templatesWorker","codeFormatter","schemaParserFabric","schemaRoutes","javascriptTranslator"],ve=class{config;swaggerSchemaResolver;schemaComponentsMap;logger;typeNameFormatter;schemaParserFabric;schemaRoutes;fileSystem;codeFormatter;templatesWorker;schemaWalker;javascriptTranslator;constructor(e){this.config=new ne(e),this.logger=new j(this),this.fileSystem=new G(this),this.schemaWalker=new we(this),this.swaggerSchemaResolver=new Ae(this),this.schemaComponentsMap=new ce(this),this.typeNameFormatter=new _e(this),this.templatesWorker=new Oe(this),this.codeFormatter=new re(this),this.schemaParserFabric=new Ee(this),this.schemaRoutes=new Fe(this),this.javascriptTranslator=new Me(this),this.config.componentTypeNameResolver.logger=this.logger;}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),this.logger.event("start generating your typescript api"),this.config.update(this.config.hooks.onInit(this.config,this)||this.config),this.schemaComponentsMap.clear(),p__default.default.each(e.usageSchema.components,(o,c)=>p__default.default.each(o,(u,h)=>{this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components",c,h]),u);}));let s=this.schemaComponentsMap.filter(p__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},i=this.config.hooks.onPrepareConfig(r)||r;this.fileSystem.pathIsExist(this.config.output)?this.config.cleanOutput&&(this.logger.debug(`cleaning dir ${this.config.output}`),this.fileSystem.cleanDir(this.config.output)):(this.logger.debug(`path ${this.config.output} is not exist. creating dir by this path`),this.fileSystem.createDir(this.config.output));let a=await this.generateOutputFiles({configuration:i});return this.fileSystem.pathIsDir(this.config.output)&&a.forEach(o=>{this.fileSystem.createFile({path:this.config.output,fileName:`${o.fileName}${o.fileExtension}`,content:o.fileContent,withPrefix:!0}),this.logger.success("api file",`"${o.fileName}${o.fileExtension}"`,`created in ${this.config.output}`);}),{files:a,configuration:i,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:b,pascalCase:b,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?`
92
+ `,G=class{logger;constructor({logger:e=new j("file-system")}={}){this.logger=e;}getFileContent=e=>v__default.default.readFileSync(e,{encoding:"utf8"});readDir=e=>v__default.default.readdirSync(e);pathIsDir=e=>{if(!e)return !1;try{return v__default.default.statSync(e).isDirectory()}catch{return !1}};cropExtension=e=>{let t=p__default.default.split(e,".");return t.length>1&&t.pop(),t.join(".")};removeDir=e=>{try{typeof v__default.default.rmSync=="function"?v__default.default.rmSync(e,{recursive:!0}):v__default.default.rmdirSync(e,{recursive:!0});}catch(t){this.logger.debug("failed to remove dir",t);}};createDir=e=>{try{v__default.default.mkdirSync(e,{recursive:!0});}catch(t){this.logger.debug("failed to create dir",t);}};cleanDir=e=>{this.removeDir(e),this.createDir(e);};pathIsExist=e=>!!e&&v__default.default.existsSync(e);createFile=({path:e,fileName:t,content:s,withPrefix:r})=>{let i=L.dirname(Vt__default.default.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('chunk-HJEBGORP.cjs', document.baseURI).href)))),a=L.resolve(i,e,`./${t}`),n=`${r?Xt:""}${s}`;return v__default.default.writeFileSync(a,n,p__default.default.noop)}};var Qt=["schemaWalker","swaggerSchemaResolver","schemaComponentsMap","typeNameFormatter","templatesWorker","codeFormatter","schemaParserFabric","schemaRoutes","javascriptTranslator"],ve=class{config;swaggerSchemaResolver;schemaComponentsMap;logger;typeNameFormatter;schemaParserFabric;schemaRoutes;fileSystem;codeFormatter;templatesWorker;schemaWalker;javascriptTranslator;constructor(e){this.config=new ne(e),this.logger=new j(this),this.fileSystem=new G(this),this.schemaWalker=new we(this),this.swaggerSchemaResolver=new Ae(this),this.schemaComponentsMap=new ce(this),this.typeNameFormatter=new _e(this),this.templatesWorker=new Oe(this),this.codeFormatter=new re(this),this.schemaParserFabric=new Ee(this),this.schemaRoutes=new Fe(this),this.javascriptTranslator=new Me(this),this.config.componentTypeNameResolver.logger=this.logger;}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),this.logger.event("start generating your typescript api"),this.config.update(this.config.hooks.onInit(this.config,this)||this.config),this.schemaComponentsMap.clear(),p__default.default.each(e.usageSchema.components,(o,c)=>p__default.default.each(o,(u,h)=>{this.schemaComponentsMap.createComponent(this.schemaComponentsMap.createRef(["components",c,h]),u);}));let s=this.schemaComponentsMap.filter(p__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},i=this.config.hooks.onPrepareConfig(r)||r;this.fileSystem.pathIsExist(this.config.output)?this.config.cleanOutput&&(this.logger.debug(`cleaning dir ${this.config.output}`),this.fileSystem.cleanDir(this.config.output)):(this.logger.debug(`path ${this.config.output} is not exist. creating dir by this path`),this.fileSystem.createDir(this.config.output));let a=await this.generateOutputFiles({configuration:i});return this.fileSystem.pathIsDir(this.config.output)&&a.forEach(o=>{this.fileSystem.createFile({path:this.config.output,fileName:`${o.fileName}${o.fileExtension}`,content:o.fileContent,withPrefix:!0}),this.logger.success("api file",`"${o.fileName}${o.fileExtension}"`,`created in ${this.config.output}`);}),{files:a,configuration:i,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:b,pascalCase:b,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?`
93
93
  `:""}`},NameResolver:w,_:p__default.default,require:this.templatesWorker.requireFnFromTemplate},config:this.config});collectModelTypes=()=>{let e=this.schemaComponentsMap.getComponents(),t=[],s=p__default.default.compact(["schemas",this.config.extractResponses&&"responses"]),r=()=>this.schemaComponentsMap.filter(...s).length,i=r(),a=0;for(;a<i;){t=[],a=0;for(let n of e)if(s.includes(n.componentName)){let o=this.prepareModelType(n);o&&t.push(o),a++;}i=r();}return this.config.sortTypes?t.sort(he("name")):t};prepareModelType=e=>{if(e.$prepared)return e.$prepared;e.typeData||(e.typeData=this.schemaParserFabric.parseSchema(e.rawTypeData,e.typeName));let t=e.typeData,s=this.schemaParserFabric.schemaFormatters.base[t.type]?this.schemaParserFabric.schemaFormatters.base[t.type](t):t,{typeIdentifier:r,name:i,content:a,description:n}=s,o=this.typeNameFormatter.format(i);if(o===null)return null;let c={...s,typeIdentifier:r,name:o,description:n,$content:t.content,rawContent:t.content,content:a,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(!p__default.default.isEmpty(e.extraTemplates))for(let i of e.extraTemplates){let a=this.templatesWorker.renderTemplate(this.fileSystem.getFileContent(i.path),e);r.push(...await this.createOutputFileInfo(e,i.name,a));}return r.filter(i=>!!i&&!!i.fileContent)};createMultipleFileInfos=async(e,t)=>{let{routes:s}=t,{fileNames:r,generateRouteTypes:i,generateClient:a}=t.config,n=[];if(s.$outOfModule){if(i){let o=this.templatesWorker.renderTemplate(e.routeTypes,{...t,route:t.routes.$outOfModule});n.push(...await this.createOutputFileInfo(t,r.outOfModuleApi,o));}if(a){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(i){let c=this.templatesWorker.renderTemplate(e.routeTypes,{...t,route:o});n.push(...await this.createOutputFileInfo(t,b(`${o.moduleName}_Route`),c));}if(a){let c=this.templatesWorker.renderTemplate(e.api,{...t,route:o});n.push(...await this.createOutputFileInfo(t,b(o.moduleName),c));}}return [...await this.createOutputFileInfo(t,r.dataContracts,this.templatesWorker.renderTemplate(e.dataContracts,t)),...a?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,p__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(`
94
- `))};createOutputFileInfo=async(e,t,s)=>{let r=this.fileSystem.cropExtension(t),i=N__default.default.Extension.Ts;return e.translateToJavaScript?(this.logger.debug("using js translator for",r),await this.javascriptTranslator.translate({fileName:r,fileExtension:i,fileContent:s})):e.customTranslator?(this.logger.debug("using custom translator for",r),await e.customTranslator.translate({fileName:r,fileExtension:i,fileContent:s})):(this.logger.debug("generating output for",`${r}${i}`),[{fileName:r,fileExtension:i,fileContent:await this.codeFormatter.formatCode(s)}])};createApiConfig=e=>{let{info:t,servers:s,host:r,basePath:i,externalDocs:a,tags:n}=e,o=s?.[0]||{url:""},{title:c="No title",version:u}=t||{},{url:h}=o;return {info:t||{},servers:s||[],basePath:i,host:r,externalDocs:p__default.default.merge({url:"",description:""},a),tags:p__default.default.compact(n),baseUrl:h,title:c,version:u}};injectClassInstance=(e,t)=>{this[e]=t,Qt.forEach(s=>{s!==e&&e in this[s]&&(this[s][e]=t);});}};var Ke=class{cleanOutput=!1;output=void 0;httpClientType=Y.FETCH;modular=!1;silent=!1;version=X;rewrite=!1;constructor(e){this.update(e);}update=e=>{V(this,e);}};var es=L__default.default.dirname(Vt__default.default.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('chunk-PZ627X5P.cjs', document.baseURI).href)))),qe=class{config;fileSystem;logger;rootDir=L__default.default.resolve(es,"../../../");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.logger=new j(this),this.fileSystem=new G(this);}async start(){this.logger.event('start generating source templates ".ejs" for code generator');let e=this.getTemplates();if(this.config.output){this.logger.log("preparing output directory for source templates");let t=L__default.default.resolve(process.cwd(),this.config.output);this.fileSystem.pathIsExist(t)?this.config.cleanOutput&&this.fileSystem.cleanDir(t):this.fileSystem.createDir(t),e.forEach(s=>{let r=this.fileSystem.cropExtension(s.name),i=L__default.default.resolve(t,`${r}.ejs`),a=L__default.default.resolve(t,`${r}.eta`),n=this.fileSystem.pathIsExist(i),o=this.fileSystem.pathIsExist(a);!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}));}),this.logger.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,i=this.getTemplateNamesFromDir(r),a=s.find(o=>o.startsWith(`${this.config.httpClientType}-`)),n="";a&&(n=this.fixTemplateContent(this.getTemplateContent(`${this.paths.httpClientTemplates}/${a}`)));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 i)e.push({name:o,content:this.fixTemplateContent(this.getTemplateContent(`${r}/${o}`))});return e};fixTemplateContent=e=>{let t=new RegExp(`includeFile\\("(${this.importTemplatePrefixes.map(i=>`(${i})`).join("|")})/`,"g"),s=new RegExp(`includeFile\\(\`(${this.importTemplatePrefixes.map(i=>`(${i})`).join("|")})/`,"g"),r=new RegExp(`includeFile\\('(${this.importTemplatePrefixes.map(i=>`(${i})`).join("|")})/`,"g");return e.replace(t,'includeFile("./').replace(s,"includeFile(`./").replace(r,"includeFile('./")};getTemplateNamesFromDir=e=>this.fileSystem.readDir(L__default.default.resolve(this.rootDir,e)).filter(t=>t.endsWith(".ejs"));getTemplateContent=e=>this.fileSystem.getFileContent(L__default.default.resolve(this.rootDir,e))};async function ts(m){return await new qe(m).start()}async function ma({name:m,prettier:e,...t}){return await new ve({...t,fileName:m,prettierOptions:e}).start()}
94
+ `))};createOutputFileInfo=async(e,t,s)=>{let r=this.fileSystem.cropExtension(t),i=N__default.default.Extension.Ts;return e.translateToJavaScript?(this.logger.debug("using js translator for",r),await this.javascriptTranslator.translate({fileName:r,fileExtension:i,fileContent:s})):e.customTranslator?(this.logger.debug("using custom translator for",r),await e.customTranslator.translate({fileName:r,fileExtension:i,fileContent:s})):(this.logger.debug("generating output for",`${r}${i}`),[{fileName:r,fileExtension:i,fileContent:await this.codeFormatter.formatCode(s)}])};createApiConfig=e=>{let{info:t,servers:s,host:r,basePath:i,externalDocs:a,tags:n}=e,o=s?.[0]||{url:""},{title:c="No title",version:u}=t||{},{url:h}=o;return {info:t||{},servers:s||[],basePath:i,host:r,externalDocs:p__default.default.merge({url:"",description:""},a),tags:p__default.default.compact(n),baseUrl:h,title:c,version:u}};injectClassInstance=(e,t)=>{this[e]=t,Qt.forEach(s=>{s!==e&&e in this[s]&&(this[s][e]=t);});}};var Ke=class{cleanOutput=!1;output=void 0;httpClientType=Y.FETCH;modular=!1;silent=!1;version=X;rewrite=!1;constructor(e){this.update(e);}update=e=>{V(this,e);}};var es=L__default.default.dirname(Vt__default.default.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('chunk-HJEBGORP.cjs', document.baseURI).href)))),qe=class{config;fileSystem;logger;rootDir=L__default.default.resolve(es,"../../../");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.logger=new j(this),this.fileSystem=new G(this);}async start(){this.logger.event('start generating source templates ".ejs" for code generator');let e=this.getTemplates();if(this.config.output){this.logger.log("preparing output directory for source templates");let t=L__default.default.resolve(process.cwd(),this.config.output);this.fileSystem.pathIsExist(t)?this.config.cleanOutput&&this.fileSystem.cleanDir(t):this.fileSystem.createDir(t),e.forEach(s=>{let r=this.fileSystem.cropExtension(s.name),i=L__default.default.resolve(t,`${r}.ejs`),a=L__default.default.resolve(t,`${r}.eta`),n=this.fileSystem.pathIsExist(i),o=this.fileSystem.pathIsExist(a);!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}));}),this.logger.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,i=this.getTemplateNamesFromDir(r),a=s.find(o=>o.startsWith(`${this.config.httpClientType}-`)),n="";a&&(n=this.fixTemplateContent(this.getTemplateContent(`${this.paths.httpClientTemplates}/${a}`)));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 i)e.push({name:o,content:this.fixTemplateContent(this.getTemplateContent(`${r}/${o}`))});return e};fixTemplateContent=e=>{let t=new RegExp(`includeFile\\("(${this.importTemplatePrefixes.map(i=>`(${i})`).join("|")})/`,"g"),s=new RegExp(`includeFile\\(\`(${this.importTemplatePrefixes.map(i=>`(${i})`).join("|")})/`,"g"),r=new RegExp(`includeFile\\('(${this.importTemplatePrefixes.map(i=>`(${i})`).join("|")})/`,"g");return e.replace(t,'includeFile("./').replace(s,"includeFile(`./").replace(r,"includeFile('./")};getTemplateNamesFromDir=e=>this.fileSystem.readDir(L__default.default.resolve(this.rootDir,e)).filter(t=>t.endsWith(".ejs"));getTemplateContent=e=>this.fileSystem.getFileContent(L__default.default.resolve(this.rootDir,e))};async function ts(m){return await new qe(m).start()}async function ma({name:m,prettier:e,...t}){return await new ve({...t,fileName:m,prettierOptions:e}).start()}
95
95
 
96
96
  exports.a = st;
97
97
  exports.b = Y;
@@ -100,5 +100,5 @@ exports.d = ne;
100
100
  exports.e = Ke;
101
101
  exports.f = ts;
102
102
  exports.g = ma;
103
- //# sourceMappingURL=chunk-PZ627X5P.cjs.map
104
- //# sourceMappingURL=chunk-PZ627X5P.cjs.map
103
+ //# sourceMappingURL=chunk-HJEBGORP.cjs.map
104
+ //# sourceMappingURL=chunk-HJEBGORP.cjs.map