-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparseReact.js
156 lines (137 loc) · 4.71 KB
/
parseReact.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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
const fs = require('fs');
const parser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const t = require('@babel/types');
function parseReact(filePaths) {
const result = { components: {}, variables: {} };
filePaths.forEach(filePath => {
try {
const code = fs.readFileSync(filePath, 'utf-8');
const ast = parser.parse(code, {
sourceType: 'module',
plugins: ['jsx', 'typescript', 'classProperties']
});
// Основной обход AST
traverse(ast, {
// Обработка переменных (только НЕ компоненты)
VariableDeclarator(path) {
if (!isArrowFunctionComponent(path)) {
const varName = path.node.id.name;
result.variables[varName] = {
types: [getType(path.node.init)],
value: path.node.init?.loc ? code.slice(
path.node.init.start,
path.node.end
) : undefined
};
}
},
// Обработка классовых компонентов
ClassDeclaration(path) {
if (isReactClassComponent(path)) {
processClassComponent(path, code, result);
}
}
});
// Отдельный обход для стрелочных компонентов
traverse(ast, {
VariableDeclarator(path) {
if (isArrowFunctionComponent(path)) {
processArrowComponent(path, code, result);
}
}
});
} catch (error) {
console.error(`Error parsing ${filePath}:`, error.message);
}
});
return result;
}
// Проверка на React-компонент (стрелочная функция)
function isArrowFunctionComponent(path) {
return (
t.isVariableDeclarator(path.node) &&
t.isArrowFunctionExpression(path.node.init) &&
containsJSX(path.get('init'))
);
}
// Проверка на JSX в теле функции
function containsJSX(path) {
const returnStatement = getReturnStatement(path);
return t.isJSXElement(returnStatement) || t.isJSXFragment(returnStatement);
}
// Проверка на классовый компонент
function isReactClassComponent(path) {
const superClass = path.node.superClass;
return (
(t.isIdentifier(superClass) && superClass.name === 'Component') ||
(t.isMemberExpression(superClass) &&
t.isIdentifier(superClass.object, { name: 'React' }) &&
t.isIdentifier(superClass.property, { name: 'Component' }))
);
}
// Обработка стрелочных компонентов
function processArrowComponent(path, code, result) {
const componentName = path.node.id.name;
const parentNode = path.parentPath.node; // Получаем VariableDeclaration
const componentCode = code.slice(parentNode.start, parentNode.end);
const arrowFunction = path.node.init;
const returns = getReturnJSXCode(arrowFunction.body, code);
result.components[componentName] = {
code: componentCode,
returns: returns
};
}
// Извлечение JSX кода возврата
function getReturnJSXCode(node, code) {
let currentNode = node;
while (t.isParenthesizedExpression(currentNode)) {
currentNode = currentNode.expression;
}
return code.slice(currentNode.start, currentNode.end);
}
// Обработка классовых компонентов
function processClassComponent(path, code, result) {
const componentName = path.node.id.name;
const componentCode = code.slice(path.node.start, path.node.end);
const renderMethod = path.node.body.body.find(m =>
t.isClassMethod(m) && m.key.name === 'render'
);
let returns = '';
if (renderMethod) {
const renderBody = renderMethod.body;
returns = code.slice(renderBody.start, renderBody.end)
.replace(/^{|}$/g, '')
.trim();
}
if (returns) {
result.components[componentName] = {
code: componentCode,
returns: returns
};
}
}
// Вспомогательные функции
function getReturnStatement(path) {
let body = path.get('body');
if (body.isBlockStatement()) {
const returnStmt = body.get('body').find(p => p.isReturnStatement());
return returnStmt ? returnStmt.get('argument').node : null;
} else {
let node = body.node;
while (t.isParenthesizedExpression(node)) {
node = node.expression;
}
return node;
}
}
function getType(node) {
if (!node) return 'any';
if (t.isNumericLiteral(node)) return 'number';
if (t.isStringLiteral(node)) return 'string';
if (t.isBooleanLiteral(node)) return 'boolean';
if (t.isArrowFunctionExpression(node)) return 'function';
if (t.isObjectExpression(node)) return 'object';
return 'any';
}
module.exports = { parseReact };