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

super-state-machine-router

v1.1.1

Published

An O(n) URL router with wildcard support

Downloads

6

Readme

super-state-machine-router test

An efficient URL router with the following features:

  • O(n) routing time, regardless of the number of routes
  • Route conflict/ambiguity detection (i.e., the order that routes are registered does not matter)
  • Wildcard path segments are supported via /foo/{myVariable}
    • Wilcards can also match one or more segments with /foo/{myVariable}+
    • Or zero or more segmetns with /foo/{myVariable}*
  • Under the hood, it uses a compressed, precise state machine with low memory overhead

Installation

npm install super-state-machine-router

Requires Node.js v14.x.x or later.

Usage

const { RouterBuilder } = require('super-state-machine-router');

const router = new RouterBuilder()
	.add('/', myIndexPath)
	.add('/index.html', myIndexPath)
	.add('/style.css', myStylesheet)
	.add('/app.js', myScript)
	.add('/login/{loginMethod}', myLoginPage)
	.add('/api/{endpoint}+', myAPI)
	.build();

const match = router.route('/api/foo/bar/baz');
assert(match === myAPI);

const noMatch = router.route('/not/a/real/page');
assert(noMatch === undefined);

API

class RouterBuilder

RouterBuilder lets you build routers. You add routes to a builder by calling .add() and, when you're done adding routes, you can build the actual router with .build().

builder.add(routeDefinition, value) -> this

Adds a new route to the builder. The route definition should be a string starting with /. Trailing slashes and empty path segments are not allowed. The route can include percent-encodings.

The value that you pass to the second argument gets associated with the route, and will be returned by the router when the route is matched.

Any path segment within the route definition can be {someVariable}, which will match any sequence of one or more characters (except /). You can have multiple variable segments within the same route.

builder.add('/article/{id}/comments/{commentId}', someValue);

If the last segment is a variable, it may be followed by + or *, which allows it to match any number of additional segments afterwards. A variable with + must match at least one segment, but a variable with * can match zero segments.

// Matches "/api/foo" and "/api/foo/bar", but not "/api"
builder.add('/api/{endpoint}+', someValue);

// Matches "/redirect/foo/bar" and "/redirect"
builder.add('/redirect/{newPath}*', someValue);

Note that variables cannot be combined with literal characters in the same segment; either a segment is a variable, or it is a literal string.

builder.addLiteral(routeDefinition, value) -> this

This is the same as builder.add(), except all special characters within the route definition are interpreted literally. As a result, percent-encodings and variables cannot be used within the route definition.

builder.build() -> Router

Constructs and returns a router based on the routes that have been added to the builder thus far. If there are multiple routes which could be matched by the same URL pathname, the ambiguity is detected and an error is thrown.

class Router

This class lets you efficiently match URL pathnames against a set of routes.

You cannot construct this class directly (you have to use the RouterBuilder). However, if you pass a router to another thread (using worker_threads), you can use new Router(oldRouter) to revive the router within the worker thread, with the correct prototype chain.

router.route(url, [outVariables]) -> value or undefined

Attempts to match the given url (a string or URL object) with a route. If a matching route is found, it returns the value that was originally associated with the route. If no matching route is found, it returns undefined.

Percent-encodings are understood and interpretted correctly.

If you pass an object as the second parameter, the values of any variables within the matching route will be assigned to the object that you provide.

const router = new RouterBuilder().add('/{first}/{second}', 123).build();

const variables = {};
const match = router.route('/foo/bar', variables);

assert(match === 123);
assert(variables.first === 'foo');
assert(variables.second === 'bar');

router.map(callback) -> Router

Creates a new router that is equivalent to this one except that each route's associated value is mapped through the given callback function.

Using this method is more efficient than building multiple separate routers because the underlying state machine (which may be quite large) will be shared among the routers created by this method.

const newRouter = oldRouter.map(value => value.id);

Iterable protocol

Routers are iterables, which means you can iterate over them using a for-of loop to get each route's associated value (i.e., the values that may be returned by router.route()).

for (const value of router) {
    console.log(value);
}

License

MIT