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