@wooksjs/event-cli 0.4.9 → 0.4.10

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 (3) hide show
  1. package/dist/index.cjs +409 -402
  2. package/dist/index.mjs +409 -402
  3. package/package.json +6 -3
package/dist/index.mjs CHANGED
@@ -3,19 +3,19 @@ import { WooksAdapterBase } from 'wooks';
3
3
  import { CliHelpRenderer } from '@prostojs/cli-help';
4
4
  import minimist from 'minimist';
5
5
 
6
- function createCliContext(data, options) {
7
- return createEventContext({
8
- event: Object.assign(Object.assign({}, data), { type: 'CLI' }),
9
- options,
10
- });
11
- }
12
- /**
13
- * Wrapper on top of useEventContext that provides
14
- * proper context types for CLI event
15
- * @returns set of hooks { getCtx, restoreCtx, clearCtx, hookStore, getStore, setStore }
16
- */
17
- function useCliContext() {
18
- return useEventContext('CLI');
6
+ function createCliContext(data, options) {
7
+ return createEventContext({
8
+ event: Object.assign(Object.assign({}, data), { type: 'CLI' }),
9
+ options,
10
+ });
11
+ }
12
+ /**
13
+ * Wrapper on top of useEventContext that provides
14
+ * proper context types for CLI event
15
+ * @returns set of hooks { getCtx, restoreCtx, clearCtx, hookStore, getStore, setStore }
16
+ */
17
+ function useCliContext() {
18
+ return useEventContext('CLI');
19
19
  }
20
20
 
21
21
  /******************************************************************************
@@ -32,6 +32,8 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
32
32
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
33
33
  PERFORMANCE OF THIS SOFTWARE.
34
34
  ***************************************************************************** */
35
+ /* global Reflect, Promise, SuppressedError, Symbol */
36
+
35
37
 
36
38
  function __awaiter(thisArg, _arguments, P, generator) {
37
39
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
@@ -41,400 +43,405 @@ function __awaiter(thisArg, _arguments, P, generator) {
41
43
  function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
42
44
  step((generator = generator.apply(thisArg, _arguments || [])).next());
43
45
  });
44
- }
45
-
46
- const cliShortcuts = {
47
- cli: 'CLI',
48
- };
49
- class WooksCli extends WooksAdapterBase {
50
- constructor(opts, wooks) {
51
- super(wooks, opts === null || opts === void 0 ? void 0 : opts.logger, opts === null || opts === void 0 ? void 0 : opts.router);
52
- this.opts = opts;
53
- this.alreadyComputedAliases = false;
54
- this.logger = (opts === null || opts === void 0 ? void 0 : opts.logger) || this.getLogger('wooks-cli');
55
- this.cliHelp =
56
- (opts === null || opts === void 0 ? void 0 : opts.cliHelp) instanceof CliHelpRenderer
57
- ? opts.cliHelp
58
- : new CliHelpRenderer(opts === null || opts === void 0 ? void 0 : opts.cliHelp);
59
- }
60
- /**
61
- * ### Register CLI Command
62
- * Command path segments may be separated by / or space.
63
- *
64
- * For example the folowing path are interpreted the same:
65
- * - "command test use:dev :name"
66
- * - "command/test/use:dev/:name"
67
- *
68
- * Where name will become an argument
69
- *
70
- * ```js
71
- * // example without options
72
- * app.cli('command/:arg', () => 'arg = ' + useRouteParams().params.arg )
73
- *
74
- * // example with options
75
- * app.cli('command/:arg', {
76
- * description: 'Description of the command',
77
- * options: [{ keys: ['project', 'p'], description: 'Description of the option', value: 'myProject' }],
78
- * args: { arg: 'Description of the arg' },
79
- * aliases: ['cmd'], // alias "cmd/:arg" will be registered
80
- * examples: [{
81
- * description: 'Example of usage with someProject',
82
- * cmd: 'argValue -p=someProject',
83
- * // will result in help display:
84
- * // "# Example of usage with someProject\n" +
85
- * // "$ myCli command argValue -p=someProject\n"
86
- * }],
87
- * handler: () => 'arg = ' + useRouteParams().params.arg
88
- * })
89
- * ```
90
- *
91
- * @param path command path
92
- * @param _options handler or options
93
- *
94
- * @returns
95
- */
96
- cli(path, _options) {
97
- var _a;
98
- const options = typeof _options === 'function' ? { handler: _options } : _options;
99
- const handler = typeof _options === 'function' ? _options : _options.handler;
100
- const makePath = (s) => '/' + s.replace(/\s+/g, '/');
101
- // register handler
102
- const targetPath = makePath(path);
103
- const routed = this.on('CLI', targetPath, handler);
104
- if (options.onRegister) {
105
- options.onRegister(targetPath, 0, routed);
106
- }
107
- // register direct aliases
108
- for (const alias of options.aliases || []) {
109
- const vars = routed.getArgs().map((k) => ':' + k).join('/');
110
- const targetPath = makePath(alias) + (vars ? '/' + vars : '');
111
- this.on('CLI', targetPath, handler);
112
- if (options.onRegister) {
113
- options.onRegister(targetPath, 1, routed);
114
- }
115
- }
116
- // register helpCli entry
117
- const command = routed.getStaticPart().replace(/\//g, ' ').trim();
118
- const args = Object.assign({}, (options.args || {}));
119
- for (const arg of routed.getArgs()) {
120
- if (!args[arg]) {
121
- args[arg] = '';
122
- }
123
- }
124
- this.cliHelp.addEntry({
125
- command,
126
- aliases: (_a = options.aliases) === null || _a === void 0 ? void 0 : _a.map(alias => alias.replace(/\\:/g, ':')),
127
- args,
128
- description: options.description,
129
- examples: options.examples,
130
- options: options.options,
131
- custom: { handler: options.handler, cb: options.onRegister },
132
- });
133
- return routed;
134
- }
135
- computeAliases() {
136
- if (!this.alreadyComputedAliases) {
137
- this.alreadyComputedAliases = true;
138
- const aliases = this.cliHelp.getComputedAliases();
139
- for (const [alias, entry] of Object.entries(aliases)) {
140
- if (entry.custom) {
141
- const vars = Object.keys(entry.args || {})
142
- .map((k) => ':' + k)
143
- .join('/');
144
- const path = '/' +
145
- alias.replace(/\s+/g, '/').replace(/:/g, '\\:') +
146
- (vars ? '/' + vars : '');
147
- this.on('CLI', path, entry.custom.handler);
148
- if (entry.custom.cb) {
149
- entry.custom.cb(path, 3);
150
- }
151
- }
152
- }
153
- }
154
- }
155
- /**
156
- * ## run
157
- * ### Start command processing
158
- * Triggers command processing
159
- *
160
- * By default takes `process.argv.slice(2)` as a command
161
- *
162
- * It's possible to replace the command by passing an argument
163
- *
164
- * @param _argv optionally overwrite `process.argv.slice(2)` with your `argv` array
165
- */
166
- run(_argv, _opts) {
167
- var _a, _b;
168
- return __awaiter(this, void 0, void 0, function* () {
169
- const argv = _argv || process.argv.slice(2);
170
- const parsedFlags = minimist(argv, _opts);
171
- const pathParams = parsedFlags._;
172
- const path = '/' +
173
- pathParams.map((v) => encodeURI(v).replace(/\//g, '%2F')).join('/');
174
- const { restoreCtx, clearCtx, store } = createCliContext({ opts: _opts, argv, pathParams, cliHelp: this.cliHelp, command: path.replace(/\//g, ' ').trim() }, this.mergeEventOptions((_a = this.opts) === null || _a === void 0 ? void 0 : _a.eventOptions));
175
- store('flags').value = parsedFlags;
176
- this.computeAliases();
177
- const { handlers: foundHandlers, firstStatic } = this.wooks.lookup('CLI', path);
178
- if (typeof firstStatic === 'string') {
179
- // overwriting command with firstStatic to properly search for help
180
- store('event').set('command', firstStatic.replace(/\//g, ' ').trim());
181
- }
182
- const handlers = foundHandlers ||
183
- (((_b = this.opts) === null || _b === void 0 ? void 0 : _b.onNotFound) && [this.opts.onNotFound]) ||
184
- null;
185
- if (handlers) {
186
- try {
187
- for (const handler of handlers) {
188
- restoreCtx();
189
- const response = yield handler();
190
- if (typeof response === 'string') {
191
- console.log(response);
192
- }
193
- else if (Array.isArray(response)) {
194
- response.forEach((r) => console.log(typeof r === 'string'
195
- ? r
196
- : JSON.stringify(r, null, ' ')));
197
- }
198
- else if (response instanceof Error) {
199
- this.onError(response);
200
- }
201
- else if (response) {
202
- if (response) {
203
- console.log(JSON.stringify(response, null, ' '));
204
- }
205
- }
206
- }
207
- }
208
- catch (e) {
209
- this.onError(e);
210
- }
211
- clearCtx();
212
- }
213
- else {
214
- this.onUnknownCommand(pathParams);
215
- clearCtx();
216
- }
217
- });
218
- }
219
- onError(e) {
220
- var _a;
221
- if ((_a = this.opts) === null || _a === void 0 ? void 0 : _a.onError) {
222
- this.opts.onError(e);
223
- }
224
- else {
225
- this.error(e.message);
226
- process.exit(1);
227
- }
228
- }
229
- /**
230
- * Triggers `unknown command` processing and callbacks
231
- * @param pathParams `string[]` containing command
232
- */
233
- onUnknownCommand(pathParams) {
234
- var _a;
235
- const raiseError = () => {
236
- this.error('' + 'Unknown command: ' + pathParams.join(' '));
237
- process.exit(1);
238
- };
239
- if ((_a = this.opts) === null || _a === void 0 ? void 0 : _a.onUnknownCommand) {
240
- this.opts.onUnknownCommand(pathParams, raiseError);
241
- }
242
- else {
243
- raiseError();
244
- }
245
- }
246
- error(e) {
247
- if (typeof e === 'string') {
248
- console.error('' + 'ERROR: ' + '' + e);
249
- }
250
- else {
251
- console.error('' + 'ERROR: ' + '' + e.message);
252
- }
253
- }
254
46
  }
255
- /**
256
- * Factory for WooksCli App
257
- * @param opts TWooksCliOptions
258
- * @param wooks Wooks | WooksAdapterBase
259
- * @returns WooksCli
260
- */
261
- function createCliApp(opts, wooks) {
262
- return new WooksCli(opts, wooks);
47
+
48
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
49
+ var e = new Error(message);
50
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
51
+ };
52
+
53
+ const cliShortcuts = {
54
+ cli: 'CLI',
55
+ };
56
+ class WooksCli extends WooksAdapterBase {
57
+ constructor(opts, wooks) {
58
+ super(wooks, opts === null || opts === void 0 ? void 0 : opts.logger, opts === null || opts === void 0 ? void 0 : opts.router);
59
+ this.opts = opts;
60
+ this.alreadyComputedAliases = false;
61
+ this.logger = (opts === null || opts === void 0 ? void 0 : opts.logger) || this.getLogger('wooks-cli');
62
+ this.cliHelp =
63
+ (opts === null || opts === void 0 ? void 0 : opts.cliHelp) instanceof CliHelpRenderer
64
+ ? opts.cliHelp
65
+ : new CliHelpRenderer(opts === null || opts === void 0 ? void 0 : opts.cliHelp);
66
+ }
67
+ /**
68
+ * ### Register CLI Command
69
+ * Command path segments may be separated by / or space.
70
+ *
71
+ * For example the folowing path are interpreted the same:
72
+ * - "command test use:dev :name"
73
+ * - "command/test/use:dev/:name"
74
+ *
75
+ * Where name will become an argument
76
+ *
77
+ * ```js
78
+ * // example without options
79
+ * app.cli('command/:arg', () => 'arg = ' + useRouteParams().params.arg )
80
+ *
81
+ * // example with options
82
+ * app.cli('command/:arg', {
83
+ * description: 'Description of the command',
84
+ * options: [{ keys: ['project', 'p'], description: 'Description of the option', value: 'myProject' }],
85
+ * args: { arg: 'Description of the arg' },
86
+ * aliases: ['cmd'], // alias "cmd/:arg" will be registered
87
+ * examples: [{
88
+ * description: 'Example of usage with someProject',
89
+ * cmd: 'argValue -p=someProject',
90
+ * // will result in help display:
91
+ * // "# Example of usage with someProject\n" +
92
+ * // "$ myCli command argValue -p=someProject\n"
93
+ * }],
94
+ * handler: () => 'arg = ' + useRouteParams().params.arg
95
+ * })
96
+ * ```
97
+ *
98
+ * @param path command path
99
+ * @param _options handler or options
100
+ *
101
+ * @returns
102
+ */
103
+ cli(path, _options) {
104
+ var _a;
105
+ const options = typeof _options === 'function' ? { handler: _options } : _options;
106
+ const handler = typeof _options === 'function' ? _options : _options.handler;
107
+ const makePath = (s) => '/' + s.replace(/\s+/g, '/');
108
+ // register handler
109
+ const targetPath = makePath(path);
110
+ const routed = this.on('CLI', targetPath, handler);
111
+ if (options.onRegister) {
112
+ options.onRegister(targetPath, 0, routed);
113
+ }
114
+ // register direct aliases
115
+ for (const alias of options.aliases || []) {
116
+ const vars = routed.getArgs().map((k) => ':' + k).join('/');
117
+ const targetPath = makePath(alias) + (vars ? '/' + vars : '');
118
+ this.on('CLI', targetPath, handler);
119
+ if (options.onRegister) {
120
+ options.onRegister(targetPath, 1, routed);
121
+ }
122
+ }
123
+ // register helpCli entry
124
+ const command = routed.getStaticPart().replace(/\//g, ' ').trim();
125
+ const args = Object.assign({}, (options.args || {}));
126
+ for (const arg of routed.getArgs()) {
127
+ if (!args[arg]) {
128
+ args[arg] = '';
129
+ }
130
+ }
131
+ this.cliHelp.addEntry({
132
+ command,
133
+ aliases: (_a = options.aliases) === null || _a === void 0 ? void 0 : _a.map(alias => alias.replace(/\\:/g, ':')), // unescape ":" character
134
+ args,
135
+ description: options.description,
136
+ examples: options.examples,
137
+ options: options.options,
138
+ custom: { handler: options.handler, cb: options.onRegister },
139
+ });
140
+ return routed;
141
+ }
142
+ computeAliases() {
143
+ if (!this.alreadyComputedAliases) {
144
+ this.alreadyComputedAliases = true;
145
+ const aliases = this.cliHelp.getComputedAliases();
146
+ for (const [alias, entry] of Object.entries(aliases)) {
147
+ if (entry.custom) {
148
+ const vars = Object.keys(entry.args || {})
149
+ .map((k) => ':' + k)
150
+ .join('/');
151
+ const path = '/' +
152
+ alias.replace(/\s+/g, '/').replace(/:/g, '\\:') +
153
+ (vars ? '/' + vars : '');
154
+ this.on('CLI', path, entry.custom.handler);
155
+ if (entry.custom.cb) {
156
+ entry.custom.cb(path, 3);
157
+ }
158
+ }
159
+ }
160
+ }
161
+ }
162
+ /**
163
+ * ## run
164
+ * ### Start command processing
165
+ * Triggers command processing
166
+ *
167
+ * By default takes `process.argv.slice(2)` as a command
168
+ *
169
+ * It's possible to replace the command by passing an argument
170
+ *
171
+ * @param _argv optionally overwrite `process.argv.slice(2)` with your `argv` array
172
+ */
173
+ run(_argv, _opts) {
174
+ var _a, _b;
175
+ return __awaiter(this, void 0, void 0, function* () {
176
+ const argv = _argv || process.argv.slice(2);
177
+ const parsedFlags = minimist(argv, _opts);
178
+ const pathParams = parsedFlags._;
179
+ const path = '/' +
180
+ pathParams.map((v) => encodeURI(v).replace(/\//g, '%2F')).join('/');
181
+ const { restoreCtx, clearCtx, store } = createCliContext({ opts: _opts, argv, pathParams, cliHelp: this.cliHelp, command: path.replace(/\//g, ' ').trim() }, this.mergeEventOptions((_a = this.opts) === null || _a === void 0 ? void 0 : _a.eventOptions));
182
+ store('flags').value = parsedFlags;
183
+ this.computeAliases();
184
+ const { handlers: foundHandlers, firstStatic } = this.wooks.lookup('CLI', path);
185
+ if (typeof firstStatic === 'string') {
186
+ // overwriting command with firstStatic to properly search for help
187
+ store('event').set('command', firstStatic.replace(/\//g, ' ').trim());
188
+ }
189
+ const handlers = foundHandlers ||
190
+ (((_b = this.opts) === null || _b === void 0 ? void 0 : _b.onNotFound) && [this.opts.onNotFound]) ||
191
+ null;
192
+ if (handlers) {
193
+ try {
194
+ for (const handler of handlers) {
195
+ restoreCtx();
196
+ const response = yield handler();
197
+ if (typeof response === 'string') {
198
+ console.log(response);
199
+ }
200
+ else if (Array.isArray(response)) {
201
+ response.forEach((r) => console.log(typeof r === 'string'
202
+ ? r
203
+ : JSON.stringify(r, null, ' ')));
204
+ }
205
+ else if (response instanceof Error) {
206
+ this.onError(response);
207
+ }
208
+ else if (response) {
209
+ if (response) {
210
+ console.log(JSON.stringify(response, null, ' '));
211
+ }
212
+ }
213
+ }
214
+ }
215
+ catch (e) {
216
+ this.onError(e);
217
+ }
218
+ clearCtx();
219
+ }
220
+ else {
221
+ this.onUnknownCommand(pathParams);
222
+ clearCtx();
223
+ }
224
+ });
225
+ }
226
+ onError(e) {
227
+ var _a;
228
+ if ((_a = this.opts) === null || _a === void 0 ? void 0 : _a.onError) {
229
+ this.opts.onError(e);
230
+ }
231
+ else {
232
+ this.error(e.message);
233
+ process.exit(1);
234
+ }
235
+ }
236
+ /**
237
+ * Triggers `unknown command` processing and callbacks
238
+ * @param pathParams `string[]` containing command
239
+ */
240
+ onUnknownCommand(pathParams) {
241
+ var _a;
242
+ const raiseError = () => {
243
+ this.error('' + 'Unknown command: ' + pathParams.join(' '));
244
+ process.exit(1);
245
+ };
246
+ if ((_a = this.opts) === null || _a === void 0 ? void 0 : _a.onUnknownCommand) {
247
+ this.opts.onUnknownCommand(pathParams, raiseError);
248
+ }
249
+ else {
250
+ raiseError();
251
+ }
252
+ }
253
+ error(e) {
254
+ if (typeof e === 'string') {
255
+ console.error('' + 'ERROR: ' + '' + e);
256
+ }
257
+ else {
258
+ console.error('' + 'ERROR: ' + '' + e.message);
259
+ }
260
+ }
261
+ }
262
+ /**
263
+ * Factory for WooksCli App
264
+ * @param opts TWooksCliOptions
265
+ * @param wooks Wooks | WooksAdapterBase
266
+ * @returns WooksCli
267
+ */
268
+ function createCliApp(opts, wooks) {
269
+ return new WooksCli(opts, wooks);
263
270
  }
264
271
 
265
- /**
266
- * ## useCliHelp
267
- * ### Composable
268
- * ```js
269
- * // example of printing cli instructions
270
- * const { print } = useCliHelp()
271
- * // print with colors
272
- * print(true)
273
- * // print with no colors
274
- * // print(false)
275
- * ```
276
- * @returns
277
- */
278
- function useCliHelp() {
279
- const event = useCliContext().store('event');
280
- const getCliHelp = () => event.get('cliHelp');
281
- const getEntry = () => { var _a; return (_a = getCliHelp().match(event.get('command'))) === null || _a === void 0 ? void 0 : _a.main; };
282
- return {
283
- getCliHelp,
284
- getEntry,
285
- render: (width, withColors) => getCliHelp().render(event.get('command'), width, withColors),
286
- print: (withColors) => getCliHelp().print(event.get('command'), withColors),
287
- };
288
- }
289
- /**
290
- * ## useAutoHelp
291
- * ### Composable
292
- *
293
- * Prints help if `--help` option provided.
294
- *
295
- * ```js
296
- * // example of use: print help and exit
297
- * app.cli('test', () => {
298
- * useAutoHelp() && process.exit(0)
299
- * return 'hit test command'
300
- * })
301
- *
302
- * // add option -h to print help, no colors
303
- * app.cli('test/nocolors', () => {
304
- * useAutoHelp(['help', 'h'], false) && process.exit(0)
305
- * return 'hit test nocolors command'
306
- * })
307
- * ```
308
- * @param keys default `['help']` - list of options to trigger help render
309
- * @param colors default `true`, prints with colors when true
310
- * @returns true when --help was provided. Otherwise returns false
311
- */
312
- function useAutoHelp(keys = ['help'], colors = true) {
313
- for (const option of keys) {
314
- if (useCliOption(option) === true) {
315
- // try {
316
- useCliHelp().print(colors);
317
- return true;
318
- // } catch (e) {
319
- // throw new
320
- // }
321
- }
322
- }
323
- }
324
- /**
325
- * ##useCommandLookupHelp
326
- * ### Composable
327
- *
328
- * Tries to find valid command based on provided command.
329
- *
330
- * If manages to find a valid command, throws an error
331
- * suggesting a list of valid commands
332
- *
333
- * Best to use in `onUnknownCommand` callback:
334
- *
335
- * ```js
336
- * const app = createCliApp({
337
- * onUnknownCommand: (path, raiseError) => {
338
- * // will throw an error suggesting a list
339
- * // of valid commands if could find some
340
- * useCommandLookupHelp()
341
- * // fallback to a regular error handler
342
- * raiseError()
343
- * },
344
- * })
345
- * ```
346
- *
347
- * @param lookupDepth depth of search in backwards
348
- * @example
349
- *
350
- * For provided command `run test:drive dir`
351
- * - lookup1: `run test:drive dir` (deep = 0)
352
- * - lookup2: `run test:drive` (deep = 1)
353
- * - lookup3: `run test` (deep = 2)
354
- * - lookup4: `run` (deep = 3)
355
- * ...
356
- */
357
- function useCommandLookupHelp(lookupDepth = 3) {
358
- const parts = useCliContext()
359
- .store('event')
360
- .get('pathParams')
361
- .map((p) => (p + ' ').split(':').map((s, i) => (i ? ':' + s : s)))
362
- .flat();
363
- const cliHelp = useCliHelp().getCliHelp();
364
- const cmd = cliHelp.getCliName();
365
- let data;
366
- for (let i = 0; i < Math.min(parts.length, lookupDepth + 1); i++) {
367
- const pathParams = parts
368
- .slice(0, i ? -i : parts.length)
369
- .join('')
370
- .trim();
371
- try {
372
- data = cliHelp.match(pathParams);
373
- break;
374
- }
375
- catch (e) {
376
- const variants = cliHelp.lookup(pathParams);
377
- if (variants.length) {
378
- throw new Error(`Wrong command, did you mean:\n${variants
379
- .slice(0, 7)
380
- .map((c) => ` $ ${cmd} ${c.main.command}`)
381
- .join('\n')}`);
382
- }
383
- }
384
- }
385
- if (data) {
386
- const { main, children } = data;
387
- if (main.args && Object.keys(main.args).length) {
388
- throw new Error(`Arguments expected: ${Object.keys(main.args)
389
- .map((l) => `<${l}>`)
390
- .join(', ')}`);
391
- }
392
- else if (children && children.length) {
393
- throw new Error(`Wrong command, did you mean:\n${children
394
- .slice(0, 7)
395
- .map((c) => ` $ ${cmd} ${c.command}`)
396
- .join('\n')}`);
397
- }
398
- }
272
+ /**
273
+ * ## useCliHelp
274
+ * ### Composable
275
+ * ```js
276
+ * // example of printing cli instructions
277
+ * const { print } = useCliHelp()
278
+ * // print with colors
279
+ * print(true)
280
+ * // print with no colors
281
+ * // print(false)
282
+ * ```
283
+ * @returns
284
+ */
285
+ function useCliHelp() {
286
+ const event = useCliContext().store('event');
287
+ const getCliHelp = () => event.get('cliHelp');
288
+ const getEntry = () => { var _a; return (_a = getCliHelp().match(event.get('command'))) === null || _a === void 0 ? void 0 : _a.main; };
289
+ return {
290
+ getCliHelp,
291
+ getEntry,
292
+ render: (width, withColors) => getCliHelp().render(event.get('command'), width, withColors),
293
+ print: (withColors) => getCliHelp().print(event.get('command'), withColors),
294
+ };
295
+ }
296
+ /**
297
+ * ## useAutoHelp
298
+ * ### Composable
299
+ *
300
+ * Prints help if `--help` option provided.
301
+ *
302
+ * ```js
303
+ * // example of use: print help and exit
304
+ * app.cli('test', () => {
305
+ * useAutoHelp() && process.exit(0)
306
+ * return 'hit test command'
307
+ * })
308
+ *
309
+ * // add option -h to print help, no colors
310
+ * app.cli('test/nocolors', () => {
311
+ * useAutoHelp(['help', 'h'], false) && process.exit(0)
312
+ * return 'hit test nocolors command'
313
+ * })
314
+ * ```
315
+ * @param keys default `['help']` - list of options to trigger help render
316
+ * @param colors default `true`, prints with colors when true
317
+ * @returns true when --help was provided. Otherwise returns false
318
+ */
319
+ function useAutoHelp(keys = ['help'], colors = true) {
320
+ for (const option of keys) {
321
+ if (useCliOption(option) === true) {
322
+ // try {
323
+ useCliHelp().print(colors);
324
+ return true;
325
+ // } catch (e) {
326
+ // throw new
327
+ // }
328
+ }
329
+ }
330
+ }
331
+ /**
332
+ * ##useCommandLookupHelp
333
+ * ### Composable
334
+ *
335
+ * Tries to find valid command based on provided command.
336
+ *
337
+ * If manages to find a valid command, throws an error
338
+ * suggesting a list of valid commands
339
+ *
340
+ * Best to use in `onUnknownCommand` callback:
341
+ *
342
+ * ```js
343
+ * const app = createCliApp({
344
+ * onUnknownCommand: (path, raiseError) => {
345
+ * // will throw an error suggesting a list
346
+ * // of valid commands if could find some
347
+ * useCommandLookupHelp()
348
+ * // fallback to a regular error handler
349
+ * raiseError()
350
+ * },
351
+ * })
352
+ * ```
353
+ *
354
+ * @param lookupDepth depth of search in backwards
355
+ * @example
356
+ *
357
+ * For provided command `run test:drive dir`
358
+ * - lookup1: `run test:drive dir` (deep = 0)
359
+ * - lookup2: `run test:drive` (deep = 1)
360
+ * - lookup3: `run test` (deep = 2)
361
+ * - lookup4: `run` (deep = 3)
362
+ * ...
363
+ */
364
+ function useCommandLookupHelp(lookupDepth = 3) {
365
+ const parts = useCliContext()
366
+ .store('event')
367
+ .get('pathParams')
368
+ .map((p) => (p + ' ').split(':').map((s, i) => (i ? ':' + s : s)))
369
+ .flat();
370
+ const cliHelp = useCliHelp().getCliHelp();
371
+ const cmd = cliHelp.getCliName();
372
+ let data;
373
+ for (let i = 0; i < Math.min(parts.length, lookupDepth + 1); i++) {
374
+ const pathParams = parts
375
+ .slice(0, i ? -i : parts.length)
376
+ .join('')
377
+ .trim();
378
+ try {
379
+ data = cliHelp.match(pathParams);
380
+ break;
381
+ }
382
+ catch (e) {
383
+ const variants = cliHelp.lookup(pathParams);
384
+ if (variants.length) {
385
+ throw new Error(`Wrong command, did you mean:\n${variants
386
+ .slice(0, 7)
387
+ .map((c) => ` $ ${cmd} ${c.main.command}`)
388
+ .join('\n')}`);
389
+ }
390
+ }
391
+ }
392
+ if (data) {
393
+ const { main, children } = data;
394
+ if (main.args && Object.keys(main.args).length) {
395
+ throw new Error(`Arguments expected: ${Object.keys(main.args)
396
+ .map((l) => `<${l}>`)
397
+ .join(', ')}`);
398
+ }
399
+ else if (children && children.length) {
400
+ throw new Error(`Wrong command, did you mean:\n${children
401
+ .slice(0, 7)
402
+ .map((c) => ` $ ${cmd} ${c.command}`)
403
+ .join('\n')}`);
404
+ }
405
+ }
399
406
  }
400
407
 
401
- /**
402
- * Get CLI Options
403
- *
404
- * @returns an object with CLI options
405
- */
406
- function useCliOptions() {
407
- const { store } = useCliContext();
408
- const flags = store('flags');
409
- if (!flags.value) {
410
- const event = store('event');
411
- flags.value = minimist(event.value.argv, event.get('opts'));
412
- }
413
- return flags.value;
414
- }
415
- /**
416
- * Getter for Cli Option value
417
- *
418
- * @param name name of the option
419
- * @returns value of a CLI option
420
- */
421
- function useCliOption(name) {
422
- var _a;
423
- try {
424
- const options = ((_a = useCliHelp().getEntry()) === null || _a === void 0 ? void 0 : _a.options) || [];
425
- const opt = options.find(o => o.keys.includes(name));
426
- if (opt) {
427
- for (const key of opt.keys) {
428
- if (useCliOptions()[key]) {
429
- return useCliOptions()[key];
430
- }
431
- }
432
- }
433
- }
434
- catch (e) {
435
- //
436
- }
437
- return useCliOptions()[name];
408
+ /**
409
+ * Get CLI Options
410
+ *
411
+ * @returns an object with CLI options
412
+ */
413
+ function useCliOptions() {
414
+ const { store } = useCliContext();
415
+ const flags = store('flags');
416
+ if (!flags.value) {
417
+ const event = store('event');
418
+ flags.value = minimist(event.value.argv, event.get('opts'));
419
+ }
420
+ return flags.value;
421
+ }
422
+ /**
423
+ * Getter for Cli Option value
424
+ *
425
+ * @param name name of the option
426
+ * @returns value of a CLI option
427
+ */
428
+ function useCliOption(name) {
429
+ var _a;
430
+ try {
431
+ const options = ((_a = useCliHelp().getEntry()) === null || _a === void 0 ? void 0 : _a.options) || [];
432
+ const opt = options.find(o => o.keys.includes(name));
433
+ if (opt) {
434
+ for (const key of opt.keys) {
435
+ if (useCliOptions()[key]) {
436
+ return useCliOptions()[key];
437
+ }
438
+ }
439
+ }
440
+ }
441
+ catch (e) {
442
+ //
443
+ }
444
+ return useCliOptions()[name];
438
445
  }
439
446
 
440
447
  export { WooksCli, cliShortcuts, createCliApp, createCliContext, useAutoHelp, useCliContext, useCliHelp, useCliOption, useCliOptions, useCommandLookupHelp };