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