@fxri/swagger2api 1.2.8 → 1.2.10
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 +33 -1
- package/NOTICE +9 -9
- package/README.md +109 -105
- package/dist/cli.cjs +1 -1
- package/dist/cli.d.cts +1 -1
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +10 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,37 @@
|
|
|
1
1
|
# @fxri/swagger2api
|
|
2
2
|
|
|
3
|
+
## 1.2.10
|
|
4
|
+
|
|
5
|
+
> 2026-11-03 发布
|
|
6
|
+
|
|
7
|
+
### ⚡ 优化改进
|
|
8
|
+
|
|
9
|
+
- 文档站主题升到 1.1,渐变改为覆盖整页
|
|
10
|
+
|
|
11
|
+
## 1.2.9
|
|
12
|
+
|
|
13
|
+
> 2026-11-03 发布
|
|
14
|
+
|
|
15
|
+
### ✨ 新增功能
|
|
16
|
+
|
|
17
|
+
- 仓库级三方一致质量门,统一实现、文档与变更集校验
|
|
18
|
+
|
|
19
|
+
### ⚡ 优化改进
|
|
20
|
+
|
|
21
|
+
- CHANGELOG 文档镜像改用全局 `toolkit changelog doc`,删除本地重复脚本
|
|
22
|
+
- 验收与文档部署不再依赖本地同步脚本,未安装全局 toolkit 时跳过镜像检查
|
|
23
|
+
- 文档站接入统一主题,公共视觉规则由 toolkit 分发
|
|
24
|
+
- README 移除内部协作规则引用,更新日志去除发布运维细节
|
|
25
|
+
- 验收脚本补文档链接与新增变更集检查
|
|
26
|
+
|
|
27
|
+
### 🐛 问题修复
|
|
28
|
+
|
|
29
|
+
- 升级 axios / glob / swagger-typescript-api 并用 overrides 锁定 transitives,清除生产依赖漏洞
|
|
30
|
+
|
|
31
|
+
### 📝 文档更新
|
|
32
|
+
|
|
33
|
+
- README 补充 AGENTS.md 入口
|
|
34
|
+
|
|
3
35
|
## 1.2.8
|
|
4
36
|
|
|
5
37
|
> 2026-09-15 发布
|
|
@@ -54,7 +86,7 @@
|
|
|
54
86
|
|
|
55
87
|
### 📦 其他变更
|
|
56
88
|
|
|
57
|
-
- 同步重发:内容与 1.2.2
|
|
89
|
+
- 同步重发:内容与 1.2.2 完全一致,本版以新版本号重发,无新增功能改动
|
|
58
90
|
|
|
59
91
|
## 1.2.2
|
|
60
92
|
|
package/NOTICE
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
@fxri/swagger2api
|
|
2
|
-
Copyright © 2025-2026 唐启云. All rights reserved.
|
|
3
|
-
|
|
4
|
-
出品方:方弦研究所(唐启云个人项目品牌,非独立法人实体)
|
|
5
|
-
|
|
6
|
-
商标声明:
|
|
7
|
-
"方弦®"为第42类注册商标(注册号89648411),核定服务项目:计算机出租、计算机软件设计、为他人研究和开发新产品、计算机软件维护、把有形的数据或文件转换成电子媒体、为他人创建和维护网站、网络服务器出租、提供互联网搜索引擎、托管计算机站(网站)、云计算。
|
|
8
|
-
本开源许可(MIT License)不授予商标使用权。
|
|
9
|
-
详见 TRADEMARK.md 了解完整商标信息。
|
|
1
|
+
@fxri/swagger2api
|
|
2
|
+
Copyright © 2025-2026 唐启云. All rights reserved.
|
|
3
|
+
|
|
4
|
+
出品方:方弦研究所(唐启云个人项目品牌,非独立法人实体)
|
|
5
|
+
|
|
6
|
+
商标声明:
|
|
7
|
+
"方弦®"为第42类注册商标(注册号89648411),核定服务项目:计算机出租、计算机软件设计、为他人研究和开发新产品、计算机软件维护、把有形的数据或文件转换成电子媒体、为他人创建和维护网站、网络服务器出租、提供互联网搜索引擎、托管计算机站(网站)、云计算。
|
|
8
|
+
本开源许可(MIT License)不授予商标使用权。
|
|
9
|
+
详见 TRADEMARK.md 了解完整商标信息。
|
package/README.md
CHANGED
|
@@ -1,105 +1,109 @@
|
|
|
1
|
-
<p align="center">
|
|
2
|
-
<img src="./docs/public/logo.png" width="128" alt="Swagger 转 API">
|
|
3
|
-
</p>
|
|
4
|
-
|
|
5
|
-
# Swagger 转 API
|
|
6
|
-
|
|
7
|
-
[](https://www.npmjs.com/package/@fxri/swagger2api)
|
|
8
|
-
[](./docs/getting-started.md#安装)
|
|
9
|
-
[](./LICENSE)
|
|
10
|
-
|
|
11
|
-
> 国内网络建议优先 [Gitee 镜像](https://gitee.com/fxri/swagger2api)(与 GitHub 同源同步);问题反馈走 [GitHub Issues](https://github.com/fxri-net/swagger2api/issues) 或 [Gitee Issues](https://gitee.com/fxri/swagger2api/issues)。
|
|
12
|
-
|
|
13
|
-
基于 [swagger-typescript-api](https://github.com/acacode/swagger-typescript-api) 封装的 CLI 工具:Swagger 文档一键转 TS/JS 格式的 API 文件。
|
|
14
|
-
|
|
15
|
-
后端给到 Swagger 文档,接口代码还要照着手写;接口一多重名 `_n` 后缀满屏;多个项目的接口配置散落各处,更新要挨个跑命令。本工具把这些沉淀为**一行命令**:配置落盘可复用,生成静默无感,调用即取即用。
|
|
16
|
-
|
|
17
|
-
- **多文档配置**:自动扫描项目下全部 `saconfig*.json`,多项目接口集中管理,搭配快速模式一行命令全量更新([怎么玩?](./docs/guide.md#多文档配置))
|
|
18
|
-
- **唯一 operationId**:接口地址 + 请求方法拼接,从源头告别 `_n` 重名后缀([拼接规则](./docs/guide.md#唯一-operationid-拼接规则))
|
|
19
|
-
- **不懂生成的代码也能用**:接口文件含请求方法与类型定义,导入即调;参数全部有默认值,交互引导填写([30 秒上手](./docs/getting-started.md))
|
|
20
|
-
|
|
21
|
-
## 🚀 30 秒上手
|
|
22
|
-
|
|
23
|
-
```bash
|
|
24
|
-
# 1. 项目目录下临时执行(免安装;已安装则直接 swagger2api)
|
|
25
|
-
pnpm dlx @fxri/swagger2api
|
|
26
|
-
|
|
27
|
-
# 2. 按提示填写 Swagger 文档地址、输出目录、文件名
|
|
28
|
-
# 自动生成接口代码与 saconfig.json 配置文件
|
|
29
|
-
```
|
|
30
|
-
|
|
31
|
-
```typescript
|
|
32
|
-
import { Api } from "./src/api/index"
|
|
33
|
-
|
|
34
|
-
/** 请求器 */
|
|
35
|
-
export const request = new Api()
|
|
36
|
-
request.getUsers().then((res) => console.log(res))
|
|
37
|
-
```
|
|
38
|
-
|
|
39
|
-
完整步骤见 [新手指南](./docs/getting-started.md)。
|
|
40
|
-
|
|
41
|
-
## ✨ 能力矩阵
|
|
42
|
-
|
|
43
|
-
| 能力 | 适用场景 | 文档 |
|
|
44
|
-
| --- | --- | --- |
|
|
45
|
-
| 快速生成 | 从 Swagger JSON 生成 TS/JS 接口文件,含请求方法与类型定义 | [新手指南](./docs/getting-started.md) |
|
|
46
|
-
| 多文档配置 | 自动扫描 `./**/saconfig*.json`,多项目接口配置集中管理 | [完整攻略](./docs/guide.md#多文档配置) |
|
|
47
|
-
| 快速模式 | 配置齐全时跳过二次确认,搭配脚本一行命令静默更新 | [完整攻略](./docs/guide.md#快速模式) |
|
|
48
|
-
| 唯一 operationId | 接口地址 + 请求方法拼接唯一 ID,可选 get 转 query 作区分 | [完整攻略](./docs/guide.md#唯一-operationid-拼接规则) |
|
|
49
|
-
| 灵活裁剪 | 移除路径参数 / 前缀索引、替换标签、移除空组件定义 | [CLI 参考](./docs/cli.md#配置选项) |
|
|
50
|
-
| 响应提取 | AxiosResponse 转移到 raw 字段,根部字段自行声明 | [完整攻略](./docs/guide.md#提取响应--extract-response-raw-err) |
|
|
51
|
-
| STA 参数透传 | swagger-typescript-api 原生参数全量可用 | [CLI 参考](./docs/cli.md) |
|
|
52
|
-
|
|
53
|
-
## 📚 文档
|
|
54
|
-
|
|
55
|
-
| 文档 | 适合谁 |
|
|
56
|
-
| --- | --- |
|
|
57
|
-
| [新手指南](./docs/getting-started.md) | 第一次接触,想 30 秒跑起来 |
|
|
58
|
-
| [完整攻略](./docs/guide.md) | 日常使用:三种模式、响应提取、配置文件 |
|
|
59
|
-
| [CLI 参考](./docs/cli.md) | 查命令、参数、默认值 |
|
|
60
|
-
| [FAQ](./docs/faq.md) | 遇到问题先来这里找 |
|
|
61
|
-
| [完整文档站](https://fxri-net.github.io/swagger2api/) | 在线阅读体验 |
|
|
62
|
-
|
|
63
|
-
## 📦 安装
|
|
64
|
-
|
|
65
|
-
```bash
|
|
66
|
-
pnpm add -D @fxri/swagger2api # 项目依赖(团队推荐,版本随仓库锁定)
|
|
67
|
-
pnpm i -g @fxri/swagger2api # 全局(个人多项目推荐)
|
|
68
|
-
pnpm dlx @fxri/swagger2api # 不安装临时执行
|
|
69
|
-
```
|
|
70
|
-
|
|
71
|
-
npm / yarn 用户、同名工具冲突说明见 [新手指南 · 安装](./docs/getting-started.md#安装)。
|
|
72
|
-
|
|
73
|
-
## 📁 多文档配置
|
|
74
|
-
|
|
75
|
-
默认配置文件为 `saconfig.json`;工具会扫描项目下所有 `saconfig*.json`(如 `saconfig.admin.json`、`config/saconfig.json`),多文件时提供选择列表。搭配快速模式与加载全部配置参数,`package.json` 一行脚本即可静默更新所有项目的接口代码:
|
|
76
|
-
|
|
77
|
-
```json
|
|
78
|
-
{
|
|
79
|
-
"scripts": {
|
|
80
|
-
"api": "swagger2api --axios --responses -q -rpi 0 -err -ca"
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
```
|
|
84
|
-
|
|
85
|
-
此功能扩展使用的话,可以作为一个独立工具使用,同时管理多个项目的接口配置。详见 [完整攻略 · 多文档配置](./docs/guide.md#多文档配置)。
|
|
86
|
-
|
|
87
|
-
## ⚙️ 环境要求
|
|
88
|
-
|
|
89
|
-
- Node.js >= 20
|
|
90
|
-
|
|
91
|
-
##
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="./docs/public/logo.png" width="128" alt="Swagger 转 API">
|
|
3
|
+
</p>
|
|
4
|
+
|
|
5
|
+
# Swagger 转 API
|
|
6
|
+
|
|
7
|
+
[](https://www.npmjs.com/package/@fxri/swagger2api)
|
|
8
|
+
[](./docs/getting-started.md#安装)
|
|
9
|
+
[](./LICENSE)
|
|
10
|
+
|
|
11
|
+
> 国内网络建议优先 [Gitee 镜像](https://gitee.com/fxri/swagger2api)(与 GitHub 同源同步);问题反馈走 [GitHub Issues](https://github.com/fxri-net/swagger2api/issues) 或 [Gitee Issues](https://gitee.com/fxri/swagger2api/issues)。
|
|
12
|
+
|
|
13
|
+
基于 [swagger-typescript-api](https://github.com/acacode/swagger-typescript-api) 封装的 CLI 工具:Swagger 文档一键转 TS/JS 格式的 API 文件。
|
|
14
|
+
|
|
15
|
+
后端给到 Swagger 文档,接口代码还要照着手写;接口一多重名 `_n` 后缀满屏;多个项目的接口配置散落各处,更新要挨个跑命令。本工具把这些沉淀为**一行命令**:配置落盘可复用,生成静默无感,调用即取即用。
|
|
16
|
+
|
|
17
|
+
- **多文档配置**:自动扫描项目下全部 `saconfig*.json`,多项目接口集中管理,搭配快速模式一行命令全量更新([怎么玩?](./docs/guide.md#多文档配置))
|
|
18
|
+
- **唯一 operationId**:接口地址 + 请求方法拼接,从源头告别 `_n` 重名后缀([拼接规则](./docs/guide.md#唯一-operationid-拼接规则))
|
|
19
|
+
- **不懂生成的代码也能用**:接口文件含请求方法与类型定义,导入即调;参数全部有默认值,交互引导填写([30 秒上手](./docs/getting-started.md))
|
|
20
|
+
|
|
21
|
+
## 🚀 30 秒上手
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
# 1. 项目目录下临时执行(免安装;已安装则直接 swagger2api)
|
|
25
|
+
pnpm dlx @fxri/swagger2api
|
|
26
|
+
|
|
27
|
+
# 2. 按提示填写 Swagger 文档地址、输出目录、文件名
|
|
28
|
+
# 自动生成接口代码与 saconfig.json 配置文件
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
```typescript
|
|
32
|
+
import { Api } from "./src/api/index"
|
|
33
|
+
|
|
34
|
+
/** 请求器 */
|
|
35
|
+
export const request = new Api()
|
|
36
|
+
request.getUsers().then((res) => console.log(res))
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
完整步骤见 [新手指南](./docs/getting-started.md)。
|
|
40
|
+
|
|
41
|
+
## ✨ 能力矩阵
|
|
42
|
+
|
|
43
|
+
| 能力 | 适用场景 | 文档 |
|
|
44
|
+
| --- | --- | --- |
|
|
45
|
+
| 快速生成 | 从 Swagger JSON 生成 TS/JS 接口文件,含请求方法与类型定义 | [新手指南](./docs/getting-started.md) |
|
|
46
|
+
| 多文档配置 | 自动扫描 `./**/saconfig*.json`,多项目接口配置集中管理 | [完整攻略](./docs/guide.md#多文档配置) |
|
|
47
|
+
| 快速模式 | 配置齐全时跳过二次确认,搭配脚本一行命令静默更新 | [完整攻略](./docs/guide.md#快速模式) |
|
|
48
|
+
| 唯一 operationId | 接口地址 + 请求方法拼接唯一 ID,可选 get 转 query 作区分 | [完整攻略](./docs/guide.md#唯一-operationid-拼接规则) |
|
|
49
|
+
| 灵活裁剪 | 移除路径参数 / 前缀索引、替换标签、移除空组件定义 | [CLI 参考](./docs/cli.md#配置选项) |
|
|
50
|
+
| 响应提取 | AxiosResponse 转移到 raw 字段,根部字段自行声明 | [完整攻略](./docs/guide.md#提取响应--extract-response-raw-err) |
|
|
51
|
+
| STA 参数透传 | swagger-typescript-api 原生参数全量可用 | [CLI 参考](./docs/cli.md) |
|
|
52
|
+
|
|
53
|
+
## 📚 文档
|
|
54
|
+
|
|
55
|
+
| 文档 | 适合谁 |
|
|
56
|
+
| --- | --- |
|
|
57
|
+
| [新手指南](./docs/getting-started.md) | 第一次接触,想 30 秒跑起来 |
|
|
58
|
+
| [完整攻略](./docs/guide.md) | 日常使用:三种模式、响应提取、配置文件 |
|
|
59
|
+
| [CLI 参考](./docs/cli.md) | 查命令、参数、默认值 |
|
|
60
|
+
| [FAQ](./docs/faq.md) | 遇到问题先来这里找 |
|
|
61
|
+
| [完整文档站](https://fxri-net.github.io/swagger2api/) | 在线阅读体验 |
|
|
62
|
+
|
|
63
|
+
## 📦 安装
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
pnpm add -D @fxri/swagger2api # 项目依赖(团队推荐,版本随仓库锁定)
|
|
67
|
+
pnpm i -g @fxri/swagger2api # 全局(个人多项目推荐)
|
|
68
|
+
pnpm dlx @fxri/swagger2api # 不安装临时执行
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
npm / yarn 用户、同名工具冲突说明见 [新手指南 · 安装](./docs/getting-started.md#安装)。
|
|
72
|
+
|
|
73
|
+
## 📁 多文档配置
|
|
74
|
+
|
|
75
|
+
默认配置文件为 `saconfig.json`;工具会扫描项目下所有 `saconfig*.json`(如 `saconfig.admin.json`、`config/saconfig.json`),多文件时提供选择列表。搭配快速模式与加载全部配置参数,`package.json` 一行脚本即可静默更新所有项目的接口代码:
|
|
76
|
+
|
|
77
|
+
```json
|
|
78
|
+
{
|
|
79
|
+
"scripts": {
|
|
80
|
+
"api": "swagger2api --axios --responses -q -rpi 0 -err -ca"
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
此功能扩展使用的话,可以作为一个独立工具使用,同时管理多个项目的接口配置。详见 [完整攻略 · 多文档配置](./docs/guide.md#多文档配置)。
|
|
86
|
+
|
|
87
|
+
## ⚙️ 环境要求
|
|
88
|
+
|
|
89
|
+
- Node.js >= 20
|
|
90
|
+
|
|
91
|
+
## 🛠️ 开发约定
|
|
92
|
+
|
|
93
|
+
构建、调试与验收命令见[完整攻略](https://fxri-net.github.io/swagger2api/guide.html)。
|
|
94
|
+
|
|
95
|
+
## 📄 版权信息
|
|
96
|
+
|
|
97
|
+
作者:唐启云 <tqy@fxri.net>
|
|
98
|
+
|
|
99
|
+
出品:方弦研究所
|
|
100
|
+
|
|
101
|
+
版权:Copyright © 2025-2026 唐启云. All rights reserved.
|
|
102
|
+
|
|
103
|
+
网站:[方弦研究信息网](https://fxri.net:444/)
|
|
104
|
+
|
|
105
|
+
协议:[MIT License](./LICENSE)
|
|
106
|
+
|
|
107
|
+
商标:"方弦®"为第42类注册商标(注册号89648411),本开源许可不授予商标使用权,详见 [TRADEMARK.md](./TRADEMARK.md)
|
|
108
|
+
|
|
109
|
+
> 方弦研究所为唐启云个人项目品牌与出品方,非独立法人实体;本软件著作权归唐启云所有。
|
package/dist/cli.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var F=Object.create;var
|
|
1
|
+
var F=Object.create;var S=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var J=Object.getPrototypeOf,_=Object.prototype.hasOwnProperty;var I=(e,r,o,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of C(r))!_.call(e,i)&&i!==o&&S(e,i,{get:()=>r[i],enumerable:!(s=N(r,i))||s.enumerable});return e};var c=(e,r,o)=>(o=e!=null?F(J(e)):{},I(r||!e||!e.__esModule?S(o,"default",{value:e,enumerable:!0}):o,e));var q=c(require("axios"),1),A=require("child_process"),j=c(require("os"),1),g=c(require("fs"),1),l=c(require("path"),1),v=c(require("prompts"),1),E=require("swagger-typescript-api");var b=e=>/^(https?:\/\/|:?\/\/)/.test(e);var f=c(require("fs"),1),w=c(require("url"),1),d=c(require("path"),1),U={},u={param:process.argv.filter((e,r)=>r>1)};function y(e,r="value",o={}){Array.isArray(e)||(e=[e]);let s;return u.param.forEach((i,m)=>{if(e.includes(i))["value"].includes(r)?s=u.param[m+1]:["array"].includes(r)?s=Array.from({length:o.length??1}).map((K,D)=>u.param[m+D+1]):s=!["false"].includes(u.param[m+1]);else return}),s}function t(e){return y(e,"key")}function p(e){return y(e,"value")}function P(e,r={}){return y(e,"array",r)??[]}function x(e,r){let o=d.default.dirname(e);f.default.existsSync(o)||f.default.mkdirSync(o,{recursive:!0}),f.default.writeFileSync(e,r)}function L(){return typeof require<"u"&&typeof module<"u"?__filename:w.default.fileURLToPath(U.url)}function R(){return typeof require<"u"&&typeof module<"u"?__dirname:d.default.dirname(L())}var T=require("glob"),a={files:[],param:{}},n={home:j.default.homedir(),enum:{}};function h(e){e&&console.log(e),process.exit()}async function G(){n.param={config:p(["--config","-c"]),configScan:t(["--config-scan","-cs"])??!0,configAll:t(["--config-all","-ca"]),quick:t(["--quick","-q"]),replaceTags:P(["--replace-tags","-rt"],{length:2}),convertGet:t(["--convert-get","-cg"]),removeParam:t(["--remove-param","-rp"]),removePrefixIndex:p(["--remove-prefix-index","-rpi"]),removeDts:t(["--remove-dts","-rd"]),removeEmptyComponents:t(["--remove-empty-components","-rec"])??!0,extractRequestQuery:p(["--extract-request-query","-erq"]),extractResponseRaw:t(["--extract-response-raw","-err"]),template:l.default.resolve(R(),"./templates")},n.config={templates:p(["--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(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")??!0,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 V(){n.param.config?a.files=n.param.config.split(","):n.param.configScan&&(a.files=(0,T.globSync)(["./**/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 B(){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,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=l.default.resolve(`${a.param.output}/${a.param.name}-${new Date().getTime()}.json`)}async function O(e=0){if(a.file=a.files[e],await B(),b(a.param.url))await q.default.get(a.param.url).then(r=>$(r.data)).catch(r=>console.log("\u5931\u8D25\uFF1A",r));else try{await $(JSON.parse(g.default.readFileSync(l.default.resolve(a.param.url),"utf8")))}catch(r){console.log("\u5931\u8D25\uFF1A",r)}a.files[e+1]&&O(e+1)}async function $(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(o=>{n.param.replaceTags.length&&(e.paths[r[0]][o].tags=e.paths[r[0]][o].tags?.map(m=>m.replace(new RegExp(`^${n.param.replaceTags[0]}$`,"g"),n.param.replaceTags[1]??"")));let s=`${r[0]}/${o}`;if(n.param.convertGet&&(s=s.replace(/([^\}]\/)get$/g,"$1query")),n.param.removeParam&&(s=s.replace(/\/\{.+?\}/g,"")),n.param.removePrefixIndex){let m=s.split("/");m=m.slice(0,1).concat(m.slice(Number(n.param.removePrefixIndex)+2)),s=m.join("/")}e.paths[r[0]][o].operationId=s;let i=s.split("/").slice(-1)[0];typeof n.enum[i]=="number"?n.enum[i]++:n.enum[i]=1})}),Object.entries(e.components).forEach(r=>{Object.keys(r[1]).forEach(o=>{n.param.removeEmptyComponents&&!Object.keys(e.components[r[0]][o]).length&&delete e.components[r[0]][o]})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(n.enum).map(r=>r.join("-"))),x(n.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",a.file),await(0,E.generateApi)({fileName:`${a.param.name}.ts`,output:l.default.resolve(a.param.output),input:n.docFile,...n.config,param:n.param}),console.log("\u5B8C\u6210\uFF1A",l.default.resolve(a.param.output,`${a.param.name}${n.config.toJS?".js":".ts"}`)),n.config.toJS&&console.log("\u5B8C\u6210\uFF1A",l.default.resolve(a.param.output,`${a.param.name}.d.ts`)),g.default.unlinkSync(n.docFile),n.param.removeDts&&(console.log("\u6E05\u7406\uFF1A",l.default.resolve(a.param.output,`${a.param.name}.d.ts`)),(0,A.execSync)(`npx rimraf ${l.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 k(){await G(),await V(),O()}k();
|
package/dist/cli.d.cts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
|
|
2
|
-
export {
|
|
2
|
+
export { };
|
package/dist/cli.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
|
|
2
|
-
export {
|
|
2
|
+
export { };
|
package/dist/cli.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var u=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,o)=>(typeof require<"u"?require:n)[o]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import E from"axios";import{execSync as T}from"child_process";import O from"os";import x from"fs";import m from"path";import P from"prompts";import{generateApi as k}from"swagger-typescript-api";var h=e=>/^(https?:\/\/|:?\/\/)/.test(e);import f from"fs";import A from"url";import v from"path";var c={param:process.argv.filter((e,n)=>n>1)};function g(e,n="value",o={}){Array.isArray(e)||(e=[e]);let s;return c.param.forEach((l,p)=>{if(e.includes(l))["value"].includes(n)?s=c.param[p+1]:["array"].includes(n)?s=Array.from({length:o.length??1}).map((J,q)=>c.param[p+q+1]):s=!["false"].includes(c.param[p+1]);else return}),s}function r(e){return g(e,"key")}function i(e){return g(e,"value")}function
|
|
1
|
+
var u=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,o)=>(typeof require<"u"?require:n)[o]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import E from"axios";import{execSync as T}from"child_process";import O from"os";import x from"fs";import m from"path";import P from"prompts";import{generateApi as k}from"swagger-typescript-api";var h=e=>/^(https?:\/\/|:?\/\/)/.test(e);import f from"fs";import A from"url";import v from"path";var c={param:process.argv.filter((e,n)=>n>1)};function g(e,n="value",o={}){Array.isArray(e)||(e=[e]);let s;return c.param.forEach((l,p)=>{if(e.includes(l))["value"].includes(n)?s=c.param[p+1]:["array"].includes(n)?s=Array.from({length:o.length??1}).map((J,q)=>c.param[p+q+1]):s=!["false"].includes(c.param[p+1]);else return}),s}function r(e){return g(e,"key")}function i(e){return g(e,"value")}function S(e,n={}){return g(e,"array",n)??[]}function d(e,n){let o=v.dirname(e);f.existsSync(o)||f.mkdirSync(o,{recursive:!0}),f.writeFileSync(e,n)}function j(){return typeof u<"u"&&typeof module<"u"?__filename:A.fileURLToPath(import.meta.url)}function b(){return typeof u<"u"&&typeof module<"u"?__dirname:v.dirname(j())}import{globSync as D}from"glob";var a={files:[],param:{}},t={home:O.homedir(),enum:{}};function y(e){e&&console.log(e),process.exit()}async function F(){t.param={config:i(["--config","-c"]),configScan:r(["--config-scan","-cs"])??!0,configAll:r(["--config-all","-ca"]),quick:r(["--quick","-q"]),replaceTags:S(["--replace-tags","-rt"],{length:2}),convertGet:r(["--convert-get","-cg"]),removeParam:r(["--remove-param","-rp"]),removePrefixIndex:i(["--remove-prefix-index","-rpi"]),removeDts:r(["--remove-dts","-rd"]),removeEmptyComponents:r(["--remove-empty-components","-rec"])??!0,extractRequestQuery:i(["--extract-request-query","-erq"]),extractResponseRaw:r(["--extract-response-raw","-err"]),template:m.resolve(b(),"./templates")},t.config={templates:i(["--templates","-t"])??t.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(i("--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")??!0,defaultResponseType:i("--default-response")??"void",typePrefix:i("--type-prefix")??"",typeSuffix:i("--type-suffix")??"",cleanOutput:r("--clean-output"),...i("--api-class-name")?{apiClassName:i("--api-class-name")}:{},patch:r("--patch"),debug:r("--debug"),anotherArrayType:r("--another-array-type"),sortTypes:r("--sort-types"),extractEnums:r("--extract-enums")}}async function N(){t.param.config?a.files=t.param.config.split(","):t.param.configScan&&(a.files=D(["./**/saconfig*.json"],{ignore:"node_modules/**"})),a.files.length==0&&(a.files=["saconfig.json"]),!t.param.configAll&&a.files.length>1&&(a.files=(await P({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:y("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),a.files?.length>0||y("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function C(){try{a.param={},a.param=JSON.parse(x.readFileSync(a.file,"utf-8"))}catch{}(!t.param.quick||[a.param.url,a.param.output,a.param.name].includes(void 0))&&(a.param=await P([{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)&&y("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),t.docFile=m.resolve(`${a.param.output}/${a.param.name}-${new Date().getTime()}.json`)}async function R(e=0){if(a.file=a.files[e],await C(),h(a.param.url))await E.get(a.param.url).then(n=>w(n.data)).catch(n=>console.log("\u5931\u8D25\uFF1A",n));else try{await w(JSON.parse(x.readFileSync(m.resolve(a.param.url),"utf8")))}catch(n){console.log("\u5931\u8D25\uFF1A",n)}a.files[e+1]&&R(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(o=>{t.param.replaceTags.length&&(e.paths[n[0]][o].tags=e.paths[n[0]][o].tags?.map(p=>p.replace(new RegExp(`^${t.param.replaceTags[0]}$`,"g"),t.param.replaceTags[1]??"")));let s=`${n[0]}/${o}`;if(t.param.convertGet&&(s=s.replace(/([^\}]\/)get$/g,"$1query")),t.param.removeParam&&(s=s.replace(/\/\{.+?\}/g,"")),t.param.removePrefixIndex){let p=s.split("/");p=p.slice(0,1).concat(p.slice(Number(t.param.removePrefixIndex)+2)),s=p.join("/")}e.paths[n[0]][o].operationId=s;let l=s.split("/").slice(-1)[0];typeof t.enum[l]=="number"?t.enum[l]++:t.enum[l]=1})}),Object.entries(e.components).forEach(n=>{Object.keys(n[1]).forEach(o=>{t.param.removeEmptyComponents&&!Object.keys(e.components[n[0]][o]).length&&delete e.components[n[0]][o]})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(t.enum).map(n=>n.join("-"))),d(t.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",a.file),await k({fileName:`${a.param.name}.ts`,output:m.resolve(a.param.output),input:t.docFile,...t.config,param:t.param}),console.log("\u5B8C\u6210\uFF1A",m.resolve(a.param.output,`${a.param.name}${t.config.toJS?".js":".ts"}`)),t.config.toJS&&console.log("\u5B8C\u6210\uFF1A",m.resolve(a.param.output,`${a.param.name}.d.ts`)),x.unlinkSync(t.docFile),t.param.removeDts&&(console.log("\u6E05\u7406\uFF1A",m.resolve(a.param.output,`${a.param.name}.d.ts`)),T(`npx rimraf ${m.resolve(a.param.output,`${a.param.name}.d.ts`)}`,{cwd:t.home}).toString()),d(a.file,JSON.stringify(a.param,null,2))}async function $(){await F(),await N(),R()}$();
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var F=Object.create;var u=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var J=Object.getPrototypeOf,_=Object.prototype.hasOwnProperty;var I=(e,r)=>{for(var o in r)u(e,o,{get:r[o],enumerable:!0})},
|
|
1
|
+
var F=Object.create;var u=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var J=Object.getPrototypeOf,_=Object.prototype.hasOwnProperty;var I=(e,r)=>{for(var o in r)u(e,o,{get:r[o],enumerable:!0})},b=(e,r,o,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of C(r))!_.call(e,i)&&i!==o&&u(e,i,{get:()=>r[i],enumerable:!(s=N(r,i))||s.enumerable});return e};var c=(e,r,o)=>(o=e!=null?F(J(e)):{},b(r||!e||!e.__esModule?u(o,"default",{value:e,enumerable:!0}):o,e)),L=e=>b(u({},"__esModule",{value:!0}),e);var M={};I(M,{generateApi:()=>H});module.exports=L(M);var j=c(require("axios"),1),A=require("child_process"),E=c(require("os"),1),d=c(require("fs"),1),l=c(require("path"),1),S=c(require("prompts"),1),T=require("swagger-typescript-api");var w=e=>/^(https?:\/\/|:?\/\/)/.test(e);var g=c(require("fs"),1),P=c(require("url"),1),y=c(require("path"),1),G={},f={param:process.argv.filter((e,r)=>r>1)};function x(e,r="value",o={}){Array.isArray(e)||(e=[e]);let s;return f.param.forEach((i,m)=>{if(e.includes(i))["value"].includes(r)?s=f.param[m+1]:["array"].includes(r)?s=Array.from({length:o.length??1}).map((Q,D)=>f.param[m+D+1]):s=!["false"].includes(f.param[m+1]);else return}),s}function t(e){return x(e,"key")}function p(e){return x(e,"value")}function R(e,r={}){return x(e,"array",r)??[]}function h(e,r){let o=y.default.dirname(e);g.default.existsSync(o)||g.default.mkdirSync(o,{recursive:!0}),g.default.writeFileSync(e,r)}function U(){return typeof require<"u"&&typeof module<"u"?__filename:P.default.fileURLToPath(G.url)}function $(){return typeof require<"u"&&typeof module<"u"?__dirname:y.default.dirname(U())}var O=require("glob"),a={files:[],param:{}},n={home:E.default.homedir(),enum:{}};function v(e){e&&console.log(e),process.exit()}async function V(){n.param={config:p(["--config","-c"]),configScan:t(["--config-scan","-cs"])??!0,configAll:t(["--config-all","-ca"]),quick:t(["--quick","-q"]),replaceTags:R(["--replace-tags","-rt"],{length:2}),convertGet:t(["--convert-get","-cg"]),removeParam:t(["--remove-param","-rp"]),removePrefixIndex:p(["--remove-prefix-index","-rpi"]),removeDts:t(["--remove-dts","-rd"]),removeEmptyComponents:t(["--remove-empty-components","-rec"])??!0,extractRequestQuery:p(["--extract-request-query","-erq"]),extractResponseRaw:t(["--extract-response-raw","-err"]),template:l.default.resolve($(),"./templates")},n.config={templates:p(["--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(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")??!0,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 B(){n.param.config?a.files=n.param.config.split(","):n.param.configScan&&(a.files=(0,O.globSync)(["./**/saconfig*.json"],{ignore:"node_modules/**"})),a.files.length==0&&(a.files=["saconfig.json"]),!n.param.configAll&&a.files.length>1&&(a.files=(await(0,S.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:v("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),a.files?.length>0||v("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function K(){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,S.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)&&v("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),n.docFile=l.default.resolve(`${a.param.output}/${a.param.name}-${new Date().getTime()}.json`)}async function k(e=0){if(a.file=a.files[e],await K(),w(a.param.url))await j.default.get(a.param.url).then(r=>q(r.data)).catch(r=>console.log("\u5931\u8D25\uFF1A",r));else try{await q(JSON.parse(d.default.readFileSync(l.default.resolve(a.param.url),"utf8")))}catch(r){console.log("\u5931\u8D25\uFF1A",r)}a.files[e+1]&&k(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(o=>{n.param.replaceTags.length&&(e.paths[r[0]][o].tags=e.paths[r[0]][o].tags?.map(m=>m.replace(new RegExp(`^${n.param.replaceTags[0]}$`,"g"),n.param.replaceTags[1]??"")));let s=`${r[0]}/${o}`;if(n.param.convertGet&&(s=s.replace(/([^\}]\/)get$/g,"$1query")),n.param.removeParam&&(s=s.replace(/\/\{.+?\}/g,"")),n.param.removePrefixIndex){let m=s.split("/");m=m.slice(0,1).concat(m.slice(Number(n.param.removePrefixIndex)+2)),s=m.join("/")}e.paths[r[0]][o].operationId=s;let i=s.split("/").slice(-1)[0];typeof n.enum[i]=="number"?n.enum[i]++:n.enum[i]=1})}),Object.entries(e.components).forEach(r=>{Object.keys(r[1]).forEach(o=>{n.param.removeEmptyComponents&&!Object.keys(e.components[r[0]][o]).length&&delete e.components[r[0]][o]})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(n.enum).map(r=>r.join("-"))),h(n.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",a.file),await(0,T.generateApi)({fileName:`${a.param.name}.ts`,output:l.default.resolve(a.param.output),input:n.docFile,...n.config,param:n.param}),console.log("\u5B8C\u6210\uFF1A",l.default.resolve(a.param.output,`${a.param.name}${n.config.toJS?".js":".ts"}`)),n.config.toJS&&console.log("\u5B8C\u6210\uFF1A",l.default.resolve(a.param.output,`${a.param.name}.d.ts`)),d.default.unlinkSync(n.docFile),n.param.removeDts&&(console.log("\u6E05\u7406\uFF1A",l.default.resolve(a.param.output,`${a.param.name}.d.ts`)),(0,A.execSync)(`npx rimraf ${l.default.resolve(a.param.output,`${a.param.name}.d.ts`)}`,{cwd:n.home}).toString()),h(a.file,JSON.stringify(a.param,null,2))}async function H(){await V(),await B(),k()}0&&(module.exports={generateApi});
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var u=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,o)=>(typeof require<"u"?require:n)[o]}):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 E}from"child_process";import T from"os";import x from"fs";import m from"path";import P from"prompts";import{generateApi as O}from"swagger-typescript-api";var h=e=>/^(https?:\/\/|:?\/\/)/.test(e);import f from"fs";import q from"url";import v from"path";var c={param:process.argv.filter((e,n)=>n>1)};function g(e,n="value",o={}){Array.isArray(e)||(e=[e]);let s;return c.param.forEach((l,p)=>{if(e.includes(l))["value"].includes(n)?s=c.param[p+1]:["array"].includes(n)?s=Array.from({length:o.length??1}).map((C,$)=>c.param[p+$+1]):s=!["false"].includes(c.param[p+1]);else return}),s}function r(e){return g(e,"key")}function i(e){return g(e,"value")}function
|
|
1
|
+
var u=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,o)=>(typeof require<"u"?require:n)[o]}):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 E}from"child_process";import T from"os";import x from"fs";import m from"path";import P from"prompts";import{generateApi as O}from"swagger-typescript-api";var h=e=>/^(https?:\/\/|:?\/\/)/.test(e);import f from"fs";import q from"url";import v from"path";var c={param:process.argv.filter((e,n)=>n>1)};function g(e,n="value",o={}){Array.isArray(e)||(e=[e]);let s;return c.param.forEach((l,p)=>{if(e.includes(l))["value"].includes(n)?s=c.param[p+1]:["array"].includes(n)?s=Array.from({length:o.length??1}).map((C,$)=>c.param[p+$+1]):s=!["false"].includes(c.param[p+1]);else return}),s}function r(e){return g(e,"key")}function i(e){return g(e,"value")}function S(e,n={}){return g(e,"array",n)??[]}function d(e,n){let o=v.dirname(e);f.existsSync(o)||f.mkdirSync(o,{recursive:!0}),f.writeFileSync(e,n)}function j(){return typeof u<"u"&&typeof module<"u"?__filename:q.fileURLToPath(import.meta.url)}function b(){return typeof u<"u"&&typeof module<"u"?__dirname:v.dirname(j())}import{globSync as k}from"glob";var a={files:[],param:{}},t={home:T.homedir(),enum:{}};function y(e){e&&console.log(e),process.exit()}async function D(){t.param={config:i(["--config","-c"]),configScan:r(["--config-scan","-cs"])??!0,configAll:r(["--config-all","-ca"]),quick:r(["--quick","-q"]),replaceTags:S(["--replace-tags","-rt"],{length:2}),convertGet:r(["--convert-get","-cg"]),removeParam:r(["--remove-param","-rp"]),removePrefixIndex:i(["--remove-prefix-index","-rpi"]),removeDts:r(["--remove-dts","-rd"]),removeEmptyComponents:r(["--remove-empty-components","-rec"])??!0,extractRequestQuery:i(["--extract-request-query","-erq"]),extractResponseRaw:r(["--extract-response-raw","-err"]),template:m.resolve(b(),"./templates")},t.config={templates:i(["--templates","-t"])??t.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(i("--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")??!0,defaultResponseType:i("--default-response")??"void",typePrefix:i("--type-prefix")??"",typeSuffix:i("--type-suffix")??"",cleanOutput:r("--clean-output"),...i("--api-class-name")?{apiClassName:i("--api-class-name")}:{},patch:r("--patch"),debug:r("--debug"),anotherArrayType:r("--another-array-type"),sortTypes:r("--sort-types"),extractEnums:r("--extract-enums")}}async function F(){t.param.config?a.files=t.param.config.split(","):t.param.configScan&&(a.files=k(["./**/saconfig*.json"],{ignore:"node_modules/**"})),a.files.length==0&&(a.files=["saconfig.json"]),!t.param.configAll&&a.files.length>1&&(a.files=(await P({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:y("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),a.files?.length>0||y("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function N(){try{a.param={},a.param=JSON.parse(x.readFileSync(a.file,"utf-8"))}catch{}(!t.param.quick||[a.param.url,a.param.output,a.param.name].includes(void 0))&&(a.param=await P([{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)&&y("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),t.docFile=m.resolve(`${a.param.output}/${a.param.name}-${new Date().getTime()}.json`)}async function R(e=0){if(a.file=a.files[e],await N(),h(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(x.readFileSync(m.resolve(a.param.url),"utf8")))}catch(n){console.log("\u5931\u8D25\uFF1A",n)}a.files[e+1]&&R(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(o=>{t.param.replaceTags.length&&(e.paths[n[0]][o].tags=e.paths[n[0]][o].tags?.map(p=>p.replace(new RegExp(`^${t.param.replaceTags[0]}$`,"g"),t.param.replaceTags[1]??"")));let s=`${n[0]}/${o}`;if(t.param.convertGet&&(s=s.replace(/([^\}]\/)get$/g,"$1query")),t.param.removeParam&&(s=s.replace(/\/\{.+?\}/g,"")),t.param.removePrefixIndex){let p=s.split("/");p=p.slice(0,1).concat(p.slice(Number(t.param.removePrefixIndex)+2)),s=p.join("/")}e.paths[n[0]][o].operationId=s;let l=s.split("/").slice(-1)[0];typeof t.enum[l]=="number"?t.enum[l]++:t.enum[l]=1})}),Object.entries(e.components).forEach(n=>{Object.keys(n[1]).forEach(o=>{t.param.removeEmptyComponents&&!Object.keys(e.components[n[0]][o]).length&&delete e.components[n[0]][o]})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(t.enum).map(n=>n.join("-"))),d(t.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",a.file),await O({fileName:`${a.param.name}.ts`,output:m.resolve(a.param.output),input:t.docFile,...t.config,param:t.param}),console.log("\u5B8C\u6210\uFF1A",m.resolve(a.param.output,`${a.param.name}${t.config.toJS?".js":".ts"}`)),t.config.toJS&&console.log("\u5B8C\u6210\uFF1A",m.resolve(a.param.output,`${a.param.name}.d.ts`)),x.unlinkSync(t.docFile),t.param.removeDts&&(console.log("\u6E05\u7406\uFF1A",m.resolve(a.param.output,`${a.param.name}.d.ts`)),E(`npx rimraf ${m.resolve(a.param.output,`${a.param.name}.d.ts`)}`,{cwd:t.home}).toString()),d(a.file,JSON.stringify(a.param,null,2))}async function ne(){await D(),await F(),R()}export{ne as generateApi};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fxri/swagger2api",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.10",
|
|
4
4
|
"description": "基于 swagger-typescript-api,将 Swagger 文档自动转为 TypeScript 格式的 API 文件。",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": {
|
|
@@ -26,10 +26,10 @@
|
|
|
26
26
|
"api"
|
|
27
27
|
],
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"axios": "^1.
|
|
30
|
-
"glob": "^
|
|
29
|
+
"axios": "^1.21.0",
|
|
30
|
+
"glob": "^14.0.3",
|
|
31
31
|
"prompts": "^2.4.2",
|
|
32
|
-
"swagger-typescript-api": "^13.
|
|
32
|
+
"swagger-typescript-api": "^13.13.0"
|
|
33
33
|
},
|
|
34
34
|
"devDependencies": {
|
|
35
35
|
"@types/node": "^20.19.43",
|
|
@@ -40,8 +40,7 @@
|
|
|
40
40
|
"esbuild-plugin-copy": "^2.1.1",
|
|
41
41
|
"eslint": "^8.57.1",
|
|
42
42
|
"eslint-config-prettier": "^9.1.2",
|
|
43
|
-
"
|
|
44
|
-
"tsup": "^8.5.1",
|
|
43
|
+
"tsup": "^9.0.0",
|
|
45
44
|
"typescript": "^5.9.3",
|
|
46
45
|
"vitepress": "^1.6.4"
|
|
47
46
|
},
|
|
@@ -63,8 +62,12 @@
|
|
|
63
62
|
"dev": "pnpm build:debug && node ./dist/cli.js",
|
|
64
63
|
"build": "cross-env NODE_ENV=production tsup",
|
|
65
64
|
"build:debug": "cross-env NODE_ENV=development tsup --config tsup.dev.config.ts",
|
|
65
|
+
"typecheck": "tsc --noEmit",
|
|
66
|
+
"lint": "eslint \"src/**/*.ts\" \"scripts/**/*.mjs\" --no-cache",
|
|
67
|
+
"lint:fix": "eslint \"src/**/*.ts\" \"scripts/**/*.mjs\" --fix",
|
|
68
|
+
"verify": "node scripts/verify.mjs",
|
|
66
69
|
"release": "pnpm build && pnpm publish",
|
|
67
|
-
"sync:changelog-doc": "
|
|
70
|
+
"sync:changelog-doc": "toolkit changelog doc",
|
|
68
71
|
"docs:dev": "vitepress dev docs",
|
|
69
72
|
"docs:build": "vitepress build docs",
|
|
70
73
|
"docs:preview": "vitepress preview docs",
|