fuse-box
Version:
Fuse-Box a bundler that does it right
76 lines (75 loc) • 2.73 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var events = require('events');
var SocketClient = (function () {
function SocketClient(opts) {
opts = opts || {};
var port = opts.port || window.location.port;
var protocol = location.protocol === 'https:' ? 'wss://' : 'ws://';
var domain = location.hostname || 'localhost';
this.url = opts.host || "" + protocol + domain + ":" + port;
if (opts.uri) {
this.url = opts.uri;
}
this.authSent = false;
this.emitter = new events.EventEmitter();
}
SocketClient.prototype.reconnect = function (fn) {
var _this = this;
setTimeout(function () {
_this.emitter.emit('reconnect', { message: 'Trying to reconnect' });
_this.connect(fn);
}, 5000);
};
SocketClient.prototype.on = function (event, fn) {
this.emitter.on(event, fn);
};
SocketClient.prototype.connect = function (fn) {
var _this = this;
console.log('%cConnecting to fusebox HMR at ' + this.url, 'color: #237abe');
setTimeout(function () {
_this.client = new WebSocket(_this.url);
_this.bindEvents(fn);
}, 0);
};
SocketClient.prototype.close = function () {
this.client.close();
};
SocketClient.prototype.send = function (eventName, data) {
if (this.client.readyState === 1) {
this.client.send(JSON.stringify({ event: eventName, data: data || {} }));
}
};
SocketClient.prototype.error = function (data) {
this.emitter.emit('error', data);
};
/** Wires up the socket client messages to be emitted on our event emitter */
SocketClient.prototype.bindEvents = function (fn) {
var _this = this;
this.client.onopen = function (event) {
console.log('%cConnected', 'color: #237abe');
if (fn) {
fn(_this);
}
};
this.client.onerror = function (event) {
_this.error({ reason: event.reason, message: 'Socket error' });
};
this.client.onclose = function (event) {
_this.emitter.emit('close', { message: 'Socket closed' });
if (event.code !== 1011) {
_this.reconnect(fn);
}
};
this.client.onmessage = function (event) {
var data = event.data;
if (data) {
var item = JSON.parse(data);
_this.emitter.emit(item.type, item.data);
_this.emitter.emit('*', item);
}
};
};
return SocketClient;
}());
exports.SocketClient = SocketClient;