Skip to main content

Built and signed on GitHub Actions

Works with
This package works with Cloudflare Workers, Node.js, Deno, Bun, Browsers
This package works with Cloudflare Workers
This package works with Node.js
This package works with Deno
This package works with Bun
This package works with Browsers
JSR Score94%
License
MIT
Downloads232/wk
Published6 days ago (1.0.0)

Type-safe combinatorial command-line interface parser

Classes

c
DuplicateOptionError(
optionName: string,
sources: readonly (string | symbol)[]
)

Error class thrown when duplicate option names are detected during parser construction. This is a programmer error, not a user error.

c
RunParserError(message: string)

An error class used to indicate that the command line arguments could not be parsed successfully.

c
WithDefaultError(message: Message)

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

f
argument<M extends Mode, T>(
valueParser: ValueParser<M, T>,
options?: ArgumentOptions
): Parser<M, T, ValueParserResult<T> | undefined>

Creates a parser that expects a single argument value. This parser is typically used for positional arguments that are not options or flags.

f
checkBooleanOption<T extends object>(
options: T | undefined,
key: keyof T
): void

Validates that an option value, if present, is a boolean. Throws a TypeError if the value is defined but not a boolean.

f
checkEnumOption<T extends object>(
options: T | undefined,
key: keyof T,
allowed: readonly string[]
): void

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.

f
choice<T extends string | number>(
choices: readonly T[],
options?: ChoiceOptionsString | ChoiceOptionsNumber
): ValueParser<"sync", T>
2 overloads

Creates a ValueParser that accepts one of multiple string values, so-called enumerated values.

f
cidr(options?: CidrOptions): ValueParser<"sync", CidrValue>

Creates a value parser for CIDR notation (IP address with prefix length).

f
cloneDocEntry(entry: DocEntry): DocEntry

Creates a deep clone of a DocEntry. The term is cloned via cloneUsageTerm, and description, default, and choices messages are cloned via cloneMessage.

f
cloneUsage(usage: Usage): UsageTerm[]

Creates a deep clone of a Usage array and all of its terms.

f
cloneUsageTerm(term: UsageTerm): UsageTerm

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.

f
command<M extends Mode, T, TState>(
name: string,
parser: Parser<M, T, TState>,
options?: CommandOptions
): Parser<M, T, CommandState<TState>>

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.

f
commandLine(commandLine: string): MessageTerm

Creates a MessageTerm for a command-line example.

f
concat(...parsers: Parser<Mode, readonly unknown[], unknown>[]): Parser<Mode, readonly unknown[], readonly unknown[]>
1 overloads

Concatenates tuple parsers into one parser with a flattened tuple value.

f
conditional(
discriminator: Parser<Mode, string, unknown>,
branches: Record<string, Parser<Mode, unknown, unknown>>,
defaultBranch?: Parser<Mode, unknown, unknown>,
options?: ConditionalOptions
): Parser<
Mode,
readonly [string | undefined, unknown],
ConditionalState<string>
>
2 overloads

Creates a conditional parser without a default branch. The discriminator option is required; parsing fails if not provided.

f
constant<T>(value: T): Parser<"sync", T, T>

Creates a parser that always succeeds without consuming any input and produces a constant value of the type T.

f
createParserContext<TState>(
frame: ParseFrame<TState>,
exec: ExecutionContext
): ParserContext<TState>

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.

f
deduplicateDocEntries(entries: readonly DocEntry[]): DocEntry[]

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.

f
deduplicateDocFragments(fragments: readonly DocFragment[]): DocFragment[]

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.

f
dependency<M extends Mode, T>(parser: ValueParser<M, T>): DependencySource<M, T>

Creates a dependency source from a ValueParser.

f
deriveFrom<
Deps extends readonly AnyDependencySource[],
T,
FM extends Mode = "sync"
>
(options: DeriveFromOptions<Deps, T, FM>): DerivedValueParser<
CombineMode<CombinedDependencyMode<Deps>, FM>,
T,
DependencyValues<Deps>
>

Creates a derived value parser from multiple dependency sources.

f
deriveFromAsync<Deps extends readonly AnyDependencySource[], T>(options: DeriveFromAsyncOptions<Deps, T>): DerivedValueParser<"async", T, DependencyValues<Deps>>

Creates a derived value parser from multiple dependency sources with an asynchronous factory.

f
deriveFromSync<Deps extends readonly AnyDependencySource[], T>(options: DeriveFromSyncOptions<Deps, T>): DerivedValueParser<CombinedDependencyMode<Deps>, T, DependencyValues<Deps>>

Creates a derived value parser from multiple dependency sources with a synchronous factory.

f
domain(options?: DomainOptions & { readonly metavar?: NonEmptyString; }): ValueParser<"sync", string>

Creates a value parser for domain names.

f
email(options?: EmailOptions): ValueParser<"sync", string | readonly string[]>
2 overloads

Creates a value parser for email addresses according to RFC 5322 (simplified).

