inquirerer 3.0.1 → 4.1.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.
package/esm/prompt.js ADDED
@@ -0,0 +1,1063 @@
1
+ import { red, whiteBright, yellow, gray, dim, white, blue } from 'yanse';
2
+ import readline from 'readline';
3
+ import { KEY_CODES, TerminalKeypress } from './keypress';
4
+ import { globalResolverRegistry } from './resolvers';
5
+ export function reorderQuestionsByDeps(questions) {
6
+ const nameToIndex = new Map();
7
+ questions.forEach((q, idx) => nameToIndex.set(q.name, idx));
8
+ const resolved = new Set();
9
+ const result = [];
10
+ function addQuestion(q) {
11
+ // If this question depends on others, ensure those are added first
12
+ if (q.dependsOn && q.dependsOn.length > 0) {
13
+ for (const dep of q.dependsOn) {
14
+ if (!resolved.has(dep)) {
15
+ const depIdx = nameToIndex.get(dep);
16
+ if (depIdx === undefined) {
17
+ throw new Error(`Unknown dependency: ${dep}`);
18
+ }
19
+ addQuestion(questions[depIdx]);
20
+ }
21
+ }
22
+ }
23
+ if (!resolved.has(q.name)) {
24
+ resolved.add(q.name);
25
+ result.push(q);
26
+ }
27
+ }
28
+ for (const q of questions) {
29
+ addQuestion(q);
30
+ }
31
+ return result;
32
+ }
33
+ const validationMessage = (question, ctx) => {
34
+ if (ctx.numTries === 0 || ctx.validation.success) {
35
+ return ''; // No message if first attempt or validation was successful
36
+ }
37
+ if (ctx.validation.reason) {
38
+ return red(`The field "${question.name}" is invalid: ${ctx.validation.reason}\n`);
39
+ }
40
+ switch (ctx.validation.type) {
41
+ case 'required':
42
+ return red(`The field "${question.name}" is required. Please provide a value.\n`);
43
+ case 'pattern':
44
+ return red(`The field "${question.name}" does not match the pattern: ${question.pattern}.\n`);
45
+ default:
46
+ return red(`The field "${question.name}" is invalid. Please try again.\n`);
47
+ }
48
+ };
49
+ class PromptContext {
50
+ numTries = 0;
51
+ needsInput = true;
52
+ validation = { success: false };
53
+ constructor() { }
54
+ tryAgain(validation) {
55
+ this.numTries++;
56
+ this.needsInput = true;
57
+ this.validation = { ...this.validation, ...validation, success: false };
58
+ }
59
+ nextQuestion() {
60
+ this.numTries = 0;
61
+ this.needsInput = false;
62
+ this.validation = { success: true };
63
+ }
64
+ process(validation) {
65
+ if (typeof validation === 'boolean') {
66
+ if (validation) {
67
+ this.nextQuestion();
68
+ }
69
+ else {
70
+ this.tryAgain({ type: 'validation' });
71
+ }
72
+ }
73
+ else {
74
+ if (validation.success) {
75
+ this.nextQuestion();
76
+ }
77
+ else {
78
+ this.tryAgain(validation);
79
+ }
80
+ }
81
+ return this.validation;
82
+ }
83
+ }
84
+ function generatePromptMessage(question, ctx) {
85
+ const { message, name, type, default: def, options = [], description } = question;
86
+ const lines = [];
87
+ // 1. Main prompt label with --name inline (and aliases if present)
88
+ const aliasInfo = question.alias
89
+ ? `, ${(Array.isArray(question.alias) ? question.alias : [question.alias])
90
+ .map(a => a.length === 1 ? `-${a}` : `--${a}`)
91
+ .join(', ')}`
92
+ : '';
93
+ let promptLine = whiteBright.bold(message || `${name}?`) + ' ' + dim(`(--${name}${aliasInfo})`);
94
+ // 2. Append default inline (only if present)
95
+ switch (type) {
96
+ case 'confirm':
97
+ promptLine += ' (y/n)';
98
+ if (def !== undefined) {
99
+ promptLine += ` ${yellow(`[${def ? 'y' : 'n'}]`)}`;
100
+ }
101
+ break;
102
+ case 'text':
103
+ case 'number':
104
+ if (def !== undefined) {
105
+ promptLine += ` ${yellow(`[${def}]`)}`;
106
+ }
107
+ break;
108
+ case 'autocomplete':
109
+ case 'list':
110
+ case 'checkbox':
111
+ if (def !== undefined) {
112
+ const defaults = Array.isArray(def) ? def : [def];
113
+ const rendered = defaults.map(d => yellow(d)).join(gray(', '));
114
+ promptLine += ` ${yellow(`[${rendered}]`)}`;
115
+ }
116
+ break;
117
+ }
118
+ lines.push(promptLine);
119
+ // 3. Optional description below title
120
+ if (description) {
121
+ lines.push(dim(description));
122
+ }
123
+ // 4. Validation message if applicable
124
+ const validation = validationMessage(question, ctx);
125
+ if (validation) {
126
+ lines.push(validation); // already styled red
127
+ }
128
+ return lines.join('\n') + '\n';
129
+ }
130
+ export class Inquirerer {
131
+ rl;
132
+ keypress;
133
+ noTty;
134
+ output;
135
+ input;
136
+ useDefaults;
137
+ globalMaxLines;
138
+ mutateArgs;
139
+ resolverRegistry;
140
+ handledKeys = new Set();
141
+ constructor(options) {
142
+ const { noTty = false, input = process.stdin, output = process.stdout, useDefaults = false, globalMaxLines = 10, mutateArgs = true, resolverRegistry = globalResolverRegistry } = options ?? {};
143
+ this.useDefaults = useDefaults;
144
+ this.noTty = noTty;
145
+ this.output = output;
146
+ this.mutateArgs = mutateArgs;
147
+ this.input = input;
148
+ this.globalMaxLines = globalMaxLines;
149
+ this.resolverRegistry = resolverRegistry;
150
+ if (!noTty) {
151
+ this.rl = readline.createInterface({
152
+ input,
153
+ output
154
+ });
155
+ this.keypress = new TerminalKeypress(noTty, input);
156
+ }
157
+ else {
158
+ this.rl = null;
159
+ this.keypress = null;
160
+ }
161
+ }
162
+ clearScreen() {
163
+ // same as console.clear()
164
+ this.output.write('\x1Bc'); // This is the escape sequence to clear the terminal screen.
165
+ }
166
+ write(message) {
167
+ this.output.write(message);
168
+ }
169
+ log(message) {
170
+ this.output.write(message + '\n');
171
+ }
172
+ getInput(input) {
173
+ return `${white('>')} ${input}`;
174
+ }
175
+ getPrompt(question, ctx, input) {
176
+ const promptMessage = generatePromptMessage(question, ctx);
177
+ return promptMessage + this.getInput(input);
178
+ }
179
+ displayPrompt(question, ctx, input) {
180
+ const prompt = this.getPrompt(question, ctx, input);
181
+ this.log(prompt);
182
+ }
183
+ generateManPage(opts) {
184
+ let manPage = `${white('NAME')}\n\t${white(opts.commandName)} ${opts.description ?? ''}\n\n`;
185
+ // Constructing the SYNOPSIS section with required and optional arguments
186
+ let requiredArgs = '';
187
+ let optionalArgs = '';
188
+ opts.questions.forEach(question => {
189
+ if (question.required) {
190
+ requiredArgs += ` ${white('--' + question.name)} <${gray(question.name)}>`;
191
+ }
192
+ else {
193
+ optionalArgs += ` [${white('--' + question.name)}${question.default ? `=${gray(String(question.default))}` : ''}]`;
194
+ }
195
+ });
196
+ manPage += `${white('SYNOPSIS')}\n\t${white(opts.commandName)}${gray(requiredArgs)}${gray(optionalArgs)}\n\n`;
197
+ manPage += `${white('DESCRIPTION')}\n\tUse this command to interact with the application. It supports the following options:\n\n`;
198
+ opts.questions.forEach(question => {
199
+ manPage += `${white(question.name.toUpperCase())}\n`;
200
+ manPage += `\t${white('Type:')} ${gray(question.type)}\n`;
201
+ if (question.alias) {
202
+ const aliases = Array.isArray(question.alias) ? question.alias : [question.alias];
203
+ const aliasStr = aliases.map(a => a.length === 1 ? `-${a}` : `--${a}`).join(', ');
204
+ manPage += `\t${white('Alias:')} ${gray(aliasStr)}\n`;
205
+ }
206
+ if (question.message) {
207
+ manPage += `\t${white('Summary:')} ${gray(question.message)}\n`;
208
+ }
209
+ if (question.description) {
210
+ manPage += `\t${white('Description:')} ${gray(question.description)}\n`;
211
+ }
212
+ if ('options' in question) {
213
+ const optionsList = Array.isArray(question.options)
214
+ ? question.options.map(opt => typeof opt === 'string' ? gray(opt) : `${gray(opt.name)} (${gray(opt.value)})`).join(', ')
215
+ : '';
216
+ manPage += `\t${white('Options:')} ${gray(optionsList)}\n`;
217
+ }
218
+ if (question.default !== undefined) {
219
+ manPage += `\t${white('Default:')} ${gray(JSON.stringify(question.default))}\n`;
220
+ }
221
+ if (question.required) {
222
+ manPage += `\t${white('Required:')} ${gray('Yes')}\n`;
223
+ }
224
+ else {
225
+ manPage += `\t${white('Required:')} ${gray('No')}\n`;
226
+ }
227
+ manPage += '\n';
228
+ });
229
+ manPage += `${white('EXAMPLES')}\n\tExample usage of \`${white(opts.commandName)}\`.\n\t$ ${white(opts.commandName)}${gray(requiredArgs)}${gray(optionalArgs)}\n\n`;
230
+ manPage += opts.author ? `${white('AUTHOR')}\n\t${white(opts.author)}\n` : '';
231
+ return manPage;
232
+ }
233
+ isValidatableAnswer(answer) {
234
+ return answer !== undefined;
235
+ }
236
+ validateAnswer(question, answer, obj, ctx) {
237
+ const validation = this.validateAnswerPattern(question, answer);
238
+ if (!validation.success) {
239
+ return ctx.process(validation);
240
+ }
241
+ if (question.validate) {
242
+ const customValidation = question.validate(answer, obj);
243
+ return ctx.process(customValidation);
244
+ }
245
+ return ctx.process({
246
+ success: true
247
+ });
248
+ }
249
+ isValid(question, obj, ctx) {
250
+ if (this.isValidatableAnswer(obj[question.name])) {
251
+ obj[question.name] = this.sanitizeAnswer(question, obj[question.name], obj);
252
+ const validationResult = this.validateAnswer(question, obj[question.name], obj, ctx);
253
+ if (!validationResult.success) {
254
+ return false;
255
+ }
256
+ }
257
+ if (question.required && this.isEmptyAnswer(obj[question.name])) {
258
+ ctx.tryAgain({ type: 'required' });
259
+ return false;
260
+ }
261
+ return true;
262
+ }
263
+ validateAnswerPattern(question, answer) {
264
+ if (question.pattern && typeof answer === 'string') {
265
+ const regex = new RegExp(question.pattern);
266
+ const success = regex.test(answer);
267
+ if (success) {
268
+ return {
269
+ success
270
+ };
271
+ }
272
+ else {
273
+ return {
274
+ type: 'pattern',
275
+ success: false,
276
+ reason: question.pattern
277
+ };
278
+ }
279
+ }
280
+ return {
281
+ success: true
282
+ };
283
+ }
284
+ isEmptyAnswer(answer) {
285
+ switch (true) {
286
+ case answer === undefined:
287
+ case answer === null:
288
+ case answer === '':
289
+ case Array.isArray(answer) && answer.length === 0:
290
+ return true;
291
+ }
292
+ return false;
293
+ }
294
+ sanitizeAnswer(question, answer, obj) {
295
+ if (question.sanitize) {
296
+ return question.sanitize(answer, obj);
297
+ }
298
+ return answer;
299
+ }
300
+ exit() {
301
+ this.clearScreen();
302
+ this.close();
303
+ }
304
+ async prompt(argv, questions, options) {
305
+ // use local mutateArgs if defined, otherwise global mutateArgs
306
+ const shouldMutate = options?.mutateArgs !== undefined ? options.mutateArgs : this.mutateArgs;
307
+ // Create a working copy of argv - deep clone the _ array to avoid shared reference
308
+ let obj = shouldMutate ? argv : { ...argv };
309
+ const argvAny = argv;
310
+ if (!shouldMutate && Array.isArray(argvAny._)) {
311
+ obj._ = [...argvAny._];
312
+ }
313
+ // Expand aliases before any other processing
314
+ // This allows users to use short flags like -w instead of --workspace
315
+ this.expandAliases(questions, obj);
316
+ // Resolve dynamic defaults before processing questions
317
+ await this.resolveDynamicDefaults(questions);
318
+ // Resolve dynamic options before processing questions
319
+ await this.resolveOptionsFrom(questions);
320
+ // Resolve setFrom values - these bypass prompting entirely
321
+ await this.resolveSetValues(questions, obj);
322
+ // Extract positional arguments from argv._ and assign to questions with _: true
323
+ // This must happen before applyOverrides so positional values flow through override pipeline
324
+ // Returns the number of positional arguments consumed for stripping
325
+ const consumedCount = this.extractPositionalArgs(obj, questions);
326
+ // Strip consumed positionals from obj._ (the working copy)
327
+ if (consumedCount > 0 && Array.isArray(obj._)) {
328
+ obj._ = obj._.slice(consumedCount);
329
+ // If mutating, also update the original argv._
330
+ if (shouldMutate) {
331
+ argvAny._ = obj._;
332
+ }
333
+ }
334
+ // first loop through the question, and set any overrides in case other questions use objs for validation
335
+ this.applyOverrides(obj, obj, questions);
336
+ // Check for required arguments when no terminal is available (non-interactive mode)
337
+ if (this.noTty && this.hasMissingRequiredArgs(questions, argv)) {
338
+ // Apply default values for all questions
339
+ this.applyDefaultValues(questions, obj);
340
+ // Recheck for missing required arguments after applying defaults
341
+ // NOT so sure this would ever happen, but possible if developer did something wrong
342
+ if (!this.hasMissingRequiredArgs(questions, argv)) {
343
+ return obj; // Return the updated object if no required arguments are missing
344
+ }
345
+ // Handle error for missing required arguments
346
+ this.handleMissingArgsError(options);
347
+ throw new Error('Missing required arguments. Please provide all required parameters.');
348
+ }
349
+ const ordered = reorderQuestionsByDeps(questions);
350
+ for (let index = 0; index < ordered.length; index++) {
351
+ const question = ordered[index];
352
+ const ctx = new PromptContext();
353
+ // obj is already either argv itself, or a clone, but let's check if it has the property
354
+ if (question.name in obj) {
355
+ this.handleOverrides(argv, obj, question);
356
+ ctx.nextQuestion();
357
+ continue;
358
+ }
359
+ if (question.when && !question.when(obj)) {
360
+ ctx.nextQuestion();
361
+ continue;
362
+ }
363
+ // Apply default value if applicable
364
+ // this is if useDefault is set, rare! not typical defaults which happen AFTER
365
+ // this is mostly to avoid a prompt for "hidden" options
366
+ if ('default' in question && (this.useDefaults || question.useDefault)) {
367
+ obj[question.name] = question.default;
368
+ continue; // Skip to the next question since the default is applied
369
+ }
370
+ while (ctx.needsInput) {
371
+ obj[question.name] = await this.handleQuestionType(question, ctx);
372
+ if (!this.isValid(question, obj, ctx)) {
373
+ if (this.noTty) {
374
+ // If you're not valid and here with noTty, you're out!
375
+ this.clearScreen(); // clear before leaving, not calling exit() since it may be a bad pattern to continue, devs should try/catch
376
+ throw new Error('Missing required arguments. Please provide all required parameters.');
377
+ }
378
+ continue;
379
+ }
380
+ // If input passes validation and is not empty, or not required, move to the next question
381
+ ctx.nextQuestion();
382
+ }
383
+ }
384
+ return obj;
385
+ }
386
+ handleMissingArgsError(options) {
387
+ this.clearScreen();
388
+ if (options?.usageText) {
389
+ this.log(options.usageText);
390
+ }
391
+ else if (options?.manPageInfo) {
392
+ this.log(this.generateManPage(options.manPageInfo));
393
+ }
394
+ else {
395
+ this.log('Missing required arguments. Please provide all required parameters.');
396
+ }
397
+ }
398
+ hasMissingRequiredArgs(questions, argv) {
399
+ return questions.some(question => question.required && this.isEmptyAnswer(argv[question.name]));
400
+ }
401
+ /**
402
+ * Resolves the default value for a question using the resolver system.
403
+ * Priority: defaultFrom > default > undefined
404
+ */
405
+ async resolveQuestionDefault(question) {
406
+ // Try to resolve from defaultFrom first
407
+ if ('defaultFrom' in question && question.defaultFrom) {
408
+ const resolved = await this.resolverRegistry.resolve(question.defaultFrom);
409
+ if (resolved !== undefined) {
410
+ return resolved;
411
+ }
412
+ }
413
+ // Fallback to static default
414
+ if ('default' in question) {
415
+ return question.default;
416
+ }
417
+ return undefined;
418
+ }
419
+ /**
420
+ * Resolves dynamic defaults for all questions that have defaultFrom specified.
421
+ * Updates the question.default property with the resolved value.
422
+ */
423
+ async resolveDynamicDefaults(questions) {
424
+ for (const question of questions) {
425
+ if ('defaultFrom' in question && question.defaultFrom) {
426
+ const resolved = await this.resolveQuestionDefault(question);
427
+ if (resolved !== undefined) {
428
+ // Update question.default with resolved value
429
+ question.default = resolved;
430
+ }
431
+ }
432
+ }
433
+ }
434
+ /**
435
+ * Resolves setFrom values for all questions that have setFrom specified.
436
+ * Sets the value directly in obj, bypassing the prompt entirely.
437
+ */
438
+ async resolveSetValues(questions, obj) {
439
+ for (const question of questions) {
440
+ if ('setFrom' in question && question.setFrom) {
441
+ // Only set if not already provided in args
442
+ if (!(question.name in obj)) {
443
+ const resolved = await this.resolverRegistry.resolve(question.setFrom);
444
+ if (resolved !== undefined) {
445
+ obj[question.name] = resolved;
446
+ }
447
+ }
448
+ }
449
+ }
450
+ }
451
+ /**
452
+ * Expands aliases for all questions that have alias specified.
453
+ * If an alias key exists in obj but the main name doesn't, copies the value to the main name.
454
+ * This allows users to use short flags like -w instead of --workspace.
455
+ */
456
+ expandAliases(questions, obj) {
457
+ for (const question of questions) {
458
+ if ('alias' in question && question.alias) {
459
+ // Skip if the main name already has a value
460
+ if (question.name in obj) {
461
+ continue;
462
+ }
463
+ // Normalize alias to array
464
+ const aliases = Array.isArray(question.alias) ? question.alias : [question.alias];
465
+ // Check each alias and use the first one found
466
+ for (const alias of aliases) {
467
+ if (alias in obj) {
468
+ obj[question.name] = obj[alias];
469
+ // Optionally clean up the alias key to avoid confusion
470
+ delete obj[alias];
471
+ break;
472
+ }
473
+ }
474
+ }
475
+ }
476
+ }
477
+ /**
478
+ * Resolves optionsFrom values for all questions that have optionsFrom specified.
479
+ * Updates the question.options property with the resolved array.
480
+ */
481
+ async resolveOptionsFrom(questions) {
482
+ for (const question of questions) {
483
+ if ('optionsFrom' in question && question.optionsFrom) {
484
+ const resolved = await this.resolverRegistry.resolve(question.optionsFrom);
485
+ if (resolved !== undefined && Array.isArray(resolved)) {
486
+ // Update question.options with resolved array
487
+ question.options = resolved;
488
+ }
489
+ }
490
+ }
491
+ }
492
+ /**
493
+ * Extracts positional arguments from obj._ and assigns them to questions marked with _: true.
494
+ *
495
+ * Rules:
496
+ * 1. Named arguments take precedence - if a question already has a value in obj, skip it
497
+ * 2. Positional questions consume from obj._ left-to-right in declaration order
498
+ * 3. Returns the count of consumed positionals so caller can strip them from obj._
499
+ * 4. Missing positional values leave questions unset (for prompting/validation)
500
+ *
501
+ * This effectively allows "naming positional parameters" - users can pass values
502
+ * without flags and they'll be assigned to the appropriate question names.
503
+ *
504
+ * @returns The number of positional arguments consumed
505
+ */
506
+ extractPositionalArgs(obj, questions) {
507
+ // Get positional arguments array from obj (minimist convention)
508
+ const positionals = Array.isArray(obj._) ? obj._ : [];
509
+ if (positionals.length === 0) {
510
+ return 0;
511
+ }
512
+ // Track which positional index we're consuming from
513
+ let positionalIndex = 0;
514
+ // Process questions in declaration order to maintain predictable assignment
515
+ for (const question of questions) {
516
+ // Only process questions marked as positional
517
+ if (!question._) {
518
+ continue;
519
+ }
520
+ // Skip if this question already has a named argument value
521
+ // Named arguments always take precedence over positional
522
+ if (question.name in obj && question.name !== '_') {
523
+ continue;
524
+ }
525
+ // Skip if we've exhausted all positional arguments
526
+ if (positionalIndex >= positionals.length) {
527
+ break;
528
+ }
529
+ // Assign the next positional value to this question
530
+ const value = positionals[positionalIndex];
531
+ obj[question.name] = value;
532
+ positionalIndex++;
533
+ }
534
+ return positionalIndex;
535
+ }
536
+ applyDefaultValues(questions, obj) {
537
+ questions.forEach(question => {
538
+ if ('default' in question) {
539
+ obj[question.name] = question.default; // Set default value if specified
540
+ }
541
+ });
542
+ }
543
+ applyOverrides(argv, obj, questions) {
544
+ questions.forEach(question => {
545
+ if (question.name in argv) {
546
+ this.handleOverrides(argv, obj, question);
547
+ }
548
+ });
549
+ }
550
+ handleOverrides(argv, obj, question) {
551
+ if (!Object.prototype.hasOwnProperty.call(argv, question.name)) {
552
+ return;
553
+ }
554
+ if (this.handledKeys.has(question.name)) {
555
+ return; // Already handled, skip further processing
556
+ }
557
+ this.handledKeys.add(question.name);
558
+ switch (question.type) {
559
+ case 'text':
560
+ case 'number':
561
+ case 'confirm':
562
+ // do nothing, already set!
563
+ break;
564
+ case 'checkbox':
565
+ this.handleOverridesForCheckboxOptions(argv, obj, question);
566
+ break;
567
+ case 'autocomplete':
568
+ case 'list':
569
+ // get the value from options :)
570
+ this.handleOverridesWithOptions(argv, obj, question);
571
+ break;
572
+ default:
573
+ return;
574
+ }
575
+ }
576
+ handleOverridesForCheckboxOptions(argv, obj, question) {
577
+ const options = this.sanitizeOptions(question);
578
+ const input = argv[question.name];
579
+ // Normalize to array
580
+ const inputs = Array.isArray(input) ? input.map(String) : [String(input)];
581
+ // Set of matched values
582
+ const inputSet = new Set(inputs);
583
+ // Base list of processed options
584
+ const result = options.map(opt => ({
585
+ ...opt,
586
+ selected: inputSet.has(opt.name) || inputSet.has(String(opt.value))
587
+ }));
588
+ // Add extras if allowed
589
+ if (question.allowCustomOptions) {
590
+ const knownValues = new Set(options.map(opt => String(opt.value)));
591
+ const unknowns = inputs.filter(val => !knownValues.has(val));
592
+ for (const val of unknowns) {
593
+ result.push({
594
+ name: val,
595
+ value: val,
596
+ selected: true
597
+ });
598
+ }
599
+ }
600
+ // Assign final result
601
+ obj[question.name] = question.returnFullResults
602
+ ? result
603
+ : result.filter(opt => opt.selected);
604
+ }
605
+ handleOverridesWithOptions(argv, obj, question) {
606
+ const input = argv[question.name];
607
+ if (typeof input !== 'string')
608
+ return;
609
+ const options = this.sanitizeOptions(question);
610
+ const found = options.find(opt => opt.name === input || String(opt.value) === input);
611
+ if (found) {
612
+ obj[question.name] = found.value;
613
+ }
614
+ else if (question.allowCustomOptions) {
615
+ obj[question.name] = input; // Store as-is
616
+ }
617
+ }
618
+ async handleQuestionType(question, ctx) {
619
+ this.keypress?.clearHandlers();
620
+ switch (question.type) {
621
+ case 'confirm':
622
+ return this.confirm(question, ctx);
623
+ case 'checkbox':
624
+ return this.checkbox(question, ctx);
625
+ case 'list':
626
+ return this.list(question, ctx);
627
+ case 'autocomplete':
628
+ return this.autocomplete(question, ctx);
629
+ case 'number':
630
+ return this.number(question, ctx);
631
+ case 'text':
632
+ return this.text(question, ctx);
633
+ default:
634
+ return this.text(question, ctx);
635
+ }
636
+ }
637
+ async confirm(question, ctx) {
638
+ if (this.noTty || !this.rl)
639
+ return question.default ?? false; // Return default if non-interactive
640
+ return new Promise((resolve) => {
641
+ this.clearScreen();
642
+ this.rl.question(this.getPrompt(question, ctx, ''), (answer) => {
643
+ const userInput = answer.trim().toLowerCase();
644
+ if (userInput === '') {
645
+ resolve(question.default ?? false); // Use default value if input is empty
646
+ }
647
+ else if (['yes', 'y'].includes(userInput)) {
648
+ resolve(true);
649
+ }
650
+ else {
651
+ resolve(false);
652
+ }
653
+ });
654
+ });
655
+ }
656
+ async text(question, ctx) {
657
+ if (this.noTty || !this.rl) {
658
+ if ('default' in question) {
659
+ return question.default;
660
+ }
661
+ return;
662
+ }
663
+ let input = '';
664
+ return new Promise((resolve) => {
665
+ this.clearScreen();
666
+ this.rl.question(this.getPrompt(question, ctx, input), (answer) => {
667
+ input = answer;
668
+ if (input.trim() !== '') {
669
+ resolve(input); // Return input if not empty
670
+ }
671
+ else if ('default' in question) {
672
+ resolve(question.default); // Use default if input is empty
673
+ }
674
+ else {
675
+ resolve(null); // Return null if empty and not required
676
+ }
677
+ });
678
+ });
679
+ }
680
+ async number(question, ctx) {
681
+ if (this.noTty || !this.rl) {
682
+ if ('default' in question) {
683
+ return question.default;
684
+ }
685
+ return;
686
+ }
687
+ let input = '';
688
+ return new Promise((resolve) => {
689
+ this.clearScreen();
690
+ this.rl.question(this.getPrompt(question, ctx, input), (answer) => {
691
+ input = answer.trim();
692
+ if (input !== '') {
693
+ const num = Number(input);
694
+ if (!isNaN(num)) {
695
+ resolve(num);
696
+ }
697
+ else {
698
+ resolve(null); // Let validation handle bad input
699
+ }
700
+ }
701
+ else if ('default' in question) {
702
+ resolve(question.default); // Use default if input is empty
703
+ }
704
+ else {
705
+ resolve(null); // Empty and no default
706
+ }
707
+ });
708
+ });
709
+ }
710
+ async checkbox(question, ctx) {
711
+ if (this.noTty || !this.rl) {
712
+ const options = this.sanitizeOptions(question);
713
+ const defaults = Array.isArray(question.default)
714
+ ? question.default
715
+ : [question.default];
716
+ // If returnFullResults is true, return all options with boolean selection
717
+ if (question.returnFullResults) {
718
+ return options.map(opt => ({
719
+ name: opt.name,
720
+ value: opt.value,
721
+ selected: defaults.includes(opt.name)
722
+ }));
723
+ }
724
+ // Otherwise, return only selected options
725
+ return options
726
+ .filter(opt => defaults.includes(opt.name) || defaults.includes(opt.value))
727
+ .map(opt => ({
728
+ name: opt.name,
729
+ value: opt.value,
730
+ selected: true
731
+ }));
732
+ }
733
+ if (!question.options.length) {
734
+ // no arguments don't make sense
735
+ throw new Error('checkbox requires options');
736
+ }
737
+ this.keypress.resume();
738
+ const options = this.sanitizeOptions(question);
739
+ let input = ''; // Search input
740
+ let filteredOptions = options;
741
+ let selectedIndex = 0;
742
+ let startIndex = 0; // Start index for visible options
743
+ const maxLines = this.getMaxLines(question, options.length); // Use provided max or total options
744
+ // const selections: boolean[] = new Array(options.length).fill(false);
745
+ const selections = options.map(opt => {
746
+ if (!question.default)
747
+ return false;
748
+ const defaults = Array.isArray(question.default)
749
+ ? question.default
750
+ : [question.default];
751
+ return defaults.includes(opt.name);
752
+ });
753
+ const updateFilteredOptions = () => {
754
+ filteredOptions = this.filterOptions(options, input);
755
+ };
756
+ const display = () => {
757
+ this.clearScreen();
758
+ this.displayPrompt(question, ctx, input);
759
+ const endIndex = Math.min(startIndex + maxLines, filteredOptions.length);
760
+ for (let i = startIndex; i < endIndex; i++) {
761
+ const option = filteredOptions[i];
762
+ const isSelected = selectedIndex === i;
763
+ const marker = isSelected ? '>' : ' ';
764
+ const index = options.map(o => o.name).indexOf(option.name);
765
+ if (index >= 0) {
766
+ const isChecked = selections[index] ? '◉' : '○'; // Use the original index in options
767
+ const line = `${marker} ${isChecked} ${option.name}`;
768
+ this.log(isSelected ? blue(line) : line);
769
+ }
770
+ else {
771
+ this.log('No options'); // sometimes user searches and there are no options...
772
+ }
773
+ }
774
+ };
775
+ display();
776
+ // Handling BACKSPACE key
777
+ this.keypress.on(KEY_CODES.BACKSPACE, () => {
778
+ input = input.slice(0, -1);
779
+ updateFilteredOptions();
780
+ display();
781
+ });
782
+ // Register alphanumeric keypresses to accumulate input, excluding space
783
+ 'abcdefghijklmnopqrstuvwxyz0123456789'.split('').forEach(char => {
784
+ this.keypress.on(char, () => {
785
+ input += char;
786
+ updateFilteredOptions();
787
+ display();
788
+ });
789
+ });
790
+ this.keypress.on(KEY_CODES.UP_ARROW, () => {
791
+ selectedIndex = selectedIndex > 0 ? selectedIndex - 1 : filteredOptions.length - 1;
792
+ if (selectedIndex < startIndex) {
793
+ startIndex = selectedIndex; // Scroll up
794
+ }
795
+ else if (selectedIndex === filteredOptions.length - 1) {
796
+ startIndex = Math.max(0, filteredOptions.length - maxLines); // Jump to the bottom of the list
797
+ }
798
+ display();
799
+ });
800
+ this.keypress.on(KEY_CODES.DOWN_ARROW, () => {
801
+ selectedIndex = (selectedIndex + 1) % filteredOptions.length;
802
+ if (selectedIndex >= startIndex + maxLines) {
803
+ startIndex = selectedIndex - maxLines + 1; // Scroll down
804
+ }
805
+ else if (selectedIndex === 0) {
806
+ startIndex = 0; // Jump to the top of the list
807
+ }
808
+ display();
809
+ });
810
+ this.keypress.on(KEY_CODES.SPACE, () => {
811
+ // Map filtered index back to the original index in options
812
+ selections[options.indexOf(filteredOptions[selectedIndex])] = !selections[options.indexOf(filteredOptions[selectedIndex])];
813
+ display();
814
+ });
815
+ return new Promise(resolve => {
816
+ this.keypress.on(KEY_CODES.ENTER, () => {
817
+ this.keypress.pause();
818
+ const result = [];
819
+ if (question.returnFullResults) {
820
+ // Return all options with their selected status
821
+ options.forEach((option, index) => {
822
+ result.push({
823
+ name: option.name,
824
+ value: option.value,
825
+ selected: selections[index]
826
+ });
827
+ });
828
+ }
829
+ else {
830
+ // Return only options that are selected
831
+ options.forEach((option, index) => {
832
+ if (selections[index]) {
833
+ result.push({
834
+ name: option.name,
835
+ value: option.value,
836
+ selected: selections[index]
837
+ });
838
+ }
839
+ });
840
+ }
841
+ resolve(result);
842
+ });
843
+ });
844
+ }
845
+ async autocomplete(question, ctx) {
846
+ if (this.noTty || !this.rl) {
847
+ if ('default' in question) {
848
+ return question.default;
849
+ }
850
+ return;
851
+ }
852
+ if (!question.options.length) {
853
+ throw new Error('autocomplete requires options');
854
+ }
855
+ this.keypress.resume();
856
+ const options = this.sanitizeOptions(question);
857
+ let input = '';
858
+ let filteredOptions = options;
859
+ let selectedIndex = 0;
860
+ let startIndex = 0; // Start index for visible options
861
+ const maxLines = this.getMaxLines(question, options.length); // Use provided max or total options
862
+ const display = () => {
863
+ this.clearScreen();
864
+ this.displayPrompt(question, ctx, input);
865
+ // Determine the range of options to display
866
+ const endIndex = Math.min(startIndex + maxLines, filteredOptions.length);
867
+ for (let i = startIndex; i < endIndex; i++) {
868
+ const option = filteredOptions[i];
869
+ if (!option) {
870
+ this.log('No options'); // sometimes user searches and there are no options...
871
+ }
872
+ else if (i === selectedIndex) {
873
+ this.log(blue('> ' + option.name)); // Highlight the selected option with yanse
874
+ }
875
+ else {
876
+ this.log(' ' + option.name);
877
+ }
878
+ }
879
+ };
880
+ const updateFilteredOptions = () => {
881
+ filteredOptions = this.filterOptions(options, input);
882
+ // Adjust startIndex to keep the selectedIndex in the visible range
883
+ if (selectedIndex < startIndex) {
884
+ startIndex = selectedIndex;
885
+ }
886
+ else if (selectedIndex >= startIndex + maxLines) {
887
+ startIndex = selectedIndex - maxLines + 1;
888
+ }
889
+ if (selectedIndex >= filteredOptions.length) {
890
+ selectedIndex = Math.max(filteredOptions.length - 1, 0);
891
+ }
892
+ };
893
+ display();
894
+ // Handling BACKSPACE key
895
+ this.keypress.on(KEY_CODES.BACKSPACE, () => {
896
+ input = input.slice(0, -1);
897
+ updateFilteredOptions();
898
+ display();
899
+ });
900
+ // Register alphanumeric and space keypresses to accumulate input
901
+ 'abcdefghijklmnopqrstuvwxyz0123456789 '.split('').forEach(char => {
902
+ this.keypress.on(char, () => {
903
+ input += char;
904
+ updateFilteredOptions();
905
+ display();
906
+ });
907
+ });
908
+ // Navigation
909
+ this.keypress.on(KEY_CODES.UP_ARROW, () => {
910
+ selectedIndex = selectedIndex - 1 >= 0 ? selectedIndex - 1 : filteredOptions.length - 1;
911
+ if (selectedIndex < startIndex) {
912
+ startIndex = selectedIndex; // Scroll up
913
+ }
914
+ else if (selectedIndex === filteredOptions.length - 1) {
915
+ startIndex = Math.max(0, filteredOptions.length - maxLines); // Jump to the bottom of the list
916
+ }
917
+ display();
918
+ });
919
+ this.keypress.on(KEY_CODES.DOWN_ARROW, () => {
920
+ selectedIndex = (selectedIndex + 1) % filteredOptions.length;
921
+ if (selectedIndex >= startIndex + maxLines) {
922
+ startIndex = selectedIndex - maxLines + 1; // Scroll down
923
+ }
924
+ else if (selectedIndex === 0) {
925
+ startIndex = 0; // Jump to the top of the list
926
+ }
927
+ display();
928
+ });
929
+ return new Promise(resolve => {
930
+ this.keypress.on(KEY_CODES.ENTER, () => {
931
+ this.keypress.pause();
932
+ resolve(filteredOptions[selectedIndex]?.value || input);
933
+ });
934
+ });
935
+ }
936
+ async list(question, ctx) {
937
+ if (this.noTty || !this.rl) {
938
+ if ('default' in question) {
939
+ return question.default;
940
+ }
941
+ return;
942
+ }
943
+ if (!question.options.length) {
944
+ throw new Error('list requires options');
945
+ }
946
+ this.keypress.resume();
947
+ const options = this.sanitizeOptions(question);
948
+ let input = '';
949
+ let selectedIndex = 0;
950
+ let startIndex = 0; // Start index for visible options
951
+ const maxLines = this.getMaxLines(question, options.length); // Use provided max or total options
952
+ const display = () => {
953
+ this.clearScreen();
954
+ this.displayPrompt(question, ctx, input);
955
+ // Determine the range of options to display
956
+ const endIndex = Math.min(startIndex + maxLines, options.length);
957
+ for (let i = startIndex; i < endIndex; i++) {
958
+ const option = options[i];
959
+ if (!option) {
960
+ this.log('No options'); // sometimes user searches and there are no options...
961
+ }
962
+ else if (i === selectedIndex) {
963
+ this.log(blue('> ' + option.name)); // Highlight the selected option with yanse
964
+ }
965
+ else {
966
+ this.log(' ' + option.name);
967
+ }
968
+ }
969
+ };
970
+ display();
971
+ // Navigation
972
+ this.keypress.on(KEY_CODES.UP_ARROW, () => {
973
+ selectedIndex = selectedIndex - 1 >= 0 ? selectedIndex - 1 : options.length - 1;
974
+ if (selectedIndex < startIndex) {
975
+ startIndex = selectedIndex; // Scroll up
976
+ }
977
+ else if (selectedIndex === options.length - 1) {
978
+ startIndex = Math.max(0, options.length - maxLines); // Jump to the bottom of the list
979
+ }
980
+ display();
981
+ });
982
+ this.keypress.on(KEY_CODES.DOWN_ARROW, () => {
983
+ selectedIndex = (selectedIndex + 1) % options.length;
984
+ if (selectedIndex >= startIndex + maxLines) {
985
+ startIndex = selectedIndex - maxLines + 1; // Scroll down
986
+ }
987
+ else if (selectedIndex === 0) {
988
+ startIndex = 0; // Jump to the top of the list
989
+ }
990
+ display();
991
+ });
992
+ return new Promise(resolve => {
993
+ this.keypress.on(KEY_CODES.ENTER, () => {
994
+ this.keypress.pause();
995
+ resolve(options[selectedIndex]?.value || input);
996
+ });
997
+ });
998
+ }
999
+ getOptionValue(option) {
1000
+ if (typeof option === 'string') {
1001
+ return { name: option, value: option };
1002
+ }
1003
+ else if (typeof option === 'object' && option && 'name' in option) {
1004
+ return { name: option.name, value: option.value };
1005
+ }
1006
+ else {
1007
+ return undefined;
1008
+ }
1009
+ }
1010
+ sanitizeOptions(question) {
1011
+ const options = (question.options ?? []).map(option => this.getOptionValue(option));
1012
+ return options.filter(Boolean);
1013
+ }
1014
+ filterOptions(options, input) {
1015
+ input = input.toLowerCase(); // Normalize input for case-insensitive comparison
1016
+ // Fuzzy matching: Check if all characters of the input can be found in the option name in order
1017
+ const fuzzyMatch = (option, input) => {
1018
+ if (!input || !input.trim().length)
1019
+ return true;
1020
+ const length = input.length;
1021
+ let position = 0; // Position in the input string
1022
+ // Iterate over each character in the option name
1023
+ for (let i = 0; i < option.length; i++) {
1024
+ if (option[i] === input[position]) {
1025
+ position++; // Move to the next character in the input
1026
+ if (position === length) { // Check if we've matched all characters
1027
+ return true;
1028
+ }
1029
+ }
1030
+ }
1031
+ return false;
1032
+ };
1033
+ return options
1034
+ .filter(option => fuzzyMatch(option.name.toLowerCase(), input))
1035
+ .sort((a, b) => {
1036
+ if (a.name < b.name) {
1037
+ return -1;
1038
+ }
1039
+ if (a.name > b.name) {
1040
+ return 1;
1041
+ }
1042
+ return 0;
1043
+ });
1044
+ }
1045
+ getMaxLines(question, defaultLength) {
1046
+ if (question.maxDisplayLines) {
1047
+ return question.maxDisplayLines;
1048
+ }
1049
+ // if (!this.noTty && (this.output as any).isTTY) {
1050
+ // const rows = Math.round(((this.output as any).rows ?? 0) / 7);
1051
+ // return Math.max(rows, defaultLength);
1052
+ // }
1053
+ return Math.min(this.globalMaxLines, defaultLength);
1054
+ }
1055
+ // Method to cleanly close the readline interface
1056
+ // NOTE: use exit() to close!
1057
+ close() {
1058
+ if (this.rl) {
1059
+ this.rl.close();
1060
+ this.keypress.destroy();
1061
+ }
1062
+ }
1063
+ }