将 tRPC 路由器转换为类型安全、功能完备、有文档的 CLI
Build production-quality command-line tools in minutes, not days
trpc-cli transforms a tRPC (or oRPC) router into a professional-grade CLI with zero boilerplate. Get end-to-end type safety, input validation, auto-generated help documentation, and command completion for free.
commander@trpc/server or @orpc/servernpx trpc-cli ./commands.tstRPC offers best-in-class type-safety and DX for building "procedures" that validate their inputs, and abide by their own contracts. This library gives you all those DX benefits, and allows mapping the procedures directly to a CLI. This offers the easiest way to build a CLI while mapping parsed options into strongly-typed inputs, and automatically outputs --help documentation that's always up-to-date.
This isn't just the easiest and safest way to build a CLI, but you also get all the benefits of tRPC (and zod). For inputs, you can use zod regex types, transforms, refinements, and those will map directly into useful help-text for CLI users, and corresponding type correctness when maintaining your CLI program. You can also use tRPC context and middleware functionality just like you could if you were building a server. And as an added bonus, it becomes trivially easy to turn your CLI program into a fully-functional HTTP server. Or, you could add a "programmatic usage" to your library, just by wrapping your server with the built-in createCaller function from tRPC. This would all, of course, have runtime and compile-time type safety.
npm install trpc-cli @trpc/server zodThe fastest way to get going is to write a normal tRPC router and turn it into a fully-functional CLI by passing it to createCli:
import {initTRPC} from '@trpc/server'
import {createCli} from 'trpc-cli'
import {z} from 'zod'
const t = initTRPC.create()
const router = t.router({
add: t.procedure
.input(z.object({left: z.number(), right: z.number()}))
.query(({input}) => input.left + input.right),
})
createCli({router}).run()And that's it! Your tRPC router is now a CLI program with help text and input validation. You can run it with node yourscript add --left 2 --right 3.
Docs here if you're not familiar with tRPC.
CLI positional arguments and options are derived from each procedure's input type. Inputs use validator types (zod, arktype, valibot, etc.) to be mapped to CLI commands.
Positional arguments passed to the CLI can be declared with types representing strings, numbers or booleans:
t.router({
double: t.procedure
.input(z.number()) //
.query(({input}) => input * 2),
})You can also use anything that accepts string, number, or boolean inputs, like z.enum(['up', 'down']), z.number().int(), z.literal(123), z.string().regex(/^\w+$/) etc.
Multiple positional arguments can use a z.tuple(...) input type:
t.router({
add: t.procedure
.input(z.tuple([z.number(), z.number()]))
.query(({input}) => input[0] + input[1]),
})Which is invoked like path/to/cli add 2 3 (outputting 5).
Note: positional arguments can use
.optional()or.nullish(), but not.nullable().
Note: positional arguments can be named using
.describe('name of parameter'), but names should not include any special characters.
Note: positional arguments are parsed based on the expected target type. Booleans must be written as
trueorfalse, spelled out. In most cases, though, you'd be better off using options for boolean inputs.
Array/spread parameters can use an array input type:
t.router({
lint: t.procedure
.input(z.array(z.string()).describe('file paths to lint'))
.mutation(({input}) => {
lintFiles(input.map(file => path.join(process.cwd(), file)))
}),
})Which is invoked like path/to/mycli lint file1 file2 file3 file4.
Array inputs can also be used with options by nesting them in a tuple.
t.router({
lint: t.procedure
.input(
z.tuple([
z.array(z.string()).describe('file paths to lint'),
z.object({maxWarnings: z.number().default(10)}),
]),
)
.mutation(({input}) => {
const result = lintFiles(
input.files.map(file => path.join(process.cwd(), file)),
)
if (result.warnings.length > input.maxWarnings) {
throw new Error(`Too many warnings: ${result.warnings.length}`)
}
}),
})Which could be invoked with any of:
mycli lint file1 file2 file3 file4 --max-warnings 10mycli lint file1 file2 file3 file4 --maxWarnings=10mycli lint --maxWarnings=10 file1 file2 file3 file4mycli lint --maxWarnings 10 file1 file2 file3 file4z.object(...) inputs become options (passed with --foo bar or --foo=bar) syntax. Values are accepted in --kebab-case, and are parsed like in most CLI programs:
Strings:
z.object({foo: z.string()}) will map:--foo bar or --foo=bar to {foo: 'bar'}Booleans:
z.object({foo: z.boolean()}) or z.object({foo: z.boolean().default(false)}) will map:
{foo: false}--foo {foo: true}z.object({foo: z.boolean().default(true)}) will map:
{foo: true}--foo false or --foo=false to {foo: false}z.object({foo: z.boolean().optional()}) will map:
{} (foo is undefined)--foo to {foo: true}--foo false to {foo: false}Negated options can be useful for default-true booleans:
z.object({foo: z.boolean().default(true).meta({negatable: true})}) will map:{foo: true}--no-foo to {foo: false}--foo false to {foo: false}(Note: you can set booleans to negatable-by-default by setting negateBooleans: true on the procedure's meta)
Numbers:
z.object({foo: z.number()}) will map:--foo 1 or --foo=1 to {foo: 1}Other types:
z.object({ foo: z.object({ bar: z.number() }) }) will parse inputs as JSON:--foo '{"bar": 1}' maps to {foo: {bar: 1}}Multi-word options:
z.object({ multiWord: z.string() }) will map:--multi-word foo to {multiWord: 'foo'}Unions and intersections should also work as expected, but make sure to test them thoroughly, especially if they are deeply-nested.
Option aliases
If you're using zod v4, or any other standard-schema library that has a similar meta functionality, you can set aliases for options with it:
const router = t.router({
deleteAll: t.procedure
.input(
z.object({
force: z.boolean().meta({alias: 'f'}),
}),
)
.mutation(async () => ___),
})If you are on an old version of zod, or another library, set aliases at the procedure level:
const router = t.router({
deleteAll: t.procedure
.meta({aliases: {options: {force: 'f'}}})
.input(
z.object({
force: z.boolean(),
}),
)
.mutation(async () => ___),
})To use positional arguments and options, there are two approaches:
1) Using input schema metadata (recommended)
Use z.string().meta({positional: true}). This is available on zod v4, and arktype via type('string').configure({positional: true}):
t.router({
copy: t.procedure
.input(
z.object({
source: z.string().meta({positional: true}),
target: z.string().meta({positional: true}),
mkdirp: z
.boolean()
.optional()
.describe("Ensure target's parent directory exists before copying"),
}),
)
.mutation(async ({input: [source, target, opts]}) => {
if (opts.mkdirp) {
await fs.mkdir(path.dirname(target, {recursive: true}))
}
await fs.copyFile(source, target)
}),
})2) Using a tuple with an object at the end
Use this if you're on an old version of zod, or using a library which doesn't support meta:
t.router({
copy: t.procedure
.input(
z.tuple([
z.string().describe('source'),
z.string().describe('target'),
z.object({
mkdirp: z
.boolean()
.optional()
.describe("Ensure target's parent directory exists before copying"),
}),
]),
)
.mutation(async ({input: [source, target, opts]}) => {
if (opts.mkdirp) {
await fs.mkdir(path.dirname(target, {recursive: true}))
}
await fs.copyFile(source, target)
}),
})You might use the above with a command like:
path/to/cli copy a.txt b.txt --mkdirpNote: when using a tuple, object types for options must appear last in the
.input(...)tuple, when being used with positional arguments. Soz.tuple([z.string(), z.object({mkdirp: z.boolean()}), z.string()])would not be allowed (inputs would have to be passed as JSON).
You can change the behaviour of the command generated for a given procedure by using trpc's meta feature.
Use description, usage and examples to add corresponding help information to your CLI:
const router = t.router({
install: t.procedure
.meta({
description: 'Installs dependencies',
// usage: 'mycli install',暂无开放 Issues,或尚未同步最近议题。