@dazhicheng/openapi 1.0.0
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/openapi.config.ts +16 -0
- package/package.json +26 -0
- package/src/cli.ts +108 -0
- package/src/discovery.ts +44 -0
- package/src/fetcher.ts +19 -0
- package/src/formatter.ts +16 -0
- package/src/generator.ts +187 -0
- package/src/parser.ts +336 -0
- package/src/types.ts +91 -0
- package/tsconfig.json +13 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { OpenAPIConfig } from "./src/types";
|
|
2
|
+
|
|
3
|
+
const config: OpenAPIConfig = {
|
|
4
|
+
outputDir: "./generated",
|
|
5
|
+
|
|
6
|
+
/** 网关地址,自动发现所有微服务的 OpenAPI 文档 */
|
|
7
|
+
gateway: "http://192.168.129.178:11000",
|
|
8
|
+
|
|
9
|
+
/** 请求函数的导入路径,生成的接口会 import request from 此路径 */
|
|
10
|
+
requestImportPath: "@dazhicheng/utils",
|
|
11
|
+
|
|
12
|
+
/** 请求函数名称 */
|
|
13
|
+
requestFnName: "request",
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export default config;
|
package/package.json
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@dazhicheng/openapi",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "根据 Swagger/OpenAPI 文档自动生成 TypeScript 接口",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"openapi",
|
|
8
|
+
"swagger",
|
|
9
|
+
"codegen",
|
|
10
|
+
"typescript"
|
|
11
|
+
],
|
|
12
|
+
"author": "",
|
|
13
|
+
"license": "ISC",
|
|
14
|
+
"devDependencies": {
|
|
15
|
+
"@types/node": "^24.5.2",
|
|
16
|
+
"typescript": "^5.9.2"
|
|
17
|
+
},
|
|
18
|
+
"paths": {},
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"tsx": "^4.19.4",
|
|
21
|
+
"prettier": "^3.6.2"
|
|
22
|
+
},
|
|
23
|
+
"scripts": {
|
|
24
|
+
"generate": "tsx src/cli.ts"
|
|
25
|
+
}
|
|
26
|
+
}
|
package/src/cli.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { resolve, dirname } from "node:path";
|
|
3
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
4
|
+
import type { OpenAPIConfig, ServiceConfig } from "./types";
|
|
5
|
+
import { fetchSwaggerDoc } from "./fetcher";
|
|
6
|
+
import { parseSwaggerDoc } from "./parser";
|
|
7
|
+
import { generateServiceFile } from "./generator";
|
|
8
|
+
import { formatTypeScript } from "./formatter";
|
|
9
|
+
import { discoverServices } from "./discovery";
|
|
10
|
+
|
|
11
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
12
|
+
const __dirname = dirname(__filename);
|
|
13
|
+
const ROOT = resolve(__dirname, "..");
|
|
14
|
+
|
|
15
|
+
async function loadConfig(): Promise<OpenAPIConfig> {
|
|
16
|
+
const configPath = resolve(ROOT, "openapi.config.ts");
|
|
17
|
+
const configUrl = pathToFileURL(configPath).href;
|
|
18
|
+
const mod = await import(configUrl);
|
|
19
|
+
return mod.default as OpenAPIConfig;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function main() {
|
|
23
|
+
console.log("🚀 开始生成 OpenAPI TypeScript 接口...\n");
|
|
24
|
+
|
|
25
|
+
const config = await loadConfig();
|
|
26
|
+
const { outputDir, requestImportPath, requestFnName = "request" } = config;
|
|
27
|
+
|
|
28
|
+
let services: ServiceConfig[];
|
|
29
|
+
|
|
30
|
+
if (config.gateway) {
|
|
31
|
+
console.log(`🔍 正在从网关自动发现服务: ${config.gateway}`);
|
|
32
|
+
services = await discoverServices(config.gateway);
|
|
33
|
+
console.log(` 发现 ${services.length} 个服务\n`);
|
|
34
|
+
} else if (config.services && config.services.length > 0) {
|
|
35
|
+
services = config.services;
|
|
36
|
+
} else {
|
|
37
|
+
console.warn("⚠️ 未配置任何 service 或 gateway,请编辑 openapi.config.ts");
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const outDir = resolve(ROOT, outputDir);
|
|
42
|
+
if (!existsSync(outDir)) {
|
|
43
|
+
mkdirSync(outDir, { recursive: true });
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
let successCount = 0;
|
|
47
|
+
let failCount = 0;
|
|
48
|
+
const generatedNames: string[] = [];
|
|
49
|
+
|
|
50
|
+
for (const service of services) {
|
|
51
|
+
try {
|
|
52
|
+
console.log(`📡 [${service.name}] 获取文档: ${service.url}`);
|
|
53
|
+
const doc = await fetchSwaggerDoc(service.url);
|
|
54
|
+
|
|
55
|
+
console.log(`🔍 [${service.name}] 解析中...`);
|
|
56
|
+
const parsed = parseSwaggerDoc(doc, {
|
|
57
|
+
pathPrefix: service.pathPrefix,
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
console.log(` ├─ ${parsed.interfaces.length} 个类型定义`);
|
|
61
|
+
console.log(` └─ ${parsed.apis.length} 个 API 接口`);
|
|
62
|
+
|
|
63
|
+
const code = generateServiceFile(parsed, {
|
|
64
|
+
requestImportPath,
|
|
65
|
+
requestFnName,
|
|
66
|
+
serviceName: service.name,
|
|
67
|
+
serviceDescription: service.description,
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
const formatted = await formatTypeScript(code);
|
|
71
|
+
|
|
72
|
+
const outFile = resolve(outDir, `${service.name}.ts`);
|
|
73
|
+
writeFileSync(outFile, formatted, "utf-8");
|
|
74
|
+
console.log(`✅ [${service.name}] -> ${outFile}\n`);
|
|
75
|
+
successCount++;
|
|
76
|
+
generatedNames.push(service.name);
|
|
77
|
+
} catch (err) {
|
|
78
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
79
|
+
console.error(`❌ [${service.name}] 失败: ${msg}\n`);
|
|
80
|
+
failCount++;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (generatedNames.length > 0) {
|
|
85
|
+
generateIndexFile(outDir, generatedNames);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
console.log("━".repeat(50));
|
|
89
|
+
console.log(`🎉 生成完毕! 成功: ${successCount}, 失败: ${failCount}`);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function generateIndexFile(outDir: string, serviceNames: string[]) {
|
|
93
|
+
const lines = ["// 此文件由 @dazhicheng/openapi 自动生成,请勿手动修改", ""];
|
|
94
|
+
|
|
95
|
+
for (const name of serviceNames) {
|
|
96
|
+
lines.push(`export * from './${name}';`);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
lines.push("");
|
|
100
|
+
|
|
101
|
+
const indexFile = resolve(outDir, "index.ts");
|
|
102
|
+
writeFileSync(indexFile, lines.join("\n"), "utf-8");
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
main().catch(err => {
|
|
106
|
+
console.error("生成过程发生错误:", err);
|
|
107
|
+
process.exit(1);
|
|
108
|
+
});
|
package/src/discovery.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { ServiceConfig } from "./types";
|
|
2
|
+
|
|
3
|
+
interface SwaggerConfigUrl {
|
|
4
|
+
name: string;
|
|
5
|
+
url: string;
|
|
6
|
+
contextPath?: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
interface SwaggerConfig {
|
|
10
|
+
urls: SwaggerConfigUrl[];
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* 从 Knife4j / SpringDoc 网关自动发现所有微服务的 OpenAPI 文档地址
|
|
15
|
+
*/
|
|
16
|
+
export async function discoverServices(baseUrl: string): Promise<ServiceConfig[]> {
|
|
17
|
+
const configUrl = `${baseUrl}/v3/api-docs/swagger-config`;
|
|
18
|
+
|
|
19
|
+
const response = await fetch(configUrl, {
|
|
20
|
+
headers: { Accept: "application/json" },
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
if (!response.ok) {
|
|
24
|
+
throw new Error(`获取 swagger-config 失败: ${configUrl} (HTTP ${response.status})`);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const config = (await response.json()) as SwaggerConfig;
|
|
28
|
+
|
|
29
|
+
if (!config.urls || config.urls.length === 0) {
|
|
30
|
+
throw new Error("swagger-config 中未发现任何服务");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
return config.urls.map(item => {
|
|
34
|
+
const pathSegments = item.url.split("/").filter(Boolean);
|
|
35
|
+
const serviceName = pathSegments[0] || item.name;
|
|
36
|
+
|
|
37
|
+
return {
|
|
38
|
+
name: serviceName,
|
|
39
|
+
url: `${baseUrl}${item.url}`,
|
|
40
|
+
description: item.name,
|
|
41
|
+
pathPrefix: item.contextPath || `/${serviceName}`,
|
|
42
|
+
};
|
|
43
|
+
});
|
|
44
|
+
}
|
package/src/fetcher.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { SwaggerDoc } from "./types";
|
|
2
|
+
|
|
3
|
+
export async function fetchSwaggerDoc(url: string): Promise<SwaggerDoc> {
|
|
4
|
+
const response = await fetch(url, {
|
|
5
|
+
headers: { Accept: "application/json" },
|
|
6
|
+
});
|
|
7
|
+
|
|
8
|
+
if (!response.ok) {
|
|
9
|
+
throw new Error(`获取 Swagger 文档失败: ${url} (HTTP ${response.status})`);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const doc = (await response.json()) as SwaggerDoc;
|
|
13
|
+
|
|
14
|
+
if (!doc.paths) {
|
|
15
|
+
throw new Error(`无效的 Swagger 文档 (缺少 paths): ${url}`);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
return doc;
|
|
19
|
+
}
|
package/src/formatter.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import prettier from "prettier";
|
|
2
|
+
|
|
3
|
+
export async function formatTypeScript(code: string): Promise<string> {
|
|
4
|
+
try {
|
|
5
|
+
return await prettier.format(code, {
|
|
6
|
+
parser: "typescript",
|
|
7
|
+
semi: true,
|
|
8
|
+
singleQuote: true,
|
|
9
|
+
trailingComma: "all",
|
|
10
|
+
printWidth: 100,
|
|
11
|
+
tabWidth: 2,
|
|
12
|
+
});
|
|
13
|
+
} catch {
|
|
14
|
+
return code;
|
|
15
|
+
}
|
|
16
|
+
}
|
package/src/generator.ts
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import type { ParseResult, ParsedAPI, ParsedInterface, ParsedProperty } from "./parser";
|
|
2
|
+
|
|
3
|
+
export interface GeneratorOptions {
|
|
4
|
+
requestImportPath: string;
|
|
5
|
+
requestFnName: string;
|
|
6
|
+
serviceName: string;
|
|
7
|
+
serviceDescription?: string;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function generateServiceFile(result: ParseResult, options: GeneratorOptions): string {
|
|
11
|
+
const lines: string[] = [];
|
|
12
|
+
const { requestImportPath, requestFnName } = options;
|
|
13
|
+
|
|
14
|
+
lines.push(`// 此文件由 @dazhicheng/openapi 自动生成,请勿手动修改`);
|
|
15
|
+
lines.push(`// 服务: ${options.serviceDescription || options.serviceName}`);
|
|
16
|
+
lines.push(`// 生成时间: ${new Date().toISOString()}`);
|
|
17
|
+
lines.push("");
|
|
18
|
+
lines.push(`import ${requestFnName} from '${requestImportPath}';`);
|
|
19
|
+
lines.push("");
|
|
20
|
+
|
|
21
|
+
lines.push("// ======================== 类型定义 ========================");
|
|
22
|
+
lines.push("");
|
|
23
|
+
|
|
24
|
+
for (const iface of result.interfaces) {
|
|
25
|
+
lines.push(generateInterface(iface));
|
|
26
|
+
lines.push("");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const apisByTag = groupApisByTag(result.apis, result.tags);
|
|
30
|
+
|
|
31
|
+
lines.push("// ======================== 接口方法 ========================");
|
|
32
|
+
lines.push("");
|
|
33
|
+
|
|
34
|
+
for (const [tagName, tagApis] of Object.entries(apisByTag)) {
|
|
35
|
+
const tagInfo = result.tags.find(t => t.name === tagName);
|
|
36
|
+
if (tagInfo?.description) {
|
|
37
|
+
lines.push(`// ---------- ${tagInfo.description} ----------`);
|
|
38
|
+
} else if (tagName !== "__ungrouped__") {
|
|
39
|
+
lines.push(`// ---------- ${tagName} ----------`);
|
|
40
|
+
}
|
|
41
|
+
lines.push("");
|
|
42
|
+
|
|
43
|
+
for (const api of tagApis) {
|
|
44
|
+
lines.push(generateApiFunction(api, requestFnName));
|
|
45
|
+
lines.push("");
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return lines.join("\n");
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function generateInterface(iface: ParsedInterface): string {
|
|
53
|
+
const lines: string[] = [];
|
|
54
|
+
|
|
55
|
+
if (iface.description) {
|
|
56
|
+
lines.push(`/** ${iface.description} */`);
|
|
57
|
+
}
|
|
58
|
+
lines.push(`export interface ${iface.name} {`);
|
|
59
|
+
|
|
60
|
+
for (const prop of iface.properties) {
|
|
61
|
+
if (prop.description) {
|
|
62
|
+
lines.push(` /** ${prop.description} */`);
|
|
63
|
+
}
|
|
64
|
+
const optional = prop.required ? "" : "?";
|
|
65
|
+
const safeName = isValidIdentifier(prop.name) ? prop.name : `'${prop.name}'`;
|
|
66
|
+
lines.push(` ${safeName}${optional}: ${prop.type};`);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
lines.push("}");
|
|
70
|
+
return lines.join("\n");
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function generateApiFunction(api: ParsedAPI, requestFnName: string): string {
|
|
74
|
+
const lines: string[] = [];
|
|
75
|
+
|
|
76
|
+
const jsdocLines: string[] = [];
|
|
77
|
+
if (api.summary || api.description) {
|
|
78
|
+
jsdocLines.push(api.summary || api.description || "");
|
|
79
|
+
}
|
|
80
|
+
if (api.deprecated) {
|
|
81
|
+
jsdocLines.push("@deprecated");
|
|
82
|
+
}
|
|
83
|
+
if (api.description && api.summary && api.description !== api.summary) {
|
|
84
|
+
jsdocLines.push(`@description ${api.description}`);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (jsdocLines.length > 0) {
|
|
88
|
+
lines.push("/**");
|
|
89
|
+
for (const line of jsdocLines) {
|
|
90
|
+
lines.push(` * ${line}`);
|
|
91
|
+
}
|
|
92
|
+
lines.push(" */");
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const params = buildFunctionParams(api);
|
|
96
|
+
const genericType = api.responseType !== "void" ? `<${api.responseType}>` : "";
|
|
97
|
+
const fnSignature = `export function ${api.name}(${params})`;
|
|
98
|
+
|
|
99
|
+
const urlExpr = buildUrlExpression(api.path, api.pathParams);
|
|
100
|
+
const requestConfig = buildRequestConfig(api);
|
|
101
|
+
|
|
102
|
+
lines.push(`${fnSignature} {`);
|
|
103
|
+
lines.push(` return ${requestFnName}${genericType}({`);
|
|
104
|
+
lines.push(` url: ${urlExpr},`);
|
|
105
|
+
lines.push(` method: '${api.method}',`);
|
|
106
|
+
if (requestConfig) {
|
|
107
|
+
lines.push(requestConfig);
|
|
108
|
+
}
|
|
109
|
+
lines.push(" });");
|
|
110
|
+
lines.push("}");
|
|
111
|
+
|
|
112
|
+
return lines.join("\n");
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function buildFunctionParams(api: ParsedAPI): string {
|
|
116
|
+
const params: string[] = [];
|
|
117
|
+
|
|
118
|
+
for (const p of api.pathParams) {
|
|
119
|
+
params.push(`${p.name}: ${p.type}`);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
if (api.queryParams.length > 0) {
|
|
123
|
+
const paramTypeParts = api.queryParams.map(p => {
|
|
124
|
+
const optional = p.required ? "" : "?";
|
|
125
|
+
return `${p.name}${optional}: ${p.type}`;
|
|
126
|
+
});
|
|
127
|
+
const allOptional = api.queryParams.every(p => !p.required);
|
|
128
|
+
params.push(`params${allOptional ? "?" : ""}: { ${paramTypeParts.join("; ")} }`);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (api.bodyType) {
|
|
132
|
+
const bodyOptional = api.bodyRequired === false ? "?" : "";
|
|
133
|
+
params.push(`data${bodyOptional}: ${api.bodyType}`);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return params.join(", ");
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function buildUrlExpression(path: string, pathParams: ParsedProperty[]): string {
|
|
140
|
+
if (pathParams.length === 0) {
|
|
141
|
+
return `'${path}'`;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const templatePath = path.replace(/\{(\w+)\}/g, (_match, name) => {
|
|
145
|
+
return `\${${name}}`;
|
|
146
|
+
});
|
|
147
|
+
return "`" + templatePath + "`";
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function buildRequestConfig(api: ParsedAPI): string | undefined {
|
|
151
|
+
const parts: string[] = [];
|
|
152
|
+
|
|
153
|
+
if (api.queryParams.length > 0) {
|
|
154
|
+
parts.push(" params,");
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
if (api.bodyType) {
|
|
158
|
+
parts.push(" data,");
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (api.hasFormData) {
|
|
162
|
+
parts.push(" headers: { 'Content-Type': 'multipart/form-data' },");
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
return parts.length > 0 ? parts.join("\n") : undefined;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function groupApisByTag(
|
|
169
|
+
apis: ParsedAPI[],
|
|
170
|
+
_tags: Array<{ name: string; description?: string }>,
|
|
171
|
+
): Record<string, ParsedAPI[]> {
|
|
172
|
+
const grouped: Record<string, ParsedAPI[]> = {};
|
|
173
|
+
|
|
174
|
+
for (const api of apis) {
|
|
175
|
+
const tag = api.tag || "__ungrouped__";
|
|
176
|
+
if (!grouped[tag]) {
|
|
177
|
+
grouped[tag] = [];
|
|
178
|
+
}
|
|
179
|
+
grouped[tag].push(api);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
return grouped;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function isValidIdentifier(name: string): boolean {
|
|
186
|
+
return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
|
|
187
|
+
}
|
package/src/parser.ts
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
import type { OperationObject, ParameterObject, SchemaObject, SwaggerDoc } from "./types";
|
|
2
|
+
|
|
3
|
+
export interface ParsedInterface {
|
|
4
|
+
name: string;
|
|
5
|
+
description?: string;
|
|
6
|
+
properties: ParsedProperty[];
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface ParsedProperty {
|
|
10
|
+
name: string;
|
|
11
|
+
type: string;
|
|
12
|
+
required: boolean;
|
|
13
|
+
description?: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface ParsedAPI {
|
|
17
|
+
path: string;
|
|
18
|
+
method: string;
|
|
19
|
+
name: string;
|
|
20
|
+
summary?: string;
|
|
21
|
+
description?: string;
|
|
22
|
+
deprecated?: boolean;
|
|
23
|
+
tag?: string;
|
|
24
|
+
pathParams: ParsedProperty[];
|
|
25
|
+
queryParams: ParsedProperty[];
|
|
26
|
+
bodyType?: string;
|
|
27
|
+
bodyRequired?: boolean;
|
|
28
|
+
responseType: string;
|
|
29
|
+
hasFormData?: boolean;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ParseResult {
|
|
33
|
+
interfaces: ParsedInterface[];
|
|
34
|
+
apis: ParsedAPI[];
|
|
35
|
+
tags: Array<{ name: string; description?: string }>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface ParseOptions {
|
|
39
|
+
/** 路径前缀,拼接到每个 API 路径前面 */
|
|
40
|
+
pathPrefix?: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function parseSwaggerDoc(doc: SwaggerDoc, options?: ParseOptions): ParseResult {
|
|
44
|
+
const isV3 = !!doc.openapi;
|
|
45
|
+
const definitions = isV3 ? doc.components?.schemas : doc.definitions;
|
|
46
|
+
const interfaces: ParsedInterface[] = [];
|
|
47
|
+
const apis: ParsedAPI[] = [];
|
|
48
|
+
const prefix = options?.pathPrefix ?? "";
|
|
49
|
+
|
|
50
|
+
if (definitions) {
|
|
51
|
+
for (const [rawName, schema] of Object.entries(definitions)) {
|
|
52
|
+
const name = sanitizeTypeName(rawName);
|
|
53
|
+
interfaces.push({
|
|
54
|
+
name,
|
|
55
|
+
description: schema.description || schema.title,
|
|
56
|
+
properties: parseSchemaProperties(schema, definitions),
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
for (const [path, pathItem] of Object.entries(doc.paths)) {
|
|
62
|
+
const methods = ["get", "post", "put", "delete", "patch"] as const;
|
|
63
|
+
|
|
64
|
+
for (const method of methods) {
|
|
65
|
+
const operation = pathItem[method] as OperationObject | undefined;
|
|
66
|
+
if (!operation) continue;
|
|
67
|
+
|
|
68
|
+
const fullPath = prefix ? `${prefix}${path}` : path;
|
|
69
|
+
const api = parseOperation(fullPath, method, operation, definitions || {}, isV3);
|
|
70
|
+
apis.push(api);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return {
|
|
75
|
+
interfaces,
|
|
76
|
+
apis,
|
|
77
|
+
tags: doc.tags || [],
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function parseOperation(
|
|
82
|
+
path: string,
|
|
83
|
+
method: string,
|
|
84
|
+
op: OperationObject,
|
|
85
|
+
definitions: Record<string, SchemaObject>,
|
|
86
|
+
isV3: boolean,
|
|
87
|
+
): ParsedAPI {
|
|
88
|
+
const pathParams: ParsedProperty[] = [];
|
|
89
|
+
const queryParams: ParsedProperty[] = [];
|
|
90
|
+
let bodyType: string | undefined;
|
|
91
|
+
let bodyRequired: boolean | undefined;
|
|
92
|
+
let hasFormData = false;
|
|
93
|
+
|
|
94
|
+
if (op.parameters) {
|
|
95
|
+
for (const param of op.parameters) {
|
|
96
|
+
const prop = paramToProperty(param, definitions);
|
|
97
|
+
switch (param.in) {
|
|
98
|
+
case "path":
|
|
99
|
+
pathParams.push(prop);
|
|
100
|
+
break;
|
|
101
|
+
case "query":
|
|
102
|
+
queryParams.push(prop);
|
|
103
|
+
break;
|
|
104
|
+
case "body":
|
|
105
|
+
bodyType = resolveSchemaType(param.schema, definitions);
|
|
106
|
+
bodyRequired = param.required;
|
|
107
|
+
break;
|
|
108
|
+
case "formData":
|
|
109
|
+
hasFormData = true;
|
|
110
|
+
queryParams.push(prop);
|
|
111
|
+
break;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (isV3 && op.requestBody) {
|
|
117
|
+
const content = op.requestBody.content;
|
|
118
|
+
const mediaType = content?.["application/json"] || content?.["multipart/form-data"];
|
|
119
|
+
if (mediaType?.schema) {
|
|
120
|
+
bodyType = resolveSchemaType(mediaType.schema, definitions);
|
|
121
|
+
bodyRequired = op.requestBody.required;
|
|
122
|
+
if (content?.["multipart/form-data"]) hasFormData = true;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const responseType = resolveResponseType(op, definitions, isV3);
|
|
127
|
+
|
|
128
|
+
const fnName = generateFunctionName(op.operationId, method, path);
|
|
129
|
+
|
|
130
|
+
return {
|
|
131
|
+
path,
|
|
132
|
+
method: method.toUpperCase(),
|
|
133
|
+
name: fnName,
|
|
134
|
+
summary: op.summary,
|
|
135
|
+
description: op.description,
|
|
136
|
+
deprecated: op.deprecated,
|
|
137
|
+
tag: op.tags?.[0],
|
|
138
|
+
pathParams,
|
|
139
|
+
queryParams,
|
|
140
|
+
bodyType,
|
|
141
|
+
bodyRequired,
|
|
142
|
+
responseType,
|
|
143
|
+
hasFormData,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function paramToProperty(param: ParameterObject, definitions: Record<string, SchemaObject>): ParsedProperty {
|
|
148
|
+
let type: string;
|
|
149
|
+
if (param.schema) {
|
|
150
|
+
type = resolveSchemaType(param.schema, definitions);
|
|
151
|
+
} else {
|
|
152
|
+
type = mapSwaggerType(param.type, param.format, param.items, definitions);
|
|
153
|
+
}
|
|
154
|
+
if (param.enum) {
|
|
155
|
+
type = param.enum.map(v => (typeof v === "string" ? `'${v}'` : v)).join(" | ");
|
|
156
|
+
}
|
|
157
|
+
return {
|
|
158
|
+
name: param.name,
|
|
159
|
+
type,
|
|
160
|
+
required: param.required ?? false,
|
|
161
|
+
description: param.description,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function resolveResponseType(op: OperationObject, definitions: Record<string, SchemaObject>, isV3: boolean): string {
|
|
166
|
+
const resp = op.responses?.["200"] || op.responses?.["201"];
|
|
167
|
+
if (!resp) return "void";
|
|
168
|
+
|
|
169
|
+
if (isV3) {
|
|
170
|
+
const content = resp.content;
|
|
171
|
+
const mediaType = content?.["application/json"] || content?.["*/*"];
|
|
172
|
+
if (mediaType?.schema) {
|
|
173
|
+
return resolveSchemaType(mediaType.schema, definitions);
|
|
174
|
+
}
|
|
175
|
+
return "void";
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (resp.schema) {
|
|
179
|
+
return resolveSchemaType(resp.schema, definitions);
|
|
180
|
+
}
|
|
181
|
+
return "void";
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function resolveSchemaType(schema: SchemaObject | undefined, definitions: Record<string, SchemaObject>): string {
|
|
185
|
+
if (!schema) return "any";
|
|
186
|
+
|
|
187
|
+
if (schema.$ref) {
|
|
188
|
+
return sanitizeTypeName(extractRefName(schema.$ref));
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (schema.originalRef) {
|
|
192
|
+
return sanitizeTypeName(schema.originalRef);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (schema.allOf) {
|
|
196
|
+
const types = schema.allOf.map(s => resolveSchemaType(s, definitions));
|
|
197
|
+
return types.join(" & ");
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
if (schema.oneOf || schema.anyOf) {
|
|
201
|
+
const arr = schema.oneOf || schema.anyOf!;
|
|
202
|
+
const types = arr.map(s => resolveSchemaType(s, definitions));
|
|
203
|
+
return types.join(" | ");
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
if (schema.enum) {
|
|
207
|
+
return schema.enum.map(v => (typeof v === "string" ? `'${v}'` : v)).join(" | ");
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return mapSwaggerType(schema.type, schema.format, schema.items, definitions);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function mapSwaggerType(
|
|
214
|
+
type?: string,
|
|
215
|
+
format?: string,
|
|
216
|
+
items?: SchemaObject,
|
|
217
|
+
definitions?: Record<string, SchemaObject>,
|
|
218
|
+
): string {
|
|
219
|
+
switch (type) {
|
|
220
|
+
case "integer":
|
|
221
|
+
case "number":
|
|
222
|
+
case "float":
|
|
223
|
+
case "double":
|
|
224
|
+
return "number";
|
|
225
|
+
case "string":
|
|
226
|
+
if (format === "binary") return "File";
|
|
227
|
+
return "string";
|
|
228
|
+
case "boolean":
|
|
229
|
+
return "boolean";
|
|
230
|
+
case "array":
|
|
231
|
+
if (items) {
|
|
232
|
+
const itemType = resolveSchemaType(items, definitions || {});
|
|
233
|
+
return `${itemType}[]`;
|
|
234
|
+
}
|
|
235
|
+
return "any[]";
|
|
236
|
+
case "object":
|
|
237
|
+
return "Record<string, any>";
|
|
238
|
+
case "file":
|
|
239
|
+
return "File";
|
|
240
|
+
default:
|
|
241
|
+
return "any";
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function parseSchemaProperties(schema: SchemaObject, definitions: Record<string, SchemaObject>): ParsedProperty[] {
|
|
246
|
+
const props: ParsedProperty[] = [];
|
|
247
|
+
const requiredSet = new Set(schema.required || []);
|
|
248
|
+
|
|
249
|
+
const allProperties: Record<string, SchemaObject> = {};
|
|
250
|
+
|
|
251
|
+
if (schema.allOf) {
|
|
252
|
+
for (const sub of schema.allOf) {
|
|
253
|
+
if (sub.$ref) {
|
|
254
|
+
const refName = extractRefName(sub.$ref);
|
|
255
|
+
const refSchema = definitions[refName];
|
|
256
|
+
if (refSchema?.properties) {
|
|
257
|
+
Object.assign(allProperties, refSchema.properties);
|
|
258
|
+
if (refSchema.required) {
|
|
259
|
+
refSchema.required.forEach(r => requiredSet.add(r));
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
if (sub.properties) {
|
|
264
|
+
Object.assign(allProperties, sub.properties);
|
|
265
|
+
if (sub.required) {
|
|
266
|
+
sub.required.forEach(r => requiredSet.add(r));
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
if (schema.properties) {
|
|
273
|
+
Object.assign(allProperties, schema.properties);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
for (const [name, propSchema] of Object.entries(allProperties)) {
|
|
277
|
+
let type = resolveSchemaType(propSchema, definitions);
|
|
278
|
+
if (propSchema.enum) {
|
|
279
|
+
type = propSchema.enum.map(v => (typeof v === "string" ? `'${v}'` : v)).join(" | ");
|
|
280
|
+
}
|
|
281
|
+
props.push({
|
|
282
|
+
name,
|
|
283
|
+
type,
|
|
284
|
+
required: requiredSet.has(name),
|
|
285
|
+
description: propSchema.description,
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
return props;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function extractRefName(ref: string): string {
|
|
293
|
+
const parts = ref.split("/");
|
|
294
|
+
return parts[parts.length - 1]!;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** 移除泛型符号等不合法 TS 标识符字符 */
|
|
298
|
+
export function sanitizeTypeName(name: string): string {
|
|
299
|
+
return name
|
|
300
|
+
.replace(/«/g, "_")
|
|
301
|
+
.replace(/»/g, "")
|
|
302
|
+
.replace(/[<>]/g, "_")
|
|
303
|
+
.replace(/[,\s]/g, "_")
|
|
304
|
+
.replace(/[^a-zA-Z0-9_$]/g, "")
|
|
305
|
+
.replace(/_+/g, "_")
|
|
306
|
+
.replace(/_$/, "");
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function generateFunctionName(operationId: string | undefined, method: string, path: string): string {
|
|
310
|
+
if (operationId) {
|
|
311
|
+
return sanitizeFnName(operationId);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const segments = path
|
|
315
|
+
.split("/")
|
|
316
|
+
.filter(Boolean)
|
|
317
|
+
.map(seg => {
|
|
318
|
+
if (seg.startsWith("{") && seg.endsWith("}")) {
|
|
319
|
+
return "By" + capitalize(seg.slice(1, -1));
|
|
320
|
+
}
|
|
321
|
+
return capitalize(seg);
|
|
322
|
+
});
|
|
323
|
+
|
|
324
|
+
return method.toLowerCase() + segments.join("");
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function sanitizeFnName(name: string): string {
|
|
328
|
+
return name
|
|
329
|
+
.replace(/[^a-zA-Z0-9_$]/g, "_")
|
|
330
|
+
.replace(/^(\d)/, "_$1")
|
|
331
|
+
.replace(/Using(GET|POST|PUT|DELETE|PATCH)(_\d+)?$/, "");
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function capitalize(str: string): string {
|
|
335
|
+
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
336
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
export interface ServiceConfig {
|
|
2
|
+
/** 服务名称,用于生成文件名 (如 'user' -> user.ts) */
|
|
3
|
+
name: string;
|
|
4
|
+
/** Swagger/OpenAPI 文档地址 */
|
|
5
|
+
url: string;
|
|
6
|
+
/** 服务描述 */
|
|
7
|
+
description?: string;
|
|
8
|
+
/** 路径前缀,会拼接到每个 API 路径前面(如 '/iam') */
|
|
9
|
+
pathPrefix?: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface OpenAPIConfig {
|
|
13
|
+
/** 生成文件输出目录 (相对于 packages/openapi) */
|
|
14
|
+
outputDir: string;
|
|
15
|
+
/** 服务列表(手动配置,与 gateway 二选一) */
|
|
16
|
+
services?: ServiceConfig[];
|
|
17
|
+
/** 网关地址,自动发现所有微服务文档(与 services 二选一) */
|
|
18
|
+
gateway?: string;
|
|
19
|
+
/** 请求函数的导入路径 */
|
|
20
|
+
requestImportPath: string;
|
|
21
|
+
/** 请求函数名称 */
|
|
22
|
+
requestFnName?: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// ---- Swagger / OpenAPI 文档解析相关类型 ----
|
|
26
|
+
|
|
27
|
+
export interface SwaggerDoc {
|
|
28
|
+
swagger?: string;
|
|
29
|
+
openapi?: string;
|
|
30
|
+
info?: { title?: string; version?: string };
|
|
31
|
+
basePath?: string;
|
|
32
|
+
paths: Record<string, PathItem>;
|
|
33
|
+
definitions?: Record<string, SchemaObject>;
|
|
34
|
+
components?: { schemas?: Record<string, SchemaObject> };
|
|
35
|
+
tags?: Array<{ name: string; description?: string }>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface PathItem {
|
|
39
|
+
[method: string]: OperationObject | undefined;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface OperationObject {
|
|
43
|
+
tags?: string[];
|
|
44
|
+
summary?: string;
|
|
45
|
+
description?: string;
|
|
46
|
+
operationId?: string;
|
|
47
|
+
parameters?: ParameterObject[];
|
|
48
|
+
requestBody?: RequestBodyObject;
|
|
49
|
+
responses?: Record<string, ResponseObject>;
|
|
50
|
+
deprecated?: boolean;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface ParameterObject {
|
|
54
|
+
name: string;
|
|
55
|
+
in: "query" | "path" | "header" | "body" | "formData";
|
|
56
|
+
required?: boolean;
|
|
57
|
+
type?: string;
|
|
58
|
+
format?: string;
|
|
59
|
+
description?: string;
|
|
60
|
+
schema?: SchemaObject;
|
|
61
|
+
items?: SchemaObject;
|
|
62
|
+
enum?: Array<string | number>;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface RequestBodyObject {
|
|
66
|
+
required?: boolean;
|
|
67
|
+
content?: Record<string, { schema?: SchemaObject }>;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface ResponseObject {
|
|
71
|
+
description?: string;
|
|
72
|
+
schema?: SchemaObject;
|
|
73
|
+
content?: Record<string, { schema?: SchemaObject }>;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface SchemaObject {
|
|
77
|
+
type?: string;
|
|
78
|
+
format?: string;
|
|
79
|
+
$ref?: string;
|
|
80
|
+
items?: SchemaObject;
|
|
81
|
+
properties?: Record<string, SchemaObject>;
|
|
82
|
+
required?: string[];
|
|
83
|
+
description?: string;
|
|
84
|
+
enum?: Array<string | number>;
|
|
85
|
+
allOf?: SchemaObject[];
|
|
86
|
+
oneOf?: SchemaObject[];
|
|
87
|
+
anyOf?: SchemaObject[];
|
|
88
|
+
title?: string;
|
|
89
|
+
additionalProperties?: boolean | SchemaObject;
|
|
90
|
+
originalRef?: string;
|
|
91
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": "../../tsconfig.json",
|
|
3
|
+
"compilerOptions": {
|
|
4
|
+
"lib": ["ESNext", "DOM"],
|
|
5
|
+
"allowSyntheticDefaultImports": true,
|
|
6
|
+
"esModuleInterop": true,
|
|
7
|
+
"outDir": "./dist",
|
|
8
|
+
"composite": false,
|
|
9
|
+
"declaration": false,
|
|
10
|
+
"declarationMap": false
|
|
11
|
+
},
|
|
12
|
+
"include": ["src/**/*"]
|
|
13
|
+
}
|