swagger2api-v3 1.1.10 → 1.1.11

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.
@@ -1,259 +1,28 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
2
16
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isValidIdentifier = isValidIdentifier;
4
- exports.formatTsPropertyName = formatTsPropertyName;
5
- exports.stripNullFromUnion = stripNullFromUnion;
6
- exports.swaggerTypeToTsType = swaggerTypeToTsType;
7
- exports.getRefName = getRefName;
8
17
  exports.swaggerParameterToSchema = swaggerParameterToSchema;
9
18
  exports.getResponseType = getResponseType;
10
19
  exports.getSchemaFromContent = getSchemaFromContent;
11
- const naming_1 = require("./naming");
12
- /**
13
- * 判断字符串是否为合法 TypeScript 标识符
14
- * @param name 属性名
15
- * @returns 是否为合法标识符
16
- */
17
- function isValidIdentifier(name) {
18
- return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
19
- }
20
- /**
21
- * 格式化 TypeScript 属性名
22
- * @param name 属性名
23
- * @returns 可用于类型声明的属性名
24
- */
25
- function formatTsPropertyName(name) {
26
- return isValidIdentifier(name) ? name : JSON.stringify(name);
27
- }
28
- /**
29
- * 移除联合类型中的顶层 null 类型
30
- * @param typeStr 类型字符串
31
- * @returns 移除 null 后的类型字符串
32
- */
33
- function stripNullFromUnion(typeStr) {
34
- if (!typeStr)
35
- return 'any';
36
- const parts = [];
37
- let current = '';
38
- let parenDepth = 0;
39
- let angleDepth = 0;
40
- let braceDepth = 0;
41
- let bracketDepth = 0;
42
- for (let i = 0; i < typeStr.length; i++) {
43
- const ch = typeStr[i];
44
- if (ch === '(')
45
- parenDepth++;
46
- else if (ch === ')')
47
- parenDepth = Math.max(0, parenDepth - 1);
48
- else if (ch === '<')
49
- angleDepth++;
50
- else if (ch === '>')
51
- angleDepth = Math.max(0, angleDepth - 1);
52
- else if (ch === '{')
53
- braceDepth++;
54
- else if (ch === '}')
55
- braceDepth = Math.max(0, braceDepth - 1);
56
- else if (ch === '[')
57
- bracketDepth++;
58
- else if (ch === ']')
59
- bracketDepth = Math.max(0, bracketDepth - 1);
60
- const isTopLevel = parenDepth === 0 &&
61
- angleDepth === 0 &&
62
- braceDepth === 0 &&
63
- bracketDepth === 0;
64
- if (ch === '|' && isTopLevel) {
65
- parts.push(current.trim());
66
- current = '';
67
- continue;
68
- }
69
- current += ch;
70
- }
71
- if (current.trim())
72
- parts.push(current.trim());
73
- const normalized = Array.from(new Set(parts.filter((part) => part && part !== 'null')));
74
- return normalized.length > 0 ? normalized.join(' | ') : 'any';
75
- }
76
- /**
77
- * 将 OpenAPI schema 转换为 TypeScript 类型
78
- * @param schema OpenAPI schema
79
- * @param schemas 可选的 schemas 上下文,用于查找被引用的类型定义
80
- * @returns TypeScript类型字符串
81
- */
82
- function swaggerTypeToTsType(schema, schemas) {
83
- if (!schema)
84
- return 'any';
85
- let baseType = 'any';
86
- if (Array.isArray(schema.type)) {
87
- const types = schema.type.map((type) => swaggerTypeToTsType({ ...schema, type, nullable: false }, schemas));
88
- const uniqueTypes = Array.from(new Set(types));
89
- baseType = uniqueTypes.includes('any') ? 'any' : uniqueTypes.join(' | ');
90
- }
91
- else if (schema.enum) {
92
- baseType = schema.enum
93
- .map((value) => toLiteralType(value))
94
- .join(' | ');
95
- }
96
- else if (schema.allOf) {
97
- const refSchema = schema.allOf.find((item) => item.$ref);
98
- const secondSchema = schema.allOf.find((item) => !item.$ref);
99
- if (refSchema && secondSchema && schema.allOf.length === 2) {
100
- const refName = getRefName(refSchema.$ref || '');
101
- const sanitizedRefName = (0, naming_1.sanitizeTypeName)(refName || '');
102
- if (secondSchema.properties) {
103
- const propertyTypes = [];
104
- for (const propSchema of Object.values(secondSchema.properties)) {
105
- const propType = swaggerTypeToTsType(propSchema, schemas);
106
- propertyTypes.push(propType);
107
- }
108
- if (propertyTypes.length === 1) {
109
- baseType = `${sanitizedRefName}<${propertyTypes[0]}>`;
110
- }
111
- else if (propertyTypes.length > 1) {
112
- const combinedType = `{ ${Object.entries(secondSchema.properties)
113
- .map(([key, value]) => {
114
- const optional = secondSchema.required?.includes(key) ? '' : '?';
115
- let type = swaggerTypeToTsType(value, schemas);
116
- if (optional === '?')
117
- type = stripNullFromUnion(type);
118
- return `${formatTsPropertyName(key)}${optional}: ${type}`;
119
- })
120
- .join('; ')} }`;
121
- baseType = `${sanitizedRefName}<${combinedType}>`;
122
- }
123
- else {
124
- baseType = sanitizedRefName || 'any';
125
- }
126
- }
127
- else {
128
- baseType = sanitizedRefName || 'any';
129
- }
130
- }
131
- else {
132
- const types = schema.allOf
133
- .map((item) => swaggerTypeToTsType(item, schemas))
134
- .filter((type) => type !== 'any');
135
- const uniqueTypes = Array.from(new Set(types));
136
- baseType = uniqueTypes.length > 0 ? uniqueTypes.join(' & ') : 'any';
137
- }
138
- }
139
- else if (schema.anyOf || schema.oneOf) {
140
- const types = (schema.anyOf || schema.oneOf).map((item) => {
141
- if (item.type === 'null')
142
- return 'null';
143
- return swaggerTypeToTsType(item, schemas);
144
- });
145
- if (types.includes('any')) {
146
- baseType = 'any';
147
- }
148
- else {
149
- const uniqueTypes = Array.from(new Set(types));
150
- baseType = uniqueTypes.length > 0 ? uniqueTypes.join(' | ') : 'any';
151
- }
152
- }
153
- else if (schema.$ref) {
154
- const refName = getRefName(schema.$ref);
155
- baseType = (0, naming_1.sanitizeTypeName)(refName || 'any');
156
- if (schemas && refName) {
157
- const referencedSchema = schemas[refName];
158
- if (referencedSchema && referencedSchema.type === 'array') {
159
- baseType = `${baseType}[]`;
160
- }
161
- }
162
- }
163
- else if (schema.type === 'array') {
164
- const itemSchema = schema.items;
165
- const itemType = swaggerTypeToTsType(itemSchema, schemas);
166
- if (itemSchema?.$ref && schemas) {
167
- const refName = getRefName(itemSchema.$ref);
168
- const referencedSchema = refName ? schemas[refName] : undefined;
169
- baseType =
170
- referencedSchema?.type === 'array' ? itemType : `${itemType}[]`;
171
- }
172
- else {
173
- baseType = `${itemType}[]`;
174
- }
175
- }
176
- else if (schema.type === 'object') {
177
- if (schema.properties) {
178
- const properties = Object.entries(schema.properties)
179
- .map(([key, value]) => {
180
- const optional = schema.required?.includes(key) ? '' : '?';
181
- let type = swaggerTypeToTsType(value, schemas);
182
- if (optional === '?')
183
- type = stripNullFromUnion(type);
184
- return ` ${formatTsPropertyName(key)}${optional}: ${type};`;
185
- })
186
- .join('\n');
187
- baseType = `{\n${properties}\n}`;
188
- }
189
- else if (schema.additionalProperties &&
190
- typeof schema.additionalProperties === 'object') {
191
- const valueType = swaggerTypeToTsType(schema.additionalProperties, schemas);
192
- baseType = `Record<string, ${valueType}>`;
193
- }
194
- else if (schema.additionalProperties === false) {
195
- baseType = 'Record<string, never>';
196
- }
197
- else {
198
- baseType = 'Record<string, any>';
199
- }
200
- }
201
- else {
202
- switch (schema.type) {
203
- case 'integer':
204
- case 'number':
205
- baseType = 'number';
206
- break;
207
- case 'string':
208
- baseType = 'string';
209
- break;
210
- case 'boolean':
211
- baseType = 'boolean';
212
- break;
213
- case 'file':
214
- baseType = 'File';
215
- break;
216
- case 'null':
217
- baseType = 'null';
218
- break;
219
- default:
220
- baseType = 'any';
221
- break;
222
- }
223
- }
224
- if (schema.nullable === true) {
225
- if (baseType === 'any')
226
- return 'any';
227
- if (baseType.includes('null'))
228
- return baseType;
229
- return `${baseType} | null`;
230
- }
231
- return baseType;
232
- }
20
+ const schema_1 = require("./schema");
21
+ __exportStar(require("./schema"), exports);
233
22
  /**
234
- * $ref 字符串中提取引用名称
235
- * @param ref OpenAPI $ref 字符串
236
- * @returns 引用名称
237
- */
238
- function getRefName(ref) {
239
- return ref.split('/').pop() || '';
240
- }
241
- /**
242
- * 将枚举值转换为 TypeScript 字面量类型
243
- * @param value 枚举值
244
- * @returns 字面量类型字符串
245
- */
246
- function toLiteralType(value) {
247
- if (value === null)
248
- return 'null';
249
- if (typeof value === 'string')
250
- return JSON.stringify(value);
251
- return String(value);
252
- }
253
- /**
254
- * 将 OpenAPI 参数转换为 schema 对象
23
+ * OpenAPI 参数转换为 Schema 对象
255
24
  * @param parameter OpenAPI 参数
256
- * @returns 参数对应的 schema
25
+ * @returns 参数对应的 Schema
257
26
  */
