Skip to content

Quickstart

This page builds a small version of the GitHub CLI, gh, with a pr list command and a pr create command. You define every way into the program, parse argv into a typed intent, and dispatch on it.

route() declares an address. command() is an address that can also execute. Definitions are immutable composition pipelines, not handler registrations:

import {
function command<const N extends string, const E extends readonly Input[]>(start: Definition<N>, ...elements: E & Validate<CommandZero<N>, E>): Materialize<Fold<CommandZero<N>, Normalize<E>>>
command
,
function description(description: string): IdentityElement<Definition<string>>
description
,
function name<N extends string>(name: N): Definition<N>
name
,
function option<const N extends string, const E extends readonly Unary[]>(named: Definition<N>, ...elements: E & Check<Zero<N>, E>): ElementOf<...>
option
,
function route<const N extends string, const E extends readonly Input[]>(start: Definition<N>, ...elements: E & Validate<RouteZero<N>, E>): Materialize<Fold<RouteZero<N>, Normalize<E>>>
route
,
function schema<S extends Schema>(schema: S): TransformElement<SchemaTransform<OutputOf<S>>>
schema
,
function toggle<const N extends string, const E extends readonly Unary[]>(named: Definition<N>, ...elements: E & Check<Zero<N>, E>): ElementOf<...>
toggle
,
function version(semver: string): MethodElement<"version">
version
,
} from "@bomb.sh/router";
import * as
import z
z
from "zod";
const
const states: z.ZodEnum<["open", "closed", "merged", "all"]>
states
=
import z
z
.
enum<string, ["open", "closed", "merged", "all"]>(values: ["open", "closed", "merged", "all"], params?: z.RawCreateParams): z.ZodEnum<["open", "closed", "merged", "all"]> (+1 overload)
export enum
enum
(["open", "closed", "merged", "all"]);
const
const app: Route<"gh", "version" | "help" | "execute", readonly [Done<{}, readonly [Route<"pr", "help", readonly [Done<{}, readonly [Route<"list", "help" | "execute", readonly [Done<{
state: "open" | "closed" | "merged" | "all";
limit: number;
}, []>]>, Route<...>]>]>]>]>
app
=
command<"gh", readonly [IdentityElement<Definition<string>>, MethodElement<"version">, Route<"pr", "help", readonly [Done<{}, readonly [Route<"list", "help" | "execute", readonly [...]>, Route<...>]>]>]>(start: Definition<...>, elements_0: IdentityElement<...>, elements_1: MethodElement<...>, elements_2: Route<...>): Route<...>
command
(
name<"gh">(name: "gh"): Definition<"gh">
name
("gh"),
function description(description: string): IdentityElement<Definition<string>>
description
("Work seamlessly with GitHub from the command line."),
function version(semver: string): MethodElement<"version">
version
("2.62.0"),
route<"pr", readonly [Route<"list", "help" | "execute", readonly [Done<{
state: "open" | "closed" | "merged" | "all";
limit: number;
}, []>]>, Route<"create", "help" | "execute", readonly [Done<{
...;
}, []>]>]>(start: Definition<...>, elements_0: Route<...>, elements_1: Route<...>): Route<...>
route
(
name<"pr">(name: "pr"): Definition<"pr">
name
("pr"),
command<"list", readonly [ModelElement<ParamModel<"state", "open" | "closed" | "merged" | "all">>, ModelElement<ParamModel<"limit", number>>]>(start: Definition<...>, elements_0: ModelElement<ParamModel<"state", "open" | "closed" | "merged" | "all">>, elements_1: ModelElement<ParamModel<"limit", number>>): Route<...>
command
(
name<"list">(name: "list"): Definition<"list">
name
("list"),
option<"state", readonly [TransformElement<SchemaTransform<"open" | "closed" | "merged" | "all">>]>(named: Definition<"state">, elements_0: TransformElement<SchemaTransform<"open" | "closed" | "merged" | "all">>): ModelElement<...>
option
(
name<"state">(name: "state"): Definition<"state">
name
("state"),
schema<z.ZodDefault<z.ZodEnum<["open", "closed", "merged", "all"]>>>(schema: z.ZodDefault<z.ZodEnum<["open", "closed", "merged", "all"]>>): TransformElement<SchemaTransform<"open" | "closed" | "merged" | "all">>
schema
(
const states: z.ZodEnum<["open", "closed", "merged", "all"]>
states
.
ZodType<"open" | "closed" | "merged" | "all", ZodEnumDef<["open", "closed", "merged", "all"]>, "open" | "closed" | "merged" | "all">.default(def: "open" | "closed" | "merged" | "all"): z.ZodDefault<z.ZodEnum<["open", "closed", "merged", "all"]>> (+1 overload)
default
("open"))),
option<"limit", readonly [TransformElement<SchemaTransform<number>>]>(named: Definition<"limit">, elements_0: TransformElement<SchemaTransform<number>>): ModelElement<...>
option
(
name<"limit">(name: "limit"): Definition<"limit">
name
("limit"),
schema<z.ZodDefault<z.ZodNumber>>(schema: z.ZodDefault<z.ZodNumber>): TransformElement<SchemaTransform<number>>
schema
(
import z
z
.
function number(params?: z.RawCreateParams & {
coerce?: boolean;
}): z.ZodNumber
export number
number
().
ZodType<number, ZodNumberDef, number>.default(def: number): z.ZodDefault<z.ZodNumber> (+1 overload)
default
(30))),
),
command<"create", readonly [ModelElement<ParamModel<"title", string>>, ModelElement<ParamModel<"draft", boolean>>]>(start: Definition<"create">, elements_0: ModelElement<ParamModel<"title", string>>, elements_1: ModelElement<ParamModel<"draft", boolean>>): Route<...>
command
(
name<"create">(name: "create"): Definition<"create">
name
("create"),
option<"title", readonly [TransformElement<SchemaTransform<string>>]>(named: Definition<"title">, elements_0: TransformElement<SchemaTransform<string>>): ModelElement<...>
option
(
name<"title">(name: "title"): Definition<"title">
name
("title"),
schema<z.ZodString>(schema: z.ZodString): TransformElement<SchemaTransform<string>>
schema
(
import z
z
.
function string(params?: z.RawCreateParams & {
coerce?: true;
}): z.ZodString
export string
string
())),
toggle<"draft", readonly []>(named: Definition<"draft">): ModelElement<ParamModel<"draft", boolean>>
toggle
(
name<"draft">(name: "draft"): Definition<"draft">
name
("draft")),
),
),
);