f
ensureNonEmptyString(value: string): asserts value is NonEmptyString

Asserts that a string is non-empty. Throws a TypeError if the string is empty.

f
envVar(envVar: string): MessageTerm

Creates a MessageTerm for an environment variable.

f
extractArgumentMetavars(usage: Usage): Set<string>

Extracts all argument metavars from a Usage array.

f
extractCommandNames(
usage: Usage,
includeHidden?: boolean
): Set<string>

Extracts all command names from a Usage array.

f
extractLiteralValues(usage: Usage): Set<string>

Extracts all literal values from a usage description.

f
extractOptionNames(
usage: Usage,
includeHidden?: boolean
): Set<string>

Extracts all option names from a usage description.

f
fail<T>(): Parser<"sync", T, undefined>

Creates a parser that always fails without consuming any input.

f
flag(...args:
readonly [OptionName, ...readonly OptionName[], FlagOptions]
| readonly [OptionName, ...readonly OptionName[]]
): Parser<"sync", true, ValueParserResult<true> | undefined>

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.

f
float(options?: FloatOptions): ValueParser<"sync", number>

Creates a ValueParser for floating-point numbers.

f
formatDocPage(
programName: string,
page: DocPage,
options?: DocPageFormatOptions
): string

Formats a documentation page into a human-readable string.

f
formatMessage(
msg: Message,
options?: MessageFormatOptions & { readonly startWidth?: number; }
): string
1 overloads

Formats a Message into a human-readable string for the terminal.

f
formatUsage(
programName: string,
usage: Usage,
options?: UsageFormatOptions
): string

Formats a usage description into a human-readable string representation suitable for command-line help text.

f
formatUsageTerm(
term: UsageTerm,
options?: UsageTermFormatOptions
): string

Formats a single UsageTerm into a string representation suitable for command-line help text.

f
getAnnotations(state: unknown): Annotations | undefined

Extracts annotations from parser state.

f
getDocPage(
parser: Parser<Mode, unknown, unknown>,
argsOrOptions?: readonly string[] | ParseOptions,
options?: ParseOptions
): DocPage | undefined | Promise<DocPage | undefined>
3 overloads

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.

f
getDocPageAsync(
parser: Parser<Mode, unknown, unknown>,
argsOrOptions?: readonly string[] | ParseOptions,
options?: ParseOptions
): Promise<DocPage | undefined>

Generates a documentation page for any parser, returning a Promise.

f
getDocPageSync(
parser: Parser<"sync", unknown, unknown>,
argsOrOptions?: readonly string[] | ParseOptions,
options?: ParseOptions
): DocPage | undefined

Generates a documentation page for a synchronous parser.

f
group<M extends Mode, TValue, TState>(
label: string,
parser: Parser<M, TValue, TState>,
options?: GroupOptions
): Parser<M, TValue, TState>
No documentation available
f
hostname(options?: HostnameOptions): ValueParser<"sync", string>

Creates a value parser for DNS hostnames.

f
integer(options?: IntegerOptionsNumber | IntegerOptionsBigInt): ValueParser<"sync", number> | ValueParser<"sync", bigint>
2 overloads

Creates a ValueParser for integers that returns JavaScript numbers.

f
ip(options?: IpOptions): ValueParser<"sync", string>

Creates a value parser that accepts both IPv4 and IPv6 addresses.

f
ipv4(options?: Ipv4Options): ValueParser<"sync", string>

Creates a value parser for IPv4 addresses.

f
ipv6(options?: Ipv6Options): ValueParser<"sync", string>

Creates a value parser for IPv6 addresses.

f
isDependencySource<M extends Mode, T>(parser: ValueParser<M, T>): parser is DependencySource<M, T>

Checks if a value parser is a DependencySource.

f
isDerivedValueParser<M extends Mode, T>(parser: ValueParser<M, T>): parser is DerivedValueParser<M, T, unknown>

Checks if a value parser is a DerivedValueParser.

f
isDocEntryHidden(entry: DocEntry): boolean

Returns whether a doc entry's term is hidden from documentation. Only term types with a hidden field (argument, option, command, passthrough) are checked; other types always return false.

f
isDocHidden(hidden?: HiddenVisibility): boolean

Returns whether the term should be hidden from documentation output.

f
isNonEmptyString(value: string): value is NonEmptyString

Checks if a string is non-empty. Can be used as a type guard for type narrowing.

f
isSuggestionHidden(hidden?: HiddenVisibility): boolean

Returns whether the term should be hidden from suggestion/error candidates.

f
isUsageHidden(hidden?: HiddenVisibility): boolean

Returns whether the term should be hidden from usage output.

f
isValueParser<M extends Mode, T>(object: unknown): object is ValueParser<M, T>

A predicate function that checks if an object is a ValueParser.

f
lineBreak(): MessageTerm

Creates a MessageTerm for an explicit single-line break.

f
locale(options?: LocaleOptions): ValueParser<"sync", Intl.Locale>

Creates a ValueParser for locale values.

