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

@dashdot/rcmd

v0.0.3

Published

Route commands

Downloads

9

Readme

rcmd

build codecov

Route command (rcmd) helps you execute commands locally or on remote environments using api routes.

Usage

Inside your Node project directory, run the following:

npm i --save rcmd

start executing commands

rcmd https://example.com/cmd/db/migrate/latest --force

or with using some additional config

rcmd db/migrate/latest --production --force

or if your only using the cli:

npx rcmd db/migrate/latest --production --force

What is rcmd?

rcmd is a simple CLI tool and a handy request handler utility. The Essence of this library can be simplified to the code below.

// cli
async function rcmd() {
    await fetch(`${environment}/${route}?argv=${process.argv.join(' ')}`)
}
// req handler util
async function parseCmdReq(req, spec, cmd) {
    const argv = new URL(req.url).searchParams.get('argv')
    const args = praseArgv(argv, spec)
    await cmd(...args)
}

The CLI will simply send the process.argv as a query param to a url. The req handler utility parseCmdReq will parse the argv based on a spec and pass the parsed options to a command function. Thats basically it.

Why would you want to do that?

Commands are a useful tool for developers to perform technical operations via the CLI on a local or remote environment. However, executing commands on serverless environments can be challenging since there is no physical machine to run the commands on. Additionally, when commands depend on environment secrets (such as database operations), sharing these secrets with the remote environment and the machine executing the command can be a difficult problem. By using rcmd, you can overcome these problems by simply exposing API routes that correspond to the commands you want to execute.

Exposing technical API routes like that obviously comes with some security concerns. rcmd provides simple tools to secure those endpoints and make sure not malicious users can access them.

Config

Config inside .rcmdrc or other formats

{
    "basePath": "/cmd",
    "envs": {
        "local": "http://localhost:3000",
        "development": "https://development.example.com",
        "staging": "http://staging.example.com",
        "production": "http://example.com"
    }
}

Example

Expose a route on your server:

// app/cmd/db/migrate/rollback/route.js
import { parseCmdReq } from 'rcmd'
import db from './db'

export async function GET(req) {
    const spec = { '--step': Number }
    const { status, body } = await parseCmdReq(req, spec, async ({ step }) => {
        db.migrate.rollback({ step })
    })
    return NextResponse.json(body, { status })
}

Run command locally

rcmd db/migrate/rollback --local

or on remote environment

RCMD_SECRET="secret" rcmd db/migrate/rollback --production

you can pass options

rcmd db/migrate/rollback --local --step=5

using express

// app/router/cmd.js
import { parseCmdReq } from 'rcmd'
import app from './app'
import db from './db'

const cmd = app.Router()
cmd.get('/db/migrate/rollback', (req, res) => {
    const { status, body } = await parseCmdReq(req, spec, async ({ step }) => {
        db.migrate.rollback({ step })
    })
    res.status(status);
    res.json(body)
})
cmd.get('/db/migrate/up', ...)
cmd.get('/db/migrate/down', ...)
app.use('/cmd', cmd);

limitation

It is not possible to make interactive commands with tools like inquirer or prompts.

Custom parsing

There is nothing special about the cli tool it just create a request with the process.argv as query params to a url.

rcmd db/migrate/rollback --local --step=5

will be converted to a fetch request to:

https://localhost:3000/cmd/db/migrate/rollback?argv="--step=5"

rcmd automatically excluded env options like --local and --staging, etc. So if you want to have custom parsing for your commands or just want to pass them to something like a library like commander it's perfectly possible

// Next.js
// app/cmd/db/migrate/rollback/route.ts
import { Command } from 'commander'
import { parseCmdReq } from 'rcmd'
import db from './db'

export async function GET(req) {
    checkSecret(req)
    const argv = new URL(req.url).searchParams.get('argv')
    const program = new Command()
    program
        .name('db/migrate/rollback')
        .option('-s, --step <number>')
        .action(({ step }) => {
            db.migrate.rollback({ step })
        })
    program.parse(argv.split(' '))
}

So theres is also nothing stopping your for using tools like curl to execute the same commands.

curl -XGET \
	"https://localhost:3000/cmd/db/migrate/rollback?argv='--step=5'" \
	-H "Authorization: Bearer secret"

FAQ

A few questions and answers that have been asked before:

Is this safe?

How to execute commands as part of deployment?

You are still sharing a secret. How is this different?