258
27
  function swaggerParameterToSchema(parameter) {
259
28
  if (parameter.schema) {
@@ -270,25 +39,23 @@ function swaggerParameterToSchema(parameter) {
270
39
  * 获取响应类型
271
40
  * @param responses OpenAPI 响应对象
272
41
  * @param schemas OpenAPI components.schemas
273
- * @returns TypeScript类型字符串
42
+ * @returns TypeScript 类型字符串
274
43
  */
275
- function getResponseType(responses, schemas) {
276
- if (!responses) {
44
+ function getResponseType(responses, schemas = {}) {
45
+ if (!responses)
277
46
  return 'any';
278
- }
279
47
  const successResponse = getSuccessResponse(responses);
280
- if (!successResponse) {
48
+ if (!successResponse)
281
49
  return 'any';
282
- }
283
50
  const contentSchema = getSchemaFromContent(successResponse.content);
284
51
  if (contentSchema) {
285
- return swaggerTypeToTsType(contentSchema, schemas);
52
+ return (0, schema_1.swaggerTypeToTsType)(contentSchema, schemas, 'response');
286
53
  }
287
54
  return successResponse.description === 'No Content' ? 'void' : 'any';
288
55
  }
289
56
  /**
290
57
  * 从响应集合中获取优先成功响应
291
- * @param responses OpenAPI响应对象
58
+ * @param responses OpenAPI 响应对象
292
59
  * @returns 成功响应对象
293
60
  */
294
61
  function getSuccessResponse(responses) {
@@ -299,12 +66,14 @@ function getSuccessResponse(responses) {
299
66
  const successStatus = Object.keys(responses)
300
67
  .filter((status) => /^2\d\d$/.test(status))
301
68
  .sort()[0];
302
- return successStatus ? responses[successStatus] : responses.default;
69
+ return successStatus
70
+ ? responses[successStatus]
71
+ : responses.default;
303
72
  }
304
73
  /**
305
- * 从 OpenAPI content 对象中获取最合适的 schema
74
+ * 从 OpenAPI content 对象中获取最合适的 Schema
306
75
  * @param content OpenAPI content 对象
307
- * @returns 匹配到的 schema
76
+ * @returns 匹配到的 Schema
308
77
  */
309
78
  function getSchemaFromContent(content) {
310
79
  if (!content)
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "swagger2api-v3",
3
- "version": "1.1.10",
4
- "description": "A command-line tool for generating TypeScript API interfaces from OpenAPI 3.x / Swagger 3.0 documentation",
3
+ "version": "1.1.11",
4
+ "description": "A command-line tool for generating TypeScript API interfaces from OpenAPI 3.0 documentation",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "type": "commonjs",
@@ -48,7 +48,7 @@
48
48
  "homepage": "https://github.com/xiaoyang33/swagger2api-v3#readme",
49
49
  "repository": {
50
50
  "type": "git",
51
- "url": "https://github.com/xiaoyang33/swagger2api-v3.git"
51
+ "url": "git+https://github.com/xiaoyang33/swagger2api-v3.git"
52
52
  },
53
53
  "bugs": {
54
54
  "url": "https://github.com/xiaoyang33/swagger2api-v3/issues"
@@ -65,7 +65,7 @@
65
65
  "typescript": "^6.0.3"
66
66
  },
67
67
  "dependencies": {
68
- "axios": "^1.18.1",
68
+ "@apidevtools/swagger-parser": "^12.1.0",
69
69
  "commander": "^12.1.0"
70
70
  }
71
71
  }