-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
index.ts
67 lines (58 loc) 路 2.16 KB
/
index.ts
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
import type { types as t } from "@babel/core";
import type { NodePath } from "@babel/traverse";
import { declare } from "@babel/helper-plugin-utils";
import convertFunctionParams from "./params";
import convertFunctionRest from "./rest";
export { convertFunctionParams };
export interface Options {
loose?: boolean;
}
export default declare((api, options: Options) => {
api.assertVersion(7);
const ignoreFunctionLength =
api.assumption("ignoreFunctionLength") ?? options.loose;
// Todo(BABEL 8): Consider default it to false
const noNewArrows = (api.assumption("noNewArrows") ?? true) as boolean;
function transformParameters(path: NodePath<t.Function>) {
if (
path.isArrowFunctionExpression() &&
path
.get("params")
.some(param => param.isRestElement() || param.isAssignmentPattern())
) {
// default/rest visitors require access to `arguments`, so it cannot be an arrow
path.arrowFunctionToExpression({ noNewArrows });
// In some cases arrowFunctionToExpression replaces the function with a wrapper.
// Return early; the wrapped function will be visited later in the AST traversal.
if (!path.isFunctionExpression()) return false;
}
const convertedRest = convertFunctionRest(path);
const convertedParams = convertFunctionParams(path, ignoreFunctionLength);
if (convertedRest || convertedParams) {
// Manually reprocess this scope to ensure that the moved params are updated.
path.scope.crawl();
return true;
}
return false;
}
return {
name: "transform-parameters",
visitor: {
Function: {
enter(path) {
if (!path.node.generator) transformParameters(path);
},
// We need to transform generator functions in `exit`,
// to avoid transforming parameters before that regenerator
// runs: https://github.com/babel/babel/issues/15012
// However, we still transform classic functions in `enter`,
// to avoid unnecessarily requeueing them.
exit(path) {
if (path.node.generator) {
if (transformParameters(path)) path.requeue();
}
},
},
},
};
});