@fxri/swagger2api 1.1.5 → 1.1.7

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/README.md CHANGED
@@ -96,9 +96,9 @@ npx @fxri/swagger2api
96
96
 
97
97
  ```json
98
98
  {
99
- "url": "https://example.com/v3/api-docs",
100
- "output": "./src/api",
101
- "name": "index"
99
+ "url": "https://example.com/v3/api-docs",
100
+ "output": "./src/api",
101
+ "name": "index"
102
102
  }
103
103
  ```
104
104
 
@@ -130,6 +130,8 @@ api.getUsers().then((res) => console.log(res))
130
130
  | `--remove-param,-rp` | boolean | `false` | 移除{.+}参数 |
131
131
  | `--remove-prefix-index,-rpi` | number | `-1` | 移除前缀索引 |
132
132
  | `--remove-dts,-rd` | boolean | `false` | 移除使用--js参数时生成的d.ts文件 |
133
+ | `--extract-request-query,-erq` | string | - | 提取参数,将query参数中的指定对象字段提取为根部字段,支持多选,用【,】分隔,每个接口只提取第一次命中的字段 |
134
+ | `--extract-response-raw,-err` | boolean | `false` | 提取响应,将AxiosResponse返回值转移到raw字段,根部字段自己定义 |
133
135
 
