1 | var Emitter = require("events").EventEmitter;
|
2 | var repl = require("repl");
|
3 | var util = require("util");
|
4 |
|
5 | var priv = new Map();
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | function Repl(opts) {
|
11 | if (!Repl.isActive) {
|
12 | Repl.isActive = true;
|
13 |
|
14 | if (!(this instanceof Repl)) {
|
15 | return new Repl(opts);
|
16 | }
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 | this.context = {};
|
23 | this.ready = false;
|
24 |
|
25 | var state = {
|
26 | opts: opts,
|
27 | board: opts.board,
|
28 | };
|
29 |
|
30 | priv.set(this, state);
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 | Repl.ref = this;
|
38 | } else {
|
39 | return Repl.ref;
|
40 | }
|
41 | }
|
42 |
|
43 |
|
44 | util.inherits(Repl, Emitter);
|
45 |
|
46 | Repl.isActive = false;
|
47 | Repl.isBlocked = false;
|
48 |
|
49 |
|
50 | Repl.ref = null;
|
51 |
|
52 | Repl.prototype.initialize = function(callback) {
|
53 | var state = priv.get(this);
|
54 |
|
55 | process.stdin.resume();
|
56 | process.stdin.setEncoding("utf8");
|
57 |
|
58 | var replDefaults = {
|
59 | prompt: ">> ",
|
60 | useGlobal: false
|
61 | };
|
62 |
|
63 |
|
64 |
|
65 | state.board.info("Repl", "Initialized");
|
66 |
|
67 |
|
68 |
|
69 |
|
70 | var cmd = repl.start(replDefaults);
|
71 |
|
72 | this.ready = true;
|
73 |
|
74 |
|
75 |
|
76 |
|
77 |
|
78 | this.cmd = cmd;
|
79 | this.context = cmd.context;
|
80 |
|
81 | cmd.on("exit", function() {
|
82 |
|
83 | var failExitTimeout = 1000;
|
84 |
|
85 | state.board.emit("exit");
|
86 | state.board.warn("Board", "Closing.");
|
87 |
|
88 |
|
89 | var timeout = setTimeout(function () {
|
90 | process.reallyExit();
|
91 | }, failExitTimeout);
|
92 |
|
93 | var interval = setInterval(function () {
|
94 | var pendingIo = false;
|
95 |
|
96 |
|
97 | if (state.board.length) {
|
98 | for (let i = 0; i < state.board.length; i++) {
|
99 | if (state.board[i].io.pending) {
|
100 | pendingIo = true;
|
101 | break;
|
102 | }
|
103 | }
|
104 | }
|
105 |
|
106 | else {
|
107 | pendingIo = state.board.io.pending;
|
108 | }
|
109 |
|
110 | if (!pendingIo) {
|
111 | clearInterval(interval);
|
112 | clearTimeout(timeout);
|
113 | process.nextTick(process.reallyExit);
|
114 | }
|
115 | }, 1);
|
116 | });
|
117 |
|
118 | this.inject(state.opts);
|
119 |
|
120 |
|
121 | if (callback) {
|
122 | process.nextTick(callback);
|
123 | }
|
124 | };
|
125 |
|
126 | Repl.prototype.close = function() {
|
127 | this.cmd.emit("exit");
|
128 | };
|
129 |
|
130 | Repl.prototype.inject = function(obj) {
|
131 | Object.keys(obj).forEach(function(key) {
|
132 | Object.defineProperty(
|
133 | this.context, key, Object.getOwnPropertyDescriptor(obj, key)
|
134 | );
|
135 | }, this);
|
136 | };
|
137 |
|
138 | module.exports = Repl;
|