This repository has been archived by the owner on Oct 7, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprompts.js
78 lines (64 loc) · 1.8 KB
/
prompts.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const { assert, array, defaulted, string, boolean, object, func, optional } = require('superstruct');
const lazyPrompts = () => require('prompts');
/**
* @param {string} objKey
*/
const unpack = (objKey) => (obj = {}) => obj[objKey];
/**
* @param {object} opts
* @param {string} opts.message
* @param {{text:string, key:string}[]} opts.questions
* @param { (prompt:any, answer:any) => void } [opts.onCancel = ()=>{}]
*
* @returns {Promise<string | undefined>}
*/
module.exports.selector = (opts) => {
const prompts = lazyPrompts();
const Options = object({
message: string(),
questions: array(object({
text: string(),
key: string(),
})),
onCancel: optional(defaulted(func(), () => {})),
});
assert(opts, Options);
const promptQuestionsChoices = opts.questions.map(({ text, key }) => ({
title: text,
value: key,
}));
const promptQuestions = {
type: 'select',
name: 'reply',
message: opts.message,
choices: promptQuestionsChoices,
};
return prompts(promptQuestions, {
onCancel: opts.onCancel,
}).then(unpack('reply'));
};
/**
* @param {object} opts
* @param {string} opts.message
* @param {boolean} [opts.hide = false]
* @param {boolean} [opts.mandatory = false]
*
* @returns {Promise<string | undefined>}
*/
module.exports.input = (opts) => {
const prompts = lazyPrompts();
const Options = object({
message: string(),
hide: optional(defaulted(boolean(), false)),
mandatory: optional(defaulted(boolean(), false)),
});
assert(opts, Options);
const promptQuestion = {
type: 'text',
style: opts.hide ? 'password' : 'default',
name: 'reply',
message: opts.message,
...(opts.mandatory && ({validate: (input = '') => !!input.trim() })),
};
return prompts(promptQuestion).then(unpack('reply'));
}