UNPKG

pusher-js

Version:

Pusher Channels JavaScript library for browsers, React Native, NodeJS and web workers

8 lines 90.3 kB
/*! * Pusher JavaScript Library v8.3.0 * https://pusher.com/ * * Copyright 2020, Pusher * Released under the MIT licence. */ module.exports=function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)n.d(r,i,function(e){return t[e]}.bind(null,i));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=15)}([function(t,e,n){"use strict";(function(t){n.d(e,"f",(function(){return s})),n.d(e,"m",(function(){return o})),n.d(e,"d",(function(){return a})),n.d(e,"k",(function(){return h})),n.d(e,"i",(function(){return c})),n.d(e,"n",(function(){return u})),n.d(e,"c",(function(){return l})),n.d(e,"j",(function(){return d})),n.d(e,"g",(function(){return f})),n.d(e,"h",(function(){return p})),n.d(e,"b",(function(){return g})),n.d(e,"a",(function(){return b})),n.d(e,"e",(function(){return y})),n.d(e,"l",(function(){return m}));var r=n(11),i=n(2);function s(t,...e){for(var n=0;n<e.length;n++){var r=e[n];for(var i in r)r[i]&&r[i].constructor&&r[i].constructor===Object?t[i]=s(t[i]||{},r[i]):t[i]=r[i]}return t}function o(){for(var t=["Pusher"],e=0;e<arguments.length;e++)"string"==typeof arguments[e]?t.push(arguments[e]):t.push(m(arguments[e]));return t.join(" : ")}function a(t,e){var n=Array.prototype.indexOf;if(null===t)return-1;if(n&&t.indexOf===n)return t.indexOf(e);for(var r=0,i=t.length;r<i;r++)if(t[r]===e)return r;return-1}function h(t,e){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e(t[n],n,t)}function c(t){var e=[];return h(t,(function(t,n){e.push(n)})),e}function u(t){var e=[];return h(t,(function(t){e.push(t)})),e}function l(e,n,r){for(var i=0;i<e.length;i++)n.call(r||t,e[i],i,e)}function d(t,e){for(var n=[],r=0;r<t.length;r++)n.push(e(t[r],r,t,n));return n}function f(t,e){e=e||function(t){return!!t};for(var n=[],r=0;r<t.length;r++)e(t[r],r,t,n)&&n.push(t[r]);return n}function p(t,e){var n={};return h(t,(function(r,i){(e&&e(r,i,t,n)||Boolean(r))&&(n[i]=r)})),n}function g(t,e){for(var n=0;n<t.length;n++)if(e(t[n],n,t))return!0;return!1}function b(t,e){for(var n=0;n<t.length;n++)if(!e(t[n],n,t))return!1;return!0}function v(t){return e=function(t){return"object"==typeof t&&(t=m(t)),encodeURIComponent(Object(r.a)(t.toString()))},n={},h(t,(function(t,r){n[r]=e(t)})),n;var e,n}function y(t){var e,n,r=p(t,(function(t){return void 0!==t}));return d((e=v(r),n=[],h(e,(function(t,e){n.push([e,t])})),n),i.a.method("join","=")).join("&")}function m(t){try{return JSON.stringify(t)}catch(r){return JSON.stringify((e=[],n=[],function t(r,i){var s,o,a;switch(typeof r){case"object":if(!r)return null;for(s=0;s<e.length;s+=1)if(e[s]===r)return{$ref:n[s]};if(e.push(r),n.push(i),"[object Array]"===Object.prototype.toString.apply(r))for(a=[],s=0;s<r.length;s+=1)a[s]=t(r[s],i+"["+s+"]");else for(o in a={},r)Object.prototype.hasOwnProperty.call(r,o)&&(a[o]=t(r[o],i+"["+JSON.stringify(o)+"]"));return a;case"number":case"string":case"boolean":return r}}(t,"$")))}var e,n}}).call(this,n(6))},function(t,e,n){"use strict";(function(t){var r=n(0),i=n(5);e.a=new class{constructor(){this.globalLog=e=>{t.console&&t.console.log&&t.console.log(e)}}debug(...t){this.log(this.globalLog,t)}warn(...t){this.log(this.globalLogWarn,t)}error(...t){this.log(this.globalLogError,t)}globalLogWarn(e){t.console&&t.console.warn?t.console.warn(e):this.globalLog(e)}globalLogError(e){t.console&&t.console.error?t.console.error(e):this.globalLogWarn(e)}log(t,...e){var n=r.m.apply(this,arguments);if(i.a.log)i.a.log(n);else if(i.a.logToConsole){t.bind(this)(n)}}}}).call(this,n(6))},function(t,e,n){"use strict";var r=n(4),i={now:()=>Date.now?Date.now():(new Date).valueOf(),defer:t=>new r.a(0,t),method(t,...e){var n=Array.prototype.slice.call(arguments,1);return function(e){return e[t].apply(e,n.concat(arguments))}}};e.a=i},function(t,e,n){"use strict";(function(t){n.d(e,"a",(function(){return s}));var r=n(0),i=n(12);class s{constructor(t){this.callbacks=new i.a,this.global_callbacks=[],this.failThrough=t}bind(t,e,n){return this.callbacks.add(t,e,n),this}bind_global(t){return this.global_callbacks.push(t),this}unbind(t,e,n){return this.callbacks.remove(t,e,n),this}unbind_global(t){return t?(this.global_callbacks=r.g(this.global_callbacks||[],e=>e!==t),this):(this.global_callbacks=[],this)}unbind_all(){return this.unbind(),this.unbind_global(),this}emit(e,n,r){for(var i=0;i<this.global_callbacks.length;i++)this.global_callbacks[i](e,n);var s=this.callbacks.get(e),o=[];if(r?o.push(n,r):n&&o.push(n),s&&s.length>0)for(i=0;i<s.length;i++)s[i].fn.apply(s[i].context||t,o);else this.failThrough&&this.failThrough(e,n);return this}}}).call(this,n(6))},function(t,e,n){"use strict";(function(t){n.d(e,"a",(function(){return o})),n.d(e,"b",(function(){return a}));var r=n(9);function i(e){t.clearTimeout(e)}function s(e){t.clearInterval(e)}class o extends r.a{constructor(t,e){super(setTimeout,i,t,(function(t){return e(),null}))}}class a extends r.a{constructor(t,e){super(setInterval,s,t,(function(t){return e(),t}))}}}).call(this,n(6))},function(t,e,n){"use strict";var r=n(0),i={VERSION:"8.3.0",PROTOCOL:7,wsPort:80,wssPort:443,wsPath:"",httpHost:"sockjs.pusher.com",httpPort:80,httpsPort:443,httpPath:"/pusher",stats_host:"stats.pusher.com",authEndpoint:"/pusher/auth",authTransport:"ajax",activityTimeout:12e4,pongTimeout:3e4,unavailableTimeout:1e4,userAuthentication:{endpoint:"/pusher/user-auth",transport:"ajax"},channelAuthorization:{endpoint:"/pusher/auth",transport:"ajax"},cdn_http:"http://js.pusher.com",cdn_https:"https://js.pusher.com",dependency_suffix:""};function s(t,e,n){return t+(e.useTLS?"s":"")+"://"+(e.useTLS?e.hostTLS:e.hostNonTLS)+n}function o(t,e){return"/app/"+t+("?protocol="+i.PROTOCOL+"&client=js&version="+i.VERSION+(e?"&"+e:""))}var a={getInitial:function(t,e){return s("ws",e,(e.httpPath||"")+o(t,"flash=false"))}},h={getInitial:function(t,e){return s("http",e,(e.httpPath||"/pusher")+o(t))}},c=n(2),u=n(3),l=n(1);class d extends u.a{constructor(t,e,n,r,i){super(),this.initialize=zt.transportConnectionInitializer,this.hooks=t,this.name=e,this.priority=n,this.key=r,this.options=i,this.state="new",this.timeline=i.timeline,this.activityTimeout=i.activityTimeout,this.id=this.timeline.generateUniqueID()}handlesActivityChecks(){return Boolean(this.hooks.handlesActivityChecks)}supportsPing(){return Boolean(this.hooks.supportsPing)}connect(){if(this.socket||"initialized"!==this.state)return!1;var t=this.hooks.urls.getInitial(this.key,this.options);try{this.socket=this.hooks.getSocket(t,this.options)}catch(t){return c.a.defer(()=>{this.onError(t),this.changeState("closed")}),!1}return this.bindListeners(),l.a.debug("Connecting",{transport:this.name,url:t}),this.changeState("connecting"),!0}close(){return!!this.socket&&(this.socket.close(),!0)}send(t){return"open"===this.state&&(c.a.defer(()=>{this.socket&&this.socket.send(t)}),!0)}ping(){"open"===this.state&&this.supportsPing()&&this.socket.ping()}onOpen(){this.hooks.beforeOpen&&this.hooks.beforeOpen(this.socket,this.hooks.urls.getPath(this.key,this.options)),this.changeState("open"),this.socket.onopen=void 0}onError(t){this.emit("error",{type:"WebSocketError",error:t}),this.timeline.error(this.buildTimelineMessage({error:t.toString()}))}onClose(t){t?this.changeState("closed",{code:t.code,reason:t.reason,wasClean:t.wasClean}):this.changeState("closed"),this.unbindListeners(),this.socket=void 0}onMessage(t){this.emit("message",t)}onActivity(){this.emit("activity")}bindListeners(){this.socket.onopen=()=>{this.onOpen()},this.socket.onerror=t=>{this.onError(t)},this.socket.onclose=t=>{this.onClose(t)},this.socket.onmessage=t=>{this.onMessage(t)},this.supportsPing()&&(this.socket.onactivity=()=>{this.onActivity()})}unbindListeners(){this.socket&&(this.socket.onopen=void 0,this.socket.onerror=void 0,this.socket.onclose=void 0,this.socket.onmessage=void 0,this.supportsPing()&&(this.socket.onactivity=void 0))}changeState(t,e){this.state=t,this.timeline.info(this.buildTimelineMessage({state:t,params:e})),this.emit(t,e)}buildTimelineMessage(t){return r.f({cid:this.id},t)}}class f{constructor(t){this.hooks=t}isSupported(t){return this.hooks.isSupported(t)}createConnection(t,e,n,r){return new d(this.hooks,t,e,n,r)}}var p=new f({urls:a,handlesActivityChecks:!1,supportsPing:!1,isInitialized:function(){return Boolean(zt.getWebSocketAPI())},isSupported:function(){return Boolean(zt.getWebSocketAPI())},getSocket:function(t){return zt.createWebSocket(t)}}),g={urls:h,handlesActivityChecks:!1,supportsPing:!0,isInitialized:function(){return!0}},b=r.f({getSocket:function(t){return zt.HTTPFactory.createStreamingSocket(t)}},g),v=r.f({getSocket:function(t){return zt.HTTPFactory.createPollingSocket(t)}},g),y={isSupported:function(){return zt.isXHRSupported()}},m={ws:p,xhr_streaming:new f(r.f({},b,y)),xhr_polling:new f(r.f({},v,y))};class w{constructor(t,e,n){this.manager=t,this.transport=e,this.minPingDelay=n.minPingDelay,this.maxPingDelay=n.maxPingDelay,this.pingDelay=void 0}createConnection(t,e,n,i){i=r.f({},i,{activityTimeout:this.pingDelay});var s=this.transport.createConnection(t,e,n,i),o=null,a=function(){s.unbind("open",a),s.bind("closed",h),o=c.a.now()},h=t=>{if(s.unbind("closed",h),1002===t.code||1003===t.code)this.manager.reportDeath();else if(!t.wasClean&&o){var e=c.a.now()-o;e<2*this.maxPingDelay&&(this.manager.reportDeath(),this.pingDelay=Math.max(e/2,this.minPingDelay))}};return s.bind("open",a),s}isSupported(t){return this.manager.isAlive()&&this.transport.isSupported(t)}}const _={decodeMessage:function(t){try{var e=JSON.parse(t.data),n=e.data;if("string"==typeof n)try{n=JSON.parse(e.data)}catch(t){}var r={event:e.event,channel:e.channel,data:n};return e.user_id&&(r.user_id=e.user_id),r}catch(e){throw{type:"MessageParseError",error:e,data:t.data}}},encodeMessage:function(t){return JSON.stringify(t)},processHandshake:function(t){var e=_.decodeMessage(t);if("pusher:connection_established"===e.event){if(!e.data.activity_timeout)throw"No activity timeout specified in handshake";return{action:"connected",id:e.data.socket_id,activityTimeout:1e3*e.data.activity_timeout}}if("pusher:error"===e.event)return{action:this.getCloseAction(e.data),error:this.getCloseError(e.data)};throw"Invalid handshake"},getCloseAction:function(t){return t.code<4e3?t.code>=1002&&t.code<=1004?"backoff":null:4e3===t.code?"tls_only":t.code<4100?"refused":t.code<4200?"backoff":t.code<4300?"retry":"refused"},getCloseError:function(t){return 1e3!==t.code&&1001!==t.code?{type:"PusherError",data:{code:t.code,message:t.reason||t.message}}:null}};var S=_;class k extends u.a{constructor(t,e){super(),this.id=t,this.transport=e,this.activityTimeout=e.activityTimeout,this.bindListeners()}handlesActivityChecks(){return this.transport.handlesActivityChecks()}send(t){return this.transport.send(t)}send_event(t,e,n){var r={event:t,data:e};return n&&(r.channel=n),l.a.debug("Event sent",r),this.send(S.encodeMessage(r))}ping(){this.transport.supportsPing()?this.transport.ping():this.send_event("pusher:ping",{})}close(){this.transport.close()}bindListeners(){var t={message:t=>{var e;try{e=S.decodeMessage(t)}catch(e){this.emit("error",{type:"MessageParseError",error:e,data:t.data})}if(void 0!==e){switch(l.a.debug("Event recd",e),e.event){case"pusher:error":this.emit("error",{type:"PusherError",data:e.data});break;case"pusher:ping":this.emit("ping");break;case"pusher:pong":this.emit("pong")}this.emit("message",e)}},activity:()=>{this.emit("activity")},error:t=>{this.emit("error",t)},closed:t=>{e(),t&&t.code&&this.handleCloseEvent(t),this.transport=null,this.emit("closed")}},e=()=>{r.k(t,(t,e)=>{this.transport.unbind(e,t)})};r.k(t,(t,e)=>{this.transport.bind(e,t)})}handleCloseEvent(t){var e=S.getCloseAction(t),n=S.getCloseError(t);n&&this.emit("error",n),e&&this.emit(e,{action:e,error:n})}}class C{constructor(t,e){this.transport=t,this.callback=e,this.bindListeners()}close(){this.unbindListeners(),this.transport.close()}bindListeners(){this.onMessage=t=>{var e;this.unbindListeners();try{e=S.processHandshake(t)}catch(t){return this.finish("error",{error:t}),void this.transport.close()}"connected"===e.action?this.finish("connected",{connection:new k(e.id,this.transport),activityTimeout:e.activityTimeout}):(this.finish(e.action,{error:e.error}),this.transport.close())},this.onClosed=t=>{this.unbindListeners();var e=S.getCloseAction(t)||"backoff",n=S.getCloseError(t);this.finish(e,{error:n})},this.transport.bind("message",this.onMessage),this.transport.bind("closed",this.onClosed)}unbindListeners(){this.transport.unbind("message",this.onMessage),this.transport.unbind("closed",this.onClosed)}finish(t,e){this.callback(r.f({transport:this.transport,action:t},e))}}class T{constructor(t,e){this.timeline=t,this.options=e||{}}send(t,e){this.timeline.isEmpty()||this.timeline.send(zt.TimelineTransport.getAgent(this,t),e)}}class E extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype)}}class A extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype)}}Error;class P extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype)}}class x extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype)}}class O extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype)}}class L extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype)}}class U extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype)}}class R extends Error{constructor(t,e){super(e),this.status=t,Object.setPrototypeOf(this,new.target.prototype)}}const M={baseUrl:"https://pusher.com",urls:{authenticationEndpoint:{path:"/docs/channels/server_api/authenticating_users"},authorizationEndpoint:{path:"/docs/channels/server_api/authorizing-users/"},javascriptQuickStart:{path:"/docs/javascript_quick_start"},triggeringClientEvents:{path:"/docs/client_api_guide/client_events#trigger-events"},encryptedChannelSupport:{fullUrl:"https://github.com/pusher/pusher-js/tree/cc491015371a4bde5743d1c87a0fbac0feb53195#encrypted-channel-support"}}};var I=function(t){const e=M.urls[t];if(!e)return"";let n;return e.fullUrl?n=e.fullUrl:e.path&&(n=M.baseUrl+e.path),n?"See: "+n:""};class N extends u.a{constructor(t,e){super((function(e,n){l.a.debug("No callbacks on "+t+" for "+e)})),this.name=t,this.pusher=e,this.subscribed=!1,this.subscriptionPending=!1,this.subscriptionCancelled=!1}authorize(t,e){return e(null,{auth:""})}trigger(t,e){if(0!==t.indexOf("client-"))throw new E("Event '"+t+"' does not start with 'client-'");if(!this.subscribed){var n=I("triggeringClientEvents");l.a.warn("Client event triggered before channel 'subscription_succeeded' event . "+n)}return this.pusher.send_event(t,e,this.name)}disconnect(){this.subscribed=!1,this.subscriptionPending=!1}handleEvent(t){var e=t.event,n=t.data;if("pusher_internal:subscription_succeeded"===e)this.handleSubscriptionSucceededEvent(t);else if("pusher_internal:subscription_count"===e)this.handleSubscriptionCountEvent(t);else if(0!==e.indexOf("pusher_internal:")){this.emit(e,n,{})}}handleSubscriptionSucceededEvent(t){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):this.emit("pusher:subscription_succeeded",t.data)}handleSubscriptionCountEvent(t){t.data.subscription_count&&(this.subscriptionCount=t.data.subscription_count),this.emit("pusher:subscription_count",t.data)}subscribe(){this.subscribed||(this.subscriptionPending=!0,this.subscriptionCancelled=!1,this.authorize(this.pusher.connection.socket_id,(t,e)=>{t?(this.subscriptionPending=!1,l.a.error(t.toString()),this.emit("pusher:subscription_error",Object.assign({},{type:"AuthError",error:t.message},t instanceof R?{status:t.status}:{}))):this.pusher.send_event("pusher:subscribe",{auth:e.auth,channel_data:e.channel_data,channel:this.name})}))}unsubscribe(){this.subscribed=!1,this.pusher.send_event("pusher:unsubscribe",{channel:this.name})}cancelSubscription(){this.subscriptionCancelled=!0}reinstateSubscription(){this.subscriptionCancelled=!1}}class j extends N{authorize(t,e){return this.pusher.config.channelAuthorizer({channelName:this.name,socketId:t},e)}}class D{constructor(){this.reset()}get(t){return Object.prototype.hasOwnProperty.call(this.members,t)?{id:t,info:this.members[t]}:null}each(t){r.k(this.members,(e,n)=>{t(this.get(n))})}setMyID(t){this.myID=t}onSubscription(t){this.members=t.presence.hash,this.count=t.presence.count,this.me=this.get(this.myID)}addMember(t){return null===this.get(t.user_id)&&this.count++,this.members[t.user_id]=t.user_info,this.get(t.user_id)}removeMember(t){var e=this.get(t.user_id);return e&&(delete this.members[t.user_id],this.count--),e}reset(){this.members={},this.count=0,this.myID=null,this.me=null}}var z=function(t,e,n,r){return new(n||(n=Promise))((function(i,s){function o(t){try{h(r.next(t))}catch(t){s(t)}}function a(t){try{h(r.throw(t))}catch(t){s(t)}}function h(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(o,a)}h((r=r.apply(t,e||[])).next())}))};class H extends j{constructor(t,e){super(t,e),this.members=new D}authorize(t,e){super.authorize(t,(t,n)=>z(this,void 0,void 0,(function*(){if(!t)if(null!=(n=n).channel_data){var r=JSON.parse(n.channel_data);this.members.setMyID(r.user_id)}else{if(yield this.pusher.user.signinDonePromise,null==this.pusher.user.user_data){let t=I("authorizationEndpoint");return l.a.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${t}, or the user should be signed in.`),void e("Invalid auth response")}this.members.setMyID(this.pusher.user.user_data.id)}e(t,n)})))}handleEvent(t){var e=t.event;if(0===e.indexOf("pusher_internal:"))this.handleInternalEvent(t);else{var n=t.data,r={};t.user_id&&(r.user_id=t.user_id),this.emit(e,n,r)}}handleInternalEvent(t){var e=t.event,n=t.data;switch(e){case"pusher_internal:subscription_succeeded":this.handleSubscriptionSucceededEvent(t);break;case"pusher_internal:subscription_count":this.handleSubscriptionCountEvent(t);break;case"pusher_internal:member_added":var r=this.members.addMember(n);this.emit("pusher:member_added",r);break;case"pusher_internal:member_removed":var i=this.members.removeMember(n);i&&this.emit("pusher:member_removed",i)}}handleSubscriptionSucceededEvent(t){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):(this.members.onSubscription(t.data),this.emit("pusher:subscription_succeeded",this.members))}disconnect(){this.members.reset(),super.disconnect()}}var B=n(13),F=n(8);class q extends j{constructor(t,e,n){super(t,e),this.key=null,this.nacl=n}authorize(t,e){super.authorize(t,(t,n)=>{if(t)return void e(t,n);let r=n.shared_secret;r?(this.key=Object(F.decode)(r),delete n.shared_secret,e(null,n)):e(new Error("No shared_secret key in auth payload for encrypted channel: "+this.name),null)})}trigger(t,e){throw new O("Client events are not currently supported for encrypted channels")}handleEvent(t){var e=t.event,n=t.data;0!==e.indexOf("pusher_internal:")&&0!==e.indexOf("pusher:")?this.handleEncryptedEvent(e,n):super.handleEvent(t)}handleEncryptedEvent(t,e){if(!this.key)return void l.a.debug("Received encrypted event before key has been retrieved from the authEndpoint");if(!e.ciphertext||!e.nonce)return void l.a.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: "+e);let n=Object(F.decode)(e.ciphertext);if(n.length<this.nacl.secretbox.overheadLength)return void l.a.error(`Expected encrypted event ciphertext length to be ${this.nacl.secretbox.overheadLength}, got: ${n.length}`);let r=Object(F.decode)(e.nonce);if(r.length<this.nacl.secretbox.nonceLength)return void l.a.error(`Expected encrypted event nonce length to be ${this.nacl.secretbox.nonceLength}, got: ${r.length}`);let i=this.nacl.secretbox.open(n,r,this.key);if(null===i)return l.a.debug("Failed to decrypt an event, probably because it was encrypted with a different key. Fetching a new key from the authEndpoint..."),void this.authorize(this.pusher.connection.socket_id,(e,s)=>{e?l.a.error(`Failed to make a request to the authEndpoint: ${s}. Unable to fetch new key, so dropping encrypted event`):(i=this.nacl.secretbox.open(n,r,this.key),null!==i?this.emit(t,this.getDataToEmit(i)):l.a.error("Failed to decrypt event with new key. Dropping encrypted event"))});this.emit(t,this.getDataToEmit(i))}getDataToEmit(t){let e=Object(B.decode)(t);try{return JSON.parse(e)}catch(t){return e}}}var Y=n(4);class K extends u.a{constructor(t,e){super(),this.state="initialized",this.connection=null,this.key=t,this.options=e,this.timeline=this.options.timeline,this.usingTLS=this.options.useTLS,this.errorCallbacks=this.buildErrorCallbacks(),this.connectionCallbacks=this.buildConnectionCallbacks(this.errorCallbacks),this.handshakeCallbacks=this.buildHandshakeCallbacks(this.errorCallbacks);var n=zt.getNetwork();n.bind("online",()=>{this.timeline.info({netinfo:"online"}),"connecting"!==this.state&&"unavailable"!==this.state||this.retryIn(0)}),n.bind("offline",()=>{this.timeline.info({netinfo:"offline"}),this.connection&&this.sendActivityCheck()}),this.updateStrategy()}connect(){this.connection||this.runner||(this.strategy.isSupported()?(this.updateState("connecting"),this.startConnecting(),this.setUnavailableTimer()):this.updateState("failed"))}send(t){return!!this.connection&&this.connection.send(t)}send_event(t,e,n){return!!this.connection&&this.connection.send_event(t,e,n)}disconnect(){this.disconnectInternally(),this.updateState("disconnected")}isUsingTLS(){return this.usingTLS}startConnecting(){var t=(e,n)=>{e?this.runner=this.strategy.connect(0,t):"error"===n.action?(this.emit("error",{type:"HandshakeError",error:n.error}),this.timeline.error({handshakeError:n.error})):(this.abortConnecting(),this.handshakeCallbacks[n.action](n))};this.runner=this.strategy.connect(0,t)}abortConnecting(){this.runner&&(this.runner.abort(),this.runner=null)}disconnectInternally(){(this.abortConnecting(),this.clearRetryTimer(),this.clearUnavailableTimer(),this.connection)&&this.abandonConnection().close()}updateStrategy(){this.strategy=this.options.getStrategy({key:this.key,timeline:this.timeline,useTLS:this.usingTLS})}retryIn(t){this.timeline.info({action:"retry",delay:t}),t>0&&this.emit("connecting_in",Math.round(t/1e3)),this.retryTimer=new Y.a(t||0,()=>{this.disconnectInternally(),this.connect()})}clearRetryTimer(){this.retryTimer&&(this.retryTimer.ensureAborted(),this.retryTimer=null)}setUnavailableTimer(){this.unavailableTimer=new Y.a(this.options.unavailableTimeout,()=>{this.updateState("unavailable")})}clearUnavailableTimer(){this.unavailableTimer&&this.unavailableTimer.ensureAborted()}sendActivityCheck(){this.stopActivityCheck(),this.connection.ping(),this.activityTimer=new Y.a(this.options.pongTimeout,()=>{this.timeline.error({pong_timed_out:this.options.pongTimeout}),this.retryIn(0)})}resetActivityCheck(){this.stopActivityCheck(),this.connection&&!this.connection.handlesActivityChecks()&&(this.activityTimer=new Y.a(this.activityTimeout,()=>{this.sendActivityCheck()}))}stopActivityCheck(){this.activityTimer&&this.activityTimer.ensureAborted()}buildConnectionCallbacks(t){return r.f({},t,{message:t=>{this.resetActivityCheck(),this.emit("message",t)},ping:()=>{this.send_event("pusher:pong",{})},activity:()=>{this.resetActivityCheck()},error:t=>{this.emit("error",t)},closed:()=>{this.abandonConnection(),this.shouldRetry()&&this.retryIn(1e3)}})}buildHandshakeCallbacks(t){return r.f({},t,{connected:t=>{this.activityTimeout=Math.min(this.options.activityTimeout,t.activityTimeout,t.connection.activityTimeout||1/0),this.clearUnavailableTimer(),this.setConnection(t.connection),this.socket_id=this.connection.id,this.updateState("connected",{socket_id:this.socket_id})}})}buildErrorCallbacks(){let t=t=>e=>{e.error&&this.emit("error",{type:"WebSocketError",error:e.error}),t(e)};return{tls_only:t(()=>{this.usingTLS=!0,this.updateStrategy(),this.retryIn(0)}),refused:t(()=>{this.disconnect()}),backoff:t(()=>{this.retryIn(1e3)}),retry:t(()=>{this.retryIn(0)})}}setConnection(t){for(var e in this.connection=t,this.connectionCallbacks)this.connection.bind(e,this.connectionCallbacks[e]);this.resetActivityCheck()}abandonConnection(){if(this.connection){for(var t in this.stopActivityCheck(),this.connectionCallbacks)this.connection.unbind(t,this.connectionCallbacks[t]);var e=this.connection;return this.connection=null,e}}updateState(t,e){var n=this.state;if(this.state=t,n!==t){var r=t;"connected"===r&&(r+=" with new socket ID "+e.socket_id),l.a.debug("State changed",n+" -> "+r),this.timeline.info({state:t,params:e}),this.emit("state_change",{previous:n,current:t}),this.emit(t,e)}}shouldRetry(){return"connecting"===this.state||"connected"===this.state}}class ${constructor(){this.channels={}}add(t,e){return this.channels[t]||(this.channels[t]=function(t,e){if(0===t.indexOf("private-encrypted-")){if(e.config.nacl)return J.createEncryptedChannel(t,e,e.config.nacl);let n="Tried to subscribe to a private-encrypted- channel but no nacl implementation available",r=I("encryptedChannelSupport");throw new O(`${n}. ${r}`)}if(0===t.indexOf("private-"))return J.createPrivateChannel(t,e);if(0===t.indexOf("presence-"))return J.createPresenceChannel(t,e);if(0===t.indexOf("#"))throw new A('Cannot create a channel with name "'+t+'".');return J.createChannel(t,e)}(t,e)),this.channels[t]}all(){return r.n(this.channels)}find(t){return this.channels[t]}remove(t){var e=this.channels[t];return delete this.channels[t],e}disconnect(){r.k(this.channels,(function(t){t.disconnect()}))}}var J={createChannels:()=>new $,createConnectionManager:(t,e)=>new K(t,e),createChannel:(t,e)=>new N(t,e),createPrivateChannel:(t,e)=>new j(t,e),createPresenceChannel:(t,e)=>new H(t,e),createEncryptedChannel:(t,e,n)=>new q(t,e,n),createTimelineSender:(t,e)=>new T(t,e),createHandshake:(t,e)=>new C(t,e),createAssistantToTheTransportManager:(t,e,n)=>new w(t,e,n)};class X{constructor(t){this.options=t||{},this.livesLeft=this.options.lives||1/0}getAssistant(t){return J.createAssistantToTheTransportManager(this,t,{minPingDelay:this.options.minPingDelay,maxPingDelay:this.options.maxPingDelay})}isAlive(){return this.livesLeft>0}reportDeath(){this.livesLeft-=1}}class W{constructor(t,e){this.strategies=t,this.loop=Boolean(e.loop),this.failFast=Boolean(e.failFast),this.timeout=e.timeout,this.timeoutLimit=e.timeoutLimit}isSupported(){return r.b(this.strategies,c.a.method("isSupported"))}connect(t,e){var n=this.strategies,r=0,i=this.timeout,s=null,o=(a,h)=>{h?e(null,h):(r+=1,this.loop&&(r%=n.length),r<n.length?(i&&(i*=2,this.timeoutLimit&&(i=Math.min(i,this.timeoutLimit))),s=this.tryStrategy(n[r],t,{timeout:i,failFast:this.failFast},o)):e(!0))};return s=this.tryStrategy(n[r],t,{timeout:i,failFast:this.failFast},o),{abort:function(){s.abort()},forceMinPriority:function(e){t=e,s&&s.forceMinPriority(e)}}}tryStrategy(t,e,n,r){var i=null,s=null;return n.timeout>0&&(i=new Y.a(n.timeout,(function(){s.abort(),r(!0)}))),s=t.connect(e,(function(t,e){t&&i&&i.isRunning()&&!n.failFast||(i&&i.ensureAborted(),r(t,e))})),{abort:function(){i&&i.ensureAborted(),s.abort()},forceMinPriority:function(t){s.forceMinPriority(t)}}}}class G{constructor(t){this.strategies=t}isSupported(){return r.b(this.strategies,c.a.method("isSupported"))}connect(t,e){return function(t,e,n){var i=r.j(t,(function(t,r,i,s){return t.connect(e,n(r,s))}));return{abort:function(){r.c(i,V)},forceMinPriority:function(t){r.c(i,(function(e){e.forceMinPriority(t)}))}}}(this.strategies,t,(function(t,n){return function(i,s){n[t].error=i,i?function(t){return r.a(t,(function(t){return Boolean(t.error)}))}(n)&&e(!0):(r.c(n,(function(t){t.forceMinPriority(s.transport.priority)})),e(null,s))}}))}}function V(t){t.error||t.aborted||(t.abort(),t.aborted=!0)}class Z{constructor(t,e,n){this.strategy=t,this.transports=e,this.ttl=n.ttl||18e5,this.usingTLS=n.useTLS,this.timeline=n.timeline}isSupported(){return this.strategy.isSupported()}connect(t,e){var n=this.usingTLS,i=function(t){var e=zt.getLocalStorage();if(e)try{var n=e[Q(t)];if(n)return JSON.parse(n)}catch(e){tt(t)}return null}(n),s=i&&i.cacheSkipCount?i.cacheSkipCount:0,o=[this.strategy];if(i&&i.timestamp+this.ttl>=c.a.now()){var a=this.transports[i.transport];a&&(["ws","wss"].includes(i.transport)||s>3?(this.timeline.info({cached:!0,transport:i.transport,latency:i.latency}),o.push(new W([a],{timeout:2*i.latency+1e3,failFast:!0}))):s++)}var h=c.a.now(),u=o.pop().connect(t,(function i(a,l){a?(tt(n),o.length>0?(h=c.a.now(),u=o.pop().connect(t,i)):e(a)):(!function(t,e,n,i){var s=zt.getLocalStorage();if(s)try{s[Q(t)]=r.l({timestamp:c.a.now(),transport:e,latency:n,cacheSkipCount:i})}catch(t){}}(n,l.transport.name,c.a.now()-h,s),e(null,l))}));return{abort:function(){u.abort()},forceMinPriority:function(e){t=e,u&&u.forceMinPriority(e)}}}}function Q(t){return"pusherTransport"+(t?"TLS":"NonTLS")}function tt(t){var e=zt.getLocalStorage();if(e)try{delete e[Q(t)]}catch(t){}}class et{constructor(t,{delay:e}){this.strategy=t,this.options={delay:e}}isSupported(){return this.strategy.isSupported()}connect(t,e){var n,r=this.strategy,i=new Y.a(this.options.delay,(function(){n=r.connect(t,e)}));return{abort:function(){i.ensureAborted(),n&&n.abort()},forceMinPriority:function(e){t=e,n&&n.forceMinPriority(e)}}}}class nt{constructor(t,e,n){this.test=t,this.trueBranch=e,this.falseBranch=n}isSupported(){return(this.test()?this.trueBranch:this.falseBranch).isSupported()}connect(t,e){return(this.test()?this.trueBranch:this.falseBranch).connect(t,e)}}class rt{constructor(t){this.strategy=t}isSupported(){return this.strategy.isSupported()}connect(t,e){var n=this.strategy.connect(t,(function(t,r){r&&n.abort(),e(t,r)}));return n}}function it(t){return function(){return t.isSupported()}}var st=function(t,e,n){var i={};function s(e,r,s,o,a){var h=n(t,e,r,s,o,a);return i[e]=h,h}var o,a=Object.assign({},e,{hostNonTLS:t.wsHost+":"+t.wsPort,hostTLS:t.wsHost+":"+t.wssPort,httpPath:t.wsPath}),h=r.f({},a,{useTLS:!0}),c=Object.assign({},e,{hostNonTLS:t.httpHost+":"+t.httpPort,hostTLS:t.httpHost+":"+t.httpsPort,httpPath:t.httpPath}),u={loop:!0,timeout:15e3,timeoutLimit:6e4},l=new X({minPingDelay:1e4,maxPingDelay:t.activityTimeout}),d=new X({lives:2,minPingDelay:1e4,maxPingDelay:t.activityTimeout}),f=s("ws","ws",3,a,l),p=s("wss","ws",3,h,l),g=s("xhr_streaming","xhr_streaming",1,c,d),b=s("xhr_polling","xhr_polling",1,c),v=new W([f],u),y=new W([p],u),m=new W([g],u),w=new W([b],u),_=new W([new nt(it(m),new G([m,new et(w,{delay:4e3})]),w)],u);return o=e.useTLS?new G([v,new et(_,{delay:2e3})]):new G([v,new et(y,{delay:2e3}),new et(_,{delay:5e3})]),new Z(new rt(new nt(it(f),o,_)),i,{ttl:18e5,timeline:e.timeline,useTLS:e.useTLS})};class ot extends u.a{constructor(t,e,n){super(),this.hooks=t,this.method=e,this.url=n}start(t){this.position=0,this.xhr=this.hooks.getRequest(this),this.unloader=()=>{this.close()},zt.addUnloadListener(this.unloader),this.xhr.open(this.method,this.url,!0),this.xhr.setRequestHeader&&this.xhr.setRequestHeader("Content-Type","application/json"),this.xhr.send(t)}close(){this.unloader&&(zt.removeUnloadListener(this.unloader),this.unloader=null),this.xhr&&(this.hooks.abortRequest(this.xhr),this.xhr=null)}onChunk(t,e){for(;;){var n=this.advanceBuffer(e);if(!n)break;this.emit("chunk",{status:t,data:n})}this.isBufferTooLong(e)&&this.emit("buffer_too_long")}advanceBuffer(t){var e=t.slice(this.position),n=e.indexOf("\n");return-1!==n?(this.position+=n+1,e.slice(0,n)):null}isBufferTooLong(t){return this.position===t.length&&t.length>262144}}var at;!function(t){t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSED=3]="CLOSED"}(at||(at={}));var ht=at,ct=1;function ut(t){var e=-1===t.indexOf("?")?"?":"&";return t+e+"t="+ +new Date+"&n="+ct++}function lt(t){return zt.randomInt(t)}var dt=class{constructor(t,e){this.hooks=t,this.session=lt(1e3)+"/"+function(t){for(var e=[],n=0;n<t;n++)e.push(lt(32).toString(32));return e.join("")}(8),this.location=function(t){var e=/([^\?]*)\/*(\??.*)/.exec(t);return{base:e[1],queryString:e[2]}}(e),this.readyState=ht.CONNECTING,this.openStream()}send(t){return this.sendRaw(JSON.stringify([t]))}ping(){this.hooks.sendHeartbeat(this)}close(t,e){this.onClose(t,e,!0)}sendRaw(t){if(this.readyState!==ht.OPEN)return!1;try{return zt.createSocketRequest("POST",ut((e=this.location,n=this.session,e.base+"/"+n+"/xhr_send"))).start(t),!0}catch(t){return!1}var e,n}reconnect(){this.closeStream(),this.openStream()}onClose(t,e,n){this.closeStream(),this.readyState=ht.CLOSED,this.onclose&&this.onclose({code:t,reason:e,wasClean:n})}onChunk(t){var e;if(200===t.status)switch(this.readyState===ht.OPEN&&this.onActivity(),t.data.slice(0,1)){case"o":e=JSON.parse(t.data.slice(1)||"{}"),this.onOpen(e);break;case"a":e=JSON.parse(t.data.slice(1)||"[]");for(var n=0;n<e.length;n++)this.onEvent(e[n]);break;case"m":e=JSON.parse(t.data.slice(1)||"null"),this.onEvent(e);break;case"h":this.hooks.onHeartbeat(this);break;case"c":e=JSON.parse(t.data.slice(1)||"[]"),this.onClose(e[0],e[1],!0)}}onOpen(t){var e,n,r;this.readyState===ht.CONNECTING?(t&&t.hostname&&(this.location.base=(e=this.location.base,n=t.hostname,(r=/(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(e))[1]+n+r[3])),this.readyState=ht.OPEN,this.onopen&&this.onopen()):this.onClose(1006,"Server lost session",!0)}onEvent(t){this.readyState===ht.OPEN&&this.onmessage&&this.onmessage({data:t})}onActivity(){this.onactivity&&this.onactivity()}onError(t){this.onerror&&this.onerror(t)}openStream(){this.stream=zt.createSocketRequest("POST",ut(this.hooks.getReceiveURL(this.location,this.session))),this.stream.bind("chunk",t=>{this.onChunk(t)}),this.stream.bind("finished",t=>{this.hooks.onFinished(this,t)}),this.stream.bind("buffer_too_long",()=>{this.reconnect()});try{this.stream.start()}catch(t){c.a.defer(()=>{this.onError(t),this.onClose(1006,"Could not start streaming",!1)})}}closeStream(){this.stream&&(this.stream.unbind_all(),this.stream.close(),this.stream=null)}},ft={getReceiveURL:function(t,e){return t.base+"/"+e+"/xhr_streaming"+t.queryString},onHeartbeat:function(t){t.sendRaw("[]")},sendHeartbeat:function(t){t.sendRaw("[]")},onFinished:function(t,e){t.onClose(1006,"Connection interrupted ("+e+")",!1)}},pt={getReceiveURL:function(t,e){return t.base+"/"+e+"/xhr"+t.queryString},onHeartbeat:function(){},sendHeartbeat:function(t){t.sendRaw("[]")},onFinished:function(t,e){200===e?t.reconnect():t.onClose(1006,"Connection interrupted ("+e+")",!1)}},gt={getRequest:function(t){var e=new(zt.getXHRAPI());return e.onreadystatechange=e.onprogress=function(){switch(e.readyState){case 3:e.responseText&&e.responseText.length>0&&t.onChunk(e.status,e.responseText);break;case 4:e.responseText&&e.responseText.length>0&&t.onChunk(e.status,e.responseText),t.emit("finished",e.status),t.close()}},e},abortRequest:function(t){t.onreadystatechange=null,t.abort()}},bt={getDefaultStrategy:st,Transports:m,transportConnectionInitializer:function(){this.timeline.info(this.buildTimelineMessage({transport:this.name+(this.options.useTLS?"s":"")})),this.hooks.isInitialized()?this.changeState("initialized"):this.onClose()},HTTPFactory:{createStreamingSocket(t){return this.createSocket(ft,t)},createPollingSocket(t){return this.createSocket(pt,t)},createSocket:(t,e)=>new dt(t,e),createXHR(t,e){return this.createRequest(gt,t,e)},createRequest:(t,e,n)=>new ot(t,e,n)},setup(t){t.ready()},getLocalStorage(){},getClientFeatures:()=>r.i(r.h({ws:m.ws},(function(t){return t.isSupported({})}))),getProtocol:()=>"http:",isXHRSupported:()=>!0,createSocketRequest(t,e){if(this.isXHRSupported())return this.HTTPFactory.createXHR(t,e);throw"Cross-origin HTTP requests are not supported"},createXHR(){return new(this.getXHRAPI())},createWebSocket(t){return new(this.getWebSocketAPI())(t)},addUnloadListener(t){},removeUnloadListener(t){}},vt=n(10),yt=n.n(vt);function mt(t){return"none"!==t.type.toLowerCase()}class wt extends u.a{constructor(){super(),this.online=!0,yt.a.fetch().then(t=>{this.online=mt(t)}),yt.a.addEventListener(t=>{var e=mt(t);this.online!==e&&(this.online=e,this.online?this.emit("online"):this.emit("offline"))})}isOnline(){return this.online}}var _t,St=new wt;!function(t){t.UserAuthentication="user-authentication",t.ChannelAuthorization="channel-authorization"}(_t||(_t={}));var kt=function(t,e,n,r,i){const s=zt.createXHR();for(var o in s.open("POST",n.endpoint,!0),s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),n.headers)s.setRequestHeader(o,n.headers[o]);if(null!=n.headersProvider){let t=n.headersProvider();for(var o in t)s.setRequestHeader(o,t[o])}return s.onreadystatechange=function(){if(4===s.readyState)if(200===s.status){let t,e=!1;try{t=JSON.parse(s.responseText),e=!0}catch(t){i(new R(200,`JSON returned from ${r.toString()} endpoint was invalid, yet status code was 200. Data was: ${s.responseText}`),null)}e&&i(null,t)}else{let t="";switch(r){case _t.UserAuthentication:t=I("authenticationEndpoint");break;case _t.ChannelAuthorization:t="Clients must be authorized to join private or presence channels. "+I("authorizationEndpoint")}i(new R(s.status,`Unable to retrieve auth string from ${r.toString()} endpoint - received status: ${s.status} from ${n.endpoint}. ${t}`),null)}},s.send(e),s},Ct={name:"xhr",getAgent:function(t,e){return function(n,i){var s="http"+(e?"s":"")+"://"+(t.host||t.options.host)+t.options.path;s+="/2?"+r.e(n);var o=zt.createXHR();o.open("GET",s,!0),o.onreadystatechange=function(){if(4===o.readyState){let{status:n,responseText:r}=o;if(200!==n)return void l.a.debug(`TimelineSender Error: received ${n} from stats.pusher.com`);try{var{host:e}=JSON.parse(r)}catch(t){l.a.debug("TimelineSenderError: invalid response "+r)}e&&(t.host=e)}},o.send()}}};const{getDefaultStrategy:Tt,Transports:Et,setup:At,getProtocol:Pt,isXHRSupported:xt,getLocalStorage:Ot,createXHR:Lt,createWebSocket:Ut,addUnloadListener:Rt,removeUnloadListener:Mt,transportConnectionInitializer:It,createSocketRequest:Nt,HTTPFactory:jt}=bt;var Dt,zt={getDefaultStrategy:Tt,Transports:Et,setup:At,getProtocol:Pt,isXHRSupported:xt,getLocalStorage:Ot,createXHR:Lt,createWebSocket:Ut,addUnloadListener:Rt,removeUnloadListener:Mt,transportConnectionInitializer:It,createSocketRequest:Nt,HTTPFactory:jt,TimelineTransport:Ct,getAuthorizers:()=>({ajax:kt}),getWebSocketAPI:()=>WebSocket,getXHRAPI:()=>XMLHttpRequest,getNetwork:()=>St,randomInt:t=>Math.floor(Math.random()*t)};!function(t){t[t.ERROR=3]="ERROR",t[t.INFO=6]="INFO",t[t.DEBUG=7]="DEBUG"}(Dt||(Dt={}));var Ht=Dt;class Bt{constructor(t,e,n){this.key=t,this.session=e,this.events=[],this.options=n||{},this.sent=0,this.uniqueID=0}log(t,e){t<=this.options.level&&(this.events.push(r.f({},e,{timestamp:c.a.now()})),this.options.limit&&this.events.length>this.options.limit&&this.events.shift())}error(t){this.log(Ht.ERROR,t)}info(t){this.log(Ht.INFO,t)}debug(t){this.log(Ht.DEBUG,t)}isEmpty(){return 0===this.events.length}send(t,e){var n=r.f({session:this.session,bundle:this.sent+1,key:this.key,lib:"js",version:this.options.version,cluster:this.options.cluster,features:this.options.features,timeline:this.events},this.options.params);return this.events=[],t(n,(t,n)=>{t||this.sent++,e&&e(t,n)}),!0}generateUniqueID(){return this.uniqueID++,this.uniqueID}}class Ft{constructor(t,e,n,r){this.name=t,this.priority=e,this.transport=n,this.options=r||{}}isSupported(){return this.transport.isSupported({useTLS:this.options.useTLS})}connect(t,e){if(!this.isSupported())return qt(new U,e);if(this.priority<t)return qt(new P,e);var n=!1,i=this.transport.createConnection(this.name,this.priority,this.options.key,this.options),s=null,o=function(){i.unbind("initialized",o),i.connect()},a=function(){s=J.createHandshake(i,(function(t){n=!0,u(),e(null,t)}))},h=function(t){u(),e(t)},c=function(){var t;u(),t=r.l(i),e(new x(t))},u=function(){i.unbind("initialized",o),i.unbind("open",a),i.unbind("error",h),i.unbind("closed",c)};return i.bind("initialized",o),i.bind("open",a),i.bind("error",h),i.bind("closed",c),i.initialize(),{abort:()=>{n||(u(),s?s.close():i.close())},forceMinPriority:t=>{n||this.priority<t&&(s?s.close():i.close())}}}}function qt(t,e){return c.a.defer((function(){e(t)})),{abort:function(){},forceMinPriority:function(){}}}const{Transports:Yt}=zt;var Kt=function(t,e,n,i,s,o){var a,h=Yt[n];if(!h)throw new L(n);return!(t.enabledTransports&&-1===r.d(t.enabledTransports,e)||t.disabledTransports&&-1!==r.d(t.disabledTransports,e))?(s=Object.assign({ignoreNullOrigin:t.ignoreNullOrigin},s),a=new Ft(e,i,o?o.getAssistant(h):h,s)):a=$t,a},$t={isSupported:function(){return!1},connect:function(t,e){var n=c.a.defer((function(){e(new U)}));return{abort:function(){n.ensureAborted()},forceMinPriority:function(){}}}},Jt=n(7);var Xt=t=>{if(void 0===zt.getAuthorizers()[t.transport])throw`'${t.transport}' is not a recognized auth transport`;return(e,n)=>{const r=((t,e)=>{var n="socket_id="+encodeURIComponent(t.socketId);for(var r in e.params)n+="&"+encodeURIComponent(r)+"="+encodeURIComponent(e.params[r]);if(null!=e.paramsProvider){let t=e.paramsProvider();for(var r in t)n+="&"+encodeURIComponent(r)+"="+encodeURIComponent(t[r])}return n})(e,t);zt.getAuthorizers()[t.transport](zt,r,t,_t.UserAuthentication,n)}};var Wt=t=>{if(void 0===zt.getAuthorizers()[t.transport])throw`'${t.transport}' is not a recognized auth transport`;return(e,n)=>{const r=((t,e)=>{var n="socket_id="+encodeURIComponent(t.socketId);for(var r in n+="&channel_name="+encodeURIComponent(t.channelName),e.params)n+="&"+encodeURIComponent(r)+"="+encodeURIComponent(e.params[r]);if(null!=e.paramsProvider){let t=e.paramsProvider();for(var r in t)n+="&"+encodeURIComponent(r)+"="+encodeURIComponent(t[r])}return n})(e,t);zt.getAuthorizers()[t.transport](zt,r,t,_t.ChannelAuthorization,n)}};function Gt(t){return t.httpHost?t.httpHost:t.cluster?`sockjs-${t.cluster}.pusher.com`:i.httpHost}function Vt(t){return t.wsHost?t.wsHost:`ws-${t.cluster}.pusher.com`}function Zt(t){return"https:"===zt.getProtocol()||!1!==t.forceTLS}function Qt(t){return"enableStats"in t?t.enableStats:"disableStats"in t&&!t.disableStats}function te(t){const e=Object.assign(Object.assign({},i.userAuthentication),t.userAuthentication);return"customHandler"in e&&null!=e.customHandler?e.customHandler:Xt(e)}function ee(t,e){const n=function(t,e){let n;return"channelAuthorization"in t?n=Object.assign(Object.assign({},i.channelAuthorization),t.channelAuthorization):(n={transport:t.authTransport||i.authTransport,endpoint:t.authEndpoint||i.authEndpoint},"auth"in t&&("params"in t.auth&&(n.params=t.auth.params),"headers"in t.auth&&(n.headers=t.auth.headers)),"authorizer"in t&&(n.customHandler=((t,e,n)=>{const r={authTransport:e.transport,authEndpoint:e.endpoint,auth:{params:e.params,headers:e.headers}};return(e,i)=>{const s=t.channel(e.channelName);n(s,r).authorize(e.socketId,i)}})(e,n,t.authorizer))),n}(t,e);return"customHandler"in n&&null!=n.customHandler?n.customHandler:Wt(n)}class ne extends u.a{constructor(t){super((function(t,e){l.a.debug("No callbacks on watchlist events for "+t)})),this.pusher=t,this.bindWatchlistInternalEvent()}handleEvent(t){t.data.events.forEach(t=>{this.emit(t.name,t)})}bindWatchlistInternalEvent(){this.pusher.connection.bind("message",t=>{"pusher_internal:watchlist_events"===t.event&&this.handleEvent(t)})}}var re=function(){let t,e;return{promise:new Promise((n,r)=>{t=n,e=r}),resolve:t,reject:e}};class ie extends u.a{constructor(t){super((function(t,e){l.a.debug("No callbacks on user for "+t)})),this.signin_requested=!1,this.user_data=null,this.serverToUserChannel=null,this.signinDonePromise=null,this._signinDoneResolve=null,this._onAuthorize=(t,e)=>{if(t)return l.a.warn("Error during signin: "+t),void this._cleanup();this.pusher.send_event("pusher:signin",{auth:e.auth,user_data:e.user_data})},this.pusher=t,this.pusher.connection.bind("state_change",({previous:t,current:e})=>{"connected"!==t&&"connected"===e&&this._signin(),"connected"===t&&"connected"!==e&&(this._cleanup(),this._newSigninPromiseIfNeeded())}),this.watchlist=new ne(t),this.pusher.connection.bind("message",t=>{"pusher:signin_success"===t.event&&this._onSigninSuccess(t.data),this.serverToUserChannel&&this.serverToUserChannel.name===t.channel&&this.serverToUserChannel.handleEvent(t)})}signin(){this.signin_requested||(this.signin_requested=!0,this._signin())}_signin(){this.signin_requested&&(this._newSigninPromiseIfNeeded(),"connected"===this.pusher.connection.state&&this.pusher.config.userAuthenticator({socketId:this.pusher.connection.socket_id},this._onAuthorize))}_onSigninSuccess(t){try{this.user_data=JSON.parse(t.user_data)}catch(e){return l.a.error("Failed parsing user data after signin: "+t.user_data),void this._cleanup()}if("string"!=typeof this.user_data.id||""===this.user_data.id)return l.a.error("user_data doesn't contain an id. user_data: "+this.user_data),void this._cleanup();this._signinDoneResolve(),this._subscribeChannels()}_subscribeChannels(){this.serverToUserChannel=new N("#server-to-user-"+this.user_data.id,this.pusher),this.serverToUserChannel.bind_global((t,e)=>{0!==t.indexOf("pusher_internal:")&&0!==t.indexOf("pusher:")&&this.emit(t,e)}),(t=>{t.subscriptionPending&&t.subscriptionCancelled?t.reinstateSubscription():t.subscriptionPending||"connected"!==this.pusher.connection.state||t.subscribe()})(this.serverToUserChannel)}_cleanup(){this.user_data=null,this.serverToUserChannel&&(this.serverToUserChannel.unbind_all(),this.serverToUserChannel.disconnect(),this.serverToUserChannel=null),this.signin_requested&&this._signinDoneResolve()}_newSigninPromiseIfNeeded(){if(!this.signin_requested)return;if(this.signinDonePromise&&!this.signinDonePromise.done)return;const{promise:t,resolve:e,reject:n}=re();t.done=!1;const r=()=>{t.done=!0};t.then(r).catch(r),this.signinDonePromise=t,this._signinDoneResolve=e}}class se{static ready(){se.isReady=!0;for(var t=0,e=se.instances.length;t<e;t++)se.instances[t].connect()}static getClientFeatures(){return r.i(r.h({ws:zt.Transports.ws},(function(t){return t.isSupported({})})))}constructor(t,e){!function(t){if(null==t)throw"You must pass your app key when you instantiate Pusher."}(t),Object(Jt.a)(e),this.key=t,this.config=function(t,e){let n={activityTimeout:t.activityTimeout||i.activityTimeout,cluster:t.cluster,httpPath:t.httpPath||i.httpPath,httpPort:t.httpPort||i.httpPort,httpsPort:t.httpsPort||i.httpsPort,pongTimeout:t.pongTimeout||i.pongTimeout,statsHost:t.statsHost||i.stats_host,unavailableTimeout:t.unavailableTimeout||i.unavailableTimeout,wsPath:t.wsPath||i.wsPath,wsPort:t.wsPort||i.wsPort,wssPort:t.wssPort||i.wssPort,enableStats:Qt(t),httpHost:Gt(t),useTLS:Zt(t),wsHost:Vt(t),userAuthenticator:te(t),channelAuthorizer:ee(t,e)};return"disabledTransports"in t&&(n.disabledTransports=t.disabledTransports),"enabledTransports"in t&&(n.enabledTransports=t.enabledTransports),"ignoreNullOrigin"in t&&(n.ignoreNullOrigin=t.ignoreNullOrigin),"timelineParams"in t&&(n.timelineParams=t.timelineParams),"nacl"in t&&(n.nacl=t.nacl),n}(e,this),this.channels=J.createChannels(),this.global_emitter=new u.a,this.sessionID=zt.randomInt(1e9),this.timeline=new Bt(this.key,this.sessionID,{cluster:this.config.cluster,features:se.getClientFeatures(),params:this.config.timelineParams||{},limit:50,level:Ht.INFO,version:i.VERSION}),this.config.enableStats&&(this.timelineSender=J.createTimelineSender(this.timeline,{host:this.config.statsHost,path:"/timeline/v2/"+zt.TimelineTransport.name}));this.connection=J.createConnectionManager(this.key,{getStrategy:t=>zt.getDefaultStrategy(this.config,t,Kt),timeline:this.timeline,activityTimeout:this.config.activityTimeout,pongTimeout:this.config.pongTimeout,unavailableTimeout:this.config.unavailableTimeout,useTLS:Boolean(this.config.useTLS)}),this.connection.bind("connected",()=>{this.subscribeAll(),this.timelineSender&&this.timelineSender.send(this.connection.isUsingTLS())}),this.connection.bind("message",t=>{var e=0===t.event.indexOf("pusher_internal:");if(t.channel){var n=this.channel(t.channel);n&&n.handleEvent(t)}e||this.global_emitter.emit(t.event,t.data)}),this.connection.bind("connecting",()=>{this.channels.disconnect()}),this.connection.bind("disconnected",()=>{this.channels.disconnect()}),this.connection.bind("error",t=>{l.a.warn(t)}),se.instances.push(this),this.timeline.info({instances:se.instances.length}),this.user=new ie(this),se.isReady&&this.connect()}channel(t){return this.channels.find(t)}allChannels(){return this.channels.all()}connect(){if(this.connection.connect(),this.timelineSender&&!this.timelineSenderTimer){var t=this.connection.isUsingTLS(),e=this.timelineSender;this.timelineSenderTimer=new Y.b(6e4,(function(){e.send(t)}))}}disconnect(){this.connection.disconnect(),this.timelineSenderTimer&&(this.timelineSenderTimer.ensureAborted(),this.timelineSenderTimer=null)}bind(t,e,n){return this.global_emitter.bind(t,e,n),this}unbind(t,e,n){return this.global_emitter.unbind(t,e,n),this}bind_global(t){return this.global_emitter.bind_global(t),this}unbind_global(t){return this.global_emitter.unbind_global(t),this}unbind_all(t){return this.global_emitter.unbind_all(),this}subscribeAll(){var t;for(t in this.channels.channels)t