or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# Optionator

1

2

Optionator is a JavaScript/Node.js option parsing and help generation library that provides strict type checking and validation. Unlike other option parsers that accept all input, Optionator validates options against specified types and provides intelligent error reporting with suggestions for misspelled options.

3

4

## Package Information

5

6

- **Package Name**: optionator

7

- **Package Type**: npm

8

- **Language**: JavaScript (compiled from LiveScript)

9

- **Installation**: `npm install optionator`

10

11

## Core Imports

12

13

```javascript

14

const optionator = require('optionator');

15

```

16

17

For ES modules (with transpilation):

18

19

```javascript

20

import optionator from 'optionator';

21

```

22

23

## Basic Usage

24

25

```javascript

26

const optionator = require('optionator')({

27

prepend: 'Usage: cmd [options]',

28

append: 'Version 1.0.0',

29

options: [{

30

option: 'help',

31

alias: 'h',

32

type: 'Boolean',

33

description: 'displays help'

34

}, {

35

option: 'count',

36

alias: 'c',

37

type: 'Int',

38

description: 'number of things',

39

example: 'cmd --count 2'

40

}]

41

});

42

43

// Parse command line arguments

44

const options = optionator.parseArgv(process.argv);

45

46

// Display help if needed

47

if (options.help) {

48

console.log(optionator.generateHelp());

49

}

50

51

console.log(options.count); // Parsed and validated count value

52

```

53

54

## Architecture

55

56

Optionator is built around a factory function that creates parser instances with configured options:

57

58

- **Factory Function**: Main export that creates optionator instances with configuration

59

- **Type System**: Integration with type-check and levn libraries for strict type validation

60

- **Help Generation**: Intelligent help text formatting that adapts to console width

61

- **Error Reporting**: Detailed error messages with suggestions for misspelled options

62

- **Validation Engine**: Comprehensive option validation including dependencies, mutual exclusivity, and requirements

63

64

## Capabilities

65

66

### Factory Function

67

68

Creates an optionator instance with the specified configuration options.

69

70

```javascript { .api }

71

/**

72

* Creates an optionator instance for parsing command line options

73

* @param {OptionatorConfig} config - Configuration object defining options and behavior

74

* @returns {OptionatorInstance} Parser instance with parse, parseArgv, generateHelp methods

75

*/

76

function optionator(config: OptionatorConfig): OptionatorInstance;

77

78

interface OptionatorConfig {

79

prepend?: string;

80

append?: string;

81

options: Array<OptionDefinition | HeadingDefinition>;

82

helpStyle?: HelpStyleConfig;

83

mutuallyExclusive?: Array<Array<string | Array<string>>>;

84

positionalAnywhere?: boolean;

85

typeAliases?: Record<string, string>;

86

defaults?: Partial<OptionDefinition>;

87

concatRepeatedArrays?: boolean | [boolean, Record<string, any>];

88

mergeRepeatedObjects?: boolean;

89

stdout?: NodeJS.WriteStream;

90

}

91

92

interface OptionDefinition {

93

option: string;

94

alias?: string | Array<string>;

95

type: string;

96

enum?: Array<string>;

97

default?: string;

98

description?: string;

99

longDescription?: string;

100

example?: string | Array<string>;

101

required?: boolean;

102

restPositional?: boolean;

103

overrideRequired?: boolean;

104

dependsOn?: string | Array<string>;

105

concatRepeatedArrays?: boolean | [boolean, Record<string, any>];

106

mergeRepeatedObjects?: boolean;

107

boolean?: boolean;

108

hidden?: boolean;

109

}

110

111

interface HeadingDefinition {

112

heading: string;

113

}

114

115

interface HelpStyleConfig {

116

aliasSeparator?: string;

117

typeSeparator?: string;

118

descriptionSeparator?: string;

119

initialIndent?: number;

120

secondaryIndent?: number;

121

maxPadFactor?: number;

122

}

123

124

interface OptionatorInstance {

125

parse: (input: string | Array<string> | Record<string, any>, options?: ParseOptions) => ParsedOptions;

126

parseArgv: (input: Array<string>) => ParsedOptions;

127

generateHelp: (options?: HelpOptions) => string;

128

generateHelpForOption: (optionName: string) => string;

129

}

130

```

