//#region ../../node_modules/.pnpm/args-tokens@0.28.1/node_modules/args-tokens/lib/parser-DT7Ztcch.d.ts //#region src/parser.d.ts /** * Entry point of argument parser. * * @module */ /** * forked from `nodejs/node` (`pkgjs/parseargs`) * repository url: https://github.com/nodejs/node (https://github.com/pkgjs/parseargs) * code url: https://github.com/nodejs/node/blob/main/lib/internal/util/parse_args/parse_args.js * * @author kazuya kawaguchi (a.k.a. kazupon) * @license MIT */ /** * Argument token Kind. * * - `option`: option token, support short option (e.g. `-x`) and long option (e.g. `--foo`) * - `option-terminator`: option terminator (`--`) token, see guideline 10 in https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html * - `positional`: positional token */ type ArgTokenKind = 'option' | 'option-terminator' | 'positional'; /** * Argument token. */ interface ArgToken { /** * Argument token kind. */ kind: ArgTokenKind; /** * Argument token index, e.g `--foo bar` => `--foo` index is 0, `bar` index is 1. */ index: number; /** * Option name, e.g. `--foo` => `foo`, `-x` => `x`. */ name?: string; /** * Raw option name, e.g. `--foo` => `--foo`, `-x` => `-x`. */ rawName?: string; /** * Option value, e.g. `--foo=bar` => `bar`, `-x=bar` => `bar`. * If the `allowCompatible` option is `true`, short option value will be same as Node.js `parseArgs` behavior. */ value?: string; /** * Inline value, e.g. `--foo=bar` => `true`, `-x=bar` => `true`. */ inlineValue?: boolean; } /** * Parser Options. */ //#endregion //#region ../../node_modules/.pnpm/args-tokens@0.28.1/node_modules/args-tokens/lib/resolver.d.ts //#region src/resolver.d.ts /** * An argument schema definition for command-line argument parsing. * * This schema is similar to the schema of Node.js `util.parseArgs` but with extended features: * - Additional `required`, `description`, and `hidden` properties * - Extended `type` support: 'string', 'boolean', 'number', 'enum', 'positional', 'custom' * - Simplified `default` property (single type, not union types) * * @example * Basic string argument: * ```ts * const schema: ArgSchema = { * type: 'string', * description: 'Server hostname', * default: 'localhost' * } * ``` * * @example * Required number argument with alias: * ```ts * const schema: ArgSchema = { * type: 'number', * short: 'p', * description: 'Port number to listen on', * required: true * } * ``` * * @example * Enum argument with choices: * ```ts * const schema: ArgSchema = { * type: 'enum', * choices: ['info', 'warn', 'error'], * description: 'Logging level', * default: 'info' * } * ``` */ interface ArgSchema { /** * Type of the argument value. * * - `'string'`: Text value (default if not specified) * - `'boolean'`: `true`/`false` flag (can be negatable with `--no-` prefix) * - `'number'`: Numeric value (parsed as integer or float) * - `'enum'`: One of predefined string values (requires `choices` property) * - `'positional'`: Non-option argument by position * - `'custom'`: Custom parsing with user-defined `parse` function * * @example * Different argument types: * ```ts * { * name: { type: 'string' }, // --name value * verbose: { type: 'boolean' }, // --verbose or --no-verbose * port: { type: 'number' }, // --port 3000 * level: { type: 'enum', choices: ['debug', 'info'] }, * file: { type: 'positional' }, // first positional arg * config: { type: 'custom', parse: JSON.parse } * } * ``` */ type: 'string' | 'boolean' | 'number' | 'enum' | 'positional' | 'custom'; /** * Single character alias for the long option name. * * As example, allows users to use `-x` instead of `--extended-option`. * Only valid for non-positional argument types. * * @example * Short alias usage: * ```ts * { * verbose: { * type: 'boolean', * short: 'v' // Enables both --verbose and -v * }, * port: { * type: 'number', * short: 'p' // Enables both --port 3000 and -p 3000 * } * } * ``` */ short?: string; /** * Human-readable description of the argument's purpose. * * Used for help text generation and documentation. * Should be concise but descriptive enough to understand the argument's role. * * @example * Descriptive help text: * ```ts * { * config: { * type: 'string', * description: 'Path to configuration file' * }, * timeout: { * type: 'number', * description: 'Request timeout in milliseconds' * } * } * ``` */ description?: string; /** * Hide the argument from generated help or usage output. * * This is metadata for renderers. It does not affect parsing, validation, * required checks, defaults, conflicts, or resolved values. * * @example * Hidden compatibility option: * ```ts * { * legacy: { * type: 'string', * hidden: true, * description: 'Deprecated compatibility option' * } * } * ``` */ hidden?: boolean; /** * Marks the argument as required. * * When `true`, the argument must be provided by the user. * If missing, an `ArgResolveError` with type 'required' will be thrown. * * For single-value positional arguments, omitting `required` keeps the argument * required for compatibility. Set `required: false` to make a positional argument * optional. Optional positional arguments leave enough input values for later * required positional arguments before consuming a value. * * @example * Required arguments: * ```ts * { * input: { * type: 'string', * required: true, // Must be provided: --input file.txt * description: 'Input file path' * }, * source: { * type: 'positional', * required: true // First positional argument must exist * } * } * ``` */ required?: boolean; /** * Allows the argument to accept multiple values. * * When `true`, the resolved value becomes an array. * For options: can be specified multiple times (--tag foo --tag bar) * For positional: collects remaining positional arguments after preserving values for * later required positional arguments. * * Note: Only `true` is allowed (not `false`) to make intent explicit. * * @example * Multiple values: * ```ts * { * tags: { * type: 'string', * multiple: true, // --tags foo --tags bar → ['foo', 'bar'] * description: 'Tags to apply' * }, * files: { * type: 'positional', * multiple: true // Collects all remaining positional args * } * } * ``` */ multiple?: true; /** * Enables negation for boolean arguments using `--no-` prefix. * * When `true`, allows users to explicitly set the boolean to `false` * using `--no-option-name`. When `false` or omitted, only positive * form is available. * * Only applicable to `type: 'boolean'` arguments. * * @example * Negatable boolean: * ```ts * { * color: { * type: 'boolean', * negatable: true, * default: true, * description: 'Enable colorized output' * } * // Usage: --color (true), --no-color (false) * } * ``` */ negatable?: boolean; /** * Array of allowed string values for enum-type arguments. * * Required when `type: 'enum'`. The argument value must be one of these choices, * otherwise an `ArgResolveError` with type 'type' will be thrown. * * Supports both mutable arrays and readonly arrays for type safety. * * @example * Enum choices: * ```ts * { * logLevel: { * type: 'enum', * choices: ['debug', 'info', 'warn', 'error'] as const, * default: 'info', * description: 'Logging verbosity level' * }, * format: { * type: 'enum', * choices: ['json', 'yaml', 'toml'], * description: 'Output format' * } * } * ``` */ choices?: string[] | readonly string[]; /** * Default value used when the argument is not provided. * * The type must match the argument's `type` property: * - `string` type: string default * - `boolean` type: boolean default * - `number` type: number default * - `enum` type: must be one of the `choices` values * - `positional`/`custom` type: string, boolean, or number default * * For single-value positional arguments, the default is used when the positional * value is missing or when the value is preserved for later required positional * arguments, unless `required: true` is set. * * @example * Default values by type: * ```ts * { * host: { * type: 'string', * default: 'localhost' // string default * }, * verbose: { * type: 'boolean', * default: false // boolean default * }, * port: { * type: 'number', * default: 8080 // number default * }, * level: { * type: 'enum', * choices: ['low', 'high'], * default: 'low' // must be in choices * } * } * ``` */ default?: string | boolean | number; /** * Converts the argument name from camelCase to kebab-case for CLI usage. * * When `true`, a property like `maxCount` becomes available as `--max-count`. * This allows [CAC](https://github.com/cacjs/cac) user-friendly property names while maintaining CLI conventions. * * Can be overridden globally with `resolveArgs({ toKebab: true })`. * * Note: Only `true` is allowed (not `false`) to make intent explicit. * * @example * Kebab-case conversion: * ```ts * { * maxRetries: { * type: 'number', * toKebab: true, // Accessible as --max-retries * description: 'Maximum retry attempts' * }, * enableLogging: { * type: 'boolean', * toKebab: true // Accessible as --enable-logging * } * } * ``` */ toKebab?: true; /** * Names of other options that conflict with this option. * * When this option is used together with any of the conflicting options, * an `ArgResolveError` with type 'conflict' will be thrown. * * Conflicts only need to be defined on one side - if option A defines a conflict * with option B, the conflict is automatically detected when both are used, * regardless of whether B also defines a conflict with A. * * Supports both single option name or array of option names. * Option names must match the property keys in the schema object exactly * (no automatic conversion between camelCase and kebab-case). * * @example * Single conflict (bidirectional definition): * ```ts * { * summer: { * type: 'boolean', * conflicts: 'autumn' // Cannot use --summer with --autumn * }, * autumn: { * type: 'boolean', * conflicts: 'summer' // Can define on both sides for clarity * } * } * ``` * * @example * Single conflict (one-way definition): * ```ts * { * summer: { * type: 'boolean', * conflicts: 'autumn' // Only defined on summer side * }, * autumn: { * type: 'boolean' * // No conflicts defined, but still cannot use with --summer * } * } * // Usage: --summer --autumn will throw error * // Error: "Optional argument '--summer' conflicts with '--autumn'" * ``` * * @example * Multiple conflicts: * ```ts * { * port: { * type: 'number', * conflicts: ['socket', 'pipe'], // Cannot use with --socket or --pipe * description: 'TCP port number' * }, * socket: { * type: 'string', * conflicts: ['port', 'pipe'], // Cannot use with --port or --pipe * description: 'Unix socket path' * }, * pipe: { * type: 'string', * conflicts: ['port', 'socket'], // Cannot use with --port or --socket * description: 'Named pipe path' * } * } * // These three options are mutually exclusive * ``` * * @example * With kebab-case conversion: * ```ts * { * summerSeason: { * type: 'boolean', * toKebab: true, // Accessible as --summer-season * conflicts: 'autumnSeason' // Must use property key, not CLI name * }, * autumnSeason: { * type: 'boolean', * toKebab: true // Accessible as --autumn-season * } * } * // Error: "Optional argument '--summer-season' conflicts with '--autumn-season'" * ``` */ conflicts?: string | string[]; /** * Display name hint for help text generation. * * Provides a meaningful type hint for the argument value in help output. * Particularly useful for `type: 'custom'` arguments where the type * name would otherwise be unhelpful. * * @example * Metavar usage: * ```ts * { * port: { * type: 'custom', * parse: (v: string) => parseInt(v, 10), * metavar: 'integer', * description: 'Port number (1-65535)' * } * } * // Help output: --port Port number (1-65535) * ``` */ metavar?: string; /** * Custom parsing function for `type: 'custom'` arguments. * * Required when `type: 'custom'`. Receives the raw string value and must * return the parsed result. Should throw an Error (or subclass) if parsing fails. * * The function's return type becomes the resolved argument type. * * @param value - Raw string value from command line * @returns Parsed value of any type * @throws {Error} Error or subclass when value is invalid * * @example * Custom parsing functions: * ```ts * { * config: { * type: 'custom', * parse: (value: string) => { * try { * return JSON.parse(value) // Parse JSON config * } catch { * throw new Error('Invalid JSON configuration') * } * }, * description: 'JSON configuration object' * }, * date: { * type: 'custom', * parse: (value: string) => { * const date = new Date(value) * if (isNaN(date.getTime())) { * throw new Error('Invalid date format') * } * return date * } * } * } * ``` */ parse?: (value: string) => any; } /** * Machine-readable error codes for {@link ArgsValidationError}. * * Each code identifies a validation failure category and is also suitable as an * i18n resource key for localized rendering. */ declare const ArgsValidationErrorKeys: { readonly requiredOption: "err:arg:required-option"; readonly requiredPositional: "err:arg:required-positional"; readonly invalidType: "err:arg:invalid-type"; readonly invalidChoice: "err:arg:invalid-choice"; readonly customParse: "err:arg:custom-parse"; readonly unknownOption: "err:arg:unknown-option"; }; /** * A machine-readable argument validation error code. * * Each code is one of {@link ArgsValidationErrorKeys} and can also be used as * an i18n resource key. */ type ArgsValidationErrorCode = (typeof ArgsValidationErrorKeys)[keyof typeof ArgsValidationErrorKeys]; /** * An error that contains structured metadata for argument validation failures. * * The `message` remains the English fallback message. Renderers can use `code` * and `values` to localize the error, falling back to `message` when localization * is unavailable. */ declare class ArgsValidationError extends Error { /** * Machine-readable error code for this validation failure. * * This code can also be used as an i18n resource key. */ readonly code?: ArgsValidationErrorCode; /** * Interpolation values for `code`. */ readonly values: Record; /** * Create an `ArgsValidationError` instance. * * @param message - fallback error message * @param options - structured validation metadata */ constructor(message: string, options?: { code?: ArgsValidationErrorCode; values?: Record; cause?: unknown; }); } /** * Check whether the given value is an {@link ArgsValidationError}. * * @param error - value to check * @returns `true` when the value is an `ArgsValidationError` */ declare function isArgsValidationError(error: unknown): error is ArgsValidationError; /** * An object that contains {@link ArgSchema | argument schema}. * * This type is used to define the structure and validation rules for command line arguments. */ interface Args { [option: string]: ArgSchema; } /** * An object that contains the values of the arguments. * * @typeParam T - {@link Args | Arguments} which is an object that defines the command line arguments. */ type ArgValues = T extends Args ? ResolveArgValues }> : { [option: string]: string | boolean | number | (string | boolean | number)[] | undefined; }; /** * Extracts the value type from the argument schema. * * @typeParam A - {@link ArgSchema | Argument schema} which is an object that defines command line arguments. * * @internal */ type ExtractOptionValue = undefined extends A['parse'] ? A['type'] extends 'string' ? ResolveOptionValue : A['type'] extends 'boolean' ? ResolveOptionValue : A['type'] extends 'number' ? ResolveOptionValue : A['type'] extends 'positional' ? ResolveOptionValue : A['type'] extends 'enum' ? A['choices'] extends string[] | readonly string[] ? ResolveOptionValue : never : A['type'] extends 'custom' ? never : ResolveOptionValue : A['parse'] extends ((value: string) => infer R) ? ResolveOptionValue : never; type ResolveOptionValue = A['multiple'] extends true ? T[] : T; /** * Resolved argument values. * * @typeParam A - {@link Arguments | Args} which is an object that defines the command line arguments. * @typeParam V - Resolvable argument values. * * @internal */ type ResolveArgValues> = { -readonly [Arg in keyof A]?: V[Arg] } & FilterArgs & FilterArgs & FilterPositionalArgs extends infer P ? { [K in keyof P]: P[K] } : never; /** * Filters the arguments based on their default values. * * @typeParam A - {@link Args | Arguments}, which is an object that defines the command line arguments. * @typeParam V - Resolvable argument values. * @typeParam K - Key of the {@link ArgSchema | argument schema} to filter by. * * @internal */ type FilterArgs, K extends keyof ArgSchema> = { [Arg in keyof A as K extends 'required' ? A[Arg][K] extends true ? Arg : never : A[Arg][K] extends {} ? Arg : never]: V[Arg] }; /** * Filters positional arguments from the argument schema. * * @typeParam A - {@link Args | Arguments}, which is an object that defines the command line arguments. * @typeParam V - Resolvable argument values. * * @internal */ type FilterPositionalArgs> = { [Arg in keyof A as IsRequiredPositionalArg extends true ? Arg : never]: V[Arg] }; type IsRequiredPositionalArg = A['type'] extends 'positional' ? A['multiple'] extends true ? A['required'] extends true ? true : false : A['required'] extends false ? A['default'] extends {} ? true : false : true : false; /** * An arguments for {@link resolveArgs | resolve arguments}. */ /** * Tracks which arguments were explicitly provided by the user. * * Each property indicates whether the corresponding argument was explicitly * provided (true) or is using a default value or not provided (false). * * @typeParam A - {@link Args | Arguments}, which is an object that defines the command line arguments. */ type ArgExplicitlyProvided = { [K in keyof A]: boolean }; /** * Resolve command line arguments. * * @typeParam A - {@link Args | Arguments}, which is an object that defines the command line arguments. * * @param args - An arguments that contains {@link ArgSchema | arguments schema}. * @param tokens - An array of {@link ArgToken | tokens}. * @param resolveArgs - An arguments that contains {@link ResolveArgs | resolve arguments}. * @returns An object that contains the values of the arguments, positional arguments, rest arguments, {@link AggregateError | validation errors}, and explicit provision status. * * @example * ```typescript * // passed tokens: --port 3000 * * const { values, explicit } = resolveArgs({ * port: { * type: 'number', * default: 8080 * }, * host: { * type: 'string', * default: 'localhost' * } * }, parsedTokens) * * values.port // 3000 * values.host // 'localhost' * * explicit.port // true (explicitly provided) * explicit.host // false (not provided, fallback to default) * ``` */ //#endregion //#region ../gunshi/src/plugin/context.d.ts /** * Gunshi plugin context interface. * * @typeParam G - A type extending {@linkcode GunshiParams} to specify the shape of command parameters. * * @since v0.27.0 */ interface PluginContext { /** * Get the global options * * @returns A map of global options. */ readonly globalOptions: Map; /** * Get the registered sub commands * * @returns A map of sub commands. */ readonly subCommands: ReadonlyMap | LazyCommand>; /** * Add a global option. * * @param name - An option name * @param schema - An {@linkcode ArgSchema} for the option */ addGlobalOption(name: string, schema: ArgSchema): void; /** * Add a sub command. * * @param name - Command name * @param command - Command definition */ addCommand(name: string, command: Command | LazyCommand): void; /** * Check if a command exists. * * @param name - Command name * @returns True if the command exists, false otherwise */ hasCommand(name: string): boolean; /** * Decorate the header renderer. * * @typeParam L - An extensions type to specify the shape of {@linkcode CommandContext}'s extensions. * * @param decorator - A decorator function that wraps the base header renderer. */ decorateHeaderRenderer = DefaultGunshiParams['extensions']>(decorator: (baseRenderer: (ctx: Readonly>>) => Promise, ctx: Readonly>>) => Promise): void; /** * Decorate the usage renderer. * * @typeParam L - An extensions type to specify the shape of {@linkcode CommandContext}'s extensions. * * @param decorator - A decorator function that wraps the base usage renderer. */ decorateUsageRenderer = DefaultGunshiParams['extensions']>(decorator: (baseRenderer: (ctx: Readonly>>) => Promise, ctx: Readonly>>) => Promise): void; /** * Decorate the validation errors renderer. * * @typeParam L - An extensions type to specify the shape of {@linkcode CommandContext}'s extensions. * * @param decorator - A decorator function that wraps the base validation errors renderer. */ decorateValidationErrorsRenderer = DefaultGunshiParams['extensions']>(decorator: (baseRenderer: (ctx: Readonly>>, error: AggregateError) => Promise, ctx: Readonly>>, error: AggregateError) => Promise): void; /** * Decorate the command execution. * * Decorators are applied in reverse order (last registered is executed first). * * @typeParam L - An extensions type to specify the shape of {@linkcode CommandContext}'s extensions. * * @param decorator - A decorator function that wraps the command runner */ decorateCommand = DefaultGunshiParams['extensions']>(decorator: (baseRunner: (ctx: Readonly>>) => Awaitable) => (ctx: Readonly>>) => Awaitable): void; } //#endregion //#region ../gunshi/src/plugin/core.d.ts type ProcessDependency = D extends string ? D extends keyof A ? { [K in D]: A[K] } : {} : D extends { id: infer ID; optional?: any; } ? ID extends string ? ID extends keyof A ? D extends { optional: true; } ? { [K in ID]: A[K] | undefined } : { [K in ID]: A[K] } : {} : never : never; /** * Helper type to infer dependency extensions with optional support * * @internal */ type InferDependencyExtensions, A extends ExtendContext> = D extends readonly [] ? {} : D extends readonly [infer First, ...infer Rest] ? ProcessDependency & (Rest extends ReadonlyArray ? InferDependencyExtensions : {}) : {}; /** * Plugin dependency definition * * @since v0.27.0 */ interface PluginDependency { /** * Dependency plugin id */ id: string; /** * Optional dependency flag. * If `true`, the plugin will not throw an error if the dependency is not found */ optional?: boolean; } /** * Plugin function type * * @typeParam G - A type extending {@linkcode GunshiParams} to specify the {@linkcode PluginContext}. * * @since v0.27.0 */ type PluginFunction = (ctx: Readonly>) => Awaitable; /** * Plugin extension * * @typeParam T - The type of the extension object returned by the plugin extension function. * @typeParam G - A type extending {@linkcode GunshiParams} to specify the shape of {@linkcode CommandContextCore}. * * @param ctx - The {@linkcode CommandContextCore | command context} core * @param cmd - The {@linkcode Command | command} to which the plugin is being applied * @returns An object of type T that represents the extension provided by the plugin * * @since v0.27.0 */ type PluginExtension, G extends GunshiParams = DefaultGunshiParams> = (ctx: CommandContextCore, cmd: Command) => Awaitable; /** * Plugin extension callback, which is called when the plugin is extended with `extension` option. * * @typeParam G - A type extending {@linkcode GunshiParams} to specify the shape of {@linkcode CommandContext} and {@linkcode Command}. * * @param ctx - The {@linkcode CommandContext | command context} * @param cmd - The {@linkcode Command | command} * * @since v0.27.0 */ type OnPluginExtension = (ctx: Readonly>, cmd: Readonly>) => Awaitable; type IsStringLiteral = string extends S ? false : true; type MergeExtension = Id extends infer I ? I extends string ? IsStringLiteral extends true ? ResolvedDepExt & { [K in I]: PluginExt } : ResolvedDepExt : ResolvedDepExt : ResolvedDepExt; /** * Extensions resolved from the declared plugin dependencies. * * @internal */ type DependencyExtensions, Context extends ExtendContext> = InferDependencyExtensions; /** * Gunshi params available while a plugin extension resolves its dependencies. * * @internal */ type DependencyParams, Context extends ExtendContext> = GunshiParams<{ args: Args; extensions: DependencyExtensions; }>; /** * Extensions available after applying the current plugin extension. * * @internal */ type MergedPluginExtensions, Context extends ExtendContext, Ext extends ExtendContext> = MergeExtension, Ext>; /** * Gunshi params available after applying the current plugin extension. * * @internal */ type MergedPluginParams, Context extends ExtendContext, Ext extends ExtendContext> = GunshiParams<{ args: Args; extensions: MergedPluginExtensions; }>; /** * Plugin definition options * * @since v0.27.0 */ interface PluginOptions = (PluginDependency | string)[], // for plugin dependencies Ext extends Record = {}, // for plugin extension type ResolvedDepExt extends GunshiParams = DependencyParams, PluginExt extends PluginExtension = PluginExtension, MergedExt extends GunshiParams = MergedPluginParams>>> { /** * Plugin unique identifier */ id: Id; /** * Plugin name */ name?: string; /** * Plugin dependencies */ dependencies?: Deps; /** * Plugin setup function */ setup?: PluginFunction; /** * Plugin extension */ extension?: PluginExt; /** * Callback for when the plugin is extended with `extension` option. */ onExtension?: OnPluginExtension; } /** * Gunshi plugin, which is a function that receives a PluginContext. * * @typeParam E - A type extending {@link GunshiParams} to specify the shape of {@linkcode CommandContext}'s extensions. * * @param ctx - A {@linkcode PluginContext}. * @returns An {@linkcode Awaitable} that resolves when the plugin is loaded. * * @since v0.27.0 */ type Plugin = PluginFunction & { id: string; name?: string; dependencies?: (PluginDependency | string)[]; extension?: CommandContextExtension; }; /** * Plugin return type with extension, which includes the plugin ID, name, dependencies, and extension. * * This type is used to define a plugin at `plugin` function. * * @typeParam E - A type extending {@link GunshiParams} to specify the shape of {@linkcode CommandContext}'s extensions. */ interface PluginWithExtension extends Plugin { /** * Plugin identifier */ id: string; /** * Plugin name */ name: string; /** * Plugin dependencies */ dependencies?: (PluginDependency | string)[]; /** * Plugin extension */ extension: CommandContextExtension; } /** * Plugin return type without extension, which includes the plugin ID, name, and dependencies, but no extension. * * This type is used to define a plugin at `plugin` function without extension. * * @typeParam E - A type extending {@link GunshiParams} to specify the shape of {@linkcode CommandContext}'s extensions. */ interface PluginWithoutExtension extends Plugin { /** * Plugin identifier */ id: string; /** * Plugin name */ name: string; /** * Plugin dependencies */ dependencies?: (PluginDependency | string)[]; } /** * Define a plugin with extension compatibility and typed dependency extensions * * @typeParam Context - A type extending {@linkcode ExtendContext} to specify the shape of plugin dependency extensions. * @typeParam Id - A string type to specify the plugin ID. * @typeParam Deps - A readonly array of {@linkcode PluginDependency} or string to specify the plugin dependencies. * @typeParam Extension - A type to specify the shape of the plugin extension object. * * @param options - {@linkcode PluginOptions | plugin options} * @returns A defined plugin with extension * * @since v0.27.0 */ declare function plugin = [], // for plugin dependencies Extension extends {} = {}, // for plugin extension type ResolvedDepExtensions extends GunshiParams = DependencyParams, PluginExt extends PluginExtension = PluginExtension, MergedExtensions extends GunshiParams = MergedPluginParams>>>(options: { id: Id; name?: string; dependencies?: Deps; setup?: (ctx: Readonly>>>>) => Awaitable; extension: PluginExt; onExtension?: OnPluginExtension; }): PluginWithExtension>>; /** * Define a plugin without extension and typed dependency extensions * * @typeParam Context - A type extending {@linkcode ExtendContext} to specify the shape of plugin dependency extensions. * @typeParam Id - A string type to specify the plugin ID. * @typeParam Deps - A readonly array of {@linkcode PluginDependency} or string to specify the plugin dependencies. * @typeParam Extension - A type to specify the shape of the plugin extension object. * * @param options - {@linkcode PluginOptions | plugin options} without extension * @returns A defined plugin without extension * * @since v0.27.0 */ declare function plugin = [], // for plugin dependencies Extension extends Record = {}, // for plugin extension type ResolvedDepExtensions extends GunshiParams = DependencyParams, PluginExt extends PluginExtension = PluginExtension, MergedExtensions extends GunshiParams = MergedPluginParams>>>(options: { id: Id; name?: string; dependencies?: Deps; setup?: (ctx: Readonly>>>>) => Awaitable; onExtension?: OnPluginExtension; }): PluginWithoutExtension; //#endregion //#region ../gunshi/src/types.d.ts /** * Awaitable type. * * @typeParam T - The type of the value that can be awaited. */ type Awaitable = T | Promise; /** * Prettify a type by flattening its structure. * * @typeParam T - The type to be prettified. */ type Prettify = { [K in keyof T]: T[K] } & {}; /** * Extend command context type. This type is used to extend the command context with additional properties at {@linkcode CommandContext.extensions}. * * @since v0.27.0 */ type ExtendContext = Record; /** * Gunshi unified parameter type. * * This type combines both argument definitions and command context extensions. * * @typeParam P - The type of parameters, which can include `args` and `extensions`. * * @since v0.27.0 */ interface GunshiParams

