Package reference
Mirrors the package README (single source). Install @basaltkit/cli v1.10.0 — npm · source.
<p align="center"> <a href="https://basaltkit-docs.pages.dev"> <img src="https://basaltkit-docs.pages.dev/social-card.png" alt="Basalt" width="440"> </a> </p>
@basaltkit/cli
Terminal command framework (the basalt command) for Basalt applications: define your own commands, run them against the already-booted application, and inspect HTTP routes and scheduled tasks. You need it when you want to give your application its own "command line" — for example basalt routes or basalt db:seed.
What this module solves
A CLI (Command Line Interface) is a way to interact with a program by typing commands into a terminal, instead of clicking buttons. Almost every server application needs administrative tasks that don't make sense as web pages: listing registered routes, running migrations, seeding the database, and so on.
The problem is that these tasks usually need the application "alive": with the database connected, plugins registered, and configuration loaded. Writing a standalone script for each task forces you to repeat all that bootstrapping manually.
@basaltkit/cli solves this: you describe each command with defineCommand, register the commands with the commandsPlugin plugin, and runCli handles the rest — boots the application, parses the terminal arguments, runs the right command, and shuts everything down at the end. It also ships with two built-in commands (routes and schedule:list) and utilities for testing commands without printing anything to the screen.
Installation
pnpm add @basaltkit/cli> Note: the package depends on @basaltkit/core (the heart of the framework, where createApp and the dependency container live). If you created the project with create-basalt --cli, both are already installed.
The global basalt launcher
Inside an app, basalt is a package.json script: pnpm basalt <command>. Install the launcher once to type basalt <command> instead:
npm i -g @basaltkit/cli
basalt routes # anywhere inside the app = pnpm basalt routes, in the app's rootIt finds the nearest package.json with a basalt script, from the current directory up, and runs that script with the app's package manager (packageManager, else the lockfile). So the code that runs is always the app's, at its pinned versions. Arguments and the exit code pass through unchanged. Outside an app it says so and exits 1. The launcher loads nothing of the framework, only Node built-ins.
basalt new <name> [flags] is the launcher's own command: it scaffolds an app with create-basalt@latest (through pnpm dlx, else npx; --pm= picks the manager), so it always gets the latest scaffolder.
Get started in 5 minutes
- Create a
bin/basalt.tsfile at the root of the project — this will be the entry point for thebasaltcommand:
#!/usr/bin/env node
import { runCli } from '@basaltkit/cli'
import { buildApp } from '../src/app.js'
const app = buildApp({ logLevel: 'silent' })
process.exit(await runCli({ app }))- Define one of your own commands, for example in
src/commands/greet.ts:
import { defineCommand } from '@basaltkit/cli'
export const greetCommand = defineCommand({
name: 'greet',
description: 'Greets someone',
usage: '[<name>] [--loud]', // shown by `basalt help greet`
flags: { '--loud': 'Shout it' },
handle({ args, flags, io }) {
const line = `Hello, ${args[0] ?? 'world'}!`
io.log(flags['loud'] === true ? line.toUpperCase() : line)
},
})- Register the command in the application (in
src/app.ts), inside the plugin list:
import { createApp } from '@basaltkit/core'
import { commandsPlugin } from '@basaltkit/cli'
import { greetCommand } from './commands/greet.js'
export function buildApp() {
return createApp({
plugins: [commandsPlugin([greetCommand])],
})
}- Add a shortcut in
package.json:
{
"scripts": {
"basalt": "tsx bin/basalt.ts"
}
}- Run it in the terminal:
pnpm basalt list # lists all available commands, grouped
pnpm basalt greet Maria # prints: Hello, Maria!
pnpm basalt help greet # Usage: basalt greet [<name>] [--loud], the description and the flagsbasalt list groups commands by the prefix before the first : — tenant:create and tenant:migrate under tenant, ai:plan under ai — with the ungrouped ones (dev, routes, greet) on top. The prefix is the whole taxonomy: name a command report:monthly and it gets a report group. basalt list tenant (or just basalt tenant) shows one group; a mistyped name gets a suggestion (Did you mean tenant:migrate?).
Command names are unique: when two registrations share a name (say, a plugin's own tenant:migrate and one you pass to commandsPlugin), the first registered runs and basalt warns on stderr that the other is ignored — basalt list shows the name once, with the same warning.
Usage guide
Built-in commands
Without registering anything, runCli always provides:
| Command | What it does |
|---|---|
basalt list [<group>] (or basalt with no arguments, or basalt <group>) | Lists the available commands with their descriptions, grouped by the prefix before : (ungrouped first, groups alphabetical); with a group, only that one. An unknown group exits 1 naming the groups there are |
basalt help <command> (or basalt <command> --help) | Prints the command's usage line, description and flags, without running it. basalt help alone lists; basalt help <group> shows a group. An app command named help keeps the name (--help still works) |
basalt routes [--json] [--unguarded --require=auth,can [--allow=<glob,…>]] | Lists the HTTP routes registered by the application with the guards each declares in meta — columns auth, can, rateLimit, tenant and guards (mfa, teamRole, scopes, subscribed, feature). --json prints one JSON array of route rows. --unguarded lists the routes that do not declare the --required guards and exits 1 when there is any (see Route security review). Read from the http:routes metadata bucket, populated by every HTTP adapter |
basalt schedule:list | Lists scheduled tasks and their cron expressions (read from the schedule:entries bucket, populated by @basaltkit/scheduler) |
basalt dev [--entry] [--worker] [--queue] [--routes] | Runs the app with watch + restart, and with --worker also starts a watched queue:work alongside it (server + worker in one command). Delegates watching to tsx watch / node --watch. Runs src/dev.ts when present (else src/main.ts, src/server.ts, …). A create-basalt bin/basalt.ts routes dev to runDev({ loadApp }) before booting anything, so it starts even while the app cannot boot. --routes boots the app once first to print the route table (shut down before the server starts: one app per session); without it nothing boots before the server — list routes with basalt routes. |
basalt upgrade [--dry] [--only=<id>] [--dir=<path>] | Applies framework upgrade codemods (ships the @machize/* → @basaltkit/* scope rename; --dry previews). create-basalt update runs them for you after an install. nodeUpgradeFs(baseDir) resolves relative paths against the directory being upgraded, so --dir= reads the tree it lists. It does not touch the dependencies: that is basalt update |
basalt publish [<id>] [--force] | Copies a bundled stub group into the app — dockerfile (a multi-stage build that runs pnpm build and ships dist/src/server.js on plain node as USER node, plus a .dockerignore keeping .env and keys out of the image — the same files create-basalt scaffolds), ci (install, typecheck, build, test), editorconfig (run with no id to list). The stub contents are exported too: DOCKERFILE, DOCKERIGNORE, CI_WORKFLOW, EDITORCONFIG, PRODUCTION_ENTRY |
Not served by runCli: the project commands update, add, doctor and info belong to create-basalt — the scaffolded bin/basalt.ts forwards them before booting the app (so pnpm basalt update works even when the app does not boot). On an older bin/basalt.ts they hit Unknown command, followed by a hint to run npx create-basalt@latest <command>.
If you also install @basaltkit/generator, you gain the make:* commands. Feature plugins register their own: queue:work|stats|retry|jobs (@basaltkit/queue), tenant:list|create|migrate|seed|run (@basaltkit/tenancy), generate:docs (@basaltkit/http), and mail:preview (@basaltkit/mailer).
Defining a command with arguments and flags
Positional arguments are the loose words after the command name; flags are options in the format --name or --name=value. The parser is simple and predictable:
--fresh→flags.fresh === true(boolean)--step=2→flags.step === '2'(string — convert it to a number yourself if you need to)
import { defineCommand } from '@basaltkit/cli'
export const migrateCommand = defineCommand({
name: 'tenant:migrate',
description: 'Migrates a tenant database',
async handle({ args, flags, container, io }) {
const tenantId = args[0]
if (!tenantId) {
io.error('Usage: basalt tenant:migrate <tenantId> [--fresh] [--step=N]')
return 1 // exit code ≠ 0 signals an error to the terminal
}
const fresh = flags['fresh'] === true
const step = typeof flags['step'] === 'string' ? Number(flags['step']) : undefined
io.log(`Migrating ${tenantId} (fresh=${fresh}, step=${step ?? 'all'})…`)
// use container.get(TOKEN) to get application services
return 0
},
})Naming convention: noun:verb, for example tenant:migrate, db:seed.
Testing commands without printing to the screen
memoryIo() captures everything the command would print, so you can assert on it in tests (a real example from the package's test suite):
import { describe, expect, it } from 'vitest'
import { createApp } from '@basaltkit/core'
import { commandsPlugin, defineCommand, memoryIo, runCli } from '@basaltkit/cli'
it('runs the greet command', async () => {
const io = memoryIo()
const app = createApp({
plugins: [
commandsPlugin([
defineCommand({
name: 'greet',
handle: ({ args, io }) => io.log(`Hello, ${args[0]}!`),
}),
]),
],
})
const code = await runCli({ app, argv: ['greet', 'world', '--loud'], io })
expect(code).toBe(0)
expect(io.lines).toEqual(['Hello, world!'])
})API reference
Everything the package exports from @basaltkit/cli:
defineCommand(command)
A typed identity function — returns the definition as-is, it just ensures the object has the right shape.
CommandDefinition:
| Field | Type | Required? | Default | Description |
|---|---|---|---|---|
name | string | Yes | — | Command name; convention noun:verb |
description | string | No | — | One line shown in basalt list. Keep the arguments out of it — they go in usage |
usage | string | No | — | What follows the name on the command line, for basalt help <name>: '<id> [--force]' prints Usage: basalt tenant:destroy <id> [--force] |
flags | Record<string, string> | No | — | Flag → what it does, listed by basalt help <name>: { '--force': 'Overwrite existing files' } |
handle | (context) => void | number | Promise<void | number> | Yes | — | The function that runs; returns the exit code (omit = 0) |
CommandContext (the object received by handle):
| Field | Type | Description |
|---|---|---|
app | BasaltApp | The application (already booted) |
container | Container | The dependency container — use container.get(TOKEN) to get services |
io | CommandIo | Write surface (log, error, table) |
args | string[] | Positional arguments after the command name |
flags | Record<string, string | boolean> | Flags: --key=value → string, --flag → true |
runCli(options): Promise<number>
Boots the application (if it's still in the created phase), resolves the command (built-in + registered in the commands metadata bucket), runs it, and shuts down the application at the end (app.shutdown(), even on error). Returns the exit code instead of calling process.exit — the caller decides what to do with it.
RunCliOptions:
| Field | Type | Required? | Default | Description |
|---|---|---|---|---|
app | BasaltApp | Yes | — | The application created with createApp |
argv | string[] | No | process.argv.slice(2) | Arguments to parse |
io | CommandIo | No | consoleIo() | Write surface — swap for memoryIo() in tests |
Behavior: no command (or list) shows the command table and returns 0; an unknown command prints an error and returns 1; otherwise it returns the command's own code (?? 0).
commandsPlugin(commands: CommandDefinition[])
A Basalt plugin that registers the commands in the 'commands' metadata bucket, where runCli fetches them from. Pass it in the plugins list of createApp.
parseArgv(argv: string[]): ParsedArgv
A minimal argument parser: the first "loose" word is the command; --key=value and --flag become flags. Returns { command: string | undefined, args: string[], flags: Record<string, string | boolean> }.
A bare --no-<name> is the conventional negation: it yields flags['<name>'] === false, not flags['no-<name>'] === true. That is what makes documented opt-outs such as basalt ai:make --no-migrate take effect — commands test flags['migrate'] !== false. Only the bare form negates: --no-cache=x still parses as the literal key no-cache.
consoleIo(): CommandIo
A CommandIo implementation that writes to the console (console.log / console.error; table renders via renderTable). It's the default for runCli.
memoryIo(): CommandIo & { lines: string[]; errors: string[] }
An in-memory implementation for tests: accumulates messages in lines and errors instead of printing them.
renderTable(rows: Record<string, unknown>[]): string
Renders the rows as an aligned text table, with no external dependencies. Returns '(empty)' for an empty list. undefined/null cells are left blank.
builtinCommands(): CommandDefinition[]
Returns [routesCommand, scheduleListCommand, devCommand, upgradeCommand, publishCommand]. (Advanced — runCli already includes them automatically.)
routesCommand / scheduleListCommand
The definitions of the built-in routes and schedule:list commands. (Advanced — useful only if you want to run them directly or compose your own list.)
routeAllowPattern(glob) compiles an --allow pattern into a (row) => boolean; UNGUARDED_SCOPE_NOTE is the "route meta only" caveat --unguarded prints.
Exported types
| Type | Description |
|---|---|
CommandDefinition, CommandContext, CommandIo | Described above |
RunCliOptions, ParsedArgv | Described above |
RouteMetadata | { method: string; url: string; meta?: Record<string, unknown>; [key: string]: unknown } — entries from the http:routes bucket |
ScheduleMetadata | { name: string; cron: string; timezone: string } — entries from the schedule:entries bucket |
Route security review
basalt routes answers "which route is unprotected?", not just "which routes exist":
method url auth can rateLimit tenant guards
------ ----------------- ----- --------------- -------------- -------- ------
GET /health false
GET /projects true projects:read
POST /projects true projects:create 10/1m per user required
POST /webhooks/stripeGate it in CI — the command exits 1 and names each offender and what it misses:
pnpm basalt routes --unguarded --require=auth,can --allow='POST /webhooks/*'--requireis mandatory (auth,can, or both). An explicit opt-out is intentional and never reported:auth: false(orpublic: true) satisfies both, andcan: falsesatisfiescan. Onlyauth: truecounts asauth— the one valueauthPluginenforces.--allowtakes comma-separated globs:*matches within one path segment,**across segments; a leading method ('POST /webhooks/*') restricts it to that method.--jsoncombines with--unguardedto print the offenders with amissingarray.- The
tenantcolumn shows the route's tenancy declaration:required(meta.tenant: true),exempt(meta.tenant: false),central-only(meta.tenant: 'never'— a request that resolves a tenant is rejected), or blank when the route inherits the app-wide default. It reflectsmeta.tenantonly;meta.central: true(the teams membership bypass) shows ascentralamong the guards.
It checks route meta only. An app-wide rate limit (securityPlugin({ rateLimit })), URL-based tenancy (tenancyPlugin({ required: { except } })), app hooks or middleware, and the edge routes plugins add through HTTP_SERVER.addRoute() (healthPlugin, metricsPlugin, openapiPlugin) are invisible to it. Routes from authRoutes(), mcpRoutes() and any other BasaltRoute[] you pass to the adapter are listed. The same rows are available to a test, without listening — describeRoutes() and findUnguardedRoutes() from @basaltkit/http:
import { ensureMetadata } from '@basaltkit/core'
import { describeRoutes, findUnguardedRoutes } from '@basaltkit/http'
const app = await buildApp().boot()
const rows = describeRoutes(ensureMetadata(app.container).get('http:routes'))
expect(findUnguardedRoutes(rows, { require: ['auth', 'can'] })).toEqual([])
await app.shutdown()Common errors and solutions (FAQ)
Unknown command "x". Run "basalt list" to see what is available. When a registered name is close (a few edits away, or the same action in a group — migrate → tenant:migrate), the line also says Did you mean …?. Otherwise the command isn't registered. Confirm you passed it inside commandsPlugin([...]) and that plugin is in the plugins list of createApp. Run basalt list to see what's available. For update, add, doctor or info, see the second line of the error: those are create-basalt's project commands, and npx create-basalt@latest update teaches an old bin/basalt.ts to forward them.
My command runs but the --step 2 flag doesn't work. The parser only recognizes the equals-sign form: --step=2. Written with a space, 2 is treated as a positional argument (it shows up in args).
basalt routes says "No routes registered." The command reads the http:routes metadata bucket, which is populated by the HTTP adapter (for example fastifyPlugin). Make sure the adapter is registered on the same application you pass to runCli.
The application "hangs" after the command finishes.runCli always calls app.shutdown() at the end. If something stays alive, it's probably a resource left open outside the application's lifecycle (a setInterval you created, for example) — close it in the command itself.
I want a custom error exit code. Return a number from handle (for example return 3). runCli propagates it; the example bin/basalt.ts passes it to process.exit.
How it connects to other modules
@basaltkit/core— direct dependency:runClireceives aBasaltAppfromcreateApp, and commands access theContainerand the metadata buckets (ensureMetadata).@basaltkit/generator— providesgeneratorCommands(), a list ofmake:*commands (code generators) ready to pass tocommandsPlugin. That's howbasalt make:resourceshows up.@basaltkit/fastify— writes routes into thehttp:routesbucket, which the built-inroutescommand reads.@basaltkit/scheduler— writes tasks into theschedule:entriesbucket, whichschedule:listreads.create-basalt— with the--cliflag (or later,create-basalt add cli), the project generator createsbin/basalt.ts, thepnpm basaltscript, and registerscommandsPlugin(generatorCommands())for you. It also provides the project commandsbin/basalt.tsforwards:update,add,doctor,info.