inquirerer 2.3.2 → 3.0.0

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