gen-api-types 1.0.17 โ†’ 1.0.18

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.en.md CHANGED
@@ -11,7 +11,7 @@ With this tool, we can mark request interface classes and methods through TypeSc
11
11
  > Note:
12
12
  >
13
13
  > 1. Because this tool uses TypeScript method decorators, APIs must be written as **API classes + API methods**.
14
- > 2. The CLI dynamically imports and executes marked API modules through the project's bundled `tsx` runtime. No global `tsx` installation is required.
14
+ > 2. The CLI dynamically imports modules containing marked methods. Module-level code runs during import; decorators only register tasks, and the CLI calls the registered API methods afterward.
15
15
  > 3. API methods are executed for real in the CLI process. Make sure required environment variables, network access, and authentication are available.
16
16
 
17
17
  #### Installation
@@ -51,10 +51,10 @@ export class TestApi {
51
51
  As shown in the code above:
52
52
 
53
53
  - `@gen_type_c()` marks an API class.
54
- - `@gen_type_m()` marks a method to execute and convert.
54
+ - `@gen_type_m()` marks a method to execute and convert. The decorator registers the task; the Runner invokes the API method after the CLI has loaded the modules.
55
55
  - `args: any[]` contains the arguments passed to the method. Both static and non-static methods are supported.
56
56
  - `typeName: string` is the generated type name. If omitted, it defaults to `Response_${ClassName}_${MethodName}`.
57
- - Prefer the exported `gen_type_c` and `gen_type_m` aliases. `GatDecorator` is the internal container used for constant-based decorator names and is not required in business code.
57
+ - The marked class is only a decorator carrier; the Runner does not instantiate it. Non-static methods must not depend on `this` or instance fields.
58
58
 
59
59
  Decorator options may span multiple lines:
60
60
 
@@ -101,21 +101,13 @@ You can also use it by configuring scripts in package.json:
101
101
  }
102
102
  ```
103
103
 
104
- The CLI scans `.ts` files in the input directories, finds marked classes and methods, and dynamically imports the modules containing them. The decorators execute the API methods during module import; the declaration file is generated after all marked methods finish.
104
+ The CLI scans `.ts` files in the input directories to find marked classes, methods, and their modules. It then imports those modules so decorators can register tasks. After all modules have loaded, the Runner invokes the registered API methods and converts successful results into a declaration file. Each API method has a default execution timeout of 5 seconds; registered methods run concurrently.
105
105
 
106
106
  Command output:
107
107
 
108
108
  ```shell
109
- ๐Ÿš€ Start generating API types...
110
109
  sourceFilesGlob [ 'src\\**\\*.ts' ]
111
- Request results:
112
- โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
113
- โ”‚ (index) โ”‚ Values โ”‚
114
- โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
115
- โ”‚ โœ”๏ธ successList โ”‚ 'TestApi.getList TestApi.getWeather' โ”‚
116
- โ”‚ โŒ errorList โ”‚ '' โ”‚
117
- โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
118
- โœ… API type generation completed
110
+ โœ… API type generation completed: /path/to/api-types.d.ts
119
111
  ```
120
112
 
121
113
  ##### 3. Using the types
@@ -178,7 +170,7 @@ export default defineConfig({
178
170
  })
179
171
  ```
180
172
 
181
- The plugin processes `.ts` and `.tsx` files and supports single-line and multi-line decorator options. Use the `gen_type_c` and `gen_type_m` aliases in business code; direct `GatDecorator.gen_type_m()` calls do not match the plugin's current decorator names.
173
+ The plugin processes `.ts` and `.tsx` files and supports single-line and multi-line decorator options. It removes decorators by the names `gen_type_c` and `gen_type_m`.
182
174
 
183
175
  The Vite plugin only affects Vite's transform pipeline. It is not involved when the CLI imports and executes API modules.
184
176
 
package/README.md CHANGED
@@ -11,7 +11,7 @@
11
11
  > ๆณจๆ„๏ผš
12
12
  >
13
13
  > 1. ็”ฑไบŽ้œ€่ฆไฝฟ็”จ TypeScript ๆ–นๆณ•่ฃ…้ฅฐๅ™จ๏ผŒๆŽฅๅฃ้œ€่ฆไปฅ **API ็ฑป + API ๆ–นๆณ•** ็š„ๅฝขๅผไนฆๅ†™ใ€‚
14
- > 2. CLI ไผšๅŠจๆ€ๅฏผๅ…ฅๅนถๆ‰ง่กŒๆ ‡่ฎฐ็š„ API ๆจกๅ—๏ผŒๅ› ๆญค้€š่ฟ‡้กน็›ฎๅ†…็ฝฎ็š„ `tsx` ่ฟ่กŒ๏ผŒไธ้œ€่ฆๅ…จๅฑ€ๅฎ‰่ฃ… `tsx`ใ€‚
14
+ > 2. CLI ไผšๅŠจๆ€ๅฏผๅ…ฅๅŒ…ๅซๆ ‡่ฎฐๆ–นๆณ•็š„ๆจกๅ—ใ€‚ๆจกๅ—้กถๅฑ‚ไปฃ็ ไผšๅœจๅฏผๅ…ฅๆ—ถๆ‰ง่กŒ๏ผ›่ฃ…้ฅฐๅ™จๅช็™ป่ฎฐไปปๅŠก๏ผŒCLI ้šๅŽๆ‰่ฐƒ็”จๅทฒ็™ป่ฎฐ็š„ API ๆ–นๆณ•ใ€‚
15
15
  > 3. API ๆ–นๆณ•ไผšๅœจ CLI ่ฟ›็จ‹ไธญ็œŸๅฎžๆ‰ง่กŒ๏ผŒ่ฏท็กฎไฟ่ฟ่กŒๆ‰€้œ€็š„็Žฏๅขƒๅ˜้‡ใ€็ฝ‘็ปœๆƒ้™ๅ’Œ้‰ดๆƒ้…็ฝฎๅทฒ็ปๅ‡†ๅค‡ๅฅฝใ€‚
