| 1 | import TraversalContext from "./context"; |
| 2 | import type { TraverseOptions } from "./index"; |
| 3 | import type NodePath from "./path"; |
| 4 | import type Scope from "./scope"; |
| 5 | import type * as t from "@babel/types"; |
| 6 | import { VISITOR_KEYS } from "@babel/types"; |
| 7 | |
| 8 | /** |
| 9 | * Traverse the children of given node |
| 10 | * @param {Node} node |
| 11 | * @param {TraverseOptions} opts The traverse options used to create a new traversal context |
| 12 | * @param {scope} scope A traversal scope used to create a new traversal context. When opts.noScope is true, scope should not be provided |
| 13 | * @param {any} state A user data storage provided as the second callback argument for traversal visitors |
| 14 | * @param {NodePath} path A NodePath of given node |
| 15 | * @param {Record<string, boolean>} skipKeys A map from key names to whether that should be skipped during traversal. The skipKeys are applied to every descendants |
| 16 | * @returns {boolean} Whether the traversal stops early |
| 17 | |
| 18 | * @note This function does not visit the given `node`. |
| 19 | */ |
| 20 | export function traverseNode( |
| 21 | node: t.Node, |
| 22 | opts: TraverseOptions, |
| 23 | scope?: Scope, |
| 24 | state?: any, |
| 25 | path?: NodePath, |
| 26 | skipKeys?: Record<string, boolean>, |
| 27 | ): boolean { |
| 28 | const keys = VISITOR_KEYS[node.type]; |
| 29 | if (!keys) return false; |
| 30 | |
| 31 | const context = new TraversalContext(scope, opts, state, path); |
| 32 | for (const key of keys) { |
| 33 | if (skipKeys && skipKeys[key]) continue; |
| 34 | if (context.visit(node, key)) { |
| 35 | return true; |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | return false; |
| 40 | } |