or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-mri

Fast and lightweight CLI argument parsing library alternative to minimist and yargs-parser

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/mri@1.2.x

To install, run

npx @tessl/cli install tessl/npm-mri@1.2.0

index.mddocs/

MRI

MRI is a fast and lightweight alternative to minimist and yargs-parser for parsing CLI flags and arguments. It provides core argument parsing functionality with support for boolean flags, string values, numeric values, aliases, defaults, and unknown flag detection. The library is designed for high performance (5x faster than minimist, 40x faster than yargs-parser) with minimal dependencies, making it ideal for CLI tools and command-line applications.

Package Information

  • Package Name: mri
  • Package Type: npm
  • Language: JavaScript (with TypeScript definitions)
  • Installation: npm install mri

Core Imports

CommonJS (primary export format):

const mri = require('mri');

ES Modules:

import mri from 'mri';

TypeScript:

import mri from 'mri';
// or
import mri, { Options, Argv } from 'mri';

Basic Usage

import mri from 'mri';

// Parse command line arguments
const argv = process.argv.slice(2);

// Basic parsing
const parsed = mri(argv);
// Example: ['--foo', '--bar=baz', '-mtv', 'hello', 'world']
// Result: { _: ['hello', 'world'], foo: true, bar: 'baz', m: true, t: true, v: true }

// With configuration options
const parsed = mri(argv, {
  boolean: ['verbose', 'debug'],
  string: ['name', 'output'],
  alias: {
    v: 'verbose',
    d: 'debug', 
    n: 'name',
    o: 'output'
  },
  default: {
    verbose: false,
    output: 'result.txt'
  }
});

Architecture

MRI is built around a single-pass argument parser with several key design principles:

  • Minimal Dependencies: Zero runtime dependencies for maximum compatibility and performance
  • Type Coercion Engine: Automatic detection and conversion of numeric values while respecting type hints
  • Alias Resolution System: Bidirectional alias mapping that maintains consistency across all related option names
  • Lazy Evaluation: Options like boolean, string, and default are processed during parsing for optimal performance
  • Strict Mode Support: Optional unknown flag detection via the unknown callback when combined with alias definitions
  • Stream Processing: Single-pass parsing that handles argument termination (--) and maintains order for non-option arguments

The parser uses character-level analysis for flag detection and supports both POSIX-style short options (-abc) and GNU-style long options (--flag=value).

Capabilities

Main Parsing Function

Parses command line arguments with configurable options for type coercion, aliases, and defaults.

/**
 * Parse command line arguments into an object
 * @param args - Array of command line arguments to parse
 * @param options - Configuration options for parsing behavior
 * @returns Parsed arguments object with _ array for non-option arguments
 */
function mri(args?: string[], options?: Options): Argv;

Usage Examples:

// Basic flag parsing
mri(['--foo', '--bar=value', 'arg1', 'arg2']);
// { _: ['arg1', 'arg2'], foo: true, bar: 'value' }

// Short flag groups
mri(['-abc']);
// { _: [], a: true, b: true, c: true }

// Negation flags
mri(['--no-cache']);
// { _: [], cache: false }

// Mixed values with type coercion
mri(['--port', '3000', '--name', 'server', '--debug']);
// { _: [], port: 3000, name: 'server', debug: true }

// Multiple values create arrays
mri(['-v', 'a', '-v', 'b', '-v', 'c']);
// { _: [], v: ['a', 'b', 'c'] }

// Argument termination
mri(['--verbose', '--', '--not-a-flag', 'value']);
// { _: ['--not-a-flag', 'value'], verbose: true }

Type Configuration

Control type coercion for specific keys.

// Force boolean parsing for specific keys
mri(['--verbose', 'true'], { boolean: ['verbose'] });
// { _: [], verbose: true }

// Force string parsing for specific keys  
mri(['--port', '3000'], { string: ['port'] });
// { _: [], port: '3000' }

