Skip to content

Query TypeScript AST with astq Query engine + TypeScript adapter

License

Notifications You must be signed in to change notification settings

adammedford/astq-ts

Repository files navigation

astq-ts

ASTQ TypeScript adapter that enables querying TypeScript generated abstract syntax trees

Project scaffolded using typescript-library-starter

styled with prettier

About

Enables usage of ASTQ's XPath-like syntax for querying abstract syntax trees generated by TypeScript's createSourceFile.

Usage

import * as astq from 'astq';
import { ASTQAdapterTypeScript } from 'astq-ts';
import * as typescript from 'typescript';

export class QueryEngineWrapper {
  queryEngine;

  constructor() {
   this.queryEngine = new astq();
   // The adapter takes a reference to your typescript install in its constructor to make sure the node types match your version
   this.queryEngine.adapter(new ASTQAdapterTypeScript(typescript));
  }

  public querySource(tsAST: any, query: string, queryOptions?: any): any[] {
   return astq.query(tsAST, query, queryOptions);
  }

}

const myTree = createASTFromSource(sampleSource);
const wrapper = new QueryEngineWrapper();

wrapper.querySource(myTree, sampleQuery).forEach((node) => {
 console.log(`${node.name.escapedText}: ${node.initializer.text}`);
})

/**
 * Prints
 * bar: quux
 * baz: 42
 */

function createASTFromSource(source: string, fileName?: string = 'test.js') {
    return typescript.createSourceFromFile(fileName, source, typescript.ScriptTarget.Latest, true);
}

const sampleSource = `
    class Foo {
        foo () {
            const bar = "quux"
            let baz = 42
        }
    }
`

const sampleQuery = `
// VariableDeclaration [
  /:name   Identifier [ @escapedText ]
  &&
  (/:initializer StringLiteral [ @text ] || /:initializer * [ @text ])
]

`

NPM scripts

  • npm t: Run test suite
  • npm start: Run npm run build in watch mode
  • npm run test:watch: Run test suite in interactive watch mode
  • npm run test:prod: Run linting and generate coverage
  • npm run build: Generate bundles and typings, create docs
  • npm run lint: Lints code

About

Query TypeScript AST with astq Query engine + TypeScript adapter

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published