@fxri/swagger2api 1.3.0 → 1.3.2

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.
@@ -8,7 +8,9 @@ const isModular = Boolean(config.modular && route);
8
8
  const moduleName = isModular ? route.moduleName : "";
9
9
  // 分组模式由命名表提供类名,与聚合入口同源;未分组时沿用依赖的 pascalCase
10
10
  const moduleClassName = isModular ? (config.param?.moduleClassNames?.[moduleName] ?? pascalCase(moduleName)) : "";
11
- const moduleRoutes = isModular ? (route.routes || []) : [];
11
+ const moduleRoutes = isModular ? (route.routes || []) : [];
12
+ // 分桶文件:按命名空间渲染多个类;未配置时走单类分支
13
+ const bucketNamespaces = isModular ? config.param?.splitBuckets?.[moduleName] : undefined;
12
14
  const dataContractsFile = config.fileNames?.dataContracts ?? "data-contracts";
13
15
  const httpClientFile = config.fileNames?.httpClient ?? "http-client";
14
16
  const dataContracts = isModular ? _.map(it.modelTypes, "name") : [];
@@ -43,13 +45,49 @@ import { HttpClient, RequestParams, ContentType } from "./<%~ httpClientFile %>"
43
45
  import { <%~ dataContracts.join(", ") %> } from "./<%~ dataContractsFile %>"
44
46
  <% } %>
45
47
 
