There's actually a library called ast-grep which does something very similar to what you're describing. They have an example in their introduction which performs a find and replace operation on a JS AST using a pattern:
ast-grep --pattern 'var code = $PAT' --rewrite 'let code = $PAT' --lang js
https://ast-grep.github.io/guide/introduction.html