// Multiple keys can be specified as array or single string
mri(args, { boolean: ['debug', 'verbose'] });
mri(args, { string: 'output' });

Alias Configuration

Define alternative names for options.

// Single alias
mri(['-v'], { alias: { v: 'verbose' } });
// { _: [], v: true, verbose: true }

// Multiple aliases for one key
mri(['-h'], { alias: { help: ['h', '?'] } });
// { _: [], h: true, help: true, '?': true }

// Bidirectional alias relationships
const options = {
  alias: {
    verbose: 'v',
    output: ['o', 'out']
  }
};

Default Values

Provide default values and automatic type inference.

const options = {
  default: {
    port: 8080,          // number default
    verbose: false,      // boolean default
    output: 'build/',    // string default
    tags: []            // array default
  }
};

// Defaults are applied when keys are missing
mri([], options);
// { _: [], port: 8080, verbose: false, output: 'build/', tags: [] }

// Type of default determines parsing behavior
mri(['--port', 'value'], options);
// { _: ['value'], port: 8080 } - 'value' becomes non-option since port expects number

// Boolean defaults with flag values
mri(['--verbose', 'false'], { default: { verbose: true } });
// { _: [], verbose: false } - 'false' string is coerced to boolean false

Unknown Flag Handling

Handle unknown flags with custom callback.

/**
 * Callback function for handling unknown flags
 * @param flag - The unknown flag that was encountered
 */
type UnknownHandler = (flag: string) => void;

const options = {
  alias: { v: 'verbose' }, // Required for strict mode
  unknown: (flag) => {
    console.error(`Unknown flag: ${flag}`);
    process.exit(1);
  }
};

// Parsing stops when unknown flag encountered
mri(['--verbose', '--invalid'], options);
// Calls unknown('--invalid') and parsing terminates

Types

Options Interface

Configuration object for customizing parsing behavior.

interface Options {
  /** Keys that should be parsed as boolean values */
  boolean?: string | string[];
  
  /** Keys that should be parsed as string values */
  string?: string | string[];
  
  /** Mapping of aliases - key can map to string or array of strings */
  alias?: Record<string, string | string[]>;
  
  /** Default values for keys - type determines parsing behavior */
  default?: Record<string, any>;
  
  /** Callback for handling unknown flags (requires alias to be set) */
  unknown?: (flag: string) => void;
}

Argv Result Type

The result object returned by the mri function.

type Argv<T = Record<string, any>> = T & {
  /** Array of non-option arguments */
  _: string[];
};

Utility Types

Helper types used in the TypeScript definitions.

/** Generic dictionary/record type */
type Dict<T> = Record<string, T>;

/** Type that can be a single value or array of values */
type Arrayable<T> = T | T[];

/** Default type for the returned argv object */
type Default = Dict<any>;

Parsing Behavior

Flag Recognition

  • Long flags: --flag, --flag=value, --flag value
  • Short flags: -f, -f=value, -f value
  • Short flag groups: -abc becomes {a: true, b: true, c: true}
  • Negation: --no-flag becomes {flag: false}
  • Termination: -- stops parsing, remaining args go to _ array

Type Coercion

  • Numbers: Automatic conversion when valid ("123"123, "0"0)
  • Booleans: true for flags without values, false for --no- prefixed flags
  • Strings: Default for values that can't be coerced to numbers
  • Arrays: Multiple values for same key create arrays (e.g., -v a -v b{v: ['a', 'b']})

Alias Resolution

  • All aliases are bidirectional - setting any alias sets all related names
  • Alias chains are fully resolved (if a aliases to b and b aliases to c, all three are set)
  • Aliases apply to boolean, string, and default configurations automatically

Error Handling

  • Unknown flags: Only checked when both unknown callback and alias object are provided
  • Type conflicts: Default value type takes precedence over inferred type
  • Invalid usage: Parsing continues with best-effort approach, no exceptions thrown