@vvlad1973/args-parser
v1.0.1
Published
Lightweight TypeScript argument parser for CLI with validation, choices, and conditional requirements
Maintainers
Readme
Args Parser
Lightweight TypeScript argument parser for command-line interfaces with validation, choices, and conditional requirements.
Features
- Positional arguments with validation
- Named flags with short aliases
- Type-safe parsing (string, number, boolean)
- Conditional requirements based on context
- Choices validation
- Custom validation functions
- Conflicting flags detection
- Multiple values support
- Rest arguments
- Default values
- Auto-generated usage and help text
- Zero dependencies
Installation
npm install @vvlad1973/args-parserQuick Start
import { ArgParser } from '@vvlad1973/args-parser';
const result = ArgParser.parse('deploy production --verbose', [
{ name: 'command', required: true, choices: ['deploy', 'build', 'test'] },
{ name: 'target', required: true },
{ name: '--verbose', alias: '-v', type: 'boolean', help: 'Verbose output' }
], 'myapp');
console.log(result.args.command); // 'deploy'
console.log(result.args.target); // 'production'
console.log(result.flags['--verbose']); // true
console.log(result.help); // Auto-generated help textAPI Reference
ArgParser.parse(input, definitions, commandName?)
Parses command-line arguments according to provided definitions.
Parameters:
input:string | string[]- Input string or arguments arraydefinitions:ArgDefinition[]- Array of argument definitionscommandName:string(optional) - Command name for usage string
Returns: ParseResult
interface ParseResult {
raw: string; // Original input
args: Record<string, ParsedValue | undefined>; // Positional arguments
flags: Record<string, ParsedValue | undefined>; // Named flags
usage: string; // Usage string
help: string; // Help text
}ArgDefinition
Argument definition interface:
interface ArgDefinition {
name: string; // Argument name (e.g., 'user' or '--force')
alias?: string; // Short alias (e.g., '-f' for '--force')
type?: 'string' | 'number' | 'boolean'; // Argument type (default: 'string')
required?: boolean | ((context) => boolean); // Required flag or function
rest?: boolean; // Accept all remaining tokens
multiple?: boolean; // Allow multiple values
help?: string; // Help text
validate?: (value, context) => boolean; // Custom validation
choices?: string[]; // List of valid choices
conflicts?: string[]; // Mutually exclusive flags
default?: ParsedValue; // Default value
}Examples
Basic Positional Arguments
const result = ArgParser.parse('john doe', [
{ name: 'firstName' },
{ name: 'lastName' }
]);
console.log(result.args.firstName); // 'john'
console.log(result.args.lastName); // 'doe'Flags with Aliases
const result = ArgParser.parse('-v -o output.txt', [
{ name: '--verbose', alias: '-v', type: 'boolean' },
{ name: '--output', alias: '-o', type: 'string' }
]);
console.log(result.flags['--verbose']); // true
console.log(result.flags['--output']); // 'output.txt'Required Arguments
const result = ArgParser.parse('deploy', [
{ name: 'command', required: true },
{ name: 'target', required: true }
]);
// Throws: ArgParseError: Argument target is requiredConditional Requirements
const result = ArgParser.parse('deploy production', [
{ name: 'command', choices: ['deploy', 'build', 'list'] },
{
name: 'target',
required: ctx => ctx.command === 'deploy' // Required only for 'deploy'
}
]);Choices Validation
const result = ArgParser.parse('json', [
{
name: 'format',
choices: ['json', 'yaml', 'xml'],
help: 'Output format'
}
]);Custom Validation
const result = ArgParser.parse('--port 8080', [
{
name: '--port',
type: 'number',
validate: (val) => val >= 1 && val <= 65535,
help: 'Server port (1-65535)'
}
]);Conflicting Flags
const result = ArgParser.parse('--json --raw', [
{ name: '--json', type: 'boolean', conflicts: ['--raw'] },
{ name: '--raw', type: 'boolean' }
]);
// Throws: ArgParseError: Flags --json and --raw are mutually exclusiveMultiple Values
const result = ArgParser.parse('--tag alpha --tag beta --tag gamma', [
{
name: '--tag',
type: 'string',
multiple: true,
help: 'Add tags (can be repeated)'
}
]);
console.log(result.flags['--tag']); // ['alpha', 'beta', 'gamma']Rest Arguments
const result = ArgParser.parse('git commit -m Initial commit', [
{ name: 'command' },
{ name: 'subcommand' },
{ name: 'args', rest: true } // Captures all remaining tokens
]);
console.log(result.args.args); // '-m Initial commit'Default Values
const result = ArgParser.parse('', [
{ name: 'format', default: 'json' },
{ name: '--verbose', type: 'boolean', default: false }
]);
console.log(result.args.format); // 'json'
console.log(result.flags['--verbose']); // falseComplex Example
const definitions = [
{
name: 'command',
required: true,
choices: ['deploy', 'build', 'test'],
help: 'Command to execute'
},
{
name: 'target',
required: ctx => ctx.command === 'deploy',
help: 'Deployment target'
},
{
name: '--env',
alias: '-e',
type: 'string',
choices: ['dev', 'staging', 'prod'],
default: 'dev',
help: 'Environment'
},
{
name: '--verbose',
alias: '-v',
type: 'boolean',
default: false,
help: 'Verbose output'
},
{
name: '--tag',
type: 'string',
multiple: true,
help: 'Tags to apply'
},
{
name: '--dry-run',
type: 'boolean',
conflicts: ['--force'],
help: 'Dry run mode'
},
{
name: '--force',
type: 'boolean',
help: 'Force operation'
}
];
const result = ArgParser.parse(
'deploy production -e prod -v --tag release --tag v1.0.0',
definitions,
'mycli'
);
console.log(result.help);
// Usage: mycli <command:deploy|build|test> [target] [--env <string>] [--verbose] [--tag <string>...] [--dry-run] [--force]
//
// Arguments:
// command Command to execute (required)
// target Deployment target
//
// Options:
// --env, -e Environment
// --verbose, -v Verbose output
// --tag Tags to apply (can be repeated)
// --dry-run Dry run mode
// --force Force operationError Handling
The parser throws ArgParseError with descriptive messages and usage information:
try {
const result = ArgParser.parse('--port invalid', [
{ name: '--port', type: 'number' }
], 'myapp');
} catch (err) {
if (err instanceof ArgParseError) {
console.error(err.message); // "Invalid number: invalid"
console.error(err.usage); // "Usage: myapp [--port <number>]"
}
}TypeScript Support
Full TypeScript support with exported types:
import {
ArgParser,
ArgParseError,
type ArgDefinition,
type ParseResult,
type ParsedValue
} from '@vvlad1973/args-parser';Comparison with minimist
See COMPARISON.md for detailed comparison with minimist.
Key advantages:
- Declarative validation (required, choices, custom validators)
- Conditional requirements
- Auto-generated help and usage
- Type-safe parsing
- Conflicting flags detection
- Better error messages
License
MIT with Commercial Use
Author
Vladislav Vnukovskiy [email protected]
