| 1 | import type { NodePath, Visitor } from "@babel/traverse"; |
| 2 | import type * as t from "@babel/types"; |
| 3 | |
| 4 | // TODO (Babel 8): Don't export this function. |
| 5 | export function skipAllButComputedKey( |
| 6 | path: NodePath<t.Method | t.ClassProperty>, |
| 7 | ) { |
| 8 | path.skip(); |
| 9 | if (path.node.computed) { |
| 10 | // requeue the computed key |
| 11 | path.context.maybeQueue(path.get("key")); |
| 12 | } |
| 13 | } |
| 14 | |
| 15 | export function requeueComputedKeyAndDecorators( |
| 16 | path: NodePath<t.Method | t.Property>, |
| 17 | ) { |
| 18 | const { context, node } = path; |
| 19 | // @ts-expect-error ClassPrivateProperty does not have computed |
| 20 | if (node.computed) { |
| 21 | // requeue the computed key |
| 22 | context.maybeQueue(path.get("key")); |
| 23 | } |
| 24 | if (node.decorators) { |
| 25 | for (const decorator of path.get("decorators")) { |
| 26 | // requeue the decorators |
| 27 | context.maybeQueue(decorator); |
| 28 | } |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | // environmentVisitor should be used when traversing the whole class and not for specific class elements/methods. |
| 33 | // For perf reasons, the environmentVisitor might be traversed with `{ noScope: true }`, which means `path.scope` is undefined. |
| 34 | // Avoid using `path.scope` here |
| 35 | const visitor: Visitor = { |
| 36 | FunctionParent(path) { |
| 37 | if (path.isArrowFunctionExpression()) { |
| 38 | // arrows are not skipped because they inherit the context. |
| 39 | return; |
| 40 | } else { |
| 41 | path.skip(); |
| 42 | if (path.isMethod()) { |
| 43 | requeueComputedKeyAndDecorators(path); |
| 44 | } |
| 45 | } |
| 46 | }, |
| 47 | Property(path) { |
| 48 | if (path.isObjectProperty()) { |
| 49 | return; |
| 50 | } |
| 51 | path.skip(); |
| 52 | requeueComputedKeyAndDecorators(path); |
| 53 | }, |
| 54 | }; |
| 55 | |
| 56 | export default visitor; |