16
16
 
17
17
  #### ๅฎ‰่ฃ…ๆ•™็จ‹
@@ -51,10 +51,10 @@ export class TestApi {
51
51
  ๅฆ‚ไธŠ้ขไปฃ็ ๆ‰€็คบ:
52
52
 
53
53
  - `@gen_type_c()` ๆ ‡่ฎฐ API ็ฑปใ€‚
54
- - `@gen_type_m()` ๆ ‡่ฎฐ้œ€่ฆๆ‰ง่กŒๅนถ็”Ÿๆˆ็ฑปๅž‹็š„ๆ–นๆณ•ใ€‚
54
+ - `@gen_type_m()` ๆ ‡่ฎฐ้œ€่ฆๆ‰ง่กŒๅนถ็”Ÿๆˆ็ฑปๅž‹็š„ๆ–นๆณ•๏ผ›่ฃ…้ฅฐๅ™จ่ดŸ่ดฃ็™ป่ฎฐไปปๅŠก๏ผŒAPI ๆ–นๆณ•ไผšๅœจ CLI ๅŠ ่ฝฝๅฎŒๆจกๅ—ๅŽ็”ฑ Runner ่ฐƒ็”จใ€‚
55
55
  - `args: any[]` ๆ˜ฏ่ฐƒ็”จๆ–นๆณ•ๆ—ถไผ ๅ…ฅ็š„ๅ‚ๆ•ฐ๏ผŒๆ”ฏๆŒ้™ๆ€ๆ–นๆณ•ๅ’Œ้ž้™ๆ€ๆ–นๆณ•ใ€‚
56
56
  - `typeName: string` ๆ˜ฏ็”Ÿๆˆ็š„็ฑปๅž‹ๅ็งฐ๏ผ›ไธๆŒ‡ๅฎšๆ—ถ้ป˜่ฎคไธบ `Response_${็ฑปๅ}_${ๆ–นๆณ•ๅ}`ใ€‚
57
- - ๆŽจ่ไฝฟ็”จๅฏผๅ‡บ็š„ `gen_type_c`ใ€`gen_type_m` ๅˆซๅใ€‚`GatDecorator` ๆ˜ฏๅ†…้ƒจ็”จไบŽๆŒ‰ๅธธ้‡ๅ็งฐๆณจๅ†Œ่ฃ…้ฅฐๅ™จ็š„ๅฎนๅ™จ๏ผŒไธๆ˜ฏไธšๅŠกไปฃ็ ๅฟ…้กปไฝฟ็”จ็š„ๅ…ฅๅฃใ€‚
57
+ - ๆ ‡่ฎฐ็ฑปไป…็”จไบŽๆ‰ฟ่ฝฝ่ฃ…้ฅฐๅ™จ๏ผ›Runner ไธไผšๅˆ›ๅปบ็ฑปๅฎžไพ‹ใ€‚ๆ™ฎ้€šๆ–นๆณ•ไธ่ฆไพ่ต– `this` ๆˆ–ๅฎžไพ‹ๅญ—ๆฎตใ€‚
58
58
 
59
59
  ่ฃ…้ฅฐๅ™จๅ‚ๆ•ฐๅฏไปฅ่ทจๅคš่กŒไนฆๅ†™๏ผš
60
60
 
@@ -101,21 +101,13 @@ Options:
101
101
  }
102
102
  ```
103
103
 
104
- CLI ไผšๆ‰ซๆ่พ“ๅ…ฅ็›ฎๅฝ•ไธญ็š„ `.ts` ๆ–‡ไปถ๏ผŒๆ‰พๅˆฐๆ ‡่ฎฐ็š„็ฑปๅ’Œๆ–นๆณ•ๅŽ๏ผŒๅŠจๆ€ๅฏผๅ…ฅๅŒ…ๅซ่ฟ™ไบ›ๆ–นๆณ•็š„ๆจกๅ—ใ€‚ๆจกๅ—ๅฏผๅ…ฅๆ—ถ่ฃ…้ฅฐๅ™จไผšๆ‰ง่กŒ API ๆ–นๆณ•๏ผŒๆ‰€ๆœ‰ๆ–นๆณ•ๅฎŒๆˆๅŽๅ†็”Ÿๆˆๅฃฐๆ˜Žๆ–‡ไปถใ€‚
104
+ CLI ไผšๆ‰ซๆ่พ“ๅ…ฅ็›ฎๅฝ•ไธญ็š„ `.ts` ๆ–‡ไปถ๏ผŒๆ‰พๅˆฐๆ ‡่ฎฐ็š„็ฑปๅ’Œๆ–นๆณ•ๅŠๅ…ถๆ‰€ๅฑžๆจกๅ—ใ€‚้šๅŽๅŠจๆ€ๅฏผๅ…ฅ่ฟ™ไบ›ๆจกๅ—๏ผŒไฝฟ่ฃ…้ฅฐๅ™จ็™ป่ฎฐไปปๅŠก๏ผ›ๅ…จ้ƒจๆจกๅ—ๅŠ ่ฝฝๅฎŒๆˆๅŽ๏ผŒRunner ๆ‰่ฐƒ็”จ็™ป่ฎฐ็š„ API ๆ–นๆณ•๏ผŒๅนถๅฐ†ๆˆๅŠŸ็ป“ๆžœ่ฝฌๆขไธบๅฃฐๆ˜Žๆ–‡ไปถใ€‚ๆฏไธช API ๆ–นๆณ•็š„้ป˜่ฎคๆ‰ง่กŒ่ถ…ๆ—ถไธบ 5 ็ง’๏ผ›ๅคšไธชๅทฒ็™ป่ฎฐๆ–นๆณ•ไผšๅนถๅ‘ๆ‰ง่กŒใ€‚
105
105
 
106
106
  ๅ‘ฝไปค่พ“ๅ‡บ๏ผš
107
107
 
108
108
  ```shell
