Abstract Syntax Trees (AST)
An Abstract Syntax Tree is a structured representation of your code that the computer can understand and manipulate. When you run a codemod:1
Parse
Your source code is parsed into an AST representation
2
Analyze
The codemod searches for specific patterns in the AST
3
Transform
Matching nodes are replaced with updated code
4
Generate
The modified AST is converted back to source code
Example: From Code to AST
Consider this simple code:variable_declarator, object_pattern, call_expression, etc. The codemod can identify these patterns and transform them.
ast-grep: The Pattern Matching Engine
ast-grep is a powerful tool for searching and manipulating ASTs using pattern matching. It provides:- Pattern-based search: Find code using intuitive patterns like
util.isArray($ARG) - Structural matching: Match based on code structure, not just text
- Language awareness: Understands JavaScript and TypeScript syntax
ast-grep is the core engine powering Node.js Userland codemods. It handles the heavy lifting of AST parsing and traversal.
The jssg API
Thejssg (JavaScript ast-grep) API is the interface codemods use to interact with ASTs. It’s provided by the Codemod.com platform.
Core Concepts
Every codemod exports a transform function:SgRoot<JS>: The root object containing the parsed ASTSgNode<JS>: Individual AST nodes you can query and manipulateEdit: Represents a single code modificationRange: Represents a location in the source code
Finding Nodes
Use pattern matching to locate code:Creating Edits
Build transformation edits:Committing Changes
Apply all edits and return the transformed code:Real-World Example
Here’s a simplified version of theutil.types.isNativeError to Error.isError migration:
- Import detection: Finding where
utilis imported or required - Binding resolution: Determining how
types.isNativeErroris accessed (could beutil.types.isNativeError,types.isNativeError, orisNativeErrordepending on the import style) - Pattern matching: Locating all usages of the resolved binding
- Replacement: Transforming to the new API
Codemod Utilities
The@nodejs/codemod-utils package provides battle-tested helpers for common operations:
Import/Require Detection
Binding Resolution
Cleanup Operations
Workflow Structure
Each codemod follows a standard workflow:Performance Considerations
- Early exit: Return
nullimmediately if the file doesn’t contain relevant code - Batch edits: Collect all edits before calling
commitEdits()once - Efficient patterns: Use specific patterns to avoid searching the entire AST
Next Steps
When to Use Codemods
Learn when codemods are the right choice for your migration
Safety Best Practices
Ensure safe, reliable code transformations