That definition makes these entry points reachable, and no others:

HELP / VERSION / EXECUTE /
HELP /pr
HELP /pr/list EXECUTE /pr/list
HELP /pr/create EXECUTE /pr/create

Every route supports help. Version exists only on the root, because only the root calls version(). pr is a route(), not a command(), so it has no execute method.

The root name identifies the executable and is not repeated in route IDs. gh pr list selects /pr/list, not /gh/pr/list.

parse() returns a discriminated union of every reachable entry point. Check ok, then switch on method and route. The dispatch stays flat even when the route tree is deep:

import
var process: NodeJS.Process
process
from "node:process";
import {
function parse<const R extends AnyRoute>(route: R, input: Input): Parse<R>
parse
,
function printErrors(result: MethodNotAllowed | UnprocessableContent): string
printErrors
,
function printHelp<const H extends Help<RoutePath>>(intent: H): string
printHelp
,
function printVersion<const V extends Version<RoutePath>>(intent: V): string
printVersion
,
} from "@bomb.sh/router";
const
const result: Parse<Route<"gh", "version" | "help" | "execute", readonly [Done<{}, readonly [Route<"pr", "help", readonly [Done<{}, readonly [Route<"list", "help" | "execute", readonly [Done<{
state: "open" | "closed" | "merged" | "all";
limit: number;
}, []>]>, Route<...>]>]>]>]>>
result
=
parse<Route<"gh", "version" | "help" | "execute", readonly [Done<{}, readonly [Route<"pr", "help", readonly [Done<{}, readonly [Route<"list", "help" | "execute", readonly [Done<{
state: "open" | "closed" | "merged" | "all";
limit: number;
}, []>]>, Route<...>]>]>]>]>>(route: Route<...>, input: Input): Parse<...>
parse
(
const app: Route<"gh", "version" | "help" | "execute", readonly [Done<{}, readonly [Route<"pr", "help", readonly [Done<{}, readonly [Route<"list", "help" | "execute", readonly [Done<{
state: "open" | "closed" | "merged" | "all";
limit: number;
}, []>]>, Route<...>]>]>]>]>
app
, {
argv: string[]
argv
:
var process: NodeJS.Process
process
.
NodeJS.Process.argv: string[]

The process.argv property returns an array containing the command-line arguments passed when the Node.js process was launched. The first element will be

execPath

. See process.argv0 if access to the original value of argv[0] is needed. The second element will be the path to the JavaScript file being executed. The remaining elements will be any additional command-line arguments.

For example, assuming the following script for process-args.js:

import { argv } from 'node:process';
// print process.argv
argv.forEach((val, index) => {
console.log(`${index}: ${val}`);
});

Launching the Node.js process as:

Terminal window
node process-args.js one two=three four

Would generate the output:

0: /usr/local/bin/node
1: /Users/mjr/work/node/process-args.js
2: one
3: two=three
4: four

@since ― v0.1.27

argv
.
Array<string>.slice(start?: number, end?: number): string[]

Returns a copy of a section of an array. For both start and end, a negative index can be used to indicate an offset from the end of the array. For example, -2 refers to the second to last element of the array.

@param ― start The beginning index of the specified portion of the array. If start is undefined, then the slice begins at index 0.

@param ― end The end index of the specified portion of the array. This is exclusive of the element at the index 'end'. If end is undefined, then the slice extends to the end of the array.

slice
(2) });
if (!
const result: Parse<Route<"gh", "version" | "help" | "execute", readonly [Done<{}, readonly [Route<"pr", "help", readonly [Done<{}, readonly [Route<"list", "help" | "execute", readonly [Done<{
state: "open" | "closed" | "merged" | "all";
limit: number;
}, []>]>, Route<...>]>]>]>]>>
result
.
ok: boolean
ok
) {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@see ― source

console
.
Console.error(message?: any, ...optionalParams: any[]): void

Prints to stderr with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr

If formatting elements (e.g. %d) are not found in the first string then util.inspect() is called on each argument and the resulting string values are concatenated. See util.format() for more information.

@since ― v0.1.100

error
(
function printErrors(result: MethodNotAllowed | UnprocessableContent): string
printErrors
(
const result: MethodNotAllowed | UnprocessableContent
result
));
var process: NodeJS.Process
process
.
NodeJS.Process.exit(code?: number | string | null): never

The process.exit() method instructs Node.js to terminate the process synchronously with an exit status of code. If code is omitted, exit uses either the 'success' code 0 or the value of process.exitCode if it has been set. Node.js will not terminate until all the 'exit' event listeners are called.

To exit with a 'failure' code:

import { exit } from 'node:process';
exit(1);

The shell that executed Node.js should see the exit code as 1.

Calling process.exit() will force the process to exit as quickly as possible even if there are still asynchronous operations pending that have not yet completed fully, including I/O operations to process.stdout and process.stderr.

In most situations, it is not actually necessary to call process.exit() explicitly. The Node.js process will exit on its own if there is no additional work pending in the event loop. The process.exitCode property can be set to tell the process which exit code to use when the process exits gracefully.

For instance, the following example illustrates a misuse of the process.exit() method that could lead to data printed to stdout being truncated and lost:

import { exit } from 'node:process';
// This is an example of what *not* to do:
if (someConditionNotMet()) {
printUsageToStdout();
exit(1);
}

The reason this is problematic is because writes to process.stdout in Node.js are sometimes asynchronous and may occur over multiple ticks of the Node.js event loop. Calling process.exit(), however, forces the process to exit before those additional writes to stdout can be performed.

Rather than calling process.exit() directly, the code should set the process.exitCode and allow the process to exit naturally by avoiding scheduling any additional work for the event loop:

import process from 'node:process';
// How to properly set the exit code while letting
// the process exit gracefully.
if (someConditionNotMet()) {
printUsageToStdout();
process.exitCode = 1;
}

If it is necessary to terminate the Node.js process due to an error condition, throwing an uncaught error and allowing the process to terminate accordingly is safer than calling process.exit().

In Worker threads, this function stops the current thread rather than the current process.

@since ― v0.1.13

@param ― code The exit code. For string type, only integer strings (e.g.,'1') are allowed.

exit
(1);
}
switch (
const result: Help<"/"> | Version<"/"> | Execute<"/", {
"/": {};
}> | Help<"/pr"> | Help<"/pr/list"> | Execute<"/pr/list", {
"/": {};
"/pr": {};
"/pr/list": {
state: "open" | "closed" | "merged" | "all";
limit: number;
};
}> | Help<...> | Execute<...>
result
.
Intent<M extends Method, P extends RoutePath>.method: "version" | "help" | "execute"
method
) {
case "help":
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@see ― source

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@since ― v0.1.100

log
(
printHelp<Help<"/"> | Help<"/pr"> | Help<"/pr/list"> | Help<"/pr/create">>(intent: Help<"/"> | Help<"/pr"> | Help<"/pr/list"> | Help<"/pr/create">): string
printHelp
(
const result: Help<"/"> | Help<"/pr"> | Help<"/pr/list"> | Help<"/pr/create">
result
));
break;
case "version":
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@see ― source

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@since ― v0.1.100

log
(
printVersion<Version<"/">>(intent: Version<"/">): string
printVersion
(
const result: Version<"/">
result
));
break;
case "execute":
switch (
const result: Execute<"/", {
"/": {};
}> | Execute<"/pr/list", {
"/": {};
"/pr": {};
"/pr/list": {
state: "open" | "closed" | "merged" | "all";
limit: number;
};
}> | Execute<...>
result
.
Intent<M extends Method, P extends RoutePath>.route: "/" | "/pr/list" | "/pr/create"
route
) {
case "/pr/list":
const result: Execute<"/pr/list", {
"/": {};
"/pr": {};
"/pr/list": {
state: "open" | "closed" | "merged" | "all";
limit: number;
};
}>
result
.
Execute<"/pr/list", { "/": {}; "/pr": {}; "/pr/list": { state: "open" | "closed" | "merged" | "all"; limit: number; }; }>.model: {
state: "open" | "closed" | "merged" | "all";
limit: number;
}
model
.
state: "open" | "closed" | "merged" | "all"
state
; // "open" | "closed" | "merged" | "all"
const result: Execute<"/pr/list", {
"/": {};
"/pr": {};
"/pr/list": {
state: "open" | "closed" | "merged" | "all";
limit: number;
};
}>
result
.
Execute<"/pr/list", { "/": {}; "/pr": {}; "/pr/list": { state: "open" | "closed" | "merged" | "all"; limit: number; }; }>.model: {
state: "open" | "closed" | "merged" | "all";
limit: number;
}
model
.
limit: number
limit
; // number
break;
case "/pr/create":
const result: Execute<"/pr/create", {
"/": {};
"/pr": {};
"/pr/create": {
title: string;
draft: boolean;
};
}>
result
.
Execute<"/pr/create", { "/": {}; "/pr": {}; "/pr/create": { title: string; draft: boolean; }; }>.model: {
title: string;
draft: boolean;
}
model
.
title: string
title
; // string
const result: Execute<"/pr/create", {
"/": {};
"/pr": {};
"/pr/create": {
title: string;
draft: boolean;
};
}>
result
.
Execute<"/pr/create", { "/": {}; "/pr": {}; "/pr/create": { title: string; draft: boolean; }; }>.model: {
title: string;
draft: boolean;
}
model
.
draft: boolean
draft
; // boolean
break;
}
}

Each branch sees only its own model. Hover any identifier to see the type TypeScript infers.

An execute intent carries two views of configuration:

  • model holds the parameters owned by the selected route.
  • models holds the model for every route along the selected path, keyed by route ID. Sibling routes are absent from both the value and its type.

For gh pr create --title "Fix typo" --draft, model is { title: "Fix typo", draft: true }, and models is { "/": {}, "/pr": {}, "/pr/create": { title: "Fix typo", draft: true } }.

InvocationResult
gh pr listEXECUTE /pr/list with { state: "open", limit: 30 }
gh pr list --state merged --limit 5EXECUTE /pr/list with { state: "merged", limit: 5 }
gh pr create --title "Fix typo" --draftEXECUTE /pr/create with { title: "Fix typo", draft: true }
gh --help pr listHELP /pr/list. Help and version target the deepest selected route.
gh prmethod-not-allowed, because /pr does not support execution
gh pr list --limit lotsunprocessable-content. Invalid data never reaches your application.

Command literals such as pr and list are routing tokens, not positional arguments. Each option binds to the route segment that owns it, so a parent and a child route can both declare an option with the same name.