ast-utils.js
2.55 KB
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
const parser = require("@babel/parser");
function parseJavaScript(source, filePath) {
return parser.parse(source, {
sourceType: "unambiguous",
sourceFilename: filePath,
plugins: [
"dynamicImport",
"jsx",
"objectRestSpread",
"optionalCatchBinding",
"optionalChaining",
"nullishCoalescingOperator",
"classProperties",
],
});
}
function propertyName(property) {
if (!property || !property.key) {
return null;
}
if (property.computed) {
return null;
}
return property.key.name || property.key.value || null;
}
function findProperty(objectNode, name) {
if (!objectNode || objectNode.type !== "ObjectExpression") {
return null;
}
return objectNode.properties.find(property => String(propertyName(property)) === String(name)) || null;
}
function staticPrimitive(node, constants = new Map()) {
if (!node) {
return null;
}
if (["StringLiteral", "NumericLiteral", "BooleanLiteral"].includes(node.type)) {
return node.value;
}
if (node.type === "Identifier" && constants.has(node.name)) {
return constants.get(node.name);
}
if (node.type === "TemplateLiteral") {
let value = "";
for (let index = 0; index < node.quasis.length; index += 1) {
value += node.quasis[index].value.cooked || "";
if (index < node.expressions.length) {
const expressionValue = staticPrimitive(node.expressions[index], constants);
if (expressionValue === null) {
return null;
}
value += String(expressionValue);
}
}
return value;
}
if (node.type === "BinaryExpression" && node.operator === "+") {
const left = staticPrimitive(node.left, constants);
const right = staticPrimitive(node.right, constants);
return left === null || right === null ? null : `${left}${right}`;
}
return null;
}
function locationOf(node, filePath) {
return {
path: filePath,
line: node && node.loc ? node.loc.start.line : 1,
column: node && node.loc ? node.loc.start.column : 0,
};
}
function objectEntries(objectNode) {
if (!objectNode || objectNode.type !== "ObjectExpression") {
return [];
}
return objectNode.properties
.map(property => ({
name: propertyName(property),
node: property,
value: property.value || property,
}))
.filter(entry => entry.name !== null);
}
function arrayValues(node, constants = new Map()) {
if (!node || node.type !== "ArrayExpression") {
return [];
}
return node.elements.map(element => staticPrimitive(element, constants)).filter(value => value !== null);
}
module.exports = {
arrayValues,
findProperty,
locationOf,
objectEntries,
parseJavaScript,
propertyName,
staticPrimitive,
};