@topcli/prompts 1.7.0 → 1.8.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/dist/index.js ADDED
@@ -0,0 +1,830 @@
1
+ // src/prompts/question.ts
2
+ import { EOL as EOL2 } from "os";
3
+ import kleur2 from "kleur";
4
+ import wcwidth from "@topcli/wcwidth";
5
+
6
+ // src/prompts/abstract.ts
7
+ import { EOL } from "os";
8
+ import { createInterface } from "readline";
9
+ import { Writable } from "stream";
10
+
11
+ // src/utils.ts
12
+ import process2 from "process";
13
+ var kAnsiRegex = ansiRegex();
14
+ function ansiRegex({ onlyFirst = false } = {}) {
15
+ const pattern = [
16
+ // eslint-disable-next-line max-len
17
+ "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
18
+ "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"
19
+ ].join("|");
20
+ return new RegExp(pattern, onlyFirst ? void 0 : "g");
21
+ }
22
+ function stripAnsi(string) {
23
+ return string.replace(kAnsiRegex, "");
24
+ }
25
+ function isUnicodeSupported() {
26
+ if (process2.platform !== "win32") {
27
+ return process2.env.TERM !== "linux";
28
+ }
29
+ return Boolean(process2.env.WT_SESSION) || Boolean(process2.env.TERMINUS_SUBLIME) || process2.env.ConEmuTask === "{cmd::Cmder}" || process2.env.TERM_PROGRAM === "Terminus-Sublime" || process2.env.TERM_PROGRAM === "vscode" || process2.env.TERM === "xterm-256color" || process2.env.TERM === "alacritty" || process2.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
30
+ }
31
+
32
+ // src/prompt-agent.ts
33
+ var kPrivateInstancier = Symbol("instancier");
34
+ var PromptAgent = class _PromptAgent {
35
+ /**
36
+ * The prompts answers queue.
37
+ * When not empty, any prompt will be answered by the first answer in this list.
38
+ */
39
+ nextAnswers = [];
40
+ /**
41
+ * The shared PromptAgent.
42
+ */
43
+ static #this;
44
+ static agent() {
45
+ return this.#this ??= new _PromptAgent(kPrivateInstancier);
46
+ }
47
+ constructor(instancier) {
48
+ if (instancier !== kPrivateInstancier) {
49
+ throw new Error("Cannot instanciate PromptAgent, use PromptAgent.agent() instead");
50
+ }
51
+ }
52
+ /**
53
+ * Programmatically set the next answer for any prompt (`question()`, `confirm()`, `select()`)
54
+ *
55
+ * This is useful for testing.
56
+ *
57
+ * @example
58
+ * ```js
59
+ * const promptAgent = PromptAgent.agent();
60
+ * promptAgent.nextAnswer("toto");
61
+ *
62
+ * const input = await question("what is your name?");
63
+ * assert.equal(input, "toto");
64
+ * ```
65
+ */
66
+ nextAnswer(value) {
67
+ if (Array.isArray(value)) {
68
+ this.nextAnswers.push(...value);
69
+ return;
70
+ }
71
+ this.nextAnswers.push(value);
72
+ }
73
+ };
74
+
75
+ // src/prompts/abstract.ts
76
+ var AbstractPrompt = class _AbstractPrompt {
77
+ stdin;
78
+ stdout;
79
+ message;
80
+ history;
81
+ agent;
82
+ mute;
83
+ rl;
84
+ constructor(message, input = process.stdin, output = process.stdout) {
85
+ if (this.constructor === _AbstractPrompt) {
86
+ throw new Error("AbstractPrompt can't be instantiated.");
87
+ }
88
+ if (typeof message !== "string") {
89
+ throw new TypeError(`message must be string, ${typeof message} given.`);
90
+ }
91
+ this.stdin = input;
92
+ this.stdout = output;
93
+ this.message = message;
94
+ this.history = [];
95
+ this.agent = PromptAgent.agent();
96
+ this.mute = false;
97
+ if (this.stdout.isTTY) {
98
+ this.stdin.setRawMode(true);
99
+ }
100
+ this.rl = createInterface({
101
+ input,
102
+ output: new Writable({
103
+ write: (chunk, encoding, callback) => {
104
+ if (!this.mute) {
105
+ this.stdout.write(chunk, encoding);
106
+ }
107
+ callback();
108
+ }
109
+ }),
110
+ terminal: true
111
+ });
112
+ }
113
+ write(data) {
114
+ const formattedData = stripAnsi(data).replace(EOL, "");
115
+ if (formattedData) {
116
+ this.history.push(formattedData);
117
+ }
118
+ return this.stdout.write(data);
119
+ }
120
+ clearLastLine() {
121
+ const lastLine = this.history.pop();
122
+ if (!lastLine) {
123
+ return;
124
+ }
125
+ const lastLineRows = Math.ceil(stripAnsi(lastLine).length / this.stdout.columns);
126
+ this.stdout.moveCursor(-this.stdout.columns, -lastLineRows);
127
+ this.stdout.clearScreenDown();
128
+ }
129
+ destroy() {
130
+ this.rl.close();
131
+ }
132
+ };
133
+
134
+ // src/constants.ts
135
+ import kleur from "kleur";
136
+ var kMainSymbols = {
137
+ tick: "\u2714",
138
+ cross: "\u2716",
139
+ pointer: "\u203A",
140
+ previous: "\u2B61",
141
+ next: "\u2B63",
142
+ active: "\u25CF",
143
+ inactive: "\u25CB"
144
+ };
145
+ var kFallbackSymbols = {
146
+ tick: "\u221A",
147
+ cross: "\xD7",
148
+ pointer: ">",
149
+ previous: "\u2191",
150
+ next: "\u2193",
151
+ active: "(+)",
152
+ inactive: "(-)"
153
+ };
154
+ var kSymbols = isUnicodeSupported() || process.env.CI ? kMainSymbols : kFallbackSymbols;
155
+ var kPointer = kleur.gray(kSymbols.pointer);
156
+ var SYMBOLS = {
157
+ QuestionMark: kleur.blue().bold("?"),
158
+ Tick: kleur.green().bold(kSymbols.tick),
159
+ Cross: kleur.red().bold(kSymbols.cross),
160
+ Pointer: kPointer,
161
+ Previous: kSymbols.previous,
162
+ Next: kSymbols.next,
163
+ ShowCursor: "\x1B[?25h",
164
+ HideCursor: "\x1B[?25l",
165
+ Active: kleur.cyan(kSymbols.active),
166
+ Inactive: kleur.gray(kSymbols.inactive)
167
+ };
168
+
169
+ // src/prompts/question.ts
170
+ var QuestionPrompt = class extends AbstractPrompt {
171
+ defaultValue;
172
+ tip;
173
+ questionSuffixError;
174
+ answer;
175
+ answerBuffer;
176
+ #validators;
177
+ #secure;
178
+ constructor(message, options = {}) {
179
+ const {
180
+ stdin = process.stdin,
181
+ stdout = process.stdout,
182
+ defaultValue,
183
+ validators = [],
184
+ secure = false
185
+ } = options;
186
+ super(message, stdin, stdout);
187
+ if (defaultValue && typeof defaultValue !== "string") {
188
+ throw new TypeError("defaultValue must be a string");
189
+ }
190
+ this.defaultValue = defaultValue;
191
+ this.tip = this.defaultValue ? ` (${this.defaultValue})` : "";
192
+ this.#validators = validators;
193
+ this.#secure = Boolean(secure);
194
+ this.questionSuffixError = "";
195
+ }
196
+ #question() {
197
+ return new Promise((resolve) => {
198
+ const questionQuery = this.#getQuestionQuery();
199
+ this.rl.question(questionQuery, (answer) => {
200
+ this.history.push(questionQuery + answer);
201
+ this.mute = false;
202
+ resolve(answer);
203
+ });
204
+ this.mute = this.#secure;
205
+ });
206
+ }
207
+ #getQuestionQuery() {
208
+ return `${kleur2.bold(`${SYMBOLS.QuestionMark} ${this.message}${this.tip}`)} ${this.questionSuffixError}`;
209
+ }
210
+ #setQuestionSuffixError(error) {
211
+ const suffix = kleur2.red(`[${error}] `);
212
+ this.questionSuffixError = suffix;
213
+ }
214
+ #writeAnswer() {
215
+ const prefix = this.answer ? SYMBOLS.Tick : SYMBOLS.Cross;
216
+ const answer = kleur2.yellow(this.#secure ? "CONFIDENTIAL" : this.answer ?? "");
217
+ this.write(`${prefix} ${kleur2.bold(this.message)} ${SYMBOLS.Pointer} ${answer}${EOL2}`);
218
+ }
219
+ #onQuestionAnswer() {
220
+ const questionLineCount = Math.ceil(
221
+ wcwidth(stripAnsi(this.#getQuestionQuery() + this.answer)) / this.stdout.columns
222
+ );
223
+ this.stdout.moveCursor(-this.stdout.columns, -questionLineCount);
224
+ this.stdout.clearScreenDown();
225
+ for (const validator of this.#validators) {
226
+ if (!validator.validate(this.answer)) {
227
+ const error = validator.error(this.answer);
228
+ this.#setQuestionSuffixError(error);
229
+ this.answerBuffer = this.#question();
230
+ return;
231
+ }
232
+ }
233
+ this.answerBuffer = void 0;
234
+ this.#writeAnswer();
235
+ }
236
+ async question() {
237
+ this.answer = this.agent.nextAnswers.shift();
238
+ if (this.answer !== void 0) {
239
+ this.#writeAnswer();
240
+ this.destroy();
241
+ return this.answer;
242
+ }
243
+ this.answer = await this.#question();
244
+ if (this.answer === "" && this.defaultValue) {
245
+ this.answer = this.defaultValue;
246
+ }
247
+ this.#onQuestionAnswer();
248
+ while (this.answerBuffer !== void 0) {
249
+ this.answer = await this.answerBuffer;
250
+ this.#onQuestionAnswer();
251
+ }
252
+ this.destroy();
253
+ return this.answer;
254
+ }
255
+ };
256
+
257
+ // src/prompts/confirm.ts
258
+ import { EOL as EOL3 } from "os";
259
+ import kleur3 from "kleur";
260
+ import wcwidth2 from "@topcli/wcwidth";
261
+ var kToggleKeys = /* @__PURE__ */ new Set([
262
+ "left",
263
+ "right",
264
+ "tab",
265
+ "q",
266
+ "a",
267
+ "d",
268
+ "h",
269
+ "j",
270
+ "k",
271
+ "l",
272
+ "space"
273
+ ]);
274
+ var ConfirmPrompt = class extends AbstractPrompt {
275
+ initial;
276
+ selectedValue;
277
+ #boundKeyPressEvent;
278
+ #boundExitEvent;
279
+ constructor(message, options = {}) {
280
+ const {
281
+ stdin = process.stdin,
282
+ stdout = process.stdout,
283
+ initial = false
284
+ } = options;
285
+ super(message, stdin, stdout);
286
+ this.initial = initial;
287
+ this.selectedValue = initial;
288
+ }
289
+ #getHint() {
290
+ const Yes = kleur3.bold().underline().cyan("Yes");
291
+ const No = kleur3.bold().underline().cyan("No");
292
+ return this.selectedValue ? `${Yes}/No` : `Yes/${No}`;
293
+ }
294
+ #render() {
295
+ this.write(this.#getQuestionQuery());
296
+ }
297
+ #question() {
298
+ return new Promise((resolve) => {
299
+ const questionQuery = this.#getQuestionQuery();
300
+ this.write(questionQuery);
301
+ this.#boundKeyPressEvent = this.#onKeypress.bind(this, resolve);
302
+ this.stdin.on("keypress", this.#boundKeyPressEvent);
303
+ this.#boundExitEvent = this.#onProcessExit.bind(this);
304
+ process.once("exit", this.#boundExitEvent);
305
+ });
306
+ }
307
+ #onKeypress(resolve, value, key) {
308
+ this.stdout.moveCursor(
309
+ -this.stdout.columns,
310
+ -Math.floor(wcwidth2(stripAnsi(this.#getQuestionQuery())) / this.stdout.columns)
311
+ );
312
+ this.stdout.clearScreenDown();
313
+ if (key.name === "return") {
314
+ resolve(this.selectedValue);
315
+ return;
316
+ }
317
+ if (kToggleKeys.has(key.name ?? "")) {
318
+ this.selectedValue = !this.selectedValue;
319
+ }
320
+ this.#render();
321
+ }
322
+ #onProcessExit() {
323
+ this.stdin.off("keypress", this.#boundKeyPressEvent);
324
+ }
325
+ #getQuestionQuery() {
326
+ const query = kleur3.bold(`${SYMBOLS.QuestionMark} ${this.message}`);
327
+ return `${query} ${this.#getHint()}`;
328
+ }
329
+ #onQuestionAnswer() {
330
+ this.stdout.moveCursor(
331
+ -this.stdout.columns,
332
+ -(Math.floor(wcwidth2(stripAnsi(this.#getQuestionQuery())) / this.stdout.columns) || 1)
333
+ );
334
+ this.stdout.clearScreenDown();
335
+ this.write(`${this.selectedValue ? SYMBOLS.Tick : SYMBOLS.Cross} ${kleur3.bold(this.message)}${EOL3}`);
336
+ }
337
+ async confirm() {
338
+ const answer = this.agent.nextAnswers.shift();
339
+ if (answer !== void 0) {
340
+ this.selectedValue = answer;
341
+ this.#onQuestionAnswer();
342
+ this.destroy();
343
+ return answer;
344
+ }
345
+ this.write(SYMBOLS.HideCursor);
346
+ try {
347
+ await this.#question();
348
+ this.#onQuestionAnswer();
349
+ return this.selectedValue;
350
+ } finally {
351
+ this.write(SYMBOLS.ShowCursor);
352
+ this.#onProcessExit();
353
+ process.off("exit", this.#boundExitEvent);
354
+ this.destroy();
355
+ }
356
+ }
357
+ };
358
+
359
+ // src/prompts/select.ts
360
+ import { EOL as EOL4 } from "os";
361
+ import kleur4 from "kleur";
362
+ import wcwidth3 from "@topcli/wcwidth";
363
+ var SelectPrompt = class extends AbstractPrompt {
364
+ #boundExitEvent = () => void 0;
365
+ #boundKeyPressEvent = () => void 0;
366
+ activeIndex = 0;
367
+ selectedIndexes = [];
368
+ questionMessage;
369
+ longestChoicelength;
370
+ options;
371
+ lastRender;
372
+ get choices() {
373
+ return this.options.choices;
374
+ }
375
+ constructor(message, options) {
376
+ const {
377
+ stdin = process.stdin,
378
+ stdout = process.stdout,
379
+ choices
380
+ } = options ?? {};
381
+ super(message, stdin, stdout);
382
+ if (!options) {
383
+ this.destroy();
384
+ throw new TypeError("Missing required options");
385
+ }
386
+ this.options = options;
387
+ if (!choices?.length) {
388
+ this.destroy();
389
+ throw new TypeError("Missing required param: choices");
390
+ }
391
+ this.longestChoicelength = Math.max(...choices.map((choice) => {
392
+ if (typeof choice === "string") {
393
+ return choice.length;
394
+ }
395
+ const kRequiredChoiceProperties2 = ["label", "value"];
396
+ for (const prop of kRequiredChoiceProperties2) {
397
+ if (!choice[prop]) {
398
+ this.destroy();
399
+ throw new TypeError(`Missing ${prop} for choice ${JSON.stringify(choice)}`);
400
+ }
401
+ }
402
+ return choice.label.length;
403
+ }));
404
+ }
405
+ #getFormattedChoice(choiceIndex) {
406
+ const choice = this.choices[choiceIndex];
407
+ if (typeof choice === "string") {
408
+ return { value: choice, label: choice };
409
+ }
410
+ return choice;
411
+ }
412
+ #getVisibleChoices() {
413
+ const maxVisible = this.options.maxVisible || 8;
414
+ let startIndex = Math.min(this.choices.length - maxVisible, this.activeIndex - Math.floor(maxVisible / 2));
415
+ if (startIndex < 0) {
416
+ startIndex = 0;
417
+ }
418
+ const endIndex = Math.min(startIndex + maxVisible, this.choices.length);
419
+ return { startIndex, endIndex };
420
+ }
421
+ #showChoices() {
422
+ const { startIndex, endIndex } = this.#getVisibleChoices();
423
+ this.lastRender = { startIndex, endIndex };
424
+ for (let choiceIndex = startIndex; choiceIndex < endIndex; choiceIndex++) {
425
+ const choice = this.#getFormattedChoice(choiceIndex);
426
+ const isChoiceSelected = choiceIndex === this.activeIndex;
427
+ const showPreviousChoicesArrow = startIndex > 0 && choiceIndex === startIndex;
428
+ const showNextChoicesArrow = endIndex < this.choices.length && choiceIndex === endIndex - 1;
429
+ let prefixArrow = " ";
430
+ if (showPreviousChoicesArrow) {
431
+ prefixArrow = SYMBOLS.Previous;
432
+ } else if (showNextChoicesArrow) {
433
+ prefixArrow = SYMBOLS.Next;
434
+ }
435
+ const prefix = `${prefixArrow}${isChoiceSelected ? `${SYMBOLS.Pointer} ` : " "}`;
436
+ const formattedLabel = choice.label.padEnd(
437
+ this.longestChoicelength < 10 ? this.longestChoicelength : 0
438
+ );
439
+ const formattedDescription = choice.description ? ` - ${choice.description}` : "";
440
+ const color = isChoiceSelected ? kleur4.white().bold : kleur4.gray;
441
+ const str = color(`${prefix}${formattedLabel}${formattedDescription}${EOL4}`);
442
+ this.write(str);
443
+ }
444
+ }
445
+ #showAnsweredQuestion(choice) {
446
+ const prefix = `${SYMBOLS.Tick} ${kleur4.bold(this.message)} ${SYMBOLS.Pointer}`;
447
+ const formattedChoice = kleur4.yellow(typeof choice === "string" ? choice : choice.label);
448
+ this.write(`${prefix} ${formattedChoice}${EOL4}`);
449
+ }
450
+ #onProcessExit() {
451
+ this.stdin.off("keypress", this.#boundKeyPressEvent);
452
+ this.stdout.moveCursor(-this.stdout.columns, 0);
453
+ this.stdout.clearScreenDown();
454
+ this.write(SYMBOLS.ShowCursor);
455
+ }
456
+ #onKeypress(...args) {
457
+ const [resolve, render, , key] = args;
458
+ if (key.name === "up") {
459
+ this.activeIndex = this.activeIndex === 0 ? this.choices.length - 1 : this.activeIndex - 1;
460
+ render();
461
+ } else if (key.name === "down") {
462
+ this.activeIndex = this.activeIndex === this.choices.length - 1 ? 0 : this.activeIndex + 1;
463
+ render();
464
+ } else if (key.name === "return") {
465
+ render({ clearRender: true });
466
+ const currentChoice = this.choices[this.activeIndex];
467
+ const value = typeof currentChoice === "string" ? currentChoice : currentChoice.value;
468
+ if (!this.options.ignoreValues?.includes(value)) {
469
+ this.#showAnsweredQuestion(currentChoice);
470
+ }
471
+ this.write(SYMBOLS.ShowCursor);
472
+ this.destroy();
473
+ this.#onProcessExit();
474
+ process.off("exit", this.#boundExitEvent);
475
+ resolve(value);
476
+ } else {
477
+ render();
478
+ }
479
+ }
480
+ async select() {
481
+ const answer = this.agent.nextAnswers.shift();
482
+ if (answer !== void 0) {
483
+ const formatedAnser = Array.isArray(answer) ? answer.join(", ") : answer;
484
+ this.#showAnsweredQuestion(formatedAnser);
485
+ this.destroy();
486
+ return Array.isArray(answer) ? answer : [answer];
487
+ }
488
+ this.write(SYMBOLS.HideCursor);
489
+ this.#showQuestion();
490
+ const render = (options = {}) => {
491
+ const {
492
+ initialRender = false,
493
+ clearRender = false
494
+ } = options;
495
+ if (!initialRender) {
496
+ let linesToClear = this.lastRender.endIndex - this.lastRender.startIndex;
497
+ while (linesToClear > 0) {
498
+ this.clearLastLine();
499
+ linesToClear--;
500
+ }
501
+ }
502
+ if (clearRender) {
503
+ const questionLineCount = Math.ceil(
504
+ wcwidth3(stripAnsi(this.questionMessage)) / this.stdout.columns
505
+ );
506
+ this.stdout.moveCursor(-this.stdout.columns, -(1 + questionLineCount));
507
+ this.stdout.clearScreenDown();
508
+ return;
509
+ }
510
+ this.#showChoices();
511
+ };
512
+ render({ initialRender: true });
513
+ return new Promise((resolve) => {
514
+ this.#boundKeyPressEvent = this.#onKeypress.bind(this, resolve, render);
515
+ this.stdin.on("keypress", this.#boundKeyPressEvent);
516
+ this.#boundExitEvent = this.#onProcessExit.bind(this);
517
+ process.once("exit", this.#boundExitEvent);
518
+ });
519
+ }
520
+ #showQuestion() {
521
+ this.questionMessage = `${SYMBOLS.QuestionMark} ${kleur4.bold(this.message)}`;
522
+ this.write(`${this.questionMessage}${EOL4}`);
523
+ }
524
+ };
525
+
526
+ // src/prompts/multiselect.ts
527
+ import { EOL as EOL5 } from "os";
528
+ import kleur5 from "kleur";
529
+ import wcwidth4 from "@topcli/wcwidth";
530
+ var kRequiredChoiceProperties = ["label", "value"];
531
+ var MultiselectPrompt = class extends AbstractPrompt {
532
+ #boundExitEvent = () => void 0;
533
+ #boundKeyPressEvent = () => void 0;
534
+ #validators;
535
+ activeIndex = 0;
536
+ selectedIndexes = [];
537
+ questionMessage;
538
+ autocompleteValue = "";
539
+ options;
540
+ lastRender;
541
+ get choices() {
542
+ return this.options.choices;
543
+ }
544
+ get filteredChoices() {
545
+ if (!(this.options.autocomplete && this.autocompleteValue.length > 0)) {
546
+ return this.choices;
547
+ }
548
+ const isCaseSensitive = this.options.caseSensitive;
549
+ const autocompleteValue = isCaseSensitive ? this.autocompleteValue : this.autocompleteValue.toLowerCase();
550
+ return this.choices.filter((choice) => this.#filterChoice(choice, autocompleteValue, isCaseSensitive));
551
+ }
552
+ #filterChoice(choice, autocompleteValue, isCaseSensitive = false) {
553
+ const choiceValue = typeof choice === "string" ? isCaseSensitive ? choice : choice.toLowerCase() : isCaseSensitive ? choice.label : choice.label.toLowerCase();
554
+ if (autocompleteValue.includes(" ")) {
555
+ return this.#filterMultipleWords(choiceValue, autocompleteValue, isCaseSensitive);
556
+ }
557
+ return choiceValue.includes(autocompleteValue);
558
+ }
559
+ #filterMultipleWords(choiceValue, autocompleteValue, isCaseSensitive) {
560
+ return autocompleteValue.split(" ").every((word) => {
561
+ const wordValue = isCaseSensitive ? word : word.toLowerCase();
562
+ return choiceValue.includes(wordValue) || choiceValue.includes(autocompleteValue);
563
+ });
564
+ }
565
+ get longestChoice() {
566
+ return Math.max(...this.filteredChoices.map((choice) => {
567
+ if (typeof choice === "string") {
568
+ return choice.length;
569
+ }
570
+ return choice.label.length;
571
+ }));
572
+ }
573
+ constructor(message, options) {
574
+ const {
575
+ stdin = process.stdin,
576
+ stdout = process.stdout,
577
+ choices,
578
+ preSelectedChoices,
579
+ validators = []
580
+ } = options ?? {};
581
+ super(message, stdin, stdout);
582
+ if (!options) {
583
+ this.destroy();
584
+ throw new TypeError("Missing required options");
585
+ }
586
+ this.options = options;
587
+ if (!choices?.length) {
588
+ this.destroy();
589
+ throw new TypeError("Missing required param: choices");
590
+ }
591
+ this.#validators = validators;
592
+ for (const choice of choices) {
593
+ if (typeof choice === "string") {
594
+ continue;
595
+ }
596
+ for (const prop of kRequiredChoiceProperties) {
597
+ if (!choice[prop]) {
598
+ this.destroy();
599
+ throw new TypeError(`Missing ${prop} for choice ${JSON.stringify(choice)}`);
600
+ }
601
+ }
602
+ }
603
+ if (!preSelectedChoices) {
604
+ return;
605
+ }
606
+ for (const choice of preSelectedChoices) {
607
+ const choiceIndex = this.filteredChoices.findIndex((item) => {
608
+ if (typeof item === "string") {
609
+ return item === choice;
610
+ }
611
+ return item.value === choice;
612
+ });
613
+ if (choiceIndex === -1) {
614
+ this.destroy();
615
+ throw new Error(`Invalid pre-selected choice: ${typeof choice === "string" ? choice : choice.value}`);
616
+ }
617
+ this.selectedIndexes.push(choiceIndex);
618
+ }
619
+ }
620
+ #getFormattedChoice(choiceIndex) {
621
+ const choice = this.filteredChoices[choiceIndex];
622
+ if (typeof choice === "string") {
623
+ return { value: choice, label: choice };
624
+ }
625
+ return choice;
626
+ }
627
+ #getVisibleChoices() {
628
+ const maxVisible = this.options.maxVisible || 8;
629
+ let startIndex = Math.min(this.filteredChoices.length - maxVisible, this.activeIndex - Math.floor(maxVisible / 2));
630
+ if (startIndex < 0) {
631
+ startIndex = 0;
632
+ }
633
+ const endIndex = Math.min(startIndex + maxVisible, this.filteredChoices.length);
634
+ return { startIndex, endIndex };
635
+ }
636
+ #showChoices() {
637
+ const { startIndex, endIndex } = this.#getVisibleChoices();
638
+ this.lastRender = { startIndex, endIndex };
639
+ if (this.options.autocomplete) {
640
+ this.write(`${SYMBOLS.Pointer} ${this.autocompleteValue}${EOL5}`);
641
+ }
642
+ for (let choiceIndex = startIndex; choiceIndex < endIndex; choiceIndex++) {
643
+ const choice = this.#getFormattedChoice(choiceIndex);
644
+ const isChoiceActive = choiceIndex === this.activeIndex;
645
+ const isChoiceSelected = this.selectedIndexes.includes(choiceIndex);
646
+ const showPreviousChoicesArrow = startIndex > 0 && choiceIndex === startIndex;
647
+ const showNextChoicesArrow = endIndex < this.filteredChoices.length && choiceIndex === endIndex - 1;
648
+ let prefixArrow = " ";
649
+ if (showPreviousChoicesArrow) {
650
+ prefixArrow = SYMBOLS.Previous + " ";
651
+ } else if (showNextChoicesArrow) {
652
+ prefixArrow = SYMBOLS.Next + " ";
653
+ }
654
+ const prefix = `${prefixArrow}${isChoiceSelected ? SYMBOLS.Active : SYMBOLS.Inactive}`;
655
+ const formattedLabel = choice.label.padEnd(
656
+ this.longestChoice < 10 ? this.longestChoice : 0
657
+ );
658
+ const formattedDescription = choice.description ? ` - ${choice.description}` : "";
659
+ const color = isChoiceActive ? kleur5.white().bold : kleur5.gray;
660
+ const str = `${prefix} ${color(`${formattedLabel}${formattedDescription}`)}${EOL5}`;
661
+ this.write(str);
662
+ }
663
+ }
664
+ #showAnsweredQuestion(choices, isAgentAnswer = false) {
665
+ const prefixSymbol = this.selectedIndexes.length === 0 && !isAgentAnswer ? SYMBOLS.Cross : SYMBOLS.Tick;
666
+ const prefix = `${prefixSymbol} ${kleur5.bold(this.message)} ${SYMBOLS.Pointer}`;
667
+ const formattedChoice = kleur5.yellow(choices);
668
+ this.write(`${prefix}${choices ? ` ${formattedChoice}` : ""}${EOL5}`);
669
+ }
670
+ #onProcessExit() {
671
+ this.stdin.off("keypress", this.#boundKeyPressEvent);
672
+ this.stdout.moveCursor(-this.stdout.columns, 0);
673
+ this.stdout.clearScreenDown();
674
+ this.write(SYMBOLS.ShowCursor);
675
+ }
676
+ #onKeypress(...args) {
677
+ const [resolve, render, , key] = args;
678
+ if (key.name === "up") {
679
+ this.activeIndex = this.activeIndex === 0 ? this.filteredChoices.length - 1 : this.activeIndex - 1;
680
+ render();
681
+ } else if (key.name === "down") {
682
+ this.activeIndex = this.activeIndex === this.filteredChoices.length - 1 ? 0 : this.activeIndex + 1;
683
+ render();
684
+ } else if (key.ctrl && key.name === "a") {
685
+ this.selectedIndexes = this.selectedIndexes.length === this.filteredChoices.length ? [] : this.filteredChoices.map((_, index) => index);
686
+ render();
687
+ } else if (key.name === "right") {
688
+ this.selectedIndexes.push(this.activeIndex);
689
+ render();
690
+ } else if (key.name === "left") {
691
+ this.selectedIndexes = this.selectedIndexes.filter((index) => index !== this.activeIndex);
692
+ render();
693
+ } else if (key.name === "return") {
694
+ const labels = this.selectedIndexes.map((index) => {
695
+ const choice = this.filteredChoices[index];
696
+ return typeof choice === "string" ? choice : choice.label;
697
+ });
698
+ const values = this.selectedIndexes.map((index) => {
699
+ const choice = this.filteredChoices[index];
700
+ return typeof choice === "string" ? choice : choice.value;
701
+ });
702
+ for (const validator of this.#validators) {
703
+ if (!validator.validate(values)) {
704
+ const error = validator.error(values);
705
+ render({ error });
706
+ return;
707
+ }
708
+ }
709
+ render({ clearRender: true });
710
+ this.#showAnsweredQuestion(labels.join(", "));
711
+ this.write(SYMBOLS.ShowCursor);
712
+ this.destroy();
713
+ this.#onProcessExit();
714
+ process.off("exit", this.#boundExitEvent);
715
+ resolve(values);
716
+ } else {
717
+ if (!key.ctrl && this.options.autocomplete) {
718
+ this.selectedIndexes = [];
719
+ this.activeIndex = 0;
720
+ if (key.name === "backspace" && this.autocompleteValue.length > 0) {
721
+ this.autocompleteValue = this.autocompleteValue.slice(0, -1);
722
+ } else if (key.name !== "backspace") {
723
+ this.autocompleteValue += key.sequence;
724
+ }
725
+ }
726
+ render();
727
+ }
728
+ }
729
+ async multiselect() {
730
+ const answer = this.agent.nextAnswers.shift();
731
+ if (answer !== void 0) {
732
+ const formatedAnser = Array.isArray(answer) ? answer.join(", ") : answer;
733
+ this.#showAnsweredQuestion(formatedAnser, true);
734
+ this.destroy();
735
+ return Array.isArray(answer) ? answer : [answer];
736
+ }
737
+ this.write(SYMBOLS.HideCursor);
738
+ this.#showQuestion();
739
+ const render = (options = {}) => {
740
+ const {
741
+ initialRender = false,
742
+ clearRender = false,
743
+ error = null
744
+ } = options;
745
+ if (!initialRender) {
746
+ let linesToClear = this.lastRender.endIndex - this.lastRender.startIndex;
747
+ while (linesToClear > 0) {
748
+ this.clearLastLine();
749
+ linesToClear--;
750
+ }
751
+ if (this.options.autocomplete) {
752
+ let linesToClear2 = Math.ceil(
753
+ wcwidth4(`${SYMBOLS.Pointer} ${this.autocompleteValue}`) / this.stdout.columns
754
+ );
755
+ while (linesToClear2 > 0) {
756
+ this.clearLastLine();
757
+ linesToClear2--;
758
+ }
759
+ }
760
+ }
761
+ if (clearRender) {
762
+ const questionLineCount = Math.ceil(
763
+ wcwidth4(stripAnsi(this.questionMessage)) / this.stdout.columns
764
+ );
765
+ this.stdout.moveCursor(-this.stdout.columns, -(1 + questionLineCount));
766
+ this.stdout.clearScreenDown();
767
+ return;
768
+ }
769
+ if (error) {
770
+ const linesToClear = Math.ceil(wcwidth4(this.questionMessage) / this.stdout.columns) + 1;
771
+ this.stdout.moveCursor(0, -linesToClear);
772
+ this.stdout.clearScreenDown();
773
+ this.#showQuestion(error);
774
+ }
775
+ this.#showChoices();
776
+ };
777
+ render({ initialRender: true });
778
+ return new Promise((resolve) => {
779
+ this.#boundKeyPressEvent = this.#onKeypress.bind(this, resolve, render);
780
+ this.stdin.on("keypress", this.#boundKeyPressEvent);
781
+ this.#boundExitEvent = this.#onProcessExit.bind(this);
782
+ process.once("exit", this.#boundExitEvent);
783
+ });
784
+ }
785
+ #showQuestion(error = null) {
786
+ let hint = kleur5.gray(
787
+ // eslint-disable-next-line max-len
788
+ `(Press ${kleur5.bold("<Ctrl+A>")} to toggle all, ${kleur5.bold("<Ctrl+Space>")} to select, ${kleur5.bold("<Left/Right>")} to toggle, ${kleur5.bold("<Return>")} to submit)`
789
+ );
790
+ if (error) {
791
+ hint += ` ${kleur5.red().bold(`[${error}]`)}`;
792
+ }
793
+ this.questionMessage = `${SYMBOLS.QuestionMark} ${kleur5.bold(this.message)} ${hint}`;
794
+ this.write(`${this.questionMessage}${EOL5}`);
795
+ }
796
+ };
797
+
798
+ // src/validators.ts
799
+ function required() {
800
+ return {
801
+ validate: (input) => Array.isArray(input) ? input.length > 0 : Boolean(input),
802
+ error: () => "required"
803
+ };
804
+ }
805
+
806
+ // index.ts
807
+ async function question(message, options = {}) {
808
+ const questionPrompt = new QuestionPrompt(message, options);
809
+ return questionPrompt.question();
810
+ }
811
+ async function select(message, options) {
812
+ const selectPrompt = new SelectPrompt(message, options);
813
+ return selectPrompt.select();
814
+ }
815
+ async function confirm(message, options) {
816
+ const confirmPrompt = new ConfirmPrompt(message, options);
817
+ return confirmPrompt.confirm();
818
+ }
819
+ async function multiselect(message, options) {
820
+ const multiselectPrompt = new MultiselectPrompt(message, options);
821
+ return multiselectPrompt.multiselect();
822
+ }
823
+ export {
824
+ PromptAgent,
825
+ confirm,
826
+ multiselect,
827
+ question,
828
+ required,
829
+ select
830
+ };