Skip to content

API Reference

ast-grep currently has an experimental API for Node.js.

You can see API usage guide for more details.


Please see the link for up-to-date type declaration.

Supported Languages

@ast-grep/napi supports html, js, jsx, ts and tsx.


A language object has following methods.

export namespace js {
  /** Parse a string to an ast-grep instance */
  export function parse(src: string): SgRoot
  /** Get the `kind` number from its string name. */
  export function kind(kindName: string): number
  /** Compile a string to ast-grep Pattern. */
  export function pattern(pattern: string): NapiConfig
   * Discover and parse multiple files in Rust.
   * `config` specifies the file path and matcher.
   * `callback` will receive matching nodes found in a file.
   * returns the number of matched files.
  export function findInFiles(
    config: FindConfig,
    callback: (err: null | Error, result: SgNode[]) => void
  ): Promise<number>


import { js } from '@ast-grep/napi'

const source = `console.log("hello world")`
const ast = js.parse(source)


You will get an SgRoot instance when you lang.parse(string).

SgRoot can also be accessed in lang.findInFiles's callback by calling node.getRoot().

In the latter case, sgRoot.filename() will return the path of the matched file.


/** Represents the parsed tree of code. */
class SgRoot {
  /** Returns the root SgNode of the ast-grep instance. */
  root(): SgNode
   * Returns the path of the file if it is discovered by ast-grep's `findInFiles`.
   * Returns `"anonymous"` if the instance is created by `lang.parse(source)`.
  filename(): string


const ast = js.parse(source)
const root = ast.root()


The main interface to traverse the AST.


Most methods are self-explanatory. Please submit a new issue if you find something confusing.

class SgNode {
  // Read node's information
  range(): Range
  isLeaf(): boolean
  isNamed(): boolean
  isNamedLeaf(): boolean
  kind(): string
  text(): string
  // Check if node meets certain patterns
  matches(m: string): boolean
  inside(m: string): boolean
  has(m: string): boolean
  precedes(m: string): boolean
  follows(m: string): boolean
  // Get nodes' matched meta variables
  getMatch(m: string): SgNode | null
  getMultipleMatches(m: string): Array<SgNode>
  // Get node's SgRoot
  getRoot(): SgRoot
  // Traverse node tree
  children(): Array<SgNode>
  find(matcher: string | number | NapiConfig): SgNode | null
  findAll(matcher: string | number | NapiConfig): Array<SgNode>
  field(name: string): SgNode | null
  parent(): SgNode | null
  child(nth: number): SgNode | null
  ancestors(): Array<SgNode>
  next(): SgNode | null
  nextAll(): Array<SgNode>
  prev(): SgNode | null
  prevAll(): Array<SgNode>


NapiConfig is used in find or findAll.


NapiConfig has similar fields as the rule config.

interface NapiConfig {
  rule: object
  constraints?: object
  language?: FrontEndLanguage
  // @experimental
  transform?: object
  utils?: object


FindConfig is used in findInFiles.


interface FindConfig {
  // You can search multiple paths
  // ast-grep will recursively find all files under the paths.
  paths: Array<string>
  // Specify what nodes will be matched
  matcher: NapiConfig

Useful Examples

Python API


The Rule object is a Python representation of the YAML rule object in the CLI. See the reference.

class Pattern(TypedDict):
    selector: str
    context: str

class Rule(TypedDict, total=False):
    # atomic rule
    pattern: str | Pattern
    kind: str
    regex: str

    # relational rule
    inside: Relation
    has: Relation
    precedes: Relation
    follows: Relation

    # composite rule
    all: List[Rule]
    any: List[Rule]
    # pseudo code below for demo.
    "not": Rule # Python does not allow "not" keyword as attribute
    matches: str

# Relational Rule Related
StopBy = Union[Literal["neighbor"], Literal["end"], Rule]
class Relation(Rule, total=False):
    stopBy: StopBy
    field: str


The Config object is similar to the YAML rule config in the CLI. See the reference.

class Config(TypedDict, total=False):
    rule: Rule
    constraints: Dict[str, Mapping]
    utils: Dict[str, Rule]
    transform: Dict[str, Mapping]

Rust API

Rust API is not stable yet. The following link is only for those who are interested in modifying ast-grep's source.

Made with ❤️ with Rust