Query TypeScript ASTs with the esquery API!
npm install @phenomnomnominal/tsquery
TSQuery is a port of the ESQuery API for TypeScript! TSQuery allows you to query a TypeScript AST for patterns of syntax using a CSS style selector system.
ESQuery demo - note that the demo requires JavaScript code, not TypeScript
TSQuery demo by Uri Shaked
``sh`
npm install @phenomnomnominal/tsquery --save-dev
Say we want to select all instances of an identifier with name "Animal", e.g. the identifier in the class declaration, and the identifier in the extends declaration.
We would do something like the following:
`ts
import { ast, query } from '@phenomnomnominal/tsquery';
const typescript =
class Animal {
constructor(public name: string) { }
move(distanceInMeters: number = 0) {
console.log(\\${this.name} moved \${distanceInMeters}m.\);
}
}
class Snake extends Animal {
constructor(name: string) { super(name); }
move(distanceInMeters = 5) {
console.log("Slithering...");
super.move(distanceInMeters);
}
}
;
const tree = ast(typescript);
const nodes = query(tree, 'Identifier[name="Animal"]');
console.log(nodes.length); // 2
`
The following selectors are supported:
* AST node type: ForStatement (see common node types)
wildcard: [attr]
* attribute existence: [attr="foo"]
* attribute value: or [attr=123][attr=/foo./]
attribute regex: [attr!="foo"]
* attribute conditions: , [attr>2], [attr<3], [attr>=2], or [attr<=3][attr.level2="foo"]
* nested attribute: FunctionDeclaration > Identifier.id
* field: :first-child
* First or last child: or :last-child:nth-child(2)
* nth-child (no ax+b support): :nth-last-child(1)
* nth-last-child (no ax+b support): ancestor descendant
* descendant: parent > child
* child: node ~ sibling
* following sibling: node + adjacent
* adjacent sibling: :not(ForStatement)
* negation: :matches([attr] > :first-child, :last-child)
* matches-any: IfStatement:has([name="foo"])
* has: :statement
* class of AST node: , :expression, :declaration, :function, or :pattern
* Identifier - any identifier (name of a function, class, variable, etc)IfStatement
* , ForStatement, WhileStatement, DoStatement - control flowFunctionDeclaration
* , ClassDeclaration, ArrowFunction - declarationsVariableStatement
* - var, const, let.ImportDeclaration
* - any import statementStringLiteral
* - any stringTrueKeyword
* , FalseKeyword, NullKeyword, AnyKeyword - various keywordsCallExpression
* - function callNumericLiteral
* - any numeric constantNoSubstitutionTemplateLiteral
* , TemplateExpression - template strings and expressions
Parse a string of code into an Abstract Syntax Tree which can then be queried with TSQuery Selectors.
`typescript
import { ast } from '@phenomnomnominal/tsquery';
const sourceFile = ast('const x = 1;');
`
Check for Nodes within a given string of code or AST Node matching a Selector.
`typescript
import { includes } from '@phenomnomnominal/tsquery';
const hasIdentifier = includes('const x = 1;', 'Identifier');
`
Transform AST Nodes within a given Node matching a Selector. Can be used to do Node-based replacement or removal of parts of the input AST.
`typescript
import { factory } from 'typescript';
import { map } from '@phenomnomnominal/tsquery';
const tree = ast('const x = 1;')
const updatedTree = map(tree, 'Identifier', () => factory.createIdentifier('y'));
`
Find AST Nodes within a given AST Node matching a Selector.
`typescript
import { ast, match } from '@phenomnomnominal/tsquery';
const tree = ast('const x = 1;')
const [xNode] = match(tree, 'Identifier');
`
Parse a string into an ESQuery Selector.
`typescript
import { parse } from '@phenomnomnominal/tsquery';
const selector = parse(':matches([attr] > :first-child, :last-child)');
`
Print a given Node or SourceFile to a string, using the default TypeScript printer.
`typescript
import { print } from '@phenomnomnominal/tsquery';
import { factory } from 'typescript';
// create synthetic node:
const node = factory.createArrowFunction(
// ...
);
const code = print(node);
`
Get all the SourceFiles included in a the TypeScript project described by a given config file.
`typescript
import { project } from '@phenomnomnominal/tsquery';
const files = project('./tsconfig.json');
`
Get all the file paths included ina the TypeScript project described by a given config file.
`typescript
import { files } from '@phenomnomnominal/tsquery';
const filePaths = files('./tsconfig.json');
`
Find AST Nodes within a given string of code or AST Node matching a Selector.
`typescript
import {query } from '@phenomnomnominal/tsquery';
const [xNode] = query('const x = 1;', 'Identifier');
`
Transform AST Nodes within a given Node matching a Selector. Can be used to do string-based replacement or removal of parts of the input AST. The updated code will be printed with the TypeScript Printer, so you may need to run your own formatter on any output code.
`typescript
import { replace } from '@phenomnomnominal/tsquery';
const updatedCode = replace('const x = 1;', 'Identifier', () => 'y'));
``