保誠-保戶業務員媒合平台
HelenHuang
2022-06-09 9bdb95c9e34cef640534e5e5a1e2225a80442000
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
'use strict';
var _ = {
  extend: require('lodash/extend'),
  omit: require('lodash/omit'),
};
var MuteStream = require('mute-stream');
var readline = require('readline');
 
/**
 * Base interface class other can inherits from
 */
 
class UI {
  constructor(opt) {
    // Instantiate the Readline interface
    // @Note: Don't reassign if already present (allow test to override the Stream)
    if (!this.rl) {
      this.rl = readline.createInterface(setupReadlineOptions(opt));
    }
 
    this.rl.resume();
 
    this.onForceClose = this.onForceClose.bind(this);
 
    // Make sure new prompt start on a newline when closing
    process.on('exit', this.onForceClose);
 
    // Terminate process on SIGINT (which will call process.on('exit') in return)
    this.rl.on('SIGINT', this.onForceClose);
  }
 
  /**
   * Handle the ^C exit
   * @return {null}
   */
 
  onForceClose() {
    this.close();
    process.kill(process.pid, 'SIGINT');
    console.log('');
  }
 
  /**
   * Close the interface and cleanup listeners
   */
 
  close() {
    // Remove events listeners
    this.rl.removeListener('SIGINT', this.onForceClose);
    process.removeListener('exit', this.onForceClose);
 
    this.rl.output.unmute();
 
    if (this.activePrompt && typeof this.activePrompt.close === 'function') {
      this.activePrompt.close();
    }
 
    // Close the readline
    this.rl.output.end();
    this.rl.pause();
    this.rl.close();
  }
}
 
function setupReadlineOptions(opt) {
  opt = opt || {};
  // Inquirer 8.x:
  // opt.skipTTYChecks = opt.skipTTYChecks === undefined ? opt.input !== undefined : opt.skipTTYChecks;
  opt.skipTTYChecks = opt.skipTTYChecks === undefined ? true : opt.skipTTYChecks;
 
  // Default `input` to stdin
  var input = opt.input || process.stdin;
 
  // Check if prompt is being called in TTY environment
  // If it isn't return a failed promise
  if (!opt.skipTTYChecks && !input.isTTY) {
    const nonTtyError = new Error(
      'Prompts can not be meaningfully rendered in non-TTY environments'
    );
    nonTtyError.isTtyError = true;
    throw nonTtyError;
  }
 
  // Add mute capabilities to the output
  var ms = new MuteStream();
  ms.pipe(opt.output || process.stdout);
  var output = ms;
 
  return _.extend(
    {
      terminal: true,
      input: input,
      output: output,
    },
    _.omit(opt, ['input', 'output'])
  );
}
 
module.exports = UI;