CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-yargs

Command-line argument parsing library for Node.js with commands, options, and validation.

Overview
Eval results
Files

validation.mddocs/

Validation and Requirements

Validate arguments, define required options and commands, and set up option relationships.

Capabilities

Required Commands

Specify minimum and maximum number of commands.

/**
 * Require minimum/maximum number of commands
 * @param min - Minimum number of commands (default: 1)
 * @param max - Maximum number of commands
 * @param minMsg - Message for too few commands
 * @param maxMsg - Message for too many commands
 * @returns YargsInstance for chaining
 */
demandCommand(min?: number, max?: number | string, minMsg?: string | null, maxMsg?: string | null): YargsInstance;

Usage Examples:

// Require at least one command
yargs()
  .command('start', 'start service')
  .command('stop', 'stop service')
  .demandCommand(1, 'You need at least one command before moving on')
  .parse();

// Require exactly one command
yargs()
  .command('build', 'build project')
  .command('test', 'run tests')
  .demandCommand(1, 1, 'Specify exactly one command', 'Too many commands specified')
  .parse();

// Custom error messages
yargs()
  .command('deploy', 'deploy app')
  .demandCommand(1, 'Please specify a command to run')
  .parse();

Required Options

Make specific options mandatory.

/**
 * Make options required
 * @param keys - Option name(s) or requirements object
 * @param msg - Error message for missing option
 * @returns YargsInstance for chaining
 */
demandOption(keys: string | string[] | Dictionary<string | undefined>, msg?: string): YargsInstance;

/**
 * Require options or commands (legacy)
 * @param keys - Option/command requirements
 * @param max - Maximum value or error message
 * @param msg - Error message
 * @returns YargsInstance for chaining
 */
demand(keys: string | string[] | Dictionary<string | undefined> | number, max?: number | string[] | string | true, msg?: string | true): YargsInstance;

/**
 * Alias for demand()
 */
required(keys: string | string[] | Dictionary<string | undefined> | number, max?: number | string[] | string | true, msg?: string | true): YargsInstance;

/**
 * Alias for demand()
 */
require(keys: string | string[] | Dictionary<string | undefined> | number, max?: number | string[] | string | true, msg?: string | true): YargsInstance;

Usage Examples:

// Single required option
yargs()
  .option('config', { describe: 'Configuration file' })
  .demandOption('config', 'Please provide a config file')
  .parse();

// Multiple required options
yargs()
  .options({
    username: { describe: 'Username' },
    password: { describe: 'Password' }
  })
  .demandOption(['username', 'password'])
  .parse();

// Required options with custom messages
yargs()
  .demandOption({
    username: 'Username is required for authentication',
    password: 'Password is required for authentication'
  })
  .parse();

Option Conflicts

Define mutually exclusive options.

/**
 * Define conflicting options
 * @param key1 - First option or conflicts map
 * @param key2 - Second option name(s)
 * @returns YargsInstance for chaining
 */
conflicts(key1: string | Dictionary<string | string[]>, key2?: string | string[]): YargsInstance;

Usage Examples:

// Two conflicting options
yargs()
  .option('json', { describe: 'Output as JSON' })
  .option('xml', { describe: 'Output as XML' })
  .conflicts('json', 'xml')
  .parse();

// Multiple conflicts
yargs()
  .conflicts({
    json: ['xml', 'yaml'],
    verbose: 'quiet',
    stdin: 'file'
  })
  .parse();

Option Implications

Define options that require other options.

/**
 * Define option implications (if X then Y is required)
 * @param key - Option name or implications map
 * @param value - Implied option name(s)
 * @returns YargsInstance for chaining
 */
implies(key: string | Dictionary<string | number | (string | number)[]>, value?: string | number | (string | number)[]): YargsInstance;

Usage Examples:

// Single implication
yargs()
  .option('ssl', { describe: 'Enable SSL' })
  .option('cert', { describe: 'SSL certificate path' })
  .implies('ssl', 'cert')
  .parse();

// Multiple implications
yargs()
  .implies({
    ssl: ['cert', 'key'],
    auth: 'username',
    database: ['host', 'port']
  })
  .parse();

// Positional implications
yargs()
  .command('deploy <env>', 'deploy to environment')
  .implies('env', 'config')  // If env positional is provided, config is required
  .parse();

Custom Validation

Add custom validation functions.

/**
 * Add custom validation function
 * @param f - Validation function that receives argv and options
 * @param global - Whether validation applies globally or just to current context
 * @returns YargsInstance for chaining
 */
check(f: (argv: Arguments, options: Options) => any, global?: boolean): YargsInstance;

Usage Examples:

// Port range validation
yargs()
  .option('port', { type: 'number' })
  .check((argv) => {
    if (argv.port && (argv.port < 1 || argv.port > 65535)) {
      throw new Error('Port must be between 1 and 65535');
    }
    return true;
  })
  .parse();

