cli-forge 0.10.1 → 0.11.0

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.
Files changed (97) hide show
  1. package/.eslintrc.json +35 -0
  2. package/LICENSE.md +5 -0
  3. package/cli.js +9 -0
  4. package/{bin → dist/bin}/cli.d.ts +1 -1
  5. package/{bin → dist/bin}/cli.js +2 -2
  6. package/dist/bin/cli.js.map +1 -0
  7. package/{bin → dist/bin}/commands/generate-documentation.d.ts +1 -1
  8. package/{bin → dist/bin}/commands/generate-documentation.js +58 -11
  9. package/dist/bin/commands/generate-documentation.js.map +1 -0
  10. package/{bin → dist/bin}/commands/init.d.ts +1 -1
  11. package/{bin → dist/bin}/commands/init.js +11 -6
  12. package/dist/bin/commands/init.js.map +1 -0
  13. package/dist/bin/utils/fs.js.map +1 -0
  14. package/{src → dist}/index.d.ts +1 -1
  15. package/dist/index.js.map +1 -0
  16. package/dist/lib/cli-option-groups.js.map +1 -0
  17. package/dist/lib/composable-builder.js.map +1 -0
  18. package/dist/lib/configuration-providers.js.map +1 -0
  19. package/{src → dist}/lib/documentation.d.ts +3 -3
  20. package/dist/lib/documentation.js.map +1 -0
  21. package/dist/lib/format-help.js.map +1 -0
  22. package/{src → dist}/lib/interactive-shell.d.ts +1 -1
  23. package/{src → dist}/lib/interactive-shell.js +6 -3
  24. package/dist/lib/interactive-shell.js.map +1 -0
  25. package/{src → dist}/lib/internal-cli.d.ts +3 -3
  26. package/{src → dist}/lib/internal-cli.js +8 -1
  27. package/dist/lib/internal-cli.js.map +1 -0
  28. package/{src → dist}/lib/public-api.d.ts +41 -6
  29. package/dist/lib/public-api.js.map +1 -0
  30. package/dist/lib/test-harness.js.map +1 -0
  31. package/dist/lib/utils.js.map +1 -0
  32. package/dist/middleware/zod.d.ts +4 -0
  33. package/dist/middleware/zod.js +18 -0
  34. package/dist/middleware/zod.js.map +1 -0
  35. package/dist/middleware.d.ts +1 -0
  36. package/dist/middleware.js +5 -0
  37. package/dist/middleware.js.map +1 -0
  38. package/package.json +28 -10
  39. package/project.json +7 -0
  40. package/src/bin/cli.ts +17 -0
  41. package/src/bin/commands/generate-documentation.ts +403 -0
  42. package/src/bin/commands/init.ts +320 -0
  43. package/src/bin/utils/fs.ts +11 -0
  44. package/src/index.ts +7 -0
  45. package/src/lib/cli-option-groups.ts +69 -0
  46. package/src/lib/composable-builder.ts +9 -0
  47. package/src/lib/configuration-providers.ts +36 -0
  48. package/src/lib/documentation.spec.ts +156 -0
  49. package/src/lib/documentation.ts +107 -0
  50. package/src/lib/format-help.ts +149 -0
  51. package/src/lib/interactive-shell.ts +115 -0
  52. package/src/lib/internal-cli.spec.ts +345 -0
  53. package/src/lib/internal-cli.ts +529 -0
  54. package/src/lib/public-api.ts +449 -0
  55. package/src/lib/test-harness.spec.ts +29 -0
  56. package/src/lib/test-harness.ts +69 -0
  57. package/src/lib/utils.spec.ts +25 -0
  58. package/src/lib/utils.ts +144 -0
  59. package/src/middleware/zod.ts +21 -0
  60. package/src/middleware.ts +1 -0
  61. package/tsconfig.json +23 -0
  62. package/tsconfig.lib.json +20 -0
  63. package/tsconfig.lib.json.tsbuildinfo +1 -0
  64. package/tsconfig.spec.json +26 -0
  65. package/vitest.config.mts +18 -0
  66. package/bin/cli.js.map +0 -1
  67. package/bin/commands/generate-documentation.js.map +0 -1
  68. package/bin/commands/init.js.map +0 -1
  69. package/bin/utils/fs.js.map +0 -1
  70. package/src/index.js.map +0 -1
  71. package/src/lib/cli-option-groups.js.map +0 -1
  72. package/src/lib/composable-builder.js.map +0 -1
  73. package/src/lib/configuration-providers.js.map +0 -1
  74. package/src/lib/documentation.js.map +0 -1
  75. package/src/lib/format-help.js.map +0 -1
  76. package/src/lib/interactive-shell.js.map +0 -1
  77. package/src/lib/internal-cli.js.map +0 -1
  78. package/src/lib/public-api.js.map +0 -1
  79. package/src/lib/test-harness.js.map +0 -1
  80. package/src/lib/utils.js.map +0 -1
  81. /package/{bin → dist/bin}/utils/fs.d.ts +0 -0
  82. /package/{bin → dist/bin}/utils/fs.js +0 -0
  83. /package/{src → dist}/index.js +0 -0
  84. /package/{src → dist}/lib/cli-option-groups.d.ts +0 -0
  85. /package/{src → dist}/lib/cli-option-groups.js +0 -0
  86. /package/{src → dist}/lib/composable-builder.d.ts +0 -0
  87. /package/{src → dist}/lib/composable-builder.js +0 -0
  88. /package/{src → dist}/lib/configuration-providers.d.ts +0 -0
  89. /package/{src → dist}/lib/configuration-providers.js +0 -0
  90. /package/{src → dist}/lib/documentation.js +0 -0
  91. /package/{src → dist}/lib/format-help.d.ts +0 -0
  92. /package/{src → dist}/lib/format-help.js +0 -0
  93. /package/{src → dist}/lib/public-api.js +0 -0
  94. /package/{src → dist}/lib/test-harness.d.ts +0 -0
  95. /package/{src → dist}/lib/test-harness.js +0 -0
  96. /package/{src → dist}/lib/utils.d.ts +0 -0
  97. /package/{src → dist}/lib/utils.js +0 -0
