import { NonEmptyString, ensureNonEmptyString, isNonEmptyString } from "./nonempty.js"; import { Message } from "./message.js"; import { Mode, ModeIterable, ModeValue, Suggestion } from "./internal/parser.js"; //#region src/valueparser.d.ts /** * Interface for parsing CLI option values and arguments. * * A `ValueParser` is responsible for converting string input (typically from * CLI arguments or option values) into strongly-typed values of type {@link T}. * * @template M The execution mode of the parser (`"sync"` or `"async"`). * @template T The type of value this parser produces. * @since 0.9.0 Added the `M` type parameter for sync/async mode support. */ interface ValueParser { /** * The execution mode of this value parser. * * - `"sync"`: The `parse` method returns values directly. * - `"async"`: The `parse` method returns Promises. * * @since 0.9.0 */ readonly mode: M; /** * 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`. */ readonly metavar: NonEmptyString; /** * Parses a string input into a value of type {@link T}. * * @param input The string input to parse * (e.g., the `value` part of `--option=value`). * @returns A result object indicating success or failure with an error * message. In async mode, returns a Promise that resolves to * the result. */ parse(input: string): ModeValue>; /** * Formats a value of type {@link T} into a string representation. * This is useful for displaying the value in help messages or * documentation. * * @param value The value to format. * @returns A string representation of the value. */ format(value: T): string; /** * Normalizes a value of type {@link T} according to this parser's * configuration. This applies the same canonicalization that * {@link parse} would apply (e.g., case conversion, separator * normalization). Built-in implementations delegate to {@link parse} * internally, so values that would fail validation are returned * unchanged rather than being canonicalized. * * When present, combinators like `withDefault()` call this method on * default values so that runtime defaults match the representation * that {@link parse} would produce. * * Parsers that do not apply any normalization during parsing do not * need to implement this method. * * **Limitation:** For dependency-derived value parsers (created via * `deriveFrom()` or `dependency().derive()`), this method uses the * default dependency value to build the inner parser, not the * dependency value resolved during the current parse. This is the * same trade-off that {@link format} makes. As a result, defaults * may not be normalized according to a non-default dependency value. * * @param value The value to normalize. * @returns The normalized value. * @since 1.0.0 */ normalize?(value: T): T; /** * Validates a value of type {@link T} as if it had been parsed from CLI * input, returning either a success result (with the possibly * canonicalized value) or a failure with an error message. * * When present, `option()` and `argument()` use this method to validate * fallback values (e.g. from `bindEnv()`/`bindConfig()`) instead of the * generic `format()`+`parse()` round-trip. Implement it when the * round-trip cannot faithfully express validation for some values, as * with combinators like `firstOf()` whose constituents may produce * overlapping string representations. * * Like {@link normalize}, this method is synchronous regardless of the * parser's mode, so wrappers that spread a sync parser into an async * one inherit it unchanged. * * @param value The value to validate. * @returns A {@link ValueParserResult} indicating success or failure. * @since 1.1.0 */ validate?(value: T): ValueParserResult; /** * Provides completion suggestions for values of this type. * This is optional and used for shell completion functionality. * * @param prefix The current input prefix to complete. * @returns An iterable of suggestion objects. * In async mode, returns an AsyncIterable. * @since 0.6.0 */ suggest?(prefix: string): ModeIterable; /** * 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. * * This field is populated automatically by the {@link choice} function. * * @since 0.10.0 */ readonly choices?: readonly 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 {@link T}. * * The placeholder does not need to be meaningful; it only needs to be * a valid inhabitant of the result type that will not crash downstream * transforms. For example, `string()` uses `""`, `integer()` uses `0`, * and `choice(["a", "b", "c"])` uses `"a"`. * * @since 1.0.0 */ readonly placeholder: T; } /** * Result type returned by {@link ValueParser#parse}. * * This is a discriminated union that represents either a successful parse * with the resulting value, or a failed parse with an error message. * * @template T The type of the successfully parsed value. */ type ValueParserResult = { /** Indicates that the parsing operation was successful. */ readonly success: true; /** The successfully parsed value of type {@link T}. */ readonly value: T; /** * When `true`, indicates that the value is a placeholder stand-in for * a deferred interactive prompt, not a real user-provided value. * Combinators propagate this flag so that the two-phase parsing * facade can strip deferred values before passing them to phase-two * contexts. * * @since 1.0.0 */ readonly deferred?: true; /** * A recursive map describing which property keys in {@link value} hold * deferred placeholder values. Set by `object()`, `tuple()`, `merge()`, * and other combinators. Intentionally not propagated by `map()` because * opaque transforms invalidate the inner key set. Used by the two-phase * facade to selectively replace only deferred fields with `undefined` * while preserving non-deferred fields for phase-two context annotation * collection. * * Each entry maps a property key to either `null` (the entire field is * deferred) or another `DeferredMap` (the field is an object whose own * sub-fields are partially deferred). * * @since 1.0.0 */ readonly deferredKeys?: DeferredMap; } | { /** Indicates that the parsing operation failed. */ readonly success: false; /** The error message describing why the parsing failed. */ readonly error: Message; }; /** * 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). * * @since 1.0.0 */ type DeferredMap = ReadonlyMap; /** * Options for creating a string parser. */ interface StringOptions { /** * 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`. * @default `"STRING"` */ readonly metavar?: NonEmptyString; /** * Optional regular expression pattern that the string must match. * * **Security note**: When using user-defined or complex patterns, be aware * of potential Regular Expression Denial of Service (ReDoS) attacks. * Maliciously crafted input strings can cause exponential backtracking in * vulnerable patterns, leading to high CPU usage. Avoid patterns with * nested quantifiers like `(a+)+` or overlapping alternations. Consider * using tools like [safe-regex](https://www.npmjs.com/package/safe-regex) * to validate patterns before use. */ readonly pattern?: RegExp; /** * 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. * * @since 1.0.0 */ readonly placeholder?: string; /** * Custom error messages for various string parsing failures. * @since 0.5.0 */ readonly errors?: { /** * Custom error message when input doesn't match the pattern. * Can be a static message or a function that receives the input and pattern. * @since 0.5.0 */ patternMismatch?: Message | ((input: string, pattern: RegExp) => Message); }; } /** * Base options for creating a {@link choice} parser. * @since 0.9.0 */ interface ChoiceOptionsBase { /** * 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`. * @default `"TYPE"` */ readonly metavar?: NonEmptyString; } /** * Options for creating a {@link choice} parser with string values. * @since 0.9.0 */ interface ChoiceOptionsString extends ChoiceOptionsBase { /** * 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. * @default `false` */ readonly caseInsensitive?: boolean; /** * Custom error messages for choice parsing failures. * @since 0.5.0 */ readonly errors?: { /** * Custom error message when input doesn't match any of the valid choices. * Can be a static message or a function that receives the input and valid choices. * @since 0.5.0 */ invalidChoice?: Message | ((input: string, choices: readonly string[]) => Message); }; } /** * Options for creating a {@link choice} parser with number values. * Note: `caseInsensitive` is not available for number choices. * @since 0.9.0 */ interface ChoiceOptionsNumber extends ChoiceOptionsBase { /** * Custom error messages for choice parsing failures. * @since 0.9.0 */ readonly errors?: { /** * Custom error message when input doesn't match any of the valid choices. * Can be a static message or a function that receives the input and valid choices. * @since 0.9.0 */ invalidChoice?: Message | ((input: string, choices: readonly number[]) => Message); }; } /** * Options for creating a {@link choice} parser. * @deprecated Use {@link ChoiceOptionsString} for string choices or * {@link ChoiceOptionsNumber} for number choices. */ type ChoiceOptions = ChoiceOptionsString; /** * A predicate function that checks if an object is a {@link ValueParser}. * @param object The object to check. * @return `true` if the object is a {@link ValueParser}, `false` otherwise. * @throws {TypeError} If the object looks like a value parser (has `mode`, * `metavar`, `parse`, and `format`) but is missing the required * `placeholder` property. */ declare function isValueParser(object: unknown): object is ValueParser; /** * Creates a {@link ValueParser} that accepts one of multiple * string values, so-called enumerated values. * * This parser validates that the input string matches one of * the specified values. If the input does not match any of the values, * it returns an error message indicating the valid options. * @param choices An array of valid string values that this parser can accept. * @param options Configuration options for the choice parser. * @returns A {@link ValueParser} that checks if the input matches one of the * specified values. * @throws {TypeError} If the choices array is empty. * @throws {TypeError} If any choice is an empty string. * @throws {TypeError} If any choice is not a string. * @throws {TypeError} If choices contain a mix of strings and numbers. * @throws {TypeError} If `caseInsensitive` is not a boolean. * @throws {TypeError} If `caseInsensitive` is `true` and multiple choices * normalize to the same lowercase value. */ declare function choice(choices: readonly T[], options?: ChoiceOptionsString): ValueParser<"sync", T>; /** * Creates a {@link ValueParser} that accepts one of multiple * number values. * * This parser validates that the input can be parsed as a number and matches * one of the specified values. If the input does not match any of the values, * it returns an error message indicating the valid options. * @param choices An array of valid number values that this parser can accept. * @param options Configuration options for the choice parser. * @returns A {@link ValueParser} that checks if the input matches one of the * specified values. * @throws {TypeError} If the choices array is empty. * @throws {TypeError} If any choice is not a number. * @throws {TypeError} If any choice is `NaN`. * @throws {TypeError} If choices contain a mix of strings and numbers. * @since 0.9.0 */ declare function choice(choices: readonly T[], options?: ChoiceOptionsNumber): ValueParser<"sync", T>; /** * Validates that an option value, if present, is a boolean. * Throws a {@link TypeError} if the value is defined but not a boolean. * * @template T The type of the options object. * @param options The options object to check. * @param key The key of the option to validate. * @throws {TypeError} If the option value is defined but not a boolean. * @since 1.0.0 */ declare function checkBooleanOption(options: T | undefined, key: keyof T): void; /** * Validates that an option value, if present, is one of the allowed values. * Throws a {@link TypeError} if the value is defined but not in the allowed * list. * * @template T The type of the options object. * @param options The options object to check. * @param key The key of the option to validate. * @param allowed The list of allowed values. * @throws {TypeError} If the option value is defined but not in the allowed * list. * @since 1.0.0 */ declare function checkEnumOption(options: T | undefined, key: keyof T, allowed: readonly string[]): void; /** * Creates a {@link ValueParser} for strings. * * This parser validates that the input is a string and optionally checks * if it matches a specified regular expression pattern. * * **Security note**: When using the `pattern` option with user-defined or * complex patterns, be aware of potential Regular Expression Denial of Service * (ReDoS) attacks. See {@link StringOptions.pattern} for more details. * * @param options Configuration options for the string parser. * @returns A {@link ValueParser} that parses strings according to the * specified options. * @throws {TypeError} If `options.pattern` is provided but is not a * `RegExp` instance. */ declare function string(options?: StringOptions): ValueParser<"sync", string>; interface KeyValueOptionsBase { /** * The metavariable name for this parser. Used in help messages to * indicate the expected key–value shape. * @default `"KEY=VALUE"` with the configured separator. */ readonly metavar?: NonEmptyString; /** * The separator between key and value. * @default `"="` */ readonly separator?: string; /** * If `true`, accepts an empty key before the separator. * @default `false` */ readonly allowEmptyKey?: boolean; /** * If `true`, accepts an empty value after the separator. * @default `true` */ readonly allowEmptyValue?: boolean; /** * Chooses which separator occurrence is used when input contains the * separator more than once. * @default `"first"` */ readonly split?: "first" | "last"; /** * Custom error messages for key–value parsing failures. * @since 1.1.0 */ readonly errors?: { /** * Custom error when the input does not contain the separator. */ readonly missingSeparator?: Message | ((input: string, separator: string) => Message); /** * Custom error when the key side is empty and empty keys are disabled. */ readonly emptyKey?: Message | ((input: string) => Message); /** * Custom error when the value side is empty and empty values are disabled. */ readonly emptyValue?: Message | ((input: string) => Message); /** * Custom error wrapper for key parser failures. */ readonly invalidKey?: Message | ((error: Message) => Message); /** * Custom error wrapper for value parser failures. */ readonly invalidValue?: Message | ((error: Message) => Message); }; } type IsDefaultString = [T] extends [string] ? [string] extends [T] ? true : false : false; type KeyValueKeyOption = IsDefaultString extends true ? { /** * Parser used to validate and transform the key side. * @default `string({ placeholder: "KEY" })` */ readonly key?: ValueParser<"sync", K>; } : { /** * Parser used to validate and transform the key side. * @default `string({ placeholder: "KEY" })` */ readonly key: ValueParser<"sync", K>; }; type KeyValueValueOption = IsDefaultString extends true ? { /** * Parser used to validate and transform the value side. * @default `string()` */ readonly value?: ValueParser<"sync", V>; } : { /** * Parser used to validate and transform the value side. * @default `string()` */ readonly value: ValueParser<"sync", V>; }; /** * Options for creating a {@link keyValue} parser. * * The default key and value parsers produce strings. If {@link K} or * {@link V} is anything other than the default `string` type, the * corresponding child parser is required so the option object cannot promise * a type that the default parser would not produce. * * @template K The parsed key type. * @template V The parsed value type. * @since 1.1.0 */ type KeyValueOptions = KeyValueOptionsBase & KeyValueKeyOption & KeyValueValueOption; type KeyValueOptionsInput = KeyValueOptionsBase & { readonly key?: ValueParser<"sync", unknown>; readonly value?: ValueParser<"sync", unknown>; }; type KeyValueKeyType = Options extends { readonly key: ValueParser<"sync", infer K>; } ? K : string; type KeyValueValueType = Options extends { readonly value: ValueParser<"sync", infer V>; } ? V : string; type KeyValueResultType = Options extends KeyValueOptionsInput ? readonly [KeyValueKeyType, KeyValueValueType] : readonly [string, string]; /** * Creates a value parser for strings shaped like `KEY=VALUE`. * * The default parser splits on the first `=`, rejects empty keys, allows * empty values, and returns a readonly `[key, value]` tuple. Custom key and * value parsers can narrow or transform either side while preserving the * inferred tuple type. * * @template Options The option object type used to infer child parser results. * @param options Configuration options for the key–value parser. * @returns A sync value parser producing readonly key–value tuples. * @throws {TypeError} If `separator` or `metavar` is empty, if * `allowEmptyKey` or `allowEmptyValue` is not a boolean, if `split` is not * `"first"` or `"last"`, or if `key` or `value` is not a sync value parser. * @since 1.1.0 */ declare function keyValue(): ValueParser<"sync", readonly [string, string]>; declare function keyValue(options: Options): ValueParser<"sync", KeyValueResultType>; /** * Options for creating an integer parser that returns a JavaScript `number`. * * This interface is used when you want to parse integers as regular JavaScript * numbers (which are safe up to `Number.MAX_SAFE_INTEGER`). */ interface IntegerOptionsNumber { /** * The type of integer to parse. * @default `"number"` */ readonly type?: "number"; /** * 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`. * @default `"INTEGER"` */ readonly metavar?: NonEmptyString; /** * Minimum allowed value (inclusive). If not specified, * no minimum is enforced. */ readonly min?: number; /** * Maximum allowed value (inclusive). If not specified, * no maximum is enforced. */ readonly max?: 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. * * @since 1.0.0 */ readonly placeholder?: number; /** * Custom error messages for integer parsing failures. * @since 0.5.0 */ readonly errors?: { /** * Custom error message when input is not a valid integer. * Can be a static message or a function that receives the input. * @since 0.5.0 */ invalidInteger?: Message | ((input: string) => Message); /** * Custom error message when integer is outside the safe integer range * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`). * Can be a static message or a function that receives the input string. * @since 1.0.0 */ unsafeInteger?: Message | ((input: string) => Message); /** * Custom error message when integer is below minimum value. * Can be a static message or a function that receives the value and minimum. * @since 0.5.0 */ belowMinimum?: Message | ((value: number, min: number) => Message); /** * Custom error message when integer is above maximum value. * Can be a static message or a function that receives the value and maximum. * @since 0.5.0 */ aboveMaximum?: Message | ((value: number, max: number) => Message); }; } /** * Options for creating an integer parser that returns a `bigint`. * * This interface is used when you need to parse very large integers that * exceed JavaScript's safe integer range. */ interface IntegerOptionsBigInt { /** Must be set to `"bigint"` to create a `bigint` parser. */ readonly type: "bigint"; /** * 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`. * @default `"INTEGER"` */ readonly metavar?: NonEmptyString; /** * Minimum allowed value (inclusive). If not specified, * no minimum is enforced. */ readonly min?: bigint; /** * Maximum allowed value (inclusive). If not specified, * no maximum is enforced. */ readonly max?: 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. * * @since 1.0.0 */ readonly placeholder?: bigint; /** * Custom error messages for bigint integer parsing failures. * @since 0.5.0 */ readonly errors?: { /** * Custom error message when input is not a valid integer. * Can be a static message or a function that receives the input. * @since 0.5.0 */ invalidInteger?: Message | ((input: string) => Message); /** * Custom error message when integer is below minimum value. * Can be a static message or a function that receives the value and minimum. * @since 0.5.0 */ belowMinimum?: Message | ((value: bigint, min: bigint) => Message); /** * Custom error message when integer is above maximum value. * Can be a static message or a function that receives the value and maximum. * @since 0.5.0 */ aboveMaximum?: Message | ((value: bigint, max: bigint) => Message); }; } /** * Creates a ValueParser for integers that returns JavaScript numbers. * * @param options Configuration options for the integer parser. * @returns A {@link ValueParser} that parses strings into numbers. */ declare function integer(options?: IntegerOptionsNumber): ValueParser<"sync", number>; /** * Creates a ValueParser for integers that returns `bigint` values. * * @param options Configuration options for the `bigint` parser. * @returns A {@link ValueParser} that parses strings into `bigint` values. */ declare function integer(options: IntegerOptionsBigInt): ValueParser<"sync", bigint>; /** * Options for creating a {@link float} parser. */ interface FloatOptions { /** * 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`. * @default `"NUMBER"` */ readonly metavar?: NonEmptyString; /** * Minimum allowed value (inclusive). If not specified, * no minimum is enforced. */ readonly min?: number; /** * Maximum allowed value (inclusive). If not specified, * no maximum is enforced. */ readonly max?: number; /** * 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. * @default `false` */ readonly allowNaN?: 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. * @default `false` */ readonly allowInfinity?: boolean; /** * 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. * * @since 1.0.0 */ readonly placeholder?: number; /** * Custom error messages for float parsing failures. * @since 0.5.0 */ readonly errors?: { /** * Custom error message when input is not a valid number. * Can be a static message or a function that receives the input. * @since 0.5.0 */ invalidNumber?: Message | ((input: string) => Message); /** * Custom error message when number is below minimum value. * Can be a static message or a function that receives the value and minimum. * @since 0.5.0 */ belowMinimum?: Message | ((value: number, min: number) => Message); /** * Custom error message when number is above maximum value. * Can be a static message or a function that receives the value and maximum. * @since 0.5.0 */ aboveMaximum?: Message | ((value: number, max: number) => Message); }; } /** * Creates a {@link ValueParser} for floating-point numbers. * * This parser validates that the input is a valid floating-point number * and optionally enforces minimum and maximum value constraints. * @param options Configuration options for the float parser. * @returns A {@link ValueParser} that parses strings into floating-point * numbers. */ declare function float(options?: FloatOptions): ValueParser<"sync", number>; /** * A canonical file size unit string. SI units use powers of 1 000 by * default; IEC units always use powers of 1 024. * @since 1.1.0 */ type FileSizeUnit = "B" | "KB" | "MB" | "GB" | "TB" | "PB" | "EB" | "KiB" | "MiB" | "GiB" | "TiB" | "PiB" | "EiB"; /** * Options for creating a {@link fileSize} parser that returns `number`. * @since 1.1.0 */ interface FileSizeOptionsNumber { /** * The return type. Defaults to `"number"`. * @default `"number"` */ readonly type?: "number"; /** * The metavariable name for this parser. Used in help messages to * indicate what kind of value this parser expects. * @default `"SIZE"` */ readonly metavar?: NonEmptyString; /** * If `true`, negative byte values are accepted. Most size-related CLI * options do not accept negative values, so this defaults to `false`. * @default `false` */ readonly allowNegative?: boolean; /** * The unit to assume when the input contains only a number with no unit * suffix (e.g., `"100"` with `defaultUnit: "MB"` → 100 000 000 bytes). * When this option is absent, a bare number without a unit is rejected. */ readonly defaultUnit?: FileSizeUnit; /** * When `true`, SI suffixes (`KB`, `MB`, `GB`, …) are interpreted as * binary powers of 1 024 rather than decimal powers of 1 000. This * matches a widespread but technically incorrect convention where * "1 KB" means 1 024 bytes. IEC suffixes (`KiB`, `MiB`, …) are * unaffected by this option. * * @default `false` * @since 1.1.0 */ readonly siAsBinary?: boolean; /** * A custom placeholder value used during deferred prompt resolution. * @default `0` * @since 1.1.0 */ readonly placeholder?: number; /** * Custom error messages for file size parsing failures. * @since 1.1.0 */ readonly errors?: { /** * Custom error message when the input is not a valid file size string. * Can be a static message or a function that receives the raw input. */ readonly invalidFormat?: Message | ((input: string) => Message); /** * Custom error message when a negative value is provided but * {@link FileSizeOptionsNumber.allowNegative} is `false`. * Can be a static message or a function that receives the byte value. */ readonly negativeNotAllowed?: Message | ((value: number) => Message); }; } /** * Options for creating a {@link fileSize} parser that returns `bigint`. * Use this when byte counts may exceed `Number.MAX_SAFE_INTEGER` (roughly * 9 PB), for example when working with EB/EiB-range values. * @since 1.1.0 */ interface FileSizeOptionsBigInt { /** * Must be set to `"bigint"` to select bigint output. */ readonly type: "bigint"; /** * The metavariable name for this parser. Used in help messages to * indicate what kind of value this parser expects. * @default `"SIZE"` */ readonly metavar?: NonEmptyString; /** * If `true`, negative byte values are accepted. * @default `false` */ readonly allowNegative?: boolean; /** * The unit to assume when the input contains only a number with no unit * suffix. When absent, a bare number is rejected. */ readonly defaultUnit?: FileSizeUnit; /** * When `true`, SI suffixes (`KB`, `MB`, `GB`, …) are interpreted as * binary powers of 1 024 rather than decimal powers of 1 000. * @default `false` * @since 1.1.0 */ readonly siAsBinary?: boolean; /** * A custom placeholder value used during deferred prompt resolution. * @default `0n` * @since 1.1.0 */ readonly placeholder?: bigint; /** * Custom error messages for file size parsing failures. * @since 1.1.0 */ readonly errors?: { /** * Custom error message when the input is not a valid file size string. * Can be a static message or a function that receives the raw input. */ readonly invalidFormat?: Message | ((input: string) => Message); /** * Custom error message when a negative value is provided but * {@link FileSizeOptionsBigInt.allowNegative} is `false`. * Can be a static message or a function that receives the byte value. */ readonly negativeNotAllowed?: Message | ((value: bigint) => Message); }; } /** * Options for creating a {@link fileSize} parser. * @since 1.1.0 */ type FileSizeOptions = FileSizeOptionsNumber | FileSizeOptionsBigInt; /** * Creates a {@link ValueParser} for human-readable file/data size strings * that returns a `number` byte count. * * @param options Configuration options for the file size parser. * @returns A {@link ValueParser} that parses file size strings into `number` * byte counts. * @throws {TypeError} If {@link FileSizeOptionsNumber.metavar} is an empty * string, if {@link FileSizeOptionsNumber.allowNegative} or * {@link FileSizeOptionsNumber.siAsBinary} is not a boolean, or if * {@link FileSizeOptionsNumber.defaultUnit} is not a valid * {@link FileSizeUnit}. * @since 1.1.0 */ declare function fileSize(options?: FileSizeOptionsNumber): ValueParser<"sync", number>; /** * Creates a {@link ValueParser} for human-readable file/data size strings * that returns a `bigint` byte count. Use this when byte counts may exceed * `Number.MAX_SAFE_INTEGER` (~9 PB), for example with EB/EiB-range values. * * @param options Configuration options for the file size parser. * @returns A {@link ValueParser} that parses file size strings into `bigint` * byte counts. * @throws {TypeError} If {@link FileSizeOptionsBigInt.metavar} is an empty * string, if {@link FileSizeOptionsBigInt.allowNegative} or * {@link FileSizeOptionsBigInt.siAsBinary} is not a boolean, or if * {@link FileSizeOptionsBigInt.defaultUnit} is not a valid * {@link FileSizeUnit}. * @since 1.1.0 */ declare function fileSize(options: FileSizeOptionsBigInt): ValueParser<"sync", bigint>; /** * A structured CSS color value with normalized RGBA components. * @since 1.1.0 */ interface Color { /** Red channel, 0–255. */ readonly r: number; /** Green channel, 0–255. */ readonly g: number; /** Blue channel, 0–255. */ readonly b: number; /** Alpha channel, 0–1 (1 = fully opaque). */ readonly a: number; } /** * The CSS color notation a {@link color} parser accepts. * @since 1.1.0 */ type ColorFormat = "hex" | "rgb" | "hsl" | "named"; /** * Options for creating a {@link color} value parser. * @since 1.1.0 */ interface ColorOptions { /** * The metavariable name for this parser. Used in help messages to * indicate what kind of value this parser expects. * @default `"COLOR"` */ readonly metavar?: NonEmptyString; /** * Restricts which CSS color notations are accepted. Defaults to all * four notations: `"hex"`, `"rgb"`, `"hsl"`, and `"named"`. * @default all formats */ readonly formats?: readonly ColorFormat[]; /** * A custom placeholder value used during deferred prompt resolution. * @default `{ r: 0, g: 0, b: 0, a: 1 }` * @since 1.1.0 */ readonly placeholder?: Color; /** * Custom error messages for color parsing failures. * @since 1.1.0 */ readonly errors?: { /** * Custom error message when the input is not a valid CSS color string. * Can be a static message or a function that receives the raw input. */ readonly invalidFormat?: Message | ((input: string) => Message); }; } /** * Creates a value parser that accepts CSS color strings and returns a * structured {@link Color} object with normalized RGBA components. * * Supported input notations by default: * - Hex: `#rgb`, `#rrggbb`, `#rgba`, `#rrggbbaa` * - RGB: `rgb(r, g, b)`, `rgba(r, g, b, a)` * - HSL: `hsl(h, s%, l%)`, `hsla(h, s%, l%, a)` * - Named: all 148 CSS Level 4 named colors (e.g., `red`, `rebeccapurple`) * * The `format()` method always outputs canonical lowercase hex * (`#rrggbb` when fully opaque, `#rrggbbaa` otherwise). * * @param options Configuration options for the parser. * @returns A sync value parser producing {@link Color} objects. * @throws {TypeError} If {@link ColorOptions.metavar} is an empty string, or * if {@link ColorOptions.formats} contains an invalid format name. * @throws {RangeError} If {@link ValueParser.format} is called with a * {@link Color} whose `r`, `g`, or `b` channel is not an integer in * 0–255, or whose `a` channel is not a finite number in 0–1. * @since 1.1.0 */ declare function color(options?: ColorOptions): ValueParser<"sync", Color>; /** * Options for creating a {@link url} parser. */ interface UrlOptions { /** * 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`. * @default `"URL"` */ readonly metavar?: NonEmptyString; /** * 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. */ readonly allowedProtocols?: readonly string[]; /** * Custom error messages for URL parsing failures. * @since 0.5.0 */ readonly errors?: { /** * Custom error message when input is not a valid URL. * Can be a static message or a function that receives the input. * @since 0.5.0 */ invalidUrl?: Message | ((input: string) => Message); /** * Custom error message when URL protocol is not allowed. * Can be a static message or a function that receives the protocol and allowed protocols. * @since 0.5.0 */ disallowedProtocol?: Message | ((protocol: string, allowedProtocols: readonly string[]) => Message); }; } /** * Creates a {@link ValueParser} for URL values. * * This parser validates that the input is a well-formed URL and optionally * restricts the allowed protocols. The parsed result is a JavaScript `URL` * object. * @param options Configuration options for the URL parser. * @returns A {@link ValueParser} that converts string input to `URL` objects. * @throws {TypeError} If any `allowedProtocols` entry is not a valid protocol * string ending with a colon (e.g., `"https:"`). */ declare function url(options?: UrlOptions): ValueParser<"sync", URL>; /** * Options for creating a {@link locale} parser. */ interface LocaleOptions { /** * 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`. * @default `"LOCALE"` */ readonly metavar?: NonEmptyString; /** * Custom error messages for locale parsing failures. * @since 0.5.0 */ readonly errors?: { /** * Custom error message when input is not a valid locale identifier. * Can be a static message or a function that receives the input. * @since 0.5.0 */ invalidLocale?: Message | ((input: string) => Message); }; } /** * Creates a {@link ValueParser} for locale values. * * This parser validates that the input is a well-formed locale identifier * according to the Unicode Locale Identifier standard (BCP 47). * The parsed result is a JavaScript `Intl.Locale` object. * @param options Configuration options for the locale parser. * @returns A {@link ValueParser} that converts string input to `Intl.Locale` * objects. */ declare function locale(options?: LocaleOptions): ValueParser<"sync", Intl.Locale>; /** * Type representing a UUID string. * * A UUID is a 36-character string in the format: * `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` * where each `x` is a hexadecimal digit. */ type Uuid = `${string}-${string}-${string}-${string}-${string}`; /** * Options for creating a {@link uuid} parser. */ interface UuidOptions { /** * 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`. * @default `"UUID"` */ readonly metavar?: NonEmptyString; /** * 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 {@link strict} option. * * [RFC 9562]: https://www.rfc-editor.org/rfc/rfc9562 */ readonly allowedVersions?: readonly number[]; /** * 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). * * The nil UUID (`00000000-0000-0000-0000-000000000000`) and max UUID * (`ffffffff-ffff-ffff-ffff-ffffffffffff`) are accepted as special * standard values regardless of this setting. * * When `false`, the parser only validates the UUID format without * checking version or variant fields. * * When {@link allowedVersions} is provided, it takes precedence over the * strict version check, but variant bit validation still applies if * `strict` is `true`. * * [RFC 9562]: https://www.rfc-editor.org/rfc/rfc9562 * @default true * @since 1.0.0 */ readonly strict?: boolean; /** * Custom error messages for UUID parsing failures. * @since 0.5.0 */ readonly errors?: { /** * Custom error message when input is not a valid UUID format. * Can be a static message or a function that receives the input. * @since 0.5.0 */ invalidUuid?: Message | ((input: string) => Message); /** * Custom error message when UUID version is not allowed. * Can be a static message or a function that receives the version and allowed versions. * @since 0.5.0 */ disallowedVersion?: Message | ((version: number, allowedVersions: readonly number[]) => Message); /** * Custom error message when UUID variant bits are not RFC 9562 compliant. * Can be a static message or a function that receives the input. * @since 1.0.0 */ invalidVariant?: Message | ((input: string) => Message); }; } /** * Creates a {@link ValueParser} for UUID values. * * This parser validates that the input is a well-formed UUID string in the * standard format: `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` where each `x` * is a hexadecimal digit. * * By default, the parser enforces strict [RFC 9562] validation: it requires * a standardized version digit (1 through 8) and the RFC 9562 variant bits * (`10xx`). The nil and max UUIDs are accepted as special standard values. * Set `strict: false` to disable the default RFC 9562 version/variant * checks. An explicit {@link UuidOptions.allowedVersions} list still * constrains the version nibble even in lenient mode. * * [RFC 9562]: https://www.rfc-editor.org/rfc/rfc9562 * @param options Configuration options for the UUID parser. * @returns A {@link ValueParser} that converts string input to {@link Uuid} * strings. * @throws {TypeError} If any element of * {@link UuidOptions.allowedVersions} is not an integer. * @throws {RangeError} If any element of * {@link UuidOptions.allowedVersions} is outside the range 1 to 8. */ declare function uuid(options?: UuidOptions): ValueParser<"sync", Uuid>; /** * Options for creating a port parser that returns a JavaScript `number`. */ interface PortOptionsNumber { /** * The type of value to return. * @default `"number"` */ readonly type?: "number"; /** * 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`. * @default `"PORT"` */ readonly metavar?: NonEmptyString; /** * Minimum allowed port number (inclusive). * @default `1` */ readonly min?: number; /** * Maximum allowed port number (inclusive). * @default `65535` */ readonly max?: number; /** * If `true`, disallows well-known ports (1-1023). * These ports typically require root/administrator privileges on most systems. * @default `false` */ readonly disallowWellKnown?: boolean; /** * A custom placeholder value used during deferred prompt resolution. * Defaults to `min` (which itself defaults to `1`). * * @since 1.0.0 */ readonly placeholder?: number; /** * Custom error messages for port parsing failures. * @since 0.10.0 */ readonly errors?: { /** * Custom error message when input is not a valid port number. * Can be a static message or a function that receives the input. * @since 0.10.0 */ invalidPort?: Message | ((input: string) => Message); /** * Custom error message when port is below minimum value. * Can be a static message or a function that receives the port and minimum. * @since 0.10.0 */ belowMinimum?: Message | ((port: number, min: number) => Message); /** * Custom error message when port is above maximum value. * Can be a static message or a function that receives the port and maximum. * @since 0.10.0 */ aboveMaximum?: Message | ((port: number, max: number) => Message); /** * Custom error message when well-known port is used but disallowed. * Can be a static message or a function that receives the port. * @since 0.10.0 */ wellKnownNotAllowed?: Message | ((port: number) => Message); }; } /** * Options for creating a port parser that returns a `bigint`. */ interface PortOptionsBigInt { /** * Must be set to `"bigint"` to create a `bigint` parser. */ readonly type: "bigint"; /** * 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`. * @default `"PORT"` */ readonly metavar?: NonEmptyString; /** * Minimum allowed port number (inclusive). * @default `1n` */ readonly min?: bigint; /** * Maximum allowed port number (inclusive). * @default `65535n` */ readonly max?: bigint; /** * If `true`, disallows well-known ports (1-1023). * These ports typically require root/administrator privileges on most systems. * @default `false` */ readonly disallowWellKnown?: boolean; /** * A custom placeholder value used during deferred prompt resolution. * Defaults to `min` (which itself defaults to `1n`). * * @since 1.0.0 */ readonly placeholder?: bigint; /** * Custom error messages for port parsing failures. * @since 0.10.0 */ readonly errors?: { /** * Custom error message when input is not a valid port number. * Can be a static message or a function that receives the input. * @since 0.10.0 */ invalidPort?: Message | ((input: string) => Message); /** * Custom error message when port is below minimum value. * Can be a static message or a function that receives the port and minimum. * @since 0.10.0 */ belowMinimum?: Message | ((port: bigint, min: bigint) => Message); /** * Custom error message when port is above maximum value. * Can be a static message or a function that receives the port and maximum. * @since 0.10.0 */ aboveMaximum?: Message | ((port: bigint, max: bigint) => Message); /** * Custom error message when well-known port is used but disallowed. * Can be a static message or a function that receives the port. * @since 0.10.0 */ wellKnownNotAllowed?: Message | ((port: bigint) => Message); }; } /** * Creates a ValueParser for TCP/UDP port numbers that returns JavaScript numbers. * * @param options Configuration options for the port parser. * @returns A {@link ValueParser} that parses strings into port numbers. * @since 0.10.0 */ declare function port(options?: PortOptionsNumber): ValueParser<"sync", number>; /** * Creates a ValueParser for TCP/UDP port numbers that returns `bigint` values. * * @param options Configuration options for the `bigint` port parser. * @returns A {@link ValueParser} that parses strings into `bigint` port values. * @since 0.10.0 */ declare function port(options: PortOptionsBigInt): ValueParser<"sync", bigint>; /** * Options for the {@link ipv4} value parser. * * @since 0.10.0 */ interface Ipv4Options { /** * The metavariable name for this parser. * * @default "IPV4" */ readonly metavar?: NonEmptyString; /** * If `true`, allows private IP ranges (10.0.0.0/8, 172.16.0.0/12, * 192.168.0.0/16). * * @default true */ readonly allowPrivate?: boolean; /** * If `true`, allows loopback addresses (127.0.0.0/8). * * @default true */ readonly allowLoopback?: boolean; /** * If `true`, allows link-local addresses (169.254.0.0/16). * * @default true */ readonly allowLinkLocal?: boolean; /** * If `true`, allows multicast addresses (224.0.0.0/4). * * @default true */ readonly allowMulticast?: boolean; /** * If `true`, allows the broadcast address (255.255.255.255). * * @default true */ readonly allowBroadcast?: boolean; /** * If `true`, allows the zero address (0.0.0.0). * * @default true */ readonly allowZero?: boolean; /** * Custom error messages for IPv4 parsing failures. */ readonly errors?: { /** * Custom error message when input is not a valid IPv4 address. * Can be a static message or a function that receives the input. */ invalidIpv4?: Message | ((input: string) => Message); /** * Custom error message when private IP is used but disallowed. * Can be a static message or a function that receives the IP. */ privateNotAllowed?: Message | ((ip: string) => Message); /** * Custom error message when loopback IP is used but disallowed. * Can be a static message or a function that receives the IP. */ loopbackNotAllowed?: Message | ((ip: string) => Message); /** * Custom error message when link-local IP is used but disallowed. * Can be a static message or a function that receives the IP. */ linkLocalNotAllowed?: Message | ((ip: string) => Message); /** * Custom error message when multicast IP is used but disallowed. * Can be a static message or a function that receives the IP. */ multicastNotAllowed?: Message | ((ip: string) => Message); /** * Custom error message when broadcast IP is used but disallowed. * Can be a static message or a function that receives the IP. */ broadcastNotAllowed?: Message | ((ip: string) => Message); /** * Custom error message when zero IP is used but disallowed. * Can be a static message or a function that receives the IP. */ zeroNotAllowed?: Message | ((ip: string) => Message); }; } /** * Creates a value parser for IPv4 addresses. * * This parser validates IPv4 addresses in dotted-decimal notation (e.g., * "192.168.1.1") and provides options to filter specific IP address types * such as private, loopback, link-local, multicast, broadcast, and zero * addresses. * * @param options The parser options. * @returns A value parser for IPv4 addresses. * @throws {TypeError} If the metavar is an empty string. * @since 0.10.0 * @example * ```typescript * import { ipv4 } from "@optique/core/valueparser"; * * // Basic IPv4 parser (allows all types) * const address = ipv4(); * * // Public IPs only (no private/loopback) * const publicIp = ipv4({ * allowPrivate: false, * allowLoopback: false * }); * * // Server binding (allow 0.0.0.0 and private IPs) * const bindAddress = ipv4({ * allowZero: true, * allowPrivate: true * }); * ``` */ declare function ipv4(options?: Ipv4Options): ValueParser<"sync", string>; /** * Options for the {@link hostname} parser. * * @since 0.10.0 */ interface HostnameOptions { /** * The metavariable name for this parser. * @default "HOST" */ readonly metavar?: NonEmptyString; /** * If `true`, allows wildcard hostnames (e.g., "*.example.com"). * @default false */ readonly allowWildcard?: boolean; /** * If `true`, allows underscores in hostnames. * Technically invalid per RFC 1123, but commonly used in some contexts * (e.g., service discovery records like "_service.example.com"). * @default false */ readonly allowUnderscore?: boolean; /** * If `true`, allows "localhost" as a hostname. * @default true */ readonly allowLocalhost?: boolean; /** * A custom placeholder value used during deferred prompt resolution. * Override when `allowLocalhost` or other constraints reject the default. * * @since 1.0.0 */ readonly placeholder?: string; /** * Maximum hostname length in characters. * @default 253 */ readonly maxLength?: number; /** * Custom error messages for hostname parsing failures. */ readonly errors?: { /** * Custom error message when input is not a valid hostname. * Can be a static message or a function that receives the input. */ invalidHostname?: Message | ((input: string) => Message); /** * Custom error message when wildcard hostname is used but disallowed. * Can be a static message or a function that receives the hostname. */ wildcardNotAllowed?: Message | ((hostname: string) => Message); /** * Custom error message when underscore is used but disallowed. * Can be a static message or a function that receives the hostname. */ underscoreNotAllowed?: Message | ((hostname: string) => Message); /** * Custom error message when "localhost" is used but disallowed. * Can be a static message or a function that receives the hostname. */ localhostNotAllowed?: Message | ((hostname: string) => Message); /** * Custom error message when hostname is too long. * Can be a static message or a function that receives the hostname and max length. */ tooLong?: Message | ((hostname: string, maxLength: number) => Message); }; } /** * Creates a value parser for DNS hostnames. * * Validates hostnames according to RFC 1123: * - Labels separated by dots * - Each label: 1-63 characters * - Labels can contain alphanumeric characters and hyphens * - Labels cannot start or end with a hyphen * - Total length ≤ 253 characters (default) * - Dotted all-numeric strings (e.g., `192.168.0.1`) are rejected as they * resemble IPv4 addresses rather than DNS hostnames * * @param options - Options for hostname validation. * @returns A value parser for hostnames. * @throws {TypeError} If `allowWildcard`, `allowUnderscore`, or * `allowLocalhost` is not a boolean. * @throws {RangeError} If `maxLength` is not a positive integer. * @since 0.10.0 * * @example * ```typescript * import { hostname } from "@optique/core/valueparser"; * * // Basic hostname parser * const host = hostname(); * * // Allow wildcards for certificate validation * const domain = hostname({ allowWildcard: true }); * * // Reject localhost * const remoteHost = hostname({ allowLocalhost: false }); * ``` */ declare function hostname(options?: HostnameOptions): ValueParser<"sync", string>; /** * Options for the {@link email} parser. * * @since 0.10.0 */ interface EmailOptions { /** * The metavariable name for this parser. * @default "EMAIL" */ readonly metavar?: NonEmptyString; /** * If `true`, allows multiple email addresses separated by commas. * Returns an array of email addresses. * @default false */ readonly allowMultiple?: boolean; /** * If `true`, allows display names in format "Name ". * When enabled, returns the email address only (strips display name). * @default false */ readonly allowDisplayName?: 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. * @default false */ readonly lowercase?: boolean; /** * List of allowed email domains (e.g., ["example.com", "test.org"]). * If specified, only emails from these domains are accepted. */ readonly allowedDomains?: readonly string[]; /** * Override the default placeholder value used for deferred parsing. * When not specified, the placeholder is derived from the first entry in * {@link allowedDomains} (or `"example.com"` when no domains are set). * @since 1.0.0 */ readonly placeholder?: string | readonly string[]; /** * Custom error messages for email parsing failures. */ readonly errors?: { /** * Custom error message when input is not a valid email address. * Can be a static message or a function that receives the input. */ invalidEmail?: Message | ((input: string) => Message); /** * Custom error message when email domain is not allowed. * Can be a static message or a function that receives the email and allowed domains. */ domainNotAllowed?: Message | ((email: string, allowedDomains: readonly string[]) => Message); }; } /** * Creates a value parser for email addresses according to RFC 5322 (simplified). * * Validates email addresses with support for: * - Simplified RFC 5322 addr-spec format (local-part@domain) * - Local part: alphanumeric, dots, hyphens, underscores, plus signs * - Quoted strings in local part * - Display names (when `allowDisplayName` is enabled) * - Multiple addresses (when `allowMultiple` is enabled) * - Domain filtering (when `allowedDomains` is specified) * * @param options - Options for email validation. * @returns A value parser for email addresses. * @throws {TypeError} If any `allowedDomains` entry is not a string, has * leading/trailing whitespace, starts with `"@"`, is empty, lacks a dot, * has invalid hostname label syntax, or is an IPv4-like dotted-quad. * @throws {TypeError} If `placeholder` type does not match `allowMultiple` * mode (string for single, array for multiple). * @since 0.10.0 * * @example * ```typescript * import { email } from "@optique/core/valueparser"; * * // Basic email parser * const userEmail = email(); * * // Multiple emails * const recipients = email({ allowMultiple: true }); * * // With display names * const from = email({ allowDisplayName: true }); * * // Restrict to company domains * const workEmail = email({ allowedDomains: ["company.com"] }); * ``` */ declare function email(options: EmailOptions & { allowMultiple: true; }): ValueParser<"sync", readonly string[]>; declare function email(options?: EmailOptions): ValueParser<"sync", string>; /** * Socket address value containing host and port. * * @since 0.10.0 */ interface SocketAddressValue { /** * The host portion (hostname or IP address). */ readonly host: string; /** * The port number. */ readonly port: number; } /** * Options for the {@link socketAddress} parser. * * @since 0.10.0 */ interface SocketAddressOptions { /** * The metavariable name for this parser. If not specified, it is derived * from the {@link separator} (e.g., `"HOST:PORT"` for `":"`). */ readonly metavar?: NonEmptyString; /** * Separator character(s) between host and port. * @default ":" */ readonly separator?: string; /** * Default port number if omitted from input. * If not specified, port is required. */ readonly defaultPort?: number; /** * If `true`, requires port to be specified in input * (ignores `defaultPort`). * @default false */ readonly requirePort?: boolean; /** * Options for hostname/IP validation. */ readonly host?: { /** * Type of host to accept. * - `"hostname"`: Accept hostnames only * - `"ip"`: Accept IP addresses only * - `"both"`: Accept both hostnames and IP addresses * @default "both" */ readonly type?: "hostname" | "ip" | "both"; /** * Options for hostname validation (when type is "hostname" or "both"). */ readonly hostname?: Omit; /** * IP version to accept when `type` is `"ip"` or `"both"`. * - `4`: IPv4 only * - `6`: IPv6 only * - `"both"`: Accept both IPv4 and IPv6 * * @default `"both"` unless only the legacy {@link ip} field is set, in * which case the default is `4` to preserve IPv4-only compatibility. * @since 1.1.0 */ readonly version?: 4 | 6 | "both"; /** * Options for IPv4 validation (when type is "ip" or "both"). * This is kept for backwards compatibility; prefer {@link ipv4} for * new code. */ readonly ip?: Omit; /** * Options for IPv4 validation (when type is "ip" or "both"). * * @since 1.1.0 */ readonly ipv4?: Omit; /** * Options for IPv6 validation (when type is "ip" or "both"). * * @since 1.1.0 */ readonly ipv6?: Omit; }; /** * Options for port validation. */ readonly port?: Omit; /** * Custom error messages for socket address parsing failures. */ readonly errors?: { /** * Custom error message when input format is invalid. * Can be a static message or a function that receives the input. */ invalidFormat?: Message | ((input: string) => Message); /** * Custom error message when port is missing but required. * Can be a static message or a function that receives the input. */ missingPort?: Message | ((input: string) => Message); }; } /** * Creates a value parser for socket addresses in "host:port" format. * * Validates socket addresses with support for: * - Hostnames, IPv4 addresses, and IPv6 addresses * - Configurable host:port separator * - Optional default port * - Host type filtering (hostname only, IP only, or both) * - Port range validation * * @param options - Options for socket address validation. * @returns A value parser for socket addresses. * @throws {TypeError} If `separator` is an empty string. * @throws {TypeError} If `separator` contains digit characters, since digits * in the separator would cause ambiguous splitting of port input. * @throws {TypeError} If `host.version` is provided but is not `4`, `6`, or * `"both"`. * @since 0.10.0 * * @example * ```typescript * import { socketAddress } from "@optique/core/valueparser"; * * // Basic socket address parser * const endpoint = socketAddress({ requirePort: true }); * * // With default port * const server = socketAddress({ defaultPort: 80 }); * * // IP addresses only * const bind = socketAddress({ * defaultPort: 8080, * host: { type: "ip" } * }); * ``` */ declare function socketAddress(options?: SocketAddressOptions): ValueParser<"sync", SocketAddressValue>; /** * Port range value with number type. * * @since 0.10.0 */ interface PortRangeValueNumber { /** * Starting port number (inclusive). */ readonly start: number; /** * Ending port number (inclusive). */ readonly end: number; } /** * Port range value with bigint type. * * @since 0.10.0 */ interface PortRangeValueBigInt { /** * Starting port number (inclusive). */ readonly start: bigint; /** * Ending port number (inclusive). */ readonly end: bigint; } /** * Options for the {@link portRange} parser that returns number values. * * @since 0.10.0 */ interface PortRangeOptionsNumber { /** * The type of values to return. * @default "number" */ readonly type?: "number"; /** * The metavariable name for this parser. If not specified, it is derived * from the {@link separator} (e.g., `"PORT-PORT"` for `"-"`). */ readonly metavar?: NonEmptyString; /** * Separator character(s) between start and end ports. * @default "-" */ readonly separator?: string; /** * Minimum allowed port number (inclusive). * Applied to both start and end ports. * @default 1 */ readonly min?: number; /** * Maximum allowed port number (inclusive). * Applied to both start and end ports. * @default 65535 */ readonly max?: number; /** * If `true`, disallows well-known ports (1-1023). * Applied to both start and end ports. * @default false */ readonly disallowWellKnown?: boolean; /** * If `true`, allows single port without range (e.g., "8080"). * The result will have `start === end`. * @default false */ readonly allowSingle?: boolean; /** * Custom error messages for port range parsing failures. */ readonly errors?: { /** * Custom error message when input format is invalid. * Can be a static message or a function that receives the input. */ invalidFormat?: Message | ((input: string) => Message); /** * Custom error message when start port is greater than end port. * Can be a static message or a function that receives start and end. */ invalidRange?: Message | ((start: number, end: number) => Message); /** * Custom error message when port is invalid. * Inherited from PortOptions. */ invalidPort?: Message | ((input: string) => Message); /** * Custom error message when port is below minimum. * Inherited from PortOptions. */ belowMinimum?: Message | ((port: number, min: number) => Message); /** * Custom error message when port is above maximum. * Inherited from PortOptions. */ aboveMaximum?: Message | ((port: number, max: number) => Message); /** * Custom error message when well-known port is not allowed. * Inherited from PortOptions. */ wellKnownNotAllowed?: Message | ((port: number) => Message); }; } /** * Options for the {@link portRange} parser that returns bigint values. * * @since 0.10.0 */ interface PortRangeOptionsBigInt { /** * Must be set to "bigint" to create a bigint parser. */ readonly type: "bigint"; /** * The metavariable name for this parser. If not specified, it is derived * from the {@link separator} (e.g., `"PORT-PORT"` for `"-"`). */ readonly metavar?: NonEmptyString; /** * Separator character(s) between start and end ports. * @default "-" */ readonly separator?: string; /** * Minimum allowed port number (inclusive). * Applied to both start and end ports. * @default 1n */ readonly min?: bigint; /** * Maximum allowed port number (inclusive). * Applied to both start and end ports. * @default 65535n */ readonly max?: bigint; /** * If `true`, disallows well-known ports (1-1023). * Applied to both start and end ports. * @default false */ readonly disallowWellKnown?: boolean; /** * If `true`, allows single port without range (e.g., "8080"). * The result will have `start === end`. * @default false */ readonly allowSingle?: boolean; /** * Custom error messages for port range parsing failures. */ readonly errors?: { /** * Custom error message when input format is invalid. * Can be a static message or a function that receives the input. */ invalidFormat?: Message | ((input: string) => Message); /** * Custom error message when start port is greater than end port. * Can be a static message or a function that receives start and end. */ invalidRange?: Message | ((start: bigint, end: bigint) => Message); /** * Custom error message when port is invalid. * Inherited from PortOptions. */ invalidPort?: Message | ((input: string) => Message); /** * Custom error message when port is below minimum. * Inherited from PortOptions. */ belowMinimum?: Message | ((port: bigint, min: bigint) => Message); /** * Custom error message when port is above maximum. * Inherited from PortOptions. */ aboveMaximum?: Message | ((port: bigint, max: bigint) => Message); /** * Custom error message when well-known port is not allowed. * Inherited from PortOptions. */ wellKnownNotAllowed?: Message | ((port: bigint) => Message); }; } /** * Creates a value parser for port ranges (e.g., "8000-8080"). * * Validates port ranges with support for: * - Custom separator between start and end ports * - Single port mode (when `allowSingle` is enabled) * - Port number or bigint types * - Min/max constraints * - Well-known port restrictions * * @param options - Options for port range validation. * @returns A value parser for port ranges. * @throws {TypeError} If `options.type` is provided but is neither `"number"` * nor `"bigint"`. * @throws {TypeError} If `separator` is an empty string. * @throws {TypeError} If `separator` contains digit characters, since digits * in the separator would cause ambiguous splitting of numeric port input. * @since 0.10.0 * * @example * ```typescript * import { portRange } from "@optique/core/valueparser"; * * // Basic port range parser * const range = portRange(); * * // Allow single port * const flexible = portRange({ allowSingle: true }); * * // Non-privileged ports only * const safe = portRange({ min: 1024 }); * * // Using bigint type * const bigRange = portRange({ type: "bigint" }); * ``` */ declare function portRange(options: PortRangeOptionsBigInt): ValueParser<"sync", PortRangeValueBigInt>; declare function portRange(options?: PortRangeOptionsNumber): ValueParser<"sync", PortRangeValueNumber>; /** * Options for the {@link macAddress} parser. * * @since 0.10.0 */ interface MacAddressOptions { /** * The metavariable name for this parser. * @default "MAC" */ readonly metavar?: NonEmptyString; /** * Separator format to accept. * - `":"`: Colon-separated (e.g., `00:1A:2B:3C:4D:5E`) * - `"-"`: Hyphen-separated (e.g., `00-1A-2B-3C-4D-5E`) * - `"."`: Dot-separated (e.g., `001A.2B3C.4D5E` - Cisco format) * - `"none"`: No separator (e.g., `001A2B3C4D5E`) * - `"any"`: Accept any of the above formats * @default "any" */ readonly separator?: ":" | "-" | "." | "none" | "any"; /** * Case for the output. * - `"preserve"`: Keep input case * - `"upper"`: Convert to uppercase * - `"lower"`: Convert to lowercase * @default "preserve" */ readonly case?: "preserve" | "upper" | "lower"; /** * Output separator format. * If not specified, uses the input separator (or ":" for "any"). * @default undefined (uses input format) */ readonly outputSeparator?: ":" | "-" | "." | "none"; /** * Custom error messages for MAC address parsing failures. */ readonly errors?: { /** * Custom error message when input is not a valid MAC address. * Can be a static message or a function that receives the input. */ invalidMacAddress?: Message | ((input: string) => Message); }; } /** * Creates a value parser for MAC (Media Access Control) addresses. * * Validates MAC-48 addresses (6 octets, 12 hex digits) in various formats: * - Colon-separated: `00:1A:2B:3C:4D:5E` (1–2 hex digits per octet) * - Hyphen-separated: `00-1A-2B-3C-4D-5E` (1–2 hex digits per octet) * - Dot-separated (Cisco): `001A.2B3C.4D5E` (exactly 4 hex digits per group) * - No separator: `001A2B3C4D5E` (exactly 12 hex digits) * * Colon-separated and hyphen-separated formats accept single-digit octets * (e.g., `0:1:2:3:4:5`), which are automatically zero-padded to canonical * two-digit form (e.g., `00:01:02:03:04:05`). * * Returns the MAC address as a formatted string according to `case` and * `outputSeparator` options. * * @param options Configuration options for the MAC address parser. * @returns A parser that validates MAC addresses and returns formatted strings. * @since 0.10.0 * * @example * ```typescript * import { macAddress } from "@optique/core/valueparser"; * * // Accept any format * const mac = macAddress(); * * // Normalize to uppercase colon-separated * const normalizedMac = macAddress({ * outputSeparator: ":", * case: "upper" * }); * ``` */ declare function macAddress(options?: MacAddressOptions): ValueParser<"sync", string>; /** * Options for {@link domain} parser. * * @since 0.10.0 */ interface DomainOptions { /** * The metavariable name for this parser. * * @default "DOMAIN" */ readonly metavar?: NonEmptyString; /** * If `true`, allows subdomains (e.g., "www.example.com"). * If `false`, only accepts root domains (e.g., "example.com"). * * @default true */ readonly allowSubdomains?: boolean; /** * List of allowed top-level domains (e.g., ["com", "org", "net"]). * If specified, only domains with these TLDs are accepted. */ readonly allowedTlds?: readonly string[]; /** * Minimum number of domain labels (parts separated by dots). * * @default 2 */ readonly minLabels?: number; /** * Maximum domain length in characters. * @default 253 * @since 1.0.0 */ readonly maxLength?: number; /** * A custom placeholder value used during deferred prompt resolution. * Override when `allowedTlds`, `minLabels`, or other constraints * reject the default `"example.com"`. * * @since 1.0.0 */ readonly placeholder?: string; /** * If `true`, converts domain to lowercase. * * @default false */ readonly lowercase?: boolean; /** * Custom error messages for domain parsing failures. */ readonly errors?: { /** * Custom error message when input is not a valid domain. * Can be a static message or a function that receives the input. */ invalidDomain?: Message | ((input: string) => Message); /** * Custom error message when subdomains are not allowed. * Can be a static message or a function that receives the domain. */ subdomainsNotAllowed?: Message | ((domain: string) => Message); /** * Custom error message when TLD is not allowed. * Can be a static message or a function that receives the TLD * and allowed TLDs. */ tldNotAllowed?: Message | ((tld: string, allowedTlds: readonly string[]) => Message); /** * Custom error message when domain has too few labels. * Can be a static message or a function that receives the domain * and minimum labels. */ tooFewLabels?: Message | ((domain: string, minLabels: number) => Message); /** * Custom error message when domain is too long. * Can be a static message or a function that receives the domain * and max length. * @since 1.0.0 */ tooLong?: Message | ((domain: string, maxLength: number) => Message); }; } /** * Creates a value parser for domain names. * * Validates domain names according to RFC 1035 with configurable options for * subdomain filtering, TLD restrictions, minimum label requirements, and case * normalization. * * @param options Parser options for domain validation. * @returns A parser that accepts valid domain names as strings. * @throws {RangeError} If `maxLength` is not a positive integer. * @throws {RangeError} If `minLabels` is not a positive integer. * @throws {TypeError} If `allowSubdomains` or `lowercase` is not a boolean. * @throws {TypeError} If any `allowedTlds` entry is not a string, is empty, * contains dots, has leading/trailing whitespace, or is not a valid DNS * label. * @throws {TypeError} If `allowSubdomains` is `false` and `minLabels` is * greater than 2, since non-subdomain domains have exactly 2 labels. * * @example * ``` typescript * import { option } from "@optique/core/primitives"; * import { domain } from "@optique/core/valueparser"; * * // Accept any valid domain * option("--domain", domain()) * * // Root domains only (no subdomains) * option("--root", domain({ allowSubdomains: false })) * * // Restrict to specific TLDs * option("--domain", domain({ allowedTlds: ["com", "org", "net"] })) * * // Normalize to lowercase * option("--domain", domain({ lowercase: true })) * ``` * * @since 0.10.0 */ declare function domain(options?: DomainOptions & { readonly metavar?: NonEmptyString; }): ValueParser<"sync", string>; /** * Options for configuring the IPv6 address value parser. * * @since 0.10.0 */ interface Ipv6Options { /** * The metavariable name for this parser. * * @default `"IPV6"` */ readonly metavar?: NonEmptyString; /** * If `true`, allows loopback address (::1). * * @default `true` */ readonly allowLoopback?: boolean; /** * If `true`, allows link-local addresses (fe80::/10). * * @default `true` */ readonly allowLinkLocal?: boolean; /** * If `true`, allows unique local addresses (fc00::/7). * * @default `true` */ readonly allowUniqueLocal?: boolean; /** * If `true`, allows multicast addresses (ff00::/8). * * @default `true` */ readonly allowMulticast?: boolean; /** * If `true`, allows the zero address (::). * * @default `true` */ readonly allowZero?: boolean; /** * Custom error messages for IPv6 parsing failures. */ readonly errors?: { /** * Custom error message when input is not a valid IPv6 address. * Can be a static message or a function that receives the input. */ invalidIpv6?: Message | ((input: string) => Message); /** * Custom error message when loopback IP is used but disallowed. * Can be a static message or a function that receives the IP. */ loopbackNotAllowed?: Message | ((ip: string) => Message); /** * Custom error message when link-local IP is used but disallowed. * Can be a static message or a function that receives the IP. */ linkLocalNotAllowed?: Message | ((ip: string) => Message); /** * Custom error message when unique local IP is used but disallowed. * Can be a static message or a function that receives the IP. */ uniqueLocalNotAllowed?: Message | ((ip: string) => Message); /** * Custom error message when multicast IP is used but disallowed. * Can be a static message or a function that receives the IP. */ multicastNotAllowed?: Message | ((ip: string) => Message); /** * Custom error message when zero IP is used but disallowed. * Can be a static message or a function that receives the IP. */ zeroNotAllowed?: Message | ((ip: string) => Message); }; } /** * Creates a value parser for IPv6 addresses. * * Validates and normalizes IPv6 addresses to canonical form (lowercase, * compressed using `::` notation where appropriate). * * @param options Configuration options for IPv6 validation. * @returns A value parser that validates IPv6 addresses. * * @example * ```typescript * // Basic IPv6 parser * option("--ipv6", ipv6()) * * // Global unicast only (no link-local, no unique local) * option("--public-ipv6", ipv6({ * allowLinkLocal: false, * allowUniqueLocal: false * })) * ``` * * @since 0.10.0 */ declare function ipv6(options?: Ipv6Options): ValueParser<"sync", string>; /** * Options for configuring the universal IP address value parser. * * @since 0.10.0 */ interface IpOptions { /** * The metavariable name for this parser. * * @default `"IP"` */ readonly metavar?: NonEmptyString; /** * IP version to accept. * - `4`: IPv4 only * - `6`: IPv6 only * - `"both"`: Accept both IPv4 and IPv6 * * @default `"both"` */ readonly version?: 4 | 6 | "both"; /** * Options for IPv4 validation (when version is 4 or "both"). */ readonly ipv4?: Omit; /** * Options for IPv6 validation (when version is 6 or "both"). */ readonly ipv6?: Omit; /** * Custom error messages for IP parsing failures. */ readonly errors?: { /** * Custom error message when input is not a valid IP address. * Can be a static message or a function that receives the input. */ invalidIP?: Message | ((input: string) => Message); /** * Custom error message when private IP is used but disallowed (IPv4). * Can be a static message or a function that receives the IP. */ privateNotAllowed?: Message | ((ip: string) => Message); /** * Custom error message when loopback IP is used but disallowed. * Can be a static message or a function that receives the IP. */ loopbackNotAllowed?: Message | ((ip: string) => Message); /** * Custom error message when link-local IP is used but disallowed. * Can be a static message or a function that receives the IP. */ linkLocalNotAllowed?: Message | ((ip: string) => Message); /** * Custom error message when multicast IP is used but disallowed. * Can be a static message or a function that receives the IP. */ multicastNotAllowed?: Message | ((ip: string) => Message); /** * Custom error message when broadcast IP is used but disallowed (IPv4). * Can be a static message or a function that receives the IP. */ broadcastNotAllowed?: Message | ((ip: string) => Message); /** * Custom error message when zero IP is used but disallowed. * Can be a static message or a function that receives the IP. */ zeroNotAllowed?: Message | ((ip: string) => Message); /** * Custom error message when unique local IP is used but disallowed (IPv6). * Can be a static message or a function that receives the IP. */ uniqueLocalNotAllowed?: Message | ((ip: string) => Message); }; } /** * Creates a value parser that accepts both IPv4 and IPv6 addresses. * * By default, accepts both IPv4 and IPv6 addresses. Use the `version` option * to restrict to a specific IP version. * * @param options Configuration options for IP validation. * @returns A value parser that validates IP addresses. * * @example * ```typescript * // Accept both IPv4 and IPv6 * option("--ip", ip()) * * // IPv4 only * option("--ipv4", ip({ version: 4 })) * * // Public IPs only (both versions) * option("--public-ip", ip({ * ipv4: { allowPrivate: false, allowLoopback: false }, * ipv6: { allowLinkLocal: false, allowUniqueLocal: false } * })) * ``` * * @since 0.10.0 */ declare function ip(options?: IpOptions): ValueParser<"sync", string>; /** * Value representing a CIDR notation (IP address with prefix length). * * @since 0.10.0 */ interface CidrValue { /** * The IP address portion (normalized). */ readonly address: string; /** * The prefix length (0-32 for IPv4, 0-128 for IPv6). */ readonly prefix: number; /** * IP version (4 or 6). */ readonly version: 4 | 6; } /** * Options for configuring the CIDR notation value parser. * * @since 0.10.0 */ interface CidrOptions { /** * The metavariable name for this parser. * * @default `"CIDR"` */ readonly metavar?: NonEmptyString; /** * IP version to accept. * - `4`: IPv4 CIDR only * - `6`: IPv6 CIDR only * - `"both"`: Accept both IPv4 and IPv6 CIDR * * @default `"both"` */ readonly version?: 4 | 6 | "both"; /** * Minimum allowed prefix length. * For IPv4: 0-32, for IPv6: 0-128. */ readonly minPrefix?: number; /** * Maximum allowed prefix length. * For IPv4: 0-32, for IPv6: 0-128. */ readonly maxPrefix?: number; /** * Options for IPv4 validation (when version is 4 or "both"). */ readonly ipv4?: Omit; /** * Options for IPv6 validation (when version is 6 or "both"). */ readonly ipv6?: Omit; /** * Custom error messages for CIDR parsing failures. */ readonly errors?: { /** * Custom error message when input is not a valid CIDR notation. * Can be a static message or a function that receives the input. */ invalidCidr?: Message | ((input: string) => Message); /** * Custom error message when prefix length is invalid. * Can be a static message or a function that receives the prefix and version. */ invalidPrefix?: Message | ((prefix: number, version: 4 | 6) => Message); /** * Custom error message when prefix is below minimum. * Can be a static message or a function that receives the prefix and minimum. */ prefixBelowMinimum?: Message | ((prefix: number, min: number) => Message); /** * Custom error message when prefix is above maximum. * Can be a static message or a function that receives the prefix and maximum. */ prefixAboveMaximum?: Message | ((prefix: number, max: number) => Message); /** * Custom error message when a private IPv4 address is used but disallowed. * Can be a static message or a function that receives the IP. * @since 1.0.0 */ privateNotAllowed?: Message | ((ip: string) => Message); /** * Custom error message when a loopback address is used but disallowed. * Can be a static message or a function that receives the IP. * @since 1.0.0 */ loopbackNotAllowed?: Message | ((ip: string) => Message); /** * Custom error message when a link-local address is used but disallowed. * Can be a static message or a function that receives the IP. * @since 1.0.0 */ linkLocalNotAllowed?: Message | ((ip: string) => Message); /** * Custom error message when a multicast address is used but disallowed. * Can be a static message or a function that receives the IP. * @since 1.0.0 */ multicastNotAllowed?: Message | ((ip: string) => Message); /** * Custom error message when the broadcast address is used but disallowed * (IPv4 only). * Can be a static message or a function that receives the IP. * @since 1.0.0 */ broadcastNotAllowed?: Message | ((ip: string) => Message); /** * Custom error message when the zero address is used but disallowed. * Can be a static message or a function that receives the IP. * @since 1.0.0 */ zeroNotAllowed?: Message | ((ip: string) => Message); /** * Custom error message when a unique local address is used but disallowed * (IPv6 only). * Can be a static message or a function that receives the IP. * @since 1.0.0 */ uniqueLocalNotAllowed?: Message | ((ip: string) => Message); }; } /** * Creates a value parser for CIDR notation (IP address with prefix length). * * Parses and validates CIDR notation like `192.168.0.0/24` or `2001:db8::/32`. * Returns a structured object with the normalized IP address, prefix length, * and IP version. * * @param options Configuration options for CIDR validation. * @returns A value parser that validates CIDR notation. * * @example * ```typescript * // Accept both IPv4 and IPv6 CIDR * option("--network", cidr()) * * // IPv4 CIDR only with prefix constraints * option("--subnet", cidr({ * version: 4, * minPrefix: 16, * maxPrefix: 24 * })) * ``` * * @since 0.10.0 */ declare function cidr(options?: CidrOptions): ValueParser<"sync", CidrValue>; /** * A normalized Semantic Versioning 2.0.0 string. * * Covers all four valid forms: * - `MAJOR.MINOR.PATCH` * - `MAJOR.MINOR.PATCH-preRelease` * - `MAJOR.MINOR.PATCH+metadata` * - `MAJOR.MINOR.PATCH-preRelease+metadata` * * Note: this type uses TypeScript template literals as a coarse structural * hint. The `${number}` slots accept any JavaScript number serialization * (including negative numbers, decimals, and `Infinity`), so the type alone * does not guarantee full SemVer 2.0.0 validity. Full validation is * enforced at parse time by {@link semVer}. Only values returned by * `semVer().parse()` are guaranteed to conform to the specification. * * @since 1.1.0 */ type SemVerString = `${number}.${number}.${number}` | `${number}.${number}.${number}-${string}` | `${number}.${number}.${number}+${string}` | `${number}.${number}.${number}-${string}+${string}`; /** * A parsed Semantic Versioning 2.0.0 value as a structured object. * * @since 1.1.0 */ interface SemVer { /** * The major version number. * * This field is a JavaScript `number`, so it is limited to * {@link Number.MAX_SAFE_INTEGER} (2⁵³ − 1). Inputs whose major * component exceeds this value are rejected by {@link semVer} in object * mode; use string mode to handle arbitrarily large version numbers. */ readonly major: number; /** * The minor version number. * * Same safe-integer constraint as {@link major}. */ readonly minor: number; /** * The patch version number. * * Same safe-integer constraint as {@link major}. */ readonly patch: number; /** * The pre-release identifier (the part after `-`, before `+`), if present. * Example: `"alpha.1"` for `1.0.0-alpha.1`. */ readonly preRelease?: string; /** * The build metadata (the part after `+`), if present. * Example: `"build.42"` for `1.0.0+build.42`. */ readonly metadata?: string; } /** @internal */ interface SemVerOptionsBase { /** * The metavariable name for this parser. Used in help messages. * @default `"SEMVER"` */ readonly metavar?: NonEmptyString; /** * Whether to accept an optional leading `v` character (e.g. `v1.2.3`). * The `v` prefix is stripped; output is always the canonical unprefixed form. * @default false */ readonly allowPrefix?: boolean; /** * Custom error messages for parse failures. * @since 1.1.0 */ readonly errors?: { /** * Message when input is not a valid SemVer string. * Can be a static message or a function receiving the rejected input. */ readonly invalidSemVer?: Message | ((input: string) => Message); }; } /** * Options for {@link semVer} in string mode (the default). * * @since 1.1.0 */ interface SemVerOptionsString extends SemVerOptionsBase { /** Return a {@link SemVerString} template-literal type. */ readonly type?: "string"; } /** * Options for {@link semVer} in object mode. * * In object mode, version components are stored as JavaScript `number` * values. Components exceeding {@link Number.MAX_SAFE_INTEGER} (2⁵³ − 1) * cannot be represented exactly and are therefore rejected with a parse * error. Use string mode (the default) if you need to handle version * numbers of arbitrary magnitude. * * @since 1.1.0 */ interface SemVerOptionsObject extends SemVerOptionsBase { /** Return a structured {@link SemVer} object. */ readonly type: "object"; } /** * Creates a {@link ValueParser} for [Semantic Versioning 2.0.0] strings. * * In string mode (the default), the parser returns a {@link SemVerString} * template-literal type. String mode accepts any spec-valid SemVer input, * including version components of arbitrary magnitude. * * In object mode (`type: "object"`), the parser returns a structured * {@link SemVer} value with `major`, `minor`, `patch`, and optional * `preRelease` and `metadata` fields. Because the numeric components are * stored as JavaScript `number`, object mode additionally rejects inputs * whose major, minor, or patch value exceeds * {@link Number.MAX_SAFE_INTEGER} (2⁵³ − 1). Use string mode if you need * to handle arbitrarily large version numbers. * * Both modes strictly enforce the SemVer 2.0.0 specification: no leading * zeros in numeric components, no empty pre-release or build identifiers, * and no invalid characters. * * [Semantic Versioning 2.0.0]: https://semver.org/ * * @param options Configuration options. * @returns A {@link ValueParser} that validates SemVer strings. * @throws {TypeError} If {@link SemVerOptionsBase.metavar} is an empty string. * @throws {TypeError} If {@link SemVerOptionsBase.allowPrefix} is not a * boolean. * @throws {TypeError} If {@link SemVerOptionsString.type} is not `"string"`, * `"object"`, or `undefined`. * @since 1.1.0 */ declare function semVer(options?: SemVerOptionsString): ValueParser<"sync", SemVerString>; /** * Creates a {@link ValueParser} for [Semantic Versioning 2.0.0] strings, * returning a structured {@link SemVer} object. * * [Semantic Versioning 2.0.0]: https://semver.org/ * * @param options Configuration options with `type: "object"`. * @returns A {@link ValueParser} that converts SemVer strings to {@link SemVer} * objects. * @throws {TypeError} If {@link SemVerOptionsBase.metavar} is an empty string. * @throws {TypeError} If {@link SemVerOptionsBase.allowPrefix} is not a * boolean. * @throws {TypeError} If {@link SemVerOptionsObject.type} is not `"string"`, * `"object"`, or `undefined`. * @since 1.1.0 */ declare function semVer(options: SemVerOptionsObject): ValueParser<"sync", SemVer>; /** * Any JSON-serializable value. * * This type is a TypeScript approximation of JSON data values. Note that * certain JavaScript distinctions are not preserved through serialization: * for example, `-0` serializes as `"0"`, so a round-trip through * `format()` and `parse()` may return `0` instead. * * @since 1.1.0 */ type Json = string | number | boolean | null | { readonly [property: string]: Json; } | readonly Json[]; /** * Options for creating a {@link json} value parser. * * @since 1.1.0 */ interface JsonOptions { /** * 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 `DATA` or `CONFIG`. * @default `"JSON"` */ readonly metavar?: NonEmptyString; /** * A custom placeholder value used during deferred prompt resolution. * @default Depends on `rootType`: `null` when unset, `""` for `"string"`, * `0` for `"number"`, `false` for `"boolean"`, `null` for `"null"`, * `{}` for `"object"`, `[]` for `"array"`. * @since 1.1.0 */ readonly placeholder?: Json; /** * Restricts the expected JSON root type. When set, the parser rejects * JSON values whose root type does not match and narrows the TypeScript * return type accordingly. * * @since 1.1.0 */ readonly rootType?: "string" | "number" | "boolean" | "null" | "object" | "array"; /** * Custom error messages for JSON parsing failures. * * @since 1.1.0 */ readonly errors?: { /** * Custom error message when the input is not valid JSON. * Can be a static message or a function that receives the raw input. * @since 1.1.0 */ readonly invalidJson?: Message | ((input: string) => Message); /** * Custom error message when the parsed JSON value does not match the * expected `rootType`. Can be a static message or a function that * receives the parsed value and the expected root type name. * @since 1.1.0 */ readonly invalidRootType?: Message | ((value: Json, expected: string) => Message); }; } /** * Creates a {@link ValueParser} that parses JSON-encoded strings and returns * a `string`. * * @param options Configuration options including `rootType: "string"`. * @returns A parser whose successful value is typed as `string`. * @since 1.1.0 */ declare function json(options: JsonOptions & { readonly rootType: "string"; readonly placeholder?: string; }): ValueParser<"sync", string>; /** * Creates a {@link ValueParser} that parses JSON-encoded strings and returns * a `number`. * * @param options Configuration options including `rootType: "number"`. * @returns A parser whose successful value is typed as `number`. * @since 1.1.0 */ declare function json(options: JsonOptions & { readonly rootType: "number"; readonly placeholder?: number; }): ValueParser<"sync", number>; /** * Creates a {@link ValueParser} that parses JSON-encoded strings and returns * a `boolean`. * * @param options Configuration options including `rootType: "boolean"`. * @returns A parser whose successful value is typed as `boolean`. * @since 1.1.0 */ declare function json(options: JsonOptions & { readonly rootType: "boolean"; readonly placeholder?: boolean; }): ValueParser<"sync", boolean>; /** * Creates a {@link ValueParser} that parses JSON-encoded strings and returns * `null`. * * @param options Configuration options including `rootType: "null"`. * @returns A parser whose successful value is typed as `null`. * @since 1.1.0 */ declare function json(options: JsonOptions & { readonly rootType: "null"; readonly placeholder?: null; }): ValueParser<"sync", null>; /** * Creates a {@link ValueParser} that parses JSON-encoded strings and returns * a plain JSON object. * * @param options Configuration options including `rootType: "object"`. * @returns A parser whose successful value is typed as * `{ readonly [property: string]: Json }`. * @since 1.1.0 */ declare function json(options: JsonOptions & { readonly rootType: "object"; readonly placeholder?: { readonly [property: string]: Json; }; }): ValueParser<"sync", { readonly [property: string]: Json; }>; /** * Creates a {@link ValueParser} that parses JSON-encoded strings and returns * a JSON array. * * @param options Configuration options including `rootType: "array"`. * @returns A parser whose successful value is typed as `readonly Json[]`. * @since 1.1.0 */ declare function json(options: JsonOptions & { readonly rootType: "array"; readonly placeholder?: readonly Json[]; }): ValueParser<"sync", readonly Json[]>; /** * Creates a {@link ValueParser} that parses JSON-encoded strings into any * {@link Json} value (object, array, string, number, boolean, or null). * * Also accepts a pre-typed `JsonOptions` variable when the `rootType` is not * known at compile time; the return type is the widened {@link Json} union. * * @param options Optional configuration for the parser. * @returns A parser whose successful value is typed as {@link Json}. * @since 1.1.0 */ declare function json(options?: JsonOptions): ValueParser<"sync", Json>; /** * Options for the {@link firstOf} combinator. * @since 1.1.0 */ interface FirstOfOptions { /** * The metavariable name for the combined parser. This is used in help * messages to indicate what kind of value this parser expects. * @default The constituent metavars joined with `|`, e.g. `"TYPE|INTEGER"`. */ readonly metavar?: NonEmptyString; /** * Custom error messages for firstOf parsing failures. * @since 1.1.0 */ readonly errors?: { /** * Custom error message when every constituent parser fails. Can be a * static message or a function that receives the input and the * constituent errors in declaration order. * @since 1.1.0 */ readonly noMatch?: Message | ((input: string, errors: readonly Message[]) => Message); }; } /** * The trailing options argument of {@link firstOf}. A {@link ValueParser} * structurally satisfies {@link FirstOfOptions} (its `metavar` field matches * the optional one), so the required `parse` method is excluded to keep * the overloads unambiguous. */ type FirstOfTailOptions = FirstOfOptions & { readonly parse?: never; }; /** * Extracts the result type of a sync {@link ValueParser}. */ type ValueParserValue

