@dazhicheng/openapi 1.1.4 → 1.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @dazhicheng/openapi
2
2
 
3
+ ## 1.1.6
4
+
5
+ ### Patch Changes
6
+
7
+ - openapi添加参数返回所有类型,列设置弹框添加重置按钮
8
+
9
+ ## 1.1.5
10
+
11
+ ### Patch Changes
12
+
13
+ - 去除console
14
+
3
15
  ## 1.1.4
4
16
 
5
17
  ### Patch Changes
package/dist/index.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- import{readFileSync as e}from"node:fs";import t from"http";import r from"https";import s from"node-fetch";import n from"swagger2openapi";import o from"chalk";import i from"mockjs";import a,{readFileSync as c}from"fs";import p,{dirname as l,join as h}from"path";import{camelCase as m,isBoolean as u,isArray as f}from"lodash-es";import g from"memoizee";import d from"tiny-pinyin";import y from"glob";import b from"nunjucks";import{fileURLToPath as j}from"url";import $ from"reserved-words";import w from"rimraf";import P from"number-to-words";const v=(...e)=>console.log(`${o.blue("[openAPI]")}: ${e.join("\n")}`),k=e=>{a.existsSync(e)||(k(p.dirname(e)),a.mkdirSync(e))},O=async e=>{let t=e,r=!1;try{const r=await import("prettier"),s=await r.resolveConfig(process.cwd());t=await r.format(e,{parser:"typescript",...s,singleQuote:!0})}catch(e){console.error("Prettier error:",e),r=!0}return[t,r]},T=async(e,t,r)=>{const s=p.join(e,t);k(p.dirname(s));const[n,o]=await O(r);return a.writeFileSync(s,n,{encoding:"utf8"}),o};function A(e){return(t=e)&&"object"==typeof t?e:{};var t}function F(e){return e.schema?e.schema:e.properties?{...e,type:"object"}:e}var x={string:"@string",string_email:"@email",string_phone:"@phone",string_username:"@cname",string_url:"@url",string_uuid:"@guid",string_id:"@increment",string_status:"@status",string_authority:"@authority",string_label:"@label",string_group:"@group",string_csentence:"@csentence",string_cname:"@cname",string_name:"@last",string_errorCode:"@increment",string_country:"@country",string_county:"@county(true)",string_province:"@province",string_city:"@city",string_avatar:"@avatar",string_href:"@href","string_string(16)":"@string(16)","string_date-time":"@datetime",string_date:"@date",number:"@integer(60, 100)",number_float:"@float(60, 100, 3, 5)",integer:"@integer(60, 100)",boolean:"@boolean"};const C=(e,t)=>{if(!e||e.length<1)return"string";if(Array.isArray(e))return C([...e].pop(),e);if(["nickname","name"].includes(e))return"cname";if(["owner","firstName","lastName","username"].includes(e))return"name";if(["avatar"].includes(e))return"avatar";if(["group"].includes(e))return"group";if(e.toLocaleLowerCase().endsWith("id"))return"uuid";if(e.toLocaleLowerCase().endsWith("type")||e.toLocaleLowerCase().endsWith("key")||["key"].includes(e))return"id";if(e.toLocaleLowerCase().endsWith("label")||["label"].includes(e)){const e=[...t];e.pop();const r=C(e);return"string"!==r&&"csentence"!==r?r:"label"}return["email"].includes(e)?"email":["password"].includes(e)?"string(16)":["phone"].includes(e)?"phone":["province"].includes(e)?"province":["city"].includes(e)?"city":["addr","address"].includes(e)?"county":["country"].includes(e)?"country":["url","imageUrl","href"].includes(e)||e.toLocaleLowerCase().endsWith("url")||e.toLocaleLowerCase().endsWith("urls")||e.toLocaleLowerCase().endsWith("image")||e.toLocaleLowerCase().endsWith("link")?"href":e.toLocaleLowerCase().endsWith("errorcode")?"errorCode":["type","status"].includes(e)||e.toLocaleLowerCase().endsWith("status")||e.toLocaleLowerCase().endsWith("type")?"status":e.toLocaleLowerCase().endsWith("authority")?"authority":"csentence"};class N{openAPI;constructor(e){this.openAPI=e,this.sampleFromSchema=g(this.sampleFromSchema)}sampleFromSchema=(e,t,r=new Set)=>{const s=e?.$ref;if(s){if(r.has(s))return null;r.add(s)}const n=s?function(e,t){let r=e;for(let e=0;e<t.length;e+=1){if(null==r)return;r=r[t[e]]}return r}(this.openAPI,s.replace("#/","").split("/")):A(e);let{type:o}=n;const{properties:i,additionalProperties:a,items:c,anyOf:p,oneOf:l,allOf:h}=n;if(h){let e={};return h.forEach(s=>{const n=this.sampleFromSchema(s,t,new Set(r));e={...e,...n}}),e}if(!o)if(i)o="object";else if(c)o="array";else{if(!p&&!l)return null;o="union"}if("null"===o)return null;if("object"===o){const e=A(i),s={};for(const n in e)s[n]=this.sampleFromSchema(e[n],[...t||[],n],new Set(r));if(!0===a)return s.additionalProp1={},s;if(a){const e=A(a),n=this.sampleFromSchema(e,t,new Set(r));for(let e=1;e<4;e+=1)s[`additionalProp${e}`]=n}return s}if("array"===o){const e=this.sampleFromSchema(c,t,new Set(r));return new Array(parseInt((20*Math.random()).toFixed(0),10)).fill(e)}if("union"===o){const e=p||l,s=e&&e.length||0;if(s){const n=function(e,t){const r=Math.ceil(e),s=Math.floor(t);return Math.floor(Math.random()*(s-r)+r)}(0,s);return this.sampleFromSchema(e[n],t,new Set(r))}}return n.enum?n.default?n.default:(m=n.enum,Array.isArray(m)?m:[m])[0]:"file"===o?null:function(e,t){const r=A(e),{type:s,format:n}=r,o=x[`${s}_${n||C(t)}`]||x[s];return void 0===r.example?o||`Unknown Type: ${r.type}`:r.example}(n,t);var m};parser=()=>{const e={...this.openAPI};for(const t in e.paths)for(const r in e.paths[t]){const s=e.paths[t][r];for(const e in s.responses){const t=s.responses[e],r=Object.keys(t.content||{});if(r.length){let e;e=r.includes("application/json")?"application/json":r.includes("*/*")?"*/*":r[0];const s=F(t.content[e]);s&&(t.example=s?this.sampleFromSchema(s):null)}}if(s.parameters)for(const e of s.parameters){const t=F(e);e.example=t?this.sampleFromSchema(t):null}}return e}}i.Random.extend({country(){const e=["阿根廷","澳大利亚","巴西","加拿大","中国","法国","德国","印度","印度尼西亚","意大利","日本","韩国","墨西哥","俄罗斯","沙特阿拉伯","南非","土耳其","英国","美国"];return e[(Math.random()*e.length).toFixed()]},phone(){return this.pick(["111","112","114"])+i.mock(/\d{8}/)},status:()=>["success","error","default","processing","warning"][(4*Math.random()).toFixed(0)],authority(){const e=["admin","user","guest"];return e[(Math.random()*e.length).toFixed(0)]},avatar(){const e=["https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg","https://gw.alipayobjects.com/zos/rmsportal/udxAbMEhpwthVVcjLXik.png","https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png","https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png","https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png","https://avatars0.githubusercontent.com/u/507615?s=40&v=4","https://avatars1.githubusercontent.com/u/8186664?s=40&v=4"];return e[(Math.random()*e.length).toFixed()]},group(){const e=["体验技术部","创新科技组","前端 6 组","区块链平台部","服务技术部"];return e[(Math.random()*e.length).toFixed()]},label(){const e=["很有想法的","小清新","傻白甜","阳光少年","大咖","健身达人","程序员","算法工程师","川妹子","名望程序员","大长腿","海纳百川","专注设计","爱好广泛","IT 互联网"];return e[(Math.random()*e.length).toFixed()]},href(){const e=["https://preview.pro.ant.design/dashboard/analysis","https://ant.design","https://procomponents.ant.design/","https://umijs.org/","https://github.com/umijs/dumi"];return e[(Math.random()*e.length).toFixed()]}});const S=async({openAPI:e,mockFolder:t,mockConfig:r})=>{const s=new N(e).parser(),n=Object.keys(s.paths),{paths:o}=s,c={};n.forEach(e=>{const t=o[e];Object.keys(t).forEach(s=>{const n=t[s];if(n){let t=(n.operationId||n?.tags?.join("/")||e.replace("/","").split("/")[1])?.replace(/[^\w^\s^\u4e00-\u9fa5]/gi,"");if(/[\u3220-\uFA29]/.test(t)&&(t=d.convertToPinyin(t,"",!0)),!t)return;const a=(o=n.responses?.[200]?.example,o?"string"==typeof o||Array.isArray(o)?i.mock(o):Object.keys(o).map(e=>({[e]:i.mock(o[e])})).reduce((e,t)=>({...e,...t}),{}):{});c[t]||(c[t]=[]);const p=(({method:e,path:t,parameters:r,status:s,data:n,mockConfig:o})=>{if(!["get","put","post","delete","patch"].includes(e.toLocaleLowerCase()))return"";let i=t;return r?.forEach(e=>{"path"===e.in&&(i=i.replace(`{${e.name}}`,`:${e.name}`))}),o.msw?`'${e.toUpperCase()} ${i}': ${n}`:`'${e.toUpperCase()} ${i}': (req: Request, res: Response) => {\n res.status(${s}).send(${n});\n }`})({method:s,path:e,parameters:n.parameters,status:"200",data:JSON.stringify(a),mockConfig:r});p&&c[t].push(p)}var o})}),Object.keys(c).forEach(e=>{if(e&&"undefined"!==e){if(e.includes("/")){const r=l(h(t,`${e}.ts`));a.existsSync(r)||a.mkdirSync(r)}T(t,`${e}.ts`,((e,t)=>O(` \n// @ts-ignore\n${t.msw?"":"import { Request, Response } from 'express'"}\n\n\nexport default {\n${e.join("\n,")}\n }`)[0])(c[e],r))}}),v("✅ 生成 mock 文件成功")},I=j(import.meta.url),q=l(I),D=e=>{if($.check(e))return`__openAPI__${e}`;let t=e.split("/").pop().split(".").pop().replace(/[-_ ](\w)/g,(e,t)=>t.toUpperCase()).replace(/[^\w^\s^\u4e00-\u9fa5]/gi,"");if("_"===t||/^\d+$/.test(t))return v("⚠️ models不能以number开头,原因可能是Model定义名称为中文, 建议联系后台修改"),`Pinyin_${t}`;if(/^\d/.test(t)){const e=parseInt(t[0]);t=`${P.toWords(e)}${t.substring(1)}`}if(!/[\u3220-\uFA29]/.test(t)&&!/^\d$/.test(t))return t;const r=t.replace(/ +/g,"");return d.convertToPinyin(r,"",!0)};function _(e){if("object"!=typeof e||!e.$ref)return e;const t=e.$ref.split("/");return D(t[t.length-1])}const L=(e,t="")=>{if(null==e)return"any";if("object"!=typeof e)return e;if(e.$ref)return[t,_(e)].filter(e=>e).join(".");let{type:r}=e;const s=["integer","long","float","double","number","int","float","double","int32","int64"];if("null"===r)return"null";if(s.includes(e.format)&&(r="number"),e.enum&&(r="enum"),s.includes(r))return"number";if(["Date","date","dateTime","date-time","datetime"].includes(r))return"Date";if(["string","email","password","url","byte","binary"].includes(r))return"string";if("boolean"===r)return"boolean";if("array"===r){let{items:r}=e;if(e.schema&&(r=e.schema.items),Array.isArray(r)){return`[${r.map(e=>L(e.schema||e,t)).toString()}]`}const s=L(r,t);return s.includes(" | ")?`(${s})[]`:`${s}[]`}return"enum"===r?Array.isArray(e.enum)?Array.from(new Set(e.enum.map(e=>"string"==typeof e?`"${e.replace(/"/g,'"')}"`:L(e)))).join(" | "):"string":e.oneOf&&e.oneOf.length?e.oneOf.map(e=>L(e,t)).join(" | "):e.anyOf&&e.anyOf.length?e.anyOf.map(e=>L(e,t)).join(" | "):e.allOf&&e.allOf.length?`(${e.allOf.map(e=>L(e,t)).join(" & ")})`:"object"===e.type||e.properties?Object.keys(e.properties||{}).length?`{ ${Object.keys(e.properties).map(r=>{let s=!1;return u(e.required)&&e.required&&(s=!0),f(e.required)&&e.required.includes(r)&&(s=!0),"required"in(e.properties[r]||{})&&(e.properties[r]||{}).required&&(s=!0),`'${r}'${s?"":"?"}: ${L(e.properties&&e.properties[r],t)}; `}).join("")}}`:"Record<string, any>":"any"},E={type:"object",properties:{id:{type:"number"}}},R={in:"path",name:null,schema:{type:"string"},required:!0,isObject:!1,type:"string"};function W(e,t,r){return e["x-swagger-router-controller"]?[e["x-swagger-router-controller"]]:e.tags||[e.operationId]||[t.replace("/","").split("/")[1]]}class M{apiData={};classNameList=[];version;mappings=[];finalPath;config;openAPIData;constructor(e,t){this.finalPath="",this.config={projectName:"api",templatesFolder:h(q,"../","templates"),...e},this.config.hook?.afterOpenApiDataInited?this.openAPIData=this.config.hook.afterOpenApiDataInited(t)||t:this.openAPIData=t;const{info:r}=this.openAPIData;this.version=r.version;const s=this.config.hook?.customFileNames||W,n=this.config.specifiedPaths;Object.keys(this.openAPIData.paths||{}).forEach(e=>{if(n?.length&&!n.includes(e))return;const t=this.openAPIData.paths[e];["get","put","post","delete","patch"].forEach(r=>{const n=t[r];if(!n)return;let o=s(n,e,r);o||(o=W(n,e)),o.forEach(t=>{const s=this.config.isCamelCase?m(D(t)):D(t);this.apiData[s]||(this.apiData[s]=[]),this.apiData[s].push({path:`${e}`,method:r,...n})})})})}async genFile(){const e=this.config.serversPath||"./src/service";try{const t=h(e,this.config.projectName);this.finalPath=t,console.log(y.sync(`${t}/**/*`),"xxxxxxxxx"),y.sync(`${t}/**/*`).filter(e=>!e.includes("_deperated")).forEach(e=>{w.sync(e)})}catch(e){v(`🚥 serves 生成失败: ${e}`)}await this.genFileFromTemplate("typings.d.ts","interface",{namespace:this.config.namespace,nullable:this.config.nullable,list:this.getInterfaceTP(),disableTypeCheck:!1,declareType:this.config.declareType||"type",equalSymbol:"type"===(this.config.declareType||"type")?"=":""});const t=[];for(const e of this.getServiceTP()){const r="serviceController",s=await this.genFileFromTemplate(this.getFinalFileName(`${e.className}.ts`),r,{namespace:this.config.namespace,requestOptionsType:this.config.requestOptionsType,requestImportStatement:this.config.requestImportStatement,disableTypeCheck:!1,...e});t.push(s)}t.includes(!0)&&v("🚥 格式化失败,请检查 service 文件内可能存在的语法错误"),await this.genFileFromTemplate("index.ts","serviceIndex",{list:this.classNameList,disableTypeCheck:!1}),v("✅ 成功生成 service 文件")}concatOrNull=(...e)=>{const t=[].concat(...e.filter(Array.isArray));return t.length>0?t:null};getFuncationName(e){const t=this.getBasePrefix(Object.keys(this.openAPIData.paths));return this.config.hook&&this.config.hook.customFunctionName?this.config.hook.customFunctionName(e):e.operationId?this.resolveFunctionName(e.operationId.replace(/[-_ .](\w)/g,(e,t)=>t.toUpperCase()),e.method):e.method+this.genDefaultFunctionName(e.path,t)}getTypeName(e){const t=this.config.namespace?`${this.config.namespace}.`:"",r=this.config?.hook?.customTypeName?.(e)||this.getFuncationName(e);return D(`${t}${r??e.operationId}Params`)}getServiceTP(){return Object.keys(this.apiData).map((e,t)=>{const r={},s=this.apiData[e].filter(e=>!e.path.includes("${")).map(t=>{const s=t;try{const t=this.getParamsTP(s.parameters,s.path),n=this.getBodyTP(s.requestBody),o=this.getResponseTP(s.responses),i=t||{},a=this.getFileTP(s.requestBody);let c=!1;(n&&(n.mediaType||"").includes("form-data")||a)&&(c=!0);let p=this.getFuncationName(s);p&&r[p]?p=`${p}_${r[p]+=1}`:p&&(r[p]=1);let l=s.path.replace(/:([^/]*)|{([^}]*)}/gi,(e,t,r)=>`\${${t||r}}`);if(s.extensions&&s.extensions["x-antTech-description"]){const{extensions:e}=s,{apiName:t,antTechVersion:r,productCode:n,antTechApiName:o}=e["x-antTech-description"];l=o||l,this.mappings.push({antTechApi:l,popAction:t,popProduct:n,antTechVersion:r}),s.antTechVersion=r}const h=i;h&&h.query&&(h.query=h.query.map(e=>({...e,isComplexType:e.isObject})));const u=()=>{if(!this.config.apiPrefix)return l;const t="function"==typeof this.config.apiPrefix?`${this.config.apiPrefix({path:l,method:s.method,namespace:e,functionName:p})}`.trim():this.config.apiPrefix.trim();if(!t)return l;if(t.startsWith("'")||t.startsWith('"')||t.startsWith("`")){const e=t.slice(1,t.length-1);return l.startsWith(e)||l.startsWith(`/${e}`)?l:`${e}${l}`}return`/${t}${l}`};return{...s,functionName:this.config.isCamelCase?m(p):p,typeName:this.getTypeName(s),path:u(),pathInComment:l.replace(/\*/g,"&#42;"),hasPathVariables:l.includes("{"),hasApiPrefix:!!this.config.apiPrefix,method:s.method,desc:p===s.summary?s.description:[s.summary,s.description,s.responses?.default?.description?`返回值: ${(s.responses?.default).description}`:""].filter(e=>e).join(" "),hasHeader:!(!i||!i.header)||!(!n||!n.mediaType),params:h,hasParams:Boolean(Object.keys(h||{}).length),options:this.config.hook?.customOptionsDefaultValue?.(s)||{},body:n,file:a,hasFormData:c,response:o}}catch(e){throw console.error("[GenSDK] gen service param error:",e),e}}).sort((e,t)=>e.path.localeCompare(t.path)),n=this.replaceDot(e)||`api${t}`;let o=n;return this.config.hook&&this.config.hook.customClassName&&(o=this.config.hook.customClassName(e)),s.length&&this.classNameList.push({fileName:o,controllerName:o}),{genType:"ts",className:o,instanceName:`${n[0]?.toLowerCase()}${n.substr(1)}`,list:s}}).filter(e=>!!e?.list?.length)}getBodyTP(e={}){const t=this.resolveRefObject(e);if(!t)return null;const r=t.content;if("object"!=typeof r||r&&0===Object.keys(r).length)return null;let s=Object.keys(r)[0];const n=r[s].schema||E;"*/*"===s&&(s="");const o="boolean"==typeof e.required&&e.required;if("object"===n.type&&n.properties){const e=Object.keys(n.properties).map(e=>{if(n.properties&&n.properties[e]&&!["binary","base64"].includes(n.properties[e].format||"")&&(!["string[]","array"].includes(n.properties[e].type||"")||!["binary","base64"].includes(n.properties[e].items.format||"")))return{key:e,schema:{...n.properties[e],type:this.getType(n.properties[e],this.config.namespace),required:n.required?.includes(e)??!1}}}).filter(e=>e);return{mediaType:s,...n,required:o,propertiesList:e}}return{mediaType:s,required:o,type:this.getType(n,this.config.namespace)}}getFileTP(e={}){const t=this.resolveRefObject(e);if(t&&t.content&&t.content["multipart/form-data"]){const e=this.resolveFileTP(t.content["multipart/form-data"].schema);return e.length>0?e:null}return null}resolveFileTP(e){let t=[];const r=this.resolveObject(e),s=r.props&&r.props.length>0&&r.props[0].filter(e=>"binary"===e.format||"base64"===e.format||("string[]"===e.type||"array"===e.type)&&("binary"===e.items.format||"base64"===e.items.format))||[];return s.length>0&&(t=s.map(e=>({title:e.name,multiple:"string[]"===e.type||"array"===e.type}))),r.type&&(t=[...t,...this.resolveFileTP(r.type)]),t}getResponseTP(e={}){const{components:t}=this.openAPIData,r=e&&this.resolveRefObject(e.default||e[200]||e[201]),s={mediaType:"*/*",type:"any"};if(!r)return s;const n=r.content,o=Object.keys(n||{}),i=o.includes("application/json")?"application/json":o[0];if("object"!=typeof n||!i)return s;let a=n[i].schema||E;if(a.$ref){const e=a.$ref.split("/"),r=e[e.length-1],s=t.schemas[r];"object"===s?.type&&"properties"in s&&this.config.dataFields&&(a=this.config.dataFields.map(e=>s.properties[e]).filter(Boolean)?.[0]||n[i].schema||E)}return"properties"in a&&Object.keys(a.properties).map(e=>{a.properties[e].required=a.required?.includes(e)??!1}),{mediaType:i,type:this.getType(a,this.config.namespace)}}getParamsTP(e=[],t=null){const r={};if(e&&e.length&&["query","path","cookie"].forEach(t=>{const s=e.map(e=>this.resolveRefObject(e)).filter(e=>e.in===t).map(e=>{const t="object"===((e.schema||{}).type||e.type),r=((e.schema||{}).$ref||e.$ref||"").split("/"),s=r[r.length-1],n="object"===((Object.entries(this.openAPIData.components&&this.openAPIData.components.schemas||{}).find(([e])=>e===s)||[])[1]||{}).type;return{...e,isObject:t||n,type:this.getType(e.schema||E,this.config.namespace)}});s.length&&(r[t]=s)}),t&&t.length>0){const e=/\{(\w+)\}/g;r.path=r.path||[];let s=null;for(;s=e.exec(t);)r.path.some(e=>e.name===s[1])||r.path.push({...R,name:s[1]});r.path.length||delete r.path}return r}collectRefs(e,t){if(e&&"object"==typeof e){if(e.$ref){const r=e.$ref.replace("#/components/schemas/","");if(!t.has(r)){t.add(r);const{components:e}=this.openAPIData;e?.schemas?.[r]&&this.collectRefs(e.schemas[r],t)}return}for(const r of Object.values(e))this.collectRefs(r,t)}}getInterfaceTP(){const{components:e}=this.openAPIData,t=this.config.specifiedPaths;let r=null;!!t?.length&&(r=new Set,t.forEach(e=>{const t=this.openAPIData.paths?.[e];t&&this.collectRefs(t,r)}));const s=e&&e.schemas&&[e.schemas].map(e=>{if(!e)return null;return Object.keys(e).filter(e=>!r||r.has(e)).map(t=>{const r=this.resolveObject(e[t]);return{typeName:D(t),type:r.type?"object"===e[t].type||r.type:"Record<string, any>",parent:r.parent,props:r.props||[],isEnum:r.isEnum}})}),n=Object.keys(this.openAPIData.paths||{});return(t?.length?n.filter(e=>t.includes(e)):n).forEach(e=>{const t=this.openAPIData.paths[e];["get","put","post","delete","patch"].forEach(r=>{const n=t[r];if(!n)return;n.parameters=n.parameters?.filter(e=>"header"!==e?.in);const o=[];n.parameters&&n.parameters.forEach(e=>{o.push({desc:e.description??"",name:e.name,required:e.required,type:this.getType(e.schema)})}),t.parameters&&t.parameters.forEach(e=>{o.push({desc:e.description??"",name:e.name,required:e.required,type:this.getType(e.schema)})}),o.length>0&&s&&s.push([{typeName:this.getTypeName({...n,method:r,path:e}),type:"Record<string, any>",parent:void 0,props:[o],isEnum:!1}])})}),s&&s.reduce((e,t)=>e&&t&&e.concat(t),[]).sort((e,t)=>e.typeName.localeCompare(t.typeName))}async genFileFromTemplate(e,t,r){try{const s=this.getTemplate(t);return b.configure({autoescape:!1}),await T(this.finalPath,e,b.renderString(s,r))}catch(r){throw console.error("[GenSDK] file gen fail:",e,"type:",t),r}}getTemplate(e){return c(h(this.config.templatesFolder,`${e}.njk`),"utf8")}getProps(e){const t=e?.required??!1;return e.properties?Object.keys(e.properties).map(r=>{const s=e.properties&&e.properties[r]||E;return{...s,name:r,type:this.getType(s),desc:[s.title,s.description].filter(e=>e).join(" "),required:!!t&&t.some(e=>e===r)}}):[]}getType(e,t){const r=this.config.hook?.customType;if(r){const s=r(e,t,L);if("string"==typeof s)return s}return L(e,t)}resolveObject(e){return(e=e??{}).$ref?this.resolveRefObject(e):e.enum?this.resolveEnumObject(e):e.allOf&&e.allOf.length?this.resolveAllOfObject(e):e.properties?this.resolveProperties(e):e.items&&"array"===e.type?this.resolveArray(e):e}resolveArray(e){if(e.items.$ref){const t=e.items.$ref.split("/");return{type:`${t[t.length-1]}[]`}}return"any[]"}resolveProperties(e){return{props:[this.getProps(e)]}}resolveEnumObject(e){const t=e.enum;let r;switch(this.config.enumStyle){case"enum":r=`{${t.map(e=>`${e}="${e}"`).join(",")}}`;break;case"string-literal":r=Array.from(new Set(t.map(e=>"string"==typeof e?`"${e.replace(/"/g,'"')}"`:this.getType(e)))).join(" | ")}return{isEnum:"enum"==this.config.enumStyle,type:Array.isArray(t)?r:"string"}}resolveAllOfObject(e){const t=(e.allOf||[]).map(e=>e.$ref?[{...e,type:this.getType(e).split("/").pop()}]:this.getProps(e));if(e.properties){const r=this.getProps(e);return{props:[...t,r]}}return{props:t}}genDefaultFunctionName(e,t){function r(e){return e.charAt(0).toUpperCase()+e.slice(1)}return e?.replace(t,"").split("/").map(e=>{let t=D(e);return t.includes("-")&&(t=t.replace(/(-\w)+/g,(e,t)=>t?.slice(1).toUpperCase())),t.match(/^{.+}$/gim)?`By${r(t.slice(1,t.length-1))}`:r(t)}).join("")}getBasePrefix(e){const t=[];e.map(e=>e.split("/")).forEach(e=>{e.forEach((e,r)=>{t.length<=r&&(t[r]=[]),t[r].push(e)})});const r=[];return t.map(e=>Array.from(new Set(e))).every(e=>{const t=1===e.length;return t&&r.push(e),t}),`${r.join("/")}/`}resolveRefObject(e){if(!e||!e.$ref)return e;const t=e.$ref.split("/");if("#"===t[0]){t.shift();let r=this.openAPIData;if(t.forEach(e=>{r=r[e]}),!r)throw new Error(`[GenSDK] Data Error! Notfoud: ${e.$ref}`);return{...this.resolveRefObject(r),type:r.$ref?this.resolveRefObject(r).type:r}}return e}getFinalFileName(e){return e.replace(/[-_ ](\w)/g,(e,t)=>t.toUpperCase())}replaceDot(e){return e.replace(/\./g,"_").replace(/[-_ ](\w)/g,(e,t)=>t.toUpperCase())}resolveFunctionName(e,t){return $.check(e)?`${e}Using${t.toUpperCase()}`:e}}const U=async(n,o)=>{if(n.startsWith("http")){const e=n.startsWith("https:")?r:t;try{const t=new e.Agent({rejectUnauthorized:!1}),r={};o&&(r.authorization=o);return await s(n,{agent:t,headers:r}).then(e=>e.json())}catch(e){console.log("fetch openapi error:",e)}return null}const i=e(n,"utf-8");return JSON.parse(i)},B=async(e,t)=>{const r=await U(e,t);if(!r)return null;a.writeFileSync("debug-output.json",JSON.stringify(r,null,2));var s;return await(s=r,s.swagger?new Promise((e,t)=>{n.convertObj(s,{},(r,s)=>{v(["💺 将 Swagger 转化为 openAPI"]),r?t(r):e(s.openapi)})}):s)},z=async({authorization:e,requestLibPath:t,schemaPath:r,mockFolder:s,nullable:n=!1,requestOptionsType:o="{[key: string]: any}",...i})=>{const a=(e=>e&&e.startsWith("import")?e:e?`import request from '${e}'`:'import { request } from "umi"')(t),c={namespace:"API",requestOptionsType:o,requestImportStatement:a,enumStyle:"string-literal",nullable:n,isCamelCase:!0,mockConfig:{},...i};i.specifiedPaths?.length&&v([`🔄 指定更新: ${i.projectName} (${i.specifiedPaths.length} 个接口)`]);const p=await B(r,e);if(!p)return void v([`⚠️ 获取文档失败: ${r}`]);const l=new M(c,p);await l.genFile(),s&&!i.specifiedPaths?.length&&await S({openAPI:p,mockFolder:s||"./mocks/",mockConfig:i.mockConfig||{}})},V=async e=>{const t=Array.isArray(e)?e:[e];for(const e of t)await z(e)};export{U as getSchema,V as ttOpenAPI};
1
+ import{readFileSync as e}from"node:fs";import t from"http";import r from"https";import s from"node-fetch";import n from"swagger2openapi";import o from"chalk";import i from"mockjs";import a,{readFileSync as c}from"fs";import p,{dirname as l,join as h}from"path";import{camelCase as m,isBoolean as u,isArray as f}from"lodash-es";import g from"memoizee";import d from"tiny-pinyin";import y from"glob";import b from"nunjucks";import{fileURLToPath as j}from"url";import $ from"reserved-words";import P from"rimraf";import w from"number-to-words";const v=(...e)=>console.log(`${o.blue("[openAPI]")}: ${e.join("\n")}`),k=e=>{a.existsSync(e)||(k(p.dirname(e)),a.mkdirSync(e))},O=async e=>{let t=e,r=!1;try{const r=await import("prettier"),s=await r.resolveConfig(process.cwd());t=await r.format(e,{parser:"typescript",...s,singleQuote:!0})}catch(e){console.error("Prettier error:",e),r=!0}return[t,r]},T=async(e,t,r)=>{const s=p.join(e,t);k(p.dirname(s));const[n,o]=await O(r);return a.writeFileSync(s,n,{encoding:"utf8"}),o};function A(e){return(t=e)&&"object"==typeof t?e:{};var t}function F(e){return e.schema?e.schema:e.properties?{...e,type:"object"}:e}var C={string:"@string",string_email:"@email",string_phone:"@phone",string_username:"@cname",string_url:"@url",string_uuid:"@guid",string_id:"@increment",string_status:"@status",string_authority:"@authority",string_label:"@label",string_group:"@group",string_csentence:"@csentence",string_cname:"@cname",string_name:"@last",string_errorCode:"@increment",string_country:"@country",string_county:"@county(true)",string_province:"@province",string_city:"@city",string_avatar:"@avatar",string_href:"@href","string_string(16)":"@string(16)","string_date-time":"@datetime",string_date:"@date",number:"@integer(60, 100)",number_float:"@float(60, 100, 3, 5)",integer:"@integer(60, 100)",boolean:"@boolean"};const N=(e,t)=>{if(!e||e.length<1)return"string";if(Array.isArray(e))return N([...e].pop(),e);if(["nickname","name"].includes(e))return"cname";if(["owner","firstName","lastName","username"].includes(e))return"name";if(["avatar"].includes(e))return"avatar";if(["group"].includes(e))return"group";if(e.toLocaleLowerCase().endsWith("id"))return"uuid";if(e.toLocaleLowerCase().endsWith("type")||e.toLocaleLowerCase().endsWith("key")||["key"].includes(e))return"id";if(e.toLocaleLowerCase().endsWith("label")||["label"].includes(e)){const e=[...t];e.pop();const r=N(e);return"string"!==r&&"csentence"!==r?r:"label"}return["email"].includes(e)?"email":["password"].includes(e)?"string(16)":["phone"].includes(e)?"phone":["province"].includes(e)?"province":["city"].includes(e)?"city":["addr","address"].includes(e)?"county":["country"].includes(e)?"country":["url","imageUrl","href"].includes(e)||e.toLocaleLowerCase().endsWith("url")||e.toLocaleLowerCase().endsWith("urls")||e.toLocaleLowerCase().endsWith("image")||e.toLocaleLowerCase().endsWith("link")?"href":e.toLocaleLowerCase().endsWith("errorcode")?"errorCode":["type","status"].includes(e)||e.toLocaleLowerCase().endsWith("status")||e.toLocaleLowerCase().endsWith("type")?"status":e.toLocaleLowerCase().endsWith("authority")?"authority":"csentence"};class x{openAPI;constructor(e){this.openAPI=e,this.sampleFromSchema=g(this.sampleFromSchema)}sampleFromSchema=(e,t,r=new Set)=>{const s=e?.$ref;if(s){if(r.has(s))return null;r.add(s)}const n=s?function(e,t){let r=e;for(let e=0;e<t.length;e+=1){if(null==r)return;r=r[t[e]]}return r}(this.openAPI,s.replace("#/","").split("/")):A(e);let{type:o}=n;const{properties:i,additionalProperties:a,items:c,anyOf:p,oneOf:l,allOf:h}=n;if(h){let e={};return h.forEach(s=>{const n=this.sampleFromSchema(s,t,new Set(r));e={...e,...n}}),e}if(!o)if(i)o="object";else if(c)o="array";else{if(!p&&!l)return null;o="union"}if("null"===o)return null;if("object"===o){const e=A(i),s={};for(const n in e)s[n]=this.sampleFromSchema(e[n],[...t||[],n],new Set(r));if(!0===a)return s.additionalProp1={},s;if(a){const e=A(a),n=this.sampleFromSchema(e,t,new Set(r));for(let e=1;e<4;e+=1)s[`additionalProp${e}`]=n}return s}if("array"===o){const e=this.sampleFromSchema(c,t,new Set(r));return new Array(parseInt((20*Math.random()).toFixed(0),10)).fill(e)}if("union"===o){const e=p||l,s=e&&e.length||0;if(s){const n=function(e,t){const r=Math.ceil(e),s=Math.floor(t);return Math.floor(Math.random()*(s-r)+r)}(0,s);return this.sampleFromSchema(e[n],t,new Set(r))}}return n.enum?n.default?n.default:(m=n.enum,Array.isArray(m)?m:[m])[0]:"file"===o?null:function(e,t){const r=A(e),{type:s,format:n}=r,o=C[`${s}_${n||N(t)}`]||C[s];return void 0===r.example?o||`Unknown Type: ${r.type}`:r.example}(n,t);var m};parser=()=>{const e={...this.openAPI};for(const t in e.paths)for(const r in e.paths[t]){const s=e.paths[t][r];for(const e in s.responses){const t=s.responses[e],r=Object.keys(t.content||{});if(r.length){let e;e=r.includes("application/json")?"application/json":r.includes("*/*")?"*/*":r[0];const s=F(t.content[e]);s&&(t.example=s?this.sampleFromSchema(s):null)}}if(s.parameters)for(const e of s.parameters){const t=F(e);e.example=t?this.sampleFromSchema(t):null}}return e}}i.Random.extend({country(){const e=["阿根廷","澳大利亚","巴西","加拿大","中国","法国","德国","印度","印度尼西亚","意大利","日本","韩国","墨西哥","俄罗斯","沙特阿拉伯","南非","土耳其","英国","美国"];return e[(Math.random()*e.length).toFixed()]},phone(){return this.pick(["111","112","114"])+i.mock(/\d{8}/)},status:()=>["success","error","default","processing","warning"][(4*Math.random()).toFixed(0)],authority(){const e=["admin","user","guest"];return e[(Math.random()*e.length).toFixed(0)]},avatar(){const e=["https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg","https://gw.alipayobjects.com/zos/rmsportal/udxAbMEhpwthVVcjLXik.png","https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png","https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png","https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png","https://avatars0.githubusercontent.com/u/507615?s=40&v=4","https://avatars1.githubusercontent.com/u/8186664?s=40&v=4"];return e[(Math.random()*e.length).toFixed()]},group(){const e=["体验技术部","创新科技组","前端 6 组","区块链平台部","服务技术部"];return e[(Math.random()*e.length).toFixed()]},label(){const e=["很有想法的","小清新","傻白甜","阳光少年","大咖","健身达人","程序员","算法工程师","川妹子","名望程序员","大长腿","海纳百川","专注设计","爱好广泛","IT 互联网"];return e[(Math.random()*e.length).toFixed()]},href(){const e=["https://preview.pro.ant.design/dashboard/analysis","https://ant.design","https://procomponents.ant.design/","https://umijs.org/","https://github.com/umijs/dumi"];return e[(Math.random()*e.length).toFixed()]}});const S=async({openAPI:e,mockFolder:t,mockConfig:r})=>{const s=new x(e).parser(),n=Object.keys(s.paths),{paths:o}=s,c={};n.forEach(e=>{const t=o[e];Object.keys(t).forEach(s=>{const n=t[s];if(n){let t=(n.operationId||n?.tags?.join("/")||e.replace("/","").split("/")[1])?.replace(/[^\w^\s^\u4e00-\u9fa5]/gi,"");if(/[\u3220-\uFA29]/.test(t)&&(t=d.convertToPinyin(t,"",!0)),!t)return;const a=(o=n.responses?.[200]?.example,o?"string"==typeof o||Array.isArray(o)?i.mock(o):Object.keys(o).map(e=>({[e]:i.mock(o[e])})).reduce((e,t)=>({...e,...t}),{}):{});c[t]||(c[t]=[]);const p=(({method:e,path:t,parameters:r,status:s,data:n,mockConfig:o})=>{if(!["get","put","post","delete","patch"].includes(e.toLocaleLowerCase()))return"";let i=t;return r?.forEach(e=>{"path"===e.in&&(i=i.replace(`{${e.name}}`,`:${e.name}`))}),o.msw?`'${e.toUpperCase()} ${i}': ${n}`:`'${e.toUpperCase()} ${i}': (req: Request, res: Response) => {\n res.status(${s}).send(${n});\n }`})({method:s,path:e,parameters:n.parameters,status:"200",data:JSON.stringify(a),mockConfig:r});p&&c[t].push(p)}var o})}),Object.keys(c).forEach(e=>{if(e&&"undefined"!==e){if(e.includes("/")){const r=l(h(t,`${e}.ts`));a.existsSync(r)||a.mkdirSync(r)}T(t,`${e}.ts`,((e,t)=>O(` \n// @ts-ignore\n${t.msw?"":"import { Request, Response } from 'express'"}\n\n\nexport default {\n${e.join("\n,")}\n }`)[0])(c[e],r))}}),v("✅ 生成 mock 文件成功")},I=j(import.meta.url),q=l(I),D=e=>{if($.check(e))return`__openAPI__${e}`;let t=e.split("/").pop().split(".").pop().replace(/[-_ ](\w)/g,(e,t)=>t.toUpperCase()).replace(/[^\w^\s^\u4e00-\u9fa5]/gi,"");if("_"===t||/^\d+$/.test(t))return v("⚠️ models不能以number开头,原因可能是Model定义名称为中文, 建议联系后台修改"),`Pinyin_${t}`;if(/^\d/.test(t)){const e=parseInt(t[0]);t=`${w.toWords(e)}${t.substring(1)}`}if(!/[\u3220-\uFA29]/.test(t)&&!/^\d$/.test(t))return t;const r=t.replace(/ +/g,"");return d.convertToPinyin(r,"",!0)};function _(e){if("object"!=typeof e||!e.$ref)return e;const t=e.$ref.split("/");return D(t[t.length-1])}const L=(e,t="")=>{if(null==e)return"any";if("object"!=typeof e)return e;if(e.$ref)return[t,_(e)].filter(e=>e).join(".");let{type:r}=e;const s=["integer","long","float","double","number","int","float","double","int32","int64"];if("null"===r)return"null";if(s.includes(e.format)&&(r="number"),e.enum&&(r="enum"),s.includes(r))return"number";if(["Date","date","dateTime","date-time","datetime"].includes(r))return"Date";if(["string","email","password","url","byte","binary"].includes(r))return"string";if("boolean"===r)return"boolean";if("array"===r){let{items:r}=e;if(e.schema&&(r=e.schema.items),Array.isArray(r)){return`[${r.map(e=>L(e.schema||e,t)).toString()}]`}const s=L(r,t);return s.includes(" | ")?`(${s})[]`:`${s}[]`}return"enum"===r?Array.isArray(e.enum)?Array.from(new Set(e.enum.map(e=>"string"==typeof e?`"${e.replace(/"/g,'"')}"`:L(e)))).join(" | "):"string":e.oneOf&&e.oneOf.length?e.oneOf.map(e=>L(e,t)).join(" | "):e.anyOf&&e.anyOf.length?e.anyOf.map(e=>L(e,t)).join(" | "):e.allOf&&e.allOf.length?`(${e.allOf.map(e=>L(e,t)).join(" & ")})`:"object"===e.type||e.properties?Object.keys(e.properties||{}).length?`{ ${Object.keys(e.properties).map(r=>{let s=!1;return u(e.required)&&e.required&&(s=!0),f(e.required)&&e.required.includes(r)&&(s=!0),"required"in(e.properties[r]||{})&&(e.properties[r]||{}).required&&(s=!0),`'${r}'${s?"":"?"}: ${L(e.properties&&e.properties[r],t)}; `}).join("")}}`:"Record<string, any>":"any"},E={type:"object",properties:{id:{type:"number"}}},R={in:"path",name:null,schema:{type:"string"},required:!0,isObject:!1,type:"string"};function W(e,t,r){return e["x-swagger-router-controller"]?[e["x-swagger-router-controller"]]:e.tags||[e.operationId]||[t.replace("/","").split("/")[1]]}class M{apiData={};classNameList=[];version;mappings=[];finalPath;config;openAPIData;constructor(e,t){this.finalPath="",this.config={projectName:"api",templatesFolder:h(q,"../","templates"),...e},this.config.hook?.afterOpenApiDataInited?this.openAPIData=this.config.hook.afterOpenApiDataInited(t)||t:this.openAPIData=t;const{info:r}=this.openAPIData;this.version=r.version;const s=this.config.hook?.customFileNames||W,n=this.config.specifiedPaths;Object.keys(this.openAPIData.paths||{}).forEach(e=>{if(n?.length&&!n.includes(e))return;const t=this.openAPIData.paths[e];["get","put","post","delete","patch"].forEach(r=>{const n=t[r];if(!n)return;let o=s(n,e,r);o||(o=W(n,e)),o.forEach(t=>{const s=this.config.isCamelCase?m(D(t)):D(t);this.apiData[s]||(this.apiData[s]=[]),this.apiData[s].push({path:`${e}`,method:r,...n})})})})}async genFile(){const e=this.config.serversPath||"./src/service";try{const t=h(e,this.config.projectName);this.finalPath=t,y.sync(`${t}/**/*`).filter(e=>!e.includes("_deperated")).forEach(e=>{P.sync(e)})}catch(e){v(`🚥 serves 生成失败: ${e}`)}await this.genFileFromTemplate("typings.d.ts","interface",{namespace:this.config.namespace,nullable:this.config.nullable,list:this.getInterfaceTP(),disableTypeCheck:!1,declareType:this.config.declareType||"type",equalSymbol:"type"===(this.config.declareType||"type")?"=":""});const t=[];for(const e of this.getServiceTP()){const r="serviceController",s=await this.genFileFromTemplate(this.getFinalFileName(`${e.className}.ts`),r,{namespace:this.config.namespace,requestOptionsType:this.config.requestOptionsType,requestImportStatement:this.config.requestImportStatement,disableTypeCheck:!1,...e});t.push(s)}t.includes(!0)&&v("🚥 格式化失败,请检查 service 文件内可能存在的语法错误"),await this.genFileFromTemplate("index.ts","serviceIndex",{list:this.classNameList,disableTypeCheck:!1}),v("✅ 成功生成 service 文件")}concatOrNull=(...e)=>{const t=[].concat(...e.filter(Array.isArray));return t.length>0?t:null};getFuncationName(e){const t=this.getBasePrefix(Object.keys(this.openAPIData.paths));return this.config.hook&&this.config.hook.customFunctionName?this.config.hook.customFunctionName(e):e.operationId?this.resolveFunctionName(e.operationId.replace(/[-_ .](\w)/g,(e,t)=>t.toUpperCase()),e.method):e.method+this.genDefaultFunctionName(e.path,t)}getTypeName(e){const t=this.config.namespace?`${this.config.namespace}.`:"",r=this.config?.hook?.customTypeName?.(e)||this.getFuncationName(e);return D(`${t}${r??e.operationId}Params`)}getServiceTP(){return Object.keys(this.apiData).map((e,t)=>{const r={},s=this.apiData[e].filter(e=>!e.path.includes("${")).map(t=>{const s=t;try{const t=this.getParamsTP(s.parameters,s.path),n=this.getBodyTP(s.requestBody),o=this.getResponseTP(s.responses),i=t||{},a=this.getFileTP(s.requestBody);let c=!1;(n&&(n.mediaType||"").includes("form-data")||a)&&(c=!0);let p=this.getFuncationName(s);p&&r[p]?p=`${p}_${r[p]+=1}`:p&&(r[p]=1);let l=s.path.replace(/:([^/]*)|{([^}]*)}/gi,(e,t,r)=>`\${${t||r}}`);if(s.extensions&&s.extensions["x-antTech-description"]){const{extensions:e}=s,{apiName:t,antTechVersion:r,productCode:n,antTechApiName:o}=e["x-antTech-description"];l=o||l,this.mappings.push({antTechApi:l,popAction:t,popProduct:n,antTechVersion:r}),s.antTechVersion=r}const h=i;h&&h.query&&(h.query=h.query.map(e=>({...e,isComplexType:e.isObject})));const u=()=>{if(!this.config.apiPrefix)return l;const t="function"==typeof this.config.apiPrefix?`${this.config.apiPrefix({path:l,method:s.method,namespace:e,functionName:p})}`.trim():this.config.apiPrefix.trim();if(!t)return l;if(t.startsWith("'")||t.startsWith('"')||t.startsWith("`")){const e=t.slice(1,t.length-1);return l.startsWith(e)||l.startsWith(`/${e}`)?l:`${e}${l}`}return`/${t}${l}`};return{...s,functionName:this.config.isCamelCase?m(p):p,typeName:this.getTypeName(s),path:u(),pathInComment:l.replace(/\*/g,"&#42;"),hasPathVariables:l.includes("{"),hasApiPrefix:!!this.config.apiPrefix,method:s.method,desc:p===s.summary?s.description:[s.summary,s.description,s.responses?.default?.description?`返回值: ${(s.responses?.default).description}`:""].filter(e=>e).join(" "),hasHeader:!(!i||!i.header)||!(!n||!n.mediaType),params:h,hasParams:Boolean(Object.keys(h||{}).length),options:this.config.hook?.customOptionsDefaultValue?.(s)||{},body:n,file:a,hasFormData:c,response:o}}catch(e){throw console.error("[GenSDK] gen service param error:",e),e}}).sort((e,t)=>e.path.localeCompare(t.path)),n=this.replaceDot(e)||`api${t}`;let o=n;return this.config.hook&&this.config.hook.customClassName&&(o=this.config.hook.customClassName(e)),s.length&&this.classNameList.push({fileName:o,controllerName:o}),{genType:"ts",className:o,instanceName:`${n[0]?.toLowerCase()}${n.substr(1)}`,list:s}}).filter(e=>!!e?.list?.length)}getBodyTP(e={}){const t=this.resolveRefObject(e);if(!t)return null;const r=t.content;if("object"!=typeof r||r&&0===Object.keys(r).length)return null;let s=Object.keys(r)[0];const n=r[s].schema||E;"*/*"===s&&(s="");const o="boolean"==typeof e.required&&e.required;if("object"===n.type&&n.properties){const e=Object.keys(n.properties).map(e=>{if(n.properties&&n.properties[e]&&!["binary","base64"].includes(n.properties[e].format||"")&&(!["string[]","array"].includes(n.properties[e].type||"")||!["binary","base64"].includes(n.properties[e].items.format||"")))return{key:e,schema:{...n.properties[e],type:this.getType(n.properties[e],this.config.namespace),required:n.required?.includes(e)??!1}}}).filter(e=>e);return{mediaType:s,...n,required:o,propertiesList:e}}return{mediaType:s,required:o,type:this.getType(n,this.config.namespace)}}getFileTP(e={}){const t=this.resolveRefObject(e);if(t&&t.content&&t.content["multipart/form-data"]){const e=this.resolveFileTP(t.content["multipart/form-data"].schema);return e.length>0?e:null}return null}resolveFileTP(e){let t=[];const r=this.resolveObject(e),s=r.props&&r.props.length>0&&r.props[0].filter(e=>"binary"===e.format||"base64"===e.format||("string[]"===e.type||"array"===e.type)&&("binary"===e.items.format||"base64"===e.items.format))||[];return s.length>0&&(t=s.map(e=>({title:e.name,multiple:"string[]"===e.type||"array"===e.type}))),r.type&&(t=[...t,...this.resolveFileTP(r.type)]),t}getResponseTP(e={}){const{components:t}=this.openAPIData,r=e&&this.resolveRefObject(e.default||e[200]||e[201]),s={mediaType:"*/*",type:"any"};if(!r)return s;const n=r.content,o=Object.keys(n||{}),i=o.includes("application/json")?"application/json":o[0];if("object"!=typeof n||!i)return s;let a=n[i].schema||E;if(a.$ref){const e=a.$ref.split("/"),r=e[e.length-1],s=t.schemas[r];"object"===s?.type&&"properties"in s&&this.config.dataFields&&(a=this.config.dataFields.map(e=>s.properties[e]).filter(Boolean)?.[0]||n[i].schema||E)}return"properties"in a&&Object.keys(a.properties).map(e=>{a.properties[e].required=a.required?.includes(e)??!1}),{mediaType:i,type:this.getType(a,this.config.namespace)}}getParamsTP(e=[],t=null){const r={};if(e&&e.length&&["query","path","cookie"].forEach(t=>{const s=e.map(e=>this.resolveRefObject(e)).filter(e=>e.in===t).map(e=>{const t="object"===((e.schema||{}).type||e.type),r=((e.schema||{}).$ref||e.$ref||"").split("/"),s=r[r.length-1],n="object"===((Object.entries(this.openAPIData.components&&this.openAPIData.components.schemas||{}).find(([e])=>e===s)||[])[1]||{}).type;return{...e,isObject:t||n,type:this.getType(e.schema||E,this.config.namespace)}});s.length&&(r[t]=s)}),t&&t.length>0){const e=/\{(\w+)\}/g;r.path=r.path||[];let s=null;for(;s=e.exec(t);)r.path.some(e=>e.name===s[1])||r.path.push({...R,name:s[1]});r.path.length||delete r.path}return r}collectRefs(e,t){if(e&&"object"==typeof e){if(e.$ref){const r=e.$ref.replace("#/components/schemas/","");if(!t.has(r)){t.add(r);const{components:e}=this.openAPIData;e?.schemas?.[r]&&this.collectRefs(e.schemas[r],t)}return}for(const r of Object.values(e))this.collectRefs(r,t)}}getInterfaceTP(){const{components:e}=this.openAPIData,t=this.config.specifiedPaths;let r=null;!!t?.length&&(r=new Set,t.forEach(e=>{const t=this.openAPIData.paths?.[e];t&&this.collectRefs(t,r)}));const s=e&&e.schemas&&[e.schemas].map(e=>{if(!e)return null;return Object.keys(e).filter(e=>!r||r.has(e)).map(t=>{const r=this.resolveObject(e[t]);return{typeName:D(t),type:r.type?"object"===e[t].type||r.type:"Record<string, any>",parent:r.parent,props:r.props||[],isEnum:r.isEnum}})}),n=Object.keys(this.openAPIData.paths||{});return(t?.length?n.filter(e=>t.includes(e)):n).forEach(e=>{const t=this.openAPIData.paths[e];["get","put","post","delete","patch"].forEach(r=>{const n=t[r];if(!n)return;n.parameters=n.parameters?.filter(e=>"header"!==e?.in);const o=[];n.parameters&&n.parameters.forEach(e=>{o.push({desc:e.description??"",name:e.name,required:e.required,type:this.getType(e.schema)})}),t.parameters&&t.parameters.forEach(e=>{o.push({desc:e.description??"",name:e.name,required:e.required,type:this.getType(e.schema)})}),o.length>0&&s&&s.push([{typeName:this.getTypeName({...n,method:r,path:e}),type:"Record<string, any>",parent:void 0,props:[o],isEnum:!1}])})}),s&&s.reduce((e,t)=>e&&t&&e.concat(t),[]).sort((e,t)=>e.typeName.localeCompare(t.typeName))}async genFileFromTemplate(e,t,r){try{const s=this.getTemplate(t);return b.configure({autoescape:!1}),await T(this.finalPath,e,b.renderString(s,r))}catch(r){throw console.error("[GenSDK] file gen fail:",e,"type:",t),r}}getTemplate(e){return c(h(this.config.templatesFolder,`${e}.njk`),"utf8")}getProps(e){const t=e?.required??!1;return e.properties?Object.keys(e.properties).map(r=>{const s=e.properties&&e.properties[r]||E;return{...s,name:r,type:this.getType(s),desc:[s.title,s.description].filter(e=>e).join(" "),required:!!t&&t.some(e=>e===r)}}):[]}getType(e,t){const r=this.config.hook?.customType;if(r){const s=r(e,t,L);if("string"==typeof s)return s}return L(e,t)}resolveObject(e){return(e=e??{}).$ref?this.resolveRefObject(e):e.enum?this.resolveEnumObject(e):e.allOf&&e.allOf.length?this.resolveAllOfObject(e):e.properties?this.resolveProperties(e):e.items&&"array"===e.type?this.resolveArray(e):e}resolveArray(e){if(e.items.$ref){const t=e.items.$ref.split("/");return{type:`${t[t.length-1]}[]`}}return"any[]"}resolveProperties(e){return{props:[this.getProps(e)]}}resolveEnumObject(e){const t=e.enum;let r;switch(this.config.enumStyle){case"enum":r=`{${t.map(e=>`${e}="${e}"`).join(",")}}`;break;case"string-literal":r=Array.from(new Set(t.map(e=>"string"==typeof e?`"${e.replace(/"/g,'"')}"`:this.getType(e)))).join(" | ")}return{isEnum:"enum"==this.config.enumStyle,type:Array.isArray(t)?r:"string"}}resolveAllOfObject(e){const t=(e.allOf||[]).map(e=>e.$ref?[{...e,type:this.getType(e).split("/").pop()}]:this.getProps(e));if(e.properties){const r=this.getProps(e);return{props:[...t,r]}}return{props:t}}genDefaultFunctionName(e,t){function r(e){return e.charAt(0).toUpperCase()+e.slice(1)}return e?.replace(t,"").split("/").map(e=>{let t=D(e);return t.includes("-")&&(t=t.replace(/(-\w)+/g,(e,t)=>t?.slice(1).toUpperCase())),t.match(/^{.+}$/gim)?`By${r(t.slice(1,t.length-1))}`:r(t)}).join("")}getBasePrefix(e){const t=[];e.map(e=>e.split("/")).forEach(e=>{e.forEach((e,r)=>{t.length<=r&&(t[r]=[]),t[r].push(e)})});const r=[];return t.map(e=>Array.from(new Set(e))).every(e=>{const t=1===e.length;return t&&r.push(e),t}),`${r.join("/")}/`}resolveRefObject(e){if(!e||!e.$ref)return e;const t=e.$ref.split("/");if("#"===t[0]){t.shift();let r=this.openAPIData;if(t.forEach(e=>{r=r[e]}),!r)throw new Error(`[GenSDK] Data Error! Notfoud: ${e.$ref}`);return{...this.resolveRefObject(r),type:r.$ref?this.resolveRefObject(r).type:r}}return e}getFinalFileName(e){return e.replace(/[-_ ](\w)/g,(e,t)=>t.toUpperCase())}replaceDot(e){return e.replace(/\./g,"_").replace(/[-_ ](\w)/g,(e,t)=>t.toUpperCase())}resolveFunctionName(e,t){return $.check(e)?`${e}Using${t.toUpperCase()}`:e}}const U=async(n,o)=>{if(n.startsWith("http")){const e=n.startsWith("https:")?r:t;try{const t=new e.Agent({rejectUnauthorized:!1}),r={};o&&(r.authorization=o);return await s(n,{agent:t,headers:r}).then(e=>e.json())}catch(e){console.log("fetch openapi error:",e)}return null}const i=e(n,"utf-8");return JSON.parse(i)},B=async(e,t)=>{const r=await U(e,t);if(!r)return null;var s;return await(s=r,s.swagger?new Promise((e,t)=>{n.convertObj(s,{},(r,s)=>{v(["💺 将 Swagger 转化为 openAPI"]),r?t(r):e(s.openapi)})}):s)},z=async({authorization:e,requestLibPath:t,schemaPath:r,mockFolder:s,nullable:n=!1,requestOptionsType:o="{[key: string]: any}",...i})=>{const a=(e=>e&&e.startsWith("import")?e:e?`import request from '${e}'`:'import { request } from "umi"')(t),c={namespace:"API",requestOptionsType:o,requestImportStatement:a,enumStyle:"string-literal",nullable:n,isCamelCase:!0,mockConfig:{},...i};i.specifiedPaths?.length&&v([`🔄 指定更新: ${i.projectName} (${i.specifiedPaths.length} 个接口)`]);const p=await B(r,e);if(!p)return void v([`⚠️ 获取文档失败: ${r}`]);const l=new M(c,p);await l.genFile(),s&&!i.specifiedPaths?.length&&await S({openAPI:p,mockFolder:s||"./mocks/",mockConfig:i.mockConfig||{}})},V=async e=>{const t=Array.isArray(e)?e:[e];for(const e of t)await z(e)};export{U as getSchema,V as ttOpenAPI};
2
2
  //# sourceMappingURL=index.esm.js.map