open-api-typescript-request-generator 0.0.1

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.
Files changed (71) hide show
  1. package/README.md +26 -0
  2. package/bin/apits-gener +4 -0
  3. package/es/Generator.d.ts +43 -0
  4. package/es/Generator.js +892 -0
  5. package/es/cli.d.ts +19 -0
  6. package/es/cli.js +547 -0
  7. package/es/console.d.ts +48 -0
  8. package/es/console.js +151 -0
  9. package/es/constants.d.ts +22 -0
  10. package/es/constants.js +39 -0
  11. package/es/dependenciesHandler.d.ts +16 -0
  12. package/es/dependenciesHandler.js +270 -0
  13. package/es/genIndex.d.ts +23 -0
  14. package/es/genIndex.js +354 -0
  15. package/es/genRequest.d.ts +3 -0
  16. package/es/genRequest.js +216 -0
  17. package/es/getOutputPath.d.ts +5 -0
  18. package/es/getOutputPath.js +28 -0
  19. package/es/helpers.d.ts +63 -0
  20. package/es/helpers.js +458 -0
  21. package/es/index.d.ts +2 -0
  22. package/es/index.js +34 -0
  23. package/es/requestYapiData.d.ts +157 -0
  24. package/es/requestYapiData.js +1010 -0
  25. package/es/responseDataJsonSchemaHandler.d.ts +11 -0
  26. package/es/responseDataJsonSchemaHandler.js +193 -0
  27. package/es/server/mock.d.ts +1 -0
  28. package/es/server/mock.js +7 -0
  29. package/es/server/swaggerJsonToYApiData.d.ts +10 -0
  30. package/es/server/swaggerJsonToYApiData.js +614 -0
  31. package/es/spinner.d.ts +15 -0
  32. package/es/spinner.js +58 -0
  33. package/es/types.d.ts +736 -0
  34. package/es/types.js +143 -0
  35. package/es/utils.d.ts +97 -0
  36. package/es/utils.js +783 -0
  37. package/lib/Generator.d.ts +43 -0
  38. package/lib/Generator.js +892 -0
  39. package/lib/cli.d.ts +19 -0
  40. package/lib/cli.js +547 -0
  41. package/lib/console.d.ts +48 -0
  42. package/lib/console.js +151 -0
  43. package/lib/constants.d.ts +22 -0
  44. package/lib/constants.js +39 -0
  45. package/lib/dependenciesHandler.d.ts +16 -0
  46. package/lib/dependenciesHandler.js +270 -0
  47. package/lib/genIndex.d.ts +23 -0
  48. package/lib/genIndex.js +354 -0
  49. package/lib/genRequest.d.ts +3 -0
  50. package/lib/genRequest.js +216 -0
  51. package/lib/getOutputPath.d.ts +5 -0
  52. package/lib/getOutputPath.js +28 -0
  53. package/lib/helpers.d.ts +63 -0
  54. package/lib/helpers.js +458 -0
  55. package/lib/index.d.ts +2 -0
  56. package/lib/index.js +34 -0
  57. package/lib/requestYapiData.d.ts +157 -0
  58. package/lib/requestYapiData.js +1010 -0
  59. package/lib/responseDataJsonSchemaHandler.d.ts +11 -0
  60. package/lib/responseDataJsonSchemaHandler.js +193 -0
  61. package/lib/server/mock.d.ts +1 -0
  62. package/lib/server/mock.js +7 -0
  63. package/lib/server/swaggerJsonToYApiData.d.ts +10 -0
  64. package/lib/server/swaggerJsonToYApiData.js +614 -0
  65. package/lib/spinner.d.ts +15 -0
  66. package/lib/spinner.js +58 -0
  67. package/lib/types.d.ts +736 -0
  68. package/lib/types.js +143 -0
  69. package/lib/utils.d.ts +97 -0
  70. package/lib/utils.js +783 -0
  71. package/package.json +106 -0
