-
Notifications
You must be signed in to change notification settings - Fork 0
/
ts_parser.js
138 lines (122 loc) · 4.67 KB
/
ts_parser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
const fs = require('fs');
const path = require('path');
const babelParser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const generator = require('@babel/generator').default;
/**
* Парсер TypeScript и TSX файлов.
*/
class TsParser {
constructor() {
this.result = {
namespace: null,
imports: [],
exports: [],
types: [],
functions: [],
classes: [],
react_components: [],
};
}
preprocessCode(code) {
// Удаляем const без значения
code = code.replace(/const\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*;/g, 'let $1;');
// Удаляем любые декларации `export const` без инициализаторов
code = code.replace(/export\s+const\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*;/g, 'export let $1;');
return code;
}
parse(filePath) {
let code = fs.readFileSync(filePath, 'utf-8');
code = this.preprocessCode(code); // Применяем предобработку кода
const isTSX = path.extname(filePath).toLowerCase() === '.tsx';
let ast;
try {
ast = babelParser.parse(code, {
sourceType: 'module',
plugins: isTSX ? ['typescript', 'jsx'] : ['typescript'],
});
} catch (parseError) {
throw new Error(`Parsing failed for ${filePath}: ${parseError.message}`);
}
const self = this; // Сохраняем контекст this для traverse
traverse(ast, {
ImportDeclaration(path) {
self.result.imports.push(path.node.source?.value || null);
},
ExportNamedDeclaration(path) {
const declaration = path.node.declaration;
if (declaration) {
const exportCode = generator(declaration).code;
self.result.exports.push({
name: declaration.id?.name || null,
type: declaration.type || null,
code: exportCode,
});
} else {
path.node.specifiers.forEach((specifier) => {
self.result.exports.push({
name: specifier.exported?.name || null,
code: null,
});
});
}
},
ExportDefaultDeclaration(path) {
const declaration = path.node.declaration;
const exportCode = declaration ? generator(declaration).code : null;
self.result.exports.push({
name: 'default',
type: declaration?.type || null,
code: exportCode,
});
},
TSInterfaceDeclaration(path) {
if (path.node.id?.name) {
const typeCode = generator(path.node).code;
self.result.types.push({
name: path.node.id.name,
kind: 'interface',
code: typeCode,
});
}
},
TSTypeAliasDeclaration(path) {
if (path.node.id?.name) {
const typeCode = generator(path.node).code;
self.result.types.push({
name: path.node.id.name,
kind: 'type',
code: typeCode,
});
}
},
FunctionDeclaration(path) {
const functionNode = path.node;
if (functionNode.id) {
self.result.functions.push({
name: functionNode.id.name,
code: generator(functionNode).code,
start_line: functionNode.loc?.start?.line || null,
end_line: functionNode.loc?.end?.line || null,
});
}
},
});
return this.result;
}
}
// Получаем путь к анализируемому файлу
const filePath = process.argv[2];
if (!filePath || !fs.existsSync(filePath)) {
console.error('Error: File path is invalid or does not exist.');
process.exit(1);
}
try {
const parser = new TsParser();
const result = parser.parse(filePath);
// Выводим только результат парсинга
console.log(JSON.stringify(result, null, 4));
} catch (error) {
console.error(JSON.stringify({ error: error.message }));
process.exit(1);
}