109
- ๐Ÿš€ ๅผ€ๅง‹็”ŸๆˆAPI็ฑปๅž‹...
110
109
  sourceFilesGlob [ 'src\\**\\*.ts' ]
111
- ่ฏทๆฑ‚็ป“ๆžœ๏ผš
112
- โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
113
- โ”‚ (index) โ”‚ Values โ”‚
114
- โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
115
- โ”‚ โœ”๏ธ successList โ”‚ 'TestApi.getList TestApi.getWeather' โ”‚
116
- โ”‚ โŒ errorList โ”‚ '' โ”‚
117
- โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
118
- โœ… API ็ฑปๅž‹็”ŸๆˆๅฎŒๆˆ
110
+ โœ… API ็ฑปๅž‹็”ŸๆˆๅฎŒๆˆ๏ผš /path/to/api-types.d.ts
119
111
  ```
120
112
 
121
113
  ##### 3. ไฝฟ็”จ็ฑปๅž‹
@@ -178,7 +170,7 @@ export default defineConfig({
178
170
  })
179
171
  ```
180
172
 
181
- ๆ’ไปถๅชๅค„็† `.ts` ๅ’Œ `.tsx` ๆ–‡ไปถ๏ผŒๅนถๆ”ฏๆŒๅ•่กŒๆˆ–ๅคš่กŒ่ฃ…้ฅฐๅ™จๅ‚ๆ•ฐใ€‚ๆŽจ่ๅœจไธšๅŠกไปฃ็ ไธญไฝฟ็”จ `gen_type_c`ใ€`gen_type_m` ๅˆซๅ๏ผ›ๅฆ‚ๆžœ็›ดๆŽฅไฝฟ็”จ `GatDecorator.gen_type_m()`๏ผŒไธไผšๅŒน้…ๆ’ไปถๅฝ“ๅ‰็š„่ฃ…้ฅฐๅ™จๅ็งฐใ€‚
173
+ ๆ’ไปถๅชๅค„็† `.ts` ๆ–‡ไปถ๏ผŒๅนถๆ”ฏๆŒๅ•่กŒๆˆ–ๅคš่กŒ่ฃ…้ฅฐๅ™จๅ‚ๆ•ฐใ€‚ๆ’ไปถๆŒ‰ `gen_type_c`ใ€`gen_type_m` ่ฟ™ไธคไธช่ฃ…้ฅฐๅ™จๅ็งฐ็งป้™ค่ฃ…้ฅฐๅ™จใ€‚
182
174
 
183
175
  Vite ๆ’ไปถๅชๅฝฑๅ“ Vite ็š„่ฝฌๆขๆต็จ‹๏ผŒไธๅ‚ไธŽ CLI ็š„ API ๆ‰ง่กŒๆต็จ‹ใ€‚
184
176
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gen-api-types",
3
- "version": "1.0.17",
3
+ "version": "1.0.18",
4
4
  "description": "ไธ€ไธช่‡ชๅŠจ็”Ÿๆˆ่ฏทๆฑ‚ๆŽฅๅฃ่ฟ”ๅ›ž็ฑปๅž‹็š„ cli ๅฐๅทฅๅ…ท",
5
5
  "main": "./src/index.ts",
6
6
  "exports": {
@@ -26,7 +26,8 @@
26
26
  "generate types",
27
27
  "TypeScript",
28
28
  "Cli",
29
- "API"
29
+ "API",
30
+ "gat"
30
31
  ],