48
+ <% if (bucketNamespaces) { %>
49
+ <% for (const ns of bucketNamespaces) { %>
50
+ <% const nsRoutes = moduleRoutes.filter((item) => item.raw?.tags?.[1] === ns.tag); %>
51
+ /** <%~ ns.title %> 模块 */
52
+ export class <%~ ns.className %><SecurityDataType = unknown> {
53
+ /** 共享请求器:由聚合入口注入;仅供模块内部调用,勿在业务侧直接使用 */
54
+ http: HttpClient<SecurityDataType>
55
+
56
+ constructor(http: HttpClient<SecurityDataType>) {
57
+ this.http = http
58
+ }
59
+
60
+ /** 底层请求实例:与聚合入口保持同一个 */
61
+ get instance(): HttpClient<SecurityDataType>["instance"] {
62
+ return this.http.instance
63
+ }
64
+ <% for (const item of nsRoutes) { %>
65
+
66
+ <%~ includeFile('./procedure-call.ejs', { ...it, route: { ...item, namespace: undefined }, moduleClient: true }) %>
67
+ <% } %>
68
+ }
69
+
70
+ <% } %>
71
+ <% } else { %>
46
72
  /** <%~ moduleName %> 模块 */
47
- export class <%~ moduleClassName %><SecurityDataType = unknown> extends HttpClient<SecurityDataType> {
73
+ export class <%~ moduleClassName %><SecurityDataType = unknown> {
74
+ /** 共享请求器:由聚合入口注入;仅供模块内部调用,勿在业务侧直接使用 */
75
+ http: HttpClient<SecurityDataType>
76
+
77
+ constructor(http: HttpClient<SecurityDataType>) {
78
+ this.http = http
79
+ }
80
+
81
+ /** 底层请求实例:与聚合入口保持同一个 */
82
+ get instance(): HttpClient<SecurityDataType>["instance"] {
83
+ return this.http.instance
84
+ }
48
85
  <% for (const item of moduleRoutes) { %>
49
86
 
50
- <%~ includeFile('./procedure-call.ejs', { ...it, route: { ...item, namespace: undefined } }) %>
87
+ <%~ includeFile('./procedure-call.ejs', { ...it, route: { ...item, namespace: undefined }, moduleClient: true }) %>
51
88
  <% } %>
52
89
  }
90
+ <% } %>
53
91
 
54
92
  <% } else { %>
55
93
 
@@ -1,5 +1,5 @@
1
1
  <%
2
- const { utils, route, config } = it;
2
+ const { utils, route, config, moduleClient } = it;
3
3
  const { requestBodyInfo, responseBodyInfo, specificArgNameResolver } = route;
4
4
  const { _, getInlineParseContent, getParseContent, parseSchema, getComponentByRef, require } = utils;
5
5
  const { parameters, path, method, payload, query, formData, security, requestParams } = route.request;
@@ -72,12 +72,20 @@ const bodyContentKindTmpl = requestContentKind[requestBodyInfo.contentKind] || n
72
72
  const responseFormatTmpl = responseContentKind[responseBodyInfo.success && responseBodyInfo.success.schema && responseBodyInfo.success.schema.contentKind] || null;
73
73
  const securityTmpl = security ? 'true' : null;
74
74
 
75
+ // 响应类型:分组模式的声明由 tsc 生成,用内联导入避免模块声明丢失类型导入
76
+ const httpClientFile = config.fileNames?.httpClient ?? "http-client";
77
+ const responseTypeRef = () => {
78
+ if (!moduleClient) return "AxiosResponse";
79
+ const target = config.param?.extractResponseRaw ? `./${httpClientFile}` : "axios";
80
+ return `import("${target}").AxiosResponse`;
81
+ };
82
+
75
83
  const describeReturnType = () => {
76
84
  if (!config.toJS) return "";
77
85
 
78
86
  switch(config.httpClientType) {
79
87
  case HTTP_CLIENT.AXIOS: {
80
- return `Promise<AxiosResponse<${type}>>`
88
+ return `Promise<${responseTypeRef()}<${type}>>`
81
89
  }
82
90
  default: {
83
91
  return `Promise<HttpResponse<${type}, ${errorType}>`
@@ -97,7 +105,7 @@ const isValidIdentifier = (name) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
97
105
 
98
106
  */
99
107
  <% 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 %>>({
108
+ <%~ config.singleHttpClient || moduleClient ? 'this.http.request' : 'this.request' %><<%~ type %>, <%~ errorType %>>({
101
109
  path: `<%~ path %>`,
102
110
  method: '<%~ _.upperCase(method) %>',
103
111
  <%~ queryTmpl ? `query: ${queryTmpl},` : '' %>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fxri/swagger2api",
3
- "version": "1.3.0",
3
+ "version": "1.3.2",
4
4
  "description": "基于 swagger-typescript-api,将 Swagger 文档自动转为 TypeScript 格式的 API 文件。",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -24,6 +24,7 @@
24
24
  },
25
25
  "files": [
26
26
  "dist",
27
+ "skills",
27
28
  "README.md",
28
29
  "CHANGELOG.md",
29
30
  "LICENSE",
@@ -31,6 +32,7 @@
31
32
  "NOTICE",
32
33
  "package.json"
33
34
  ],
35
+ "agentSkills": "./skills",
34
36
  "keywords": [
35
37
  "swagger",
36
38
  "typescript",
@@ -44,7 +46,8 @@
44
46
  "dependencies": {
45
47
  "axios": "^1.21.0",
46
48
  "prompts": "^2.4.2",
47
- "swagger-typescript-api": "13.0.28"
49
+ "swagger-typescript-api": "13.0.28",
50
+ "typescript": "^5.9.3"
48
51
  },
49
52
  "devDependencies": {
50
53
  "@types/node": "^18.19.0",
@@ -56,7 +59,6 @@
56
59
  "eslint": "^10.15.0",
57
60
  "eslint-config-prettier": "^10.1.8",
58
61
  "tsup": "^8.5.1",
59
- "typescript": "^5.9.3",
60
62
  "vitepress": "^1.6.4",
61
63
  "vitest": "^4.1.12"
62
64
  },
@@ -0,0 +1,51 @@
1
+ ---
2
+ name: fxri-swagger2api
3
+ description: 首次为项目初始化 swagger2api 配置、迁移旧脚本配置或调整产物结构时加载:给出最小配置、先预览再落盘、说明分组产物与验收方式。日常生成、--check 与验收不加载。不用于一般 TypeScript / axios 用法或接口文档编写。
4
+ license: MIT
5
+ metadata:
6
+ version: "1.1.2"
7
+ tier: optional
8
+ author: fxri
9
+ source: https://github.com/fxri-net/swagger2api
10
+ ---
11
+
12
+ # swagger2api 接入
13
+
14
+ > 本技能版本 1.1.2(随 @fxri/swagger2api 分发)。被问版本时即报此值(不读磁盘、不跑 CLI);与已安装依赖的技能版本不一致即说明会话上下文已过期,开新会话即可。
15
+
16
+ ## 何时使用
17
+
18
+ - **首次给项目接入**:还没有 `swagger2api.json`,需要定最小配置并生成第一版产物。
19
+ - **迁移旧用法**:从 npm script 或旧的 `saconfig.json` 迁到分层配置,需要判断哪些参数仍适用。
20
+ - **调整产物结构**:从单文件切到分组、改客户端或语言、调整命名与契约拆分。
21
+
22
+ 不适用:日常生成、`--check`、CI 验收——这些直接跑既有脚本,不要为一次生成加载本技能。
23
+ 也不用于一般 TypeScript / axios 用法或接口文档写作。
24
+
25
+ ## 工作流
26
+
27
+ 1. **先判断是否真的需要**:只有配置形态要变时才读本技能;日常生成按项目里的既有命令执行即可。
28
+ 2. **定最小配置**:只写 `input`、`output`、`client`,其余按默认;需要分组、JS、响应类型或 query 提取时再逐项加。
29
+ 决策项与默认值见 `references/config.md`。
30
+ 3. **写入项目层**:配置落到仓库根 `swagger2api.json`(随仓库提交);个人差异写本地层,不入库。
31
+ 4. **先预览再落盘**:分组模式加 `--dry-run --json`,确认命名映射、桶与分片规划、预计新增文件;
32
+ 单文件模式可先 `--dry-run` 看报表。发现拆法不符合预期时改分组规则,不要生成后再手改。
33
+ 5. **生成**:用项目既有脚本或 `swagger2api`(本地安装后)执行;首次生成后确认产物目录与配置一致。
34
+ 6. **验收**:跑 `swagger2api --check` 确认产物与配置一致;再跑项目类型检查。产物结构与验收口径见 `references/output.md`。
35
+ 7. **记录边界**:生成物默认沿用 `// @ts-nocheck`,类型错误不进入下游检查;需要类型检查接管时配置 `typeCheck: "enforce"`,由工具统一剥离,不要手改生成物。
36
+
37
+ ## 不做
38
+
39
+ - 不手改生成物;需要去掉 `@ts-nocheck` 时用 `typeCheck: "enforce"` 由工具剥离,不要手删后提交。
40
+ - 不在日常生成、`--check` 或验收时加载本技能,避免把低频能力写成常驻流程。
41
+ - 不猜分桶 / 分片阈值:阈值属于工具默认,业务配置只决定分组策略与命名。
42
+ - 不把本机绝对路径、令牌或私网地址写进配置与示例。
43
+ - 不在未预览的情况下直接切换 `mode`,尤其是已有产物需要清理或迁移时。
44
+
45
+ ## 参考
46
+
47
+ - 配置决策:`references/config.md`
48
+ - CLI 参数与常用组合:`references/cli.md`
49
+ - 产物结构与验收:`references/output.md`
50
+ - 旧用法迁移:`references/migration.md`
51
+ - 定位本技能:`swagger2api skill`(入口路径)/ `swagger2api skill --print`(入口全文)/ `swagger2api skill --json`(结构化定位)
@@ -0,0 +1,40 @@
1
+ # CLI 参数
2
+
3
+ > 由 `../SKILL.md` 按需加载。可执行文件短名 `swagger2api`;npx / dlx 时用全名 `@fxri/swagger2api`。
4
+
5
+ ## 常用命令
6
+
7
+ ```bash
8
+ swagger2api # 按最近的 swagger2api.json 生成
9
+ swagger2api --target lc # 多目标配置下只生成指定目标
10
+ swagger2api --check # 生成到临时目录并与现有产物比对,不写真实目录
11
+ swagger2api init # 交互生成 swagger2api.json
12
+ swagger2api init --from-script package.json # 从既有 npm script 迁移参数
13
+ swagger2api grouping # 查看分组分布并写入分组配置
14
+ swagger2api config status # 查看配置分层与生效结果
15
+ swagger2api surface --out .swagger2api/surface.json # 写接口面基线
16
+ swagger2api surface --compare .swagger2api/surface.json # 与基线比对接口与类型增删
17
+ swagger2api skill # 输出包内技能入口绝对路径
18
+ swagger2api skill --print # 输出技能入口全文
19
+ swagger2api skill --json # 输出入口、references 目录与技能版本
20
+ ```
21
+
22
+ ## 生成相关开关
23
+
24
+ | 参数 | 作用 |
25
+ | --- | --- |
26
+ | `--modular` | 按组拆分为多文件并生成聚合入口 |
27
+ | `--dry-run` | 只输出报表,不写产物;分组模式给出命名、桶 / 分片规划与预计新增文件 |
28
+ | `--json` | 与 `--dry-run` 组合时输出结构化报表 |
29
+ | `--prune-output` | 按上一轮清单清理已消失模块,不触碰手写文件 |
30
+ | `--config <path>` | 显式指定项目层配置 |
31
+ | `--target <id>` | 多目标配置下只执行指定目标;未知目标退出码 2 |
32
+ | `--profile <name>` | 选用配置内的命名预设 |
33
+
34
+ ## 使用顺序
35
+
36
+ 1. 改配置后先 `--dry-run --json`,重点看命名映射、桶与分片规划、预计新增文件。
37
+ 2. 确认后生成;产物结构有变化时先清理旧产物或确认清单已覆盖。
38
+ 3. 最后用 `--check` 验收,不要在 `--check` 模式下期待写盘。
39
+
40
+ 完整参数与边界见仓库 `docs/cli.md`。
@@ -0,0 +1,59 @@
1
+ # 配置决策
2
+
3
+ > 由 `../SKILL.md` 按需加载。只列需要判断的字段;完整字段与层级规则见仓库 `docs/config.md`。
4
+
5
+ ## 最小配置
6
+
7
+ ```json
8
+ {
9
+ "input": { "url": "https://example.com/v3/api-docs" },
10
+ "output": { "dir": "./src/api", "name": "index" },
11
+ "client": { "type": "axios" }
12
+ }
13
+ ```
14
+
15
+ 本地文件用 `input.file`,相对路径按配置文件所在目录解析。
16
+
17
+ ## 决策项
18
+
19
+ | 字段 | 取值 | 什么时候改 |
20
+ | --- | --- | --- |
21
+ | `output.mode` | `single`(默认)/ `grouped` | 接口多、单文件过大时切 `grouped` |
22
+ | `client.type` | `fetch`(默认)/ `axios` | 项目已用 axios 或需要拦截器时选 `axios` |
23
+ | `language.target` | `ts`(默认)/ `js` | 产物要与现有 JS 代码共存时选 `js`(同时生成声明) |
24
+ | `output.typeCheck` | `skip`(默认)/ `enforce` | 需要项目类型检查覆盖生成物时选 `enforce`(工具剥离 `@ts-nocheck`) |
25
+ | `types.responses` | 布尔 | 需要响应类型信息时开启 |
26
+ | `types.extractQuery` | 字段名数组 | 后端把分页 / 筛选包在 query 对象里,需要提到根部时 |
27
+ | `types.extractResponseRaw` | 布尔 | 需要在响应里保留原始 `raw` 时 |
28
+ | `naming.pathPrefixIndex` | 非负整数 | 路径首段是网关前缀、不该进命名时去掉 |
29
+ | `naming.tagRewrite` | `[匹配, 替换]` | 标签带环境前缀或需要统一命名时 |
30
+
31
+ ## 多目标
32
+
33
+ 同一仓多个 Swagger 文档用一份配置,公共口径写 `defaults`:
34
+
35
+ ```json
36
+ {
37
+ "defaults": { "mode": "grouped", "client": "axios" },
38
+ "targets": [
39
+ { "id": "base", "url": "https://example.com/base/v3/api-docs", "output": "./src/api/base" },
40
+ { "id": "lc", "url": "https://example.com/lc/v3/api-docs", "output": "./src/api/lc" }
41
+ ]
42
+ }
43
+ ```
44
+
45
+ - `id` 唯一,`name` 仍是入口文件名;目标项覆盖 `defaults`
46
+ - 无参数跑全部,`--target <id>` 跑单个,`--check` 校验全部
47
+ - 输出目录相同或互相嵌套会被拒绝(退出码 2,不落盘);目标内相对路径按配置文件所在目录解析
48
+
49
+ ## 分层
50
+
51
+ - 项目层 `swagger2api.json`:随仓库提交,团队共用。
52
+ - 本地层:个人地址、令牌等放本地文件,加入忽略清单,不提交。
53
+ - 环境变量可覆盖地址等敏感项;优先级与字段映射见 `docs/config.md`。
54
+
55
+ ## 判断顺序
56
+
57
+ 1. 先确认输入地址可访问、返回 OpenAPI / Swagger 文档。
58
+ 2. 再定 `mode`:不确定时先用 `single` 生成,确认调用形态后再评估是否分组。
59
+ 3. 最后按需加 `language`、`types`、`naming`;每加一项都跑一次 `--dry-run` 对比报表。
@@ -0,0 +1,41 @@
1
+ # 旧用法迁移
2
+
3
+ > 由 `../SKILL.md` 按需加载。迁移只在首次接入或结构调整时做一次。
4
+
5
+ ## 从 npm script 迁移
6
+
7
+ ```bash
8
+ swagger2api init --from-script package.json
9
+ ```
10
+
11
+ - 读取 `package.json` 里调用本工具的脚本,把可识别的参数转成配置。
12
+ - 未能识别的参数会在 stderr 列出,逐项确认后再手工补进 `swagger2api.json`。
13
+ - 有未识别参数时退出码非 0;补完后重跑一次直到干净。
14
+
15
+ ## 从 saconfig.json 迁移
16
+
17
+ - 新项目优先用分层 `swagger2api.json`;旧的 `saconfig.json` 仍兼容,但不再承载分组与清理能力。
18
+ - 迁移时只搬实际生效的字段,不照抄整份旧配置。
19
+ - 路径、输出目录与名字按新项目重定;旧项目的绝对路径不要带过来。
20
+
21
+ ## 跨版本迁移比对
22
+
23
+ 迁移工具版本或产物结构前,先固定接口面基线:
24
+
25
+ ```bash
26
+ swagger2api surface --out .swagger2api/surface.json
27
+ # 迁移后
28
+ swagger2api surface --compare .swagger2api/surface.json
29
+ ```
30
+
31
+ - 从产物目录的 `.ts` / `.d.ts` / `.js` 提取 `@request`、`@name` 与导出类型,结果带 `formatVersion`,默认不提交
32
+ - 比对一致退出 0;有增删逐条输出 `+` / `-` 并非 0 退出;`--requests-only` 只锁接口集合,忽略方法名与类型名
33
+ - 多目标配置按 `id` 分组比对,目标新增 / 缺失同样报错;`--target <id>` 只处理单个目标
34
+ - 基线建议放 `.swagger2api/` 并加入忽略清单;需要长期回归时由 CI 生成后临时比对
35
+
36
+ ## 迁移后的验收
37
+
38
+ 1. `--dry-run --json` 对比迁移前后的命名与预计文件。
39
+ 2. 生成一次,确认产物结构与旧产物差异符合预期。
40
+ 3. `--check` 通过后删除旧配置文件与旧产物;不要把两套配置同时留在仓库。
41
+ 4. 更新项目脚本与文档中的命令;后续日常生成不再需要加载本技能。
@@ -0,0 +1,32 @@
1
+ # 产物结构与验收
2
+
3
+ > 由 `../SKILL.md` 按需加载。产物由工具生成,不手改。
4
+
5
+ ## 单文件模式
6
+
7
+ - 入口文件 `index.ts`(名称取 `output.name`),导出 API 类与全部契约。
8
+ - 客户端实例与请求参数类型由生成器内置,调用形态为 `api.<方法>()`。
9
+
10
+ ## 分组模式
11
+
12
+ 固定产物:
13
+
14
+ - `index.ts`:聚合入口,按命名空间挂载模块实例,共享同一个请求实例。
15
+ - `client.ts`:客户端底座。
16
+ - `types/index.ts`:契约出口;契约按业务文件拆到 `types/<业务文件>.ts`,共享或未归类进 `types/shared.ts`。
17
+ - 业务模块文件:按命名空间装箱;超大命名空间按子分类分片,由门面类合并实例与类型。
18
+
19
+ 调用形态仍为 `api.<命名空间>.<方法>`;替换 `api.instance` 或调用 `setSecurityData` 会对所有组生效。
20
+
21
+ ## 边界
22
+
23
+ - 生成物默认沿用 `// @ts-nocheck`:类型错误不进入下游检查,不要靠手改生成物修类型;需要类型检查接管时配置 `typeCheck: "enforce"`,由工具统一剥离该行,`--check` 走同一处理。
24
+ - 生成清单落在系统临时目录,不进入仓库;`--check` 据此判断缺失、多出与内容不一致。
25
+ - 旧版 `data-contracts.ts` / `http-client.ts` 不再生成,重新生成成功后会清理残留。
26
+ - 手写文件不在清单内时不会被清理;同名冲突会终止生成并提示。
27
+
28
+ ## 验收
29
+
30
+ 1. `swagger2api --check` 通过(产物与配置一致)。
31
+ 2. 项目类型检查通过;未开启 `typeCheck: "enforce"` 时需要更强约束就在项目侧写类型探针,不改生成物。
32
+ 3. 抽查聚合入口:模块挂载、`export * from "./types"`、`export * from "./client"` 均存在。