@jayfong/x-server 2.30.3 → 2.31.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.
@@ -1,137 +1,227 @@
1
1
  "use strict";
2
2
 
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
3
  var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
4
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
5
5
  exports.__esModule = true;
6
6
  exports.ApiGenerator = void 0;
7
- var parseComment = _interopRequireWildcard(require("comment-parser"));
7
+ var _path = _interopRequireDefault(require("path"));
8
8
  var _debug = _interopRequireDefault(require("debug"));
9
9
  var _fsExtra = _interopRequireDefault(require("fs-extra"));
10
- var _nodePath = _interopRequireDefault(require("node:path"));
11
- var ts = _interopRequireWildcard(require("ts-morph"));
10
+ var _tsMorph = _interopRequireWildcard(require("ts-morph"));
12
11
  var _vtils = require("vtils");
13
12
  var _http_method = require("../core/http_method");
13
+ /** 注释 */
14
+
15
+ /** 接口传输数据 */
16
+
17
+ /** 接口数据 */
18
+
14
19
  class ApiGenerator {
15
- constructor() {
20
+ constructor(cwd = process.cwd()) {
21
+ this.cwd = cwd;
16
22
  this.debug = (0, _debug.default)('api');
17
- this.cwd = process.cwd();
18
- // cwd = '/Users/admin/Documents/jfWorks/x-server-test'
19
- this.project = void 0;
23
+ // 几种情况:
24
+ // /index.ts
25
+ // /user/index.ts
26
+ // /post.ts
27
+ // /user/list.ts
28
+ this.categoryUrlRe = /^.+\/src\/handlers\/(?:index\.ts|(.*)\/index\.ts|(.*)\.ts)$/;
29
+ this.checker = void 0;
20
30
  }
21
- getTypeBySymbol(symbol) {
22
- return symbol.getTypeAtLocation(symbol.getDeclarations()[0] || symbol.getValueDeclarationOrThrow());
31
+ async start() {
32
+ this.debug('启动项目...');
33
+ const tsConfigPath = _path.default.join(this.cwd, 'tsconfig.json');
34
+ const handlersPath = _path.default.join(this.cwd, 'node_modules/.x/handlers.ts');
35
+ const entryFile = _path.default.join(this.cwd, 'src/generated/handlers.ts');
36
+
37
+ // 仅使用 ts-morph 初始化项目
38
+ const moProject = new _tsMorph.default.Project({
39
+ tsConfigFilePath: tsConfigPath
40
+ });
41
+ moProject.createSourceFile(entryFile, await _fsExtra.default.readFile(handlersPath, 'utf-8'));
42
+ const program = moProject.getProgram().compilerObject;
43
+ const checker = program.getTypeChecker();
44
+ this.checker = checker;
45
+ const moduleSymbol = checker.getSymbolAtLocation(program.getSourceFile(entryFile));
46
+ const categorySymbols = checker.getExportsOfModule(moduleSymbol);
47
+ const apiData = [];
48
+ for (const categorySymbol of categorySymbols) {
49
+ var _ref, _categoryUrlMatch$;
50
+ // 分类的类型
51
+ const categoryType = checker.getTypeOfSymbolAtLocation(categorySymbol, categorySymbol.getDeclarations()[0]);
52
+
53
+ // 处理器列表
54
+ const handlerSymbols = categoryType.getProperties();
55
+
56
+ // 分类源文件
57
+ const categorySourceFile = handlerSymbols[0].getDeclarations()[0].getSourceFile();
58
+
59
+ // 分类源文件路径
60
+ const categorySourceFilePath = categorySourceFile.fileName;
61
+
62
+ // 分类 URL
63
+ const categoryUrlMatch = categorySourceFilePath.match(this.categoryUrlRe);
64
+ let categoryUrl = (_ref = (_categoryUrlMatch$ = categoryUrlMatch[1]) != null ? _categoryUrlMatch$ : categoryUrlMatch[2]) != null ? _ref : '';
65
+ categoryUrl = categoryUrl === '' ? '/' : `/${categoryUrl}/`;
66
+ for (const handlerSymbol of handlerSymbols) {
67
+ // 处理器名称
68
+ const handlerName = handlerSymbol.getName();
69
+
70
+ // 处理器 URL
71
+ const handlerUrl = `${categoryUrl}${handlerName}`;
72
+
73
+ // 处理器注释
74
+ const handlerComment = this.getComment(handlerSymbol);
75
+ if (handlerComment.tags.has('private')) {
76
+ this.debug('跳过生成接口: %s', `${handlerUrl}`);
77
+ continue;
78
+ }
79
+ this.debug('生成接口: %s ...', handlerUrl);
80
+ const handlerNode = handlerSymbol.getDeclarations()[0];
81
+ const handlerType = checker.getTypeAtLocation(handlerNode);
82
+ const [requestType, responseType, methodType] = checker.getTypeArguments(handlerType);
83
+ const handlerCategory = (0, _vtils.pascalCase)(categoryUrl) || 'Index';
84
+ const handlerDescription = handlerComment.description || handlerUrl;
85
+ const handlerMethod = methodType.value;
86
+ const httpMethod = _http_method.HandlerMethodToHttpMethod[handlerMethod];
87
+ const requestData = this.getApiDto({
88
+ type: requestType
89
+ });
90
+ const responseData = this.getApiDto({
91
+ type: responseType
92
+ });
93
+ const requestDataJsonSchema = this.apiDataToJsonSchema(requestData);
94
+ const responseDataJsonSchema = this.apiDataToJsonSchema(responseData);
95
+ apiData.push({
96
+ category: handlerCategory,
97
+ name: handlerDescription,
98
+ path: handlerUrl,
99
+ handlerMethod: handlerMethod,
100
+ method: httpMethod,
101
+ requestData: requestData,
102
+ responseData: responseData,
103
+ requestDataJsonSchema: requestDataJsonSchema,
104
+ responseDataJsonSchema: responseDataJsonSchema
105
+ });
106
+ }
107
+ }
108
+ this.debug('写入文件...');
109
+ await Promise.all([_fsExtra.default.outputJSON(_path.default.join(this.cwd, 'temp/api.json'), apiData, {
110
+ spaces: 2
111
+ }), _fsExtra.default.outputJSON(_path.default.join(this.cwd, 'temp/yapi.json'), this.genYApiData(apiData), {
112
+ spaces: 2
113
+ })]);
23
114
  }
24
- getComment(declaration) {
25
- var _declaration$getLeadi;
26
- const text = ((declaration == null || (_declaration$getLeadi = declaration.getLeadingCommentRanges()[0]) == null ? void 0 : _declaration$getLeadi.getText()) || '').trim();
27
- const comment = parseComment.parse(text)[0];
28
- const description = (comment == null ? void 0 : comment.description) || '';
29
- const tags = new Map();
30
- comment == null ? void 0 : comment.tags.forEach(tag => {
31
- tags.set(tag.tag, tag.description);
115
+
116
+ // ref: https://github.com/styleguidist/react-docgen-typescript/blob/master/src/parser.ts#L777
117
+ getComment(symbol) {
118
+ if (!symbol) {
119
+ return {
120
+ existing: false,
121
+ description: '',
122
+ tags: new Map()
123
+ };
124
+ }
125
+ const description = _tsMorph.ts.displayPartsToString(symbol.getDocumentationComment(this.checker)).trim();
126
+ const tags = symbol.getJsDocTags().map(item => {
127
+ return {
128
+ label: item.name,
129
+ value: _tsMorph.ts.displayPartsToString(item.text).trim()
130
+ };
32
131
  });
33
132
  return {
34
- existing: !!comment,
133
+ existing: !!description,
35
134
  description: description,
36
- tags: tags
135
+ tags: tags.reduce((res, item) => {
136
+ res.set(item.label, item.value);
137
+ return res;
138
+ }, new Map())
37
139
  };
38
140
  }
39
- getCommentBySymbol(symbol) {
40
- var _this$getComment;
41
- return ((_this$getComment = this.getComment(symbol.getDeclarations()[0])) == null ? void 0 : _this$getComment.description) || '';
42
- }
43
- typeToApiData(type, _symbol) {
44
- var _type$getSymbol, _type$getSymbol2, _type$getSymbol3;
45
- // ws
46
- if (((_type$getSymbol = type.getSymbol()) == null ? void 0 : _type$getSymbol.getName()) === 'SocketStream') {
141
+ getApiDto({
142
+ type,
143
+ keySymbol = type.symbol || type.aliasSymbol
144
+ }) {
145
+ var _valueSymbol;
146
+ const hasTypeFlag = (flag, _type = type) => (_type.flags & flag) === flag;
147
+ let valueSymbol = type.symbol || type.aliasSymbol;
148
+ const keySymbolName = (keySymbol == null ? void 0 : keySymbol.getName()) || '';
149
+ let valueSymbolName = ((_valueSymbol = valueSymbol) == null ? void 0 : _valueSymbol.getName()) || '';
150
+ const comment = this.getComment(keySymbol);
151
+ let isRequired = keySymbol ? !(keySymbol.getFlags() & _tsMorph.ts.SymbolFlags.Optional) : false;
152
+
153
+ // WS
154
+ if (valueSymbolName === 'SocketStream') {
47
155
  return {
48
156
  name: 'ws',
49
- desc: 'ws',
50
- required: false,
157
+ desc: comment.description,
158
+ required: isRequired,
51
159
  type: 'object',
52
- children: [],
53
- enum: []
160
+ enum: [],
161
+ children: []
54
162
  };
55
163
  }
56
164
 
57
- // XFile
58
- if (((_type$getSymbol2 = type.getSymbol()) == null ? void 0 : _type$getSymbol2.getName()) === 'MultipartFile') {
59
- const symbol = _symbol || type.getSymbol();
165
+ // 文件
166
+ if (valueSymbolName === 'MultipartFile') {
60
167
  return {
61
168
  name: 'file',
62
- desc: symbol && this.getCommentBySymbol(symbol) || '',
63
- required: !!symbol && !(symbol.getFlags() & ts.SymbolFlags.Optional),
169
+ desc: comment.description,
170
+ required: isRequired,
64
171
  type: 'file',
65
- children: [],
66
- enum: []
172
+ enum: [],
173
+ children: []
67
174
  };
68
175
  }
69
- let isRequired = true;
70
- let isUnion = type.isUnion();
71
- const unionTypes = isUnion ? type.getUnionTypes().filter(item => !item.isBooleanLiteral() && !item.isNull() && !item.isUndefined()) : [];
72
- isUnion = !!unionTypes.length;
176
+
177
+ // 联合类型
178
+ // 布尔、枚举也会用这表示
179
+ const rawUnionTypes = type.isUnion() && type.types || [];
180
+ const unionTypes = rawUnionTypes.filter(item => !hasTypeFlag(_tsMorph.ts.TypeFlags.Null, item) && !hasTypeFlag(_tsMorph.ts.TypeFlags.Undefined, item));
181
+ const isUnion = !!unionTypes.length;
73
182
  if (isUnion) {
74
- if (unionTypes.length === 1 && !unionTypes[0].isLiteral()) {
75
- isUnion = false;
183
+ var _this$checker$getBase;
184
+ if (unionTypes.length !== rawUnionTypes.length) {
185
+ isRequired = false;
76
186
  }
77
- // 兼容 prisma 生成的类型用 null 表示可选
78
- isRequired = unionTypes.length === type.getUnionTypes().length;
79
- // 必须用 getBaseTypeOfLiteralType 获取枚举字面量的原始类型
80
- type = unionTypes[0].getBaseTypeOfLiteralType();
187
+ type = unionTypes[0];
188
+ valueSymbol = type.symbol || type.aliasSymbol;
189
+ valueSymbolName = ((_this$checker$getBase = this.checker.getBaseTypeOfLiteralType(type).getSymbol()) == null ? void 0 : _this$checker$getBase.getName()) || '';
81
190
  }
82
- const isEnum = type.isEnum();
83
- const enumData = isEnum ?
84
- // @ts-ignore
85
- type.compilerType.types.reduce((res, item) => {
86
- res[item.getSymbol().getName()] = item.value;
87
- return res;
88
- }, {}) : {};
89
- const enumKeys = Object.keys(enumData);
90
- const enumValues = Object.values(enumData);
91
191
  const isIntersection = type.isIntersection();
92
- const intersectionTypes = isIntersection && type.getIntersectionTypes();
93
- const isArray = type.isArray();
94
- const isString = isEnum ? typeof enumValues[0] === 'string' : type.isString() || ['Date'].includes(((_type$getSymbol3 = type.getSymbol()) == null ? void 0 : _type$getSymbol3.getName()) || '');
95
- const isNumber = isEnum ? typeof enumValues[0] === 'number' : type.isNumber();
96
- const isBoolean = type.isBoolean() || type.isUnion() && type.getUnionTypes().some(item => item.isBooleanLiteral()) && type.getUnionTypes().every(item => item.isBooleanLiteral() || item.isNull() || item.isUndefined());
97
- const isObject = !isArray && !isString && !isNumber && !isBoolean && type.isObject() ||
98
- // 将交集类型视为对象
192
+ const intersectionTypes = isIntersection && type.types || [];
193
+ const isDate = valueSymbolName === 'Date';
194
+ const isBigIntLiteral = hasTypeFlag(_tsMorph.ts.TypeFlags.BigIntLiteral);
195
+ const isBigInt = hasTypeFlag(_tsMorph.ts.TypeFlags.BigInt) || isBigIntLiteral;
196
+ const isArray = valueSymbolName === 'Array' || valueSymbolName === 'ReadonlyArray';
197
+ const isStringLiteral = hasTypeFlag(_tsMorph.ts.TypeFlags.StringLiteral);
198
+ const isString = hasTypeFlag(_tsMorph.ts.TypeFlags.String) || isStringLiteral ||
199
+ // BigInt 类型视为字符串
200
+ isBigInt ||
201
+ // Date 类型视为字符串
202
+ isDate;
203
+ const isNumberLiteral = hasTypeFlag(_tsMorph.ts.TypeFlags.NumberLiteral);
204
+ const isNumber = hasTypeFlag(_tsMorph.ts.TypeFlags.Number) || isNumberLiteral;
205
+ const isBoolean = hasTypeFlag(_tsMorph.ts.TypeFlags.Boolean) || hasTypeFlag(_tsMorph.ts.TypeFlags.BooleanLiteral);
206
+ const isLiteral = isStringLiteral || isNumberLiteral || isBigIntLiteral;
207
+ const isObject = !isArray && !isString && !isNumber && !isBoolean && hasTypeFlag(_tsMorph.ts.TypeFlags.Object) ||
208
+ // 交集类型视为对象
99
209
  isIntersection;
100
- const symbol = _symbol || type.getSymbol();
101
- const parentSymbol = symbol;
102
- const apiName = (symbol == null ? void 0 : symbol.getName()) || '__type';
103
- const apiDesc = [symbol && this.getCommentBySymbol(symbol), isEnum && `枚举:${enumKeys.map((key, index) => `${key}->${enumValues[index]}`).join('; ')}`].filter(Boolean).join('\n');
104
- const apiEnum = isUnion ? unionTypes.map(t => t.getLiteralValue()) : isEnum ? enumValues : [];
210
+ const apiName = keySymbolName || '__type';
211
+ const apiDesc = keySymbol && this.getComment(keySymbol).description || '';
212
+ const apiEnum = (isUnion ? unionTypes.map(item => item.value) : isLiteral ? [type.value] : []).filter(v => v != null);
105
213
  const apiType = isArray ? 'array' : isString ? 'string' : isNumber ? 'number' : isBoolean ? 'boolean' : 'object';
106
- const apiRequired = isRequired === false ? false : !!symbol && !(symbol.getFlags() & ts.SymbolFlags.Optional);
107
- const apiChildren = isArray ? [this.typeToApiData(type.getArrayElementTypeOrThrow())] : isObject ? (0, _vtils.ii)(() => {
108
- const context = type._context;
109
- const compilerFactory = context.compilerFactory;
110
- const rawChecker = type.compilerType.checker;
111
- let symbols = [];
112
- if (intersectionTypes) {
113
- // https://github.com/microsoft/TypeScript/issues/38184
114
- symbols = rawChecker.getAllPossiblePropertiesOfTypes(intersectionTypes.map(item => item.compilerType))
115
- // https://github.com/dsherret/ts-morph/blob/a7072fcf6f9babb784b40f0326c80dea4563a4aa/packages/ts-morph/src/compiler/types/Type.ts#L296
116
- .map(symbol => compilerFactory.getSymbol(symbol));
117
- } else {
118
- // symbols = type.getApparentProperties()
119
- // https://github.com/microsoft/TypeScript/issues/38184
120
- symbols = rawChecker.getAllPossiblePropertiesOfTypes([type.compilerType])
121
- // https://github.com/dsherret/ts-morph/blob/a7072fcf6f9babb784b40f0326c80dea4563a4aa/packages/ts-morph/src/compiler/types/Type.ts#L296
122
- .map(symbol => compilerFactory.getSymbol(symbol));
123
- }
124
- return symbols.map(symbol => {
125
- return this.typeToApiData(!symbol.compilerSymbol.declarations ?
126
- // 对于复杂对象,没有定义的,通过 type 直接获取(在前面通过 getText 预处理得到)
127
- symbol.compilerSymbol.type ? compilerFactory.getType(symbol.compilerSymbol.type) :
128
- // fix: symbol.compilerSymbol.type 为 undefined
129
- // https://github.com/styleguidist/react-docgen-typescript/blob/master/src/parser.ts#L696
130
- compilerFactory.getType(rawChecker.getTypeOfSymbolAtLocation(
131
- // @ts-ignore
132
- symbol.compilerSymbol,
133
- // @ts-ignore
134
- parentSymbol.compilerSymbol.declarations[0])) : this.getTypeBySymbol(symbol), symbol);
214
+ const apiRequired = isRequired;
215
+ const apiChildren = isArray ? [this.getApiDto({
216
+ type: this.checker.getTypeArguments(type)[0]
217
+ })] : isObject ? (0, _vtils.ii)(() => {
218
+ const childSymbols = this.checker.getAllPossiblePropertiesOfTypes(intersectionTypes.length ? intersectionTypes : [type]);
219
+ return childSymbols.map(childSymbol => {
220
+ const childType = this.checker.getTypeOfSymbol(childSymbol);
221
+ return this.getApiDto({
222
+ type: childType,
223
+ keySymbol: childSymbol
224
+ });
135
225
  });
136
226
  }) : [];
137
227
  return {
@@ -148,7 +238,6 @@ class ApiGenerator {
148
238
  if (apiData.type === 'object') {
149
239
  jsonSchema.type = 'object';
150
240
  jsonSchema.properties = apiData.children.reduce((res, item) => {
151
- ;
152
241
  res[item.name] = this.apiDataToJsonSchema(item);
153
242
  return res;
154
243
  }, {});
@@ -225,63 +314,5 @@ class ApiGenerator {
225
314
  list: data[cat]
226
315
  }));
227
316
  }
228
- async generate() {
229
- this.debug('启动项目...');
230
- this.project = new ts.Project({
231
- tsConfigFilePath: _nodePath.default.join(this.cwd, 'tsconfig.json')
232
- });
233
- this.debug('加载文件...');
234
- const sourceFile = this.project.createSourceFile(_nodePath.default.join(this.cwd, 'src/generated/handlers.ts'), await _fsExtra.default.readFile(_nodePath.default.join(this.cwd, 'node_modules/.x/handlers.ts'), 'utf-8'));
235
- this.debug('导出处理器...');
236
- const handlerGroup = sourceFile.getExportSymbols();
237
- const handles = [];
238
- this.debug('生成API文档...');
239
- for (const handlerList of handlerGroup) {
240
- const handlerListSourceFile = this.getTypeBySymbol(handlerList).getProperties()[0].getDeclarations()[0].getSourceFile();
241
- const basePath = `/${handlerListSourceFile.getFilePath().replace('.ts', '').split('/src/handlers/')[1].replace(/(^|\/)index$/, '/').split('/').map(v => (0, _vtils.snakeCase)(v)).join('/')}/`.replace(/\/{2,}/g, '/');
242
- for (const handler of handlerListSourceFile.getVariableStatements().filter(item => item.isExported())) {
243
- // 重要:这一步必须,先调一遍 getText 获取看到的对象,后续对于复杂定义才不会报错
244
- handler.getDeclarations().forEach(exp => {
245
- exp.getType().getText();
246
- });
247
- const handlerExp = handler.getDeclarations()[0];
248
- const handlerPath = `${basePath}${handlerExp.getName()}`;
249
- this.debug('生成接口: %s ...', handlerPath);
250
- const [requestType, responseType, methodType] = handlerExp.getType().getTypeArguments();
251
- const handlerComment = this.getComment(handlerExp.getParent().getParent());
252
- if (handlerComment.tags.has('private')) {
253
- this.debug('跳过生成接口: %s', `${handlerPath}`);
254
- continue;
255
- }
256
- const handlerCategory = (0, _vtils.pascalCase)(basePath) || 'Index';
257
- const handlerName = handlerComment.description || handlerPath;
258
- const handlerMethod = methodType.getLiteralValueOrThrow();
259
- const serverMethod = _http_method.HandlerMethodToHttpMethod[handlerMethod];
260
- const requestData = this.typeToApiData(requestType);
261
- const responseData = this.typeToApiData(responseType);
262
- const requestDataJsonSchema = this.apiDataToJsonSchema(requestData);
263
- const responseDataJsonSchema = this.apiDataToJsonSchema(responseData);
264
- handles.push({
265
- category: handlerCategory,
266
- name: handlerName,
267
- path: handlerPath,
268
- handlerMethod: handlerMethod,
269
- method: serverMethod,
270
- requestData: requestData,
271
- responseData: responseData,
272
- requestDataJsonSchema: requestDataJsonSchema,
273
- responseDataJsonSchema: responseDataJsonSchema
274
- });
275
- }
276
- }
277
- this.debug('写入文件...');
278
- await Promise.all([_fsExtra.default.outputJSON(_nodePath.default.join(this.cwd, 'temp/api.json'), handles, {
279
- spaces: 2
280
- }), _fsExtra.default.outputJSON(_nodePath.default.join(this.cwd, 'temp/yapi.json'), this.genYApiData(handles), {
281
- spaces: 2
282
- })]);
283
- }
284
317
  }
285
-
286
- // new ApiGenerator().generate()
287
318
  exports.ApiGenerator = ApiGenerator;