anl 26.123.0 → 26.201.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,8 @@
1
- # an-cli
1
+ ## 🌐 Language / 语言
2
2
 
3
- [简体中文](./README.zh.md) | English | [Español](./README.es.md) | [العربية](./README.ar.md) | [Français](./README.fr.md) | [Русский](./README.ru.md) | [日本語](./README.jp.md)
3
+ [English](https://bianliuzhu.github.io/an-cli/#/en/) | [简体中文](https://bianliuzhu.github.io/an-cli/#/zh-cn/) | [日本語](https://bianliuzhu.github.io/an-cli/#/jp/) | [Español](https://bianliuzhu.github.io/an-cli/#/es/) | [Français](https://bianliuzhu.github.io/an-cli/#/fr/) | [Русский](https://bianliuzhu.github.io/an-cli/#/ru/) | [العربية](https://bianliuzhu.github.io/an-cli/#/ar/)
4
+
5
+ ---
4
6
 
5
7
  # Overview
6
8
 
@@ -10,7 +12,7 @@
10
12
  > - `anl lint` command: Generates eslint, stylelint, prettier, commitLint, and VSCode related configurations for React or Vue projects
11
13
  > - `anl git` command: Generates git local configuration with optional features: gitflow standard branch creation, git commit messages subject, and git custom command configuration
12
14
 
13
- # Features
15
+ ## Features
14
16
 
15
17
  - `anl type`
16
18
  - 🚀 Automatically parses Swagger JSON documentation
@@ -38,1384 +40,230 @@
38
40
  - 🔄 Provides git custom command configuration and entry points
39
41
  - 📦 Automated generation with zero configuration
40
42
 
41
- # Installation
42
-
43
- > [!NOTE]
44
- > Requires global installation
45
-
46
- ```bash
47
- $ npm install anl -g
48
- ```
49
-
50
- ```bash
51
- $ yarn global add anl
52
- ```
53
-
54
- ```bash
55
- $ pnpm add -g anl
56
- ```
43
+ ---
57
44
 
58
- # Usage
45
+ # 功能概述
59
46
 
60
- > [!TIP]
47
+ > an-cli 是前端命令行工具,包含以下命令:
61
48
  >
62
- > 1. If you're using it for the first time and unsure about the results, it's recommended to execute the command first, observe what changes occur in the project, then combine with the documentation to further modify the configuration and regenerate until you achieve your ideal setup
63
- > 2. Or follow the steps below step by step for results
64
- > 3. Please execute `anl type`, `anl lint`, `anl git` commands in the project root directory
49
+ > - `anl type` 命令:基于 Swagger JSON 自动生成 TypeScript 类型定义和 API 请求函数的命令行工具。
50
+ > - `anl lint` 命令: 生成 react vue 项目 eslint、stylelint、prettier、commitLint、VSCode相关配置
51
+ > - `anl git` 命令: 生成 git 本地配置,并设有可选功能: gitflow 标准分支创建、git commit messages 主题、git 自定义命令配置
65
52
 
66
- ## `anl type` Command Usage
53
+ ## 功能特点
67
54
 
68
- - **First time** executing the `anl type` command will automatically create a configuration file named `an.config.json` in the _project root directory_ (can also be created manually) to initialize the configuration template.
69
-
70
- - When executing the `anl type` command, it will look for the `an.config.json` configuration file in the user's project root directory, read its configuration information, and generate corresponding axios encapsulation, configuration, interface list, interface requests, and TS types for each interface request parameters and responses
71
-
72
- - Configuration items in the configuration file can be freely modified
73
-
74
- - About the `an.config.json` configuration file
75
- - The configuration file must be in the project root directory
55
+ - `anl type`
56
+ - 🚀 自动解析 Swagger JSON 文档
57
+ - 📦 生成 TypeScript 类型定义文件
58
+ - 🔄 生成类型安全的 API 请求函数
59
+ - 🎯 支持路径参数、查询参数和请求体
60
+ - 📝 自动生成枚举类型定义
61
+ - 🎨 支持代码格式化
62
+ - ⚡️ 支持文件上传
63
+ - 🛠 可配置的代码生成选项
64
+ - 🌐 支持多 Swagger 服务器配置
65
+ - 🔧 支持 OPTIONS、HEAD、SEARCH 等 HTTP 方法
76
66
 
77
- - The configuration file name cannot be changed
67
+ - `anl lint`
68
+ - 🔍 一键配置各种 lint 工具
69
+ - 🎨 ESLint 配置自动化
70
+ - 🎯Prettier 格式化配置
71
+ - 🔄 CommitLint 提交规范
72
+ - 📦 VSCode 编辑器配置
78
73
 
79
- - For specific parameter descriptions, see [Configuration File Details](#configuration-file-details)
74
+ - `anl git`
75
+ - 🔍 多种功能可选安装
76
+ - 🎨 标准 git flow 分支创建
77
+ - 🎯 符合 CommitLint 提交规范的主题自动设置
78
+ - 🔄 提供 git 自定义命令配置以及入口
79
+ - 📦 自动化生成 0 配置
80
80
 
81
- - Update the configuration file according to your needs, then execute the `anl type` command again, and it will generate corresponding type information according to the specified configuration information in the configuration file
81
+ ---
82
82
 
83
- - If files like 'config.ts', 'error-message.ts', 'fetch.ts', 'api-type.d.ts' exist, they will not be regenerated
83
+ # نظرة عامة على الوظائف
84
84
 
85
- > [!NOTE]
85
+ > an-cli هو أداة سطر أوامر للواجهة الأمامية، يتضمن الأوامر التالية:
86
86
  >
87
- > If you're unclear about these configurations, you can first execute the anl type command to generate the types, then check the project directory, combine with the configuration item descriptions, adjust the configuration items, and regenerate to gradually verify the role of configuration items and complete the final configuration
88
-
89
- ### Usage Method
90
-
91
- ```bash
92
- $ anl type
93
- ```
94
-
95
- ### Configuration File Details
96
-
97
- #### Configuration File Example
98
-
99
- **Single Swagger Server Configuration:**
100
-
101
- ```json
102
- {
103
- "saveTypeFolderPath": "apps/types",
104
- "saveApiListFolderPath": "apps/api/",
105
- "saveEnumFolderPath": "apps/enums",
106
- "importEnumPath": "../../enums",
107
- "requestMethodsImportPath": "./fetch",
108
- "formatting": {
109
- "indentation": "\t",
110
- "lineEnding": "\n"
111
- },
112
- "enmuConfig": {
113
- "erasableSyntaxOnly": false,
114
- "varnames": "enum-varnames",
115
- "comment": "enum-descriptions"
116
- },
117
- "swaggerConfig": {
118
- "url": "https://generator3.swagger.io/openapi2.json",
119
- "apiListFileName": "index.ts",
120
- "publicPrefix": "/api",
121
- "modulePrefix": "/gateway",
122
- "dataLevel": "serve",
123
- "parameterSeparator": "_",
124
- "headers": {
125
- "Authorization": "Bearer token"
126
- },
127
- "includeInterface": [
128
- {
129
- "path": "/api/user",
130
- "method": "get",
131
- "dataLevel": "data"
132
- }
133
- ],
134
- "excludeInterface": []
135
- }
136
- }
137
- ```
138
-
139
- **Multiple Swagger Servers Configuration:**
140
-
141
- ```json
142
- {
143
- "saveTypeFolderPath": "apps/types",
144
- "saveApiListFolderPath": "apps/api/",
145
- "saveEnumFolderPath": "apps/enums",
146
- "importEnumPath": "../../enums",
147
- "requestMethodsImportPath": "./fetch",
148
- "dataLevel": "serve",
149
- "formatting": {
150
- "indentation": "\t",
151
- "lineEnding": "\n"
152
- },
153
- "enmuConfig": {
154
- "erasableSyntaxOnly": false,
155
- "varnames": "enum-varnames",
156
- "comment": "enum-descriptions"
157
- },
158
- "swaggerConfig": [
159
- {
160
- "url": "https://generator3.swagger.io/openapi1.json",
161
- "apiListFileName": "op.ts",
162
- "modulePrefix": "/forward",
163
- "dataLevel": "serve",
164
- "parameterSeparator": "_",
165
- "headers": {},
166
- "includeInterface": [
167
- {
168
- "path": "/generate",
169
- "method": "post",
170
- "dataLevel": "axios"
171
- }
172
- ],
173
- "excludeInterface": []
174
- },
175
- {
176
- "url": "https://generator3.swagger.io/openapi2.json",
177
- "apiListFileName": "index.ts",
178
- "publicPrefix": "/api",
179
- "dataLevel": "data",
180
- "headers": {}
181
- }
182
- ]
183
- }
184
- ```
185
-
186
- #### Configuration Item Descriptions
187
-
188
- | Configuration Item | Type | Required | Description |
189
- | ---------------------------------------------------- | ------------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
190
- | saveTypeFolderPath | string | Yes | Type definition file save path |
191
- | saveApiListFolderPath | string | Yes | API request function file save path |
192
- | saveEnumFolderPath | string | Yes | Enum data file save path |
193
- | importEnumPath | string | Yes | Enum import path (path referenced by enum files in apps/types/models/\*.ts) |
194
- | swaggerJsonUrl | string | No | Swagger JSON documentation address (migrated to `swaggerConfig`, retained for backward compatibility) **This field will be removed in future versions** |
195
- | swaggerConfig | object \| Array<object> | No | Swagger server configuration. Single server can be an object, multiple servers use an array. Each server can configure `url`, `publicPrefix`, `modulePrefix`, `apiListFileName`, `headers`, `dataLevel`, `parameterSeparator`, `includeInterface`, `excludeInterface`, `responseModelTransform`<br />See single and multiple Swagger server configuration examples above |
196
- | swaggerConfig[].url | string | Yes | Swagger JSON documentation address |
197
- | swaggerConfig[].publicPrefix | string | No | Common prefix on url path, e.g.: api/users, api/users/{id}, api is the common prefix |
198
- | swaggerConfig[].apiListFileName | string | No | API list file name, defaults to `index.ts`. When using multiple servers, each server's file name must be unique |
199
- | swaggerConfig[].headers | object | No | Request header configuration for this server |
200
- | swaggerConfig[].modulePrefix | string | No | Request path prefix (can be understood as module name), automatically added to the front of each API request path.<br />For example: when `modulePrefix: "/forward"`<br />`/publicPrefix/modulePrefix/user` becomes `/api/forward/user` |
201
- | swaggerConfig[].dataLevel | 'data' \| 'serve' \| 'axios' | No | Interface return data level for this server. If not set, uses global `dataLevel` configuration |
202
- | swaggerConfig[].parameterSeparator | '$' \| '\_' | No | Separator used when generating API names and type names for this server. If not set, uses global `parameterSeparator` configuration |
203
- | swaggerConfig[].includeInterface | Array<{path: string, method: string, dataLevel?: 'data' \| 'serve' \| 'axios'}> | No | List of interfaces to include for this server. Each interface can configure `dataLevel` individually with the highest priority. If not set, uses global `includeInterface` configuration |
204
- | swaggerConfig[].excludeInterface | Array<{path: string, method: string}> | No | List of interfaces to exclude for this server. If not set, uses global `excludeInterface` configuration |
205
- | swaggerConfig[].responseModelTransform | object | No | Response model transformation configuration for this server. Supports three modes: `unwrap` (extract response model), `wrap` (add response model), `replace` (replace response model). If not set, uses global `responseModelTransform` configuration. See [Response Model Transform](#response-model-transform) |
206
- | swaggerConfig[].responseModelTransform.type | `'unwrap'` \| `'wrap'` \| `'replace'` | Yes | Response model transformation type. `unwrap`: Extract data field from response wrapper; `wrap`: Add unified wrapper structure to original response; `replace`: Replace response with custom type. See [Scenario 1](#scenario-1-add-response-model-to-interfaces-without-one-wrap), [Scenario 2](#scenario-2-remove-existing-response-model-unwrap), [Scenario 3](#scenario-3-replace-response-model-replace) |
207
- | swaggerConfig[].responseModelTransform.dataField | string | No | Data field name for `unwrap` and `wrap` modes, defaults to `"data"` |
208
- | swaggerConfig[].responseModelTransform.wrapperFields | Record<string, string> | No | Wrapper field definitions for `wrap` mode, key is field name, value is field type. Example: `{"success": "boolean", "code": "number", "message": "string", "data": "T"}` |
209
- | swaggerConfig[].responseModelTransform.wrapperType | string | No | Replacement type string for `replace` mode. Can be any TypeScript type, e.g.: `"ApiResponse<T>"` |
210
- | requestMethodsImportPath | string | Yes | Request method import path |
211
- | dataLevel | 'data' \| 'serve' \| 'axios' | No | Global interface return data level configuration, default: `'serve'`. Each server can override individually |
212
- | responseModelTransform | object | No | Global response model transformation configuration. Each server can override individually. Configuration items same as `swaggerConfig[].responseModelTransform`. See [Response Model Transform](#response-model-transform) |
213
- | formatting | object | No | Code formatting configuration |
214
- | formatting.indentation | string | No | Code indentation character, e.g.: `"\t"` or `" "` (two spaces) |
215
- | formatting.lineEnding | string | No | Line ending, e.g.: `"\n"` (LF) or `"\r\n"` (CRLF) |
216
- | headers | object | No | Request header configuration (migrated to `swaggerConfig`, retained for backward compatibility) |
217
- | includeInterface | Array<{path: string, method: string, dataLevel?: 'data' \| 'serve' \| 'axios'}> | No | Global included interfaces: The interface list file specified by `saveApiListFolderPath` will only include interfaces in the list, mutually exclusive with `excludeInterface` field. Each interface can configure `dataLevel` individually. Each server can override individually |
218
- | excludeInterface | Array<{path: string, method: string}> | No | Global excluded interfaces: The interface list file specified by `saveApiListFolderPath` will not include interfaces in this list, mutually exclusive with `includeInterface`. Each server can override individually |
219
- | publicPrefix | string | No | Global common prefix on url path (migrated to `swaggerConfig`, retained for backward compatibility) |
220
- | modulePrefix | string | No | Global request path prefix (each server can override individually) |
221
- | apiListFileName | string | No | Global API list file name, defaults to `index.ts` (migrated to `swaggerConfig`, retained for backward compatibility) |
222
- | enmuConfig | object | Yes | Enum configuration object |
223
- | enmuConfig.erasableSyntaxOnly | boolean | Yes | Align with tsconfig.json `compilerOptions.erasableSyntaxOnly`. When `true`, generates const objects instead of enums (type-only syntax). Default: `false` |
224
- | enmuConfig.varnames | string | No | Swagger schema field name for custom enum member names. Default: `enum-varnames`. |
225
- | enmuConfig.comment | string | No | Swagger schema field name for custom enum descriptions (used for generating comments). Default: `enum-descriptions`. |
226
- | parameterSeparator | '$' \| '\_' | No | Global separator used between path segments and parameters when generating API names and type names. For example, `/users/{userId}/posts` with separator `'_'` generates `users_userId_posts_GET`. Default: `'_'`. Each server can override individually |
227
- | enmuConfig.varnames | string | No | Schema field name that stores custom enum member identifiers. Default: `enum-varnames`. |
228
- | enmuConfig.comment | string | No | Schema field name that stores enum member descriptions (used for inline comments). Default: `enum-descriptions`. |
229
-
230
- #### Configuration Items and Generated Files Correspondence
231
-
232
- > File structure is generated based on configuration file, marked **uncontrolled** indicates: The folder and its files are automatically generated and not controlled by configuration items
233
-
234
- ```
235
- project/
236
- ├── apps/
237
- │ ├── types/ # Specified by saveTypeFolderPath configuration item
238
- │ │ ├── models/ # All type definition files (excluding enum types) uncontrolled
239
- │ │ ├── connectors/ # API type definitions (interface definition files) uncontrolled
240
- │ └── api/ # Request files: Specified by saveApiListFolderPath configuration item
241
- │ │ └── index.ts # API request function list (single server or first server) uncontrolled
242
- │ │ └── op.ts # Other servers' API list files when using multiple servers uncontrolled
243
- │ │ └── api-type.d.ts # Request type definition file uncontrolled
244
- │ │ └── config.ts # Request, response interceptor, request configuration uncontrolled
245
- │ │ └── error-message.ts # System-level error messages uncontrolled
246
- │ │ ├── fetch.ts # Axios request encapsulation, can be replaced with fetch uncontrolled
247
- │ └── enums/ # Enum data type definitions: Specified by saveEnumFolderPath configuration item
248
- ```
249
-
250
- ### Generated Code Examples
251
-
252
- #### Interface Type Definition
253
-
254
- ```typescript
255
- declare namespace UserDetail_GET {
256
- interface Query {
257
- userId: string;
258
- }
259
-
260
- interface Response {
261
- id: string;
262
- name: string;
263
- age: number;
264
- role: UserRole;
265
- }
266
- }
267
- ```
268
-
269
- #### API Request Function
270
-
271
- ```typescript
272
- import { GET } from './fetch';
273
-
274
- /**
275
- * Get user details
276
- */
277
- export const userDetailGet = (params: UserDetail_GET.Query) => GET<UserDetail_GET.Response>('/user/detail', params);
278
- ```
279
-
280
- ### Feature Descriptions
281
-
282
- #### Configuration Priority
87
+ > - أمر `anl type`: أداة سطر أوامر لتوليد تعريفات أنواع TypeScript ودوال طلبات API تلقائيًا بناءً على Swagger JSON.
88
+ > - أمر `anl lint`: توليد تكوينات eslint و stylelint و prettier و commitLint و VSCode ذات الصلة لمشاريع react أو vue
89
+ > - أمر `anl git`: توليد تكوين git المحلي، مع وظائف اختيارية: إنشاء فروع gitflow القياسية، موضوعات رسائل git commit، تكوين أوامر git المخصصة
283
90
 
284
- The tool supports global configuration and server-level configuration, following these priority rules:
91
+ ## الميزات الرئيسية
285
92
 
286
- **Priority: Interface-level configuration > Server-level configuration > Global configuration > Default values**
287
-
288
- The following configuration items support multi-level priority override:
289
-
290
- - `dataLevel`: Interface return data level
291
- - **Interface-level**: `includeInterface[].dataLevel` - Highest priority
292
- - **Server-level**: `swaggerConfig[].dataLevel` - Secondary priority
293
- - **Global configuration**: `dataLevel` - Base priority
294
- - **Default value**: `'serve'`
295
- - `parameterSeparator`: Separator for API names and type names
296
- - `includeInterface`: List of included interfaces
297
- - `excludeInterface`: List of excluded interfaces
298
- - `modulePrefix`: Request path prefix
299
- - `publicPrefix`: URL common prefix
300
- - `headers`: Request header configuration
301
-
302
- **Example:**
303
-
304
- ```json
305
- {
306
- "dataLevel": "serve",
307
- "parameterSeparator": "_",
308
- "swaggerConfig": [
309
- {
310
- "url": "http://api1.example.com/swagger.json",
311
- "dataLevel": "data",
312
- "apiListFileName": "api1.ts"
313
- },
314
- {
315
- "url": "http://api2.example.com/swagger.json",
316
- "apiListFileName": "api2.ts"
317
- }
318
- ]
319
- }
320
- ```
321
-
322
- In the above configuration:
323
-
324
- - `api1.ts` uses `dataLevel: "data"` (server-level configuration)
325
- - `api2.ts` uses `dataLevel: "serve"` (global configuration)
326
- - Both servers use `parameterSeparator: "_"` (global configuration)
327
-
328
- #### Type Parsing
329
-
330
- - Supports all OpenAPI 3.0 specification data types
331
- - Automatically handles complex nested types
332
- - Supports arrays, objects, enums, and other types
333
- - Automatically generates interface comments
334
-
335
- #### Enum Generation
336
-
337
- The tool supports two enum generation modes, controlled by the `enmuConfig.erasableSyntaxOnly` configuration:
338
-
339
- **Traditional Enum Mode** (`enmuConfig.erasableSyntaxOnly: false`, default):
340
-
341
- ```typescript
342
- export enum Status {
343
- Success = 'Success',
344
- Error = 'Error',
345
- Pending = 'Pending',
346
- }
347
- ```
348
-
349
- **Const Object Mode** (`enmuConfig.erasableSyntaxOnly: true`):
350
-
351
- ```typescript
352
- export const Status = {
353
- Success: 'Success',
354
- Error: 'Error',
355
- Pending: 'Pending',
356
- } as const;
357
-
358
- export type StatusType = (typeof Status)[keyof typeof Status];
359
- ```
360
-
361
- > **Why use const object mode?**
362
- > When TypeScript's `compilerOptions.erasableSyntaxOnly` is set to `true`, the code can only use type-erasable syntax. Traditional `enum` generates runtime code, while const objects are type-only and get completely erased during compilation. This ensures compatibility with build tools that require type-only syntax.
363
-
364
- **Usage in types:**
365
-
366
- ```typescript
367
- // Traditional enum mode
368
- interface User {
369
- status: Status; // Use enum as type directly
370
- }
371
-
372
- // Const object mode
373
- interface User {
374
- status: StatusType; // Use the generated type with 'Type' suffix
375
- }
376
- ```
377
-
378
- #### Data Level Configuration (dataLevel)
379
-
380
- `dataLevel` is used to configure the extraction level of interface return data, supporting three options:
381
-
382
- 1. **`'serve'` (default)**: Extracts the `data` field from server response
383
-
384
- ```typescript
385
- // Server returns: { code: 200, message: 'success', data: { id: 1, name: 'user' } }
386
- // Function returns: { id: 1, name: 'user' }
387
- ```
388
-
389
- 2. **`'data'`**: Extracts the `data.data` field (for nested data scenarios)
390
-
391
- ```typescript
392
- // Server returns: { data: { code: 200, data: { id: 1, name: 'user' } } }
393
- // Function returns: { id: 1, name: 'user' }
394
- ```
395
-
396
- 3. **`'axios'`**: Returns the complete axios response object
397
- ```typescript
398
- // Server returns: { code: 200, message: 'success', data: { id: 1, name: 'user' } }
399
- // Function returns: { code: 200, message: 'success', data: { id: 1, name: 'user' } }
400
- ```
401
-
402
- **Configuration Priority:**
403
-
404
- `dataLevel` supports three-level configuration priority:
405
-
406
- ```
407
- Interface-level > Server-level > Global configuration > Default value
408
- ```
93
+ - `anl type`
94
+ - 🚀 تحليل مستندات Swagger JSON تلقائيًا
95
+ - 📦 توليد ملفات تعريف أنواع TypeScript
96
+ - 🔄 توليد دوال طلبات API آمنة من حيث الأنواع
97
+ - 🎯 دعم معاملات المسار ومعاملات الاستعلام وجسم الطلب
98
+ - 📝 توليد تعريفات أنواع التعداد تلقائيًا
99
+ - 🎨 دعم تنسيق الكود
100
+ - ⚡️ دعم تحميل الملفات
101
+ - 🛠 خيارات توليد كود قابلة للتكوين
102
+ - 🌐 دعم تكوين خوادم Swagger متعددة
103
+ - 🔧 دعم طرق HTTP مثل OPTIONS و HEAD و SEARCH
409
104
 
410
- **Configuration example:**
105
+ - `anl lint`
106
+ - 🔍 تكوين أدوات lint المختلفة بنقرة واحدة
107
+ - 🎨 أتمتة تكوين ESLint
108
+ - 🎯 تكوين تنسيق Prettier
109
+ - 🔄 معيار التزام CommitLint
110
+ - 📦 تكوين محرر VSCode
411
111
 
412
- ```json
413
- {
414
- "dataLevel": "serve",
415
- "swaggerConfig": [
416
- {
417
- "url": "http://api1.example.com/swagger.json",
418
- "dataLevel": "data",
419
- "includeInterface": [
420
- {
421
- "path": "/api/user/detail",
422
- "method": "get",
423
- "dataLevel": "axios"
424
- },
425
- {
426
- "path": "/api/user/list",
427
- "method": "get"
428
- }
429
- ]
430
- }
431
- ]
432
- }
433
- ```
112
+ - `anl git`
113
+ - 🔍 تثبيت اختياري لوظائف متعددة
114
+ - 🎨 إنشاء فروع git flow القياسية
115
+ - 🎯 تعيين موضوع تلقائي يتوافق مع معيار CommitLint
116
+ - 🔄 توفير تكوين أوامر git المخصصة ونقطة الدخول
117
+ - 📦 توليد تلقائي بدون تكوين
434
118
 
435
- In the above configuration:
119
+ ---
436
120
 
437
- - `/api/user/detail` interface uses `dataLevel: "axios"` (interface-level configuration, highest priority)
438
- - `/api/user/list` interface uses `dataLevel: "data"` (server-level configuration)
439
- - Other server interfaces use `dataLevel: "serve"` (global configuration)
121
+ # Descripción General de Funciones
440
122
 
441
- > **Note**:
123
+ > an-cli es una herramienta de línea de comandos para frontend que incluye los siguientes comandos:
442
124
  >
443
- > - Interface-level `dataLevel` configuration has the highest priority, suitable for scenarios where individual interfaces need special handling
444
- > - Server-level `dataLevel` configuration will override global configuration
445
- > - Uses default value `'serve'` when not configured
446
-
447
- #### Code Formatting
448
-
449
- The tool supports custom code formatting options, controlled by the `formatting` configuration:
450
-
451
- **Configuration example:**
452
-
453
- ```json
454
- {
455
- "formatting": {
456
- "indentation": "\t",
457
- "lineEnding": "\n"
458
- }
459
- }
460
- ```
461
-
462
- **Configuration description:**
463
-
464
- - `indentation`: Code indentation character
465
- - `"\t"`: Use Tab indentation (default)
466
- - `" "`: Use 2 spaces indentation
467
- - `" "`: Use 4 spaces indentation
468
- - `lineEnding`: Line ending type
469
- - `"\n"`: LF (Linux/macOS style, recommended)
470
- - `"\r\n"`: CRLF (Windows style)
471
-
472
- **Note:** If Prettier is configured in the project, the generated code will automatically use Prettier for formatting, and the `formatting` configuration may be overridden by Prettier.
473
-
474
- #### File Upload
475
-
476
- When file upload types are detected, corresponding request headers are automatically added:
477
-
478
- ```typescript
479
- export const uploadFile = (params: UploadFile.Body) =>
480
- POST<UploadFile.Response>('/upload', params, {
481
- headers: { 'Content-Type': 'multipart/form-data' },
482
- });
483
- ```
484
-
485
- #### Error Handling
486
-
487
- The tool has built-in comprehensive error handling mechanisms:
488
-
489
- - Parse error prompts
490
- - Type generation failure warnings
491
- - File write exception handling
492
-
493
- #### Interface Filtering
494
-
495
- The tool supports filtering interfaces to be generated through configuration:
496
-
497
- 1. Include specific interfaces
498
- - Specify interfaces to be generated through the `includeInterface` configuration item
499
- - Only interfaces specified in the configuration will be generated
500
- - Configuration format is an object array containing `path`, `method`, and optional `dataLevel`
501
- - Each interface can configure `dataLevel` individually with the highest priority
502
-
503
- 2. Exclude specific interfaces
504
- - Specify interfaces to be excluded through the `excludeInterface` configuration item
505
- - All interfaces except those specified in the configuration will be generated
506
- - Configuration format is an object array containing `path` and `method`
507
-
508
- Example configuration: This configuration is in `an.config.json`
509
-
510
- ```json
511
- {
512
- "includeInterface": [
513
- {
514
- "path": "/api/user",
515
- "method": "get",
516
- "dataLevel": "data"
517
- }
518
- ],
519
- "excludeInterface": [
520
- {
521
- "path": "/api/admin",
522
- "method": "post"
523
- }
524
- ]
525
- }
526
- ```
527
-
528
- Note: `includeInterface` and `excludeInterface` cannot be used simultaneously. If both are configured, `includeInterface` will be prioritized.
529
-
530
- #### Multiple Swagger Servers Support
531
-
532
- The tool supports configuring multiple Swagger servers, each server can be configured independently:
533
-
534
- - **Single server**: `swaggerConfig` can be directly filled with an object
535
- - **Multiple servers**: `swaggerConfig` uses an array format, each server must configure a unique `apiListFileName`
536
-
537
- **How it works:**
538
-
539
- - The first server's APIs will be generated to the specified `apiListFileName` (defaults to `index.ts`)
540
- - Subsequent servers' APIs will be appended to their respective `apiListFileName` files
541
- - Type definitions and enums will be merged into a unified folder to avoid duplication
542
-
543
- **Server-level configuration:**
544
-
545
- Each server supports independent configuration of the following options. If not set, global configuration will be used:
546
-
547
- - `dataLevel` - Interface return data level
548
- - `parameterSeparator` - Separator for API names and type names
549
- - `includeInterface` - List of included interfaces
550
- - `excludeInterface` - List of excluded interfaces
551
- - `modulePrefix` - Request path prefix
552
-
553
- #### Path Prefix (modulePrefix)
554
-
555
- `modulePrefix` is used to automatically add a prefix to all API request paths, which is particularly useful in the following scenarios:
556
-
557
- 1. **Reverse proxy scenarios**: When backend services are forwarded through a reverse proxy
558
- 2. **API Gateway**: Uniformly add gateway prefix to paths
559
- 3. **Multi-environment configuration**: Use different path prefixes for different environments
560
-
561
- **Usage example:**
562
-
563
- ```json
564
- {
565
- "swaggerConfig": [
566
- {
567
- "url": "http://api.example.com/swagger.json",
568
- "modulePrefix": "/forward",
569
- "apiListFileName": "api.ts"
570
- }
571
- ]
572
- }
573
- ```
574
-
575
- **Effect:**
576
-
577
- The path `/api/user/list` defined in Swagger will be generated as:
578
-
579
- ```typescript
580
- export const apiUserListGet = (params: ApiUserList_GET.Query) => GET<ApiUserList_GET.Response>('/forward/api/user/list', params);
581
- ```
582
-
583
- **Difference from publicPrefix:**
584
-
585
- - `publicPrefix`: Used to remove common prefix from interface paths (only affects generated function names)
586
- - `modulePrefix`: Used to add prefix to actual request paths (affects runtime request URLs)
587
-
588
- **Configuration example:**
589
-
590
- ```json
591
- {
592
- "swaggerConfig": [
593
- {
594
- "url": "http://api1.example.com/swagger.json",
595
- "apiListFileName": "api1.ts",
596
- "publicPrefix": "/api/v1",
597
- "modulePrefix": "/forward",
598
- "dataLevel": "serve",
599
- "parameterSeparator": "_",
600
- "headers": {
601
- "Authorization": "Bearer token1"
602
- },
603
- "includeInterface": [
604
- {
605
- "path": "/api/v1/users",
606
- "method": "get"
607
- }
608
- ]
609
- },
610
- {
611
- "url": "http://api2.example.com/swagger.json",
612
- "apiListFileName": "api2.ts",
613
- "publicPrefix": "/api/v2",
614
- "dataLevel": "data",
615
- "headers": {
616
- "Authorization": "Bearer token2"
617
- }
618
- }
619
- ]
620
- }
621
- ```
622
-
623
- **Migration notes:**
624
-
625
- - Old configuration (`swaggerJsonUrl`, `publicPrefix`, `headers`) is still compatible
626
- - The tool will automatically detect old configuration and suggest migration methods
627
- - It's recommended to migrate to the new `swaggerConfig` configuration for better flexibility
628
-
629
- #### HTTP Method Support
630
-
631
- The tool supports the following HTTP methods:
632
-
633
- - `GET` - Get resources
634
- - `POST` - Create resources
635
- - `PUT` - Update resources (full replacement)
636
- - `PATCH` - Update resources (partial update)
637
- - `DELETE` - Delete resources
638
- - `OPTIONS` - Preflight requests
639
- - `HEAD` - Get response headers
640
- - `SEARCH` - Search requests
641
-
642
- All methods support type-safe parameter and response type definitions.
643
-
644
- #### Response Model Transform
645
-
646
- The response model transformation feature allows you to automatically transform Swagger/OpenAPI response types when generating TypeScript types. It supports three transformation modes:
647
-
648
- 1. **unwrap (extract response model)**: Extract the data field from the response wrapper
649
- 2. **wrap (add response model)**: Add a unified wrapper structure to the original response
650
- 3. **replace (replace response model)**: Replace the response with a custom type
651
-
652
- ##### Configuration Location
653
-
654
- Add `responseModelTransform` configuration in the `swaggerConfig` of your `an.config.json` file:
655
-
656
- ```json
657
- {
658
- "swaggerConfig": [
659
- {
660
- "url": "./data/api.json",
661
- "apiListFileName": "api.ts",
662
- "responseModelTransform": {
663
- // configuration items
664
- }
665
- }
666
- ]
667
- }
668
- ```
669
-
670
- ##### Scenario 1: Add Response Model to Interfaces Without One (wrap)
671
-
672
- **Use Case**
673
-
674
- When Swagger definitions directly return data objects, but actual API responses contain a unified wrapper structure.
675
-
676
- **Problem Example**
677
-
678
- Swagger definition directly returns user data:
679
-
680
- ```json
681
- {
682
- "paths": {
683
- "/api/user/current": {
684
- "get": {
685
- "responses": {
686
- "200": {
687
- "content": {
688
- "application/json": {
689
- "schema": {
690
- "$ref": "#/components/schemas/UsersEntityDto"
691
- }
692
- }
693
- }
694
- }
695
- }
696
- }
697
- }
698
- }
699
- }
700
- ```
701
-
702
- Generated type (without response model):
703
-
704
- ```typescript
705
- declare namespace ApiUserCurrent_GET {
706
- type Response = import('../models/users-entity-dto').UsersEntityDto;
707
- }
708
- ```
709
-
710
- Actual API response:
711
-
712
- ```json
713
- {
714
- "success": true,
715
- "code": 0,
716
- "message": "success",
717
- "data": {
718
- "uid": "user123",
719
- "username": "Zhang San",
720
- "email": "zhangsan@example.com"
721
- }
722
- }
723
- ```
724
-
725
- **Solution**
726
-
727
- Add `wrap` type response model transformation in configuration:
125
+ > - Comando `anl type`: Herramienta de línea de comandos que genera automáticamente definiciones de tipos TypeScript y funciones de solicitud API basadas en Swagger JSON.
126
+ > - Comando `anl lint`: Genera configuraciones de eslint, stylelint, prettier, commitLint y VSCode para proyectos React o Vue.
127
+ > - Comando `anl git`: Genera configuración local de git con funciones opcionales: creación de ramas estándar gitflow, temas de mensajes git commit y configuración de comandos personalizados de git.
728
128
 
729
- ```json
730
- {
731
- "swaggerConfig": [
732
- {
733
- "url": "./data/df.json",
734
- "apiListFileName": "df.ts",
735
- "responseModelTransform": {
736
- "type": "wrap",
737
- "dataField": "data",
738
- "wrapperFields": {
739
- "success": "boolean",
740
- "code": "number",
741
- "message": "string",
742
- "data": "T"
743
- }
744
- }
745
- }
746
- ]
747
- }
748
- ```
129
+ ## Características
749
130
 
750
- **Configuration Description**
751
-
752
- | Field | Type | Required | Description |
753
- | --------------- | ------------------------ | -------- | ----------------------------------------------------------------- |
754
- | `type` | `"wrap"` | Yes | Transformation type, fixed as `"wrap"` |
755
- | `dataField` | `string` | No | Field name where original data is placed, defaults to `"data"` |
756
- | `wrapperFields` | `Record<string, string>` | Yes | Wrapper field definitions, key is field name, value is field type |
757
-
758
- **Transformed Type**
759
-
760
- ```typescript
761
- declare namespace ApiUserCurrent_GET {
762
- interface Response {
763
- success?: boolean;
764
- code?: number;
765
- message?: string;
766
- data?: import('../models/users-entity-dto').UsersEntityDto;
767
- }
768
- }
769
- ```
770
-
771
- **Usage Example**
772
-
773
- ```typescript
774
- import { apiUserCurrent_GET } from './api/df';
775
-
776
- const response = await apiUserCurrent_GET();
777
- // response type is:
778
- // {
779
- // success?: boolean;
780
- // code?: number;
781
- // message?: string;
782
- // data?: UsersEntityDto;
783
- // }
784
-
785
- if (response.success && response.data) {
786
- console.log(response.data.username);
787
- }
788
- ```
789
-
790
- ##### Scenario 2: Remove Existing Response Model (unwrap)
791
-
792
- **Use Case**
793
-
794
- When Swagger definitions include a response wrapper, but you want to use the internal data type directly.
795
-
796
- **Problem Example**
797
-
798
- Swagger definition includes `ResultMessageBoolean` response wrapper:
799
-
800
- ```json
801
- {
802
- "paths": {
803
- "/op/trade/refund_order/createOrder": {
804
- "post": {
805
- "responses": {
806
- "200": {
807
- "content": {
808
- "*/*": {
809
- "schema": {
810
- "$ref": "#/components/schemas/ResultMessageBoolean"
811
- }
812
- }
813
- }
814
- }
815
- }
816
- }
817
- }
818
- },
819
- "components": {
820
- "schemas": {
821
- "ResultMessageBoolean": {
822
- "type": "object",
823
- "properties": {
824
- "success": { "type": "boolean" },
825
- "msg": { "type": "string" },
826
- "code": { "type": "integer" },
827
- "timestamp": { "type": "integer" },
828
- "data": { "type": "boolean" }
829
- }
830
- }
831
- }
832
- }
833
- }
834
- ```
835
-
836
- Generated type (with response model):
837
-
838
- ```typescript
839
- declare namespace OpTradeRefundOrderCreateorder_POST {
840
- type Body = import('../models/refund-order-create-dto').RefundOrderCreateDTO;
841
- type Response = import('../models/result-message-boolean').ResultMessageBoolean;
842
- }
843
- ```
844
-
845
- Desired type (only data field):
846
-
847
- ```typescript
848
- declare namespace OpTradeRefundOrderCreateorder_POST {
849
- type Body = import('../models/refund-order-create-dto').RefundOrderCreateDTO;
850
- type Response = boolean;
851
- }
852
- ```
853
-
854
- **Solution**
855
-
856
- Add `unwrap` type response model transformation in configuration:
857
-
858
- ```json
859
- {
860
- "swaggerConfig": [
861
- {
862
- "url": "./data/op.json",
863
- "apiListFileName": "op.ts",
864
- "responseModelTransform": {
865
- "type": "unwrap",
866
- "dataField": "data"
867
- }
868
- }
869
- ]
870
- }
871
- ```
872
-
873
- **Configuration Description**
874
-
875
- | Field | Type | Required | Description |
876
- | ----------- | ---------- | -------- | ------------------------------------------- |
877
- | `type` | `"unwrap"` | Yes | Transformation type, fixed as `"unwrap"` |
878
- | `dataField` | `string` | No | Field name to extract, defaults to `"data"` |
879
-
880
- **Transformed Type**
881
-
882
- ```typescript
883
- declare namespace OpTradeRefundOrderCreateorder_POST {
884
- type Body = import('../models/refund-order-create-dto').RefundOrderCreateDTO;
885
- type Response = boolean;
886
- }
887
- ```
888
-
889
- **More Examples**
890
-
891
- Example 1: Extract paginated data
892
-
893
- ```typescript
894
- // Original type:
895
- type Response = import('../models/result-message-ipage-refund-order-query-vo').ResultMessageIPageRefundOrderQueryVO
896
-
897
- // Configuration:
898
- {
899
- "responseModelTransform": {
900
- "type": "unwrap",
901
- "dataField": "data"
902
- }
903
- }
904
-
905
- // Transformed:
906
- type Response = import('../models/ipage-refund-order-query-vo').IPageRefundOrderQueryVO
907
- ```
908
-
909
- Example 2: Extract custom field
910
-
911
- If the response model's data field is not `data`, but `result`:
912
-
913
- ```json
914
- {
915
- "responseModelTransform": {
916
- "type": "unwrap",
917
- "dataField": "result"
918
- }
919
- }
920
- ```
921
-
922
- ##### Scenario 3: Replace Response Model (replace)
923
-
924
- **Use Case**
925
-
926
- When you want to completely replace the original response type with a custom generic type or other types.
927
-
928
- **Problem Example**
929
-
930
- Original response type:
931
-
932
- ```typescript
933
- type Response = import('../models/activity-response-dto-ilist-service-response').ActivityResponseDTOIListServiceResponse;
934
- ```
935
-
936
- Desired type:
937
-
938
- ```typescript
939
- type Response = ApiResponse<ActivityData>;
940
- ```
941
-
942
- **Solution**
943
-
944
- Add `replace` type response model transformation in configuration:
945
-
946
- ```json
947
- {
948
- "swaggerConfig": [
949
- {
950
- "url": "./data/sau.json",
951
- "apiListFileName": "sau.ts",
952
- "responseModelTransform": {
953
- "type": "replace",
954
- "wrapperType": "ApiResponse<T>"
955
- }
956
- }
957
- ]
958
- }
959
- ```
960
-
961
- **Configuration Description**
962
-
963
- | Field | Type | Required | Description |
964
- | ------------- | ----------- | -------- | ----------------------------------------- |
965
- | `type` | `"replace"` | Yes | Transformation type, fixed as `"replace"` |
966
- | `wrapperType` | `string` | Yes | Replacement type string |
967
-
968
- **Transformed Type**
969
-
970
- ```typescript
971
- declare namespace ApiActivityServicevisitServiceVisitId_GET {
972
- type Response = ApiResponse<T>;
973
- }
974
- ```
975
-
976
- **Notes**
977
-
978
- - `wrapperType` can be any TypeScript type string
979
- - If using generic types (like `ApiResponse<T>`), ensure the type is defined in your project
980
- - Usually need to define custom types in `api-type.d.ts`:
981
-
982
- ```typescript
983
- // apps/api/api-type.d.ts
984
- type ApiResponse<T> = {
985
- code: number;
986
- message: string;
987
- data: T;
988
- success: boolean;
989
- };
990
- ```
991
-
992
- ##### Complete Configuration Example
993
-
994
- ```json
995
- {
996
- "saveTypeFolderPath": "apps/types",
997
- "saveApiListFolderPath": "apps/api/",
998
- "saveEnumFolderPath": "apps/enums",
999
- "importEnumPath": "../../enums",
1000
- "requestMethodsImportPath": "./fetch",
1001
- "formatting": {
1002
- "indentation": "\t",
1003
- "lineEnding": "\n"
1004
- },
1005
- "enmuConfig": {
1006
- "erasableSyntaxOnly": false,
1007
- "varnames": "enum-varnames",
1008
- "comment": "enum-descriptions"
1009
- },
1010
- "swaggerConfig": [
1011
- {
1012
- "url": "./data/op.json",
1013
- "apiListFileName": "op.ts",
1014
- "publicPrefix": "/forward",
1015
- "dataLevel": "serve",
1016
- "parameterSeparator": "_",
1017
- "responseModelTransform": {
1018
- "type": "unwrap",
1019
- "dataField": "data"
1020
- }
1021
- },
1022
- {
1023
- "url": "./data/df.json",
1024
- "apiListFileName": "df.ts",
1025
- "publicPrefix": "/api",
1026
- "dataLevel": "serve",
1027
- "parameterSeparator": "_",
1028
- "responseModelTransform": {
1029
- "type": "wrap",
1030
- "dataField": "data",
1031
- "wrapperFields": {
1032
- "success": "boolean",
1033
- "code": "number",
1034
- "message": "string",
1035
- "data": "T"
1036
- }
1037
- }
1038
- },
1039
- {
1040
- "url": "./data/sau.json",
1041
- "apiListFileName": "sau.ts",
1042
- "publicPrefix": "/api",
1043
- "dataLevel": "serve",
1044
- "parameterSeparator": "_",
1045
- "responseModelTransform": {
1046
- "type": "replace",
1047
- "wrapperType": "CustomApiResponse"
1048
- }
1049
- }
1050
- ]
1051
- }
1052
- ```
1053
-
1054
- ##### Common Questions
1055
-
1056
- **Q1: Can different interfaces use different transformations?**
1057
-
1058
- A: Currently, transformation configuration is per Swagger service. If you need different transformations for different interfaces in the same Swagger file, you can:
1059
-
1060
- 1. Split the Swagger into multiple files
1061
- 2. Use `includeInterface` and `excludeInterface` to configure different Swagger services for different interface groups
1062
-
1063
- **Q2: What if unwrap transformation fails?**
1064
-
1065
- A: unwrap transformation requires:
1066
-
1067
- 1. Response type must be a `$ref` reference type (not an inline object)
1068
- 2. The referenced schema must contain the specified `dataField` (defaults to `data`)
1069
- 3. If transformation fails, the original type will be kept unchanged, and a warning will be logged
1070
-
1071
- **Q3: What if the original type is an object when using wrap transformation?**
1072
-
1073
- A: If the original response type is an inline object (with multiple fields), wrap transformation will use the entire object as the value of the `data` field.
1074
-
1075
- **Q4: What happens if responseModelTransform is not configured?**
1076
-
1077
- A: If not configured, the generated types will exactly match the Swagger definitions without any transformation.
1078
-
1079
- **Q5: Can I configure a default transformation globally?**
1080
-
1081
- A: Yes, you can configure `responseModelTransform` at the root level outside of `swaggerConfig`, and all services without configuration will inherit it:
1082
-
1083
- ```json
1084
- {
1085
- "responseModelTransform": {
1086
- "type": "unwrap",
1087
- "dataField": "data"
1088
- },
1089
- "swaggerConfig": [
1090
- {
1091
- "url": "./data/op.json",
1092
- "apiListFileName": "op.ts"
1093
- // Will use global configuration
1094
- },
1095
- {
1096
- "url": "./data/df.json",
1097
- "apiListFileName": "df.ts",
1098
- "responseModelTransform": {
1099
- "type": "wrap",
1100
- "dataField": "data",
1101
- "wrapperFields": {
1102
- "success": "boolean",
1103
- "data": "T"
1104
- }
1105
- }
1106
- // Will override global configuration
1107
- }
1108
- ]
1109
- }
1110
- ```
1111
-
1112
- ##### Best Practices
1113
-
1114
- **1. Unified Response Model Standards**
1115
-
1116
- If your backend APIs use a unified response format, it's recommended to:
1117
-
1118
- - Use `wrap` transformation for Swagger without response models
1119
- - Use `unwrap` transformation for Swagger with different response models
1120
- - Ultimately maintain consistent response types for all APIs
1121
-
1122
- **2. Use with api-type.d.ts**
1123
-
1124
- Define unified response types in `apps/api/api-type.d.ts`:
1125
-
1126
- ```typescript
1127
- type ResponseModel<T> = {
1128
- code: number;
1129
- message: string;
1130
- data: T;
1131
- success: boolean;
1132
- };
1133
- ```
1134
-
1135
- Then use consistently in code:
1136
-
1137
- ```typescript
1138
- export const apiUserCurrent_GET = (params?: IRequestFnParams) => GET<ResponseModel<UsersEntityDto>>(`/api/user/current`, { ...params }, 'serve');
1139
- ```
1140
-
1141
- **3. Progressive Migration**
1142
-
1143
- If the project is already using old type definitions, it's recommended to:
1144
-
1145
- 1. First configure response model transformation for new Swagger services
1146
- 2. Gradually migrate old services
1147
- 3. Use version control tools to ensure changes are reversible
1148
-
1149
- ##### Technical Details
1150
-
1151
- **Transformation Timing**
1152
-
1153
- Response model transformation occurs during the type generation phase, the specific process:
1154
-
1155
- 1. Parse Swagger/OpenAPI documentation
1156
- 2. Parse response types
1157
- 3. Apply `responseModelTransform` configuration
1158
- 4. Generate final TypeScript type definition files
1159
-
1160
- **Supported Response Types**
1161
-
1162
- - ✅ `$ref` reference types (e.g., `#/components/schemas/ResultMessageBoolean`)
1163
- - ✅ Inline object types (e.g., `{ type: 'object', properties: {...} }`)
1164
- - ✅ Primitive types (e.g., `string`, `number`, `boolean`)
1165
- - ✅ Array types (e.g., `Array<T>`)
1166
- - ✅ Union types (e.g., `string | number`)
1167
-
1168
- **Unsupported Scenarios**
1169
-
1170
- - ❌ Unwrap transformation for inline object types (cannot extract fields from schema)
1171
- - ❌ Dynamic field extraction (must explicitly specify `dataField`)
1172
-
1173
- ### Notes
1174
-
1175
- 1. Ensure the Swagger JSON documentation address is accessible
1176
- 2. Paths in the configuration file need to be relative to the project root directory
1177
- 3. Generated files will overwrite existing files with the same name (but `config.ts`, `error-message.ts`, `fetch.ts`, `api-type.d.ts` will not be overwritten if they already exist)
1178
- 4. It's recommended to add generated files to version control
1179
- 5. When using multiple Swagger servers, ensure each server's `apiListFileName` is unique to avoid file overwriting
1180
- 6. When configuring multiple servers, type definitions and enums will be merged. If different servers have types with the same name, conflicts may occur
1181
- 7. Server-level configuration (`dataLevel`, `parameterSeparator`, `includeInterface`, `excludeInterface`, `modulePrefix`, `responseModelTransform`) will override global configuration
1182
- 8. `includeInterface` and `excludeInterface` cannot be configured simultaneously. If both are configured, `includeInterface` will be prioritized
1183
- 9. When using `responseModelTransform`, ensure the configuration is correct, otherwise it may cause type generation errors
1184
- 10. `unwrap` transformation requires the response type to be a `$ref` reference type and contain the specified `dataField`
1185
-
1186
- ### Common Issues
1187
-
1188
- 1. **Generated type file formatting fails**
1189
- - Check if prettier is installed
1190
- - Confirm if there's a prettier configuration file in the project root directory
1191
- - Check if the `formatting` configuration is correct
1192
-
1193
- 2. **Request function import path error**
1194
- - Check if the `requestMethodsImportPath` configuration is correct
1195
- - Confirm if the request method file exists
1196
-
1197
- 3. **When to use `modulePrefix`?**
1198
- - When your APIs need to be accessed through a reverse proxy or gateway
1199
- - For example: Swagger defines `/api/user`, but the actual request needs to be `/gateway/api/user`
1200
- - Set `modulePrefix: "/gateway"` to achieve this
1201
-
1202
- 4. **What's the difference between `publicPrefix` and `modulePrefix`?**
1203
- - `publicPrefix`: Removes prefix from interface paths, only affects generated function names
1204
- - Example: `/api/user/list` after removing `/api`, function name becomes `userListGet`
1205
- - `modulePrefix`: Adds prefix to request paths, affects actual request URLs
1206
- - Example: `/api/user/list` after adding `/forward`, request URL becomes `/forward/api/user/list`
1207
-
1208
- 5. **How to configure different `dataLevel` for multiple servers?**
1209
-
1210
- ```json
1211
- {
1212
- "dataLevel": "serve",
1213
- "swaggerConfig": [
1214
- {
1215
- "url": "http://old-api.com/swagger.json",
1216
- "dataLevel": "axios",
1217
- "apiListFileName": "old-api.ts"
1218
- },
1219
- {
1220
- "url": "http://new-api.com/swagger.json",
1221
- "apiListFileName": "new-api.ts"
1222
- }
1223
- ]
1224
- }
1225
- ```
1226
-
1227
- - `old-api.ts` uses `dataLevel: "axios"`
1228
- - `new-api.ts` uses the global `dataLevel: "serve"`
1229
-
1230
- 6. **How to configure different `dataLevel` for individual interfaces?**
1231
-
1232
- ```json
1233
- {
1234
- "dataLevel": "serve",
1235
- "swaggerConfig": [
1236
- {
1237
- "url": "http://api.com/swagger.json",
1238
- "apiListFileName": "api.ts",
1239
- "dataLevel": "data",
1240
- "includeInterface": [
1241
- {
1242
- "path": "/api/user/detail",
1243
- "method": "get",
1244
- "dataLevel": "axios"
1245
- },
1246
- {
1247
- "path": "/api/user/list",
1248
- "method": "get"
1249
- }
1250
- ]
1251
- }
1252
- ]
1253
- }
1254
- ```
1255
-
1256
- - `/api/user/detail` uses interface-level `dataLevel: "axios"` (highest priority)
1257
- - `/api/user/list` uses server-level `dataLevel: "data"`
1258
- - Other server interfaces use global `dataLevel: "serve"`
1259
-
1260
- 7. **How to generate only specific interfaces?**
1261
- - Use `includeInterface` configuration:
1262
- ```json
1263
- {
1264
- "swaggerConfig": [
1265
- {
1266
- "url": "http://api.com/swagger.json",
1267
- "includeInterface": [
1268
- { "path": "/api/user", "method": "get" },
1269
- { "path": "/api/user/{id}", "method": "post" }
1270
- ]
1271
- }
1272
- ]
1273
- }
1274
- ```
1275
- - Or use `excludeInterface` to exclude unwanted interfaces
1276
-
1277
- 8. **What if generated files are overwritten?**
1278
- - Files like `config.ts`, `error-message.ts`, `fetch.ts`, `api-type.d.ts` are only generated when they don't exist
1279
- - API list files and type files are regenerated each time
1280
- - It's recommended to add generated files to version control for easy tracking of changes
131
+ - `anl type`
132
+ - 🚀 Análisis automático de documentos Swagger JSON
133
+ - 📦 Generación de archivos de definición de tipos TypeScript
134
+ - 🔄 Generación de funciones de solicitud API con seguridad de tipos
135
+ - 🎯 Soporte para parámetros de ruta, parámetros de consulta y cuerpo de solicitud
136
+ - 📝 Generación automática de definiciones de tipos enum
137
+ - 🎨 Soporte para formateo de código
138
+ - ⚡️ Soporte para carga de archivos
139
+ - 🛠 Opciones de generación de código configurables
140
+ - 🌐 Soporte para configuración de múltiples servidores Swagger
141
+ - 🔧 Soporte para métodos HTTP como OPTIONS, HEAD, SEARCH
1281
142
 
1282
- 9. **How to use response model transformation?**
1283
- - See [Response Model Transform](#response-model-transform) section
1284
- - Supports `unwrap` (extract), `wrap` (add), `replace` (replace) three transformation modes
1285
- - Can be configured globally or individually for each server
143
+ - `anl lint`
144
+ - 🔍 Configuración de varias herramientas lint con un solo clic
145
+ - 🎨 Automatización de configuración ESLint
146
+ - 🎯 Configuración de formateo Prettier
147
+ - 🔄 Especificaciones de commits CommitLint
148
+ - 📦 Configuración del editor VSCode
1286
149
 
1287
- 10. **What if response model transformation fails?**
1288
- - Check if configuration items are correct, especially the `type` field
1289
- - `unwrap` mode requires the response type to be a `$ref` reference type
1290
- - `wrap` mode requires configuration of `wrapperFields` field
1291
- - `replace` mode requires configuration of `wrapperType` field
1292
- - Check console logs, which usually output detailed error information
150
+ - `anl git`
151
+ - 🔍 Instalación opcional de múltiples funciones
152
+ - 🎨 Creación de ramas estándar git flow
153
+ - 🎯 Configuración automática de temas que cumplen con las especificaciones CommitLint
154
+ - 🔄 Proporciona configuración de comandos personalizados de git y punto de entrada
155
+ - 📦 Generación automatizada con 0 configuración
1293
156
 
1294
- 11. **Can different interfaces use different response model transformations?**
1295
- - Currently, transformation configuration is per Swagger service granularity
1296
- - If different transformations are needed for different interfaces in the same Swagger file, you can:
1297
- 1. Split the Swagger into multiple files
1298
- 2. Use `includeInterface` and `excludeInterface` to configure different Swagger services for different interface groups
157
+ ---
1299
158
 
1300
- # `anl lint` Command Usage
159
+ # Aperçu des fonctionnalités
1301
160
 
1302
- > Provides **interactive multi-select** configuration for various lint tools in frontend projects, including:
161
+ > an-cli est un outil de ligne de commande frontend qui inclut les commandes suivantes :
1303
162
  >
1304
- > - ESLint - JavaScript/TypeScript code linting
1305
- > - Stylelint - CSS/SCSS/Less style linting
1306
- > - Prettier - Code formatting
1307
- > - CommitLint - Git commit message standards
1308
- > - VSCode - Editor configuration
1309
-
1310
- ### Usage Method
1311
-
1312
- ```bash
1313
- $ anl lint
1314
- ```
1315
-
1316
- After executing the command, an interactive multi-select interface will appear where you can choose the tools to install:
1317
-
1318
- ```
1319
- ? Select the linting tools to install (multi-select):
1320
- ❯◯ ESLint - JavaScript/TypeScript linter
1321
- ◯ Stylelint - CSS/SCSS/Less linter
1322
- ◯ Commitlint - Git commit message linter
1323
- ◯ Prettier - Code formatter
1324
- ◯ VSCode - Editor settings
1325
- ```
1326
-
1327
- Use **spacebar** to select/deselect, **Enter** to confirm.
1328
-
1329
- ### Configuration Details
1330
-
1331
- #### 1. ESLint Configuration
1332
-
1333
- - Automatically installs required dependencies
1334
- - Supports React/Vue frameworks (you'll be prompted to choose a framework if selected)
1335
- - Automatically generates `.eslintrc.js` and `.eslintignore`
1336
- - Integrates TypeScript support
1337
-
1338
- #### 2. Stylelint Configuration
163
+ > - Commande `anl type` : Un outil de ligne de commande qui génère automatiquement des définitions de types TypeScript et des fonctions de requête API basées sur Swagger JSON.
164
+ > - Commande `anl lint` : Génère les configurations eslint, stylelint, prettier, commitLint et VSCode pour les projets React ou Vue
165
+ > - Commande `anl git` : Génère la configuration locale Git avec des fonctionnalités optionnelles : création de branches selon le standard gitflow, thèmes de messages git commit, configuration de commandes git personnalisées
1339
166
 
1340
- - Automatically installs stylelint related dependencies
1341
- - Supports Less/Sass preprocessors (you'll be prompted to choose a preprocessor if selected)
1342
- - Generates `.stylelintrc.js` configuration file
1343
- - Integrates Prettier support
167
+ ## Caractéristiques
1344
168
 
1345
- #### 3. Prettier Configuration
1346
-
1347
- - Automatically installs prettier related dependencies
1348
- - Generates `.prettierrc.js` configuration file
1349
- - Default configuration includes:
1350
- - Line width: 80
1351
- - Tab indentation
1352
- - Use single quotes
1353
- - Arrow function parentheses
1354
- - Other code style standards
1355
-
1356
- #### 4. CommitLint Configuration
1357
-
1358
- - Installs commitlint related dependencies
1359
- - Configures husky git hooks
1360
- - Generates `commitlint.config.js`
1361
- - Standardizes git commit messages
1362
-
1363
- #### 5. VSCode Configuration
1364
-
1365
- - Creates `.vscode/settings.json`
1366
- - Configures editor auto-formatting
1367
- - Sets default formatting tools
1368
- - Supports updating existing configuration files
169
+ - `anl type`
170
+ - 🚀 Analyse automatique des documents Swagger JSON
171
+ - 📦 Génération de fichiers de définition de types TypeScript
172
+ - 🔄 Génération de fonctions de requête API type-safe
173
+ - 🎯 Support des paramètres de chemin, de requête et de corps
174
+ - 📝 Génération automatique de définitions de types enum
175
+ - 🎨 Support du formatage de code
176
+ - ⚡️ Support du téléchargement de fichiers
177
+ - 🛠 Options de génération de code configurables
178
+ - 🌐 Support de la configuration de plusieurs serveurs Swagger
179
+ - 🔧 Support des méthodes HTTP OPTIONS, HEAD, SEARCH, etc.
1369
180
 
1370
- ### Usage Examples
181
+ - `anl lint`
182
+ - 🔍 Configuration en un clic de divers outils lint
183
+ - 🎨 Configuration ESLint automatisée
184
+ - 🎯 Configuration de formatage Prettier
185
+ - 🔄 Normes de commit CommitLint
186
+ - 📦 Configuration de l'éditeur VSCode
1371
187
 
1372
- 1. **Install ESLint and Prettier Only**
1373
- - Select ESLint and Prettier
1374
- - If ESLint is selected, you'll be prompted to choose a framework (React/Vue)
1375
- - After installation, your project will have `.eslintrc.js` and `.prettierrc.js`
188
+ - `anl git`
189
+ - 🔍 Installation optionnelle de plusieurs fonctionnalités
190
+ - 🎨 Création de branches selon le standard git flow
191
+ - 🎯 Configuration automatique de thèmes conformes aux normes CommitLint
192
+ - 🔄 Fournit la configuration et le point d'entrée pour les commandes git personnalisées
193
+ - 📦 Génération automatisée avec configuration zéro
1376
194
 
1377
- 2. **Full Configuration**
1378
- - Select all options
1379
- - Complete the framework and preprocessor selection prompts
1380
- - Your project will have a complete code standards system configured
195
+ ---
1381
196
 
1382
- # `anl git` Command
197
+ # 機能概要
1383
198
 
1384
- ### Feature Overview
199
+ > an-cli はフロントエンド開発用コマンドラインツールで、以下のコマンドを含みます:
200
+ >
201
+ > - `anl type` コマンド:Swagger JSON に基づいて TypeScript 型定義と API リクエスト関数を自動生成するコマンドラインツール。
202
+ > - `anl lint` コマンド:React または Vue プロジェクト用の eslint、stylelint、prettier、commitLint、VSCode 関連設定を生成
203
+ > - `anl git` コマンド:Git ローカル設定を生成し、オプション機能として gitflow 標準ブランチ作成、git commit メッセージテーマ、git カスタムコマンド設定を提供
1385
204
 
1386
- - Through interactive multi-selection, applies the following Git capabilities to the current repository:
1387
- - gitflow standard branch creation
1388
- - Copies `.gitscripts/`, `.gitconfig`, `.commit-type.cjs` to the project (only when missing)
1389
- - Adds executable permissions to `.gitscripts/random-branch.sh`
1390
- - Executes `git config --local include.path ../.gitconfig`
1391
- - Automatic commit subject setting
1392
- - Copies `.githooks/commit-msg` and sets it as executable
1393
- - Executes `git config core.hooksPath .githooks`
1394
- - Custom git commands
1395
- - Adds `.gitattributes` to the project (only when missing)
205
+ ## 機能特徴
1396
206
 
1397
- ### Usage Method
207
+ - `anl type`
208
+ - 🚀 Swagger JSON ドキュメントの自動解析
209
+ - 📦 TypeScript 型定義ファイルの生成
210
+ - 🔄 型安全な API リクエスト関数の生成
211
+ - 🎯 パスパラメータ、クエリパラメータ、リクエストボディのサポート
212
+ - 📝 列挙型定義の自動生成
213
+ - 🎨 コードフォーマットのサポート
214
+ - ⚡️ ファイルアップロードのサポート
215
+ - 🛠 カスタマイズ可能なコード生成オプション
216
+ - 🌐 複数の Swagger サーバー設定のサポート
217
+ - 🔧 OPTIONS、HEAD、SEARCH などの HTTP メソッドのサポート
1398
218
 
1399
- ```bash
1400
- $ anl git
1401
- ```
219
+ - `anl lint`
220
+ - 🔍 各種 lint ツールのワンクリック設定
221
+ - 🎨 ESLint 設定の自動化
222
+ - 🎯 Prettier フォーマット設定
223
+ - 🔄 CommitLint コミット規約
224
+ - 📦 VSCode エディタ設定
1402
225
 
1403
- Select one or more features in the prompts. Files are only created when they don't exist; existing files are preserved.
226
+ - `anl git`
227
+ - 🔍 複数の機能を選択してインストール
228
+ - 🎨 標準的な git flow ブランチ作成
229
+ - 🎯 CommitLint 規約に準拠したテーマの自動設定
230
+ - 🔄 git カスタムコマンド設定とエントリーポイントの提供
231
+ - 📦 ゼロ設定の自動生成
1404
232
 
1405
- ### Notes
233
+ ---
1406
234
 
1407
- - Please run within a Git repository.
1408
- - If automatically executed git config fails, please execute manually:
235
+ # Обзор функций
1409
236
 
1410
- ```bash
1411
- git config --local include.path ../.gitconfig
1412
- git config core.hooksPath .githooks
1413
- ```
237
+ > an-cli — это CLI-инструмент для фронтенда, включающий следующие команды:
238
+ >
239
+ > - Команда `anl type`: CLI-инструмент для автоматической генерации определений типов TypeScript и функций API-запросов на основе Swagger JSON.
240
+ > - Команда `anl lint`: Генерирует конфигурации eslint, stylelint, prettier, commitLint, VSCode для проектов react или vue
241
+ > - Команда `anl git`: Генерирует локальную конфигурацию git с опциональными функциями: создание стандартных веток gitflow, темы сообщений git commit, конфигурация пользовательских команд git
1414
242
 
1415
- # License
243
+ ## Особенности функций
1416
244
 
1417
- ISC License
245
+ - `anl type`
246
+ - 🚀 Автоматически парсит Swagger JSON документы
247
+ - 📦 Генерирует файлы определений типов TypeScript
248
+ - 🔄 Генерирует типобезопасные функции API-запросов
249
+ - 🎯 Поддерживает параметры пути, запроса и тела запроса
250
+ - 📝 Автоматически генерирует определения типов enum
251
+ - 🎨 Поддерживает форматирование кода
252
+ - ⚡️ Поддерживает загрузку файлов
253
+ - 🛠 Настраиваемые опции генерации кода
254
+ - 🌐 Поддерживает конфигурации нескольких Swagger серверов
255
+ - 🔧 Поддерживает HTTP методы OPTIONS, HEAD, SEARCH и другие
1418
256
 
1419
- # Contributing
257
+ - `anl lint`
258
+ - 🔍 Настройка различных инструментов линтинга в один клик
259
+ - 🎨 Автоматизация конфигурации ESLint
260
+ - 🎯 Конфигурация форматирования Prettier
261
+ - 🔄 Стандарты коммитов CommitLint
262
+ - 📦 Конфигурация редактора VSCode
1420
263
 
1421
- Welcome to submit [Issues](https://github.com/bianliuzhu/an-cli/issues) and [Pull Requests](https://github.com/bianliuzhu/an-cli/pulls)!
264
+ - `anl git`
265
+ - 🔍 Множественные опциональные функции для установки
266
+ - 🎨 Создание стандартных веток git flow
267
+ - 🎯 Автоматическая настройка тем, соответствующих стандартам CommitLint
268
+ - 🔄 Предоставляет конфигурацию пользовательских команд git и точки входа
269
+ - 📦 Автоматическая генерация с нулевой конфигурацией