yapi-apifox-to-typescript 4.2.3 → 5.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.
@@ -1,1155 +1,512 @@
1
- import _taggedTemplateLiteralLoose from "@babel/runtime/helpers/esm/taggedTemplateLiteralLoose";
2
- import _createForOfIteratorHelperLoose from "@babel/runtime/helpers/esm/createForOfIteratorHelperLoose";
3
- import _extends from "@babel/runtime/helpers/esm/extends";
4
- import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
5
-
6
- var _templateObject, _templateObject2, _templateObject3, _templateObject4, _templateObject5, _templateObject6, _templateObject7, _templateObject8, _templateObject9, _templateObject10, _templateObject11, _templateObject12;
7
-
8
- import _regeneratorRuntime from "@babel/runtime/regenerator";
9
- import * as changeCase from 'change-case';
10
- import dayjs from 'dayjs';
11
- import fs from 'fs-extra';
12
- import path from 'path';
13
- import { ApifoxToYApiData } from './ApifoxToYApiData';
14
- import { castArray, cloneDeepFast, dedent, groupBy, isEmpty, isFunction, last, memoize, noop, omit, uniq, values } from 'vtils';
15
- import { Method, RequestBodyType } from './types';
16
- import { exec } from 'child_process';
17
- import { getCachedPrettierOptions, getFilteredCat, getNormalizedRelativePath, getPrettier, getRequestDataJsonSchema, getResponseDataJsonSchema, httpGet, jsonSchemaToType, sortByWeights, throwError } from './utils';
18
- import { SwaggerToYApiServer } from './SwaggerToYApiServer';
19
-
1
+ import { __require } from "./_virtual/_rolldown/runtime.js";
2
+ import { Method, RequestBodyType } from "./types.js";
3
+ import { castArray, cloneDeepFast, dedent, groupBy, isEmpty, isFunction, last, memoize, noop, omit, uniq, values } from "./mini-ut.js";
4
+ import { getCachedPrettierOptions, getFilteredCat, getNormalizedRelativePath, getPrettier, getRequestDataJsonSchema, getResponseDataJsonSchema, httpGet, jsonSchemaToType, sortByWeights, throwError } from "./utils.js";
5
+ import { ApifoxToYApiData } from "./ApifoxToYApiData.js";
6
+ import { SwaggerToYApiServer } from "./SwaggerToYApiServer.js";
7
+ import fs from "fs-extra";
8
+ import path from "path";
9
+ import * as changeCase from "change-case";
10
+ import dayjs from "dayjs";
11
+ import { exec } from "child_process";
12
+ //#region src/Generator.ts
20
13
  /**
21
- * @see https://webpack.js.org/guides/tree-shaking/#mark-a-function-call-as-side-effect-free
22
- * @see https://terser.org/docs/api-reference.html#annotations
23
- */
24
- var COMPRESSOR_TREE_SHAKING_ANNOTATION = '/*#__PURE__*/';
25
- export var Generator = /*#__PURE__*/function () {
26
- /** 配置 */
27
- function Generator(config, options) {
28
- var _this = this;
29
-
30
- if (options === void 0) {
31
- options = {
32
- cwd: process.cwd()
33
- };
34
- }
35
-
36
- this.options = options;
37
- this.config = [];
38
- this.disposes = [];
39
- this.fetchProject = memoize( /*#__PURE__*/function () {
40
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref) {
41
- var serverUrl, token, projectInfo, basePath;
42
- return _regeneratorRuntime.wrap(function _callee$(_context) {
43
- while (1) {
44
- switch (_context.prev = _context.next) {
45
- case 0:
46
- serverUrl = _ref.serverUrl, token = _ref.token;
47
- _context.next = 3;
48
- return _this.fetchApi(serverUrl + "/api/project/get", {
49
- token: token
50
- });
51
-
52
- case 3:
53
- projectInfo = _context.sent;
54
- basePath = ("/" + (projectInfo.basepath || '/')).replace(/\/+$/, '').replace(/^\/+/, '/');
55
- projectInfo.basepath = basePath; // 实现项目在 YApi 上的地址
56
-
57
- projectInfo._url = serverUrl + "/project/" + projectInfo._id + "/interface/api";
58
- return _context.abrupt("return", projectInfo);
59
-
60
- case 8:
61
- case "end":
62
- return _context.stop();
63
- }
64
- }
65
- }, _callee);
66
- }));
67
-
68
- return function (_x) {
69
- return _ref2.apply(this, arguments);
70
- };
71
- }(), function (_ref3) {
72
- var serverUrl = _ref3.serverUrl,
73
- token = _ref3.token;
74
- return serverUrl + "|" + token;
75
- });
76
- this.fetchExport = memoize( /*#__PURE__*/function () {
77
- var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(_ref4) {
78
- var serverUrl, token, projectInfo, categoryList;
79
- return _regeneratorRuntime.wrap(function _callee2$(_context2) {
80
- while (1) {
81
- switch (_context2.prev = _context2.next) {
82
- case 0:
83
- serverUrl = _ref4.serverUrl, token = _ref4.token;
84
- _context2.next = 3;
85
- return _this.fetchProject({
86
- serverUrl: serverUrl,
87
- token: token
88
- });
89
-
90
- case 3:
91
- projectInfo = _context2.sent;
92
- _context2.next = 6;
93
- return _this.fetchApi(serverUrl + "/api/plugin/export", {
94
- type: 'json',
95
- status: 'all',
96
- isWiki: 'false',
97
- token: token
98
- });
99
-
100
- case 6:
101
- categoryList = _context2.sent;
102
- return _context2.abrupt("return", categoryList.map(function (cat) {
103
- var _cat$list, _cat$list$, _cat$list2, _cat$list2$;
104
-
105
- var projectId = ((_cat$list = cat.list) == null ? void 0 : (_cat$list$ = _cat$list[0]) == null ? void 0 : _cat$list$.project_id) || 0;
106
- var catId = ((_cat$list2 = cat.list) == null ? void 0 : (_cat$list2$ = _cat$list2[0]) == null ? void 0 : _cat$list2$.catid) || 0; // 实现分类在 YApi 上的地址
107
-
108
- // 实现分类在 YApi 上的地址
109
- cat._url = serverUrl + "/project/" + projectId + "/interface/api/cat_" + catId;
110
- cat.list = (cat.list || []).map(function (item) {
111
- var interfaceId = item._id; // 实现接口在 YApi 上的地址
112
-
113
- // 实现接口在 YApi 上的地址
114
- item._url = serverUrl + "/project/" + projectId + "/interface/api/" + interfaceId;
115
- item.path = "" + projectInfo.basepath + item.path;
116
- return item;
117
- });
118
- return cat;
119
- }));
120
-
121
- case 8:
122
- case "end":
123
- return _context2.stop();
124
- }
125
- }
126
- }, _callee2);
127
- }));
128
-
129
- return function (_x2) {
130
- return _ref5.apply(this, arguments);
131
- };
132
- }(), function (_ref6) {
133
- var serverUrl = _ref6.serverUrl,
134
- token = _ref6.token;
135
- return serverUrl + "|" + token;
136
- });
137
- // config 可能是对象或数组,统一为数组
138
- this.config = castArray(config);
139
- }
140
-
141
- var _proto = Generator.prototype;
142
-
143
- _proto.prepare = /*#__PURE__*/function () {
144
- var _prepare = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() {
145
- var _this2 = this;
146
-
147
- return _regeneratorRuntime.wrap(function _callee4$(_context4) {
148
- while (1) {
149
- switch (_context4.prev = _context4.next) {
150
- case 0:
151
- _context4.next = 2;
152
- return Promise.all( // config 可能是对象或数组,统一为数组
153
- this.config.map( /*#__PURE__*/function () {
154
- var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(item) {
155
- var swaggerToYApiServer;
156
- return _regeneratorRuntime.wrap(function _callee3$(_context3) {
157
- while (1) {
158
- switch (_context3.prev = _context3.next) {
159
- case 0:
160
- if (!(item.serverType === 'swagger')) {
161
- _context3.next = 6;
162
- break;
163
- }
164
-
165
- swaggerToYApiServer = new SwaggerToYApiServer({
166
- swaggerJsonUrl: item.serverUrl
167
- });
168
- _context3.next = 4;
169
- return swaggerToYApiServer.start();
170
-
171
- case 4:
172
- item.serverUrl = _context3.sent;
173
-
174
- _this2.disposes.push(function () {
175
- return swaggerToYApiServer.stop();
176
- });
177
-
178
- case 6:
179
- if (item.serverUrl) {
180
- // 去除地址后面的 /
181
- // fix: https://github.com/fjc0k/yapi-to-typescript/issues/22
182
- item.serverUrl = item.serverUrl.replace(/\/+$/, '');
183
- }
184
-
185
- return _context3.abrupt("return", item);
186
-
187
- case 8:
188
- case "end":
189
- return _context3.stop();
190
- }
191
- }
192
- }, _callee3);
193
- }));
194
-
195
- return function (_x3) {
196
- return _ref7.apply(this, arguments);
197
- };
198
- }()));
199
-
200
- case 2:
201
- this.config = _context4.sent;
202
-
203
- case 3:
204
- case "end":
205
- return _context4.stop();
206
- }
207
- }
208
- }, _callee4, this);
209
- }));
210
-
211
- function prepare() {
212
- return _prepare.apply(this, arguments);
213
- }
214
-
215
- return prepare;
216
- }();
217
-
218
- _proto.generate = /*#__PURE__*/function () {
219
- var _generate = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10() {
220
- var _this3 = this;
221
-
222
- var outputFileList;
223
- return _regeneratorRuntime.wrap(function _callee10$(_context10) {
224
- while (1) {
225
- switch (_context10.prev = _context10.next) {
226
- case 0:
227
- outputFileList = Object.create(null);
228
- _context10.next = 3;
229
- return Promise.all(this.config.map( /*#__PURE__*/function () {
230
- var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(serverConfig, serverIndex) {
231
- var projects;
232
- return _regeneratorRuntime.wrap(function _callee9$(_context9) {
233
- while (1) {
234
- switch (_context9.prev = _context9.next) {
235
- case 0:
236
- projects = serverConfig.projects.reduce(function (projects, project) {
237
- projects.push.apply(projects, castArray(project.token).map(function (token) {
238
- return _extends({}, project, {
239
- token: token
240
- });
241
- }));
242
- return projects;
243
- }, []);
244
- return _context9.abrupt("return", Promise.all(projects.map( /*#__PURE__*/function () {
245
- var _ref9 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(projectConfig, projectIndex) {
246
- var projectInfo, apifoxInstance;
247
- return _regeneratorRuntime.wrap(function _callee8$(_context8) {
248
- while (1) {
249
- switch (_context8.prev = _context8.next) {
250
- case 0:
251
- apifoxInstance = null;
252
-
253
- if (!(serverConfig.serverType === 'apifox')) {
254
- _context8.next = 10;
255
- break;
256
- }
257
-
258
- if (projectConfig.projectId) {
259
- _context8.next = 4;
260
- break;
261
- }
262
-
263
- throw new Error('projectId is required when serverType is apifox');
264
-
265
- case 4:
266
- apifoxInstance = new ApifoxToYApiData({
267
- token: projectConfig.token,
268
- projectId: projectConfig.projectId,
269
- categories: projectConfig.categories,
270
- serverUrl: serverConfig.serverUrl,
271
- addFoldersToTags: projectConfig.addFoldersToTags,
272
- oasVersion: projectConfig.oasVersion,
273
- exportFormat: projectConfig.exportFormat
274
- });
275
- _context8.next = 7;
276
- return apifoxInstance.getProjectInfo();
277
-
278
- case 7:
279
- projectInfo = _context8.sent;
280
- _context8.next = 13;
281
- break;
282
-
283
- case 10:
284
- _context8.next = 12;
285
- return _this3.fetchProjectInfo(_extends({}, serverConfig, projectConfig));
286
-
287
- case 12:
288
- projectInfo = _context8.sent;
289
-
290
- case 13:
291
- _context8.next = 15;
292
- return Promise.all(projectConfig.categories.map( /*#__PURE__*/function () {
293
- var _ref10 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(categoryConfig, categoryIndex) {
294
- var categoryIds, codes, _iterator, _step, _outputFileList$group, groupedCodes;
295
-
296
- return _regeneratorRuntime.wrap(function _callee7$(_context7) {
297
- while (1) {
298
- switch (_context7.prev = _context7.next) {
299
- case 0:
300
- categoryIds = [];
301
-
302
- if (serverConfig.serverType === 'apifox' && apifoxInstance) {
303
- categoryIds = apifoxInstance.getCats(categoryConfig);
304
- } else {
305
- categoryIds = getFilteredCat(categoryConfig, projectInfo.cats);
306
- }
307
-
308
- _context7.next = 4;
309
- return Promise.all(categoryIds.map( /*#__PURE__*/function () {
310
- var _ref11 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(id, categoryIndex2) {
311
- var syntheticalConfig, interfaceList, interfaceCodes, groupedInterfaceCodes;
312
- return _regeneratorRuntime.wrap(function _callee6$(_context6) {
313
- while (1) {
314
- switch (_context6.prev = _context6.next) {
315
- case 0:
316
- categoryConfig = _extends({}, categoryConfig, {
317
- id: id
318
- });
319
- syntheticalConfig = _extends({}, serverConfig, projectConfig, categoryConfig, {
320
- mockUrl: projectInfo.getMockUrl()
321
- });
322
- syntheticalConfig.target = syntheticalConfig.target || 'typescript';
323
- syntheticalConfig.devUrl = projectInfo.getDevUrl(syntheticalConfig.devEnvName);
324
- syntheticalConfig.prodUrl = projectInfo.getProdUrl(syntheticalConfig.prodEnvName); // 接口列表
325
-
326
- // 接口列表
327
- interfaceList = [];
328
-
329
- if (!(syntheticalConfig.serverType === 'apifox' && apifoxInstance)) {
330
- _context6.next = 12;
331
- break;
332
- }
333
-
334
- _context6.next = 9;
335
- return apifoxInstance.getInterfaceList(syntheticalConfig);
336
-
337
- case 9:
338
- interfaceList = _context6.sent;
339
- _context6.next = 15;
340
- break;
341
-
342
- case 12:
343
- _context6.next = 14;
344
- return _this3.fetchInterfaceList(syntheticalConfig);
345
-
346
- case 14:
347
- interfaceList = _context6.sent;
348
-
349
- case 15:
350
- interfaceList = interfaceList.map(function (interfaceInfo) {
351
- // 实现 _project 字段
352
- interfaceInfo._project = omit(projectInfo, ['cats', 'getMockUrl', 'getDevUrl', 'getProdUrl']); // 预处理
353
-
354
- // 预处理
355
- var _interfaceInfo = isFunction(syntheticalConfig.preproccessInterface) ? syntheticalConfig.preproccessInterface(cloneDeepFast(interfaceInfo), changeCase, syntheticalConfig) : interfaceInfo;
356
-
357
- return _interfaceInfo;
358
- }).filter(Boolean);
359
- interfaceList.sort(function (a, b) {
360
- return a._id - b._id;
361
- });
362
- _context6.next = 19;
363
- return Promise.all(interfaceList.map( /*#__PURE__*/function () {
364
- var _ref12 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(interfaceInfo) {
365
- var outputFilePath, categoryUID, code, weights;
366
- return _regeneratorRuntime.wrap(function _callee5$(_context5) {
367
- while (1) {
368
- switch (_context5.prev = _context5.next) {
369
- case 0:
370
- outputFilePath = path.resolve(_this3.options.cwd, typeof syntheticalConfig.outputFilePath === 'function' ? syntheticalConfig.outputFilePath(interfaceInfo, changeCase) : syntheticalConfig.outputFilePath);
371
- categoryUID = "_" + serverIndex + "_" + projectIndex + "_" + categoryIndex + "_" + categoryIndex2;
372
- _context5.next = 4;
373
- return _this3.generateInterfaceCode(syntheticalConfig, interfaceInfo, categoryUID);
374
-
375
- case 4:
376
- code = _context5.sent;
377
- weights = [serverIndex, projectIndex, categoryIndex, categoryIndex2];
378
- return _context5.abrupt("return", {
379
- categoryUID: categoryUID,
380
- outputFilePath: outputFilePath,
381
- weights: weights,
382
- code: code
383
- });
384
-
385
- case 7:
386
- case "end":
387
- return _context5.stop();
388
- }
389
- }
390
- }, _callee5);
391
- }));
392
-
393
- return function (_x12) {
394
- return _ref12.apply(this, arguments);
395
- };
396
- }()));
397
-
398
- case 19:
399
- interfaceCodes = _context6.sent;
400
- groupedInterfaceCodes = groupBy(interfaceCodes, function (item) {
401
- return item.outputFilePath;
402
- });
403
- return _context6.abrupt("return", Object.keys(groupedInterfaceCodes).map(function (outputFilePath) {
404
- var categoryCode = [].concat(uniq(sortByWeights(groupedInterfaceCodes[outputFilePath]).map(function (item) {
405
- return item.categoryUID;
406
- })).map(function (categoryUID) {
407
- if (syntheticalConfig.typesOnly) return '';
408
- var text = '';
409
-
410
- if (syntheticalConfig.withoutUrl !== true) {
411
- text += "const devUrl" + categoryUID + " = " + JSON.stringify(syntheticalConfig.devUrl) + " as any;\n const mockUrl" + categoryUID + " = " + JSON.stringify(syntheticalConfig.mockUrl) + " as any;\n const prodUrl" + categoryUID + " = " + JSON.stringify(syntheticalConfig.prodUrl) + " as any;";
412
- }
413
-
414
- if (syntheticalConfig.ignoreUselessConfigVar !== true) {
415
- text += "const dataKey" + categoryUID + " = " + JSON.stringify(syntheticalConfig.dataKey) + " as any;";
416
- }
417
-
418
- return dedent(text);
419
- }), sortByWeights(groupedInterfaceCodes[outputFilePath]).map(function (item) {
420
- return item.code;
421
- })).filter(Boolean).join('\n\n');
422
-
423
- if (!outputFileList[outputFilePath]) {
424
- outputFileList[outputFilePath] = {
425
- syntheticalConfig: syntheticalConfig,
426
- content: [],
427
- requestFunctionFilePath: syntheticalConfig.requestFunctionFilePath ? path.resolve(_this3.options.cwd, syntheticalConfig.requestFunctionFilePath) : path.join(path.dirname(outputFilePath), 'request.ts'),
428
- requestHookMakerFilePath: syntheticalConfig.reactHooks && syntheticalConfig.reactHooks.enabled ? syntheticalConfig.reactHooks.requestHookMakerFilePath ? path.resolve(_this3.options.cwd, syntheticalConfig.reactHooks.requestHookMakerFilePath) : path.join(path.dirname(outputFilePath), 'makeRequestHook.ts') : ''
429
- };
430
- }
431
-
432
- return {
433
- outputFilePath: outputFilePath,
434
- code: categoryCode,
435
- weights: last(sortByWeights(groupedInterfaceCodes[outputFilePath])).weights
436
- };
437
- }));
438
-
439
- case 22:
440
- case "end":
441
- return _context6.stop();
442
- }
443
- }
444
- }, _callee6);
445
- }));
446
-
447
- return function (_x10, _x11) {
448
- return _ref11.apply(this, arguments);
449
- };
450
- }()));
451
-
452
- case 4:
453
- codes = _context7.sent.flat();
454
-
455
- for (_iterator = _createForOfIteratorHelperLoose(values(groupBy(codes, function (item) {
456
- return item.outputFilePath;
457
- }))); !(_step = _iterator()).done;) {
458
- groupedCodes = _step.value;
459
- sortByWeights(groupedCodes);
460
-
461
- (_outputFileList$group = outputFileList[groupedCodes[0].outputFilePath].content).push.apply(_outputFileList$group, groupedCodes.map(function (item) {
462
- return item.code;
463
- }));
464
- }
465
-
466
- case 6:
467
- case "end":
468
- return _context7.stop();
469
- }
470
- }
471
- }, _callee7);
472
- }));
473
-
474
- return function (_x8, _x9) {
475
- return _ref10.apply(this, arguments);
476
- };
477
- }()));
478
-
479
- case 15:
480
- case "end":
481
- return _context8.stop();
482
- }
483
- }
484
- }, _callee8);
485
- }));
486
-
487
- return function (_x6, _x7) {
488
- return _ref9.apply(this, arguments);
489
- };
490
- }())));
491
-
492
- case 2:
493
- case "end":
494
- return _context9.stop();
495
- }
496
- }
497
- }, _callee9);
498
- }));
499
-
500
- return function (_x4, _x5) {
501
- return _ref8.apply(this, arguments);
502
- };
503
- }()));
504
-
505
- case 3:
506
- return _context10.abrupt("return", outputFileList);
507
-
508
- case 4:
509
- case "end":
510
- return _context10.stop();
511
- }
512
- }
513
- }, _callee10, this);
514
- }));
515
-
516
- function generate() {
517
- return _generate.apply(this, arguments);
518
- }
519
-
520
- return generate;
521
- }();
522
-
523
- _proto.write = /*#__PURE__*/function () {
524
- var _write = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee12(outputFileList) {
525
- var _this4 = this;
526
-
527
- return _regeneratorRuntime.wrap(function _callee12$(_context12) {
528
- while (1) {
529
- switch (_context12.prev = _context12.next) {
530
- case 0:
531
- return _context12.abrupt("return", Promise.all(Object.keys(outputFileList).map( /*#__PURE__*/function () {
532
- var _ref13 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11(outputFilePath) {
533
- var _outputFileList$outpu, content, requestFunctionFilePath, requestHookMakerFilePath, syntheticalConfig, rawRequestFunctionFilePath, rawRequestHookMakerFilePath, rawOutputContent, prettier, prettyOutputContent, outputContent;
534
-
535
- return _regeneratorRuntime.wrap(function _callee11$(_context11) {
536
- while (1) {
537
- switch (_context11.prev = _context11.next) {
538
- case 0:
539
- _outputFileList$outpu = outputFileList[outputFilePath], content = _outputFileList$outpu.content, requestFunctionFilePath = _outputFileList$outpu.requestFunctionFilePath, requestHookMakerFilePath = _outputFileList$outpu.requestHookMakerFilePath, syntheticalConfig = _outputFileList$outpu.syntheticalConfig;
540
- rawRequestFunctionFilePath = requestFunctionFilePath;
541
- rawRequestHookMakerFilePath = requestHookMakerFilePath; // 支持 .jsx? 后缀
542
-
543
- // 支持 .jsx? 后缀
544
- outputFilePath = outputFilePath.replace(/\.js(x)?$/, '.ts$1');
545
- requestFunctionFilePath = requestFunctionFilePath.replace(/\.js(x)?$/, '.ts$1');
546
- requestHookMakerFilePath = requestHookMakerFilePath.replace(/\.js(x)?$/, '.ts$1');
547
-
548
- if (syntheticalConfig.typesOnly) {
549
- _context11.next = 20;
550
- break;
551
- }
552
-
553
- _context11.next = 9;
554
- return fs.pathExists(rawRequestFunctionFilePath);
555
-
556
- case 9:
557
- if (_context11.sent) {
558
- _context11.next = 12;
559
- break;
560
- }
561
-
562
- _context11.next = 12;
563
- return fs.outputFile(requestFunctionFilePath, dedent(_templateObject || (_templateObject = _taggedTemplateLiteralLoose(["\n import type { RequestFunctionParams } from 'yapi-apifox-to-typescript'\n\n export interface RequestOptions {\n /**\n * \u4F7F\u7528\u7684\u670D\u52A1\u5668\u3002\n *\n * - `prod`: \u751F\u4EA7\u670D\u52A1\u5668\n * - `dev`: \u6D4B\u8BD5\u670D\u52A1\u5668\n * - `mock`: \u6A21\u62DF\u670D\u52A1\u5668\n *\n * @default prod\n */\n server?: 'prod' | 'dev' | 'mock',\n }\n\n export default function request<TResponseData>(\n payload: RequestFunctionParams,\n options: RequestOptions = {\n server: 'prod',\n },\n ): Promise<TResponseData> {\n return new Promise<TResponseData>((resolve, reject) => {\n // \u57FA\u672C\u5730\u5740\n ", "\n\n // \u8BF7\u6C42\u5730\u5740\n const url = `${baseUrl}${payload.path}`\n\n // \u5177\u4F53\u8BF7\u6C42\u903B\u8F91\n })\n }\n "], ["\n import type { RequestFunctionParams } from 'yapi-apifox-to-typescript'\n\n export interface RequestOptions {\n /**\n * \u4F7F\u7528\u7684\u670D\u52A1\u5668\u3002\n *\n * - \\`prod\\`: \u751F\u4EA7\u670D\u52A1\u5668\n * - \\`dev\\`: \u6D4B\u8BD5\u670D\u52A1\u5668\n * - \\`mock\\`: \u6A21\u62DF\u670D\u52A1\u5668\n *\n * @default prod\n */\n server?: 'prod' | 'dev' | 'mock',\n }\n\n export default function request<TResponseData>(\n payload: RequestFunctionParams,\n options: RequestOptions = {\n server: 'prod',\n },\n ): Promise<TResponseData> {\n return new Promise<TResponseData>((resolve, reject) => {\n // \u57FA\u672C\u5730\u5740\n ", "\n\n // \u8BF7\u6C42\u5730\u5740\n const url = \\`\\${baseUrl}\\${payload.path}\\`\n\n // \u5177\u4F53\u8BF7\u6C42\u903B\u8F91\n })\n }\n "])), syntheticalConfig.withoutUrl ? "const baseUrl = ''" : " const baseUrl = options.server === 'mock'\n ? payload.mockUrl\n : options.server === 'dev'\n ? payload.devUrl\n : payload.prodUrl"));
564
-
565
- case 12:
566
- _context11.t0 = syntheticalConfig.reactHooks && syntheticalConfig.reactHooks.enabled;
567
-
568
- if (!_context11.t0) {
569
- _context11.next = 17;
570
- break;
571
- }
572
-
573
- _context11.next = 16;
574
- return fs.pathExists(rawRequestHookMakerFilePath);
575
-
576
- case 16:
577
- _context11.t0 = !_context11.sent;
578
-
579
- case 17:
580
- if (!_context11.t0) {
581
- _context11.next = 20;
582
- break;
583
- }
584
-
585
- _context11.next = 20;
586
- return fs.outputFile(requestHookMakerFilePath, dedent(_templateObject2 || (_templateObject2 = _taggedTemplateLiteralLoose(["\n import { useState, useEffect } from 'react'\n import type { RequestConfig } from 'yapi-apifox-to-typescript'\n import type { Request } from ", "\n import baseRequest from ", "\n\n export default function makeRequestHook<TRequestData, TRequestConfig extends RequestConfig, TRequestResult extends ReturnType<typeof baseRequest>>(request: Request<TRequestData, TRequestConfig, TRequestResult>) {\n type Data = TRequestResult extends Promise<infer R> ? R : TRequestResult\n return function useRequest(requestData: TRequestData) {\n // \u4E00\u4E2A\u7B80\u5355\u7684 Hook \u5B9E\u73B0\uFF0C\u5B9E\u9645\u9879\u76EE\u53EF\u7ED3\u5408\u5176\u4ED6\u5E93\u4F7F\u7528\uFF0C\u6BD4\u5982\uFF1A\n // @umijs/hooks \u7684 useRequest (https://github.com/umijs/hooks)\n // swr (https://github.com/zeit/swr)\n\n const [loading, setLoading] = useState(true)\n const [data, setData] = useState<Data>()\n\n useEffect(() => {\n request(requestData).then(data => {\n setLoading(false)\n setData(data as any)\n })\n }, [JSON.stringify(requestData)])\n\n return {\n loading,\n data,\n }\n }\n }\n "])), JSON.stringify(getNormalizedRelativePath(requestHookMakerFilePath, outputFilePath)), JSON.stringify(getNormalizedRelativePath(requestHookMakerFilePath, requestFunctionFilePath))));
587
-
588
- case 20:
589
- // 始终写入主文件
590
- rawOutputContent = dedent(_templateObject3 || (_templateObject3 = _taggedTemplateLiteralLoose(["\n /* tslint:disable */\n /* eslint-disable */\n\n /* \u8BE5\u6587\u4EF6\u7531 yapi-apifox-to-typescript \u81EA\u52A8\u751F\u6210\uFF0C\u8BF7\u52FF\u76F4\u63A5\u4FEE\u6539\uFF01\uFF01\uFF01 */\n\n ", "\n "])), syntheticalConfig.typesOnly ? dedent(_templateObject4 || (_templateObject4 = _taggedTemplateLiteralLoose(["\n // @ts-ignore\n type FileData = File\n\n ", "\n "])), content.join('\n\n').trim()) : dedent(_templateObject5 || (_templateObject5 = _taggedTemplateLiteralLoose(["\n // @ts-ignore\n // prettier-ignore\n import { QueryStringArrayFormat, Method, RequestBodyType, ", "FileData, prepare } from 'yapi-apifox-to-typescript'\n // @ts-ignore\n // prettier-ignore\n import type { RequestConfig, RequestFunctionRestArgs } from 'yapi-apifox-to-typescript'\n // @ts-ignore\n import request from ", "\n ", "\n\n type UserRequestRestArgs = RequestFunctionRestArgs<typeof request>\n\n // Request: \u76EE\u524D React Hooks \u529F\u80FD\u6709\u7528\u5230\n export type Request<TRequestData, TRequestConfig extends RequestConfig, TRequestResult> = (\n TRequestConfig['requestDataOptional'] extends true\n ? (requestData?: TRequestData, ...args: RequestFunctionRestArgs<typeof request>) => TRequestResult\n : (requestData: TRequestData, ...args: RequestFunctionRestArgs<typeof request>) => TRequestResult\n ) & {\n requestConfig: TRequestConfig\n }\n\n ", "\n "])), syntheticalConfig.ignoreUselessConfigVar ? "" : "ResponseBodyType, ", JSON.stringify(getNormalizedRelativePath(outputFilePath, requestFunctionFilePath)), !syntheticalConfig.reactHooks || !syntheticalConfig.reactHooks.enabled ? '' : dedent(_templateObject6 || (_templateObject6 = _taggedTemplateLiteralLoose(["\n // @ts-ignore\n import makeRequestHook from ", "\n "])), JSON.stringify(getNormalizedRelativePath(outputFilePath, requestHookMakerFilePath))), content.join('\n\n').trim())); // ref: https://prettier.io/docs/en/options.html
591
-
592
- _context11.next = 23;
593
- return getPrettier(_this4.options.cwd);
594
-
595
- case 23:
596
- prettier = _context11.sent;
597
- _context11.t1 = prettier;
598
- _context11.t2 = rawOutputContent;
599
- _context11.t3 = _extends;
600
- _context11.t4 = {};
601
- _context11.next = 30;
602
- return getCachedPrettierOptions();
603
-
604
- case 30:
605
- _context11.t5 = _context11.sent;
606
- _context11.t6 = {
607
- filepath: outputFilePath
608
- };
609
- _context11.t7 = (0, _context11.t3)(_context11.t4, _context11.t5, _context11.t6);
610
- _context11.next = 35;
611
- return _context11.t1.format.call(_context11.t1, _context11.t2, _context11.t7);
612
-
613
- case 35:
614
- prettyOutputContent = _context11.sent;
615
- outputContent = dedent(_templateObject7 || (_templateObject7 = _taggedTemplateLiteralLoose(["\n /* prettier-ignore-start */\n ", "\n /* prettier-ignore-end */\n "])), prettyOutputContent) + "\n";
616
- _context11.next = 39;
617
- return fs.outputFile(outputFilePath, outputContent);
618
-
619
- case 39:
620
- if (!(syntheticalConfig.target === 'javascript')) {
621
- _context11.next = 44;
622
- break;
623
- }
624
-
625
- _context11.next = 42;
626
- return _this4.tsc(outputFilePath);
627
-
628
- case 42:
629
- _context11.next = 44;
630
- return Promise.all([fs.remove(requestFunctionFilePath).catch(noop), fs.remove(requestHookMakerFilePath).catch(noop), fs.remove(outputFilePath).catch(noop)]);
631
-
632
- case 44:
633
- case "end":
634
- return _context11.stop();
635
- }
636
- }
637
- }, _callee11);
638
- }));
639
-
640
- return function (_x14) {
641
- return _ref13.apply(this, arguments);
642
- };
643
- }())));
644
-
645
- case 1:
646
- case "end":
647
- return _context12.stop();
648
- }
649
- }
650
- }, _callee12);
651
- }));
652
-
653
- function write(_x13) {
654
- return _write.apply(this, arguments);
655
- }
656
-
657
- return write;
658
- }();
659
-
660
- _proto.tsc = /*#__PURE__*/function () {
661
- var _tsc = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee13(file) {
662
- var _this5 = this;
663
-
664
- return _regeneratorRuntime.wrap(function _callee13$(_context13) {
665
- while (1) {
666
- switch (_context13.prev = _context13.next) {
667
- case 0:
668
- return _context13.abrupt("return", new Promise(function (resolve) {
669
- // add this to fix bug that not-generator-file-on-window
670
- var command = "" + (require('os').platform() === 'win32' ? 'node ' : '') + JSON.stringify(require.resolve("typescript/bin/tsc"));
671
- exec(command + " --target ES2019 --module ESNext --jsx preserve --declaration --esModuleInterop " + JSON.stringify(file), {
672
- cwd: _this5.options.cwd,
673
- env: process.env
674
- }, function () {
675
- return resolve();
676
- });
677
- }));
678
-
679
- case 1:
680
- case "end":
681
- return _context13.stop();
682
- }
683
- }
684
- }, _callee13);
685
- }));
686
-
687
- function tsc(_x15) {
688
- return _tsc.apply(this, arguments);
689
- }
690
-
691
- return tsc;
692
- }();
693
-
694
- _proto.fetchApi = /*#__PURE__*/function () {
695
- var _fetchApi = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee14(url, query) {
696
- var res;
697
- return _regeneratorRuntime.wrap(function _callee14$(_context14) {
698
- while (1) {
699
- switch (_context14.prev = _context14.next) {
700
- case 0:
701
- _context14.next = 2;
702
- return httpGet(url, query);
703
-
704
- case 2:
705
- res = _context14.sent;
706
-
707
- /* istanbul ignore next */
708
- if (res && res.errcode) {
709
- throwError(res.errmsg + " [\u8BF7\u6C42\u5730\u5740: " + url + "] [\u8BF7\u6C42\u53C2\u6570: " + new URLSearchParams(query).toString() + "]");
710
- }
711
-
712
- return _context14.abrupt("return", res.data || res);
713
-
714
- case 5:
715
- case "end":
716
- return _context14.stop();
717
- }
718
- }
719
- }, _callee14);
720
- }));
721
-
722
- function fetchApi(_x16, _x17) {
723
- return _fetchApi.apply(this, arguments);
724
- }
725
-
726
- return fetchApi;
727
- }();
728
-
729
- /** 获取分类的接口列表 */
730
- _proto.fetchInterfaceList =
731
- /*#__PURE__*/
732
- function () {
733
- var _fetchInterfaceList = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee15(_ref14) {
734
- var serverUrl, token, id, category;
735
- return _regeneratorRuntime.wrap(function _callee15$(_context15) {
736
- while (1) {
737
- switch (_context15.prev = _context15.next) {
738
- case 0:
739
- serverUrl = _ref14.serverUrl, token = _ref14.token, id = _ref14.id;
740
- _context15.next = 3;
741
- return this.fetchExport({
742
- serverUrl: serverUrl,
743
- token: token
744
- });
745
-
746
- case 3:
747
- _context15.t0 = _context15.sent;
748
-
749
- if (_context15.t0) {
750
- _context15.next = 6;
751
- break;
752
- }
753
-
754
- _context15.t0 = [];
755
-
756
- case 6:
757
- category = _context15.t0.find(function (cat) {
758
- return !isEmpty(cat) && !isEmpty(cat.list) && cat.list[0].catid === id;
759
- });
760
-
761
- if (category) {
762
- category.list.forEach(function (interfaceInfo) {
763
- // 实现 _category 字段
764
- interfaceInfo._category = omit(category, ['list']);
765
- });
766
- }
767
-
768
- return _context15.abrupt("return", category ? category.list : []);
769
-
770
- case 9:
771
- case "end":
772
- return _context15.stop();
773
- }
774
- }
775
- }, _callee15, this);
776
- }));
777
-
778
- function fetchInterfaceList(_x18) {
779
- return _fetchInterfaceList.apply(this, arguments);
780
- }
781
-
782
- return fetchInterfaceList;
783
- }()
784
- /** 获取项目信息 */
785
- ;
786
-
787
- _proto.fetchProjectInfo =
788
- /*#__PURE__*/
789
- function () {
790
- var _fetchProjectInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee16(syntheticalConfig) {
791
- var projectInfo, projectCats;
792
- return _regeneratorRuntime.wrap(function _callee16$(_context16) {
793
- while (1) {
794
- switch (_context16.prev = _context16.next) {
795
- case 0:
796
- _context16.next = 2;
797
- return this.fetchProject(syntheticalConfig);
798
-
799
- case 2:
800
- projectInfo = _context16.sent;
801
- _context16.next = 5;
802
- return this.fetchApi(syntheticalConfig.serverUrl + "/api/interface/getCatMenu", {
803
- token: syntheticalConfig.token,
804
- project_id: projectInfo._id
805
- });
806
-
807
- case 5:
808
- projectCats = _context16.sent;
809
- return _context16.abrupt("return", _extends({}, projectInfo, {
810
- cats: projectCats,
811
- getMockUrl: function getMockUrl() {
812
- return syntheticalConfig.serverUrl + "/mock/" + projectInfo._id;
813
- },
814
- getDevUrl: function getDevUrl(devEnvName) {
815
- var env = projectInfo.env.find(function (e) {
816
- return e.name === devEnvName;
817
- });
818
- return env && env.domain
819
- /* istanbul ignore next */
820
- || '';
821
- },
822
- getProdUrl: function getProdUrl(prodEnvName) {
823
- var env = projectInfo.env.find(function (e) {
824
- return e.name === prodEnvName;
825
- });
826
- return env && env.domain
827
- /* istanbul ignore next */
828
- || '';
14
+ * @see https://webpack.js.org/guides/tree-shaking/#mark-a-function-call-as-side-effect-free
15
+ * @see https://terser.org/docs/api-reference.html#annotations
16
+ */
17
+ var COMPRESSOR_TREE_SHAKING_ANNOTATION = "/*#__PURE__*/";
18
+ var Generator = class {
19
+ constructor(config, options = { cwd: process.cwd() }) {
20
+ this.options = options;
21
+ this.config = [];
22
+ this.disposes = [];
23
+ this.barrelOutputMap = /* @__PURE__ */ new Map();
24
+ this.fetchProject = memoize(async ({ serverUrl, token }) => {
25
+ const projectInfo = await this.fetchApi(`${serverUrl}/api/project/get`, { token });
26
+ projectInfo.basepath = `/${projectInfo.basepath || "/"}`.replace(/\/+$/, "").replace(/^\/+/, "/");
27
+ projectInfo._url = `${serverUrl}/project/${projectInfo._id}/interface/api`;
28
+ return projectInfo;
29
+ }, ({ serverUrl, token }) => `${serverUrl}|${token}`);
30
+ this.fetchExport = memoize(async ({ serverUrl, token }) => {
31
+ const projectInfo = await this.fetchProject({
32
+ serverUrl,
33
+ token
34
+ });
35
+ return (await this.fetchApi(`${serverUrl}/api/plugin/export`, {
36
+ type: "json",
37
+ status: "all",
38
+ isWiki: "false",
39
+ token
40
+ })).map((cat) => {
41
+ const projectId = cat.list?.[0]?.project_id || 0;
42
+ cat._url = `${serverUrl}/project/${projectId}/interface/api/cat_${cat.list?.[0]?.catid || 0}`;
43
+ cat.list = (cat.list || []).map((item) => {
44
+ const interfaceId = item._id;
45
+ item._url = `${serverUrl}/project/${projectId}/interface/api/${interfaceId}`;
46
+ item.path = `${projectInfo.basepath}${item.path}`;
47
+ return item;
48
+ });
49
+ return cat;
50
+ });
51
+ }, ({ serverUrl, token }) => `${serverUrl}|${token}`);
52
+ this.config = castArray(config);
53
+ }
54
+ async prepare() {
55
+ this.config = await Promise.all(this.config.map(async (item) => {
56
+ if (item.serverType === "swagger" || item.serverType === "local") {
57
+ const swaggerToYApiServer = new SwaggerToYApiServer(item.serverType === "local" ? { swaggerJsonPath: path.isAbsolute(item.serverUrl || "") ? item.serverUrl : path.resolve(this.options.cwd, item.serverUrl || "") } : { swaggerJsonUrl: item.serverUrl });
58
+ item.serverUrl = await swaggerToYApiServer.start();
59
+ this.disposes.push(() => swaggerToYApiServer.stop());
60
+ }
61
+ if (item.serverUrl) item.serverUrl = item.serverUrl.replace(/\/+$/, "");
62
+ return item;
63
+ }));
64
+ }
65
+ async generate() {
66
+ const outputFileList = Object.create(null);
67
+ await Promise.all(this.config.map(async (serverConfig, serverIndex) => {
68
+ const projects = (serverConfig.projects?.length ? serverConfig.projects : serverConfig.serverType === "swagger" || serverConfig.serverType === "local" ? [{
69
+ token: "local",
70
+ categories: [{ id: 0 }]
71
+ }] : throwError(`projects is required when serverType is ${serverConfig.serverType || "yapi"}`)).reduce((projects, project) => {
72
+ projects.push(...castArray(project.token).map((token) => ({
73
+ ...project,
74
+ token
75
+ })));
76
+ return projects;
77
+ }, []);
78
+ return Promise.all(projects.map(async (projectConfig, projectIndex) => {
79
+ let projectInfo;
80
+ let apifoxInstance = null;
81
+ if (serverConfig.serverType === "apifox") {
82
+ if (!projectConfig.projectId) throw new Error("projectId is required when serverType is apifox");
83
+ apifoxInstance = new ApifoxToYApiData({
84
+ token: projectConfig.token,
85
+ projectId: projectConfig.projectId,
86
+ categories: projectConfig.categories,
87
+ serverUrl: serverConfig.serverUrl,
88
+ addFoldersToTags: projectConfig.addFoldersToTags,
89
+ oasVersion: projectConfig.oasVersion,
90
+ exportFormat: projectConfig.exportFormat
91
+ });
92
+ projectInfo = await apifoxInstance.getProjectInfo();
93
+ } else projectInfo = await this.fetchProjectInfo({
94
+ ...serverConfig,
95
+ ...projectConfig
96
+ });
97
+ await Promise.all(projectConfig.categories.map(async (categoryConfig, categoryIndex) => {
98
+ let categoryIds = [];
99
+ if (serverConfig.serverType === "apifox" && apifoxInstance) categoryIds = apifoxInstance.getCats(categoryConfig);
100
+ else categoryIds = getFilteredCat(categoryConfig, projectInfo.cats);
101
+ const codes = (await Promise.all(categoryIds.map(async (id, categoryIndex2) => {
102
+ categoryConfig = {
103
+ ...categoryConfig,
104
+ id
105
+ };
106
+ const syntheticalConfig = {
107
+ ...serverConfig,
108
+ ...projectConfig,
109
+ ...categoryConfig,
110
+ mockUrl: projectInfo.getMockUrl()
111
+ };
112
+ syntheticalConfig.target = syntheticalConfig.target || "typescript";
113
+ syntheticalConfig.devUrl = projectInfo.getDevUrl(syntheticalConfig.devEnvName);
114
+ syntheticalConfig.prodUrl = projectInfo.getProdUrl(syntheticalConfig.prodEnvName);
115
+ let interfaceList = [];
116
+ if (syntheticalConfig.serverType === "apifox" && apifoxInstance) interfaceList = await apifoxInstance.getInterfaceList(syntheticalConfig);
117
+ else interfaceList = await this.fetchInterfaceList(syntheticalConfig);
118
+ interfaceList = interfaceList.map((interfaceInfo) => {
119
+ interfaceInfo._project = omit(projectInfo, [
120
+ "cats",
121
+ "getMockUrl",
122
+ "getDevUrl",
123
+ "getProdUrl"
124
+ ]);
125
+ return isFunction(syntheticalConfig.preproccessInterface) ? syntheticalConfig.preproccessInterface(cloneDeepFast(interfaceInfo), changeCase, syntheticalConfig) : interfaceInfo;
126
+ }).filter(Boolean);
127
+ interfaceList.sort((a, b) => a._id - b._id);
128
+ const interfaceCodes = await Promise.all(interfaceList.map(async (interfaceInfo) => {
129
+ const baseOutputFilePath = path.resolve(this.options.cwd, typeof syntheticalConfig.outputFilePath === "function" ? syntheticalConfig.outputFilePath(interfaceInfo, changeCase) : syntheticalConfig.outputFilePath);
130
+ let outputFilePath = baseOutputFilePath;
131
+ if (syntheticalConfig.splitByModule) {
132
+ const moduleName = interfaceInfo.path.split("/").filter(Boolean)[0] || "default";
133
+ outputFilePath = path.join(path.dirname(baseOutputFilePath), "modules", `${moduleName}.ts`);
134
+ this.barrelOutputMap.set(baseOutputFilePath, true);
135
+ }
136
+ const categoryUID = `_${serverIndex}_${projectIndex}_${categoryIndex}_${categoryIndex2}`;
137
+ const code = await this.generateInterfaceCode(syntheticalConfig, interfaceInfo, categoryUID);
138
+ return {
139
+ categoryUID,
140
+ outputFilePath,
141
+ weights: [
142
+ serverIndex,
143
+ projectIndex,
144
+ categoryIndex,
145
+ categoryIndex2
146
+ ],
147
+ code
148
+ };
149
+ }));
150
+ const groupedInterfaceCodes = groupBy(interfaceCodes, (item) => item.outputFilePath);
151
+ return Object.keys(groupedInterfaceCodes).map((outputFilePath) => {
152
+ const categoryCode = [...uniq(sortByWeights(groupedInterfaceCodes[outputFilePath]).map((item) => item.categoryUID)).map((categoryUID) => {
153
+ if (syntheticalConfig.typesOnly) return "";
154
+ let text = "";
155
+ if (syntheticalConfig.withoutUrl !== true) text += `const devUrl${categoryUID} = ${JSON.stringify(syntheticalConfig.devUrl)} as any;
156
+ const mockUrl${categoryUID} = ${JSON.stringify(syntheticalConfig.mockUrl)} as any;
157
+ const prodUrl${categoryUID} = ${JSON.stringify(syntheticalConfig.prodUrl)} as any;`;
158
+ if (syntheticalConfig.ignoreUselessConfigVar !== true) text += `const dataKey${categoryUID} = ${JSON.stringify(syntheticalConfig.dataKey)} as any;`;
159
+ return dedent(text);
160
+ }), ...sortByWeights(groupedInterfaceCodes[outputFilePath]).map((item) => item.code)].filter(Boolean).join("\n\n");
161
+ if (!outputFileList[outputFilePath]) outputFileList[outputFilePath] = {
162
+ syntheticalConfig,
163
+ content: [],
164
+ requestFunctionFilePath: syntheticalConfig.requestFunctionFilePath ? path.resolve(this.options.cwd, syntheticalConfig.requestFunctionFilePath) : path.join(path.dirname(outputFilePath), "request.ts"),
165
+ requestHookMakerFilePath: syntheticalConfig.reactHooks && syntheticalConfig.reactHooks.enabled ? syntheticalConfig.reactHooks.requestHookMakerFilePath ? path.resolve(this.options.cwd, syntheticalConfig.reactHooks.requestHookMakerFilePath) : path.join(path.dirname(outputFilePath), "makeRequestHook.ts") : ""
166
+ };
167
+ return {
168
+ outputFilePath,
169
+ code: categoryCode,
170
+ weights: last(sortByWeights(groupedInterfaceCodes[outputFilePath])).weights
171
+ };
172
+ });
173
+ }))).flat();
174
+ for (const groupedCodes of values(groupBy(codes, (item) => item.outputFilePath))) {
175
+ sortByWeights(groupedCodes);
176
+ outputFileList[groupedCodes[0].outputFilePath].content.push(...groupedCodes.map((item) => item.code));
177
+ }
178
+ }));
179
+ }));
180
+ }));
181
+ return outputFileList;
182
+ }
183
+ async write(outputFileList) {
184
+ await Promise.all(Object.keys(outputFileList).map(async (outputFilePath) => {
185
+ let { content, requestFunctionFilePath, requestHookMakerFilePath, syntheticalConfig } = outputFileList[outputFilePath];
186
+ const rawRequestFunctionFilePath = requestFunctionFilePath;
187
+ const rawRequestHookMakerFilePath = requestHookMakerFilePath;
188
+ outputFilePath = outputFilePath.replace(/\.js(x)?$/, ".ts$1");
189
+ requestFunctionFilePath = requestFunctionFilePath.replace(/\.js(x)?$/, ".ts$1");
190
+ requestHookMakerFilePath = requestHookMakerFilePath.replace(/\.js(x)?$/, ".ts$1");
191
+ if (!syntheticalConfig.typesOnly) {
192
+ if (!await fs.pathExists(rawRequestFunctionFilePath)) await fs.outputFile(requestFunctionFilePath, dedent`
193
+ import type { RequestFunctionParams } from 'yapi-apifox-to-typescript'
194
+
195
+ export interface RequestOptions {
196
+ /**
197
+ * 使用的服务器。
198
+ *
199
+ * - \`prod\`: 生产服务器
200
+ * - \`dev\`: 测试服务器
201
+ * - \`mock\`: 模拟服务器
202
+ *
203
+ * @default prod
204
+ */
205
+ server?: 'prod' | 'dev' | 'mock',
829
206
  }
830
- }));
831
-
832
- case 7:
833
- case "end":
834
- return _context16.stop();
835
- }
836
- }
837
- }, _callee16, this);
838
- }));
839
-
840
- function fetchProjectInfo(_x19) {
841
- return _fetchProjectInfo.apply(this, arguments);
842
- }
843
-
844
- return fetchProjectInfo;
845
- }()
846
- /** 生成接口代码 */
847
- ;
848
-
849
- _proto.generateInterfaceCode =
850
- /*#__PURE__*/
851
- function () {
852
- var _generateInterfaceCode = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee17(syntheticalConfig, interfaceInfo, categoryUID) {
853
- var _syntheticalConfig$js, _syntheticalConfig$js2, _syntheticalConfig$js3, _syntheticalConfig$js4;
854
-
855
- var extendedInterfaceInfo, requestFunctionName, requestConfigName, requestConfigTypeName, requestDataTypeName, responseDataTypeName, requestDataJsonSchema, requestDataType, responseDataJsonSchema, responseDataType, isRequestDataOptional, requestHookName, paramNames, paramNamesLiteral, queryNames, queryNamesLiteral, genComment, requestFunctionExtraInfo, requestHeaders;
856
- return _regeneratorRuntime.wrap(function _callee17$(_context17) {
857
- while (1) {
858
- switch (_context17.prev = _context17.next) {
859
- case 0:
860
- extendedInterfaceInfo = _extends({}, interfaceInfo, {
861
- parsedPath: path.parse(interfaceInfo.path)
862
- });
863
-
864
- if (!isFunction(syntheticalConfig.getRequestFunctionName)) {
865
- _context17.next = 7;
866
- break;
867
- }
868
-
869
- _context17.next = 4;
870
- return syntheticalConfig.getRequestFunctionName(extendedInterfaceInfo, changeCase);
871
-
872
- case 4:
873
- _context17.t0 = _context17.sent;
874
- _context17.next = 8;
875
- break;
876
207
 
877
- case 7:
878
- _context17.t0 = changeCase.camelCase(extendedInterfaceInfo.parsedPath.name);
879
-
880
- case 8:
881
- requestFunctionName = _context17.t0;
882
- requestConfigName = changeCase.camelCase(requestFunctionName + "RequestConfig");
883
- requestConfigTypeName = 'RequestConfig';
884
-
885
- if (!isFunction(syntheticalConfig.getRequestDataTypeName)) {
886
- _context17.next = 17;
887
- break;
888
- }
889
-
890
- _context17.next = 14;
891
- return syntheticalConfig.getRequestDataTypeName(extendedInterfaceInfo, changeCase);
892
-
893
- case 14:
894
- _context17.t1 = _context17.sent;
895
- _context17.next = 18;
896
- break;
897
-
898
- case 17:
899
- _context17.t1 = changeCase.pascalCase(requestFunctionName + "Request");
900
-
901
- case 18:
902
- requestDataTypeName = _context17.t1;
903
-
904
- if (!isFunction(syntheticalConfig.getResponseDataTypeName)) {
905
- _context17.next = 25;
906
- break;
907
- }
908
-
909
- _context17.next = 22;
910
- return syntheticalConfig.getResponseDataTypeName(extendedInterfaceInfo, changeCase);
911
-
912
- case 22:
913
- _context17.t2 = _context17.sent;
914
- _context17.next = 26;
915
- break;
916
-
917
- case 25:
918
- _context17.t2 = changeCase.pascalCase(requestFunctionName + "Response");
919
-
920
- case 26:
921
- responseDataTypeName = _context17.t2;
922
- requestDataJsonSchema = getRequestDataJsonSchema(extendedInterfaceInfo, syntheticalConfig.customTypeMapping || {});
923
- _context17.next = 30;
924
- return jsonSchemaToType(requestDataJsonSchema, requestDataTypeName);
925
-
926
- case 30:
927
- requestDataType = _context17.sent;
928
- responseDataJsonSchema = getResponseDataJsonSchema(extendedInterfaceInfo, syntheticalConfig.customTypeMapping || {}, syntheticalConfig.dataKey);
929
- _context17.next = 34;
930
- return jsonSchemaToType(responseDataJsonSchema, responseDataTypeName);
931
-
932
- case 34:
933
- responseDataType = _context17.sent;
934
- // @ts-ignore
935
- isRequestDataOptional = /(\{\}|any)$/.test(requestDataType);
936
-
937
- if (!(syntheticalConfig.reactHooks && syntheticalConfig.reactHooks.enabled)) {
938
- _context17.next = 47;
939
- break;
940
- }
941
-
942
- if (!isFunction(syntheticalConfig.reactHooks.getRequestHookName)) {
943
- _context17.next = 43;
944
- break;
945
- }
946
-
947
- _context17.next = 40;
948
- return syntheticalConfig.reactHooks.getRequestHookName(extendedInterfaceInfo, changeCase);
949
-
950
- case 40:
951
- _context17.t4 = _context17.sent;
952
- _context17.next = 44;
953
- break;
954
-
955
- case 43:
956
- _context17.t4 = "use" + changeCase.pascalCase(requestFunctionName);
957
-
958
- case 44:
959
- _context17.t3 = _context17.t4;
960
- _context17.next = 48;
961
- break;
962
-
963
- case 47:
964
- _context17.t3 = '';
965
-
966
- case 48:
967
- requestHookName = _context17.t3;
968
- // 支持路径参数
969
- paramNames = (extendedInterfaceInfo.req_params
970
- /* istanbul ignore next */
971
- || []).map(function (item) {
972
- return item.name;
973
- });
974
- paramNamesLiteral = JSON.stringify(paramNames); // const paramNameType =
975
- // paramNames.length === 0 ? 'string' : `'${paramNames.join("' | '")}'`
976
- // 支持查询参数
977
-
978
- queryNames = (extendedInterfaceInfo.req_query
979
- /* istanbul ignore next */
980
- || []).map(function (item) {
981
- return item.name;
982
- });
983
- queryNamesLiteral = JSON.stringify(queryNames); // const queryNameType =
984
- // queryNames.length === 0 ? 'string' : `'${queryNames.join("' | '")}'`
985
- // 接口注释
986
-
987
- genComment = function genComment(genTitle) {
988
- var _ref15 = _extends({}, syntheticalConfig.comment, syntheticalConfig.serverType === 'swagger' ? {
989
- tag: false,
990
- updateTime: false,
991
- link: false
992
- } : {}),
993
- _ref15$enabled = _ref15.enabled,
994
- isEnabled = _ref15$enabled === void 0 ? true : _ref15$enabled,
995
- _ref15$title = _ref15.title,
996
- hasTitle = _ref15$title === void 0 ? true : _ref15$title,
997
- _ref15$category = _ref15.category,
998
- hasCategory = _ref15$category === void 0 ? true : _ref15$category,
999
- _ref15$tag = _ref15.tag,
1000
- hasTag = _ref15$tag === void 0 ? true : _ref15$tag,
1001
- _ref15$requestHeader = _ref15.requestHeader,
1002
- hasRequestHeader = _ref15$requestHeader === void 0 ? true : _ref15$requestHeader,
1003
- _ref15$updateTime = _ref15.updateTime,
1004
- hasUpdateTime = _ref15$updateTime === void 0 ? true : _ref15$updateTime,
1005
- _ref15$link = _ref15.link,
1006
- hasLink = _ref15$link === void 0 ? true : _ref15$link,
1007
- extraTags = _ref15.extraTags;
1008
-
1009
- if (!isEnabled) {
1010
- return '';
1011
- } // 转义标题中的 /
1012
-
1013
-
1014
- var escapedTitle = String(extendedInterfaceInfo.title).replace(/\//g, '\\/');
1015
- var description = hasLink ? "[" + escapedTitle + "\u2197](" + extendedInterfaceInfo._url + ")" : escapedTitle;
1016
- var summary = [hasCategory && {
1017
- label: '分类',
1018
- value: hasLink ? "[" + extendedInterfaceInfo._category.name + "\u2197](" + extendedInterfaceInfo._category._url + ")" : extendedInterfaceInfo._category.name
1019
- }, hasTag && {
1020
- label: '标签',
1021
- value: extendedInterfaceInfo.tag.map(function (tag) {
1022
- return "`" + tag + "`";
208
+ export default function request<TResponseData>(
209
+ payload: RequestFunctionParams,
210
+ options: RequestOptions = {
211
+ server: 'prod',
212
+ },
213
+ ): Promise<TResponseData> {
214
+ return new Promise<TResponseData>((resolve, reject) => {
215
+ // 基本地址
216
+ ${syntheticalConfig.withoutUrl ? `const baseUrl = ''` : ` const baseUrl = options.server === 'mock'
217
+ ? payload.mockUrl
218
+ : options.server === 'dev'
219
+ ? payload.devUrl
220
+ : payload.prodUrl`}
221
+
222
+ // 请求地址
223
+ const url = \`\${baseUrl}\${payload.path}\`
224
+
225
+ // 具体请求逻辑
1023
226
  })
1024
- }, hasRequestHeader && {
1025
- label: '请求头',
1026
- value: "`" + extendedInterfaceInfo.method.toUpperCase() + " " + extendedInterfaceInfo.path + "`"
1027
- }, hasUpdateTime && {
1028
- label: '更新时间',
1029
- value: process.env.JEST_WORKER_ID // 测试时使用 unix 时间戳
1030
- ? String(extendedInterfaceInfo.up_time) :
1031
- /* istanbul ignore next */
1032
- "`" + dayjs(extendedInterfaceInfo.up_time * 1000).format('YYYY-MM-DD HH:mm:ss') + "`"
1033
- }];
1034
-
1035
- if (typeof extraTags === 'function') {
1036
- var tags = extraTags(extendedInterfaceInfo);
1037
-
1038
- for (var _iterator2 = _createForOfIteratorHelperLoose(tags), _step2; !(_step2 = _iterator2()).done;) {
1039
- var tag = _step2.value;
1040
- ;
1041
- (tag.position === 'start' ? summary.unshift : summary.push).call(summary, {
1042
- label: tag.name,
1043
- value: tag.value
1044
- });
227
+ }
228
+ `);
229
+ if (syntheticalConfig.reactHooks && syntheticalConfig.reactHooks.enabled && !await fs.pathExists(rawRequestHookMakerFilePath)) await fs.outputFile(requestHookMakerFilePath, dedent`
230
+ import { useState, useEffect } from 'react'
231
+ import type { RequestConfig } from 'yapi-apifox-to-typescript'
232
+ import type { Request } from ${JSON.stringify(getNormalizedRelativePath(requestHookMakerFilePath, outputFilePath))}
233
+ import baseRequest from ${JSON.stringify(getNormalizedRelativePath(requestHookMakerFilePath, requestFunctionFilePath))}
234
+
235
+ export default function makeRequestHook<TRequestData, TRequestConfig extends RequestConfig, TRequestResult extends ReturnType<typeof baseRequest>>(request: Request<TRequestData, TRequestConfig, TRequestResult>) {
236
+ type Data = TRequestResult extends Promise<infer R> ? R : TRequestResult
237
+ return function useRequest(requestData: TRequestData) {
238
+ // 一个简单的 Hook 实现,实际项目可结合其他库使用,比如:
239
+ // @umijs/hooks 的 useRequest (https://github.com/umijs/hooks)
240
+ // swr (https://github.com/zeit/swr)
241
+
242
+ const [loading, setLoading] = useState(true)
243
+ const [data, setData] = useState<Data>()
244
+
245
+ useEffect(() => {
246
+ request(requestData).then(data => {
247
+ setLoading(false)
248
+ setData(data as any)
249
+ })
250
+ }, [JSON.stringify(requestData)])
251
+
252
+ return {
253
+ loading,
254
+ data,
255
+ }
1045
256
  }
1046
257
  }
1047
-
1048
- var titleComment = hasTitle ? dedent(_templateObject8 || (_templateObject8 = _taggedTemplateLiteralLoose(["\n * ", "\n *\n "])), genTitle(description)) : '';
1049
- var extraComment = summary.filter(function (item) {
1050
- return typeof item !== 'boolean' && !isEmpty(item.value);
1051
- }).map(function (item) {
1052
- var _item = item;
1053
- return "* @" + _item.label + " " + castArray(_item.value).join(', ');
1054
- }).join('\n');
1055
- return dedent(_templateObject9 || (_templateObject9 = _taggedTemplateLiteralLoose(["\n /**\n ", "\n */\n "])), [titleComment, extraComment].filter(Boolean).join('\n'));
1056
- }; // 请求参数额外信息
1057
-
1058
-
1059
- if (!(typeof syntheticalConfig.setRequestFunctionExtraInfo === 'function')) {
1060
- _context17.next = 60;
1061
- break;
1062
- }
1063
-
1064
- _context17.next = 57;
1065
- return syntheticalConfig.setRequestFunctionExtraInfo(extendedInterfaceInfo, changeCase);
1066
-
1067
- case 57:
1068
- _context17.t5 = _context17.sent;
1069
- _context17.next = 61;
1070
- break;
1071
-
1072
- case 60:
1073
- _context17.t5 = {};
1074
-
1075
- case 61:
1076
- requestFunctionExtraInfo = _context17.t5;
1077
- requestHeaders = JSON.stringify((extendedInterfaceInfo.req_headers || []).filter(function (item) {
1078
- return item.name.toLowerCase() !== 'content-type';
1079
- }).reduce(function (res, item) {
1080
- res[item.name] = item.value;
1081
- return res;
1082
- }, {}));
1083
- return _context17.abrupt("return", dedent(_templateObject10 || (_templateObject10 = _taggedTemplateLiteralLoose(["\n ", "\n ", "\n\n ", "\n ", "\n\n ", "\n "])), genComment(function (title) {
1084
- return "\u63A5\u53E3 " + title + " \u7684 **\u8BF7\u6C42\u7C7B\u578B**";
1085
- }), requestDataType.trim(), genComment(function (title) {
1086
- return "\u63A5\u53E3 " + title + " \u7684 **\u8FD4\u56DE\u7C7B\u578B**";
1087
- }), responseDataType.trim(), syntheticalConfig.typesOnly ? '' : dedent(_templateObject11 || (_templateObject11 = _taggedTemplateLiteralLoose(["\n ", "\n ", "\n path: ", ",\n method: Method.", ",\n ", "", "", "", "requestBodyType: RequestBodyType.", ",\n ", "\n }\n\n ", "\n export const ", " = ", " (\n requestData", ": ", ",\n ...args: UserRequestRestArgs\n ) => {\n return request<", ">(\n prepare(", ", requestData),\n ...args,\n )\n }\n\n ", ".requestConfig = ", "\n\n ", "\n "])), genComment(function (title) {
1088
- return "\u63A5\u53E3 " + title + " \u7684 **\u8BF7\u6C42\u914D\u7F6E**";
1089
- }), syntheticalConfig.withoutUrl !== true ? "const " + requestConfigName + ": " + requestConfigTypeName + " = " + COMPRESSOR_TREE_SHAKING_ANNOTATION + " {\n mockUrl: mockUrl" + categoryUID + ",\n devUrl: devUrl" + categoryUID + ",\n prodUrl: prodUrl" + categoryUID + "," : "const " + requestConfigName + ": " + requestConfigTypeName + " = " + COMPRESSOR_TREE_SHAKING_ANNOTATION + " {", JSON.stringify(extendedInterfaceInfo.path), extendedInterfaceInfo.method, paramNames.length === 0 ? '' : "paramNames: " + paramNamesLiteral + ",", queryNames.length === 0 ? '' : "queryNames: " + queryNamesLiteral + ",", syntheticalConfig.queryStringArrayFormat ? "queryStringArrayFormat: QueryStringArrayFormat." + syntheticalConfig.queryStringArrayFormat + "," : '', requestHeaders === '{}' ? '' : "requestHeaders: " + requestHeaders + ",", extendedInterfaceInfo.method === Method.GET ? RequestBodyType.query : extendedInterfaceInfo.req_body_type
1090
- /* istanbul ignore next */
1091
- || RequestBodyType.none, syntheticalConfig.ignoreUselessConfigVar ? "" : "responseBodyType: ResponseBodyType." + extendedInterfaceInfo.res_body_type + ",\n dataKey: dataKey" + categoryUID + ",\n requestDataOptional: " + JSON.stringify(isRequestDataOptional) + ",\n requestDataJsonSchema: " + JSON.stringify((_syntheticalConfig$js = syntheticalConfig.jsonSchema) != null && _syntheticalConfig$js.enabled && ((_syntheticalConfig$js2 = syntheticalConfig.jsonSchema) == null ? void 0 : _syntheticalConfig$js2.requestData) !== false ? requestDataJsonSchema : {}) + ",\n responseDataJsonSchema: " + JSON.stringify((_syntheticalConfig$js3 = syntheticalConfig.jsonSchema) != null && _syntheticalConfig$js3.enabled && ((_syntheticalConfig$js4 = syntheticalConfig.jsonSchema) == null ? void 0 : _syntheticalConfig$js4.responseData) !== false ? responseDataJsonSchema : {}) + ",\n requestFunctionName: " + JSON.stringify(requestFunctionName) + ",\n extraInfo: " + JSON.stringify(requestFunctionExtraInfo), genComment(function (title) {
1092
- return "\u63A5\u53E3 " + title + " \u7684 **\u8BF7\u6C42\u51FD\u6570**";
1093
- }), requestFunctionName, COMPRESSOR_TREE_SHAKING_ANNOTATION, isRequestDataOptional ? '?' : '', requestDataTypeName, responseDataTypeName, requestConfigName, requestFunctionName, requestConfigName, !syntheticalConfig.reactHooks || !syntheticalConfig.reactHooks.enabled ? '' : dedent(_templateObject12 || (_templateObject12 = _taggedTemplateLiteralLoose(["\n ", "\n export const ", " = ", " makeRequestHook<", ", ", ", ReturnType<typeof ", ">>(", ")\n "])), genComment(function (title) {
1094
- return "\u63A5\u53E3 " + title + " \u7684 **React Hook**";
1095
- }), requestHookName, COMPRESSOR_TREE_SHAKING_ANNOTATION, requestDataTypeName, requestConfigTypeName, requestFunctionName, requestFunctionName))));
1096
-
1097
- case 64:
1098
- case "end":
1099
- return _context17.stop();
1100
- }
1101
- }
1102
- }, _callee17);
1103
- }));
1104
-
1105
- function generateInterfaceCode(_x20, _x21, _x22) {
1106
- return _generateInterfaceCode.apply(this, arguments);
1107
- }
1108
-
1109
- return generateInterfaceCode;
1110
- }();
1111
-
1112
- _proto.destroy = /*#__PURE__*/function () {
1113
- var _destroy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee19() {
1114
- return _regeneratorRuntime.wrap(function _callee19$(_context19) {
1115
- while (1) {
1116
- switch (_context19.prev = _context19.next) {
1117
- case 0:
1118
- return _context19.abrupt("return", Promise.all(this.disposes.map( /*#__PURE__*/function () {
1119
- var _ref16 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee18(dispose) {
1120
- return _regeneratorRuntime.wrap(function _callee18$(_context18) {
1121
- while (1) {
1122
- switch (_context18.prev = _context18.next) {
1123
- case 0:
1124
- return _context18.abrupt("return", dispose());
1125
-
1126
- case 1:
1127
- case "end":
1128
- return _context18.stop();
258
+ `);
259
+ }
260
+ const rawOutputContent = dedent`
261
+ /* tslint:disable */
262
+ /* eslint-disable */
263
+
264
+ /* 该文件由 yapi-apifox-to-typescript 自动生成,请勿直接修改!!! */
265
+
266
+ ${syntheticalConfig.typesOnly ? dedent`
267
+ // @ts-ignore
268
+ type FileData = File
269
+
270
+ ${content.join("\n\n").trim()}
271
+ ` : dedent`
272
+ // @ts-ignore
273
+ // prettier-ignore
274
+ import { QueryStringArrayFormat, Method, RequestBodyType, ${syntheticalConfig.ignoreUselessConfigVar ? `` : `ResponseBodyType, `}FileData, prepare } from 'yapi-apifox-to-typescript'
275
+ // @ts-ignore
276
+ // prettier-ignore
277
+ import type { RequestConfig, RequestFunctionRestArgs } from 'yapi-apifox-to-typescript'
278
+ // @ts-ignore
279
+ import request from ${JSON.stringify(getNormalizedRelativePath(outputFilePath, requestFunctionFilePath))}
280
+ ${!syntheticalConfig.reactHooks || !syntheticalConfig.reactHooks.enabled ? "" : dedent`
281
+ // @ts-ignore
282
+ import makeRequestHook from ${JSON.stringify(getNormalizedRelativePath(outputFilePath, requestHookMakerFilePath))}
283
+ `}
284
+
285
+ type UserRequestRestArgs = RequestFunctionRestArgs<typeof request>
286
+ ${!syntheticalConfig.reactHooks || !syntheticalConfig.reactHooks.enabled ? "" : `\n${dedent`
287
+ // Request: 目前 React Hooks 功能有用到
288
+ export type Request<TRequestData, TRequestConfig extends RequestConfig, TRequestResult> = (
289
+ TRequestConfig['requestDataOptional'] extends true
290
+ ? (requestData?: TRequestData, ...args: RequestFunctionRestArgs<typeof request>) => TRequestResult
291
+ : (requestData: TRequestData, ...args: RequestFunctionRestArgs<typeof request>) => TRequestResult
292
+ ) & {
293
+ requestConfig: TRequestConfig
1129
294
  }
1130
- }
1131
- }, _callee18);
1132
- }));
1133
-
1134
- return function (_x23) {
1135
- return _ref16.apply(this, arguments);
1136
- };
1137
- }())));
1138
-
1139
- case 1:
1140
- case "end":
1141
- return _context19.stop();
1142
- }
1143
- }
1144
- }, _callee19, this);
1145
- }));
1146
-
1147
- function destroy() {
1148
- return _destroy.apply(this, arguments);
1149
- }
295
+ `}`}
296
+
297
+ ${content.join("\n\n").trim()}
298
+ `}
299
+ `;
300
+ const outputContent = `/* prettier-ignore-start */\n${await (await getPrettier(this.options.cwd)).format(rawOutputContent, {
301
+ ...await getCachedPrettierOptions(),
302
+ filepath: outputFilePath
303
+ })}\n/* prettier-ignore-end */\n`;
304
+ await fs.outputFile(outputFilePath, outputContent);
305
+ if (syntheticalConfig.target === "javascript") {
306
+ await this.tsc(outputFilePath);
307
+ await Promise.all([
308
+ fs.remove(requestFunctionFilePath).catch(noop),
309
+ fs.remove(requestHookMakerFilePath).catch(noop),
310
+ fs.remove(outputFilePath).catch(noop)
311
+ ]);
312
+ }
313
+ }));
314
+ if (this.barrelOutputMap.size > 0) {
315
+ const prettier = await getPrettier(this.options.cwd);
316
+ const barrelPaths = Array.from(this.barrelOutputMap.keys());
317
+ for (let bi = 0; bi < barrelPaths.length; bi++) {
318
+ const barrelPath = barrelPaths[bi];
319
+ const modulesDir = path.join(path.dirname(barrelPath), "modules");
320
+ const moduleExports = Object.keys(outputFileList).filter((f) => f.startsWith(modulesDir)).map((f) => `./modules/${path.basename(f, path.extname(f))}`).sort();
321
+ if (moduleExports.length === 0) continue;
322
+ const rawBarrelContent = [
323
+ "/* tslint:disable */",
324
+ "/* eslint-disable */",
325
+ "",
326
+ "/* 该文件由 yapi-apifox-to-typescript 自动生成,请勿直接修改!!! */",
327
+ "",
328
+ ...moduleExports.map((m) => `export * from ${JSON.stringify(m)}`)
329
+ ].join("\n");
330
+ const prettyBarrelContent = await prettier.format(rawBarrelContent, {
331
+ ...await getCachedPrettierOptions(),
332
+ filepath: barrelPath
333
+ });
334
+ await fs.outputFile(barrelPath, `/* prettier-ignore-start */\n${prettyBarrelContent}\n/* prettier-ignore-end */\n`);
335
+ }
336
+ }
337
+ }
338
+ async tsc(file) {
339
+ return new Promise((resolve) => {
340
+ const command = `${__require("os").platform() === "win32" ? "node " : ""}${JSON.stringify(__require.resolve(`typescript/bin/tsc`))}`;
341
+ exec(`${command} --target ES2019 --module ESNext --jsx preserve --declaration --esModuleInterop ${JSON.stringify(file)}`, {
342
+ cwd: this.options.cwd,
343
+ env: process.env
344
+ }, () => resolve());
345
+ });
346
+ }
347
+ async fetchApi(url, query) {
348
+ const res = await httpGet(url, query);
349
+ /* istanbul ignore next */
350
+ if (res && res.errcode) throwError(`${res.errmsg} [请求地址: ${url}] [请求参数: ${new URLSearchParams(query).toString()}]`);
351
+ return res.data || res;
352
+ }
353
+ /** 获取分类的接口列表 */
354
+ async fetchInterfaceList({ serverUrl, token, id }) {
355
+ const category = (await this.fetchExport({
356
+ serverUrl,
357
+ token
358
+ }) || []).find((cat) => !isEmpty(cat) && !isEmpty(cat.list) && cat.list[0].catid === id);
359
+ if (category) category.list.forEach((interfaceInfo) => {
360
+ interfaceInfo._category = omit(category, ["list"]);
361
+ });
362
+ return category ? category.list : [];
363
+ }
364
+ /** 获取项目信息 */
365
+ async fetchProjectInfo(syntheticalConfig) {
366
+ const projectInfo = await this.fetchProject(syntheticalConfig);
367
+ const projectCats = await this.fetchApi(`${syntheticalConfig.serverUrl}/api/interface/getCatMenu`, {
368
+ token: syntheticalConfig.token,
369
+ project_id: projectInfo._id
370
+ });
371
+ return {
372
+ ...projectInfo,
373
+ cats: projectCats,
374
+ getMockUrl: () => `${syntheticalConfig.serverUrl}/mock/${projectInfo._id}`,
375
+ getDevUrl: (devEnvName) => {
376
+ const env = projectInfo.env.find((e) => e.name === devEnvName);
377
+ return env && env.domain || "";
378
+ },
379
+ getProdUrl: (prodEnvName) => {
380
+ const env = projectInfo.env.find((e) => e.name === prodEnvName);
381
+ return env && env.domain || "";
382
+ }
383
+ };
384
+ }
385
+ /** 生成接口代码 */
386
+ async generateInterfaceCode(syntheticalConfig, interfaceInfo, categoryUID) {
387
+ const extendedInterfaceInfo = {
388
+ ...interfaceInfo,
389
+ parsedPath: path.parse(interfaceInfo.path)
390
+ };
391
+ const requestFunctionName = isFunction(syntheticalConfig.getRequestFunctionName) ? await syntheticalConfig.getRequestFunctionName(extendedInterfaceInfo, changeCase) : changeCase.camelCase(extendedInterfaceInfo.parsedPath.name);
392
+ const requestConfigName = changeCase.camelCase(`${requestFunctionName}RequestConfig`);
393
+ const requestConfigTypeName = "RequestConfig";
394
+ const requestDataTypeName = isFunction(syntheticalConfig.getRequestDataTypeName) ? await syntheticalConfig.getRequestDataTypeName(extendedInterfaceInfo, changeCase) : changeCase.pascalCase(`${requestFunctionName}Request`);
395
+ const responseDataTypeName = isFunction(syntheticalConfig.getResponseDataTypeName) ? await syntheticalConfig.getResponseDataTypeName(extendedInterfaceInfo, changeCase) : changeCase.pascalCase(`${requestFunctionName}Response`);
396
+ const requestDataJsonSchema = getRequestDataJsonSchema(extendedInterfaceInfo, syntheticalConfig.customTypeMapping || {});
397
+ const requestDataType = await jsonSchemaToType(requestDataJsonSchema, requestDataTypeName);
398
+ const responseDataJsonSchema = getResponseDataJsonSchema(extendedInterfaceInfo, syntheticalConfig.customTypeMapping || {}, syntheticalConfig.dataKey);
399
+ const responseDataType = await jsonSchemaToType(responseDataJsonSchema, responseDataTypeName);
400
+ const isRequestDataOptional = /(\{\}|any)$/s.test(requestDataType);
401
+ const requestHookName = syntheticalConfig.reactHooks && syntheticalConfig.reactHooks.enabled ? isFunction(syntheticalConfig.reactHooks.getRequestHookName) ? await syntheticalConfig.reactHooks.getRequestHookName(extendedInterfaceInfo, changeCase) : `use${changeCase.pascalCase(requestFunctionName)}` : "";
402
+ const paramNames = (extendedInterfaceInfo.req_params || []).map((item) => item.name);
403
+ const paramNamesLiteral = JSON.stringify(paramNames);
404
+ const queryNames = (extendedInterfaceInfo.req_query || []).map((item) => item.name);
405
+ const queryNamesLiteral = JSON.stringify(queryNames);
406
+ const genComment = (genTitle) => {
407
+ const { enabled: isEnabled = true, title: hasTitle = true, category: hasCategory = true, tag: hasTag = true, requestHeader: hasRequestHeader = true, updateTime: hasUpdateTime = true, link: hasLink = true, extraTags } = {
408
+ ...syntheticalConfig.comment,
409
+ ...syntheticalConfig.serverType === "swagger" || syntheticalConfig.serverType === "local" ? {
410
+ tag: false,
411
+ updateTime: false,
412
+ link: false
413
+ } : {}
414
+ };
415
+ if (!isEnabled) return "";
416
+ const escapedTitle = String(extendedInterfaceInfo.title).replace(/\//g, "\\/");
417
+ const description = hasLink ? `[${escapedTitle}↗](${extendedInterfaceInfo._url})` : escapedTitle;
418
+ const summary = [
419
+ hasCategory && {
420
+ label: "分类",
421
+ value: hasLink ? `[${extendedInterfaceInfo._category.name}↗](${extendedInterfaceInfo._category._url})` : extendedInterfaceInfo._category.name
422
+ },
423
+ hasTag && {
424
+ label: "标签",
425
+ value: extendedInterfaceInfo.tag.map((tag) => `\`${tag}\``)
426
+ },
427
+ hasRequestHeader && {
428
+ label: "请求头",
429
+ value: `\`${extendedInterfaceInfo.method.toUpperCase()} ${extendedInterfaceInfo.path}\``
430
+ },
431
+ hasUpdateTime && {
432
+ label: "更新时间",
433
+ value: process.env.JEST_WORKER_ID ? String(extendedInterfaceInfo.up_time) : `\`${dayjs(extendedInterfaceInfo.up_time * 1e3).format("YYYY-MM-DD HH:mm:ss")}\``
434
+ }
435
+ ];
436
+ if (typeof extraTags === "function") {
437
+ const tags = extraTags(extendedInterfaceInfo);
438
+ for (const tag of tags) (tag.position === "start" ? summary.unshift : summary.push).call(summary, {
439
+ label: tag.name,
440
+ value: tag.value
441
+ });
442
+ }
443
+ const titleComment = hasTitle ? dedent`
444
+ * ${genTitle(description)}
445
+ *
446
+ ` : "";
447
+ const extraComment = summary.filter((item) => typeof item !== "boolean" && !isEmpty(item.value)).map((item) => {
448
+ const _item = item;
449
+ return `* @${_item.label} ${castArray(_item.value).join(", ")}`;
450
+ }).join("\n");
451
+ return dedent`
452
+ /**
453
+ ${[titleComment, extraComment].filter(Boolean).join("\n")}
454
+ */
455
+ `;
456
+ };
457
+ const requestFunctionExtraInfo = typeof syntheticalConfig.setRequestFunctionExtraInfo === "function" ? await syntheticalConfig.setRequestFunctionExtraInfo(extendedInterfaceInfo, changeCase) : {};
458
+ const requestHeaders = JSON.stringify((extendedInterfaceInfo.req_headers || []).filter((item) => item.name.toLowerCase() !== "content-type").reduce((res, item) => {
459
+ res[item.name] = item.value;
460
+ return res;
461
+ }, {}));
462
+ return dedent`
463
+ ${genComment((title) => `接口 ${title} 的 **请求类型**`)}
464
+ ${requestDataType.trim()}
465
+
466
+ ${genComment((title) => `接口 ${title} 的 **返回类型**`)}
467
+ ${responseDataType.trim()}
468
+
469
+ ${syntheticalConfig.typesOnly ? "" : dedent`
470
+ ${genComment((title) => `接口 ${title} 的 **请求配置**`)}
471
+ ${syntheticalConfig.withoutUrl !== true ? `const ${requestConfigName}: ${requestConfigTypeName} = ${COMPRESSOR_TREE_SHAKING_ANNOTATION} {
472
+ mockUrl: mockUrl${categoryUID},
473
+ devUrl: devUrl${categoryUID},
474
+ prodUrl: prodUrl${categoryUID},` : `const ${requestConfigName}: ${requestConfigTypeName} = ${COMPRESSOR_TREE_SHAKING_ANNOTATION} {`}
475
+ path: ${JSON.stringify(extendedInterfaceInfo.path)},
476
+ method: Method.${extendedInterfaceInfo.method},
477
+ ${paramNames.length === 0 ? "" : `paramNames: ${paramNamesLiteral},`}${queryNames.length === 0 ? "" : `queryNames: ${queryNamesLiteral},`}${syntheticalConfig.queryStringArrayFormat ? `queryStringArrayFormat: QueryStringArrayFormat.${syntheticalConfig.queryStringArrayFormat},` : ""}${requestHeaders === "{}" ? "" : `requestHeaders: ${requestHeaders},`}requestBodyType: RequestBodyType.${extendedInterfaceInfo.method === Method.GET ? RequestBodyType.query : extendedInterfaceInfo.req_body_type || RequestBodyType.none},
478
+ ${syntheticalConfig.ignoreUselessConfigVar ? `` : `responseBodyType: ResponseBodyType.${extendedInterfaceInfo.res_body_type},
479
+ dataKey: dataKey${categoryUID},
480
+ requestDataOptional: ${JSON.stringify(isRequestDataOptional)},
481
+ requestDataJsonSchema: ${JSON.stringify(syntheticalConfig.jsonSchema?.enabled && syntheticalConfig.jsonSchema?.requestData !== false ? requestDataJsonSchema : {})},
482
+ responseDataJsonSchema: ${JSON.stringify(syntheticalConfig.jsonSchema?.enabled && syntheticalConfig.jsonSchema?.responseData !== false ? responseDataJsonSchema : {})},
483
+ requestFunctionName: ${JSON.stringify(requestFunctionName)},
484
+ extraInfo: ${JSON.stringify(requestFunctionExtraInfo)}`}
485
+ }
1150
486
 
1151
- return destroy;
1152
- }();
487
+ ${genComment((title) => `接口 ${title} 的 **请求函数**`)}
488
+ export const ${requestFunctionName} = ${COMPRESSOR_TREE_SHAKING_ANNOTATION} (
489
+ requestData${isRequestDataOptional ? "?" : ""}: ${requestDataTypeName},
490
+ ...args: UserRequestRestArgs
491
+ ) => {
492
+ return request<${responseDataTypeName}>(
493
+ prepare(${requestConfigName}, requestData),
494
+ ...args,
495
+ )
496
+ }
1153
497
 
1154
- return Generator;
1155
- }();
498
+ ${requestFunctionName}.requestConfig = ${requestConfigName}
499
+
500
+ ${!syntheticalConfig.reactHooks || !syntheticalConfig.reactHooks.enabled ? "" : dedent`
501
+ ${genComment((title) => `接口 ${title} 的 **React Hook**`)}
502
+ export const ${requestHookName} = ${COMPRESSOR_TREE_SHAKING_ANNOTATION} makeRequestHook<${requestDataTypeName}, ${requestConfigTypeName}, ReturnType<typeof ${requestFunctionName}>>(${requestFunctionName})
503
+ `}
504
+ `}
505
+ `;
506
+ }
507
+ async destroy() {
508
+ return Promise.all(this.disposes.map(async (dispose) => dispose()));
509
+ }
510
+ };
511
+ //#endregion
512
+ export { Generator };