Built and signed on GitHub ActionsBuilt and signed on GitHub Actions
Type-safe combinatorial command-line interface parser
Classes
Error class thrown when duplicate option names are detected during parser construction. This is a programmer error, not a user error.
An error class used to indicate that the command line arguments could not be parsed successfully.
Error type for structured error messages in withDefault default value callbacks. Unlike regular errors that only support string messages, this error type accepts a Message object that supports rich formatting, colors, and structured content.
- errorMessage: Message
The structured message associated with this error.
Functions
Creates a parser that expects a single argument value. This parser is typically used for positional arguments that are not options or flags.
Validates that an option value, if present, is a boolean. Throws a TypeError if the value is defined but not a boolean.
Validates that an option value, if present, is one of the allowed values. Throws a TypeError if the value is defined but not in the allowed list.
Creates a ValueParser that accepts one of multiple string values, so-called enumerated values.
Creates a value parser for CIDR notation (IP address with prefix length).
Creates a deep clone of a DocEntry. The term is cloned via
cloneUsageTerm, and description, default, and choices
messages are cloned via cloneMessage.
Creates a deep clone of a Usage array and all of its terms.
Creates a deep clone of a single UsageTerm. Recursive term
variants (optional, multiple, exclusive) are cloned recursively.
For command terms, a function-valued usageLine is preserved by
reference (functions are stateless callbacks), while an array-valued
usageLine is deep-cloned.
Creates a parser that matches a specific subcommand name and then applies an inner parser to the remaining arguments. This is useful for building CLI tools with subcommands like git, npm, etc.
Creates a MessageTerm for a command-line example.
Concatenates tuple parsers into one parser with a flattened tuple value.
Creates a conditional parser without a default branch. The discriminator option is required; parsing fails if not provided.
Creates a parser that always succeeds without consuming any input and produces a constant value of the type T.
Creates a ParserContext from a ParseFrame and an
ExecutionContext. The returned object provides both structured
access (frame, exec) and flat access (buffer, state, etc.)
for backward compatibility.
Removes duplicate DocEntry values that share the same surface syntax (same term type and identifying names). Doc-hidden entries are filtered out first so they cannot influence the ordering of visible entries. Among the remaining visible entries, the first occurrence is kept and later duplicates are discarded.
Removes duplicate entries from a list of DocFragment values. Entry-type fragments are deduplicated by their surface syntax key. Section-type fragments have their entries deduplicated internally.
Creates a dependency source from a ValueParser.
Creates a derived value parser from multiple dependency sources.
Creates a derived value parser from multiple dependency sources with an asynchronous factory.
Creates a derived value parser from multiple dependency sources with a synchronous factory.
Creates a value parser for domain names.
Creates a value parser for email addresses according to RFC 5322 (simplified).
Asserts that a string is non-empty.
Throws a TypeError if the string is empty.
Creates a MessageTerm for an environment variable.
Extracts all argument metavars from a Usage array.
Extracts all command names from a Usage array.
Extracts all literal values from a usage description.
Extracts all option names from a usage description.
Creates a parser that always fails without consuming any input.
| readonly [OptionName, ...readonly OptionName[]]
Creates a parser for command-line flags that must be explicitly provided. Unlike option, this parser fails if the flag is not present, making it suitable for required boolean flags that don't have a meaningful default.
Creates a ValueParser for floating-point numbers.
Formats a documentation page into a human-readable string.
Formats a Message into a human-readable string for the terminal.
Formats a usage description into a human-readable string representation suitable for command-line help text.
Formats a single UsageTerm into a string representation suitable for command-line help text.
Extracts annotations from parser state.
Generates a documentation page for a parser based on its current state after attempting to parse the provided arguments. This function is useful for creating help documentation that reflects the current parsing context.
Generates a documentation page for any parser, returning a Promise.
Generates a documentation page for a synchronous parser.
Creates a value parser for DNS hostnames.
Creates a ValueParser for integers that returns JavaScript numbers.
Creates a value parser that accepts both IPv4 and IPv6 addresses.
Creates a value parser for IPv4 addresses.
Creates a value parser for IPv6 addresses.
Checks if a value parser is a DependencySource.
Checks if a value parser is a DerivedValueParser.
Checks if a string is non-empty. Can be used as a type guard for type narrowing.
A predicate function that checks if an object is a ValueParser.
Creates a MessageTerm for an explicit single-line break.
Creates a MessageTerm for a URL (alias for url).
Creates a ValueParser for locale values.
Creates a parser that selects the successful branch that consumed the most input tokens.
Creates a value parser for MAC (Media Access Control) addresses.
Creates a parser that transforms the result value of another parser using a mapping function. This enables value transformation while preserving the original parser's parsing logic and state management.
Merges multiple object-like parsers into one parser, with options.
Creates a structured message with template strings and values.
Creates a MessageTerm for a metavariable.
Creates a parser that allows multiple occurrences of a given parser. This parser can be used to parse multiple values of the same type, such as multiple command-line arguments or options.
Creates a parser that requires the wrapped parser to consume at least one input token to succeed. If the wrapped parser succeeds without consuming any tokens, this parser fails with an error.
Normalizes a usage description by flattening nested exclusive terms, sorting terms for better readability, and ensuring consistent structure throughout the usage tree.
Creates a parser that combines multiple parsers into a single object parser. Each parser in the object is applied to parse different parts of the input, and the results are combined into an object with the same structure.
| readonly [OptionName, ...readonly OptionName[], ValueParser<M, T>]
| readonly [OptionName, ...readonly OptionName[], OptionOptions]
| readonly [OptionName, ...readonly OptionName[]]
Creates a parser for various styles of command-line options that take an
argument value, such as --option=value, -option=value, -o value,
or /option:value.
Creates a parser that makes another parser optional, allowing it to succeed
without consuming input if the wrapped parser fails to match.
If the wrapped parser succeeds, this returns its value.
If the wrapped parser fails, this returns undefined without consuming input.
Creates a MessageTerm for an option name.
Creates a MessageTerm for a list of option names.
Creates a parser that combines two mutually exclusive parsers into one. The resulting parser will try each of the provided parsers in order, and return the result of the first successful parser.
Parses an array of command-line arguments using the provided combined parser. This function processes the input arguments, applying the parser to each argument until all arguments are consumed or an error occurs.
Parses an array of command-line arguments using the provided combined parser. This function processes the input arguments, applying the parser to each argument until all arguments are consumed or an error occurs.
Parses an array of command-line arguments using the provided combined parser. This function processes the input arguments, applying the parser to each argument until all arguments are consumed or an error occurs.
Creates a parser that collects unrecognized options and passes them through. This is useful for building wrapper CLI tools that need to forward unknown options to an underlying tool.
Creates a ValueParser for TCP/UDP port numbers that returns JavaScript numbers.
Creates a value parser for port ranges (e.g., "8000-8080").
Runs a parser against command-line arguments with built-in help and error handling.
Runs any command-line parser asynchronously with the given options.
Runs a synchronous command-line parser with the given options.
& ContextOptionsParam<TContexts, InferValue<TParser>>
Runs a parser with multiple source contexts.
& ContextOptionsParam<TContexts, InferValue<TParser>>
Runs any parser asynchronously with multiple source contexts.
& ContextOptionsParam<TContexts, InferValue<TParser>>
Runs a synchronous parser with multiple source contexts.
Creates a value parser for socket addresses in "host:port" format.
Creates a ValueParser for strings.
Generates command-line suggestions based on current parsing state. This function processes the input arguments up to the last argument, then calls the parser's suggest method with the remaining prefix.
Generates command-line suggestions based on current parsing state. This function processes the input arguments up to the last argument, then calls the parser's suggest method with the remaining prefix.
Generates command-line suggestions based on current parsing state. This function processes the input arguments up to the last argument, then calls the parser's suggest method with the remaining prefix.
Creates a MessageTerm for plain text. Usually used for dynamically generated messages.
Creates a parser that combines multiple parsers into a sequential tuple parser. The parsers are applied in the order they appear in the array, and all must succeed for the tuple parser to succeed.
Creates a ValueParser for URL values.
Creates a ValueParser for UUID values.
Creates a MessageTerm for a single value. However, you usually don't need to use this function directly, as message string template will automatically create a MessageTerm for a value when you use a string in a template literal.
Creates a MessageTerm for a list of consecutive values.
Creates a parser that makes another parser use a default value when it fails
to match or consume input. This is similar to optional, but instead
of returning undefined when the wrapped parser doesn't match, it returns
a specified default value.
Interfaces
Minimal structural supertype for dependency-source tuple constraints.
- dependencyId: symbolNo documentation available
- dependencySourceMarker: trueNo documentation available
- mode: MNo documentation available
Options for customizing error messages in the argument parser.
- endOfInput: Message
Custom error message when input is empty but argument is expected.
- invalidValue: Message | ((error: Message) => Message)
Custom error message when value parsing fails. Can be a static message or a function that receives the error message.
- multiple: Message | ((metavar: string) => Message)
Custom error message when argument is used multiple times. Can be a static message or a function that receives the metavar.
Options for the argument parser.
- description: Message
The description of the argument, which can be used for help messages.
- errors: ArgumentErrorOptions
Error message customization options.
- hidden: HiddenVisibility
Controls argument visibility:
Base options for creating a choice parser.
- metavar: NonEmptyString
The metavariable name for this parser. This is used in help messages to indicate what kind of value this parser expects. Usually a single word in uppercase, like
TYPEorMODE.
Options for creating a choice parser with number values.
Note: caseInsensitive is not available for number choices.
- errors: { invalidChoice?:Message; }
| (() => Message)input: string,choices: readonly number[]Custom error messages for choice parsing failures.
Options for creating a choice parser with string values.
- caseInsensitive: boolean
If
true, the parser will perform case-insensitive matching against the enumerated values. This means that input like "value", "Value", or "VALUE" will all match the same enumerated value. Iffalse, the matching will be case-sensitive. - errors: { invalidChoice?:Message; }
| (() => Message)input: string,choices: readonly string[]Custom error messages for choice parsing failures.
Options for configuring the CIDR notation value parser.
- errors: { invalidCidr?: Message | ((input: string) => Message); invalidPrefix?: Message | (() => Message); prefixBelowMinimum?: Message | ((prefix: number,version: 4 | 6) => Message); prefixAboveMaximum?: Message | ((prefix: number,min: number) => Message); privateNotAllowed?: Message | ((ip: string) => Message); loopbackNotAllowed?: Message | ((ip: string) => Message); linkLocalNotAllowed?: Message | ((ip: string) => Message); multicastNotAllowed?: Message | ((ip: string) => Message); broadcastNotAllowed?: Message | ((ip: string) => Message); zeroNotAllowed?: Message | ((ip: string) => Message); uniqueLocalNotAllowed?: Message | ((ip: string) => Message); }prefix: number,max: number
Custom error messages for CIDR parsing failures.
- ipv4: Omit<Ipv4Options, "metavar" | "errors">
Options for IPv4 validation (when version is 4 or "both").
- ipv6: Omit<Ipv6Options, "metavar" | "errors">
Options for IPv6 validation (when version is 6 or "both").
- maxPrefix: number
Maximum allowed prefix length. For IPv4: 0-32, for IPv6: 0-128.
- metavar: NonEmptyString
The metavariable name for this parser.
- minPrefix: number
Minimum allowed prefix length. For IPv4: 0-32, for IPv6: 0-128.
- version: 4 | 6 | "both"
IP version to accept.
Value representing a CIDR notation (IP address with prefix length).
Options for customizing error messages in the command parser.
- invalidState: Message
Error message for invalid command state.
- notFound: Message
Error message when command was not matched during completion.
- notMatched:Message
| (() => Message)expected: string,actual: string | null,suggestions?: readonly string[]Error message when command is expected but not found. Since version 0.7.0, the function signature now includes suggestions:
Options for the command parser.
- brief: Message
A brief description of the command, shown in command lists. If provided along with description, this will be used in command listings (e.g.,
myapp help), while description will be used for detailed help (e.g.,myapp help subcommandormyapp subcommand --help). - description: Message
A description of the command, used for documentation.
- errors: CommandErrorOptions
Error messages customization.
- footer: Message
A footer message that appears at the bottom of the command's help text. Useful for showing examples, notes, or additional information.
- hidden: HiddenVisibility
Controls command visibility:
- usageLine: Usage | ((defaultUsageLine: Usage) => Usage)
Usage line override for this command's own help page.
Sub-configuration for a meta command's command form.
- group: string
Group label for the command in help output. When specified, the command appears under a titled section with this name instead of alongside user-defined commands.
- hidden: HiddenVisibility
Granular visibility control.
- names: readonly [string, ...string[]]
Command names. The first element is the display name shown in help output; additional elements are hidden aliases that are accepted but not shown.
Options for customizing error messages in the conditional combinator.
- branchError: () => MessagediscriminatorValue: string | undefined,error: Message
Custom error message when branch parser fails. Receives the discriminator value for context.
- branchMismatch: () => MessagediscriminatorValue: string,speculativeKey: string
Custom error message when speculative branch parsing committed to one branch but the resolved discriminator value names a different branch. This is the contradictory-input case: tokens specific to one branch were consumed during the parse phase, but the discriminator (e.g., from
prompt()or a deferred config source) ultimately resolved to a different key. - noMatch: Message | ((context: NoMatchContext) => Message)
Custom error message for no matching input.
Options for customizing the conditional combinator behavior.
- errors: ConditionalErrorOptions
Custom error messages.
Represents a dependency source that can be used to create derived parsers.
- dependencyId: symbol
Unique identifier for this dependency source.
- dependencySourceMarker: true
Marker to identify this as a dependency source.
- derive<U, FM extends Mode = "sync">(options: DeriveOptions<T, U, FM>): DerivedValueParser<CombineMode<M, FM>, U, T>
Creates a derived value parser whose behavior depends on this dependency source's value.
- deriveAsync<U>(options: DeriveAsyncOptions<T, U>): DerivedValueParser<"async", U, T>
Creates a derived value parser with an asynchronous factory.
- deriveSync<U>(options: DeriveSyncOptions<T, U>): DerivedValueParser<M, U, T>
Creates a derived value parser with a synchronous factory.
Options for creating a derived value parser with an asynchronous factory.
- defaultValue: () => S
Default value to use when the dependency source is not provided.
- factory: (sourceValue: S) => ValueParser<"async", T>
Factory function that creates an asynchronous ValueParser.
- metavar: NonEmptyString
The metavariable name for the derived parser.
A value parser that depends on another parser's value.
- defaultValues: () => readonly unknown[]
The default values function for this parser's dependencies. Used during partial dependency resolution to fill in missing values.
- dependencyId: symbol
The unique identifier of the dependency source this parser depends on. For parsers created with deriveFrom that have multiple dependencies, this is set to the first dependency's ID for backwards compatibility.
- dependencyIds: readonly symbol[]
The unique identifiers of all dependency sources this parser depends on. Present only for parsers created with deriveFrom that have multiple dependencies. If present, this takes precedence over dependencyId during dependency resolution.
- derivedValueParserMarker: true
Marker to identify this as a derived value parser.
- parseWithDependency: () => ValueParserResult<T> | Promise<ValueParserResult<T>>input: string,dependencyValue: S
Parses the input using the actual dependency value instead of the default. This method is used during dependency resolution in
complete(). - singleDefaultValue: () => S
The single default value thunk for single-source derived parsers. Read by the dependency-metadata bridge; not consumed by
createDeferredParseState(). - suggestWithDependency: () => Iterable<Suggestion> | AsyncIterable<Suggestion>prefix: string,dependencyValue: S
Generates suggestions using the provided dependency value instead of the default. This method is used during shell completion when dependency sources have been parsed.
Options for creating a derived value parser from multiple dependencies with an asynchronous factory.
- defaultValues: () => DependencyValues<Deps>
Default values to use when the dependency sources are not provided.
- dependencies: Deps
The dependency sources that this derived parser depends on.
- factory: (...values: DependencyValues<Deps>) => ValueParser<"async", T>
Factory function that creates an asynchronous ValueParser.
- metavar: NonEmptyString
The metavariable name for the derived parser.
Options for creating a derived value parser from multiple dependencies.
- defaultValues: () => DependencyValues<Deps>
Default values to use when the dependency sources are not provided. Must return a tuple with the same length and types as the dependencies.
- dependencies: Deps
The dependency sources that this derived parser depends on.
- factory: (...values: DependencyValues<Deps>) => ValueParser<NoInfer<FM>, T>
Factory function that creates a ValueParser based on the dependency sources' values.
- metavar: NonEmptyString
The metavariable name for the derived parser. Used in help messages to indicate what kind of value this parser expects.
- mode: FM
The execution mode of the factory's returned parser. This tells the runtime whether the factory returns a sync or async parser, avoiding the need to call the factory during parser construction.
Options for creating a derived value parser from multiple dependencies with a synchronous factory.
- defaultValues: () => DependencyValues<Deps>
Default values to use when the dependency sources are not provided.
- dependencies: Deps
The dependency sources that this derived parser depends on.
- factory: (...values: DependencyValues<Deps>) => ValueParser<"sync", T>
Factory function that creates a synchronous ValueParser.
- metavar: NonEmptyString
The metavariable name for the derived parser.
Options for creating a derived value parser.
- defaultValue: () => S
Default value to use when the dependency source is not provided. This allows the derived parser to work even when the dependency is optional.
- factory: (sourceValue: S) => ValueParser<NoInfer<FM>, T>
Factory function that creates a ValueParser based on the dependency source's value.
- metavar: NonEmptyString
The metavariable name for the derived parser. Used in help messages to indicate what kind of value this parser expects.
- mode: FM
The execution mode of the factory's returned parser. This tells the runtime whether the factory returns a sync or async parser, avoiding the need to call the factory during parser construction.
Options for creating a derived value parser with a synchronous factory.
- defaultValue: () => S
Default value to use when the dependency source is not provided.
- factory: (sourceValue: S) => ValueParser<"sync", T>
Factory function that creates a synchronous ValueParser.
- metavar: NonEmptyString
The metavariable name for the derived parser.
A documentation entry which describes a specific usage of a command or option. It includes a subject (the usage), a description, and an optional default value.
- choices: Message
An optional list of valid choices for the entry, formatted as a comma-separated Message. When present and the
showChoicesformatting option is enabled, this is appended to the entry description. - default: Message
An optional default value for the entry, which can be used to indicate what the default behavior is if the command or option is not specified.
- description: Message
A description of the entry, which provides additional context or information about the usage.
- term: UsageTerm
The subject of the entry, which is typically a command or option usage.
A collection of documentation fragments with an optional description. This structure is used to gather fragments before organizing them into a final document page.
- brief: Message
An optional brief that provides a short summary for the collection of fragments.
- description: Message
An optional description that applies to the entire collection of fragments.
- footer: Message
An optional footer that appears at the bottom of the documentation.
- fragments: readonly DocFragment[]
An array of documentation fragments that can be entries or sections.
A document page that contains multiple sections, each with its own brief and a list of entries. This structure is used to organize documentation for commands, options, and other related information.
- author: Message
Author information.
- brief: MessageNo documentation available
- bugs: Message
Information about where to report bugs.
- description: MessageNo documentation available
- examples: Message
Usage examples for the program.
- footer: MessageNo documentation available
- sections: readonly DocSection[]No documentation available
- usage: UsageNo documentation available
Options for formatting a documentation page.
- colors: boolean
Whether to include ANSI color codes in the output.
- maxWidth: number
Maximum width of the entire formatted output.
- sectionOrder: () => numbera: DocSection,b: DocSection
A custom comparator function to control the order of sections in the help output. When provided, it is used instead of the default smart sort (command-only sections first, then mixed, then option/argument-only sections). Sections that compare equal (return
0) preserve their original relative order (stable sort). - showChoices: boolean | ShowChoicesOptions
Whether and how to display valid choices for options and arguments backed by enumerated value parsers (e.g.,
choice()). - showDefault: boolean | ShowDefaultOptions
Whether and how to display default values for options and arguments.
- termIndent: number
Number of spaces to indent terms in documentation entries.
- termWidth: number
Width allocated for terms before descriptions start.
A section in a document that groups related entries together.
Options for domain parser.
- allowSubdomains: boolean
If
true, allows subdomains (e.g., "www.example.com"). Iffalse, only accepts root domains (e.g., "example.com"). - allowedTlds: readonly string[]
List of allowed top-level domains (e.g., ["com", "org", "net"]). If specified, only domains with these TLDs are accepted.
- errors: { invalidDomain?: Message | ((input: string) => Message); subdomainsNotAllowed?: Message | ((domain: string) => Message); tldNotAllowed?:Message; tooFewLabels?: Message | ((
| (() => Message)tld: string,allowedTlds: readonly string[]) => Message); tooLong?: Message | ((domain: string,minLabels: number) => Message); }domain: string,maxLength: numberCustom error messages for domain parsing failures.
- lowercase: boolean
If
true, converts domain to lowercase. - maxLength: number
Maximum domain length in characters.
- metavar: NonEmptyString
The metavariable name for this parser.
- minLabels: number
Minimum number of domain labels (parts separated by dots).
- placeholder: string
A custom placeholder value used during deferred prompt resolution. Override when
allowedTlds,minLabels, or other constraints reject the default"example.com".
Options for the email parser.
- allowDisplayName: boolean
If
true, allows display names in format "Name [email protected]". When enabled, returns the email address only (strips display name). - allowMultiple: boolean
If
true, allows multiple email addresses separated by commas. Returns an array of email addresses. - allowedDomains: readonly string[]
List of allowed email domains (e.g., ["example.com", "test.org"]). If specified, only emails from these domains are accepted.
- errors: { invalidEmail?: Message | ((input: string) => Message); domainNotAllowed?:Message; }
| (() => Message)email: string,allowedDomains: readonly string[]Custom error messages for email parsing failures.
- lowercase: boolean
If
true, converts the domain part of the email to lowercase. The local part is preserved as-is, since it is technically case-sensitive per RFC 5321. - metavar: NonEmptyString
The metavariable name for this parser.
- placeholder: string | readonly string[]
Override the default placeholder value used for deferred parsing. When not specified, the placeholder is derived from the first entry in allowedDomains (or
"example.com"when no domains are set).
Shared execution context carrying cross-cutting runtime data. This includes information that is shared across all parsers in a parse tree, such as usage information, dependency registries, and the current execution phase.
- commandPath: readonly string[]
Matched command names in parse order.
- dependencyRegistry: DependencyRegistryLike
A registry containing resolved dependency values from DependencySource parsers.
- dependencyRuntime: DependencyRuntimeContext
The dependency runtime context for dependency resolution. Coexists with
dependencyRegistryduring the transition period. - excludedSourceFields: ReadonlySet<string | symbol>
Field names that should be ignored when a construct seeds dependency sources from child state during completion.
- path: readonly PropertyKey[]
The path from the root to the current parser in the parse tree. Used by constructs to track the current position during dependency resolution and completion.
- phase: ExecutionPhase
The current phase of the execution pipeline.
- preCompletedByParser: ReadonlyMap<string | symbol, unknown>
Immutable map of pre-completed results from the parent construct's Phase 1, keyed by field name. Each construct passes its own
preCompleteAndRegisterDependenciesresults directly to children in Phase 3. Children read it in their own Phase 1 to avoid re-evaluating non-idempotent default thunks, but never write to it — this prevents sibling completions from leaking into each other. - trace: InputTrace
Immutable trace of raw primitive inputs recorded during parsing.
- usage: Usage
Usage information for the entire parser tree.
Options for customizing error messages in the flag parser.
- duplicate: Message | ((token: string) => Message)
Custom error message when flag is used multiple times. Can be a static message or a function that receives the token.
- endOfInput: Message
Custom error message when input is empty but flag is expected.
- missing: Message | ((optionNames: readonly string[]) => Message)
Custom error message when the flag is missing (for required flags). Can be a static message or a function that receives the option names.
- noMatch:Message
| (() => Message)invalidOption: string,suggestions: readonly string[]Custom error message when no matching flag is found. Can be a static message or a function that receives:
- optionsTerminated: Message
Custom error message when options are terminated (after --).
Options for the flag parser.
- description: Message
The description of the flag, which can be used for help messages.
- errors: FlagErrorOptions
Error message customization options.
- hidden: HiddenVisibility
Controls flag visibility:
Options for creating a float parser.
- allowInfinity: boolean
If
true, allows the special valuesInfinityand-Infinity. This is useful for cases where infinite values are valid inputs, such as in mathematical calculations or limits. - allowNaN: boolean
If
true, allows the special valueNaN(not a number). This is useful for cases whereNaNis a valid input, such as in some scientific calculations. - errors: { invalidNumber?: Message | ((input: string) => Message); belowMinimum?: Message | (() => Message); aboveMaximum?: Message | ((value: number,min: number) => Message); }value: number,max: number
Custom error messages for float parsing failures.
- max: number
Maximum allowed value (inclusive). If not specified, no maximum is enforced.
- metavar: NonEmptyString
The metavariable name for this parser. This is used in help messages to indicate what kind of value this parser expects. Usually a single word in uppercase, like
RATEorPRICE. - min: number
Minimum allowed value (inclusive). If not specified, no minimum is enforced.
- placeholder: number
A custom placeholder value used during deferred prompt resolution. Override the default
0whenmin/maxconstraints or downstreammap()transforms require a specific value.
Options for the group parser wrapper.
- hidden: HiddenVisibility
Controls visibility of all terms emitted by this group.
Options for the hostname parser.
- allowLocalhost: boolean
If
true, allows "localhost" as a hostname. - allowUnderscore: boolean
If
true, allows underscores in hostnames. Technically invalid per RFC 1123, but commonly used in some contexts (e.g., service discovery records like "_service.example.com"). - allowWildcard: boolean
If
true, allows wildcard hostnames (e.g., "*.example.com"). - errors: { invalidHostname?: Message | ((input: string) => Message); wildcardNotAllowed?: Message | ((hostname: string) => Message); underscoreNotAllowed?: Message | ((hostname: string) => Message); localhostNotAllowed?: Message | ((hostname: string) => Message); tooLong?: Message | (() => Message); }hostname: string,maxLength: number
Custom error messages for hostname parsing failures.
- maxLength: number
Maximum hostname length in characters.
- metavar: NonEmptyString
The metavariable name for this parser.
- placeholder: string
A custom placeholder value used during deferred prompt resolution. Override when
allowLocalhostor other constraints reject the default.
Options for creating an integer parser that returns a bigint.
- errors: { invalidInteger?: Message | ((input: string) => Message); belowMinimum?: Message | (() => Message); aboveMaximum?: Message | ((value: bigint,min: bigint) => Message); }value: bigint,max: bigint
Custom error messages for bigint integer parsing failures.
- max: bigint
Maximum allowed value (inclusive). If not specified, no maximum is enforced.
- metavar: NonEmptyString
The metavariable name for this parser. This is used in help messages to indicate what kind of value this parser expects. Usually a single word in uppercase, like
PORT. - min: bigint
Minimum allowed value (inclusive). If not specified, no minimum is enforced.
- placeholder: bigint
A custom placeholder value used during deferred prompt resolution. Override the default
0nwhenmin/maxconstraints or downstreammap()transforms require a specific value. - type: "bigint"
Must be set to
"bigint"to create abigintparser.
Options for creating an integer parser that returns a JavaScript number.
- errors: { invalidInteger?: Message | ((input: string) => Message); unsafeInteger?: Message | ((input: string) => Message); belowMinimum?: Message | (() => Message); aboveMaximum?: Message | ((value: number,min: number) => Message); }value: number,max: number
Custom error messages for integer parsing failures.
- max: number
Maximum allowed value (inclusive). If not specified, no maximum is enforced.
- metavar: NonEmptyString
The metavariable name for this parser. This is used in help messages to indicate what kind of value this parser expects. Usually a single word in uppercase, like
PORT. - min: number
Minimum allowed value (inclusive). If not specified, no minimum is enforced.
- placeholder: number
A custom placeholder value used during deferred prompt resolution. Override the default
0whenmin/maxconstraints or downstreammap()transforms require a specific value. - type: "number"
The type of integer to parse.
Options for configuring the universal IP address value parser.
- errors: { invalidIP?: Message | ((input: string) => Message); privateNotAllowed?: Message | ((ip: string) => Message); loopbackNotAllowed?: Message | ((ip: string) => Message); linkLocalNotAllowed?: Message | ((ip: string) => Message); multicastNotAllowed?: Message | ((ip: string) => Message); broadcastNotAllowed?: Message | ((ip: string) => Message); zeroNotAllowed?: Message | ((ip: string) => Message); uniqueLocalNotAllowed?: Message | ((ip: string) => Message); }
Custom error messages for IP parsing failures.
- ipv4: Omit<Ipv4Options, "metavar" | "errors">
Options for IPv4 validation (when version is 4 or "both").
- ipv6: Omit<Ipv6Options, "metavar" | "errors">
Options for IPv6 validation (when version is 6 or "both").
- metavar: NonEmptyString
The metavariable name for this parser.
- version: 4 | 6 | "both"
IP version to accept.
Options for the ipv4 value parser.
- allowBroadcast: boolean
If
true, allows the broadcast address (255.255.255.255). - allowLinkLocal: boolean
If
true, allows link-local addresses (169.254.0.0/16). - allowLoopback: boolean
If
true, allows loopback addresses (127.0.0.0/8). - allowMulticast: boolean
If
true, allows multicast addresses (224.0.0.0/4). - allowPrivate: boolean
If
true, allows private IP ranges (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16). - allowZero: boolean
If
true, allows the zero address (0.0.0.0). - errors: { invalidIpv4?: Message | ((input: string) => Message); privateNotAllowed?: Message | ((ip: string) => Message); loopbackNotAllowed?: Message | ((ip: string) => Message); linkLocalNotAllowed?: Message | ((ip: string) => Message); multicastNotAllowed?: Message | ((ip: string) => Message); broadcastNotAllowed?: Message | ((ip: string) => Message); zeroNotAllowed?: Message | ((ip: string) => Message); }
Custom error messages for IPv4 parsing failures.
- metavar: NonEmptyString
The metavariable name for this parser.
Options for configuring the IPv6 address value parser.
- allowLinkLocal: boolean
If
true, allows link-local addresses (fe80::/10). - allowLoopback: boolean
If
true, allows loopback address (::1). - allowMulticast: boolean
If
true, allows multicast addresses (ff00::/8). - allowUniqueLocal: boolean
If
true, allows unique local addresses (fc00::/7). - allowZero: boolean
If
true, allows the zero address (::). - errors: { invalidIpv6?: Message | ((input: string) => Message); loopbackNotAllowed?: Message | ((ip: string) => Message); linkLocalNotAllowed?: Message | ((ip: string) => Message); uniqueLocalNotAllowed?: Message | ((ip: string) => Message); multicastNotAllowed?: Message | ((ip: string) => Message); zeroNotAllowed?: Message | ((ip: string) => Message); }
Custom error messages for IPv6 parsing failures.
- metavar: NonEmptyString
The metavariable name for this parser.
Options for creating a locale parser.
- errors: { invalidLocale?: Message | ((input: string) => Message); }
Custom error messages for locale parsing failures.
- metavar: NonEmptyString
The metavariable name for this parser. This is used in help messages to indicate what kind of value this parser expects. Usually a single word in uppercase, like
LOCALEorLANG.
Options for customizing error messages in the longestMatch parser.
- noMatch: Message | ((context: NoMatchContext) => Message)
Custom error message when no parser matches. Can be a static message or a function that receives context about what types of inputs are expected, allowing for more precise error messages.
- suggestions: (suggestions: readonly string[]) => Message
Custom function to format suggestion messages. If provided, this will be used instead of the default "Did you mean?" formatting. The function receives an array of similar valid options/commands and should return a formatted message to append to the error.
- unexpectedInput: Message | ((token: string) => Message)
Custom error message for unexpected input. Can be a static message or a function that receives the unexpected token.
Options for customizing error messages in the longestMatch combinator.
- errors: LongestMatchErrorOptions
Error message customization options.
Options for the macAddress parser.
- case: "preserve" | "upper" | "lower"
Case for the output.
- errors: { invalidMacAddress?: Message | ((input: string) => Message); }
Custom error messages for MAC address parsing failures.
- metavar: NonEmptyString
The metavariable name for this parser.
- outputSeparator: ":" | "-" | "." | "none"
Output separator format. If not specified, uses the input separator (or ":" for "any").
- separator: ":" | "-" | "." | "none" | "any"
Separator format to accept.
Options for the merge parser.
- allowDuplicates: boolean
When
true, allows duplicate option names across merged parsers. By default (false), duplicate option names cause a construction-time error. - hidden: HiddenVisibility
Controls visibility of all terms emitted by this merged parser.
Options for the formatMessage function.
- colors: boolean | { readonly resetSuffix?: string; }
Whether to use colors in the formatted message. If
true, the formatted message will include ANSI escape codes for colors. Iffalse, the message will be plain text without colors. - maxWidth: number
The maximum width of the formatted message. If specified, the message will be wrapped to fit within this width. If not specified, the message will not be wrapped.
- quotes: boolean
Whether to use quotes around values in the formatted message. If
true, values will be wrapped in quotes (e.g.,"value"). Iffalse, values will be displayed without quotes.
Options for customizing error messages in the multiple parser.
Options for the multiple parser.
- errors: MultipleErrorOptions
Error messages customization.
- max: number
The maximum number of occurrences allowed for the parser. If the number of occurrences exceeds this value, the parser will fail with an error.
- min: number
The minimum number of occurrences required for the parser to succeed. If the number of occurrences is less than this value, the parser will fail with an error.
Context information about what types of inputs are expected, used for generating contextual error messages.
- hasArguments: boolean
Whether any of the parsers expect arguments.
- hasCommands: boolean
Whether any of the parsers expect commands.
- hasOptions: boolean
Whether any of the parsers expect options.
Options for customizing error messages in the object parser.
- endOfInput: Message | ((context: NoMatchContext) => Message)
Error message when end of input is reached unexpectedly. Can be a static message or a function that receives context about what types of inputs are expected, allowing for more precise error messages.
- suggestions: (suggestions: readonly string[]) => Message
Custom function to format suggestion messages. If provided, this will be used instead of the default "Did you mean?" formatting. The function receives an array of similar valid options/commands and should return a formatted message to append to the error.
- unexpectedInput: Message | ((token: string) => Message)
Error message when an unexpected option or argument is encountered.
Options for the object parser.
- allowDuplicates: boolean
When
true, allows duplicate option names across different fields. By default (false), duplicate option names cause a construction-time error. - errors: ObjectErrorOptions
Error messages customization.
- hidden: HiddenVisibility
Controls visibility of all terms emitted by this object parser.
Options for customizing error messages in the option parser.
- duplicate: Message | ((token: string) => Message)
Custom error message when option is used multiple times. Can be a static message or a function that receives the token.
- endOfInput: Message
Custom error message when input is empty but option is expected.
- invalidValue: Message | ((error: Message) => Message)
Custom error message when value parsing fails. Can be a static message or a function that receives the error message.
- missing: Message | ((optionNames: readonly string[]) => Message)
Custom error message when the option is missing (for required options). Can be a static message or a function that receives the option names.
- noMatch:Message
| (() => Message)invalidOption: string,suggestions: readonly string[]Custom error message when no matching option is found. Can be a static message or a function that receives:
- optionsTerminated: Message
Custom error message when options are terminated (after
--). - unexpectedValue: Message | ((value: string) => Message)
Custom error message when a Boolean flag receives an unexpected value. Can be a static message or a function that receives the value.
Options for the option parser.
- description: Message
The description of the option, which can be used for help messages.
- errors: OptionErrorOptions
Error message customization options.
- hidden: HiddenVisibility
Controls option visibility:
Sub-configuration for a meta command's option form.
Options for customizing error messages in the or parser.
- noMatch: Message | ((context: NoMatchContext) => Message)
Custom error message when no parser matches. Can be a static message or a function that receives context about what types of inputs are expected, allowing for more precise error messages.
- suggestions: (suggestions: readonly string[]) => Message
Custom function to format suggestion messages. If provided, this will be used instead of the default "Did you mean?" formatting. The function receives an array of similar valid options/commands and should return a formatted message to append to the error.
- unexpectedInput: Message | ((token: string) => Message)
Custom error message for unexpected input. Can be a static message or a function that receives the unexpected token.
- errors: OrErrorOptions
Error message customization options.
Parser-local frame data containing the input buffer and parser state. This represents the per-parser progress during parsing, separated from cross-cutting execution context.
- buffer: readonly string[]
The array of input strings that the parser is currently processing.
- optionsTerminated: boolean
A flag indicating whether no more options should be parsed and instead the remaining input should be treated as positional arguments.
- state: TState
The current state of the parser, which is used to track the progress of parsing and any accumulated data.
Options for parse functions.
- annotations: Annotations
Annotations to attach to the parsing session. Parsers can access these annotations via getAnnotations(state).
Parser interface for command-line argument parsing.
- $stateType: readonly TState[]
A type tag for the state of this parser, used for type inference. Usually this is an empty array at runtime, but it does not matter what it contains.
- $valueType: readonly TValue[]
A type tag for the result value of this parser, used for type inference. Usually this is an empty array at runtime, but it does not matter what it contains.
- acceptingAnyToken: boolean
Whether this parser unconditionally consumes any positional token at the first buffer position. A parser with this flag accepts any non-option token but may still reject option-like tokens (those starting with
"-"). - complete(): ModeValue<M, ValueParserResult<TValue>>state: TState,exec?: ExecutionContext
Transforms a TState into a TValue, if applicable. If the transformation is not applicable, it should return a
ValueParserResultwithsuccess: falseand an appropriate error message. - dependencyMetadata: ParserDependencyMetadata
Internal dependency metadata describing this parser's dependency capabilities. Used by the dependency runtime to resolve dependencies without relying on state-shape protocols.
- getDocFragments(): DocFragmentsstate: DocState<TState>,defaultValue?: TValue
Generates a documentation fragment for this parser, which can be used to describe the parser's usage, description, and default value.
- getSuggestRuntimeNodes(): readonly RuntimeNode[]state: TState,path: readonly PropertyKey[]
Internal hook for top-level suggest-time dependency seeding.
- initialState: TState
The initial state for this parser. This is used to initialize the state when parsing starts.
- leadingNames: ReadonlySet<string>
Names that this parser could match at the first buffer position. Used by
runParser()to detect collisions with built-in meta features (help, version, completion). - mode: M
The execution mode of this parser.
- normalizeValue(value: TValue): TValue
Normalizes a parsed value according to the underlying value parser's configuration. When present, withDefault calls this method on default values so that runtime defaults match the representation that the value parser's
parse()would produce. - parse(context: ParserContext<TState>): ModeValue<M, ParserResult<TState>>
Parses the input context and returns a result indicating whether the parsing was successful or not.
- placeholder: TValue
A type-appropriate default value used as a stand-in during deferred prompt resolution. When present, combinators like
prompt()use this value instead of an internal sentinel during two-phase parsing, so thatmap()transforms and two-pass contexts always receive a valid value of type TValue. - priority: number
The priority of this parser, which determines the order in which parsers are applied when multiple parsers are available. The greater the number, the higher the priority.
- shouldDeferCompletion(): booleanstate: TState,exec?: ExecutionContext
Optional predicate that determines whether completion should be deferred for the given parser state.
- suggest(): ModeIterable<M, Suggestion>context: ParserContext<TState>,prefix: string
Generates next-step suggestions based on the current context and an optional prefix. This can be used to provide shell completion suggestions or to guide users in constructing valid commands.
Internal marker for wrappers whose
{ hasCliValue: false }states should be treated as unmatched dependency-source states during completion-time Phase 1.- usage: Usage
The usage information for this parser, which describes how to use it in command-line interfaces.
- validateValue(value: TValue): ModeValue<M, ValueParserResult<TValue>>
Optionally re-validates a value as if it had been parsed from CLI input, surfacing any constraint violations from the underlying value parser (e.g., regex patterns, numeric bounds,
choice()values).
The context of the parser, which includes the input buffer and the state.
- buffer: readonly string[]
The array of input strings that the parser is currently processing.
- dependencyRegistry: DependencyRegistryLike
A registry containing resolved dependency values from DependencySource parsers. This is used during shell completion to provide suggestions based on the actual dependency values that have been parsed, rather than defaults.
- exec: ExecutionContext
Shared execution context (usage, phase, path, dependencyRegistry).
- optionsTerminated: boolean
A flag indicating whether no more options should be parsed and instead the remaining input should be treated as positional arguments. This is typically set when the parser encounters a
--in the input, which is a common convention in command-line interfaces to indicate that no further options should be processed. - state: TState
The current state of the parser, which is used to track the progress of parsing and any accumulated data.
- trace: InputTrace
Immutable trace of raw primitive inputs recorded during parsing.
- usage: Usage
Usage information for the entire parser tree. Used to provide better error messages with suggestions for typos. When a parser encounters an invalid option or command, it can use this information to suggest similar valid options.
Options for the passThrough parser.
- description: Message
A description of what pass-through options are used for.
- format: PassThroughFormat
How to capture option values:
- hidden: HiddenVisibility
Controls pass-through visibility:
Options for creating a port parser that returns a bigint.
- disallowWellKnown: boolean
If
true, disallows well-known ports (1-1023). These ports typically require root/administrator privileges on most systems. - errors: { invalidPort?: Message | ((input: string) => Message); belowMinimum?: Message | (() => Message); aboveMaximum?: Message | ((port: bigint,min: bigint) => Message); wellKnownNotAllowed?: Message | ((port: bigint) => Message); }port: bigint,max: bigint
Custom error messages for port parsing failures.
- max: bigint
Maximum allowed port number (inclusive).
- metavar: NonEmptyString
The metavariable name for this parser. This is used in help messages to indicate what kind of value this parser expects. Usually a single word in uppercase, like
PORT. - min: bigint
Minimum allowed port number (inclusive).
- placeholder: bigint
A custom placeholder value used during deferred prompt resolution. Defaults to
min(which itself defaults to1n). - type: "bigint"
Must be set to
"bigint"to create abigintparser.
Options for creating a port parser that returns a JavaScript number.
- disallowWellKnown: boolean
If
true, disallows well-known ports (1-1023). These ports typically require root/administrator privileges on most systems. - errors: { invalidPort?: Message | ((input: string) => Message); belowMinimum?: Message | (() => Message); aboveMaximum?: Message | ((port: number,min: number) => Message); wellKnownNotAllowed?: Message | ((port: number) => Message); }port: number,max: number
Custom error messages for port parsing failures.
- max: number
Maximum allowed port number (inclusive).
- metavar: NonEmptyString
The metavariable name for this parser. This is used in help messages to indicate what kind of value this parser expects. Usually a single word in uppercase, like
PORT. - min: number
Minimum allowed port number (inclusive).
- placeholder: number
A custom placeholder value used during deferred prompt resolution. Defaults to
min(which itself defaults to1). - type: "number"
The type of value to return.
Options for the portRange parser that returns bigint values.
- allowSingle: boolean
If
true, allows single port without range (e.g., "8080"). The result will havestart === end. - disallowWellKnown: boolean
If
true, disallows well-known ports (1-1023). Applied to both start and end ports. - errors: { invalidFormat?: Message | ((input: string) => Message); invalidRange?: Message | (() => Message); invalidPort?: Message | ((input: string) => Message); belowMinimum?: Message | ((start: bigint,end: bigint) => Message); aboveMaximum?: Message | ((port: bigint,min: bigint) => Message); wellKnownNotAllowed?: Message | ((port: bigint) => Message); }port: bigint,max: bigint
Custom error messages for port range parsing failures.
- max: bigint
Maximum allowed port number (inclusive). Applied to both start and end ports.
- metavar: NonEmptyString
The metavariable name for this parser. If not specified, it is derived from the separator (e.g.,
"PORT-PORT"for"-"). - min: bigint
Minimum allowed port number (inclusive). Applied to both start and end ports.
- separator: string
Separator character(s) between start and end ports.
- type: "bigint"
Must be set to "bigint" to create a bigint parser.
Options for the portRange parser that returns number values.
- allowSingle: boolean
If
true, allows single port without range (e.g., "8080"). The result will havestart === end. - disallowWellKnown: boolean
If
true, disallows well-known ports (1-1023). Applied to both start and end ports. - errors: { invalidFormat?: Message | ((input: string) => Message); invalidRange?: Message | (() => Message); invalidPort?: Message | ((input: string) => Message); belowMinimum?: Message | ((start: number,end: number) => Message); aboveMaximum?: Message | ((port: number,min: number) => Message); wellKnownNotAllowed?: Message | ((port: number) => Message); }port: number,max: number
Custom error messages for port range parsing failures.
- max: number
Maximum allowed port number (inclusive). Applied to both start and end ports.
- metavar: NonEmptyString
The metavariable name for this parser. If not specified, it is derived from the separator (e.g.,
"PORT-PORT"for"-"). - min: number
Minimum allowed port number (inclusive). Applied to both start and end ports.
- separator: string
Separator character(s) between start and end ports.
- type: "number"
The type of values to return.
Port range value with bigint type.
Port range value with number type.
Configuration options for the run function.
- aboveError: "usage" | "help" | "none"
What to display above error messages:
- author: Message
Author information.
- brief: Message
Brief description shown at the top of help text.
- bugs: Message
Information about where to report bugs.
- colors: boolean
Enable colored output in help and error messages.
- completion:{ readonly shells?: Record<string, ShellCompletion>; readonly onShow?: (() => THelp) | ((exitCode: number) => THelp); }
& ({ readonly command: true | CommandSubConfig; readonly option?: true | OptionSubConfig; })
| { readonly option: true | OptionSubConfig; readonly command?: true | CommandSubConfig; }Completion configuration. When provided, enables shell completion. At least one of
commandoroptionmust be specified. - description: Message
Detailed description shown after the usage line.
- examples: Message
Usage examples for the program.
- footer: Message
Footer text shown at the bottom of help text.
- help:{ readonly onShow?: (() => THelp) | ((exitCode: number) => THelp); }
& ({ readonly command: true | CommandSubConfig; readonly option?: true | OptionSubConfig; })
| { readonly option: true | OptionSubConfig; readonly command?: true | CommandSubConfig; }Help configuration. When provided, enables help functionality. At least one of
commandoroptionmust be specified. - maxWidth: number
Maximum width for output formatting. Text will be wrapped to fit within this width. If not specified, text will not be wrapped.
- onError: (() => TError) | ((exitCode: number) => TError)
Callback function invoked when parsing fails. The function can optionally receive an exit code parameter.
- sectionOrder: () => numbera: DocSection,b: DocSection
A custom comparator function to control the order of sections in the help output. When provided, it is used instead of the default smart sort (command-only sections first, then mixed, then option/argument-only sections). Sections that compare equal (return
0) preserve their original relative order. - showChoices: boolean | ShowChoicesOptions
Whether and how to display valid choices for options and arguments backed by enumerated value parsers (e.g.,
choice()). - showDefault: boolean | ShowDefaultOptions
Whether and how to display default values for options and arguments.
- stderr: (text: string) => void
Function used to output error messages. Assumes it prints the ending newline.
- stdout: (text: string) => void
Function used to output help and usage messages. Assumes it prints the ending newline.
- version:{ readonly value: string; readonly onShow?: (() => THelp) | ((exitCode: number) => THelp); }
& ({ readonly command: true | CommandSubConfig; readonly option?: true | OptionSubConfig; })
| { readonly option: true | OptionSubConfig; readonly command?: true | CommandSubConfig; }Version configuration. When provided, enables version functionality. At least one of
commandoroptionmust be specified.
Options for runWith functions. Extends RunOptions with additional context-related settings.
- args: readonly string[]
Command-line arguments to parse. If not provided, defaults to
process.argv.slice(2)on Node.js/Bun orDeno.argson Deno. - contextOptions: Record<string, unknown>
Options to forward to source contexts. When contexts declare required options (via
$requiredOptions), pass them here to avoid name collisions with runner-level options such asargs,help, orcolors.
A shell completion generator.
- encodeSuggestions(suggestions: readonly Suggestion[]): Iterable<string>
Encodes Suggestions into chunks of strings suitable for the shell. All chunks will be joined without any separator.
- generateScript(): stringprogramName: string,args?: readonly string[]
Generates a shell completion script for the given program name.
- name: string
The name of the shell.
Configuration for customizing choices display formatting.
- label: string
Label text to display before the individual choice values.
- maxItems: number
Maximum number of choice values to display before truncating with
.... Must be at least1. Set toInfinityto show all choices. - prefix: string
Text to display before the choices list.
- suffix: string
Text to display after the choices list.
Configuration for customizing default value display formatting.
Options for the socketAddress parser.
- defaultPort: number
Default port number if omitted from input. If not specified, port is required.
- errors: { invalidFormat?: Message | ((input: string) => Message); missingPort?: Message | ((input: string) => Message); }
Custom error messages for socket address parsing failures.
- host: { readonly type?: "hostname" | "ip" | "both"; readonly hostname?: Omit<HostnameOptions, "metavar" | "errors">; readonly ip?: Omit<Ipv4Options, "metavar" | "errors">; }
Options for hostname/IP validation.
- metavar: NonEmptyString
The metavariable name for this parser. If not specified, it is derived from the separator (e.g.,
"HOST:PORT"for":"). - port: Omit<PortOptionsNumber, "metavar" | "errors" | "type">
Options for port validation.
- requirePort: boolean
If
true, requires port to be specified in input (ignoresdefaultPort). - separator: string
Separator character(s) between host and port.
Socket address value containing host and port.
A source context that can provide data to parsers via annotations.
- $requiredOptions: TRequiredOptions
Type-level marker for the required options. Not used at runtime.
- getAnnotations(): Promise<Annotations> | Annotationsrequest?: SourceContextRequest,options?: unknown
Get annotations to inject into parsing.
- getInternalAnnotations(): Annotations | undefinedrequest: SourceContextRequest,annotations: Annotations
Optional hook to provide additional internal annotations during annotation collection. Called after getAnnotations with the same request object and the annotations returned by
getAnnotations(). - id: symbol
Unique identifier for this context.
- phase: SourceContextPhase
Declares whether this context is collected once or recollected after a usable first parse pass.
Options for creating a string parser.
- errors: { patternMismatch?: Message | (() => Message); }input: string,pattern: RegExp
Custom error messages for various string parsing failures.
- metavar: NonEmptyString
The metavariable name for this parser. This is used in help messages to indicate what kind of value this parser expects. Usually a single word in uppercase, like
HOSTorNAME. - pattern: RegExp
Optional regular expression pattern that the string must match.
- placeholder: string
A custom placeholder value used during deferred prompt resolution. Override the default
""when apatternconstraint or downstreammap()transform requires a non-empty or specially shaped string.
Options for the tuple parser.
- allowDuplicates: boolean
When
true, allows duplicate option names across different parsers. By default (false), duplicate option names cause a construction-time error.
Options for creating a url parser.
- allowedProtocols: readonly string[]
List of allowed URL protocols (e.g.,
["http:", "https:"]). If specified, the parsed URL must use one of these protocols. Protocol names should include the trailing colon (e.g.,"https:"). If not specified, any protocol is allowed. - errors: { invalidUrl?: Message | ((input: string) => Message); disallowedProtocol?:Message; }
| (() => Message)protocol: string,allowedProtocols: readonly string[]Custom error messages for URL parsing failures.
- metavar: NonEmptyString
The metavariable name for this parser. This is used in help messages to indicate what kind of value this parser expects. Usually a single word in uppercase, like
URLorENDPOINT.
Options for formatting usage descriptions.
- colors: boolean
When
true, applies ANSI color codes to the output for better readability. Different elements (options, arguments, commands, etc.) will be styled with different colors and formatting. - expandCommands: boolean
When
true, expands commands in the usage description to multiple lines, showing each command on a new line. This is useful for commands with many subcommands, making it easier to read and understand the available commands. - maxWidth: number
The maximum width of the formatted output. If specified, the output will be wrapped to fit within this width, breaking lines as necessary. If not specified, the output will not be wrapped.
- onlyShortestOptions: boolean
When
true, only shows the shortest option name for each option instead of showing all aliases separated by/. For example,--verbose/-vbecomes just-v.
Options for formatting a single UsageTerm.
- context: "usage" | "doc"
The rendering context, which determines which hidden visibility values cause terms to be filtered out.
- optionsSeparator: string
A string that separates multiple option names in the formatted output.
Options for creating a uuid parser.
- allowedVersions: readonly number[]
List of allowed UUID versions (e.g.,
[4, 5]for UUIDs version 4 and 5). Each version must be an integer between 1 and 8 (the standardized RFC 9562 versions). Duplicate entries are automatically removed. If specified, the parser will validate that the UUID matches one of the allowed versions. If not specified, the accepted versions depend on the strict option. - errors: { invalidUuid?: Message | ((input: string) => Message); disallowedVersion?:Message; invalidVariant?: Message | ((input: string) => Message); }
| (() => Message)version: number,allowedVersions: readonly number[]Custom error messages for UUID parsing failures.
- metavar: NonEmptyString
The metavariable name for this parser. This is used in help messages to indicate what kind of value this parser expects. Usually a single word in uppercase, like
UUIDorID. - strict: boolean
Whether to enforce strict RFC 9562 validation. When
true(the default), the parser validates that the version digit is one of the currently standardized versions (1 through 8) and that the variant bits follow the RFC 9562 layout (10xx, i.e., hex digits8,9,a, orbat position 20 of the UUID string).
Interface for parsing CLI option values and arguments.
- choices: readonly T[]
An optional array of valid choices for this parser. When present, indicates that this parser accepts only a fixed set of values, which can be displayed in help output via the
showChoicesformatting option. - format(value: T): string
Formats a value of type T into a string representation. This is useful for displaying the value in help messages or documentation.
- metavar: NonEmptyString
The metavariable name for this parser. Used in help messages to indicate what kind of value this parser expects. Usually a single word in uppercase, like
PORTorFILE. - mode: M
The execution mode of this value parser.
- normalize(value: T): T
Normalizes a value of type T according to this parser's configuration. This applies the same canonicalization that parse would apply (e.g., case conversion, separator normalization). Built-in implementations delegate to parse internally, so values that would fail validation are returned unchanged rather than being canonicalized.
- parse(input: string): ModeValue<M, ValueParserResult<T>>
Parses a string input into a value of type T.
- placeholder: T
A type-appropriate default value used as a stand-in during deferred prompt resolution. When an interactive prompt is deferred during two-phase parsing, this value is used instead of an internal sentinel so that
map()transforms and two-pass contexts always receive a valid value of type T. - suggest(prefix: string): ModeIterable<M, Suggestion>
Provides completion suggestions for values of this type. This is optional and used for shell completion functionality.
Options for the valueSet function.
- fallback: string
- locale:string
| readonly string[]
| Intl.Locale
| readonly Intl.Locale[]The locale(s) to use for list formatting. Can be a BCP 47 language tag string, an array of language tags, an
Intl.Localeobject, or an array ofIntl.Localeobjects. If not specified, the system default locale is used. - style: "long" | "short" | "narrow"
The style of the list formatting:
- type: "conjunction" | "disjunction" | "unit"
The type of list to format:
Options for the withDefault parser.
- message: Message
Custom message to display in help output instead of the formatted default value. This allows showing descriptive text like "SERVICE_URL environment variable" instead of the actual default value.
Type Aliases
Annotations that can be passed to parsers during execution. Allows external packages to provide additional data that parsers can access during complete() or parse() phases.
Combines modes from multiple dependency sources. If any source is async, the result is async.
Combines two modes into a single mode. If either mode is async, the result is async.
Combines multiple modes into a single mode.
If any mode is "async", the result is "async"; otherwise "sync".
When contexts require options, demands a contextOptions property
typed to those requirements. When no context needs options
(void, unknown, or {}), resolves to unknown (intersection no-op).
When all context option keys are optional, contextOptions itself becomes
optional so callers are not forced to pass an empty wrapper.
A recursive map that tracks which fields in a parsed object hold deferred
placeholder values. Each entry maps a property key to either null
(the field is fully deferred and should be replaced with undefined)
or another DeferredMap (the field is partially deferred — recurse into
its sub-fields).
Extracts the mode from a DependencySource.
Extracts the value type from a DependencySource.
Maps a tuple of DependencySources to a tuple of their value types.
| { readonly type: "section"; } & DocSection
A documentation fragment that can be either an entry or a section. Fragments are building blocks used to construct documentation pages.
| { readonly kind: "unavailable"; }
Represents the state passed to getDocFragments. Can be either the actual parser state or an explicit indicator that no state is available.
The phase of the execution pipeline.
Extracts and merges required options from an array of source contexts.
Infers the result value type of a Parser.
Type representing a message that can include styled/colored values. This type is used to create structured messages that can be displayed to the user with specific formatting.
| { readonly type: "optionName"; readonly optionName: string; }
| { readonly type: "optionNames"; readonly optionNames: readonly string[]; }
| { readonly type: "metavar"; readonly metavar: NonEmptyString; }
| { readonly type: "value"; readonly value: string; }
| { readonly type: "values"; readonly values: readonly string[]; }
| { readonly type: "envVar"; readonly envVar: string; }
| { readonly type: "commandLine"; readonly commandLine: string; }
| { readonly type: "lineBreak"; }
| { readonly type: "url"; readonly url: URL; }
Represents a single term in a message, which can be a text, an option name, a list of option names, a metavariable, a value, or a list of consecutive values.
Represents the execution mode for parsers.
Wraps an iterable type based on the execution mode.
Wraps a value type based on the execution mode.
A string type that guarantees at least one character.
Used for metavar properties to ensure they are never empty.
| `-${NonEmptyString}`
| `/${NonEmptyString}`
| `+${NonEmptyString}`
Represents the name of a command-line option. There are four types of option syntax:
| { readonly success: false; readonly consumed: number; readonly error: Message; }
A discriminated union type representing the result of a parser operation. It can either indicate a successful parse with the next state and context, or a failure with an error message.
A placeholder type that represents the parser's result value type.
- parserValuePlaceholderBrand: "ParserValuePlaceholder"No documentation available
Format options for how passThrough captures options.
| { readonly success: false; readonly error: Message; }
The result type of a whole parser operation, which can either be a successful
result with a value of type T, or a failure with an error message.
Request object passed to SourceContext.getAnnotations and SourceContext.getInternalAnnotations.
Substitutes ParserValuePlaceholder with the actual parser value type.
| { readonly kind: "file"; readonly pattern?: string; readonly type: "file" | "directory" | "any"; readonly extensions?: readonly string[]; readonly includeHidden?: boolean; readonly description?: Message; }
Represents a suggestion for command-line completion or guidance.
| { readonly type: "option"; readonly names: readonly OptionName[]; readonly metavar?: NonEmptyString; readonly hidden?: HiddenVisibility; }
| { readonly type: "command"; readonly name: string; readonly usageLine?: Usage | ((defaultUsageLine: Usage) => Usage); readonly hidden?: HiddenVisibility; }
| { readonly type: "optional"; readonly terms: Usage; }
| { readonly type: "multiple"; readonly terms: Usage; readonly min: number; }
| { readonly type: "exclusive"; readonly terms: readonly Usage[]; }
| { readonly type: "literal"; readonly value: string; readonly optionValue?: boolean; }
| { readonly type: "passthrough"; readonly hidden?: HiddenVisibility; }
| { readonly type: "ellipsis"; }
Represents a single term in a command-line usage description.
Type representing a UUID string.
| { readonly success: false; readonly error: Message; }
Result type returned by ValueParser#parse.
Options for creating a choice parser.