= P extends ValueParser<"sync", infer T> ? T : never; /** * Creates a {@link ValueParser} that tries two value parsers in declaration * order and returns the result of the first one that succeeds. * * The result type is the union of the constituent result types: * * ```typescript * const count = firstOf(choice(["auto"]), integer({ min: 1 })); * // Inferred type: ValueParser<"sync", "auto" | number> * ``` * * When every constituent fails, the combined error lists each constituent's * error on its own line. * @template TA The result type of the first parser. * @template TB The result type of the second parser. * @param a The first value parser to try. * @param b The second value parser to try. * @param options Configuration options for the combined parser. * @returns A {@link ValueParser} that accepts values matching any of the * constituent parsers. * @throws {TypeError} If any constituent is not a sync value parser. * @throws {TypeError} If any constituent is a dependency-derived value * parser (created via `deriveFrom()` or `dependency().derive()`). * @since 1.1.0 */ declare function firstOf(a: ValueParser<"sync", TA>, b: ValueParser<"sync", TB>, options?: FirstOfTailOptions): ValueParser<"sync", TA | TB>; /** * Creates a {@link ValueParser} that tries three value parsers in declaration * order and returns the result of the first one that succeeds. * @template TA The result type of the first parser. * @template TB The result type of the second parser. * @template TC The result type of the third parser. * @param a The first value parser to try. * @param b The second value parser to try. * @param c The third value parser to try. * @param options Configuration options for the combined parser. * @returns A {@link ValueParser} that accepts values matching any of the * constituent parsers. * @throws {TypeError} If any constituent is not a sync value parser. * @throws {TypeError} If any constituent is a dependency-derived value * parser (created via `deriveFrom()` or `dependency().derive()`). * @since 1.1.0 */ declare function firstOf(a: ValueParser<"sync", TA>, b: ValueParser<"sync", TB>, c: ValueParser<"sync", TC>, options?: FirstOfTailOptions): ValueParser<"sync", TA | TB | TC>; /** * Creates a {@link ValueParser} that tries four value parsers in declaration * order and returns the result of the first one that succeeds. * @template TA The result type of the first parser. * @template TB The result type of the second parser. * @template TC The result type of the third parser. * @template TD The result type of the fourth parser. * @param a The first value parser to try. * @param b The second value parser to try. * @param c The third value parser to try. * @param d The fourth value parser to try. * @param options Configuration options for the combined parser. * @returns A {@link ValueParser} that accepts values matching any of the * constituent parsers. * @throws {TypeError} If any constituent is not a sync value parser. * @throws {TypeError} If any constituent is a dependency-derived value * parser (created via `deriveFrom()` or `dependency().derive()`). * @since 1.1.0 */ declare function firstOf(a: ValueParser<"sync", TA>, b: ValueParser<"sync", TB>, c: ValueParser<"sync", TC>, d: ValueParser<"sync", TD>, options?: FirstOfTailOptions): ValueParser<"sync", TA | TB | TC | TD>; /** * Creates a {@link ValueParser} that tries five value parsers in declaration * order and returns the result of the first one that succeeds. * @template TA The result type of the first parser. * @template TB The result type of the second parser. * @template TC The result type of the third parser. * @template TD The result type of the fourth parser. * @template TE The result type of the fifth parser. * @param a The first value parser to try. * @param b The second value parser to try. * @param c The third value parser to try. * @param d The fourth value parser to try. * @param e The fifth value parser to try. * @param options Configuration options for the combined parser. * @returns A {@link ValueParser} that accepts values matching any of the * constituent parsers. * @throws {TypeError} If any constituent is not a sync value parser. * @throws {TypeError} If any constituent is a dependency-derived value * parser (created via `deriveFrom()` or `dependency().derive()`). * @since 1.1.0 */ declare function firstOf(a: ValueParser<"sync", TA>, b: ValueParser<"sync", TB>, c: ValueParser<"sync", TC>, d: ValueParser<"sync", TD>, e: ValueParser<"sync", TE>, options?: FirstOfTailOptions): ValueParser<"sync", TA | TB | TC | TD | TE>; /** * Creates a {@link ValueParser} that tries any number of value parsers in * declaration order and returns the result of the first one that succeeds. * @template TParsers The tuple of constituent value parsers. * @param args The value parsers to try, followed by configuration options. * @returns A {@link ValueParser} that accepts values matching any of the * constituent parsers. * @throws {TypeError} If any constituent is not a sync value parser. * @throws {TypeError} If any constituent is a dependency-derived value * parser (created via `deriveFrom()` or `dependency().derive()`). * @since 1.1.0 */ declare function firstOf, ValueParser<"sync", unknown>, ...ValueParser<"sync", unknown>[]]>(...args: [...parsers: TParsers, options: FirstOfTailOptions]): ValueParser<"sync", ValueParserValue>; /** * Creates a {@link ValueParser} that tries any number of value parsers in * declaration order and returns the result of the first one that succeeds. * @template TParsers The tuple of constituent value parsers. * @param parsers The value parsers to try. * @returns A {@link ValueParser} that accepts values matching any of the * constituent parsers. * @throws {TypeError} If any constituent is not a sync value parser. * @throws {TypeError} If any constituent is a dependency-derived value * parser (created via `deriveFrom()` or `dependency().derive()`). * @since 1.1.0 */ declare function firstOf, ValueParser<"sync", unknown>, ...ValueParser<"sync", unknown>[]]>(...parsers: TParsers): ValueParser<"sync", ValueParserValue>; /** * Creates a {@link ValueParser} that tries the value parsers in the given * array in declaration order and returns the result of the first one that * succeeds. * * Unlike the variadic overloads, which require at least two statically * known arguments, this form accepts a dynamically built array: * * ```typescript * const parsers: ValueParser<"sync", string | number>[] = buildParsers(); * const combined = firstOf(parsers); * ``` * @template TParsers The array of constituent value parsers. * @param parsers The value parsers to try. Must contain at least two * parsers. * @param options Configuration options for the combined parser. * @returns A {@link ValueParser} that accepts values matching any of the * constituent parsers. * @throws {TypeError} If the array contains fewer than two value parsers. * @throws {TypeError} If any constituent is not a sync value parser. * @throws {TypeError} If any constituent is a dependency-derived value * parser (created via `deriveFrom()` or `dependency().derive()`). * @since 1.1.0 */ declare function firstOf[]>(parsers: TParsers, options?: FirstOfOptions): ValueParser<"sync", ValueParserValue>; //#endregion export { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FirstOfOptions, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, KeyValueOptions, LocaleOptions, MacAddressOptions, type Mode, type ModeIterable, type ModeValue, type NonEmptyString, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, SocketAddressOptions, SocketAddressValue, StringOptions, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, checkBooleanOption, checkEnumOption, choice, cidr, color, domain, email, ensureNonEmptyString, fileSize, firstOf, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, json, keyValue, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid };