@bemoje/cli 3.0.0 → 3.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +475 -0
- package/index.mjs +53 -86
- package/package.json +1 -1
package/README.md
ADDED
|
@@ -0,0 +1,475 @@
|
|
|
1
|
+
# @bemoje/cli
|
|
2
|
+
|
|
3
|
+
A type-safe CLI framework for building command-line interfaces with typed arguments, options, subcommands, and
|
|
4
|
+
auto-generated help - without execution coupling.
|
|
5
|
+
|
|
6
|
+
[](https://www.typescriptlang.org/)
|
|
7
|
+
[](https://nodejs.org/api/esm.html)
|
|
8
|
+
|
|
9
|
+
## Installation
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @bemoje/cli
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Features
|
|
16
|
+
|
|
17
|
+
- **Full type inference** - Arguments, options, and parsed results are fully typed. The types update as you chain
|
|
18
|
+
`.addArgument()` and `.addOption()` calls.
|
|
19
|
+
- **Declarative, chainable API** - Build commands fluently with method chaining; each call returns a narrowed type.
|
|
20
|
+
- **Subcommand hierarchies** - Nest commands arbitrarily deep. Options are inherited by subcommands. Aliases are
|
|
21
|
+
auto-generated.
|
|
22
|
+
- **Auto-generated help** - Colorized, grouped, and wrapped help output from your command definitions. Fully
|
|
23
|
+
customizable via the `Help` class.
|
|
24
|
+
- **Built-in `--help`, `--debug`, and `--version` flags** - Automatically added to root commands.
|
|
25
|
+
- **Option hooks** - Register side-effect actions that trigger when specific options are set (e.g., `--help` prints
|
|
26
|
+
help and sets `process.exitCode`).
|
|
27
|
+
- **Parse-only design** - `parseArgv()` returns a result object with `args`, `opts`, `errors`, `hooks`, and an
|
|
28
|
+
`execute()` method. You control when and whether execution happens.
|
|
29
|
+
- **Validation** - Missing required arguments, unknown options, and invalid choices are reported as errors on the
|
|
30
|
+
result.
|
|
31
|
+
- **Variadic arguments and options** - Both arguments and options support variadic (`...`) syntax to collect
|
|
32
|
+
multiple values into arrays.
|
|
33
|
+
- **Environment variable defaults** - Options can fall back to environment variables via the `env` option.
|
|
34
|
+
- **Argument and option choices** - Restrict allowed values with `choices` arrays; violations are reported as
|
|
35
|
+
validation errors.
|
|
36
|
+
- **Negatable boolean flags** - Pass `--no-<flag>` to set a boolean option to `false`.
|
|
37
|
+
- **kebab-case to camelCase mapping** - Multi-word option names like `--output-dir` are automatically available as
|
|
38
|
+
`opts.outputDir`.
|
|
39
|
+
- **Hidden commands and options** - Exclude items from help output while keeping them functional.
|
|
40
|
+
- **Grouped help sections** - Organize options and subcommands into named groups in the help output.
|
|
41
|
+
|
|
42
|
+
## Usage
|
|
43
|
+
|
|
44
|
+
### Basic Command
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
import { Command } from '@bemoje/cli'
|
|
48
|
+
|
|
49
|
+
const cli = new Command('greet')
|
|
50
|
+
.setDescription('Greet someone')
|
|
51
|
+
.addArgument('<name>')
|
|
52
|
+
.addOption('-l, --loud', { description: 'Shout the greeting' })
|
|
53
|
+
.setAction((name, opts) => {
|
|
54
|
+
const msg = `Hello, ${name}!`
|
|
55
|
+
console.log(opts.loud ? msg.toUpperCase() : msg)
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
cli.parseArgv(process.argv.slice(2))
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### Arguments
|
|
62
|
+
|
|
63
|
+
Arguments are positional values parsed from `argv`. They support required (`<name>`), optional (`[name]`), and
|
|
64
|
+
variadic (`<name...>`, `[name...]`) forms.
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
const cmd = new Command('copy')
|
|
68
|
+
.addArgument('<source>') // required string
|
|
69
|
+
.addArgument('[destination]', { defaultValue: '.' }) // optional with default
|
|
70
|
+
.setAction((source, destination, opts) => {
|
|
71
|
+
console.log(`Copying ${source} to ${destination}`)
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
cmd.parseArgv(['file.txt'])
|
|
75
|
+
// args: ['file.txt', '.']
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
**Variadic arguments** collect all remaining positional values into an array. Only the last argument may be
|
|
79
|
+
variadic.
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
const cmd = new Command('concat').addArgument('<files...>').setAction((files, opts) => {
|
|
83
|
+
// files is string[]
|
|
84
|
+
console.log(`Concatenating: ${files.join(', ')}`)
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
cmd.parseArgv(['a.txt', 'b.txt', 'c.txt'])
|
|
88
|
+
// args: [['a.txt', 'b.txt', 'c.txt']]
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
**Choices** can restrict which values are accepted:
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
const cmd = new Command('deploy').addArgument('<env>', { choices: ['dev', 'staging', 'prod'] })
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
**Ordering rules** are enforced at both the type level and at runtime:
|
|
98
|
+
|
|
99
|
+
- Required arguments must come before optional ones
|
|
100
|
+
- Only the last argument may be variadic
|
|
101
|
+
- A command with arguments cannot have subcommands (and vice versa)
|
|
102
|
+
|
|
103
|
+
### Options
|
|
104
|
+
|
|
105
|
+
Options are named flags parsed from `argv`. The format is always `-<short>, --<long> [value-syntax]`.
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
const cmd = new Command('build')
|
|
109
|
+
.addOption('-o, --output <dir>', { description: 'Output directory' }) // required string
|
|
110
|
+
.addOption('-m, --minify', { description: 'Minify output' }) // boolean flag
|
|
111
|
+
.addOption('-w, --watch [mode]', { description: 'Watch mode', defaultValue: 'poll' }) // optional string with default
|
|
112
|
+
.setAction((opts) => {
|
|
113
|
+
console.log(opts.output) // string
|
|
114
|
+
console.log(opts.minify) // boolean | undefined
|
|
115
|
+
console.log(opts.watch) // string
|
|
116
|
+
})
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
**Variadic options** collect multiple values into an array:
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
const cmd = new Command('lint')
|
|
123
|
+
.addOption('-i, --include <patterns...>', { description: 'Include globs' }) // required: string[]
|
|
124
|
+
.addOption('-e, --exclude [patterns...]', { description: 'Exclude globs', defaultValue: ['node_modules'] })
|
|
125
|
+
|
|
126
|
+
cmd.parseArgv(['-i', 'src', 'lib', '-e', 'test'])
|
|
127
|
+
// opts.include: ['src', 'lib']
|
|
128
|
+
// opts.exclude: ['test']
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
**Option choices** restrict valid values:
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
const cmd = new Command('format').addOption('-f, --format <type>', {
|
|
135
|
+
description: 'Output format',
|
|
136
|
+
choices: ['json', 'xml', 'yaml'],
|
|
137
|
+
})
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
**Environment variable defaults** let options fall back to env vars:
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
const cmd = new Command('deploy').addOption('-t, --token <value>', {
|
|
144
|
+
description: 'Auth token',
|
|
145
|
+
env: 'AUTH_TOKEN',
|
|
146
|
+
})
|
|
147
|
+
// If AUTH_TOKEN is set and --token is not passed, opts.token defaults to process.env.AUTH_TOKEN
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
**Hidden options** are excluded from help output:
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
const cmd = new Command('tool').addOption('-x, --experimental', {
|
|
154
|
+
description: 'Experimental feature',
|
|
155
|
+
hidden: true,
|
|
156
|
+
})
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
**Grouped options** appear under custom headings in help:
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
const cmd = new Command('server')
|
|
163
|
+
.addOption('-p, --port <n>', { description: 'Port number', group: 'Network:' })
|
|
164
|
+
.addOption('-H, --host [addr]', { description: 'Host address', group: 'Network:' })
|
|
165
|
+
.addOption('-v, --verbose', { description: 'Verbose logging', group: 'Logging:' })
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
**Negatable flags** - any boolean option can be negated with `--no-<name>`:
|
|
169
|
+
|
|
170
|
+
```ts
|
|
171
|
+
const cmd = new Command('build').addOption('-c, --color', { description: 'Colorize output' })
|
|
172
|
+
|
|
173
|
+
cmd.parseArgv(['--no-color'])
|
|
174
|
+
// opts.color: false
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
**kebab-case to camelCase** - multi-word option names are automatically camelCased:
|
|
178
|
+
|
|
179
|
+
```ts
|
|
180
|
+
const cmd = new Command('build').addOption('-o, --output-dir <path>', { description: 'Output directory' })
|
|
181
|
+
|
|
182
|
+
cmd.parseArgv(['--output-dir', '/tmp'])
|
|
183
|
+
// opts.outputDir: '/tmp'
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
### Subcommands
|
|
187
|
+
|
|
188
|
+
Use `.command()` to create a subcommand and get it back, or `.addCommand()` to add one via callback and get the
|
|
189
|
+
parent back for chaining.
|
|
190
|
+
|
|
191
|
+
Options defined on the parent are automatically inherited by subcommands. Aliases are auto-generated from
|
|
192
|
+
subcommand name initials (e.g., `build-project` gets alias `bp`).
|
|
193
|
+
|
|
194
|
+
```ts
|
|
195
|
+
const cli = new Command('git')
|
|
196
|
+
.setDescription('A version control system')
|
|
197
|
+
.addOption('-v, --verbose', { description: 'Verbose output' })
|
|
198
|
+
|
|
199
|
+
.addCommand('clone', (sub) =>
|
|
200
|
+
sub
|
|
201
|
+
.setDescription('Clone a repository')
|
|
202
|
+
.addArgument('<url>')
|
|
203
|
+
.addOption('-d, --depth <n>', { description: 'Shallow clone depth' })
|
|
204
|
+
.setAction((url, opts) => {
|
|
205
|
+
// opts.verbose is inherited from parent
|
|
206
|
+
console.log(`Cloning ${url} with depth ${opts.depth ?? 'full'}`)
|
|
207
|
+
})
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
.addCommand('status', (sub) =>
|
|
211
|
+
sub
|
|
212
|
+
.setDescription('Show working tree status')
|
|
213
|
+
.addOption('-s, --short', { description: 'Short format output' })
|
|
214
|
+
.setAction((opts) => {
|
|
215
|
+
console.log('Status:', opts.short ? 'clean' : 'On branch main...')
|
|
216
|
+
})
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
cli.parseArgv(['clone', 'https://github.com/user/repo', '-d', '1'])
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
**Aliases** can also be set manually:
|
|
223
|
+
|
|
224
|
+
```ts
|
|
225
|
+
const cli = new Command('app')
|
|
226
|
+
cli.command('install').setAliases('i', 'add')
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
### Parsing and Execution
|
|
230
|
+
|
|
231
|
+
`parseArgv()` does not execute the action - it returns a result object:
|
|
232
|
+
|
|
233
|
+
```ts
|
|
234
|
+
const cli = new Command('tool')
|
|
235
|
+
.addArgument('<input>')
|
|
236
|
+
.addOption('-v, --verbose', { description: 'Verbose' })
|
|
237
|
+
.setAction((input, opts) => {
|
|
238
|
+
console.log(`Processing ${input}`)
|
|
239
|
+
})
|
|
240
|
+
|
|
241
|
+
const result = cli.parseArgv(['file.txt', '-v'])
|
|
242
|
+
|
|
243
|
+
result.path // string[] - subcommand path segments
|
|
244
|
+
result.name // string - command name
|
|
245
|
+
result.argv // string[] - the argv that was parsed
|
|
246
|
+
result.args // [string] - typed parsed arguments
|
|
247
|
+
result.opts // { verbose: true } - typed parsed options
|
|
248
|
+
result.errors // string[] | undefined - validation errors
|
|
249
|
+
result.hooks // HookDefinition[] - triggered hooks
|
|
250
|
+
result.cmd // Command - the matched command instance
|
|
251
|
+
|
|
252
|
+
// Execute the action (and any triggered hooks) when you're ready:
|
|
253
|
+
await result.execute()
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
**Validation errors** are collected, not thrown. Check `result.errors` before executing:
|
|
257
|
+
|
|
258
|
+
```ts
|
|
259
|
+
const result = cli.parseArgv([])
|
|
260
|
+
if (result.errors) {
|
|
261
|
+
console.error(result.errors.join('\n'))
|
|
262
|
+
process.exitCode = 1
|
|
263
|
+
} else {
|
|
264
|
+
await result.execute()
|
|
265
|
+
}
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
When `execute()` is called, hooks run first (in order). If any hook sets `process.exitCode`, execution stops. Then
|
|
269
|
+
the main action runs inside a timer that provides a logger.
|
|
270
|
+
|
|
271
|
+
### Option Hooks
|
|
272
|
+
|
|
273
|
+
Hooks let you attach side-effect actions that run when a specific option is set. The built-in `--help`, `--debug`,
|
|
274
|
+
and `--version` flags are all implemented as hooks.
|
|
275
|
+
|
|
276
|
+
```ts
|
|
277
|
+
const cli = new Command('tool')
|
|
278
|
+
.addOption('-c, --clean', { description: 'Clean before running' })
|
|
279
|
+
.addOptionHook('clean', ({ cmd, opts }) => {
|
|
280
|
+
console.log('Cleaning build artifacts...')
|
|
281
|
+
// Hook runs before the main action
|
|
282
|
+
})
|
|
283
|
+
.setAction((opts) => {
|
|
284
|
+
console.log('Running tool...')
|
|
285
|
+
})
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
Hooks are evaluated in registration order. If a hook sets `process.exitCode`, subsequent hooks and the main action
|
|
289
|
+
are skipped.
|
|
290
|
+
|
|
291
|
+
### Help Output
|
|
292
|
+
|
|
293
|
+
Help is auto-generated with ANSI color support, word wrapping, and section grouping.
|
|
294
|
+
|
|
295
|
+
```ts
|
|
296
|
+
const cli = new Command('my-tool')
|
|
297
|
+
.setVersion('1.0.0')
|
|
298
|
+
.setDescription('A great CLI tool')
|
|
299
|
+
.addArgument('<input>')
|
|
300
|
+
.addOption('-v, --verbose', { description: 'Verbose output' })
|
|
301
|
+
|
|
302
|
+
// Render help string (with ANSI colors)
|
|
303
|
+
console.log(cli.renderHelp())
|
|
304
|
+
|
|
305
|
+
// Render plain text (no ANSI)
|
|
306
|
+
console.log(cli.renderHelp({ noColor: true }))
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
**Customize help rendering** via `.helpConfiguration()`:
|
|
310
|
+
|
|
311
|
+
```ts
|
|
312
|
+
cli.helpConfiguration((help) => {
|
|
313
|
+
help.sortSubcommands = false
|
|
314
|
+
help.sortOptions = false
|
|
315
|
+
help.helpWidth = 120
|
|
316
|
+
})
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
The `Help` class exposes many styleable and overridable methods for full control over the output format:
|
|
320
|
+
|
|
321
|
+
| Method | Purpose |
|
|
322
|
+
| --------------------------- | --------------------------------------------- |
|
|
323
|
+
| `styleTitle(str)` | Style section headings ("Usage:", "Options:") |
|
|
324
|
+
| `styleUsage(str)` | Style the usage line |
|
|
325
|
+
| `styleOptionTerm(str)` | Style option flags |
|
|
326
|
+
| `styleSubcommandTerm(str)` | Style subcommand entries |
|
|
327
|
+
| `styleArgumentTerm(str)` | Style argument entries |
|
|
328
|
+
| `styleDescriptionText(str)` | Base style for all descriptions |
|
|
329
|
+
| `formatItem(term, w, desc)` | Format a term/description pair with padding |
|
|
330
|
+
| `boxWrap(str, width)` | Wrap text at whitespace to fit width |
|
|
331
|
+
|
|
332
|
+
### Type Safety
|
|
333
|
+
|
|
334
|
+
The `Command` class tracks argument and option types through generics that update with each chained call. This
|
|
335
|
+
means your action handler receives correctly typed parameters:
|
|
336
|
+
|
|
337
|
+
```ts
|
|
338
|
+
const cmd = new Command('example')
|
|
339
|
+
.addArgument('<name>') // A = [string]
|
|
340
|
+
.addArgument('[count]', { defaultValue: '1' }) // A = [string, string]
|
|
341
|
+
.addOption('-v, --verbose', {}) // O = { verbose?: boolean, ... }
|
|
342
|
+
.addOption('-f, --format <type>', {}) // O = { verbose?: boolean, format: string, ... }
|
|
343
|
+
.setAction((name, count, opts) => {
|
|
344
|
+
// name: string, count: string, opts: { verbose?: boolean, format: string, ... }
|
|
345
|
+
})
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
Invalid argument orderings (e.g., required after optional, anything after variadic) are caught at the **type
|
|
349
|
+
level** - TypeScript will reject the code before it runs.
|
|
350
|
+
|
|
351
|
+
### Helpers
|
|
352
|
+
|
|
353
|
+
```ts
|
|
354
|
+
import {
|
|
355
|
+
findCommand,
|
|
356
|
+
findOption,
|
|
357
|
+
parseOptionFlags,
|
|
358
|
+
getCommandAncestors,
|
|
359
|
+
getCommandAndAncestors,
|
|
360
|
+
} from '@bemoje/cli'
|
|
361
|
+
|
|
362
|
+
// Find a subcommand by name or alias
|
|
363
|
+
const sub = findCommand(cli, 'clone') // Command | undefined
|
|
364
|
+
const sub2 = findCommand(cli, 'c') // also works with aliases
|
|
365
|
+
|
|
366
|
+
// Find an option by name, short flag, or long flag
|
|
367
|
+
const opt = findOption(cli, 'verbose') // Option | undefined
|
|
368
|
+
const opt2 = findOption(cli, '-v') // by short flag
|
|
369
|
+
const opt3 = findOption(cli, '--verbose') // by long flag
|
|
370
|
+
|
|
371
|
+
// Parse raw flag syntax into components
|
|
372
|
+
parseOptionFlags('-o, --output <dir>')
|
|
373
|
+
// => { short: 'o', long: 'output', name: 'output', argName: 'dir' }
|
|
374
|
+
|
|
375
|
+
// Navigate command hierarchy
|
|
376
|
+
getCommandAncestors(sub) // parent commands (excluding self)
|
|
377
|
+
getCommandAndAncestors(sub) // [self, parent, grandparent, ...]
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
## API Reference
|
|
381
|
+
|
|
382
|
+
### `Command` Class
|
|
383
|
+
|
|
384
|
+
#### Constructor
|
|
385
|
+
|
|
386
|
+
| Method | Description |
|
|
387
|
+
| ------------------- | ----------------------------------------- |
|
|
388
|
+
| `new Command(name)` | Create a new root command with given name |
|
|
389
|
+
|
|
390
|
+
#### Configuration
|
|
391
|
+
|
|
392
|
+
| Method | Returns | Description |
|
|
393
|
+
| --------------------------- | ------- | ------------------------------------------------- |
|
|
394
|
+
| `.setName(name)` | `void` | Rename the command |
|
|
395
|
+
| `.setDescription(...lines)` | `this` | Set full description (lines are joined with `\n`) |
|
|
396
|
+
| `.setSummary(text)` | `this` | Set brief one-line summary for command listings |
|
|
397
|
+
| `.setVersion(version)` | `this` | Set version and add `--version` flag |
|
|
398
|
+
| `.setHidden(hidden?)` | `this` | Hide from help listings |
|
|
399
|
+
| `.setGroup(group)` | `this` | Set category for help organization |
|
|
400
|
+
| `.setAliases(...aliases)` | `this` | Replace all aliases |
|
|
401
|
+
| `.addAliases(...aliases)` | `this` | Append aliases |
|
|
402
|
+
| `.helpConfiguration(cb?)` | `this` | Configure `Help` instance via callback |
|
|
403
|
+
|
|
404
|
+
#### Arguments
|
|
405
|
+
|
|
406
|
+
| Method | Returns | Description |
|
|
407
|
+
| ------------------------------- | -------------- | ------------------------- |
|
|
408
|
+
| `.addArgument(usage, options?)` | `Command<...>` | Add a positional argument |
|
|
409
|
+
|
|
410
|
+
Argument usage patterns: `<name>` (required), `[name]` (optional), `<name...>` (required variadic), `[name...]`
|
|
411
|
+
(optional variadic).
|
|
412
|
+
|
|
413
|
+
Argument options: `description`, `choices`, `defaultValue`, `defaultValueDescription`.
|
|
414
|
+
|
|
415
|
+
#### Options
|
|
416
|
+
|
|
417
|
+
| Method | Returns | Description |
|
|
418
|
+
| ----------------------------- | -------------- | -------------------------------------- |
|
|
419
|
+
| `.addOption(flags, options?)` | `Command<...>` | Add a named option with type inference |
|
|
420
|
+
|
|
421
|
+
Option flag patterns: `-s, --long` (boolean), `-s, --long <val>` (required string), `-s, --long [val]` (optional
|
|
422
|
+
string), `-s, --long <val...>` (required variadic), `-s, --long [val...]` (optional variadic).
|
|
423
|
+
|
|
424
|
+
Option properties: `description`, `defaultValue`, `defaultValueDescription`, `choices`, `env`, `hidden`, `group`.
|
|
425
|
+
|
|
426
|
+
#### Subcommands
|
|
427
|
+
|
|
428
|
+
| Method | Returns | Description |
|
|
429
|
+
| ----------------------- | --------- | --------------------------------------------- |
|
|
430
|
+
| `.command(name, cb?)` | `Command` | Create subcommand, return the subcommand |
|
|
431
|
+
| `.addCommand(name, cb)` | `this` | Create subcommand via callback, return parent |
|
|
432
|
+
|
|
433
|
+
#### Actions and Hooks
|
|
434
|
+
|
|
435
|
+
| Method | Returns | Description |
|
|
436
|
+
| -------------------------------- | ------- | ------------------------------------------ |
|
|
437
|
+
| `.setAction(fn)` | `this` | Set main action handler |
|
|
438
|
+
| `.addOptionHook(optionName, fn)` | `this` | Register hook triggered when option is set |
|
|
439
|
+
|
|
440
|
+
#### Parsing
|
|
441
|
+
|
|
442
|
+
| Method | Returns | Description |
|
|
443
|
+
| ------------------- | ----------------- | ----------------------------------------- |
|
|
444
|
+
| `.parseArgv(argv?)` | `ParseArgvResult` | Parse argv and return result with execute |
|
|
445
|
+
| `.renderHelp(cfg?)` | `string` | Render help text |
|
|
446
|
+
|
|
447
|
+
### Helper Functions
|
|
448
|
+
|
|
449
|
+
| Export | Description |
|
|
450
|
+
| ------------------------ | -------------------------------------------------------------- |
|
|
451
|
+
| `findCommand(cmd, name)` | Find subcommand by name or alias |
|
|
452
|
+
| `findOption(cmd, name)` | Find option by name, `-short`, or `--long` |
|
|
453
|
+
| `getCommandAncestors` | Get all parent commands (excluding self) |
|
|
454
|
+
| `getCommandAndAncestors` | Get self and all parent commands |
|
|
455
|
+
| `parseOptionFlags` | Parse flag syntax string into `{ short, long, name, argName }` |
|
|
456
|
+
|
|
457
|
+
### `Help` Class
|
|
458
|
+
|
|
459
|
+
Renders formatted, colorized help text. Instantiated automatically by `Command`. Override style methods by
|
|
460
|
+
subclassing or via `helpConfiguration()`.
|
|
461
|
+
|
|
462
|
+
Key properties: `helpWidth`, `sortSubcommands`, `sortOptions`, `minWidthToWrap`.
|
|
463
|
+
|
|
464
|
+
### Types
|
|
465
|
+
|
|
466
|
+
| Type | Description |
|
|
467
|
+
| ------------------- | ------------------------------------------------------------ |
|
|
468
|
+
| `ParseArgvResult` | Return type of `parseArgv()` with args, opts, execute, etc. |
|
|
469
|
+
| `ActionHandler` | Action function signature receiving args, opts, and metadata |
|
|
470
|
+
| `HookActionHandler` | Hook function signature receiving parse context |
|
|
471
|
+
| `HookDefinition` | Hook with name, predicate, and action |
|
|
472
|
+
| `Argument` | Argument descriptor |
|
|
473
|
+
| `Option` | Option descriptor |
|
|
474
|
+
| `ICommand` | Command interface for loose coupling |
|
|
475
|
+
| `IHelp` | Help interface |
|
package/index.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import memoizee from 'memoizee';
|
|
|
4
4
|
import { ms } from 'enhanced-ms';
|
|
5
5
|
import { inspect, parseArgs } from 'util';
|
|
6
6
|
import { kebabCase } from 'es-toolkit/string';
|
|
7
|
+
import { uniq, upperFirst, last } from 'es-toolkit';
|
|
7
8
|
import humanizeDuration from 'humanize-duration';
|
|
8
9
|
import { isPromise } from 'util/types';
|
|
9
10
|
|
|
@@ -326,8 +327,7 @@ var Help = class {
|
|
|
326
327
|
const args = sub.arguments.map((arg) => {
|
|
327
328
|
return arg.usage;
|
|
328
329
|
}).join(" ");
|
|
329
|
-
return (sub.aliases[0] ? `${sub.aliases[0].padEnd(this.longestSubcommandAliasLength(), " ")} | ` : "") + sub.name + (sub.options.length ? ` ${this.usageDisplayOptionsAs}` : "") +
|
|
330
|
-
(args ? ` ${args}` : "");
|
|
330
|
+
return (sub.aliases[0] ? `${sub.aliases[0].padEnd(this.longestSubcommandAliasLength(), " ")} | ` : "") + sub.name + (sub.options.length ? ` ${this.usageDisplayOptionsAs}` : "") + (args ? ` ${args}` : "");
|
|
331
331
|
}
|
|
332
332
|
/**
|
|
333
333
|
* Get the option term to show in the list of options.
|
|
@@ -418,11 +418,12 @@ var Help = class {
|
|
|
418
418
|
optionDescription(option) {
|
|
419
419
|
const extraInfo = [];
|
|
420
420
|
if (option.choices) {
|
|
421
|
+
const choices = option.choices.length > 5 ? option.choices.slice(0, 5).concat([
|
|
422
|
+
"..."
|
|
423
|
+
]) : option.choices;
|
|
421
424
|
extraInfo.push(
|
|
422
425
|
// use stringify to match the display of the default value
|
|
423
|
-
`choices: ${
|
|
424
|
-
return String(choice);
|
|
425
|
-
}).join(", ")}`
|
|
426
|
+
`choices: ${choices.map(String).join(", ")}`
|
|
426
427
|
);
|
|
427
428
|
}
|
|
428
429
|
if (option.defaultValue && !(Array.isArray(option.defaultValue) && option.defaultValue.length === 0)) {
|
|
@@ -446,11 +447,12 @@ var Help = class {
|
|
|
446
447
|
argumentDescription(argument) {
|
|
447
448
|
const extraInfo = [];
|
|
448
449
|
if (argument.choices) {
|
|
450
|
+
const choices = argument.choices.length > 5 ? argument.choices.slice(0, 5).concat([
|
|
451
|
+
"..."
|
|
452
|
+
]) : argument.choices;
|
|
449
453
|
extraInfo.push(
|
|
450
454
|
// use stringify to match the display of the default value
|
|
451
|
-
`choices: ${
|
|
452
|
-
return String(choice);
|
|
453
|
-
}).join(", ")}`
|
|
455
|
+
`choices: ${choices.map(String).join(", ")}`
|
|
454
456
|
);
|
|
455
457
|
}
|
|
456
458
|
if (argument.defaultValue && !(Array.isArray(argument.defaultValue) && argument.defaultValue.length === 0)) {
|
|
@@ -502,8 +504,8 @@ var Help = class {
|
|
|
502
504
|
* Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
|
|
503
505
|
*/
|
|
504
506
|
displayWidth(str) {
|
|
505
|
-
const sgrPattern = /\
|
|
506
|
-
return str.
|
|
507
|
+
const sgrPattern = /\u001b\[\d*(;\d*)*m/g;
|
|
508
|
+
return str.replaceAll(sgrPattern, "").length;
|
|
507
509
|
}
|
|
508
510
|
/**
|
|
509
511
|
* Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
|
|
@@ -630,7 +632,7 @@ var Help = class {
|
|
|
630
632
|
* Detect manually wrapped and indented strings by checking for line break followed by whitespace.
|
|
631
633
|
*/
|
|
632
634
|
preformatted(str) {
|
|
633
|
-
return /\n[^\S\r
|
|
635
|
+
return /\n[^\S\n\r]/.test(str);
|
|
634
636
|
}
|
|
635
637
|
/**
|
|
636
638
|
* Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
|
|
@@ -654,10 +656,10 @@ var Help = class {
|
|
|
654
656
|
formattedDescription = description;
|
|
655
657
|
} else {
|
|
656
658
|
const wrappedDescription = this.boxWrap(description, remainingWidth);
|
|
657
|
-
formattedDescription = wrappedDescription.
|
|
659
|
+
formattedDescription = wrappedDescription.replaceAll("\n", `
|
|
658
660
|
${" ".repeat(termWidth + spacerWidth)}`);
|
|
659
661
|
}
|
|
660
|
-
return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.
|
|
662
|
+
return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replaceAll("\n", `
|
|
661
663
|
${itemIndentStr}`);
|
|
662
664
|
}
|
|
663
665
|
/**
|
|
@@ -669,7 +671,7 @@ ${itemIndentStr}`);
|
|
|
669
671
|
return str;
|
|
670
672
|
}
|
|
671
673
|
const rawLines = str.split(/\r\n|\n/);
|
|
672
|
-
const chunkPattern =
|
|
674
|
+
const chunkPattern = /\s*\S+/g;
|
|
673
675
|
const wrappedLines = [];
|
|
674
676
|
rawLines.forEach((line) => {
|
|
675
677
|
const chunks = line.match(chunkPattern);
|
|
@@ -788,21 +790,6 @@ _ts_decorate([
|
|
|
788
790
|
_ts_metadata("design:returntype", Number)
|
|
789
791
|
], Help.prototype, "padWidth", null);
|
|
790
792
|
|
|
791
|
-
// ../array/src/lib/arrLast.ts
|
|
792
|
-
function arrLast(array) {
|
|
793
|
-
if (!array.length) {
|
|
794
|
-
throw new Error("Cannot get last element of empty array.");
|
|
795
|
-
}
|
|
796
|
-
return array[array.length - 1];
|
|
797
|
-
}
|
|
798
|
-
__name(arrLast, "arrLast");
|
|
799
|
-
|
|
800
|
-
// ../array/src/lib/arrRemoveDuplicates.ts
|
|
801
|
-
function arrRemoveDuplicates(array) {
|
|
802
|
-
return Array.from(new Set(array));
|
|
803
|
-
}
|
|
804
|
-
__name(arrRemoveDuplicates, "arrRemoveDuplicates");
|
|
805
|
-
|
|
806
793
|
// src/lib/internal/collectVariadicOptionValues.ts
|
|
807
794
|
function collectVariadicOptionValues(parsed, options) {
|
|
808
795
|
for (let i = 0; i < parsed.tokens.length; i++) {
|
|
@@ -905,7 +892,7 @@ __name(normalizeArgv, "normalizeArgv");
|
|
|
905
892
|
|
|
906
893
|
// src/lib/helpers/parseOptionFlags.ts
|
|
907
894
|
function parseOptionFlags(flags) {
|
|
908
|
-
const match = flags.match(/^-(.+?), --([
|
|
895
|
+
const match = flags.match(/^-(.+?), --([A-Za-z][\w-]*)(?:\s*(<(.+?)>|\[(.+?)]))?$/);
|
|
909
896
|
if (!match) {
|
|
910
897
|
throw new Error(`Invalid option format: ${flags}`);
|
|
911
898
|
}
|
|
@@ -914,7 +901,7 @@ function parseOptionFlags(flags) {
|
|
|
914
901
|
throw new Error(`Expected short name to be a single character. Got: -${short}`);
|
|
915
902
|
}
|
|
916
903
|
const long = match[2];
|
|
917
|
-
const argName = (match[4] || match[5])?.replace(
|
|
904
|
+
const argName = (match[4] || match[5])?.replace(/\.{3}$/, "") || void 0;
|
|
918
905
|
const name = long.split("-").reduce((str, word) => {
|
|
919
906
|
return str + word[0].toUpperCase() + word.slice(1);
|
|
920
907
|
});
|
|
@@ -926,8 +913,6 @@ function parseOptionFlags(flags) {
|
|
|
926
913
|
};
|
|
927
914
|
}
|
|
928
915
|
__name(parseOptionFlags, "parseOptionFlags");
|
|
929
|
-
|
|
930
|
-
// src/lib/internal/resolveArguments.ts
|
|
931
916
|
function resolveArguments(positionals, args) {
|
|
932
917
|
const result = args.map((arg, index) => {
|
|
933
918
|
if (arg.variadic) {
|
|
@@ -936,7 +921,7 @@ function resolveArguments(positionals, args) {
|
|
|
936
921
|
}
|
|
937
922
|
return positionals[index] ?? arg.defaultValue;
|
|
938
923
|
});
|
|
939
|
-
while (result.length &&
|
|
924
|
+
while (result.length && last(result) === void 0) {
|
|
940
925
|
result.pop();
|
|
941
926
|
}
|
|
942
927
|
return result;
|
|
@@ -952,12 +937,6 @@ function setName(name, target) {
|
|
|
952
937
|
});
|
|
953
938
|
}
|
|
954
939
|
__name(setName, "setName");
|
|
955
|
-
|
|
956
|
-
// ../string/src/lib/strFirstCharToUpperCase.ts
|
|
957
|
-
function strFirstCharToUpperCase(string) {
|
|
958
|
-
return string.charAt(0).toUpperCase() + string.substring(1);
|
|
959
|
-
}
|
|
960
|
-
__name(strFirstCharToUpperCase, "strFirstCharToUpperCase");
|
|
961
940
|
function createLogger(name) {
|
|
962
941
|
const NAME = name ? C.dim.cyan(name) : name;
|
|
963
942
|
const START = [
|
|
@@ -1021,11 +1000,7 @@ function createColoredArgs(colorFn) {
|
|
|
1021
1000
|
return (args) => {
|
|
1022
1001
|
return args.map((arg) => {
|
|
1023
1002
|
if (isString(arg)) {
|
|
1024
|
-
|
|
1025
|
-
return colorFn(arg);
|
|
1026
|
-
} else {
|
|
1027
|
-
return arg;
|
|
1028
|
-
}
|
|
1003
|
+
return arg === C.stripColor(arg) ? colorFn(arg) : arg;
|
|
1029
1004
|
} else if (isPrimitive(arg)) {
|
|
1030
1005
|
return colorFn(String(arg));
|
|
1031
1006
|
} else {
|
|
@@ -1068,21 +1043,17 @@ __name(timer, "timer");
|
|
|
1068
1043
|
function validateParsed(args, optionValues, argDefs, optionDefs) {
|
|
1069
1044
|
return argDefs.map((def, index) => {
|
|
1070
1045
|
const value = args[index];
|
|
1071
|
-
if (def.required) {
|
|
1072
|
-
|
|
1073
|
-
return `Missing argument [${index}] ${def.usage}`;
|
|
1074
|
-
}
|
|
1046
|
+
if (def.required && (def.variadic ? Array.isArray(value) && value.length === 0 : value === void 0)) {
|
|
1047
|
+
return `Missing argument [${index}] ${def.usage}`;
|
|
1075
1048
|
}
|
|
1076
|
-
if (def.choices && value !== void 0
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
})
|
|
1082
|
-
return
|
|
1083
|
-
|
|
1084
|
-
}).join(",")}]`;
|
|
1085
|
-
}
|
|
1049
|
+
if (def.choices && value !== void 0 && ![
|
|
1050
|
+
value
|
|
1051
|
+
].flat().every((v) => {
|
|
1052
|
+
return def.choices.includes(v);
|
|
1053
|
+
})) {
|
|
1054
|
+
return `Invalid argument [${index}] ${def.usage}: Got \`${value}\`. Accepted values: [${def.choices.map((c) => {
|
|
1055
|
+
return `\`${c}\``;
|
|
1056
|
+
}).join(",")}]`;
|
|
1086
1057
|
}
|
|
1087
1058
|
}).concat(entriesOf(optionValues).map(([key, value]) => {
|
|
1088
1059
|
const def = optionDefs.find((o) => {
|
|
@@ -1091,16 +1062,14 @@ function validateParsed(args, optionValues, argDefs, optionDefs) {
|
|
|
1091
1062
|
if (!def) {
|
|
1092
1063
|
return `Unknown option --${key}`;
|
|
1093
1064
|
}
|
|
1094
|
-
if (def.choices && value !== void 0
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
})
|
|
1100
|
-
return
|
|
1101
|
-
|
|
1102
|
-
}).join(",")}]`;
|
|
1103
|
-
}
|
|
1065
|
+
if (def.choices && value !== void 0 && !(def.variadic ? value : [
|
|
1066
|
+
value
|
|
1067
|
+
]).every((v) => {
|
|
1068
|
+
return def.choices.includes(v);
|
|
1069
|
+
})) {
|
|
1070
|
+
return `Invalid option value ${def.flags}: Got \`${value}\`. Accepted values: [${def.choices.map((c) => {
|
|
1071
|
+
return `\`${c}\``;
|
|
1072
|
+
}).join(",")}]`;
|
|
1104
1073
|
}
|
|
1105
1074
|
})).filter((s) => {
|
|
1106
1075
|
return s !== void 0;
|
|
@@ -1217,7 +1186,7 @@ var Command = class _Command {
|
|
|
1217
1186
|
...c.aliases
|
|
1218
1187
|
];
|
|
1219
1188
|
}) : [];
|
|
1220
|
-
|
|
1189
|
+
uniq(aliases.flat()).filter((a) => {
|
|
1221
1190
|
return !this.aliases.includes(a) && a !== this.name;
|
|
1222
1191
|
}).forEach((a) => {
|
|
1223
1192
|
if (taken.includes(a)) {
|
|
@@ -1296,15 +1265,15 @@ var Command = class _Command {
|
|
|
1296
1265
|
const initials = words.map((s) => {
|
|
1297
1266
|
return s[0];
|
|
1298
1267
|
}).join("");
|
|
1299
|
-
if (
|
|
1300
|
-
sub.addAliases(initials);
|
|
1301
|
-
} else {
|
|
1268
|
+
if (taken.includes(initials)) {
|
|
1302
1269
|
const initials2 = words.map((s) => {
|
|
1303
1270
|
return s[0] + s[1];
|
|
1304
1271
|
}).join("");
|
|
1305
1272
|
if (!taken.includes(initials2)) {
|
|
1306
1273
|
sub.addAliases(initials2);
|
|
1307
1274
|
}
|
|
1275
|
+
} else {
|
|
1276
|
+
sub.addAliases(initials);
|
|
1308
1277
|
}
|
|
1309
1278
|
this.commands[name] = sub;
|
|
1310
1279
|
return cb ? cb(sub, this) : sub;
|
|
@@ -1317,10 +1286,10 @@ var Command = class _Command {
|
|
|
1317
1286
|
}
|
|
1318
1287
|
// implementation
|
|
1319
1288
|
addArgument(usage, options = {}) {
|
|
1320
|
-
if (!/^<(.*?)>$|^\[(.*?)
|
|
1289
|
+
if (!/^<(.*?)>$|^\[(.*?)]$/.test(usage)) {
|
|
1321
1290
|
throw new Error(`Invalid argument format: ${usage}`);
|
|
1322
1291
|
}
|
|
1323
|
-
const name = usage.slice(1, -1).replace(
|
|
1292
|
+
const name = usage.slice(1, -1).replace(/\.{3}$/, "");
|
|
1324
1293
|
const required = usage.startsWith("<");
|
|
1325
1294
|
const variadic = usage.slice(0, -1).endsWith("...");
|
|
1326
1295
|
const prevArg = this.arguments[this.arguments.length - 1];
|
|
@@ -1365,9 +1334,7 @@ var Command = class _Command {
|
|
|
1365
1334
|
ins.long = long;
|
|
1366
1335
|
ins.name = name;
|
|
1367
1336
|
ins.description = "";
|
|
1368
|
-
if (
|
|
1369
|
-
ins.type = "boolean";
|
|
1370
|
-
} else {
|
|
1337
|
+
if (argName) {
|
|
1371
1338
|
ins.type = "string";
|
|
1372
1339
|
ins.argName = argName;
|
|
1373
1340
|
if (flags.endsWith(">")) {
|
|
@@ -1377,12 +1344,12 @@ var Command = class _Command {
|
|
|
1377
1344
|
} else {
|
|
1378
1345
|
ins.required = true;
|
|
1379
1346
|
}
|
|
1380
|
-
} else if (flags.endsWith("]")) {
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
ins.defaultValue = opts.defaultValue ?? [];
|
|
1384
|
-
}
|
|
1347
|
+
} else if (flags.endsWith("]") && flags.endsWith("...]")) {
|
|
1348
|
+
ins.variadic = true;
|
|
1349
|
+
ins.defaultValue = opts.defaultValue ?? [];
|
|
1385
1350
|
}
|
|
1351
|
+
} else {
|
|
1352
|
+
ins.type = "boolean";
|
|
1386
1353
|
}
|
|
1387
1354
|
for (const [key, value] of Object.entries(opts)) {
|
|
1388
1355
|
if (value !== void 0) {
|
|
@@ -1395,7 +1362,7 @@ var Command = class _Command {
|
|
|
1395
1362
|
if (ins.type === "boolean") {
|
|
1396
1363
|
ins.defaultValue = /^(t(rue)?|y(es)?|1)$/i.test(process.env[ins.env]);
|
|
1397
1364
|
} else if (ins.variadic) {
|
|
1398
|
-
ins.defaultValue = process.env[ins.env].replace(/\]
|
|
1365
|
+
ins.defaultValue = process.env[ins.env].replace(/\[]/, "").split(",").map((v) => {
|
|
1399
1366
|
return v.trim();
|
|
1400
1367
|
});
|
|
1401
1368
|
} else {
|
|
@@ -1414,12 +1381,12 @@ var Command = class _Command {
|
|
|
1414
1381
|
*/
|
|
1415
1382
|
addOptionHook(optionName, action) {
|
|
1416
1383
|
const def = findOption(this, optionName);
|
|
1417
|
-
if (!def.group && /process\.exitCode ?= ?.+;?\s
|
|
1384
|
+
if (!def.group && /process\.exitCode ?= ?.+;?\s*}$/.test(action.toString())) {
|
|
1418
1385
|
def.group = "Command Options";
|
|
1419
1386
|
}
|
|
1420
1387
|
this.hooks.push({
|
|
1421
1388
|
name: optionName,
|
|
1422
|
-
predicate: setName(`has${
|
|
1389
|
+
predicate: setName(`has${upperFirst(optionName)}`, ({ opts }) => {
|
|
1423
1390
|
return opts[optionName] !== void 0 && opts[optionName] !== false && !(Array.isArray(opts[optionName]) && opts[optionName].length === 0);
|
|
1424
1391
|
}),
|
|
1425
1392
|
action: setName(optionName, action)
|