134
136
  扩展:[更多 swagger-typescript-api 配置选项](https://fig.io/manual/swagger-typescript-api)
135
137
 
@@ -149,39 +151,6 @@ npx @fxri/swagger2api [--quick,-q] [--quick,-q <boolean>]
149
151
  npx swagger2api [--config,-c <path>]
150
152
 
151
153
  npx @fxri/swagger2api [--config,-c <path>]
152
- ```
153
-
154
- ```bash
155
- # 加载全部配置文件,不进行选择
156
-
157
- npx swagger2api [--config-all,-ca] [--config-all,-ca <boolean>]
158
-
159
- npx @fxri/swagger2api [--config-all,-ca] [--config-all,-ca <boolean>]
160
- ```
161
-
162
- ```bash
163
- # 扫描全部配置文件,并提供选择列表,该参数默认为true
164
-
165
- npx swagger2api [--config-scan,-cs] [--config-scan,-cs <boolean>]
166
-
167
- npx @fxri/swagger2api [--config-scan,-cs] [--config-scan,-cs <boolean>]
168
- ```
169
-
170
- ```bash
171
- # 转换无{.+}get为query
172
-
173
- npx swagger2api [--convert-get,-cg] [--convert-get,-cg <boolean>]
174
-
175
- npx @fxri/swagger2api [--convert-get,-cg] [--convert-get,-cg <boolean>]
176
- ```
177
-
178
- ```bash
179
- # 移除{.+}参数
180
-
181
- npx swagger2api [--remove-param,-rp] [--remove-param,-rp <boolean>]
182
-
183
- npx @fxri/swagger2api [--remove-param,-rp] [--remove-param,-rp <boolean>]
184
- ```
185
154
 
186
155
  ```bash
187
156
  # 移除前缀索引
@@ -191,14 +160,6 @@ npx swagger2api [--remove-prefix-index,-rpi <number>]
191
160
  npx @fxri/swagger2api [--remove-prefix-index,-rpi <number>]
192
161
  ```
193
162
 
194
- ```bash
195
- # 移除使用--js参数时生成的d.ts文件
196
-
197
- npx swagger2api [--remove-dts,-rd] [--remove-dts,-rd <boolean>]
198
-
199
- npx @fxri/swagger2api [--remove-dts,-rd] [--remove-dts,-rd <boolean>]
200
- ```
201
-
202
163
  ## 🤝 贡献
203
164
 
204
165
  欢迎提交 Issue 和 Pull Request!
package/dist/cli.cjs ADDED
@@ -0,0 +1 @@
1
+ var $=Object.create;var v=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var E=Object.getPrototypeOf,_=Object.prototype.hasOwnProperty;var C=(e,r,s,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of k(r))!_.call(e,i)&&i!==s&&v(e,i,{get:()=>r[i],enumerable:!(o=T(r,i))||o.enumerable});return e};var l=(e,r,s)=>(s=e!=null?$(E(e)):{},C(r||!e||!e.__esModule?v(s,"default",{value:e,enumerable:!0}):s,e));var R=l(require("axios"),1),j=require("child_process"),A=l(require("os"),1),g=l(require("fs"),1),c=l(require("path"),1),h=l(require("prompts"),1),F=require("swagger-typescript-api");var b=e=>/^(https?:\/\/|:?\/\/)/.test(e);var f=l(require("fs"),1),w=l(require("url"),1),d=l(require("path"),1),L={},u={param:process.argv.filter((e,r)=>r>1),used:{}};function S(e,r=!0,s=!0){Array.isArray(e)||(e=[e]);let o;return u.param.forEach((i,p)=>{if(e.includes(i))r?(o=u.param[p+1],s&&Object.assign(u.used,{[p+1]:!0})):["true","false"].includes(u.param[p+1])?(o=u.param[p+1].toLowerCase()=="true",s&&Object.assign(u.used,{[p+1]:!0})):o=!0;else return;s&&Object.assign(u.used,{[p]:!0})}),o}function t(e,r=!0){return S(e,!1,r)}function m(e,r=!0){return S(e,!0,r)}function y(e,r){let s=d.default.dirname(e);f.default.existsSync(s)||f.default.mkdirSync(s,{recursive:!0}),f.default.writeFileSync(e,r)}function I(){return typeof require<"u"&&typeof module<"u"?__filename:w.default.fileURLToPath(L.url)}function P(){return typeof require<"u"&&typeof module<"u"?__dirname:d.default.dirname(I())}var O=require("glob"),a={files:[],param:{}},n={home:A.default.homedir(),enum:{}};function x(e){e&&console.log(e),process.exit()}async function J(){n.param={config:m(["--config","-c"]),configScan:t(["--config-scan","-cs"]),configAll:t(["--config-all","-ca"]),quick:t(["--quick","-q"]),convertGet:t(["--convert-get","-cg"]),removeParam:t(["--remove-param","-rp"]),removePrefixIndex:m(["--remove-prefix-index","-rpi"]),removeDts:t(["--remove-dts","-rd"]),extractRequestQuery:m(["--extract-request-query","-erq"]),extractResponseRaw:t(["--extract-response-raw","-err"]),template:c.default.resolve(P(),"./templates")},n.config={templates:m(["--templates","-t"])??n.param.template,defaultResponseAsSuccess:t(["--default-as-success","-d"]),generateResponses:t(["--responses","-r"]),generateUnionEnums:t("--union-enums"),addReadonly:t("--add-readonly"),generateRouteTypes:t("--route-types"),generateClient:!t("--no-client"),enumNamesAsValues:t("--enum-names-as-values"),extractRequestParams:t("--extract-request-params"),extractRequestBody:t("--extract-request-body"),extractResponseBody:t("--extract-response-body"),extractResponseError:t("--extract-response-error"),modular:t("--modular"),toJS:t("--js"),moduleNameIndex:Number(m("--module-name-index")??0),moduleNameFirstTag:t("--module-name-first-tag"),httpClientType:t("--axios")?"axios":"fetch",unwrapResponseData:t("--unwrap-response-data"),disableThrowOnError:t("--disable-throw-on-error"),singleHttpClient:t("--single-http-client"),silent:t("--silent"),defaultResponseType:m("--default-response")??"void",typePrefix:m("--type-prefix")??"",typeSuffix:m("--type-suffix")??"",cleanOutput:t("--clean-output"),...m("--api-class-name")?{apiClassName:m("--api-class-name")}:{},patch:t("--patch"),debug:t("--debug"),anotherArrayType:t("--another-array-type"),sortTypes:t("--sort-types"),extractEnums:t("--extract-enums")}}async function U(){n.param.config?a.files=n.param.config.split(","):(n.param.configScan??!0)&&(a.files=O.glob.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),a.files.length==0&&(a.files=["saconfig.json"]),!n.param.configAll&&a.files.length>1&&(a.files=(await(0,h.default)({type:"multiselect",name:"files",message:"\u9009\u62E9\u914D\u7F6E\u6587\u4EF6",hint:"\u53EF\u591A\u9009\uFF0C\u7A7A\u683C\u952E\u52FE\u9009\uFF0C\u56DE\u8F66\u5B8C\u6210",choices:a.files.map(e=>({title:e.replace(/\\/g,"/"),value:e}))}).then(e=>e.files?.length!=0?e:x("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),a.files?.length>0||x("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function G(){try{a.param={},a.param=JSON.parse(g.default.readFileSync(a.file,"utf-8"))}catch{}(!n.param.quick||[a.param.url,a.param.output,a.param.name].includes(void 0))&&(a.param=await(0,h.default)([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:a.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:a.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:a.param.name??"index"}])),[a.param.url,a.param.output,a.param.name].includes(void 0)&&x("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),n.docFile=c.default.resolve(`${a.param.output}/${a.param.name}-${new Date().getTime()}.json`)}async function D(e=0){if(a.file=a.files[e],await G(),b(a.param.url))await R.default.get(a.param.url).then(r=>q(r.data)).catch(r=>console.log("\u5931\u8D25\uFF1A",r));else try{await q(JSON.parse(g.default.readFileSync(c.default.resolve(a.param.url),"utf8")))}catch(r){console.log("\u5931\u8D25\uFF1A",r)}a.files[e+1]&&D(e+1)}async function q(e){if(typeof e?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");Object.entries(e.paths).forEach(r=>{Object.keys(r[1]).forEach(s=>{let o=`${r[0]}/${s}`;if(n.param.convertGet&&(o=o.replace(/([^\}]\/)get$/g,"$1query")),n.param.removeParam&&(o=o.replace(/\/\{.+?\}/g,"")),n.param.removePrefixIndex){let p=o.split("/");p=p.slice(0,1).concat(p.slice(Number(n.param.removePrefixIndex)+2)),o=p.join("/")}e.paths[r[0]][s].operationId=o;let i=o.split("/").slice(-1)[0];typeof n.enum[i]=="number"?n.enum[i]++:n.enum[i]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(n.enum).map(r=>r.join("-"))),y(n.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",a.file),await(0,F.generateApi)({fileName:`${a.param.name}.ts`,output:c.default.resolve(a.param.output),input:n.docFile,...n.config,param:n.param}),g.default.unlinkSync(n.docFile),n.param.removeDts&&(console.log("\u6E05\u7406\uFF1A",c.default.resolve(a.param.output,`${a.param.name}.d.ts`)),(0,j.execSync)(`npx rimraf ${c.default.resolve(a.param.output,`${a.param.name}.d.ts`)}`,{cwd:n.home}).toString()),y(a.file,JSON.stringify(a.param,null,2))}async function N(){await J(),await U(),D()}N();
package/dist/cli.js ADDED
@@ -0,0 +1 @@
1
+ var c=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,s)=>(typeof require<"u"?require:n)[s]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import A from"axios";import{execSync as F}from"child_process";import O from"os";import y from"fs";import l from"path";import S from"prompts";import{generateApi as D}from"swagger-typescript-api";var x=e=>/^(https?:\/\/|:?\/\/)/.test(e);import f from"fs";import R from"url";import h from"path";var m={param:process.argv.filter((e,n)=>n>1),used:{}};function v(e,n=!0,s=!0){Array.isArray(e)||(e=[e]);let o;return m.param.forEach((u,i)=>{if(e.includes(u))n?(o=m.param[i+1],s&&Object.assign(m.used,{[i+1]:!0})):["true","false"].includes(m.param[i+1])?(o=m.param[i+1].toLowerCase()=="true",s&&Object.assign(m.used,{[i+1]:!0})):o=!0;else return;s&&Object.assign(m.used,{[i]:!0})}),o}function t(e,n=!0){return v(e,!1,n)}function p(e,n=!0){return v(e,!0,n)}function g(e,n){let s=h.dirname(e);f.existsSync(s)||f.mkdirSync(s,{recursive:!0}),f.writeFileSync(e,n)}function j(){return typeof c<"u"&&typeof module<"u"?__filename:R.fileURLToPath(import.meta.url)}function b(){return typeof c<"u"&&typeof module<"u"?__dirname:h.dirname(j())}import{glob as N}from"glob";var a={files:[],param:{}},r={home:O.homedir(),enum:{}};function d(e){e&&console.log(e),process.exit()}async function $(){r.param={config:p(["--config","-c"]),configScan:t(["--config-scan","-cs"]),configAll:t(["--config-all","-ca"]),quick:t(["--quick","-q"]),convertGet:t(["--convert-get","-cg"]),removeParam:t(["--remove-param","-rp"]),removePrefixIndex:p(["--remove-prefix-index","-rpi"]),removeDts:t(["--remove-dts","-rd"]),extractRequestQuery:p(["--extract-request-query","-erq"]),extractResponseRaw:t(["--extract-response-raw","-err"]),template:l.resolve(b(),"./templates")},r.config={templates:p(["--templates","-t"])??r.param.template,defaultResponseAsSuccess:t(["--default-as-success","-d"]),generateResponses:t(["--responses","-r"]),generateUnionEnums:t("--union-enums"),addReadonly:t("--add-readonly"),generateRouteTypes:t("--route-types"),generateClient:!t("--no-client"),enumNamesAsValues:t("--enum-names-as-values"),extractRequestParams:t("--extract-request-params"),extractRequestBody:t("--extract-request-body"),extractResponseBody:t("--extract-response-body"),extractResponseError:t("--extract-response-error"),modular:t("--modular"),toJS:t("--js"),moduleNameIndex:Number(p("--module-name-index")??0),moduleNameFirstTag:t("--module-name-first-tag"),httpClientType:t("--axios")?"axios":"fetch",unwrapResponseData:t("--unwrap-response-data"),disableThrowOnError:t("--disable-throw-on-error"),singleHttpClient:t("--single-http-client"),silent:t("--silent"),defaultResponseType:p("--default-response")??"void",typePrefix:p("--type-prefix")??"",typeSuffix:p("--type-suffix")??"",cleanOutput:t("--clean-output"),...p("--api-class-name")?{apiClassName:p("--api-class-name")}:{},patch:t("--patch"),debug:t("--debug"),anotherArrayType:t("--another-array-type"),sortTypes:t("--sort-types"),extractEnums:t("--extract-enums")}}async function T(){r.param.config?a.files=r.param.config.split(","):(r.param.configScan??!0)&&(a.files=N.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),a.files.length==0&&(a.files=["saconfig.json"]),!r.param.configAll&&a.files.length>1&&(a.files=(await S({type:"multiselect",name:"files",message:"\u9009\u62E9\u914D\u7F6E\u6587\u4EF6",hint:"\u53EF\u591A\u9009\uFF0C\u7A7A\u683C\u952E\u52FE\u9009\uFF0C\u56DE\u8F66\u5B8C\u6210",choices:a.files.map(e=>({title:e.replace(/\\/g,"/"),value:e}))}).then(e=>e.files?.length!=0?e:d("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),a.files?.length>0||d("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function k(){try{a.param={},a.param=JSON.parse(y.readFileSync(a.file,"utf-8"))}catch{}(!r.param.quick||[a.param.url,a.param.output,a.param.name].includes(void 0))&&(a.param=await S([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:a.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:a.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:a.param.name??"index"}])),[a.param.url,a.param.output,a.param.name].includes(void 0)&&d("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),r.docFile=l.resolve(`${a.param.output}/${a.param.name}-${new Date().getTime()}.json`)}async function P(e=0){if(a.file=a.files[e],await k(),x(a.param.url))await A.get(a.param.url).then(n=>w(n.data)).catch(n=>console.log("\u5931\u8D25\uFF1A",n));else try{await w(JSON.parse(y.readFileSync(l.resolve(a.param.url),"utf8")))}catch(n){console.log("\u5931\u8D25\uFF1A",n)}a.files[e+1]&&P(e+1)}async function w(e){if(typeof e?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");Object.entries(e.paths).forEach(n=>{Object.keys(n[1]).forEach(s=>{let o=`${n[0]}/${s}`;if(r.param.convertGet&&(o=o.replace(/([^\}]\/)get$/g,"$1query")),r.param.removeParam&&(o=o.replace(/\/\{.+?\}/g,"")),r.param.removePrefixIndex){let i=o.split("/");i=i.slice(0,1).concat(i.slice(Number(r.param.removePrefixIndex)+2)),o=i.join("/")}e.paths[n[0]][s].operationId=o;let u=o.split("/").slice(-1)[0];typeof r.enum[u]=="number"?r.enum[u]++:r.enum[u]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(r.enum).map(n=>n.join("-"))),g(r.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",a.file),await D({fileName:`${a.param.name}.ts`,output:l.resolve(a.param.output),input:r.docFile,...r.config,param:r.param}),y.unlinkSync(r.docFile),r.param.removeDts&&(console.log("\u6E05\u7406\uFF1A",l.resolve(a.param.output,`${a.param.name}.d.ts`)),F(`npx rimraf ${l.resolve(a.param.output,`${a.param.name}.d.ts`)}`,{cwd:r.home}).toString()),g(a.file,JSON.stringify(a.param,null,2))}async function q(){await $(),await T(),P()}q();
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- var P=Object.create;var f=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var T=Object.getPrototypeOf,q=Object.prototype.hasOwnProperty;var D=(e,a)=>{for(var s in a)f(e,s,{get:a[s],enumerable:!0})},b=(e,a,s,n)=>{if(a&&typeof a=="object"||typeof a=="function")for(let i of E(a))!q.call(e,i)&&i!==s&&f(e,i,{get:()=>a[i],enumerable:!(n=A(a,i))||n.enumerable});return e};var m=(e,a,s)=>(s=e!=null?P(T(e)):{},b(a||!e||!e.__esModule?f(s,"default",{value:e,enumerable:!0}):s,e)),C=e=>b(f({},"__esModule",{value:!0}),e);var U={};D(U,{generateApi:()=>I});module.exports=C(U);var O=m(require("axios"),1),F=require("child_process"),N=m(require("os"),1),d=m(require("fs"),1),c=m(require("path"),1),x=m(require("prompts"),1),$=require("swagger-typescript-api");var v=e=>/^(https?:\/\/|:?\/\/)/.test(e);var g=m(require("fs"),1),w=m(require("path"),1),u={param:process.argv.filter((e,a)=>a>1),used:{}};function S(e,a=!0,s=!0){Array.isArray(e)||(e=[e]);let n;return u.param.forEach((i,p)=>{if(e.includes(i))a?(n=u.param[p+1],s&&Object.assign(u.used,{[p+1]:!0})):["true","false"].includes(u.param[p+1])?(n=u.param[p+1].toLowerCase()=="true",s&&Object.assign(u.used,{[p+1]:!0})):n=!0;else return;s&&Object.assign(u.used,{[p]:!0})}),n}function r(e,a=!0){return S(e,!1,a)}function o(e,a=!0){return S(e,!0,a)}function y(e,a){let s=w.default.dirname(e);g.default.existsSync(s)||g.default.mkdirSync(s,{recursive:!0}),g.default.writeFileSync(e,a)}var k=require("glob"),t={files:[],param:{}},l={home:N.default.homedir(),enum:{}};function h(e){e&&console.log(e),process.exit()}async function J(){o(["--config","-c"])?t.files=o(["--config","-c"]).split(","):(r(["--config-scan","-cs"])??!0)&&(t.files=k.glob.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),t.files.length==0&&(t.files=["saconfig.json"]),!r(["--config-all","-ca"])&&t.files.length>1&&(t.files=(await(0,x.default)({type:"multiselect",name:"files",message:"\u9009\u62E9\u914D\u7F6E\u6587\u4EF6",hint:"\u53EF\u591A\u9009\uFF0C\u7A7A\u683C\u952E\u52FE\u9009\uFF0C\u56DE\u8F66\u5B8C\u6210",choices:t.files.map(e=>({title:e.replace(/\\/g,"/"),value:e}))}).then(e=>e.files?.length!=0?e:h("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),t.files?.length>0||h("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function L(){try{t.param={},t.param=JSON.parse(d.default.readFileSync(t.file,"utf-8"))}catch{}(!r(["--quick","-q"])||[t.param.url,t.param.output,t.param.name].includes(void 0))&&(t.param=await(0,x.default)([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:t.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:t.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:t.param.name??"index"}])),[t.param.url,t.param.output,t.param.name].includes(void 0)&&h("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),l.docFile=c.default.resolve(`${t.param.output}/${t.param.name}-${new Date().getTime()}.json`)}async function R(e=0){if(t.file=t.files[e],await L(),v(t.param.url))await O.default.get(t.param.url).then(a=>j(a.data)).catch(a=>console.log("\u5931\u8D25\uFF1A",a));else try{await j(JSON.parse(d.default.readFileSync(c.default.resolve(t.param.url),"utf8")))}catch(a){console.log("\u5931\u8D25\uFF1A",a)}t.files[e+1]&&R(e+1)}async function j(e){if(typeof e?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");Object.entries(e.paths).forEach(a=>{Object.keys(a[1]).forEach(s=>{let n=`${a[0]}/${s}`;if(r(["--convert-get","-cg"])&&(n=n.replace(/([^\}]\/)get$/g,"$1query")),r(["--remove-param","-rp"])&&(n=n.replace(/\/\{.+?\}/g,"")),o(["--remove-prefix-index","-rpi"])){let p=n.split("/");p=p.slice(0,1).concat(p.slice(Number(o(["--remove-prefix-index","-rpi"]))+2)),n=p.join("/")}e.paths[a[0]][s].operationId=n;let i=n.split("/").slice(-1)[0];typeof l.enum[i]=="number"?l.enum[i]++:l.enum[i]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(l.enum).map(a=>a.join("-"))),y(l.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",t.file),await(0,$.generateApi)({fileName:`${t.param.name}.ts`,output:c.default.resolve(t.param.output),input:l.docFile,templates:o(["--templates","-t"]),defaultResponseAsSuccess:r(["--default-as-success","-d"]),generateResponses:r(["--responses","-r"]),generateUnionEnums:r("--union-enums"),addReadonly:r("--add-readonly"),generateRouteTypes:r("--route-types"),generateClient:!r("--no-client"),enumNamesAsValues:r("--enum-names-as-values"),extractRequestParams:r("--extract-request-params"),extractRequestBody:r("--extract-request-body"),extractResponseBody:r("--extract-response-body"),extractResponseError:r("--extract-response-error"),modular:r("--modular"),toJS:r("--js"),moduleNameIndex:Number(o("--module-name-index")??0),moduleNameFirstTag:r("--module-name-first-tag"),httpClientType:r("--axios")?"axios":"fetch",unwrapResponseData:r("--unwrap-response-data"),disableThrowOnError:r("--disable-throw-on-error"),singleHttpClient:r("--single-http-client"),silent:r("--silent"),defaultResponseType:o("--default-response")??"void",typePrefix:o("--type-prefix")??"",typeSuffix:o("--type-suffix")??"",cleanOutput:r("--clean-output"),...o("--api-class-name")?{apiClassName:o("--api-class-name")}:{},patch:r("--patch"),debug:r("--debug"),anotherArrayType:r("--another-array-type"),sortTypes:r("--sort-types"),extractEnums:r("--extract-enums")}),d.default.unlinkSync(l.docFile),r(["--remove-dts","-rd"])&&(console.log("\u6E05\u7406\uFF1A",c.default.resolve(t.param.output,`${t.param.name}.d.ts`)),(0,F.execSync)(`npx rimraf ${c.default.resolve(t.param.output,`${t.param.name}.d.ts`)}`,{cwd:l.home}).toString()),y(t.file,JSON.stringify(t.param,null,2))}async function I(){await J(),R()}0&&(module.exports={generateApi});
1
+ var $=Object.create;var f=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var E=Object.getPrototypeOf,_=Object.prototype.hasOwnProperty;var C=(e,t)=>{for(var o in t)f(e,o,{get:t[o],enumerable:!0})},b=(e,t,o,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of k(t))!_.call(e,i)&&i!==o&&f(e,i,{get:()=>t[i],enumerable:!(s=T(t,i))||s.enumerable});return e};var l=(e,t,o)=>(o=e!=null?$(E(e)):{},b(t||!e||!e.__esModule?f(o,"default",{value:e,enumerable:!0}):o,e)),I=e=>b(f({},"__esModule",{value:!0}),e);var K={};C(K,{generateApi:()=>B});module.exports=I(K);var j=l(require("axios"),1),F=require("child_process"),O=l(require("os"),1),d=l(require("fs"),1),c=l(require("path"),1),v=l(require("prompts"),1),A=require("swagger-typescript-api");var w=e=>/^(https?:\/\/|:?\/\/)/.test(e);var g=l(require("fs"),1),S=l(require("url"),1),y=l(require("path"),1),J={},u={param:process.argv.filter((e,t)=>t>1),used:{}};function P(e,t=!0,o=!0){Array.isArray(e)||(e=[e]);let s;return u.param.forEach((i,p)=>{if(e.includes(i))t?(s=u.param[p+1],o&&Object.assign(u.used,{[p+1]:!0})):["true","false"].includes(u.param[p+1])?(s=u.param[p+1].toLowerCase()=="true",o&&Object.assign(u.used,{[p+1]:!0})):s=!0;else return;o&&Object.assign(u.used,{[p]:!0})}),s}function r(e,t=!0){return P(e,!1,t)}function m(e,t=!0){return P(e,!0,t)}function x(e,t){let o=y.default.dirname(e);g.default.existsSync(o)||g.default.mkdirSync(o,{recursive:!0}),g.default.writeFileSync(e,t)}function L(){return typeof require<"u"&&typeof module<"u"?__filename:S.default.fileURLToPath(J.url)}function q(){return typeof require<"u"&&typeof module<"u"?__dirname:y.default.dirname(L())}var D=require("glob"),a={files:[],param:{}},n={home:O.default.homedir(),enum:{}};function h(e){e&&console.log(e),process.exit()}async function U(){n.param={config:m(["--config","-c"]),configScan:r(["--config-scan","-cs"]),configAll:r(["--config-all","-ca"]),quick:r(["--quick","-q"]),convertGet:r(["--convert-get","-cg"]),removeParam:r(["--remove-param","-rp"]),removePrefixIndex:m(["--remove-prefix-index","-rpi"]),removeDts:r(["--remove-dts","-rd"]),extractRequestQuery:m(["--extract-request-query","-erq"]),extractResponseRaw:r(["--extract-response-raw","-err"]),template:c.default.resolve(q(),"./templates")},n.config={templates:m(["--templates","-t"])??n.param.template,defaultResponseAsSuccess:r(["--default-as-success","-d"]),generateResponses:r(["--responses","-r"]),generateUnionEnums:r("--union-enums"),addReadonly:r("--add-readonly"),generateRouteTypes:r("--route-types"),generateClient:!r("--no-client"),enumNamesAsValues:r("--enum-names-as-values"),extractRequestParams:r("--extract-request-params"),extractRequestBody:r("--extract-request-body"),extractResponseBody:r("--extract-response-body"),extractResponseError:r("--extract-response-error"),modular:r("--modular"),toJS:r("--js"),moduleNameIndex:Number(m("--module-name-index")??0),moduleNameFirstTag:r("--module-name-first-tag"),httpClientType:r("--axios")?"axios":"fetch",unwrapResponseData:r("--unwrap-response-data"),disableThrowOnError:r("--disable-throw-on-error"),singleHttpClient:r("--single-http-client"),silent:r("--silent"),defaultResponseType:m("--default-response")??"void",typePrefix:m("--type-prefix")??"",typeSuffix:m("--type-suffix")??"",cleanOutput:r("--clean-output"),...m("--api-class-name")?{apiClassName:m("--api-class-name")}:{},patch:r("--patch"),debug:r("--debug"),anotherArrayType:r("--another-array-type"),sortTypes:r("--sort-types"),extractEnums:r("--extract-enums")}}async function G(){n.param.config?a.files=n.param.config.split(","):(n.param.configScan??!0)&&(a.files=D.glob.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),a.files.length==0&&(a.files=["saconfig.json"]),!n.param.configAll&&a.files.length>1&&(a.files=(await(0,v.default)({type:"multiselect",name:"files",message:"\u9009\u62E9\u914D\u7F6E\u6587\u4EF6",hint:"\u53EF\u591A\u9009\uFF0C\u7A7A\u683C\u952E\u52FE\u9009\uFF0C\u56DE\u8F66\u5B8C\u6210",choices:a.files.map(e=>({title:e.replace(/\\/g,"/"),value:e}))}).then(e=>e.files?.length!=0?e:h("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),a.files?.length>0||h("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function V(){try{a.param={},a.param=JSON.parse(d.default.readFileSync(a.file,"utf-8"))}catch{}(!n.param.quick||[a.param.url,a.param.output,a.param.name].includes(void 0))&&(a.param=await(0,v.default)([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:a.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:a.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:a.param.name??"index"}])),[a.param.url,a.param.output,a.param.name].includes(void 0)&&h("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),n.docFile=c.default.resolve(`${a.param.output}/${a.param.name}-${new Date().getTime()}.json`)}async function N(e=0){if(a.file=a.files[e],await V(),w(a.param.url))await j.default.get(a.param.url).then(t=>R(t.data)).catch(t=>console.log("\u5931\u8D25\uFF1A",t));else try{await R(JSON.parse(d.default.readFileSync(c.default.resolve(a.param.url),"utf8")))}catch(t){console.log("\u5931\u8D25\uFF1A",t)}a.files[e+1]&&N(e+1)}async function R(e){if(typeof e?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");Object.entries(e.paths).forEach(t=>{Object.keys(t[1]).forEach(o=>{let s=`${t[0]}/${o}`;if(n.param.convertGet&&(s=s.replace(/([^\}]\/)get$/g,"$1query")),n.param.removeParam&&(s=s.replace(/\/\{.+?\}/g,"")),n.param.removePrefixIndex){let p=s.split("/");p=p.slice(0,1).concat(p.slice(Number(n.param.removePrefixIndex)+2)),s=p.join("/")}e.paths[t[0]][o].operationId=s;let i=s.split("/").slice(-1)[0];typeof n.enum[i]=="number"?n.enum[i]++:n.enum[i]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(n.enum).map(t=>t.join("-"))),x(n.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",a.file),await(0,A.generateApi)({fileName:`${a.param.name}.ts`,output:c.default.resolve(a.param.output),input:n.docFile,...n.config,param:n.param}),d.default.unlinkSync(n.docFile),n.param.removeDts&&(console.log("\u6E05\u7406\uFF1A",c.default.resolve(a.param.output,`${a.param.name}.d.ts`)),(0,F.execSync)(`npx rimraf ${c.default.resolve(a.param.output,`${a.param.name}.d.ts`)}`,{cwd:n.home}).toString()),x(a.file,JSON.stringify(a.param,null,2))}async function B(){await U(),await G(),N()}0&&(module.exports={generateApi});
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import S from"axios";import{execSync as j}from"child_process";import O from"os";import d from"fs";import u from"path";import b from"prompts";import{generateApi as F}from"swagger-typescript-api";var y=t=>/^(https?:\/\/|:?\/\/)/.test(t);import c from"fs";import w from"path";var l={param:process.argv.filter((t,r)=>r>1),used:{}};function h(t,r=!0,i=!0){Array.isArray(t)||(t=[t]);let s;return l.param.forEach((m,o)=>{if(t.includes(m))r?(s=l.param[o+1],i&&Object.assign(l.used,{[o+1]:!0})):["true","false"].includes(l.param[o+1])?(s=l.param[o+1].toLowerCase()=="true",i&&Object.assign(l.used,{[o+1]:!0})):s=!0;else return;i&&Object.assign(l.used,{[o]:!0})}),s}function a(t,r=!0){return h(t,!1,r)}function n(t,r=!0){return h(t,!0,r)}function f(t,r){let i=w.dirname(t);c.existsSync(i)||c.mkdirSync(i,{recursive:!0}),c.writeFileSync(t,r)}import{glob as N}from"glob";var e={files:[],param:{}},p={home:O.homedir(),enum:{}};function g(t){t&&console.log(t),process.exit()}async function $(){n(["--config","-c"])?e.files=n(["--config","-c"]).split(","):(a(["--config-scan","-cs"])??!0)&&(e.files=N.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),e.files.length==0&&(e.files=["saconfig.json"]),!a(["--config-all","-ca"])&&e.files.length>1&&(e.files=(await b({type:"multiselect",name:"files",message:"\u9009\u62E9\u914D\u7F6E\u6587\u4EF6",hint:"\u53EF\u591A\u9009\uFF0C\u7A7A\u683C\u952E\u52FE\u9009\uFF0C\u56DE\u8F66\u5B8C\u6210",choices:e.files.map(t=>({title:t.replace(/\\/g,"/"),value:t}))}).then(t=>t.files?.length!=0?t:g("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),e.files?.length>0||g("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function k(){try{e.param={},e.param=JSON.parse(d.readFileSync(e.file,"utf-8"))}catch{}(!a(["--quick","-q"])||[e.param.url,e.param.output,e.param.name].includes(void 0))&&(e.param=await b([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:e.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:e.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:e.param.name??"index"}])),[e.param.url,e.param.output,e.param.name].includes(void 0)&&g("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),p.docFile=u.resolve(`${e.param.output}/${e.param.name}-${new Date().getTime()}.json`)}async function v(t=0){if(e.file=e.files[t],await k(),y(e.param.url))await S.get(e.param.url).then(r=>x(r.data)).catch(r=>console.log("\u5931\u8D25\uFF1A",r));else try{await x(JSON.parse(d.readFileSync(u.resolve(e.param.url),"utf8")))}catch(r){console.log("\u5931\u8D25\uFF1A",r)}e.files[t+1]&&v(t+1)}async function x(t){if(typeof t?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");Object.entries(t.paths).forEach(r=>{Object.keys(r[1]).forEach(i=>{let s=`${r[0]}/${i}`;if(a(["--convert-get","-cg"])&&(s=s.replace(/([^\}]\/)get$/g,"$1query")),a(["--remove-param","-rp"])&&(s=s.replace(/\/\{.+?\}/g,"")),n(["--remove-prefix-index","-rpi"])){let o=s.split("/");o=o.slice(0,1).concat(o.slice(Number(n(["--remove-prefix-index","-rpi"]))+2)),s=o.join("/")}t.paths[r[0]][i].operationId=s;let m=s.split("/").slice(-1)[0];typeof p.enum[m]=="number"?p.enum[m]++:p.enum[m]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(p.enum).map(r=>r.join("-"))),f(p.docFile,JSON.stringify(t)),console.log("\u6267\u884C\uFF1A",e.file),await F({fileName:`${e.param.name}.ts`,output:u.resolve(e.param.output),input:p.docFile,templates:n(["--templates","-t"]),defaultResponseAsSuccess:a(["--default-as-success","-d"]),generateResponses:a(["--responses","-r"]),generateUnionEnums:a("--union-enums"),addReadonly:a("--add-readonly"),generateRouteTypes:a("--route-types"),generateClient:!a("--no-client"),enumNamesAsValues:a("--enum-names-as-values"),extractRequestParams:a("--extract-request-params"),extractRequestBody:a("--extract-request-body"),extractResponseBody:a("--extract-response-body"),extractResponseError:a("--extract-response-error"),modular:a("--modular"),toJS:a("--js"),moduleNameIndex:Number(n("--module-name-index")??0),moduleNameFirstTag:a("--module-name-first-tag"),httpClientType:a("--axios")?"axios":"fetch",unwrapResponseData:a("--unwrap-response-data"),disableThrowOnError:a("--disable-throw-on-error"),singleHttpClient:a("--single-http-client"),silent:a("--silent"),defaultResponseType:n("--default-response")??"void",typePrefix:n("--type-prefix")??"",typeSuffix:n("--type-suffix")??"",cleanOutput:a("--clean-output"),...n("--api-class-name")?{apiClassName:n("--api-class-name")}:{},patch:a("--patch"),debug:a("--debug"),anotherArrayType:a("--another-array-type"),sortTypes:a("--sort-types"),extractEnums:a("--extract-enums")}),d.unlinkSync(p.docFile),a(["--remove-dts","-rd"])&&(console.log("\u6E05\u7406\uFF1A",u.resolve(e.param.output,`${e.param.name}.d.ts`)),j(`npx rimraf ${u.resolve(e.param.output,`${e.param.name}.d.ts`)}`,{cwd:p.home}).toString()),f(e.file,JSON.stringify(e.param,null,2))}async function G(){await $(),v()}export{G as generateApi};
1
+ var c=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,s)=>(typeof require<"u"?require:n)[s]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import j from"axios";import{execSync as F}from"child_process";import O from"os";import y from"fs";import l from"path";import S from"prompts";import{generateApi as A}from"swagger-typescript-api";var x=e=>/^(https?:\/\/|:?\/\/)/.test(e);import f from"fs";import q from"url";import h from"path";var m={param:process.argv.filter((e,n)=>n>1),used:{}};function v(e,n=!0,s=!0){Array.isArray(e)||(e=[e]);let o;return m.param.forEach((u,i)=>{if(e.includes(u))n?(o=m.param[i+1],s&&Object.assign(m.used,{[i+1]:!0})):["true","false"].includes(m.param[i+1])?(o=m.param[i+1].toLowerCase()=="true",s&&Object.assign(m.used,{[i+1]:!0})):o=!0;else return;s&&Object.assign(m.used,{[i]:!0})}),o}function t(e,n=!0){return v(e,!1,n)}function p(e,n=!0){return v(e,!0,n)}function g(e,n){let s=h.dirname(e);f.existsSync(s)||f.mkdirSync(s,{recursive:!0}),f.writeFileSync(e,n)}function R(){return typeof c<"u"&&typeof module<"u"?__filename:q.fileURLToPath(import.meta.url)}function b(){return typeof c<"u"&&typeof module<"u"?__dirname:h.dirname(R())}import{glob as D}from"glob";var a={files:[],param:{}},r={home:O.homedir(),enum:{}};function d(e){e&&console.log(e),process.exit()}async function N(){r.param={config:p(["--config","-c"]),configScan:t(["--config-scan","-cs"]),configAll:t(["--config-all","-ca"]),quick:t(["--quick","-q"]),convertGet:t(["--convert-get","-cg"]),removeParam:t(["--remove-param","-rp"]),removePrefixIndex:p(["--remove-prefix-index","-rpi"]),removeDts:t(["--remove-dts","-rd"]),extractRequestQuery:p(["--extract-request-query","-erq"]),extractResponseRaw:t(["--extract-response-raw","-err"]),template:l.resolve(b(),"./templates")},r.config={templates:p(["--templates","-t"])??r.param.template,defaultResponseAsSuccess:t(["--default-as-success","-d"]),generateResponses:t(["--responses","-r"]),generateUnionEnums:t("--union-enums"),addReadonly:t("--add-readonly"),generateRouteTypes:t("--route-types"),generateClient:!t("--no-client"),enumNamesAsValues:t("--enum-names-as-values"),extractRequestParams:t("--extract-request-params"),extractRequestBody:t("--extract-request-body"),extractResponseBody:t("--extract-response-body"),extractResponseError:t("--extract-response-error"),modular:t("--modular"),toJS:t("--js"),moduleNameIndex:Number(p("--module-name-index")??0),moduleNameFirstTag:t("--module-name-first-tag"),httpClientType:t("--axios")?"axios":"fetch",unwrapResponseData:t("--unwrap-response-data"),disableThrowOnError:t("--disable-throw-on-error"),singleHttpClient:t("--single-http-client"),silent:t("--silent"),defaultResponseType:p("--default-response")??"void",typePrefix:p("--type-prefix")??"",typeSuffix:p("--type-suffix")??"",cleanOutput:t("--clean-output"),...p("--api-class-name")?{apiClassName:p("--api-class-name")}:{},patch:t("--patch"),debug:t("--debug"),anotherArrayType:t("--another-array-type"),sortTypes:t("--sort-types"),extractEnums:t("--extract-enums")}}async function $(){r.param.config?a.files=r.param.config.split(","):(r.param.configScan??!0)&&(a.files=D.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),a.files.length==0&&(a.files=["saconfig.json"]),!r.param.configAll&&a.files.length>1&&(a.files=(await S({type:"multiselect",name:"files",message:"\u9009\u62E9\u914D\u7F6E\u6587\u4EF6",hint:"\u53EF\u591A\u9009\uFF0C\u7A7A\u683C\u952E\u52FE\u9009\uFF0C\u56DE\u8F66\u5B8C\u6210",choices:a.files.map(e=>({title:e.replace(/\\/g,"/"),value:e}))}).then(e=>e.files?.length!=0?e:d("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),a.files?.length>0||d("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function T(){try{a.param={},a.param=JSON.parse(y.readFileSync(a.file,"utf-8"))}catch{}(!r.param.quick||[a.param.url,a.param.output,a.param.name].includes(void 0))&&(a.param=await S([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:a.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:a.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:a.param.name??"index"}])),[a.param.url,a.param.output,a.param.name].includes(void 0)&&d("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),r.docFile=l.resolve(`${a.param.output}/${a.param.name}-${new Date().getTime()}.json`)}async function P(e=0){if(a.file=a.files[e],await T(),x(a.param.url))await j.get(a.param.url).then(n=>w(n.data)).catch(n=>console.log("\u5931\u8D25\uFF1A",n));else try{await w(JSON.parse(y.readFileSync(l.resolve(a.param.url),"utf8")))}catch(n){console.log("\u5931\u8D25\uFF1A",n)}a.files[e+1]&&P(e+1)}async function w(e){if(typeof e?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");Object.entries(e.paths).forEach(n=>{Object.keys(n[1]).forEach(s=>{let o=`${n[0]}/${s}`;if(r.param.convertGet&&(o=o.replace(/([^\}]\/)get$/g,"$1query")),r.param.removeParam&&(o=o.replace(/\/\{.+?\}/g,"")),r.param.removePrefixIndex){let i=o.split("/");i=i.slice(0,1).concat(i.slice(Number(r.param.removePrefixIndex)+2)),o=i.join("/")}e.paths[n[0]][s].operationId=o;let u=o.split("/").slice(-1)[0];typeof r.enum[u]=="number"?r.enum[u]++:r.enum[u]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(r.enum).map(n=>n.join("-"))),g(r.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",a.file),await A({fileName:`${a.param.name}.ts`,output:l.resolve(a.param.output),input:r.docFile,...r.config,param:r.param}),y.unlinkSync(r.docFile),r.param.removeDts&&(console.log("\u6E05\u7406\uFF1A",l.resolve(a.param.output,`${a.param.name}.d.ts`)),F(`npx rimraf ${l.resolve(a.param.output,`${a.param.name}.d.ts`)}`,{cwd:r.home}).toString()),g(a.file,JSON.stringify(a.param,null,2))}async function te(){await N(),await $(),P()}export{te as generateApi};
@@ -0,0 +1,69 @@
1
+ <%
2
+ const { apiConfig, routes, utils, config } = it;
3
+ const { info, servers, externalDocs } = apiConfig;
4
+ const { _, require, formatDescription } = utils;
5
+
6
+ const server = (servers && servers[0]) || { url: "" };
7
+
8
+ const descriptionLines = _.compact([
9
+ `@title ${info.title || "No title"}`,
10
+ info.version && `@version ${info.version}`,
11
+ info.license && `@license ${_.compact([
12
+ info.license.name,
13
+ info.license.url && `(${info.license.url})`,
14
+ ]).join(" ")}`,
15
+ info.termsOfService && `@termsOfService ${info.termsOfService}`,
16
+ server.url && `@baseUrl ${server.url}`,
17
+ externalDocs.url && `@externalDocs ${externalDocs.url}`,
18
+ info.contact && `@contact ${_.compact([
19
+ info.contact.name,
20
+ info.contact.email && `<${info.contact.email}>`,
21
+ info.contact.url && `(${info.contact.url})`,
22
+ ]).join(" ")}`,
23
+ info.description && " ",
24
+ info.description && _.replace(formatDescription(info.description), /\n/g, "\n * "),
25
+ ]);
26
+
27
+ %>
28
+
29
+ <% if (config.httpClientType === config.constants.HTTP_CLIENT.AXIOS) { %> import type { AxiosRequestConfig, AxiosResponse } from "axios"; <% } %>
30
+
31
+ <% if (descriptionLines.length) { %>
32
+ /**
33
+ <% descriptionLines.forEach((descriptionLine) => { %>
34
+ * <%~ descriptionLine %>
35
+
36
+ <% }) %>
37
+ */
38
+ <% } %>
39
+ export class <%~ config.apiClassName %><SecurityDataType extends unknown><% if (!config.singleHttpClient) { %> extends HttpClient<SecurityDataType> <% } %> {
40
+
41
+ <% if(config.singleHttpClient) { %>
42
+ http: HttpClient<SecurityDataType>;
43
+
44
+ constructor (http: HttpClient<SecurityDataType>) {
45
+ this.http = http;
46
+ }
47
+ <% } %>
48
+
49
+
50
+ <% if (routes.outOfModule) { %>
51
+ <% for (const route of routes.outOfModule) { %>
52
+
53
+ <%~ includeFile('./procedure-call.ejs', { ...it, route }) %>
54
+
55
+ <% } %>
56
+ <% } %>
57
+
58
+ <% if (routes.combined) { %>
59
+ <% for (const { routes: combinedRoutes = [], moduleName } of routes.combined) { %>
60
+ <%~ moduleName %> = {
61
+ <% for (const route of combinedRoutes) { %>
62
+
63
+ <%~ includeFile('./procedure-call.ejs', { ...it, route }) %>
64
+
65
+ <% } %>
66
+ }
67
+ <% } %>
68
+ <% } %>
69
+ }
@@ -0,0 +1,37 @@
1
+ <%
2
+ const { data, utils } = it;
3
+ const { formatDescription, require, _ } = utils;
4
+
5
+ const stringify = (value) => _.isObject(value) ? JSON.stringify(value) : _.isString(value) ? `"${value}"` : value;
6
+
7
+ const jsDocLines = _.compact([
8
+ data.title,
9
+ data.description && formatDescription(data.description),
10
+ !_.isUndefined(data.deprecated) && data.deprecated && '@deprecated',
11
+ !_.isUndefined(data.format) && `@format ${data.format}`,
12
+ !_.isUndefined(data.minimum) && `@min ${data.minimum}`,
13
+ !_.isUndefined(data.multipleOf) && `@multipleOf ${data.multipleOf}`,
14
+ !_.isUndefined(data.exclusiveMinimum) && `@exclusiveMin ${data.exclusiveMinimum}`,
15
+ !_.isUndefined(data.maximum) && `@max ${data.maximum}`,
16
+ !_.isUndefined(data.minLength) && `@minLength ${data.minLength}`,
17
+ !_.isUndefined(data.maxLength) && `@maxLength ${data.maxLength}`,
18
+ !_.isUndefined(data.exclusiveMaximum) && `@exclusiveMax ${data.exclusiveMaximum}`,
19
+ !_.isUndefined(data.maxItems) && `@maxItems ${data.maxItems}`,
20
+ !_.isUndefined(data.minItems) && `@minItems ${data.minItems}`,
21
+ !_.isUndefined(data.uniqueItems) && `@uniqueItems ${data.uniqueItems}`,
22
+ !_.isUndefined(data.default) && `@default ${stringify(data.default)}`,
23
+ !_.isUndefined(data.pattern) && `@pattern ${data.pattern}`,
24
+ !_.isUndefined(data.example) && `@example ${stringify(data.example)}`
25
+ ]).join('\n').split('\n');
26
+ %>
27
+ <% if (jsDocLines.every(_.isEmpty)) { %>
28
+ <% } else if (jsDocLines.length === 1) { %>
29
+ /** <%~ jsDocLines[0] %> */
30
+ <% } else if (jsDocLines.length) { %>
31
+ /**
32
+ <% for (jsDocLine of jsDocLines) { %>
33
+ * <%~ jsDocLine %>
34
+
35
+ <% } %>
36
+ */
37
+ <% } %>
@@ -0,0 +1,40 @@
1
+ <%
2
+ const { modelTypes, utils, config } = it;
3
+ const { formatDescription, require, _, Ts } = utils;
4
+
5
+
6
+ const buildGenerics = (contract) => {
7
+ if (!contract.genericArgs || !contract.genericArgs.length) return '';
8
+
9
+ return '<' + contract.genericArgs.map(({ name, default: defaultType, extends: extendsType }) => {
10
+ return [
11
+ name,
12
+ extendsType && `extends ${extendsType}`,
13
+ defaultType && `= ${defaultType}`,
14
+ ].join('')
15
+ }).join(',') + '>'
16
+ }
17
+
18
+ const dataContractTemplates = {
19
+ enum: (contract) => {
20
+ return `enum ${contract.name} {\r\n${contract.content} \r\n }`;
21
+ },
22
+ interface: (contract) => {
23
+ return `interface ${contract.name}${buildGenerics(contract)} {\r\n${contract.content}}`;
24
+ },
25
+ type: (contract) => {
26
+ return `type ${contract.name}${buildGenerics(contract)} = ${contract.content}`;
27
+ },
28
+ }
29
+ %>
30
+
31
+ <% if (config.internalTemplateOptions.addUtilRequiredKeysType) { %>
32
+ type <%~ config.Ts.CodeGenKeyword.UtilRequiredKeys %><T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>
33
+ <% } %>
34
+
35
+ <% for (const contract of modelTypes) { %>
36
+ <%~ includeFile('./data-contract-jsdoc.ejs', { ...it, data: { ...contract, ...contract.typeData } }) %>
37
+ <%~ contract.internal ? '' : 'export'%> <%~ (dataContractTemplates[contract.typeIdentifier] || dataContractTemplates.type)(contract) %>
38
+
39
+
40
+ <% } %>
@@ -0,0 +1,18 @@
1
+ <%
2
+ const { contract, utils, config } = it;
3
+ const { formatDescription, require, _ } = utils;
4
+ const { name, $content } = contract;
5
+ %>
6
+ <% if (config.generateUnionEnums) { %>
7
+ export type <%~ name %> = <%~ _.map($content, ({ value }) => value).join(" | ") %>
8
+ <% } else { %>
9
+ export enum <%~ name %> {
10
+ <%~ _.map($content, ({ key, value, description }) => {
11
+ let formattedDescription = description && formatDescription(description, true);
12
+ return [
13
+ formattedDescription && `/** ${formattedDescription} */`,
14
+ `${key} = ${value}`
15
+ ].filter(Boolean).join("\n");
16
+ }).join(",\n") %>
17
+ }
18
+ <% } %>
@@ -0,0 +1,155 @@
1
+ <%
2
+ const { apiConfig, generateResponses, config } = it;
3
+ %>
4
+
5
+ import type { AxiosInstance, AxiosRequestConfig, HeadersDefaults, ResponseType, AxiosResponse } from "axios";
6
+ import axios from "axios";
7
+
8
+ export type QueryParamsType = Record<string | number, any>;
9
+
10
+ <% if (config.param?.extractResponseRaw) { %>
11
+ /** 提取响应 */
12
+ export interface AxiosResponseRaw<T = any> {
13
+ /** 原始数据 */
14
+ raw: AxiosResponse<T>;
15
+ }
16
+
17
+ <% } %>
18
+ export interface FullRequestParams extends Omit<AxiosRequestConfig, "data" | "params" | "url" | "responseType"> {
19
+ /** set parameter to `true` for call `securityWorker` for this request */
20
+ secure?: boolean;
21
+ /** request path */
22
+ path: string;
23
+ /** content type of request body */
24
+ type?: ContentType;
25
+ /** query params */
26
+ query?: QueryParamsType;
27
+ /** format of response (i.e. response.json() -> format: "json") */
28
+ format?: ResponseType;
29
+ /** request body */
30
+ body?: unknown;
31
+ }
32
+
33
+ export type RequestParams = Omit<FullRequestParams, "body" | "method" | "query" | "path">;
34
+
35
+ export interface ApiConfig<SecurityDataType = unknown> extends Omit<AxiosRequestConfig, "data" | "cancelToken"> {
36
+ securityWorker?: (securityData: SecurityDataType | null) => Promise<AxiosRequestConfig | void> | AxiosRequestConfig | void;
37
+ secure?: boolean;
38
+ format?: ResponseType;
39
+ }
40
+
41
+ export enum ContentType {
42
+ Json = "application/json",
43
+ JsonApi = "application/vnd.api+json",
44
+ FormData = "multipart/form-data",
45
+ UrlEncoded = "application/x-www-form-urlencoded",
46
+ Text = "text/plain",
47
+ }
48
+
49
+ export class HttpClient<SecurityDataType = unknown> {
50
+ public instance: AxiosInstance;
51
+ private securityData: SecurityDataType | null = null;
52
+ private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];
53
+ private secure?: boolean;
54
+ private format?: ResponseType;
55
+
56
+ constructor({ securityWorker, secure, format, ...axiosConfig }: ApiConfig<SecurityDataType> = {}) {
57
+ this.instance = axios.create({ ...axiosConfig, baseURL: axiosConfig.baseURL || "<%~ apiConfig.baseUrl %>" })
58
+ this.secure = secure;
59
+ this.format = format;
60
+ this.securityWorker = securityWorker;
61
+ }
62
+
63
+ public setSecurityData = (data: SecurityDataType | null) => {
64
+ this.securityData = data
65
+ }
66
+
67
+ protected mergeRequestParams(params1: AxiosRequestConfig, params2?: AxiosRequestConfig): AxiosRequestConfig {
68
+ const method = params1.method || (params2 && params2.method)
69
+
70
+ return {
71
+ ...this.instance.defaults,
72
+ ...params1,
73
+ ...(params2 || {}),
74
+ headers: {
75
+ ...((method && this.instance.defaults.headers[method.toLowerCase() as keyof HeadersDefaults]) || {}),
76
+ ...(params1.headers || {}),
77
+ ...((params2 && params2.headers) || {}),
78
+ },
79
+ };
80
+ }
81
+
82
+ protected stringifyFormItem(formItem: unknown) {
83
+ if (typeof formItem === "object" && formItem !== null) {
84
+ return JSON.stringify(formItem);
85
+ } else {
86
+ return `${formItem}`;
87
+ }
88
+ }
89
+
90
+ protected createFormData(input: Record<string, unknown>): FormData {
91
+ if (input instanceof FormData) {
92
+ return input;
93
+ }
94
+ return Object.keys(input || {}).reduce((formData, key) => {
95
+ const property = input[key];
96
+ const propertyContent: any[] = (property instanceof Array) ? property : [property]
97
+
98
+ for (const formItem of propertyContent) {
99
+ const isFileType = formItem instanceof Blob || formItem instanceof File;
100
+ formData.append(
101
+ key,
102
+ isFileType ? formItem : this.stringifyFormItem(formItem)
103
+ );
104
+ }
105
+
106
+ return formData;
107
+ }, new FormData());
108
+ }
109
+
110
+ public request = async <T = any, _E = any>({
111
+ secure,
112
+ path,
113
+ type,
114
+ query,
115
+ format,
116
+ body,
117
+ ...params
118
+ <% if (config.unwrapResponseData) { %>
119
+ }: FullRequestParams): Promise<T> => {
120
+ <% } else if (config.param?.extractResponseRaw) { %>
121
+ }: FullRequestParams): Promise<AxiosResponseRaw<T>> => {
122
+ <% } else { %>
123
+ }: FullRequestParams): Promise<AxiosResponse<T>> => {
124
+ <% } %>
125
+ const secureParams = ((typeof secure === 'boolean' ? secure : this.secure) && this.securityWorker && (await this.securityWorker(this.securityData))) || {};
126
+ const requestParams = this.mergeRequestParams(params, secureParams);
127
+ const responseFormat = (format || this.format) || undefined;
128
+
129
+ if (type === ContentType.FormData && body && body !== null && typeof body === "object") {
130
+ body = this.createFormData(body as Record<string, unknown>);
131
+ }
132
+
133
+ if (type === ContentType.Text && body && body !== null && typeof body !== "string") {
134
+ body = JSON.stringify(body);
135
+ }
136
+
137
+ return this.instance.request({
138
+ ...requestParams,
139
+ headers: {
140
+ ...(requestParams.headers || {}),
141
+ ...(type ? { "Content-Type": type } : {}),
142
+ },
143
+ params: query,
144
+ responseType: responseFormat,
145
+ data: body,
146
+ url: path,
147
+ <% if (config.unwrapResponseData) { %>
148
+ }).then(response => response.data);
149
+ <% } else if (config.param?.extractResponseRaw) { %>
150
+ }).then(response => { raw: response });
151
+ <% } else { %>
152
+ });
153
+ <% } %>
154
+ };
155
+ }
@@ -0,0 +1,10 @@
1
+ <%
2
+ const { contract, utils } = it;
3
+ const { formatDescription, require, _ } = utils;
4
+ %>
5
+ export interface <%~ contract.name %> {
6
+ <% for (const field of contract.$content) { %>
7
+ <%~ includeFile('./object-field-jsdoc.ejs', { ...it, field }) %>
8
+ <%~ field.name %><%~ field.isRequired ? '' : '?' %>: <%~ field.value %><%~ field.isNullable ? ' | null' : ''%>;
9
+ <% } %>
10
+ }
@@ -0,0 +1,28 @@
1
+ <%
2
+ const { field, utils } = it;
3
+ const { formatDescription, require, _ } = utils;
4
+
5
+ const comments = _.uniq(
6
+ _.compact([
7
+ field.title,
8
+ field.description,
9
+ field.deprecated && ` * @deprecated`,
10
+ !_.isUndefined(field.format) && `@format ${field.format}`,
11
+ !_.isUndefined(field.minimum) && `@min ${field.minimum}`,
12
+ !_.isUndefined(field.maximum) && `@max ${field.maximum}`,
13
+ !_.isUndefined(field.pattern) && `@pattern ${field.pattern}`,
14
+ !_.isUndefined(field.example) &&
15
+ `@example ${_.isObject(field.example) ? JSON.stringify(field.example) : field.example}`,
16
+ ]).reduce((acc, comment) => [...acc, ...comment.split(/\n/g)], []),
17
+ );
18
+ %>
19
+ <% if (comments.length === 1) { %>
20
+ /** <%~ comments[0] %> */
21
+ <% } else if (comments.length) { %>
22
+ /**
23
+ <% comments.forEach(comment => { %>
24
+ * <%~ comment %>
25
+
26
+ <% }) %>
27
+ */
28
+ <% } %>
@@ -0,0 +1,109 @@
1
+ <%
2
+ const { utils, route, config } = it;
3
+ const { requestBodyInfo, responseBodyInfo, specificArgNameResolver } = route;
4
+ const { _, getInlineParseContent, getParseContent, parseSchema, getComponentByRef, require } = utils;
5
+ const { parameters, path, method, payload, query, formData, security, requestParams } = route.request;
6
+ const { type, errorType, contentTypes } = route.response;
7
+ const { HTTP_CLIENT, RESERVED_REQ_PARAMS_ARG_NAMES } = config.constants;
8
+ const routeDocs = includeFile("./route-docs", { config, route, utils });
9
+ const queryName = (query && query.name) || "query";
10
+ const pathParams = _.values(parameters);
11
+ const pathParamsNames = _.map(pathParams, "name");
12
+
13
+ // 提取参数
14
+ if (config.param?.extractRequestQuery && query && query.type) {
15
+ const queryExtract = config.param?.extractRequestQuery?.split(",")
16
+ query.type = query.type.replace(new RegExp(`[\\s\\S\\n]+ (${queryExtract.join("|")}): ([a-z]+),[\\s\\S\\n]+`, "i"), "$2")
17
+ }
18
+
19
+ const isFetchTemplate = config.httpClientType === HTTP_CLIENT.FETCH;
20
+
21
+ const requestConfigParam = {
22
+ name: specificArgNameResolver.resolve(RESERVED_REQ_PARAMS_ARG_NAMES),
23
+ optional: true,
24
+ type: "RequestParams",
25
+ defaultValue: "{}",
26
+ }
27
+
28
+ const argToTmpl = ({ name, optional, type, defaultValue }) => `${name}${!defaultValue && optional ? '?' : ''}: ${type}${defaultValue ? ` = ${defaultValue}` : ''}`;
29
+
30
+ const rawWrapperArgs = config.extractRequestParams ?
31
+ _.compact([
32
+ requestParams && {
33
+ name: pathParams.length ? `{ ${_.join(pathParamsNames, ", ")}, ...${queryName} }` : queryName,
34
+ optional: false,
35
+ type: getInlineParseContent(requestParams),
36
+ },
37
+ ...(!requestParams ? pathParams : []),
38
+ payload,
39
+ requestConfigParam,
40
+ ]) :
41
+ _.compact([
42
+ ...pathParams,
43
+ query,
44
+ payload,
45
+ requestConfigParam,
46
+ ])
47
+
48
+ const wrapperArgs = _
49
+ // Sort by optionality
50
+ .sortBy(rawWrapperArgs, [o => o.optional])
51
+ .map(argToTmpl)
52
+ .join(', ')
53
+
54
+ // RequestParams["type"]
55
+ const requestContentKind = {
56
+ "JSON": "ContentType.Json",
57
+ "JSON_API": "ContentType.JsonApi",
58
+ "URL_ENCODED": "ContentType.UrlEncoded",
59
+ "FORM_DATA": "ContentType.FormData",
60
+ "TEXT": "ContentType.Text",
61
+ }
62
+ // RequestParams["format"]
63
+ const responseContentKind = {
64
+ "JSON": '"json"',
65
+ "IMAGE": '"blob"',
66
+ "FORM_DATA": isFetchTemplate ? '"formData"' : '"document"'
67
+ }
68
+
69
+ const bodyTmpl = _.get(payload, "name") || null;
70
+ const queryTmpl = (query != null && queryName) || null;
71
+ const bodyContentKindTmpl = requestContentKind[requestBodyInfo.contentKind] || null;
72
+ const responseFormatTmpl = responseContentKind[responseBodyInfo.success && responseBodyInfo.success.schema && responseBodyInfo.success.schema.contentKind] || null;
73
+ const securityTmpl = security ? 'true' : null;
74
+
75
+ const describeReturnType = () => {
76
+ if (!config.toJS) return "";
77
+
78
+ switch(config.httpClientType) {
79
+ case HTTP_CLIENT.AXIOS: {
80
+ return `Promise<AxiosResponse<${type}>>`
81
+ }
82
+ default: {
83
+ return `Promise<HttpResponse<${type}, ${errorType}>`
84
+ }
85
+ }
86
+ }
87
+
88
+ const isValidIdentifier = (name) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
89
+
90
+ %>
91
+ /**
92
+ <%~ routeDocs.description %>
93
+
94
+ *<% /* Here you can add some other JSDoc tags */ %>
95
+
96
+ <%~ routeDocs.lines %>
97
+
98
+ */
99
+ <% if (isValidIdentifier(route.routeName.usage)) { %><%~ route.routeName.usage %><%~ route.namespace ? ': ' : ' = ' %><% } else { %>"<%~ route.routeName.usage %>"<%~ route.namespace ? ': ' : ' = ' %><% } %>(<%~ wrapperArgs %>)<%~ config.toJS ? `: ${describeReturnType()}` : "" %> =>
100
+ <%~ config.singleHttpClient ? 'this.http.request' : 'this.request' %><<%~ type %>, <%~ errorType %>>({
101
+ path: `<%~ path %>`,
102
+ method: '<%~ _.upperCase(method) %>',
103
+ <%~ queryTmpl ? `query: ${queryTmpl},` : '' %>
104
+ <%~ bodyTmpl ? `body: ${bodyTmpl},` : '' %>
105
+ <%~ securityTmpl ? `secure: ${securityTmpl},` : '' %>
106
+ <%~ bodyContentKindTmpl ? `type: ${bodyContentKindTmpl},` : '' %>
107
+ <%~ responseFormatTmpl ? `format: ${responseFormatTmpl},` : '' %>
108
+ ...<%~ _.get(requestConfigParam, "name") %>,
109
+ })<%~ route.namespace ? ',' : '' %>
@@ -0,0 +1,30 @@
1
+ <%
2
+ const { config, route, utils } = it;
3
+ const { _, formatDescription, fmtToJSDocLine, pascalCase, require } = utils;
4
+ const { raw, request, routeName } = route;
5
+
6
+ const jsDocDescription = raw.description ?
7
+ ` * @description ${formatDescription(raw.description, true)}` :
8
+ fmtToJSDocLine('No description', { eol: false });
9
+ const jsDocLines = _.compact([
10
+ _.size(raw.tags) && ` * @tags ${raw.tags.join(", ")}`,
11
+ ` * @name ${pascalCase(routeName.usage)}`,
12
+ raw.summary && ` * @summary ${raw.summary}`,
13
+ ` * @request ${_.upperCase(request.method)}:${raw.route}`,
14
+ raw.deprecated && ` * @deprecated`,
15
+ routeName.duplicate && ` * @originalName ${routeName.original}`,
16
+ routeName.duplicate && ` * @duplicate`,
17
+ request.security && ` * @secure`,
18
+ ...(config.generateResponses && raw.responsesTypes.length
19
+ ? raw.responsesTypes.map(
20
+ ({ type, status, description, isSuccess }) =>
21
+ ` * @response \`${status}\` \`${_.replace(_.replace(type, /\/\*/g, "\\*"), /\*\//g, "*\\")}\` ${description}`,
22
+ )
23
+ : []),
24
+ ]).map(str => str.trimEnd()).join("\n");
25
+
26
+ return {
27
+ description: jsDocDescription,
28
+ lines: jsDocLines,
29
+ }
30
+ %>
@@ -0,0 +1,43 @@
1
+ <%
2
+ const { routeInfo, utils } = it;
3
+ const {
4
+ operationId,
5
+ method,
6
+ route,
7
+ moduleName,
8
+ responsesTypes,
9
+ description,
10
+ tags,
11
+ summary,
12
+ pathArgs,
13
+ } = routeInfo;
14
+ const { _, fmtToJSDocLine, require } = utils;
15
+
16
+ const methodAliases = {
17
+ get: (pathName, hasPathInserts) =>
18
+ _.camelCase(`${pathName}_${hasPathInserts ? "detail" : "list"}`),
19
+ post: (pathName, hasPathInserts) => _.camelCase(`${pathName}_create`),
20
+ put: (pathName, hasPathInserts) => _.camelCase(`${pathName}_update`),
21
+ patch: (pathName, hasPathInserts) => _.camelCase(`${pathName}_partial_update`),
22
+ delete: (pathName, hasPathInserts) => _.camelCase(`${pathName}_delete`),
23
+ };
24
+
25
+ const createCustomOperationId = (method, route, moduleName) => {
26
+ const hasPathInserts = /\{(\w){1,}\}$/g.test(route);
27
+ const splittedRouteBySlash = _.compact(_.replace(route, /\{(\w){1,}\}/g, "").split("/"));
28
+ const routeParts = (splittedRouteBySlash.length > 1
29
+ ? splittedRouteBySlash.splice(1)
30
+ : splittedRouteBySlash
31
+ ).join("_");
32
+ return routeParts.length > 3 && methodAliases[method]
33
+ ? methodAliases[method](routeParts, hasPathInserts)
34
+ : _.camelCase(_.lowerCase(method) + "_" + [moduleName].join("_")) || "index";
35
+ };
36
+
37
+ if (operationId)
38
+ return _.camelCase(operationId);
39
+ if (route === "/")
40
+ return _.camelCase(`${_.lowerCase(method)}Root`);
41
+
42
+ return createCustomOperationId(method, route, moduleName);
43
+ %>
@@ -0,0 +1,24 @@
1
+ <%
2
+ const { route, utils, config } = it;
3
+ const { _, pascalCase, require } = utils;
4
+ const { query, payload, pathParams, headers } = route.request;
5
+
6
+ const routeDocs = includeFile("./route-docs", { config, route, utils });
7
+ const isValidIdentifier = (name) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
8
+ const routeNamespace = pascalCase(route.routeName.usage);
9
+
10
+ %>
11
+
12
+ /**
13
+ <%~ routeDocs.description %>
14
+
15
+ <%~ routeDocs.lines %>
16
+
17
+ */
18
+ export namespace <% if (isValidIdentifier(routeNamespace)) { %><%~ routeNamespace %><% } else { %>"<%~ routeNamespace %>"<% } %> {
19
+ export type RequestParams = <%~ (pathParams && pathParams.type) || '{}' %>;
20
+ export type RequestQuery = <%~ (query && query.type) || '{}' %>;
21
+ export type RequestBody = <%~ (payload && payload.type) || 'never' %>;
22
+ export type RequestHeaders = <%~ (headers && headers.type) || '{}' %>;
23
+ export type ResponseBody = <%~ route.response.type %>;
24
+ }
@@ -0,0 +1,32 @@
1
+ <%
2
+ const { utils, config, routes, modelTypes } = it;
3
+ const { _, pascalCase } = utils;
4
+ const dataContracts = config.modular ? _.map(modelTypes, "name") : [];
5
+ %>
6
+
7
+ <% if (dataContracts.length) { %>
8
+ import { <%~ dataContracts.join(", ") %> } from "./<%~ config.fileNames.dataContracts %>"
9
+ <% } %>
10
+
11
+ <%
12
+ /* TODO: outOfModule, combined should be attributes of route, which will allow to avoid duplication of code */
13
+ %>
14
+
15
+ <% if (routes.outOfModule) { %>
16
+ <% for (const { routes: outOfModuleRoutes = [] } of routes.outOfModule) { %>
17
+ <% for (const route of outOfModuleRoutes) { %>
18
+ <%~ includeFile('./route-type.ejs', { ...it, route }) %>
19
+ <% } %>
20
+ <% } %>
21
+ <% } %>
22
+
23
+ <% if (routes.combined) { %>
24
+ <% for (const { routes: combinedRoutes = [], moduleName } of routes.combined) { %>
25
+ export namespace <%~ pascalCase(moduleName) %> {
26
+ <% for (const route of combinedRoutes) { %>
27
+ <%~ includeFile('./route-type.ejs', { ...it, route }) %>
28
+ <% } %>
29
+ }
30
+
31
+ <% } %>
32
+ <% } %>
@@ -0,0 +1,15 @@
1
+ <%
2
+ const { contract, utils } = it;
3
+ const { formatDescription, require, _ } = utils;
4
+
5
+ %>
6
+ <% if (contract.$content.length) { %>
7
+ export type <%~ contract.name %> = {
8
+ <% for (const field of contract.$content) { %>
9
+ <%~ includeFile('./object-field-jsdoc.ejs', { ...it, field }) %>
10
+ <%~ field.field %>;
11
+ <% } %>
12
+ }<%~ utils.isNeedToAddNull(contract) ? ' | null' : ''%>
13
+ <% } else { %>
14
+ export type <%~ contract.name %> = Record<string, any>;
15
+ <% } %>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fxri/swagger2api",
3
- "version": "1.1.5",
3
+ "version": "1.1.7",
4
4
  "description": "基于 swagger-typescript-api,将 Swagger 文档自动转为 TypeScript 格式的 API 文件。",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -10,7 +10,7 @@
