{"version":3,"sources":["../Pusher/webpack/universalModuleDefinition","../Pusher/webpack/bootstrap","../Pusher/node_modules/@stablelib/base64/base64.ts","../Pusher/node_modules/@stablelib/utf8/utf8.ts","../Pusher/src/core/pusher.js","../Pusher/src/runtimes/web/dom/script_receiver_factory.ts","../Pusher/src/core/defaults.ts","../Pusher/src/runtimes/web/dom/dependencies.ts","../Pusher/src/runtimes/web/dom/dependency_loader.ts","../Pusher/src/core/utils/url_store.ts","../Pusher/src/core/auth/options.ts","../Pusher/src/core/errors.ts","../Pusher/src/core/base64.ts","../Pusher/src/runtimes/isomorphic/auth/xhr_auth.ts","../Pusher/src/core/utils/timers/abstract_timer.ts","../Pusher/src/core/utils/timers/index.ts","../Pusher/src/core/util.ts","../Pusher/src/core/utils/collections.ts","../Pusher/src/core/logger.ts","../Pusher/src/runtimes/web/auth/jsonp_auth.ts","../Pusher/src/runtimes/web/dom/script_request.ts","../Pusher/src/runtimes/web/dom/jsonp_request.ts","../Pusher/src/runtimes/web/timeline/jsonp_timeline.ts","../Pusher/src/core/transports/url_schemes.ts","../Pusher/src/core/events/callback_registry.ts","../Pusher/src/core/events/dispatcher.ts","../Pusher/src/core/transports/transport_connection.ts","../Pusher/src/core/transports/transport.ts","../Pusher/src/runtimes/isomorphic/transports/transports.ts","../Pusher/src/runtimes/web/transports/transports.ts","../Pusher/src/runtimes/web/net_info.ts","../Pusher/src/core/transports/assistant_to_the_transport_manager.ts","../Pusher/src/core/connection/protocol/protocol.ts","../Pusher/src/core/connection/connection.ts","../Pusher/src/core/connection/handshake/index.ts","../Pusher/src/core/timeline/timeline_sender.ts","../Pusher/src/core/channels/channel.ts","../Pusher/src/core/channels/private_channel.ts","../Pusher/src/core/channels/members.ts","../Pusher/src/core/channels/presence_channel.ts","../Pusher/src/core/channels/encrypted_channel.ts","../Pusher/src/core/connection/connection_manager.ts","../Pusher/src/core/channels/channels.ts","../Pusher/src/core/utils/factory.ts","../Pusher/src/core/transports/transport_manager.ts","../Pusher/src/core/strategies/sequential_strategy.ts","../Pusher/src/core/strategies/best_connected_ever_strategy.ts","../Pusher/src/core/strategies/websocket_prioritized_cached_strategy.ts","../Pusher/src/core/strategies/delayed_strategy.ts","../Pusher/src/core/strategies/if_strategy.ts","../Pusher/src/core/strategies/first_connected_strategy.ts","../Pusher/src/runtimes/web/default_strategy.ts","../Pusher/src/core/http/state.ts","../Pusher/src/runtimes/web/http/http_xdomain_request.ts","../Pusher/src/core/http/http_request.ts","../Pusher/src/core/http/http_socket.ts","../Pusher/src/core/timeline/level.ts","../Pusher/src/core/http/http_streaming_socket.ts","../Pusher/src/core/http/http_polling_socket.ts","../Pusher/src/runtimes/isomorphic/http/http_xhr_request.ts","../Pusher/src/runtimes/isomorphic/http/http.ts","../Pusher/src/runtimes/web/http/http.ts","../Pusher/src/runtimes/web/runtime.ts","../Pusher/src/runtimes/web/transports/transport_connection_initializer.ts","../Pusher/src/core/timeline/timeline.ts","../Pusher/src/core/strategies/transport_strategy.ts","../Pusher/src/core/strategies/strategy_builder.ts","../Pusher/src/core/auth/user_authenticator.ts","../Pusher/src/core/auth/channel_authorizer.ts","../Pusher/src/core/auth/deprecated_channel_authorizer.ts","../Pusher/src/core/config.ts","../Pusher/src/core/watchlist.ts","../Pusher/src/core/utils/flat_promise.ts","../Pusher/src/core/user.ts","../Pusher/src/core/pusher.ts","../Pusher/src/core/options.ts"],"names":["factory","window","installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","INVALID_BYTE","Coder","_paddingCharacter","encodedLength","length","this","encode","data","out","_encodeByte","left","maxDecodedLength","decodedLength","_getPaddingLength","decode","Uint8Array","paddingLength","op","haveBad","v0","v1","v2","v3","_decodeChar","charCodeAt","Error","b","result","String","fromCharCode","stdCoder","URLSafeCoder","_super","__extends","urlSafeCoder","encodeURLSafe","decodeURLSafe","INVALID_UTF16","INVALID_UTF8","arr","pos","chars","min","n1","n2","n3","push","join","default","ScriptReceiverFactory","constructor","prefix","lastId","callback","number","id","called","callbackWrapper","apply","arguments","remove","receiver","ScriptReceivers","defaults","VERSION","PROTOCOL","wsPort","wssPort","wsPath","httpHost","httpPort","httpsPort","httpPath","stats_host","authEndpoint","authTransport","activityTimeout","pongTimeout","unavailableTimeout","userAuthentication","endpoint","transport","channelAuthorization","cdn_http","cdn_https","dependency_suffix","DependenciesReceivers","Dependencies","options","receivers","loading","load","self","request","runtime","createScriptRequest","getPath","error","callbacks","successCallback","wasSuccessful","cleanup","send","getRoot","protocol","getDocument","location","useTLS","replace","version","suffix","urlStore","baseUrl","urls","authenticationEndpoint","path","authorizationEndpoint","javascriptQuickStart","triggeringClientEvents","encryptedChannelSupport","fullUrl","AuthRequestType","url_store","urlObj","url","concat","BadEventName","msg","super","setPrototypeOf","BadChannelName","RequestTimedOut","TransportPriorityTooLow","TransportClosed","UnsupportedFeature","UnsupportedTransport","UnsupportedStrategy","HTTPAuthError","status","xhr_auth","context","query","authOptions","authRequestType","xhr","createXHR","headerName","open","setRequestHeader","headers","headersProvider","dynamicHeaders","onreadystatechange","readyState","parsed","JSON","parse","responseText","e","toString","UserAuthentication","ChannelAuthorization","b64chars","b64tab","base64_i","charAt","cb_utob","cc","utob","u","cb_encode","ccc","padlen","ord","btoa","abstract_timer","set","clear","delay","timer","isRunning","ensureAborted","timers_clearTimeout","clearTimeout","timers_clearInterval","clearInterval","timers_OneOffTimer","setTimeout","timers_PeriodicTimer","setInterval","Util","now","Date","valueOf","defer","method","_len","args","Array","_key","boundArguments","slice","util","extend","target","extensions","undefined","stringify","safeJSONStringify","arrayIndexOf","array","item","nativeIndexOf","indexOf","objectApply","f","keys","_","map","filter","test","filterObject","Boolean","any","encodeParamsObject","mapObject","encodeURIComponent","buildQueryString","flatten","source","objects","paths","derez","nu","$ref","decycleObject","logger","globalLog","message","console","log","debug","_len2","_key2","warn","_len3","_key3","globalLogWarn","_len4","_key4","globalLogError","defaultLoggingFunction","_len5","_key5","core_pusher","logToConsole","jsonp_auth","callbackName","nextAuthCallbackID","document","script","createElement","auth_callbacks","callback_name","src","head","getElementsByTagName","documentElement","insertBefore","firstChild","ScriptRequest","errorString","type","charset","addEventListener","onerror","onload","async","attachEvent","navigator","userAgent","errorScript","text","nextSibling","parentNode","removeChild","jsonp_request_JSONPRequest","jsonp_timeline","getAgent","sender","host","createJSONPRequest","getGenericURL","baseScheme","params","hostTLS","hostNonTLS","getGenericPath","queryString","ws","getInitial","http","sockjs","callback_registry_CallbackRegistry","_callbacks","add","prefixedEventName","fn","names","removeCallback","removeAllCallbacks","binding","dispatcher_Dispatcher","failThrough","global_callbacks","eventName","bind_global","unbind","unbind_global","unbind_all","emit","metadata","transport_connection_TransportConnection","hooks","priority","initialize","transportConnectionInitializer","state","timeline","generateUniqueID","handlesActivityChecks","supportsPing","connect","socket","getSocket","onError","changeState","bindListeners","close","ping","onOpen","beforeOpen","onopen","buildTimelineMessage","onClose","closeEvent","code","reason","wasClean","unbindListeners","onMessage","onActivity","onclose","onmessage","onactivity","info","cid","transport_Transport","isSupported","environment","createConnection","WSTransport","isInitialized","getWebSocketAPI","createWebSocket","httpConfiguration","streamingConfiguration","HTTPFactory","createStreamingSocket","pollingConfiguration","createPollingSocket","xhrConfiguration","isXHRSupported","transports","xhr_streaming","xhr_polling","SockJSTransport","file","SockJS","js_path","ignore_null_origin","ignoreNullOrigin","xdrConfiguration","isXDRSupported","XDRStreamingTransport","XDRPollingTransport","xdr_streaming","xdr_polling","transports_transports","net_info_Network","isOnline","onLine","assistant_to_the_transport_manager_AssistantToTheTransportManager","manager","minPingDelay","maxPingDelay","pingDelay","connection","openTimestamp","onClosed","reportDeath","lifespan","Math","max","isAlive","Protocol","decodeMessage","messageEvent","messageData","pusherEventData","pusherEvent","event","channel","user_id","encodeMessage","processHandshake","activity_timeout","action","socket_id","getCloseAction","getCloseError","protocol_protocol","connection_Connection","send_event","listeners","activity","closed","handleCloseEvent","listener","handshake_Handshake","finish","timeline_sender_TimelineSender","isEmpty","TimelineTransport","channel_Channel","pusher","subscribed","subscriptionPending","subscriptionCancelled","authorize","socketId","auth","trigger","disconnect","handleEvent","handleSubscriptionSucceededEvent","handleSubscriptionCountEvent","unsubscribe","subscription_count","subscriptionCount","subscribe","assign","channel_data","cancelSubscription","reinstateSubscription","private_channel_PrivateChannel","config","channelAuthorizer","channelName","members_Members","reset","members","each","member","setMyID","myID","onSubscription","subscriptionData","presence","hash","count","me","addMember","memberData","user_info","removeMember","presence_channel_PresenceChannel","authData","__awaiter","channelData","user","signinDonePromise","user_data","handleInternalEvent","addedMember","removedMember","encrypted_channel_EncryptedChannel","nacl","sharedSecret","base64","handleEncryptedEvent","ciphertext","nonce","cipherText","secretbox","overheadLength","nonceLength","bytes","getDataToEmit","raw","utf8","_a","connection_manager_ConnectionManager","usingTLS","errorCallbacks","buildErrorCallbacks","connectionCallbacks","buildConnectionCallbacks","handshakeCallbacks","buildHandshakeCallbacks","Network","getNetwork","netinfo","retryIn","sendActivityCheck","updateStrategy","runner","strategy","updateState","startConnecting","setUnavailableTimer","disconnectInternally","isUsingTLS","handshake","handshakeError","abortConnecting","abort","clearRetryTimer","clearUnavailableTimer","abandonConnection","getStrategy","round","retryTimer","unavailableTimer","stopActivityCheck","activityTimer","pong_timed_out","resetActivityCheck","shouldRetry","connected","Infinity","setConnection","withErrorEmitted","tls_only","refused","backoff","retry","newState","previousState","newStateDescription","previous","current","channels_Channels","channels","createEncryptedChannel","errMsg","createPrivateChannel","createPresenceChannel","createChannel","all","values","find","createChannels","createConnectionManager","createTimelineSender","createHandshake","createAssistantToTheTransportManager","transport_manager_TransportManager","livesLeft","lives","getAssistant","sequential_strategy_SequentialStrategy","strategies","loop","failFast","timeout","timeoutLimit","minPriority","tryNextStrategy","tryStrategy","forceMinPriority","best_connected_ever_strategy_BestConnectedEverStrategy","callbackBuilder","runners","rs","abortRunner","collections_all","allRunnersFailed","aborted","websocket_prioritized_cached_strategy_WebSocketPrioritizedCachedStrategy","ttl","storage","getLocalStorage","serializedCache","getTransportCacheKey","flushTransportCache","fetchTransportCache","cacheSkipCount","timestamp","includes","cached","latency","startTimestamp","pop","cb","storeTransportCache","delayed_strategy_DelayedStrategy","_ref","IfStrategy","trueBranch","falseBranch","FirstConnectedStrategy","testSupportsStrategy","State","default_strategy","baseOptions","defineTransport","definedTransports","defineTransportStrategy","wsStrategy","ws_options","wsHost","wss_options","sockjs_options","timeouts","ws_manager","streaming_manager","ws_transport","wss_transport","sockjs_transport","xhr_streaming_transport","xdr_streaming_transport","xhr_polling_transport","xdr_polling_transport","ws_loop","wss_loop","sockjs_loop","streaming_loop","polling_loop","http_loop","http_fallback_loop","http_xdomain_request","getRequest","xdr","XDomainRequest","ontimeout","onprogress","onChunk","abortRequest","http_request_HTTPRequest","start","payload","position","unloader","addUnloadListener","removeUnloadListener","chunk","advanceBuffer","isBufferTooLong","buffer","unreadData","endOfLinePosition","autoIncrement","getUniqueURL","separator","randomNumber","randomInt","TimelineLevel","http_socket","session","randomString","parts","exec","base","getLocation","CONNECTING","openStream","sendRaw","sendHeartbeat","OPEN","createSocketRequest","reconnect","closeStream","CLOSED","onEvent","onHeartbeat","hostname","urlParts","replaceHost","stream","getReceiveURL","onFinished","http_streaming_socket","http_polling_socket","http_xhr_request","getXHRAPI","http_http","createSocket","createRequest","getDefaultStrategy","Transports","XMLHttpRequest","WebSocket","MozWebSocket","setup","PusherClass","Pusher","initializeOnDocumentBody","onDocumentBody","ready","getProtocol","getAuthorizers","ajax","jsonp","body","localStorage","createXMLHttpRequest","createMicrosoftXHR","ActiveXObject","createXDR","Constructor","withCredentials","documentProtocol","removeEventListener","detachEvent","floor","crypto","getRandomValues","Uint32Array","pow","timeline_level","timeline_Timeline","events","sent","uniqueID","level","limit","shift","ERROR","INFO","DEBUG","sendfn","bundle","lib","cluster","features","transport_strategy_TransportStrategy","failAttempt","onInitialized","serializedTransport","strategy_builder_Transports","strategy_builder_defineTransport","transportClass","enabledTransports","disabledTransports","strategy_builder_UnsupportedStrategy","deferred","user_authenticator","composeChannelQuery","paramsProvider","dynamicParams","channel_authorizer","channel_authorizer_composeChannelQuery","ChannelAuthorizerProxy","channelAuthorizerGenerator","deprecatedAuthorizerOptions","getHttpHost","opts","getWebsocketHost","shouldUseTLS","forceTLS","getEnableStatsConfig","enableStats","disableStats","buildUserAuthenticator","buildChannelAuthorizer","customHandler","authorizer","buildChannelAuth","watchlist_WatchlistFacade","bindWatchlistInternalEvent","forEach","watchlistEvent","flat_promise","resolve","reject","promise","Promise","res","rej","user_UserFacade","signin_requested","serverToUserChannel","_signinDoneResolve","_onAuthorize","err","_cleanup","_ref2","_signin","_newSigninPromiseIfNeeded","watchlist","_onSigninSuccess","signin","userAuthenticator","_subscribeChannels","ensure_subscribed","done","setDone","then","catch","pusher_Pusher","isReady","instances","getClientFeatures","app_key","checkAppKey","validateOptions","statsHost","timelineParams","getConfig","global_emitter","sessionID","timelineSender","subscribeAll","internal","allChannels","timelineSenderTimer","event_name","channel_name","Runtime","__webpack_exports__"],"mappings":";iGAAA,IAAAA,EASCC,OATDD,EASC,WACD,O,YCTA,IAAAE,EAAA,GAGA,SAAAC,EAAAC,GAGA,GAAAF,EAAAE,GACA,OAAAF,EAAAE,GAAAC,QAGA,IAAAC,EAAAJ,EAAAE,GAAA,CACAG,EAAAH,EACAI,GAAA,EACAH,QAAA,IAUA,OANAI,EAAAL,GAAAM,KAAAJ,EAAAD,QAAAC,IAAAD,QAAAF,GAGAG,EAAAE,GAAA,EAGAF,EAAAD,OACA,CAyDA,OArDAF,EAAAQ,EAAAF,EAGAN,EAAAS,EAAAV,EAGAC,EAAAU,EAAA,SAAAR,EAAAS,EAAAC,GACAZ,EAAAa,EAAAX,EAAAS,IACAG,OAAAC,eAAAb,EAAAS,EAAA,CAA0CK,YAAA,EAAAC,IAAAL,GAE1C,EAGAZ,EAAAkB,EAAA,SAAAhB,GACA,qBAAAiB,eAAAC,a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K+yB,eAAetf,cAAczQ,GAC3BhD,IACT,CAEA0T,WAAW1Q,GAET,OADAhD,KAAK+yB,eAAerf,aACb1T,IACT,CAEAkzB,eACE,IAAI7W,EACJ,IAAKA,KAAerc,KAAKoiB,SAASA,SAC5BpiB,KAAKoiB,SAASA,SAAS5iB,eAAe6c,IACxCrc,KAAK6b,UAAUQ,EAGrB,CAEAR,UAAU0X,GACR,IAAIha,EAAUvZ,KAAKoiB,SAASxP,IAAI2gB,EAAcvzB,MAS9C,OARIuZ,EAAQyB,qBAAuBzB,EAAQ0B,sBACzC1B,EAAQ0C,wBAEP1C,EAAQyB,qBACiB,cAA1Bhb,KAAKwY,WAAWtE,OAEhBqF,EAAQsC,YAEHtC,CACT,CAEAmC,YAAY6X,GACV,IAAIha,EAAUvZ,KAAKoiB,SAASQ,KAAK2Q,GAC7Bha,GAAWA,EAAQyB,oBACrBzB,EAAQyC,sBAERzC,EAAUvZ,KAAKoiB,SAAS7e,OAAOgwB,KAChBha,EAAQwB,YACrBxB,EAAQmC,aAGd,CAEAxB,WAAWoZ,EAAoBpzB,EAAWqZ,GACxC,OAAOvZ,KAAKwY,WAAW0B,WAAWoZ,EAAYpzB,EAAMqZ,EACtD,CAEAqW,eACE,OAAO5vB,KAAKmc,OAAO7V,MACrB,CAEAurB,SACE7xB,KAAK2d,KAAKkU,QACZ,EAzNOQ,GAAAE,UAAsB,GACtBF,GAAAC,SAAmB,EACnBD,GAAA3iB,cAAwB,EAGxB2iB,GAAAmB,QAA2B/tB,GAC3B4sB,GAAA5uB,gBAA6BgC,GAAShC,gBACtC4uB,GAAAptB,sBAAmCQ,GAASR,sBAC5CotB,GAAApiB,eAA4BxK,GAASwK,eAVzB,IAAAR,GAAAgkB,EAAA,QAAApB,GAoOrB5sB,GAAQkmB,MAAM0G,G,K1E1Pd30B,EAAAD,QAAAL,G","file":"static/js/1.febfd2ee.chunk.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"Pusher\"] = factory();\n\telse\n\t\troot[\"Pusher\"] = factory();\n})(window, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 2);\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package base64 implements Base64 encoding and decoding.\n */\n\n// Invalid character used in decoding to indicate\n// that the character to decode is out of range of\n// alphabet and cannot be decoded.\nconst INVALID_BYTE = 256;\n\n/**\n * Implements standard Base64 encoding.\n *\n * Operates in constant time.\n */\nexport class Coder {\n // TODO(dchest): methods to encode chunk-by-chunk.\n\n constructor(private _paddingCharacter = \"=\") { }\n\n encodedLength(length: number): number {\n if (!this._paddingCharacter) {\n return (length * 8 + 5) / 6 | 0;\n }\n return (length + 2) / 3 * 4 | 0;\n }\n\n encode(data: Uint8Array): string {\n let out = \"\";\n\n let i = 0;\n for (; i < data.length - 2; i += 3) {\n let c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);\n out += this._encodeByte((c >>> 3 * 6) & 63);\n out += this._encodeByte((c >>> 2 * 6) & 63);\n out += this._encodeByte((c >>> 1 * 6) & 63);\n out += this._encodeByte((c >>> 0 * 6) & 63);\n }\n\n const left = data.length - i;\n if (left > 0) {\n let c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);\n out += this._encodeByte((c >>> 3 * 6) & 63);\n out += this._encodeByte((c >>> 2 * 6) & 63);\n if (left === 2) {\n out += this._encodeByte((c >>> 1 * 6) & 63);\n } else {\n out += this._paddingCharacter || \"\";\n }\n out += this._paddingCharacter || \"\";\n }\n\n return out;\n }\n\n maxDecodedLength(length: number): number {\n if (!this._paddingCharacter) {\n return (length * 6 + 7) / 8 | 0;\n }\n return length / 4 * 3 | 0;\n }\n\n decodedLength(s: string): number {\n return this.maxDecodedLength(s.length - this._getPaddingLength(s));\n }\n\n decode(s: string): Uint8Array {\n if (s.length === 0) {\n return new Uint8Array(0);\n }\n const paddingLength = this._getPaddingLength(s);\n const length = s.length - paddingLength;\n const out = new Uint8Array(this.maxDecodedLength(length));\n let op = 0;\n let i = 0;\n let haveBad = 0;\n let v0 = 0, v1 = 0, v2 = 0, v3 = 0;\n for (; i < length - 4; i += 4) {\n v0 = this._decodeChar(s.charCodeAt(i + 0));\n v1 = this._decodeChar(s.charCodeAt(i + 1));\n v2 = this._decodeChar(s.charCodeAt(i + 2));\n v3 = this._decodeChar(s.charCodeAt(i + 3));\n out[op++] = (v0 << 2) | (v1 >>> 4);\n out[op++] = (v1 << 4) | (v2 >>> 2);\n out[op++] = (v2 << 6) | v3;\n haveBad |= v0 & INVALID_BYTE;\n haveBad |= v1 & INVALID_BYTE;\n haveBad |= v2 & INVALID_BYTE;\n haveBad |= v3 & INVALID_BYTE;\n }\n if (i < length - 1) {\n v0 = this._decodeChar(s.charCodeAt(i));\n v1 = this._decodeChar(s.charCodeAt(i + 1));\n out[op++] = (v0 << 2) | (v1 >>> 4);\n haveBad |= v0 & INVALID_BYTE;\n haveBad |= v1 & INVALID_BYTE;\n }\n if (i < length - 2) {\n v2 = this._decodeChar(s.charCodeAt(i + 2));\n out[op++] = (v1 << 4) | (v2 >>> 2);\n haveBad |= v2 & INVALID_BYTE;\n }\n if (i < length - 3) {\n v3 = this._decodeChar(s.charCodeAt(i + 3));\n out[op++] = (v2 << 6) | v3;\n haveBad |= v3 & INVALID_BYTE;\n }\n if (haveBad !== 0) {\n throw new Error(\"Base64Coder: incorrect characters for decoding\");\n }\n return out;\n }\n\n // Standard encoding have the following encoded/decoded ranges,\n // which we need to convert between.\n //\n // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /\n // Index: 0 - 25 26 - 51 52 - 61 62 63\n // ASCII: 65 - 90 97 - 122 48 - 57 43 47\n //\n\n // Encode 6 bits in b into a new character.\n protected _encodeByte(b: number): string {\n // Encoding uses constant time operations as follows:\n //\n // 1. Define comparison of A with B using (A - B) >>> 8:\n // if A > B, then result is positive integer\n // if A <= B, then result is 0\n //\n // 2. Define selection of C or 0 using bitwise AND: X & C:\n // if X == 0, then result is 0\n // if X != 0, then result is C\n //\n // 3. Start with the smallest comparison (b >= 0), which is always\n // true, so set the result to the starting ASCII value (65).\n //\n // 4. Continue comparing b to higher ASCII values, and selecting\n // zero if comparison isn't true, otherwise selecting a value\n // to add to result, which:\n //\n // a) undoes the previous addition\n // b) provides new value to add\n //\n let result = b;\n // b >= 0\n result += 65;\n // b > 25\n result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);\n // b > 51\n result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);\n // b > 61\n result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);\n // b > 62\n result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);\n\n return String.fromCharCode(result);\n }\n\n // Decode a character code into a byte.\n // Must return 256 if character is out of alphabet range.\n protected _decodeChar(c: number): number {\n // Decoding works similar to encoding: using the same comparison\n // function, but now it works on ranges: result is always incremented\n // by value, but this value becomes zero if the range is not\n // satisfied.\n //\n // Decoding starts with invalid value, 256, which is then\n // subtracted when the range is satisfied. If none of the ranges\n // apply, the function returns 256, which is then checked by\n // the caller to throw error.\n let result = INVALID_BYTE; // start with invalid character\n\n // c == 43 (c > 42 and c < 44)\n result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);\n // c == 47 (c > 46 and c < 48)\n result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);\n // c > 47 and c < 58\n result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);\n // c > 64 and c < 91\n result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);\n // c > 96 and c < 123\n result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);\n\n return result;\n }\n\n private _getPaddingLength(s: string): number {\n let paddingLength = 0;\n if (this._paddingCharacter) {\n for (let i = s.length - 1; i >= 0; i--) {\n if (s[i] !== this._paddingCharacter) {\n break;\n }\n paddingLength++;\n }\n if (s.length < 4 || paddingLength > 2) {\n throw new Error(\"Base64Coder: incorrect padding\");\n }\n }\n return paddingLength;\n }\n\n}\n\nconst stdCoder = new Coder();\n\nexport function encode(data: Uint8Array): string {\n return stdCoder.encode(data);\n}\n\nexport function decode(s: string): Uint8Array {\n return stdCoder.decode(s);\n}\n\n/**\n * Implements URL-safe Base64 encoding.\n * (Same as Base64, but '+' is replaced with '-', and '/' with '_').\n *\n * Operates in constant time.\n */\nexport class URLSafeCoder extends Coder {\n // URL-safe encoding have the following encoded/decoded ranges:\n //\n // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _\n // Index: 0 - 25 26 - 51 52 - 61 62 63\n // ASCII: 65 - 90 97 - 122 48 - 57 45 95\n //\n\n protected _encodeByte(b: number): string {\n let result = b;\n // b >= 0\n result += 65;\n // b > 25\n result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);\n // b > 51\n result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);\n // b > 61\n result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);\n // b > 62\n result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);\n\n return String.fromCharCode(result);\n }\n\n protected _decodeChar(c: number): number {\n let result = INVALID_BYTE;\n\n // c == 45 (c > 44 and c < 46)\n result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62);\n // c == 95 (c > 94 and c < 96)\n result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63);\n // c > 47 and c < 58\n result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);\n // c > 64 and c < 91\n result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);\n // c > 96 and c < 123\n result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);\n\n return result;\n }\n}\n\nconst urlSafeCoder = new URLSafeCoder();\n\nexport function encodeURLSafe(data: Uint8Array): string {\n return urlSafeCoder.encode(data);\n}\n\nexport function decodeURLSafe(s: string): Uint8Array {\n return urlSafeCoder.decode(s);\n}\n\n\nexport const encodedLength = (length: number) =>\n stdCoder.encodedLength(length);\n\nexport const maxDecodedLength = (length: number) =>\n stdCoder.maxDecodedLength(length);\n\nexport const decodedLength = (s: string) =>\n stdCoder.decodedLength(s);\n","// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package utf8 implements UTF-8 encoding and decoding.\n */\n\nconst INVALID_UTF16 = \"utf8: invalid string\";\nconst INVALID_UTF8 = \"utf8: invalid source encoding\";\n\n/**\n * Encodes the given string into UTF-8 byte array.\n * Throws if the source string has invalid UTF-16 encoding.\n */\nexport function encode(s: string): Uint8Array {\n // Calculate result length and allocate output array.\n // encodedLength() also validates string and throws errors,\n // so we don't need repeat validation here.\n const arr = new Uint8Array(encodedLength(s));\n\n let pos = 0;\n for (let i = 0; i < s.length; i++) {\n let c = s.charCodeAt(i);\n if (c < 0x80) {\n arr[pos++] = c;\n } else if (c < 0x800) {\n arr[pos++] = 0xc0 | c >> 6;\n arr[pos++] = 0x80 | c & 0x3f;\n } else if (c < 0xd800) {\n arr[pos++] = 0xe0 | c >> 12;\n arr[pos++] = 0x80 | (c >> 6) & 0x3f;\n arr[pos++] = 0x80 | c & 0x3f;\n } else {\n i++; // get one more character\n c = (c & 0x3ff) << 10;\n c |= s.charCodeAt(i) & 0x3ff;\n c += 0x10000;\n\n arr[pos++] = 0xf0 | c >> 18;\n arr[pos++] = 0x80 | (c >> 12) & 0x3f;\n arr[pos++] = 0x80 | (c >> 6) & 0x3f;\n arr[pos++] = 0x80 | c & 0x3f;\n }\n }\n return arr;\n}\n\n/**\n * Returns the number of bytes required to encode the given string into UTF-8.\n * Throws if the source string has invalid UTF-16 encoding.\n */\nexport function encodedLength(s: string): number {\n let result = 0;\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n if (c < 0x80) {\n result += 1;\n } else if (c < 0x800) {\n result += 2;\n } else if (c < 0xd800) {\n result += 3;\n } else if (c <= 0xdfff) {\n if (i >= s.length - 1) {\n throw new Error(INVALID_UTF16);\n }\n i++; // \"eat\" next character\n result += 4;\n } else {\n throw new Error(INVALID_UTF16);\n }\n }\n return result;\n}\n\n/**\n * Decodes the given byte array from UTF-8 into a string.\n * Throws if encoding is invalid.\n */\nexport function decode(arr: Uint8Array): string {\n const chars: string[] = [];\n for (let i = 0; i < arr.length; i++) {\n let b = arr[i];\n\n if (b & 0x80) {\n let min;\n if (b < 0xe0) {\n // Need 1 more byte.\n if (i >= arr.length) {\n throw new Error(INVALID_UTF8);\n }\n const n1 = arr[++i];\n if ((n1 & 0xc0) !== 0x80) {\n throw new Error(INVALID_UTF8);\n }\n b = (b & 0x1f) << 6 | (n1 & 0x3f);\n min = 0x80;\n } else if (b < 0xf0) {\n // Need 2 more bytes.\n if (i >= arr.length - 1) {\n throw new Error(INVALID_UTF8);\n }\n const n1 = arr[++i];\n const n2 = arr[++i];\n if ((n1 & 0xc0) !== 0x80 || (n2 & 0xc0) !== 0x80) {\n throw new Error(INVALID_UTF8);\n }\n b = (b & 0x0f) << 12 | (n1 & 0x3f) << 6 | (n2 & 0x3f);\n min = 0x800;\n } else if (b < 0xf8) {\n // Need 3 more bytes.\n if (i >= arr.length - 2) {\n throw new Error(INVALID_UTF8);\n }\n const n1 = arr[++i];\n const n2 = arr[++i];\n const n3 = arr[++i];\n if ((n1 & 0xc0) !== 0x80 || (n2 & 0xc0) !== 0x80 || (n3 & 0xc0) !== 0x80) {\n throw new Error(INVALID_UTF8);\n }\n b = (b & 0x0f) << 18 | (n1 & 0x3f) << 12 | (n2 & 0x3f) << 6 | (n3 & 0x3f);\n min = 0x10000;\n } else {\n throw new Error(INVALID_UTF8);\n }\n\n if (b < min || (b >= 0xd800 && b <= 0xdfff)) {\n throw new Error(INVALID_UTF8);\n }\n\n if (b >= 0x10000) {\n // Surrogate pair.\n if (b > 0x10ffff) {\n throw new Error(INVALID_UTF8);\n }\n b -= 0x10000;\n chars.push(String.fromCharCode(0xd800 | (b >> 10)));\n b = 0xdc00 | (b & 0x3ff);\n }\n }\n\n chars.push(String.fromCharCode(b));\n }\n return chars.join(\"\");\n}\n","// required so we don't have to do require('pusher').default etc.\nmodule.exports = require('./pusher').default;\n","import ScriptReceiver from './script_receiver';\n\n/** Builds receivers for JSONP and Script requests.\n *\n * Each receiver is an object with following fields:\n * - number - unique (for the factory instance), numerical id of the receiver\n * - id - a string ID that can be used in DOM attributes\n * - name - name of the function triggering the receiver\n * - callback - callback function\n *\n * Receivers are triggered only once, on the first callback call.\n *\n * Receivers can be called by their name or by accessing factory object\n * by the number key.\n *\n * @param {String} prefix the prefix used in ids\n * @param {String} name the name of the object\n */\nexport class ScriptReceiverFactory {\n lastId: number;\n prefix: string;\n name: string;\n\n constructor(prefix: string, name: string) {\n this.lastId = 0;\n this.prefix = prefix;\n this.name = name;\n }\n\n create(callback: Function): ScriptReceiver {\n this.lastId++;\n\n var number = this.lastId;\n var id = this.prefix + number;\n var name = this.name + '[' + number + ']';\n\n var called = false;\n var callbackWrapper = function() {\n if (!called) {\n callback.apply(null, arguments);\n called = true;\n }\n };\n\n this[number] = callbackWrapper;\n return { number: number, id: id, name: name, callback: callbackWrapper };\n }\n\n remove(receiver: ScriptReceiver) {\n delete this[receiver.number];\n }\n}\n\nexport var ScriptReceivers = new ScriptReceiverFactory(\n '_pusher_script_',\n 'Pusher.ScriptReceivers'\n);\n","import {\n ChannelAuthorizationOptions,\n UserAuthenticationOptions\n} from './auth/options';\nimport { AuthTransport } from './config';\n\nexport interface DefaultConfig {\n VERSION: string;\n PROTOCOL: number;\n wsPort: number;\n wssPort: number;\n wsPath: string;\n httpHost: string;\n httpPort: number;\n httpsPort: number;\n httpPath: string;\n stats_host: string;\n authEndpoint: string;\n authTransport: AuthTransport;\n activityTimeout: number;\n pongTimeout: number;\n unavailableTimeout: number;\n userAuthentication: UserAuthenticationOptions;\n channelAuthorization: ChannelAuthorizationOptions;\n\n cdn_http?: string;\n cdn_https?: string;\n dependency_suffix?: string;\n}\n\nvar Defaults: DefaultConfig = {\n VERSION: VERSION,\n PROTOCOL: 7,\n\n wsPort: 80,\n wssPort: 443,\n wsPath: '',\n // DEPRECATED: SockJS fallback parameters\n httpHost: 'sockjs.pusher.com',\n httpPort: 80,\n httpsPort: 443,\n httpPath: '/pusher',\n // DEPRECATED: Stats\n stats_host: 'stats.pusher.com',\n // DEPRECATED: Other settings\n authEndpoint: '/pusher/auth',\n authTransport: 'ajax',\n activityTimeout: 120000,\n pongTimeout: 30000,\n unavailableTimeout: 10000,\n userAuthentication: {\n endpoint: '/pusher/user-auth',\n transport: 'ajax'\n },\n channelAuthorization: {\n endpoint: '/pusher/auth',\n transport: 'ajax'\n },\n\n // CDN configuration\n cdn_http: CDN_HTTP,\n cdn_https: CDN_HTTPS,\n dependency_suffix: DEPENDENCY_SUFFIX\n};\n\nexport default Defaults;\n","import { ScriptReceiverFactory } from './script_receiver_factory';\nimport Defaults from 'core/defaults';\nimport DependencyLoader from './dependency_loader';\n\nexport var DependenciesReceivers = new ScriptReceiverFactory(\n '_pusher_dependencies',\n 'Pusher.DependenciesReceivers'\n);\n\nexport var Dependencies = new DependencyLoader({\n cdn_http: Defaults.cdn_http,\n cdn_https: Defaults.cdn_https,\n version: Defaults.VERSION,\n suffix: Defaults.dependency_suffix,\n receivers: DependenciesReceivers\n});\n","import {\n ScriptReceivers,\n ScriptReceiverFactory\n} from './script_receiver_factory';\nimport Runtime from 'runtime';\nimport ScriptRequest from './script_request';\n\n/** Handles loading dependency files.\n *\n * Dependency loaders don't remember whether a resource has been loaded or\n * not. It is caller's responsibility to make sure the resource is not loaded\n * twice. This is because it's impossible to detect resource loading status\n * without knowing its content.\n *\n * Options:\n * - cdn_http - url to HTTP CND\n * - cdn_https - url to HTTPS CDN\n * - version - version of pusher-js\n * - suffix - suffix appended to all names of dependency files\n *\n * @param {Object} options\n */\nexport default class DependencyLoader {\n options: any;\n receivers: ScriptReceiverFactory;\n loading: any;\n\n constructor(options: any) {\n this.options = options;\n this.receivers = options.receivers || ScriptReceivers;\n this.loading = {};\n }\n\n /** Loads the dependency from CDN.\n *\n * @param {String} name\n * @param {Function} callback\n */\n load(name: string, options: any, callback: Function) {\n var self = this;\n\n if (self.loading[name] && self.loading[name].length > 0) {\n self.loading[name].push(callback);\n } else {\n self.loading[name] = [callback];\n\n var request = Runtime.createScriptRequest(self.getPath(name, options));\n var receiver = self.receivers.create(function(error) {\n self.receivers.remove(receiver);\n\n if (self.loading[name]) {\n var callbacks = self.loading[name];\n delete self.loading[name];\n\n var successCallback = function(wasSuccessful) {\n if (!wasSuccessful) {\n request.cleanup();\n }\n };\n for (var i = 0; i < callbacks.length; i++) {\n callbacks[i](error, successCallback);\n }\n }\n });\n request.send(receiver);\n }\n }\n\n /** Returns a root URL for pusher-js CDN.\n *\n * @returns {String}\n */\n getRoot(options: any): string {\n var cdn;\n var protocol = Runtime.getDocument().location.protocol;\n if ((options && options.useTLS) || protocol === 'https:') {\n cdn = this.options.cdn_https;\n } else {\n cdn = this.options.cdn_http;\n }\n // make sure there are no double slashes\n return cdn.replace(/\\/*$/, '') + '/' + this.options.version;\n }\n\n /** Returns a full path to a dependency file.\n *\n * @param {String} name\n * @returns {String}\n */\n getPath(name: string, options: any): string {\n return this.getRoot(options) + '/' + name + this.options.suffix + '.js';\n }\n}\n","/**\n * A place to store help URLs for error messages etc\n */\n\nconst urlStore = {\n baseUrl: 'https://pusher.com',\n urls: {\n authenticationEndpoint: {\n path: '/docs/channels/server_api/authenticating_users'\n },\n authorizationEndpoint: {\n path: '/docs/channels/server_api/authorizing-users/'\n },\n javascriptQuickStart: {\n path: '/docs/javascript_quick_start'\n },\n triggeringClientEvents: {\n path: '/docs/client_api_guide/client_events#trigger-events'\n },\n encryptedChannelSupport: {\n fullUrl:\n 'https://github.com/pusher/pusher-js/tree/cc491015371a4bde5743d1c87a0fbac0feb53195#encrypted-channel-support'\n }\n }\n};\n\n/** Builds a consistent string with links to pusher documentation\n *\n * @param {string} key - relevant key in the url_store.urls object\n * @return {string} suffix string to append to log message\n */\nconst buildLogSuffix = function(key: string): string {\n const urlPrefix = 'See:';\n const urlObj = urlStore.urls[key];\n if (!urlObj) return '';\n\n let url;\n if (urlObj.fullUrl) {\n url = urlObj.fullUrl;\n } else if (urlObj.path) {\n url = urlStore.baseUrl + urlObj.path;\n }\n\n if (!url) return '';\n return `${urlPrefix} ${url}`;\n};\n\nexport default { buildLogSuffix };\n","export enum AuthRequestType {\n UserAuthentication = 'user-authentication',\n ChannelAuthorization = 'channel-authorization'\n}\n\nexport interface ChannelAuthorizationData {\n auth: string;\n channel_data?: string;\n shared_secret?: string;\n}\n\nexport type ChannelAuthorizationCallback = (\n error: Error | null,\n authData: ChannelAuthorizationData | null\n) => void;\n\nexport interface ChannelAuthorizationRequestParams {\n socketId: string;\n channelName: string;\n}\n\nexport interface ChannelAuthorizationHandler {\n (\n params: ChannelAuthorizationRequestParams,\n callback: ChannelAuthorizationCallback\n ): void;\n}\n\nexport interface UserAuthenticationData {\n auth: string;\n user_data: string;\n}\n\nexport type UserAuthenticationCallback = (\n error: Error | null,\n authData: UserAuthenticationData | null\n) => void;\n\nexport interface UserAuthenticationRequestParams {\n socketId: string;\n}\n\nexport interface UserAuthenticationHandler {\n (\n params: UserAuthenticationRequestParams,\n callback: UserAuthenticationCallback\n ): void;\n}\n\nexport type AuthTransportCallback =\n | ChannelAuthorizationCallback\n | UserAuthenticationCallback;\n\nexport interface AuthOptionsT {\n transport: 'ajax' | 'jsonp';\n endpoint: string;\n params?: any;\n headers?: any;\n paramsProvider?: () => any;\n headersProvider?: () => any;\n customHandler?: AuthHandler;\n}\n\nexport declare type UserAuthenticationOptions = AuthOptionsT<\n UserAuthenticationHandler\n>;\nexport declare type ChannelAuthorizationOptions = AuthOptionsT<\n ChannelAuthorizationHandler\n>;\n\nexport interface InternalAuthOptions {\n transport: 'ajax' | 'jsonp';\n endpoint: string;\n params?: any;\n headers?: any;\n paramsProvider?: () => any;\n headersProvider?: () => any;\n}\n","/** Error classes used throughout the library. */\n// https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\nexport class BadEventName extends Error {\n constructor(msg?: string) {\n super(msg);\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class BadChannelName extends Error {\n constructor(msg?: string) {\n super(msg);\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class RequestTimedOut extends Error {\n constructor(msg?: string) {\n super(msg);\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\nexport class TransportPriorityTooLow extends Error {\n constructor(msg?: string) {\n super(msg);\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\nexport class TransportClosed extends Error {\n constructor(msg?: string) {\n super(msg);\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\nexport class UnsupportedFeature extends Error {\n constructor(msg?: string) {\n super(msg);\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\nexport class UnsupportedTransport extends Error {\n constructor(msg?: string) {\n super(msg);\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\nexport class UnsupportedStrategy extends Error {\n constructor(msg?: string) {\n super(msg);\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\nexport class HTTPAuthError extends Error {\n status: number;\n constructor(status: number, msg?: string) {\n super(msg);\n this.status = status;\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","export default function encode(s: any): string {\n return btoa(utob(s));\n}\n\nvar fromCharCode = String.fromCharCode;\n\nvar b64chars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nvar b64tab = {};\n\nfor (var i = 0, l = b64chars.length; i < l; i++) {\n b64tab[b64chars.charAt(i)] = i;\n}\n\nvar cb_utob = function(c) {\n var cc = c.charCodeAt(0);\n return cc < 0x80\n ? c\n : cc < 0x800\n ? fromCharCode(0xc0 | (cc >>> 6)) + fromCharCode(0x80 | (cc & 0x3f))\n : fromCharCode(0xe0 | ((cc >>> 12) & 0x0f)) +\n fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) +\n fromCharCode(0x80 | (cc & 0x3f));\n};\n\nvar utob = function(u) {\n return u.replace(/[^\\x00-\\x7F]/g, cb_utob);\n};\n\nvar cb_encode = function(ccc) {\n var padlen = [0, 2, 1][ccc.length % 3];\n var ord =\n (ccc.charCodeAt(0) << 16) |\n ((ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8) |\n (ccc.length > 2 ? ccc.charCodeAt(2) : 0);\n var chars = [\n b64chars.charAt(ord >>> 18),\n b64chars.charAt((ord >>> 12) & 63),\n padlen >= 2 ? '=' : b64chars.charAt((ord >>> 6) & 63),\n padlen >= 1 ? '=' : b64chars.charAt(ord & 63)\n ];\n return chars.join('');\n};\n\nvar btoa =\n global.btoa ||\n function(b) {\n return b.replace(/[\\s\\S]{1,3}/g, cb_encode);\n };\n","import TimelineSender from 'core/timeline/timeline_sender';\nimport * as Collections from 'core/utils/collections';\nimport Util from 'core/util';\nimport Runtime from 'runtime';\nimport { AuthTransport } from 'core/auth/auth_transports';\nimport AbstractRuntime from 'runtimes/interface';\nimport UrlStore from 'core/utils/url_store';\nimport {\n AuthRequestType,\n AuthTransportCallback,\n InternalAuthOptions\n} from 'core/auth/options';\nimport { HTTPAuthError } from 'core/errors';\n\nconst ajax: AuthTransport = function(\n context: AbstractRuntime,\n query: string,\n authOptions: InternalAuthOptions,\n authRequestType: AuthRequestType,\n callback: AuthTransportCallback\n) {\n const xhr = Runtime.createXHR();\n xhr.open('POST', authOptions.endpoint, true);\n\n // add request headers\n xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');\n for (var headerName in authOptions.headers) {\n xhr.setRequestHeader(headerName, authOptions.headers[headerName]);\n }\n if (authOptions.headersProvider != null) {\n let dynamicHeaders = authOptions.headersProvider();\n for (var headerName in dynamicHeaders) {\n xhr.setRequestHeader(headerName, dynamicHeaders[headerName]);\n }\n }\n\n xhr.onreadystatechange = function() {\n if (xhr.readyState === 4) {\n if (xhr.status === 200) {\n let data;\n let parsed = false;\n\n try {\n data = JSON.parse(xhr.responseText);\n parsed = true;\n } catch (e) {\n callback(\n new HTTPAuthError(\n 200,\n `JSON returned from ${authRequestType.toString()} endpoint was invalid, yet status code was 200. Data was: ${\n xhr.responseText\n }`\n ),\n null\n );\n }\n\n if (parsed) {\n // prevents double execution.\n callback(null, data);\n }\n } else {\n let suffix = '';\n switch (authRequestType) {\n case AuthRequestType.UserAuthentication:\n suffix = UrlStore.buildLogSuffix('authenticationEndpoint');\n break;\n case AuthRequestType.ChannelAuthorization:\n suffix = `Clients must be authorized to join private or presence channels. ${UrlStore.buildLogSuffix(\n 'authorizationEndpoint'\n )}`;\n break;\n }\n callback(\n new HTTPAuthError(\n xhr.status,\n `Unable to retrieve auth string from ${authRequestType.toString()} endpoint - ` +\n `received status: ${xhr.status} from ${authOptions.endpoint}. ${suffix}`\n ),\n null\n );\n }\n }\n };\n\n xhr.send(query);\n return xhr;\n};\n\nexport default ajax;\n","import TimedCallback from './timed_callback';\nimport { Delay, Scheduler, Canceller } from './scheduling';\n\nabstract class Timer {\n protected clear: Canceller;\n protected timer: number | void;\n\n constructor(\n set: Scheduler,\n clear: Canceller,\n delay: Delay,\n callback: TimedCallback\n ) {\n this.clear = clear;\n this.timer = set(() => {\n if (this.timer) {\n this.timer = callback(this.timer);\n }\n }, delay);\n }\n\n /** Returns whether the timer is still running.\n *\n * @return {Boolean}\n */\n isRunning(): boolean {\n return this.timer !== null;\n }\n\n /** Aborts a timer when it's running. */\n ensureAborted() {\n if (this.timer) {\n this.clear(this.timer);\n this.timer = null;\n }\n }\n}\n\nexport default Timer;\n","import Timer from './abstract_timer';\nimport TimedCallback from './timed_callback';\nimport { Delay } from './scheduling';\n\n// We need to bind clear functions this way to avoid exceptions on IE8\nfunction clearTimeout(timer) {\n global.clearTimeout(timer);\n}\nfunction clearInterval(timer) {\n global.clearInterval(timer);\n}\n\n/** Cross-browser compatible one-off timer abstraction.\n *\n * @param {Number} delay\n * @param {Function} callback\n */\nexport class OneOffTimer extends Timer {\n constructor(delay: Delay, callback: TimedCallback) {\n super(setTimeout, clearTimeout, delay, function(timer) {\n callback();\n return null;\n });\n }\n}\n\n/** Cross-browser compatible periodic timer abstraction.\n *\n * @param {Number} delay\n * @param {Function} callback\n */\nexport class PeriodicTimer extends Timer {\n constructor(delay: Delay, callback: TimedCallback) {\n super(setInterval, clearInterval, delay, function(timer) {\n callback();\n return timer;\n });\n }\n}\n","import * as Collections from './utils/collections';\nimport TimedCallback from './utils/timers/timed_callback';\nimport { OneOffTimer, PeriodicTimer } from './utils/timers';\n\nvar Util = {\n now(): number {\n if (Date.now) {\n return Date.now();\n } else {\n return new Date().valueOf();\n }\n },\n\n defer(callback: TimedCallback): OneOffTimer {\n return new OneOffTimer(0, callback);\n },\n\n /** Builds a function that will proxy a method call to its first argument.\n *\n * Allows partial application of arguments, so additional arguments are\n * prepended to the argument list.\n *\n * @param {String} name method name\n * @return {Function} proxy function\n */\n method(name: string, ...args: any[]): Function {\n var boundArguments = Array.prototype.slice.call(arguments, 1);\n return function(object) {\n return object[name].apply(object, boundArguments.concat(arguments));\n };\n }\n};\n\nexport default Util;\n","import base64encode from '../base64';\nimport Util from '../util';\n\n/** Merges multiple objects into the target argument.\n *\n * For properties that are plain Objects, performs a deep-merge. For the\n * rest it just copies the value of the property.\n *\n * To extend prototypes use it as following:\n * Pusher.Util.extend(Target.prototype, Base.prototype)\n *\n * You can also use it to merge objects without altering them:\n * Pusher.Util.extend({}, object1, object2)\n *\n * @param {Object} target\n * @return {Object} the target argument\n */\nexport function extend(target: any, ...sources: any[]): T {\n for (var i = 0; i < sources.length; i++) {\n var extensions = sources[i];\n for (var property in extensions) {\n if (\n extensions[property] &&\n extensions[property].constructor &&\n extensions[property].constructor === Object\n ) {\n target[property] = extend(target[property] || {}, extensions[property]);\n } else {\n target[property] = extensions[property];\n }\n }\n }\n return target;\n}\n\nexport function stringify(): string {\n var m = ['Pusher'];\n for (var i = 0; i < arguments.length; i++) {\n if (typeof arguments[i] === 'string') {\n m.push(arguments[i]);\n } else {\n m.push(safeJSONStringify(arguments[i]));\n }\n }\n return m.join(' : ');\n}\n\nexport function arrayIndexOf(array: any[], item: any): number {\n // MSIE doesn't have array.indexOf\n var nativeIndexOf = Array.prototype.indexOf;\n if (array === null) {\n return -1;\n }\n if (nativeIndexOf && array.indexOf === nativeIndexOf) {\n return array.indexOf(item);\n }\n for (var i = 0, l = array.length; i < l; i++) {\n if (array[i] === item) {\n return i;\n }\n }\n return -1;\n}\n\n/** Applies a function f to all properties of an object.\n *\n * Function f gets 3 arguments passed:\n * - element from the object\n * - key of the element\n * - reference to the object\n *\n * @param {Object} object\n * @param {Function} f\n */\nexport function objectApply(object: any, f: Function) {\n for (var key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n f(object[key], key, object);\n }\n }\n}\n\n/** Return a list of objects own proerty keys\n *\n * @param {Object} object\n * @returns {Array}\n */\nexport function keys(object: any): string[] {\n var keys = [];\n objectApply(object, function(_, key) {\n keys.push(key);\n });\n return keys;\n}\n\n/** Return a list of object's own property values\n *\n * @param {Object} object\n * @returns {Array}\n */\nexport function values(object: any): any[] {\n var values = [];\n objectApply(object, function(value) {\n values.push(value);\n });\n return values;\n}\n\n/** Applies a function f to all elements of an array.\n *\n * Function f gets 3 arguments passed:\n * - element from the array\n * - index of the element\n * - reference to the array\n *\n * @param {Array} array\n * @param {Function} f\n */\nexport function apply(array: any[], f: Function, context?: any) {\n for (var i = 0; i < array.length; i++) {\n f.call(context || global, array[i], i, array);\n }\n}\n\n/** Maps all elements of the array and returns the result.\n *\n * Function f gets 4 arguments passed:\n * - element from the array\n * - index of the element\n * - reference to the source array\n * - reference to the destination array\n *\n * @param {Array} array\n * @param {Function} f\n */\nexport function map(array: any[], f: Function): any[] {\n var result = [];\n for (var i = 0; i < array.length; i++) {\n result.push(f(array[i], i, array, result));\n }\n return result;\n}\n\n/** Maps all elements of the object and returns the result.\n *\n * Function f gets 4 arguments passed:\n * - element from the object\n * - key of the element\n * - reference to the source object\n * - reference to the destination object\n *\n * @param {Object} object\n * @param {Function} f\n */\nexport function mapObject(object: any, f: Function): any {\n var result = {};\n objectApply(object, function(value, key) {\n result[key] = f(value);\n });\n return result;\n}\n\n/** Filters elements of the array using a test function.\n *\n * Function test gets 4 arguments passed:\n * - element from the array\n * - index of the element\n * - reference to the source array\n * - reference to the destination array\n *\n * @param {Array} array\n * @param {Function} f\n */\nexport function filter(array: any[], test: Function): any[] {\n test =\n test ||\n function(value) {\n return !!value;\n };\n\n var result = [];\n for (var i = 0; i < array.length; i++) {\n if (test(array[i], i, array, result)) {\n result.push(array[i]);\n }\n }\n return result;\n}\n\n/** Filters properties of the object using a test function.\n *\n * Function test gets 4 arguments passed:\n * - element from the object\n * - key of the element\n * - reference to the source object\n * - reference to the destination object\n *\n * @param {Object} object\n * @param {Function} f\n */\nexport function filterObject(object: Object, test: Function) {\n var result = {};\n objectApply(object, function(value, key) {\n if ((test && test(value, key, object, result)) || Boolean(value)) {\n result[key] = value;\n }\n });\n return result;\n}\n\n/** Flattens an object into a two-dimensional array.\n *\n * @param {Object} object\n * @return {Array} resulting array of [key, value] pairs\n */\nexport function flatten(object: Object): any[] {\n var result = [];\n objectApply(object, function(value, key) {\n result.push([key, value]);\n });\n return result;\n}\n\n/** Checks whether any element of the array passes the test.\n *\n * Function test gets 3 arguments passed:\n * - element from the array\n * - index of the element\n * - reference to the source array\n *\n * @param {Array} array\n * @param {Function} f\n */\nexport function any(array: any[], test: Function): boolean {\n for (var i = 0; i < array.length; i++) {\n if (test(array[i], i, array)) {\n return true;\n }\n }\n return false;\n}\n\n/** Checks whether all elements of the array pass the test.\n *\n * Function test gets 3 arguments passed:\n * - element from the array\n * - index of the element\n * - reference to the source array\n *\n * @param {Array} array\n * @param {Function} f\n */\nexport function all(array: any[], test: Function): boolean {\n for (var i = 0; i < array.length; i++) {\n if (!test(array[i], i, array)) {\n return false;\n }\n }\n return true;\n}\n\nexport function encodeParamsObject(data): string {\n return mapObject(data, function(value) {\n if (typeof value === 'object') {\n value = safeJSONStringify(value);\n }\n return encodeURIComponent(base64encode(value.toString()));\n });\n}\n\nexport function buildQueryString(data: any): string {\n var params = filterObject(data, function(value) {\n return value !== undefined;\n });\n\n var query = map(\n flatten(encodeParamsObject(params)),\n Util.method('join', '=')\n ).join('&');\n\n return query;\n}\n\n/**\n * See https://github.com/douglascrockford/JSON-js/blob/master/cycle.js\n *\n * Remove circular references from an object. Required for JSON.stringify in\n * React Native, which tends to blow up a lot.\n *\n * @param {any} object\n * @return {any} Decycled object\n */\nexport function decycleObject(object: any): any {\n var objects = [],\n paths = [];\n\n return (function derez(value, path) {\n var i, name, nu;\n\n switch (typeof value) {\n case 'object':\n if (!value) {\n return null;\n }\n for (i = 0; i < objects.length; i += 1) {\n if (objects[i] === value) {\n return { $ref: paths[i] };\n }\n }\n\n objects.push(value);\n paths.push(path);\n\n if (Object.prototype.toString.apply(value) === '[object Array]') {\n nu = [];\n for (i = 0; i < value.length; i += 1) {\n nu[i] = derez(value[i], path + '[' + i + ']');\n }\n } else {\n nu = {};\n for (name in value) {\n if (Object.prototype.hasOwnProperty.call(value, name)) {\n nu[name] = derez(\n value[name],\n path + '[' + JSON.stringify(name) + ']'\n );\n }\n }\n }\n return nu;\n case 'number':\n case 'string':\n case 'boolean':\n return value;\n }\n })(object, '$');\n}\n\n/**\n * Provides a cross-browser and cross-platform way to safely stringify objects\n * into JSON. This is particularly necessary for ReactNative, where circular JSON\n * structures throw an exception.\n *\n * @param {any} source The object to stringify\n * @return {string} The serialized output.\n */\nexport function safeJSONStringify(source: any): string {\n try {\n return JSON.stringify(source);\n } catch (e) {\n return JSON.stringify(decycleObject(source));\n }\n}\n","import { stringify } from './utils/collections';\nimport Pusher from './pusher';\n\nclass Logger {\n debug(...args: any[]) {\n this.log(this.globalLog, args);\n }\n\n warn(...args: any[]) {\n this.log(this.globalLogWarn, args);\n }\n\n error(...args: any[]) {\n this.log(this.globalLogError, args);\n }\n\n private globalLog = (message: string) => {\n if (global.console && global.console.log) {\n global.console.log(message);\n }\n };\n\n private globalLogWarn(message: string) {\n if (global.console && global.console.warn) {\n global.console.warn(message);\n } else {\n this.globalLog(message);\n }\n }\n\n private globalLogError(message: string) {\n if (global.console && global.console.error) {\n global.console.error(message);\n } else {\n this.globalLogWarn(message);\n }\n }\n\n private log(\n defaultLoggingFunction: (message: string) => void,\n ...args: any[]\n ) {\n var message = stringify.apply(this, arguments);\n if (Pusher.log) {\n Pusher.log(message);\n } else if (Pusher.logToConsole) {\n const log = defaultLoggingFunction.bind(this);\n log(message);\n }\n }\n}\n\nexport default new Logger();\n","import Browser from '../browser';\nimport Logger from 'core/logger';\nimport JSONPRequest from '../dom/jsonp_request';\nimport { ScriptReceivers } from '../dom/script_receiver_factory';\nimport { AuthTransport } from 'core/auth/auth_transports';\nimport {\n AuthRequestType,\n AuthTransportCallback,\n InternalAuthOptions\n} from 'core/auth/options';\n\nvar jsonp: AuthTransport = function(\n context: Browser,\n query: string,\n authOptions: InternalAuthOptions,\n authRequestType: AuthRequestType,\n callback: AuthTransportCallback\n) {\n if (\n authOptions.headers !== undefined ||\n authOptions.headersProvider != null\n ) {\n Logger.warn(\n `To send headers with the ${authRequestType.toString()} request, you must use AJAX, rather than JSONP.`\n );\n }\n\n var callbackName = context.nextAuthCallbackID.toString();\n context.nextAuthCallbackID++;\n\n var document = context.getDocument();\n var script = document.createElement('script');\n // Hacked wrapper.\n context.auth_callbacks[callbackName] = function(data) {\n callback(null, data);\n };\n\n var callback_name = \"Pusher.auth_callbacks['\" + callbackName + \"']\";\n script.src =\n authOptions.endpoint +\n '?callback=' +\n encodeURIComponent(callback_name) +\n '&' +\n query;\n\n var head =\n document.getElementsByTagName('head')[0] || document.documentElement;\n head.insertBefore(script, head.firstChild);\n};\n\nexport default jsonp;\n","import ScriptReceiver from './script_receiver';\n\n/** Sends a generic HTTP GET request using a script tag.\n *\n * By constructing URL in a specific way, it can be used for loading\n * JavaScript resources or JSONP requests. It can notify about errors, but\n * only in certain environments. Please take care of monitoring the state of\n * the request yourself.\n *\n * @param {String} src\n */\nexport default class ScriptRequest {\n src: string;\n script: any;\n errorScript: any;\n\n constructor(src: string) {\n this.src = src;\n }\n\n send(receiver: ScriptReceiver) {\n var self = this;\n var errorString = 'Error loading ' + self.src;\n\n self.script = document.createElement('script');\n self.script.id = receiver.id;\n self.script.src = self.src;\n self.script.type = 'text/javascript';\n self.script.charset = 'UTF-8';\n\n if (self.script.addEventListener) {\n self.script.onerror = function() {\n receiver.callback(errorString);\n };\n self.script.onload = function() {\n receiver.callback(null);\n };\n } else {\n self.script.onreadystatechange = function() {\n if (\n self.script.readyState === 'loaded' ||\n self.script.readyState === 'complete'\n ) {\n receiver.callback(null);\n }\n };\n }\n\n // Opera<11.6 hack for missing onerror callback\n if (\n self.script.async === undefined &&\n (document).attachEvent &&\n /opera/i.test(navigator.userAgent)\n ) {\n self.errorScript = document.createElement('script');\n self.errorScript.id = receiver.id + '_error';\n self.errorScript.text = receiver.name + \"('\" + errorString + \"');\";\n self.script.async = self.errorScript.async = false;\n } else {\n self.script.async = true;\n }\n\n var head = document.getElementsByTagName('head')[0];\n head.insertBefore(self.script, head.firstChild);\n if (self.errorScript) {\n head.insertBefore(self.errorScript, self.script.nextSibling);\n }\n }\n\n /** Cleans up the DOM remains of the script request. */\n cleanup() {\n if (this.script) {\n this.script.onload = this.script.onerror = null;\n this.script.onreadystatechange = null;\n }\n if (this.script && this.script.parentNode) {\n this.script.parentNode.removeChild(this.script);\n }\n if (this.errorScript && this.errorScript.parentNode) {\n this.errorScript.parentNode.removeChild(this.errorScript);\n }\n this.script = null;\n this.errorScript = null;\n }\n}\n","import ScriptReceiver from './script_receiver';\nimport ScriptRequest from './script_request';\nimport * as Collections from 'core/utils/collections';\nimport Util from 'core/util';\nimport Runtime from '../runtime';\n\n/** Sends data via JSONP.\n *\n * Data is a key-value map. Its values are JSON-encoded and then passed\n * through base64. Finally, keys and encoded values are appended to the query\n * string.\n *\n * The class itself does not guarantee raising errors on failures, as it's not\n * possible to support such feature on all browsers. Instead, JSONP endpoint\n * should call back in a way that's easy to distinguish from browser calls,\n * for example by passing a second argument to the receiver.\n *\n * @param {String} url\n * @param {Object} data key-value map of data to be submitted\n */\nexport default class JSONPRequest {\n url: string;\n data: any;\n request: ScriptRequest;\n\n constructor(url: string, data: any) {\n this.url = url;\n this.data = data;\n }\n\n /** Sends the actual JSONP request.\n *\n * @param {ScriptReceiver} receiver\n */\n send(receiver: ScriptReceiver) {\n if (this.request) {\n return;\n }\n\n var query = Collections.buildQueryString(this.data);\n var url = this.url + '/' + receiver.number + '?' + query;\n this.request = Runtime.createScriptRequest(url);\n this.request.send(receiver);\n }\n\n /** Cleans up the DOM remains of the JSONP request. */\n cleanup() {\n if (this.request) {\n this.request.cleanup();\n }\n }\n}\n","import TimelineSender from 'core/timeline/timeline_sender';\nimport TimelineTransport from 'core/timeline/timeline_transport';\nimport Browser from 'runtime';\nimport { AuthTransport } from 'core/auth/auth_transports';\nimport { ScriptReceivers } from '../dom/script_receiver_factory';\n\nvar getAgent = function(sender: TimelineSender, useTLS: boolean) {\n return function(data: any, callback: Function) {\n var scheme = 'http' + (useTLS ? 's' : '') + '://';\n var url =\n scheme + (sender.host || sender.options.host) + sender.options.path;\n var request = Browser.createJSONPRequest(url, data);\n\n var receiver = Browser.ScriptReceivers.create(function(error, result) {\n ScriptReceivers.remove(receiver);\n request.cleanup();\n\n if (result && result.host) {\n sender.host = result.host;\n }\n if (callback) {\n callback(error, result);\n }\n });\n request.send(receiver);\n };\n};\n\nvar jsonp = {\n name: 'jsonp',\n getAgent\n};\n\nexport default jsonp;\n","import Defaults from '../defaults';\nimport { default as URLScheme, URLSchemeParams } from './url_scheme';\n\nfunction getGenericURL(\n baseScheme: string,\n params: URLSchemeParams,\n path: string\n): string {\n var scheme = baseScheme + (params.useTLS ? 's' : '');\n var host = params.useTLS ? params.hostTLS : params.hostNonTLS;\n return scheme + '://' + host + path;\n}\n\nfunction getGenericPath(key: string, queryString?: string): string {\n var path = '/app/' + key;\n var query =\n '?protocol=' +\n Defaults.PROTOCOL +\n '&client=js' +\n '&version=' +\n Defaults.VERSION +\n (queryString ? '&' + queryString : '');\n return path + query;\n}\n\nexport var ws: URLScheme = {\n getInitial: function(key: string, params: URLSchemeParams): string {\n var path = (params.httpPath || '') + getGenericPath(key, 'flash=false');\n return getGenericURL('ws', params, path);\n }\n};\n\nexport var http: URLScheme = {\n getInitial: function(key: string, params: URLSchemeParams): string {\n var path = (params.httpPath || '/pusher') + getGenericPath(key);\n return getGenericURL('http', params, path);\n }\n};\n\nexport var sockjs: URLScheme = {\n getInitial: function(key: string, params: URLSchemeParams): string {\n return getGenericURL('http', params, params.httpPath || '/pusher');\n },\n getPath: function(key: string, params: URLSchemeParams): string {\n return getGenericPath(key);\n }\n};\n","import Callback from './callback';\nimport * as Collections from '../utils/collections';\nimport CallbackTable from './callback_table';\n\nexport default class CallbackRegistry {\n _callbacks: CallbackTable;\n\n constructor() {\n this._callbacks = {};\n }\n\n get(name: string): Callback[] {\n return this._callbacks[prefix(name)];\n }\n\n add(name: string, callback: Function, context: any) {\n var prefixedEventName = prefix(name);\n this._callbacks[prefixedEventName] =\n this._callbacks[prefixedEventName] || [];\n this._callbacks[prefixedEventName].push({\n fn: callback,\n context: context\n });\n }\n\n remove(name?: string, callback?: Function, context?: any) {\n if (!name && !callback && !context) {\n this._callbacks = {};\n return;\n }\n\n var names = name ? [prefix(name)] : Collections.keys(this._callbacks);\n\n if (callback || context) {\n this.removeCallback(names, callback, context);\n } else {\n this.removeAllCallbacks(names);\n }\n }\n\n private removeCallback(names: string[], callback: Function, context: any) {\n Collections.apply(\n names,\n function(name) {\n this._callbacks[name] = Collections.filter(\n this._callbacks[name] || [],\n function(binding) {\n return (\n (callback && callback !== binding.fn) ||\n (context && context !== binding.context)\n );\n }\n );\n if (this._callbacks[name].length === 0) {\n delete this._callbacks[name];\n }\n },\n this\n );\n }\n\n private removeAllCallbacks(names: string[]) {\n Collections.apply(\n names,\n function(name) {\n delete this._callbacks[name];\n },\n this\n );\n }\n}\n\nfunction prefix(name: string): string {\n return '_' + name;\n}\n","import * as Collections from '../utils/collections';\nimport Callback from './callback';\nimport Metadata from '../channels/metadata';\nimport CallbackRegistry from './callback_registry';\n\n/** Manages callback bindings and event emitting.\n *\n * @param Function failThrough called when no listeners are bound to an event\n */\nexport default class Dispatcher {\n callbacks: CallbackRegistry;\n global_callbacks: Function[];\n failThrough: Function;\n\n constructor(failThrough?: Function) {\n this.callbacks = new CallbackRegistry();\n this.global_callbacks = [];\n this.failThrough = failThrough;\n }\n\n bind(eventName: string, callback: Function, context?: any) {\n this.callbacks.add(eventName, callback, context);\n return this;\n }\n\n bind_global(callback: Function) {\n this.global_callbacks.push(callback);\n return this;\n }\n\n unbind(eventName?: string, callback?: Function, context?: any) {\n this.callbacks.remove(eventName, callback, context);\n return this;\n }\n\n unbind_global(callback?: Function) {\n if (!callback) {\n this.global_callbacks = [];\n return this;\n }\n\n this.global_callbacks = Collections.filter(\n this.global_callbacks || [],\n c => c !== callback\n );\n\n return this;\n }\n\n unbind_all() {\n this.unbind();\n this.unbind_global();\n return this;\n }\n\n emit(eventName: string, data?: any, metadata?: Metadata): Dispatcher {\n for (var i = 0; i < this.global_callbacks.length; i++) {\n this.global_callbacks[i](eventName, data);\n }\n\n var callbacks = this.callbacks.get(eventName);\n var args = [];\n\n if (metadata) {\n // if there's a metadata argument, we need to call the callback with both\n // data and metadata regardless of whether data is undefined\n args.push(data, metadata);\n } else if (data) {\n // metadata is undefined, so we only need to call the callback with data\n // if data exists\n args.push(data);\n }\n\n if (callbacks && callbacks.length > 0) {\n for (var i = 0; i < callbacks.length; i++) {\n callbacks[i].fn.apply(callbacks[i].context || global, args);\n }\n } else if (this.failThrough) {\n this.failThrough(eventName, data);\n }\n\n return this;\n }\n}\n","import Util from '../util';\nimport * as Collections from '../utils/collections';\nimport { default as EventsDispatcher } from '../events/dispatcher';\nimport Logger from '../logger';\nimport TransportHooks from './transport_hooks';\nimport Socket from '../socket';\nimport Runtime from 'runtime';\nimport Timeline from '../timeline/timeline';\nimport TransportConnectionOptions from './transport_connection_options';\n\n/** Provides universal API for transport connections.\n *\n * Transport connection is a low-level object that wraps a connection method\n * and exposes a simple evented interface for the connection state and\n * messaging. It does not implement Pusher-specific WebSocket protocol.\n *\n * Additionally, it fetches resources needed for transport to work and exposes\n * an interface for querying transport features.\n *\n * States:\n * - new - initial state after constructing the object\n * - initializing - during initialization phase, usually fetching resources\n * - intialized - ready to establish a connection\n * - connection - when connection is being established\n * - open - when connection ready to be used\n * - closed - after connection was closed be either side\n *\n * Emits:\n * - error - after the connection raised an error\n *\n * Options:\n * - useTLS - whether connection should be over TLS\n * - hostTLS - host to connect to when connection is over TLS\n * - hostNonTLS - host to connect to when connection is over TLS\n *\n * @param {String} key application key\n * @param {Object} options\n */\nexport default class TransportConnection extends EventsDispatcher {\n hooks: TransportHooks;\n name: string;\n priority: number;\n key: string;\n options: TransportConnectionOptions;\n state: string;\n timeline: Timeline;\n activityTimeout: number;\n id: number;\n socket: Socket;\n beforeOpen: Function;\n initialize: Function;\n\n constructor(\n hooks: TransportHooks,\n name: string,\n priority: number,\n key: string,\n options: TransportConnectionOptions\n ) {\n super();\n this.initialize = Runtime.transportConnectionInitializer;\n this.hooks = hooks;\n this.name = name;\n this.priority = priority;\n this.key = key;\n this.options = options;\n\n this.state = 'new';\n this.timeline = options.timeline;\n this.activityTimeout = options.activityTimeout;\n this.id = this.timeline.generateUniqueID();\n }\n\n /** Checks whether the transport handles activity checks by itself.\n *\n * @return {Boolean}\n */\n handlesActivityChecks(): boolean {\n return Boolean(this.hooks.handlesActivityChecks);\n }\n\n /** Checks whether the transport supports the ping/pong API.\n *\n * @return {Boolean}\n */\n supportsPing(): boolean {\n return Boolean(this.hooks.supportsPing);\n }\n\n /** Tries to establish a connection.\n *\n * @returns {Boolean} false if transport is in invalid state\n */\n connect(): boolean {\n if (this.socket || this.state !== 'initialized') {\n return false;\n }\n\n var url = this.hooks.urls.getInitial(this.key, this.options);\n try {\n this.socket = this.hooks.getSocket(url, this.options);\n } catch (e) {\n Util.defer(() => {\n this.onError(e);\n this.changeState('closed');\n });\n return false;\n }\n\n this.bindListeners();\n\n Logger.debug('Connecting', { transport: this.name, url });\n this.changeState('connecting');\n return true;\n }\n\n /** Closes the connection.\n *\n * @return {Boolean} true if there was a connection to close\n */\n close(): boolean {\n if (this.socket) {\n this.socket.close();\n return true;\n } else {\n return false;\n }\n }\n\n /** Sends data over the open connection.\n *\n * @param {String} data\n * @return {Boolean} true only when in the \"open\" state\n */\n send(data: any): boolean {\n if (this.state === 'open') {\n // Workaround for MobileSafari bug (see https://gist.github.com/2052006)\n Util.defer(() => {\n if (this.socket) {\n this.socket.send(data);\n }\n });\n return true;\n } else {\n return false;\n }\n }\n\n /** Sends a ping if the connection is open and transport supports it. */\n ping() {\n if (this.state === 'open' && this.supportsPing()) {\n this.socket.ping();\n }\n }\n\n private onOpen() {\n if (this.hooks.beforeOpen) {\n this.hooks.beforeOpen(\n this.socket,\n this.hooks.urls.getPath(this.key, this.options)\n );\n }\n this.changeState('open');\n this.socket.onopen = undefined;\n }\n\n private onError(error) {\n this.emit('error', { type: 'WebSocketError', error: error });\n this.timeline.error(this.buildTimelineMessage({ error: error.toString() }));\n }\n\n private onClose(closeEvent?: any) {\n if (closeEvent) {\n this.changeState('closed', {\n code: closeEvent.code,\n reason: closeEvent.reason,\n wasClean: closeEvent.wasClean\n });\n } else {\n this.changeState('closed');\n }\n this.unbindListeners();\n this.socket = undefined;\n }\n\n private onMessage(message) {\n this.emit('message', message);\n }\n\n private onActivity() {\n this.emit('activity');\n }\n\n private bindListeners() {\n this.socket.onopen = () => {\n this.onOpen();\n };\n this.socket.onerror = error => {\n this.onError(error);\n };\n this.socket.onclose = closeEvent => {\n this.onClose(closeEvent);\n };\n this.socket.onmessage = message => {\n this.onMessage(message);\n };\n\n if (this.supportsPing()) {\n this.socket.onactivity = () => {\n this.onActivity();\n };\n }\n }\n\n private unbindListeners() {\n if (this.socket) {\n this.socket.onopen = undefined;\n this.socket.onerror = undefined;\n this.socket.onclose = undefined;\n this.socket.onmessage = undefined;\n if (this.supportsPing()) {\n this.socket.onactivity = undefined;\n }\n }\n }\n\n private changeState(state: string, params?: any) {\n this.state = state;\n this.timeline.info(\n this.buildTimelineMessage({\n state: state,\n params: params\n })\n );\n this.emit(state, params);\n }\n\n buildTimelineMessage(message): any {\n return Collections.extend({ cid: this.id }, message);\n }\n}\n","import Factory from '../utils/factory';\nimport TransportHooks from './transport_hooks';\nimport TransportConnection from './transport_connection';\nimport TransportConnectionOptions from './transport_connection_options';\n\n/** Provides interface for transport connection instantiation.\n *\n * Takes transport-specific hooks as the only argument, which allow checking\n * for transport support and creating its connections.\n *\n * Supported hooks: * - file - the name of the file to be fetched during initialization\n * - urls - URL scheme to be used by transport\n * - handlesActivityCheck - true when the transport handles activity checks\n * - supportsPing - true when the transport has a ping/activity API\n * - isSupported - tells whether the transport is supported in the environment\n * - getSocket - creates a WebSocket-compatible transport socket\n *\n * See transports.js for specific implementations.\n *\n * @param {Object} hooks object containing all needed transport hooks\n */\nexport default class Transport {\n hooks: TransportHooks;\n\n constructor(hooks: TransportHooks) {\n this.hooks = hooks;\n }\n\n /** Returns whether the transport is supported in the environment.\n *\n * @param {Object} envronment te environment details (encryption, settings)\n * @returns {Boolean} true when the transport is supported\n */\n isSupported(environment: any): boolean {\n return this.hooks.isSupported(environment);\n }\n\n /** Creates a transport connection.\n *\n * @param {String} name\n * @param {Number} priority\n * @param {String} key the application key\n * @param {Object} options\n * @returns {TransportConnection}\n */\n createConnection(\n name: string,\n priority: number,\n key: string,\n options: any\n ): TransportConnection {\n return new TransportConnection(this.hooks, name, priority, key, options);\n }\n}\n","import * as URLSchemes from 'core/transports/url_schemes';\nimport URLScheme from 'core/transports/url_scheme';\nimport Transport from 'core/transports/transport';\nimport Util from 'core/util';\nimport * as Collections from 'core/utils/collections';\nimport TransportHooks from 'core/transports/transport_hooks';\nimport TransportsTable from 'core/transports/transports_table';\nimport Runtime from 'runtime';\n\n/** WebSocket transport.\n *\n * Uses native WebSocket implementation, including MozWebSocket supported by\n * earlier Firefox versions.\n */\nvar WSTransport = new Transport({\n urls: URLSchemes.ws,\n handlesActivityChecks: false,\n supportsPing: false,\n\n isInitialized: function() {\n return Boolean(Runtime.getWebSocketAPI());\n },\n isSupported: function(): boolean {\n return Boolean(Runtime.getWebSocketAPI());\n },\n getSocket: function(url) {\n return Runtime.createWebSocket(url);\n }\n});\n\nvar httpConfiguration = {\n urls: URLSchemes.http,\n handlesActivityChecks: false,\n supportsPing: true,\n isInitialized: function() {\n return true;\n }\n};\n\nexport var streamingConfiguration = Collections.extend(\n {\n getSocket: function(url) {\n return Runtime.HTTPFactory.createStreamingSocket(url);\n }\n },\n httpConfiguration\n);\nexport var pollingConfiguration = Collections.extend(\n {\n getSocket: function(url) {\n return Runtime.HTTPFactory.createPollingSocket(url);\n }\n },\n httpConfiguration\n);\n\nvar xhrConfiguration = {\n isSupported: function(): boolean {\n return Runtime.isXHRSupported();\n }\n};\n\n/** HTTP streaming transport using CORS-enabled XMLHttpRequest. */\nvar XHRStreamingTransport = new Transport(\n (\n Collections.extend({}, streamingConfiguration, xhrConfiguration)\n )\n);\n\n/** HTTP long-polling transport using CORS-enabled XMLHttpRequest. */\nvar XHRPollingTransport = new Transport(\n Collections.extend({}, pollingConfiguration, xhrConfiguration)\n);\n\nvar Transports: TransportsTable = {\n ws: WSTransport,\n xhr_streaming: XHRStreamingTransport,\n xhr_polling: XHRPollingTransport\n};\n\nexport default Transports;\n","import {\n default as Transports,\n streamingConfiguration,\n pollingConfiguration\n} from 'isomorphic/transports/transports';\nimport Transport from 'core/transports/transport';\nimport TransportHooks from 'core/transports/transport_hooks';\nimport * as URLSchemes from 'core/transports/url_schemes';\nimport Runtime from 'runtime';\nimport { Dependencies } from '../dom/dependencies';\nimport * as Collections from 'core/utils/collections';\n\nvar SockJSTransport = new Transport({\n file: 'sockjs',\n urls: URLSchemes.sockjs,\n handlesActivityChecks: true,\n supportsPing: false,\n\n isSupported: function() {\n return true;\n },\n isInitialized: function() {\n return window.SockJS !== undefined;\n },\n getSocket: function(url, options) {\n return new window.SockJS(url, null, {\n js_path: Dependencies.getPath('sockjs', {\n useTLS: options.useTLS\n }),\n ignore_null_origin: options.ignoreNullOrigin\n });\n },\n beforeOpen: function(socket, path) {\n socket.send(\n JSON.stringify({\n path: path\n })\n );\n }\n});\n\nvar xdrConfiguration = {\n isSupported: function(environment): boolean {\n var yes = Runtime.isXDRSupported(environment.useTLS);\n return yes;\n }\n};\n\n/** HTTP streaming transport using XDomainRequest (IE 8,9). */\nvar XDRStreamingTransport = new Transport(\n (\n Collections.extend({}, streamingConfiguration, xdrConfiguration)\n )\n);\n\n/** HTTP long-polling transport using XDomainRequest (IE 8,9). */\nvar XDRPollingTransport = new Transport(\n Collections.extend({}, pollingConfiguration, xdrConfiguration)\n);\n\nTransports.xdr_streaming = XDRStreamingTransport;\nTransports.xdr_polling = XDRPollingTransport;\nTransports.sockjs = SockJSTransport;\n\nexport default Transports;\n","import Reachability from 'core/reachability';\nimport { default as EventsDispatcher } from 'core/events/dispatcher';\n\n/** Really basic interface providing network availability info.\n *\n * Emits:\n * - online - when browser goes online\n * - offline - when browser goes offline\n */\nexport class NetInfo extends EventsDispatcher implements Reachability {\n constructor() {\n super();\n var self = this;\n // This is okay, as IE doesn't support this stuff anyway.\n if (window.addEventListener !== undefined) {\n window.addEventListener(\n 'online',\n function() {\n self.emit('online');\n },\n false\n );\n window.addEventListener(\n 'offline',\n function() {\n self.emit('offline');\n },\n false\n );\n }\n }\n\n /** Returns whether browser is online or not\n *\n * Offline means definitely offline (no connection to router).\n * Inverse does NOT mean definitely online (only currently supported in Safari\n * and even there only means the device has a connection to the router).\n *\n * @return {Boolean}\n */\n isOnline(): boolean {\n if (window.navigator.onLine === undefined) {\n return true;\n } else {\n return window.navigator.onLine;\n }\n }\n}\n\nexport var Network = new NetInfo();\n","import Util from '../util';\nimport * as Collections from '../utils/collections';\nimport TransportManager from './transport_manager';\nimport TransportConnection from './transport_connection';\nimport Transport from './transport';\nimport PingDelayOptions from './ping_delay_options';\n\n/** Creates transport connections monitored by a transport manager.\n *\n * When a transport is closed, it might mean the environment does not support\n * it. It's possible that messages get stuck in an intermediate buffer or\n * proxies terminate inactive connections. To combat these problems,\n * assistants monitor the connection lifetime, report unclean exits and\n * adjust ping timeouts to keep the connection active. The decision to disable\n * a transport is the manager's responsibility.\n *\n * @param {TransportManager} manager\n * @param {TransportConnection} transport\n * @param {Object} options\n */\nexport default class AssistantToTheTransportManager {\n manager: TransportManager;\n transport: Transport;\n minPingDelay: number;\n maxPingDelay: number;\n pingDelay: number;\n\n constructor(\n manager: TransportManager,\n transport: Transport,\n options: PingDelayOptions\n ) {\n this.manager = manager;\n this.transport = transport;\n this.minPingDelay = options.minPingDelay;\n this.maxPingDelay = options.maxPingDelay;\n this.pingDelay = undefined;\n }\n\n /** Creates a transport connection.\n *\n * This function has the same API as Transport#createConnection.\n *\n * @param {String} name\n * @param {Number} priority\n * @param {String} key the application key\n * @param {Object} options\n * @returns {TransportConnection}\n */\n createConnection(\n name: string,\n priority: number,\n key: string,\n options: Object\n ): TransportConnection {\n options = Collections.extend({}, options, {\n activityTimeout: this.pingDelay\n });\n var connection = this.transport.createConnection(\n name,\n priority,\n key,\n options\n );\n\n var openTimestamp = null;\n\n var onOpen = function() {\n connection.unbind('open', onOpen);\n connection.bind('closed', onClosed);\n openTimestamp = Util.now();\n };\n var onClosed = closeEvent => {\n connection.unbind('closed', onClosed);\n\n if (closeEvent.code === 1002 || closeEvent.code === 1003) {\n // we don't want to use transports not obeying the protocol\n this.manager.reportDeath();\n } else if (!closeEvent.wasClean && openTimestamp) {\n // report deaths only for short-living transport\n var lifespan = Util.now() - openTimestamp;\n if (lifespan < 2 * this.maxPingDelay) {\n this.manager.reportDeath();\n this.pingDelay = Math.max(lifespan / 2, this.minPingDelay);\n }\n }\n };\n\n connection.bind('open', onOpen);\n return connection;\n }\n\n /** Returns whether the transport is supported in the environment.\n *\n * This function has the same API as Transport#isSupported. Might return false\n * when the manager decides to kill the transport.\n *\n * @param {Object} environment the environment details (encryption, settings)\n * @returns {Boolean} true when the transport is supported\n */\n isSupported(environment: string): boolean {\n return this.manager.isAlive() && this.transport.isSupported(environment);\n }\n}\n","import Action from './action';\nimport { PusherEvent } from './message-types';\n/**\n * Provides functions for handling Pusher protocol-specific messages.\n */\n\nconst Protocol = {\n /**\n * Decodes a message in a Pusher format.\n *\n * The MessageEvent we receive from the transport should contain a pusher event\n * (https://pusher.com/docs/pusher_protocol#events) serialized as JSON in the\n * data field\n *\n * The pusher event may contain a data field too, and it may also be\n * serialised as JSON\n *\n * Throws errors when messages are not parse'able.\n *\n * @param {MessageEvent} messageEvent\n * @return {PusherEvent}\n */\n decodeMessage: function(messageEvent: MessageEvent): PusherEvent {\n try {\n var messageData = JSON.parse(messageEvent.data);\n var pusherEventData = messageData.data;\n if (typeof pusherEventData === 'string') {\n try {\n pusherEventData = JSON.parse(messageData.data);\n } catch (e) {}\n }\n var pusherEvent: PusherEvent = {\n event: messageData.event,\n channel: messageData.channel,\n data: pusherEventData\n };\n if (messageData.user_id) {\n pusherEvent.user_id = messageData.user_id;\n }\n return pusherEvent;\n } catch (e) {\n throw { type: 'MessageParseError', error: e, data: messageEvent.data };\n }\n },\n\n /**\n * Encodes a message to be sent.\n *\n * @param {PusherEvent} event\n * @return {String}\n */\n encodeMessage: function(event: PusherEvent): string {\n return JSON.stringify(event);\n },\n\n /**\n * Processes a handshake message and returns appropriate actions.\n *\n * Returns an object with an 'action' and other action-specific properties.\n *\n * There are three outcomes when calling this function. First is a successful\n * connection attempt, when pusher:connection_established is received, which\n * results in a 'connected' action with an 'id' property. When passed a\n * pusher:error event, it returns a result with action appropriate to the\n * close code and an error. Otherwise, it raises an exception.\n *\n * @param {String} message\n * @result Object\n */\n processHandshake: function(messageEvent: MessageEvent): Action {\n var message = Protocol.decodeMessage(messageEvent);\n\n if (message.event === 'pusher:connection_established') {\n if (!message.data.activity_timeout) {\n throw 'No activity timeout specified in handshake';\n }\n return {\n action: 'connected',\n id: message.data.socket_id,\n activityTimeout: message.data.activity_timeout * 1000\n };\n } else if (message.event === 'pusher:error') {\n // From protocol 6 close codes are sent only once, so this only\n // happens when connection does not support close codes\n return {\n action: this.getCloseAction(message.data),\n error: this.getCloseError(message.data)\n };\n } else {\n throw 'Invalid handshake';\n }\n },\n\n /**\n * Dispatches the close event and returns an appropriate action name.\n *\n * See:\n * 1. https://developer.mozilla.org/en-US/docs/WebSockets/WebSockets_reference/CloseEvent\n * 2. http://pusher.com/docs/pusher_protocol\n *\n * @param {CloseEvent} closeEvent\n * @return {String} close action name\n */\n getCloseAction: function(closeEvent): string {\n if (closeEvent.code < 4000) {\n // ignore 1000 CLOSE_NORMAL, 1001 CLOSE_GOING_AWAY,\n // 1005 CLOSE_NO_STATUS, 1006 CLOSE_ABNORMAL\n // ignore 1007...3999\n // handle 1002 CLOSE_PROTOCOL_ERROR, 1003 CLOSE_UNSUPPORTED,\n // 1004 CLOSE_TOO_LARGE\n if (closeEvent.code >= 1002 && closeEvent.code <= 1004) {\n return 'backoff';\n } else {\n return null;\n }\n } else if (closeEvent.code === 4000) {\n return 'tls_only';\n } else if (closeEvent.code < 4100) {\n return 'refused';\n } else if (closeEvent.code < 4200) {\n return 'backoff';\n } else if (closeEvent.code < 4300) {\n return 'retry';\n } else {\n // unknown error\n return 'refused';\n }\n },\n\n /**\n * Returns an error or null basing on the close event.\n *\n * Null is returned when connection was closed cleanly. Otherwise, an object\n * with error details is returned.\n *\n * @param {CloseEvent} closeEvent\n * @return {Object} error object\n */\n getCloseError: function(closeEvent): any {\n if (closeEvent.code !== 1000 && closeEvent.code !== 1001) {\n return {\n type: 'PusherError',\n data: {\n code: closeEvent.code,\n message: closeEvent.reason || closeEvent.message\n }\n };\n } else {\n return null;\n }\n }\n};\n\nexport default Protocol;\n","import * as Collections from '../utils/collections';\nimport { default as EventsDispatcher } from '../events/dispatcher';\nimport Protocol from './protocol/protocol';\nimport { PusherEvent } from './protocol/message-types';\nimport Logger from '../logger';\nimport TransportConnection from '../transports/transport_connection';\nimport Socket from '../socket';\n/**\n * Provides Pusher protocol interface for transports.\n *\n * Emits following events:\n * - message - on received messages\n * - ping - on ping requests\n * - pong - on pong responses\n * - error - when the transport emits an error\n * - closed - after closing the transport\n *\n * It also emits more events when connection closes with a code.\n * See Protocol.getCloseAction to get more details.\n *\n * @param {Number} id\n * @param {AbstractTransport} transport\n */\nexport default class Connection extends EventsDispatcher implements Socket {\n id: string;\n transport: TransportConnection;\n activityTimeout: number;\n\n constructor(id: string, transport: TransportConnection) {\n super();\n this.id = id;\n this.transport = transport;\n this.activityTimeout = transport.activityTimeout;\n this.bindListeners();\n }\n\n /** Returns whether used transport handles activity checks by itself\n *\n * @returns {Boolean} true if activity checks are handled by the transport\n */\n handlesActivityChecks() {\n return this.transport.handlesActivityChecks();\n }\n\n /** Sends raw data.\n *\n * @param {String} data\n */\n send(data: any): boolean {\n return this.transport.send(data);\n }\n\n /** Sends an event.\n *\n * @param {String} name\n * @param {String} data\n * @param {String} [channel]\n * @returns {Boolean} whether message was sent or not\n */\n send_event(name: string, data: any, channel?: string): boolean {\n var event: PusherEvent = { event: name, data: data };\n if (channel) {\n event.channel = channel;\n }\n Logger.debug('Event sent', event);\n return this.send(Protocol.encodeMessage(event));\n }\n\n /** Sends a ping message to the server.\n *\n * Basing on the underlying transport, it might send either transport's\n * protocol-specific ping or pusher:ping event.\n */\n ping() {\n if (this.transport.supportsPing()) {\n this.transport.ping();\n } else {\n this.send_event('pusher:ping', {});\n }\n }\n\n /** Closes the connection. */\n close() {\n this.transport.close();\n }\n\n private bindListeners() {\n var listeners = {\n message: (messageEvent: MessageEvent) => {\n var pusherEvent;\n try {\n pusherEvent = Protocol.decodeMessage(messageEvent);\n } catch (e) {\n this.emit('error', {\n type: 'MessageParseError',\n error: e,\n data: messageEvent.data\n });\n }\n\n if (pusherEvent !== undefined) {\n Logger.debug('Event recd', pusherEvent);\n\n switch (pusherEvent.event) {\n case 'pusher:error':\n this.emit('error', {\n type: 'PusherError',\n data: pusherEvent.data\n });\n break;\n case 'pusher:ping':\n this.emit('ping');\n break;\n case 'pusher:pong':\n this.emit('pong');\n break;\n }\n this.emit('message', pusherEvent);\n }\n },\n activity: () => {\n this.emit('activity');\n },\n error: error => {\n this.emit('error', error);\n },\n closed: closeEvent => {\n unbindListeners();\n\n if (closeEvent && closeEvent.code) {\n this.handleCloseEvent(closeEvent);\n }\n\n this.transport = null;\n this.emit('closed');\n }\n };\n\n var unbindListeners = () => {\n Collections.objectApply(listeners, (listener, event) => {\n this.transport.unbind(event, listener);\n });\n };\n\n Collections.objectApply(listeners, (listener, event) => {\n this.transport.bind(event, listener);\n });\n }\n\n private handleCloseEvent(closeEvent: any) {\n var action = Protocol.getCloseAction(closeEvent);\n var error = Protocol.getCloseError(closeEvent);\n if (error) {\n this.emit('error', error);\n }\n if (action) {\n this.emit(action, { action: action, error: error });\n }\n }\n}\n","import Util from '../../util';\nimport * as Collections from '../../utils/collections';\nimport Protocol from '../protocol/protocol';\nimport Connection from '../connection';\nimport TransportConnection from '../../transports/transport_connection';\nimport HandshakePayload from './handshake_payload';\n\n/**\n * Handles Pusher protocol handshakes for transports.\n *\n * Calls back with a result object after handshake is completed. Results\n * always have two fields:\n * - action - string describing action to be taken after the handshake\n * - transport - the transport object passed to the constructor\n *\n * Different actions can set different additional properties on the result.\n * In the case of 'connected' action, there will be a 'connection' property\n * containing a Connection object for the transport. Other actions should\n * carry an 'error' property.\n *\n * @param {AbstractTransport} transport\n * @param {Function} callback\n */\nexport default class Handshake {\n transport: TransportConnection;\n callback: (HandshakePayload) => void;\n onMessage: Function;\n onClosed: Function;\n\n constructor(\n transport: TransportConnection,\n callback: (HandshakePayload) => void\n ) {\n this.transport = transport;\n this.callback = callback;\n this.bindListeners();\n }\n\n close() {\n this.unbindListeners();\n this.transport.close();\n }\n\n private bindListeners() {\n this.onMessage = m => {\n this.unbindListeners();\n\n var result;\n try {\n result = Protocol.processHandshake(m);\n } catch (e) {\n this.finish('error', { error: e });\n this.transport.close();\n return;\n }\n\n if (result.action === 'connected') {\n this.finish('connected', {\n connection: new Connection(result.id, this.transport),\n activityTimeout: result.activityTimeout\n });\n } else {\n this.finish(result.action, { error: result.error });\n this.transport.close();\n }\n };\n\n this.onClosed = closeEvent => {\n this.unbindListeners();\n\n var action = Protocol.getCloseAction(closeEvent) || 'backoff';\n var error = Protocol.getCloseError(closeEvent);\n this.finish(action, { error: error });\n };\n\n this.transport.bind('message', this.onMessage);\n this.transport.bind('closed', this.onClosed);\n }\n\n private unbindListeners() {\n this.transport.unbind('message', this.onMessage);\n this.transport.unbind('closed', this.onClosed);\n }\n\n private finish(action: string, params: any) {\n this.callback(\n Collections.extend({ transport: this.transport, action: action }, params)\n );\n }\n}\n","import * as Collections from '../utils/collections';\nimport Util from '../util';\nimport base64encode from '../base64';\nimport Timeline from './timeline';\nimport Runtime from 'runtime';\n\nexport interface TimelineSenderOptions {\n host?: string;\n port?: number;\n path?: string;\n}\n\nexport default class TimelineSender {\n timeline: Timeline;\n options: TimelineSenderOptions;\n host: string;\n\n constructor(timeline: Timeline, options: TimelineSenderOptions) {\n this.timeline = timeline;\n this.options = options || {};\n }\n\n send(useTLS: boolean, callback?: Function) {\n if (this.timeline.isEmpty()) {\n return;\n }\n\n this.timeline.send(\n Runtime.TimelineTransport.getAgent(this, useTLS),\n callback\n );\n }\n}\n","import { default as EventsDispatcher } from '../events/dispatcher';\nimport * as Errors from '../errors';\nimport Logger from '../logger';\nimport Pusher from '../pusher';\nimport { PusherEvent } from '../connection/protocol/message-types';\nimport Metadata from './metadata';\nimport UrlStore from '../utils/url_store';\nimport {\n ChannelAuthorizationData,\n ChannelAuthorizationCallback\n} from '../auth/options';\nimport { HTTPAuthError } from '../errors';\n\n/** Provides base public channel interface with an event emitter.\n *\n * Emits:\n * - pusher:subscription_succeeded - after subscribing successfully\n * - other non-internal events\n *\n * @param {String} name\n * @param {Pusher} pusher\n */\nexport default class Channel extends EventsDispatcher {\n name: string;\n pusher: Pusher;\n subscribed: boolean;\n subscriptionPending: boolean;\n subscriptionCancelled: boolean;\n subscriptionCount: null;\n\n constructor(name: string, pusher: Pusher) {\n super(function(event, data) {\n Logger.debug('No callbacks on ' + name + ' for ' + event);\n });\n\n this.name = name;\n this.pusher = pusher;\n this.subscribed = false;\n this.subscriptionPending = false;\n this.subscriptionCancelled = false;\n }\n\n /** Skips authorization, since public channels don't require it.\n *\n * @param {Function} callback\n */\n authorize(socketId: string, callback: ChannelAuthorizationCallback) {\n return callback(null, { auth: '' });\n }\n\n /** Triggers an event */\n trigger(event: string, data: any) {\n if (event.indexOf('client-') !== 0) {\n throw new Errors.BadEventName(\n \"Event '\" + event + \"' does not start with 'client-'\"\n );\n }\n if (!this.subscribed) {\n var suffix = UrlStore.buildLogSuffix('triggeringClientEvents');\n Logger.warn(\n `Client event triggered before channel 'subscription_succeeded' event . ${suffix}`\n );\n }\n return this.pusher.send_event(event, data, this.name);\n }\n\n /** Signals disconnection to the channel. For internal use only. */\n disconnect() {\n this.subscribed = false;\n this.subscriptionPending = false;\n }\n\n /** Handles a PusherEvent. For internal use only.\n *\n * @param {PusherEvent} event\n */\n handleEvent(event: PusherEvent) {\n var eventName = event.event;\n var data = event.data;\n if (eventName === 'pusher_internal:subscription_succeeded') {\n this.handleSubscriptionSucceededEvent(event);\n } else if (eventName === 'pusher_internal:subscription_count') {\n this.handleSubscriptionCountEvent(event);\n } else if (eventName.indexOf('pusher_internal:') !== 0) {\n var metadata: Metadata = {};\n this.emit(eventName, data, metadata);\n }\n }\n\n handleSubscriptionSucceededEvent(event: PusherEvent) {\n this.subscriptionPending = false;\n this.subscribed = true;\n if (this.subscriptionCancelled) {\n this.pusher.unsubscribe(this.name);\n } else {\n this.emit('pusher:subscription_succeeded', event.data);\n }\n }\n\n handleSubscriptionCountEvent(event: PusherEvent) {\n if (event.data.subscription_count) {\n this.subscriptionCount = event.data.subscription_count;\n }\n\n this.emit('pusher:subscription_count', event.data);\n }\n\n /** Sends a subscription request. For internal use only. */\n subscribe() {\n if (this.subscribed) {\n return;\n }\n this.subscriptionPending = true;\n this.subscriptionCancelled = false;\n this.authorize(\n this.pusher.connection.socket_id,\n (error: Error | null, data: ChannelAuthorizationData) => {\n if (error) {\n this.subscriptionPending = false;\n // Why not bind to 'pusher:subscription_error' a level up, and log there?\n // Binding to this event would cause the warning about no callbacks being\n // bound (see constructor) to be suppressed, that's not what we want.\n Logger.error(error.toString());\n this.emit(\n 'pusher:subscription_error',\n Object.assign(\n {},\n {\n type: 'AuthError',\n error: error.message\n },\n error instanceof HTTPAuthError ? { status: error.status } : {}\n )\n );\n } else {\n this.pusher.send_event('pusher:subscribe', {\n auth: data.auth,\n channel_data: data.channel_data,\n channel: this.name\n });\n }\n }\n );\n }\n\n /** Sends an unsubscription request. For internal use only. */\n unsubscribe() {\n this.subscribed = false;\n this.pusher.send_event('pusher:unsubscribe', {\n channel: this.name\n });\n }\n\n /** Cancels an in progress subscription. For internal use only. */\n cancelSubscription() {\n this.subscriptionCancelled = true;\n }\n\n /** Reinstates an in progress subscripiton. For internal use only. */\n reinstateSubscription() {\n this.subscriptionCancelled = false;\n }\n}\n","import Factory from '../utils/factory';\nimport Channel from './channel';\nimport { ChannelAuthorizationCallback } from '../auth/options';\n\n/** Extends public channels to provide private channel interface.\n *\n * @param {String} name\n * @param {Pusher} pusher\n */\nexport default class PrivateChannel extends Channel {\n /** Authorizes the connection to use the channel.\n *\n * @param {String} socketId\n * @param {Function} callback\n */\n authorize(socketId: string, callback: ChannelAuthorizationCallback) {\n return this.pusher.config.channelAuthorizer(\n {\n channelName: this.name,\n socketId: socketId\n },\n callback\n );\n }\n}\n","import * as Collections from '../utils/collections';\n\n/** Represents a collection of members of a presence channel. */\nexport default class Members {\n members: any;\n count: number;\n myID: any;\n me: any;\n\n constructor() {\n this.reset();\n }\n\n /** Returns member's info for given id.\n *\n * Resulting object containts two fields - id and info.\n *\n * @param {Number} id\n * @return {Object} member's info or null\n */\n get(id: string): any {\n if (Object.prototype.hasOwnProperty.call(this.members, id)) {\n return {\n id: id,\n info: this.members[id]\n };\n } else {\n return null;\n }\n }\n\n /** Calls back for each member in unspecified order.\n *\n * @param {Function} callback\n */\n each(callback: Function) {\n Collections.objectApply(this.members, (member, id) => {\n callback(this.get(id));\n });\n }\n\n /** Updates the id for connected member. For internal use only. */\n setMyID(id: string) {\n this.myID = id;\n }\n\n /** Handles subscription data. For internal use only. */\n onSubscription(subscriptionData: any) {\n this.members = subscriptionData.presence.hash;\n this.count = subscriptionData.presence.count;\n this.me = this.get(this.myID);\n }\n\n /** Adds a new member to the collection. For internal use only. */\n addMember(memberData: any) {\n if (this.get(memberData.user_id) === null) {\n this.count++;\n }\n this.members[memberData.user_id] = memberData.user_info;\n return this.get(memberData.user_id);\n }\n\n /** Adds a member from the collection. For internal use only. */\n removeMember(memberData: any) {\n var member = this.get(memberData.user_id);\n if (member) {\n delete this.members[memberData.user_id];\n this.count--;\n }\n return member;\n }\n\n /** Resets the collection to the initial state. For internal use only. */\n reset() {\n this.members = {};\n this.count = 0;\n this.myID = null;\n this.me = null;\n }\n}\n","import PrivateChannel from './private_channel';\nimport Logger from '../logger';\nimport Members from './members';\nimport Pusher from '../pusher';\nimport UrlStore from 'core/utils/url_store';\nimport { PusherEvent } from '../connection/protocol/message-types';\nimport Metadata from './metadata';\nimport { ChannelAuthorizationData } from '../auth/options';\n\nexport default class PresenceChannel extends PrivateChannel {\n members: Members;\n\n /** Adds presence channel functionality to private channels.\n *\n * @param {String} name\n * @param {Pusher} pusher\n */\n constructor(name: string, pusher: Pusher) {\n super(name, pusher);\n this.members = new Members();\n }\n\n /** Authorizes the connection as a member of the channel.\n *\n * @param {String} socketId\n * @param {Function} callback\n */\n authorize(socketId: string, callback: Function) {\n super.authorize(socketId, async (error, authData) => {\n if (!error) {\n authData = authData as ChannelAuthorizationData;\n if (authData.channel_data != null) {\n var channelData = JSON.parse(authData.channel_data);\n this.members.setMyID(channelData.user_id);\n } else {\n await this.pusher.user.signinDonePromise;\n if (this.pusher.user.user_data != null) {\n // If the user is signed in, get the id of the authenticated user\n // and allow the presence authorization to continue.\n this.members.setMyID(this.pusher.user.user_data.id);\n } else {\n let suffix = UrlStore.buildLogSuffix('authorizationEndpoint');\n Logger.error(\n `Invalid auth response for channel '${this.name}', ` +\n `expected 'channel_data' field. ${suffix}, ` +\n `or the user should be signed in.`\n );\n callback('Invalid auth response');\n return;\n }\n }\n }\n callback(error, authData);\n });\n }\n\n /** Handles presence and subscription events. For internal use only.\n *\n * @param {PusherEvent} event\n */\n handleEvent(event: PusherEvent) {\n var eventName = event.event;\n if (eventName.indexOf('pusher_internal:') === 0) {\n this.handleInternalEvent(event);\n } else {\n var data = event.data;\n var metadata: Metadata = {};\n if (event.user_id) {\n metadata.user_id = event.user_id;\n }\n this.emit(eventName, data, metadata);\n }\n }\n handleInternalEvent(event: PusherEvent) {\n var eventName = event.event;\n var data = event.data;\n switch (eventName) {\n case 'pusher_internal:subscription_succeeded':\n this.handleSubscriptionSucceededEvent(event);\n break;\n case 'pusher_internal:subscription_count':\n this.handleSubscriptionCountEvent(event);\n break;\n case 'pusher_internal:member_added':\n var addedMember = this.members.addMember(data);\n this.emit('pusher:member_added', addedMember);\n break;\n case 'pusher_internal:member_removed':\n var removedMember = this.members.removeMember(data);\n if (removedMember) {\n this.emit('pusher:member_removed', removedMember);\n }\n break;\n }\n }\n\n handleSubscriptionSucceededEvent(event: PusherEvent) {\n this.subscriptionPending = false;\n this.subscribed = true;\n if (this.subscriptionCancelled) {\n this.pusher.unsubscribe(this.name);\n } else {\n this.members.onSubscription(event.data);\n this.emit('pusher:subscription_succeeded', this.members);\n }\n }\n\n /** Resets the channel state, including members map. For internal use only. */\n disconnect() {\n this.members.reset();\n super.disconnect();\n }\n}\n","import PrivateChannel from './private_channel';\nimport * as Errors from '../errors';\nimport Logger from '../logger';\nimport Pusher from '../pusher';\nimport { decode as encodeUTF8 } from '@stablelib/utf8';\nimport { decode as decodeBase64 } from '@stablelib/base64';\nimport Dispatcher from '../events/dispatcher';\nimport { PusherEvent } from '../connection/protocol/message-types';\nimport {\n ChannelAuthorizationData,\n ChannelAuthorizationCallback\n} from '../auth/options';\nimport * as nacl from 'tweetnacl';\n\n/** Extends private channels to provide encrypted channel interface.\n *\n * @param {String} name\n * @param {Pusher} pusher\n */\nexport default class EncryptedChannel extends PrivateChannel {\n key: Uint8Array = null;\n nacl: nacl;\n\n constructor(name: string, pusher: Pusher, nacl: nacl) {\n super(name, pusher);\n this.nacl = nacl;\n }\n\n /** Authorizes the connection to use the channel.\n *\n * @param {String} socketId\n * @param {Function} callback\n */\n authorize(socketId: string, callback: ChannelAuthorizationCallback) {\n super.authorize(\n socketId,\n (error: Error | null, authData: ChannelAuthorizationData) => {\n if (error) {\n callback(error, authData);\n return;\n }\n let sharedSecret = authData['shared_secret'];\n if (!sharedSecret) {\n callback(\n new Error(\n `No shared_secret key in auth payload for encrypted channel: ${this.name}`\n ),\n null\n );\n return;\n }\n this.key = decodeBase64(sharedSecret);\n delete authData['shared_secret'];\n callback(null, authData);\n }\n );\n }\n\n trigger(event: string, data: any): boolean {\n throw new Errors.UnsupportedFeature(\n 'Client events are not currently supported for encrypted channels'\n );\n }\n\n /** Handles an event. For internal use only.\n *\n * @param {PusherEvent} event\n */\n handleEvent(event: PusherEvent) {\n var eventName = event.event;\n var data = event.data;\n if (\n eventName.indexOf('pusher_internal:') === 0 ||\n eventName.indexOf('pusher:') === 0\n ) {\n super.handleEvent(event);\n return;\n }\n this.handleEncryptedEvent(eventName, data);\n }\n\n private handleEncryptedEvent(event: string, data: any): void {\n if (!this.key) {\n Logger.debug(\n 'Received encrypted event before key has been retrieved from the authEndpoint'\n );\n return;\n }\n if (!data.ciphertext || !data.nonce) {\n Logger.error(\n 'Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: ' +\n data\n );\n return;\n }\n let cipherText = decodeBase64(data.ciphertext);\n if (cipherText.length < this.nacl.secretbox.overheadLength) {\n Logger.error(\n `Expected encrypted event ciphertext length to be ${this.nacl.secretbox.overheadLength}, got: ${cipherText.length}`\n );\n return;\n }\n let nonce = decodeBase64(data.nonce);\n if (nonce.length < this.nacl.secretbox.nonceLength) {\n Logger.error(\n `Expected encrypted event nonce length to be ${this.nacl.secretbox.nonceLength}, got: ${nonce.length}`\n );\n return;\n }\n\n let bytes = this.nacl.secretbox.open(cipherText, nonce, this.key);\n if (bytes === null) {\n Logger.debug(\n 'Failed to decrypt an event, probably because it was encrypted with a different key. Fetching a new key from the authEndpoint...'\n );\n // Try a single time to retrieve a new auth key and decrypt the event with it\n // If this fails, a new key will be requested when a new message is received\n this.authorize(this.pusher.connection.socket_id, (error, authData) => {\n if (error) {\n Logger.error(\n `Failed to make a request to the authEndpoint: ${authData}. Unable to fetch new key, so dropping encrypted event`\n );\n return;\n }\n bytes = this.nacl.secretbox.open(cipherText, nonce, this.key);\n if (bytes === null) {\n Logger.error(\n `Failed to decrypt event with new key. Dropping encrypted event`\n );\n return;\n }\n this.emit(event, this.getDataToEmit(bytes));\n return;\n });\n return;\n }\n this.emit(event, this.getDataToEmit(bytes));\n }\n\n // Try and parse the decrypted bytes as JSON. If we can't parse it, just\n // return the utf-8 string\n getDataToEmit(bytes: Uint8Array): string {\n let raw = encodeUTF8(bytes);\n try {\n return JSON.parse(raw);\n } catch {\n return raw;\n }\n }\n}\n","import { default as EventsDispatcher } from '../events/dispatcher';\nimport { OneOffTimer as Timer } from '../utils/timers';\nimport { Config } from '../config';\nimport Logger from '../logger';\nimport HandshakePayload from './handshake/handshake_payload';\nimport Connection from './connection';\nimport Strategy from '../strategies/strategy';\nimport StrategyRunner from '../strategies/strategy_runner';\nimport * as Collections from '../utils/collections';\nimport Timeline from '../timeline/timeline';\nimport ConnectionManagerOptions from './connection_manager_options';\nimport Runtime from 'runtime';\n\nimport {\n ErrorCallbacks,\n HandshakeCallbacks,\n ConnectionCallbacks\n} from './callbacks';\nimport Action from './protocol/action';\n\n/** Manages connection to Pusher.\n *\n * Uses a strategy (currently only default), timers and network availability\n * info to establish a connection and export its state. In case of failures,\n * manages reconnection attempts.\n *\n * Exports state changes as following events:\n * - \"state_change\", { previous: p, current: state }\n * - state\n *\n * States:\n * - initialized - initial state, never transitioned to\n * - connecting - connection is being established\n * - connected - connection has been fully established\n * - disconnected - on requested disconnection\n * - unavailable - after connection timeout or when there's no network\n * - failed - when the connection strategy is not supported\n *\n * Options:\n * - unavailableTimeout - time to transition to unavailable state\n * - activityTimeout - time after which ping message should be sent\n * - pongTimeout - time for Pusher to respond with pong before reconnecting\n *\n * @param {String} key application key\n * @param {Object} options\n */\nexport default class ConnectionManager extends EventsDispatcher {\n key: string;\n options: ConnectionManagerOptions;\n state: string;\n connection: Connection;\n usingTLS: boolean;\n timeline: Timeline;\n socket_id: string;\n unavailableTimer: Timer;\n activityTimer: Timer;\n retryTimer: Timer;\n activityTimeout: number;\n strategy: Strategy;\n runner: StrategyRunner;\n errorCallbacks: ErrorCallbacks;\n handshakeCallbacks: HandshakeCallbacks;\n connectionCallbacks: ConnectionCallbacks;\n\n constructor(key: string, options: ConnectionManagerOptions) {\n super();\n this.state = 'initialized';\n this.connection = null;\n\n this.key = key;\n this.options = options;\n this.timeline = this.options.timeline;\n this.usingTLS = this.options.useTLS;\n\n this.errorCallbacks = this.buildErrorCallbacks();\n this.connectionCallbacks = this.buildConnectionCallbacks(\n this.errorCallbacks\n );\n this.handshakeCallbacks = this.buildHandshakeCallbacks(this.errorCallbacks);\n\n var Network = Runtime.getNetwork();\n\n Network.bind('online', () => {\n this.timeline.info({ netinfo: 'online' });\n if (this.state === 'connecting' || this.state === 'unavailable') {\n this.retryIn(0);\n }\n });\n Network.bind('offline', () => {\n this.timeline.info({ netinfo: 'offline' });\n if (this.connection) {\n this.sendActivityCheck();\n }\n });\n\n this.updateStrategy();\n }\n\n /** Establishes a connection to Pusher.\n *\n * Does nothing when connection is already established. See top-level doc\n * to find events emitted on connection attempts.\n */\n connect() {\n if (this.connection || this.runner) {\n return;\n }\n if (!this.strategy.isSupported()) {\n this.updateState('failed');\n return;\n }\n this.updateState('connecting');\n this.startConnecting();\n this.setUnavailableTimer();\n }\n\n /** Sends raw data.\n *\n * @param {String} data\n */\n send(data) {\n if (this.connection) {\n return this.connection.send(data);\n } else {\n return false;\n }\n }\n\n /** Sends an event.\n *\n * @param {String} name\n * @param {String} data\n * @param {String} [channel]\n * @returns {Boolean} whether message was sent or not\n */\n send_event(name: string, data: any, channel?: string) {\n if (this.connection) {\n return this.connection.send_event(name, data, channel);\n } else {\n return false;\n }\n }\n\n /** Closes the connection. */\n disconnect() {\n this.disconnectInternally();\n this.updateState('disconnected');\n }\n\n isUsingTLS() {\n return this.usingTLS;\n }\n\n private startConnecting() {\n var callback = (error, handshake) => {\n if (error) {\n this.runner = this.strategy.connect(0, callback);\n } else {\n if (handshake.action === 'error') {\n this.emit('error', {\n type: 'HandshakeError',\n error: handshake.error\n });\n this.timeline.error({ handshakeError: handshake.error });\n } else {\n this.abortConnecting(); // we don't support switching connections yet\n this.handshakeCallbacks[handshake.action](handshake);\n }\n }\n };\n this.runner = this.strategy.connect(0, callback);\n }\n\n private abortConnecting() {\n if (this.runner) {\n this.runner.abort();\n this.runner = null;\n }\n }\n\n private disconnectInternally() {\n this.abortConnecting();\n this.clearRetryTimer();\n this.clearUnavailableTimer();\n if (this.connection) {\n var connection = this.abandonConnection();\n connection.close();\n }\n }\n\n private updateStrategy() {\n this.strategy = this.options.getStrategy({\n key: this.key,\n timeline: this.timeline,\n useTLS: this.usingTLS\n });\n }\n\n private retryIn(delay) {\n this.timeline.info({ action: 'retry', delay: delay });\n if (delay > 0) {\n this.emit('connecting_in', Math.round(delay / 1000));\n }\n this.retryTimer = new Timer(delay || 0, () => {\n this.disconnectInternally();\n this.connect();\n });\n }\n\n private clearRetryTimer() {\n if (this.retryTimer) {\n this.retryTimer.ensureAborted();\n this.retryTimer = null;\n }\n }\n\n private setUnavailableTimer() {\n this.unavailableTimer = new Timer(this.options.unavailableTimeout, () => {\n this.updateState('unavailable');\n });\n }\n\n private clearUnavailableTimer() {\n if (this.unavailableTimer) {\n this.unavailableTimer.ensureAborted();\n }\n }\n\n private sendActivityCheck() {\n this.stopActivityCheck();\n this.connection.ping();\n // wait for pong response\n this.activityTimer = new Timer(this.options.pongTimeout, () => {\n this.timeline.error({ pong_timed_out: this.options.pongTimeout });\n this.retryIn(0);\n });\n }\n\n private resetActivityCheck() {\n this.stopActivityCheck();\n // send ping after inactivity\n if (this.connection && !this.connection.handlesActivityChecks()) {\n this.activityTimer = new Timer(this.activityTimeout, () => {\n this.sendActivityCheck();\n });\n }\n }\n\n private stopActivityCheck() {\n if (this.activityTimer) {\n this.activityTimer.ensureAborted();\n }\n }\n\n private buildConnectionCallbacks(\n errorCallbacks: ErrorCallbacks\n ): ConnectionCallbacks {\n return Collections.extend({}, errorCallbacks, {\n message: message => {\n // includes pong messages from server\n this.resetActivityCheck();\n this.emit('message', message);\n },\n ping: () => {\n this.send_event('pusher:pong', {});\n },\n activity: () => {\n this.resetActivityCheck();\n },\n error: error => {\n // just emit error to user - socket will already be closed by browser\n this.emit('error', error);\n },\n closed: () => {\n this.abandonConnection();\n if (this.shouldRetry()) {\n this.retryIn(1000);\n }\n }\n });\n }\n\n private buildHandshakeCallbacks(\n errorCallbacks: ErrorCallbacks\n ): HandshakeCallbacks {\n return Collections.extend({}, errorCallbacks, {\n connected: (handshake: HandshakePayload) => {\n this.activityTimeout = Math.min(\n this.options.activityTimeout,\n handshake.activityTimeout,\n handshake.connection.activityTimeout || Infinity\n );\n this.clearUnavailableTimer();\n this.setConnection(handshake.connection);\n this.socket_id = this.connection.id;\n this.updateState('connected', { socket_id: this.socket_id });\n }\n });\n }\n\n private buildErrorCallbacks(): ErrorCallbacks {\n let withErrorEmitted = callback => {\n return (result: Action | HandshakePayload) => {\n if (result.error) {\n this.emit('error', { type: 'WebSocketError', error: result.error });\n }\n callback(result);\n };\n };\n\n return {\n tls_only: withErrorEmitted(() => {\n this.usingTLS = true;\n this.updateStrategy();\n this.retryIn(0);\n }),\n refused: withErrorEmitted(() => {\n this.disconnect();\n }),\n backoff: withErrorEmitted(() => {\n this.retryIn(1000);\n }),\n retry: withErrorEmitted(() => {\n this.retryIn(0);\n })\n };\n }\n\n private setConnection(connection) {\n this.connection = connection;\n for (var event in this.connectionCallbacks) {\n this.connection.bind(event, this.connectionCallbacks[event]);\n }\n this.resetActivityCheck();\n }\n\n private abandonConnection() {\n if (!this.connection) {\n return;\n }\n this.stopActivityCheck();\n for (var event in this.connectionCallbacks) {\n this.connection.unbind(event, this.connectionCallbacks[event]);\n }\n var connection = this.connection;\n this.connection = null;\n return connection;\n }\n\n private updateState(newState: string, data?: any) {\n var previousState = this.state;\n this.state = newState;\n if (previousState !== newState) {\n var newStateDescription = newState;\n if (newStateDescription === 'connected') {\n newStateDescription += ' with new socket ID ' + data.socket_id;\n }\n Logger.debug(\n 'State changed',\n previousState + ' -> ' + newStateDescription\n );\n this.timeline.info({ state: newState, params: data });\n this.emit('state_change', { previous: previousState, current: newState });\n this.emit(newState, data);\n }\n }\n\n private shouldRetry(): boolean {\n return this.state === 'connecting' || this.state === 'connected';\n }\n}\n","import Channel from './channel';\nimport * as Collections from '../utils/collections';\nimport ChannelTable from './channel_table';\nimport Factory from '../utils/factory';\nimport Pusher from '../pusher';\nimport Logger from '../logger';\nimport * as Errors from '../errors';\nimport urlStore from '../utils/url_store';\n\n/** Handles a channel map. */\nexport default class Channels {\n channels: ChannelTable;\n\n constructor() {\n this.channels = {};\n }\n\n /** Creates or retrieves an existing channel by its name.\n *\n * @param {String} name\n * @param {Pusher} pusher\n * @return {Channel}\n */\n add(name: string, pusher: Pusher) {\n if (!this.channels[name]) {\n this.channels[name] = createChannel(name, pusher);\n }\n return this.channels[name];\n }\n\n /** Returns a list of all channels\n *\n * @return {Array}\n */\n all(): Channel[] {\n return Collections.values(this.channels);\n }\n\n /** Finds a channel by its name.\n *\n * @param {String} name\n * @return {Channel} channel or null if it doesn't exist\n */\n find(name: string) {\n return this.channels[name];\n }\n\n /** Removes a channel from the map.\n *\n * @param {String} name\n */\n remove(name: string) {\n var channel = this.channels[name];\n delete this.channels[name];\n return channel;\n }\n\n /** Proxies disconnection signal to all channels. */\n disconnect() {\n Collections.objectApply(this.channels, function(channel) {\n channel.disconnect();\n });\n }\n}\n\nfunction createChannel(name: string, pusher: Pusher): Channel {\n if (name.indexOf('private-encrypted-') === 0) {\n if (pusher.config.nacl) {\n return Factory.createEncryptedChannel(name, pusher, pusher.config.nacl);\n }\n let errMsg =\n 'Tried to subscribe to a private-encrypted- channel but no nacl implementation available';\n let suffix = urlStore.buildLogSuffix('encryptedChannelSupport');\n throw new Errors.UnsupportedFeature(`${errMsg}. ${suffix}`);\n } else if (name.indexOf('private-') === 0) {\n return Factory.createPrivateChannel(name, pusher);\n } else if (name.indexOf('presence-') === 0) {\n return Factory.createPresenceChannel(name, pusher);\n } else if (name.indexOf('#') === 0) {\n throw new Errors.BadChannelName(\n 'Cannot create a channel with name \"' + name + '\".'\n );\n } else {\n return Factory.createChannel(name, pusher);\n }\n}\n","import AssistantToTheTransportManager from '../transports/assistant_to_the_transport_manager';\nimport PingDelayOptions from '../transports/ping_delay_options';\nimport Transport from '../transports/transport';\nimport TransportManager from '../transports/transport_manager';\nimport Handshake from '../connection/handshake';\nimport TransportConnection from '../transports/transport_connection';\nimport SocketHooks from '../http/socket_hooks';\nimport HTTPSocket from '../http/http_socket';\n\nimport Timeline from '../timeline/timeline';\nimport {\n default as TimelineSender,\n TimelineSenderOptions\n} from '../timeline/timeline_sender';\nimport PresenceChannel from '../channels/presence_channel';\nimport PrivateChannel from '../channels/private_channel';\nimport EncryptedChannel from '../channels/encrypted_channel';\nimport Channel from '../channels/channel';\nimport ConnectionManager from '../connection/connection_manager';\nimport ConnectionManagerOptions from '../connection/connection_manager_options';\nimport Ajax from '../http/ajax';\nimport Channels from '../channels/channels';\nimport Pusher from '../pusher';\nimport { Config } from '../config';\nimport * as nacl from 'tweetnacl';\n\nvar Factory = {\n createChannels(): Channels {\n return new Channels();\n },\n\n createConnectionManager(\n key: string,\n options: ConnectionManagerOptions\n ): ConnectionManager {\n return new ConnectionManager(key, options);\n },\n\n createChannel(name: string, pusher: Pusher): Channel {\n return new Channel(name, pusher);\n },\n\n createPrivateChannel(name: string, pusher: Pusher): PrivateChannel {\n return new PrivateChannel(name, pusher);\n },\n\n createPresenceChannel(name: string, pusher: Pusher): PresenceChannel {\n return new PresenceChannel(name, pusher);\n },\n\n createEncryptedChannel(\n name: string,\n pusher: Pusher,\n nacl: nacl\n ): EncryptedChannel {\n return new EncryptedChannel(name, pusher, nacl);\n },\n\n createTimelineSender(timeline: Timeline, options: TimelineSenderOptions) {\n return new TimelineSender(timeline, options);\n },\n\n createHandshake(\n transport: TransportConnection,\n callback: (HandshakePayload) => void\n ): Handshake {\n return new Handshake(transport, callback);\n },\n\n createAssistantToTheTransportManager(\n manager: TransportManager,\n transport: Transport,\n options: PingDelayOptions\n ): AssistantToTheTransportManager {\n return new AssistantToTheTransportManager(manager, transport, options);\n }\n};\n\nexport default Factory;\n","import AssistantToTheTransportManager from './assistant_to_the_transport_manager';\nimport Transport from './transport';\nimport PingDelayOptions from './ping_delay_options';\nimport Factory from '../utils/factory';\n\nexport interface TransportManagerOptions extends PingDelayOptions {\n lives?: number;\n}\n\n/** Keeps track of the number of lives left for a transport.\n *\n * In the beginning of a session, transports may be assigned a number of\n * lives. When an AssistantToTheTransportManager instance reports a transport\n * connection closed uncleanly, the transport loses a life. When the number\n * of lives drops to zero, the transport gets disabled by its manager.\n *\n * @param {Object} options\n */\nexport default class TransportManager {\n options: TransportManagerOptions;\n livesLeft: number;\n\n constructor(options: TransportManagerOptions) {\n this.options = options || {};\n this.livesLeft = this.options.lives || Infinity;\n }\n\n /** Creates a assistant for the transport.\n *\n * @param {Transport} transport\n * @returns {AssistantToTheTransportManager}\n */\n getAssistant(transport: Transport): AssistantToTheTransportManager {\n return Factory.createAssistantToTheTransportManager(this, transport, {\n minPingDelay: this.options.minPingDelay,\n maxPingDelay: this.options.maxPingDelay\n });\n }\n\n /** Returns whether the transport has any lives left.\n *\n * @returns {Boolean}\n */\n isAlive(): boolean {\n return this.livesLeft > 0;\n }\n\n /** Takes one life from the transport. */\n reportDeath() {\n this.livesLeft -= 1;\n }\n}\n","import * as Collections from '../utils/collections';\nimport Util from '../util';\nimport { OneOffTimer as Timer } from '../utils/timers';\nimport Strategy from './strategy';\nimport StrategyOptions from './strategy_options';\n\n/** Loops through strategies with optional timeouts.\n *\n * Options:\n * - loop - whether it should loop through the substrategy list\n * - timeout - initial timeout for a single substrategy\n * - timeoutLimit - maximum timeout\n *\n * @param {Strategy[]} strategies\n * @param {Object} options\n */\nexport default class SequentialStrategy implements Strategy {\n strategies: Strategy[];\n loop: boolean;\n failFast: boolean;\n timeout: number;\n timeoutLimit: number;\n\n constructor(strategies: Strategy[], options: StrategyOptions) {\n this.strategies = strategies;\n this.loop = Boolean(options.loop);\n this.failFast = Boolean(options.failFast);\n this.timeout = options.timeout;\n this.timeoutLimit = options.timeoutLimit;\n }\n\n isSupported(): boolean {\n return Collections.any(this.strategies, Util.method('isSupported'));\n }\n\n connect(minPriority: number, callback: Function) {\n var strategies = this.strategies;\n var current = 0;\n var timeout = this.timeout;\n var runner = null;\n\n var tryNextStrategy = (error, handshake) => {\n if (handshake) {\n callback(null, handshake);\n } else {\n current = current + 1;\n if (this.loop) {\n current = current % strategies.length;\n }\n\n if (current < strategies.length) {\n if (timeout) {\n timeout = timeout * 2;\n if (this.timeoutLimit) {\n timeout = Math.min(timeout, this.timeoutLimit);\n }\n }\n runner = this.tryStrategy(\n strategies[current],\n minPriority,\n { timeout, failFast: this.failFast },\n tryNextStrategy\n );\n } else {\n callback(true);\n }\n }\n };\n\n runner = this.tryStrategy(\n strategies[current],\n minPriority,\n { timeout: timeout, failFast: this.failFast },\n tryNextStrategy\n );\n\n return {\n abort: function() {\n runner.abort();\n },\n forceMinPriority: function(p) {\n minPriority = p;\n if (runner) {\n runner.forceMinPriority(p);\n }\n }\n };\n }\n\n private tryStrategy(\n strategy: Strategy,\n minPriority: number,\n options: StrategyOptions,\n callback: Function\n ) {\n var timer = null;\n var runner = null;\n\n if (options.timeout > 0) {\n timer = new Timer(options.timeout, function() {\n runner.abort();\n callback(true);\n });\n }\n\n runner = strategy.connect(minPriority, function(error, handshake) {\n if (error && timer && timer.isRunning() && !options.failFast) {\n // advance to the next strategy after the timeout\n return;\n }\n if (timer) {\n timer.ensureAborted();\n }\n callback(error, handshake);\n });\n\n return {\n abort: function() {\n if (timer) {\n timer.ensureAborted();\n }\n runner.abort();\n },\n forceMinPriority: function(p) {\n runner.forceMinPriority(p);\n }\n };\n }\n}\n","import * as Collections from '../utils/collections';\nimport Util from '../util';\nimport Strategy from './strategy';\n\n/** Launches all substrategies and emits prioritized connected transports.\n *\n * @param {Array} strategies\n */\nexport default class BestConnectedEverStrategy implements Strategy {\n strategies: Strategy[];\n\n constructor(strategies: Strategy[]) {\n this.strategies = strategies;\n }\n\n isSupported(): boolean {\n return Collections.any(this.strategies, Util.method('isSupported'));\n }\n\n connect(minPriority: number, callback: Function) {\n return connect(this.strategies, minPriority, function(i, runners) {\n return function(error, handshake) {\n runners[i].error = error;\n if (error) {\n if (allRunnersFailed(runners)) {\n callback(true);\n }\n return;\n }\n Collections.apply(runners, function(runner) {\n runner.forceMinPriority(handshake.transport.priority);\n });\n callback(null, handshake);\n };\n });\n }\n}\n\n/** Connects to all strategies in parallel.\n *\n * Callback builder should be a function that takes two arguments: index\n * and a list of runners. It should return another function that will be\n * passed to the substrategy with given index. Runners can be aborted using\n * abortRunner(s) functions from this class.\n *\n * @param {Array} strategies\n * @param {Function} callbackBuilder\n * @return {Object} strategy runner\n */\nfunction connect(\n strategies: Strategy[],\n minPriority: number,\n callbackBuilder: Function\n) {\n var runners = Collections.map(strategies, function(strategy, i, _, rs) {\n return strategy.connect(minPriority, callbackBuilder(i, rs));\n });\n return {\n abort: function() {\n Collections.apply(runners, abortRunner);\n },\n forceMinPriority: function(p) {\n Collections.apply(runners, function(runner) {\n runner.forceMinPriority(p);\n });\n }\n };\n}\n\nfunction allRunnersFailed(runners): boolean {\n return Collections.all(runners, function(runner) {\n return Boolean(runner.error);\n });\n}\n\nfunction abortRunner(runner) {\n if (!runner.error && !runner.aborted) {\n runner.abort();\n runner.aborted = true;\n }\n}\n","import Util from '../util';\nimport Runtime from 'runtime';\nimport Strategy from './strategy';\nimport SequentialStrategy from './sequential_strategy';\nimport StrategyOptions from './strategy_options';\nimport TransportStrategy from './transport_strategy';\nimport Timeline from '../timeline/timeline';\nimport * as Collections from '../utils/collections';\n\nexport interface TransportStrategyDictionary {\n [key: string]: TransportStrategy;\n}\n\n/** Caches the last successful transport and, after the first few attempts,\n * uses the cached transport for subsequent attempts.\n *\n * @param {Strategy} strategy\n * @param {Object} transports\n * @param {Object} options\n */\nexport default class WebSocketPrioritizedCachedStrategy implements Strategy {\n strategy: Strategy;\n transports: TransportStrategyDictionary;\n ttl: number;\n usingTLS: boolean;\n timeline: Timeline;\n\n constructor(\n strategy: Strategy,\n transports: TransportStrategyDictionary,\n options: StrategyOptions\n ) {\n this.strategy = strategy;\n this.transports = transports;\n this.ttl = options.ttl || 1800 * 1000;\n this.usingTLS = options.useTLS;\n this.timeline = options.timeline;\n }\n\n isSupported(): boolean {\n return this.strategy.isSupported();\n }\n\n connect(minPriority: number, callback: Function) {\n var usingTLS = this.usingTLS;\n var info = fetchTransportCache(usingTLS);\n var cacheSkipCount = info && info.cacheSkipCount ? info.cacheSkipCount : 0;\n\n var strategies = [this.strategy];\n if (info && info.timestamp + this.ttl >= Util.now()) {\n var transport = this.transports[info.transport];\n if (transport) {\n if (['ws', 'wss'].includes(info.transport) || cacheSkipCount > 3) {\n this.timeline.info({\n cached: true,\n transport: info.transport,\n latency: info.latency\n });\n strategies.push(\n new SequentialStrategy([transport], {\n timeout: info.latency * 2 + 1000,\n failFast: true\n })\n );\n } else {\n cacheSkipCount++;\n }\n }\n }\n\n var startTimestamp = Util.now();\n var runner = strategies\n .pop()\n .connect(minPriority, function cb(error, handshake) {\n if (error) {\n flushTransportCache(usingTLS);\n if (strategies.length > 0) {\n startTimestamp = Util.now();\n runner = strategies.pop().connect(minPriority, cb);\n } else {\n callback(error);\n }\n } else {\n storeTransportCache(\n usingTLS,\n handshake.transport.name,\n Util.now() - startTimestamp,\n cacheSkipCount\n );\n callback(null, handshake);\n }\n });\n\n return {\n abort: function() {\n runner.abort();\n },\n forceMinPriority: function(p) {\n minPriority = p;\n if (runner) {\n runner.forceMinPriority(p);\n }\n }\n };\n }\n}\n\nfunction getTransportCacheKey(usingTLS: boolean): string {\n return 'pusherTransport' + (usingTLS ? 'TLS' : 'NonTLS');\n}\n\nfunction fetchTransportCache(usingTLS: boolean): any {\n var storage = Runtime.getLocalStorage();\n if (storage) {\n try {\n var serializedCache = storage[getTransportCacheKey(usingTLS)];\n if (serializedCache) {\n return JSON.parse(serializedCache);\n }\n } catch (e) {\n flushTransportCache(usingTLS);\n }\n }\n return null;\n}\n\nfunction storeTransportCache(\n usingTLS: boolean,\n transport: TransportStrategy,\n latency: number,\n cacheSkipCount: number\n) {\n var storage = Runtime.getLocalStorage();\n if (storage) {\n try {\n storage[getTransportCacheKey(usingTLS)] = Collections.safeJSONStringify({\n timestamp: Util.now(),\n transport: transport,\n latency: latency,\n cacheSkipCount: cacheSkipCount\n });\n } catch (e) {\n // catch over quota exceptions raised by localStorage\n }\n }\n}\n\nfunction flushTransportCache(usingTLS: boolean) {\n var storage = Runtime.getLocalStorage();\n if (storage) {\n try {\n delete storage[getTransportCacheKey(usingTLS)];\n } catch (e) {\n // catch exceptions raised by localStorage\n }\n }\n}\n","import { OneOffTimer as Timer } from '../utils/timers';\nimport Strategy from './strategy';\nimport StrategyOptions from './strategy_options';\n\n/** Runs substrategy after specified delay.\n *\n * Options:\n * - delay - time in miliseconds to delay the substrategy attempt\n *\n * @param {Strategy} strategy\n * @param {Object} options\n */\nexport default class DelayedStrategy implements Strategy {\n strategy: Strategy;\n options: { delay: number };\n\n constructor(strategy: Strategy, { delay: number }) {\n this.strategy = strategy;\n this.options = { delay: number };\n }\n\n isSupported(): boolean {\n return this.strategy.isSupported();\n }\n\n connect(minPriority: number, callback: Function) {\n var strategy = this.strategy;\n var runner;\n var timer = new Timer(this.options.delay, function() {\n runner = strategy.connect(minPriority, callback);\n });\n\n return {\n abort: function() {\n timer.ensureAborted();\n if (runner) {\n runner.abort();\n }\n },\n forceMinPriority: function(p) {\n minPriority = p;\n if (runner) {\n runner.forceMinPriority(p);\n }\n }\n };\n }\n}\n","import Strategy from './strategy';\nimport StrategyRunner from './strategy_runner';\n\n/** Proxies method calls to one of substrategies basing on the test function.\n *\n * @param {Function} test\n * @param {Strategy} trueBranch strategy used when test returns true\n * @param {Strategy} falseBranch strategy used when test returns false\n */\nexport default class IfStrategy implements Strategy {\n test: () => boolean;\n trueBranch: Strategy;\n falseBranch: Strategy;\n\n constructor(\n test: () => boolean,\n trueBranch: Strategy,\n falseBranch: Strategy\n ) {\n this.test = test;\n this.trueBranch = trueBranch;\n this.falseBranch = falseBranch;\n }\n\n isSupported(): boolean {\n var branch = this.test() ? this.trueBranch : this.falseBranch;\n return branch.isSupported();\n }\n\n connect(minPriority: number, callback: Function): StrategyRunner {\n var branch = this.test() ? this.trueBranch : this.falseBranch;\n return branch.connect(minPriority, callback);\n }\n}\n","import Strategy from './strategy';\nimport StrategyRunner from './strategy_runner';\n\n/** Launches the substrategy and terminates on the first open connection.\n *\n * @param {Strategy} strategy\n */\nexport default class FirstConnectedStrategy implements Strategy {\n strategy: Strategy;\n\n constructor(strategy: Strategy) {\n this.strategy = strategy;\n }\n\n isSupported(): boolean {\n return this.strategy.isSupported();\n }\n\n connect(minPriority: number, callback: Function): StrategyRunner {\n var runner = this.strategy.connect(minPriority, function(error, handshake) {\n if (handshake) {\n runner.abort();\n }\n callback(error, handshake);\n });\n return runner;\n }\n}\n","import * as Collections from 'core/utils/collections';\nimport TransportManager from 'core/transports/transport_manager';\nimport Strategy from 'core/strategies/strategy';\nimport StrategyOptions from 'core/strategies/strategy_options';\nimport SequentialStrategy from 'core/strategies/sequential_strategy';\nimport BestConnectedEverStrategy from 'core/strategies/best_connected_ever_strategy';\nimport WebSocketPrioritizedCachedStrategy, {\n TransportStrategyDictionary\n} from 'core/strategies/websocket_prioritized_cached_strategy';\nimport DelayedStrategy from 'core/strategies/delayed_strategy';\nimport IfStrategy from 'core/strategies/if_strategy';\nimport FirstConnectedStrategy from 'core/strategies/first_connected_strategy';\nimport { Config } from 'core/config';\n\nfunction testSupportsStrategy(strategy: Strategy) {\n return function() {\n return strategy.isSupported();\n };\n}\n\nvar getDefaultStrategy = function(\n config: Config,\n baseOptions: StrategyOptions,\n defineTransport: Function\n): Strategy {\n var definedTransports = {};\n\n function defineTransportStrategy(\n name: string,\n type: string,\n priority: number,\n options: StrategyOptions,\n manager?: TransportManager\n ) {\n var transport = defineTransport(\n config,\n name,\n type,\n priority,\n options,\n manager\n );\n\n definedTransports[name] = transport;\n\n return transport;\n }\n\n var ws_options: StrategyOptions = Object.assign({}, baseOptions, {\n hostNonTLS: config.wsHost + ':' + config.wsPort,\n hostTLS: config.wsHost + ':' + config.wssPort,\n httpPath: config.wsPath\n });\n var wss_options: StrategyOptions = Object.assign({}, ws_options, {\n useTLS: true\n });\n var sockjs_options: StrategyOptions = Object.assign({}, baseOptions, {\n hostNonTLS: config.httpHost + ':' + config.httpPort,\n hostTLS: config.httpHost + ':' + config.httpsPort,\n httpPath: config.httpPath\n });\n\n var timeouts = {\n loop: true,\n timeout: 15000,\n timeoutLimit: 60000\n };\n\n var ws_manager = new TransportManager({\n minPingDelay: 10000,\n maxPingDelay: config.activityTimeout\n });\n var streaming_manager = new TransportManager({\n lives: 2,\n minPingDelay: 10000,\n maxPingDelay: config.activityTimeout\n });\n\n var ws_transport = defineTransportStrategy(\n 'ws',\n 'ws',\n 3,\n ws_options,\n ws_manager\n );\n var wss_transport = defineTransportStrategy(\n 'wss',\n 'ws',\n 3,\n wss_options,\n ws_manager\n );\n var sockjs_transport = defineTransportStrategy(\n 'sockjs',\n 'sockjs',\n 1,\n sockjs_options\n );\n var xhr_streaming_transport = defineTransportStrategy(\n 'xhr_streaming',\n 'xhr_streaming',\n 1,\n sockjs_options,\n streaming_manager\n );\n var xdr_streaming_transport = defineTransportStrategy(\n 'xdr_streaming',\n 'xdr_streaming',\n 1,\n sockjs_options,\n streaming_manager\n );\n var xhr_polling_transport = defineTransportStrategy(\n 'xhr_polling',\n 'xhr_polling',\n 1,\n sockjs_options\n );\n var xdr_polling_transport = defineTransportStrategy(\n 'xdr_polling',\n 'xdr_polling',\n 1,\n sockjs_options\n );\n\n var ws_loop = new SequentialStrategy([ws_transport], timeouts);\n var wss_loop = new SequentialStrategy([wss_transport], timeouts);\n var sockjs_loop = new SequentialStrategy([sockjs_transport], timeouts);\n var streaming_loop = new SequentialStrategy(\n [\n new IfStrategy(\n testSupportsStrategy(xhr_streaming_transport),\n xhr_streaming_transport,\n xdr_streaming_transport\n )\n ],\n timeouts\n );\n var polling_loop = new SequentialStrategy(\n [\n new IfStrategy(\n testSupportsStrategy(xhr_polling_transport),\n xhr_polling_transport,\n xdr_polling_transport\n )\n ],\n timeouts\n );\n\n var http_loop = new SequentialStrategy(\n [\n new IfStrategy(\n testSupportsStrategy(streaming_loop),\n new BestConnectedEverStrategy([\n streaming_loop,\n new DelayedStrategy(polling_loop, { delay: 4000 })\n ]),\n polling_loop\n )\n ],\n timeouts\n );\n\n var http_fallback_loop = new IfStrategy(\n testSupportsStrategy(http_loop),\n http_loop,\n sockjs_loop\n );\n\n var wsStrategy;\n if (baseOptions.useTLS) {\n wsStrategy = new BestConnectedEverStrategy([\n ws_loop,\n new DelayedStrategy(http_fallback_loop, { delay: 2000 })\n ]);\n } else {\n wsStrategy = new BestConnectedEverStrategy([\n ws_loop,\n new DelayedStrategy(wss_loop, { delay: 2000 }),\n new DelayedStrategy(http_fallback_loop, { delay: 5000 })\n ]);\n }\n\n return new WebSocketPrioritizedCachedStrategy(\n new FirstConnectedStrategy(\n new IfStrategy(\n testSupportsStrategy(ws_transport),\n wsStrategy,\n http_fallback_loop\n )\n ),\n definedTransports,\n {\n ttl: 1800000,\n timeline: baseOptions.timeline,\n useTLS: baseOptions.useTLS\n }\n );\n};\n\nexport default getDefaultStrategy;\n","enum State {\n CONNECTING = 0,\n OPEN = 1,\n CLOSED = 3\n}\n\nexport default State;\n","import HTTPRequest from 'core/http/http_request';\nimport RequestHooks from 'core/http/request_hooks';\nimport Ajax from 'core/http/ajax';\nimport * as Errors from 'core/errors';\n\nvar hooks: RequestHooks = {\n getRequest: function(socket: HTTPRequest): Ajax {\n var xdr = new (window).XDomainRequest();\n xdr.ontimeout = function() {\n socket.emit('error', new Errors.RequestTimedOut());\n socket.close();\n };\n xdr.onerror = function(e) {\n socket.emit('error', e);\n socket.close();\n };\n xdr.onprogress = function() {\n if (xdr.responseText && xdr.responseText.length > 0) {\n socket.onChunk(200, xdr.responseText);\n }\n };\n xdr.onload = function() {\n if (xdr.responseText && xdr.responseText.length > 0) {\n socket.onChunk(200, xdr.responseText);\n }\n socket.emit('finished', 200);\n socket.close();\n };\n return xdr;\n },\n abortRequest: function(xdr: Ajax) {\n xdr.ontimeout = xdr.onerror = xdr.onprogress = xdr.onload = null;\n xdr.abort();\n }\n};\n\nexport default hooks;\n","import Runtime from 'runtime';\nimport RequestHooks from './request_hooks';\nimport Ajax from './ajax';\nimport { default as EventsDispatcher } from '../events/dispatcher';\n\nconst MAX_BUFFER_LENGTH = 256 * 1024;\n\nexport default class HTTPRequest extends EventsDispatcher {\n hooks: RequestHooks;\n method: string;\n url: string;\n position: number;\n xhr: Ajax;\n unloader: Function;\n\n constructor(hooks: RequestHooks, method: string, url: string) {\n super();\n this.hooks = hooks;\n this.method = method;\n this.url = url;\n }\n\n start(payload?: any) {\n this.position = 0;\n this.xhr = this.hooks.getRequest(this);\n\n this.unloader = () => {\n this.close();\n };\n Runtime.addUnloadListener(this.unloader);\n\n this.xhr.open(this.method, this.url, true);\n\n if (this.xhr.setRequestHeader) {\n this.xhr.setRequestHeader('Content-Type', 'application/json'); // ReactNative doesn't set this header by default.\n }\n this.xhr.send(payload);\n }\n\n close() {\n if (this.unloader) {\n Runtime.removeUnloadListener(this.unloader);\n this.unloader = null;\n }\n if (this.xhr) {\n this.hooks.abortRequest(this.xhr);\n this.xhr = null;\n }\n }\n\n onChunk(status: number, data: any) {\n while (true) {\n var chunk = this.advanceBuffer(data);\n if (chunk) {\n this.emit('chunk', { status: status, data: chunk });\n } else {\n break;\n }\n }\n if (this.isBufferTooLong(data)) {\n this.emit('buffer_too_long');\n }\n }\n\n private advanceBuffer(buffer: any[]): any {\n var unreadData = buffer.slice(this.position);\n var endOfLinePosition = unreadData.indexOf('\\n');\n\n if (endOfLinePosition !== -1) {\n this.position += endOfLinePosition + 1;\n return unreadData.slice(0, endOfLinePosition);\n } else {\n // chunk is not finished yet, don't move the buffer pointer\n return null;\n }\n }\n\n private isBufferTooLong(buffer: any): boolean {\n return this.position === buffer.length && buffer.length > MAX_BUFFER_LENGTH;\n }\n}\n","import URLLocation from './url_location';\nimport State from './state';\nimport Socket from '../socket';\nimport SocketHooks from './socket_hooks';\nimport Util from '../util';\nimport Ajax from './ajax';\nimport HTTPRequest from './http_request';\nimport Runtime from 'runtime';\n\nvar autoIncrement = 1;\n\nclass HTTPSocket implements Socket {\n hooks: SocketHooks;\n session: string;\n location: URLLocation;\n readyState: State;\n stream: HTTPRequest;\n\n onopen: () => void;\n onerror: (error: any) => void;\n onclose: (closeEvent: any) => void;\n onmessage: (message: any) => void;\n onactivity: () => void;\n\n constructor(hooks: SocketHooks, url: string) {\n this.hooks = hooks;\n this.session = randomNumber(1000) + '/' + randomString(8);\n this.location = getLocation(url);\n this.readyState = State.CONNECTING;\n this.openStream();\n }\n\n send(payload: any) {\n return this.sendRaw(JSON.stringify([payload]));\n }\n\n ping() {\n this.hooks.sendHeartbeat(this);\n }\n\n close(code: any, reason: any) {\n this.onClose(code, reason, true);\n }\n\n /** For internal use only */\n sendRaw(payload: any): boolean {\n if (this.readyState === State.OPEN) {\n try {\n Runtime.createSocketRequest(\n 'POST',\n getUniqueURL(getSendURL(this.location, this.session))\n ).start(payload);\n return true;\n } catch (e) {\n return false;\n }\n } else {\n return false;\n }\n }\n\n /** For internal use only */\n reconnect() {\n this.closeStream();\n this.openStream();\n }\n\n /** For internal use only */\n onClose(code, reason, wasClean) {\n this.closeStream();\n this.readyState = State.CLOSED;\n if (this.onclose) {\n this.onclose({\n code: code,\n reason: reason,\n wasClean: wasClean\n });\n }\n }\n\n private onChunk(chunk) {\n if (chunk.status !== 200) {\n return;\n }\n if (this.readyState === State.OPEN) {\n this.onActivity();\n }\n\n var payload;\n var type = chunk.data.slice(0, 1);\n switch (type) {\n case 'o':\n payload = JSON.parse(chunk.data.slice(1) || '{}');\n this.onOpen(payload);\n break;\n case 'a':\n payload = JSON.parse(chunk.data.slice(1) || '[]');\n for (var i = 0; i < payload.length; i++) {\n this.onEvent(payload[i]);\n }\n break;\n case 'm':\n payload = JSON.parse(chunk.data.slice(1) || 'null');\n this.onEvent(payload);\n break;\n case 'h':\n this.hooks.onHeartbeat(this);\n break;\n case 'c':\n payload = JSON.parse(chunk.data.slice(1) || '[]');\n this.onClose(payload[0], payload[1], true);\n break;\n }\n }\n\n private onOpen(options) {\n if (this.readyState === State.CONNECTING) {\n if (options && options.hostname) {\n this.location.base = replaceHost(this.location.base, options.hostname);\n }\n this.readyState = State.OPEN;\n\n if (this.onopen) {\n this.onopen();\n }\n } else {\n this.onClose(1006, 'Server lost session', true);\n }\n }\n\n private onEvent(event) {\n if (this.readyState === State.OPEN && this.onmessage) {\n this.onmessage({ data: event });\n }\n }\n\n private onActivity() {\n if (this.onactivity) {\n this.onactivity();\n }\n }\n\n private onError(error) {\n if (this.onerror) {\n this.onerror(error);\n }\n }\n\n private openStream() {\n this.stream = Runtime.createSocketRequest(\n 'POST',\n getUniqueURL(this.hooks.getReceiveURL(this.location, this.session))\n );\n\n this.stream.bind('chunk', chunk => {\n this.onChunk(chunk);\n });\n this.stream.bind('finished', status => {\n this.hooks.onFinished(this, status);\n });\n this.stream.bind('buffer_too_long', () => {\n this.reconnect();\n });\n\n try {\n this.stream.start();\n } catch (error) {\n Util.defer(() => {\n this.onError(error);\n this.onClose(1006, 'Could not start streaming', false);\n });\n }\n }\n\n private closeStream() {\n if (this.stream) {\n this.stream.unbind_all();\n this.stream.close();\n this.stream = null;\n }\n }\n}\n\nfunction getLocation(url): URLLocation {\n var parts = /([^\\?]*)\\/*(\\??.*)/.exec(url);\n return {\n base: parts[1],\n queryString: parts[2]\n };\n}\n\nfunction getSendURL(url: URLLocation, session: string): string {\n return url.base + '/' + session + '/xhr_send';\n}\n\nfunction getUniqueURL(url: string): string {\n var separator = url.indexOf('?') === -1 ? '?' : '&';\n return url + separator + 't=' + +new Date() + '&n=' + autoIncrement++;\n}\n\nfunction replaceHost(url: string, hostname: string): string {\n var urlParts = /(https?:\\/\\/)([^\\/:]+)((\\/|:)?.*)/.exec(url);\n return urlParts[1] + hostname + urlParts[3];\n}\n\nfunction randomNumber(max: number): number {\n return Runtime.randomInt(max);\n}\n\nfunction randomString(length: number): string {\n var result = [];\n\n for (var i = 0; i < length; i++) {\n result.push(randomNumber(32).toString(32));\n }\n\n return result.join('');\n}\n\nexport default HTTPSocket;\n","enum TimelineLevel {\n ERROR = 3,\n INFO = 6,\n DEBUG = 7\n}\n\nexport default TimelineLevel;\n","import SocketHooks from './socket_hooks';\nimport HTTPSocket from './http_socket';\n\nvar hooks: SocketHooks = {\n getReceiveURL: function(url, session) {\n return url.base + '/' + session + '/xhr_streaming' + url.queryString;\n },\n onHeartbeat: function(socket) {\n socket.sendRaw('[]');\n },\n sendHeartbeat: function(socket) {\n socket.sendRaw('[]');\n },\n onFinished: function(socket, status) {\n socket.onClose(1006, 'Connection interrupted (' + status + ')', false);\n }\n};\n\nexport default hooks;\n","import SocketHooks from './socket_hooks';\nimport URLLocation from './url_location';\nimport HTTPSocket from './http_socket';\n\nvar hooks: SocketHooks = {\n getReceiveURL: function(url: URLLocation, session: string): string {\n return url.base + '/' + session + '/xhr' + url.queryString;\n },\n onHeartbeat: function() {\n // next HTTP request will reset server's activity timer\n },\n sendHeartbeat: function(socket) {\n socket.sendRaw('[]');\n },\n onFinished: function(socket, status) {\n if (status === 200) {\n socket.reconnect();\n } else {\n socket.onClose(1006, 'Connection interrupted (' + status + ')', false);\n }\n }\n};\n\nexport default hooks;\n","import HTTPRequest from 'core/http/http_request';\nimport RequestHooks from 'core/http/request_hooks';\nimport Ajax from 'core/http/ajax';\nimport Runtime from 'runtime';\n\nvar hooks: RequestHooks = {\n getRequest: function(socket: HTTPRequest): Ajax {\n var Constructor = Runtime.getXHRAPI();\n var xhr = new Constructor();\n xhr.onreadystatechange = xhr.onprogress = function() {\n switch (xhr.readyState) {\n case 3:\n if (xhr.responseText && xhr.responseText.length > 0) {\n socket.onChunk(xhr.status, xhr.responseText);\n }\n break;\n case 4:\n // this happens only on errors, never after calling close\n if (xhr.responseText && xhr.responseText.length > 0) {\n socket.onChunk(xhr.status, xhr.responseText);\n }\n socket.emit('finished', xhr.status);\n socket.close();\n break;\n }\n };\n return xhr;\n },\n abortRequest: function(xhr: Ajax) {\n xhr.onreadystatechange = null;\n xhr.abort();\n }\n};\n\nexport default hooks;\n","import HTTPRequest from 'core/http/http_request';\nimport HTTPSocket from 'core/http/http_socket';\nimport SocketHooks from 'core/http/socket_hooks';\nimport RequestHooks from 'core/http/request_hooks';\nimport streamingHooks from 'core/http/http_streaming_socket';\nimport pollingHooks from 'core/http/http_polling_socket';\nimport xhrHooks from './http_xhr_request';\nimport HTTPFactory from 'core/http/http_factory';\n\nvar HTTP: HTTPFactory = {\n createStreamingSocket(url: string): HTTPSocket {\n return this.createSocket(streamingHooks, url);\n },\n\n createPollingSocket(url: string): HTTPSocket {\n return this.createSocket(pollingHooks, url);\n },\n\n createSocket(hooks: SocketHooks, url: string): HTTPSocket {\n return new HTTPSocket(hooks, url);\n },\n\n createXHR(method: string, url: string): HTTPRequest {\n return this.createRequest(xhrHooks, method, url);\n },\n\n createRequest(hooks: RequestHooks, method: string, url: string): HTTPRequest {\n return new HTTPRequest(hooks, method, url);\n }\n};\n\nexport default HTTP;\n","import xdrHooks from './http_xdomain_request';\nimport HTTP from 'isomorphic/http/http';\n\nHTTP.createXDR = function(method, url) {\n return this.createRequest(xdrHooks, method, url);\n};\n\nexport default HTTP;\n","import Browser from './browser';\nimport { Dependencies, DependenciesReceivers } from './dom/dependencies';\nimport { AuthTransport, AuthTransports } from 'core/auth/auth_transports';\nimport xhrAuth from 'isomorphic/auth/xhr_auth';\nimport jsonpAuth from './auth/jsonp_auth';\nimport TimelineTransport from 'core/timeline/timeline_transport';\nimport TimelineSender from 'core/timeline/timeline_sender';\nimport ScriptRequest from './dom/script_request';\nimport JSONPRequest from './dom/jsonp_request';\nimport * as Collections from 'core/utils/collections';\nimport { ScriptReceivers } from './dom/script_receiver_factory';\nimport jsonpTimeline from './timeline/jsonp_timeline';\nimport Transports from './transports/transports';\nimport Ajax from 'core/http/ajax';\nimport { Network } from './net_info';\nimport getDefaultStrategy from './default_strategy';\nimport transportConnectionInitializer from './transports/transport_connection_initializer';\nimport HTTPFactory from './http/http';\nimport HTTPRequest from 'core/http/http_request';\n\nvar Runtime: Browser = {\n // for jsonp auth\n nextAuthCallbackID: 1,\n auth_callbacks: {},\n ScriptReceivers,\n DependenciesReceivers,\n getDefaultStrategy,\n Transports,\n transportConnectionInitializer,\n HTTPFactory,\n\n TimelineTransport: jsonpTimeline,\n\n getXHRAPI() {\n return window.XMLHttpRequest;\n },\n\n getWebSocketAPI() {\n return window.WebSocket || window.MozWebSocket;\n },\n\n setup(PusherClass): void {\n (window).Pusher = PusherClass; // JSONp requires Pusher to be in the global scope.\n var initializeOnDocumentBody = () => {\n this.onDocumentBody(PusherClass.ready);\n };\n if (!(window).JSON) {\n Dependencies.load('json2', {}, initializeOnDocumentBody);\n } else {\n initializeOnDocumentBody();\n }\n },\n\n getDocument(): Document {\n return document;\n },\n\n getProtocol(): string {\n return this.getDocument().location.protocol;\n },\n\n getAuthorizers(): AuthTransports {\n return { ajax: xhrAuth, jsonp: jsonpAuth };\n },\n\n onDocumentBody(callback: Function) {\n if (document.body) {\n callback();\n } else {\n setTimeout(() => {\n this.onDocumentBody(callback);\n }, 0);\n }\n },\n\n createJSONPRequest(url: string, data: any): JSONPRequest {\n return new JSONPRequest(url, data);\n },\n\n createScriptRequest(src: string): ScriptRequest {\n return new ScriptRequest(src);\n },\n\n getLocalStorage() {\n try {\n return window.localStorage;\n } catch (e) {\n return undefined;\n }\n },\n\n createXHR(): Ajax {\n if (this.getXHRAPI()) {\n return this.createXMLHttpRequest();\n } else {\n return this.createMicrosoftXHR();\n }\n },\n\n createXMLHttpRequest(): Ajax {\n var Constructor = this.getXHRAPI();\n return new Constructor();\n },\n\n createMicrosoftXHR(): Ajax {\n return new ActiveXObject('Microsoft.XMLHTTP');\n },\n\n getNetwork() {\n return Network;\n },\n\n createWebSocket(url: string): any {\n var Constructor = this.getWebSocketAPI();\n return new Constructor(url);\n },\n\n createSocketRequest(method: string, url: string): HTTPRequest {\n if (this.isXHRSupported()) {\n return this.HTTPFactory.createXHR(method, url);\n } else if (this.isXDRSupported(url.indexOf('https:') === 0)) {\n return this.HTTPFactory.createXDR(method, url);\n } else {\n throw 'Cross-origin HTTP requests are not supported';\n }\n },\n\n isXHRSupported(): boolean {\n var Constructor = this.getXHRAPI();\n return (\n Boolean(Constructor) && new Constructor().withCredentials !== undefined\n );\n },\n\n isXDRSupported(useTLS?: boolean): boolean {\n var protocol = useTLS ? 'https:' : 'http:';\n var documentProtocol = this.getProtocol();\n return (\n Boolean(window['XDomainRequest']) && documentProtocol === protocol\n );\n },\n\n addUnloadListener(listener: any) {\n if (window.addEventListener !== undefined) {\n window.addEventListener('unload', listener, false);\n } else if (window.attachEvent !== undefined) {\n window.attachEvent('onunload', listener);\n }\n },\n\n removeUnloadListener(listener: any) {\n if (window.addEventListener !== undefined) {\n window.removeEventListener('unload', listener, false);\n } else if (window.detachEvent !== undefined) {\n window.detachEvent('onunload', listener);\n }\n },\n\n randomInt(max: number): number {\n /**\n * Return values in the range of [0, 1[\n */\n const random = function() {\n const crypto = window.crypto || window['msCrypto'];\n const random = crypto.getRandomValues(new Uint32Array(1))[0];\n\n return random / 2 ** 32;\n };\n\n return Math.floor(random() * max);\n }\n};\n\nexport default Runtime;\n","import { Dependencies } from '../dom/dependencies';\n\n/** Initializes the transport.\n *\n * Fetches resources if needed and then transitions to initialized.\n */\nexport default function() {\n var self = this;\n\n self.timeline.info(\n self.buildTimelineMessage({\n transport: self.name + (self.options.useTLS ? 's' : '')\n })\n );\n\n if (self.hooks.isInitialized()) {\n self.changeState('initialized');\n } else if (self.hooks.file) {\n self.changeState('initializing');\n Dependencies.load(\n self.hooks.file,\n { useTLS: self.options.useTLS },\n function(error, callback) {\n if (self.hooks.isInitialized()) {\n self.changeState('initialized');\n callback(true);\n } else {\n if (error) {\n self.onError(error);\n }\n self.onClose();\n callback(false);\n }\n }\n );\n } else {\n self.onClose();\n }\n}\n","import * as Collections from '../utils/collections';\nimport Util from '../util';\nimport { default as Level } from './level';\n\nexport interface TimelineOptions {\n level?: Level;\n limit?: number;\n version?: string;\n cluster?: string;\n features?: string[];\n params?: any;\n}\n\nexport default class Timeline {\n key: string;\n session: number;\n events: any[];\n options: TimelineOptions;\n sent: number;\n uniqueID: number;\n\n constructor(key: string, session: number, options: TimelineOptions) {\n this.key = key;\n this.session = session;\n this.events = [];\n this.options = options || {};\n this.sent = 0;\n this.uniqueID = 0;\n }\n\n log(level, event) {\n if (level <= this.options.level) {\n this.events.push(\n Collections.extend({}, event, { timestamp: Util.now() })\n );\n if (this.options.limit && this.events.length > this.options.limit) {\n this.events.shift();\n }\n }\n }\n\n error(event) {\n this.log(Level.ERROR, event);\n }\n\n info(event) {\n this.log(Level.INFO, event);\n }\n\n debug(event) {\n this.log(Level.DEBUG, event);\n }\n\n isEmpty() {\n return this.events.length === 0;\n }\n\n send(sendfn, callback) {\n var data = Collections.extend(\n {\n session: this.session,\n bundle: this.sent + 1,\n key: this.key,\n lib: 'js',\n version: this.options.version,\n cluster: this.options.cluster,\n features: this.options.features,\n timeline: this.events\n },\n this.options.params\n );\n\n this.events = [];\n sendfn(data, (error, result) => {\n if (!error) {\n this.sent++;\n }\n if (callback) {\n callback(error, result);\n }\n });\n\n return true;\n }\n\n generateUniqueID(): number {\n this.uniqueID++;\n return this.uniqueID;\n }\n}\n","import Factory from '../utils/factory';\nimport Util from '../util';\nimport * as Errors from '../errors';\nimport * as Collections from '../utils/collections';\nimport Strategy from './strategy';\nimport Transport from '../transports/transport';\nimport StrategyOptions from './strategy_options';\nimport Handshake from '../connection/handshake';\n\n/** Provides a strategy interface for transports.\n *\n * @param {String} name\n * @param {Number} priority\n * @param {Class} transport\n * @param {Object} options\n */\nexport default class TransportStrategy implements Strategy {\n name: string;\n priority: number;\n transport: Transport;\n options: StrategyOptions;\n\n constructor(\n name: string,\n priority: number,\n transport: Transport,\n options: StrategyOptions\n ) {\n this.name = name;\n this.priority = priority;\n this.transport = transport;\n this.options = options || {};\n }\n\n /** Returns whether the transport is supported in the browser.\n *\n * @returns {Boolean}\n */\n isSupported(): boolean {\n return this.transport.isSupported({\n useTLS: this.options.useTLS\n });\n }\n\n /** Launches a connection attempt and returns a strategy runner.\n *\n * @param {Function} callback\n * @return {Object} strategy runner\n */\n connect(minPriority: number, callback: Function) {\n if (!this.isSupported()) {\n return failAttempt(new Errors.UnsupportedStrategy(), callback);\n } else if (this.priority < minPriority) {\n return failAttempt(new Errors.TransportPriorityTooLow(), callback);\n }\n\n var connected = false;\n var transport = this.transport.createConnection(\n this.name,\n this.priority,\n this.options.key,\n this.options\n );\n var handshake = null;\n\n var onInitialized = function() {\n transport.unbind('initialized', onInitialized);\n transport.connect();\n };\n var onOpen = function() {\n handshake = Factory.createHandshake(transport, function(result) {\n connected = true;\n unbindListeners();\n callback(null, result);\n });\n };\n var onError = function(error) {\n unbindListeners();\n callback(error);\n };\n var onClosed = function() {\n unbindListeners();\n var serializedTransport;\n\n // The reason for this try/catch block is that on React Native\n // the WebSocket object is circular. Therefore transport.socket will\n // throw errors upon stringification. Collections.safeJSONStringify\n // discards circular references when serializing.\n serializedTransport = Collections.safeJSONStringify(transport);\n callback(new Errors.TransportClosed(serializedTransport));\n };\n\n var unbindListeners = function() {\n transport.unbind('initialized', onInitialized);\n transport.unbind('open', onOpen);\n transport.unbind('error', onError);\n transport.unbind('closed', onClosed);\n };\n\n transport.bind('initialized', onInitialized);\n transport.bind('open', onOpen);\n transport.bind('error', onError);\n transport.bind('closed', onClosed);\n\n // connect will be called automatically after initialization\n transport.initialize();\n\n return {\n abort: () => {\n if (connected) {\n return;\n }\n unbindListeners();\n if (handshake) {\n handshake.close();\n } else {\n transport.close();\n }\n },\n forceMinPriority: p => {\n if (connected) {\n return;\n }\n if (this.priority < p) {\n if (handshake) {\n handshake.close();\n } else {\n transport.close();\n }\n }\n }\n };\n }\n}\n\nfunction failAttempt(error: Error, callback: Function) {\n Util.defer(function() {\n callback(error);\n });\n return {\n abort: function() {},\n forceMinPriority: function() {}\n };\n}\n","import * as Collections from '../utils/collections';\nimport Util from '../util';\nimport TransportManager from '../transports/transport_manager';\nimport * as Errors from '../errors';\nimport Strategy from './strategy';\nimport TransportStrategy from './transport_strategy';\nimport StrategyOptions from '../strategies/strategy_options';\nimport { Config } from '../config';\nimport Runtime from 'runtime';\n\nconst { Transports } = Runtime;\n\nexport var defineTransport = function(\n config: Config,\n name: string,\n type: string,\n priority: number,\n options: StrategyOptions,\n manager?: TransportManager\n): Strategy {\n var transportClass = Transports[type];\n if (!transportClass) {\n throw new Errors.UnsupportedTransport(type);\n }\n\n var enabled =\n (!config.enabledTransports ||\n Collections.arrayIndexOf(config.enabledTransports, name) !== -1) &&\n (!config.disabledTransports ||\n Collections.arrayIndexOf(config.disabledTransports, name) === -1);\n\n var transport;\n if (enabled) {\n options = Object.assign(\n { ignoreNullOrigin: config.ignoreNullOrigin },\n options\n );\n\n transport = new TransportStrategy(\n name,\n priority,\n manager ? manager.getAssistant(transportClass) : transportClass,\n options\n );\n } else {\n transport = UnsupportedStrategy;\n }\n\n return transport;\n};\n\nvar UnsupportedStrategy: Strategy = {\n isSupported: function() {\n return false;\n },\n connect: function(_, callback) {\n var deferred = Util.defer(function() {\n callback(new Errors.UnsupportedStrategy());\n });\n return {\n abort: function() {\n deferred.ensureAborted();\n },\n forceMinPriority: function() {}\n };\n }\n};\n","import {\n UserAuthenticationCallback,\n InternalAuthOptions,\n UserAuthenticationHandler,\n UserAuthenticationRequestParams,\n AuthRequestType\n} from './options';\n\nimport Runtime from 'runtime';\n\nconst composeChannelQuery = (\n params: UserAuthenticationRequestParams,\n authOptions: InternalAuthOptions\n) => {\n var query = 'socket_id=' + encodeURIComponent(params.socketId);\n\n for (var key in authOptions.params) {\n query +=\n '&' +\n encodeURIComponent(key) +\n '=' +\n encodeURIComponent(authOptions.params[key]);\n }\n\n if (authOptions.paramsProvider != null) {\n let dynamicParams = authOptions.paramsProvider();\n for (var key in dynamicParams) {\n query +=\n '&' +\n encodeURIComponent(key) +\n '=' +\n encodeURIComponent(dynamicParams[key]);\n }\n }\n\n return query;\n};\n\nconst UserAuthenticator = (\n authOptions: InternalAuthOptions\n): UserAuthenticationHandler => {\n if (typeof Runtime.getAuthorizers()[authOptions.transport] === 'undefined') {\n throw `'${authOptions.transport}' is not a recognized auth transport`;\n }\n\n return (\n params: UserAuthenticationRequestParams,\n callback: UserAuthenticationCallback\n ) => {\n const query = composeChannelQuery(params, authOptions);\n\n Runtime.getAuthorizers()[authOptions.transport](\n Runtime,\n query,\n authOptions,\n AuthRequestType.UserAuthentication,\n callback\n );\n };\n};\n\nexport default UserAuthenticator;\n","import {\n AuthRequestType,\n InternalAuthOptions,\n ChannelAuthorizationHandler,\n ChannelAuthorizationRequestParams,\n ChannelAuthorizationCallback\n} from './options';\n\nimport Runtime from 'runtime';\n\nconst composeChannelQuery = (\n params: ChannelAuthorizationRequestParams,\n authOptions: InternalAuthOptions\n) => {\n var query = 'socket_id=' + encodeURIComponent(params.socketId);\n\n query += '&channel_name=' + encodeURIComponent(params.channelName);\n\n for (var key in authOptions.params) {\n query +=\n '&' +\n encodeURIComponent(key) +\n '=' +\n encodeURIComponent(authOptions.params[key]);\n }\n\n if (authOptions.paramsProvider != null) {\n let dynamicParams = authOptions.paramsProvider();\n for (var key in dynamicParams) {\n query +=\n '&' +\n encodeURIComponent(key) +\n '=' +\n encodeURIComponent(dynamicParams[key]);\n }\n }\n\n return query;\n};\n\nconst ChannelAuthorizer = (\n authOptions: InternalAuthOptions\n): ChannelAuthorizationHandler => {\n if (typeof Runtime.getAuthorizers()[authOptions.transport] === 'undefined') {\n throw `'${authOptions.transport}' is not a recognized auth transport`;\n }\n\n return (\n params: ChannelAuthorizationRequestParams,\n callback: ChannelAuthorizationCallback\n ) => {\n const query = composeChannelQuery(params, authOptions);\n\n Runtime.getAuthorizers()[authOptions.transport](\n Runtime,\n query,\n authOptions,\n AuthRequestType.ChannelAuthorization,\n callback\n );\n };\n};\n\nexport default ChannelAuthorizer;\n","import Channel from '../channels/channel';\nimport {\n ChannelAuthorizationCallback,\n ChannelAuthorizationHandler,\n ChannelAuthorizationRequestParams,\n InternalAuthOptions\n} from './options';\n\nexport interface DeprecatedChannelAuthorizer {\n authorize(socketId: string, callback: ChannelAuthorizationCallback): void;\n}\n\nexport interface ChannelAuthorizerGenerator {\n (\n channel: Channel,\n options: DeprecatedAuthorizerOptions\n ): DeprecatedChannelAuthorizer;\n}\n\nexport interface DeprecatedAuthOptions {\n params?: any;\n headers?: any;\n}\n\nexport interface DeprecatedAuthorizerOptions {\n authTransport: 'ajax' | 'jsonp';\n authEndpoint: string;\n auth?: DeprecatedAuthOptions;\n}\n\nexport const ChannelAuthorizerProxy = (\n pusher,\n authOptions: InternalAuthOptions,\n channelAuthorizerGenerator: ChannelAuthorizerGenerator\n): ChannelAuthorizationHandler => {\n const deprecatedAuthorizerOptions: DeprecatedAuthorizerOptions = {\n authTransport: authOptions.transport,\n authEndpoint: authOptions.endpoint,\n auth: {\n params: authOptions.params,\n headers: authOptions.headers\n }\n };\n return (\n params: ChannelAuthorizationRequestParams,\n callback: ChannelAuthorizationCallback\n ) => {\n const channel = pusher.channel(params.channelName);\n // This line creates a new channel authorizer every time.\n // In the past, this was only done once per channel and reused.\n // We can do that again if we want to keep this behavior intact.\n const channelAuthorizer: DeprecatedChannelAuthorizer = channelAuthorizerGenerator(\n channel,\n deprecatedAuthorizerOptions\n );\n channelAuthorizer.authorize(params.socketId, callback);\n };\n};\n","import { Options } from './options';\nimport Defaults from './defaults';\nimport {\n ChannelAuthorizationHandler,\n UserAuthenticationHandler,\n ChannelAuthorizationOptions\n} from './auth/options';\nimport UserAuthenticator from './auth/user_authenticator';\nimport ChannelAuthorizer from './auth/channel_authorizer';\nimport { ChannelAuthorizerProxy } from './auth/deprecated_channel_authorizer';\nimport Runtime from 'runtime';\nimport * as nacl from 'tweetnacl';\n\nexport type AuthTransport = 'ajax' | 'jsonp';\nexport type Transport =\n | 'ws'\n | 'wss'\n | 'xhr_streaming'\n | 'xhr_polling'\n | 'sockjs';\n\nexport interface Config {\n // these are all 'required' config parameters, it's not necessary for the user\n // to set them, but they have configured defaults.\n activityTimeout: number;\n enableStats: boolean;\n httpHost: string;\n httpPath: string;\n httpPort: number;\n httpsPort: number;\n pongTimeout: number;\n statsHost: string;\n unavailableTimeout: number;\n useTLS: boolean;\n wsHost: string;\n wsPath: string;\n wsPort: number;\n wssPort: number;\n userAuthenticator: UserAuthenticationHandler;\n channelAuthorizer: ChannelAuthorizationHandler;\n\n // these are all optional parameters or overrrides. The customer can set these\n // but it's not strictly necessary\n forceTLS?: boolean;\n cluster?: string;\n disabledTransports?: Transport[];\n enabledTransports?: Transport[];\n ignoreNullOrigin?: boolean;\n nacl?: nacl;\n timelineParams?: any;\n}\n\n// getConfig mainly sets the defaults for the options that are not provided\nexport function getConfig(opts: Options, pusher): Config {\n let config: Config = {\n activityTimeout: opts.activityTimeout || Defaults.activityTimeout,\n cluster: opts.cluster,\n httpPath: opts.httpPath || Defaults.httpPath,\n httpPort: opts.httpPort || Defaults.httpPort,\n httpsPort: opts.httpsPort || Defaults.httpsPort,\n pongTimeout: opts.pongTimeout || Defaults.pongTimeout,\n statsHost: opts.statsHost || Defaults.stats_host,\n unavailableTimeout: opts.unavailableTimeout || Defaults.unavailableTimeout,\n wsPath: opts.wsPath || Defaults.wsPath,\n wsPort: opts.wsPort || Defaults.wsPort,\n wssPort: opts.wssPort || Defaults.wssPort,\n\n enableStats: getEnableStatsConfig(opts),\n httpHost: getHttpHost(opts),\n useTLS: shouldUseTLS(opts),\n wsHost: getWebsocketHost(opts),\n\n userAuthenticator: buildUserAuthenticator(opts),\n channelAuthorizer: buildChannelAuthorizer(opts, pusher)\n };\n\n if ('disabledTransports' in opts)\n config.disabledTransports = opts.disabledTransports;\n if ('enabledTransports' in opts)\n config.enabledTransports = opts.enabledTransports;\n if ('ignoreNullOrigin' in opts)\n config.ignoreNullOrigin = opts.ignoreNullOrigin;\n if ('timelineParams' in opts) config.timelineParams = opts.timelineParams;\n if ('nacl' in opts) {\n config.nacl = opts.nacl;\n }\n\n return config;\n}\n\nfunction getHttpHost(opts: Options): string {\n if (opts.httpHost) {\n return opts.httpHost;\n }\n if (opts.cluster) {\n return `sockjs-${opts.cluster}.pusher.com`;\n }\n return Defaults.httpHost;\n}\n\nfunction getWebsocketHost(opts: Options): string {\n if (opts.wsHost) {\n return opts.wsHost;\n }\n return getWebsocketHostFromCluster(opts.cluster);\n}\n\nfunction getWebsocketHostFromCluster(cluster: string): string {\n return `ws-${cluster}.pusher.com`;\n}\n\nfunction shouldUseTLS(opts: Options): boolean {\n if (Runtime.getProtocol() === 'https:') {\n return true;\n } else if (opts.forceTLS === false) {\n return false;\n }\n return true;\n}\n\n// if enableStats is set take the value\n// if disableStats is set take the inverse\n// otherwise default to false\nfunction getEnableStatsConfig(opts: Options): boolean {\n if ('enableStats' in opts) {\n return opts.enableStats;\n }\n if ('disableStats' in opts) {\n return !opts.disableStats;\n }\n return false;\n}\n\nfunction buildUserAuthenticator(opts: Options): UserAuthenticationHandler {\n const userAuthentication = {\n ...Defaults.userAuthentication,\n ...opts.userAuthentication\n };\n if (\n 'customHandler' in userAuthentication &&\n userAuthentication['customHandler'] != null\n ) {\n return userAuthentication['customHandler'];\n }\n\n return UserAuthenticator(userAuthentication);\n}\n\nfunction buildChannelAuth(opts: Options, pusher): ChannelAuthorizationOptions {\n let channelAuthorization: ChannelAuthorizationOptions;\n if ('channelAuthorization' in opts) {\n channelAuthorization = {\n ...Defaults.channelAuthorization,\n ...opts.channelAuthorization\n };\n } else {\n channelAuthorization = {\n transport: opts.authTransport || Defaults.authTransport,\n endpoint: opts.authEndpoint || Defaults.authEndpoint\n };\n if ('auth' in opts) {\n if ('params' in opts.auth) channelAuthorization.params = opts.auth.params;\n if ('headers' in opts.auth)\n channelAuthorization.headers = opts.auth.headers;\n }\n if ('authorizer' in opts)\n channelAuthorization.customHandler = ChannelAuthorizerProxy(\n pusher,\n channelAuthorization,\n opts.authorizer\n );\n }\n return channelAuthorization;\n}\n\nfunction buildChannelAuthorizer(\n opts: Options,\n pusher\n): ChannelAuthorizationHandler {\n const channelAuthorization = buildChannelAuth(opts, pusher);\n if (\n 'customHandler' in channelAuthorization &&\n channelAuthorization['customHandler'] != null\n ) {\n return channelAuthorization['customHandler'];\n }\n\n return ChannelAuthorizer(channelAuthorization);\n}\n","import Logger from './logger';\nimport Pusher from './pusher';\nimport EventsDispatcher from './events/dispatcher';\n\nexport default class WatchlistFacade extends EventsDispatcher {\n private pusher: Pusher;\n\n public constructor(pusher: Pusher) {\n super(function(eventName, data) {\n Logger.debug(`No callbacks on watchlist events for ${eventName}`);\n });\n\n this.pusher = pusher;\n this.bindWatchlistInternalEvent();\n }\n\n handleEvent(pusherEvent) {\n pusherEvent.data.events.forEach(watchlistEvent => {\n this.emit(watchlistEvent.name, watchlistEvent);\n });\n }\n\n private bindWatchlistInternalEvent() {\n this.pusher.connection.bind('message', pusherEvent => {\n var eventName = pusherEvent.event;\n if (eventName === 'pusher_internal:watchlist_events') {\n this.handleEvent(pusherEvent);\n }\n });\n }\n}\n","function flatPromise() {\n let resolve, reject;\n const promise = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n}\n\nexport default flatPromise;\n","import Pusher from './pusher';\nimport Logger from './logger';\nimport {\n UserAuthenticationData,\n UserAuthenticationCallback\n} from './auth/options';\nimport Channel from './channels/channel';\nimport WatchlistFacade from './watchlist';\nimport EventsDispatcher from './events/dispatcher';\nimport flatPromise from './utils/flat_promise';\n\nexport default class UserFacade extends EventsDispatcher {\n pusher: Pusher;\n signin_requested: boolean = false;\n user_data: any = null;\n serverToUserChannel: Channel = null;\n signinDonePromise: Promise = null;\n watchlist: WatchlistFacade;\n private _signinDoneResolve: Function = null;\n\n public constructor(pusher: Pusher) {\n super(function(eventName, data) {\n Logger.debug('No callbacks on user for ' + eventName);\n });\n this.pusher = pusher;\n this.pusher.connection.bind('state_change', ({ previous, current }) => {\n if (previous !== 'connected' && current === 'connected') {\n this._signin();\n }\n if (previous === 'connected' && current !== 'connected') {\n this._cleanup();\n this._newSigninPromiseIfNeeded();\n }\n });\n\n this.watchlist = new WatchlistFacade(pusher);\n\n this.pusher.connection.bind('message', event => {\n var eventName = event.event;\n if (eventName === 'pusher:signin_success') {\n this._onSigninSuccess(event.data);\n }\n if (\n this.serverToUserChannel &&\n this.serverToUserChannel.name === event.channel\n ) {\n this.serverToUserChannel.handleEvent(event);\n }\n });\n }\n\n public signin() {\n if (this.signin_requested) {\n return;\n }\n\n this.signin_requested = true;\n this._signin();\n }\n\n private _signin() {\n if (!this.signin_requested) {\n return;\n }\n\n this._newSigninPromiseIfNeeded();\n\n if (this.pusher.connection.state !== 'connected') {\n // Signin will be attempted when the connection is connected\n return;\n }\n\n this.pusher.config.userAuthenticator(\n {\n socketId: this.pusher.connection.socket_id\n },\n this._onAuthorize\n );\n }\n\n private _onAuthorize: UserAuthenticationCallback = (\n err,\n authData: UserAuthenticationData\n ) => {\n if (err) {\n Logger.warn(`Error during signin: ${err}`);\n this._cleanup();\n return;\n }\n\n this.pusher.send_event('pusher:signin', {\n auth: authData.auth,\n user_data: authData.user_data\n });\n\n // Later when we get pusher:singin_success event, the user will be marked as signed in\n };\n\n private _onSigninSuccess(data: any) {\n try {\n this.user_data = JSON.parse(data.user_data);\n } catch (e) {\n Logger.error(`Failed parsing user data after signin: ${data.user_data}`);\n this._cleanup();\n return;\n }\n\n if (typeof this.user_data.id !== 'string' || this.user_data.id === '') {\n Logger.error(\n `user_data doesn't contain an id. user_data: ${this.user_data}`\n );\n this._cleanup();\n return;\n }\n\n // Signin succeeded\n this._signinDoneResolve();\n this._subscribeChannels();\n }\n\n private _subscribeChannels() {\n const ensure_subscribed = channel => {\n if (channel.subscriptionPending && channel.subscriptionCancelled) {\n channel.reinstateSubscription();\n } else if (\n !channel.subscriptionPending &&\n this.pusher.connection.state === 'connected'\n ) {\n channel.subscribe();\n }\n };\n\n this.serverToUserChannel = new Channel(\n `#server-to-user-${this.user_data.id}`,\n this.pusher\n );\n this.serverToUserChannel.bind_global((eventName, data) => {\n if (\n eventName.indexOf('pusher_internal:') === 0 ||\n eventName.indexOf('pusher:') === 0\n ) {\n // ignore internal events\n return;\n }\n this.emit(eventName, data);\n });\n ensure_subscribed(this.serverToUserChannel);\n }\n\n private _cleanup() {\n this.user_data = null;\n if (this.serverToUserChannel) {\n this.serverToUserChannel.unbind_all();\n this.serverToUserChannel.disconnect();\n this.serverToUserChannel = null;\n }\n\n if (this.signin_requested) {\n // If signin is in progress and cleanup is called,\n // Mark the current signin process as done.\n this._signinDoneResolve();\n }\n }\n\n private _newSigninPromiseIfNeeded() {\n if (!this.signin_requested) {\n return;\n }\n\n // If there is a promise and it is not resolved, return without creating a new one.\n if (this.signinDonePromise && !(this.signinDonePromise as any).done) {\n return;\n }\n\n // This promise is never rejected.\n // It gets resolved when the signin process is done whether it failed or succeeded\n const { promise, resolve, reject: _ } = flatPromise();\n (promise as any).done = false;\n const setDone = () => {\n (promise as any).done = true;\n };\n promise.then(setDone).catch(setDone);\n this.signinDonePromise = promise;\n this._signinDoneResolve = resolve;\n }\n}\n","import AbstractRuntime from '../runtimes/interface';\nimport Runtime from 'runtime';\nimport Util from './util';\nimport * as Collections from './utils/collections';\nimport Channels from './channels/channels';\nimport Channel from './channels/channel';\nimport { default as EventsDispatcher } from './events/dispatcher';\nimport Timeline from './timeline/timeline';\nimport TimelineSender from './timeline/timeline_sender';\nimport TimelineLevel from './timeline/level';\nimport { defineTransport } from './strategies/strategy_builder';\nimport ConnectionManager from './connection/connection_manager';\nimport ConnectionManagerOptions from './connection/connection_manager_options';\nimport { PeriodicTimer } from './utils/timers';\nimport Defaults from './defaults';\nimport * as DefaultConfig from './config';\nimport Logger from './logger';\nimport Factory from './utils/factory';\nimport UrlStore from 'core/utils/url_store';\nimport { Options, validateOptions } from './options';\nimport { Config, getConfig } from './config';\nimport StrategyOptions from './strategies/strategy_options';\nimport UserFacade from './user';\n\nexport default class Pusher {\n /* STATIC PROPERTIES */\n static instances: Pusher[] = [];\n static isReady: boolean = false;\n static logToConsole: boolean = false;\n\n // for jsonp\n static Runtime: AbstractRuntime = Runtime;\n static ScriptReceivers: any = (Runtime).ScriptReceivers;\n static DependenciesReceivers: any = (Runtime).DependenciesReceivers;\n static auth_callbacks: any = (Runtime).auth_callbacks;\n\n static ready() {\n Pusher.isReady = true;\n for (var i = 0, l = Pusher.instances.length; i < l; i++) {\n Pusher.instances[i].connect();\n }\n }\n\n static log: (message: any) => void;\n\n private static getClientFeatures(): string[] {\n return Collections.keys(\n Collections.filterObject({ ws: Runtime.Transports.ws }, function(t) {\n return t.isSupported({});\n })\n );\n }\n\n /* INSTANCE PROPERTIES */\n key: string;\n config: Config;\n channels: Channels;\n global_emitter: EventsDispatcher;\n sessionID: number;\n timeline: Timeline;\n timelineSender: TimelineSender;\n connection: ConnectionManager;\n timelineSenderTimer: PeriodicTimer;\n user: UserFacade;\n constructor(app_key: string, options: Options) {\n checkAppKey(app_key);\n validateOptions(options);\n this.key = app_key;\n this.config = getConfig(options, this);\n\n this.channels = Factory.createChannels();\n this.global_emitter = new EventsDispatcher();\n this.sessionID = Runtime.randomInt(1000000000);\n\n this.timeline = new Timeline(this.key, this.sessionID, {\n cluster: this.config.cluster,\n features: Pusher.getClientFeatures(),\n params: this.config.timelineParams || {},\n limit: 50,\n level: TimelineLevel.INFO,\n version: Defaults.VERSION\n });\n if (this.config.enableStats) {\n this.timelineSender = Factory.createTimelineSender(this.timeline, {\n host: this.config.statsHost,\n path: '/timeline/v2/' + Runtime.TimelineTransport.name\n });\n }\n\n var getStrategy = (options: StrategyOptions) => {\n return Runtime.getDefaultStrategy(this.config, options, defineTransport);\n };\n\n this.connection = Factory.createConnectionManager(this.key, {\n getStrategy: getStrategy,\n timeline: this.timeline,\n activityTimeout: this.config.activityTimeout,\n pongTimeout: this.config.pongTimeout,\n unavailableTimeout: this.config.unavailableTimeout,\n useTLS: Boolean(this.config.useTLS)\n });\n\n this.connection.bind('connected', () => {\n this.subscribeAll();\n if (this.timelineSender) {\n this.timelineSender.send(this.connection.isUsingTLS());\n }\n });\n\n this.connection.bind('message', event => {\n var eventName = event.event;\n var internal = eventName.indexOf('pusher_internal:') === 0;\n if (event.channel) {\n var channel = this.channel(event.channel);\n if (channel) {\n channel.handleEvent(event);\n }\n }\n // Emit globally [deprecated]\n if (!internal) {\n this.global_emitter.emit(event.event, event.data);\n }\n });\n this.connection.bind('connecting', () => {\n this.channels.disconnect();\n });\n this.connection.bind('disconnected', () => {\n this.channels.disconnect();\n });\n this.connection.bind('error', err => {\n Logger.warn(err);\n });\n\n Pusher.instances.push(this);\n this.timeline.info({ instances: Pusher.instances.length });\n\n this.user = new UserFacade(this);\n\n if (Pusher.isReady) {\n this.connect();\n }\n }\n\n channel(name: string): Channel {\n return this.channels.find(name);\n }\n\n allChannels(): Channel[] {\n return this.channels.all();\n }\n\n connect() {\n this.connection.connect();\n\n if (this.timelineSender) {\n if (!this.timelineSenderTimer) {\n var usingTLS = this.connection.isUsingTLS();\n var timelineSender = this.timelineSender;\n this.timelineSenderTimer = new PeriodicTimer(60000, function() {\n timelineSender.send(usingTLS);\n });\n }\n }\n }\n\n disconnect() {\n this.connection.disconnect();\n\n if (this.timelineSenderTimer) {\n this.timelineSenderTimer.ensureAborted();\n this.timelineSenderTimer = null;\n }\n }\n\n bind(event_name: string, callback: Function, context?: any): Pusher {\n this.global_emitter.bind(event_name, callback, context);\n return this;\n }\n\n unbind(event_name?: string, callback?: Function, context?: any): Pusher {\n this.global_emitter.unbind(event_name, callback, context);\n return this;\n }\n\n bind_global(callback: Function): Pusher {\n this.global_emitter.bind_global(callback);\n return this;\n }\n\n unbind_global(callback?: Function): Pusher {\n this.global_emitter.unbind_global(callback);\n return this;\n }\n\n unbind_all(callback?: Function): Pusher {\n this.global_emitter.unbind_all();\n return this;\n }\n\n subscribeAll() {\n var channelName;\n for (channelName in this.channels.channels) {\n if (this.channels.channels.hasOwnProperty(channelName)) {\n this.subscribe(channelName);\n }\n }\n }\n\n subscribe(channel_name: string) {\n var channel = this.channels.add(channel_name, this);\n if (channel.subscriptionPending && channel.subscriptionCancelled) {\n channel.reinstateSubscription();\n } else if (\n !channel.subscriptionPending &&\n this.connection.state === 'connected'\n ) {\n channel.subscribe();\n }\n return channel;\n }\n\n unsubscribe(channel_name: string) {\n var channel = this.channels.find(channel_name);\n if (channel && channel.subscriptionPending) {\n channel.cancelSubscription();\n } else {\n channel = this.channels.remove(channel_name);\n if (channel && channel.subscribed) {\n channel.unsubscribe();\n }\n }\n }\n\n send_event(event_name: string, data: any, channel?: string) {\n return this.connection.send_event(event_name, data, channel);\n }\n\n shouldUseTLS(): boolean {\n return this.config.useTLS;\n }\n\n signin() {\n this.user.signin();\n }\n}\n\nfunction checkAppKey(key) {\n if (key === null || key === undefined) {\n throw 'You must pass your app key when you instantiate Pusher.';\n }\n}\n\nRuntime.setup(Pusher);\n","import ConnectionManager from './connection/connection_manager';\nimport {\n ChannelAuthorizationOptions,\n UserAuthenticationOptions\n} from './auth/options';\nimport {\n ChannelAuthorizerGenerator,\n DeprecatedAuthOptions\n} from './auth/deprecated_channel_authorizer';\nimport { AuthTransport, Transport } from './config';\nimport * as nacl from 'tweetnacl';\nimport Logger from './logger';\n\nexport interface Options {\n activityTimeout?: number;\n\n auth?: DeprecatedAuthOptions; // DEPRECATED use channelAuthorization instead\n authEndpoint?: string; // DEPRECATED use channelAuthorization instead\n authTransport?: AuthTransport; // DEPRECATED use channelAuthorization instead\n authorizer?: ChannelAuthorizerGenerator; // DEPRECATED use channelAuthorization instead\n\n channelAuthorization?: ChannelAuthorizationOptions;\n userAuthentication?: UserAuthenticationOptions;\n\n cluster: string;\n enableStats?: boolean;\n disableStats?: boolean;\n disabledTransports?: Transport[];\n enabledTransports?: Transport[];\n forceTLS?: boolean;\n httpHost?: string;\n httpPath?: string;\n httpPort?: number;\n httpsPort?: number;\n ignoreNullOrigin?: boolean;\n nacl?: nacl;\n pongTimeout?: number;\n statsHost?: string;\n timelineParams?: any;\n unavailableTimeout?: number;\n wsHost?: string;\n wsPath?: string;\n wsPort?: number;\n wssPort?: number;\n}\n\nexport function validateOptions(options) {\n if (options == null) {\n throw 'You must pass an options object';\n }\n if (options.cluster == null) {\n throw 'Options object must provide a cluster';\n }\n if ('disableStats' in options) {\n Logger.warn(\n 'The disableStats option is deprecated in favor of enableStats'\n );\n }\n}\n"],"sourceRoot":""}