f
longestMatch(...args: Array<Parser<Mode, unknown, unknown> | LongestMatchOptions>): Parser<Mode, unknown, undefined | [number, ParserResult<unknown>]>
6 overloads

Creates a parser that selects the successful branch that consumed the most input tokens.

f
macAddress(options?: MacAddressOptions): ValueParser<"sync", string>

Creates a value parser for MAC (Media Access Control) addresses.

f
map<M extends Mode, T, U, TState>(
parser: Parser<M, T, TState>,
transform: (value: T) => U
): Parser<M, U, TState>

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.

f
merge(...args: readonly unknown[]): Parser<
Mode,
Record<string | symbol, unknown>,
Record<string | symbol, unknown>
>
4 overloads

Merges multiple object-like parsers into one parser, with options.

f
mergeHidden(
a?: HiddenVisibility,
b?: HiddenVisibility
): HiddenVisibility | undefined

Merges two hidden visibility settings by taking the union of restrictions.

f
message(
message: TemplateStringsArray,
...values: readonly (MessageTerm | Message | string)[]
): Message

Creates a structured message with template strings and values.

f
metavar(metavar: NonEmptyString): MessageTerm

Creates a MessageTerm for a metavariable.

f
multiple<M extends Mode, TValue, TState>(
parser: Parser<M, TValue, TState>,
options?: MultipleOptions
): Parser<M, readonly TValue[], readonly TState[]>

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.

f
nonEmpty<M extends Mode, T, TState>(parser: Parser<M, T, TState>): Parser<M, T, TState>

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.

f
normalizeUsage(usage: Usage): Usage

Normalizes a usage description by flattening nested exclusive terms, sorting terms for better readability, and ensuring consistent structure throughout the usage tree.

f
object<
T extends { readonly [key: string | symbol]: Parser<Mode, unknown, unknown>; }
>
(
labelOrParsers: string | T,
maybeParsersOrOptions?: T | ObjectOptions,
maybeOptions?: ObjectOptions
): Parser<
Mode,
readonly [K in keyof T]: unknown,
readonly [K in keyof T]: unknown
>
4 overloads

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.

f
option<M extends Mode, T>(...args:
readonly [
OptionName,
...readonly OptionName[],
ValueParser<M, T>,
OptionOptions
]

| readonly [OptionName, ...readonly OptionName[], ValueParser<M, T>]
| readonly [OptionName, ...readonly OptionName[], OptionOptions]
| readonly [OptionName, ...readonly OptionName[]]
): Parser<M, T | boolean, ValueParserResult<T | boolean> | undefined>
4 overloads

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.

f
optional<M extends Mode, TValue, TState>(parser: Parser<M, TValue, TState>): Parser<M, TValue | undefined, [TState] | undefined>

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.

f
optionName(name: string): MessageTerm

Creates a MessageTerm for an option name.

f
optionNames(names: readonly string[]): MessageTerm

Creates a MessageTerm for a list of option names.

f
or(...args: Array<Parser<Mode, unknown, unknown> | OrOptions>): Parser<Mode, unknown, undefined | [number, ParserResult<unknown>]>
18 overloads

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.

f
parse<M extends Mode, T>(
parser: Parser<M, T, unknown>,
args: readonly string[],
options?: ParseOptions
): ModeValue<M, Result<T>>

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.

f
parseAsync<T>(
parser: Parser<Mode, T, unknown>,
args: readonly string[],
options?: ParseOptions
): Promise<Result<T>>

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.

f
parseSync<T>(
parser: Parser<"sync", T, unknown>,
args: readonly string[],
options?: ParseOptions
): Result<T>

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.

f
passThrough(options?: PassThroughOptions): Parser<"sync", readonly string[], readonly string[]>

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.

f
port(options?: PortOptionsNumber | PortOptionsBigInt): ValueParser<"sync", number> | ValueParser<"sync", bigint>
2 overloads

Creates a ValueParser for TCP/UDP port numbers that returns JavaScript numbers.

f
portRange(options?: PortRangeOptionsNumber | PortRangeOptionsBigInt): ValueParser<"sync", PortRangeValueNumber | PortRangeValueBigInt>
2 overloads

Creates a value parser for port ranges (e.g., "8000-8080").

f
runParser<
TParser extends Parser<Mode, unknown, unknown>,
THelp = void,
TError = never
>
(
parserOrProgram: TParser | Program<Mode, unknown>,
programNameOrArgs: string | readonly string[],
argsOrOptions?: readonly string[] | RunOptions<THelp, TError>,
optionsParam?: RunOptions<THelp, TError>
): ModeValue<InferMode<TParser>, InferValue<TParser>>
5 overloads

Runs a parser against command-line arguments with built-in help and error handling.

f
runParserAsync<
TParser extends Parser<Mode, unknown, unknown>,
THelp = void,
TError = never
>
(
parser: TParser,
programName: string,
args: readonly string[],
options?: RunOptions<THelp, TError>
): Promise<InferValue<TParser>>