@@ -0,0 +1,892 @@
1
+ "use strict";
2
+
3
+ var __makeTemplateObject = this && this.__makeTemplateObject || function (cooked, raw) {
4
+ if (Object.defineProperty) {
5
+ Object.defineProperty(cooked, "raw", {
6
+ value: raw
7
+ });
8
+ } else {
9
+ cooked.raw = raw;
10
+ }
11
+
12
+ return cooked;
13
+ };
14
+
15
+ var __assign = this && this.__assign || function () {
16
+ __assign = Object.assign || function (t) {
17
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
18
+ s = arguments[i];
19
+
20
+ for (var p in s) {
21
+ if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
22
+ }
23
+ }
24
+
25
+ return t;
26
+ };
27
+
28
+ return __assign.apply(this, arguments);
29
+ };
30
+
31
+ var __createBinding = this && this.__createBinding || (Object.create ? function (o, m, k, k2) {
32
+ if (k2 === undefined) k2 = k;
33
+ var desc = Object.getOwnPropertyDescriptor(m, k);
34
+
35
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
36
+ desc = {
37
+ enumerable: true,
38
+ get: function get() {
39
+ return m[k];
40
+ }
41
+ };
42
+ }
43
+
44
+ Object.defineProperty(o, k2, desc);
45
+ } : function (o, m, k, k2) {
46
+ if (k2 === undefined) k2 = k;
47
+ o[k2] = m[k];
48
+ });
49
+
50
+ var __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function (o, v) {
51
+ Object.defineProperty(o, "default", {
52
+ enumerable: true,
53
+ value: v
54
+ });
55
+ } : function (o, v) {
56
+ o["default"] = v;
57
+ });
58
+
59
+ var __importStar = this && this.__importStar || function (mod) {
60
+ if (mod && mod.__esModule) return mod;
61
+ var result = {};
62
+ if (mod != null) for (var k in mod) {
63
+ if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
64
+ }
65
+
66
+ __setModuleDefault(result, mod);
67
+
68
+ return result;
69
+ };
70
+
71
+ var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
72
+ function adopt(value) {
73
+ return value instanceof P ? value : new P(function (resolve) {
74
+ resolve(value);
75
+ });
76
+ }
77
+
78
+ return new (P || (P = Promise))(function (resolve, reject) {
79
+ function fulfilled(value) {
80
+ try {
81
+ step(generator.next(value));
82
+ } catch (e) {
83
+ reject(e);
84
+ }
85
+ }
86
+
87
+ function rejected(value) {
88
+ try {
89
+ step(generator["throw"](value));
90
+ } catch (e) {
91
+ reject(e);
92
+ }
93
+ }
94
+
95
+ function step(result) {
96
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
97
+ }
98
+
99
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
100
+ });
101
+ };
102
+
103
+ var __generator = this && this.__generator || function (thisArg, body) {
104
+ var _ = {
105
+ label: 0,
106
+ sent: function sent() {
107
+ if (t[0] & 1) throw t[1];
108
+ return t[1];
109
+ },
110
+ trys: [],
111
+ ops: []
112
+ },
113
+ f,
114
+ y,
115
+ t,
116
+ g;
117
+ return g = {
118
+ next: verb(0),
119
+ "throw": verb(1),
120
+ "return": verb(2)
121
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
122
+ return this;
123
+ }), g;
124
+
125
+ function verb(n) {
126
+ return function (v) {
127
+ return step([n, v]);
128
+ };
129
+ }
130
+
131
+ function step(op) {
132
+ if (f) throw new TypeError("Generator is already executing.");
133
+
134
+ while (_) {
135
+ try {
136
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
137
+ if (y = 0, t) op = [op[0] & 2, t.value];
138
+
139
+ switch (op[0]) {
140
+ case 0:
141
+ case 1:
142
+ t = op;
143
+ break;
144
+
145
+ case 4:
146
+ _.label++;
147
+ return {
148
+ value: op[1],
149
+ done: false
150
+ };
151
+
152
+ case 5:
153
+ _.label++;
154
+ y = op[1];
155
+ op = [0];
156
+ continue;
157
+
158
+ case 7:
159
+ op = _.ops.pop();
160
+
161
+ _.trys.pop();
162
+
163
+ continue;
164
+
165
+ default:
166
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
167
+ _ = 0;
168
+ continue;
169
+ }
170
+
171
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
172
+ _.label = op[1];
173
+ break;
174
+ }
175
+
176
+ if (op[0] === 6 && _.label < t[1]) {
177
+ _.label = t[1];
178
+ t = op;
179
+ break;
180
+ }
181
+
182
+ if (t && _.label < t[2]) {
183
+ _.label = t[2];
184
+
185
+ _.ops.push(op);
186
+
187
+ break;
188
+ }
189
+
190
+ if (t[2]) _.ops.pop();
191
+
192
+ _.trys.pop();
193
+
194
+ continue;
195
+ }
196
+
197
+ op = body.call(thisArg, _);
198
+ } catch (e) {
199
+ op = [6, e];
200
+ y = 0;
201
+ } finally {
202
+ f = t = 0;
203
+ }
204
+ }
205
+
206
+ if (op[0] & 5) throw op[1];
207
+ return {
208
+ value: op[0] ? op[1] : void 0,
209
+ done: true
210
+ };
211
+ }
212
+ };
213
+
214
+ var __spreadArray = this && this.__spreadArray || function (to, from, pack) {
215
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
216
+ if (ar || !(i in from)) {
217
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
218
+ ar[i] = from[i];
219
+ }
220
+ }
221
+ return to.concat(ar || Array.prototype.slice.call(from));
222
+ };
223
+
224
+ var __importDefault = this && this.__importDefault || function (mod) {
225
+ return mod && mod.__esModule ? mod : {
226
+ "default": mod
227
+ };
228
+ };
229
+
230
+ Object.defineProperty(exports, "__esModule", {
231
+ value: true
232
+ });
233
+ exports.Generator = void 0;
234
+
235
+ var changeCase = __importStar(require("change-case"));
236
+
237
+ var dayjs_1 = __importDefault(require("dayjs"));
238
+
239
+ var fs_extra_1 = __importDefault(require("fs-extra"));
240
+
241
+ var path_1 = __importDefault(require("path"));
242
+
243
+ var conso = __importStar(require("./console"));
244
+
245
+ var got_1 = __importDefault(require("got"));
246
+
247
+ var swaggerJsonToYApiData_1 = require("./server/swaggerJsonToYApiData");
248
+
249
+ var os_1 = __importDefault(require("os"));
250
+
251
+ var vtils_1 = require("vtils");
252
+
253
+ var child_process_1 = require("child_process");
254
+
255
+ var utils_1 = require("./utils");
256
+
257
+ var genIndex_1 = __importDefault(require("./genIndex"));
258
+
259
+ var responseDataJsonSchemaHandler_1 = require("./responseDataJsonSchemaHandler");
260
+
261
+ var getOutputPath_1 = require("./getOutputPath");
262
+
263
+ var genRequest_1 = __importDefault(require("./genRequest")); // 默认顶部依赖生成模板
264
+
265
+
266
+ function defaultTopImportPkgTemplate(config) {
267
+ return "import request from '../request'";
268
+ }
269
+
270
+ var getDataKeySetStr = function getDataKeySetStr(method) {
271
+ if (['head', 'option', 'get'].includes(method.toLowerCase())) {
272
+ return 'params: data';
273
+ }
274
+
275
+ return 'data';
276
+ }; // 处理路劲参数
277
+
278
+
279
+ function handlePathParam(path) {
280
+ if (path.match(/\{(\w+)\}/)) {
281
+ // eslint-disable-next-line no-template-curly-in-string
282
+ return "`".concat(path.replace(/\{(\w+)\}/g, '${data.$1}'), "`");
283
+ }
284
+
285
+ return JSON.stringify(path);
286
+ } // 默认请求函数体生成模板
287
+
288
+
289
+ function defaultRequestFunctionTemplate(props, config) {
290
+ var requestFunctionExtraParams = (config || {}).requestFunctionExtraParams;
291
+ var baseURL = props.baseURL,
292
+ requestFunctionName = props.requestFunctionName,
293
+ requestDataTypeName = props.requestDataTypeName,
294
+ responseDataTypeName = props.responseDataTypeName,
295
+ extendedInterfaceInfo = props.extendedInterfaceInfo;
296
+ var req_params = extendedInterfaceInfo.req_params,
297
+ req_query = extendedInterfaceInfo.req_query;
298
+ var hasData = req_params.length || req_query.length;
299
+ var method = extendedInterfaceInfo.method.toLowerCase();
300
+ var finalBaseUrl = '';
301
+
302
+ if (baseURL === null || baseURL === void 0 ? void 0 : baseURL.match(/^\[code\]:/)) {
303
+ // 如果使用[code]开头则表示,作为代码段执行,否则仅作为字符串
304
+ finalBaseUrl = baseURL.replace(/^\[code\]:/, '');
305
+ } else {
306
+ finalBaseUrl = "\"".concat(baseURL, "\"");
307
+ }
308
+
309
+ return "export const ".concat(requestFunctionName, " = (data").concat(hasData ? '' : '?', ": ").concat(requestDataTypeName).concat(requestFunctionExtraParams ? ",extra?:Record<string,any>" : '', ") => {\n return request.").concat(method, "<").concat(requestDataTypeName, ",").concat(responseDataTypeName, ">(").concat(handlePathParam(extendedInterfaceInfo.path), ", {\n ").concat(getDataKeySetStr(method), ",\n ").concat(baseURL ? "baseURL: ".concat(finalBaseUrl, ",") : '', "\n ").concat(requestFunctionExtraParams ? "...extra" : '', "\n })\n }");
310
+ } // 后台统一网关函数体生成模板
311
+
312
+
313
+ function adminRequestFunctionTemplate(props, config) {
314
+ var _a;
315
+
316
+ var baseURL = props.baseURL,
317
+ requestFunctionName = props.requestFunctionName,
318
+ requestDataTypeName = props.requestDataTypeName,
319
+ responseDataTypeName = props.responseDataTypeName,
320
+ extendedInterfaceInfo = props.extendedInterfaceInfo;
321
+ var req_params = extendedInterfaceInfo.req_params,
322
+ req_query = extendedInterfaceInfo.req_query;
323
+ var hasData = req_params.length || req_query.length;
324
+ var finalBaseUrl = '';
325
+
326
+ if (baseURL === null || baseURL === void 0 ? void 0 : baseURL.match(/^\[code\]:/)) {
327
+ // 如果使用[code]开头则表示,作为代码段执行,否则仅作为字符串
328
+ finalBaseUrl = baseURL.replace(/^\[code\]:/, '');
329
+ } else {
330
+ finalBaseUrl = "\"".concat(baseURL, "\"");
331
+ }
332
+
333
+ var url = ((_a = config === null || config === void 0 ? void 0 : config.proxyInterface) === null || _a === void 0 ? void 0 : _a.path) || '/proxy';
334
+ return "export const ".concat(requestFunctionName, " = (data").concat(hasData ? '' : '?', ": ").concat(requestDataTypeName, ") => {\n return request.post<").concat(requestDataTypeName, ",").concat(responseDataTypeName, ">( '").concat(url, "', {\n data:{\n real_url: '").concat(extendedInterfaceInfo.path, "',\n params: data\n },\n ").concat(baseURL ? "baseURL: ".concat(finalBaseUrl) : '', "\n })\n }");
335
+ }
336
+
337
+ var Generator =
338
+ /** @class */
339
+ function () {
340
+ function Generator(config, options) {
341
+ if (options === void 0) {
342
+ options = {
343
+ cwd: process.cwd()
344
+ };
345
+ }
346
+
347
+ this.options = options;
348
+ this.disposes = []; // config 可能是对象或数组,统一为数组
349
+
350
+ this.config = config;
351
+ }
352
+
353
+ Generator.prototype.getOpenApiV3Json = function (url) {
354
+ return __awaiter(this, void 0, void 0, function () {
355
+ var res;
356
+ return __generator(this, function (_a) {
357
+ switch (_a.label) {
358
+ case 0:
359
+ return [4
360
+ /*yield*/
361
+ , got_1.default.get(url, {
362
+ responseType: 'json'
363
+ })];
364
+
365
+ case 1:
366
+ res = _a.sent();
367
+ return [2
368
+ /*return*/
369
+ , res.body];
370
+ }
371
+ });
372
+ });
373
+ };
374
+ /**
375
+ * 生成代码
376
+ * @returns
377
+ */
378
+
379
+
380
+ Generator.prototype.generate = function () {
381
+ return __awaiter(this, void 0, void 0, function () {
382
+ var outputFileList, _a, project, serverUrl, preproccessInterface, outputFilePath, filter, configIndex, name, typesName, openApiV3Json, componentsCode, allApi, interfaceList, categoryCode, categoryResponseDataJsonSchemaContent, _i, interfaceList_1, interfaceInfo, _b, code, responseDataJsonSchema, catOutputFilePath;
383
+
384
+ var _this = this;
385
+
386
+ return __generator(this, function (_c) {
387
+ switch (_c.label) {
388
+ case 0:
389
+ outputFileList = Object.create(null);
390
+ _a = this.config, project = _a.project, serverUrl = _a.serverUrl, preproccessInterface = _a.preproccessInterface, outputFilePath = _a.outputFilePath, filter = _a.filter, configIndex = _a.configIndex, name = _a.name;
391
+ typesName = name || '_types_' + (configIndex + 1);
392
+ return [4
393
+ /*yield*/
394
+ , this.getOpenApiV3Json(serverUrl)];
395
+
396
+ case 1:
397
+ openApiV3Json = _c.sent();
398
+ componentsCode = [];
399
+ return [4
400
+ /*yield*/
401
+ , Promise.all(Object.keys(openApiV3Json.components.schemas).map(function (key) {
402
+ return __awaiter(_this, void 0, void 0, function () {
403
+ var code;
404
+ return __generator(this, function (_a) {
405
+ switch (_a.label) {
406
+ case 0:
407
+ return [4
408
+ /*yield*/
409
+ , (0, utils_1.jsonSchemaToTsCode)(__assign(__assign({}, openApiV3Json.components.schemas[key]), {
410
+ components: openApiV3Json.components
411
+ }), key)];
412
+
413
+ case 1:
414
+ code = _a.sent();
415
+ componentsCode.push(code);
416
+ return [2
417
+ /*return*/
418
+ ];
419
+ }
420
+ });
421
+ });
422
+ }))];
423
+
424
+ case 2:
425
+ _c.sent();
426
+
427
+ return [4
428
+ /*yield*/
429
+ , (0, swaggerJsonToYApiData_1.swaggerJsonToYApiData)(openApiV3Json)];
430
+
431
+ case 3:
432
+ allApi = _c.sent();
433
+ interfaceList = allApi.interfaces;
434
+ categoryCode = __spreadArray([], componentsCode, true);
435
+ categoryResponseDataJsonSchemaContent = [];
436
+ _i = 0, interfaceList_1 = interfaceList;
437
+ _c.label = 4;
438
+
439
+ case 4:
440
+ if (!(_i < interfaceList_1.length)) return [3
441
+ /*break*/
442
+ , 7];
443
+ interfaceInfo = interfaceList_1[_i];
444
+ return [4
445
+ /*yield*/
446
+ , this.generateInterfaceCode(__assign(__assign(__assign({}, this.config), project), {
447
+ components: openApiV3Json.components
448
+ }), interfaceInfo)];
449
+
450
+ case 5:
451
+ _b = _c.sent(), code = _b.code, responseDataJsonSchema = _b.responseDataJsonSchema;
452
+ categoryCode.push(code);
453
+ categoryResponseDataJsonSchemaContent.push(responseDataJsonSchema);
454
+ _c.label = 6;
455
+
456
+ case 6:
457
+ _i++;
458
+ return [3
459
+ /*break*/
460
+ , 4];
461
+
462
+ case 7:
463
+ catOutputFilePath = (0, getOutputPath_1.getOutputFilePath)(this.config, "/".concat(typesName, ".ts"));
464
+
465
+ if (categoryCode.length > 0) {
466
+ outputFileList[catOutputFilePath] = {
467
+ projectId: typesName,
468
+ categoryId: typesName,
469
+ syntheticalConfig: this.config,
470
+ content: categoryCode,
471
+ outputResponseDataJsonSchemaFilePath: (0, getOutputPath_1.getOutputFilePath)(this.config, "/".concat(typesName, "/responseDataJsonSchema.ts")),
472
+ responseDataJsonSchemaContent: categoryResponseDataJsonSchemaContent,
473
+ requestFunctionFilePath: this.config.requestFunctionFilePath ? path_1.default.resolve(this.options.cwd, this.config.requestFunctionFilePath) : path_1.default.join(path_1.default.dirname(catOutputFilePath), 'request.ts'),
474
+ requestHookMakerFilePath: ''
475
+ };
476
+ }
477
+
478
+ return [2
479
+ /*return*/
480
+ , outputFileList];
481
+ }
482
+ });
483
+ });
484
+ };
485
+ /**
486
+ * 写入文件
487
+ * @param outputFileList
488
+ * @returns
489
+ */
490
+
491
+
492
+ Generator.prototype.write = function (outputFileList) {
493
+ return __awaiter(this, void 0, void 0, function () {
494
+ var JsonSchemaContentList, projects, config, outputContent;
495
+
496
+ var _this = this;
497
+
498
+ return __generator(this, function (_a) {
499
+ switch (_a.label) {
500
+ case 0:
501
+ JsonSchemaContentList = [];
502
+ projects = [];
503
+ Object.keys(outputFileList).forEach(function (filePath) {
504
+ var item = outputFileList[filePath];
505
+ JsonSchemaContentList.push(item.responseDataJsonSchemaContent.join('\n'));
506
+ projects.push({
507
+ projectId: item.projectId
508
+ });
509
+ });
510
+ config = this.config || {}; // config.getRequestFunctionName;
511
+ // this.requestFunctionNameGen;
512
+ // 生成 request.ts
513
+
514
+ return [4
515
+ /*yield*/
516
+ , (0, genRequest_1.default)(config)];
517
+
518
+ case 1:
519
+ // config.getRequestFunctionName;
520
+ // this.requestFunctionNameGen;
521
+ // 生成 request.ts
522
+ _a.sent(); // 生成入口 index.ts
523
+
524
+
525
+ return [4
526
+ /*yield*/
527
+ , (0, genIndex_1.default)(config, projects)];
528
+
529
+ case 2:
530
+ // 生成入口 index.ts
531
+ _a.sent();
532
+
533
+ outputContent = '';
534
+ return [2
535
+ /*return*/
536
+ , Promise.all(Object.keys(outputFileList).map(function (outputFilePath, index) {
537
+ return __awaiter(_this, void 0, void 0, function () {
538
+ var _a, content, requestFunctionFilePath, requestHookMakerFilePath, syntheticalConfig, outputResponseDataJsonSchemaFilePath, responseDataJsonSchemaContent, topImportPkgTemplate, rawOutputContent;
539
+
540
+ return __generator(this, function (_b) {
541
+ switch (_b.label) {
542
+ case 0:
543
+ _a = outputFileList[outputFilePath], content = _a.content, requestFunctionFilePath = _a.requestFunctionFilePath, requestHookMakerFilePath = _a.requestHookMakerFilePath, syntheticalConfig = _a.syntheticalConfig, outputResponseDataJsonSchemaFilePath = _a.outputResponseDataJsonSchemaFilePath, responseDataJsonSchemaContent = _a.responseDataJsonSchemaContent; // 支持 .jsx? 后缀
544
+
545
+ outputFilePath = outputFilePath.replace(/\.js(x)?$/, '.ts$1');
546
+ requestFunctionFilePath = requestFunctionFilePath.replace(/\.js(x)?$/, '.ts$1');
547
+ requestHookMakerFilePath = requestHookMakerFilePath.replace(/\.js(x)?$/, '.ts$1');
548
+ topImportPkgTemplate = syntheticalConfig.topImportPkgTemplate || defaultTopImportPkgTemplate;
549
+ rawOutputContent = (0, vtils_1.dedent)(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n ", "\n ", "\n\n ", "\n "], ["\n ", "\n ", "\n\n ", "\n "])), (0, utils_1.topNotesContent)(), topImportPkgTemplate(config), content.join('\n\n').trim());
550
+ outputContent += (0, utils_1.formatContent)((0, vtils_1.dedent)(templateObject_2 || (templateObject_2 = __makeTemplateObject(["", ""], ["", ""])), rawOutputContent), config.prettierConfigPath);
551
+ if (!(Object.keys(outputFileList).length - 1 === index)) return [3
552
+ /*break*/
553
+ , 2];
554
+ return [4
555
+ /*yield*/
556
+ , fs_extra_1.default.outputFile(outputFilePath, outputContent)];
557
+
558
+ case 1:
559
+ _b.sent();
560
+
561
+ _b.label = 2;
562
+
563
+ case 2:
564
+ if (!(syntheticalConfig.target === 'javascript')) return [3
565
+ /*break*/
566
+ , 5];
567
+ return [4
568
+ /*yield*/
569
+ , this.tsc(outputFilePath)];
570
+
571
+ case 3:
572
+ _b.sent();
573
+
574
+ return [4
575
+ /*yield*/
576
+ , Promise.all([fs_extra_1.default.remove(requestFunctionFilePath).catch(vtils_1.noop), fs_extra_1.default.remove(requestHookMakerFilePath).catch(vtils_1.noop), fs_extra_1.default.remove(outputFilePath).catch(vtils_1.noop)])];
577
+
578
+ case 4:
579
+ _b.sent();
580
+
581
+ _b.label = 5;
582
+
583
+ case 5:
584
+ return [2
585
+ /*return*/
586
+ ];
587
+ }
588
+ });
589
+ });
590
+ }))];
591
+ }
592
+ });
593
+ });
594
+ };
595
+
596
+ Generator.prototype.tsc = function (file) {
597
+ return __awaiter(this, void 0, void 0, function () {
598
+ var _this = this;
599
+
600
+ return __generator(this, function (_a) {
601
+ return [2
602
+ /*return*/
603
+ , new Promise(function (resolve) {
604
+ // add this to fix bug that not-generator-file-on-window
605
+ var command = "".concat(os_1.default.platform() === 'win32' ? 'node ' : '').concat(require.resolve("typescript/bin/tsc"));
606
+ (0, child_process_1.exec)("".concat(command, " --target ES2019 --module ESNext --jsx preserve --declaration --esModuleInterop ").concat(file), {
607
+ cwd: _this.options.cwd,
608
+ env: process.env
609
+ }, function () {
610
+ return resolve();
611
+ });
612
+ })];
613
+ });
614
+ });
615
+ };
616
+ /** 请求函数名生成 */
617
+
618
+
619
+ Generator.prototype.requestFunctionNameGen = function (extendedInterfaceInfo) {
620
+ var path = extendedInterfaceInfo.parsedPath.dir;
621
+ var method = extendedInterfaceInfo.method; // 可能存在同path,不同method的用法
622
+
623
+ var words = __spreadArray(__spreadArray([method], path.split('/'), true), [extendedInterfaceInfo.parsedPath.name], false).join('_');
624
+
625
+ return changeCase.camelCase(words);
626
+ };
627
+ /** 生成接口代码 */
628
+
629
+
630
+ Generator.prototype.generateInterfaceCode = function (syntheticalConfig, interfaceInfo) {
631
+ return __awaiter(this, void 0, void 0, function () {
632
+ var extendedInterfaceInfo, requestFunctionName, _a, requestConfigName, requestConfigTypeName, requestDataTypeName, _b, responseDataTypeName, _c, requestDataJsonSchema, requestDataType, responseDataJsonSchema, responseDataType, isRequestDataOptional, requestHookName, _d, _e, paramNames, paramNamesLiteral, paramNameType, queryNames, queryNamesLiteral, queryNameType, genComment, requestFunctionTemplate, baseURL, baseUrl, code;
633
+
634
+ return __generator(this, function (_f) {
635
+ switch (_f.label) {
636
+ case 0:
637
+ extendedInterfaceInfo = __assign(__assign({}, interfaceInfo), {
638
+ parsedPath: path_1.default.parse(interfaceInfo.path)
639
+ });
640
+ if (!(0, vtils_1.isFunction)(syntheticalConfig.getRequestFunctionName)) return [3
641
+ /*break*/
642
+ , 2];
643
+ return [4
644
+ /*yield*/
645
+ , syntheticalConfig.getRequestFunctionName(extendedInterfaceInfo, changeCase)];
646
+
647
+ case 1:
648
+ _a = _f.sent();
649
+ return [3
650
+ /*break*/
651
+ , 3];
652
+
653
+ case 2:
654
+ _a = this.requestFunctionNameGen(extendedInterfaceInfo);
655
+ _f.label = 3;
656
+
657
+ case 3:
658
+ requestFunctionName = _a;
659
+ requestConfigName = changeCase.camelCase("".concat(requestFunctionName, "RequestConfig"));
660
+ requestConfigTypeName = changeCase.pascalCase(requestConfigName);
661
+ if (!(0, vtils_1.isFunction)(syntheticalConfig.getRequestDataTypeName)) return [3
662
+ /*break*/
663
+ , 5];
664
+ return [4
665
+ /*yield*/
666
+ , syntheticalConfig.getRequestDataTypeName(extendedInterfaceInfo, changeCase)];
667
+
668
+ case 4:
669
+ _b = _f.sent();
670
+ return [3
671
+ /*break*/
672
+ , 6];
673
+
674
+ case 5:
675
+ _b = changeCase.pascalCase("".concat(requestFunctionName, "Request"));
676
+ _f.label = 6;
677
+
678
+ case 6:
679
+ requestDataTypeName = _b;
680
+ if (!(0, vtils_1.isFunction)(syntheticalConfig.getResponseDataTypeName)) return [3
681
+ /*break*/
682
+ , 8];
683
+ return [4
684
+ /*yield*/
685
+ , syntheticalConfig.getResponseDataTypeName(extendedInterfaceInfo, changeCase)];
686
+
687
+ case 7:
688
+ _c = _f.sent();
689
+ return [3
690
+ /*break*/
691
+ , 9];
692
+
693
+ case 8:
694
+ _c = changeCase.pascalCase("".concat(requestFunctionName, "Response"));
695
+ _f.label = 9;
696
+
697
+ case 9:
698
+ responseDataTypeName = _c;
699
+ requestDataJsonSchema = (0, utils_1.getRequestDataJsonSchema)(extendedInterfaceInfo);
700
+ return [4
701
+ /*yield*/
702
+ , (0, utils_1.jsonSchemaToTsCode)(__assign(__assign({}, requestDataJsonSchema), {
703
+ components: syntheticalConfig.components
704
+ }), requestDataTypeName)];
705
+
706
+ case 10:
707
+ requestDataType = _f.sent();
708
+
709
+ if (interfaceInfo.path.includes('/path')) {
710
+ console.log(requestDataType);
711
+ }
712
+
713
+ responseDataJsonSchema = (0, utils_1.getResponseDataJsonSchema)(extendedInterfaceInfo, syntheticalConfig.dataKey);
714
+ return [4
715
+ /*yield*/
716
+ , (0, utils_1.jsonSchemaToTsCode)(__assign(__assign({}, responseDataJsonSchema), {
717
+ components: syntheticalConfig.components
718
+ }), responseDataTypeName)];
719
+
720
+ case 11:
721
+ responseDataType = _f.sent();
722
+
723
+ if (interfaceInfo.path.includes('/path')) {
724
+ console.log(requestDataType);
725
+ }
726
+
727
+ isRequestDataOptional = /(\{\}|any)$/.test(requestDataType);
728
+ if (!(syntheticalConfig.reactHooks && syntheticalConfig.reactHooks.enabled)) return [3
729
+ /*break*/
730
+ , 15];
731
+ if (!(0, vtils_1.isFunction)(syntheticalConfig.reactHooks.getRequestHookName)) return [3
732
+ /*break*/
733
+ , 13];
734
+ return [4
735
+ /*yield*/
736
+ , syntheticalConfig.reactHooks.getRequestHookName(extendedInterfaceInfo, changeCase)];
737
+
738
+ case 12:
739
+ _e = _f.sent();
740
+ return [3
741
+ /*break*/
742
+ , 14];
743
+
744
+ case 13:
745
+ _e = "use".concat(changeCase.pascalCase(requestFunctionName));
746
+ _f.label = 14;
747
+
748
+ case 14:
749
+ _d = _e;
750
+ return [3
751
+ /*break*/
752
+ , 16];
753
+
754
+ case 15:
755
+ _d = '';
756
+ _f.label = 16;
757
+
758
+ case 16:
759
+ requestHookName = _d;
760
+ paramNames = (extendedInterfaceInfo.req_params
761
+ /* istanbul ignore next */
762
+ || []).map(function (item) {
763
+ return item.name;
764
+ });
765
+ paramNamesLiteral = JSON.stringify(paramNames);
766
+ paramNameType = paramNames.length === 0 ? 'string' : "'".concat(paramNames.join("' | '"), "'");
767
+ queryNames = (extendedInterfaceInfo.req_query
768
+ /* istanbul ignore next */
769
+ || []).map(function (item) {
770
+ return item.name;
771
+ });
772
+ queryNamesLiteral = JSON.stringify(queryNames);
773
+ queryNameType = queryNames.length === 0 ? 'string' : "'".concat(queryNames.join("' | '"), "'");
774
+
775
+ genComment = function genComment(genTitle) {
776
+ var _a = __assign(__assign({}, syntheticalConfig.comment), {
777
+ // Swagger 时总是禁用标签、更新时间、链接
778
+ tag: false,
779
+ updateTime: false,
780
+ link: false
781
+ }),
782
+ _b = _a.enabled,
783
+ isEnabled = _b === void 0 ? true : _b,
784
+ _c = _a.title,
785
+ hasTitle = _c === void 0 ? true : _c,
786
+ _d = _a.category,
787
+ hasCategory = _d === void 0 ? true : _d,
788
+ _e = _a.tag,
789
+ hasTag = _e === void 0 ? true : _e,
790
+ _f = _a.requestHeader,
791
+ hasRequestHeader = _f === void 0 ? true : _f,
792
+ _g = _a.updateTime,
793
+ hasUpdateTime = _g === void 0 ? true : _g,
794
+ _h = _a.link,
795
+ hasLink = _h === void 0 ? true : _h;
796
+
797
+ if (!isEnabled) {
798
+ return '';
799
+ } // 转义标题中的 /
800
+
801
+
802
+ var escapedTitle = String(extendedInterfaceInfo.title).replace(/\//g, '\\/');
803
+ var description = hasLink ? "[".concat(escapedTitle, "\u2197](").concat(syntheticalConfig.serverUrl, "/project/").concat(extendedInterfaceInfo.project_id, "/interface/api/").concat(extendedInterfaceInfo._id, ")") : escapedTitle;
804
+ var summary = [// hasCategory && {
805
+ // label: '分类',
806
+ // value: hasLink
807
+ // ? `[${extendedInterfaceInfo._category.name}↗](${syntheticalConfig.serverUrl}/project/${extendedInterfaceInfo.project_id}/interface/api/cat_${extendedInterfaceInfo.catid})`
808
+ // : extendedInterfaceInfo._category.name
809
+ // },
810
+ hasTag && {
811
+ label: '标签',
812
+ value: extendedInterfaceInfo.tag.map(function (tag) {
813
+ return "`".concat(tag, "`");
814
+ })
815
+ }, hasRequestHeader && {
816
+ label: '请求头',
817
+ value: "`".concat(extendedInterfaceInfo.method.toUpperCase(), " ").concat(extendedInterfaceInfo.path, "`")
818
+ }, hasUpdateTime && {
819
+ label: '更新时间',
820
+ value: process.env.JEST_WORKER_ID // 测试时使用 unix 时间戳
821
+ ? String(extendedInterfaceInfo.up_time) :
822
+ /* istanbul ignore next */
823
+ "`".concat((0, dayjs_1.default)(extendedInterfaceInfo.up_time * 1000).format('YYYY-MM-DD HH:mm:ss'), "`")
824
+ }];
825
+ var titleComment = hasTitle ? (0, vtils_1.dedent)(templateObject_3 || (templateObject_3 = __makeTemplateObject(["\n * ", "\n *\n "], ["\n * ", "\n *\n "])), genTitle(description)) : '';
826
+ var extraComment = summary.filter(function (item) {
827
+ return typeof item !== 'boolean' && !(0, vtils_1.isEmpty)(item.value);
828
+ }).map(function (item) {
829
+ var _item = item;
830
+ return "* @".concat(_item.label, " ").concat((0, vtils_1.castArray)(_item.value).join(', '));
831
+ }).join('\n');
832
+ return (0, vtils_1.dedent)(templateObject_4 || (templateObject_4 = __makeTemplateObject(["\n /**\n ", "\n */\n "], ["\n /**\n ", "\n */\n "])), [titleComment].filter(Boolean).join('\n'));
833
+ };
834
+
835
+ requestFunctionTemplate = syntheticalConfig.requestFunctionTemplate || (syntheticalConfig.proxyInterface ? adminRequestFunctionTemplate : defaultRequestFunctionTemplate);
836
+ baseURL = syntheticalConfig.baseURL;
837
+
838
+ try {
839
+ baseUrl = typeof baseURL === 'string' ? baseURL : typeof baseURL === 'function' ? baseURL(extendedInterfaceInfo.path) : '';
840
+ } catch (e) {
841
+ conso.error(e);
842
+ }
843
+
844
+ code = (0, vtils_1.dedent)(templateObject_6 || (templateObject_6 = __makeTemplateObject(["\n ", "\n ", "\n\n ", "\n ", "\n\n ", "\n "], ["\n ", "\n ", "\n\n ", "\n ", "\n\n ", "\n "])), genComment(function (title) {
845
+ return "".concat(title, " \u8BF7\u6C42\u53C2\u6570");
846
+ }), requestDataType.trim(), genComment(function (title) {
847
+ return "".concat(title, " \u54CD\u5E94\u6570\u636E");
848
+ }), responseDataType.trim(), syntheticalConfig.typesOnly ? '' : (0, vtils_1.dedent)(templateObject_5 || (templateObject_5 = __makeTemplateObject(["\n ", "\n ", "\n\n "], ["\n ", "\n ", "\n\n "])), genComment(function (title) {
849
+ return "".concat(title);
850
+ }), requestFunctionTemplate({
851
+ baseURL: baseUrl,
852
+ requestFunctionName: requestFunctionName,
853
+ requestDataTypeName: requestDataTypeName,
854
+ responseDataTypeName: responseDataTypeName,
855
+ extendedInterfaceInfo: extendedInterfaceInfo
856
+ }, syntheticalConfig)));
857
+ return [2
858
+ /*return*/
859
+ , {
860
+ code: code,
861
+ responseDataJsonSchema: (0, responseDataJsonSchemaHandler_1.genJsonSchemeConstContent)(extendedInterfaceInfo.path, syntheticalConfig.serverUrl || '', extendedInterfaceInfo, responseDataJsonSchema)
862
+ }];
863
+ }
864
+ });
865
+ });
866
+ };
867
+
868
+ Generator.prototype.destroy = function () {
869
+ return __awaiter(this, void 0, void 0, function () {
870
+ var _this = this;
871
+
872
+ return __generator(this, function (_a) {
873
+ return [2
874
+ /*return*/
875
+ , Promise.all(this.disposes.map(function (dispose) {
876
+ return __awaiter(_this, void 0, void 0, function () {
877
+ return __generator(this, function (_a) {
878
+ return [2
879
+ /*return*/
880
+ , dispose()];
881
+ });
882
+ });
883
+ }))];
884
+ });
885
+ });
886
+ };
887
+
888
+ return Generator;
889
+ }();
890
+
891
+ exports.Generator = Generator;
892
+ var templateObject_1, templateObject_2, templateObject_3, templateObject_4, templateObject_5, templateObject_6;