Console
Introduction
The console package gives your application a command line. You write each command as a class with a signature string that declares its arguments and options, register the classes on a kernel, and dispatch argv to the kernel. The kernel parses the input, binds it to your command, runs handle() and returns an exit code.
Everything a command prints goes through an injected output object and everything it reads goes through an injected input object. That means a command never touches process on its own, and you can run any command in a test and assert on exactly what it printed.
pnpm add @plinthjs/consoleWriting commands
A command extends Command, declares a static signature and description, and implements handle(). The return value of handle() is the exit code. Returning nothing is the same as returning 0.
import { Command } from '@plinthjs/console'
export class GreetCommand extends Command {
static override signature = 'greet {name=World}'
static override description = 'Print a greeting'
override handle(): number {
this.info(`Hello, ${String(this.argument('name'))}!`)
return 0
}
}handle() may be async. The kernel awaits it, so you can query a database or call an API inside a command.
export class PruneCommand extends Command {
static override signature = 'sessions:prune'
static override description = 'Delete expired sessions'
override async handle(): Promise<number> {
const removed = await pruneExpiredSessions()
this.info(`Removed ${String(removed)} sessions.`)
return removed > 0 ? 0 : 1
}
}Registering commands
Create a kernel, register your command classes, and call run() with the arguments you want to dispatch. The first element of argv is the command name and the rest are its arguments and options.
import { BufferedOutput, createKernel } from '@plinthjs/console'
const kernel = createKernel([GreetCommand])
// or: new Kernel().register(GreetCommand)
const output = new BufferedOutput()
const code = await kernel.run(['greet', 'Ada'], output)
code // => 0
output.lines // => ['Hello, Ada!']register() returns the kernel, so registrations chain. kernel.has('greet') and kernel.names() tell you what is registered. Calling run([]) with no command name runs the built-in list command, which prints every registered command with its description.
await kernel.run([], output)
// Available commands:
// list List the registered commands
// greet Print a greetingDispatching an unknown name throws an error that includes the registered command names.
Commands in the generated app
A project created with create-plinthjs-app has the wiring already. src/routes/console.ts exports registerConsole(kernel), which registers every command class in src/commands/. src/console.ts boots the application, builds the kernel, calls registerConsole() and runs process.argv. To add a command of your own, create the class in src/commands/ and add one .register(...) line to src/routes/console.ts.
Run a command by passing its name to the console entry:
npx tsx src/console.ts list
npx tsx src/console.ts migrate
npx tsx src/console.ts route:listThe generated project also depends on @plinthjs/cli, which provides the plinth command: npx plinth migrate runs the same entry from any folder inside the project. See The plinth command.
Defining the signature
The signature is the command name followed by arguments and options in braces. The parser turns it into definitions that decide how argv is bound.
static override signature = 'mail:send {user} {tags*} {--queue} {--times=1} {--subject=}'Arguments
| Token | Meaning |
|---|---|
{user} | Required positional argument |
{user?} | Optional argument, undefined when absent |
{user=ann} | Optional argument with a default value |
{tags*} | Array argument that consumes every remaining positional value |
{tags?*} | Same as {tags*}; an empty array when nothing is supplied |
An array argument must be the last argument in the signature, otherwise parsing the signature throws. A required argument that is missing makes the kernel throw Not enough arguments (missing: "user").
Options
| Token | Meaning |
|---|---|
{--queue} | Boolean flag. false when absent, true when --queue is passed |
{--times=1} | Option that takes a value, with a default of '1' |
{--subject=} | Option that takes a value and has no default |
Value options accept both --times=3 and --times 3. A flag does not accept a value, so --queue=yes throws. An option that is not in the signature throws an error that lists the known options. A value option with no default is absent from the options map when you do not pass it, so this.option('subject') returns undefined.
Descriptions
Add : description after an argument or option to document it. The description is ignored by the parser, so it is purely for readers of the signature.
static override signature =
'report:build {month : The month to report on} {--force : Overwrite an existing report}'Reading arguments and options
Inside handle() read the bound input with argument() and option(). Arguments come back as string, string[] for an array argument, or undefined. Options come back as string, boolean or undefined, and every value is a string because it came from argv, so convert numbers yourself.
export class MailSendCommand extends Command {
static override signature = 'mail:send {user} {tags*} {--queue} {--times=1} {--subject=}'
static override description = 'Send a mail to the given user'
override handle(): number {
const user = this.argument('user') // => 'ann'
const tags = this.argument('tags') // => ['a', 'b']
const queued = this.option('queue') === true // => true
const times = Number(this.option('times')) // => 3
const subject = this.option('subject') // => 'Hi'
this.info(`Sending ${String(times)} mail(s) to ${String(user)}`)
return 0
}
}
await kernel.run(['mail:send', 'ann', 'a', 'b', '--queue', '--times', '3', '--subject=Hi'], output)The same data is available in bulk: arguments() and options() return the whole map, and hasArgument(name) and hasOption(name) test for presence.
Writing output
A command has a handful of methods for writing lines. They all go to the output object the kernel was given.
this.line('A plain line')
this.info('Something worked')
this.comment('A side note')
this.warn('Careful')
this.error('Something failed')
this.question('A question line')
this.alert('Pay attention') // => '*** Pay attention ***'
this.newLine(2) // two blank linesBy default the output writes to console.log. In the generated app, src/console.ts passes an Output whose sink writes to process.stdout. The output does not add colour, so the methods differ only in how they would be used, except alert(), which wraps the message in asterisks.
To send output somewhere else, construct an Output with your own sink. This is how you redirect a command to a log file or collect lines for a test.
import { Output } from '@plinthjs/console'
const lines: string[] = []
const output = new Output({ sink: (line) => lines.push(line) })BufferedOutput is a ready-made version of that. It keeps every line in output.lines, toString() joins them with newlines, and clear() empties the buffer.
Tables
table(headers, rows) renders a box-drawn table. Each column is padded to its widest cell.
this.table(
['Name', 'Role'],
[
['Ada', 'admin'],
['Linus', 'dev'],
],
)
// +-------+-------+
// | Name | Role |
// +-------+-------+
// | Ada | admin |
// | Linus | dev |
// +-------+-------+Cells must be strings, so convert numbers first. The generated route:list command uses table() to print the router's routes.
Progress bars
createProgressBar(total) returns a bar you drive yourself. Each call to start(), advance(), setProgress() or finish() writes one line, or, when the output is an interactive terminal (Output.forStdout() on a TTY), redraws a single line in place and ends it on finish(). spin() and spinWith() behave the same way.
const bar = this.createProgressBar(4)
bar.start() // [ ] 0/4 ( 0%)
bar.advance(2) // [=========> ] 2/4 ( 50%)
bar.finish() // [====================] 4/4 (100%)The position is clamped between zero and the total. When you simply have a list to walk through, withProgressBar(items, callback) renders a bar that advances once per item and returns the callback results in order.
const doubled = this.withProgressBar([1, 2, 3], (n) => n * 2)
doubled // => [2, 4, 6]The bar is line based, so every update is a new line rather than a redrawn terminal row. That keeps it easy to assert on in tests.
Asking for input
There are two families of input helpers. The methods on Command (ask, secret, confirm, choice, anticipate) are the simple ones. The prompt functions (text, select, multiselect, textarea, pause, and friends) are richer and can be used outside a command.
Both families print the question and read one line at a time from an Input. The input is the third argument to kernel.run() and kernel.call().
INFO
A bare new Input() has no source, so every prompt falls back to its default value. The generated app's src/console.ts passes a StdinInput, which reads answers from the terminal; when stdin is not a TTY (CI, pipes) it never reads and every prompt uses its default. See Supplying input.
Question helpers on the command
const name = this.ask('Name?', 'bob') // prints "Name? [bob]", returns the answer or 'bob'
const token = this.secret('Token?') // returns undefined for an empty answer
const sure = this.confirm('Continue?', false) // accepts y, yes, 1, true, n, no, 0, false
const color = this.choice('Pick one', ['red', 'blue'], 'red') // answer by name or by zero-based index
const city = this.anticipate('City?', ['Paris', 'Rome'], 'Paris') // prints suggestionssecret() reads through Input.readSecret(). With a StdinInput on a TTY the typed characters are not echoed; with scripted inputs it reads a plain line.
Prompt functions
The prompt functions take an options object. Pass the same input and output your command uses so they work with the kernel and in tests.
import { multiselect, select, text } from '@plinthjs/console'
const name = text({ label: 'Name', input, output })
const city = text({ label: 'City', default: 'Paris', input, output })
// prints "City [Paris]"; an empty answer returns 'Paris'
const role = select({
label: 'Role',
options: { admin: 'Administrator', editor: 'Editor' },
input,
output,
})
// lists "[0] Administrator" and "[1] Editor"; answer with 'editor' or '1'; returns the key
const tags = multiselect({
label: 'Tags',
options: ['x', 'y', 'z'],
default: ['x'],
input,
output,
})
// answer "1,2" or "y z"; returns the chosen values in option orderoptions is either an array of strings or an object whose keys are the returned values and whose values are the labels. A user answers a select or multiselect by value or by zero-based index. For select, an empty or unrecognised answer returns the default (the first option when you set none). For multiselect, an empty answer returns the default list, unrecognised values are dropped, and required: true re-prompts when nothing valid was chosen.
text also takes placeholder, required and validate. A validate function receives the value and returns an error message or undefined. A required or invalid answer is re-prompted until it is valid. If the input has run out, the prompt throws instead of looping forever.
const email = text({
label: 'Email',
required: true,
validate: (value) => (value.includes('@') ? undefined : 'That is not an email address.'),
input,
output,
})The other prompts:
import { password, pause, promptConfirm, search, suggest, textarea } from '@plinthjs/console'
password({ label: 'Password', required: true, input, output }) // like text, no default
textarea('Bio', { input, output })
// reads lines until a line that contains only "." (or the input ends), joined with newlines
pause('Press enter to continue...', { input, output }) // => true when a line was read
promptConfirm({ label: 'Delete everything?', default: false, yes: 'Yes', no: 'No', input, output })
suggest({ label: 'City', options: ['Paris', 'Rome'], input, output }) // text with a suggestion line
search({
label: 'User',
options: (query) => users.filter((u) => u.startsWith(query)),
input,
output,
})
// reads a query, lists the matches, then reads the pick; returns '' when nothing matchesconfirm is exported as promptConfirm so it does not clash with other names.
Spinners, notes and progress
spin() runs a callback while showing a message and returns the callback's result. spinWith(output, ...) does the same through a specific output.
import { intro, noteWith, outro, progress, spinWith } from '@plinthjs/console'
intro('Importing users', output) // writes "┌ Importing users"
const count = await spinWith(output, async () => importUsers(), 'Importing')
// writes "⠋ Importing", then "✔ Importing" when the callback resolves
noteWith(output, 'Skipped 3 rows', 'warning') // 'info' | 'warning' | 'error' | 'alert' | 'intro' | 'outro'
outro('Done', output) // writes "└ Done"
progress({ label: 'Steps', steps: [1, 2, 3], callback: (n) => n * 2, output })
// writes the label and a progress bar, returns [2, 4, 6]The standalone helpers info, warning, error, alert, note, intro and outro take an optional output as their last argument. Without one they write with console.log. The error helper is exported as promptError.
Supplying input
An Input wraps a synchronous function that returns the next line or undefined when there is none. In tests use ArrayInput, which serves a fixed list of answers in order.
import { ArrayInput, BufferedOutput } from '@plinthjs/console'
const output = new BufferedOutput()
const input = new ArrayInput(['Ann', 'yes'])
await kernel.run(['onboard'], output, input)
input.remaining() // => 0 once every answer was usedFor a real terminal, pass a StdinInput. It reads lines from standard input synchronously, hides typed characters for secret() on a TTY, and when stdin is not a TTY it reports end of input so every prompt uses its default (pass readPiped: true to read piped answers instead).
import { Output, StdinInput } from '@plinthjs/console'
process.exitCode = await kernel.run(process.argv.slice(2), Output.forStdout(), new StdinInput())StdinInput takes isTTY, read, setRawMode and write options, so a test can drive it with a fake stream.
Calling other commands
A command dispatched through the kernel can run another registered command with call(). It returns that command's exit code. The called command writes to the same output.
export class DeployCommand extends Command {
static override signature = 'deploy'
static override description = 'Run the deployment steps'
override async handle(): Promise<number> {
const code = await this.call('migrate')
if (code !== 0) return code
await this.callSilently('cache:clear') // output is discarded
await this.call('mail:send', ['ops', '--queue'])
return 0
}
}call(name, args) takes the arguments as an array of strings, in the same form as argv. callSilently() is identical except that the output goes to a buffer nobody reads. A command that was not dispatched through a kernel (for example one you built by hand) has no runner, and calling call() on it rejects with an error.
You can do the same from outside a command with kernel.call(name, argv, output, input), which is what run() uses internally.
Generating files
A GeneratorCommand is a command that writes one file from a stub. You implement four methods and it handles the "already exists" check, the --force option and the success message.
import { GeneratorCommand } from '@plinthjs/console'
import { Str } from '@plinthjs/support'
export class MakeJobCommand extends GeneratorCommand {
static override signature = 'make:job {name} {--force}'
static override description = 'Create a new job class'
protected override stub(): string {
return 'export class {{ class }}Job {\n handle(): void {}\n}\n'
}
protected override getPath(name: string): string {
return `src/jobs/${Str.studly(name)}.ts`
}
protected override replacements(name: string): Record<string, string> {
return { class: Str.studly(name) }
}
protected override type(): string {
return 'Job'
}
}The command needs a name argument. stub() returns the template, and any {{ key }} placeholder (spaces optional) is replaced with the matching entry from replacements(). Placeholders with no matching key are left untouched. getPath() returns where to write the file and type() is the label used in messages (it defaults to the class name without the Command suffix).
npx tsx src/console.ts make:job send_mail
# Job [src/jobs/SendMail.ts] created successfully.
npx tsx src/console.ts make:job send_mail
# Job [src/jobs/SendMail.ts] already exists. (exit code 1)
npx tsx src/console.ts make:job send_mail --force
# Job [src/jobs/SendMail.ts] created successfully.The --force option has to be declared in the signature, as above, for the check to see it.
renderStub(stub, replacements) is exported on its own if you want the same substitution elsewhere.
Testing generators
Files are written through a Filesystem. The default NodeFilesystem creates parent directories and writes to disk. InMemoryFilesystem keeps everything in a map. The kernel constructs your command, so to inject a filesystem in a test override the files property in a subclass.
import { InMemoryFilesystem } from '@plinthjs/console'
const files = new InMemoryFilesystem()
const kernel = createKernel([MakeJobCommand], { files })
await kernel.call('make:job', ['send_mail'], new BufferedOutput())
files.get('src/jobs/SendMail.ts') // => 'export class SendMailJob {...'
files.paths() // => ['src/jobs/SendMail.ts']The kernel hands its files option to every generator it runs, so no subclass is needed. To set a default for all generators, assign GeneratorCommand.defaultFilesystem. If you construct a command yourself, usingFilesystem(files) swaps the filesystem.
The package also ships MakeClassCommand (make:class {name} {--force}), which writes an empty class to src/<Name>.ts. It is a working example of a generator you can read and copy.
The commands in a generated app
The scaffolder registers these commands for you. Each one is a plain command class in src/commands/, so you can read and change them.
| Command | What it does |
|---|---|
list | Lists every registered command (built into the kernel) |
migrate | Runs pending migrations |
migrate:rollback {--step=1} | Rolls back the last batch (or --step batches) |
migrate:status | Shows which migrations have run |
migrate:refresh {--seed} | Rolls back everything, migrates again, and seeds with --seed |
db:seed {--class=} | Runs DatabaseSeeder, or the seeder named by --class |
key:generate | Writes a new random APP_KEY into .env |
route:list | Prints the registered routes as a table |
inspire | Prints a quote; the smallest possible command example |
make:controller {name} {--resource} {--force} | Creates src/controllers/<name>.ts |
make:model {name} {--force} | Creates src/models/<name>.ts |
make:migration {name} {--create=} {--table=} {--force} | Creates a timestamped file in src/database/migrations/ |
make:seeder {name} {--force} | Creates src/database/seeders/<name>.ts |
make:middleware {name} {--force} | Creates src/middleware/<name>.ts |
The file name is the kebab-case of the name you pass, and the class keeps its name: make:controller PostController creates src/controllers/post-controller.ts containing PostController.
For example:
npx tsx src/console.ts make:controller PostController --resource
npx tsx src/console.ts make:migration create_posts_table --create=posts
npx tsx src/console.ts migrateDatabase-aware commands resolve the connection through the container, which src/console.ts boots before dispatching. See Migrations and Seeding for what they run.
Testing commands
Because output and input are injected, a command test needs no process tricks. Build a kernel, run it with a BufferedOutput and an ArrayInput, and assert on the exit code and the lines.
import { ArrayInput, BufferedOutput, createKernel } from '@plinthjs/console'
import { expect, it } from 'vitest'
it('greets the user', async () => {
const kernel = createKernel([GreetCommand])
const output = new BufferedOutput()
const code = await kernel.run(['greet', 'Ada'], output, new ArrayInput())
expect(code).toBe(0)
expect(output.lines).toEqual(['Hello, Ada!'])
})To check that a bad invocation is rejected, assert that kernel.run() rejects. Parsing errors (a missing argument, an unknown option) and unknown command names are thrown, not returned as exit codes.
await expect(kernel.run(['greet', '--nope'], output)).rejects.toThrow(
'The "--nope" option does not exist',
)Related
Scheduled tasks can run work on a timer; see Scheduling. To run a shell command from inside a command, see Process. For an interactive session that evaluates code against your application, see REPL.