Runs any command-line parser asynchronously with the given options.

f
runParserSync<
TParser extends Parser<"sync", unknown, unknown>,
THelp = void,
TError = never
>
(
parser: TParser,
programName: string,
args: readonly string[],
options?: RunOptions<THelp, TError>
): InferValue<TParser>

Runs a synchronous command-line parser with the given options.

f
runWith<
TParser extends Parser<Mode, unknown, unknown>,
TContexts extends readonly SourceContext<unknown>[],
THelp = void,
TError = never
>
(
parser: TParser,
programName: string,
contexts: TContexts,
options:
RunWithOptions<THelp, TError>
& ContextOptionsParam<TContexts, InferValue<TParser>>
): Promise<InferValue<TParser>>

Runs a parser with multiple source contexts.

f
runWithAsync<
TParser extends Parser<Mode, unknown, unknown>,
TContexts extends readonly SourceContext<unknown>[],
THelp = void,
TError = never
>
(
parser: TParser,
programName: string,
contexts: TContexts,
options:
RunWithOptions<THelp, TError>
& ContextOptionsParam<TContexts, InferValue<TParser>>
): Promise<InferValue<TParser>>

Runs any parser asynchronously with multiple source contexts.

f
runWithSync<
TParser extends Parser<"sync", unknown, unknown>,
TContexts extends readonly SourceContext<unknown>[],
THelp = void,
TError = never
>
(
parser: TParser,
programName: string,
contexts: TContexts,
options:
RunWithOptions<THelp, TError>
& ContextOptionsParam<TContexts, InferValue<TParser>>
): InferValue<TParser>

Runs a synchronous parser with multiple source contexts.

f
socketAddress(options?: SocketAddressOptions): ValueParser<"sync", SocketAddressValue>

Creates a value parser for socket addresses in "host:port" format.

f
string(options?: StringOptions): ValueParser<"sync", string>

Creates a ValueParser for strings.

f
suggest<M extends Mode, T>(
parser: Parser<M, T, unknown>,
args: readonly [string, ...readonly string[]],
options?: ParseOptions
): ModeValue<M, readonly Suggestion[]>

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.

f
suggestAsync<T>(
parser: Parser<Mode, T, unknown>,
args: readonly [string, ...readonly string[]],
options?: ParseOptions
): Promise<readonly Suggestion[]>

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.

f
suggestSync<T>(
parser: Parser<"sync", T, unknown>,
args: readonly [string, ...readonly string[]],
options?: ParseOptions
): readonly Suggestion[]

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.

f
text(text: string): MessageTerm

Creates a MessageTerm for plain text. Usually used for dynamically generated messages.

f
tuple<T extends readonly Parser<Mode, unknown, unknown>[]>(
labelOrParsers: string | T,
maybeParsersOrOptions?: T | TupleOptions,
maybeOptions?: TupleOptions
): Parser<
Mode,
readonly [K in keyof T]: unknown,
readonly [K in keyof T]: unknown
>
2 overloads

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.

f
url(options?: UrlOptions): ValueParser<"sync", URL>

Creates a ValueParser for URL values.

f
uuid(options?: UuidOptions): ValueParser<"sync", Uuid>

Creates a ValueParser for UUID values.

f
value(value: string): MessageTerm

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.

f
values(values: readonly string[]): MessageTerm

Creates a MessageTerm for a list of consecutive values.

f
valueSet(
values: readonly string[],
fallbackOrOptions: string | ValueSetOptions
): Message

Creates a Message for a formatted list of values using the Intl.ListFormat API. This is useful for displaying choice lists in error messages with proper locale-aware formatting.

f
withDefault<M extends Mode, TValue, TState, TDefault = TValue>(
parser: Parser<M, TValue, TState>,
defaultValue: TDefault | (() => TDefault),
options?: WithDefaultOptions
): Parser<M, TValue | TDefault, [TState] | undefined>
2 overloads

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

I

Minimal structural supertype for dependency-source tuple constraints.

I

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.

I

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:

I

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 TYPE or MODE.

I

Options for creating a choice parser with number values. Note: caseInsensitive is not available for number choices.

  • errors: { invalidChoice?:
    Message
    | ((
    input: string,
    choices: readonly number[]
    ) => Message)
    ; }

    Custom error messages for choice parsing failures.

I

Options for creating a choice parser with string values.

  • 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. If false, the matching will be case-sensitive.

  • errors: { invalidChoice?:
    Message
    | ((
    input: string,
    choices: readonly string[]
    ) => Message)
    ; }

    Custom error messages for choice parsing failures.

I

