forked from sindresorhus/ora
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutilities.js
85 lines (69 loc) · 1.71 KB
/
utilities.js
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
import process from 'node:process';
import readline from 'node:readline';
import {BufferListStream} from 'bl';
const ASCII_ETX_CODE = 0x03; // Ctrl+C emits this code
export class StdinDiscarder {
#requests = 0;
#mutedStream = new BufferListStream();
#ourEmit;
#rl;
constructor() {
this.#mutedStream.pipe(process.stdout);
const self = this; // eslint-disable-line unicorn/no-this-assignment
this.#ourEmit = function (event, data, ...args) {
const {stdin} = process;
if (self.#requests > 0 || stdin.emit === self.#ourEmit) {
if (event === 'keypress') { // Fixes readline behavior
return;
}
if (event === 'data' && data.includes(ASCII_ETX_CODE)) {
process.emit('SIGINT');
}
Reflect.apply(self.#ourEmit, this, [event, data, ...args]);
} else {
Reflect.apply(process.stdin.emit, this, [event, data, ...args]);
}
};
}
start() {
this.#requests++;
if (this.#requests === 1) {
this._realStart();
}
}
stop() {
if (this.#requests <= 0) {
throw new Error('`stop` called more times than `start`');
}
this.#requests--;
if (this.#requests === 0) {
this._realStop();
}
}
// TODO: Use private methods when targeting Node.js 14.
_realStart() {
// No known way to make it work reliably on Windows
if (process.platform === 'win32') {
return;
}
this.#rl = readline.createInterface({
input: process.stdin,
output: this.#mutedStream,
});
this.#rl.on('SIGINT', () => {
if (process.listenerCount('SIGINT') === 0) {
process.emit('SIGINT');
} else {
this.#rl.close();
process.kill(process.pid, 'SIGINT');
}
});
}
_realStop() {
if (process.platform === 'win32') {
return;
}
this.#rl.close();
this.#rl = undefined;
}
}