{ /** * Command argument definitions. */ args: P extends { args: infer A extends Args; } ? A : Args; /** * Command context extensions. */ extensions: P extends { extensions: infer E extends ExtendContext; } ? E : {}; } /** * Default Gunshi parameters. * * @since v0.27.0 */ type DefaultGunshiParams = GunshiParams; /** * Generic constraint for command-related types. * * This type constraint allows both {@linkcode GunshiParams} and objects with extensions. * * @since v0.27.0 */ type GunshiParamsConstraint = GunshiParams | { args: Args; } | { extensions: ExtendContext; }; /** * Type helper to extract args * * @typeParam G - The type of {@linkcode GunshiParams} or an object with {@linkcode Args}. * * @internal */ type ExtractArgs = G extends GunshiParams ? G['args'] : G extends { args: infer A extends Args; } ? A : Args; /** * Type helper to extract explicitly provided argument flags. * * @typeParam G - The type of {@linkcode GunshiParams}. * * @internal */ type ExtractArgExplicitlyProvided = ArgExplicitlyProvided>; /** * Type helper to extract extensions from G * * @internal */ type ExtractExtensions = G extends GunshiParams ? G['extensions'] : G extends { extensions: infer E; } ? E : {}; /** * Type helper to normalize G to GunshiParams * * @internal */ type NormalizeToGunshiParams = G extends GunshiParams ? G : G extends { args: infer A extends Args; extensions: infer E extends ExtendContext; } ? GunshiParams<{ args: A; extensions: E; }> : G extends { args: infer A extends Args; } ? GunshiParams<{ args: A; extensions: {}; }> : G extends { extensions: infer E extends ExtendContext; } ? GunshiParams<{ args: Args; extensions: E; }> : DefaultGunshiParams; /** * Type helper to merge command context extensions into G * * @internal */ type MergeGunshiExtensions = GunshiParams<{ /** * Command argument definitions. */ args: ExtractArgs; /** * Merged command context extensions. */ extensions: ExtractExtensions & E; }>; /** * Command environment. * * @typeParam G - A type extending {@linkcode GunshiParams} to specify the shape of command environments. */ interface CommandEnvironment { /** * Current working directory. * * @see {@linkcode CliOptions.cwd} */ cwd: string | undefined; /** * Command name. * * @see {@linkcode CliOptions.name} */ name: string | undefined; /** * Command description. * * @see {@linkcode CliOptions.description} */ description: string | undefined; /** * Command version. * * @see {@linkcode CliOptions.version} */ version: string | undefined; /** * Left margin of the command output. * * @default 2 * @see {@linkcode CliOptions.leftMargin} */ leftMargin: number; /** * Middle margin of the command output. * * @default 10 * @see {@linkcode CliOptions.middleMargin} */ middleMargin: number; /** * Whether to display the usage option type. * * @default false * @see {@linkcode CliOptions.usageOptionType} */ usageOptionType: boolean; /** * Whether to display the option value. * * @default true * @see {@linkcode CliOptions.usageOptionValue} */ usageOptionValue: boolean; /** * Whether to display the command usage. * * @default false * @see {@linkcode CliOptions.usageSilent} */ usageSilent: boolean; /** * Whether to treat undefined options as argument validation errors. * * @default false * @see {@linkcode CliOptions.strict} */ strict: boolean; /** * Sub commands. * * @see {@linkcode CliOptions.subCommands} */ subCommands: Map | LazyCommand> | undefined; /** * Render function the command usage. */ renderUsage: ((ctx: Readonly>) => Promise) | null | undefined; /** * Render function the header section in the command usage. */ renderHeader: ((ctx: Readonly>) => Promise) | null | undefined; /** * Render function the validation errors. */ renderValidationErrors: ((ctx: Readonly>, error: AggregateError) => Promise) | null | undefined; /** * Hook that runs before any command execution * * @see {@linkcode CliOptions.onBeforeCommand} * @since v0.27.0 */ onBeforeCommand: ((ctx: Readonly>) => Awaitable) | undefined; /** * Hook that runs after successful command execution * * @see {@linkcode CliOptions.onAfterCommand} * @since v0.27.0 */ onAfterCommand: ((ctx: Readonly>, result: string | undefined) => Awaitable) | undefined; /** * Hook that runs when a command throws an error * * @see {@linkcode CliOptions.onErrorCommand} * @since v0.27.0 */ onErrorCommand: ((ctx: Readonly>, error: Error) => Awaitable) | undefined; } /** * CLI options of {@linkcode cli} function. * * @typeParam G - A type extending {@linkcode GunshiParams} to specify the shape of cli options. */ interface CliOptions { /** * Current working directory. */ cwd?: string; /** * Command program name. */ name?: string; /** * Command program description. * */ description?: string; /** * Command program version. */ version?: string; /** * Sub commands. */ subCommands?: Record | Map; /** * Left margin of the command output. */ leftMargin?: number; /** * Middle margin of the command output. */ middleMargin?: number; /** * Whether to display the usage optional argument type. */ usageOptionType?: boolean; /** * Whether to display the optional argument value. */ usageOptionValue?: boolean; /** * Whether to display the command usage. */ usageSilent?: boolean; /** * Whether to treat undefined options as argument validation errors. * * When enabled, option tokens that are not declared by the resolved command * arguments or installed global options are reported as validation errors * before the command runner is executed. * * @default false */ strict?: boolean; /** * Render function the command usage. */ renderUsage?: ((ctx: Readonly>) => Promise) | null; /** * Render function the header section in the command usage. */ renderHeader?: ((ctx: Readonly>) => Promise) | null; /** * Render function the validation errors. */ renderValidationErrors?: ((ctx: Readonly>, error: AggregateError) => Promise) | null; /** * Whether to fallback to entry command when the sub-command is not found. * * @default false * @since v0.27.0 */ fallbackToEntry?: boolean; /** * User plugins. * * @since v0.27.0 */ plugins?: Plugin[]; /** * Hook that runs before any command execution * * @param ctx - The command context * @since v0.27.0 */ onBeforeCommand?: (ctx: Readonly>) => Awaitable; /** * Hook that runs after successful command execution * * @param ctx - The command context * @param result - The command execution result * @since v0.27.0 */ onAfterCommand?: (ctx: Readonly>, result: string | undefined) => Awaitable; /** * Hook that runs when a command throws an error * * @param ctx - The command context * @param error - The error thrown during execution * @since v0.27.0 */ onErrorCommand?: (ctx: Readonly>, error: Error) => Awaitable; } /** * Command call mode. * * - `entry`: The command is executed as an entry command. * - `subCommand`: The command is executed as a sub-command. */ type CommandCallMode = 'entry' | 'subCommand' | 'unexpected'; /** * Command context. * * Command context is the context of the command execution. * * @typeParam G - A type extending {@linkcode GunshiParams} to specify the shape of command context. */ interface CommandContext { /** * Command name, that is the command that is executed. * The command name is same {@linkcode CommandEnvironment.name}. */ name: string | undefined; /** * Command description, that is the description of the command that is executed. * The command description is same {@linkcode CommandEnvironment.description}. */ description: string | undefined; /** * Command environment, that is the environment of the command that is executed. * The command environment is same {@linkcode CommandEnvironment}. */ env: Readonly>; /** * Command arguments, that is the arguments of the command that is executed. * The command arguments is same {@linkcode Command.args}. */ args: ExtractArgs; /** * Whether arguments were explicitly provided by the user. * * - `true`: The argument was explicitly provided via command line * - `false`: The argument was not explicitly provided. This means either: * - The value comes from a default value defined in the argument schema * - The value is `undefined` (no explicit input and no default value) */ explicit: ExtractArgExplicitlyProvided; /** * Command values, that is the values of the command that is executed. * Resolve values with `resolveArgs` from command arguments and {@linkcode Command.args}. */ values: ArgValues>; /** * Command positionals arguments, that is the positionals of the command that is executed. * Resolve positionals with `resolveArgs` from command arguments. */ positionals: string[]; /** * Command rest arguments, that is the remaining argument not resolved by the optional command option delimiter `--`. */ rest: string[]; /** * Original command line arguments. * This argument is passed from `cli` function. */ _: string[]; /** * Argument tokens, that is parsed by `parseArgs` function. */ tokens: ArgToken[]; /** * Whether the currently executing command has been executed with the sub-command name omitted. */ omitted: boolean; /** * Command call mode. * The command call mode is `entry` when the command is executed as an entry command, and `subCommand` when the command is executed as a sub-command. */ callMode: CommandCallMode; /** * The path of nested sub-commands that were resolved to reach the current command. * * For example, if the user runs `git remote add`, `commandPath` would be `['remote', 'add']`. * For the entry command, this is an empty array. * * @since v0.28.0 */ commandPath: string[]; /** * Whether to convert the camel-case style argument name to kebab-case. * This context value is set from {@linkcode Command.toKebab} option. */ toKebab?: boolean; /** * Output a message. * * If {@linkcode CommandEnvironment.usageSilent} is true, the message is not output. * * @param message - an output message, see {@linkcode console.log} * @param optionalParams - an optional parameters, see {@linkcode console.log} */ log: (message?: any, ...optionalParams: any[]) => void; /** * Command context extensions. * * @since v0.27.0 */ extensions: keyof ExtractExtensions extends never ? any : ExtractExtensions; /** * Validation error from argument parsing. * This will be set if argument validation fails during CLI execution. */ validationError?: AggregateError; } /** * Readonly command context available to a command context extension factory. * * @typeParam G - A type extending {@linkcode GunshiParams} to specify the shape of command context. * * @since v0.27.0 */ type CommandContextCore = Readonly>; /** * Command context extension * * @typeParam E - A type extending {@linkcode GunshiParams.extensions} to specify the shape of the extension. * * @since v0.27.0 */ interface CommandContextExtension { /** * Plugin identifier */ readonly key: symbol; /** * Plugin extension factory */ readonly factory: (ctx: CommandContextCore, cmd: Command) => Awaitable; /** * Plugin extension factory after hook */ readonly onFactory?: (ctx: Readonly, cmd: Readonly) => Awaitable; } /** * Rendering control options * * @typeParam G - A type extending {@linkcode GunshiParams} to specify the shape of render options. * * @since v0.27.0 */ interface RenderingOptions { /** * Header rendering configuration * - `null`: Disable rendering * - `function`: Use custom renderer * - `undefined` (when omitted): Use default renderer */ header?: ((ctx: Readonly>) => Promise) | null; /** * Usage rendering configuration * - `null`: Disable rendering * - `function`: Use custom renderer * - `undefined` (when omitted): Use default renderer */ usage?: ((ctx: Readonly>) => Promise) | null; /** * Validation errors rendering configuration * - `null`: Disable rendering * - `function`: Use custom renderer * - `undefined` (when omitted): Use default renderer */ validationErrors?: ((ctx: Readonly>, error: AggregateError) => Promise) | null; } /** * Command interface. * * @typeParam G - The Gunshi parameters constraint */ interface Command { /** * Command name. * It's used to find command line arguments to execute from sub commands, and it's recommended to specify. */ name?: string; /** * Command description. * It's used to describe the command in usage and it's recommended to specify. */ description?: string; /** * Command arguments. * Each argument can include a description property to describe the argument in usage. */ args?: ExtractArgs; /** * Command examples. * examples of how to use the command. */ examples?: string | CommandExamplesFetcher; /** * Command runner. it's the command to be executed */ run?: CommandRunner; /** * Whether to convert the camel-case style argument name to kebab-case. * If you will set to `true`, All {@linkcode Command.args} names will be converted to kebab-case. */ toKebab?: boolean; /** * Whether this is an internal command. * Internal commands are not shown in help usage. * * @default false * @since v0.27.0 */ internal?: boolean; /** * Whether this command is an entry command. * * @default undefined * @since v0.27.0 */ entry?: boolean; /** * Rendering control options * * @since v0.27.0 */ rendering?: RenderingOptions; /** * Nested sub-commands for this command. * * Allows building command trees like `git remote add`. * Each key is the sub-command name, and the value is a command or lazy command. * * @since v0.28.0 */ subCommands?: Record | Map; } /** * Lazy command interface. * * Lazy command that's not loaded until it is executed. * * @typeParam G - The Gunshi parameters constraint * @typeParam D - The partial command definition provided to lazy function */ type LazyCommand> = {}> = { /** * Command load function */ (): Awaitable | CommandRunner>; } & (D extends { name: infer N; } ? { commandName: N; } : { commandName?: string; }) & Omit & Partial, keyof D | 'run' | 'name'>>; /** * Sub-command entry type for use in subCommands. * * This type uses a loose structural match to bypass TypeScript's contravariance issues * with function parameters, allowing any Command or LazyCommand to be used as a sub-command. * * @since v0.27.1 */ interface SubCommandable { /** * see {@link Command.name} */ name?: string; /** * see {@link Command.description} */ description?: string; /** * see {@link Command.args} */ args?: Args | Record; /** * see {@link Command.examples} */ examples?: string | ((...args: any[]) => any); /** * see {@link Command.run} */ run?: (...args: any[]) => any; /** * see {@link Command.toKebab} */ toKebab?: boolean; /** * see {@link Command.internal} */ internal?: boolean; /** * see {@link Command.entry} */ entry?: boolean; /** * see {@link Command.rendering} */ rendering?: any; /** * see {@link LazyCommand.commandName} */ commandName?: string; /** * Nested sub-commands for this command. * * @see {@link Command.subCommands} * @since v0.28.0 */ subCommands?: Record | Map; /** * Index signature to allow additional properties */ [key: string]: any; } /** * Command examples fetcher. * * @typeParam G - A type extending {@linkcode GunshiParams} to specify the shape of command context. * * @param ctx - A {@link CommandContext | command context} * @returns A fetched command examples. */ type CommandExamplesFetcher = (ctx: Readonly>) => Awaitable; /** * Command runner. * * @typeParam G - A type extending {@linkcode GunshiParams} to specify the shape of command context. * * @param ctx - A {@link CommandContext | command context} * @returns void or string (for CLI output) */ type CommandRunner = (ctx: Readonly>) => Awaitable; /** * Command decorator. * * A function that wraps a command runner to add or modify its behavior. * * @typeParam G - A type extending {@linkcode GunshiParams} to specify the shape of command context. * * @param baseRunner - The base command runner to decorate * @returns The decorated command runner * * @since v0.27.0 */ type CommandDecorator = (baseRunner: (ctx: Readonly>) => Awaitable) => (ctx: Readonly>) => Awaitable; /** * Renderer decorator type. * * A function that wraps a base renderer to add or modify its behavior. * * @typeParam T - The type of the rendered result. * @typeParam G - A type extending {@linkcode GunshiParams} to specify the shape of command context. * * @param baseRenderer - The base renderer function to decorate * @param ctx - The command context * @returns The decorated result * * @since v0.27.0 */ type RendererDecorator = (baseRenderer: (ctx: Readonly>) => Promise, ctx: Readonly>) => Promise; /** * Validation errors renderer decorator type. * A function that wraps a validation errors renderer to add or modify its behavior. * * @typeParam G - A type extending {@linkcode GunshiParams} to specify the shape of command context. * * @param baseRenderer - The base validation errors renderer function to decorate * @param ctx - The command context * @param error - The aggregate error containing validation errors * @returns The decorated result * * @since v0.27.0 */ type ValidationErrorsDecorator = (baseRenderer: (ctx: Readonly>, error: AggregateError) => Promise, ctx: Readonly>, error: AggregateError) => Promise; //#endregion //#region ../gunshi/src/constants.d.ts declare const ANONYMOUS_COMMAND_NAME = "(anonymous)"; declare const CLI_OPTIONS_DEFAULT: CliOptions; //#endregion //#region ../gunshi/src/context.d.ts /** * Extract extension return types from extensions record * * @internal */ type ExtractExtensionValues> = { [K in keyof E]: E[K] extends CommandContextExtension ? T : never }; /** * Return type of {@link createCommandContext} * * @internal */ type CommandContextResult> = {} extends ExtractExtensionValues ? Readonly> : Readonly; extensions: ExtractExtensionValues; }>>>; /** * Parameters of {@link createCommandContext} */ interface CommandContextParams>, C extends Command | LazyCommand = Command, E extends Record = Record> { /** * An arguments of target command */ args?: ExtractArgs; /** * Explicitly provided arguments */ explicit?: ExtractArgExplicitlyProvided; /** * A values of target command */ values?: V; /** * A positionals arguments, which passed to the target command */ positionals?: string[]; /** * A rest arguments, which passed to the target command */ rest?: string[]; /** * Original command line arguments */ argv?: string[]; /** * Argument tokens that are parsed by the `parseArgs` function */ tokens?: ArgToken[]; /** * Whether the command is omitted */ omitted?: boolean; /** * Command call mode. */ callMode?: CommandCallMode; /** * The path of nested sub-commands resolved to reach the current command. */ commandPath?: string[]; /** * A target command */ command?: C; /** * Plugin extensions to apply as the command context extension. */ extensions?: E; /** * A command options, which is spicialized from `cli` function */ cliOptions?: CliOptions; /** * Validation error from argument parsing. */ validationError?: AggregateError; } /** * Create a command context. * * @param param - A {@link CommandContextParams | parameters} to create a command context. * @returns A {@link CommandContext | command context}, which is readonly. */ declare function createCommandContext> = ArgValues>, C extends Command | LazyCommand = Command, E extends Record = {}>({ args, explicit, values, positionals, rest, argv, tokens, command, extensions, cliOptions, callMode, commandPath, omitted, validationError }: CommandContextParams): Promise>; //#endregion //#region ../gunshi/src/error.d.ts /** * @author kazuya kawaguchi (a.k.a. kazupon) * @license MIT */ /** * Command not found error resource keys. */ declare const CommandNotFoundErrorKeys: { readonly notFound: "err:cmd:not-found"; }; /** * Command not found error code. */ type CommandNotFoundErrorCode = (typeof CommandNotFoundErrorKeys)[keyof typeof CommandNotFoundErrorKeys]; /** * Options for {@link CommandNotFoundError}. */ type CommandNotFoundErrorOptions = { /** * Localization resource key for command-not-found rendering. */ code?: CommandNotFoundErrorCode; /** * Values used when localizing the message. */ values?: Record; /** * The command name that could not be resolved. */ commandName: string; /** * Command names available at the same level. */ candidates?: readonly string[]; /** * Parent command path where resolution failed. */ commandPath?: readonly string[]; /** * Underlying cause. */ cause?: unknown; }; /** * Error raised when a command cannot be resolved. */ declare class CommandNotFoundError extends Error { readonly code?: CommandNotFoundErrorCode; readonly values: Record; readonly commandName: string; readonly candidates: readonly string[]; readonly commandPath: readonly string[]; /** * Create a command-not-found error. * * @param message - Fallback error message * @param options - Command-not-found metadata */ constructor(message: string, options: CommandNotFoundErrorOptions); } /** * Check whether an error is a {@link CommandNotFoundError}. * * @param error - An unknown error * @returns `true` if the error is a {@link CommandNotFoundError} */ declare function isCommandNotFoundError(error: unknown): error is CommandNotFoundError; /** * Check whether validation errors should be handled before version, help, or command execution. * * @param error - An aggregate validation error * @returns `true` if the validation error must be handled with priority */ declare function hasPriorityValidationError(error: AggregateError | undefined): boolean; //#endregion //#region src/index.d.ts /** * @author kazuya kawaguchi (a.k.a. kazupon) * @license MIT */ //#endregion export { ANONYMOUS_COMMAND_NAME, type ArgSchema, type ArgToken, type ArgValues, type Args, ArgsValidationError, ArgsValidationErrorCode, ArgsValidationErrorKeys, Awaitable, CLI_OPTIONS_DEFAULT, Command, CommandContext, CommandContextCore, CommandContextExtension, CommandContextParams, CommandDecorator, CommandExamplesFetcher, CommandNotFoundError, CommandNotFoundErrorCode, CommandNotFoundErrorKeys, CommandNotFoundErrorOptions, CommandRunner, DefaultGunshiParams, ExtendContext, ExtractArgs, ExtractExtensions, GunshiParams, GunshiParamsConstraint, LazyCommand, MergeGunshiExtensions, NormalizeToGunshiParams, OnPluginExtension, Plugin, PluginContext, PluginDependency, PluginExtension, PluginFunction, PluginOptions, PluginWithExtension, PluginWithoutExtension, Prettify, RendererDecorator, ValidationErrorsDecorator, createCommandContext, hasPriorityValidationError, isArgsValidationError, isCommandNotFoundError, plugin };