3 * Base prompt implementation
4 * Should be extended by prompt types.
7 assign: require('lodash/assign'),
8 defaults: require('lodash/defaults'),
9 clone: require('lodash/clone'),
11 var chalk = require('chalk');
12 var runAsync = require('run-async');
13 var { filter, flatMap, share, take, takeUntil } = require('rxjs/operators');
14 var Choices = require('../objects/choices');
15 var ScreenManager = require('../utils/screen-manager');
18 constructor(question, rl, answers) {
19 // Setup instance defaults property
25 // Set defaults prompt options
26 this.opt = _.defaults(_.clone(question), {
31 prefix: chalk.green('?'),
34 // Make sure name is present
36 this.throwParamError('name');
39 // Set default message if no message defined
40 if (!this.opt.message) {
41 this.opt.message = this.opt.name + ':';
45 if (Array.isArray(this.opt.choices)) {
46 this.opt.choices = new Choices(this.opt.choices, answers);
50 this.screen = new ScreenManager(this.rl);
54 * Start the Inquiry session and manage output value filtering
59 return new Promise((resolve) => {
60 this._run((value) => resolve(value));
64 // Default noop (this one should be overwritten in prompts)
70 * Throw an error telling a required parameter is missing
71 * @param {String} name Name of the missing param
72 * @return {Throw Error}
75 throwParamError(name) {
76 throw new Error('You must provide a `' + name + '` parameter');
80 * Called when the UI closes. Override to do any specific cleanup necessary
83 this.screen.releaseCursor();
87 * Run the provided validation method each time a submit event occur.
88 * @param {Rx.Observable} submit - submit event flow
89 * @return {Object} Object containing two observables: `success` and `error`
91 handleSubmitEvents(submit) {
93 var validate = runAsync(this.opt.validate);
94 var asyncFilter = runAsync(this.opt.filter);
95 var validation = submit.pipe(
97 asyncFilter(value, self.answers).then(
99 validate(filteredValue, self.answers).then(
100 (isValid) => ({ isValid: isValid, value: filteredValue }),
101 (err) => ({ isValid: err, value: filteredValue })
103 (err) => ({ isValid: err })
109 var success = validation.pipe(
110 filter((state) => state.isValid === true),
113 var error = validation.pipe(
114 filter((state) => state.isValid !== true),
125 * Generate the prompt question string
126 * @return {String} prompt question string
133 chalk.bold(this.opt.message) +
137 // Append the default if available, and if question isn't answered
138 if (this.opt.default != null && this.status !== 'answered') {
139 // If default password is supplied, hide it
140 if (this.opt.type === 'password') {
141 message += chalk.italic.dim('[hidden] ');
143 message += chalk.dim('(' + this.opt.default + ') ');
151 module.exports = Prompt;