31
32
  "files": [
32
33
  "bin",
package/src/cli/index.ts CHANGED
@@ -2,137 +2,47 @@
2
2
 
3
3
 
4
4
  import * as path from 'path';
5
- import { Project } from 'ts-morph';
6
- import { pathToFileURL } from 'url';
7
- import { isExported, output_dir, output_file, positionals, ts_config_path } from '../argv';
8
- import { DECO_NAME_C, DECO_NAME_M } from '../constant';
9
- import { ExecuteApiMethodResult, executeState } from '../state';
10
- import { TypeTransformer } from '../transformer';
11
- import { formatResultList } from '../utils';
12
-
13
- // console.log('positionals', positionals)
14
-
15
- const sourceFilesGlob = positionals.map(dir => path.normalize(`${dir}/**/*.ts`))
16
- const out_put_target = path.resolve(output_dir, output_file)
17
-
18
- // console.log('arg', _arg)
19
- // console.log('sourceFilesGlob', sourceFilesGlob)
20
- // debugger
21
-
22
-
23
- function getModulePathSet() {
24
- console.log('sourceFilesGlob', sourceFilesGlob)
25
- const modulePathSet: Set<string> = new Set()
26
- // 2. ไฝฟ็”จts-morphๅˆ›ๅปบ้กน็›ฎ๏ผŒไพฟไบŽ่งฃๆžๆบ็ 
27
- // const project = new Project({ tsConfigFilePath: ts_config_path });
28
- const project = new Project({
29
- tsConfigFilePath: ts_config_path
30
- });
31
- project.addSourceFilesAtPaths(sourceFilesGlob);
32
- // console.log('project.getSourceFiles().length', project.getSourceFiles().length)
33
- // debugger
34
- // 3. ้ๅކๆ‰€ๆœ‰ๆบๆ–‡ไปถ
35
- for (const sourceFile of project.getSourceFiles()) {
36
-
37
- const classes = sourceFile.getClasses();
38
- for (const classDeclaration of classes) {
39
- const c_deco = classDeclaration.getDecorator(DECO_NAME_C)
40
- if (!c_deco) continue
41
- const methods = classDeclaration.getMethods();
42
- for (const method of methods) {
43
- const className = classDeclaration.getName()!;
44
- const methodName = method.getName();
45
- const fullMethodName = `${className}.${methodName}`;
46
-
47
- // 4. ๆฃ€ๆŸฅๆ–นๆณ•ๆ˜ฏๅฆ่ขซๆˆ‘ไปฌ็š„่ฃ…้ฅฐๅ™จๆ ‡่ฎฐ
48
- const m_deco = method.getDecorator(DECO_NAME_M)
49
- if (!m_deco) continue
50
- executeState.emit(executeState.ADD_TASK, fullMethodName)
51
- const modulePath = sourceFile.getFilePath()
52
- if (!modulePathSet.has(modulePath)) modulePathSet.add(modulePath)
53
-
54
-
55
- }
56
- }
57
- }
58
- return modulePathSet
59
- }
5
+ import { isExported, output_dir, output_file, positionals } from '../argv';
6
+ import { runner, scanner } from '../generation';
7
+ import { importApiModule } from '../generation/moduleLoader';
8
+ import { createDeclarationFile } from '../transformer';
9
+ import { formatResultList, getSourceFilesGlobFromEntrances, logResultList } from '../utils';
60
10
 
61
11
 
62
- /**
63
- * ๅผ•ๅ…ฅๅŒ…ๅซๆ ‡่ฎฐ็š„ๆ–นๆณ•็š„ๆจกๅ—๏ผŒ่งฆๅ‘่ฃ…้ฅฐๅ™จๆ‰ง่กŒ๏ผŒ่ฎฐๅฝ•ๆ‰ง่กŒ็ป“ๆžœ
64
- * @param modulePathSet
65
- * @returns
66
- */
67
- async function importApiModule<T extends string>(modulePathSet: Set<T>) {
68
- return Promise.all(
69
- Array.from(modulePathSet).map(modulePath => import(pathToFileURL(modulePath).href))
70
- )
71
12
 
72
- }
13
+ async function main() {
73
14
 
74
15
 
75
- function createDeclarationFile(successList: ExecuteApiMethodResult[]) {
76
- const ttf = new TypeTransformer({ filePath: out_put_target, isExported })
77
- const tasks = successList.map(async ({ data, typeName, fullMethodName }) => {
78
- try {
79
- await ttf.transform(data, typeName)
80
- return { fullMethodName }
81
- } catch (error) {
82
- console.error('transform error', error)
83
- return { fullMethodName, error }
84
- }
85
- })
86
- return Promise.all(tasks)
87
- }
16
+ try {
88
17
 
18
+ const sourceFilesGlob = getSourceFilesGlobFromEntrances(positionals)
19
+ console.log('sourceFilesGlob', sourceFilesGlob,)
89
20
 
21
+ const modules = scanner.scan(sourceFilesGlob)
22
+ if (modules.size === 0) {
23
+ console.warn('โš ๏ธ ๆœชๆ‰พๅˆฐ้œ€่ฆ่ฝฌๆข็š„API,่ฏทๆฃ€ๆŸฅapi_dir ๅ’Œ gen_type่ฃ…้ฅฐๅ™จๆ ‡ๆณจๆ˜ฏๅฆๆญฃ็กฎ!')
24
+ process.exit(0)
25
+ }
90
26
 
27
+ await importApiModule(Array.from(modules.keys()))
91
28
 
92
- async function main() {
93
- console.log('๐Ÿš€ ๅผ€ๅง‹็”ŸๆˆAPI็ฑปๅž‹...');
94
- const modulePathSet = getModulePathSet();
95
- if (modulePathSet.size == 0) {
29
+ const executeResultList = await runner.run()
96
30
 
97
- console.error('โš ๏ธ ๆœชๆ‰พๅˆฐ้œ€่ฆ่ฝฌๆข็š„API,่ฏทๆฃ€ๆŸฅapi_dir ๅ’Œ gen_type่ฃ…้ฅฐๅ™จๆ ‡ๆณจๆ˜ฏๅฆๆญฃ็กฎ!')
98
- process.exit(1)
99
- }
100
- try {
101
- await importApiModule(modulePathSet);
102
- // executeState.addListener(executeState.TASKLIST_CLEAR, executeResultList=>{
103
- // })
104
-
105
- const executeResultList = await executeState.promise
106
31
  const { successList: executeSuccessList, errorList: executeErrorList } = formatResultList(executeResultList)
107
- if (executeErrorList.length) {
108
- console.group('่ฏทๆฑ‚็ป“ๆžœ๏ผš')
109
- console.table({
110
- "โœ”๏ธ executeSuccessList": executeSuccessList.map(item => item.fullMethodName).join(' '),
111
- "โŒ executeErrorList": executeErrorList.map(item => item.fullMethodName).join(' ')
112
- })
113
- console.groupEnd()
114
- }
115
- const transformList = await createDeclarationFile(executeSuccessList)
32
+ if (executeErrorList.length) logResultList('่ฏทๆฑ‚็ป“ๆžœ๏ผš', executeSuccessList, executeErrorList)
33
+
34
+ const out_put_target = path.resolve(output_dir, output_file)
35
+ const transformList = await createDeclarationFile(executeSuccessList, out_put_target, isExported)
116
36
  const { successList: transformSuccessList, errorList: transformErrorList } = formatResultList(transformList)
117
37
 
118
- if (transformErrorList.length) {
119
- console.group('่ฝฌๆข็ป“ๆžœ๏ผš')
120
- console.table({
121
- "โœ”๏ธ transformSuccessList": transformSuccessList.map(item => item.fullMethodName).join(' '),
122
- "โŒ transformErrorList": transformErrorList.map(item => item.fullMethodName).join(' ')
123
- })
124
- console.groupEnd()
38
+ if (transformErrorList.length) logResultList('่ฝฌๆข็ป“ๆžœ๏ผš', transformSuccessList, transformErrorList)
125
39
 
126
- }
127
40
  if (transformSuccessList.length) console.log('โœ… API ็ฑปๅž‹็”ŸๆˆๅฎŒๆˆ๏ผš', out_put_target);
128
41
  } catch (error) {
129
42
  console.error('โŒ ๅ‡บ้”™ไบ†', error)
130
43
  process.exitCode = 1
131
44
  }
132
45
 
133
-
134
-
135
-
136
46
  }
137
47
 
138
48
  main()
@@ -3,3 +3,6 @@ export const GEN_TYPE_METADATA_KEY = Symbol('gen:type:metadata');
3
3
  export const DECO_NAME_M = 'gen_type_m';
4
4
  /** ๆ ‡่ฎฐ็ฑป็š„่ฃ…้ฅฐๅ™จๅ็งฐ */
5
5
  export const DECO_NAME_C = 'gen_type_c';
6
+
7
+
8
+ export const EXEC_TIMEOUT = 5_000
@@ -1,10 +1,8 @@
1
1
  // import 'reflect-metadata';
2
2
 
3
- import { DECO_NAME_C, DECO_NAME_M } from "../constant/index.ts";
4
- import { executeState } from "../state/index.ts";
5
- import { executeApiMethod } from "../utils/index.ts";
3
+ import { registry } from "../generation/index.ts";
4
+ import { createClassDecorator, createMethodDecorator } from "../utils/decoratorHelper.ts";
6
5
 
7
- // ๅฎšไน‰ไธ€ไธชๅ”ฏไธ€็š„metadata key
8
6
 
9
7
 
10
8
  export interface GenTypeOptions {
@@ -13,43 +11,24 @@ export interface GenTypeOptions {
13
11
  }
14
12
 
15
13
 
16
- const EXEC_TIMEOUT = 5_000
17
- export class GatDecorator {
18
- static [DECO_NAME_C]() {
19
- return function <T>(target: T) {
20
- };
21
- }
22
- static [DECO_NAME_M]({ args = [], typeName }: GenTypeOptions = {}) {
23
- return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
24
-
25
-
26
- (async () => {
27
- const className = typeof target == 'function' ? target.name : target.constructor.name
28
- const fullMethodName = `${className}.${propertyKey}`
29
- console.log('fullMethodName', fullMethodName)
30
- typeName ??= `Response_${className}_${propertyKey}`
31
- let resultInfo = null
32
- try {
33
- const apiMethod = descriptor.value as Function
34
- // console.log(`๐Ÿ” Calling ${fullMethodName} with args:`, args);
35
-
36
- const data = await executeApiMethod({
37
- timeout: EXEC_TIMEOUT,
38
- method: () => apiMethod.apply(target, args)
39
- })
40
-
41
- resultInfo = { data, typeName, fullMethodName }
42
- } catch (error) {
43
- console.error(`โŒ ${fullMethodName} execute error:`, error)
44
- resultInfo = { error, fullMethodName, typeName }
45
- } finally {
46
- executeState.emit(executeState.EXECUTE_END, resultInfo)
47
- }
48
- })();
49
-
50
- };
51
- }
52
- }
53
14
 
54
- export const gen_type_c = GatDecorator[DECO_NAME_C]
55
- export const gen_type_m = GatDecorator[DECO_NAME_M]
15
+
16
+
17
+
18
+ export const gen_type_c = createClassDecorator((ctx, options) => {
19
+
20
+ })
21
+ export const gen_type_m = createMethodDecorator(async (
22
+ { target, propertyKey, descriptor },
23
+ { typeName, args }: GenTypeOptions = { args: [] }
24
+ ) => {
25
+ const className = typeof target == 'function' ? target.name : target.constructor.name
26
+ const fullMethodName = `${className}.${propertyKey}`
27
+ typeName ??= `Response_${className}_${propertyKey}`
28
+ const handler = () => (descriptor.value).apply(target, args)
29
+ registry.register({
30
+ key: descriptor.value,
31
+ meta: { typeName, name: fullMethodName, handler }
32
+ })
33
+ })
34
+
@@ -0,0 +1,11 @@
1
+ import { Registry } from "./registry";
2
+ import { Runner } from "./runner";
3
+ import { Scanner } from "./scanner";
4
+
5
+
6
+ export const scanner = new Scanner()
7
+ export const registry = new Registry()
8
+ export const runner = new Runner(registry)
9
+
10
+
11
+
@@ -0,0 +1,13 @@
1
+ import { pathToFileURL } from "node:url";
2
+
3
+ /**
4
+ * ๅผ•ๅ…ฅๅŒ…ๅซๆ ‡่ฎฐ็š„ๆ–นๆณ•็š„ๆจกๅ—๏ผŒ่งฆๅ‘่ฃ…้ฅฐๅ™จๆ‰ง่กŒ
5
+ * @param modulePathSet
6
+ * @returns
7
+ */
8
+ export function importApiModule(modulePathSet: string[]) {
9
+ return Promise.all(
10
+ Array.from(modulePathSet).map(modulePath => import(pathToFileURL(modulePath).href))
11
+ )
12
+
13
+ }
@@ -0,0 +1,25 @@
1
+ import { ApiMethod } from "./types"
2
+
3
+ type Task = {
4
+ key: string | symbol | object
5
+ meta: {
6
+ name: string
7
+ handler: ApiMethod
8
+ typeName: string
9
+ }
10
+ }
11
+
12
+ export class Registry {
13
+ private _taskMap: Map<Task['key'], Task['meta']> = new Map()
14
+ get taskMetas() {
15
+ return Array.from(this._taskMap.values())
16
+ }
17
+ get taskeys() {
18
+ return Array.from(this._taskMap.keys())
19
+ }
20
+
21
+ register(task: Task) {
22
+ this._taskMap.set(task.key, task.meta)
23
+ }
24
+
25
+ }
@@ -0,0 +1,25 @@
1
+ import { EXEC_TIMEOUT } from "../constant"
2
+ import { executeApiMethod } from "../utils"
3
+ import { Registry } from "./registry"
4
+
5
+
6
+ export class Runner {
7
+ constructor(private registry: Registry) {
8
+ }
9
+
10
+ run() {
11
+ return Promise.all(
12
+ this.registry.taskMetas.map(async ({ name: fullMethodName, handler, typeName }) => {
13
+ try {
14
+ const data = await executeApiMethod({ timeout: EXEC_TIMEOUT, method: handler })
15
+ return { data, typeName, fullMethodName }
16
+ } catch (error) {
17
+ console.error(`โŒ ${fullMethodName} execute error:`, error)
18
+ return { error, fullMethodName, typeName }
19
+ } finally {
20
+ }
21
+ })
22
+
23
+ )
24
+ }
25
+ }
@@ -0,0 +1,52 @@
1
+ import { Project } from "ts-morph";
2
+ import { DECO_NAME_C, DECO_NAME_M } from "../constant";
3
+
4
+
5
+ type ScanResult = Map<string, Set<string>>
6
+
7
+ export class Scanner {
8
+ constructor(public ts_config_path?: string) { }
9
+ public cacheResult: ScanResult | null = null
10
+ /**
11
+ * ๆ‰ซๆๆŒ‡ๅฎš็š„ๆบๆ–‡ไปถ่ทฏๅพ„๏ผŒๆŸฅๆ‰พ่ขซ่ฃ…้ฅฐๅ™จๆ ‡่ฎฐ็š„็ฑปๅ’Œๆ–นๆณ•๏ผŒๅนถ่ฟ”ๅ›žไธ€ไธชๆ˜ ๅฐ„๏ผŒ้”ฎไธบๆจกๅ—่ทฏๅพ„๏ผŒๅ€ผไธบ่ฏฅๆจกๅ—ไธญ่ขซๆ ‡่ฎฐ็š„ๆ–นๆณ•้›†ๅˆใ€‚
12
+ * @param sourceFilesGlob
13
+ * @returns modulepath -> methods
14
+ */
15
+ scan(sourceFilesGlob: string[]) {
16
+ const moduleMap: ScanResult = new Map()
17
+ const project = new Project({ tsConfigFilePath: this.ts_config_path, });
18
+ project.addSourceFilesAtPaths(sourceFilesGlob);
19
+ for (const sourceFile of project.getSourceFiles()) {
20
+
21
+ const classes = sourceFile.getClasses();
22
+ for (const classDeclaration of classes) {
23
+ const c_deco = classDeclaration.getDecorator(DECO_NAME_C)
24
+ if (!c_deco) continue
25
+ const methods = classDeclaration.getMethods();
26
+ for (const method of methods) {
27
+ const className = classDeclaration.getName()!;
28
+ const methodName = method.getName();
29
+ const fullMethodName = `${className}.${methodName}`;
30
+
31
+ const m_deco = method.getDecorator(DECO_NAME_M)
32
+ if (!m_deco) continue
33
+ const modulePath = sourceFile.getFilePath()
34
+
35
+ const methods = moduleMap.get(modulePath) ?? new Set()
36
+ methods.add(fullMethodName)
37
+ moduleMap.set(modulePath, methods)
38
+ }
39
+ }
40
+ }
41
+ this.cacheResult = moduleMap
42
+ return moduleMap
43
+ }
44
+
45
+ get methods() {
46
+ return Array.from(this.cacheResult?.values()!).flatMap(item => [...item])
47
+ }
48
+
49
+
50
+
51
+
52
+ }
@@ -0,0 +1,11 @@
1
+
2
+
3
+
4
+ export type Task = CallableFunction
5
+
6
+ export type ApiMethod<T = any> = () => (T | PromiseLike<T>)
7
+
8
+
9
+ export type ExecuteApiMethodResult = {
10
+ data?: any, typeName: string, fullMethodName: string, error?: any
11
+ }
@@ -1,62 +1,17 @@
1
- import { Project, SourceFile } from "ts-morph";
1
+ import { ExecuteApiMethodResult } from "../generation/types"
2
+ import { TypeTransformer } from "./typeTransformer"
2
3
 
3
- function inferType(value: any): string {
4
- if (Array.isArray(value)) {
5
- if (value.length === 0) return "any[]";
6
- // ๅ–็ฌฌไธ€ไธชๅ…ƒ็ด ็ฑปๅž‹๏ผŒๅ‡่ฎพๆ•ฐ็ป„ๅ…ƒ็ด ็ฑปๅž‹ไธ€่‡ด
7
- return `${inferType(value[0])}[]`;
8
- } else if (typeof value === "object" && value !== null) {
9
- const props = Object.entries(value).map(([k, v]) => `${k}: ${inferType(v)}`).join(";\n");
10
- return `{${props}}`;
11
- } else if (typeof value === "string") {
12
- return "string";
13
- } else if (typeof value === "number") {
14
- return "number";
15
- } else if (typeof value === "boolean") {
16
- return "boolean";
17
- } else if (value === null) {
18
- return "null";
19
- } else if (!value) {
20
- return "undefined";
21
- } else {
22
- return "any";
23
- }
4
+ export function createDeclarationFile(executeList: ExecuteApiMethodResult[], out_put_target: string, isExported: boolean) {
5
+ const ttf = new TypeTransformer({ filePath: out_put_target, isExported })
6
+ const tasks = executeList.map(async ({ data, typeName, fullMethodName }) => {
7
+ try {
8
+ await ttf.transform(data, typeName)
9
+ return { fullMethodName }
10
+ } catch (error) {
11
+ console.error('transform error', error)
12
+ return { fullMethodName, error }
13
+ }
14
+ })
15
+ return Promise.all(tasks)
24
16
  }
25
17
 
26
-
27
- export class TypeTransformer {
28
- project: Project;
29
- sourceFile: SourceFile;
30
- isExported: boolean
31
- constructor({ projectOptions = {}, filePath = "types.d.ts", isExported = false } = {}) {
32
- this.project = new Project(projectOptions);
33
- this.sourceFile = this.createSourceFile(filePath);
34
- this.isExported = isExported
35
- }
36
-
37
- createSourceFile(filePath: string) {
38
- // try {
39
- // return project.addSourceFileAtPath(filePath);
40
- // } catch (error) {
41
- // return project.createSourceFile(filePath);
42
- // }
43
- return this.project.createSourceFile(filePath, '', { overwrite: true });
44
- }
45
-
46
- // ๆ นๆฎ่ฟ่กŒๆ—ถๅฏน่ฑก็”Ÿๆˆ็ฑปๅž‹ๅฎšไน‰
47
-
48
- generateTypeFromObject(val: any, typeName: string) {
49
- // 4. ๆทปๅŠ ็ฑปๅž‹ๅˆซๅ
50
- this.sourceFile.addTypeAlias({
51
- name: typeName,
52
- isExported: this.isExported,
53
- type: inferType(val)
54
- });
55
- // if (typeName == 'Res_Weather') throw Error('res_weather test error')
56
- }
57
- async transform(res: any, typeName: string, isAsync = true) {
58
- this.generateTypeFromObject(res, typeName)
59
- await this.sourceFile.save();
60
- }
61
-
62
- }
@@ -0,0 +1,62 @@
1
+ import { Project, SourceFile } from "ts-morph";
2
+
3
+ function inferType(value: any): string {
4
+ if (Array.isArray(value)) {
5
+ if (value.length === 0) return "any[]";
6
+ // ๅ–็ฌฌไธ€ไธชๅ…ƒ็ด ็ฑปๅž‹๏ผŒๅ‡่ฎพๆ•ฐ็ป„ๅ…ƒ็ด ็ฑปๅž‹ไธ€่‡ด
7
+ return `${inferType(value[0])}[]`;
8
+ } else if (typeof value === "object" && value !== null) {
9
+ const props = Object.entries(value).map(([k, v]) => `${k}: ${inferType(v)}`).join(";\n");
10
+ return `{${props}}`;
11
+ } else if (typeof value === "string") {
12
+ return "string";
13
+ } else if (typeof value === "number") {
14
+ return "number";
15
+ } else if (typeof value === "boolean") {
16
+ return "boolean";
17
+ } else if (value === null) {
18
+ return "null";
19
+ } else if (!value) {
20
+ return "undefined";
21
+ } else {
22
+ return "any";
23
+ }
24
+ }
25
+
26
+
27
+ export class TypeTransformer {
28
+ project: Project;
29
+ sourceFile: SourceFile;
30
+ isExported: boolean
31
+ constructor({ projectOptions = {}, filePath = "types.d.ts", isExported = false } = {}) {
32
+ this.project = new Project(projectOptions);
33
+ this.sourceFile = this.createSourceFile(filePath);
34
+ this.isExported = isExported
35
+ }
36
+
37
+ createSourceFile(filePath: string) {
38
+ // try {
39
+ // return project.addSourceFileAtPath(filePath);
40
+ // } catch (error) {
41
+ // return project.createSourceFile(filePath);
42
+ // }
43
+ return this.project.createSourceFile(filePath, '', { overwrite: true });
44
+ }
45
+
46
+ // ๆ นๆฎ่ฟ่กŒๆ—ถๅฏน่ฑก็”Ÿๆˆ็ฑปๅž‹ๅฎšไน‰
47
+
48
+ generateTypeFromObject(val: any, typeName: string) {
49
+ // 4. ๆทปๅŠ ็ฑปๅž‹ๅˆซๅ
50
+ this.sourceFile.addTypeAlias({
51
+ name: typeName,
52
+ isExported: this.isExported,
53
+ type: inferType(val)
54
+ });
55
+ // if (typeName == 'Res_Weather') throw Error('res_weather test error')
56
+ }
57
+ async transform(res: any, typeName: string, isAsync = true) {
58
+ this.generateTypeFromObject(res, typeName)
59
+ await this.sourceFile.save();
60
+ }
61
+
62
+ }
@@ -0,0 +1,38 @@
1
+
2
+
3
+
4
+
5
+ interface MethodContext {
6
+ target: any,
7
+ propertyKey: string,
8
+ descriptor: PropertyDescriptor
9
+ }
10
+
11
+
12
+ export function createMethodDecorator<Options>(
13
+ handler: (ctx: MethodContext, options?: Options) => any,
14
+ defaultOptions?: Options
15
+ ) {
16
+
17
+ return (options?: Options) =>
18
+ (target: any, propertyKey: string, descriptor: PropertyDescriptor) =>
19
+ handler({ target, propertyKey, descriptor }, options ?? defaultOptions)
20
+ }
21
+
22
+
23
+ interface ClassContext {
24
+ target: any
25
+ }
26
+
27
+
28
+ export function createClassDecorator<Options>(
29
+ handler: (ctx: ClassContext, options?: Options,) => any,
30
+ defaultOptions?: Options
31
+ ) {
32
+
33
+ return (options?: Options) => (target: any) => handler({ target }, options ?? defaultOptions)
34
+
35
+ }
36
+
37
+
38
+
@@ -1,3 +1,6 @@
1
+ import path from "path"
2
+ import { ApiMethod } from "../generation/types"
3
+
1
4
  type ResultInfoBase = { error?: any }
2
5
  export function formatResultList<T extends ResultInfoBase>(list: T[]) {
3
6
  return list.reduce((acc, item) => {
@@ -20,11 +23,15 @@ export function promiseWithResolvers<T>() {
20
23
  }
21
24
  }
22
25
 
26
+
27
+
28
+
29
+
23
30
  export async function executeApiMethod<T>({
24
31
  method,
25
32
  timeout = 10 * 1000
26
33
  }: {
27
- method: () => T | PromiseLike<T>
34
+ method: ApiMethod<T>
28
35
  timeout?: number
29
36
  }): Promise<T> {
30
37
  let timer: ReturnType<typeof setTimeout> | undefined
@@ -45,3 +52,21 @@ export async function executeApiMethod<T>({
45
52
  }
46
53
  }
47
54
 
55
+
56
+
57
+
58
+
59
+
60
+ export function getSourceFilesGlobFromEntrances(entrances: string[]): string[] {
61
+ return entrances.map(dir => path.normalize(`${dir}/**/*.ts`))
62
+ }
63
+
64
+
65
+ export function logResultList(title: string, successLis: any[], errorList: any[]) {
66
+ console.group(`\r\n${title}`)
67
+ console.table({
68
+ "โœ”๏ธ Success": successLis.map(item => item.fullMethodName).join(' '),
69
+ "โŒ Error": errorList.map(item => item.fullMethodName).join(' ')
70
+ })
71
+ console.groupEnd()
72
+ }
@@ -1,45 +0,0 @@
1
- import EventEmitter from "events"
2
- import { promiseWithResolvers } from "../utils/index.ts"
3
-
4
- export type ExecuteApiMethodResult = {
5
- data?: any, typeName: string, fullMethodName: string, error?: any
6
- }
7
-
8
-
9
-
10
-
11
-
12
-
13
- export class ExecuteState extends EventEmitter {
14
-
15
- EXECUTE_END = 'executeEnd'
16
- TASKLIST_CLEAR = 'taskClear'
17
- ADD_TASK = 'addTask'
18
- private resultList: ExecuteApiMethodResult[] = []
19
- private taskList: string[] = []
20
- promiseWithResolvers = promiseWithResolvers<ExecuteApiMethodResult[]>()
21
- constructor() {
22
- super()
23
- this.init()
24
- }
25
- init() {
26
- this.addListener(this.EXECUTE_END, (result: ExecuteApiMethodResult) => {
27
- this.resultList.push(result)
28
- if (this.resultList.length === this.taskList.length) {
29
- this.emit(this.TASKLIST_CLEAR, this.resultList)
30
- this.promiseWithResolvers?.resolve(this.resultList)
31
- }
32
- })
33
-
34
- this.addListener(this.ADD_TASK, (taskName) => {
35
- this.taskList.push(taskName)
36
- })
37
- }
38
-
39
- get promise() {
40
- return this.promiseWithResolvers?.promise
41
- }
42
-
43
- }
44
-
45
- export const executeState = new ExecuteState()