Sputter is a CSS-like selector library that lets you query an arbitrary AST.
Sputter is a fork of ESQuery.
The following selectors are supported:
- AST node type:
ForStatement - wildcard:
* - attribute existence:
[attr] - attribute value:
[attr="foo"]or[attr=123] - attribute regex:
[attr=/foo.*/] - attribute conditons:
[attr!="foo"],[attr>2],[attr<3],[attr>=2], or[attr<=3] - nested attribute:
[attr.level2="foo"] - field:
FunctionDeclaration > Identifier.id - First or last child:
:first-childor:last-child - nth-child (no ax+b support):
:nth-child(2) - nth-last-child (no ax+b support):
:nth-last-child(1) - descendant:
ancestor descendant - child:
parent > child - following sibling:
node ~ sibling - adjacent sibling:
node + adjacent - negation:
:not(ForStatement) - matches-any:
:matches([attr] > :first-child, :last-child) - subject indicator:
!IfStatement > [name="foo"] evalfor complex queries::eval('node.type === "Foo"')
const ast = {
type: "Foo",
children: [
{
type: "Bar",
value: 5,
},
],
};
const sputter = require("sputter");
sputter.query(ast, "Foo > Bar[value=5]"); // [ { type: "Bar", value: 5 } ]If your ast uses a key other than type to identify the type of a node, use .configure:
const ast = {
kind: "Foo",
children: [
{
kind: "Bar",
value: 5,
},
],
};
const sputter = require("sputter").configure({
identifierKey: "kind",
});
sputter.query(ast, "Foo > Bar[value=5]"); // [ { kind: "Bar", value: 5 } ]