0
# yargs-parser
1
2
yargs-parser is the mighty option parser used by yargs for parsing command-line arguments. It provides comprehensive argument parsing capabilities with extensive configuration options, supporting various data types, complex option configurations, and advanced parsing features like dot-notation, camel-case expansion, and configurable parsing behaviors.
3
4
## Package Information
5
6
- **Package Name**: yargs-parser
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install yargs-parser`
10
11
## Core Imports
12
13
### Node.js
14
15
**ESM (ES Modules):**
16
```typescript
17
import parser from "yargs-parser";
18
19
// Individual utilities (separate import paths)
20
import { camelCase, decamelize, looksLikeNumber } from "yargs-parser";
21
import { tokenizeArgString } from "yargs-parser/build/lib/tokenize-arg-string.js";
22
```
23
24
**CommonJS:**
25
```javascript
26
const parser = require("yargs-parser");
27
28
// Access utilities via parser object
29
const { camelCase, decamelize, looksLikeNumber } = parser;
30
```
31
32
### Browser (ESM)
33
34
```html
35
<script type="module">
36
import parser from "https://unpkg.com/yargs-parser@22.0.0/browser.js";
37
38
// Utilities are available on the parser object
39
const { camelCase, decamelize, looksLikeNumber } = parser;
40
41
// Note: tokenizeArgString and config file loading not supported in browser
42
</script>
43
```
44
45
### Deno
46
47
```typescript
48
import parser from "https://deno.land/x/yargs_parser/deno.ts";
49
// or from specific version:
50
// import parser from "https://deno.land/x/yargs_parser@v22.0.0/deno.ts";
51
52
// Utilities available on parser object
53
const { camelCase, decamelize, looksLikeNumber } = parser;
54
55
// Note: Only .json config files supported in Deno
56
```
57
58
## Basic Usage
59
60
```typescript
61
import parser from "yargs-parser";
62
63
// Parse process arguments
64
const argv = parser(process.argv.slice(2));
65
console.log(argv);
66
67
// Parse string directly
68
const result = parser("--foo=99 --bar hello -x 33");
69
console.log(result);
70
// Output: { _: [], foo: 99, bar: 'hello', x: 33 }
71
72
// Parse with options
73
const parsed = parser(['--name', 'Alice', '--age', '25', '--verbose'], {
74
string: ['name'],
75
number: ['age'],
76
boolean: ['verbose']
77
});
78
console.log(parsed);
79
// Output: { _: [], name: 'Alice', age: 25, verbose: true }
80
```
81
82
## Architecture
83
84
yargs-parser is built around several key components:
85
86
- **Core Parser**: Main parsing function that handles argument tokenization and processing
87
- **Type System**: Complete TypeScript integration with detailed type definitions for all options and return values
88
- **Configuration Engine**: Extensive configuration system with 18+ behavioral options (camel-case expansion, dot-notation, etc.)
89
- **Platform Support**: Cross-platform compatibility with Node.js, browser, and Deno environments
90
- **String Utilities**: Built-in utility functions for camelCase conversion, number detection, and string manipulation
91
92
## Capabilities
93
94
### Core Parsing
95
96
Main argument parsing functionality that converts command-line arguments into structured JavaScript objects with extensive configuration options.
97
98
```typescript { .api }
99
function parser(args: string | any[], opts?: Partial<Options>): Arguments;
100
101
interface Arguments {
102
_: (string | number)[];
103
'--'?: (string | number)[];
104
[argName: string]: any;
105
}
106
```
107
108
[Core Parsing](./core-parsing.md)
109
110
### Detailed Parsing
111
112
Advanced parsing mode that returns comprehensive information including error details, alias mappings, and parsing metadata.
113
114
```typescript { .api }
115
function parser.detailed(args: string | any[], opts?: Partial<Options>): DetailedArguments;
116
117
interface DetailedArguments {
118
argv: Arguments;
119
error: Error | null;
120
aliases: Dictionary<string[]>;
121
newAliases: Dictionary<boolean>;
122
defaulted: Dictionary<boolean>;
123
configuration: Configuration;
124
}
125
```
126
127
[Detailed Parsing](./detailed-parsing.md)
128
129
### Configuration Options
130
131
Comprehensive parsing behavior configuration with 18+ options controlling how arguments are interpreted and processed.
132
133
```typescript { .api }
134
interface Configuration {
135
'boolean-negation': boolean;
136
'camel-case-expansion': boolean;
137
'combine-arrays': boolean;
138
'dot-notation': boolean;
139
'duplicate-arguments-array': boolean;
140
'flatten-duplicate-arrays': boolean;
141
'greedy-arrays': boolean;
142
'halt-at-non-option': boolean;
143
'nargs-eats-options': boolean;
144
'negation-prefix': string;
145
'parse-positional-numbers': boolean;
146
'parse-numbers': boolean;
147
'populate--': boolean;
148
'set-placeholder-key': boolean;
149
'short-option-groups': boolean;
150
'strip-aliased': boolean;
151
'strip-dashed': boolean;
152
'unknown-options-as-args': boolean;
153
}
154
```
155
156
[Configuration Options](./configuration.md)
157
158
### Parser Options
159
160
Parsing hints and type specifications that control how individual arguments are processed and coerced.
161
162
```typescript { .api }
163
interface Options {
164
alias: Dictionary<string | string[]>;
165
array: ArrayOption | ArrayOption[];
166
boolean: string | string[];
167
config: string | string[] | Dictionary<boolean | ConfigCallback>;
168
configObjects: Dictionary<any>[];
169
configuration: Partial<Configuration>;
170
coerce: Dictionary<CoerceCallback>;
171
count: string | string[];
172
default: Dictionary<any>;
173
envPrefix?: string;
174
narg: Dictionary<number>;
175
normalize: string | string[];
176
string: string | string[];
177
number: string | string[];
178
__: (format: any, ...param: any[]) => string;
179
key: Dictionary<any>;
180
}
181
```
182
183
[Parser Options](./parser-options.md)
184
185
### String Utilities
186
187
Built-in utility functions for string manipulation and number detection that are also exposed as part of the public API.
188
189
```typescript { .api }
190
function parser.camelCase(str: string): string;
191
function parser.decamelize(str: string, joinString?: string): string;
192
function parser.looksLikeNumber(x: null | undefined | number | string): boolean;
193
```
194
195
[String Utilities](./string-utilities.md)
196
197
### Argument String Tokenization
198
199
Low-level utility for tokenizing argument strings into arrays, handling quoted strings and escape sequences.
200
201
```typescript { .api }
202
function tokenizeArgString(argString: string | any[]): string[];
203
```
204
205
[Argument String Tokenization](./tokenize-arg-string.md)
206
207
## Types
208
209
### Core Types
210
211
```typescript { .api }
212
type ArgsInput = string | any[];
213
type ArgsOutput = (string | number)[];
214
215
interface Dictionary<T = any> {
216
[key: string]: T;
217
}
218
```
219
220
### Parser Types
221
222
```typescript { .api }
223
interface Parser {
224
(args: ArgsInput, opts?: Partial<Options>): Arguments;
225
detailed(args: ArgsInput, opts?: Partial<Options>): DetailedArguments;
226
camelCase(str: string): string;
227
decamelize(str: string, joinString?: string): string;
228
looksLikeNumber(x: null | undefined | number | string): boolean;
229
}
230
```
231
232
### Configuration Types
233
234
```typescript { .api }
235
type ArrayOption = string | {
236
key: string;
237
boolean?: boolean;
238
string?: boolean;
239
number?: boolean;
240
integer?: boolean;
241
};
242
243
type CoerceCallback = (arg: any) => any;
244
type ConfigCallback = (configPath: string) => { [key: string]: any } | Error;
245
```
246
247
### Advanced Types
248
249
```typescript { .api }
250
// Utility types for working with keys and values
251
type KeyOf<T> = {
252
[K in keyof T]: string extends K ? never : number extends K ? never : K
253
} extends { [_ in keyof T]: infer U } ? U : never;
254
255
type ValueOf<T> = T extends (infer U)[] ? U : T[keyof T];
256
257
// Internal flag management types
258
type StringFlag = Dictionary<string[]>;
259
type BooleanFlag = Dictionary<boolean>;
260
type NumberFlag = Dictionary<number>;
261
type ConfigsFlag = Dictionary<string | string[] | boolean | ConfigCallback>;
262
type CoercionsFlag = Dictionary<CoerceCallback>;
263
type KeysFlag = string[];
264
265
interface Flags {
266
aliases: StringFlag;
267
arrays: BooleanFlag;
268
bools: BooleanFlag;
269
strings: BooleanFlag;
270
numbers: BooleanFlag;
271
counts: BooleanFlag;
272
normalize: BooleanFlag;
273
configs: ConfigsFlag;
274
nargs: NumberFlag;
275
coercions: CoercionsFlag;
276
keys: KeysFlag;
277
}
278
279
type Flag = ValueOf<Omit<Flags, 'keys'>>;
280
type FlagValue = ValueOf<Flag>;
281
type FlagsKey = KeyOf<Omit<Flags, 'keys'>>;
282
type ArrayFlagsKey = Extract<FlagsKey, 'bools' | 'strings' | 'numbers'>;
283
284
// Parser mixin interface for platform-specific implementations
285
interface YargsParserMixin {
286
cwd: Function;
287
format: Function;
288
normalize: Function;
289
require: Function;
290
resolve: Function;
291
env: Function;
292
}
293
294
// Default values configuration
295
enum DefaultValuesForTypeKey {
296
BOOLEAN = 'boolean',
297
STRING = 'string',
298
NUMBER = 'number',
299
ARRAY = 'array',
300
}
301
302
interface DefaultValuesForType {
303
[DefaultValuesForTypeKey.BOOLEAN]: boolean;
304
[DefaultValuesForTypeKey.STRING]: string;
305
[DefaultValuesForTypeKey.NUMBER]: undefined;
306
[DefaultValuesForTypeKey.ARRAY]: any[];
307
}
308
309
type OptionsDefault = ValueOf<Pick<Required<Options>, 'default'>>;
310
```