prompt.js
20.7 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
/*
* prompt.js: Simple prompt for prompting information from the command line
*
* (C) 2010, Nodejitsu Inc.
*
*/
var events = require('events'),
readline = require('readline'),
eachSeries = require('async/eachSeries'),
rejectSeries = require('async/rejectSeries'),
read = require('read'),
validate = require('revalidator').validate,
winston = require('winston'),
colors = require('@colors/colors/safe');
//
// Monkey-patch readline.Interface to work-around
// https://github.com/joyent/node/issues/3860
//
readline.Interface.prototype.setPrompt = function(prompt, length) {
this._prompt = prompt;
if (length) {
this._promptLength = length;
} else {
var lines = prompt.split(/[\r\n]/);
var lastLine = lines[lines.length - 1];
this._promptLength = lastLine.replace(/\u001b\[(\d+(;\d+)*)?m/g, '').length;
}
};
//
// Expose version using `pkginfo`
//
module.exports.version = require('../package.json').version;
var stdin, stdout, history = [];
var prompt = module.exports = Object.create(events.EventEmitter.prototype);
var logger = prompt.logger = new winston.Logger({
transports: [new (winston.transports.Console)()]
});
prompt.started = false;
prompt.paused = false;
prompt.stopped = true;
prompt.allowEmpty = false;
prompt.message = 'prompt';
prompt.delimiter = ': ';
prompt.colors = true;
//
// Create an empty object for the properties
// known to `prompt`
//
prompt.properties = {};
//
// Setup the default winston logger to use
// the `cli` levels and colors.
//
logger.cli();
//
// ### function start (options)
// #### @options {Object} **Optional** Options to consume by prompt
// Starts the prompt by listening to the appropriate events on `options.stdin`
// and `options.stdout`. If no streams are supplied, then `process.stdin`
// and `process.stdout` are used, respectively.
//
prompt.start = function (options) {
if (prompt.started) {
return;
}
options = options || {};
stdin = options.stdin || process.stdin;
stdout = options.stdout || process.stdout;
//
// By default: Remember the last `10` prompt property /
// answer pairs and don't allow empty responses globally.
//
prompt.memory = options.memory || 10;
prompt.allowEmpty = options.allowEmpty || false;
prompt.message = options.message || prompt.message;
prompt.delimiter = options.delimiter || prompt.delimiter;
prompt.colors = options.colors || prompt.colors;
if (!options.noHandleSIGINT) {
if (process.platform !== 'win32') {
// windows falls apart trying to deal with SIGINT
process.on('SIGINT', function () {
stdout.write('\n');
process.exit(1);
});
} else {
// listen for the "Ctrl+C" key combination and trigger process event.
// See https://stackoverflow.com/questions/10021373/what-is-the-windows-equivalent-of-process-onsigint-in-node-js
stdin.on('keypress', function(char, key) {
if (key && key.ctrl && key.name == 'c') {
stdout.write('\n');
process.emit("SIGINT");
process.exit(1);
}
});
}
}
prompt.emit('start');
prompt.started = true;
prompt.stopped = false;
return prompt;
};
//
// ### function pause ()
// Pauses input coming in from stdin
//
prompt.pause = function () {
if (!prompt.started || prompt.stopped || prompt.paused) {
return;
}
stdin.pause();
prompt.emit('pause');
prompt.paused = true;
return prompt;
};
//
// ### function stop ()
// Stops input coming in from stdin
//
prompt.stop = function () {
if (prompt.stopped || !prompt.started) {
return;
}
stdin.destroy();
prompt.emit('stop');
prompt.stopped = true;
prompt.started = false;
prompt.paused = false;
return prompt;
}
//
// ### function resume ()
// Resumes input coming in from stdin
//
prompt.resume = function () {
if (!prompt.started || !prompt.paused) {
return;
}
stdin.resume();
prompt.emit('resume');
prompt.paused = false;
return prompt;
};
//
// ### function history (search)
// #### @search {Number|string} Index or property name to find.
// Returns the `property:value` pair from within the prompts
// `history` array.
//
prompt.history = function (search) {
if (typeof search === 'number') {
return history[search] || {};
}
var names = history.map(function (pair) {
return typeof pair.property === 'string'
? pair.property
: pair.property.name;
});
if (!~names.indexOf(search)) {
return null;
}
return history.filter(function (pair) {
return typeof pair.property === 'string'
? pair.property === search
: pair.property.name === search;
})[0];
};
//
// ### function get (schema, callback)
// #### @schema {Array|Object|string} Set of variables to get input for.
// #### @callback {function} Continuation to pass control to when complete.
// Gets input from the user via stdin for the specified message(s) `msg`.
//
prompt.get = function (schema, callback) {
if (typeof callback === 'function') return prompt._get(schema, callback);
return new Promise(function (resolve, reject) {
prompt._get(schema, function (err, result) {
return err ? reject(err) : resolve(result);
});
});
};
prompt._get = function (schema, callback) {
//
// Transforms a full JSON-schema into an array describing path and sub-schemas.
// Used for iteration purposes.
//
function untangle(schema, path) {
var results = [];
path = path || [];
if (schema.properties) {
//
// Iterate over the properties in the schema and use recursion
// to process sub-properties.
//
Object.keys(schema.properties).forEach(function (key) {
var obj = {};
obj[key] = schema.properties[key];
//
// Concat a sub-untangling to the results.
//
results = results.concat(untangle(obj[key], path.concat(key)));
});
// Return the results.
return results;
}
//
// This is a schema "leaf".
//
return {
path: path,
schema: schema
};
}
//
// Iterate over the values in the schema, represented as
// a legit single-property object subschemas. Accepts `schema`
// of the forms:
//
// 'prop-name'
//
// ['string-name', { path: ['or-well-formed-subschema'], properties: ... }]
//
// { path: ['or-well-formed-subschema'], properties: ... ] }
//
// { properties: { 'schema-with-no-path' } }
//
// And transforms them all into
//
// { path: ['path', 'to', 'property'], properties: { path: { to: ...} } }
//
function iterate(schema, get, done) {
var iterator = [],
result = {};
if (typeof schema === 'string') {
//
// We can iterate over a single string.
//
iterator.push({
path: [schema],
schema: prompt.properties[schema.toLowerCase()] || {}
});
}
else if (Array.isArray(schema)) {
//
// An array of strings and/or single-prop schema and/or no-prop schema.
//
iterator = schema.map(function (element) {
if (typeof element === 'string') {
return {
path: [element],
schema: prompt.properties[element.toLowerCase()] || {}
};
}
else if (element.properties) {
return {
path: [Object.keys(element.properties)[0]],
schema: element.properties[Object.keys(element.properties)[0]]
};
}
else if (element.path && element.schema) {
return element;
}
else {
return {
path: [element.name || 'question'],
schema: element
};
}
});
}
else if (schema.properties) {
//
// Or a complete schema `untangle` it for use.
//
iterator = untangle(schema);
}
else {
//
// Or a partial schema and path.
// TODO: Evaluate need for this option.
//
iterator = [{
schema: schema.schema ? schema.schema : schema,
path: schema.path || [schema.name || 'question']
}];
}
//
// Now, iterate and assemble the result.
//
eachSeries(iterator, function (branch, next) {
get(branch, function assembler(err, line) {
if (err) {
return next(err);
}
function build(path, line) {
var obj = {};
if (path.length) {
obj[path[0]] = build(path.slice(1), line);
return obj;
}
return line;
}
function attach(obj, attr) {
var keys;
if (typeof attr !== 'object' || attr instanceof Array) {
return attr;
}
keys = Object.keys(attr);
if (keys.length) {
if (!obj[keys[0]]) {
obj[keys[0]] = {};
}
obj[keys[0]] = attach(obj[keys[0]], attr[keys[0]]);
}
return obj;
}
result = attach(result, build(branch.path, line));
next();
});
}, function (err) {
return err ? done(err) : done(null, result);
});
}
iterate(schema, function get(target, next) {
prompt.getInput(target, function (err, line) {
return err ? next(err) : next(null, line);
});
}, callback);
return prompt;
};
//
// ### function confirm (msg, callback)
// #### @msg {Array|Object|string} set of message to confirm
// #### @callback {function} Continuation to pass control to when complete.
// Confirms a single or series of messages by prompting the user for a Y/N response.
// Returns `true` if ALL messages are answered in the affirmative, otherwise `false`
//
// `msg` can be a string, or object (or array of strings/objects).
// An object may have the following properties:
//
// {
// description: 'yes/no' // message to prompt user
// pattern: /^[yntf]{1}/i // optional - regex defining acceptable responses
// yes: /^[yt]{1}/i // optional - regex defining `affirmative` responses
// message: 'yes/no' // optional - message to display for invalid responses
// }
//
prompt.confirm = function (/* msg, options, callback */) {
var args = Array.prototype.slice.call(arguments),
msg = args.shift(),
callback = args.pop(),
opts = args.shift(),
vars = !Array.isArray(msg) ? [msg] : msg,
RX_Y = /^[yt]{1}/i,
RX_YN = /^[yntf]{1}/i;
function confirm(target, next) {
var yes = target.yes || RX_Y,
options = {
description: typeof target === 'string' ? target : target.description || 'yes/no',
pattern: target.pattern || RX_YN,
name: 'confirm',
message: target.message || 'yes/no'
};
for (var k in (opts || {})) {
if (opts.hasOwnProperty(k)) {
options[k] = opts[k];
}
}
prompt.get([options], function (err, result) {
next(null, err ? false : yes.test(result[options.name]));
});
}
rejectSeries(vars, confirm, function(err, result) {
callback(null, result.length===0);
});
};
// Variables needed outside of getInput for multiline arrays.
var tmp = [];
// ### function getInput (prop, callback)
// #### @prop {Object|string} Variable to get input for.
// #### @callback {function} Continuation to pass control to when complete.
// Gets input from the user via stdin for the specified message `msg`.
//
prompt.getInput = function (prop, callback) {
var schema = prop.schema || prop,
propName = prop.path && prop.path.join(':') || prop,
storedSchema = prompt.properties[propName.toLowerCase()],
delim = prompt.delimiter,
defaultLine,
against,
hidden,
length,
valid,
name,
raw,
msg;
//
// If there is a stored schema for `propName` in `propmpt.properties`
// then use it.
//
if (schema instanceof Object && !Object.keys(schema).length &&
typeof storedSchema !== 'undefined') {
schema = storedSchema;
}
//
// Build a proper validation schema if we just have a string
// and no `storedSchema`.
//
if (typeof prop === 'string' && !storedSchema) {
schema = {};
}
schema = convert(schema);
defaultLine = schema.default;
name = prop.description || schema.description || propName;
raw = prompt.colors
? [colors.grey(name), colors.grey(delim)]
: [name, delim];
if (prompt.message)
raw.unshift(prompt.message, delim);
prop = {
schema: schema,
path: propName.split(':')
};
//
// If the schema has no `properties` value then set
// it to an object containing the current schema
// for `propName`.
//
if (!schema.properties) {
schema = (function () {
var obj = { properties: {} };
obj.properties[propName] = schema;
return obj;
})();
}
//
// Handle overrides here.
// TODO: Make overrides nestable
//
if (prompt.override && prompt.override.hasOwnProperty(propName)) {
if (prompt._performValidation(name, prop, prompt.override, schema, -1, callback)) {
return callback(null, prompt.override[propName]);
}
delete prompt.override[propName];
}
//
// Check if we should skip this prompt
//
if (typeof prop.schema.ask === 'function' &&
!prop.schema.ask()) {
return callback(null, prop.schema.default || '');
}
var type = (schema.properties && schema.properties[propName] &&
schema.properties[propName].type || '').toLowerCase().trim(),
wait = type === 'array';
if (type === 'array') {
length = prop.schema.maxItems;
if (length) {
msg = (tmp.length + 1).toString() + '/' + length.toString();
}
else {
msg = (tmp.length + 1).toString();
}
msg += delim;
raw.push(prompt.colors ? colors.grey(msg) : msg);
}
//
// Calculate the raw length and colorize the prompt
//
length = raw.join('').length;
// raw[0] = raw[0];
msg = raw.join('');
if (schema.help) {
schema.help.forEach(function (line) {
logger.help(line);
});
}
//
// Emit a "prompting" event
//
prompt.emit('prompt', prop);
//
// If defaultLine is a function, execute it and store it back to defaultLine
//
if(typeof defaultLine === 'function') {
defaultLine = defaultLine();
}
//
// If there is no default line, set it to an empty string
//
if(typeof defaultLine === 'undefined') {
defaultLine = '';
}
//
// set to string for readline ( will not accept Numbers )
//
defaultLine = defaultLine.toString();
//
// Make the actual read
//
read({
prompt: msg,
silent: prop.schema && prop.schema.hidden,
replace: prop.schema && prop.schema.replace,
default: defaultLine,
input: stdin,
output: stdout
}, function (err, line) {
if (err && wait === false) {
return callback(err);
}
var against = {},
numericInput,
isValid;
if (line !== '') {
if (schema.properties[propName]) {
var type = (schema.properties[propName].type || '').toLowerCase().trim() || undefined;
//
// If type is some sort of numeric create a Number object to pass to revalidator
//
if (type === 'number' || type === 'integer') {
line = Number(line);
}
//
// Attempt to parse input as a boolean if the schema expects a boolean
//
if (type == 'boolean') {
if(line.toLowerCase() === "true" || line.toLowerCase() === 't') {
line = true;
} else if(line.toLowerCase() === "false" || line.toLowerCase() === 'f') {
line = false;
}
}
//
// If the type is an array, wait for the end. Fixes #54
//
if (type == 'array') {
var length = prop.schema.maxItems;
if (err) {
if (err.message == 'canceled') {
wait = false;
stdout.write('\n');
}
}
else {
if (length) {
if (tmp.length + 1 < length) {
isValid = false;
wait = true;
}
else {
isValid = true;
wait = false;
}
}
else {
isValid = false;
wait = true;
}
tmp.push(line);
}
line = tmp;
}
}
against[propName] = line;
}
if (prop && prop.schema.before) {
line = prop.schema.before(line);
}
// Validate
if (isValid === undefined) isValid = prompt._performValidation(name, prop, against, schema, line, callback);
if (!isValid) {
return prompt.getInput(prop, callback);
}
//
// Log the resulting line, append this `property:value`
// pair to the history for `prompt` and respond to
// the callback.
//
logger.input(line.yellow);
prompt._remember(propName, line);
callback(null, line);
// Make sure `tmp` is emptied
tmp = [];
});
};
//
// ### function performValidation (name, prop, against, schema, line, callback)
// #### @name {Object} Variable name
// #### @prop {Object|string} Variable to get input for.
// #### @against {Object} Input
// #### @schema {Object} Validation schema
// #### @line {String|Boolean} Input line
// #### @callback {function} Continuation to pass control to when complete.
// Perfoms user input validation, print errors if needed and returns value according to validation
//
prompt._performValidation = function (name, prop, against, schema, line, callback) {
var numericInput, valid, msg;
try {
valid = validate(against, schema);
}
catch (err) {
return (line !== -1) ? callback(err) : false;
}
if (!valid.valid) {
if (prop.schema.message) {
logger.error(prop.schema.message);
} else {
msg = line !== -1 ? 'Invalid input for ' : 'Invalid command-line input for ';
if (prompt.colors) {
logger.error(msg + colors.grey(name));
}
else {
logger.error(msg + name);
}
}
prompt.emit('invalid', prop, line);
}
return valid.valid;
};
//
// ### function addProperties (obj, properties, callback)
// #### @obj {Object} Object to add properties to
// #### @properties {Array} List of properties to get values for
// #### @callback {function} Continuation to pass control to when complete.
// Prompts the user for values each of the `properties` if `obj` does not already
// have a value for the property. Responds with the modified object.
//
prompt.addProperties = function (obj, properties, callback) {
properties = properties.filter(function (prop) {
return typeof obj[prop] === 'undefined';
});
if (properties.length === 0) {
return callback(null, obj);
}
prompt.get(properties, function (err, results) {
if (err) {
return callback(err);
}
else if (!results) {
return callback(null, obj);
}
function putNested (obj, path, value) {
var last = obj, key;
while (path.length > 1) {
key = path.shift();
if (!last[key]) {
last[key] = {};
}
last = last[key];
}
last[path.shift()] = value;
}
Object.keys(results).forEach(function (key) {
putNested(obj, key.split('.'), results[key]);
});
callback(null, obj);
});
return prompt;
};
//
// ### @private function _remember (property, value)
// #### @property {Object|string} Property that the value is in response to.
// #### @value {string} User input captured by `prompt`.
// Prepends the `property:value` pair into the private `history` Array
// for `prompt` so that it can be accessed later.
//
prompt._remember = function (property, value) {
history.unshift({
property: property,
value: value
});
//
// If the length of the `history` Array
// has exceeded the specified length to remember,
// `prompt.memory`, truncate it.
//
if (history.length > prompt.memory) {
history.splice(prompt.memory, history.length - prompt.memory);
}
};
//
// ### @private function convert (schema)
// #### @schema {Object} Schema for a property
// Converts the schema into new format if it is in old format
//
function convert(schema) {
var newProps = Object.keys(validate.messages),
newSchema = false,
key;
newProps = newProps.concat(['description', 'dependencies']);
for (key in schema) {
if (newProps.indexOf(key) > 0) {
newSchema = true;
break;
}
}
if (!newSchema || schema.validator || schema.warning || typeof schema.empty !== 'undefined') {
if(typeof schema.message !== 'undefined'){
schema.description = schema.message;
}
if(typeof schema.warning !== 'undefined'){
schema.message = schema.warning;
}
if (typeof schema.validator === 'function') {
schema.conform = schema.validator;
} else {
schema.pattern = schema.validator;
}
if (typeof schema.empty !== 'undefined') {
schema.required = !(schema.empty);
}
delete schema.warning;
delete schema.validator;
delete schema.empty;
}
return schema;
}