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