( ast: T, callbackMap: Visitors<T, Meta> | Visitor<T, Meta>, )
| 36 | |
| 37 | // https://lihautan.com/manipulating-ast-with-javascript/ |
| 38 | export function visit<T extends {}, Meta extends Record<string, unknown>>( |
| 39 | ast: T, |
| 40 | callbackMap: Visitors<T, Meta> | Visitor<T, Meta>, |
| 41 | ) { |
| 42 | function _visit(node: any, path: Path<T, Meta>, meta: Meta) { |
| 43 | if (typeof callbackMap === 'function') { |
| 44 | if (callbackMap(node, path, meta) === false) { |
| 45 | return |
| 46 | } |
| 47 | } else if (node.type in callbackMap) { |
| 48 | if (callbackMap[node.type](node, path, meta) === false) { |
| 49 | return |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | const keys = Object.keys(node) |
| 54 | for (let i = 0; i < keys.length; i++) { |
| 55 | const child = node[keys[i]] |
| 56 | if (Array.isArray(child)) { |
| 57 | for (let j = 0; j < child.length; j++) { |
| 58 | if (isNodeLike(child[j])) { |
| 59 | let newMeta = { ...meta } |
| 60 | let newPath = [ |
| 61 | { |
| 62 | node: child[j], |
| 63 | parent: node, |
| 64 | key: keys[i], |
| 65 | index: j, |
| 66 | meta: newMeta, |
| 67 | }, |
| 68 | ...path, |
| 69 | ] |
| 70 | |
| 71 | _visit(child[j], newPath, newMeta) |
| 72 | } |
| 73 | } |
| 74 | } else if (isNodeLike(child)) { |
| 75 | let newMeta = { ...meta } |
| 76 | let newPath = [ |
| 77 | { |
| 78 | node: child, |
| 79 | parent: node, |
| 80 | key: keys[i], |
| 81 | index: i, |
| 82 | meta: newMeta, |
| 83 | }, |
| 84 | ...path, |
| 85 | ] |
| 86 | |
| 87 | _visit(child, newPath, newMeta) |
| 88 | } |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | let newMeta: Meta = {} as any |
| 93 | let newPath: Path<T, Meta> = [ |
| 94 | { |
| 95 | node: ast, |
no test coverage detected
searching dependent graphs…