10
10
  },
11
11
  "type": "module",
12
12
  "main": "./dist/index.js",
13
- "bin": "./dist/bin/index.js",
13
+ "bin": "./dist/cli.js",
14
14
  "files": [
15
15
  "dist",
16
16
  "README.md",
@@ -32,6 +32,7 @@
32
32
  "@types/prompts": "^2.4.9",
33
33
  "@typescript-eslint/eslint-plugin": "^6.21.0",
34
34
  "@typescript-eslint/parser": "^6.21.0",
35
+ "esbuild-plugin-copy": "^2.1.1",
35
36
  "eslint": "^8.57.1",
36
37
  "eslint-config-prettier": "^9.1.2",
37
38
  "eslint-plugin-vue": "^9.33.0",
@@ -53,10 +54,10 @@
53
54
  "url": "https://github.com/fxri-net/swagger2api/issues"
54
55
  },
55
56
  "scripts": {
56
- "dev": "pnpm build:debug && node ./dist/bin/index.js",
57
+ "dev": "pnpm build:debug && node ./dist/cli.js",
57
58
  "build": "NODE_ENV=production tsup",
58
- "build:debug": "NODE_ENV=development tsup",
59
+ "build:debug": "NODE_ENV=development tsup --config tsup.dev.config.ts",
59
60
  "release": "pnpm build && pnpm publish",
60
- "api": "pnpm dev --axios --responses --remove-prefix-index 0"
61
+ "api": "pnpm dev --axios --responses --remove-prefix-index 0 --quick --extract-request-query param --extract-response-raw"
61
62
  }