@@ -0,0 +1,449 @@
1
+ import {
2
+ type ConfigurationFiles,
3
+ OptionConfig,
4
+ OptionConfigToType,
5
+ ParsedArgs,
6
+ EnvOptionConfig,
7
+ ObjectOptionConfig,
8
+ StringOptionConfig,
9
+ NumberOptionConfig,
10
+ BooleanOptionConfig,
11
+ ArrayOptionConfig,
12
+ ResolveProperties,
13
+ AdditionalPropertiesType,
14
+ WithOptional,
15
+ } from '@cli-forge/parser';
16
+
17
+ import { InternalCLI } from './internal-cli';
18
+
19
+ /**
20
+ * The interface for a CLI application or subcommands.
21
+ *
22
+ * {@link cli} is provided as a small helper function to create a new CLI instance.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * import { cli } from 'cli-forge';
27
+ *
28
+ * cli('basic-cli').command('hello', {
29
+ * builder: (args) =>
30
+ * args.option('name', {
31
+ * type: 'string',
32
+ * }),
33
+ * handler: (args) => {
34
+ * console.log(`Hello, ${args.name}!`);
35
+ * }).forge();
36
+ * ```
37
+ */
38
+ export interface CLI<TArgs extends ParsedArgs = ParsedArgs> {
39
+ command<TCommandArgs extends TArgs>(
40
+ cmd: Command<TArgs, TCommandArgs>
41
+ ): CLI<TArgs>;
42
+
43
+ /**
44
+ * Registers a new command with the CLI.
45
+ * @param key What should the new command be called?
46
+ * @param options Settings for the new command. See {@link CLICommandOptions}.
47
+ * @returns Updated CLI instance with the new command registered.
48
+ */
49
+ command<TCommandArgs extends TArgs>(
50
+ key: string,
51
+ options: CLICommandOptions<TArgs, TCommandArgs>
52
+ ): CLI<TArgs>;
53
+
54
+ /**
55
+ * Registers multiple subcommands with the CLI.
56
+ * @param commands Several commands to register. Can be the result of a call to {@link cli} or a configuration object.
57
+ */
58
+ commands(commands: Command[]): CLI<TArgs>;
59
+ /**
60
+ * Registers multiple subcommands with the CLI.
61
+ * @param commands Several commands to register. Can be the result of a call to {@link cli} or a configuration object.
62
+ */
63
+ commands(...commands: Command[]): CLI<TArgs>;
64
+
65
+ /**
66
+ * Register's a configuration provider for the CLI. See {@link ConfigurationProviders} for built-in providers.
67
+ *
68
+ * @param provider Provider to register.
69
+ */
70
+ config(provider: ConfigurationFiles.ConfigurationProvider<TArgs>): CLI<TArgs>;
71
+
72
+ /**
73
+ * Enables the ability to run CLI commands that contain subcommands as an interactive shell.
74
+ * This presents as a small shell that only knows the current command and its subcommands.
75
+ * Any flags already consumed by the command will be passed to every subcommand invocation.
76
+ */
77
+ enableInteractiveShell(): CLI<TArgs>;
78
+
79
+ /**
80
+ * Registers a custom global error handler for the CLI. This handler will be called when an error is thrown
81
+ * during the execution of the CLI and not otherwise handled. Error handlers should re-throw the error if they
82
+ * cannot handle it, s.t. the next error handler can attempt to handle it.
83
+ *
84
+ * @param handler Typically called with an Error object, but you should be prepared to handle any type of error.
85
+ * @param actions Actions that can be taken by the error handler. Prefer using these over process.exit for better support of interactive shells.
86
+ */
87
+ errorHandler(handler: ErrorHandler): CLI<TArgs>;
88
+
89
+ /**
90
+ * Registers a new option for the CLI command. This option will be accessible
91
+ * within the command handler, as well as any subcommands.
92
+ *
93
+ * @param name The name of the option.
94
+ * @param config Configuration for the option. See {@link UnknownOptionConfig}.
95
+ * @returns Updated CLI instance with the new option registered.
96
+ */
97
+ // Object option overload - must come first for proper contextual typing
98
+ // Uses direct ObjectOptionConfig type (not `extends`) to ensure TypeScript
99
+ // infers TProps from `properties` BEFORE evaluating the coerce callback type
100
+ option<
101
+ TOption extends string,
102
+ TCoerce,
103
+ const TProps extends Record<string, { type: string }>,
104
+ TAdditionalProps extends false | 'string' | 'number' | 'boolean' = false
105
+ >(
106
+ name: TOption,
107
+ config: ObjectOptionConfig<TCoerce, TProps, TAdditionalProps>
108
+ ): CLI<
109
+ TArgs & {
110
+ [key in TOption]: WithOptional<
111
+ unknown extends TCoerce
112
+ ? ResolveProperties<TProps> & AdditionalPropertiesType<TAdditionalProps>
113
+ : TCoerce,
114
+ ObjectOptionConfig<TCoerce, TProps, TAdditionalProps>
115
+ >;
116
+ }
117
+ >;
118
+ // String option overload
119
+ option<
120
+ TOption extends string,
121
+ const TConfig extends StringOptionConfig<any, any>
122
+ >(
123
+ name: TOption,
124
+ config: TConfig
125
+ ): CLI<
126
+ TArgs & {
127
+ [key in TOption]: OptionConfigToType<TConfig>;
128
+ }
129
+ >;
130
+ // Number option overload
131
+ option<
132
+ TOption extends string,
133
+ const TConfig extends NumberOptionConfig<any, any>
134
+ >(
135
+ name: TOption,
136
+ config: TConfig
137
+ ): CLI<
138
+ TArgs & {
139
+ [key in TOption]: OptionConfigToType<TConfig>;
140
+ }
141
+ >;
142
+ // Boolean option overload
143
+ option<
144
+ TOption extends string,
145
+ const TConfig extends BooleanOptionConfig<any, any>
146
+ >(
147
+ name: TOption,
148
+ config: TConfig
149
+ ): CLI<
150
+ TArgs & {
151
+ [key in TOption]: OptionConfigToType<TConfig>;
152
+ }
153
+ >;
154
+ // Array option overload
155
+ option<
156
+ TOption extends string,
157
+ const TConfig extends ArrayOptionConfig<any, any>
158
+ >(
159
+ name: TOption,
160
+ config: TConfig
161
+ ): CLI<
162
+ TArgs & {
163
+ [key in TOption]: OptionConfigToType<TConfig>;
164
+ }
165
+ >;
166
+ // Generic fallback overload
167
+ option<
168
+ TOption extends string,
169
+ const TOptionConfig extends OptionConfig<any, any, any, any>
170
+ >(
171
+ name: TOption,
172
+ config: TOptionConfig
173
+ ): CLI<
174
+ TArgs & {
175
+ [key in TOption]: OptionConfigToType<TOptionConfig>;
176
+ }
177
+ >;
178
+
179
+ /**
180
+ * Registers a new positional argument for the CLI command. This argument will be accessible
181
+ * within the command handler, as well as any subcommands.
182
+ * @param name The name of the positional argument.
183
+ * @param config Configuration for the positional argument. See {@link UnknownOptionConfig}.
184
+ * @returns Updated CLI instance with the new positional argument registered.
185
+ */
186
+ // Object option overload - must come first for proper contextual typing
187
+ // Uses direct ObjectOptionConfig type (not `extends`) to ensure TypeScript
188
+ // infers TProps from `properties` BEFORE evaluating the coerce callback type
189
+ positional<
190
+ TOption extends string,
191
+ TCoerce,
192
+ const TProps extends Record<string, { type: string }>,
193
+ TAdditionalProps extends false | 'string' | 'number' | 'boolean' = false
194
+ >(
195
+ name: TOption,
196
+ config: ObjectOptionConfig<TCoerce, TProps, TAdditionalProps>
197
+ ): CLI<
198
+ TArgs & {
199
+ [key in TOption]: WithOptional<
200
+ unknown extends TCoerce
201
+ ? ResolveProperties<TProps> & AdditionalPropertiesType<TAdditionalProps>
202
+ : TCoerce,
203
+ ObjectOptionConfig<TCoerce, TProps, TAdditionalProps>
204
+ >;
205
+ }
206
+ >;
207
+ // String option overload
208
+ positional<
209
+ TOption extends string,
210
+ const TConfig extends StringOptionConfig<any, any>
211
+ >(
212
+ name: TOption,
213
+ config: TConfig
214
+ ): CLI<
215
+ TArgs & {
216
+ [key in TOption]: OptionConfigToType<TConfig>;
217
+ }
218
+ >;
219
+ // Number option overload
220
+ positional<
221
+ TOption extends string,
222
+ const TConfig extends NumberOptionConfig<any, any>
223
+ >(
224
+ name: TOption,
225
+ config: TConfig
226
+ ): CLI<
227
+ TArgs & {
228
+ [key in TOption]: OptionConfigToType<TConfig>;
229
+ }
230
+ >;
231
+ // Boolean option overload
232
+ positional<
233
+ TOption extends string,
234
+ const TConfig extends BooleanOptionConfig<any, any>
235
+ >(
236
+ name: TOption,
237
+ config: TConfig
238
+ ): CLI<
239
+ TArgs & {
240
+ [key in TOption]: OptionConfigToType<TConfig>;
241
+ }
242
+ >;
243
+ // Array option overload
244
+ positional<
245
+ TOption extends string,
246
+ const TConfig extends ArrayOptionConfig<any, any>
247
+ >(
248
+ name: TOption,
249
+ config: TConfig
250
+ ): CLI<
251
+ TArgs & {
252
+ [key in TOption]: OptionConfigToType<TConfig>;
253
+ }
254
+ >;
255
+ // Generic fallback overload
256
+ positional<
257
+ TOption extends string,
258
+ const TOptionConfig extends OptionConfig<any, any, any, any>
259
+ >(
260
+ name: TOption,
261
+ config: TOptionConfig
262
+ ): CLI<
263
+ TArgs & {
264
+ [key in TOption]: OptionConfigToType<TOptionConfig>;
265
+ }
266
+ >;
267
+
268
+ /**
269
+ * Adds support for reading CLI options from environment variables.
270
+ * @param prefix The prefix to use when looking up environment variables. Defaults to the command name.
271
+ */
272
+ env(prefix?: string): CLI<TArgs>;
273
+
274
+ env(options: EnvOptionConfig): CLI<TArgs>;
275
+
276
+ /**
277
+ * Sets a group of options as mutually exclusive. If more than one option is provided, there will be a validation error.
278
+ * @param options The options that should be mutually exclusive.
279
+ */
280
+ conflicts(...options: [string, string, ...string[]]): CLI<TArgs>;
281
+
282
+ /**
283
+ * Sets a group of options as mutually inclusive. If one option is provided, all other options must also be provided.
284
+ * @param option The option that implies the other options.
285
+ * @param impliedOptions The options which become required when the option is provided.
286
+ */
287
+ implies(option: string, ...impliedOptions: string[]): CLI<TArgs>;
288
+
289
+ /**
290
+ * Requires a command to be provided when executing the CLI. Useful if your parent command
291
+ * cannot be executed on its own.
292
+ * @returns Updated CLI instance.
293
+ */
294
+ demandCommand(): CLI<TArgs>;
295
+
296
+ /**
297
+ * Sets the usage text for the CLI. This text will be displayed in place of the default usage text
298
+ * @param usageText Text displayed in place of the default usage text for `--help` and in generated docs.
299
+ */
300
+ usage(usageText: string): CLI<TArgs>;
301
+
302
+ /**
303
+ * Sets the description for the CLI. This text will be displayed in the help text and generated docs.
304
+ * @param examples Examples to display in the help text and generated docs.
305
+ */
306
+ examples(...examples: string[]): CLI<TArgs>;
307
+
308
+ /**
309
+ * Allows overriding the version displayed when passing `--version`. Defaults to crawling
310
+ * the file system to get the package.json of the currently executing command.
311
+ * @param override
312
+ */
313
+ version(override?: string): CLI<TArgs>;
314
+
315
+ /**
316
+ * Prints help text to stdout.
317
+ */
318
+ printHelp(): void;
319
+
320
+ group({
321
+ label,
322
+ keys,
323
+ sortOrder,
324
+ }: {
325
+ label: string;
326
+ keys: (keyof TArgs)[];
327
+ sortOrder: number;
328
+ }): CLI<TArgs>;
329
+ group(label: string, keys: (keyof TArgs)[]): CLI<TArgs>;
330
+
331
+ middleware<TArgs2>(
332
+ callback: MiddlewareFunction<TArgs, TArgs2>
333
+ ): CLI<TArgs2 extends void ? TArgs : TArgs & TArgs2>;
334
+
335
+ /**
336
+ * Parses argv and executes the CLI
337
+ * @param args argv. Defaults to process.argv.slice(2)
338
+ * @returns Promise that resolves when the handler completes.
339
+ */
340
+ forge(args?: string[]): Promise<TArgs>;
341
+ }
342
+
343
+ export interface CLIHandlerContext {
344
+ command: CLI<any>;
345
+ }
346
+
347
+ /**
348
+ * Represents the configuration needed to create a CLI command.
349
+ */
350
+ export interface CLICommandOptions<
351
+ /**
352
+ * The type of the arguments that are already registered before `builder` is invoked.
353
+ */
354
+ TInitial extends ParsedArgs,
355
+ /**
356
+ * The type of the arguments that are registered after `builder` is invoked, and the type that is passed to the handler.
357
+ */
358
+ TArgs extends TInitial = TInitial
359
+ > {
360
+ /**
361
+ * If set the command will be registered under the provided name and any aliases.
362
+ *
363
+ * This can be useful if a command should be executed under more than one name, e.g. `npx my-cli` and `npx my-cli hello`.
364
+ */
365
+ alias?: string[];
366
+
367
+ /**
368
+ * The command description. This will be displayed in the help text and generated docs.
369
+ */
370
+ description?: string;
371
+
372
+ /**
373
+ * The command builder. This function is called before the command is executed, and is used to register options and positional parameters.
374
+ * @param parser The parser instance to register options and positionals with.
375
+ */
376
+ builder?: (parser: CLI<TInitial>) => CLI<TArgs>;
377
+
378
+ /**
379
+ * The command handler. This function is called when the command is executed.
380
+ * @param args The parsed arguments.
381
+ * @param context Context for the handler. Contains the command instance.
382
+ */
383
+ handler?: (args: TArgs, context: CLIHandlerContext) => void | Promise<void>;
384
+
385
+ /**
386
+ * The usage text for the command. This text will be displayed in place of the default usage text in the help text and generated docs.
387
+ */
388
+ usage?: string;
389
+
390
+ /**
391
+ * Examples to display in the help text and generated docs.
392
+ */
393
+ examples?: string[];
394
+
395
+ /**
396
+ * Hides the command from the help text and generated docs. Useful primarily for experimental or internal commands.
397
+ */
398
+ hidden?: boolean;
399
+
400
+ /**
401
+ * The epilogue text for the command. This text will be displayed at the end of the help text and generated docs.
402
+ */
403
+ epilogue?: string;
404
+ }
405
+
406
+ export type Command<
407
+ TInitial extends ParsedArgs = any,
408
+ TArgs extends TInitial = TInitial
409
+ > =
410
+ | ({
411
+ name: string;
412
+ } & CLICommandOptions<TInitial, TArgs>)
413
+ | CLI<TArgs>;
414
+
415
+ /**
416
+ * Error Handler for CLI applications. Error handlers should re-throw the error if they cannot handle it.
417
+ *
418
+ * @param e The error that was thrown.
419
+ * @param actions Actions that can be taken by the error handler. Prefer using these over process.exit for better support of interactive shells.
420
+ */
421
+ export type ErrorHandler = (
422
+ e: unknown,
423
+ actions: {
424
+ /**
425
+ * Exits the process immediately.
426
+ * @param code
427
+ */
428
+ exit: (code?: number) => void;
429
+ }
430
+ ) => void;
431
+
432
+ export type MiddlewareFunction<TArgs extends ParsedArgs, TArgs2> = (
433
+ args: TArgs
434
+ ) => TArgs2 | Promise<TArgs2>;
435
+
436
+ /**
437
+ * Constructs a CLI instance. See {@link CLI} for more information.
438
+ * @param name Name for the top level CLI
439
+ * @param rootCommandConfiguration Configuration used when running the bare CLI. e.g. npx my-cli, rather than npx my-cli [cmd]
440
+ * @returns A {@link CLI} instance.
441
+ */
442
+ export function cli<TArgs extends ParsedArgs>(
443
+ name: string,
444
+ rootCommandConfiguration?: CLICommandOptions<ParsedArgs, TArgs>
445
+ ) {
446
+ return new InternalCLI(name, rootCommandConfiguration) as any as CLI<TArgs>;
447
+ }
448
+
449
+ export default cli;
@@ -0,0 +1,29 @@
1
+ import cli from './public-api';
2
+ import { TestHarness } from './test-harness';
3
+
4
+ describe('test harness', () => {
5
+ it('should not actually run commands', async () => {
6
+ let commandsExecuted = 0;
7
+ const cliUnderTest = cli('test').commands(
8
+ {
9
+ name: 'foo',
10
+ builder: (argv) => argv.option('bar', { type: 'string' }),
11
+ handler: () => {
12
+ commandsExecuted++;
13
+ },
14
+ },
15
+ {
16
+ name: 'bar',
17
+ builder: (argv) => argv.option('baz', { type: 'string' }),
18
+ handler: () => {
19
+ commandsExecuted++;
20
+ },
21
+ }
22
+ );
23
+ const harness = new TestHarness(cliUnderTest);
24
+ const { commandChain, args } = await harness.parse(['foo', '--bar', 'baz']);
25
+ expect(commandChain).toEqual(['foo']);
26
+ expect(commandsExecuted).toEqual(0);
27
+ expect(args).toEqual({ bar: 'baz', unmatched: [] });
28
+ });
29
+ });
@@ -0,0 +1,69 @@
1
+ import { ParsedArgs } from '@cli-forge/parser';
2
+ import { InternalCLI } from './internal-cli';
3
+ import { CLI } from './public-api';
4
+
5
+ export type TestHarnessParseResult<T extends ParsedArgs> = {
6
+ /**
7
+ * Parsed arguments. Note the the typing of this is based on the CLI typings,
8
+ * but no runtime validation outside of the configured validation checks on
9
+ * individual options will be performed. If you want to validate the arguments,
10
+ * you should do so in your test or configure a `validate` callback for the option.
11
+ */
12
+ args: T;
13
+
14
+ /**
15
+ * The command chain that was resolved during parsing. This is used for testing
16
+ * that the correct command is ran when resolving a subcommand. A test that checks
17
+ * this may look like:
18
+ *
19
+ * ```ts
20
+ * const harness = new TestHarness(cli);
21
+ * const { args, commandChain } = await harness.parse(['hello', '--name=sir']);
22
+ * expect(commandChain).toEqual(['hello']);
23
+ * ```
24
+ *
25
+ * The above test would check that the `hello` command was resolved when parsing
26
+ * the argstring, and since only one command's handler will ever be called, this
27
+ * can be used to ensure that the correct command is ran.
28
+ */
29
+ commandChain: string[];
30
+ };
31
+
32
+ /**
33
+ * Utility for testing CLI instances. Can check argument parsing and validation, including
34
+ * command chain resolution.
35
+ */
36
+ export class TestHarness<T extends ParsedArgs> {
37
+ private cli: InternalCLI<T>;
38
+
39
+ constructor(cli: CLI<T>) {
40
+ if (cli instanceof InternalCLI) {
41
+ this.cli = cli;
42
+ mockHandler(cli);
43
+ } else {
44
+ throw new Error(
45
+ 'TestHarness can only be used with CLI instances created by `cli`.'
46
+ );
47
+ }
48
+ }
49
+
50
+ async parse(args: string[]): Promise<TestHarnessParseResult<T>> {
51
+ const argv = await this.cli.forge(args);
52
+
53
+ return {
54
+ args: argv,
55
+ commandChain: this.cli.commandChain,
56
+ };
57
+ }
58
+ }
59
+
60
+ function mockHandler(cli: InternalCLI) {
61
+ if (cli.configuration?.handler) {
62
+ cli.configuration.handler = () => {
63
+ // Mocked, should do nothing.
64
+ };
65
+ }
66
+ for (const command in cli.registeredCommands) {
67
+ mockHandler(cli.registeredCommands[command]);
68
+ }
69
+ }
@@ -0,0 +1,25 @@
1
+ import { stringToArgs } from './utils';
2
+
3
+ describe('utils', () => {
4
+ describe('stringToArgs', () => {
5
+ it.each([
6
+ ['hello', ['hello']],
7
+ ['hello world', ['hello', 'world']],
8
+ ['hello "world"', ['hello', 'world']],
9
+ ['hello "mom and dad"', ['hello', 'mom and dad']],
10
+ [
11
+ 'hello "mom and dad" "brother and sister"',
12
+ ['hello', 'mom and dad', 'brother and sister'],
13
+ ],
14
+ [
15
+ 'hello "mom and \\"dad\\"" "brother and sister"',
16
+ ['hello', 'mom and "dad"', 'brother and sister'],
17
+ ],
18
+ ["hello 'world'", ['hello', 'world']],
19
+ ["hello 'mom and dad'", ['hello', 'mom and dad']],
20
+ ['hello \'mom and "dad"\'', ['hello', 'mom and "dad"']],
21
+ ])(`should parse %s`, (input, expected) => {
22
+ expect(stringToArgs(input)).toEqual(expected);
23
+ });
24
+ });
25
+ });