{"version":3,"sources":["webpack://Pusher/webpack/universalModuleDefinition","webpack://Pusher/webpack/bootstrap","webpack://Pusher/./node_modules/@stablelib/base64/base64.ts","webpack://Pusher/./node_modules/@stablelib/utf8/utf8.ts","webpack://Pusher/./src/core/pusher.js","webpack://Pusher/./src/runtimes/web/dom/script_receiver_factory.ts","webpack://Pusher/./src/core/defaults.ts","webpack://Pusher/./src/runtimes/web/dom/dependency_loader.ts","webpack://Pusher/./src/runtimes/web/dom/dependencies.ts","webpack://Pusher/./src/core/utils/url_store.ts","webpack://Pusher/./src/core/errors.ts","webpack://Pusher/./src/runtimes/isomorphic/auth/xhr_auth.ts","webpack://Pusher/./src/core/base64.ts","webpack://Pusher/./src/core/utils/timers/abstract_timer.ts","webpack://Pusher/./src/core/utils/timers/index.ts","webpack://Pusher/./src/core/util.ts","webpack://Pusher/./src/core/utils/collections.ts","webpack://Pusher/./src/core/logger.ts","webpack://Pusher/./src/runtimes/web/auth/jsonp_auth.ts","webpack://Pusher/./src/runtimes/web/dom/script_request.ts","webpack://Pusher/./src/runtimes/web/dom/jsonp_request.ts","webpack://Pusher/./src/runtimes/web/timeline/jsonp_timeline.ts","webpack://Pusher/./src/core/transports/url_schemes.ts","webpack://Pusher/./src/core/events/callback_registry.ts","webpack://Pusher/./src/core/events/dispatcher.ts","webpack://Pusher/./src/core/transports/transport_connection.ts","webpack://Pusher/./src/core/transports/transport.ts","webpack://Pusher/./src/runtimes/isomorphic/transports/transports.ts","webpack://Pusher/./src/runtimes/web/transports/transports.ts","webpack://Pusher/./src/runtimes/web/net_info.ts","webpack://Pusher/./src/core/transports/assistant_to_the_transport_manager.ts","webpack://Pusher/./src/core/connection/protocol/protocol.ts","webpack://Pusher/./src/core/connection/connection.ts","webpack://Pusher/./src/core/connection/handshake/index.ts","webpack://Pusher/./src/core/auth/pusher_authorizer.ts","webpack://Pusher/./src/core/timeline/timeline_sender.ts","webpack://Pusher/./src/core/channels/channel.ts","webpack://Pusher/./src/core/channels/private_channel.ts","webpack://Pusher/./src/core/channels/members.ts","webpack://Pusher/./src/core/channels/presence_channel.ts","webpack://Pusher/./src/core/channels/encrypted_channel.ts","webpack://Pusher/./src/core/connection/connection_manager.ts","webpack://Pusher/./src/core/channels/channels.ts","webpack://Pusher/./src/core/utils/factory.ts","webpack://Pusher/./src/core/transports/transport_manager.ts","webpack://Pusher/./src/core/strategies/sequential_strategy.ts","webpack://Pusher/./src/core/strategies/best_connected_ever_strategy.ts","webpack://Pusher/./src/core/strategies/cached_strategy.ts","webpack://Pusher/./src/core/strategies/delayed_strategy.ts","webpack://Pusher/./src/core/strategies/if_strategy.ts","webpack://Pusher/./src/core/strategies/first_connected_strategy.ts","webpack://Pusher/./src/runtimes/web/default_strategy.ts","webpack://Pusher/./src/core/http/state.ts","webpack://Pusher/./src/runtimes/web/http/http_xdomain_request.ts","webpack://Pusher/./src/core/http/http_request.ts","webpack://Pusher/./src/core/http/http_socket.ts","webpack://Pusher/./src/core/timeline/level.ts","webpack://Pusher/./src/core/http/http_streaming_socket.ts","webpack://Pusher/./src/core/http/http_polling_socket.ts","webpack://Pusher/./src/runtimes/isomorphic/http/http_xhr_request.ts","webpack://Pusher/./src/runtimes/isomorphic/http/http.ts","webpack://Pusher/./src/runtimes/web/http/http.ts","webpack://Pusher/./src/runtimes/web/runtime.ts","webpack://Pusher/./src/runtimes/web/transports/transport_connection_initializer.ts","webpack://Pusher/./src/core/timeline/timeline.ts","webpack://Pusher/./src/core/strategies/transport_strategy.ts","webpack://Pusher/./src/core/strategies/strategy_builder.ts","webpack://Pusher/./src/core/config.ts","webpack://Pusher/./src/core/pusher.ts"],"names":["root","factory","exports","module","define","amd","window","installedModules","__webpack_require__","moduleId","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","_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","Coder","stdCoder","URLSafeCoder","urlSafeCoder","INVALID_UTF8","arr","pos","chars","min","n1","n2","n3","push","join","default","prefix","lastId","callback","number","id","called","callbackWrapper","apply","arguments","remove","receiver","ScriptReceivers","ScriptReceiverFactory","VERSION","PROTOCOL","wsPort","wssPort","wsPath","httpHost","httpPort","httpsPort","httpPath","stats_host","authEndpoint","authTransport","activityTimeout","pongTimeout","unavailableTimeout","cluster","cdn_http","cdn_https","dependency_suffix","options","receivers","loading","load","self","request","createScriptRequest","getPath","error","callbacks","successCallback","wasSuccessful","cleanup","send","getRoot","protocol","getDocument","location","useTLS","replace","version","suffix","DependenciesReceivers","Dependencies","urlStore","baseUrl","urls","authenticationEndpoint","path","javascriptQuickStart","triggeringClientEvents","encryptedChannelSupport","fullUrl","url","urlObj","urlPrefix","msg","setPrototypeOf","status","context","socketId","xhr","headerName","createXHR","open","setRequestHeader","authOptions","headers","onreadystatechange","readyState","parsed","JSON","parse","responseText","e","HTTPAuthError","auth","composeQuery","b64chars","b64tab","charAt","cb_utob","cc","utob","u","cb_encode","ccc","padlen","ord","btoa","set","clear","delay","timer","isRunning","ensureAborted","clearTimeout","clearInterval","setTimeout","setInterval","now","Date","valueOf","defer","OneOffTimer","method","boundArguments","Array","slice","concat","extend","target","sources","extensions","constructor","stringify","safeJSONStringify","arrayIndexOf","array","item","nativeIndexOf","indexOf","objectApply","f","keys","_","map","filter","test","filterObject","Boolean","any","encodeParamsObject","encodeURIComponent","toString","buildQueryString","params","undefined","source","objects","paths","derez","nu","$ref","globalLog","message","console","log","debug","args","warn","globalLogWarn","globalLogError","defaultLoggingFunction","logToConsole","callbackName","nextAuthCallbackID","document","script","createElement","auth_callbacks","callback_name","src","head","getElementsByTagName","documentElement","insertBefore","firstChild","errorString","type","charset","addEventListener","onerror","onload","async","attachEvent","navigator","userAgent","errorScript","text","nextSibling","parentNode","removeChild","query","getAgent","sender","host","createJSONPRequest","getGenericURL","baseScheme","hostTLS","hostNonTLS","getGenericPath","queryString","ws","getInitial","http","sockjs","_callbacks","add","prefixedEventName","fn","names","removeCallback","removeAllCallbacks","binding","failThrough","global_callbacks","eventName","bind_global","unbind","unbind_global","unbind_all","emit","metadata","hooks","priority","initialize","transportConnectionInitializer","state","timeline","generateUniqueID","handlesActivityChecks","supportsPing","connect","socket","getSocket","onError","changeState","bindListeners","transport","close","ping","onOpen","beforeOpen","onopen","buildTimelineMessage","onClose","closeEvent","code","reason","wasClean","unbindListeners","onMessage","onActivity","onclose","onmessage","onactivity","info","cid","isSupported","environment","createConnection","WSTransport","isInitialized","getWebSocketAPI","createWebSocket","httpConfiguration","streamingConfiguration","HTTPFactory","createStreamingSocket","pollingConfiguration","createPollingSocket","xhrConfiguration","isXHRSupported","xhr_streaming","xhr_polling","SockJSTransport","file","SockJS","js_path","ignore_null_origin","ignoreNullOrigin","xdrConfiguration","isXDRSupported","XDRStreamingTransport","XDRPollingTransport","xdr_streaming","xdr_polling","isOnline","onLine","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","send_event","listeners","activity","closed","handleCloseEvent","listener","finish","getAuthorizers","authorize","PusherAuthorizer","authorizers","isEmpty","TimelineTransport","pusher","subscribed","subscriptionPending","subscriptionCancelled","trigger","disconnect","handleEvent","handleSubscriptionSucceededEvent","unsubscribe","subscribe","assign","channel_data","cancelSubscription","reinstateSubscription","createAuthorizer","config","reset","members","each","member","setMyID","myID","onSubscription","subscriptionData","presence","hash","count","me","addMember","memberData","user_info","removeMember","authData","channelData","handleInternalEvent","addedMember","removedMember","nacl","sharedSecret","handleEncryptedEvent","ciphertext","nonce","cipherText","secretbox","overheadLength","nonceLength","bytes","getDataToEmit","raw","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","createEncryptedChannel","errMsg","createPrivateChannel","createPresenceChannel","createChannel","all","values","find","createChannels","createConnectionManager","createTimelineSender","authorizer","createHandshake","createAssistantToTheTransportManager","livesLeft","lives","getAssistant","strategies","loop","failFast","timeout","timeoutLimit","minPriority","tryNextStrategy","tryStrategy","forceMinPriority","callbackBuilder","runners","rs","abortRunner","allRunnersFailed","aborted","transports","ttl","storage","getLocalStorage","serializedCache","getTransportCacheKey","flushTransportCache","fetchTransportCache","timestamp","cached","latency","startTimestamp","pop","cb","storeTransportCache","trueBranch","falseBranch","testSupportsStrategy","State","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","getRequest","xdr","XDomainRequest","ontimeout","onprogress","onChunk","abortRequest","start","payload","position","unloader","addUnloadListener","removeUnloadListener","chunk","advanceBuffer","isBufferTooLong","buffer","unreadData","endOfLinePosition","autoIncrement","getUniqueURL","separator","randomNumber","floor","random","TimelineLevel","session","randomString","parts","exec","base","getLocation","CONNECTING","openStream","sendRaw","sendHeartbeat","OPEN","createSocketRequest","reconnect","closeStream","CLOSED","onEvent","onHeartbeat","hostname","urlParts","stream","getReceiveURL","onFinished","getXHRAPI","createSocket","createRequest","getDefaultStrategy","Transports","XMLHttpRequest","WebSocket","MozWebSocket","setup","PusherClass","Pusher","initializeOnDocumentBody","onDocumentBody","ready","getProtocol","ajax","jsonp","body","localStorage","createXMLHttpRequest","createMicrosoftXHR","ActiveXObject","createXDR","Constructor","withCredentials","documentProtocol","removeEventListener","detachEvent","events","sent","uniqueID","level","limit","shift","ERROR","INFO","DEBUG","sendfn","bundle","lib","features","failAttempt","onInitialized","serializedTransport","transportClass","enabledTransports","disabledTransports","deferred","getHttpHost","opts","getWebsocketHost","getWebsocketHostFromCluster","shouldUseTLS","forceTLS","getEnableStatsConfig","enableStats","disableStats","app_key","checkAppKey","statsHost","timelineParams","global_emitter","sessionID","getClientFeatures","timelineSender","subscribeAll","internal","err","instances","isReady","allChannels","timelineSenderTimer","PeriodicTimer","event_name","channelName","channel_name","Runtime"],"mappings":";;;;;;;CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAgB,OAAID,IAEpBD,EAAa,OAAIC,IARnB,CASGK,QAAQ,WACX,O,YCTE,IAAIC,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUP,QAGnC,IAAIC,EAASI,EAAiBE,GAAY,CACzCC,EAAGD,EACHE,GAAG,EACHT,QAAS,IAUV,OANAU,EAAQH,GAAUI,KAAKV,EAAOD,QAASC,EAAQA,EAAOD,QAASM,GAG/DL,EAAOQ,GAAI,EAGJR,EAAOD,QA0Df,OArDAM,EAAoBM,EAAIF,EAGxBJ,EAAoBO,EAAIR,EAGxBC,EAAoBQ,EAAI,SAASd,EAASe,EAAMC,GAC3CV,EAAoBW,EAAEjB,EAASe,IAClCG,OAAOC,eAAenB,EAASe,EAA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,EAAAC,SAAmB,EACnB,EAAA7c,cAAwB,EAGxB,EAAAod,QAA2B,GAC3B,EAAA/mB,gBAA6B,GAASA,gBACtC,EAAA2C,sBAAmC,GAASA,sBAC5C,EAAAsH,eAA4B,GAASA,eAwN9C,EAlOA,GAAqB,gBA0OrB,GAAQ0Y,MAAM","file":"pusher.min.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 { 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 cluster: string;\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 cluster: 'mt1',\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 {\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","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","/**\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/authenticating_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","/** 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}\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","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 { AuthorizerCallback } from 'core/auth/options';\nimport { HTTPAuthError } from 'core/errors';\n\nvar ajax: AuthTransport = function(\n context: AbstractRuntime,\n socketId: string,\n callback: AuthorizerCallback\n) {\n var self = this,\n xhr;\n\n xhr = Runtime.createXHR();\n xhr.open('POST', self.options.authEndpoint, true);\n\n // add request headers\n xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');\n for (var headerName in this.authOptions.headers) {\n xhr.setRequestHeader(headerName, this.authOptions.headers[headerName]);\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 auth endpoint was invalid, yet status code was 200. Data was: ' +\n xhr.responseText\n ),\n { auth: '' }\n );\n }\n\n if (parsed) {\n // prevents double execution.\n callback(null, data);\n }\n } else {\n var suffix = UrlStore.buildLogSuffix('authenticationEndpoint');\n callback(\n new HTTPAuthError(\n xhr.status,\n 'Unable to retrieve auth string from auth endpoint - ' +\n `received status: ${xhr.status} from ${self.options.authEndpoint}. ` +\n `Clients must be authenticated to join private or presence channels. ${suffix}`\n ),\n { auth: '' }\n );\n }\n }\n };\n\n xhr.send(this.composeQuery(socketId));\n return xhr;\n};\n\nexport default ajax;\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 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 { AuthorizerCallback } from 'core/auth/options';\n\nvar jsonp: AuthTransport = function(\n context: Browser,\n socketId: string,\n callback: AuthorizerCallback\n) {\n if (this.authOptions.headers !== undefined) {\n Logger.warn(\n 'To send headers with the auth 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 this.options.authEndpoint +\n '?callback=' +\n encodeURIComponent(callback_name) +\n '&' +\n this.composeQuery(socketId);\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 Logger from '../logger';\nimport Channel from '../channels/channel';\nimport Factory from '../utils/factory';\nimport Runtime from 'runtime';\nimport { AuthTransports } from './auth_transports';\nimport {\n AuthOptions,\n AuthorizerOptions,\n Authorizer,\n AuthorizerCallback\n} from './options';\n\nexport default class PusherAuthorizer implements Authorizer {\n static authorizers: AuthTransports;\n\n channel: Channel;\n type: string;\n options: AuthorizerOptions;\n authOptions: AuthOptions;\n\n constructor(channel: Channel, options: AuthorizerOptions) {\n this.channel = channel;\n\n let { authTransport } = options;\n\n if (typeof Runtime.getAuthorizers()[authTransport] === 'undefined') {\n throw `'${authTransport}' is not a recognized auth transport`;\n }\n\n this.type = authTransport;\n this.options = options;\n this.authOptions = options.auth || {};\n }\n\n composeQuery(socketId: string): string {\n var query =\n 'socket_id=' +\n encodeURIComponent(socketId) +\n '&channel_name=' +\n encodeURIComponent(this.channel.name);\n\n for (var i in this.authOptions.params) {\n query +=\n '&' +\n encodeURIComponent(i) +\n '=' +\n encodeURIComponent(this.authOptions.params[i]);\n }\n\n return query;\n }\n\n authorize(socketId: string, callback: AuthorizerCallback): void {\n PusherAuthorizer.authorizers =\n PusherAuthorizer.authorizers || Runtime.getAuthorizers();\n\n PusherAuthorizer.authorizers[this.type].call(\n this,\n Runtime,\n socketId,\n callback\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 { AuthData, AuthorizerCallback } 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\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: AuthorizerCallback) {\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.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 /** 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: AuthData) => {\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 { AuthorizerCallback } 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: AuthorizerCallback) {\n var authorizer = Factory.createAuthorizer(this, this.pusher.config);\n return authorizer.authorize(socketId, callback);\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 { AuthData } 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 /** Authenticates 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, (error, authData) => {\n if (!error) {\n authData = authData as AuthData;\n if (authData.channel_data === undefined) {\n let suffix = UrlStore.buildLogSuffix('authenticationEndpoint');\n Logger.error(\n `Invalid auth response for channel '${this.name}',` +\n `expected 'channel_data' field. ${suffix}`\n );\n callback('Invalid auth response');\n return;\n }\n var channelData = JSON.parse(authData.channel_data);\n this.members.setMyID(channelData.user_id);\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: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 { AuthData, AuthorizerCallback } 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: AuthorizerCallback) {\n super.authorize(socketId, (error: Error | null, authData: AuthData) => {\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 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 {\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';\nimport { AuthorizerOptions, Authorizer } from '../auth/options';\nimport PusherAuthorizer from '../auth/pusher_authorizer';\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 createAuthorizer(channel: Channel, options: AuthorizerOptions): Authorizer {\n if (options.authorizer) {\n return options.authorizer(channel, options);\n }\n\n return new PusherAuthorizer(channel, 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 last successful transport and uses it for following attempts.\n *\n * @param {Strategy} strategy\n * @param {Object} transports\n * @param {Object} options\n */\nexport default class CachedStrategy 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\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 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 }\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 );\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) {\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 });\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 CachedStrategy, {\n TransportStrategyDictionary\n} from 'core/strategies/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 lives: 2,\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 CachedStrategy(\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 Math.floor(Math.random() * max);\n}\n\nfunction randomString(length: number): string {\n var result = [];\n for (var i = 0; i < length; i++) {\n result.push(randomNumber(32).toString(32));\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\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 { Options } from './options';\nimport Defaults from './defaults';\nimport { AuthOptions, AuthorizerGenerator } from './auth/options';\nimport Runtime from 'runtime';\nimport * as nacl from 'tweetnacl';\nimport Logger from './logger';\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 authEndpoint: string;\n authTransport: AuthTransport;\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\n // these are all optional parameters or overrrides. The customer can set these\n // but it's not strictly necessary\n forceTLS?: boolean;\n auth?: AuthOptions;\n authorizer?: AuthorizerGenerator;\n cluster?: string;\n disabledTransports?: Transport[];\n enabledTransports?: Transport[];\n ignoreNullOrigin?: boolean;\n nacl?: nacl;\n timelineParams?: any;\n}\n\nexport function getConfig(opts: Options): Config {\n let config: Config = {\n activityTimeout: opts.activityTimeout || Defaults.activityTimeout,\n authEndpoint: opts.authEndpoint || Defaults.authEndpoint,\n authTransport: opts.authTransport || Defaults.authTransport,\n cluster: opts.cluster || Defaults.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\n if ('auth' in opts) config.auth = opts.auth;\n if ('authorizer' in opts) config.authorizer = opts.authorizer;\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 if (opts.cluster) {\n return getWebsocketHostFromCluster(opts.cluster);\n }\n return getWebsocketHostFromCluster(Defaults.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","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 } from './options';\nimport { Config, getConfig } from './config';\nimport StrategyOptions from './strategies/strategy_options';\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\n constructor(app_key: string, options?: Options) {\n checkAppKey(app_key);\n options = options || {};\n if (!options.cluster && !(options.wsHost || options.httpHost)) {\n let suffix = UrlStore.buildLogSuffix('javascriptQuickStart');\n Logger.warn(\n `You should always specify a cluster when connecting. ${suffix}`\n );\n }\n if ('disableStats' in options) {\n Logger.warn(\n 'The disableStats option is deprecated in favor of enableStats'\n );\n }\n\n this.key = app_key;\n this.config = getConfig(options);\n\n this.channels = Factory.createChannels();\n this.global_emitter = new EventsDispatcher();\n this.sessionID = Math.floor(Math.random() * 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 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\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"],"sourceRoot":""}