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.
package/lib/esm/cli.js CHANGED
@@ -1,257 +1,168 @@
1
1
  #!/usr/bin/env node
2
- import _taggedTemplateLiteralLoose from "@babel/runtime/helpers/esm/taggedTemplateLiteralLoose";
3
- import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
4
-
5
- var _templateObject, _templateObject2;
6
-
7
- import _regeneratorRuntime from "@babel/runtime/regenerator";
8
- import * as TSNode from 'ts-node';
9
- import consola from 'consola';
10
- import fs from 'fs-extra';
11
- import ora from 'ora';
12
- import path from 'path';
13
- import prompt from 'prompts';
14
- import yargs from 'yargs';
15
- import { dedent, wait } from 'vtils';
16
- import { Generator } from './Generator';
2
+ import { __require } from "./_virtual/_rolldown/runtime.js";
3
+ import { dedent, wait } from "./mini-ut.js";
4
+ import { Generator } from "./Generator.js";
5
+ import * as TSNode from "ts-node";
6
+ import consola from "consola";
7
+ import fs from "fs-extra";
8
+ import ora from "ora";
9
+ import path from "path";
10
+ import prompt from "prompts";
11
+ import yargs from "yargs";
12
+ //#region src/cli.ts
17
13
  TSNode.register({
18
- // 不加载本地的 tsconfig.json
19
- skipProject: true,
20
- // 仅转译,不做类型检查
21
- transpileOnly: true,
22
- // 自定义编译选项
23
- compilerOptions: {
24
- strict: false,
25
- target: 'es2017',
26
- module: 'commonjs',
27
- moduleResolution: 'node',
28
- declaration: false,
29
- removeComments: false,
30
- esModuleInterop: true,
31
- allowSyntheticDefaultImports: true,
32
- importHelpers: false,
33
- // 转换 js,支持在 ytt.config.js 里使用最新语法
34
- allowJs: true,
35
- lib: ['es2017']
36
- }
14
+ skipProject: true,
15
+ transpileOnly: true,
16
+ compilerOptions: {
17
+ strict: false,
18
+ target: "es2017",
19
+ module: "commonjs",
20
+ moduleResolution: "node",
21
+ declaration: false,
22
+ removeComments: false,
23
+ esModuleInterop: true,
24
+ allowSyntheticDefaultImports: true,
25
+ importHelpers: false,
26
+ allowJs: true,
27
+ lib: ["es2017"]
28
+ }
37
29
  });
