@nodesecure/estree-ast-utils
ESTree compliant utilities to manipulate, extract and transform AST nodes.
Getting Started
This package is available in the Node Package Repository and can be easily installed with npm or yarn.
$ npm i @nodesecure/estree-ast-utils
$ yarn add @nodesecure/estree-ast-utils
API
Most utility options extend the DefaultOptions interface:
export interface DefaultOptions {
externalIdentifierLookup?(name: string): string | null;
}
You can provide a custom externalIdentifierLookup function to enable the utilities to resolve identifiers from external sources—such as VariableTracer, for example.
arrayExpressionToString(node: ESTree.Node | null): IterableIterator< string >
Transforms an ESTree ArrayExpression into an iterable of literal values.
["foo", "bar"];
will yield "foo", then "bar".
concatBinaryExpression(node: ESTree.BinaryExpression, options?: ConcatBinaryExpressionOptions): IterableIterator< string >
Returns all Literal nodes from a binary expression.
"foo" + "bar";
Will yield "foo", then "bar".
Options are described by the following interface:
interface ConcatBinaryExpressionOptions extends DefaultOptions {
stopOnUnsupportedNode?: boolean;
}
extractLogicalExpression(node: ESTree.Node): IterableIterator< { operator: string; node: ESTree.Expression; } >
Recursively extracts all LogicalExpression components.
{ operator: "||" | "&&" | "??", node: ESTree.Expression }
For example:
freeGlobal || freeSelf || Function('return this')();
Will yield three components:
- freeGlobal
- freeSelf
- and finally
Function('return this')();
getCallExpressionArguments(node: ESTree.Node, options?: DefaultOptions): string[] | null
Returns the literal arguments of a CallExpression.
For example:
eval("require");
Returns
["require"]
getCallExpressionIdentifier(node: ESTree.Node, options?: GetCallExpressionIdentifierOptions): string | null
Returns the identifier name of a CallExpression, or null if not resolvable.
foobar();
Returns "foobar".
By default, it resolves member expressions.
This can be disabled with resolveCallExpression: false.
require('./file.js')();
With resolveCallExpression: false, the function will return null.
interface GetCallExpressionIdentifierOptions extends DefaultOptions {
resolveCallExpression?: boolean;
}
getMemberExpressionIdentifier(node: ESTree.MemberExpression, options?: DefaultOptions): IterableIterator< string >
Returns the identifier chain from a MemberExpression.
foo.bar();
will return "foo" then "bar".
getVariableDeclarationIdentifiers(node: any, options?: GetVariableDeclarationIdentifiersOptions): IterableIterator< string >
Extracts all variable identifiers from a declaration.
const [foo, bar] = [1, 2];
will return "foo" then "bar".
License
MIT