Options for configuring the CIDR notation value parser.

  • errors: { invalidCidr?: Message | ((input: string) => Message); invalidPrefix?: Message | ((
    prefix: number,
    version: 4 | 6
    ) => Message)
    ; prefixBelowMinimum?: Message | ((
    prefix: number,
    min: number
    ) => Message)
    ; prefixAboveMaximum?: Message | ((
    prefix: number,
    max: 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); }

    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.

I

Value representing a CIDR notation (IP address with prefix length).

  • address: string

    The IP address portion (normalized).

  • prefix: number

    The prefix length (0-32 for IPv4, 0-128 for IPv6).

  • version: 4 | 6

    IP version (4 or 6).

I

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
    | ((
    expected: string,
    actual: string | null,
    suggestions?: readonly string[]
    ) => Message)

    Error message when command is expected but not found. Since version 0.7.0, the function signature now includes suggestions:

I

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 subcommand or myapp 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.

I

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.

I

Options for customizing error messages in the conditional combinator.

  • branchError: (
    discriminatorValue: string | undefined,
    error: Message
    ) => Message

    Custom error message when branch parser fails. Receives the discriminator value for context.

  • branchMismatch: (
    discriminatorValue: string,
    speculativeKey: string
    ) => Message

    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.

I

Options for customizing the conditional combinator behavior.

  • errors: ConditionalErrorOptions

    Custom error messages.

I

Represents a dependency source that can be used to create derived parsers.

  • dependencyId: symbol

    Unique identifier for this dependency source.

  • 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.

I

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.

I

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.

  • Marker to identify this as a derived value parser.

  • parseWithDependency: (
    input: string,
    dependencyValue: S
    ) => ValueParserResult<T> | Promise<ValueParserResult<T>>

    Parses the input using the actual dependency value instead of the default. This method is used during dependency resolution in complete().

  • The single default value thunk for single-source derived parsers. Read by the dependency-metadata bridge; not consumed by createDeferredParseState().

  • suggestWithDependency: (
    prefix: string,
    dependencyValue: S
    ) => Iterable<Suggestion> | AsyncIterable<Suggestion>

    Generates suggestions using the provided dependency value instead of the default. This method is used during shell completion when dependency sources have been parsed.

I

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.

  • 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.

I

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.

  • 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.

I

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.

  • 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.

I

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.

I

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.

I

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 showChoices formatting 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.

I

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.

I

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: Message
    No documentation available
  • bugs: Message

    Information about where to report bugs.

  • description: Message
    No documentation available
  • examples: Message

    Usage examples for the program.

  • footer: Message
    No documentation available
  • sections: readonly DocSection[]
    No documentation available
  • usage: Usage
    No documentation available
I

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: (
    a: DocSection,
    b: DocSection
    ) => number

    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.

I

A section in a document that groups related entries together.

  • entries: readonly DocEntry[]
    No documentation available
  • title: string
    No documentation available
I

Options for domain parser.

  • If true, allows subdomains (e.g., "www.example.com"). If false, 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
    | ((
    tld: string,
    allowedTlds: readonly string[]
    ) => Message)
    ; tooFewLabels?: Message | ((
    domain: string,
    minLabels: number
    ) => Message)
    ; tooLong?: Message | ((
    domain: string,
    maxLength: number
    ) => Message)
    ; }

    Custom 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".

I

Options for the email parser.

  • 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
    | ((
    email: string,
    allowedDomains: readonly string[]
    ) => Message)
    ; }

    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).

I

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 dependencyRegistry during 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 preCompleteAndRegisterDependencies results 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.

I

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
    | ((
    invalidOption: string,
    suggestions: readonly string[]
    ) => Message)

    Custom error message when no matching flag is found. Can be a static message or a function that receives:

  • Custom error message when options are terminated (after --).

I

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:

I

Options for creating a float parser.

  • allowInfinity: boolean

    If true, allows the special values Infinity and -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 value NaN (not a number). This is useful for cases where NaN is a valid input, such as in some scientific calculations.

  • errors: { invalidNumber?: Message | ((input: string) => Message); belowMinimum?: Message | ((
    value: number,
    min: number
    ) => Message)
    ; aboveMaximum?: Message | ((
    value: number,
    max: number
    ) => Message)
    ; }

    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 RATE or PRICE.

  • 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 0 when min/max constraints or downstream map() transforms require a specific value.

I

Options for the group parser wrapper.

  • hidden: HiddenVisibility

    Controls visibility of all terms emitted by this group.

I

Options for the hostname parser.

  • If true, allows "localhost" as a hostname.

  • 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 | ((
    hostname: string,
    maxLength: number
    ) => Message)
    ; }

    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 allowLocalhost or other constraints reject the default.

I

Options for creating an integer parser that returns a bigint.

  • errors: { invalidInteger?: Message | ((input: string) => Message); belowMinimum?: Message | ((
    value: bigint,
    min: bigint
    ) => Message)
    ; aboveMaximum?: Message | ((
    value: bigint,
    max: bigint
    ) => Message)
    ; }

    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 0n when min/max constraints or downstream map() transforms require a specific value.

  • type: "bigint"

    Must be set to "bigint" to create a bigint parser.

I

