-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
86 lines (66 loc) · 1.65 KB
/
index.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
86
const Pipe = require('bare-pipe')
const { Duplex } = require('bare-stream')
const errors = require('./lib/errors')
module.exports = exports = class IPC extends Duplex {
constructor(port) {
const { incoming, outgoing } = port
super()
this._incoming = new Pipe(incoming)
this._outgoing = new Pipe(outgoing)
this._pendingWrite = null
this._incoming
.on('data', this._ondata.bind(this))
.on('end', this._onend.bind(this))
this._outgoing.on('drain', this._ondrain.bind(this))
}
_write(chunk, encoding, cb) {
if (this._outgoing.write(chunk)) cb(null)
else this._pendingWrite = cb
}
_final(cb) {
this._outgoing.end()
cb(null)
}
_ondata(data) {
this.push(data)
}
_onend() {
this.push(null)
}
_ondrain() {
if (this._pendingWrite === null) return
const cb = this._pendingWrite
this._pendingWrite = null
cb(null)
}
}
const IPC = exports
class IPCPort {
constructor(incoming, outgoing) {
this.incoming = incoming
this.outgoing = outgoing
this.detached = false
}
connect() {
const ipc = new IPC(this)
this.detached = true
return ipc
}
[Symbol.for('bare.detach')]() {
if (this.detached) {
throw errors.ALREADY_CONNECTED(
'Port has already started receiving messages'
)
}
this.detached = true
return [this.incoming, this.outgoing]
}
static [Symbol.for('bare.attach')]([incoming, outgoing]) {
return new this(incoming, outgoing)
}
}
exports.open = function open(opts) {
const a = Pipe.pipe(opts)
const b = Pipe.pipe(opts)
return [new IPCPort(a[0], b[1], opts), new IPCPort(b[0], a[1], opts)]
}