easy-cli-framework
Version:
A framework for building CLI applications that are robust and easy to maintain. Supports theming, configuration files, interactive prompts, and more.
66 lines (62 loc) • 2.19 kB
JavaScript
var yargsInteractive = require('yargs-interactive');
// @ts-ignore Untyped Module
/**
* Prompts the user to enter text.
*
* @param {string} prompt The prompt to display to the user
* @param {PromptTextOptions} options The options for the prompt
*
* @returns {Promise<string>} The validated text the user entered
*
* @example
* ```typescript
* // Prompt the user to enter some text
* const text = await promptTextInput('Enter some text');
* console.log(text);
*
* // Prompt the user to enter a password
* const password = await promptTextInput('Enter a password', { type: 'password' });
* console.log(password);
*
* // Prompt the user to enter some text using an editor
* const editor = await promptTextInput('Enter some text', { type: 'editor' });
* console.log(editor);
*
* // Prompt the user to enter some text longer than 5 characters
* const text = await promptTextInput('Enter some text', {
* validator: (input) => input.length > 5,
* validationErrorMessage: 'Text must be longer than 5 characters',
* });
* console.log(text);
*
* // Prompt the user to enter some text using a custom theme
* const text = await promptTextInput('Enter some text', {
* theme: new EasyCLITheme(),
* promptTheme: 'info',
* });
* console.log(text);
* ```
*
*/
const promptTextInput = async (prompt, { type = 'input', defaultText = '', validator = (input) => true, validationErrorMessage = 'Invalid input', theme = null, promptTheme = 'default', } = {}) => {
var _a;
while (true) {
const { choice } = await yargsInteractive()
.usage('$0 <command> [args]')
.interactive({
interactive: { default: true },
choice: {
type,
describe: (_a = theme === null || theme === undefined ? undefined : theme.formattedString(prompt, promptTheme)) !== null && _a !== undefined ? _a : prompt,
default: defaultText,
prompt: 'always',
},
});
if (!validator || validator(choice)) {
return choice;
}
console.log(validationErrorMessage);
}
};
exports.promptTextInput = promptTextInput;
;