Options for creating an integer parser that returns a JavaScript number.

  • errors: { invalidInteger?: Message | ((input: string) => Message); unsafeInteger?: Message | ((input: string) => Message); belowMinimum?: Message | ((
    value: number,
    min: number
    ) => Message)
    ; aboveMaximum?: Message | ((
    value: number,
    max: number
    ) => Message)
    ; }

    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 0 when min/max constraints or downstream map() transforms require a specific value.

  • type: "number"

    The type of integer to parse.

I

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.

I

Options for the ipv4 value parser.

  • If true, allows the broadcast address (255.255.255.255).

  • If true, allows link-local addresses (169.254.0.0/16).

  • allowLoopback: boolean

    If true, allows loopback addresses (127.0.0.0/8).

  • 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.

I

Options for configuring the IPv6 address value parser.

  • If true, allows link-local addresses (fe80::/10).

  • allowLoopback: boolean

    If true, allows loopback address (::1).

  • If true, allows multicast addresses (ff00::/8).

  • 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.

I

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 LOCALE or LANG.

I

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.

I

Options for customizing error messages in the longestMatch combinator.

  • errors: LongestMatchErrorOptions

    Error message customization options.

I

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.

I

Options for the merge parser.

  • 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.

I

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. If false, 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"). If false, values will be displayed without quotes.

I

Options for customizing error messages in the multiple parser.

  • tooFew: Message | ((
    min: number,
    actual: number
    ) => Message)

    Error message when fewer than the minimum number of values are provided.

  • tooMany: Message | ((
    max: number,
    actual: number
    ) => Message)

    Error message when more than the maximum number of values are provided.

I

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.

I

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.

I

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.

I

Options for the object parser.

  • 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.

I

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
    | ((
    invalidOption: string,
    suggestions: readonly string[]
    ) => Message)

    Custom error message when no matching option is found. Can be a static message or a function that receives:

  • 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.

I

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:

I

Sub-configuration for a meta command's option form.

  • group: string

    Group label for the option in help output.

  • hidden: HiddenVisibility

    Granular visibility control.

  • names: readonly [OptionName, ...OptionName[]]

    Option names (all shown in help, e.g., "-h", "--help").

I

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.

I

Options for customizing error messages in the or combinator.

  • errors: OrErrorOptions

    Error message customization options.

I

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.

  • 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.

I

Options for parse functions.

  • annotations: Annotations

    Annotations to attach to the parsing session. Parsers can access these annotations via getAnnotations(state).

I

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.

  • 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(
    state: TState,
    exec?: ExecutionContext
    ): ModeValue<M, ValueParserResult<TValue>>

    Transforms a TState into a TValue, if applicable. If the transformation is not applicable, it should return a ValueParserResult with success: false and 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(
    state: DocState<TState>,
    defaultValue?: TValue
    ): DocFragments

    Generates a documentation fragment for this parser, which can be used to describe the parser's usage, description, and default value.

  • getSuggestRuntimeNodes(
    state: TState,
    path: readonly PropertyKey[]
    ): readonly RuntimeNode[]

    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 that map() 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(
    state: TState,
    exec?: ExecutionContext
    ): boolean

    Optional predicate that determines whether completion should be deferred for the given parser state.

  • suggest(
    context: ParserContext<TState>,
    prefix: string
    ): ModeIterable<M, Suggestion>

    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).

I

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).

  • 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.

I

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:

I

Options for creating a port parser that returns a bigint.

  • 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 | ((
    port: bigint,
    min: bigint
    ) => Message)
    ; aboveMaximum?: Message | ((
    port: bigint,
    max: bigint
    ) => Message)
    ; wellKnownNotAllowed?: Message | ((port: bigint) => Message); }

    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 to 1n).

  • type: "bigint"

    Must be set to "bigint" to create a bigint parser.

I

Options for creating a port parser that returns a JavaScript number.

  • 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 | ((
    port: number,
    min: number
    ) => Message)
    ; aboveMaximum?: Message | ((
    port: number,
    max: number
    ) => Message)
    ; wellKnownNotAllowed?: Message | ((port: number) => Message); }

    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 to 1).

  • type: "number"

    The type of value to return.

I

Options for the portRange parser that returns bigint values.

  • allowSingle: boolean

    If true, allows single port without range (e.g., "8080"). The result will have start === end.

  • If true, disallows well-known ports (1-1023). Applied to both start and end ports.

  • errors: { invalidFormat?: Message | ((input: string) => Message); invalidRange?: Message | ((
    start: bigint,
    end: bigint
    ) => Message)
    ; invalidPort?: Message | ((input: string) => Message); belowMinimum?: Message | ((
    port: bigint,
    min: bigint
    ) => Message)
    ; aboveMaximum?: Message | ((
    port: bigint,
    max: bigint
    ) => Message)
    ; wellKnownNotAllowed?: Message | ((port: bigint) => Message); }

    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.

I