// File existence validation
yargs()
  .option('input', { describe: 'Input file' })
  .check((argv) => {
    if (argv.input && !require('fs').existsSync(argv.input)) {
      throw new Error(`Input file does not exist: ${argv.input}`);
    }
    return true;
  })
  .parse();

// Async validation
yargs()
  .option('url', { describe: 'URL to validate' })
  .check(async (argv) => {
    if (argv.url) {
      try {
        await fetch(argv.url);
        return true;
      } catch (error) {
        throw new Error(`URL is not accessible: ${argv.url}`);
      }
    }
    return true;
  })
  .parse();

// Global validation (applies to all commands)
yargs()
  .check((argv) => {
    if (argv.debug && argv.quiet) {
      throw new Error('Cannot use --debug and --quiet together');
    }
    return true;
  }, true)
  .parse();

Strict Mode

Enable strict parsing to catch unknown options and commands.

/**
 * Enable strict mode for unknown options/commands
 * @param enabled - Whether to enable strict mode
 * @returns YargsInstance for chaining
 */
strict(enabled?: boolean): YargsInstance;

/**
 * Enable strict mode for unknown commands only
 * @param enabled - Whether to enable strict command mode
 * @returns YargsInstance for chaining
 */
strictCommands(enabled?: boolean): YargsInstance;

/**
 * Enable strict mode for unknown options only
 * @param enabled - Whether to enable strict option mode
 * @returns YargsInstance for chaining
 */
strictOptions(enabled?: boolean): YargsInstance;

Usage Examples:

// Full strict mode
yargs()
  .option('verbose', { type: 'boolean' })
  .command('build', 'build project')
  .strict()
  .parse();
// Will error on: --unknown-option or unknown-command

// Strict commands only
yargs()
  .command('start', 'start service')
  .command('stop', 'stop service')
  .strictCommands()
  .parse();
// Will error on unknown commands but allow unknown options

// Strict options only
yargs()
  .option('port', { type: 'number' })
  .strictOptions()
  .parse();
// Will error on unknown options but allow unknown commands

Deprecation

Mark options as deprecated with warnings.

/**
 * Mark option as deprecated
 * @param option - Option name to deprecate
 * @param message - Deprecation message or true for default message
 * @returns YargsInstance for chaining
 */
deprecateOption(option: string, message: string | boolean): YargsInstance;

Usage Examples:

// Basic deprecation
yargs()
  .option('old-option', { describe: 'Legacy option' })
  .deprecateOption('old-option', 'Use --new-option instead')
  .parse();

// Default deprecation message
yargs()
  .option('legacy', { describe: 'Legacy flag' })
  .deprecateOption('legacy', true)
  .parse();

Getters for Validation State

Retrieve current validation configuration.

/**
 * Get demanded options configuration
 * @returns Object containing required options
 */
getDemandedOptions(): Dictionary<string | undefined>;

/**
 * Get demanded commands configuration
 * @returns Object containing command requirements
 */
getDemandedCommands(): Dictionary<{ min: number; max: number; minMsg?: string; maxMsg?: string }>;

/**
 * Get deprecated options configuration
 * @returns Object containing deprecated options and their messages
 */
getDeprecatedOptions(): Dictionary<string | boolean | undefined>;

/**
 * Get current strict mode settings
 * @returns Whether strict mode is enabled
 */
getStrict(): boolean;

/**
 * Get strict commands setting
 * @returns Whether strict commands mode is enabled
 */
getStrictCommands(): boolean;

/**
 * Get strict options setting
 * @returns Whether strict options mode is enabled
 */
getStrictOptions(): boolean;

Usage Examples:

const yarg = yargs()
  .demandOption('config')
  .strict()
  .deprecateOption('old', 'Use new instead');

console.log('Required options:', yarg.getDemandedOptions());
console.log('Strict mode:', yarg.getStrict());
console.log('Deprecated options:', yarg.getDeprecatedOptions());

Types

/**
 * Validation function type
 */
type ValidationFunction = (argv: Arguments, options: Options) => any;

/**
 * Options object containing parser configuration
 */
interface Options {
  alias: Dictionary<string[]>;
  array: string[];
  boolean: string[];
  choices: Dictionary<string[]>;
  config: Dictionary<Function | boolean>;
  configObjects: Dictionary[];
  configuration: Configuration;
  count: string[];
  defaultDescription: Dictionary<string | undefined>;
  demandedCommands: Dictionary<{
    min: number;
    max: number;
    minMsg?: string | null;
    maxMsg?: string | null;
  }>;
  demandedOptions: Dictionary<string | undefined>;
  deprecatedOptions: Dictionary<string | boolean | undefined>;
  hiddenOptions: string[];
  key: Dictionary<boolean | string>;
  local: string[];
  normalize: string[];
  number: string[];
  showHiddenOpt: string;
  skipValidation: string[];
  string: string[];
}

Install with Tessl CLI

npx tessl i tessl/npm-yargs

docs

command-system.md

core-parser.md

help-output.md

index.md

option-definition.md

parsing.md

validation.md

tile.json