npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@rushstack/tree-pattern

v0.3.4

Published

A fast, lightweight pattern matcher for tree structures such as an Abstract Syntax Tree (AST)

Downloads

392,422

Readme

@rushstack/tree-pattern

This is a simple, fast pattern matcher for JavaScript tree structures. It was designed for ESLint rules and transforms that match parse trees such as produced by Esprima. However, it can be used with any JSON-like data structure.

Usage

Suppose we are fixing up obsolete Promise calls, and we need to match an input like this:

Promise.fulfilled(123);

The parsed subtree looks like this:

{
  "type": "Program",
  "body": [
    {
      "type": "ExpressionStatement",
      "expression": {  // <---- expressionNode
        "type": "CallExpression",
        "callee": {
          "type": "MemberExpression",
          "object": {
            "type": "Identifier",
            "name": "Promise"
          },
          "property": {
            "type": "Identifier",
            "name": "fulfilled"
          },
          "computed": false,
          "optional": false
        },
        "arguments": [
          {
            "type": "Literal",
            "value": 123,
            "raw": "123"
          }
        ],
        "optional": false
      }
    }
  ],
  "sourceType": "module"
}

Throwing away the details that we don't care about, we can specify a pattern expression with the parts that need to be present:

const pattern1: TreePattern = new TreePattern({
  type: 'CallExpression',
  callee: {
    type: 'MemberExpression',
    object: {
      type: 'Identifier',
      name: 'Promise'
    },
    property: {
      type: 'Identifier',
      name: 'fulfilled'
    },
    computed: false
  }
});

Then when our visitor encounters an ExpressionStatement, we can match the expressionNode like this:

if (pattern1.match(expressionNode)) {
  console.log('Success!');
}

Capturing matched subtrees

Suppose we want to generalize this to match any API such as Promise.thing(123); or Promise.otherThing(123);. We can use a "tag" to extract the matching identifier:

const pattern2: TreePattern = new TreePattern({
  type: 'CallExpression',
  callee: {
    type: 'MemberExpression',
    object: {
      type: 'Identifier',
      name: 'Promise'
    },
    property: TreePattern.tag('promiseMethod', {
      type: 'Identifier'
    }),
    computed: false
  }
});

On a successful match, the tagged promiseMethod subtree can be retrieved like this:

interface IMyCaptures {
  // Captures the "promiseMethod" tag specified using TreePattern.tag()
  promiseMethod?: { name?: string }; // <--- substitute your real AST interface here
}

const captures: IMyCaptures = {};

if (pattern2.match(node, captures)) {
  // Prints: "Matched fulfilled"
  console.log('Matched ' + captures?.promiseMethod?.name);
}

Alternative subtrees

The oneOf API enables you to write patterns that match alternative subtrees.

const pattern3: TreePattern = new TreePattern({
  animal: TreePattern.oneOf([
    { kind: 'dog', bark: 'loud' },
    { kind: 'cat', meow: 'quiet' }
  ])
});

if (pattern3.match({ animal: { kind: 'dog', bark: 'loud' } })) {
  console.log('I can match dog.');
}

if (pattern3.match({ animal: { kind: 'cat', meow: 'quiet' } })) {
  console.log('I can match cat, too.');
}

For example, maybe we want to match Promise['fulfilled'](123); as well as Promise.fulfilled(123);. If the structure of the expressions is similar enough, TreePattern.oneOf avoids having to create two separate patterns.

Links

@rushstack/tree-pattern is part of the Rush Stack family of projects.