Options for the portRange parser that returns number values.

  • allowSingle: boolean

    If true, allows single port without range (e.g., "8080"). The result will have start === end.

  • If true, disallows well-known ports (1-1023). Applied to both start and end ports.

  • errors: { invalidFormat?: Message | ((input: string) => Message); invalidRange?: Message | ((
    start: number,
    end: number
    ) => Message)
    ; invalidPort?: Message | ((input: string) => Message); belowMinimum?: Message | ((
    port: number,
    min: number
    ) => Message)
    ; aboveMaximum?: Message | ((
    port: number,
    max: number
    ) => Message)
    ; wellKnownNotAllowed?: Message | ((port: number) => Message); }

    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.

I

Port range value with bigint type.

  • end: bigint

    Ending port number (inclusive).

  • start: bigint

    Starting port number (inclusive).

I

Port range value with number type.

  • end: number

    Ending port number (inclusive).

  • start: number

    Starting port number (inclusive).

I

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 command or option must 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 command or option must 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: (
    a: DocSection,
    b: DocSection
    ) => number

    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 command or option must be specified.

I

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 or Deno.args on 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 as args, help, or colors.

I

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(
    programName: string,
    args?: readonly string[]
    ): string

    Generates a shell completion script for the given program name.

  • name: string

    The name of the shell.

I

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 least 1. Set to Infinity to show all choices.

  • prefix: string

    Text to display before the choices list.

  • suffix: string

    Text to display after the choices list.

I

Configuration for customizing default value display formatting.

  • prefix: string

    Text to display before the default value.

  • suffix: string

    Text to display after the default value.

I

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 (ignores defaultPort).

  • separator: string

    Separator character(s) between host and port.

I

Socket address value containing host and port.

  • host: string

    The host portion (hostname or IP address).

  • port: number

    The port number.

I

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(
    request?: SourceContextRequest,
    options?: unknown
    ): Promise<Annotations> | Annotations

    Get annotations to inject into parsing.

  • getInternalAnnotations(
    request: SourceContextRequest,
    annotations: Annotations
    ): Annotations | undefined

    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.

I

Options for creating a string parser.

  • errors: { patternMismatch?: Message | ((
    input: string,
    pattern: RegExp
    ) => Message)
    ; }

    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 HOST or NAME.

  • 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 a pattern constraint or downstream map() transform requires a non-empty or specially shaped string.

I

Options for the tuple parser.

  • When true, allows duplicate option names across different parsers. By default (false), duplicate option names cause a construction-time error.

I

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
    | ((
    protocol: string,
    allowedProtocols: readonly string[]
    ) => Message)
    ; }

    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 URL or ENDPOINT.

I

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.

  • 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.

  • When true, only shows the shortest option name for each option instead of showing all aliases separated by /. For example, --verbose/-v becomes just -v.

I

Options for formatting a single UsageTerm.

  • context: "usage" | "doc"

    The rendering context, which determines which hidden visibility values cause terms to be filtered out.

  • A string that separates multiple option names in the formatted output.

I

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
    | ((
    version: number,
    allowedVersions: readonly number[]
    ) => Message)
    ; invalidVariant?: Message | ((input: string) => Message); }

    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 UUID or ID.

  • 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 digits 8, 9, a, or b at position 20 of the UUID string).

I

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 showChoices formatting 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 PORT or FILE.

  • 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.

  • 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.

I

Options for the valueSet function.

  • fallback: string

    A fallback text to return when the values array is empty. When provided and the values array is empty, a Message containing a single text term with this string is returned instead of an empty Message. An empty string produces an empty Message.

  • 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.Locale object, or an array of Intl.Locale objects. 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:

I

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

T
Annotations = Record<symbol, unknown>

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.

T
CombinedDependencyMode<T extends readonly unknown[]> = "async" extends [K in keyof T]: T[K] extends DependencySource<infer M, unknown> ? M : never[number] ? "async" : "sync"

Combines modes from multiple dependency sources. If any source is async, the result is async.

T
CombineMode<M1 extends Mode, M2 extends Mode> = M1 extends "async" ? "async" : M2 extends "async" ? "async" : "sync"

Combines two modes into a single mode. If either mode is async, the result is async.

T
CombineModes<T extends readonly Mode[]> = "async" extends T[number] ? "async" : "sync"

Combines multiple modes into a single mode. If any mode is "async", the result is "async"; otherwise "sync".

T
ContextOptionsParam<
TContexts extends readonly SourceContext<unknown>[],
TValue
>
= keyof ExtractRequiredOptions<TContexts, TValue> extends never ? unknown : Record<string, never> extends ExtractRequiredOptions<TContexts, TValue> ? { readonly contextOptions?: ExtractRequiredOptions<TContexts, TValue>; } : { readonly contextOptions: ExtractRequiredOptions<TContexts, TValue>; }

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.

T
DeferredMap = ReadonlyMap<PropertyKey, DeferredMap | null>

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).

T
DependencyMode<D> = D extends DependencySource<infer M, unknown> ? M : never

Extracts the mode from a DependencySource.

T
DependencyValue<D> = D extends DependencySource<Mode, infer T> ? T : never

Extracts the value type from a DependencySource.

