UNPKG

2.19 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.BufferedDuplex = exports.writev = void 0;
4const readable_stream_1 = require("readable-stream");
5const buffer_1 = require("buffer");
6function writev(chunks, cb) {
7 const buffers = new Array(chunks.length);
8 for (let i = 0; i < chunks.length; i++) {
9 if (typeof chunks[i].chunk === 'string') {
10 buffers[i] = buffer_1.Buffer.from(chunks[i].chunk, 'utf8');
11 }
12 else {
13 buffers[i] = chunks[i].chunk;
14 }
15 }
16 this._write(buffer_1.Buffer.concat(buffers), 'binary', cb);
17}
18exports.writev = writev;
19class BufferedDuplex extends readable_stream_1.Duplex {
20 constructor(opts, proxy, socket) {
21 super({
22 objectMode: true,
23 });
24 this.proxy = proxy;
25 this.socket = socket;
26 this.writeQueue = [];
27 if (!opts.objectMode) {
28 this._writev = writev.bind(this);
29 }
30 this.isSocketOpen = false;
31 this.proxy.on('data', (chunk) => {
32 this.push(chunk);
33 });
34 }
35 _read(size) {
36 this.proxy.read(size);
37 }
38 _write(chunk, encoding, cb) {
39 if (!this.isSocketOpen) {
40 this.writeQueue.push({ chunk, encoding, cb });
41 }
42 else {
43 this.writeToProxy(chunk, encoding, cb);
44 }
45 }
46 _final(callback) {
47 this.writeQueue = [];
48 this.proxy.end(callback);
49 }
50 _destroy(err, callback) {
51 this.writeQueue = [];
52 this.proxy.destroy();
53 callback(err);
54 }
55 socketReady() {
56 this.emit('connect');
57 this.isSocketOpen = true;
58 this.processWriteQueue();
59 }
60 writeToProxy(chunk, encoding, cb) {
61 if (this.proxy.write(chunk, encoding) === false) {
62 this.proxy.once('drain', cb);
63 }
64 else {
65 cb();
66 }
67 }
68 processWriteQueue() {
69 while (this.writeQueue.length > 0) {
70 const { chunk, encoding, cb } = this.writeQueue.shift();
71 this.writeToProxy(chunk, encoding, cb);
72 }
73 }
74}
75exports.BufferedDuplex = BufferedDuplex;
76//# sourceMappingURL=BufferedDuplex.js.map
\No newline at end of file