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