T
DependencyValues<T extends readonly unknown[]> = [K in keyof T]: T[K] extends DependencySource<Mode, infer V> ? V : never

Maps a tuple of DependencySources to a tuple of their value types.

T
DocFragment =
{ readonly type: "entry"; } & DocEntry
| { 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.

T
DocState<TState> =
{ readonly kind: "available"; readonly state: TState; }
| { 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.

T
ExecutionPhase = "parse" | "precomplete" | "resolve" | "complete" | "suggest"

The phase of the execution pipeline.

T
ExtractRequiredOptions<
TContexts extends readonly SourceContext<unknown>[],
TValue
>
= [
TContexts[number] extends SourceContext<infer O> ? O extends void ? never : SubstituteParserValue<O, TValue> : never
] extends [never] ? unknown : UnionToIntersection<
TContexts[number] extends SourceContext<infer O> ? O extends void ? never : SubstituteParserValue<O, TValue> : never
>

Extracts and merges required options from an array of source contexts.

T
HiddenVisibility = boolean | "usage" | "doc" | "help"

Visibility control for parser terms.

T
InferMode<T extends Parser<Mode, unknown, unknown>> = T["mode"]

Infers the execution mode of a Parser.

T
InferValue<T extends Parser<Mode, unknown, unknown>> = T["$valueType"][number]

Infers the result value type of a Parser.

T
Message = readonly MessageTerm[]

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.

T
MessageTerm =
{ readonly type: "text"; readonly text: string; }
| { 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.

T
Mode = "sync" | "async"

Represents the execution mode for parsers.

T
ModeIterable<M extends Mode, T> = M extends "async" ? AsyncIterable<T> : Iterable<T>

Wraps an iterable type based on the execution mode.

T
ModeValue<M extends Mode, T> = M extends "async" ? Promise<T> : T

Wraps a value type based on the execution mode.

T
NonEmptyString = `${any}${string}`

A string type that guarantees at least one character. Used for metavar properties to ensure they are never empty.

T
OptionName =
`--${NonEmptyString}`
| `-${NonEmptyString}`
| `/${NonEmptyString}`
| `+${NonEmptyString}`

Represents the name of a command-line option. There are four types of option syntax:

T
ParserResult<TState> =
{ readonly success: true; readonly next: ParserContext<TState>; readonly consumed: readonly string[]; readonly provisional?: true; }
| { 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.

T
ParserValuePlaceholder = { readonly [parserValuePlaceholderBrand]: "ParserValuePlaceholder"; }

A placeholder type that represents the parser's result value type.

T
PassThroughFormat = "equalsOnly" | "nextToken" | "greedy"

Format options for how passThrough captures options.

T
Result<T> =
{ readonly success: true; readonly value: T; readonly deferred?: true; readonly deferredKeys?: DeferredMap; }
| { 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.

T
SourceContextRequest = SourceContextPhase1Request | SourceContextPhase2Request

Request object passed to SourceContext.getAnnotations and SourceContext.getInternalAnnotations.

T
SubstituteParserValue<T, TValue> = T extends ParserValuePlaceholder ? TValue : T extends (...args: infer A) => infer R ? (...args: [K in keyof A]: SubstituteParserValue<A[K], TValue>) => SubstituteParserValue<R, TValue> : T extends object ? [K in keyof T]: SubstituteParserValue<T[K], TValue> : T

Substitutes ParserValuePlaceholder with the actual parser value type.

T
Suggestion =
{ readonly kind: "literal"; readonly text: string; readonly description?: Message; }
| { 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.

T
Usage = readonly UsageTerm[]

Represents a command-line usage description, which is a sequence of UsageTerm objects. This type is used to describe how a command-line parser expects its input to be structured, including the required and optional components, as well as any exclusive groups of terms.

T
UsageTerm =
{ readonly type: "argument"; readonly metavar: NonEmptyString; readonly hidden?: HiddenVisibility; }
| { 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.

T
Uuid = `${string}-${string}-${string}-${string}-${string}`

Type representing a UUID string.

T
ValueParserResult<T> =
{ readonly success: true; readonly value: T; readonly deferred?: true; readonly deferredKeys?: DeferredMap; }
| { readonly success: false; readonly error: Message; }

Result type returned by ValueParser#parse.

T
ChoiceOptions = ChoiceOptionsString

Options for creating a choice parser.

Variables

v
bash: ShellCompletion

The Bash shell completion generator.

v
fish: ShellCompletion

The fish shell completion generator.

v
nu: ShellCompletion

The Nushell completion generator.

v
pwsh: ShellCompletion

The PowerShell completion generator.

v
zsh: ShellCompletion

The Zsh shell completion generator.

Report package

Please provide a reason for reporting this package. We will review your report and take appropriate action.

Please review the JSR usage policy before submitting a report.

Add Package

deno add jsr:@optique/core

Import symbol

import * as mod from "@optique/core";
or

Import directly with a jsr specifier

import * as mod from "jsr:@optique/core";