62
63
  }
@@ -1 +0,0 @@
1
- var A=Object.create;var x=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var T=Object.getPrototypeOf,q=Object.prototype.hasOwnProperty;var D=(e,r,n,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of E(r))!q.call(e,i)&&i!==n&&x(e,i,{get:()=>r[i],enumerable:!(s=P(r,i))||s.enumerable});return e};var m=(e,r,n)=>(n=e!=null?A(T(e)):{},D(r||!e||!e.__esModule?x(n,"default",{value:e,enumerable:!0}):n,e));var j=m(require("axios"),1),O=require("child_process"),F=m(require("os"),1),g=m(require("fs"),1),c=m(require("path"),1),h=m(require("prompts"),1),N=require("swagger-typescript-api");var b=e=>/^(https?:\/\/|:?\/\/)/.test(e);var f=m(require("fs"),1),v=m(require("path"),1),u={param:process.argv.filter((e,r)=>r>1),used:{}};function w(e,r=!0,n=!0){Array.isArray(e)||(e=[e]);let s;return u.param.forEach((i,p)=>{if(e.includes(i))r?(s=u.param[p+1],n&&Object.assign(u.used,{[p+1]:!0})):["true","false"].includes(u.param[p+1])?(s=u.param[p+1].toLowerCase()=="true",n&&Object.assign(u.used,{[p+1]:!0})):s=!0;else return;n&&Object.assign(u.used,{[p]:!0})}),s}function a(e,r=!0){return w(e,!1,r)}function o(e,r=!0){return w(e,!0,r)}function d(e,r){let n=v.default.dirname(e);f.default.existsSync(n)||f.default.mkdirSync(n,{recursive:!0}),f.default.writeFileSync(e,r)}var $=require("glob"),t={files:[],param:{}},l={home:F.default.homedir(),enum:{}};function y(e){e&&console.log(e),process.exit()}async function C(){o(["--config","-c"])?t.files=o(["--config","-c"]).split(","):(a(["--config-scan","-cs"])??!0)&&(t.files=$.glob.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),t.files.length==0&&(t.files=["saconfig.json"]),!a(["--config-all","-ca"])&&t.files.length>1&&(t.files=(await(0,h.default)({type:"multiselect",name:"files",message:"\u9009\u62E9\u914D\u7F6E\u6587\u4EF6",hint:"\u53EF\u591A\u9009\uFF0C\u7A7A\u683C\u952E\u52FE\u9009\uFF0C\u56DE\u8F66\u5B8C\u6210",choices:t.files.map(e=>({title:e.replace(/\\/g,"/"),value:e}))}).then(e=>e.files?.length!=0?e:y("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),t.files?.length>0||y("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function J(){try{t.param={},t.param=JSON.parse(g.default.readFileSync(t.file,"utf-8"))}catch{}(!a(["--quick","-q"])||[t.param.url,t.param.output,t.param.name].includes(void 0))&&(t.param=await(0,h.default)([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:t.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:t.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:t.param.name??"index"}])),[t.param.url,t.param.output,t.param.name].includes(void 0)&&y("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),l.docFile=c.default.resolve(`${t.param.output}/${t.param.name}-${new Date().getTime()}.json`)}async function k(e=0){if(t.file=t.files[e],await J(),b(t.param.url))await j.default.get(t.param.url).then(r=>S(r.data)).catch(r=>console.log("\u5931\u8D25\uFF1A",r));else try{await S(JSON.parse(g.default.readFileSync(c.default.resolve(t.param.url),"utf8")))}catch(r){console.log("\u5931\u8D25\uFF1A",r)}t.files[e+1]&&k(e+1)}async function S(e){if(typeof e?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");Object.entries(e.paths).forEach(r=>{Object.keys(r[1]).forEach(n=>{let s=`${r[0]}/${n}`;if(a(["--convert-get","-cg"])&&(s=s.replace(/([^\}]\/)get$/g,"$1query")),a(["--remove-param","-rp"])&&(s=s.replace(/\/\{.+?\}/g,"")),o(["--remove-prefix-index","-rpi"])){let p=s.split("/");p=p.slice(0,1).concat(p.slice(Number(o(["--remove-prefix-index","-rpi"]))+2)),s=p.join("/")}e.paths[r[0]][n].operationId=s;let i=s.split("/").slice(-1)[0];typeof l.enum[i]=="number"?l.enum[i]++:l.enum[i]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(l.enum).map(r=>r.join("-"))),d(l.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",t.file),await(0,N.generateApi)({fileName:`${t.param.name}.ts`,output:c.default.resolve(t.param.output),input:l.docFile,templates:o(["--templates","-t"]),defaultResponseAsSuccess:a(["--default-as-success","-d"]),generateResponses:a(["--responses","-r"]),generateUnionEnums:a("--union-enums"),addReadonly:a("--add-readonly"),generateRouteTypes:a("--route-types"),generateClient:!a("--no-client"),enumNamesAsValues:a("--enum-names-as-values"),extractRequestParams:a("--extract-request-params"),extractRequestBody:a("--extract-request-body"),extractResponseBody:a("--extract-response-body"),extractResponseError:a("--extract-response-error"),modular:a("--modular"),toJS:a("--js"),moduleNameIndex:Number(o("--module-name-index")??0),moduleNameFirstTag:a("--module-name-first-tag"),httpClientType:a("--axios")?"axios":"fetch",unwrapResponseData:a("--unwrap-response-data"),disableThrowOnError:a("--disable-throw-on-error"),singleHttpClient:a("--single-http-client"),silent:a("--silent"),defaultResponseType:o("--default-response")??"void",typePrefix:o("--type-prefix")??"",typeSuffix:o("--type-suffix")??"",cleanOutput:a("--clean-output"),...o("--api-class-name")?{apiClassName:o("--api-class-name")}:{},patch:a("--patch"),debug:a("--debug"),anotherArrayType:a("--another-array-type"),sortTypes:a("--sort-types"),extractEnums:a("--extract-enums")}),g.default.unlinkSync(l.docFile),a(["--remove-dts","-rd"])&&(console.log("\u6E05\u7406\uFF1A",c.default.resolve(t.param.output,`${t.param.name}.d.ts`)),(0,O.execSync)(`npx rimraf ${c.default.resolve(t.param.output,`${t.param.name}.d.ts`)}`,{cwd:l.home}).toString()),d(t.file,JSON.stringify(t.param,null,2))}async function R(){await C(),k()}R();
package/dist/bin/index.js DELETED
@@ -1 +0,0 @@
1
- import j from"axios";import{execSync as O}from"child_process";import F from"os";import d from"fs";import u from"path";import b from"prompts";import{generateApi as N}from"swagger-typescript-api";var y=t=>/^(https?:\/\/|:?\/\/)/.test(t);import c from"fs";import S from"path";var l={param:process.argv.filter((t,r)=>r>1),used:{}};function h(t,r=!0,i=!0){Array.isArray(t)||(t=[t]);let s;return l.param.forEach((m,o)=>{if(t.includes(m))r?(s=l.param[o+1],i&&Object.assign(l.used,{[o+1]:!0})):["true","false"].includes(l.param[o+1])?(s=l.param[o+1].toLowerCase()=="true",i&&Object.assign(l.used,{[o+1]:!0})):s=!0;else return;i&&Object.assign(l.used,{[o]:!0})}),s}function a(t,r=!0){return h(t,!1,r)}function n(t,r=!0){return h(t,!0,r)}function f(t,r){let i=S.dirname(t);c.existsSync(i)||c.mkdirSync(i,{recursive:!0}),c.writeFileSync(t,r)}import{glob as $}from"glob";var e={files:[],param:{}},p={home:F.homedir(),enum:{}};function g(t){t&&console.log(t),process.exit()}async function k(){n(["--config","-c"])?e.files=n(["--config","-c"]).split(","):(a(["--config-scan","-cs"])??!0)&&(e.files=$.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),e.files.length==0&&(e.files=["saconfig.json"]),!a(["--config-all","-ca"])&&e.files.length>1&&(e.files=(await b({type:"multiselect",name:"files",message:"\u9009\u62E9\u914D\u7F6E\u6587\u4EF6",hint:"\u53EF\u591A\u9009\uFF0C\u7A7A\u683C\u952E\u52FE\u9009\uFF0C\u56DE\u8F66\u5B8C\u6210",choices:e.files.map(t=>({title:t.replace(/\\/g,"/"),value:t}))}).then(t=>t.files?.length!=0?t:g("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),e.files?.length>0||g("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function R(){try{e.param={},e.param=JSON.parse(d.readFileSync(e.file,"utf-8"))}catch{}(!a(["--quick","-q"])||[e.param.url,e.param.output,e.param.name].includes(void 0))&&(e.param=await b([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:e.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:e.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:e.param.name??"index"}])),[e.param.url,e.param.output,e.param.name].includes(void 0)&&g("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),p.docFile=u.resolve(`${e.param.output}/${e.param.name}-${new Date().getTime()}.json`)}async function v(t=0){if(e.file=e.files[t],await R(),y(e.param.url))await j.get(e.param.url).then(r=>x(r.data)).catch(r=>console.log("\u5931\u8D25\uFF1A",r));else try{await x(JSON.parse(d.readFileSync(u.resolve(e.param.url),"utf8")))}catch(r){console.log("\u5931\u8D25\uFF1A",r)}e.files[t+1]&&v(t+1)}async function x(t){if(typeof t?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");Object.entries(t.paths).forEach(r=>{Object.keys(r[1]).forEach(i=>{let s=`${r[0]}/${i}`;if(a(["--convert-get","-cg"])&&(s=s.replace(/([^\}]\/)get$/g,"$1query")),a(["--remove-param","-rp"])&&(s=s.replace(/\/\{.+?\}/g,"")),n(["--remove-prefix-index","-rpi"])){let o=s.split("/");o=o.slice(0,1).concat(o.slice(Number(n(["--remove-prefix-index","-rpi"]))+2)),s=o.join("/")}t.paths[r[0]][i].operationId=s;let m=s.split("/").slice(-1)[0];typeof p.enum[m]=="number"?p.enum[m]++:p.enum[m]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(p.enum).map(r=>r.join("-"))),f(p.docFile,JSON.stringify(t)),console.log("\u6267\u884C\uFF1A",e.file),await N({fileName:`${e.param.name}.ts`,output:u.resolve(e.param.output),input:p.docFile,templates:n(["--templates","-t"]),defaultResponseAsSuccess:a(["--default-as-success","-d"]),generateResponses:a(["--responses","-r"]),generateUnionEnums:a("--union-enums"),addReadonly:a("--add-readonly"),generateRouteTypes:a("--route-types"),generateClient:!a("--no-client"),enumNamesAsValues:a("--enum-names-as-values"),extractRequestParams:a("--extract-request-params"),extractRequestBody:a("--extract-request-body"),extractResponseBody:a("--extract-response-body"),extractResponseError:a("--extract-response-error"),modular:a("--modular"),toJS:a("--js"),moduleNameIndex:Number(n("--module-name-index")??0),moduleNameFirstTag:a("--module-name-first-tag"),httpClientType:a("--axios")?"axios":"fetch",unwrapResponseData:a("--unwrap-response-data"),disableThrowOnError:a("--disable-throw-on-error"),singleHttpClient:a("--single-http-client"),silent:a("--silent"),defaultResponseType:n("--default-response")??"void",typePrefix:n("--type-prefix")??"",typeSuffix:n("--type-suffix")??"",cleanOutput:a("--clean-output"),...n("--api-class-name")?{apiClassName:n("--api-class-name")}:{},patch:a("--patch"),debug:a("--debug"),anotherArrayType:a("--another-array-type"),sortTypes:a("--sort-types"),extractEnums:a("--extract-enums")}),d.unlinkSync(p.docFile),a(["--remove-dts","-rd"])&&(console.log("\u6E05\u7406\uFF1A",u.resolve(e.param.output,`${e.param.name}.d.ts`)),O(`npx rimraf ${u.resolve(e.param.output,`${e.param.name}.d.ts`)}`,{cwd:p.home}).toString()),f(e.file,JSON.stringify(e.param,null,2))}async function w(){await k(),v()}w();
File without changes
File without changes