UNPKG

1.03 kBJavaScriptView Raw
1'use strict';
2const Emittery = require('emittery');
3
4const emitter = new Emittery();
5process.on('message', message => {
6 if (!message.ava) {
7 return;
8 }
9
10 switch (message.ava.type) {
11 case 'options':
12 emitter.emit('options', message.ava.options);
13 break;
14 case 'peer-failed':
15 emitter.emit('peerFailed');
16 break;
17 case 'pong':
18 emitter.emit('pong');
19 break;
20 default:
21 break;
22 }
23});
24
25exports.options = emitter.once('options');
26exports.peerFailed = emitter.once('peerFailed');
27
28function send(evt) {
29 if (process.connected) {
30 process.send({ava: evt});
31 }
32}
33
34exports.send = send;
35
36function unref() {
37 process.channel.unref();
38}
39
40exports.unref = unref;
41
42let pendingPings = Promise.resolve();
43async function flush() {
44 process.channel.ref();
45 const promise = pendingPings.then(async () => { // eslint-disable-line promise/prefer-await-to-then
46 send({type: 'ping'});
47 await emitter.once('pong');
48 if (promise === pendingPings) {
49 unref();
50 }
51 });
52 pendingPings = promise;
53 await promise;
54}
55
56exports.flush = flush;