@flowscripter/dynamic-cli-framework 1.0.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 (133) hide show
  1. package/.github/workflows/check-bun-dependencies.yml +9 -0
  2. package/.github/workflows/lint-pr-message.yml +11 -0
  3. package/.github/workflows/release-bun-library.yml +8 -0
  4. package/.github/workflows/validate-bun-library-pr.yml +8 -0
  5. package/LICENSE +21 -0
  6. package/README.md +1475 -0
  7. package/bun.lock +63 -0
  8. package/index.ts +89 -0
  9. package/package.json +23 -0
  10. package/src/api/CLI.ts +17 -0
  11. package/src/api/CLIConfig.ts +19 -0
  12. package/src/api/Context.ts +25 -0
  13. package/src/api/RunResult.ts +142 -0
  14. package/src/api/argument/Argument.ts +36 -0
  15. package/src/api/argument/ArgumentValueTypes.ts +87 -0
  16. package/src/api/argument/ComplexOption.ts +31 -0
  17. package/src/api/argument/GlobalCommandArgument.ts +17 -0
  18. package/src/api/argument/Option.ts +32 -0
  19. package/src/api/argument/Positional.ts +27 -0
  20. package/src/api/argument/SubCommandArgument.ts +20 -0
  21. package/src/api/command/Command.ts +22 -0
  22. package/src/api/command/GlobalCommand.ts +33 -0
  23. package/src/api/command/GlobalModifierCommand.ts +12 -0
  24. package/src/api/command/GroupCommand.ts +20 -0
  25. package/src/api/command/SubCommand.ts +41 -0
  26. package/src/api/command/UsageExample.ts +21 -0
  27. package/src/api/service/ServiceProvider.ts +52 -0
  28. package/src/api/service/core/AsciiBannerGeneratorService.ts +35 -0
  29. package/src/api/service/core/KeyValueService.ts +28 -0
  30. package/src/api/service/core/PrinterService.ts +266 -0
  31. package/src/api/service/core/ShutdownService.ts +12 -0
  32. package/src/api/service/core/SyntaxHighlighterService.ts +42 -0
  33. package/src/cli/BaseCLI.ts +312 -0
  34. package/src/cli/DefaultRuntimeCLI.ts +54 -0
  35. package/src/command/MultiCommandCliHelpCommand.ts +394 -0
  36. package/src/command/SingleCommandCliHelpCommand.ts +183 -0
  37. package/src/command/UsageCommand.ts +35 -0
  38. package/src/command/VersionCommand.ts +22 -0
  39. package/src/launcher.ts +127 -0
  40. package/src/runtime/DefaultContext.ts +32 -0
  41. package/src/runtime/argument/ArgumentTypeGuards.ts +8 -0
  42. package/src/runtime/command/CommandTypeGuards.ts +30 -0
  43. package/src/runtime/command/CommandValidator.ts +549 -0
  44. package/src/runtime/parser.ts +219 -0
  45. package/src/runtime/registry/CommandRegistry.ts +121 -0
  46. package/src/runtime/registry/DefaultCommandRegistry.ts +318 -0
  47. package/src/runtime/registry/DefaultServiceProviderRegistry.ts +26 -0
  48. package/src/runtime/registry/ServiceProviderRegistry.ts +11 -0
  49. package/src/runtime/runner.ts +697 -0
  50. package/src/runtime/scanner.ts +417 -0
  51. package/src/runtime/values/ValuePopulationResult.ts +41 -0
  52. package/src/runtime/values/argumentValueMerge.ts +201 -0
  53. package/src/runtime/values/argumentValueValidation.ts +610 -0
  54. package/src/runtime/values/globalCommandValuePopulation.ts +96 -0
  55. package/src/runtime/values/subCommandValuePopulation.ts +680 -0
  56. package/src/service/asciiBannerGenerator/AsciiBannerGeneratorServiceProvider.ts +45 -0
  57. package/src/service/asciiBannerGenerator/DefaultAsciiBannerGeneratorService.ts +38 -0
  58. package/src/service/asciiBannerGenerator/standard.flf.json +3 -0
  59. package/src/service/banner/BannerServiceProvider.ts +99 -0
  60. package/src/service/banner/command/NoBannerCommand.ts +42 -0
  61. package/src/service/configuration/ConfigurationServiceProvider.ts +571 -0
  62. package/src/service/configuration/DefaultKeyValueService.ts +60 -0
  63. package/src/service/configuration/command/ConfigCommand.ts +43 -0
  64. package/src/service/configuration/command/DumpConfigCommand.ts +47 -0
  65. package/src/service/printer/DefaultPrinterService.ts +256 -0
  66. package/src/service/printer/PrinterServiceProvider.ts +61 -0
  67. package/src/service/printer/command/DarkModeCommand.ts +43 -0
  68. package/src/service/printer/command/LogLevelCommand.ts +68 -0
  69. package/src/service/printer/command/NoColorCommand.ts +43 -0
  70. package/src/service/printer/terminal/Ansi.ts +10 -0
  71. package/src/service/printer/terminal/Color.ts +14 -0
  72. package/src/service/printer/terminal/Progress.ts +373 -0
  73. package/src/service/printer/terminal/Spinner.ts +100 -0
  74. package/src/service/printer/terminal/Styler.ts +5 -0
  75. package/src/service/printer/terminal/Terminal.ts +8 -0
  76. package/src/service/printer/terminal/Theme.ts +34 -0
  77. package/src/service/printer/terminal/TtyStyler.ts +39 -0
  78. package/src/service/printer/terminal/TtyTerminal.ts +65 -0
  79. package/src/service/shutdown/DefaultShutdownService.ts +9 -0
  80. package/src/service/shutdown/ShutdownServiceProvider.ts +55 -0
  81. package/src/service/syntaxHighlighter/DefaultSyntaxHighlighterService.ts +52 -0
  82. package/src/service/syntaxHighlighter/SyntaxHighlighterServiceProvider.ts +51 -0
  83. package/src/util/configHelper.ts +95 -0
  84. package/src/util/envVarHelper.ts +338 -0
  85. package/src/util/helpHelper.ts +751 -0
  86. package/src/util/logger.ts +84 -0
  87. package/src/util/runnerHelper.ts +112 -0
  88. package/tests/cli/BaseCLI.test.ts +344 -0
  89. package/tests/command/MultiCommandCliHelpCommand.test.ts +650 -0
  90. package/tests/command/SingleCommandCliHelpCommand.test.ts +384 -0
  91. package/tests/command/UsageCommand.test.ts +53 -0
  92. package/tests/command/VersionCommand.test.ts +36 -0
  93. package/tests/fixtures/CLIConfig.ts +9 -0
  94. package/tests/fixtures/Command.ts +229 -0
  95. package/tests/fixtures/CommandRegistry.ts +8 -0
  96. package/tests/fixtures/ConfigurationServiceProvider.ts +28 -0
  97. package/tests/fixtures/Context.ts +33 -0
  98. package/tests/fixtures/ServiceProviderRegistry.ts +16 -0
  99. package/tests/fixtures/StreamString.ts +37 -0
  100. package/tests/fixtures/util.ts +41 -0
  101. package/tests/runtime/DefaultContext.test.ts +20 -0
  102. package/tests/runtime/argument/ArgumentTypeGuards.test.ts +49 -0
  103. package/tests/runtime/command/CommandTypeGuards.test.ts +43 -0
  104. package/tests/runtime/command/CommandValidator.test.ts +816 -0
  105. package/tests/runtime/parser.test.ts +766 -0
  106. package/tests/runtime/registry/DefaultCommandRegistry.test.ts +166 -0
  107. package/tests/runtime/registry/DefaultServiceProviderRegistry.test.ts +42 -0
  108. package/tests/runtime/runner.test.ts +1298 -0
  109. package/tests/runtime/scanner.test.ts +1113 -0
  110. package/tests/runtime/values/argumentValueMerge.test.ts +314 -0
  111. package/tests/runtime/values/argumentValueValidation.test.ts +1020 -0
  112. package/tests/runtime/values/globalCommandValuePopulation.test.ts +662 -0
  113. package/tests/runtime/values/subCommandValuePopulation.test.ts +2658 -0
  114. package/tests/service/asciiBannerGenerator/AsciiBannerGeneratorServiceProvider.test.ts +22 -0
  115. package/tests/service/asciiBannerGenerator/DefaultAsciiBannerGeneratorService.test.ts +70 -0
  116. package/tests/service/asciiBannerGenerator/__snapshots__/DefaultAsciiBannerGeneratorService.test.ts.snap +22 -0
  117. package/tests/service/asciiBannerGenerator/small.flf.json +3 -0
  118. package/tests/service/configuration/ConfigurationServiceProvider.test.ts +249 -0
  119. package/tests/service/configuration/DefaultKeyValueService.test.ts +65 -0
  120. package/tests/service/launchBanner/BannerServiceProvider.test.ts +49 -0
  121. package/tests/service/launchBanner/__snapshots__/BannerServiceProvider.test.ts.snap +3 -0
  122. package/tests/service/launchBanner/command/NoBannerCommand.test.ts +21 -0
  123. package/tests/service/printer/DefaultPrinterService.test.ts +409 -0
  124. package/tests/service/printer/PrinterServiceProvider.test.ts +29 -0
  125. package/tests/service/printer/command/LogLevelCommand.test.ts +58 -0
  126. package/tests/service/printer/terminal/Progress.test.ts +40 -0
  127. package/tests/service/printer/terminal/Spinner.test.ts +57 -0
  128. package/tests/service/shutdown/ShutdownServiceProvider.test.ts +13 -0
  129. package/tests/service/syntaxHighlighter/DefaultSyntaxHighlighterService.test.ts +123 -0
  130. package/tests/service/syntaxHighlighter/SyntaxHighlighterServiceProvider.test.ts +41 -0
  131. package/tests/util/configHelper.test.ts +275 -0
  132. package/tests/util/envVarHelper.test.ts +318 -0
  133. package/tests/util/logger.test.ts +10 -0
