forked from babel/babel
/
index.js
54 lines (47 loc) 路 1.46 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
import regexpTree from "regexp-tree";
export default function({ types: t }, options) {
const { runtime = true } = options;
if (typeof runtime !== "boolean") {
throw new Error("The 'runtime' option must be boolean");
}
return {
name: "transform-named-capturing-groups-regex",
visitor: {
RegExpLiteral(path) {
const node = path.node;
if (!/\(\?<(?![=!])/.test(node.pattern)) {
// Return early if there are no named groups.
// The .indexOf check may have false positives (e.g. /\(?</); in
// this case we parse the regex and regexp-tree won't transform it.
return;
}
const result = regexpTree.compatTranspile(node.extra.raw, [
"namedCapturingGroups",
]);
const { namedCapturingGroups } = result.getExtra();
if (
namedCapturingGroups &&
Object.keys(namedCapturingGroups).length > 0
) {
node.pattern = result.getSource();
if (runtime && !isRegExpTest(path)) {
path.replaceWith(
t.callExpression(this.addHelper("wrapRegExp"), [
node,
t.valueToNode(namedCapturingGroups),
]),
);
}
}
},
},
};
}
function isRegExpTest(path) {
return (
path.parentPath.isMemberExpression({
object: path.node,
computed: false,
}) && path.parentPath.get("property").isIdentifier({ name: "test" })
);
}