@topcli/prompts 3.0.0 → 4.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/dist/index.mjs ADDED
@@ -0,0 +1,1171 @@
1
+ import EventEmitter, { once } from "node:events";
2
+ import { EOL } from "node:os";
3
+ import readline from "node:readline";
4
+ import { Writable } from "node:stream";
5
+ import { stripVTControlCharacters, styleText } from "node:util";
6
+ import process$1 from "node:process";
7
+ //#region src/validators.ts
8
+ function required() {
9
+ return { validate: (input) => {
10
+ const isValid = Array.isArray(input) ? input.length > 0 : Boolean(input);
11
+ return isValid ? null : {
12
+ isValid,
13
+ error: "required"
14
+ };
15
+ } };
16
+ }
17
+ function isValid(result) {
18
+ if (typeof result === "object") return result?.isValid !== false;
19
+ if (typeof result === "string") return result.length === 0;
20
+ return true;
21
+ }
22
+ function isValidTransformation(result) {
23
+ return typeof result === "object" && result.isValid === true;
24
+ }
25
+ function resultError(result) {
26
+ if (typeof result === "object") return result.error;
27
+ return result;
28
+ }
29
+ //#endregion
30
+ //#region src/prompt-agent.ts
31
+ var PromptAgent = class PromptAgent {
32
+ /**
33
+ * The prompts answers queue.
34
+ * When not empty, any prompt will be answered by the first answer in this list.
35
+ */
36
+ nextAnswers = [];
37
+ static #sharedInstance;
38
+ static shared() {
39
+ this.#sharedInstance ??= new PromptAgent();
40
+ return this.#sharedInstance;
41
+ }
42
+ /**
43
+ * Programmatically set the next answer for any prompt (`question()`, `confirm()`, `select()`)
44
+ *
45
+ * This is useful for testing.
46
+ *
47
+ * @example
48
+ * ```js
49
+ * const promptAgent = PromptAgent.shared();
50
+ * promptAgent.nextAnswer("toto");
51
+ *
52
+ * const input = await question("what is your name?");
53
+ * assert.equal(input, "toto");
54
+ * ```
55
+ */
56
+ nextAnswer(value) {
57
+ if (Array.isArray(value)) this.nextAnswers.push(...value);
58
+ else this.nextAnswers.push(value);
59
+ }
60
+ clear() {
61
+ this.nextAnswers = [];
62
+ }
63
+ };
64
+ //#endregion
65
+ //#region src/transformers.ts
66
+ function number() {
67
+ return { transform(input) {
68
+ if (input.trim() === "") return {
69
+ isValid: false,
70
+ error: "not a number"
71
+ };
72
+ const parsed = Number(input.replace(",", "."));
73
+ if (Number.isNaN(parsed)) return {
74
+ isValid: false,
75
+ error: "not a number"
76
+ };
77
+ return {
78
+ isValid: true,
79
+ transformed: parsed
80
+ };
81
+ } };
82
+ }
83
+ function integer() {
84
+ return { transform(input) {
85
+ if (input.trim() === "") return {
86
+ isValid: false,
87
+ error: "not an integer"
88
+ };
89
+ const parsed = Number(input);
90
+ if (Number.isNaN(parsed) || !Number.isInteger(parsed)) return {
91
+ isValid: false,
92
+ error: "not an integer"
93
+ };
94
+ return {
95
+ isValid: true,
96
+ transformed: parsed
97
+ };
98
+ } };
99
+ }
100
+ function url() {
101
+ return { transform(input) {
102
+ if (URL.canParse(input)) return {
103
+ isValid: true,
104
+ transformed: new URL(input)
105
+ };
106
+ try {
107
+ const parsed = new URL(`https://${input}`);
108
+ if (!parsed.hostname.includes(".") && parsed.hostname !== "localhost") return {
109
+ isValid: false,
110
+ error: "invalid URL"
111
+ };
112
+ return {
113
+ isValid: true,
114
+ transformed: parsed
115
+ };
116
+ } catch {
117
+ return {
118
+ isValid: false,
119
+ error: "invalid URL"
120
+ };
121
+ }
122
+ } };
123
+ }
124
+ //#endregion
125
+ //#region src/errors/abort.ts
126
+ var AbortError = class extends Error {
127
+ constructor(message) {
128
+ super(message);
129
+ this.name = "AbortError";
130
+ }
131
+ };
132
+ //#endregion
133
+ //#region src/prompts/abstract.ts
134
+ function kNoopTransformer(input) {
135
+ return input;
136
+ }
137
+ var AbstractPrompt = class AbstractPrompt extends EventEmitter {
138
+ stdin;
139
+ stdout;
140
+ message;
141
+ signal;
142
+ skip;
143
+ history;
144
+ agent;
145
+ transformer = kNoopTransformer;
146
+ rl;
147
+ #signalHandler;
148
+ constructor(options) {
149
+ super();
150
+ if (this.constructor === AbstractPrompt) throw new Error("AbstractPrompt can't be instantiated.");
151
+ const { stdin: input = process.stdin, stdout: output = process.stdout, message, signal, skip = false, agent = PromptAgent.shared() } = options;
152
+ if (typeof message !== "string") throw new TypeError(`message must be string, ${typeof message} given.`);
153
+ if (!output.isTTY) Object.assign(output, {
154
+ moveCursor: () => void 0,
155
+ clearScreenDown: () => void 0
156
+ });
157
+ this.stdin = input;
158
+ this.stdout = output;
159
+ this.message = message;
160
+ this.signal = signal;
161
+ this.skip = skip;
162
+ this.history = [];
163
+ this.agent = agent;
164
+ if (this.stdout.isTTY) this.stdin.setRawMode(true);
165
+ this.rl = readline.createInterface({
166
+ input,
167
+ output: new Writable({ write: (chunk, encoding, callback) => {
168
+ if (chunk) {
169
+ const transformed = this.transformer(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
170
+ if (transformed !== null) this.stdout.write(transformed, encoding);
171
+ }
172
+ callback();
173
+ } }),
174
+ terminal: true
175
+ });
176
+ if (this.signal) {
177
+ this.#signalHandler = () => {
178
+ this.rl.close();
179
+ for (let i = 0; i < this.history.length; i++) this.clearLastLine();
180
+ this.emit("error", new AbortError("Prompt aborted"));
181
+ };
182
+ if (this.signal.aborted) this.#signalHandler();
183
+ this.signal.addEventListener("abort", this.#signalHandler, { once: true });
184
+ }
185
+ }
186
+ reset() {
187
+ this.transformer = kNoopTransformer;
188
+ }
189
+ write(data) {
190
+ const formattedData = stripVTControlCharacters(data).replace(EOL, "");
191
+ if (formattedData) this.history.push(formattedData);
192
+ return this.stdout.write(data);
193
+ }
194
+ clearLastLine() {
195
+ const lastLine = this.history.pop();
196
+ if (!lastLine) return;
197
+ const lastLineRows = Math.ceil(stripVTControlCharacters(lastLine).length / this.stdout.columns);
198
+ this.stdout.moveCursor(-this.stdout.columns, -lastLineRows);
199
+ this.stdout.clearScreenDown();
200
+ }
201
+ destroy() {
202
+ this.rl.close();
203
+ if (this.signal) this.signal.removeEventListener("abort", this.#signalHandler);
204
+ }
205
+ };
206
+ //#endregion
207
+ //#region src/utils.ts
208
+ function isSeparator(choice) {
209
+ return typeof choice === "object" && choice !== null && choice.type === "separator";
210
+ }
211
+ const kLenSegmenter = new Intl.Segmenter();
212
+ /**
213
+ * @see https://github.com/sindresorhus/is-unicode-supported
214
+ */
215
+ function isUnicodeSupported() {
216
+ if (process$1.platform !== "win32") return process$1.env.TERM !== "linux";
217
+ return Boolean(process$1.env.WT_SESSION) || Boolean(process$1.env.TERMINUS_SUBLIME) || process$1.env.ConEmuTask === "{cmd::Cmder}" || process$1.env.TERM_PROGRAM === "Terminus-Sublime" || process$1.env.TERM_PROGRAM === "vscode" || process$1.env.TERM === "xterm-256color" || process$1.env.TERM === "alacritty" || process$1.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
218
+ }
219
+ function stringLength(string) {
220
+ if (string === "") return 0;
221
+ let length = 0;
222
+ for (const _ of kLenSegmenter.segment(stripVTControlCharacters(string))) length++;
223
+ return length;
224
+ }
225
+ //#endregion
226
+ //#region src/constants.ts
227
+ const kSymbols = isUnicodeSupported() || process.env.CI ? {
228
+ tick: "✔",
229
+ cross: "✖",
230
+ pointer: "›",
231
+ previous: "⭡",
232
+ next: "⭣",
233
+ active: "●",
234
+ inactive: "○",
235
+ separator: "─"
236
+ } : {
237
+ tick: "√",
238
+ cross: "×",
239
+ pointer: ">",
240
+ previous: "↑",
241
+ next: "↓",
242
+ active: "(+)",
243
+ inactive: "(-)",
244
+ separator: "-"
245
+ };
246
+ const kPointer = styleText("gray", kSymbols.pointer);
247
+ const SYMBOLS = {
248
+ QuestionMark: styleText(["blue", "bold"], "?"),
249
+ Tick: styleText(["green", "bold"], kSymbols.tick),
250
+ Cross: styleText(["red", "bold"], kSymbols.cross),
251
+ Pointer: kPointer,
252
+ Previous: kSymbols.previous,
253
+ Next: kSymbols.next,
254
+ ShowCursor: "\x1B[?25h",
255
+ HideCursor: "\x1B[?25l",
256
+ Active: styleText("cyan", kSymbols.active),
257
+ Inactive: styleText("gray", kSymbols.inactive),
258
+ SeparatorLine: kSymbols.separator
259
+ };
260
+ //#endregion
261
+ //#region src/prompts/question.ts
262
+ var QuestionPrompt = class extends AbstractPrompt {
263
+ defaultValue;
264
+ hint;
265
+ tip;
266
+ questionSuffixError;
267
+ answer;
268
+ answerBuffer;
269
+ #validators;
270
+ #transformer;
271
+ #transformedAnswer;
272
+ #secure;
273
+ #securePlaceholder = null;
274
+ constructor(options) {
275
+ const { defaultValue, hint, validators = [], transformer, secure = false, ...baseOptions } = options;
276
+ super({ ...baseOptions });
277
+ if (validators.length > 0 && transformer !== void 0) throw new Error("validators and transformer are mutually exclusive");
278
+ if (defaultValue && typeof defaultValue !== "string") throw new TypeError("defaultValue must be a string");
279
+ this.defaultValue = defaultValue;
280
+ this.hint = hint;
281
+ this.tip = this.defaultValue ? ` (${this.defaultValue})` : "";
282
+ this.#validators = validators;
283
+ this.#transformer = transformer;
284
+ if (typeof secure === "object") {
285
+ this.#secure = true;
286
+ this.#securePlaceholder = secure.placeholder;
287
+ } else this.#secure = Boolean(secure);
288
+ this.questionSuffixError = "";
289
+ }
290
+ get formattedHint() {
291
+ return this.hint ? styleText("gray", this.hint) : "";
292
+ }
293
+ #question() {
294
+ const { resolve, promise } = Promise.withResolvers();
295
+ const questionQuery = this.#getQuestionQuery();
296
+ this.history.push(questionQuery);
297
+ this.rl.question(questionQuery, (answer) => {
298
+ this.history.push(questionQuery + answer);
299
+ this.reset();
300
+ resolve(answer);
301
+ });
302
+ if (this.#securePlaceholder !== null) this.transformer = (input) => Buffer.from(this.#securePlaceholder.repeat(input.length), "utf-8");
303
+ return promise;
304
+ }
305
+ #getQuestionQuery() {
306
+ const hintPart = this.formattedHint ? ` ${this.formattedHint}` : "";
307
+ return `${styleText("bold", `${SYMBOLS.QuestionMark} ${this.message}${this.tip}`)}${hintPart} ${this.questionSuffixError}`;
308
+ }
309
+ #setQuestionSuffixError(error) {
310
+ const suffix = styleText("red", `[${error}] `);
311
+ this.questionSuffixError = suffix;
312
+ }
313
+ #writeAnswer() {
314
+ const prefix = this.answer ? SYMBOLS.Tick : SYMBOLS.Cross;
315
+ const answer = this.answer ?? "";
316
+ const maskedAnswer = this.#securePlaceholder ? this.#securePlaceholder.repeat(answer.length) : answer;
317
+ const stylizedAnswer = styleText("yellow", this.#secure && this.#securePlaceholder === null ? "CONFIDENTIAL" : maskedAnswer);
318
+ this.write(`${prefix} ${styleText("bold", this.message)} ${SYMBOLS.Pointer} ${stylizedAnswer}${EOL}`);
319
+ }
320
+ #getValidatingQuery(dotCount) {
321
+ return `${styleText("bold", `${SYMBOLS.QuestionMark} ${this.message}${this.tip}`)}${this.formattedHint ? ` ${this.formattedHint}` : ""} ${styleText("yellow", `[validating${".".repeat(dotCount)}]`)}${EOL}`;
322
+ }
323
+ async #runTransformer() {
324
+ const result = this.#transformer.transform(this.answer);
325
+ if (result instanceof Promise) {
326
+ let dotCount = 1;
327
+ this.write(this.#getValidatingQuery(dotCount));
328
+ const spinnerInterval = setInterval(() => {
329
+ dotCount = dotCount % 3 + 1;
330
+ this.clearLastLine();
331
+ this.write(this.#getValidatingQuery(dotCount));
332
+ }, 300);
333
+ try {
334
+ return await result;
335
+ } finally {
336
+ clearInterval(spinnerInterval);
337
+ this.clearLastLine();
338
+ }
339
+ }
340
+ return result;
341
+ }
342
+ async #onQuestionAnswer() {
343
+ const questionLineCount = Math.ceil(stringLength(this.#getQuestionQuery() + this.answer) / this.stdout.columns);
344
+ this.stdout.moveCursor(-this.stdout.columns, -questionLineCount);
345
+ this.stdout.clearScreenDown();
346
+ if (this.#transformer) {
347
+ const result = await this.#runTransformer();
348
+ if (isValidTransformation(result) === false) {
349
+ this.#setQuestionSuffixError(resultError(result));
350
+ this.answerBuffer = this.#question();
351
+ return;
352
+ }
353
+ this.#transformedAnswer = result.transformed;
354
+ this.answerBuffer = void 0;
355
+ this.#writeAnswer();
356
+ return;
357
+ }
358
+ for (const validator of this.#validators) {
359
+ let validationResult;
360
+ const result = validator.validate(this.answer);
361
+ if (result instanceof Promise) {
362
+ let dotCount = 1;
363
+ this.write(this.#getValidatingQuery(dotCount));
364
+ const spinnerInterval = setInterval(() => {
365
+ dotCount = dotCount % 3 + 1;
366
+ this.clearLastLine();
367
+ this.write(this.#getValidatingQuery(dotCount));
368
+ }, 300);
369
+ try {
370
+ validationResult = await result;
371
+ } finally {
372
+ clearInterval(spinnerInterval);
373
+ this.clearLastLine();
374
+ }
375
+ } else validationResult = result;
376
+ if (isValid(validationResult) === false) {
377
+ this.#setQuestionSuffixError(resultError(validationResult));
378
+ this.answerBuffer = this.#question();
379
+ return;
380
+ }
381
+ }
382
+ this.answerBuffer = void 0;
383
+ this.#writeAnswer();
384
+ }
385
+ async listen() {
386
+ if (this.skip) {
387
+ this.destroy();
388
+ if (this.#transformer) {
389
+ const rawValue = this.defaultValue ?? "";
390
+ const result = await this.#transformer.transform(rawValue);
391
+ if (isValidTransformation(result) === false) throw new Error(`Transformer failed for default value "${rawValue}": ${resultError(result)}`);
392
+ return result.transformed;
393
+ }
394
+ return this.defaultValue ?? "";
395
+ }
396
+ const agentAnswer = this.agent.nextAnswers.shift();
397
+ if (agentAnswer !== void 0) {
398
+ this.answer = agentAnswer;
399
+ this.#writeAnswer();
400
+ this.destroy();
401
+ if (this.#transformer) {
402
+ const result = await this.#transformer.transform(agentAnswer);
403
+ if (isValidTransformation(result) === false) throw new Error(`(PromptAgent) transformer failed for answer "${agentAnswer}": ${resultError(result)}`);
404
+ return result.transformed;
405
+ }
406
+ return this.answer;
407
+ }
408
+ this.answer = await this.#question();
409
+ if (this.answer === "" && this.defaultValue) this.answer = this.defaultValue;
410
+ await this.#onQuestionAnswer();
411
+ while (this.answerBuffer !== void 0) {
412
+ this.answer = await this.answerBuffer;
413
+ await this.#onQuestionAnswer();
414
+ }
415
+ this.destroy();
416
+ return this.#transformedAnswer ?? this.answer;
417
+ }
418
+ };
419
+ //#endregion
420
+ //#region src/prompts/confirm.ts
421
+ const kToggleKeys = /* @__PURE__ */ new Set([
422
+ "left",
423
+ "right",
424
+ "tab",
425
+ "q",
426
+ "a",
427
+ "d",
428
+ "h",
429
+ "j",
430
+ "k",
431
+ "l",
432
+ "space"
433
+ ]);
434
+ var ConfirmPrompt = class extends AbstractPrompt {
435
+ initial;
436
+ selectedValue;
437
+ fastAnswer;
438
+ #boundKeyPressEvent;
439
+ #boundExitEvent;
440
+ constructor(options) {
441
+ const { initial = false, ...baseOptions } = options;
442
+ super({ ...baseOptions });
443
+ this.initial = initial;
444
+ this.selectedValue = initial;
445
+ }
446
+ #getHint() {
447
+ const Yes = styleText([
448
+ "cyan",
449
+ "bold",
450
+ "underline"
451
+ ], "Yes");
452
+ const No = styleText([
453
+ "cyan",
454
+ "bold",
455
+ "underline"
456
+ ], "No");
457
+ return this.selectedValue ? `${Yes}/No` : `Yes/${No}`;
458
+ }
459
+ #render() {
460
+ this.write(this.#getQuestionQuery());
461
+ }
462
+ #onKeypress(resolve, _value, key) {
463
+ this.stdout.moveCursor(-this.stdout.columns, -Math.floor(stringLength(this.#getQuestionQuery()) / this.stdout.columns));
464
+ this.stdout.clearScreenDown();
465
+ if (key.name === "return") {
466
+ resolve(this.selectedValue);
467
+ return;
468
+ }
469
+ if (kToggleKeys.has(key.name ?? "")) this.selectedValue = !this.selectedValue;
470
+ if (key.name === "y") {
471
+ this.selectedValue = true;
472
+ resolve(true);
473
+ this.fastAnswer = true;
474
+ } else if (key.name === "n") {
475
+ this.selectedValue = false;
476
+ resolve(false);
477
+ this.fastAnswer = true;
478
+ }
479
+ if (!this.fastAnswer) this.#render();
480
+ }
481
+ #onProcessExit() {
482
+ this.stdin.off("keypress", this.#boundKeyPressEvent);
483
+ }
484
+ #getQuestionQuery() {
485
+ return `${styleText("bold", `${SYMBOLS.QuestionMark} ${this.message}`)} ${this.#getHint()}`;
486
+ }
487
+ #onQuestionAnswer() {
488
+ this.clearLastLine();
489
+ this.stdout.moveCursor(-this.stdout.columns, -Math.floor(stringLength(this.#getQuestionQuery()) / this.stdout.columns));
490
+ this.stdout.clearScreenDown();
491
+ this.write(`${this.selectedValue ? SYMBOLS.Tick : SYMBOLS.Cross} ${styleText("bold", this.message)}${EOL}`);
492
+ }
493
+ async listen() {
494
+ if (this.skip) {
495
+ this.destroy();
496
+ return this.initial;
497
+ }
498
+ const answer = this.agent.nextAnswers.shift();
499
+ if (answer !== void 0) {
500
+ this.selectedValue = answer;
501
+ this.#onQuestionAnswer();
502
+ this.destroy();
503
+ return answer;
504
+ }
505
+ this.write(SYMBOLS.HideCursor);
506
+ try {
507
+ const { resolve, promise } = Promise.withResolvers();
508
+ const questionQuery = this.#getQuestionQuery();
509
+ this.write(questionQuery);
510
+ this.#boundKeyPressEvent = this.#onKeypress.bind(this, resolve);
511
+ this.stdin.on("keypress", this.#boundKeyPressEvent);
512
+ this.#boundExitEvent = this.#onProcessExit.bind(this);
513
+ process.once("exit", this.#boundExitEvent);
514
+ await promise;
515
+ this.#onQuestionAnswer();
516
+ } finally {
517
+ this.write(SYMBOLS.ShowCursor);
518
+ this.#onProcessExit();
519
+ process.off("exit", this.#boundExitEvent);
520
+ this.destroy();
521
+ }
522
+ return this.selectedValue;
523
+ }
524
+ };
525
+ //#endregion
526
+ //#region src/prompts/select.ts
527
+ const kRequiredChoiceProperties$1 = ["label", "value"];
528
+ var SelectPrompt = class extends AbstractPrompt {
529
+ #boundExitEvent = () => void 0;
530
+ #boundKeyPressEvent = () => void 0;
531
+ #validators;
532
+ #isValidating = false;
533
+ activeIndex = 0;
534
+ questionMessage;
535
+ autocompleteValue = "";
536
+ options;
537
+ lastRender;
538
+ get choices() {
539
+ return this.options.choices;
540
+ }
541
+ get filteredChoices() {
542
+ if (!(this.options.autocomplete && this.autocompleteValue.length > 0)) return this.choices;
543
+ const isCaseSensitive = this.options.caseSensitive;
544
+ const autocompleteValue = isCaseSensitive ? this.autocompleteValue : this.autocompleteValue.toLowerCase();
545
+ return this.choices.filter((choice) => !isSeparator(choice) && this.#filterChoice(choice, autocompleteValue, isCaseSensitive));
546
+ }
547
+ #filterChoice(choice, autocompleteValue, isCaseSensitive = false) {
548
+ const choiceValue = typeof choice === "string" ? isCaseSensitive ? choice : choice.toLowerCase() : isCaseSensitive ? choice.label : choice.label.toLowerCase();
549
+ if (autocompleteValue.includes(" ")) return this.#filterMultipleWords(choiceValue, autocompleteValue, isCaseSensitive);
550
+ return choiceValue.includes(autocompleteValue);
551
+ }
552
+ #filterMultipleWords(choiceValue, autocompleteValue, isCaseSensitive) {
553
+ return autocompleteValue.split(" ").every((word) => {
554
+ const wordValue = isCaseSensitive ? word : word.toLowerCase();
555
+ return choiceValue.includes(wordValue) || choiceValue.includes(autocompleteValue);
556
+ });
557
+ }
558
+ #isChoiceDisabled(choice) {
559
+ return typeof choice !== "string" && Boolean(choice.disabled);
560
+ }
561
+ #findNextEnabledIndex(from, direction) {
562
+ const total = this.filteredChoices.length;
563
+ if (total === 0) return from;
564
+ let index = (from + direction + total) % total;
565
+ while (index !== from) {
566
+ const choice = this.filteredChoices[index];
567
+ if (!isSeparator(choice) && !this.#isChoiceDisabled(choice)) return index;
568
+ index = (index + direction + total) % total;
569
+ }
570
+ return from;
571
+ }
572
+ #findFirstEnabledIndex() {
573
+ const index = this.filteredChoices.findIndex((choice) => !isSeparator(choice) && !this.#isChoiceDisabled(choice));
574
+ return index === -1 ? 0 : index;
575
+ }
576
+ get longestChoice() {
577
+ const selectableChoices = this.filteredChoices.filter((choice) => !isSeparator(choice));
578
+ if (selectableChoices.length === 0) return 0;
579
+ return Math.max(...selectableChoices.map((choice) => {
580
+ if (typeof choice === "string") return choice.length;
581
+ return choice.label.length;
582
+ }));
583
+ }
584
+ constructor(options) {
585
+ const { choices, validators = [], ...baseOptions } = options;
586
+ super({ ...baseOptions });
587
+ this.options = options;
588
+ if (!choices?.length) {
589
+ this.destroy();
590
+ throw new TypeError("Missing required param: choices");
591
+ }
592
+ this.#validators = validators;
593
+ for (const choice of choices) {
594
+ if (typeof choice === "string" || isSeparator(choice)) continue;
595
+ for (const prop of kRequiredChoiceProperties$1) if (!choice[prop]) {
596
+ this.destroy();
597
+ throw new TypeError(`Missing ${prop} for choice ${JSON.stringify(choice)}`);
598
+ }
599
+ }
600
+ if (choices.findIndex((choice) => !isSeparator(choice)) === -1) {
601
+ this.destroy();
602
+ throw new TypeError("choices must contain at least one non-separator item");
603
+ }
604
+ this.activeIndex = this.#findFirstEnabledIndex();
605
+ }
606
+ #getFormattedChoice(choiceIndex) {
607
+ const choice = this.filteredChoices[choiceIndex];
608
+ if (typeof choice === "string") return {
609
+ value: choice,
610
+ label: choice
611
+ };
612
+ return choice;
613
+ }
614
+ #getVisibleChoices() {
615
+ const maxVisible = this.options.maxVisible || 8;
616
+ let startIndex = Math.min(this.filteredChoices.length - maxVisible, this.activeIndex - Math.floor(maxVisible / 2));
617
+ if (startIndex < 0) startIndex = 0;
618
+ const endIndex = Math.min(startIndex + maxVisible, this.filteredChoices.length);
619
+ return {
620
+ startIndex,
621
+ endIndex
622
+ };
623
+ }
624
+ #showChoices() {
625
+ const { startIndex, endIndex } = this.#getVisibleChoices();
626
+ this.lastRender = {
627
+ startIndex,
628
+ endIndex
629
+ };
630
+ if (this.options.autocomplete) this.write(`${SYMBOLS.Pointer} ${this.autocompleteValue}${EOL}`);
631
+ for (let choiceIndex = startIndex; choiceIndex < endIndex; choiceIndex++) {
632
+ const rawChoice = this.filteredChoices[choiceIndex];
633
+ if (isSeparator(rawChoice)) {
634
+ const separatorLabel = rawChoice.label ? ` ${rawChoice.label} ` : "";
635
+ this.write(` ${styleText("gray", `${SYMBOLS.SeparatorLine}${SYMBOLS.SeparatorLine}${separatorLabel}${SYMBOLS.SeparatorLine}${SYMBOLS.SeparatorLine}`)}${EOL}`);
636
+ continue;
637
+ }
638
+ const formattedChoice = this.#getFormattedChoice(choiceIndex);
639
+ const isChoiceSelected = choiceIndex === this.activeIndex;
640
+ const isChoiceDisabled = this.#isChoiceDisabled(rawChoice);
641
+ const showPreviousChoicesArrow = startIndex > 0 && choiceIndex === startIndex;
642
+ const showNextChoicesArrow = endIndex < this.filteredChoices.length && choiceIndex === endIndex - 1;
643
+ let prefixArrow = " ";
644
+ if (showPreviousChoicesArrow) prefixArrow = SYMBOLS.Previous;
645
+ else if (showNextChoicesArrow) prefixArrow = SYMBOLS.Next;
646
+ const prefix = isChoiceDisabled ? `${prefixArrow} ` : `${prefixArrow}${isChoiceSelected ? `${SYMBOLS.Pointer} ` : " "}`;
647
+ const formattedLabel = formattedChoice.label.padEnd(this.longestChoice < 10 ? this.longestChoice : 0);
648
+ const formattedDescription = formattedChoice.description ? ` - ${formattedChoice.description}` : "";
649
+ const disabledMessage = isChoiceDisabled && typeof rawChoice !== "string" && typeof rawChoice.disabled === "string" ? ` [${rawChoice.disabled}]` : "";
650
+ let textStyles;
651
+ if (isChoiceDisabled) textStyles = ["gray", "dim"];
652
+ else if (isChoiceSelected) textStyles = ["white", "bold"];
653
+ else textStyles = ["gray"];
654
+ const str = `${prefix}${styleText(textStyles, `${formattedLabel}${formattedDescription}${disabledMessage}`)}${EOL}`;
655
+ this.write(str);
656
+ }
657
+ }
658
+ async #handleReturn(resolve, render) {
659
+ const activeChoice = this.filteredChoices[this.activeIndex];
660
+ if (isSeparator(activeChoice)) return;
661
+ if (activeChoice !== void 0 && this.#isChoiceDisabled(activeChoice)) return;
662
+ this.#isValidating = true;
663
+ try {
664
+ const choice = activeChoice ?? "";
665
+ const label = typeof choice === "string" ? choice : choice.label;
666
+ const value = typeof choice === "string" ? choice : choice.value;
667
+ for (const validator of this.#validators) {
668
+ let validationResult;
669
+ const result = validator.validate(value);
670
+ if (result instanceof Promise) {
671
+ let dotCount = 1;
672
+ render({ validating: `validating${".".repeat(dotCount)}` });
673
+ const spinnerInterval = setInterval(() => {
674
+ dotCount = dotCount % 3 + 1;
675
+ render({ validating: `validating${".".repeat(dotCount)}` });
676
+ }, 300);
677
+ try {
678
+ validationResult = await result;
679
+ } finally {
680
+ clearInterval(spinnerInterval);
681
+ }
682
+ } else validationResult = result;
683
+ if (isValid(validationResult) === false) {
684
+ render({ error: resultError(validationResult) });
685
+ return;
686
+ }
687
+ }
688
+ render({ clearRender: true });
689
+ if (!this.options.ignoreValues?.includes(value)) this.#showAnsweredQuestion(label);
690
+ this.write(SYMBOLS.ShowCursor);
691
+ this.destroy();
692
+ this.#onProcessExit();
693
+ process.off("exit", this.#boundExitEvent);
694
+ resolve(value);
695
+ } finally {
696
+ this.#isValidating = false;
697
+ }
698
+ }
699
+ #showAnsweredQuestion(label) {
700
+ const prefix = `${label === "" ? SYMBOLS.Cross : SYMBOLS.Tick} ${styleText("bold", this.message)} ${SYMBOLS.Pointer}`;
701
+ const formattedChoice = styleText("yellow", label);
702
+ this.write(`${prefix} ${formattedChoice}${EOL}`);
703
+ }
704
+ #onProcessExit() {
705
+ this.stdin.off("keypress", this.#boundKeyPressEvent);
706
+ this.stdout.moveCursor(-this.stdout.columns, 0);
707
+ this.stdout.clearScreenDown();
708
+ this.write(SYMBOLS.ShowCursor);
709
+ }
710
+ #onKeypress(...args) {
711
+ const [resolve, render, , key] = args;
712
+ if (this.#isValidating) return;
713
+ if (key.name === "up") {
714
+ this.activeIndex = this.#findNextEnabledIndex(this.activeIndex, -1);
715
+ render();
716
+ } else if (key.name === "down") {
717
+ this.activeIndex = this.#findNextEnabledIndex(this.activeIndex, 1);
718
+ render();
719
+ } else if (key.name === "return") this.#handleReturn(resolve, render);
720
+ else {
721
+ if (!key.ctrl && this.options.autocomplete) {
722
+ this.activeIndex = this.#findFirstEnabledIndex();
723
+ if (key.name === "backspace" && this.autocompleteValue.length > 0) this.autocompleteValue = this.autocompleteValue.slice(0, -1);
724
+ else if (key.name !== "backspace") this.autocompleteValue += key.sequence;
725
+ }
726
+ render();
727
+ }
728
+ }
729
+ async listen() {
730
+ if (this.skip) {
731
+ this.destroy();
732
+ const firstSelectable = this.filteredChoices.find((choice) => !isSeparator(choice));
733
+ return typeof firstSelectable === "string" ? firstSelectable : firstSelectable?.value ?? "";
734
+ }
735
+ const answer = this.agent.nextAnswers.shift();
736
+ if (answer !== void 0) {
737
+ this.#showAnsweredQuestion(answer);
738
+ this.destroy();
739
+ return answer;
740
+ }
741
+ this.transformer = () => null;
742
+ this.write(SYMBOLS.HideCursor);
743
+ this.#showQuestion();
744
+ const render = (options = {}) => {
745
+ const { initialRender = false, clearRender = false, error = null, validating = null } = options;
746
+ if (!initialRender) {
747
+ let linesToClear = this.lastRender.endIndex - this.lastRender.startIndex;
748
+ while (linesToClear > 0) {
749
+ this.clearLastLine();
750
+ linesToClear--;
751
+ }
752
+ if (this.options.autocomplete) {
753
+ let linesToClear = Math.ceil(stringLength(`${SYMBOLS.Pointer} ${this.autocompleteValue}`) / this.stdout.columns);
754
+ while (linesToClear > 0) {
755
+ this.clearLastLine();
756
+ linesToClear--;
757
+ }
758
+ }
759
+ }
760
+ if (clearRender) {
761
+ this.clearLastLine();
762
+ return;
763
+ }
764
+ if (error || validating) {
765
+ this.clearLastLine();
766
+ this.#showQuestion(error, validating);
767
+ }
768
+ this.#showChoices();
769
+ };
770
+ render({ initialRender: true });
771
+ this.#boundExitEvent = this.#onProcessExit.bind(this);
772
+ process.once("exit", this.#boundExitEvent);
773
+ const { resolve, promise } = Promise.withResolvers();
774
+ this.#boundKeyPressEvent = this.#onKeypress.bind(this, resolve, render);
775
+ this.stdin.on("keypress", this.#boundKeyPressEvent);
776
+ return promise;
777
+ }
778
+ #showQuestion(error = null, validating = null) {
779
+ let hint = "";
780
+ if (validating) hint = styleText("yellow", `[${validating}]`);
781
+ else if (error) hint += `${hint.length > 0 ? " " : ""}${styleText(["red", "bold"], `[${error}]`)}`;
782
+ this.questionMessage = `${SYMBOLS.QuestionMark} ${styleText("bold", this.message)}${hint.length > 0 ? ` ${hint}` : ""}`;
783
+ this.write(`${this.questionMessage}${EOL}`);
784
+ }
785
+ };
786
+ //#endregion
787
+ //#region src/prompts/multiselect.ts
788
+ const kRequiredChoiceProperties = ["label", "value"];
789
+ var MultiselectPrompt = class extends AbstractPrompt {
790
+ #boundExitEvent = () => void 0;
791
+ #boundKeyPressEvent = () => void 0;
792
+ #validators;
793
+ #showHint;
794
+ #isValidating = false;
795
+ activeIndex = 0;
796
+ selectedIndexes = /* @__PURE__ */ new Set();
797
+ questionMessage;
798
+ autocompleteValue = "";
799
+ options;
800
+ lastRender;
801
+ get choices() {
802
+ return this.options.choices;
803
+ }
804
+ get filteredChoices() {
805
+ if (!(this.options.autocomplete && this.autocompleteValue.length > 0)) return this.choices;
806
+ const isCaseSensitive = this.options.caseSensitive;
807
+ const autocompleteValue = isCaseSensitive ? this.autocompleteValue : this.autocompleteValue.toLowerCase();
808
+ return this.choices.filter((choice) => !isSeparator(choice) && this.#filterChoice(choice, autocompleteValue, isCaseSensitive));
809
+ }
810
+ #filterChoice(choice, autocompleteValue, isCaseSensitive = false) {
811
+ const choiceValue = typeof choice === "string" ? isCaseSensitive ? choice : choice.toLowerCase() : isCaseSensitive ? choice.label : choice.label.toLowerCase();
812
+ if (autocompleteValue.includes(" ")) return this.#filterMultipleWords(choiceValue, autocompleteValue, isCaseSensitive);
813
+ return choiceValue.includes(autocompleteValue);
814
+ }
815
+ #filterMultipleWords(choiceValue, autocompleteValue, isCaseSensitive) {
816
+ return autocompleteValue.split(" ").every((word) => {
817
+ const wordValue = isCaseSensitive ? word : word.toLowerCase();
818
+ return choiceValue.includes(wordValue) || choiceValue.includes(autocompleteValue);
819
+ });
820
+ }
821
+ #isChoiceDisabled(choice) {
822
+ return typeof choice !== "string" && Boolean(choice.disabled);
823
+ }
824
+ #findNextEnabledIndex(from, direction) {
825
+ const total = this.filteredChoices.length;
826
+ if (total === 0) return from;
827
+ let index = (from + direction + total) % total;
828
+ while (index !== from) {
829
+ const choice = this.filteredChoices[index];
830
+ if (!isSeparator(choice) && !this.#isChoiceDisabled(choice)) return index;
831
+ index = (index + direction + total) % total;
832
+ }
833
+ return from;
834
+ }
835
+ #findFirstEnabledIndex() {
836
+ const index = this.filteredChoices.findIndex((choice) => !isSeparator(choice) && !this.#isChoiceDisabled(choice));
837
+ return index === -1 ? 0 : index;
838
+ }
839
+ get longestChoice() {
840
+ const selectableChoices = this.filteredChoices.filter((choice) => !isSeparator(choice));
841
+ if (selectableChoices.length === 0) return 0;
842
+ return Math.max(...selectableChoices.map((choice) => {
843
+ if (typeof choice === "string") return choice.length;
844
+ return choice.label.length;
845
+ }));
846
+ }
847
+ constructor(options) {
848
+ const { choices, preSelectedChoices = [], validators = [], showHint = true, ...baseOptions } = options;
849
+ super({ ...baseOptions });
850
+ this.options = options;
851
+ if (!choices?.length) {
852
+ this.destroy();
853
+ throw new TypeError("Missing required param: choices");
854
+ }
855
+ this.#validators = validators;
856
+ this.#showHint = showHint;
857
+ for (const choice of choices) {
858
+ if (typeof choice === "string" || isSeparator(choice)) continue;
859
+ for (const prop of kRequiredChoiceProperties) if (!choice[prop]) {
860
+ this.destroy();
861
+ throw new TypeError(`Missing ${prop} for choice ${JSON.stringify(choice)}`);
862
+ }
863
+ }
864
+ if (choices.findIndex((choice) => !isSeparator(choice)) === -1) {
865
+ this.destroy();
866
+ throw new TypeError("choices must contain at least one non-separator item");
867
+ }
868
+ this.activeIndex = this.#findFirstEnabledIndex();
869
+ for (const choice of preSelectedChoices) {
870
+ const choiceIndex = this.filteredChoices.findIndex((item) => {
871
+ if (typeof item === "string") return item === choice;
872
+ if (isSeparator(item)) return false;
873
+ return item.value === (typeof choice === "string" ? choice : choice.value);
874
+ });
875
+ if (choiceIndex === -1) {
876
+ this.destroy();
877
+ throw new Error(`Invalid pre-selected choice: ${typeof choice === "string" ? choice : choice.value}`);
878
+ }
879
+ if (this.#isChoiceDisabled(this.filteredChoices[choiceIndex])) {
880
+ this.destroy();
881
+ throw new Error(`Cannot pre-select a disabled choice: ${typeof choice === "string" ? choice : choice.value}`);
882
+ }
883
+ this.selectedIndexes.add(choiceIndex);
884
+ }
885
+ }
886
+ #getFormattedChoice(choiceIndex) {
887
+ const choice = this.filteredChoices[choiceIndex];
888
+ if (typeof choice === "string") return {
889
+ value: choice,
890
+ label: choice
891
+ };
892
+ return choice;
893
+ }
894
+ #getVisibleChoices() {
895
+ const maxVisible = this.options.maxVisible || 8;
896
+ let startIndex = Math.min(this.filteredChoices.length - maxVisible, this.activeIndex - Math.floor(maxVisible / 2));
897
+ if (startIndex < 0) startIndex = 0;
898
+ const endIndex = Math.min(startIndex + maxVisible, this.filteredChoices.length);
899
+ return {
900
+ startIndex,
901
+ endIndex
902
+ };
903
+ }
904
+ #showChoices() {
905
+ const { startIndex, endIndex } = this.#getVisibleChoices();
906
+ this.lastRender = {
907
+ startIndex,
908
+ endIndex
909
+ };
910
+ if (this.options.autocomplete) this.write(`${SYMBOLS.Pointer} ${this.autocompleteValue}${EOL}`);
911
+ for (let choiceIndex = startIndex; choiceIndex < endIndex; choiceIndex++) {
912
+ const rawChoice = this.filteredChoices[choiceIndex];
913
+ if (isSeparator(rawChoice)) {
914
+ const separatorLabel = rawChoice.label ? ` ${rawChoice.label} ` : "";
915
+ this.write(` ${styleText("gray", `${SYMBOLS.SeparatorLine}${SYMBOLS.SeparatorLine}${separatorLabel}${SYMBOLS.SeparatorLine}${SYMBOLS.SeparatorLine}`)}${EOL}`);
916
+ continue;
917
+ }
918
+ const formattedChoice = this.#getFormattedChoice(choiceIndex);
919
+ const isChoiceActive = choiceIndex === this.activeIndex;
920
+ const isChoiceSelected = this.selectedIndexes.has(choiceIndex);
921
+ const isChoiceDisabled = this.#isChoiceDisabled(rawChoice);
922
+ const showPreviousChoicesArrow = startIndex > 0 && choiceIndex === startIndex;
923
+ const showNextChoicesArrow = endIndex < this.filteredChoices.length && choiceIndex === endIndex - 1;
924
+ let prefixArrow = " ";
925
+ if (showPreviousChoicesArrow) prefixArrow = SYMBOLS.Previous + " ";
926
+ else if (showNextChoicesArrow) prefixArrow = SYMBOLS.Next + " ";
927
+ const prefix = `${prefixArrow}${isChoiceSelected ? SYMBOLS.Active : SYMBOLS.Inactive}`;
928
+ const formattedLabel = formattedChoice.label.padEnd(this.longestChoice < 10 ? this.longestChoice : 0);
929
+ const formattedDescription = formattedChoice.description ? ` - ${formattedChoice.description}` : "";
930
+ const disabledMessage = isChoiceDisabled && typeof rawChoice !== "string" && typeof rawChoice.disabled === "string" ? ` [${rawChoice.disabled}]` : "";
931
+ let textStyles;
932
+ if (isChoiceDisabled) textStyles = ["gray", "dim"];
933
+ else if (isChoiceActive) textStyles = ["white", "bold"];
934
+ else textStyles = ["gray"];
935
+ const str = `${prefix} ${styleText(textStyles, `${formattedLabel}${formattedDescription}${disabledMessage}`)}${EOL}`;
936
+ this.write(str);
937
+ }
938
+ }
939
+ async #handleReturn(resolve, render) {
940
+ this.#isValidating = true;
941
+ try {
942
+ const { values, labels } = this.#selectedChoices();
943
+ for (const validator of this.#validators) {
944
+ let validationResult;
945
+ const result = validator.validate(values);
946
+ if (result instanceof Promise) {
947
+ let dotCount = 1;
948
+ render({ validating: `validating${".".repeat(dotCount)}` });
949
+ const spinnerInterval = setInterval(() => {
950
+ dotCount = dotCount % 3 + 1;
951
+ render({ validating: `validating${".".repeat(dotCount)}` });
952
+ }, 300);
953
+ try {
954
+ validationResult = await result;
955
+ } finally {
956
+ clearInterval(spinnerInterval);
957
+ }
958
+ } else validationResult = result;
959
+ if (isValid(validationResult) === false) {
960
+ render({ error: resultError(validationResult) });
961
+ return;
962
+ }
963
+ }
964
+ render({ clearRender: true });
965
+ this.#showAnsweredQuestion(labels.join(", "));
966
+ this.write(SYMBOLS.ShowCursor);
967
+ this.destroy();
968
+ this.#onProcessExit();
969
+ process.off("exit", this.#boundExitEvent);
970
+ resolve(values);
971
+ } finally {
972
+ this.#isValidating = false;
973
+ }
974
+ }
975
+ #showAnsweredQuestion(choices, isAgentAnswer = false) {
976
+ const prefix = `${this.selectedIndexes.size === 0 && !isAgentAnswer ? SYMBOLS.Cross : SYMBOLS.Tick} ${styleText("bold", this.message)} ${SYMBOLS.Pointer}`;
977
+ const formattedChoice = styleText("yellow", choices);
978
+ this.write(`${prefix}${choices ? ` ${formattedChoice}` : ""}${EOL}`);
979
+ }
980
+ #selectedChoices() {
981
+ return [...this.selectedIndexes].reduce((acc, index) => {
982
+ const choice = this.filteredChoices[index];
983
+ if (typeof choice === "string") {
984
+ acc.values.push(choice);
985
+ acc.labels.push(choice);
986
+ } else if (!isSeparator(choice)) {
987
+ acc.values.push(choice.value);
988
+ acc.labels.push(choice.label);
989
+ }
990
+ return acc;
991
+ }, {
992
+ values: [],
993
+ labels: []
994
+ });
995
+ }
996
+ #onProcessExit() {
997
+ this.stdin.off("keypress", this.#boundKeyPressEvent);
998
+ this.stdout.moveCursor(-this.stdout.columns, 0);
999
+ this.stdout.clearScreenDown();
1000
+ this.write(SYMBOLS.ShowCursor);
1001
+ }
1002
+ #onKeypress(...args) {
1003
+ const [resolve, render, , key] = args;
1004
+ if (this.#isValidating) return;
1005
+ if (key.name === "up") {
1006
+ this.activeIndex = this.#findNextEnabledIndex(this.activeIndex, -1);
1007
+ render();
1008
+ } else if (key.name === "down") {
1009
+ this.activeIndex = this.#findNextEnabledIndex(this.activeIndex, 1);
1010
+ render();
1011
+ } else if (key.ctrl && key.name === "a") {
1012
+ const enabledIndexes = this.filteredChoices.flatMap((choice, index) => {
1013
+ if (isSeparator(choice)) return [];
1014
+ return this.#isChoiceDisabled(choice) ? [] : [index];
1015
+ });
1016
+ this.selectedIndexes = this.selectedIndexes.size === enabledIndexes.length ? /* @__PURE__ */ new Set() : new Set(enabledIndexes);
1017
+ render();
1018
+ } else if (key.name === "right") {
1019
+ const activeChoice = this.filteredChoices[this.activeIndex];
1020
+ if (!isSeparator(activeChoice) && !this.#isChoiceDisabled(activeChoice)) {
1021
+ this.selectedIndexes.add(this.activeIndex);
1022
+ render();
1023
+ }
1024
+ } else if (key.name === "left") {
1025
+ const activeChoice = this.filteredChoices[this.activeIndex];
1026
+ if (!isSeparator(activeChoice) && !this.#isChoiceDisabled(activeChoice)) {
1027
+ this.selectedIndexes = new Set([...this.selectedIndexes].filter((index) => index !== this.activeIndex));
1028
+ render();
1029
+ }
1030
+ } else if (key.name === "return") this.#handleReturn(resolve, render);
1031
+ else {
1032
+ if (!key.ctrl && this.options.autocomplete) {
1033
+ this.selectedIndexes.clear();
1034
+ this.activeIndex = this.#findFirstEnabledIndex();
1035
+ if (key.name === "backspace" && this.autocompleteValue.length > 0) this.autocompleteValue = this.autocompleteValue.slice(0, -1);
1036
+ else if (key.name !== "backspace") this.autocompleteValue += key.sequence;
1037
+ }
1038
+ render();
1039
+ }
1040
+ }
1041
+ async listen() {
1042
+ if (this.skip) {
1043
+ this.destroy();
1044
+ const { values } = this.#selectedChoices();
1045
+ return values;
1046
+ }
1047
+ const answer = this.agent.nextAnswers.shift();
1048
+ if (answer !== void 0) {
1049
+ const formatedAnser = Array.isArray(answer) ? answer.join(", ") : answer;
1050
+ this.#showAnsweredQuestion(formatedAnser, true);
1051
+ this.destroy();
1052
+ return Array.isArray(answer) ? answer : [answer];
1053
+ }
1054
+ this.transformer = () => null;
1055
+ this.write(SYMBOLS.HideCursor);
1056
+ this.#showQuestion();
1057
+ const render = (options = {}) => {
1058
+ const { initialRender = false, clearRender = false, error = null, validating = null } = options;
1059
+ if (!initialRender) {
1060
+ let linesToClear = this.lastRender.endIndex - this.lastRender.startIndex;
1061
+ while (linesToClear > 0) {
1062
+ this.clearLastLine();
1063
+ linesToClear--;
1064
+ }
1065
+ if (this.options.autocomplete) {
1066
+ let linesToClear = Math.ceil(stringLength(`${SYMBOLS.Pointer} ${this.autocompleteValue}`) / this.stdout.columns);
1067
+ while (linesToClear > 0) {
1068
+ this.clearLastLine();
1069
+ linesToClear--;
1070
+ }
1071
+ }
1072
+ }
1073
+ if (clearRender) {
1074
+ this.clearLastLine();
1075
+ return;
1076
+ }
1077
+ if (error || validating) {
1078
+ this.clearLastLine();
1079
+ this.#showQuestion(error, validating);
1080
+ }
1081
+ this.#showChoices();
1082
+ };
1083
+ render({ initialRender: true });
1084
+ this.#boundExitEvent = this.#onProcessExit.bind(this);
1085
+ process.once("exit", this.#boundExitEvent);
1086
+ const { promise, resolve } = Promise.withResolvers();
1087
+ this.#boundKeyPressEvent = this.#onKeypress.bind(this, resolve, render);
1088
+ this.stdin.on("keypress", this.#boundKeyPressEvent);
1089
+ return promise;
1090
+ }
1091
+ #showQuestion(error = null, validating = null) {
1092
+ let hint = this.#showHint ? styleText("gray", `(Press ${styleText("bold", "<Ctrl+A>")} to toggle all, ${styleText("bold", "<Left/Right>")} to toggle, ${styleText("bold", "<Return>")} to submit)`) : "";
1093
+ if (validating) hint += `${hint.length > 0 ? " " : ""}${styleText("yellow", `[${validating}]`)}`;
1094
+ else if (error) hint += `${hint.length > 0 ? " " : ""}${styleText(["red", "bold"], `[${error}]`)}`;
1095
+ this.questionMessage = `${SYMBOLS.QuestionMark} ${styleText("bold", this.message)}${hint.length > 0 ? ` ${hint}` : ""}`;
1096
+ this.write(`${this.questionMessage}${EOL}`);
1097
+ }
1098
+ };
1099
+ //#endregion
1100
+ //#region src/index.ts
1101
+ async function question(message, options = {}) {
1102
+ const prompt = new QuestionPrompt({
1103
+ ...options,
1104
+ message
1105
+ });
1106
+ const onErrorSignal = new AbortController();
1107
+ const onError = once(prompt, "error", { signal: onErrorSignal.signal });
1108
+ const result = await Promise.race([prompt.listen(), onError]);
1109
+ if (isAbortError(result)) {
1110
+ prompt.destroy();
1111
+ throw result[0];
1112
+ }
1113
+ onErrorSignal.abort();
1114
+ return result;
1115
+ }
1116
+ async function select(message, options) {
1117
+ const prompt = new SelectPrompt({
1118
+ ...options,
1119
+ message
1120
+ });
1121
+ const onErrorSignal = new AbortController();
1122
+ const onError = once(prompt, "error", { signal: onErrorSignal.signal });
1123
+ const result = await Promise.race([prompt.listen(), onError]);
1124
+ if (isAbortError(result)) {
1125
+ prompt.destroy();
1126
+ throw result[0];
1127
+ }
1128
+ onErrorSignal.abort();
1129
+ return result;
1130
+ }
1131
+ async function confirm(message, options = {}) {
1132
+ const prompt = new ConfirmPrompt({
1133
+ ...options,
1134
+ message
1135
+ });
1136
+ const onErrorSignal = new AbortController();
1137
+ const onError = once(prompt, "error", { signal: onErrorSignal.signal });
1138
+ const result = await Promise.race([prompt.listen(), onError]);
1139
+ if (isAbortError(result)) {
1140
+ prompt.destroy();
1141
+ throw result[0];
1142
+ }
1143
+ onErrorSignal.abort();
1144
+ return result;
1145
+ }
1146
+ async function multiselect(message, options) {
1147
+ const prompt = new MultiselectPrompt({
1148
+ ...options,
1149
+ message
1150
+ });
1151
+ const onErrorSignal = new AbortController();
1152
+ const onError = once(prompt, "error", { signal: onErrorSignal.signal });
1153
+ const result = await Promise.race([prompt.listen(), onError]);
1154
+ if (isAbortError(result)) {
1155
+ prompt.destroy();
1156
+ throw result[0];
1157
+ }
1158
+ onErrorSignal.abort();
1159
+ return result;
1160
+ }
1161
+ function isAbortError(error) {
1162
+ return Array.isArray(error) && error.length > 0 && error[0] instanceof Error;
1163
+ }
1164
+ const validators = { required };
1165
+ const transformers = {
1166
+ number,
1167
+ integer,
1168
+ url
1169
+ };
1170
+ //#endregion
1171
+ export { PromptAgent, confirm, multiselect, question, select, transformers, validators };