131

132

### Parse Method

133

134

Processes input according to the configured options and returns parsed results.

135

136

```javascript { .api }

137

/**

138

* Processes input according to settings and returns parsed options

139

* @param {string | Array<string> | Record<string, any>} input - The input to parse

140

* @param {ParseOptions} options - Optional parsing configuration

141

* @returns {ParsedOptions} Object with parsed options and positional arguments

142

*/

143

parse(input: string | Array<string> | Record<string, any>, options?: ParseOptions): ParsedOptions;

144

145

interface ParseOptions {

146

slice?: number;

147

}

148

149

interface ParsedOptions {

150

[optionName: string]: any;

151

_: Array<string>;

152

}

153

```

154

155

**Usage Examples:**

156

157

```javascript

158

// Parse array of arguments

159

const result = optionator.parse(['--count', '5', 'file.txt']);

160

// Result: { count: 5, _: ['file.txt'] }

161

162

// Parse string input

163

const result = optionator.parse('--count 5 file.txt');

164

// Result: { count: 5, _: ['file.txt'] }

165

166

// Parse object input

167

const result = optionator.parse({ count: 5, _: ['file.txt'] });

168

// Result: { count: 5, _: ['file.txt'] }

169

```

170

171

### Parse Argv Method

172

173

Parses array input with automatic slicing for process.argv compatibility.

174

175

```javascript { .api }

176

/**

177

* Parses array input with default slice of 2 for process.argv

178

* @param {Array<string>} input - Array of command line arguments

179

* @returns {ParsedOptions} Object with parsed options and positional arguments

180

*/

181

parseArgv(input: Array<string>): ParsedOptions;

182

```

183

184

**Usage Example:**

185

186

```javascript

187

// Typically used with process.argv

188

const options = optionator.parseArgv(process.argv);

189

190

// Equivalent to: optionator.parse(process.argv, { slice: 2 })

191

```

192

193

### Generate Help Method

194

195

Produces formatted help text based on the configured options.

196

197

```javascript { .api }

198

/**

199

* Generates formatted help text based on configuration

200

* @param {HelpOptions} options - Optional help generation settings

201

* @returns {string} Formatted help text

202

*/

203

generateHelp(options?: HelpOptions): string;

204

205

interface HelpOptions {

206

showHidden?: boolean;

207

interpolate?: Record<string, string>;

208

}

209

```

210

211

**Usage Example:**

212

213

```javascript

214

console.log(optionator.generateHelp());

215

/*

216

Usage: cmd [options]

217

218

-h, --help displays help

219

-c, --count Int number of things

220

221

Version 1.0.0

222

*/

223

224

// With interpolation

225

console.log(optionator.generateHelp({

226

interpolate: { version: '2.1.0' }

227

}));

228

```

229

230

### Generate Help For Option Method

231

232

Generates detailed help text for a specific option.

233

234

```javascript { .api }

235

/**

236

* Generates detailed help text for a specific option

237

* @param {string} optionName - Name of the option to display help for

238

* @returns {string} Detailed help text for the option

239

*/

240

generateHelpForOption(optionName: string): string;

241

```

242

243

**Usage Example:**

244

245

```javascript

246

console.log(optionator.generateHelpForOption('count'));

247

/*

248

-c, --count Int

249

description: number of things

250

example: cmd --count 2

251

*/

252

```

253

254

### Version Property

255

256

Static version property available on the main export.

257

258

```javascript { .api }

259

/**

260

* Current version of the optionator library

261

*/

262

optionator.VERSION: string;

263

```

264

265

## Types

266

267

### Option Types

268

269

Optionator uses type-check format for type specifications. Common types include:

270

271

- `Boolean` - Boolean flags

272

- `Int` - Integer numbers

273

- `Number` - Floating point numbers

274

- `String` - Text strings

275

- `[String]` - Arrays of strings

276

- `{String: Number}` - Objects with string keys and number values

277

- `String | Number` - Union types

278

- `Maybe String` - Optional types

279

280

### Configuration Options

281

282

