UNPKG

1.95 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const DEFAULT_MAX_RETRIES = 3;
4function getInputStream(config) {
5 return config.inputStream || process.stdin;
6}
7function print(text, config) {
8 const inputStream = getInputStream(config);
9 if (inputStream !== process.stdin)
10 return;
11 const { options } = config;
12 if (options)
13 text += ' [' + options.join('/') + ']';
14 text += ': ';
15 process.stdout.write(text);
16}
17function getOnError(question, config, callback) {
18 const inputStream = getInputStream(config);
19 return (listener, tries) => {
20 if (inputStream === process.stdin)
21 console.log('Unexpected answer. %d retries left.', tries);
22 if (!tries) {
23 inputStream.removeListener('data', listener);
24 inputStream.pause();
25 callback('Retries spent');
26 }
27 else {
28 print(question, config);
29 }
30 };
31}
32function getListener(question, config, callback) {
33 const inputStream = getInputStream(config);
34 let tries = config.maxRetries || DEFAULT_MAX_RETRIES;
35 const onError = getOnError(question, config, callback);
36 function listener(data) {
37 const answer = data.toString().trim();
38 if (config.options && !config.options.includes(answer))
39 return onError(listener, --tries);
40 inputStream.removeListener('data', listener);
41 inputStream.pause();
42 callback('', answer);
43 }
44 return listener;
45}
46function ask(question, config = {}) {
47 return new Promise((resolve, reject) => {
48 const callback = (error, value) => (error ? reject(new Error(error)) : resolve(value));
49 const inputStream = getInputStream(config);
50 inputStream.resume();
51 const listener = getListener(question, config, callback);
52 inputStream.addListener('data', listener);
53 print(question, config);
54 });
55}
56exports.default = ask;