38
- export function run(_x, _x2) {
39
- return _run.apply(this, arguments);
30
+ async function run(cmd, options) {
31
+ let useCustomConfigFile = false;
32
+ let cwd;
33
+ let configTSFile;
34
+ let configJSFile;
35
+ let configFile;
36
+ let configFileExist;
37
+ if (!options?.configFile) {
38
+ cwd = process.cwd();
39
+ configTSFile = path.join(cwd, "ytt.config.ts");
40
+ configJSFile = path.join(cwd, "ytt.config.js");
41
+ const configTSFileExist = await fs.pathExists(configTSFile);
42
+ const configJSFileExist = !configTSFileExist && await fs.pathExists(configJSFile);
43
+ configFileExist = configTSFileExist || configJSFileExist;
44
+ configFile = configTSFileExist ? configTSFile : configJSFile;
45
+ } else {
46
+ useCustomConfigFile = true;
47
+ configFile = options.configFile;
48
+ cwd = path.dirname(configFile);
49
+ configFileExist = await fs.pathExists(configFile);
50
+ }
51
+ if (cmd === "help") console.log(`\n${dedent`
52
+ # 用法
53
+ 初始化配置文件: ytt init
54
+ 生成代码: ytt
55
+ 查看帮助: ytt help
56
+
57
+ # GitHub
58
+ https://github.com/kekexunxun/yapi-to-typescript
59
+ `}\n`);
60
+ else if (cmd === "init") {
61
+ if (configFileExist) {
62
+ consola.info(`检测到配置文件: ${configFile}`);
63
+ if (!(await prompt({
64
+ message: "是否覆盖已有配置文件?",
65
+ name: "override",
66
+ type: "confirm"
67
+ })).override) return;
68
+ }
69
+ let outputConfigFile;
70
+ let outputConfigFileType;
71
+ if (useCustomConfigFile) {
72
+ outputConfigFile = configFile;
73
+ outputConfigFileType = configFile.endsWith(".js") ? "js" : "ts";
74
+ } else {
75
+ const answers = await prompt({
76
+ message: "选择配置文件类型?",
77
+ name: "configFileType",
78
+ type: "select",
79
+ choices: [{
80
+ title: "TypeScript(ytt.config.ts)",
81
+ value: "ts"
82
+ }, {
83
+ title: "JavaScript(ytt.config.js)",
84
+ value: "js"
85
+ }]
86
+ });
87
+ outputConfigFile = answers.configFileType === "js" ? configJSFile : configTSFile;
88
+ outputConfigFileType = answers.configFileType;
89
+ }
90
+ await fs.outputFile(outputConfigFile, dedent`
91
+ import { defineConfig } from 'yapi-apifox-to-typescript'
92
+
93
+ export default defineConfig([
94
+ {
95
+ serverUrl: 'http://foo.bar',
96
+ typesOnly: false,
97
+ target: '${outputConfigFileType === "js" ? "javascript" : "typescript"}',
98
+ reactHooks: {
99
+ enabled: false,
100
+ },
101
+ prodEnvName: 'production',
102
+ outputFilePath: 'src/api/index.${outputConfigFileType}',
103
+ requestFunctionFilePath: 'src/api/request.${outputConfigFileType}',
104
+ dataKey: 'data',
105
+ projects: [
106
+ {
107
+ token: 'hello',
108
+ categories: [
109
+ {
110
+ id: 0,
111
+ getRequestFunctionName(interfaceInfo, changeCase) {
112
+ // 以接口全路径生成请求函数名
113
+ return changeCase.camelCase(interfaceInfo.path)
114
+
115
+ // 若生成的请求函数名存在语法关键词报错、或想通过某个关键词触发 IDE 自动引入提示,可考虑加前缀,如:
116
+ // return changeCase.camelCase(\`api_\${interfaceInfo.path}\`)
117
+
118
+ // 若生成的请求函数名有重复报错,可考虑将接口请求方式纳入生成条件,如:
119
+ // return changeCase.camelCase(\`\${interfaceInfo.method}_\${interfaceInfo.path}\`)
120
+ },
121
+ },
122
+ ],
123
+ },
124
+ ],
125
+ },
126
+ ])
127
+ `);
128
+ consola.success("写入配置文件完毕");
129
+ } else {
130
+ if (!configFileExist) return consola.error(`找不到配置文件: ${useCustomConfigFile ? configFile : `${configTSFile} 或 ${configJSFile}`}`);
131
+ consola.success(`找到配置文件: ${configFile}`);
132
+ let config;
133
+ let generator;
134
+ let spinner;
135
+ try {
136
+ config = __require(configFile).default;
137
+ generator = new Generator(config, { cwd });
138
+ spinner = ora("正在获取数据并生成代码...").start();
139
+ const delayNotice = wait(5e3);
140
+ delayNotice.then(() => {
141
+ spinner.text = `正在获取数据并生成代码... (若长时间处于此状态,请检查是否有接口定义的数据过大导致拉取或解析缓慢)`;
142
+ });
143
+ await generator.prepare();
144
+ delayNotice.cancel();
145
+ const output = await generator.generate();
146
+ spinner.stop();
147
+ consola.success("获取数据并生成代码完毕");
148
+ await generator.write(output);
149
+ consola.success("写入文件完毕");
150
+ await generator.destroy();
151
+ await config.hooks?.success?.();
152
+ } catch (err) {
153
+ spinner?.stop();
154
+ await generator?.destroy();
155
+ await config?.hooks?.fail?.();
156
+ /* istanbul ignore next */
157
+ consola.error(err);
158
+ }
159
+ await config?.hooks?.complete?.();
160
+ }
40
161
  }
41
162
  /* istanbul ignore next */
42
-
43
- function _run() {
44
- _run = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(cmd, options) {
45
- var useCustomConfigFile, cwd, configTSFile, configJSFile, configFile, configFileExist, configTSFileExist, configJSFileExist, answers, outputConfigFile, outputConfigFileType, _answers, _config2, _config2$hooks, config, generator, spinner, _hooks, delayNotice, output, _spinner, _generator, _config, _config$hooks;
46
-
47
- return _regeneratorRuntime.wrap(function _callee$(_context) {
48
- while (1) {
49
- switch (_context.prev = _context.next) {
50
- case 0:
51
- useCustomConfigFile = false;
52
-
53
- if (options != null && options.configFile) {
54
- _context.next = 18;
55
- break;
56
- }
57
-
58
- cwd = process.cwd();
59
- configTSFile = path.join(cwd, 'ytt.config.ts');
60
- configJSFile = path.join(cwd, 'ytt.config.js');
61
- _context.next = 7;
62
- return fs.pathExists(configTSFile);
63
-
64
- case 7:
65
- configTSFileExist = _context.sent;
66
- _context.t0 = !configTSFileExist;
67
-
68
- if (!_context.t0) {
69
- _context.next = 13;
70
- break;
71
- }
72
-
73
- _context.next = 12;
74
- return fs.pathExists(configJSFile);
75
-
76
- case 12:
77
- _context.t0 = _context.sent;
78
-
79
- case 13:
80
- configJSFileExist = _context.t0;
81
- configFileExist = configTSFileExist || configJSFileExist;
82
- configFile = configTSFileExist ? configTSFile : configJSFile;
83
- _context.next = 24;
84
- break;
85
-
86
- case 18:
87
- useCustomConfigFile = true;
88
- configFile = options.configFile;
89
- cwd = path.dirname(configFile);
90
- _context.next = 23;
91
- return fs.pathExists(configFile);
92
-
93
- case 23:
94
- configFileExist = _context.sent;
95
-
96
- case 24:
97
- if (!(cmd === 'help')) {
98
- _context.next = 28;
99
- break;
100
- }
101
-
102
- console.log("\n" + dedent(_templateObject || (_templateObject = _taggedTemplateLiteralLoose(["\n # \u7528\u6CD5\n \u521D\u59CB\u5316\u914D\u7F6E\u6587\u4EF6: ytt init\n \u751F\u6210\u4EE3\u7801: ytt\n \u67E5\u770B\u5E2E\u52A9: ytt help\n\n # GitHub\n https://github.com/kekexunxun/yapi-to-typescript\n "]))) + "\n");
103
- _context.next = 87;
104
- break;
105
-
106
- case 28:
107
- if (!(cmd === 'init')) {
108
- _context.next = 51;
109
- break;
110
- }
111
-
112
- if (!configFileExist) {
113
- _context.next = 36;
114
- break;
115
- }
116
-
117
- consola.info("\u68C0\u6D4B\u5230\u914D\u7F6E\u6587\u4EF6: " + configFile);
118
- _context.next = 33;
119
- return prompt({
120
- message: '是否覆盖已有配置文件?',
121
- name: 'override',
122
- type: 'confirm'
123
- });
124
-
125
- case 33:
126
- answers = _context.sent;
127
-
128
- if (answers.override) {
129
- _context.next = 36;
130
- break;
131
- }
132
-
133
- return _context.abrupt("return");
134
-
135
- case 36:
136
- if (!useCustomConfigFile) {
137
- _context.next = 41;
138
- break;
139
- }
140
-
141
- outputConfigFile = configFile;
142
- outputConfigFileType = configFile.endsWith('.js') ? 'js' : 'ts';
143
- _context.next = 46;
144
- break;
145
-
146
- case 41:
147
- _context.next = 43;
148
- return prompt({
149
- message: '选择配置文件类型?',
150
- name: 'configFileType',
151
- type: 'select',
152
- choices: [{
153
- title: 'TypeScript(ytt.config.ts)',
154
- value: 'ts'
155
- }, {
156
- title: 'JavaScript(ytt.config.js)',
157
- value: 'js'
158
- }]
159
- });
160
-
161
- case 43:
162
- _answers = _context.sent;
163
- outputConfigFile = _answers.configFileType === 'js' ? configJSFile : configTSFile;
164
- outputConfigFileType = _answers.configFileType;
165
-
166
- case 46:
167
- _context.next = 48;
168
- return fs.outputFile(outputConfigFile, dedent(_templateObject2 || (_templateObject2 = _taggedTemplateLiteralLoose(["\n import { defineConfig } from 'yapi-apifox-to-typescript'\n\n export default defineConfig([\n {\n serverUrl: 'http://foo.bar',\n typesOnly: false,\n target: '", "',\n reactHooks: {\n enabled: false,\n },\n prodEnvName: 'production',\n outputFilePath: 'src/api/index.", "',\n requestFunctionFilePath: 'src/api/request.", "',\n dataKey: 'data',\n projects: [\n {\n token: 'hello',\n categories: [\n {\n id: 0,\n getRequestFunctionName(interfaceInfo, changeCase) {\n // \u4EE5\u63A5\u53E3\u5168\u8DEF\u5F84\u751F\u6210\u8BF7\u6C42\u51FD\u6570\u540D\n return changeCase.camelCase(interfaceInfo.path)\n\n // \u82E5\u751F\u6210\u7684\u8BF7\u6C42\u51FD\u6570\u540D\u5B58\u5728\u8BED\u6CD5\u5173\u952E\u8BCD\u62A5\u9519\u3001\u6216\u60F3\u901A\u8FC7\u67D0\u4E2A\u5173\u952E\u8BCD\u89E6\u53D1 IDE \u81EA\u52A8\u5F15\u5165\u63D0\u793A\uFF0C\u53EF\u8003\u8651\u52A0\u524D\u7F00\uFF0C\u5982:\n // return changeCase.camelCase(`api_${interfaceInfo.path}`)\n\n // \u82E5\u751F\u6210\u7684\u8BF7\u6C42\u51FD\u6570\u540D\u6709\u91CD\u590D\u62A5\u9519\uFF0C\u53EF\u8003\u8651\u5C06\u63A5\u53E3\u8BF7\u6C42\u65B9\u5F0F\u7EB3\u5165\u751F\u6210\u6761\u4EF6\uFF0C\u5982:\n // return changeCase.camelCase(`${interfaceInfo.method}_${interfaceInfo.path}`)\n },\n },\n ],\n },\n ],\n },\n ])\n "], ["\n import { defineConfig } from 'yapi-apifox-to-typescript'\n\n export default defineConfig([\n {\n serverUrl: 'http://foo.bar',\n typesOnly: false,\n target: '", "',\n reactHooks: {\n enabled: false,\n },\n prodEnvName: 'production',\n outputFilePath: 'src/api/index.", "',\n requestFunctionFilePath: 'src/api/request.", "',\n dataKey: 'data',\n projects: [\n {\n token: 'hello',\n categories: [\n {\n id: 0,\n getRequestFunctionName(interfaceInfo, changeCase) {\n // \u4EE5\u63A5\u53E3\u5168\u8DEF\u5F84\u751F\u6210\u8BF7\u6C42\u51FD\u6570\u540D\n return changeCase.camelCase(interfaceInfo.path)\n\n // \u82E5\u751F\u6210\u7684\u8BF7\u6C42\u51FD\u6570\u540D\u5B58\u5728\u8BED\u6CD5\u5173\u952E\u8BCD\u62A5\u9519\u3001\u6216\u60F3\u901A\u8FC7\u67D0\u4E2A\u5173\u952E\u8BCD\u89E6\u53D1 IDE \u81EA\u52A8\u5F15\u5165\u63D0\u793A\uFF0C\u53EF\u8003\u8651\u52A0\u524D\u7F00\uFF0C\u5982:\n // return changeCase.camelCase(\\`api_\\${interfaceInfo.path}\\`)\n\n // \u82E5\u751F\u6210\u7684\u8BF7\u6C42\u51FD\u6570\u540D\u6709\u91CD\u590D\u62A5\u9519\uFF0C\u53EF\u8003\u8651\u5C06\u63A5\u53E3\u8BF7\u6C42\u65B9\u5F0F\u7EB3\u5165\u751F\u6210\u6761\u4EF6\uFF0C\u5982:\n // return changeCase.camelCase(\\`\\${interfaceInfo.method}_\\${interfaceInfo.path}\\`)\n },\n },\n ],\n },\n ],\n },\n ])\n "])), outputConfigFileType === 'js' ? 'javascript' : 'typescript', outputConfigFileType, outputConfigFileType));
169
-
170
- case 48:
171
- consola.success('写入配置文件完毕');
172
- _context.next = 87;
173
- break;
174
-
175
- case 51:
176
- if (configFileExist) {
177
- _context.next = 53;
178
- break;
179
- }
180
-
181
- return _context.abrupt("return", consola.error("\u627E\u4E0D\u5230\u914D\u7F6E\u6587\u4EF6: " + (useCustomConfigFile ? configFile : configTSFile + " \u6216 " + configJSFile)));
182
-
183
- case 53:
184
- consola.success("\u627E\u5230\u914D\u7F6E\u6587\u4EF6: " + configFile);
185
- _context.prev = 54;
186
- config = require(configFile).default;
187
- generator = new Generator(config, {
188
- cwd: cwd
189
- });
190
- spinner = ora('正在获取数据并生成代码...').start();
191
- delayNotice = wait(5000);
192
- delayNotice.then(function () {
193
- spinner.text = "\u6B63\u5728\u83B7\u53D6\u6570\u636E\u5E76\u751F\u6210\u4EE3\u7801... (\u82E5\u957F\u65F6\u95F4\u5904\u4E8E\u6B64\u72B6\u6001\uFF0C\u8BF7\u68C0\u67E5\u662F\u5426\u6709\u63A5\u53E3\u5B9A\u4E49\u7684\u6570\u636E\u8FC7\u5927\u5BFC\u81F4\u62C9\u53D6\u6216\u89E3\u6790\u7F13\u6162)";
194
- });
195
- _context.next = 62;
196
- return generator.prepare();
197
-
198
- case 62:
199
- delayNotice.cancel();
200
- _context.next = 65;
201
- return generator.generate();
202
-
203
- case 65:
204
- output = _context.sent;
205
- spinner.stop();
206
- consola.success('获取数据并生成代码完毕');
207
- _context.next = 70;
208
- return generator.write(output);
209
-
210
- case 70:
211
- consola.success('写入文件完毕');
212
- _context.next = 73;
213
- return generator.destroy();
214
-
215
- case 73:
216
- _context.next = 75;
217
- return (_hooks = config.hooks) == null ? void 0 : _hooks.success == null ? void 0 : _hooks.success();
218
-
219
- case 75:
220
- _context.next = 85;
221
- break;
222
-
223
- case 77:
224
- _context.prev = 77;
225
- _context.t1 = _context["catch"](54);
226
- (_spinner = spinner) == null ? void 0 : _spinner.stop();
227
- _context.next = 82;
228
- return (_generator = generator) == null ? void 0 : _generator.destroy();
229
-
230
- case 82:
231
- _context.next = 84;
232
- return (_config = config) == null ? void 0 : (_config$hooks = _config.hooks) == null ? void 0 : _config$hooks.fail == null ? void 0 : _config$hooks.fail();
233
-
234
- case 84:
235
- /* istanbul ignore next */
236
- consola.error(_context.t1);
237
-
238
- case 85:
239
- _context.next = 87;
240
- return (_config2 = config) == null ? void 0 : (_config2$hooks = _config2.hooks) == null ? void 0 : _config2$hooks.complete == null ? void 0 : _config2$hooks.complete();
241
-
242
- case 87:
243
- case "end":
244
- return _context.stop();
245
- }
246
- }
247
- }, _callee, null, [[54, 77]]);
248
- }));
249
- return _run.apply(this, arguments);
163
+ if (__require.main === module) {
164
+ const argv = yargs(process.argv).help(false).version(false).alias("c", "config").parseSync();
165
+ run(argv._[2], { configFile: argv.config ? path.resolve(process.cwd(), argv.config) : void 0 });
250
166
  }