package/README.md ADDED
@@ -0,0 +1,1475 @@
1
+ # dynamic-cli-framework
2
+
3
+ [![version](https://img.shields.io/github/v/release/flowscripter/dynamic-cli-framework?sort=semver)](https://github.com/flowscripter/dynamic-cli-framework/releases)
4
+ [![build](https://img.shields.io/github/actions/workflow/status/flowscripter/dynamic-cli-framework/release-bun-library.yml)](https://github.com/flowscripter/dynamic-cli-framework/actions/workflows/release-bun-library.yml)
5
+ [![coverage](https://codecov.io/gh/flowscripter/dynamic-cli-framework/branch/main/graph/badge.svg?token=EMFT2938ZF)](https://codecov.io/gh/flowscripter/dynamic-cli-framework)
6
+ [![docs](https://img.shields.io/badge/docs-API-blue)](https://flowscripter.github.io/dynamic-cli-framework/index.html)
7
+ [![license: MIT](https://img.shields.io/github/license/flowscripter/dynamic-cli-framework)](https://github.com/flowscripter/dynamic-cli-framework/blob/main/LICENSE)
8
+
9
+ > A framework for developing CLI applications which supports dynamic discovery
10
+ > and installation of new commands
11
+
12
+ [//]: # (TODO: Remove this when plugin support and compiled binaries available.)
13
+
14
+ NOTE: The dynamic aspect is still in development as it relies upon:
15
+
16
+ - some outstanding work on the
17
+ [dynamic-plugin-framework](https://github.com/flowscripter/dynamic-plugin-framework)
18
+ dependency.
19
+
20
+ So it isn't really dynamic at the moment! 😜
21
+
22
+ ## Key Features
23
+
24
+ - Flexible CLI definitions:
25
+ - a single default global command with global arguments e.g.
26
+ `executable [global_arguments]`
27
+ - multiple sub-commands with sub-command based arguments e.g.
28
+ `executable <sub_command> [sub_command_arguments]`
29
+ - multiple grouped member sub-commands with member sub-command based arguments
30
+ e.g.
31
+ `executable <group_command> <member_sub_command> [member_sub_command_arguments]`
32
+ - A mix of the above!
33
+ - Support for both named option and position based arguments e.g.
34
+ `executable --<option_name>=<option_value> <positional_value>`
35
+ - Support for specifying multiple values for:
36
+ - named options arguments via either:
37
+ - implicitly indexed repeated arguments e.g.
38
+ `executable --<option_name>=<option_value_1> --<option_name>=<option_value_2>`
39
+ - or explicitly indexed arguments e.g.
40
+ `executable --<option_name>[0]=<option_value_1> --<option_name>[1]=<option_value_2>`
41
+ - position based arguments ("varargs") e.g.
42
+ `executable <positional_1_value_1> <positional_1_value_2>`
43
+ - Support for complex nested options e.g.
44
+ `executable --<option_name>.<property_1_name>=<property_1_value> --<option_name>.<property_1>.<property_1_a>=<property_1_a_value>`
45
+ - Support (optional) for persisted configuration and environment variables to
46
+ specify command argument defaults.
47
+ - Core (but optional) commands for help, logging level and version management.
48
+ - Core (but optional) services for color output to stdout/stderr and
49
+ configuration management.
50
+ - Core (but optional) support for dynamic discovery and installation of commands
51
+ and services using
52
+ [dynamic-plugin-framework](https://github.com/flowscripter/dynamic-plugin-framework)
53
+ - Minimal dependencies.
54
+ - Bun based.
55
+ - Based on native JavaScript modules.
56
+ - Written in Typescript.
57
+ - Compiled to a binary executable using a Bun runtime.
58
+
59
+ ## Usage Examples
60
+
61
+ The following example projects are available:
62
+
63
+ - [example-cli](https://github.com/flowscripter/example-cli) is an example CLI
64
+ application based on this framework.
65
+
66
+ [//]: # (TODO: Add this when implemented.)
67
+ [//]: # (- [example-cli-plugin]&#40;https://github.com/flowscripter/example-cli-plugin&#41; is an)
68
+ [//]: # ( example command and service plugin based on this framework.)
69
+ [//]: # (TODO: Add this when implemented.)
70
+ [//]: # (- [sdl-tool]&#40;https://github.com/flowscripter/sdl-tool&#41; is a real world use case CLI)
71
+ [//]: # ( application based on this framework.)
72
+
73
+ ## Key Concepts
74
+
75
+ The key concepts are:
76
+
77
+ - Specific command functionality is implemented within one or more `Command`
78
+ instances.
79
+ - Generic support functionality is implemented within or or more `Service`
80
+ instances.
81
+ - The `CLI` is responsible for:
82
+ - maintaining a `CommandRegistry` and ensuring the `Command` instances it has
83
+ registered are available when scanning and parsing arguments and executing
84
+ specified commands.
85
+ - maintaining a `ServiceProviderRegistry` and ensuring that services provided
86
+ by each of the registered `ServiceProvider` instances are available for use
87
+ by any invoked `Command` via a a `Context`.
88
+ - Dynamic plugins (enabled by
89
+ [dynamic-plugin-framework](https://github.com/flowscripter/dynamic-plugin-framework))
90
+ allow:
91
+ - dynamic load and import of one or more `CommandFactory` implementations
92
+ providing one or more `Command` implementations.
93
+ - dynamic load and import of one or more `ServiceProviderFactory`
94
+ implementations providing one or more `ServiceProvider` implementations.
95
+
96
+ The following high-level conceptual diagram illustrates these relationships:
97
+
98
+ ```mermaid
99
+ classDiagram
100
+ class CLI {
101
+ <<interface>>
102
+ }
103
+
104
+ class CLIConfig {
105
+ }
106
+
107
+ class Command {
108
+ <<interface>>
109
+ }
110
+
111
+ class ServiceProvider {
112
+ <<interface>>
113
+ serviceId
114
+ servicePriority
115
+ }
116
+
117
+ class Context {
118
+ <<interface>>
119
+ }
120
+
121
+ class CommandRegistry {
122
+ <<interface>>
123
+ }
124
+
125
+ class ServiceProviderRegistry {
126
+ <<interface>>
127
+ }
128
+
129
+ class Service {
130
+ <<interface>>
131
+ }
132
+
133
+ CLI --> CLIConfig
134
+
135
+ CLI --> Context
136
+
137
+ CLI --> CommandRegistry
138
+
139
+ CommandRegistry --> "*" Command : registers
140
+
141
+ ServiceProviderRegistry --> "*" ServiceProvider : registers
142
+
143
+ CLI --> "1..*" Command : executes
144
+
145
+ Command --> Context : executed within
146
+
147
+ Context --> CLIConfig
148
+
149
+ Context --> "*" Service : access to
150
+
151
+ ServiceProvider --> "*" Service : provides
152
+
153
+ class PluginManager {
154
+ }
155
+
156
+ class Plugin {
157
+ <<interface>>
158
+ }
159
+
160
+ CLI --> PluginManager
161
+
162
+ class CommandFactory {
163
+ <<interface>>
164
+ }
165
+
166
+ class ServiceProviderFactory {
167
+ <<interface>>
168
+ }
169
+
170
+ CLI-->ServiceProviderRegistry
171
+
172
+ PluginManager --> "*" Plugin : registers
173
+
174
+ Plugin --> "*" CommandFactory: implements
175
+
176
+ Plugin --> "*" ServiceProviderFactory: implements
177
+
178
+ CommandFactory --> "*" Command : provides
179
+
180
+ ServiceProviderFactory --> "*" ServiceProvider : provides
181
+ ```
182
+
183
+ ### Commands
184
+
185
+ A `Command` declares:
186
+
187
+ - a `name` which is to be used in command line arguments to invoke it.
188
+ - a function `execute()` which is invoked if the command is specified. This
189
+ function is invoked with the parsed arguments and a context.
190
+ - an optional declaration of arguments it supports.
191
+
192
+ The sub-types of command are: `GlobalCommand`, `GlobalModifierCommand`,
193
+ `SubCommand` and `GroupCommand`.
194
+
195
+ The following high-level conceptual diagram illustrates the Command API:
196
+
197
+ ```mermaid
198
+ classDiagram
199
+ class Command {
200
+ <<interface>>
201
+ name
202
+ description
203
+ enableConfiguration
204
+ }
205
+
206
+ class SubCommand {
207
+ <<interface>>
208
+ execute()
209
+ }
210
+
211
+ class GroupCommand {
212
+ <<interface>>
213
+ execute()
214
+ }
215
+
216
+ class GlobalCommand {
217
+ <<interface>>
218
+ shortAlias
219
+ execute()
220
+ }
221
+
222
+ class GlobalModifierCommand {
223
+ <<interface>>
224
+ executePriority
225
+ }
226
+
227
+ class Argument {
228
+ <<interface>>
229
+ type
230
+ allowableValues
231
+ configurationKey
232
+ }
233
+
234
+ class SubCommandArgument {
235
+ name
236
+ description
237
+ <<interface>>
238
+ }
239
+
240
+ class Option {
241
+ <<interface>>
242
+ shortAlias
243
+ defaultValue
244
+ isOptional
245
+ isArray
246
+ }
247
+
248
+ class Positional {
249
+ <<interface>>
250
+ isVarArgMultiple
251
+ isVarArgOptional
252
+ }
253
+
254
+ class ComplexOption {
255
+ <<interface>>
256
+ }
257
+
258
+ class GlobalCommandArgument {
259
+ <<interface>>
260
+ defaultValue
261
+ isOptional
262
+ }
263
+
264
+ class UsageExample {
265
+ description
266
+ exampleArguments
267
+ output
268
+ }
269
+
270
+ Argument <|-- SubCommandArgument
271
+
272
+ Argument <|-- GlobalCommandArgument
273
+
274
+ SubCommandArgument <|-- Option
275
+
276
+ SubCommandArgument <|-- Positional
277
+
278
+ Option <|-- ComplexOption
279
+
280
+ Option "1..*" <-- ComplexOption : properties
281
+
282
+ Command <|-- GroupCommand
283
+
284
+ Option "0..*" <-- SubCommand
285
+
286
+ Positional "0..*" <-- SubCommand
287
+
288
+ GlobalCommand --> "0..1" GlobalCommandArgument
289
+
290
+ Command <|-- SubCommand
291
+
292
+ GlobalCommand <|-- GlobalModifierCommand
293
+
294
+ Command <|-- GlobalCommand
295
+
296
+ GroupCommand --> "1..*" SubCommand : memberSubCommands
297
+
298
+ SubCommand --> "0..*" UsageExample
299
+ ```
300
+
301
+ #### Global Command
302
+
303
+ A `GlobalCommand` provides the ability to invoke functionality via a global
304
+ argument and one optional value:
305
+
306
+ executable --<global_command>[=<value>]
307
+
308
+ A concrete example:
309
+
310
+ myNetworkApp --help=connect
311
+
312
+ A `GlobalCommand` also supports a short character alias:
313
+
314
+ executable -<global_command_short_alias>[=<value>]
315
+
316
+ A concrete example:
317
+
318
+ myNetworkApp -h=connect
319
+
320
+ #### Global Modifier Commands
321
+
322
+ Any number of `GlobalModifierCommand` instances can be specified as long as they
323
+ are accompanied by a `GlobalCommand` or a `SubCommand`:
324
+
325
+ executable --<global_modifier_command_1>[=<global_modifier_command_1_argument>] \
326
+ --<global_modifier_command_2>[=<global_modifier_command_2_argument>] \
327
+ <global_command>[=<value>]
328
+
329
+ Each `GlobalModifierCommand` will be executed before the single specified
330
+ `GlobalCommand` or `SubCommand` is executed. This behaviour allows
331
+ `GlobalModifierCommands` to modify the context in which later commands execute.
332
+
333
+ A `GlobalModifierCommand` defines an "execution priority" which is used to
334
+ determine the order of execution when multiple `GlobalModifierCommands` are
335
+ specified.
336
+
337
+ A concrete example:
338
+
339
+ myNetworkApp --log-level=DEBUG --config=./config.json --help
340
+
341
+ where:
342
+
343
+ - `log-level` is a `GlobalModifierCommand` with a value of `DEBUG`
344
+ - `config` is a `GlobalModifierCommand` with a value of `./config.json`
345
+ - `help` is a `GlobalCommand`.
346
+
347
+ #### Sub-Command
348
+
349
+ A `SubCommand` provides the ability to invoke functionality via specifying the
350
+ command name followed by any number of option and positional arguments.
351
+
352
+ A sub-command is invoked as follows:
353
+
354
+ executable <sub_command> [sub_command_arguments]
355
+
356
+ A concrete example:
357
+
358
+ myNetworkApp serve --host=localhost
359
+
360
+ #### Group Command
361
+
362
+ A `GroupCommand` allows multiple member `SubCommand` instances to be grouped
363
+ under a single named group. The name of the `GroupCommand` is specified before
364
+ the desired member `SubCommand` in one of two ways:
365
+
366
+ executable <group_command> <member_sub_command> [member_sub_command_arguments]
367
+ executable <group_command>:<member_sub_command> [member_sub_command_arguments]
368
+
369
+ Some concrete examples:
370
+
371
+ myNetworkApp utils ping --host=localhost
372
+ myNetworkApp utils:ping --host=localhost
373
+
374
+ **NOTE**: A `GroupCommand` also provides for it's own logic to be invoked BEFORE
375
+ the specified sub-command. However, a `GroupCommand` does not support any
376
+ arguments itself.
377
+
378
+ ### Arguments
379
+
380
+ #### Global Command and Global Modifier Command Arguments
381
+
382
+ `GlobalCommand` and `GlobalModifierCommand` instances support the definition of
383
+ a single `GlobalCommandArgument` consisting of:
384
+
385
+ - a type: `NUMBER`, `INTEGER`, `BOOLEAN`, `STRING` or `SECRET`.
386
+ - an optional set of allowable values.
387
+ - an optional default value.
388
+ - whether the value is mandatory.
389
+
390
+ There are four ways in which these argument values can be specified:
391
+
392
+ executable --<global_command>=<value>
393
+ executable --<global_command> <value>
394
+ executable -<global_command_short_alias>=<value>
395
+ executable -<global_command_short_alias> <value>
396
+
397
+ Some concrete examples:
398
+
399
+ myNetworkApp --help=connect
400
+ myNetworkApp --help connect
401
+ myNetworkApp -h=connect
402
+ myNetworkApp -h connect
403
+
404
+ ###### Boolean Values
405
+
406
+ For boolean options, specifying the value as `true` is not required. All of the
407
+ following set the value to `true`:
408
+
409
+ executable --<global_command>=true
410
+ executable --<global_command> true
411
+ executable --<global_command>
412
+ executable -<global_command_short_alias>=true
413
+ executable -<global_command_short_alias> true
414
+ executable -<global_command_short_alias>
415
+
416
+ #### Sub-Command Arguments
417
+
418
+ Arguments for a `SubCommand` can take two forms: `Option` or `Positional`.
419
+
420
+ Common to both are the following features:
421
+
422
+ - a name which must consist of alphanumeric non-whitespace ASCII characters or
423
+ `_` and `-` characters. It cannot start with `-`.
424
+ - a type: `NUMBER`, `INTEGER`, `BOOLEAN`, `STRING` or `SECRET`.
425
+ - an optional set of valid value choices.
426
+
427
+ ##### Options
428
+
429
+ An `option` argument also provides for:
430
+
431
+ - a short character alias for the option.
432
+ - whether the option is mandatory.
433
+ - an optional default value.
434
+ - whether the option can be specified more than once (i.e. it is an array value)
435
+ - an additional type: `COMPLEX` which allows for nested arguments
436
+
437
+ There are four ways in which options can be specified:
438
+
439
+ executable <sub_command> --<option_name>=<value>
440
+ executable <sub_command> --<option_name> <value>
441
+ executable <sub_command> -<option_short_alias>=<value>
442
+ executable <sub_command> -<option_short_alias> <value>
443
+
444
+ ###### Boolean Values
445
+
446
+ For boolean options, specifying the value as `true` is not required. All of the
447
+ following set the value to `true`:
448
+
449
+ executable <sub_command> --<boolean_option_name>=true
450
+ executable <sub_command> --<boolean_option_name> true
451
+ executable <sub_command> --<boolean_option_name>
452
+ executable <sub_command> -<boolean_option_short_alias>=true
453
+ executable <sub_command> -<boolean_option_short_alias> true
454
+ executable <sub_command> -<boolean_option_short_alias>
455
+
456
+ ###### Array Options
457
+
458
+ For array options, multiple values can be specified using explicit indices:
459
+
460
+ executable <sub_command> --<array_option_name>[index]=value --<array_option_name>[index]=value
461
+
462
+ or with implicit indices:
463
+
464
+ executable <sub_command> --<array_option_name>=value --<array_option_name>=value
465
+
466
+ Some concrete examples:
467
+
468
+ myNetworkApp --bind --interface[0]=eth0 --interface[1]=eth1
469
+ myNetworkApp --bind --interface=eth0 --interface=eth1
470
+
471
+ **NOTE**: When using explicit indices, the indices may be specified in any
472
+ order, however specifying a sparse array is not supported:
473
+
474
+ myNetworkApp --bind --interface[2]=eth0 --interface[1]=eth1 --interface[0]=eth2
475
+ myNetworkApp --bind --interface[1]=eth0 --interface[2]=eth1 // invalid as index 0 is not specified
476
+
477
+ **NOTE**: Arrays of arrays are not supported:
478
+
479
+ myNetworkApp --bind --interfaces[0][0]=eth0 // invalid as multi-dimensional arrays are not supported
480
+
481
+ ###### Complex Options
482
+
483
+ For complex options, the path to the desired property is specified using a `.`
484
+ separator:
485
+
486
+ executable <sub_command> --<parent_option_name>.<property_name>=<value> --<parent_option_name>.<property_name>.<sub-property-name>=<value>
487
+ executable <sub_command> --<parent_option_name>.<property_short_alias>=<value> --<parent_option_short_alias>.<property_name>.<sub-property-name>=<value>
488
+
489
+ Mixed use of option names and short aliases is supported when specifying nested
490
+ complex option properties. If the property specification starts with the root
491
+ options's name then `--` must be used; whereas if it starts with the root
492
+ option's short alias then `-` must be used. The following are all equivalent:
493
+
494
+ --alpha.beta.gamma=1
495
+ --alpha.b.gamma=1
496
+ --alpha.b.g=1
497
+ -a.beta.gamma=1
498
+ -a.beta.g=1
499
+ -a.b.g=1
500
+
501
+ Implicit and explicit array indexing is supported when specifying nested complex
502
+ option properties. However the implicit indexing is only applied to the last
503
+ nested property reference. The following are equivalent:
504
+
505
+ --foo.bar=1 --foo.bar=2
506
+ --foo.bar[0]=1 --foo.bar[1]=2
507
+
508
+ If arrays of complex options need to be referenced then explicit indexing is
509
+ required. As an example:
510
+
511
+ --foo[0].bar=1 --foo[1].bar=2
512
+
513
+ Some concrete examples:
514
+
515
+ myNetworkApp --connect --address.host=127.0.0.1 --address.port=8080
516
+ myNetworkApp --poll --address[0].host=127.0.0.1 --address[0].port=8080 --address[1].host=10.0.10.1 --address[1].port=443
517
+
518
+ ##### Positionals
519
+
520
+ A `positional` argument is specified by a value which appears at the correct
521
+ position in the list of `SubCommand` arguments:
522
+
523
+ executable <sub_command_name> <positional_1_value> <positional_2_value>
524
+
525
+ A concrete example:
526
+
527
+ myHelloWorldApp say hello
528
+
529
+ where:
530
+
531
+ - `say` is a sub-command.
532
+ - `hello` is the value for the first positional argument.
533
+
534
+ ###### Varargs Positionals
535
+
536
+ A `positional` argument also provides for "varargs" support (both optional and
537
+ multiple) which allows for zero, one or more entries:
538
+
539
+ **NOTE**: Only one "varargs" `positional` can be defined and it must be the last
540
+ positional expected for the command.
541
+
542
+ If "varargs" optional is set for `positional_1`, these are both valid:
543
+
544
+ executable <sub_command>
545
+ executable <sub_command> <positional_1_value_1>
546
+
547
+ If "varargs" multiple is set for `positional_1`, these are both valid:
548
+
549
+ executable <sub_command> <positional_1_value_1>
550
+ executable <sub_command> <positional_1_value_1> <positional_1_value_2>
551
+
552
+ If "varargs" optional AND multiple is set for `positional_1`, these are all
553
+ valid:
554
+
555
+ executable <sub_command>
556
+ executable <sub_command> <positional_1_value_1>
557
+ executable <sub_command> <positional_1_value_1> <positional_1_value_2> <positional_1_value_3>
558
+
559
+ ### Argument Values
560
+
561
+ #### Value Types
562
+
563
+ The supported value types which can be specified for an `Option`, a `Positional`
564
+ or `GlobalCommandArgument` are:
565
+
566
+ - `STRING` - a string value where whitespace can be included by using double
567
+ quotes e.g. `myHelloWorldApp say "hello world"`
568
+ - `NUMBER` - any number value such as `0.01` or `-10`
569
+ - `INTEGER` - any positive or negative integer value. Note that these values
570
+ will still be stored as a JavaScript number and specification as `INTEGER` is
571
+ only used for validation when parsing arguments.
572
+ - `BOOLEAN` - string values of `true`, `TRUE`, `false` and `FALSE` are converted
573
+ to a JavaScript boolean value. Specifying just the argument name is also
574
+ sufficient to indicate a value of `true`.
575
+ - `SECRET` - a string value which may be specified as an argument, as a default
576
+ value in a configuration file or (ideally) sourced from an environment
577
+ variable.
578
+
579
+ [//]: # (TODO: remove when PromptService is implemented: https://github.com/flowscripter/dynamic-cli-framework/issues/10)
580
+
581
+ **NOTE**: `SECRET` will be more useful as a type when a `PromptService` is
582
+ implemented.
583
+
584
+ #### Default Values
585
+
586
+ Support for reading default argument values from a configuration file and/or
587
+ environment variables is provided by `ConfigurationServiceProvider`.
588
+
589
+ Usage of configured default values for each `Command` is only enabled if
590
+ `Command.enableConfiguration` is `true`.
591
+
592
+ ##### Configuration File
593
+
594
+ Default values can be stored in a JSON file which contains a top level
595
+ `defaults` property. The second level of properties under `defaults` is used to
596
+ refer to each `Command` by `Command.name` and the contained values are treated
597
+ as command argument values. As an example:
598
+
599
+ ```
600
+ {
601
+ "defaults": {
602
+ "subCommand1": {
603
+ "arg1": [
604
+ 1,
605
+ 2
606
+ ],
607
+ "arg2": {
608
+ "arg3": "foo"
609
+ }
610
+ },
611
+ "subCommand2": {
612
+ "arg4": true
613
+ },
614
+ "globalCommand": "globalArgumentValue"
615
+ }
616
+ }
617
+ ```
618
+
619
+ The default location of the configuration file is
620
+ `$HOME/.<application_name>.json`. If `$HOME` is not defined then no default
621
+ configuration will be used. The location of the configuration file can be
622
+ modified via the `ConfigCommand` global modifier command.
623
+
624
+ As a concrete example, the following command line:
625
+
626
+ `myNetworkApp --connect --address.host=127.0.0.1 --address.port=8080`
627
+
628
+ is equivalent to specifying default values for the `address.host` and
629
+ `address.port` arguments in the configuration file `$HOME/.myNetworkApp.json`:
630
+
631
+ ```
632
+ {
633
+ "defaults": {
634
+ "connect": {
635
+ "address.host": "127.0.0.1",
636
+ "address.port": 8080
637
+ }
638
+ }
639
+ }
640
+ ```
641
+
642
+ and using the command line:
643
+
644
+ `myNetworkApp --connect`
645
+
646
+ These defaults can then be overridden on the command line:
647
+
648
+ `myNetworkApp --connect --address.host=192.168.1.1`
649
+
650
+ ##### Environment Variables
651
+
652
+ Default values are also sourced from environment variable values. Any values set
653
+ by environment variables will override those sourced from a configuration file.
654
+ Any values set on the command line override environment variable and
655
+ configuration file values.
656
+
657
+ The optional `Argument.configurationKey` value is a configuration key to use for
658
+ the argument. It must consist of alphanumeric non-whitespace uppercase ASCII or
659
+ `_` characters and must not start with a digit.
660
+
661
+ If not specified a default configuration key is determined as follows:
662
+
663
+ The `Argument.name` is capitalized and any `-` characters are replaced with `_`
664
+ characters. If the result starts with a digit, it is prefixed with `_`. Some
665
+ examples:
666
+
667
+ - name: `FooBar` => default configuration key: `FOOBAR`
668
+ - name: `Hello-World-` => default configuration key: `HELLO_WORLD_`
669
+ - name: `3` => default configuration key: `_3`
670
+
671
+ **NOTE**: Regardless of whether a `configurationKey` is specified, or the
672
+ default is relied upon, it will only be used if the parent `Command` has
673
+ `Command.enableConfiguration` specified as `true`.
674
+
675
+ The full key for an argument (or a nested option in a complex option) is
676
+ determined as follows:
677
+
678
+ - Nested argument configuration keys are concatenated with a `_` separator.
679
+ - Any arguments which support array values must by suffixed with `_` and an
680
+ explicit array index.
681
+ - If the root argument in the path does not use a custom
682
+ `Argument.configurationKey` then the key path is additionally suffixed with
683
+ the `CLIConfig.name` and the `Command.name` with `_` separators.
684
+
685
+ This is best explained with examples...
686
+
687
+ Examples for no custom configuration key:
688
+
689
+ - executable: `MyCLI`, command: `command1`, simple argument: `arg1` =>
690
+ environment variable: `MYCLI_COMMAND1_ARG1`
691
+ - executable: `MyCLI`, command: `command1`, array argument referring to the 1st
692
+ element: `arg2[0]` => environment variable: `MYCLI_COMMAND1_ARG2_0`
693
+ - executable: `MyCLI`, command: `command1`, argument name: `3` (this is a digit
694
+ so it is by default suffixed with `_`) => environment variable:
695
+ `MYCLI_COMMAND1__3`
696
+ - executable: `MyCLI`, command: `command1`, nested option: `arg1.arg2` =>
697
+ environment variable: `MYCLI_COMMAND1_ARG1_ARG2`
698
+ - executable: `MyCLI`, command: `command1`, nested option with both levels being
699
+ arrays and referring to the 2nd element of each: `arg1[1].arg2[1]` =>
700
+ environment variable: `MYCLI_COMMAND1_ARG1_1_ARG2_1`
701
+
702
+ Examples for custom configuration key at the root level (and therefore not
703
+ prefixed with CLI and command names):
704
+
705
+ - executable: `MyCLI`, command: `command1`, simple argument: `arg1` with
706
+ configuration key: `FOO` => environment variable: `FOO`
707
+ - executable: `MyCLI`, command: `command1`, array argument referring to the 1st
708
+ element: `arg2[0]` and with configuration key: `BAR` => environment variable:
709
+ `BAR_0`
710
+
711
+ Examples for custom configuration key NOT at the root level (and therefore
712
+ prefixed with CLI and command names) examples:
713
+
714
+ - executable: `MyCLI`, command: `command1`, nested option: `arg1.arg2` with
715
+ `arg2` configuration key: `FOO` => environment variable:
716
+ `MYCLI_COMMAND1_ARG1_FOO`
717
+ - executable: `MyCLI`, command: `command1`, nested option with both levels being
718
+ arrays and referring to the 2nd element of each: `arg1[1].arg2[1]` and with
719
+ arg2 configuration key: `BAR` => environment variable:
720
+ `MYCLI_COMMAND1_ARG1_1_BAR_1`
721
+
722
+ As a concrete example, the following command line:
723
+
724
+ `myNetworkApp --connect --address.host=127.0.0.1 --address.port=8080`
725
+
726
+ is equivalent to defining the following environment variables:
727
+
728
+ - `MYNETWORKAPP_CONNECT_ADDRESS_HOST=127.0.0.1`
729
+ - `MYNETWORKAPP_CONNECT_ADDRESS_PORT=8080`
730
+
731
+ and using the command line:
732
+
733
+ `myNetworkApp --connect`
734
+
735
+ **NOTE**: For boolean values, defining the environment variable with ANY value
736
+ is equivalent to setting it to `true`. All of the following set the value to
737
+ `true`:
738
+
739
+ NO_COLOR=1
740
+ NO_COLOR=true
741
+ NO_COLOR=false // sets the value to true as the environment variable has a value set!
742
+
743
+ To specify the value as `false`, set the environment variable to be an empty
744
+ string e.g.
745
+
746
+ NO_COLOR= // sets the value to false
747
+
748
+ #### Configured Value Merging
749
+
750
+ Any configured values are merged with parsed values before being validated based
751
+ on their associated argument definitions.
752
+
753
+ The following logic is applied during merging of configured and parsed values:
754
+
755
+ **Configured primitive values are used unless overridden by parsed values**
756
+
757
+ Example:
758
+
759
+ configured: { "foo": "bar" }
760
+ parsed: undefined
761
+ result: { "foo": "bar1" }
762
+
763
+ Example:
764
+
765
+ configured: { "foo": "bar" }
766
+ parsed: { "foo": "bar1" }
767
+ result: { "foo": "bar1" }
768
+
769
+ **Configured complex values are merged (union of unique property names) or
770
+ overridden (replacement of duplicate property names) by parsed values**
771
+
772
+ Example:
773
+
774
+ configured: { "foo": { "a": 1, "b": 2 } }
775
+ parsed: { "foo": { "a": 3, "c": 4 } }
776
+ result: { "foo": { "a": 1, "b": 2, "c": 4 } }
777
+
778
+ **Configured array values are merged (for unique indices) or overridden
779
+ (replacement of duplicate indices) by parsed values**
780
+
781
+ Example:
782
+
783
+ configured: { "foo": [ 0, 1, 2, 3 ] }
784
+ parsed: { "foo": [ 0, 4, 2 ] }
785
+ result: { "foo": [ 0, 4, 2, 3 ] }
786
+
787
+ Example:
788
+
789
+ configured: { "foo": [ 0, 1, 2, 3 ] }
790
+ parsed: { "foo": [ 0, undefined, 2 ] }
791
+ result: { "foo": [ 0, 4, 2, 3 ] }
792
+
793
+ Example:
794
+
795
+ configured: { "foo": [ { "a": 1 }, { "a": 2 }, { "a": 3 }, { "a": 4 } ] }
796
+ parsed: { "foo": [ { "a": 5 }, undefined, { "a": 6, "b": 7 } ] }
797
+ result: { "foo": [ { "a": 5 }, { "a": 2 }, { "a": 6, "b": 7 }, { "a": 4 } ] }
798
+
799
+ ####
800
+
801
+ ### Value Validation
802
+
803
+ After parsing of specified arguments, merging with configured defaults and
804
+ assigning values to relevant command arguments, values are validated based on
805
+ the argument definitions.
806
+
807
+ The following scenarios produce validation errors:
808
+
809
+ - **Missing Value**: If an argument is not optional and no value has been
810
+ provided.
811
+ - **Incorrect Value Type**: The value specified was not the correct type for the
812
+ argument. e.g. `foo` cannot be provided for a boolean argument, nor for a
813
+ complex object argument.
814
+ - **Illegal Multiple Values**: The argument does not support multiple values but
815
+ multiple values have been provided.
816
+ - **Illegal Value**: If the argument defines possible allowable values and the
817
+ value provided is not one of these.
818
+ - **Illegal Sparse Array**: If multiple values were specified using array
819
+ indices and this resulted in empty entries in the array of values.
820
+ - **Unknown Property**: If the value provided is for a property which is not
821
+ defined on a complex object argument.
822
+ - **Nesting Depth Exceeded**: If there is an attempt specify a complex option
823
+ property at a nesting depth more than the maximum (10).
824
+ - **Array Size Exceeded**: If there is an attempt set more than the maximum
825
+ (255) number of values for an array option.
826
+ - **Option Is Complex**: If the argument attempts to set a value on a complex
827
+ option rather than on a primitive option or a primitive property of a complex
828
+ option.
829
+
830
+ ## Implementation Details
831
+
832
+ ### `launcher`
833
+
834
+ The standard way to make use of the framework is to import `launcher` and use
835
+ one of the two helper functions it provides:
836
+
837
+ - `launchSingleCommandCLI`
838
+ - `launchMultiCommandCLI`
839
+
840
+ These allow a CLI implementor to specify `Command` instances to use together
841
+ with basic CLI details such as name and description.
842
+
843
+ ### `CLI`
844
+
845
+ The `CLI` interface has the simple responsibility of taking a `CLIConfig` and a
846
+ list of user specified command line arguments which it should then parse and
847
+ execute any valid specified `Command` it discovers.
848
+
849
+ #### `BaseCLI`
850
+
851
+ The `BaseCLI` class provides a base implementation of the `CLI` interface which
852
+ supports both single command and multiple sub-command CLI scenarios. It provides
853
+ the ability to add any number of `Command` and `ServiceProvider` instances.
854
+
855
+ If only one command is provided, `BaseCLI` will operate as a single command CLI
856
+ and the provided command will be set as a default command. If more than one
857
+ command is added, `BaseCLI` will operate as a multi-command CLI. In this case
858
+ the default command will be set to a help command. In the case of no command
859
+ being specified or a parse error occurring, appropriate help will be displayed.
860
+
861
+ By default the `BaseCLI` adds the following `ServiceProvider` implementations
862
+ (these are documented in further detail below):
863
+
864
+ - `ShutdownServiceProvider` allowing CLI shutdown hooks to be registered.
865
+ - `ConfigurationServiceProvider` allowing argument value defaults to be loaded
866
+ from a configuration file or environment variables. This also provides a
867
+ key-value store service.
868
+ - `PrinterServiceProvider` allowing CLI output to stdout and stderr writable
869
+ streams.
870
+
871
+ By default the `BaseCLI` adds the following `Command` implementations (these are
872
+ documented in further detail below):
873
+
874
+ - Appropriate help commands depending on whether the CLI is configured with a
875
+ single command or multiple sub-command.
876
+ - commands provided by the `ConfigurationServiceProvider`.
877
+ - commands provided by the `PrinterServiceProvider`.
878
+ - `VersionCommand`
879
+
880
+ #### `DefaultRuntimeCLI`
881
+
882
+ `DefaultRuntimeCLI` is a simple extension to `BaseCLI` which uses NodeJS
883
+ specific APIs to access the command line arguments, stdout and stderr streams
884
+ and to exit the process.
885
+
886
+ ### `runner`
887
+
888
+ Core CLI behaviour is provided by a `runner` implementation which is responsible
889
+ for parsing arguments, determining which `Command` instances to execute and then
890
+ executing them.
891
+
892
+ The `runner` implementation supports specification of a default command which
893
+ should be executed if no command names are parsed on the command line. In this
894
+ scenario, any arguments provided will also be parsed as possible arguments for
895
+ the default command.
896
+
897
+ The logic for the `runner` is somewhat complex as it allows for the prioritised
898
+ execution of `GlobalModifierCommand` instances and the prioritised
899
+ initialisation of `ServiceProvider` instances. One reason for this is to allow
900
+ the `ConfigurationServiceProvider` to be initialised first and for the resulting
901
+ configuration to be available to other `ServiceProvider` instances which are yet
902
+ to be initialised.
903
+
904
+ The following activity diagram illustrates the `runner` logic:
905
+
906
+ ```mermaid
907
+ flowchart TD
908
+ A([start])
909
+
910
+ subgraph 1 [for each ServiceProvider in servicePriority order:]
911
+
912
+ B([scan args for provided\nGlobalModifierCommand clauses])
913
+
914
+ subgraph 2 [for each discovered clause:]
915
+ C([set default\narg values])
916
+ D([parse args])
917
+ E([add to list of\nGlobalModifierCommands\nclauses to execute])
918
+ end
919
+
920
+ F([scan default arg values for provided\nGlobalModifierCommand clauses])
921
+
922
+ subgraph 3 [for each discovered clause:]
923
+ G([parse args])
924
+ H([add to list of\nGlobalModifierCommands\nclauses to execute])
925
+ end
926
+
927
+ I([order GlobalModifierCommands\nclauses by executePriority])
928
+
929
+ subgraph 4 [for each discovered clause:]
930
+ J([execute GlobalModifierCommand])
931
+ end
932
+
933
+ K([init service provided by ServiceProvider])
934
+ end
935
+
936
+ L([scan args for non-ServiceProvider\nGlobalModifierCommand clauses])
937
+
938
+ subgraph 5 [for each discovered clause:]
939
+ M([set default\narg values])
940
+ N([parse args])
941
+ O([add to list of\nGlobalModifierCommands\nclauses to execute])
942
+ end
943
+
944
+ P([scan default arg values for non-ServiceProvider\nGlobalModifierCommand clauses])
945
+
946
+ subgraph 6 [for each discovered clause:]
947
+ Q([parse args])
948
+ R([add to list of\nGlobalModifierCommands\nclauses to execute])
949
+ end
950
+
951
+ S([order GlobalModifierCommands\nclauses by executePriority])
952
+
953
+ subgraph 7 [for each discovered clause:]
954
+ T([execute GlobalModifierCommand])
955
+ end
956
+
957
+ U([scan args for non-modifier Command clause])
958
+
959
+ V{clause found?}
960
+ V1([set default\narg values])
961
+ V2([parse args])
962
+ V3([execute\nnon-modifier Command])
963
+ W{default\nnon-modifier Command\nprovided?}
964
+ W1([scan args for\nnon-modifier Command clause])
965
+ W2{clause\nfound?}
966
+ W21([set default\narg values])
967
+ W22([parse args])
968
+ W23{valid?}
969
+ W24([execute\nnon-modifier Command])
970
+ W3([set default\narg values])
971
+ W31{valid?}
972
+ W32([execute\nnon-modifier Command])
973
+
974
+ Z([end])
975
+
976
+ C --> D
977
+ D --> E
978
+
979
+ G --> H
980
+
981
+ M --> N
982
+ N --> O
983
+
984
+ Q --> R
985
+
986
+ A --> 1
987
+ B --> 2
988
+ 2 --> F
989
+ F --> 3
990
+ 3 --> I
991
+ I --> 4
992
+ 4 --> K
993
+ 1 --> L
994
+ L --> 5
995
+ 5 --> P
996
+ P --> 6
997
+ 6 --> S
998
+ S --> 7
999
+ 7 --> U
1000
+ U --> V
1001
+ V --> |yes|V1
1002
+ V --> |no|W
1003
+ W --> |yes|W1
1004
+ W --> |no|Z
1005
+
1006
+ V1 --> V2
1007
+ V2 --> V3
1008
+ V3 --> Z
1009
+
1010
+ W1 --> W2
1011
+ W2 --> |yes|W21
1012
+ W2 --> |no|W3
1013
+
1014
+ W21 --> W22
1015
+ W22 --> W23
1016
+
1017
+ W23 --> |yes|W24
1018
+ W23 --> |no|Z
1019
+
1020
+ W24 --> Z
1021
+
1022
+ W3 --> W31
1023
+ W31 --> |yes|W32
1024
+ W31 --> |no|Z
1025
+
1026
+ W32 --> Z
1027
+ ```
1028
+
1029
+ ### `scanner`
1030
+
1031
+ The `runner` defers to a `scanner` implementation which scans arguments for
1032
+ potential `CommandClause` instances e.g. a `Command.name` followed by potential
1033
+ arguments for that command..
1034
+
1035
+ ### `parser`
1036
+
1037
+ The `runner` defers to a `parser` implementation which performs the actual
1038
+ argument parsing based on the `CommandClause` instances returned from the
1039
+ `scanner`.
1040
+
1041
+ The following parsing rules apply:
1042
+
1043
+ **Arguments Must Follow Command**
1044
+
1045
+ All arguments for a command are expected to FOLLOW the command i.e. this is
1046
+ **NOT** valid:
1047
+
1048
+ executable <sub_command_argument> <sub_command> // not valid
1049
+
1050
+ **Arbitrary Option Order**
1051
+
1052
+ The order of options for a particular command is not important i.e. these are
1053
+ equivalent:
1054
+
1055
+ executable <sub_command> --<option_1_name> <option_1_value> --<option_2_name> <option_2_value>
1056
+ executable <sub_command> --<option_2_name> <option_2_value> --<option_1_name> <option_1_value>
1057
+
1058
+ **Arbitrary Command Order**
1059
+
1060
+ The order of commands is not important i.e. these are equivalent:
1061
+
1062
+ executable <sub_command> [sub_command_arguments] --<modifier_command_1> [modifier_command_1_arguments] \
1063
+ --<modifier_command_2> [modifier_command_2_arguments]
1064
+ executable --<modifier_command_1> [modifier_command_1_arguments] <sub_command> [sub_command_arguments] \
1065
+ --<modifier_command_2> [modifier_command_2_arguments]
1066
+
1067
+ **No Command Interleaving**
1068
+
1069
+ Arguments for commands cannot be interleaved with other commands i.e. this is
1070
+ **NOT** valid:
1071
+
1072
+ executable --<modifier_command> <sub_command> [sub_command_arguments] [modifier_command_arguments] // not valid
1073
+
1074
+ **Single Command**
1075
+
1076
+ Apart from global modifier commands, there is expected to be only one command
1077
+ specified i.e. these will **NOT** work as intended:
1078
+
1079
+ // not valid - sub-command 2 and arguments will be treated as trailing arguments of sub-command 1.
1080
+ executable <sub_command_1> [sub_command_1_arguments] <sub_command_2> [sub_command_2_arguments]
1081
+
1082
+ // not valid - sub-command and arguments will be treated as trailing arguments of global command.
1083
+ executable --<global_command> <sub_command> [sub_command_arguments]
1084
+
1085
+ **Group Command**
1086
+
1087
+ A group command name must always be following immediately by a container
1088
+ sub-command name i.e. these are **NOT** valid:
1089
+
1090
+ executable <member_sub_command> <group_command> // not valid
1091
+ executable <group_command> <global_command> <member_sub_command> // not valid
1092
+
1093
+ **Unused Leading and Trailing Arguments**
1094
+
1095
+ Any leading arguments which appear BEFORE an identified command name are
1096
+ retained. Any trailing arguments which appear after an identified name which are
1097
+ not consumed when parsing the command arguments are also retained.
1098
+
1099
+ Once a command has been identified and parsed any retained arguments are
1100
+ considered unused and a warning is output.
1101
+
1102
+ If a command is NOT identified, any retained arguments are considered potential
1103
+ arguments for a default command if it has been configured. This behaviour means
1104
+ the following are equivalent:
1105
+
1106
+ executable <default_command_argument> --<modifier_command_name> <modifier_command_argument>
1107
+ executable --<modifier_command_name> <modifier_command_argument> <default_command_argument>
1108
+
1109
+ ### Command Execution
1110
+
1111
+ A `Command` is executed via the implemented function:
1112
+
1113
+ execute(argumentValues: ArgumentValues, context: Context): Promise<void>;
1114
+
1115
+ The `Context` instance allow access to the `CLIConfig` and the ability to access
1116
+ services by registered service IDs.
1117
+
1118
+ The `ArgumentValues` instance provides access to the populated and validated
1119
+ arguments for the command. These values are provided either:
1120
+
1121
+ - as a single key-value pair in the form `commandName: globalArgumentValue` for
1122
+ a `GlobalCommand` or a `GlobalModifierCommand`.
1123
+ - as a complex nested key-value structure mirroring the defined `Option` and
1124
+ `Positional` instances of a `SubCommand`
1125
+
1126
+ As an example, if a `GlobalModifierCommand` is defined as follows:
1127
+
1128
+ ```
1129
+ const globalModifierCommand: GlobalModifierCommand = {
1130
+ name: "log-level",
1131
+ argument: {
1132
+ name: "level",
1133
+ type: ArgumentValueTypeName.STRING,
1134
+ },
1135
+ executePriority: 1,
1136
+ execute: (argumentValues: ArgumentValues, context: Context) => Promise.resolve()
1137
+ };
1138
+ ```
1139
+
1140
+ and a `SubCommand` is defined as follows:
1141
+
1142
+ ```
1143
+ const subCommand: SubCommand = {
1144
+ name: "connect",
1145
+ options: [
1146
+ {
1147
+ name: "address",
1148
+ type: ComplexValueTypeName.COMPLEX,
1149
+ properties: [
1150
+ {
1151
+ name: "host",
1152
+ type: ArgumentValueTypeName.STRING
1153
+ },
1154
+ {
1155
+ name: "port",
1156
+ type: ArgumentValueTypeName.NUMBER
1157
+ }
1158
+ ]
1159
+ }
1160
+ ],
1161
+ positionals: [
1162
+ {
1163
+ name: "retryOnError",
1164
+ type: ArgumentValueTypeName.BOOLEAN
1165
+ }
1166
+ ],
1167
+ execute: (argumentValues: ArgumentValues, context: Context) => Promise.resolve()
1168
+ };
1169
+ ```
1170
+
1171
+ when the following command line arguments are specified:
1172
+
1173
+ `myNetworkApp --connect --address.host=127.0.0.1 --address.port=8080 true --log-level=DEBUG`
1174
+
1175
+ then the `ArgumentValues` passed to the `globalModifierCommand.execute(...)`
1176
+ function would be:
1177
+
1178
+ ```
1179
+ {
1180
+ "log-level": "DEBUG"
1181
+ }
1182
+ ```
1183
+
1184
+ and the `ArgumentValues` passed to the `subCommand.execute(...)` function would
1185
+ be:
1186
+
1187
+ ```
1188
+ {
1189
+ address: {
1190
+ host: "127.0.0.1",
1191
+ port: 8080
1192
+ },
1193
+ retryOnError: true
1194
+ }
1195
+ ```
1196
+
1197
+ ### Core Service Providers
1198
+
1199
+ The core `ServiceProvider` implementations (and the service and `Command`
1200
+ implementations they provide) built into the framework are:
1201
+
1202
+ #### `BannerServiceProvider`
1203
+
1204
+ On initialisation this uses the `PrinterService` to output the CLI name in ASCII
1205
+ banner text together with the CLI description and version.
1206
+
1207
+ Provides:
1208
+
1209
+ - `NoBannerCommand` allowing banner printing to be disabled via the argument
1210
+ `--no-banner` or the env var `NO_BANNER`.
1211
+
1212
+ #### `ConfigurationServiceProvider`
1213
+
1214
+ Provides:
1215
+
1216
+ - `KeyValueService` allowing the storage and retrieval of key value pairs scoped
1217
+ to the current `Command` or service being executed. The values are persisted
1218
+ to the CLI configuration file.
1219
+ - `ConfigCommand` allowing the default location of the configuration file to be
1220
+ overridden via the argument `--config` or the env var `CONFIG_LOCATION`.
1221
+ - `DumpConfigCommand` a global command which dumps the full CLI configuration to
1222
+ stdout via `--dump-config`.
1223
+
1224
+ #### `ShutdownServiceProvider`
1225
+
1226
+ Provides:
1227
+
1228
+ - `ShutdownService` allowing registration of callbacks for CLI shutdown.
1229
+
1230
+ #### `PrinterServiceProvider`
1231
+
1232
+ Provides:
1233
+
1234
+ - `DefaultPrinterService` allowing color output to stdout, stderr, management of
1235
+ log levels and widgets such as a spinner and progress bars.
1236
+ - `DarkModeCommand` which allows dark or light mode to be enabled via the
1237
+ argument `--dark-mode` or the env var `DARK_MODE`.
1238
+ - `NoColorCommand` which allows color output to be disabled via the argument
1239
+ `--no-color` or the env var `NO_COLOR`.
1240
+ - `LogLevelCommand` which allows the log level to be set via the argument
1241
+ `--log-level` or the env var `LOG_LEVEL`.
1242
+
1243
+ #### `SyntaxHighlighterServiceProvider`
1244
+
1245
+ Provides:
1246
+
1247
+ - `SyntaxHighlighterService` allowing ANSI based color highlighting of
1248
+ structured data and source code. JSON highlighting is provided by default and
1249
+ other data or language formats can be added on demand by commands.
1250
+
1251
+ Note that the `SyntaxHighlighterService` has no effect if the
1252
+ `DefaultPrinterService` is configured to disable color output.
1253
+
1254
+ #### `AsciiBannerGeneratorServiceProvider`
1255
+
1256
+ Provides:
1257
+
1258
+ - `AsciiBannerGeneratorService` allowing messages to be rendered using ASCII
1259
+ banner [FIGlet](http://www.figlet.org) fonts. The FIGlet "standard" font is
1260
+ provided by default and other fonts can be added on demand by commands.
1261
+
1262
+ ### Core Commands
1263
+
1264
+ The core `Command` implementations provided with the framework are:
1265
+
1266
+ #### `MultiCommandCliHelpGlobalCommand`
1267
+
1268
+ Implementation of multi-command CLI help. Some examples:
1269
+
1270
+ - `myCli --help`
1271
+ - `myCli -h`
1272
+ - `myCli --help <command>`
1273
+ - `myCli -h <command>`
1274
+
1275
+ #### `MultiCommandCliHelpSubCommand`
1276
+
1277
+ Implementation of multi-command CLI help. Some examples:
1278
+
1279
+ - `myCli help`
1280
+ - `myCli help <command>`
1281
+
1282
+ #### `SingleCommandCliHelpGlobalCommand`
1283
+
1284
+ Implementation of single (default) command CLI help. Some examples:
1285
+
1286
+ - `myCli --help`
1287
+ - `myCli -h`
1288
+
1289
+ #### `SingleCommandCliHelpSubCommand`
1290
+
1291
+ Implementation of single (default) command CLI help. An example:
1292
+
1293
+ - `myCli help`
1294
+
1295
+ #### `UsageCommand`
1296
+
1297
+ Implementation which prints basic CLI usage instructions.
1298
+
1299
+ #### `VersionCommand`
1300
+
1301
+ Implementation which prints the version of the CLI.
1302
+
1303
+ ## API
1304
+
1305
+ API docs for the library:
1306
+
1307
+ [API Documentation](https://jsr.io/@flowscripter/dynamic-cli-framework/doc)
1308
+
1309
+ ## Development
1310
+
1311
+ Test:
1312
+
1313
+ `bun test`
1314
+
1315
+ **NOTE**: The following tasks use Deno as it excels at these and Bun does not
1316
+ currently provide such functionality:
1317
+
1318
+ Format:
1319
+
1320
+ `deno fmt`
1321
+
1322
+ Lint:
1323
+
1324
+ `deno lint index.ts src/ tests/`
1325
+
1326
+ Generate HTML API Documentation:
1327
+
1328
+ `deno doc --html --name=template-bun-library index.ts`
1329
+
1330
+ The following diagram provides an overview of the main internal modules and
1331
+ classes:
1332
+
1333
+ ```mermaid
1334
+ classDiagram
1335
+
1336
+ class parser {
1337
+ }
1338
+
1339
+ class scanner {
1340
+ }
1341
+
1342
+ class Context {
1343
+ <<interface>>
1344
+ }
1345
+
1346
+ class CLI {
1347
+ <<interface>>
1348
+ }
1349
+
1350
+ class runner {
1351
+ }
1352
+
1353
+ class BaseCLI {
1354
+ }
1355
+
1356
+ class Command {
1357
+ <<interface>>
1358
+ }
1359
+
1360
+ class DefaultCommandRegistry {
1361
+ }
1362
+
1363
+ class launcher {
1364
+ }
1365
+
1366
+ class DefaultServiceProviderRegistry {
1367
+ }
1368
+
1369
+ class ServiceProvider {
1370
+ <<interface>>
1371
+ }
1372
+
1373
+ class DefaultContext {
1374
+ }
1375
+
1376
+ class CommandRegistry {
1377
+ <<interface>>
1378
+ }
1379
+
1380
+ class ServiceProviderRegistry {
1381
+ <<interface>>
1382
+ }
1383
+
1384
+ class DefaultRuntimeCLI {
1385
+ }
1386
+
1387
+ class CLIConfig {
1388
+ }
1389
+
1390
+ class ServiceXYZ {
1391
+ }
1392
+
1393
+ runner --> scanner
1394
+
1395
+ runner --> parser
1396
+
1397
+ CLI <|.. BaseCLI
1398
+
1399
+ BaseCLI <|-- DefaultRuntimeCLI
1400
+
1401
+ runner --> Context
1402
+
1403
+ runner --> CommandRegistry
1404
+
1405
+ runner --> ServiceProviderRegistry
1406
+
1407
+ ServiceProviderRegistry <|.. DefaultServiceProviderRegistry
1408
+
1409
+ ServiceProviderRegistry --> "0..*" ServiceProvider : registers
1410
+
1411
+ BaseCLI --> DefaultCommandRegistry
1412
+
1413
+ CommandRegistry <|.. DefaultCommandRegistry
1414
+
1415
+ CommandRegistry --> "0..*" Command : registers
1416
+
1417
+ runner --> "0..1" Command : defaultCommand
1418
+
1419
+ Context <|.. DefaultContext
1420
+
1421
+ BaseCLI --> DefaultContext
1422
+
1423
+ BaseCLI --> DefaultServiceProviderRegistry
1424
+
1425
+ Context --> CLIConfig
1426
+
1427
+ BaseCLI --> CLIConfig
1428
+
1429
+ Context --> ServiceProviderRegistry
1430
+
1431
+ ServiceProvider --> ServiceXYZ : provides
1432
+
1433
+ Context --> ServiceXYZ : access to
1434
+
1435
+ DefaultRuntimeCLI <-- launcher
1436
+ ```
1437
+
1438
+ ### Debug Logging
1439
+
1440
+ Internal framework logging can be enabled by setting the `CLI_DEBUG` environment
1441
+ variable.
1442
+
1443
+ The logging implementation will look for an object conforming to the `Logger`
1444
+ interface and use it if found. If not found, a simple logging implementation
1445
+ using the `console` object will be used.
1446
+
1447
+ ### Command and Service Validation
1448
+
1449
+ By default, commands and services that are built into the CLI or provided by
1450
+ already installed plugins are not validated as they are loaded. The only
1451
+ validation that takes place is for commands or services provided by plugins
1452
+ BEFORE they are installed.
1453
+
1454
+ When using `launcher.ts` runtime validation of all commands and services can be
1455
+ forced by defining the `CLI_VALIDATE_ALL` environment variable.
1456
+
1457
+ Command validation includes:
1458
+
1459
+ - ensuring multiple commands in the CLI do not have duplicate names or short
1460
+ aliases.
1461
+ - command options for each command do not include duplicate names or short
1462
+ aliases.
1463
+ - default values for options have the type specified by the option.
1464
+ - default values for options match an allowable value if specified by the
1465
+ option.
1466
+ - default array values for options are specified only for array options.
1467
+ - command options for each command do not include duplicate names or short
1468
+ aliases.
1469
+ - only the last positional for a command is defined as a vararg.
1470
+ - default values for complex options match the nested property hierarchy.
1471
+ - paths to nested properties of complex options are unique.
1472
+
1473
+ ## License
1474
+
1475
+ MIT © Flowscripter