-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
81 lines (69 loc) · 1.97 KB
/
index.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
const { parseExpression } = require("@babel/parser");
module.exports = function ({ types: t }, options = {}) {
const replace = options.replace || {};
const allowConflictingReplacements = !!options.allowConflictingReplacements;
function asArray(obj) {
if (Array.isArray(obj)) {
return obj;
}
return Object.keys(obj).map((key) => [key, obj[key]]);
}
const types = new Map();
asArray(replace).forEach(([key, value]) => {
const kNode = parseExpression(key);
const vNode = parseExpression(value);
const candidates = types.get(kNode.type) || [];
candidates.push({ key: kNode, value: vNode, originalKey: key });
types.set(kNode.type, candidates);
for (let i = 0; i < candidates.length - 1; i++) {
if (!t.isNodesEquivalent(candidates[i].key, kNode)) {
continue;
}
if (allowConflictingReplacements) {
candidates[i] = candidates.pop();
break;
}
throw new Error(
`Expressions ${JSON.stringify(
candidates[i].originalKey
)} and ${JSON.stringify(key)} conflict`
);
}
});
const values = new Set();
types.forEach((candidates) => {
candidates.forEach((candidate) => {
values.add(candidate.value);
});
});
return {
name: "transform-replace-expressions",
visitor: {
Expression(path) {
if (values.has(path.node)) {
path.skip();
return;
}
const candidates = types.get(path.node.type);
if (!candidates) {
return;
}
for (const { key, value } of candidates) {
if (t.isNodesEquivalent(key, path.node)) {
try {
t.validate(path.parent, path.key, value);
} catch (err) {
if (!(err instanceof TypeError)) {
throw err;
}
path.skip();
return;
}
path.replaceWith(value);
return;
}
}
},
},
};
};