251
-
252
- if (require.main === module) {
253
- var argv = yargs(process.argv).alias('c', 'config').argv;
254
- run(argv._[2], {
255
- configFile: argv.config ? path.resolve(process.cwd(), argv.config) : undefined
256
- });
257
- }
167
+ //#endregion
168
+ export { run };
@@ -0,0 +1,49 @@
1
+ import { CliHooks, Config, ConfigWithHooks, RequestConfig, RequestFunctionParams } from './types';
2
+ import { AppendOptions } from 'form-data';
3
+ /**
4
+ * 定义配置。
5
+ *
6
+ * @param config 配置
7
+ */
8
+ export declare function defineConfig(config: Config, hooks?: CliHooks): ConfigWithHooks;
9
+ export declare class FileData<T = any> {
10
+ /**
11
+ * 原始文件数据。
12
+ */
13
+ private originalFileData;
14
+ /**
15
+ * 选项。
16
+ */
17
+ private options;
18
+ /**
19
+ * 文件数据辅助类,统一网页、小程序等平台的文件上传。
20
+ *
21
+ * @param originalFileData 原始文件数据
22
+ * @param options 若使用内部的 getFormData,则选项会被其使用
23
+ */
24
+ constructor(originalFileData: T, options?: AppendOptions);
25
+ /**
26
+ * 获取原始文件数据。
27
+ *
28
+ * @returns 原始文件数据
29
+ */
30
+ getOriginalFileData(): T;
31
+ /**
32
+ * 获取选项。
33
+ */
34
+ getOptions(): AppendOptions | undefined;
35
+ }
36
+ /**
37
+ * 解析请求数据,从请求数据中分离出普通数据和文件数据。
38
+ *
39
+ * @param requestData 要解析的请求数据
40
+ * @returns 包含普通数据(data)和文件数据(fileData)的对象,data、fileData 为空对象时,表示没有此类数据
41
+ */
42
+ export declare function parseRequestData(requestData?: any): {
43
+ data: any;
44
+ fileData: any;
45
+ };
46
+ /**
47
+ * 准备要传给请求函数的参数。
48
+ */
49
+ export declare function prepare(requestConfig: RequestConfig, requestData: any): RequestFunctionParams;