centrifuge
Advanced tools
Comparing version 2.0.1 to 2.1.0
@@ -0,1 +1,8 @@ | ||
2.1.0 | ||
===== | ||
* new `publish` method of Centrifuge object to publish into channels without being subscribed | ||
* check connection state to prevent writing to closed connection and thus unhandled errors | ||
* `send` method now sends message to server immediately and returns Promise | ||
2.0.1 | ||
@@ -2,0 +9,0 @@ ===== |
@@ -1,2 +0,2 @@ | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("Centrifuge",[],t):"object"==typeof exports?exports.Centrifuge=t():e.Centrifuge=t()}("undefined"!=typeof self?self:this,function(){return function(e){function t(s){if(n[s])return n[s].exports;var i=n[s]={i:s,l:!1,exports:{}};return e[s].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,s){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:s})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=31)}({10:function(e,t,n){"use strict";(function(e){function s(e){return e&&e.__esModule?e:{default:e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function r(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0}),t.Centrifuge=void 0;var u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a=function(){function e(e,t){for(var n=0;n<t.length;n++){var s=t[n];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}return function(t,n,s){return n&&e(t.prototype,n),s&&e(t,s),t}}(),c=n(6),h=s(c),l=n(11),_=s(l),f=n(12),d=n(7);t.Centrifuge=function(t){function n(e,t){i(this,n);var s=r(this,(n.__proto__||Object.getPrototypeOf(n)).call(this));return s._url=e,s._sockjs=null,s._isSockjs=!1,s._binary=!1,s._methodType=null,s._pushType=null,s._encoder=null,s._decoder=null,s._status="disconnected",s._reconnect=!0,s._reconnecting=!1,s._transport=null,s._transportName=null,s._transportClosed=!0,s._messageId=0,s._clientID=null,s._refreshRequired=!1,s._subs={},s._lastSeq={},s._lastGen={},s._lastEpoch={},s._messages=[],s._isBatching=!1,s._isSubscribeBatching=!1,s._privateChannels={},s._numRefreshFailed=0,s._refreshTimeout=null,s._pingTimeout=null,s._pongTimeout=null,s._subRefreshTimeouts={},s._retries=0,s._callbacks={},s._latency=null,s._latencyStart=null,s._connectData=null,s._token=null,s._config={debug:!1,sockjs:null,promise:null,minRetry:1e3,maxRetry:2e4,timeout:5e3,ping:!0,pingInterval:25e3,pongWaitTimeout:5e3,privateChannelPrefix:"$",onTransportClose:null,sockjsServer:null,sockjsTransports:["websocket","xdr-streaming","xhr-streaming","eventsource","iframe-eventsource","iframe-htmlfile","xdr-polling","xhr-polling","iframe-xhr-polling","jsonp-polling"],refreshEndpoint:"/centrifuge/refresh",refreshHeaders:{},refreshParams:{},refreshData:{},refreshAttempts:null,refreshInterval:1e3,onRefreshFailed:null,onRefresh:null,subscribeEndpoint:"/centrifuge/subscribe",subscribeHeaders:{},subscribeParams:{},subRefreshInterval:1e3,onPrivateSubscribe:null},s._configure(t),s}return o(n,t),a(n,[{key:"setToken",value:function(e){this._token=e}},{key:"setConnectData",value:function(e){this._connectData=e}},{key:"_ajax",value:function(t,n,s,i,r){var o=this,u="";this._debug("sending AJAX request to",t,"with data",JSON.stringify(i));var a=e.XMLHttpRequest?new e.XMLHttpRequest:new e.ActiveXObject("Microsoft.XMLHTTP");for(var c in n)n.hasOwnProperty(c)&&(u.length>0&&(u+="&"),u+=encodeURIComponent(c)+"="+encodeURIComponent(n[c]));u.length>0&&(u="?"+u),a.open("POST",t+u,!0),"withCredentials"in a&&(a.withCredentials=!0),a.setRequestHeader("X-Requested-With","XMLHttpRequest"),a.setRequestHeader("Content-Type","application/json");for(var h in s)s.hasOwnProperty(h)&&a.setRequestHeader(h,s[h]);return a.onreadystatechange=function(){if(4===a.readyState)if(200===a.status){var e=void 0,t=!1;try{e=JSON.parse(a.responseText),t=!0}catch(e){r({error:"Invalid JSON. Data was: "+a.responseText,status:200,data:null})}t&&r({data:e,status:200})}else o._log("wrong status code in AJAX response",a.status),r({status:a.status,data:null})},setTimeout(function(){return a.send(JSON.stringify(i))},20),a}},{key:"_log",value:function(){(0,d.log)("info",arguments)}},{key:"_debug",value:function(){!0===this._config.debug&&(0,d.log)("debug",arguments)}},{key:"_websocketSupported",value:function(){return!("function"!=typeof WebSocket&&"object"!==("undefined"==typeof WebSocket?"undefined":u(WebSocket)))}},{key:"_setFormat",value:function(e){if(!this._formatOverride(e)){if("protobuf"===e)throw new Error("not implemented by JSON only Centrifuge client – use client with Protobuf");this._binary=!1,this._methodType=f.JsonMethodType,this._pushType=f.JsonPushType,this._encoder=new f.JsonEncoder,this._decoder=new f.JsonDecoder}}},{key:"_formatOverride",value:function(e){return!1}},{key:"_configure",value:function(t){if(!("Promise"in e))throw new Error("Promise polyfill required");if(Object.assign(this._config,t||{}),this._debug("centrifuge config",this._config),!this._url)throw new Error("url required");if((0,d.startsWith)(this._url,"ws")&&this._url.indexOf("format=protobuf")>-1?this._setFormat("protobuf"):this._setFormat("json"),(0,d.startsWith)(this._url,"http"))if(this._debug("client will try to connect to SockJS endpoint"),null!==this._config.sockjs)this._debug("SockJS explicitly provided in options"),this._sockjs=this._config.sockjs;else{if(void 0===e.SockJS)throw new Error("SockJS not found, use ws:// in url or include SockJS");this._debug("use globally defined SockJS"),this._sockjs=e.SockJS}else this._debug("client will connect to websocket endpoint")}},{key:"_setStatus",value:function(e){this._status!==e&&(this._debug("Status",this._status,"->",e),this._status=e)}},{key:"_isDisconnected",value:function(){return"disconnected"===this._status}},{key:"_isConnecting",value:function(){return"connecting"===this._status}},{key:"_isConnected",value:function(){return"connected"===this._status}},{key:"_nextMessageId",value:function(){return++this._messageId}},{key:"_resetRetry",value:function(){this._debug("reset retries count to 0"),this._retries=0}},{key:"_getRetryInterval",value:function(){var e=(0,d.backoff)(this._retries,this._config.minRetry,this._config.maxRetry);return this._retries+=1,e}},{key:"_clearConnectedState",value:function(e){this._clientID=null,this._stopPing();for(var t in this._callbacks)if(this._callbacks.hasOwnProperty(t)){var n=this._callbacks[t];clearTimeout(n.timeout);var s=n.errback;if(!s)continue;s(this._createErrorObject("disconnected"))}this._callbacks={};for(var i in this._subs)if(this._subs.hasOwnProperty(i)){var r=this._subs[i];e?(r._isSuccess()&&(r._triggerUnsubscribe(),r._recover=!0),r._setSubscribing()):r._setUnsubscribed()}null!==this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null);for(var o in this._subRefreshTimeouts)this._subRefreshTimeouts.hasOwnProperty(o)&&this._subRefreshTimeouts[o]&&this._clearSubRefreshTimeout(o);this._subRefreshTimeouts={},this._reconnect||(this._subs={})}},{key:"_transportSend",value:function(e){if(e.length){if(!this._transport)throw new Error("transport not connected");this._transport.send(this._encoder.encodeCommands(e))}}},{key:"_setupTransport",value:function(){var e=this;if(this._isSockjs=!1,null!==this._sockjs){var t={transports:this._config.sockjsTransports};null!==this._config.sockjsServer&&(t.server=this._config.sockjsServer),this._isSockjs=!0,this._transport=new this._sockjs(this._url,null,t)}else{if(!this._websocketSupported())return void this._debug("No Websocket support and no SockJS configured, can not connect");this._transport=new WebSocket(this._url),!0===this._binary&&(this._transport.binaryType="arraybuffer")}this._transport.onopen=function(){e._transportClosed=!1,e._isSockjs?(e._transportName="sockjs-"+e._transport.transport,e._transport.onheartbeat=function(){return e._restartPing()}):e._transportName="websocket";var t={};(e._token||e._connectData)&&(t.params={}),e._token&&(t.params.token=e._token),e._connectData&&(t.params.data=e._connectData),e._latencyStart=new Date,e._call(t).then(function(t){e._connectResponse(e._decoder.decodeCommandResult(e._methodType.CONNECT,t.result)),t.next&&t.next()},function(t){109===t.code&&(e._refreshRequired=!0),e._disconnect("connect error",!0)})},this._transport.onerror=function(t){e._debug("transport level error",t)},this._transport.onclose=function(t){e._transportClosed=!0;var n="connection closed",s=!0;if(t&&"reason"in t&&t.reason)try{var i=JSON.parse(t.reason);e._debug("reason is an advice object",i),n=i.reason,s=i.reconnect}catch(s){n=t.reason,e._debug("reason is a plain string",n)}if(null!==e._config.onTransportClose&&e._config.onTransportClose({event:t,reason:n,reconnect:s}),e._disconnect(n,s),!0===e._reconnect){e._reconnecting=!0;var r=e._getRetryInterval();e._debug("reconnect after "+r+" milliseconds"),setTimeout(function(){!0===e._reconnect&&(e._refreshRequired?e._refresh():e._connect())},r)}},this._transport.onmessage=function(t){e._dataReceived(t.data)}}},{key:"rpc",value:function(e){var t=this,n={method:this._methodType.RPC,params:{data:e}};return this._call(n).then(function(e){return e.next&&e.next(),t._decoder.decodeCommandResult(t._methodType.RPC,e.result)})}},{key:"send",value:function(e){var t={method:this._methodType.SEND,params:{data:e}};return this._callAsync(t)}},{key:"_dataReceived",value:function(e){var t=this,n=this._decoder.decodeReplies(e),s=Promise.resolve();for(var i in n)!function(e){n.hasOwnProperty(e)&&(s=s.then(function(){return t._dispatchReply(n[e])}))}(i);this._restartPing()}},{key:"_callAsync",value:function(e){this._addMessage(e,!0)}},{key:"_call",value:function(t){var n=this;return new e.Promise(function(e,s){var i=n._addMessage(t);n._registerCall(i,e,s)})}},{key:"_connect",value:function(){if(this.isConnected())return void this._debug("connect called when already connected");"connecting"!==this._status&&(this._debug("start connecting"),this._setStatus("connecting"),this._clientID=null,this._reconnect=!0,this._setupTransport())}},{key:"_disconnect",value:function(e,t){if(!this._isDisconnected()){this._debug("disconnected:",e,t);var n=t||!1;!1===n&&(this._reconnect=!1),this._clearConnectedState(n),this._isDisconnected()||(this._setStatus("disconnected"),this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),!1===this._reconnecting&&this.emit("disconnect",{reason:e,reconnect:n})),this._transportClosed||this._transport.close()}}},{key:"_refreshFailed",value:function(){this._numRefreshFailed=0,this._isDisconnected()||this._disconnect("refresh failed",!1),null!==this._config.onRefreshFailed&&this._config.onRefreshFailed()}},{key:"_refresh",value:function(){var e=this;if(this._debug("refresh token"),0===this._config.refreshAttempts)return this._debug("refresh attempts set to 0, do not send refresh request at all"),void this._refreshFailed();null!==this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null);var t=function(t){if(t.error||200!==t.status){if(t.error?e._debug("error refreshing connection token",t.error):e._debug("error refreshing connection token: wrong status code",t.status),e._numRefreshFailed++,null!==e._refreshTimeout&&(clearTimeout(e._refreshTimeout),e._refreshTimeout=null),null!==e._config.refreshAttempts&&e._numRefreshFailed>=e._config.refreshAttempts)return void e._refreshFailed();var n=Math.round(1e3*Math.random()*Math.max(e._numRefreshFailed,20)),s=e._config.refreshInterval+n;return void(e._refreshTimeout=setTimeout(function(){return e._refresh()},s))}if(e._numRefreshFailed=0,e._token=t.data.token,!e._token)return void e._refreshFailed();if(e._isDisconnected()&&e._reconnect)e._debug("token refreshed, connect from scratch"),e._connect();else{e._debug("send refreshed token");var i={method:e._methodType.REFRESH,params:{token:e._token}};e._call(i).then(function(t){e._refreshResponse(e._decoder.decodeCommandResult(e._methodType.REFRESH,t.result)),t.next&&t.next()},function(t){e._refreshError(t)})}};if(null!==this._config.onRefresh){var n={};this._config.onRefresh(n,t)}else this._ajax(this._config.refreshEndpoint,this._config.refreshParams,this._config.refreshHeaders,this._config.refreshData,t)}},{key:"_refreshError",value:function(e){var t=this;this._debug("refresh error",e),this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null);var n=this._config.refreshInterval+Math.round(1e3*Math.random());this._refreshTimeout=setTimeout(function(){return t._refresh()},n)}},{key:"_refreshResponse",value:function(e){var t=this;this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._clientID=e.client,this._refreshTimeout=setTimeout(function(){return t._refresh()},1e3*e.ttl))}},{key:"_subRefresh",value:function(e){var t=this;if(this._debug("refresh subscription token for channel",e),void 0!==this._subRefreshTimeouts[e]){this._clearSubRefreshTimeout(e);var n=function(n){if(!n.error&&200===n.status){var i={};if(n.data.channels)for(var r in s.channels){var o=n.data.channels[r];o.channel&&(i[o.channel]=o.token)}var u=i[e];if(u){var a={method:t._methodType.SUB_REFRESH,params:{channel:e,token:u}};null!==t._getSub(e)&&t._call(a).then(function(n){t._subRefreshResponse(e,t._decoder.decodeCommandResult(t._methodType.SUB_REFRESH,n.result)),n.next&&n.next()},function(n){t._subRefreshError(e,n)})}}},s={client:this._clientID,channels:[e]};null!==this._config.onPrivateSubscribe?this._config.onPrivateSubscribe({data:s},n):this._ajax(this._config.subscribeEndpoint,this._config.subscribeParams,this._config.subscribeHeaders,s,n)}}},{key:"_clearSubRefreshTimeout",value:function(e){void 0!==this._subRefreshTimeouts[e]&&(clearTimeout(this._subRefreshTimeouts[e]),delete this._subRefreshTimeouts[e])}},{key:"_subRefreshError",value:function(e,t){var n=this;if(this._debug("subscription refresh error",e,t),this._clearSubRefreshTimeout(e),null!==this._getSub(e)){var s=Math.round(1e3*Math.random()),i=setTimeout(function(){return n._subRefresh(e)},this._config.subRefreshInterval+s);this._subRefreshTimeouts[e]=i}}},{key:"_subRefreshResponse",value:function(e,t){var n=this;if(this._debug("subscription refresh success",e),this._clearSubRefreshTimeout(e),null!==this._getSub(e)&&!0===t.expires){var s=setTimeout(function(){return n._subRefresh(e)},1e3*t.ttl);this._subRefreshTimeouts[e]=s}}},{key:"_subscribe",value:function(e,t){var n=this;this._debug("subscribing on",e.channel);var s=e.channel;if(s in this._subs||(this._subs[s]=e),!this.isConnected())return void e._setNew();e._setSubscribing(t);var i={method:this._methodType.SUBSCRIBE,params:{channel:s}};if((0,d.startsWith)(s,this._config.privateChannelPrefix))this._isSubscribeBatching?this._privateChannels[s]=!0:(this.startSubscribeBatching(),this._subscribe(e),this.stopSubscribeBatching());else{if(!0===e._needRecover()){i.params.recover=!0;var r=this._getLastSeq(s);r&&(i.params.seq=r);var o=this._getLastGen(s);o&&(i.params.gen=o);var u=this._getLastEpoch(s);u&&(i.params.epoch=u)}this._call(i).then(function(e){n._subscribeResponse(s,n._decoder.decodeCommandResult(n._methodType.SUBSCRIBE,e.result)),e.next&&e.next()},function(e){n._subscribeError(s,e)})}}},{key:"_unsubscribe",value:function(e){this.isConnected()&&this._addMessage({method:this._methodType.UNSUBSCRIBE,params:{channel:e.channel}})}},{key:"getSub",value:function(e){return this._getSub(e)}},{key:"_getSub",value:function(e){var t=this._subs[e];return t||null}},{key:"_connectResponse",value:function(e){var t=this,n=this._reconnecting;if(this._reconnecting=!1,this._resetRetry(),!this.isConnected()){null!==this._latencyStart&&(this._latency=(new Date).getTime()-this._latencyStart.getTime(),this._latencyStart=null),this._clientID=e.client,this._setStatus("connected"),this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout(function(){return t._refresh()},1e3*e.ttl)),this.startBatching(),this.startSubscribeBatching();for(var s in this._subs)if(this._subs.hasOwnProperty(s)){var i=this._subs[s];i._shouldResubscribe()&&this._subscribe(i,n)}this.stopSubscribeBatching(),this.stopBatching(),this._startPing();var r={client:e.client,transport:this._transportName,latency:this._latency};e.data&&(r.data=e.data),this.emit("connect",r)}}},{key:"_stopPing",value:function(){null!==this._pongTimeout&&(clearTimeout(this._pongTimeout),this._pongTimeout=null),null!==this._pingTimeout&&(clearTimeout(this._pingTimeout),this._pingTimeout=null)}},{key:"_startPing",value:function(){var e=this;!0!==this._config.ping||this._config.pingInterval<=0||this.isConnected()&&(this._pingTimeout=setTimeout(function(){if(!e.isConnected())return void e._stopPing();e.ping(),e._pongTimeout=setTimeout(function(){e._disconnect("no ping",!0)},e._config.pongWaitTimeout)},this._config.pingInterval))}},{key:"_restartPing",value:function(){this._stopPing(),this._startPing()}},{key:"_subscribeError",value:function(e,t){var n=this._getSub(e);if(n&&n._isSubscribing())return 0===t.code&&"timeout"===t.message?void this._disconnect("timeout",!0):void n._setSubscribeError(t)}},{key:"_subscribeResponse",value:function(e,t){var n=this,s=this._getSub(e);if(s&&s._isSubscribing()){var i=!1;"recovered"in t&&(i=t.recovered),s._setSubscribeSuccess(i);var r=t.publications;if(r&&r.length>0){r=r.reverse();for(var o in r)r.hasOwnProperty(o)&&this._handlePublication(e,r[o])}else t.recoverable&&(this._lastSeq[e]=t.seq||0,this._lastGen[e]=t.gen||0);if(this._lastEpoch[e]=t.epoch||"",t.recoverable&&(s._recoverable=!0),!0===t.expires){var u=setTimeout(function(){return n._subRefresh(e)},1e3*t.ttl);this._subRefreshTimeouts[e]=u}}}},{key:"_handleReply",value:function(e,t){var n=e.id,s=e.result;if(n in this._callbacks){var i=this._callbacks[n];if(clearTimeout(this._callbacks[n].timeout),delete this._callbacks[n],(0,d.errorExists)(e)){var r=i.errback;if(!r)return;r(e.error)}else{var o=i.callback;if(!o)return;o({result:s,next:t})}}}},{key:"_handleJoin",value:function(e,t){var n=this._getSub(e);n&&n.emit("join",t)}},{key:"_handleLeave",value:function(e,t){var n=this._getSub(e);n&&n.emit("leave",t)}},{key:"_handleUnsub",value:function(e,t){var n=this._getSub(e);n&&(n.unsubscribe(),!0===t.resubscribe&&n.subscribe())}},{key:"_handlePublication",value:function(e,t){var n=this._getSub(e);n&&(void 0!==t.seq&&(this._lastSeq[e]=t.seq),void 0!==t.gen&&(this._lastGen[e]=t.gen),n.emit("publish",t))}},{key:"_handleMessage",value:function(e){this.emit("message",e.data)}},{key:"_handlePush",value:function(e,t){var n=this._decoder.decodePush(e),s=0;"type"in n&&(s=n.type);var i=n.channel;if(s===this._pushType.PUBLICATION){var r=this._decoder.decodePushData(this._pushType.PUBLICATION,n.data);this._handlePublication(i,r)}else if(s===this._pushType.MESSAGE){var o=this._decoder.decodePushData(this._pushType.MESSAGE,n.data);this._handleMessage(o)}else if(s===this._pushType.JOIN){var u=this._decoder.decodePushData(this._pushType.JOIN,n.data);this._handleJoin(i,u)}else if(s===this._pushType.LEAVE){var a=this._decoder.decodePushData(this._pushType.LEAVE,n.data);this._handleLeave(i,a)}else if(s===this._pushType.UNSUB){var c=this._decoder.decodePushData(this._pushType.UNSUB,n.data);this._handleUnsub(i,c)}t()}},{key:"_dispatchReply",value:function(e){var t,n=new Promise(function(e){t=e});if(void 0===e||null===e)return this._debug("dispatch: got undefined or null reply"),t(),n;var s=e.id;return s&&s>0?this._handleReply(e,t):this._handlePush(e.result,t),n}},{key:"_flush",value:function(){var e=this._messages.slice(0);this._messages=[],this._transportSend(e)}},{key:"_ping",value:function(){var e=this,t={method:this._methodType.PING};this._call(t).then(function(t){e._pingResponse(e._decoder.decodeCommandResult(e._methodType.PING,t.result)),t.next()},function(t){e._debug("ping error",t)})}},{key:"_pingResponse",value:function(e){this.isConnected()&&(this._stopPing(),this._startPing())}},{key:"_getLastSeq",value:function(e){var t=this._lastSeq[e];return t||0}},{key:"_getLastGen",value:function(e){var t=this._lastGen[e];return t||0}},{key:"_getLastEpoch",value:function(e){var t=this._lastEpoch[e];return t||""}},{key:"_createErrorObject",value:function(e,t){return{message:e,code:t||0}}},{key:"_registerCall",value:function(e,t,n){var s=this;this._callbacks[e]={callback:t,errback:n,timeout:null},this._callbacks[e].timeout=setTimeout(function(){delete s._callbacks[e],(0,d.isFunction)(n)&&n(s._createErrorObject("timeout"))},this._config.timeout)}},{key:"_addMessage",value:function(e,t){var n=void 0;return t||(n=this._nextMessageId(),e.id=n),!0===this._isBatching?this._messages.push(e):this._transportSend([e]),t?0:n}},{key:"isConnected",value:function(){return this._isConnected()}},{key:"connect",value:function(){this._connect()}},{key:"disconnect",value:function(){this._disconnect("client",!1)}},{key:"ping",value:function(){return this._ping()}},{key:"startBatching",value:function(){this._isBatching=!0}},{key:"stopBatching",value:function(){this._isBatching=!1,this._flush()}},{key:"startSubscribeBatching",value:function(){this._isSubscribeBatching=!0}},{key:"stopSubscribeBatching",value:function(){var e=this;this._isSubscribeBatching=!1;var t=this._privateChannels;this._privateChannels={};var n=[];for(var s in t)if(t.hasOwnProperty(s)){var i=this._getSub(s);if(!i)continue;n.push(s)}if(0===n.length)return void this._debug("no private channels found, no need to make request");var r={client:this._clientID,channels:n},o=function(t){if(t.error||200!==t.status){e._debug("authorization request failed");for(var s in n)if(n.hasOwnProperty(s)){var i=n[s];e._subscribeError(i,e._createErrorObject("authorization request failed"))}}else{var r={};if(t.data.channels)for(var o in t.data.channels){var u=t.data.channels[o];u.channel&&(r[u.channel]=u.token)}var a=!1;e._isBatching||(e.startBatching(),a=!0);for(var c in n)if(n.hasOwnProperty(c)){var h=function(){var t=n[c],s=r[t];if(!s)return e._subscribeError(t,e._createErrorObject("permission denied",103)),"continue";var i={method:e._methodType.SUBSCRIBE,params:{channel:t,token:s}},o=e._getSub(t);if(null===o)return"continue";if(!0===o._needRecover()){i.params.recover=!0;var u=e._getLastSeq(t);u&&(i.params.seq=u);var a=e._getLastGen(t);a&&(i.params.gen=a);var h=e._getLastEpoch(t);h&&(i.params.epoch=h)}e._call(i).then(function(n){e._subscribeResponse(t,e._decoder.decodeCommandResult(e._methodType.SUBSCRIBE,n.result)),n.next&&n.next()},function(n){e._subscribeError(t,n)})}();if("continue"===h)continue}a&&e.stopBatching()}};null!==this._config.onPrivateSubscribe?this._config.onPrivateSubscribe({data:r},o):this._ajax(this._config.subscribeEndpoint,this._config.subscribeParams,this._config.subscribeHeaders,r,o)}},{key:"subscribe",value:function(e,t){var n=this._getSub(e);if(null!==n)return n._setEvents(t),n._isUnsubscribed()&&n.subscribe(),n;var s=new _.default(this,e,t);return this._subs[e]=s,s.subscribe(),s}}]),n}(h.default)}).call(t,n(3))},11:function(e,t,n){"use strict";(function(s){function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function r(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t){for(var n=0;n<t.length;n++){var s=t[n];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}return function(t,n,s){return n&&e(t.prototype,n),s&&e(t,s),t}}(),a=n(6),c=function(e){return e&&e.__esModule?e:{default:e}}(a),h=n(7),l=0,_=function(e){function t(e,n,s){i(this,t);var o=r(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return o.channel=n,o._centrifuge=e,o._status=l,o._error=null,o._isResubscribe=!1,o._ready=!1,o._subscriptionPromise=null,o._noResubscribe=!1,o._recoverable=!1,o._recover=!1,o._setEvents(s),o._initializePromise(),o._promises={},o.on("error",function(e){this._centrifuge._debug("subscription error",e)}),o}return o(t,e),u(t,[{key:"_initializePromise",value:function(){var e=this;this._ready=!1,this._subscriptionPromise=new s.Promise(function(t,n){e._resolve=function(n){e._ready=!0,t(n)},e._reject=function(t){e._ready=!0,n(t)}}).then(function(){},function(){})}},{key:"_needRecover",value:function(){return!0===this._recoverable&&!0===this._recover}},{key:"_setEvents",value:function(e){if(e)if((0,h.isFunction)(e))this.on("publish",e);else if(Object.prototype.toString.call(e)===Object.prototype.toString.call({}))for(var t=["publish","join","leave","unsubscribe","subscribe","error"],n=0,s=t.length;n<s;n++){var i=t[n];i in e&&this.on(i,e[i])}}},{key:"_isNew",value:function(){return this._status===l}},{key:"_isUnsubscribed",value:function(){return 4===this._status}},{key:"_isSubscribing",value:function(){return 1===this._status}},{key:"_isReady",value:function(){return 2===this._status||3===this._status}},{key:"_isSuccess",value:function(){return 2===this._status}},{key:"_isError",value:function(){return 3===this._status}},{key:"_setNew",value:function(){this._status=l}},{key:"_setSubscribing",value:function(e){this._isResubscribe=e||!1,!0===this._ready&&this._initializePromise(),this._status=1}},{key:"_setSubscribeSuccess",value:function(e){if(2!==this._status){this._status=2;var t=this._getSubscribeSuccessContext(e);this._recover=!1,this.emit("subscribe",t),this._resolve(t);for(var n in this._promises)clearTimeout(n),this._promises[n].resolve(),delete this._promises[n]}}},{key:"_setSubscribeError",value:function(e){if(3!==this._status){this._status=3,this._error=e;var t=this._getSubscribeErrorContext();this.emit("error",t),this._reject(t);for(var n in this._promises)clearTimeout(n),this._promises[n].reject(e),delete this._promises[n]}}},{key:"_triggerUnsubscribe",value:function(){this.emit("unsubscribe",{channel:this.channel})}},{key:"_setUnsubscribed",value:function(e){if(this._centrifuge._clearSubRefreshTimeout(this.channel),4!==this._status){var t=2===this._status;this._status=4,!0===e&&(this._recover=!1,this._noResubscribe=!0,delete this._centrifuge._lastSeq[this.channel],delete this._centrifuge._lastGen[this.channel],delete this._centrifuge._lastEpoch[this.channel]),t&&this._triggerUnsubscribe()}}},{key:"_shouldResubscribe",value:function(){return!this._noResubscribe}},{key:"_getSubscribeSuccessContext",value:function(e){return{channel:this.channel,isResubscribe:this._isResubscribe,recovered:e}}},{key:"_getSubscribeErrorContext",value:function(){var e=this._error;return e.channel=this.channel,e.isResubscribe=this._isResubscribe,e}},{key:"ready",value:function(e,t){this._ready&&(this._isSuccess()?e(this._getSubscribeSuccessContext()):t(this._getSubscribeErrorContext()))}},{key:"subscribe",value:function(){2!==this._status&&(this._noResubscribe=!1,this._centrifuge._subscribe(this))}},{key:"unsubscribe",value:function(){this._setUnsubscribed(!0),this._centrifuge._unsubscribe(this)}},{key:"_methodCall",value:function(e,t){var n=this;return new Promise(function(s,i){var r=void 0;r=n._isSuccess()?Promise.resolve():n._isError()?Promise.reject(n._error):new Promise(function(e,t){var s=setTimeout(function(){t({code:0,message:"timeout"})},n._centrifuge._config.timeout);n._promises[s]={resolve:e,reject:t}}),r.then(function(){return n._centrifuge._call(e).then(function(e){s(n._centrifuge._decoder.decodeCommandResult(t,e.result)),e.next&&e.next()},function(e){i(e)})},function(e){i(e)})})}},{key:"publish",value:function(e){return this._methodCall({method:this._centrifuge._methodType.PUBLISH,params:{channel:this.channel,data:e}},this._centrifuge._methodType.PUBLISH)}},{key:"presence",value:function(){return this._methodCall({method:this._centrifuge._methodType.PRESENCE,params:{channel:this.channel}},this._centrifuge._methodType.PRESENCE)}},{key:"presenceStats",value:function(){return this._methodCall({method:this._centrifuge._methodType.PRESENCE_STATS,params:{channel:this.channel}},this._centrifuge._methodType.PRESENCE_STATS)}},{key:"history",value:function(){return this._methodCall({method:this._centrifuge._methodType.HISTORY,params:{channel:this.channel}},this._centrifuge._methodType.HISTORY)}}]),t}(c.default);t.default=_,e.exports=t.default}).call(t,n(3))},12:function(e,t,n){"use strict";function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var s=t[n];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}return function(t,n,s){return n&&e(t.prototype,n),s&&e(t,s),t}}();t.JsonMethodType={CONNECT:0,SUBSCRIBE:1,UNSUBSCRIBE:2,PUBLISH:3,PRESENCE:4,PRESENCE_STATS:5,HISTORY:6,PING:7,SEND:8,RPC:9,REFRESH:10,SUB_REFRESH:11},t.JsonPushType={PUBLICATION:0,JOIN:1,LEAVE:2,UNSUB:3,MESSAGE:4},t.JsonEncoder=function(){function e(){s(this,e)}return i(e,[{key:"encodeCommands",value:function(e){var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(JSON.stringify(e[n]));return t.join("\n")}}]),e}(),t.JsonDecoder=function(){function e(){s(this,e)}return i(e,[{key:"decodeReplies",value:function(e){var t=[],n=e.split("\n");for(var s in n)if(n.hasOwnProperty(s)){if(!n[s])continue;var i=JSON.parse(n[s]);t.push(i)}return t}},{key:"decodeCommandResult",value:function(e,t){return t}},{key:"decodePush",value:function(e){return e}},{key:"decodePushData",value:function(e,t){return t}}]),e}()},3:function(e,t){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(n=window)}e.exports=n},31:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var s=n(10);t.default=s.Centrifuge,e.exports=t.default},6:function(e,t){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function s(e){return"function"==typeof e}function i(e){return"number"==typeof e}function r(e){return"object"==typeof e&&null!==e}function o(e){return void 0===e}e.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(e){if(!i(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},n.prototype.emit=function(e){var t,n,i,u,a,c;if(this._events||(this._events={}),"error"===e&&(!this._events.error||r(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var h=new Error('Uncaught, unspecified "error" event. ('+t+")");throw h.context=t,h}if(n=this._events[e],o(n))return!1;if(s(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:u=Array.prototype.slice.call(arguments,1),n.apply(this,u)}else if(r(n))for(u=Array.prototype.slice.call(arguments,1),c=n.slice(),i=c.length,a=0;a<i;a++)c[a].apply(this,u);return!0},n.prototype.addListener=function(e,t){var i;if(!s(t))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,s(t.listener)?t.listener:t),this._events[e]?r(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,r(this._events[e])&&!this._events[e].warned&&(i=o(this._maxListeners)?n.defaultMaxListeners:this._maxListeners)&&i>0&&this._events[e].length>i&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){function n(){this.removeListener(e,n),i||(i=!0,t.apply(this,arguments))}if(!s(t))throw TypeError("listener must be a function");var i=!1;return n.listener=t,this.on(e,n),this},n.prototype.removeListener=function(e,t){var n,i,o,u;if(!s(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(n=this._events[e],o=n.length,i=-1,n===t||s(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(r(n)){for(u=o;u-- >0;)if(n[u]===t||n[u].listener&&n[u].listener===t){i=u;break}if(i<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(i,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},n.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[e],s(n))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){return this._events&&this._events[e]?s(this._events[e])?[this._events[e]]:this._events[e].slice():[]},n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(s(t))return 1;if(t)return t.length}return 0},n.listenerCount=function(e,t){return e.listenerCount(t)}},7:function(e,t,n){"use strict";(function(e){function n(e,t){return 0===e.lastIndexOf(t,0)}function s(e){return void 0!==e&&null!==e&&"function"==typeof e}function i(t,n){if(e.console){var i=e.console[t];s(i)&&i.apply(e.console,n)}}function r(e,t,n){var s=.5*Math.random(),i=Math.min(n,t*Math.pow(2,e+1));return Math.floor((1-s)*i)}function o(e){return"error"in e&&null!==e.error}Object.defineProperty(t,"__esModule",{value:!0}),t.startsWith=n,t.isFunction=s,t.log=i,t.backoff=r,t.errorExists=o}).call(t,n(3))}})}); | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("Centrifuge",[],t):"object"==typeof exports?exports.Centrifuge=t():e.Centrifuge=t()}("undefined"!=typeof self?self:this,function(){return function(e){function t(s){if(n[s])return n[s].exports;var r=n[s]={i:s,l:!1,exports:{}};return e[s].call(r.exports,r,r.exports,t),r.l=!0,r.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,s){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:s})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=31)}({10:function(e,t,n){"use strict";(function(e){function s(e){return e&&e.__esModule?e:{default:e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0}),t.Centrifuge=void 0;var u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a=function(){function e(e,t){for(var n=0;n<t.length;n++){var s=t[n];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}return function(t,n,s){return n&&e(t.prototype,n),s&&e(t,s),t}}(),c=n(6),h=s(c),l=n(11),_=s(l),f=n(12),d=n(7);t.Centrifuge=function(t){function n(e,t){r(this,n);var s=i(this,(n.__proto__||Object.getPrototypeOf(n)).call(this));return s._url=e,s._sockjs=null,s._isSockjs=!1,s._binary=!1,s._methodType=null,s._pushType=null,s._encoder=null,s._decoder=null,s._status="disconnected",s._reconnect=!0,s._reconnecting=!1,s._transport=null,s._transportName=null,s._transportClosed=!0,s._messageId=0,s._clientID=null,s._refreshRequired=!1,s._subs={},s._lastSeq={},s._lastGen={},s._lastEpoch={},s._messages=[],s._isBatching=!1,s._isSubscribeBatching=!1,s._privateChannels={},s._numRefreshFailed=0,s._refreshTimeout=null,s._pingTimeout=null,s._pongTimeout=null,s._subRefreshTimeouts={},s._retries=0,s._callbacks={},s._latency=null,s._latencyStart=null,s._connectData=null,s._token=null,s._config={debug:!1,sockjs:null,promise:null,minRetry:1e3,maxRetry:2e4,timeout:5e3,ping:!0,pingInterval:25e3,pongWaitTimeout:5e3,privateChannelPrefix:"$",onTransportClose:null,sockjsServer:null,sockjsTransports:["websocket","xdr-streaming","xhr-streaming","eventsource","iframe-eventsource","iframe-htmlfile","xdr-polling","xhr-polling","iframe-xhr-polling","jsonp-polling"],refreshEndpoint:"/centrifuge/refresh",refreshHeaders:{},refreshParams:{},refreshData:{},refreshAttempts:null,refreshInterval:1e3,onRefreshFailed:null,onRefresh:null,subscribeEndpoint:"/centrifuge/subscribe",subscribeHeaders:{},subscribeParams:{},subRefreshInterval:1e3,onPrivateSubscribe:null},s._configure(t),s}return o(n,t),a(n,[{key:"setToken",value:function(e){this._token=e}},{key:"setConnectData",value:function(e){this._connectData=e}},{key:"_ajax",value:function(t,n,s,r,i){var o=this,u="";this._debug("sending AJAX request to",t,"with data",JSON.stringify(r));var a=e.XMLHttpRequest?new e.XMLHttpRequest:new e.ActiveXObject("Microsoft.XMLHTTP");for(var c in n)n.hasOwnProperty(c)&&(u.length>0&&(u+="&"),u+=encodeURIComponent(c)+"="+encodeURIComponent(n[c]));u.length>0&&(u="?"+u),a.open("POST",t+u,!0),"withCredentials"in a&&(a.withCredentials=!0),a.setRequestHeader("X-Requested-With","XMLHttpRequest"),a.setRequestHeader("Content-Type","application/json");for(var h in s)s.hasOwnProperty(h)&&a.setRequestHeader(h,s[h]);return a.onreadystatechange=function(){if(4===a.readyState)if(200===a.status){var e=void 0,t=!1;try{e=JSON.parse(a.responseText),t=!0}catch(e){i({error:"Invalid JSON. Data was: "+a.responseText,status:200,data:null})}t&&i({data:e,status:200})}else o._log("wrong status code in AJAX response",a.status),i({status:a.status,data:null})},setTimeout(function(){return a.send(JSON.stringify(r))},20),a}},{key:"_log",value:function(){(0,d.log)("info",arguments)}},{key:"_debug",value:function(){!0===this._config.debug&&(0,d.log)("debug",arguments)}},{key:"_websocketSupported",value:function(){return!("function"!=typeof WebSocket&&"object"!==("undefined"==typeof WebSocket?"undefined":u(WebSocket)))}},{key:"_setFormat",value:function(e){if(!this._formatOverride(e)){if("protobuf"===e)throw new Error("not implemented by JSON only Centrifuge client – use client with Protobuf");this._binary=!1,this._methodType=f.JsonMethodType,this._pushType=f.JsonPushType,this._encoder=new f.JsonEncoder,this._decoder=new f.JsonDecoder}}},{key:"_formatOverride",value:function(e){return!1}},{key:"_configure",value:function(t){if(!("Promise"in e))throw new Error("Promise polyfill required");if(Object.assign(this._config,t||{}),this._debug("centrifuge config",this._config),!this._url)throw new Error("url required");if((0,d.startsWith)(this._url,"ws")&&this._url.indexOf("format=protobuf")>-1?this._setFormat("protobuf"):this._setFormat("json"),(0,d.startsWith)(this._url,"http"))if(this._debug("client will try to connect to SockJS endpoint"),null!==this._config.sockjs)this._debug("SockJS explicitly provided in options"),this._sockjs=this._config.sockjs;else{if(void 0===e.SockJS)throw new Error("SockJS not found, use ws:// in url or include SockJS");this._debug("use globally defined SockJS"),this._sockjs=e.SockJS}else this._debug("client will connect to websocket endpoint")}},{key:"_setStatus",value:function(e){this._status!==e&&(this._debug("Status",this._status,"->",e),this._status=e)}},{key:"_isDisconnected",value:function(){return"disconnected"===this._status}},{key:"_isConnecting",value:function(){return"connecting"===this._status}},{key:"_isConnected",value:function(){return"connected"===this._status}},{key:"_nextMessageId",value:function(){return++this._messageId}},{key:"_resetRetry",value:function(){this._debug("reset retries count to 0"),this._retries=0}},{key:"_getRetryInterval",value:function(){var e=(0,d.backoff)(this._retries,this._config.minRetry,this._config.maxRetry);return this._retries+=1,e}},{key:"_clearConnectedState",value:function(e){this._clientID=null,this._stopPing();for(var t in this._callbacks)if(this._callbacks.hasOwnProperty(t)){var n=this._callbacks[t];clearTimeout(n.timeout);var s=n.errback;if(!s)continue;s(this._createErrorObject("disconnected"))}this._callbacks={};for(var r in this._subs)if(this._subs.hasOwnProperty(r)){var i=this._subs[r];e?(i._isSuccess()&&(i._triggerUnsubscribe(),i._recover=!0),i._setSubscribing()):i._setUnsubscribed()}null!==this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null);for(var o in this._subRefreshTimeouts)this._subRefreshTimeouts.hasOwnProperty(o)&&this._subRefreshTimeouts[o]&&this._clearSubRefreshTimeout(o);this._subRefreshTimeouts={},this._reconnect||(this._subs={})}},{key:"_transportSend",value:function(e){if(!e.length)return!0;if(!this._transport||!this._transport._transport||this._transport._transport.readyState!==this._transport._transport.OPEN){for(var t in e){var n=t.id;if(n in this._callbacks){var s=this._callbacks[n];clearTimeout(this._callbacks[n].timeout),delete this._callbacks[n],(0,s.errback)(this._createErrorObject("connection closed",0))}}return!1}return this._transport.send(this._encoder.encodeCommands(e)),!0}},{key:"_setupTransport",value:function(){var e=this;if(this._isSockjs=!1,null!==this._sockjs){var t={transports:this._config.sockjsTransports};null!==this._config.sockjsServer&&(t.server=this._config.sockjsServer),this._isSockjs=!0,this._transport=new this._sockjs(this._url,null,t)}else{if(!this._websocketSupported())return void this._debug("No Websocket support and no SockJS configured, can not connect");this._transport=new WebSocket(this._url),!0===this._binary&&(this._transport.binaryType="arraybuffer")}this._transport.onopen=function(){e._transportClosed=!1,e._isSockjs?(e._transportName="sockjs-"+e._transport.transport,e._transport.onheartbeat=function(){return e._restartPing()}):e._transportName="websocket";var t={};(e._token||e._connectData)&&(t.params={}),e._token&&(t.params.token=e._token),e._connectData&&(t.params.data=e._connectData),e._latencyStart=new Date,e._call(t).then(function(t){e._connectResponse(e._decoder.decodeCommandResult(e._methodType.CONNECT,t.result)),t.next&&t.next()},function(t){109===t.code&&(e._refreshRequired=!0),e._disconnect("connect error",!0)})},this._transport.onerror=function(t){e._debug("transport level error",t)},this._transport.onclose=function(t){e._transportClosed=!0;var n="connection closed",s=!0;if(t&&"reason"in t&&t.reason)try{var r=JSON.parse(t.reason);e._debug("reason is an advice object",r),n=r.reason,s=r.reconnect}catch(s){n=t.reason,e._debug("reason is a plain string",n)}if(null!==e._config.onTransportClose&&e._config.onTransportClose({event:t,reason:n,reconnect:s}),e._disconnect(n,s),!0===e._reconnect){e._reconnecting=!0;var i=e._getRetryInterval();e._debug("reconnect after "+i+" milliseconds"),setTimeout(function(){!0===e._reconnect&&(e._refreshRequired?e._refresh():e._connect())},i)}},this._transport.onmessage=function(t){e._dataReceived(t.data)}}},{key:"rpc",value:function(e){var t=this,n={method:this._methodType.RPC,params:{data:e}};return this.isConnected()?this._call(n).then(function(e){return e.next&&e.next(),t._decoder.decodeCommandResult(t._methodType.RPC,e.result)}):Promise.reject(this._createErrorObject("connection closed",0))}},{key:"send",value:function(e){var t={method:this._methodType.SEND,params:{data:e}};return this.isConnected()&&this._transportSend([t])?Promise.resolve({}):Promise.reject(this._createErrorObject("connection closed",0))}},{key:"publish",value:function(e,t){var n={method:this._methodType.PUBLISH,params:{channel:e,data:t}};return this.isConnected()?this._call(n).then(function(e){return e.next&&e.next(),{}}):Promise.reject(this._createErrorObject("connection closed",0))}},{key:"_dataReceived",value:function(e){var t=this,n=this._decoder.decodeReplies(e),s=Promise.resolve();for(var r in n)!function(e){n.hasOwnProperty(e)&&(s=s.then(function(){return t._dispatchReply(n[e])}))}(r);this._restartPing()}},{key:"_call",value:function(e){var t=this;return new Promise(function(n,s){var r=t._addMessage(e);t._registerCall(r,n,s)})}},{key:"_connect",value:function(){if(this.isConnected())return void this._debug("connect called when already connected");"connecting"!==this._status&&(this._debug("start connecting"),this._setStatus("connecting"),this._clientID=null,this._reconnect=!0,this._setupTransport())}},{key:"_disconnect",value:function(e,t){if(!this._isDisconnected()){this._debug("disconnected:",e,t);var n=t||!1;!1===n&&(this._reconnect=!1),this._clearConnectedState(n),this._isDisconnected()||(this._setStatus("disconnected"),this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),!1===this._reconnecting&&this.emit("disconnect",{reason:e,reconnect:n})),this._transportClosed||this._transport.close()}}},{key:"_refreshFailed",value:function(){this._numRefreshFailed=0,this._isDisconnected()||this._disconnect("refresh failed",!1),null!==this._config.onRefreshFailed&&this._config.onRefreshFailed()}},{key:"_refresh",value:function(){var e=this;if(this._debug("refresh token"),0===this._config.refreshAttempts)return this._debug("refresh attempts set to 0, do not send refresh request at all"),void this._refreshFailed();null!==this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null);var t=function(t){if(t.error||200!==t.status){if(t.error?e._debug("error refreshing connection token",t.error):e._debug("error refreshing connection token: wrong status code",t.status),e._numRefreshFailed++,null!==e._refreshTimeout&&(clearTimeout(e._refreshTimeout),e._refreshTimeout=null),null!==e._config.refreshAttempts&&e._numRefreshFailed>=e._config.refreshAttempts)return void e._refreshFailed();var n=Math.round(1e3*Math.random()*Math.max(e._numRefreshFailed,20)),s=e._config.refreshInterval+n;return void(e._refreshTimeout=setTimeout(function(){return e._refresh()},s))}if(e._numRefreshFailed=0,e._token=t.data.token,!e._token)return void e._refreshFailed();if(e._isDisconnected()&&e._reconnect)e._debug("token refreshed, connect from scratch"),e._connect();else{e._debug("send refreshed token");var r={method:e._methodType.REFRESH,params:{token:e._token}};e._call(r).then(function(t){e._refreshResponse(e._decoder.decodeCommandResult(e._methodType.REFRESH,t.result)),t.next&&t.next()},function(t){e._refreshError(t)})}};if(null!==this._config.onRefresh){var n={};this._config.onRefresh(n,t)}else this._ajax(this._config.refreshEndpoint,this._config.refreshParams,this._config.refreshHeaders,this._config.refreshData,t)}},{key:"_refreshError",value:function(e){var t=this;this._debug("refresh error",e),this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null);var n=this._config.refreshInterval+Math.round(1e3*Math.random());this._refreshTimeout=setTimeout(function(){return t._refresh()},n)}},{key:"_refreshResponse",value:function(e){var t=this;this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._clientID=e.client,this._refreshTimeout=setTimeout(function(){return t._refresh()},1e3*e.ttl))}},{key:"_subRefresh",value:function(e){var t=this;if(this._debug("refresh subscription token for channel",e),void 0!==this._subRefreshTimeouts[e]){this._clearSubRefreshTimeout(e);var n=function(n){if(!n.error&&200===n.status){var r={};if(n.data.channels)for(var i in s.channels){var o=n.data.channels[i];o.channel&&(r[o.channel]=o.token)}var u=r[e];if(u){var a={method:t._methodType.SUB_REFRESH,params:{channel:e,token:u}};null!==t._getSub(e)&&t._call(a).then(function(n){t._subRefreshResponse(e,t._decoder.decodeCommandResult(t._methodType.SUB_REFRESH,n.result)),n.next&&n.next()},function(n){t._subRefreshError(e,n)})}}},s={client:this._clientID,channels:[e]};null!==this._config.onPrivateSubscribe?this._config.onPrivateSubscribe({data:s},n):this._ajax(this._config.subscribeEndpoint,this._config.subscribeParams,this._config.subscribeHeaders,s,n)}}},{key:"_clearSubRefreshTimeout",value:function(e){void 0!==this._subRefreshTimeouts[e]&&(clearTimeout(this._subRefreshTimeouts[e]),delete this._subRefreshTimeouts[e])}},{key:"_subRefreshError",value:function(e,t){var n=this;if(this._debug("subscription refresh error",e,t),this._clearSubRefreshTimeout(e),null!==this._getSub(e)){var s=Math.round(1e3*Math.random()),r=setTimeout(function(){return n._subRefresh(e)},this._config.subRefreshInterval+s);this._subRefreshTimeouts[e]=r}}},{key:"_subRefreshResponse",value:function(e,t){var n=this;if(this._debug("subscription refresh success",e),this._clearSubRefreshTimeout(e),null!==this._getSub(e)&&!0===t.expires){var s=setTimeout(function(){return n._subRefresh(e)},1e3*t.ttl);this._subRefreshTimeouts[e]=s}}},{key:"_subscribe",value:function(e,t){var n=this;this._debug("subscribing on",e.channel);var s=e.channel;if(s in this._subs||(this._subs[s]=e),!this.isConnected())return void e._setNew();e._setSubscribing(t);var r={method:this._methodType.SUBSCRIBE,params:{channel:s}};if((0,d.startsWith)(s,this._config.privateChannelPrefix))this._isSubscribeBatching?this._privateChannels[s]=!0:(this.startSubscribeBatching(),this._subscribe(e),this.stopSubscribeBatching());else{if(!0===e._needRecover()){r.params.recover=!0;var i=this._getLastSeq(s);i&&(r.params.seq=i);var o=this._getLastGen(s);o&&(r.params.gen=o);var u=this._getLastEpoch(s);u&&(r.params.epoch=u)}this._call(r).then(function(e){n._subscribeResponse(s,n._decoder.decodeCommandResult(n._methodType.SUBSCRIBE,e.result)),e.next&&e.next()},function(e){n._subscribeError(s,e)})}}},{key:"_unsubscribe",value:function(e){this.isConnected()&&this._addMessage({method:this._methodType.UNSUBSCRIBE,params:{channel:e.channel}})}},{key:"getSub",value:function(e){return this._getSub(e)}},{key:"_getSub",value:function(e){var t=this._subs[e];return t||null}},{key:"_connectResponse",value:function(e){var t=this,n=this._reconnecting;if(this._reconnecting=!1,this._resetRetry(),!this.isConnected()){null!==this._latencyStart&&(this._latency=(new Date).getTime()-this._latencyStart.getTime(),this._latencyStart=null),this._clientID=e.client,this._setStatus("connected"),this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout(function(){return t._refresh()},1e3*e.ttl)),this.startBatching(),this.startSubscribeBatching();for(var s in this._subs)if(this._subs.hasOwnProperty(s)){var r=this._subs[s];r._shouldResubscribe()&&this._subscribe(r,n)}this.stopSubscribeBatching(),this.stopBatching(),this._startPing();var i={client:e.client,transport:this._transportName,latency:this._latency};e.data&&(i.data=e.data),this.emit("connect",i)}}},{key:"_stopPing",value:function(){null!==this._pongTimeout&&(clearTimeout(this._pongTimeout),this._pongTimeout=null),null!==this._pingTimeout&&(clearTimeout(this._pingTimeout),this._pingTimeout=null)}},{key:"_startPing",value:function(){var e=this;!0!==this._config.ping||this._config.pingInterval<=0||this.isConnected()&&(this._pingTimeout=setTimeout(function(){if(!e.isConnected())return void e._stopPing();e.ping(),e._pongTimeout=setTimeout(function(){e._disconnect("no ping",!0)},e._config.pongWaitTimeout)},this._config.pingInterval))}},{key:"_restartPing",value:function(){this._stopPing(),this._startPing()}},{key:"_subscribeError",value:function(e,t){var n=this._getSub(e);if(n&&n._isSubscribing())return 0===t.code&&"timeout"===t.message?void this._disconnect("timeout",!0):void n._setSubscribeError(t)}},{key:"_subscribeResponse",value:function(e,t){var n=this,s=this._getSub(e);if(s&&s._isSubscribing()){var r=!1;"recovered"in t&&(r=t.recovered),s._setSubscribeSuccess(r);var i=t.publications;if(i&&i.length>0){i=i.reverse();for(var o in i)i.hasOwnProperty(o)&&this._handlePublication(e,i[o])}else t.recoverable&&(this._lastSeq[e]=t.seq||0,this._lastGen[e]=t.gen||0);if(this._lastEpoch[e]=t.epoch||"",t.recoverable&&(s._recoverable=!0),!0===t.expires){var u=setTimeout(function(){return n._subRefresh(e)},1e3*t.ttl);this._subRefreshTimeouts[e]=u}}}},{key:"_handleReply",value:function(e,t){var n=e.id,s=e.result;if(n in this._callbacks){var r=this._callbacks[n];if(clearTimeout(this._callbacks[n].timeout),delete this._callbacks[n],(0,d.errorExists)(e)){var i=r.errback;if(!i)return;i(e.error)}else{var o=r.callback;if(!o)return;o({result:s,next:t})}}}},{key:"_handleJoin",value:function(e,t){var n=this._getSub(e);n&&n.emit("join",t)}},{key:"_handleLeave",value:function(e,t){var n=this._getSub(e);n&&n.emit("leave",t)}},{key:"_handleUnsub",value:function(e,t){var n=this._getSub(e);n&&(n.unsubscribe(),!0===t.resubscribe&&n.subscribe())}},{key:"_handlePublication",value:function(e,t){var n=this._getSub(e);n&&(void 0!==t.seq&&(this._lastSeq[e]=t.seq),void 0!==t.gen&&(this._lastGen[e]=t.gen),n.emit("publish",t))}},{key:"_handleMessage",value:function(e){this.emit("message",e.data)}},{key:"_handlePush",value:function(e,t){var n=this._decoder.decodePush(e),s=0;"type"in n&&(s=n.type);var r=n.channel;if(s===this._pushType.PUBLICATION){var i=this._decoder.decodePushData(this._pushType.PUBLICATION,n.data);this._handlePublication(r,i)}else if(s===this._pushType.MESSAGE){var o=this._decoder.decodePushData(this._pushType.MESSAGE,n.data);this._handleMessage(o)}else if(s===this._pushType.JOIN){var u=this._decoder.decodePushData(this._pushType.JOIN,n.data);this._handleJoin(r,u)}else if(s===this._pushType.LEAVE){var a=this._decoder.decodePushData(this._pushType.LEAVE,n.data);this._handleLeave(r,a)}else if(s===this._pushType.UNSUB){var c=this._decoder.decodePushData(this._pushType.UNSUB,n.data);this._handleUnsub(r,c)}t()}},{key:"_dispatchReply",value:function(e){var t,n=new Promise(function(e){t=e});if(void 0===e||null===e)return this._debug("dispatch: got undefined or null reply"),t(),n;var s=e.id;return s&&s>0?this._handleReply(e,t):this._handlePush(e.result,t),n}},{key:"_flush",value:function(){var e=this._messages.slice(0);this._messages=[],this._transportSend(e)}},{key:"_ping",value:function(){var e=this,t={method:this._methodType.PING};this._call(t).then(function(t){e._pingResponse(e._decoder.decodeCommandResult(e._methodType.PING,t.result)),t.next()},function(t){e._debug("ping error",t)})}},{key:"_pingResponse",value:function(e){this.isConnected()&&(this._stopPing(),this._startPing())}},{key:"_getLastSeq",value:function(e){var t=this._lastSeq[e];return t||0}},{key:"_getLastGen",value:function(e){var t=this._lastGen[e];return t||0}},{key:"_getLastEpoch",value:function(e){var t=this._lastEpoch[e];return t||""}},{key:"_createErrorObject",value:function(e,t){return{message:e,code:t||0}}},{key:"_registerCall",value:function(e,t,n){var s=this;this._callbacks[e]={callback:t,errback:n,timeout:null},this._callbacks[e].timeout=setTimeout(function(){delete s._callbacks[e],(0,d.isFunction)(n)&&n(s._createErrorObject("timeout"))},this._config.timeout)}},{key:"_addMessage",value:function(e){var t=this._nextMessageId();return e.id=t,!0===this._isBatching?this._messages.push(e):this._transportSend([e]),t}},{key:"isConnected",value:function(){return this._isConnected()}},{key:"connect",value:function(){this._connect()}},{key:"disconnect",value:function(){this._disconnect("client",!1)}},{key:"ping",value:function(){return this._ping()}},{key:"startBatching",value:function(){this._isBatching=!0}},{key:"stopBatching",value:function(){this._isBatching=!1,this._flush()}},{key:"startSubscribeBatching",value:function(){this._isSubscribeBatching=!0}},{key:"stopSubscribeBatching",value:function(){var e=this;this._isSubscribeBatching=!1;var t=this._privateChannels;this._privateChannels={};var n=[];for(var s in t)if(t.hasOwnProperty(s)){var r=this._getSub(s);if(!r)continue;n.push(s)}if(0===n.length)return void this._debug("no private channels found, no need to make request");var i={client:this._clientID,channels:n},o=function(t){if(t.error||200!==t.status){e._debug("authorization request failed");for(var s in n)if(n.hasOwnProperty(s)){var r=n[s];e._subscribeError(r,e._createErrorObject("authorization request failed"))}}else{var i={};if(t.data.channels)for(var o in t.data.channels){var u=t.data.channels[o];u.channel&&(i[u.channel]=u.token)}var a=!1;e._isBatching||(e.startBatching(),a=!0);for(var c in n)if(n.hasOwnProperty(c)){var h=function(){var t=n[c],s=i[t];if(!s)return e._subscribeError(t,e._createErrorObject("permission denied",103)),"continue";var r={method:e._methodType.SUBSCRIBE,params:{channel:t,token:s}},o=e._getSub(t);if(null===o)return"continue";if(!0===o._needRecover()){r.params.recover=!0;var u=e._getLastSeq(t);u&&(r.params.seq=u);var a=e._getLastGen(t);a&&(r.params.gen=a);var h=e._getLastEpoch(t);h&&(r.params.epoch=h)}e._call(r).then(function(n){e._subscribeResponse(t,e._decoder.decodeCommandResult(e._methodType.SUBSCRIBE,n.result)),n.next&&n.next()},function(n){e._subscribeError(t,n)})}();if("continue"===h)continue}a&&e.stopBatching()}};null!==this._config.onPrivateSubscribe?this._config.onPrivateSubscribe({data:i},o):this._ajax(this._config.subscribeEndpoint,this._config.subscribeParams,this._config.subscribeHeaders,i,o)}},{key:"subscribe",value:function(e,t){var n=this._getSub(e);if(null!==n)return n._setEvents(t),n._isUnsubscribed()&&n.subscribe(),n;var s=new _.default(this,e,t);return this._subs[e]=s,s.subscribe(),s}}]),n}(h.default)}).call(t,n(3))},11:function(e,t,n){"use strict";function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function r(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var o=function(){function e(e,t){for(var n=0;n<t.length;n++){var s=t[n];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}return function(t,n,s){return n&&e(t.prototype,n),s&&e(t,s),t}}(),u=n(6),a=function(e){return e&&e.__esModule?e:{default:e}}(u),c=n(7),h=0,l=function(e){function t(e,n,i){s(this,t);var o=r(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return o.channel=n,o._centrifuge=e,o._status=h,o._error=null,o._isResubscribe=!1,o._ready=!1,o._subscriptionPromise=null,o._noResubscribe=!1,o._recoverable=!1,o._recover=!1,o._setEvents(i),o._initializePromise(),o._promises={},o.on("error",function(e){this._centrifuge._debug("subscription error",e)}),o}return i(t,e),o(t,[{key:"_initializePromise",value:function(){var e=this;this._ready=!1,this._subscriptionPromise=new Promise(function(t,n){e._resolve=function(n){e._ready=!0,t(n)},e._reject=function(t){e._ready=!0,n(t)}}).then(function(){},function(){})}},{key:"_needRecover",value:function(){return!0===this._recoverable&&!0===this._recover}},{key:"_setEvents",value:function(e){if(e)if((0,c.isFunction)(e))this.on("publish",e);else if(Object.prototype.toString.call(e)===Object.prototype.toString.call({}))for(var t=["publish","join","leave","unsubscribe","subscribe","error"],n=0,s=t.length;n<s;n++){var r=t[n];r in e&&this.on(r,e[r])}}},{key:"_isNew",value:function(){return this._status===h}},{key:"_isUnsubscribed",value:function(){return 4===this._status}},{key:"_isSubscribing",value:function(){return 1===this._status}},{key:"_isReady",value:function(){return 2===this._status||3===this._status}},{key:"_isSuccess",value:function(){return 2===this._status}},{key:"_isError",value:function(){return 3===this._status}},{key:"_setNew",value:function(){this._status=h}},{key:"_setSubscribing",value:function(e){this._isResubscribe=e||!1,!0===this._ready&&this._initializePromise(),this._status=1}},{key:"_setSubscribeSuccess",value:function(e){if(2!==this._status){this._status=2;var t=this._getSubscribeSuccessContext(e);this._recover=!1,this.emit("subscribe",t),this._resolve(t);for(var n in this._promises)clearTimeout(n),this._promises[n].resolve(),delete this._promises[n]}}},{key:"_setSubscribeError",value:function(e){if(3!==this._status){this._status=3,this._error=e;var t=this._getSubscribeErrorContext();this.emit("error",t),this._reject(t);for(var n in this._promises)clearTimeout(n),this._promises[n].reject(e),delete this._promises[n]}}},{key:"_triggerUnsubscribe",value:function(){this.emit("unsubscribe",{channel:this.channel})}},{key:"_setUnsubscribed",value:function(e){if(this._centrifuge._clearSubRefreshTimeout(this.channel),4!==this._status){var t=2===this._status;this._status=4,!0===e&&(this._recover=!1,this._noResubscribe=!0,delete this._centrifuge._lastSeq[this.channel],delete this._centrifuge._lastGen[this.channel],delete this._centrifuge._lastEpoch[this.channel]),t&&this._triggerUnsubscribe()}}},{key:"_shouldResubscribe",value:function(){return!this._noResubscribe}},{key:"_getSubscribeSuccessContext",value:function(e){return{channel:this.channel,isResubscribe:this._isResubscribe,recovered:e}}},{key:"_getSubscribeErrorContext",value:function(){var e=this._error;return e.channel=this.channel,e.isResubscribe=this._isResubscribe,e}},{key:"ready",value:function(e,t){this._ready&&(this._isSuccess()?e(this._getSubscribeSuccessContext()):t(this._getSubscribeErrorContext()))}},{key:"subscribe",value:function(){2!==this._status&&(this._noResubscribe=!1,this._centrifuge._subscribe(this))}},{key:"unsubscribe",value:function(){this._setUnsubscribed(!0),this._centrifuge._unsubscribe(this)}},{key:"_methodCall",value:function(e,t){var n=this;return new Promise(function(s,r){var i=void 0;i=n._isSuccess()?Promise.resolve():n._isError()?Promise.reject(n._error):new Promise(function(e,t){var s=setTimeout(function(){t({code:0,message:"timeout"})},n._centrifuge._config.timeout);n._promises[s]={resolve:e,reject:t}}),i.then(function(){return n._centrifuge._call(e).then(function(e){s(n._centrifuge._decoder.decodeCommandResult(t,e.result)),e.next&&e.next()},function(e){r(e)})},function(e){r(e)})})}},{key:"publish",value:function(e){return this._methodCall({method:this._centrifuge._methodType.PUBLISH,params:{channel:this.channel,data:e}},this._centrifuge._methodType.PUBLISH)}},{key:"presence",value:function(){return this._methodCall({method:this._centrifuge._methodType.PRESENCE,params:{channel:this.channel}},this._centrifuge._methodType.PRESENCE)}},{key:"presenceStats",value:function(){return this._methodCall({method:this._centrifuge._methodType.PRESENCE_STATS,params:{channel:this.channel}},this._centrifuge._methodType.PRESENCE_STATS)}},{key:"history",value:function(){return this._methodCall({method:this._centrifuge._methodType.HISTORY,params:{channel:this.channel}},this._centrifuge._methodType.HISTORY)}}]),t}(a.default);t.default=l,e.exports=t.default},12:function(e,t,n){"use strict";function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e,t){for(var n=0;n<t.length;n++){var s=t[n];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}return function(t,n,s){return n&&e(t.prototype,n),s&&e(t,s),t}}();t.JsonMethodType={CONNECT:0,SUBSCRIBE:1,UNSUBSCRIBE:2,PUBLISH:3,PRESENCE:4,PRESENCE_STATS:5,HISTORY:6,PING:7,SEND:8,RPC:9,REFRESH:10,SUB_REFRESH:11},t.JsonPushType={PUBLICATION:0,JOIN:1,LEAVE:2,UNSUB:3,MESSAGE:4},t.JsonEncoder=function(){function e(){s(this,e)}return r(e,[{key:"encodeCommands",value:function(e){var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(JSON.stringify(e[n]));return t.join("\n")}}]),e}(),t.JsonDecoder=function(){function e(){s(this,e)}return r(e,[{key:"decodeReplies",value:function(e){var t=[],n=e.split("\n");for(var s in n)if(n.hasOwnProperty(s)){if(!n[s])continue;var r=JSON.parse(n[s]);t.push(r)}return t}},{key:"decodeCommandResult",value:function(e,t){return t}},{key:"decodePush",value:function(e){return e}},{key:"decodePushData",value:function(e,t){return t}}]),e}()},3:function(e,t){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(n=window)}e.exports=n},31:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var s=n(10);t.default=s.Centrifuge,e.exports=t.default},6:function(e,t){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function s(e){return"function"==typeof e}function r(e){return"number"==typeof e}function i(e){return"object"==typeof e&&null!==e}function o(e){return void 0===e}e.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(e){if(!r(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},n.prototype.emit=function(e){var t,n,r,u,a,c;if(this._events||(this._events={}),"error"===e&&(!this._events.error||i(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var h=new Error('Uncaught, unspecified "error" event. ('+t+")");throw h.context=t,h}if(n=this._events[e],o(n))return!1;if(s(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:u=Array.prototype.slice.call(arguments,1),n.apply(this,u)}else if(i(n))for(u=Array.prototype.slice.call(arguments,1),c=n.slice(),r=c.length,a=0;a<r;a++)c[a].apply(this,u);return!0},n.prototype.addListener=function(e,t){var r;if(!s(t))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,s(t.listener)?t.listener:t),this._events[e]?i(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,i(this._events[e])&&!this._events[e].warned&&(r=o(this._maxListeners)?n.defaultMaxListeners:this._maxListeners)&&r>0&&this._events[e].length>r&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}if(!s(t))throw TypeError("listener must be a function");var r=!1;return n.listener=t,this.on(e,n),this},n.prototype.removeListener=function(e,t){var n,r,o,u;if(!s(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(n=this._events[e],o=n.length,r=-1,n===t||s(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(i(n)){for(u=o;u-- >0;)if(n[u]===t||n[u].listener&&n[u].listener===t){r=u;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},n.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[e],s(n))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){return this._events&&this._events[e]?s(this._events[e])?[this._events[e]]:this._events[e].slice():[]},n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(s(t))return 1;if(t)return t.length}return 0},n.listenerCount=function(e,t){return e.listenerCount(t)}},7:function(e,t,n){"use strict";(function(e){function n(e,t){return 0===e.lastIndexOf(t,0)}function s(e){return void 0!==e&&null!==e&&"function"==typeof e}function r(t,n){if(e.console){var r=e.console[t];s(r)&&r.apply(e.console,n)}}function i(e,t,n){var s=.5*Math.random(),r=Math.min(n,t*Math.pow(2,e+1));return Math.floor((1-s)*r)}function o(e){return"error"in e&&null!==e.error}Object.defineProperty(t,"__esModule",{value:!0}),t.startsWith=n,t.isFunction=s,t.log=r,t.backoff=i,t.errorExists=o}).call(t,n(3))}})}); | ||
//# sourceMappingURL=centrifuge.min.js.map |
{ | ||
"name": "centrifuge", | ||
"version": "2.0.1", | ||
"version": "2.1.0", | ||
"description": "Centrifuge and Centrifugo client for NodeJS and browser", | ||
@@ -5,0 +5,0 @@ "main": "dist/centrifuge.js", |
@@ -281,2 +281,38 @@ # Centrifuge client for NodeJS and browser | ||
#### publish method | ||
Sometimes you need to publish into channel with `publish` option set to `true` without actually being subscribed to it. In this case you can use `publish` method: | ||
```javascript | ||
centrifuge.publish("channel", {"input": "hello"}).then(function(res) { | ||
console.log('successfully published'); | ||
}, function(err) { | ||
console.log('publish error', err); | ||
}); | ||
``` | ||
#### send method | ||
This is only valid for Centrifuge library and does not work for Centrifugo server. `send` method allows to send asynchronous message from client to server. | ||
```javascript | ||
centrifuge.send({"input": "hello"}).then(function(res) { | ||
console.log('successfully sent'); | ||
}, function(err) { | ||
console.log('send error', err); | ||
}); | ||
``` | ||
#### rpc method | ||
This is only valid for Centrifuge library and does not work for Centrifugo server. `rpc` method allows to send rpc request from client to server and wait for data response. | ||
```javascript | ||
centrifuge.rpc({"input": "hello"}).then(function(res) { | ||
console.log('rpc result', res); | ||
}, function(err) { | ||
console.log('rpc error', err); | ||
}); | ||
``` | ||
## Subscriptions | ||
@@ -636,2 +672,9 @@ | ||
**Important thing to know** is that unsubscribing from subscription does not remove event hanlers you already set to that subscription object. This allows to simply subscribe to channel again later calling `.subscribe()` method of subscription (see below). But there are cases when your code structured in a way that you need to remove event handlers after unsubscribe **to prevent them be executed twice** in the future. To do this remove event listeners explicitly after calling `unsubscribe()`: | ||
```javascript | ||
subscription.unsubscribe(); | ||
subscription.removeAllListeners(); | ||
``` | ||
### subscribe method of subscription | ||
@@ -638,0 +681,0 @@ |
@@ -20,2 +20,3 @@ import EventEmitter from 'events'; | ||
const _errorTimeout = 'timeout'; | ||
const _errorConnectionClosed = 'connection closed'; | ||
@@ -334,8 +335,26 @@ export class Centrifuge extends EventEmitter { | ||
if (!commands.length) { | ||
return; | ||
return true; | ||
} | ||
if (!this._transport) { | ||
throw new Error('transport not connected'); | ||
const transportOpen = this._transport && | ||
this._transport._transport && | ||
this._transport._transport.readyState === this._transport._transport.OPEN; | ||
if (!transportOpen) { | ||
// resolve pending commands with error if transport is not open | ||
for (let command in commands) { | ||
let id = command.id; | ||
if (!(id in this._callbacks)) { | ||
continue; | ||
} | ||
const callbacks = this._callbacks[id]; | ||
clearTimeout(this._callbacks[id].timeout); | ||
delete this._callbacks[id]; | ||
const errback = callbacks.errback; | ||
errback(this._createErrorObject(_errorConnectionClosed, 0)); | ||
} | ||
return false; | ||
} | ||
this._transport.send(this._encoder.encodeCommands(commands)); | ||
return true; | ||
} | ||
@@ -415,3 +434,3 @@ | ||
this._transportClosed = true; | ||
let reason = 'connection closed'; | ||
let reason = _errorConnectionClosed; | ||
let needReconnect = true; | ||
@@ -474,2 +493,7 @@ | ||
}; | ||
if (!this.isConnected()) { | ||
return Promise.reject(this._createErrorObject(_errorConnectionClosed, 0)); | ||
} | ||
return this._call(msg).then(result => { | ||
@@ -491,5 +515,34 @@ if (result.next) { | ||
return this._callAsync(msg); | ||
if (!this.isConnected()) { | ||
return Promise.reject(this._createErrorObject(_errorConnectionClosed, 0)); | ||
} | ||
const sent = this._transportSend([msg]); // can send async message to server without id set | ||
if (!sent) { | ||
return Promise.reject(this._createErrorObject(_errorConnectionClosed, 0)); | ||
}; | ||
return Promise.resolve({}); | ||
} | ||
publish(channel, data) { | ||
const msg = { | ||
method: this._methodType.PUBLISH, | ||
params: { | ||
channel: channel, | ||
data: data | ||
} | ||
}; | ||
if (!this.isConnected()) { | ||
return Promise.reject(this._createErrorObject(_errorConnectionClosed, 0)); | ||
} | ||
return this._call(msg).then(result => { | ||
if (result.next) { | ||
result.next(); | ||
} | ||
return {}; | ||
}); | ||
} | ||
_dataReceived(data) { | ||
@@ -512,8 +565,4 @@ const replies = this._decoder.decodeReplies(data); | ||
_callAsync(msg) { | ||
this._addMessage(msg, true); | ||
} | ||
_call(msg) { | ||
return new global.Promise((resolve, reject) => { | ||
return new Promise((resolve, reject) => { | ||
const id = this._addMessage(msg); | ||
@@ -1220,8 +1269,5 @@ this._registerCall(id, resolve, reject); | ||
_addMessage(message, async) { | ||
let id; | ||
if (!async) { | ||
id = this._nextMessageId(); | ||
message.id = id; | ||
} | ||
_addMessage(message) { | ||
let id = this._nextMessageId(); | ||
message.id = id; | ||
if (this._isBatching === true) { | ||
@@ -1232,6 +1278,3 @@ this._messages.push(message); | ||
} | ||
if (!async) { | ||
return id; | ||
} | ||
return 0; | ||
return id; | ||
}; | ||
@@ -1238,0 +1281,0 @@ |
@@ -40,3 +40,3 @@ import EventEmitter from 'events'; | ||
this._subscriptionPromise = new global.Promise((resolve, reject) => { | ||
this._subscriptionPromise = new Promise((resolve, reject) => { | ||
this._resolve = value => { | ||
@@ -43,0 +43,0 @@ this._ready = true; |
@@ -30,6 +30,6 @@ /* global describe, it, before */ | ||
describe('when I try to send message in disconnected state', () => { | ||
it('should throw an error', () => { | ||
expect(function () { | ||
centrifugeJSON.send({}); | ||
}).to.throw('transport not connected'); | ||
it('send rejects a promise', () => { | ||
return centrifugeJSON.send({}) | ||
.then(function () { throw new Error('was not supposed to succeed'); }) | ||
.catch(function (m) { expect(m.code).to.equal(0); }); | ||
}); | ||
@@ -36,0 +36,0 @@ }); |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
2281826
14023
835