### Installing Optique Packages Source: https://context7_llms Provides installation commands for Optique packages using Deno, npm, pnpm, Yarn, and Bun. It covers installing both core and run packages, as well as only the core package for browser environments. ```bash deno add --jsr @optique/core @optique/run ``` ```bash npm add @optique/core @optique/run ``` ```bash pnpm add @optique/core @optique/run ``` ```bash yarn add @optique/core @optique/run ``` ```bash bun add @optique/core @optique/run ``` ```bash deno add jsr:@optique/core ``` ```bash npm add @optique/core ``` ```bash pnpm add @optique/core ``` ```bash yarn add @optique/core ``` ```bash bun add @optique/core ``` -------------------------------- ### CLI Execution Example Source: https://context7_llms Demonstrates how to run the defined CLI parser with a specific set of arguments and capture the resulting configuration object. ```typescript 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" ] }); ``` -------------------------------- ### CLI Usage Examples Source: https://context7_llms Demonstrates how to use the built CLI application for various tasks including building, development server, testing, and accessing help information. ```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 ``` -------------------------------- ### Argument Parsing with @optique/run Source: https://context7_llms Shows a concise example of parsing command-line arguments using @optique/run, which automatically handles argument processing and error display. ```typescript import { argument, object, option, optional } from "@optique/core/parser"; import { integer, string } from "@optique/core/valueparser"; import { path, run } from "@optique/run"; 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: 65535 }))), verbose: option("-v", "--verbose") }); // @optique/run handles everything automatically const config = run(parser); console.log(`Processing ${config.input} -> ${config.output}`); if (config.port) { console.log(`Server will run on port ${config.port}`); } ``` -------------------------------- ### Integer Parser Validation Examples Source: https://context7_llms Demonstrates validation and error messages for the integer parser, including format, range, and overflow checks. ```bash $ myapp --port "abc" Error: Expected a valid integer, but got abc. $ myapp --port "99999" Error: Expected a value less than or equal to 65,535, but got 99999. ``` -------------------------------- ### Optique Error Handling Example Source: https://context7_llms Shows examples of error messages generated by Optique's primitive parsers when invalid input is encountered, aiding in user-friendly error reporting. ```typescript // Parsing ["--port", "invalid"] with integer value parser // { // success: false, // error: "Expected a valid integer, but got invalid." // } // Parsing ["--missing-option"] where no parser matches // { // success: false, // error: "No matched option for --missing-option." // } ``` -------------------------------- ### UUID Format Validation Examples (Text) Source: https://context7_llms Provides examples of valid and invalid UUID formats that the `uuid()` parser validates. This includes standard formats and common errors like incorrect length or missing hyphens. ```text # Valid UUID formats 550e8400-e29b-41d4-a716-446655440000 # Version 1 123e4567-e89b-12d3-a456-426614174000 # Version 1 6ba7b810-9dad-11d1-80b4-00c04fd430c8 # Version 1 6ba7b811-9dad-11d1-80b4-00c04fd430c8 # Version 1 # Invalid formats 550e8400-e29b-41d4-a716-44665544000 # Too short 550e8400-e29b-41d4-a716-446655440000x # Extra character 550e8400e29b41d4a716446655440000 # Missing hyphens ``` -------------------------------- ### Locale Validation Examples (TypeScript) Source: https://context7_llms Provides examples of valid and invalid locale identifiers that can be used with the `locale()` parser. It highlights the expected format and common mistakes. ```typescript // Valid locales const validLocales = [ "en", // Language only "en-US", // Language and region "zh-Hans-CN", // Language, script, and region "de-DE-u-co-phonebk" // With Unicode extension ]; // Invalid locales will be rejected const invalidLocales = [ "invalid-locale", "en_US", // Underscore instead of hyphen "toolong-language-tag-name" ]; ``` -------------------------------- ### Define Subcommand Parsers Source: https://context7_llms Illustrates how to create a CLI interface with subcommands using Optique's `command()` parser. This example defines 'add' and 'remove' subcommands with their respective options. ```typescript import { command, object, option, or } from "@optique/core/parser"; import { string } from "@optique/core/valueparser"; const addCommand = command("add", object({ file: option("-f", "--file", string()), all: option("-A", "--all") })); const removeCommand = command("remove", object({ force: option("--force"), recursive: option("-r", "--recursive") })); const parser = or(addCommand, removeCommand); ``` -------------------------------- ### Pattern Validation Error Example Source: https://context7_llms Illustrates the error message provided by the string() parser when input fails pattern validation. This example shows the expected output when a version string does not match the defined pattern. ```bash $ myapp --version 1.2 Error: Expected a string matching pattern ^\d+\.\d+\.\d+$, but got 1.2. ``` -------------------------------- ### URL Object Benefits and Parsing (TypeScript) Source: https://context7_llms Shows how the `url()` parser returns native `URL` objects, providing direct access to components like hostname, port, and path. Includes an example of parsing a URL string. ```typescript import { parse, url, argument } from "@optique/core"; const apiUrl = argument(url()); // ---cut-before--- const result = parse(apiUrl, ["https://api.example.com:8080/v1/users"]); if (result.success) { const url = result.value; console.log(`Host: ${url.hostname}`); // "api.example.com" console.log(`Port: ${url.port}`); // "8080" console.log(`Path: ${url.pathname}`); // "/v1/users" console.log(`Protocol: ${url.protocol}`); // "https:" } ``` -------------------------------- ### Argument Ordering and Priority Source: https://context7_llms Shows an example of how argument ordering affects parsing and the priority of the `argument()` parser relative to options. It highlights a scenario where an option is expected but an argument is encountered. ```typescript import { object, option, argument } from "@optique/core/parser"; import { string } from "@optique/core/valueparser"; const parser = object({ input: argument(string({ metavar: "INPUT" })), output: argument(string({ metavar: "OUTPUT" })), verbose: option("-v", "--verbose") }); // Valid: myapp input.txt output.txt -v // Invalid: myapp -v input.txt (expects INPUT but got option) ``` -------------------------------- ### Tuple Usage Patterns Source: https://context7_llms Illustrates practical use cases for tuples in Optique, such as handling ordered results, integrating with APIs expecting arrays, and processing homogeneous data where position is significant. Includes an example of parsing a range of integers. ```typescript import { argument, parse, tuple } from "@optique/core/parser"; import { integer } from "@optique/core/valueparser"; // ---cut-before--- const rangeParser = tuple([ argument(integer({ metavar: "START" })), argument(integer({ metavar: "END" })) ]); // Usage: myapp 10 20 // Result: [10, 20] const config = parse(rangeParser, ["10", "20"]); if (config.success) { const [start, end] = config.value; console.log(`Processing range ${start} to ${end}`); } ``` -------------------------------- ### Nested Command Parsing with Optique Source: https://context7_llms Demonstrates how to create nested command structures in Optique by using `command()` parsers as inner parsers. This allows for hierarchical command definitions, such as 'config get' or 'config set'. ```typescript import { argument, command, object, option, or } from "@optique/core/parser"; import { string } from "@optique/core/valueparser"; const configCommands = or( command("get", object({ key: argument(string({ metavar: "KEY" })) })), command("set", object({ key: argument(string({ metavar: "KEY" })), value: argument(string({ metavar: "VALUE" })) })) ); const parser = or( command("config", configCommands), command("init", object({ template: option("-t", "--template", string()) })) ); // Usage: myapp config get database.url // Usage: myapp config set database.url "postgres://localhost/mydb" // Usage: myapp init --template react ``` -------------------------------- ### Choice Parser Error Message Example Source: https://context7_llms Shows the error message generated by the choice parser when an invalid option is provided, listing all valid choices. ```bash $ myapp --format "txt" Error: Expected one of json, yaml, xml, csv, but got txt. ``` -------------------------------- ### Date Parser with Options Source: https://context7_llms An example of a configurable date parser in TypeScript. It allows specifying the date format (ISO, US, EU) and whether future dates are permitted. ```typescript import { message } from "@optique/core/message"; import type { ValueParser, ValueParserResult } from "@optique/core/valueparser"; interface DateParserOptions { metavar?: string; format?: 'iso' | 'us' | 'eu'; allowFuture?: boolean; } function date(options: DateParserOptions = {}): ValueParser { const { metavar = "DATE", format = 'iso', allowFuture = true } = options; return { metavar, parse(input: string): ValueParserResult { let date: Date; // Parse according to format switch (format) { case 'iso': date = new Date(input); break; case 'us': // MM/DD/YYYY format const usMatch = input.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/); if (!usMatch) { return { success: false, error: message`Expected US date format MM/DD/YYYY, but got ${input}.` }; } date = new Date(parseInt(usMatch[3]), parseInt(usMatch[1]) - 1, parseInt(usMatch[2])); break; case 'eu': // DD/MM/YYYY format const euMatch = input.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/); if (!euMatch) { return { success: false, error: message`Expected EU date format DD/MM/YYYY, but got ${input}.` }; } date = new Date(parseInt(euMatch[3]), parseInt(euMatch[2]) - 1, parseInt(euMatch[1])); break; } // Validate parsed date if (isNaN(date.getTime())) { return { success: false, error: message`Invalid date: ${input}.` }; } // Check future constraint if (!allowFuture && date > new Date()) { return { success: false, error: message`Future dates not allowed, but got ${input}.` }; } return { success: true, value: date }; }, format(value: Date): string { switch (format) { case 'iso': return value.toISOString().split('T')[0]; case 'us': return `${value.getMonth() + 1}/${value.getDate()}/${value.getFullYear()}`; case 'eu': return `${value.getDate()}/${value.getMonth() + 1}/${value.getFullYear()}`; } } }; } // Usage const birthDate = date({ format: 'us', allowFuture: false, metavar: "BIRTH_DATE" }); ``` -------------------------------- ### Combining Positional Arguments and Options Source: https://context7_llms Shows how to combine positional arguments and options into a single structured parser using Optique's `object` combinator. This example parses a required file argument, an optional output file option, and a verbose flag, with automatic TypeScript type inference for the resulting configuration object. ```typescript import { type InferValue, argument, object, option } from "@optique/core/parser"; import { string } from "@optique/core/valueparser"; import { run } from "@optique/run"; import { path } from "@optique/run/valueparser"; 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" ] }); console.log(`Converting ${config.file} to ${config.output}`); if (config.verbose) { console.log("Verbose mode enabled"); } ``` -------------------------------- ### URL Validation Error Examples (Bash) Source: https://context7_llms Illustrates common validation errors when parsing URLs, such as providing a non-URL string or a URL with a disallowed protocol. Shows the expected error messages. ```bash $ myapp --url "not-a-url" Error: Invalid URL: not-a-url. $ myapp --url "ftp://example.com" # when only HTTPS allowed Error: URL protocol ftp: is not allowed. Allowed protocols: https:. ``` -------------------------------- ### Basic IPv4 Address Parser Source: https://context7_llms A TypeScript example demonstrating a custom value parser for IPv4 addresses. It validates the input string format and converts it into a structured IPv4Address object. ```typescript import { message } from "@optique/core/message"; import type { ValueParser, ValueParserResult } from "@optique/core/valueparser"; interface IPv4Address { octets: [number, number, number, number]; toString(): string; } function ipv4(): ValueParser { return { metavar: "IP_ADDRESS", parse(input: string): ValueParserResult { const parts = input.split('.'); if (parts.length !== 4) { return { success: false, error: message`Expected IPv4 address in format a.b.c.d, but got ${input}.` }; } const octets: number[] = []; for (const part of parts) { const num = parseInt(part, 10); if (isNaN(num) || num < 0 || num > 255) { return { success: false, error: message`Invalid IPv4 octet: ${part}. Must be 0-255.` }; } octets.push(num); } return { success: true, value: { octets: octets as [number, number, number, number], toString() { return octets.join('.'); } } }; }, format(value: IPv4Address): string { return value.toString(); } }; } ``` -------------------------------- ### Combining Primitive Parsers with object() in Optique Source: https://context7_llms Illustrates how to combine multiple primitive parsers using the `object()` combinator to define complex CLI structures. This example defines arguments and options for input, output, port, and verbosity, with automatic type inference. ```typescript import { type InferValue, object, option, argument } from "@optique/core/parser"; import { string, integer } from "@optique/core/valueparser"; const parser = object({ input: argument(string({ metavar: "INPUT" })), output: option("-o", "--output", string({ metavar: "OUTPUT" })), port: option("-p", "--port", integer({ min: 1, max: 65535 })), verbose: option("-v", "--verbose") }); type Result = InferValue; // ^? // TypeScript automatically infers the result type! ``` -------------------------------- ### Reusable Option Groups with Optique `merge()` Source: https://context7_llms Demonstrates defining and combining reusable option groups for different CLI modes (development and production) using Optique's `merge()` and `or()` combinators. This example showcases type safety and modularity in CLI application development. ```typescript import { constant, merge, object, option, optional, or } from "@optique/core/parser"; import { choice, integer, string } from "@optique/core/valueparser"; import { path, run } from "@optique/run"; // Define reusable option groups const networkOptions = object("Network", { host: option("--host", string({ metavar: "HOST" })), port: option("--port", integer({ min: 1, max: 65535 })) }); 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" ] }); ``` -------------------------------- ### Nested Subcommands for Complex CLIs Source: https://context7_llms Illustrates creating nested subcommands in Optique, exemplified by an 'app config' command with 'get', 'set', and 'list' subcommands. This structure allows for complex CLI hierarchies while maintaining type safety and clarity. ```typescript import { argument, command, constant, object, option, or } from "@optique/core/parser"; import { choice, string } from "@optique/core/valueparser"; import { run } from "@optique/run"; // 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"] }); ``` -------------------------------- ### map() Transformation Patterns Source: https://context7_llms Provides examples of various transformation patterns using the `map()` modifier, including type conversions (e.g., integer to BigInt), data structure transformations (e.g., string pairs to an object), validation, and computing values based on parsed input. ```typescript import { map, multiple, option } from "@optique/core/parser"; import { integer, string } from "@optique/core/valueparser"; // Type conversions const convertedValue = map(option("--count", integer()), count => BigInt(count)); // Data structure transformations const keyValuePairs = map( multiple(option("-D", string())), pairs => Object.fromEntries(pairs.map(pair => pair.split('='))) ); // Validation transformations const validatedEmail = map( option("--email", string()), email => { if (!email.includes('@')) throw new Error(`Invalid email: ${email}`); return email.toLowerCase(); } ); // Computed values const expiryTime = map( option("--ttl", integer()), ttlSeconds => new Date(Date.now() + ttlSeconds * 1000) ); ``` -------------------------------- ### Tuple Parser Priority Example Source: https://context7_llms The tuple() parser processes its component parsers in priority order, not array order. Parsers with higher priority are tried first regardless of their position in the tuple, ensuring correct parsing logic. This involves importing `argument`, `command`, `option`, and `tuple`. ```typescript import { argument, command, option, tuple } from "@optique/core/parser"; import { string } from "@optique/core/valueparser"; // --- // Even though argument is last in the array, it might be parsed first // depending on the current parsing context and available input const mixedTuple = tuple([ option("-v", "--verbose"), // Priority 10 command("start", argument(string())), // Priority 15 - tried first argument(string()) // Priority 5 ] as const); ``` -------------------------------- ### Configure Help System Options Source: https://context7_llms Demonstrates how to configure the built-in help functionality in Optique applications. The `run` function accepts a `help` option to control the display of `--help` and help subcommands. ```typescript // @noErrors: 1117 import { run } from "@optique/run"; import { object, option } from "@optique/core/parser"; import { string } from "@optique/core/valueparser"; const parser = object({ name: option("-n", "--name", string()) }); const result = run(parser, { help: "option", // Adds --help option only help: "command", // Adds help subcommand only help: "both", // Adds both --help and help command help: "none", // No help (default) }); ``` -------------------------------- ### Basic CLI: Single Option Parser Source: https://context7_llms Demonstrates creating a simple CLI that accepts a '--name' option using Optique's option() and string() parsers. Shows how Optique infers types and handles results. ```typescript import { option } from "@optique/core/parser"; import { string } from "@optique/core/valueparser"; import { run } from "@optique/run"; // 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"] }); console.log(`Hello, ${result}!`); // Output: Hello, Alice! ``` -------------------------------- ### Flexible Configuration Parsing with or() Source: https://context7_llms Demonstrates using the `or()` parser to handle different configuration strategies: individual options, a config file, or a connection string URL. It showcases how to define parsers for each strategy and combine them. ```typescript import { constant, object, option, or } from "@optique/core/parser"; import { integer, string, url } from "@optique/core/valueparser"; const flexibleConfig = or( // Configuration via individual options object({ source: constant("options"), host: option("--host", string()), port: option("--port", integer()), ssl: option("--ssl") }), // Configuration via config file object({ source: constant("file"), configFile: option("-c", "--config", string()) }), // Configuration via URL object({ source: constant("url"), connectionString: option("--url", url()) }) ); ``` -------------------------------- ### Functional Parser Transformations with Defaults Source: https://context7_llms Demonstrates transforming a base server options parser by applying default values for port and host using `withDefault`. It shows how to create different configurations (e.g., for production) while maintaining type safety. ```typescript import { object, option, withDefault } from "@optique/core/parser"; import { string, integer } from "@optique/core/valueparser"; // Start with a base parser const serverOptions = object({ port: option("--port", integer()), host: option("--host", string()) }); // Transform it for different contexts const withDefaults = object({ port: withDefault(option("--port", integer()), 3000), host: withDefault(option("--host", string()), "localhost") }); const forProduction = object({ port: withDefault(option("--port", integer()), 80), host: withDefault(option("--host", string()), "0.0.0.0") }); const config = forProduction; ``` -------------------------------- ### Customizing @optique/core/facade RunOptions Source: https://context7_llms Illustrates advanced customization of `run()` options within `@optique/core/facade`. This includes forcing colored output, setting text wrapping width, controlling help display modes, and defining custom handlers for errors and standard output. ```typescript import { run } from "@optique/core/facade"; import { object, option } from "@optique/core/parser"; import { string } from "@optique/core/valueparser"; const parser = object({ name: option("-n", "--name", string()) }); const result = run(parser, "myapp", ["--name", "test"], { colors: true, // Force colored output maxWidth: 80, // Wrap text at 80 columns help: "option", // Only --help option, no help command aboveError: "help", // Show full help before error messages stderr: (text) => { // Custom error output handler console.error(`ERROR: ${text}`); }, stdout: console.log, // Custom help output handler }); ``` -------------------------------- ### @optique/run Configuration Options Source: https://context7_llms Illustrates various configuration options available for @optique/run to customize its behavior, including program name, help display, color output, and exit codes. ```typescript import { object, option } from "@optique/core/parser"; import { string } from "@optique/core/valueparser"; import { run } from "@optique/run"; const parser = object({ name: option("-n", "--name", string()), debug: option("--debug") }); const config = run(parser, { programName: "my-tool", // Override detected program name (default: process.argv[1]) 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 (terminal width by default) errorExitCode: 2 // Custom exit code for errors (default: 1) }); // The help system automatically generates comprehensive help text: // $ my-tool --help // $ my-tool help ``` -------------------------------- ### Server Configuration with Defaults Source: https://context7_llms Illustrates a common usage pattern for the withDefault() modifier in defining server configurations. It shows how to handle required and optional parameters, simplifying code by eliminating the need for explicit undefined checks. ```typescript import { object, option, parse, withDefault } from "@optique/core/parser"; import { choice, integer, string } from "@optique/core/valueparser"; class Server { constructor(config: { name: string; host: string; port: number; logLevel: "debug" | "info" | "warn" | "error"; maxConnections: number; }) { } } const serverConfig = object({ // Required parameters name: option("-n", "--name", string()), // Optional with defaults - no undefined handling needed host: withDefault(option("-h", "--host", string()), "0.0.0.0"), port: withDefault(option("-p", "--port", integer({ min: 1, max: 65535 })), 3000), logLevel: withDefault( option("--log-level", choice(["debug", "info", "warn", "error"])), "info", ), maxConnections: withDefault(option("--max-conn", integer({ min: 1 })), 100) }); // Clean usage without undefined checks const config = parse(serverConfig, ["--name", "my-server", "--port", "8080"]); if (config.success) { const server = new Server({ name: config.value.name, host: config.value.host, // Always "0.0.0.0" if not specified port: config.value.port, // 8080 from input logLevel: config.value.logLevel, // Always "info" if not specified maxConnections: config.value.maxConnections // Always 100 if not specified }); } ``` -------------------------------- ### Consistent Metavar Naming in Value Parsers Source: https://context7_llms Provides examples of good and poor metavar naming conventions for custom Optique value parsers to ensure clarity and descriptiveness. ```typescript // Good metavar examples metavar: "EMAIL" metavar: "FILE" metavar: "PORT" metavar: "UUID" // Poor metavar examples metavar: "input" metavar: "value" metavar: "thing" ``` -------------------------------- ### Git-style CLI with Subcommands Source: https://context7_llms Demonstrates building a Git-like CLI using Optique's `command()` combinator. It defines 'add', 'commit', and 'push' subcommands, each with its own options and arguments. The parser creates a discriminated union for type safety. ```typescript import { type InferValue, argument, command, constant, multiple, object, option, or, } from "@optique/core/parser"; import { string } from "@optique/core/valueparser"; import { path, run } from "@optique/run"; const parser = or( command("add", object({ type: constant("add"), files: multiple(argument(path())), all: option("-A", "--all"), force: option("-f", "--force") })), command("commit", object({ type: constant("commit"), message: option("-m", "--message", string()), amend: option("--amend"), all: option("-a", "--all") })), command("push", object({ 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"] }); ``` -------------------------------- ### Low-level Parsing with `parse()` - TypeScript Source: https://context7_llms Illustrates the basic parsing operation using the `parse()` function from `@optique/core/parser`. It shows how to define a parser for options like name and port, execute it with arguments, and handle the success or failure result. ```typescript import { object, option, parse } from "@optique/core/parser"; import { string, integer } from "@optique/core/valueparser"; import { formatMessage } from "@optique/core/message"; const parser = object({ name: option("-n", "--name", string()), port: option("-p", "--port", integer({ min: 1000 })), }); const result = parse(parser, ["--name", "server", "--port", "8080"]); // ^? if (result.success) { console.log(`Starting ${result.value.name} on port ${result.value.port}`); } else { console.error(`Parse error: ${formatMessage(result.error)}`); process.exit(1); } ``` -------------------------------- ### Deployment Tool CLI Parser Source: https://context7_llms Defines the structure and options for a multi-command CLI deployment tool. It utilizes reusable option groups and the `merge` combinator for flexible command definition. Includes commands for deploy, status, rollback, and logs with various options and validation. ```typescript import { type InferValue, argument, command, constant, merge, multiple, object, option, optional, or, withDefault, } from "@optique/core/parser"; import { choice, integer, string, url } from "@optique/core/valueparser"; import { path, run } from "@optique/run"; // 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; ``` -------------------------------- ### String Parser Pattern Validation Source: https://context7_llms Shows how to use the optional 'pattern' parameter with the string() parser for regular expression-based validation. It includes examples for email-like and semantic version patterns. ```typescript import { string } from "@optique/core/valueparser"; // --- // Email-like pattern const email = string({ pattern: /^[^@]+@[^@]+\.[^@]+$/, metavar: "EMAIL" }); // Semantic version pattern const version = string({ pattern: /^\d+\.\d+\.\d+$/, metavar: "VERSION" }); ``` -------------------------------- ### Single Primitive Parser Usage in Optique Source: https://context7_llms Demonstrates the basic usage of a single primitive parser, like `option()`, for simple CLI applications. It shows how to parse arguments and handle the success or failure of the parsing operation. ```typescript import { option, parse } from "@optique/core/parser"; import { string } from "@optique/core/valueparser"; const nameParser = option("--name", string()); const result = parse(nameParser, ["--name", "Alice"]); if (result.success) { console.log(`Hello, ${result.value}!`); } else { console.error(result.error); } ``` -------------------------------- ### Define Verbose Option with Description Source: https://context7_llms Demonstrates how to define a command-line option for verbose output using Optique's `option()` parser. The description is provided using a structured message system for enhanced help text. ```typescript import { message } from "@optique/core/message"; import { option } from "@optique/core/parser"; // ---cut-before--- const parser = option("-v", "--verbose", { description: message`Enable verbose output for debugging` }); ``` -------------------------------- ### Clear Error Messages in Value Parsers Source: https://context7_llms Illustrates how to provide specific and helpful error messages within custom Optique value parsers to guide users during input validation. ```typescript import { message } from "@optique/core/message"; function _(input: string) { // ---cut-before--- // Good: Specific and helpful return { success: false, error: message`Expected IPv4 address in format a.b.c.d, but got ${input}.` }; // Bad: Vague and unhelpful return { success: false, error: message`Invalid input.` }; // ---cut-after--- } ``` -------------------------------- ### Mid-level CLI Execution with @optique/core/facade Source: https://context7_llms Demonstrates using `run()` from `@optique/core/facade` for controlled CLI execution. It allows customization of help generation, error messages, and process behavior via callbacks, integrating with Node.js process arguments. ```typescript import { run } from "@optique/core/facade"; import { object, option } from "@optique/core/parser"; import { string, integer } from "@optique/core/valueparser"; const parser = object({ name: option("-n", "--name", string()), port: option("-p", "--port", integer({ min: 1000 })), }); // Manual process integration (Node.js example) const config = run( parser, "myserver", // program name process.argv.slice(2), // arguments { help: "both", // Enable --help and help command colors: process.stdout.isTTY, // Auto-detect color support onHelp: process.exit, // Exit after showing help onError: process.exit, // Exit with error code } ); config // Its result type is: // ^? console.log(`Starting ${config.name} on port ${config.port}`); ``` -------------------------------- ### Locale Object Benefits and Parsing (TypeScript) Source: https://context7_llms Illustrates how the `locale()` parser returns `Intl.Locale` objects, offering rich locale information and integration with internationalization APIs. Includes a parsing example. ```typescript import { parse, locale, argument } from "@optique/core"; const userLocale = argument(locale()); // ---cut-before--- const result = parse(userLocale, ["zh-Hans-CN"]); if (result.success) { const locale = result.value; console.log(`Language: ${locale.language}`); // "zh" console.log(`Script: ${locale.script}`); // "Hans" console.log(`Region: ${locale.region}`); // "CN" console.log(`Base name: ${locale.baseName}`); // "zh-Hans-CN" } ```