**Main Configuration Properties:**

283

284

- `prepend`: Text displayed before the options in help output

285

- `append`: Text displayed after the options in help output

286

- `options` (required): Array of option definitions and heading definitions

287

- `helpStyle`: Object configuring help text formatting

288

- `mutuallyExclusive`: Array of mutually exclusive option groups

289

- `positionalAnywhere`: Whether positional arguments can appear anywhere (default: true)

290

- `typeAliases`: Object defining type aliases for custom type names

291

- `defaults`: Default values applied to all option definitions

292

- `concatRepeatedArrays`: Global setting for concatenating repeated array values

293

- `mergeRepeatedObjects`: Global setting for merging repeated object values

294

- `stdout`: Output stream for help text (default: process.stdout)

295

296

**Option Definition Properties:**

297

298

- `option` (required): Option name in dash-case without leading dashes

299

- `alias`: String or array of alias names (single character for short flags)

300

- `type` (required): Type specification in type-check format

301

- `enum`: Array of allowed values (parsed by levn)

302

- `default`: Default value as string (parsed by levn)

303

- `description`: Short description for help text

304

- `longDescription`: Detailed description for individual option help

305

- `example`: Usage example(s) for option help

306

- `required`: Whether the option is required

307

- `restPositional`: Take all remaining arguments as positional

308

- `overrideRequired`: Override required validation when this option is used

309

- `dependsOn`: Other options this option depends on

310

- `concatRepeatedArrays`: Concatenate repeated array values instead of overwriting (can be boolean or [boolean, options])

311

- `mergeRepeatedObjects`: Merge repeated object values instead of overwriting

312

- `boolean`: Treat option as boolean flag (auto-set for Boolean type)

313

- `hidden`: Hide from help unless showHidden is true

314

315

**Mutual Exclusivity:**

316

317

```javascript

318

mutuallyExclusive: [

319

['verbose', 'quiet'], // --verbose and --quiet are mutually exclusive

320

[['output', 'o'], 'silent'] // --output/-o and --silent are mutually exclusive

321

]

322

```

323

324

**Dependencies:**

325

326

```javascript

327

dependsOn: 'config' // Simple dependency

328

dependsOn: ['and', 'user', 'pass'] // Requires both user AND pass

329

dependsOn: ['or', 'token', 'key'] // Requires either token OR key

330

```

331

332

## Special Features

333

334

### NUM Option Support

335

336

Optionator supports a special `-NUM` pattern for numeric flags (e.g., `-42`, `-3.14`):

337

338

```javascript

339

// Define NUM option

340

options: [{

341

option: 'NUM',

342

type: 'Number',

343

description: 'Set numeric value'

344

}]

345

346

// Usage: command -42 will set NUM option to 42

347

```

348

349

**Note**: NUM options cannot have aliases and are accessed via `-NUM` format.

350

351

### No-prefix Boolean Options

352

353

For Boolean options without aliases that default to true, optionator automatically enables no-prefix negation:

354

355

```javascript

356

// This Boolean option with default 'true' and no aliases

357

{ option: 'color', type: 'Boolean', default: 'true' }

358

359

// Can be negated with --no-color

360

```

361

362

## Error Handling

363

364

Optionator provides detailed error messages for various validation failures:

365

366

- **Invalid options**: Suggests closest matching option using Levenshtein distance

367

- **Type validation**: Shows expected vs received type with the invalid value

368

- **Missing required**: Lists which required options are missing

369

- **Mutual exclusivity**: Identifies conflicting options that cannot be used together

370

- **Dependencies**: Reports which dependency requirements are not met

371

- **Enum validation**: Shows which values are allowed for enum-type options

372

- **NUM option errors**: Reports when NUM option is used but not defined

373

374

Example error messages:

375

376

```

377

Invalid option '--halp' - perhaps you meant '--help'?

378

Invalid value for option 'count' - expected type Int, received value: abc.

379

Option --verbose is required.

380

The options --verbose and --quiet are mutually exclusive.

381

The option 'secure' did not have its dependencies met.

382

No -NUM option defined.

383

Only use 'no-' prefix for Boolean options, not with 'verbose'.

384

```