--- description: >- This tutorial walks you through building type-safe command-line applications using Optique's parser combinators, starting from simple options to complex subcommands. --- Optique tutorial: Build type-safe CLIs step by step =================================================== Optique is a type-safe combinatorial CLI parser that makes building command-line interfaces both powerful and predictable. Unlike traditional CLI parsers that rely on configuration objects, Optique uses composable functions that automatically infer TypeScript types. How Optique works ----------------- Instead of describing your CLI with configuration objects, you *build* it using small, composable functions called *parser combinators*. TypeScript automatically infers the exact type of data your parser will produce. For a deeper look at this approach and how it compares to other CLI libraries, see [Why Optique?](./why.md). The core building blocks are: - [`option()`](./concepts/primitives.md#option-parser) and [`argument()`](./concepts/primitives.md#argument-parser) for individual CLI elements - [`object()`](./concepts/constructs.md#object-parser) to group parsers into structured results - [`or()`](./concepts/constructs.md#or-parser) for mutually exclusive alternatives - [`optional()`](./concepts/modifiers.md#optional-parser), [`multiple()`](./concepts/modifiers.md#multiple-parser), and [`merge()`](./concepts/constructs.md#merge-parser) for flexible composition In this tutorial, we'll build progressively more complex CLI applications, starting with simple options and building up to production-ready tools with integration support. Getting started --------------- The journey into parser combinators begins with understanding the fundamental building blocks. In this section, we'll explore the most basic parsers and see how TypeScript's type inference makes CLI development both safer and more enjoyable. Every CLI parser in Optique is a function that takes command-line arguments and produces either a successfully parsed value or an error. The key insight is that these parsers can be composed and combined to create more sophisticated argument handling without losing type information. ### Your first CLI: single option Let's start with the simplest possible CLI—a greeting program that accepts a name. This example demonstrates the core concepts of value parsers and type inference. ~~~~ typescript twoslash import { option } from "@optique/core/primitives"; import { string } from "@optique/core/valueparser"; import { run, print } from "@optique/run"; import { message } from "@optique/core/message"; // Create a parser for --name option const nameParser = option("--name", string()); // ^? // Run the parser with some example arguments const result = run(nameParser, { // ^? args: ["--name", "Alice"] }); print(message`Hello, ${result}!`); // Output: Hello, Alice! ~~~~ This simple example demonstrates several important concepts: [Value parsers](./concepts/valueparsers.md) : The [`string()`](./concepts/valueparsers.md#string-parser) function is a [*value parser*](./concepts/valueparsers.md)—it knows how to convert a raw command-line argument (which is always a string) into a typed value. Optique provides many built-in value parsers for common data types. Type inference : Notice how TypeScript automatically infers that `nameParser` returns a `Parser`. You don't need to write any type annotations—the compiler figures out the types based on how you compose the parsers. Result handling : The *@optique/run* version of `run()` never returns on errors—it displays error messages and exits the process automatically. This makes CLI applications simpler since you only need to handle the success case. Boolean flags work differently—they don't take values and simply indicate presence or absence: ~~~~ typescript twoslash import { option } from "@optique/core/primitives"; import { run } from "@optique/run"; // Boolean flag (no value parser needed) const verboseParser = option("-v", "--verbose"); // ^? const result = run(verboseParser); // ^? // This returns true when present, false when absent ~~~~ ### Working with positional arguments While options use flags like `--name` or `-v`, positional arguments are values that appear in specific positions on the command line. Think of commands like `cp source.txt destination.txt`—the filenames are positional arguments because their meaning depends on their position, not on any flag. Positional arguments are essential for creating intuitive CLIs. Users expect to type `git commit message.txt` rather than `git commit --file message.txt`. Let's create a file processor that demonstrates this pattern: ~~~~ typescript twoslash import { argument } from "@optique/core/primitives"; import { run, print } from "@optique/run"; import { path } from "@optique/run/valueparser"; import { message } from "@optique/core/message"; // Create a parser for a required file argument const fileParser = argument(path({ metavar: "FILE" })); // ^? const result = run(fileParser, { // ^? args: ["input.txt"] }); print(message`Processing file: ${result}`); // Output: Processing file: input.txt ~~~~ The [`argument()`](./concepts/primitives.md#argument-parser) function creates a parser that consumes the next positional argument from the command line. The [`path()`](./concepts/valueparsers.md#path-parser) value parser is perfect for file and directory paths, and we'll explore its validation capabilities later in the tutorial. The `metavar: "FILE"` parameter is used in help text generation. Instead of showing a generic placeholder, help messages will display `FILE` to indicate what kind of argument is expected. ### Combining options and arguments Real CLI programs usually need both options and arguments working together. This is where Optique's compositional nature shines—the [`object()`](./concepts/constructs.md#object-parser) combinator lets us group multiple parsers into a single, structured result. The `object()` combinator is one of the most important tools in Optique. It takes multiple named parsers and combines them into a single parser that produces an object with all the parsed values. The beauty is that TypeScript automatically infers the exact shape of this object, including which fields are optional and what types they contain. ~~~~ typescript twoslash import { object } from "@optique/core/constructs"; import type { InferValue } from "@optique/core/parser"; import { argument, option } from "@optique/core/primitives"; import { string } from "@optique/core/valueparser"; import { run, print } from "@optique/run"; import { path } from "@optique/run/valueparser"; import { message } from "@optique/core/message"; const parser = object({ file: argument(path({ metavar: "FILE" })), output: option("-o", "--output", path({ metavar: "OUTPUT" })), verbose: option("-v", "--verbose") }); // TypeScript automatically infers the complete type! type Config = InferValue; // ^? const config: Config = run(parser, { args: [ "input.txt", "--output", "output.txt", "--verbose" ] }); print(message`Converting ${config.file} to ${config.output}.`); if (config.verbose) { print(message`Verbose mode enabled.`); } ~~~~ This example showcases the power of parser composition. We've created a parser that handles both positional arguments and options, and TypeScript automatically infers the complete result type. The `config` object is fully typed—the compiler knows that `file` and `output` are strings, while `verbose` is a boolean. Notice how natural the composition feels. Each parser handles one concern: - `argument(path(...))` handles the required input file - `option("-o", "--output", path(...))` handles the optional output location - `option("-v", "--verbose")` handles the verbose flag The `object()` combinator weaves them together into a cohesive whole, and the type system ensures everything fits together correctly. > [!NOTE] > The `InferValue` utility type extracts the TypeScript type that a parser > will produce. This is useful for type annotations and ensuring type safety > throughout your application. However, in most cases you won't need > it—TypeScript's inference handles everything automatically. Value parsers and validation ---------------------------- [Value parsers](./concepts/valueparsers.md) are the foundation of type-safe CLI parsing. While command-line arguments are always strings, your application needs them as numbers, URLs, file paths, or other typed values. Value parsers handle this conversion and provide validation at parse time, catching errors before they can cause problems in your application logic. The philosophy behind Optique's value parsers is “fail fast, fail clearly.” Instead of letting invalid data flow through your application and cause mysterious errors later, value parsers validate input immediately and provide clear error messages that help users fix their mistakes. ### Rich value types with built-in validation Optique provides powerful value parsers that go beyond simple strings. Each parser not only handles type conversion but also provides meaningful validation rules. Let's explore the most commonly used ones, with special attention to the versatile `path()` parser: ~~~~ typescript twoslash import { defineProgram } from "@optique/core/program"; import { object } from "@optique/core/constructs"; import { option, argument } from "@optique/core/primitives"; import { string } from "@optique/core/valueparser"; import { message } from "@optique/core/message"; import { run, print } from "@optique/run"; import { optional, withDefault, map } from "@optique/core/modifiers"; const parser = object({ name: option("-n", "--name", string()), config: optional(option("-c", "--config", string())), debug: option("--debug"), upperName: map( argument(string({ metavar: "NAME" })), (s) => s.toUpperCase(), ), host: withDefault(option("-h", "--host", string()), "localhost"), port: withDefault(option("-p", "--port", string()), "8080"), portDescription: map( withDefault(option("-p", "--port", string()), "8080"), (port) => `Server will run on port ${port}`, ), }); const prog = defineProgram({ parser, metadata: { name: "server" }, }); const config = run(prog, { args: ["--name", "test"] }); // Optional properties need checking if (config.config) { print(message`Using config: ${config.config}.`); } // Default values are always available print(message`Starting ${config.upperName} on ${config.host}:${config.port.toString()}.`); print(message`${config.portDescription}`); ~~~~ *Value transformation with `map()`*: The `map()` combinator deserves special attention. It allows you to transform parsed values while preserving the original parsing logic. This is incredibly useful for normalizing data, computing derived values, or adapting to different data formats your application expects. ### Repeatable values with `multiple()` Command-line interfaces often need to accept multiple values for the same option. Consider `gcc -I include1 -I include2 -I include3` or `curl -H "Accept: application/json" -H "Authorization: Bearer token"`. The [`multiple()`](./concepts/modifiers.md#multiple-parser) combinator handles these patterns naturally. What makes `multiple()` special is how it handles the common case gracefully. When no matches are found, it returns an empty array rather than failing to parse. This means you can make repeated options truly optional—if the user doesn't provide any, your application gets an empty array and can continue normally: ~~~~ typescript twoslash import { object } from "@optique/core/constructs"; import { message, values } from "@optique/core/message"; import { multiple } from "@optique/core/modifiers"; import { argument, option } from "@optique/core/primitives"; import { path, print, run } from "@optique/run"; import { string } from "@optique/core/valueparser"; const parser = object({ // Multiple files with constraints files: multiple(argument(path()), { min: 1, max: 5 }), // ^? // Multiple options (can be empty) headers: multiple(option("-H", "--header", string())), // ^? // Multiple with no constraints tags: multiple(option("-t", "--tag", string())), // ^? // Boolean flag (single occurrence) verbose: option("-v", "--verbose") // ^? }); // Usage: myapp file1.txt file2.txt -H "Accept: application/json" -H "User-Agent: myapp" -t web -t api -v const config = run(parser, { args: [ "file1.txt", "file2.txt", "-H", "Accept: application/json", "-H", "User-Agent: myapp", "-t", "web", "-t", "api", "-v" ] }); print(message`Processing ${config.files.length.toString()} files:`); // ^? config.files.forEach((file, index) => { // ^? print(message` ${(index + 1).toString()}. ${file}`); }); if (config.headers.length > 0) { // ^? print(message`Custom headers:`); config.headers.forEach(header => { print(message` ${header}`); }); } print(message`Tags: ${values(config.tags)}.`); // ^? ~~~~ *Constraints and validation*: The `{ min: 1, max: 5 }` constraint in the files example demonstrates another powerful feature. You can specify minimum and maximum bounds for repeated values, ensuring your application receives a reasonable number of arguments. This prevents both user error (forgetting to specify required files) and potential abuse (specifying thousands of files that might overwhelm your system). The `multiple()` combinator automatically provides empty arrays as defaults when no matches are found, making it safe to use without additional null checking. Your code can always assume arrays exist, simplifying the logic considerably. Building subcommands -------------------- Subcommands are the hallmark of sophisticated CLI tools. They allow you to group related functionality under a single program while keeping individual commands focused and easy to understand. Think of `git add`, `docker run`, or `npm install`—each subcommand is essentially a mini-program with its own options and behavior. The [`command()`](./concepts/primitives.md#command-parser) combinator makes subcommands natural to express in Optique. Unlike some CLI libraries that require complex routing logic, Optique treats subcommands as just another form of parser composition. This means you can combine subcommands with all the other patterns you've learned—they can have optional parameters, repeated arguments, discriminated unions, and more. ### Git-style CLI Let's build a `git`-like CLI that demonstrates how subcommands work in practice. Each subcommand will have its own unique options, but they'll all be part of a single, type-safe parser: ~~~~ typescript twoslash import { object, or } from "@optique/core/constructs"; import { multiple } from "@optique/core/modifiers"; import type { InferValue } from "@optique/core/parser"; import { argument, command, constant, option} from "@optique/core/primitives"; import { path, run } from "@optique/run"; import { string } from "@optique/core/valueparser"; const parser = or( command("add", object({ // [!code highlight] type: constant("add"), files: multiple(argument(path())), all: option("-A", "--all"), force: option("-f", "--force") })), command("commit", object({ // [!code highlight] type: constant("commit"), message: option("-m", "--message", string()), amend: option("--amend"), all: option("-a", "--all") })), command("push", object({ // [!code highlight] type: constant("push"), remote: option("-r", "--remote", string()), force: option("-f", "--force"), setUpstream: option("-u", "--set-upstream") })) ); // TypeScript creates a perfect discriminated union type GitCommand = InferValue; // ^? const result = run(parser, { args: ["commit", "-m", "Fix parsing bug", "--amend"] }); ~~~~ ### Nested subcommands For more complex tools, you can nest subcommands multiple levels deep: ~~~~ typescript twoslash import { object, or } from "@optique/core/constructs"; import { argument, command, constant, option } from "@optique/core/primitives"; import { run } from "@optique/run"; import { choice, string } from "@optique/core/valueparser"; // Second-level commands for "app config" const configCommands = or( command("get", object({ action: constant("get"), key: argument(string({ metavar: "KEY" })), format: option("-f", "--format", choice(["json", "yaml", "plain"])) })), command("set", object({ action: constant("set"), key: argument(string({ metavar: "KEY" })), value: argument(string({ metavar: "VALUE" })), global: option("-g", "--global") })), command("list", object({ action: constant("list"), format: option("-f", "--format", choice(["json", "yaml", "table"])) })) ); // Top-level commands const parser = or( // Nested: app config get/set/list command("config", object({ command: constant("config"), subcommand: configCommands })), // Simple: app init command("init", object({ command: constant("init"), template: option("-t", "--template", string()), force: option("-f", "--force") })), // Simple: app build command("build", object({ command: constant("build"), watch: option("-w", "--watch"), minify: option("-m", "--minify") })) ); // Usage examples: // app config get database.url --format json // app config set database.url "postgres://localhost/mydb" --global // app init --template react --force // app build --watch --minify const result = run(parser, { // ^? args: ["config", "set", "api.url", "https://api.example.com", "--global"] }); ~~~~ *The power of nested parsing*: Notice how the nested structure mirrors the command structure itself. The `config` command contains its own subparser that handles `get`, `set`, and `list`. This compositional approach scales naturally—you can nest commands as deeply as needed without losing type safety or clarity. *Global vs. local options*: This pattern also demonstrates how to handle global options (like `--global-config`) that apply to all commands, while still providing command-specific options. The type system ensures that you can only access the options that are actually available for each command. This pattern scales well for complex CLI tools with multiple levels of subcommands, each with their own options and behaviors. The type system tracks the structure automatically, so you never have to worry about accessing the wrong properties or forgetting to handle a case. ### When commands outgrow one file The examples above define the command tree directly with `command()` and `or()`. That is the clearest way to learn the model, and it works well for small and medium CLIs. When each command starts to feel like its own module, *@optique/discover* can build the same command tree from files instead. > [!WARNING] > `runProgram()` discovers command modules from the runtime file system and > imports them dynamically. This is useful for source-layout CLIs, but it is > not a good default when the CLI must be aggressively tree-shaken, statically > bundled, or packaged as a single executable. In those cases, import command > modules manually and pass them as `commands`. Each command module default-exports a command created with `defineCommand()`. The entry point then points `runProgram()` at the command directory: ~~~~ typescript twoslash import { message } from "@optique/core/message"; import { runProgram } from "@optique/discover"; await runProgram({ dir: new URL("./commands/", import.meta.url), metadata: { name: "app", brief: message`Project tools.`, }, }); ~~~~ For a bundled CLI, declare each command's path and pass the imported commands directly: ~~~~ typescript twoslash import { object } from "@optique/core/constructs"; import { message } from "@optique/core/message"; import { option } from "@optique/core/primitives"; import { string } from "@optique/core/valueparser"; import { defineCommand, runProgram } from "@optique/discover"; const build = defineCommand({ path: ["build"], parser: object({ target: option("--target", string()), }), metadata: { brief: message`Build the project.`, }, handler(value) { console.log(`Building ${value.target}.`); }, }); await runProgram({ commands: [build], metadata: { name: "app", brief: message`Project tools.`, }, }); ~~~~ With this layout: ~~~~ text commands/ build.ts deploy.ts config/ set.ts ~~~~ the file paths become command paths: ~~~~ bash app build app deploy app config set ~~~~ Use this pattern when the command file is the natural place to keep the parser, help metadata, and handler together. See the [command discovery guide](./concepts/discover.md) for the full API and the [cookbook recipe](./cookbook.md#file-based-command-discovery) for a complete example. Modularization and reusability ------------------------------ As CLI applications grow in complexity, you'll find yourself repeating similar patterns across different commands. Database connection options, logging configuration, and authentication settings tend to appear in multiple places. Rather than duplicating this logic, Optique provides powerful tools for creating reusable, composable option groups. The [`merge()`](./concepts/constructs.md#merge-parser) combinator is the key to building modular CLI applications. It allows you to define option groups once and reuse them across different commands, while maintaining complete type safety. This approach promotes consistency across your CLI—users learn the database options once and can apply that knowledge to any command that needs database access. ### Reusable option groups with `merge()` The philosophy behind option groups is separation of concerns. Instead of monolithic parsers that handle everything, you create focused parsers that handle specific areas of functionality. Then you compose these focused parsers in different combinations depending on what each command needs: ~~~~ typescript twoslash import { merge, object, or } from "@optique/core/constructs"; import { optional } from "@optique/core/modifiers"; import { constant, option } from "@optique/core/primitives"; import { path, run } from "@optique/run"; import { choice, integer, string } from "@optique/core/valueparser"; // Define reusable option groups const networkOptions = object("Network", { host: option("--host", string({ metavar: "HOST" })), port: option("--port", integer({ min: 1, max: 0xffff })) }); const authOptions = object("Authentication", { username: option("-u", "--user", string({ metavar: "USER" })), password: optional(option("-p", "--password", string({ metavar: "PASS" }))), token: optional(option("-t", "--token", string({ metavar: "TOKEN" }))) }); const loggingOptions = object("Logging", { logLevel: option("--log-level", choice(["debug", "info", "warn", "error"])), logFile: optional(option("--log-file", path({ metavar: "FILE" }))) }); // Combine groups differently for different modes const parser = or( // Development mode: minimal required options merge( object({ mode: constant("dev") }), networkOptions, object({ debug: option("--debug") }) ), // Production mode: full configuration required merge( object({ mode: constant("prod") }), networkOptions, authOptions, loggingOptions, object({ configFile: option("-c", "--config", path({ mustExist: true })), workers: option("-w", "--workers", integer({ min: 1, max: 16 })) }) ) ); const config = run(parser, { // ^? args: [ "--host", "0.0.0.0", "--port", "8080", "--user", "admin", "--log-level", "info", "--config", "prod.json", "--workers", "4" ] }); ~~~~ ### Real-world example: deployment tool CLI Let's build a comprehensive deployment tool that demonstrates all the features we've learned: ~~~~ typescript twoslash import { merge, object, or } from "@optique/core/constructs"; import { multiple, optional, withDefault } from "@optique/core/modifiers"; import type { InferValue } from "@optique/core/parser"; import { argument, command, constant, option } from "@optique/core/primitives"; import { path, run } from "@optique/run"; import { choice, integer, string, url } from "@optique/core/valueparser"; // Reusable option groups const commonOptions = object("Common", { verbose: optional(option("-v", "--verbose")), config: optional(option("-c", "--config", path({ mustExist: true }))), dryRun: optional(option("--dry-run")) }); const environmentOptions = object("Environment", { environment: argument(choice(["dev", "staging", "prod"])), region: option("-r", "--region", string()), timeout: withDefault(option("-t", "--timeout", integer({ min: 0 })), 300) }); const deployOptions = object("Deploy", { image: option("-i", "--image", string({ metavar: "IMAGE:TAG" })), replicas: withDefault(option("--replicas", integer({ min: 1, max: 50 })), 1), healthCheck: option("--health-check", url()), secrets: multiple(option("-s", "--secret", string())) }); // Main CLI parser const deploymentTool = object({ // Global options available to all commands globalConfig: optional(option("--global-config", path())), quiet: optional(option("-q", "--quiet")), // Command with rich subcommand structure command: or( // Deploy command: merge multiple option groups command("deploy", merge( object({ action: constant("deploy") }), commonOptions, environmentOptions, deployOptions, object({ // Deploy-specific options force: optional(option("-f", "--force")), rollback: optional(option("--rollback-on-failure")) }) )), // Status command: simpler option set command("status", merge( object({ action: constant("status") }), commonOptions, object({ environment: argument(choice(["dev", "staging", "prod"])), watch: optional(option("-w", "--watch")), format: withDefault( option("--format", choice(["table", "json", "yaml"])), "table" ) }) )), // Rollback command: targeted options command("rollback", merge( object({ action: constant("rollback") }), commonOptions, environmentOptions, object({ revision: option("--revision", string({ metavar: "REV" })), confirm: optional(option("--confirm")) }) )), // Logs command: streaming options command("logs", merge( object({ action: constant("logs") }), commonOptions, object({ environment: argument(choice(["dev", "staging", "prod"])), service: argument(string({ metavar: "SERVICE" })), follow: optional(option("-f", "--follow")), lines: withDefault(option("-n", "--lines", integer({ min: 1 })), 100), since: optional(option("--since", string({ metavar: "TIME" }))) }) )) ) }); // The complete inferred type - look how rich this is! type DeployConfig = InferValue; // ^? // Example usage scenarios: // deploy-tool deploy prod -i myapp:v1.2.3 --replicas 5 --health-check https://api.example.com/health -v // deploy-tool status staging --watch --format json // deploy-tool rollback prod --revision v1.2.2 --confirm // deploy-tool logs prod api-service --follow --lines 1000 const config = run(deploymentTool, { args: [ "deploy", "prod", "--image", "myapp:v1.2.3", "--replicas", "3", "--health-check", "https://api.example.com/health", "--secret", "DB_PASSWORD", "--secret", "API_KEY", "--region", "us-east-1", "--verbose", "--force" ] }); ~~~~ This example showcases: - *Modular design* with reusable option groups (`commonOptions`, `environmentOptions`, `deployOptions`) - *Rich type inference* with complex discriminated unions - *Flexible composition* using `merge()` to combine option groups differently per command - *Real-world validation* with path checking, URL validation, integer bounds, and choice constraints The `merge()` combinator is particularly powerful here—it lets us define option groups once and reuse them across different commands, while TypeScript automatically combines the types correctly. Production CLI applications --------------------------- Throughout this tutorial, we've been using *@optique/run* which provides a batteries-included experience for building CLI applications. This is the recommended approach for most use cases, as it handles all the common concerns automatically: reading from [`process.argv`] (or [`Deno.args`] on Deno), detecting terminal capabilities, displaying help text, and exiting with appropriate status codes. However, it's worth understanding the difference between *@optique/run* and *@optique/core*, and when you might choose one over the other. [`process.argv`]: https://nodejs.org/api/process.html#processargv [`Deno.args`]: https://docs.deno.com/api/deno/~/Deno.args ### *@optique/run* vs. *@optique/core* The difference between *@optique/core* and *@optique/run* is primarily about convenience and control: Use *@optique/run* when: - Building standalone CLI applications - You want automatic [`process.argv`] (or [`Deno.args`] on Deno) handling and error display - You need terminal capability detection (colors, width) - You prefer convention over configuration Use *@optique/core* when: - Building libraries that need to parse CLI-like arguments - Working in web applications or environments without [`node:process`] - You need full control over error handling and result processing - You want to integrate parsing into larger application logic Here's how the same parser would work with *@optique/core*: ~~~~ typescript twoslash import type { Program } from "@optique/core/program"; import type { InferValue } from "@optique/core/parser"; import { object } from "@optique/core/constructs"; import { runParser } from "@optique/core/facade"; import { optional } from "@optique/core/modifiers"; import { argument, option } from "@optique/core/primitives"; import { integer, string } from "@optique/core/valueparser"; import process from "node:process"; const parser = object({ input: argument(string({ metavar: "FILE" })), output: option("-o", "--output", string({ metavar: "FILE" })), port: optional(option("-p", "--port", integer({ min: 1, max: 0xffff }))), verbose: option("-v", "--verbose") }); const prog: Program<"sync", InferValue> = { parser, metadata: { name: "myapp" }, }; // @optique/core requires explicit argument handling const config = runParser(prog, process.argv.slice(2), { // ^? onError: process.exit, help: { option: true, onShow: process.exit }, }); console.log(`Processing ${config.input} -> ${config.output}.`); if (config.port) { console.log(`Server will run on port ${config.port}.`); } ~~~~ Compare this to the *@optique/run* version we've been using throughout this tutorial: ~~~~ typescript twoslash import { object } from "@optique/core/constructs"; import { optional } from "@optique/core/modifiers"; import { argument, option } from "@optique/core/primitives"; import { integer, string } from "@optique/core/valueparser"; import { path, run, print } from "@optique/run"; import { message } from "@optique/core/message"; const parser = object({ input: argument(path({ mustExist: true, metavar: "FILE" })), output: option("-o", "--output", path({ metavar: "FILE" })), port: optional(option("-p", "--port", integer({ min: 1, max: 0xffff }))), verbose: option("-v", "--verbose") }); // @optique/run handles everything automatically const config = run(parser); // ^? print(message`Processing ${config.input} -> ${config.output}.`); if (config.port) { print(message`Server will run on port ${config.port.toString()}.`); } ~~~~ The *@optique/run* version is much more concise and handles all error cases automatically. [`node:process`]: https://nodejs.org/api/process.html ### Configuration options *@optique/run* provides several configuration options for fine-tuning behavior: ~~~~ typescript twoslash import type { Program } from "@optique/core/program"; import type { InferValue } from "@optique/core/parser"; import { object } from "@optique/core/constructs"; import { map, optional, withDefault } from "@optique/core/modifiers"; import { option } from "@optique/core/primitives"; import { path, print, run } from "@optique/run"; import { integer, string } from "@optique/core/valueparser"; const parser = object({ name: option("-n", "--name", string()), config: optional(option("-c", "--config", path())), port: withDefault(option("-p", "--port", integer()), 3000), portDescription: map( // ^? withDefault(option("--port", integer()), 3000), port => `Server will run on port ${port}` ) }); const prog: Program<"sync", InferValue> = { parser, metadata: { name: "my-tool" }, }; const config = run(prog, { help: "both", // Enable --help option AND help subcommand // ^? aboveError: "usage", // Show usage information above errors // ^? colors: true, // Force colored output (auto-detected by default) maxWidth: 100, // Set help text width (auto-detected by default) termWidth: "auto", // Fit the term column to visible help entries errorExitCode: 2 // Custom exit code for errors (default: 1) }); // The help system automatically generates comprehensive help text: // $ my-tool --help // $ my-tool help ~~~~ With `termWidth: "auto"`, Optique measures the terminal display width of visible terms after built-in help/version/completion entries have been added. The default remains a fixed 26-column term width when this option is omitted. ### Complete CLI application Here's a complete, production-ready CLI application using everything we've learned: ~~~~ typescript twoslash #!/usr/bin/env node import { merge, object, or } from "@optique/core/constructs"; import { multiple, optional, withDefault } from "@optique/core/modifiers"; import type { InferValue } from "@optique/core/parser"; import type { Program } from "@optique/core/program"; import { argument, command, constant, option } from "@optique/core/primitives"; import { choice, integer, string } from "@optique/core/valueparser"; import { message } from "@optique/core/message"; import { path, run } from "@optique/run"; // Reusable option groups const globalOptions = object("Global Options", { config: optional(option("-c", "--config", path({ mustExist: true }))), verbose: optional(option("-v", "--verbose")), quiet: optional(option("-q", "--quiet")) }); const buildOptions = object("Build Options", { watch: optional(option("-w", "--watch")), minify: optional(option("--minify")), sourcemap: withDefault(option("--sourcemap", choice(["inline", "external", "none"])), "external"), outDir: withDefault(option("--out-dir", path()), "./dist") }); // Complete CLI parser const cli = merge( globalOptions, object({ command: or( // Build command command("build", merge( object({ action: constant("build") }), buildOptions, object({ entry: multiple(argument(path({ mustExist: true })), { min: 1 }), target: withDefault(option("--target", choice(["es2015", "es2018", "es2022", "esnext"])), "es2018") }) )), // Dev command command("dev", merge( object({ action: constant("dev") }), buildOptions, object({ port: withDefault( option("-p", "--port", integer({ min: 1, max: 0xffff })), 3000 ), host: withDefault(option("--host", string()), "localhost"), open: optional(option("--open")) }) )), // Test command command("test", object({ action: constant("test"), watch: optional(option("-w", "--watch")), coverage: optional(option("--coverage")), pattern: optional(option("--pattern", string())), timeout: withDefault(option("--timeout", integer({ min: 1 })), 5000) })) ) }) ); type Config = InferValue; // ^? const prog: Program<"sync", Config> = { parser: cli, metadata: { name: "build-tool", version: "1.0.0", brief: message`A modern build tool for JavaScript projects`, }, }; // Run with comprehensive configuration const config: Config = run(prog, { help: "both", // Both --help and help command version: prog.metadata.version, // Enable version display aboveError: "usage", // Show usage on errors colors: true, // Colored output }); ~~~~ This complete example demonstrates: - *Process integration* with automatic `process.argv` handling - *Comprehensive help system* with both `--help` and `help` command - *Error handling* with custom exit codes and error formatting - *Type safety* throughout the entire application - *Modular design* with reusable option groups - *Real-world patterns* commonly used in build tools and CLI applications Usage examples: ~~~~ bash # Build command $ build-tool build src/index.ts --target es2022 --minify -v # Dev server $ build-tool dev --port 8080 --open --watch # Testing $ build-tool test --coverage --pattern "*.spec.ts" --timeout 10000 # Help system $ build-tool --help $ build-tool help $ build-tool help build ~~~~ Integrating external data sources --------------------------------- Real CLI applications often get values from multiple sources beyond command-line arguments. Optique's integration packages let you layer these sources with a clear priority order, all while preserving the same composition model. ### Environment variables with *@optique/env* Use `bindEnv()` to fall back to an environment variable when a CLI option is not provided: ~~~~ typescript twoslash import { bindEnv, createEnvContext } from "@optique/env"; import { object } from "@optique/core/constructs"; import { option } from "@optique/core/primitives"; import { integer, string } from "@optique/core/valueparser"; import { runAsync } from "@optique/run"; const envContext = createEnvContext({ prefix: "MYAPP_" }); const parser = object({ host: bindEnv(option("--host", string()), { context: envContext, key: "HOST", parser: string(), default: "localhost", }), port: bindEnv(option("--port", integer()), { context: envContext, key: "PORT", parser: integer(), default: 3000, }), }); // Pass the context to the runner const result = await runAsync(parser, { contexts: [envContext], }); ~~~~ Priority order: CLI argument > environment variable > default value. With the `MYAPP_` prefix, the parser reads `MYAPP_HOST` and `MYAPP_PORT`. See the [environment variable guide](./integrations/env.md) for more details. ### Config files with *@optique/config* Use `bindConfig()` to fall back to a configuration file. The schema is validated using any [Standard Schema]-compatible library (Zod, Valibot, ArkType): ~~~~ typescript twoslash import { z } from "zod"; import { bindConfig, createConfigContext } from "@optique/config"; import { object } from "@optique/core/constructs"; import { withDefault } from "@optique/core/modifiers"; import { option } from "@optique/core/primitives"; import { integer, string } from "@optique/core/valueparser"; import { runAsync } from "@optique/run"; const configSchema = z.object({ host: z.string().optional(), port: z.number().optional(), }); const configContext = createConfigContext({ schema: configSchema }); const parser = object({ config: withDefault(option("--config", string()), "config.json"), host: bindConfig(option("--host", string()), { context: configContext, key: "host", default: "localhost", }), port: bindConfig(option("--port", integer()), { context: configContext, key: "port", default: 3000, }), }); const result = await runAsync(parser, { contexts: [configContext], contextOptions: { getConfigPath: (parsed) => parsed.config, }, }); ~~~~ Priority order: CLI argument > config file value > default value. See the [config file guide](./integrations/config.md) for more details. [Standard Schema]: https://standardschema.dev/ ### Inquirer.js prompts with *@optique/inquirer* Use `prompt()` to show an interactive prompt when a value is not provided on the command line: ~~~~ typescript twoslash import { object } from "@optique/core/constructs"; import { option } from "@optique/core/primitives"; import { integer, string } from "@optique/core/valueparser"; import { prompt } from "@optique/inquirer"; import { run } from "@optique/run"; const parser = object({ name: prompt(option("--name", string()), { type: "input", message: "Project name:", }), port: prompt(option("--port", integer()), { type: "number", message: "Port number:", default: 3000, }), }); await run(parser); ~~~~ When `--name` and `--port` are provided, the prompts are skipped. Otherwise, the user sees Inquirer.js prompts. See the [Inquirer.js prompt guide](./integrations/inquirer.md) for more details. ### Composing multiple sources These integrations compose naturally. Wrapping order determines fallback priority: ~~~~ typescript // CLI > environment > config > interactive prompt prompt(bindEnv(bindConfig(option("--host", string()), { ... }), { ... }), { ... }) ~~~~ See the [cookbook](./cookbook.md#combining-with-interactive-prompts) for a complete example. Testing your CLI ---------------- A CLI can be tested at more than one depth, and choosing the depth is most of the work. Checking that `--timeout 10000` becomes the number `10000` does not require rendering help text or starting a process, and checking what `--help` prints does not require running the code that consumes the parsed value. The *@optique/testing* package gives each of those boundaries its own entry point, so the scope of a test is visible from its import: *@optique/testing/parser* for a parser alone, *@optique/testing/run* for what the runner writes and how it exits, *@optique/testing/discover* for command dispatch, and *@optique/testing/cli* for a real entry point in a child process. The narrowest layer runs the parser over a complete argument list and hands the outcome back as a value. Nothing is rendered and nothing exits, so the assertions are about the data your parser produces. Here is the `test` command from the build tool above: ~~~~ typescript twoslash import assert from "node:assert/strict"; import { object } from "@optique/core/constructs"; import { optional, withDefault } from "@optique/core/modifiers"; import { command, constant, option } from "@optique/core/primitives"; import { integer, string } from "@optique/core/valueparser"; import { parseArgsSync } from "@optique/testing/parser"; const testCommand = command("test", object({ action: constant("test"), watch: optional(option("-w", "--watch")), coverage: optional(option("--coverage")), pattern: optional(option("--pattern", string())), timeout: withDefault(option("--timeout", integer({ min: 1 })), 5000) })); const result = parseArgsSync(testCommand, [ "test", "--coverage", "--timeout", "10000", ]); if (result.success) { assert.equal(result.value.timeout, 10000); assert.ok(result.value.coverage); } else { assert.fail(`Unexpected failure: ${result.remainingArgs.join(" ")}`); } ~~~~ Use `parseArgsSync()` for synchronous parsers and `parseArgs()` when a parser may be asynchronous. Both return failures as values instead of throwing, so a test can assert on the error the same way it asserts on a success. Once help text is what you care about, move one layer out. `captureRun()` runs what `run()` runs, but writes into strings and records the exit code instead of touching process streams: ~~~~ typescript twoslash import { object } from "@optique/core/constructs"; import { optional, withDefault } from "@optique/core/modifiers"; import { command, constant, option } from "@optique/core/primitives"; import { integer, string } from "@optique/core/valueparser"; const testCommand = command("test", object({ action: constant("test"), watch: optional(option("-w", "--watch")), coverage: optional(option("--coverage")), pattern: optional(option("--pattern", string())), timeout: withDefault(option("--timeout", integer({ min: 1 })), 5000) })); // ---cut-before--- import assert from "node:assert/strict"; import { captureRun } from "@optique/testing/run"; const result = await captureRun(testCommand, { args: ["test", "--help"], programName: "build-tool", help: "option", colors: false, maxWidth: 80, }); assert.equal(result.kind, "exited"); assert.match(result.stdout, /--coverage/); assert.equal(result.stderr, ""); ~~~~ Setting `colors` and `maxWidth` explicitly matters here. Without them the runner keeps its usual defaults, which depend on the test process's terminal and environment variables, and the rendered text differs between your machine and CI. Command dispatch and full process behavior have their own layers, which the [testing guide](./concepts/testing.md) covers along with the one rule that catches people out: output written directly through `console.log()` or `print()` bypasses the in-process captures, so asserting on it needs a child process. Next steps ---------- For a complete executable, follow the [file inspection example]. It connects static `runProgram()` registration and resource hooks to tests, Bash completion, an offline npm package, and a standalone executable. You now have a solid foundation for building CLI applications with Optique. Here are some directions to explore next: - [Cookbook](./cookbook.md): Practical recipes for common patterns like mutually exclusive options, dependent flags, and integration examples - [Command discovery](./concepts/discover.md): File-based command modules and static `runProgram({ commands })` registration for CLIs that have outgrown a single parser file - [Concept guides](./concepts/primitives.md): Deep dives into primitives, value parsers, combinators, shell completion, and man page generation - Integration packages: [environment variables](./integrations/env.md), [config files](./integrations/config.md), [Inquirer.js prompts](./integrations/inquirer.md), [Zod](./integrations/zod.md)/[Valibot](./integrations/valibot.md), [Git references](./integrations/git.md), [Temporal dates](./integrations/temporal.md) - [Why Optique?](./why.md): The design philosophy behind parser combinators [file inspection example]: https://github.com/dahlia/optique/tree/main/examples/file-inspect