UNPKG

ws-streamify

Version:

Pipe Node.js streams over WebSockets (with back-pressure!).

153 lines (118 loc) 5.59 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _stream = require('stream'); var _assert = require('assert'); var _assert2 = _interopRequireDefault(_assert); var _debug = require('debug'); var _debug2 = _interopRequireDefault(_debug); var _semver = require('semver'); var _semver2 = _interopRequireDefault(_semver); var _codes = require('./codes'); var _codes2 = _interopRequireDefault(_codes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var DATA = _codes2.default.DATA, ACK = _codes2.default.ACK, END = _codes2.default.END; var OLD_BUFFER = !global.window && _semver2.default.lt(process.version, '6.0.0'); var debug = (0, _debug2.default)('ws-streamify'); var WebSocketStream = function (_Duplex) { _inherits(WebSocketStream, _Duplex); function WebSocketStream(socket, options) { _classCallCheck(this, WebSocketStream); var _this = _possibleConstructorReturn(this, (WebSocketStream.__proto__ || Object.getPrototypeOf(WebSocketStream)).call(this, options)); (0, _assert2.default)(socket, 'You must provide a socket'); _this.socket = socket; socket.binaryType = 'arraybuffer'; // You can provide a socket name for debugging purposes. Shh, that's a secret! socket._name = socket._name || Math.random().toString(36).slice(2, 7); // When the first message is received it becomes true _this._started = false; _this.on('finish', function () { debug(_this.socket._name + ': I\'m done'); _this._send(END); }); // Buffer data until connection is established if (socket.readyState !== socket.OPEN) _this.cork(); socket.onopen = function () { debug(_this.socket._name + ': okay, I\'m ready'); _this.uncork(); }; socket.onclose = function (code, msg) { debug(_this.socket._name + ': I\'ve lost the connection'); _this.emit('close', code, msg); }; socket.onerror = function (err) { debug(_this.socket._name + ': uh oh, error!'); _this.emit('error', err); }; socket.onmessage = function (msg) { var data = OLD_BUFFER ? new Buffer(new Uint8Array(msg.data)) : Buffer.from(msg.data); switch (data[0]) { case DATA: _this._started = true; if (!_this.push(data.slice(1))) { // Note that this will execute after // all callbacks on 'readable' and 'data' events. debug(_this.socket._name + ': ouch, I\'m full...'); } break; case ACK: _this._cb(); break; case END: debug(_this.socket._name + ': okay, bye'); _this.push(null); break; default: throw new Error('Unsupported message type'); } }; return _this; } _createClass(WebSocketStream, [{ key: '_writev', value: function _writev(chunks, callback) { debug(this.socket._name + ': hey, I\'m sending you all buffered data'); var chunk = chunks.reduce(function (prev, next) { return Buffer.concat([prev.chunk, next.chunk].filter(function (b) { return b; })); }); this._send(DATA, chunk); this._cb = callback; } }, { key: '_write', value: function _write(chunk, encoding, callback) { debug(this.socket._name + ': hey, I\'m sending you data'); this._send(DATA, chunk); this._cb = callback; } }, { key: '_read', value: function _read(size) { // Let's not send the first ACK, since it's redundant if (this._started) { debug(this.socket._name + ': go ahead, send some more'); this._send(ACK); } } }, { key: '_send', value: function _send(code, data) { if (this.socket.readyState === this.socket.OPEN) { var type = OLD_BUFFER ? new Buffer(new Uint8Array([code])) : Buffer.from([code]); this.socket.send(data ? Buffer.concat([type, data]) : type); } } }]); return WebSocketStream; }(_stream.Duplex); exports.default = WebSocketStream; //# sourceMappingURL=index.js.map