UNPKG

pusher-js

Version:

Pusher JavaScript library for browser, React Native, NodeJS and web workers

1,517 lines (1,432 loc) 136 kB
/*! * Pusher JavaScript Library v3.1.0-pre11 * http://pusher.com/ * * Copyright 2016, Pusher * Released under the MIT licence. */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["Pusher"] = factory(); else root["Pusher"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var pusher_1 = __webpack_require__(1); module.exports = pusher_1["default"]; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var runtime_1 = __webpack_require__(2); var Collections = __webpack_require__(9); var dispatcher_1 = __webpack_require__(23); var timeline_1 = __webpack_require__(38); var level_1 = __webpack_require__(39); var StrategyBuilder = __webpack_require__(40); var timers_1 = __webpack_require__(12); var defaults_1 = __webpack_require__(5); var DefaultConfig = __webpack_require__(62); var logger_1 = __webpack_require__(8); var factory_1 = __webpack_require__(42); var Pusher = (function () { function Pusher(app_key, options) { var _this = this; checkAppKey(app_key); options = options || {}; this.key = app_key; this.config = Collections.extend(DefaultConfig.getGlobalConfig(), options.cluster ? DefaultConfig.getClusterConfig(options.cluster) : {}, options); this.channels = factory_1["default"].createChannels(); this.global_emitter = new dispatcher_1["default"](); this.sessionID = Math.floor(Math.random() * 1000000000); this.timeline = new timeline_1["default"](this.key, this.sessionID, { cluster: this.config.cluster, features: Pusher.getClientFeatures(), params: this.config.timelineParams || {}, limit: 50, level: level_1["default"].INFO, version: defaults_1["default"].VERSION }); if (!this.config.disableStats) { this.timelineSender = factory_1["default"].createTimelineSender(this.timeline, { host: this.config.statsHost, path: "/timeline/v2/" + runtime_1["default"].TimelineTransport.name }); } var getStrategy = function (options) { var config = Collections.extend({}, _this.config, options); return StrategyBuilder.build(runtime_1["default"].getDefaultStrategy(config), config); }; this.connection = factory_1["default"].createConnectionManager(this.key, Collections.extend({ getStrategy: getStrategy, timeline: this.timeline, activityTimeout: this.config.activity_timeout, pongTimeout: this.config.pong_timeout, unavailableTimeout: this.config.unavailable_timeout }, this.config, { encrypted: this.isEncrypted() })); this.connection.bind('connected', function () { _this.subscribeAll(); if (_this.timelineSender) { _this.timelineSender.send(_this.connection.isEncrypted()); } }); this.connection.bind('message', function (params) { var internal = (params.event.indexOf('pusher_internal:') === 0); if (params.channel) { var channel = _this.channel(params.channel); if (channel) { channel.handleEvent(params.event, params.data); } } if (!internal) { _this.global_emitter.emit(params.event, params.data); } }); this.connection.bind('disconnected', function () { _this.channels.disconnect(); }); this.connection.bind('error', function (err) { logger_1["default"].warn('Error', err); }); Pusher.instances.push(this); this.timeline.info({ instances: Pusher.instances.length }); if (Pusher.isReady) { this.connect(); } } Pusher.ready = function () { Pusher.isReady = true; for (var i = 0, l = Pusher.instances.length; i < l; i++) { Pusher.instances[i].connect(); } }; Pusher.log = function (message) { var global = Function("return this")(); if (Pusher.logToConsole && global.console && global.console.log) { global.console.log(message); } }; Pusher.getClientFeatures = function () { return Collections.keys(Collections.filterObject({ "ws": runtime_1["default"].Transports.ws }, function (t) { return t.isSupported({}); })); }; Pusher.prototype.channel = function (name) { return this.channels.find(name); }; Pusher.prototype.allChannels = function () { return this.channels.all(); }; Pusher.prototype.connect = function () { this.connection.connect(); if (this.timelineSender) { if (!this.timelineSenderTimer) { var encrypted = this.connection.isEncrypted(); var timelineSender = this.timelineSender; this.timelineSenderTimer = new timers_1.PeriodicTimer(60000, function () { timelineSender.send(encrypted); }); } } }; Pusher.prototype.disconnect = function () { this.connection.disconnect(); if (this.timelineSenderTimer) { this.timelineSenderTimer.ensureAborted(); this.timelineSenderTimer = null; } }; Pusher.prototype.bind = function (event_name, callback) { this.global_emitter.bind(event_name, callback); return this; }; Pusher.prototype.bind_all = function (callback) { this.global_emitter.bind_all(callback); return this; }; Pusher.prototype.subscribeAll = function () { var channelName; for (channelName in this.channels.channels) { if (this.channels.channels.hasOwnProperty(channelName)) { this.subscribe(channelName); } } }; Pusher.prototype.subscribe = function (channel_name) { var channel = this.channels.add(channel_name, this); if (this.connection.state === "connected") { channel.subscribe(); } return channel; }; Pusher.prototype.unsubscribe = function (channel_name) { var channel = this.channels.remove(channel_name); if (channel && this.connection.state === "connected") { channel.unsubscribe(); } }; Pusher.prototype.send_event = function (event_name, data, channel) { return this.connection.send_event(event_name, data, channel); }; Pusher.prototype.isEncrypted = function () { if (runtime_1["default"].getProtocol() === "https:") { return true; } else { return Boolean(this.config.encrypted); } }; Pusher.instances = []; Pusher.isReady = false; Pusher.logToConsole = false; Pusher.Runtime = runtime_1["default"]; Pusher.ScriptReceivers = runtime_1["default"].ScriptReceivers; Pusher.DependenciesReceivers = runtime_1["default"].DependenciesReceivers; Pusher.auth_callbacks = runtime_1["default"].auth_callbacks; return Pusher; }()); exports.__esModule = true; exports["default"] = Pusher; function checkAppKey(key) { if (key === null || key === undefined) { throw "You must pass your app key when you instantiate Pusher."; } } runtime_1["default"].setup(Pusher); /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var dependencies_1 = __webpack_require__(3); var xhr_auth_1 = __webpack_require__(7); var jsonp_auth_1 = __webpack_require__(14); var script_request_1 = __webpack_require__(15); var jsonp_request_1 = __webpack_require__(16); var script_receiver_factory_1 = __webpack_require__(4); var jsonp_timeline_1 = __webpack_require__(17); var transports_1 = __webpack_require__(18); var net_info_1 = __webpack_require__(25); var default_strategy_1 = __webpack_require__(26); var transport_connection_initializer_1 = __webpack_require__(27); var http_1 = __webpack_require__(28); var Runtime = { nextAuthCallbackID: 1, auth_callbacks: {}, ScriptReceivers: script_receiver_factory_1.ScriptReceivers, DependenciesReceivers: dependencies_1.DependenciesReceivers, getDefaultStrategy: default_strategy_1["default"], Transports: transports_1["default"], transportConnectionInitializer: transport_connection_initializer_1["default"], HTTPFactory: http_1["default"], TimelineTransport: jsonp_timeline_1["default"], getXHRAPI: function () { return window.XMLHttpRequest; }, getWebSocketAPI: function () { return window.WebSocket || window.MozWebSocket; }, setup: function (PusherClass) { var _this = this; window.Pusher = PusherClass; var initializeOnDocumentBody = function () { _this.onDocumentBody(PusherClass.ready); }; if (!window.JSON) { dependencies_1.Dependencies.load("json2", {}, initializeOnDocumentBody); } else { initializeOnDocumentBody(); } }, getDocument: function () { return document; }, getProtocol: function () { return this.getDocument().location.protocol; }, getGlobal: function () { return window; }, getAuthorizers: function () { return { ajax: xhr_auth_1["default"], jsonp: jsonp_auth_1["default"] }; }, onDocumentBody: function (callback) { var _this = this; if (document.body) { callback(); } else { setTimeout(function () { _this.onDocumentBody(callback); }, 0); } }, createJSONPRequest: function (url, data) { return new jsonp_request_1["default"](url, data); }, createScriptRequest: function (src) { return new script_request_1["default"](src); }, getLocalStorage: function () { try { return window.localStorage; } catch (e) { return undefined; } }, createXHR: function () { if (this.getXHRAPI()) { return this.createXMLHttpRequest(); } else { return this.createMicrosoftXHR(); } }, createXMLHttpRequest: function () { var Constructor = this.getXHRAPI(); return new Constructor(); }, createMicrosoftXHR: function () { return new ActiveXObject("Microsoft.XMLHTTP"); }, getNetwork: function () { return net_info_1.Network; }, createWebSocket: function (url) { var Constructor = this.getWebSocketAPI(); return new Constructor(url); }, createSocketRequest: function (method, url) { if (this.isXHRSupported()) { return this.HTTPFactory.createXHR(method, url); } else if (this.isXDRSupported(url.indexOf("https:") === 0)) { return this.HTTPFactory.createXDR(method, url); } else { throw "Cross-origin HTTP requests are not supported"; } }, isXHRSupported: function () { var Constructor = this.getXHRAPI(); return Boolean(Constructor) && (new Constructor()).withCredentials !== undefined; }, isXDRSupported: function (encrypted) { var protocol = encrypted ? "https:" : "http:"; var documentProtocol = this.getProtocol(); return Boolean((window['XDomainRequest'])) && documentProtocol === protocol; }, addUnloadListener: function (listener) { if (window.addEventListener !== undefined) { window.addEventListener("unload", listener, false); } else if (window.attachEvent !== undefined) { window.attachEvent("onunload", listener); } }, removeUnloadListener: function (listener) { if (window.addEventListener !== undefined) { window.removeEventListener("unload", listener, false); } else if (window.detachEvent !== undefined) { window.detachEvent("onunload", listener); } } }; exports.__esModule = true; exports["default"] = Runtime; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var script_receiver_factory_1 = __webpack_require__(4); var defaults_1 = __webpack_require__(5); var dependency_loader_1 = __webpack_require__(6); exports.DependenciesReceivers = new script_receiver_factory_1.ScriptReceiverFactory("_pusher_dependencies", "Pusher.DependenciesReceivers"); exports.Dependencies = new dependency_loader_1["default"]({ cdn_http: defaults_1["default"].cdn_http, cdn_https: defaults_1["default"].cdn_https, version: defaults_1["default"].VERSION, suffix: defaults_1["default"].dependency_suffix, receivers: exports.DependenciesReceivers }); /***/ }, /* 4 */ /***/ function(module, exports) { "use strict"; var ScriptReceiverFactory = (function () { function ScriptReceiverFactory(prefix, name) { this.lastId = 0; this.prefix = prefix; this.name = name; } ScriptReceiverFactory.prototype.create = function (callback) { this.lastId++; var number = this.lastId; var id = this.prefix + number; var name = this.name + "[" + number + "]"; var called = false; var callbackWrapper = function () { if (!called) { callback.apply(null, arguments); called = true; } }; this[number] = callbackWrapper; return { number: number, id: id, name: name, callback: callbackWrapper }; }; ScriptReceiverFactory.prototype.remove = function (receiver) { delete this[receiver.number]; }; return ScriptReceiverFactory; }()); exports.ScriptReceiverFactory = ScriptReceiverFactory; exports.ScriptReceivers = new ScriptReceiverFactory("_pusher_script_", "Pusher.ScriptReceivers"); /***/ }, /* 5 */ /***/ function(module, exports) { "use strict"; var Defaults = { VERSION: "3.1.0-pre11", PROTOCOL: 7, host: 'ws.pusherapp.com', ws_port: 80, wss_port: 443, sockjs_host: 'sockjs.pusher.com', sockjs_http_port: 80, sockjs_https_port: 443, sockjs_path: "/pusher", stats_host: 'stats.pusher.com', channel_auth_endpoint: '/pusher/auth', channel_auth_transport: 'ajax', activity_timeout: 120000, pong_timeout: 30000, unavailable_timeout: 10000, cdn_http: 'http://js.pusher.com', cdn_https: 'https://js.pusher.com', dependency_suffix: '' }; exports.__esModule = true; exports["default"] = Defaults; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var script_receiver_factory_1 = __webpack_require__(4); var runtime_1 = __webpack_require__(2); var DependencyLoader = (function () { function DependencyLoader(options) { this.options = options; this.receivers = options.receivers || script_receiver_factory_1.ScriptReceivers; this.loading = {}; } DependencyLoader.prototype.load = function (name, options, callback) { var self = this; if (self.loading[name] && self.loading[name].length > 0) { self.loading[name].push(callback); } else { self.loading[name] = [callback]; var request = runtime_1["default"].createScriptRequest(self.getPath(name, options)); var receiver = self.receivers.create(function (error) { self.receivers.remove(receiver); if (self.loading[name]) { var callbacks = self.loading[name]; delete self.loading[name]; var successCallback = function (wasSuccessful) { if (!wasSuccessful) { request.cleanup(); } }; for (var i = 0; i < callbacks.length; i++) { callbacks[i](error, successCallback); } } }); request.send(receiver); } }; DependencyLoader.prototype.getRoot = function (options) { var cdn; var protocol = runtime_1["default"].getDocument().location.protocol; if ((options && options.encrypted) || protocol === "https:") { cdn = this.options.cdn_https; } else { cdn = this.options.cdn_http; } return cdn.replace(/\/*$/, "") + "/" + this.options.version; }; DependencyLoader.prototype.getPath = function (name, options) { return this.getRoot(options) + '/' + name + this.options.suffix + '.js'; }; ; return DependencyLoader; }()); exports.__esModule = true; exports["default"] = DependencyLoader; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var logger_1 = __webpack_require__(8); var runtime_1 = __webpack_require__(2); var ajax = function (context, socketId, callback) { var self = this, xhr; xhr = runtime_1["default"].createXHR(); xhr.open("POST", self.options.authEndpoint, true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); for (var headerName in this.authOptions.headers) { xhr.setRequestHeader(headerName, this.authOptions.headers[headerName]); } xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { var data, parsed = false; try { data = JSON.parse(xhr.responseText); parsed = true; } catch (e) { callback(true, 'JSON returned from webapp was invalid, yet status code was 200. Data was: ' + xhr.responseText); } if (parsed) { callback(false, data); } } else { logger_1["default"].warn("Couldn't get auth info from your webapp", xhr.status); callback(true, xhr.status); } } }; xhr.send(this.composeQuery(socketId)); return xhr; }; exports.__esModule = true; exports["default"] = ajax; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var collections_1 = __webpack_require__(9); var pusher_1 = __webpack_require__(1); var Logger = { debug: function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i - 0] = arguments[_i]; } if (!pusher_1["default"].log) { return; } pusher_1["default"].log(collections_1.stringify.apply(this, arguments)); }, warn: function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i - 0] = arguments[_i]; } var message = collections_1.stringify.apply(this, arguments); var global = Function("return this")(); if (global.console) { if (global.console.warn) { global.console.warn(message); } else if (global.console.log) { global.console.log(message); } } if (pusher_1["default"].log) { pusher_1["default"].log(message); } } }; exports.__esModule = true; exports["default"] = Logger; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var base64_1 = __webpack_require__(10); var util_1 = __webpack_require__(11); var global = Function("return this")(); function extend(target) { var sources = []; for (var _i = 1; _i < arguments.length; _i++) { sources[_i - 1] = arguments[_i]; } for (var i = 0; i < sources.length; i++) { var extensions = sources[i]; for (var property in extensions) { if (extensions[property] && extensions[property].constructor && extensions[property].constructor === Object) { target[property] = extend(target[property] || {}, extensions[property]); } else { target[property] = extensions[property]; } } } return target; } exports.extend = extend; function stringify() { var m = ["Pusher"]; for (var i = 0; i < arguments.length; i++) { if (typeof arguments[i] === "string") { m.push(arguments[i]); } else { m.push(JSON.stringify(arguments[i])); } } return m.join(" : "); } exports.stringify = stringify; function arrayIndexOf(array, item) { var nativeIndexOf = Array.prototype.indexOf; if (array === null) { return -1; } if (nativeIndexOf && array.indexOf === nativeIndexOf) { return array.indexOf(item); } for (var i = 0, l = array.length; i < l; i++) { if (array[i] === item) { return i; } } return -1; } exports.arrayIndexOf = arrayIndexOf; function objectApply(object, f) { for (var key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { f(object[key], key, object); } } } exports.objectApply = objectApply; function keys(object) { var keys = []; objectApply(object, function (_, key) { keys.push(key); }); return keys; } exports.keys = keys; function values(object) { var values = []; objectApply(object, function (value) { values.push(value); }); return values; } exports.values = values; function apply(array, f, context) { for (var i = 0; i < array.length; i++) { f.call(context || global, array[i], i, array); } } exports.apply = apply; function map(array, f) { var result = []; for (var i = 0; i < array.length; i++) { result.push(f(array[i], i, array, result)); } return result; } exports.map = map; function mapObject(object, f) { var result = {}; objectApply(object, function (value, key) { result[key] = f(value); }); return result; } exports.mapObject = mapObject; function filter(array, test) { test = test || function (value) { return !!value; }; var result = []; for (var i = 0; i < array.length; i++) { if (test(array[i], i, array, result)) { result.push(array[i]); } } return result; } exports.filter = filter; function filterObject(object, test) { var result = {}; objectApply(object, function (value, key) { if ((test && test(value, key, object, result)) || Boolean(value)) { result[key] = value; } }); return result; } exports.filterObject = filterObject; function flatten(object) { var result = []; objectApply(object, function (value, key) { result.push([key, value]); }); return result; } exports.flatten = flatten; function any(array, test) { for (var i = 0; i < array.length; i++) { if (test(array[i], i, array)) { return true; } } return false; } exports.any = any; function all(array, test) { for (var i = 0; i < array.length; i++) { if (!test(array[i], i, array)) { return false; } } return true; } exports.all = all; function encodeParamsObject(data) { return mapObject(data, function (value) { if (typeof value === "object") { value = JSON.stringify(value); } return encodeURIComponent(base64_1["default"](value.toString())); }); } exports.encodeParamsObject = encodeParamsObject; function buildQueryString(data) { var params = filterObject(data, function (value) { return value !== undefined; }); var query = map(flatten(encodeParamsObject(params)), util_1["default"].method("join", "=")).join("&"); return query; } exports.buildQueryString = buildQueryString; function safeJSONStringify(source) { var cache = []; var serialized = JSON.stringify(source, function (key, value) { if (typeof value === 'object' && value !== null) { if (cache.indexOf(value) !== -1) { return; } cache.push(value); } return value; }); cache = null; return serialized; } exports.safeJSONStringify = safeJSONStringify; /***/ }, /* 10 */ /***/ function(module, exports) { "use strict"; var global = Function("return this")(); function encode(s) { return btoa(utob(s)); } exports.__esModule = true; exports["default"] = encode; var fromCharCode = String.fromCharCode; var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var b64tab = {}; for (var i = 0, l = b64chars.length; i < l; i++) { b64tab[b64chars.charAt(i)] = i; } var cb_utob = function (c) { var cc = c.charCodeAt(0); return cc < 0x80 ? c : cc < 0x800 ? fromCharCode(0xc0 | (cc >>> 6)) + fromCharCode(0x80 | (cc & 0x3f)) : fromCharCode(0xe0 | ((cc >>> 12) & 0x0f)) + fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) + fromCharCode(0x80 | (cc & 0x3f)); }; var utob = function (u) { return u.replace(/[^\x00-\x7F]/g, cb_utob); }; var cb_encode = function (ccc) { var padlen = [0, 2, 1][ccc.length % 3]; var ord = ccc.charCodeAt(0) << 16 | ((ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8) | ((ccc.length > 2 ? ccc.charCodeAt(2) : 0)); var chars = [ b64chars.charAt(ord >>> 18), b64chars.charAt((ord >>> 12) & 63), padlen >= 2 ? '=' : b64chars.charAt((ord >>> 6) & 63), padlen >= 1 ? '=' : b64chars.charAt(ord & 63) ]; return chars.join(''); }; var btoa = global.btoa || function (b) { return b.replace(/[\s\S]{1,3}/g, cb_encode); }; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var timers_1 = __webpack_require__(12); var Util = { getGlobal: function () { return Function("return this")(); }, now: function () { if (Date.now) { return Date.now(); } else { return new Date().valueOf(); } }, defer: function (callback) { return new timers_1.OneOffTimer(0, callback); }, method: function (name) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } var boundArguments = Array.prototype.slice.call(arguments, 1); return function (object) { return object[name].apply(object, boundArguments.concat(arguments)); }; } }; exports.__esModule = true; exports["default"] = Util; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var abstract_timer_1 = __webpack_require__(13); var global = Function("return this")(); function clearTimeout(timer) { global.clearTimeout(timer); } function clearInterval(timer) { global.clearInterval(timer); } var OneOffTimer = (function (_super) { __extends(OneOffTimer, _super); function OneOffTimer(delay, callback) { _super.call(this, setTimeout, clearTimeout, delay, function (timer) { callback(); return null; }); } return OneOffTimer; }(abstract_timer_1["default"])); exports.OneOffTimer = OneOffTimer; var PeriodicTimer = (function (_super) { __extends(PeriodicTimer, _super); function PeriodicTimer(delay, callback) { _super.call(this, setInterval, clearInterval, delay, function (timer) { callback(); return timer; }); } return PeriodicTimer; }(abstract_timer_1["default"])); exports.PeriodicTimer = PeriodicTimer; /***/ }, /* 13 */ /***/ function(module, exports) { "use strict"; var Timer = (function () { function Timer(set, clear, delay, callback) { var _this = this; this.clear = clear; this.timer = set(function () { if (_this.timer) { _this.timer = callback(_this.timer); } }, delay); } Timer.prototype.isRunning = function () { return this.timer !== null; }; Timer.prototype.ensureAborted = function () { if (this.timer) { this.clear(this.timer); this.timer = null; } }; return Timer; }()); exports.__esModule = true; exports["default"] = Timer; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var logger_1 = __webpack_require__(8); var jsonp = function (context, socketId, callback) { if (this.authOptions.headers !== undefined) { logger_1["default"].warn("Warn", "To send headers with the auth request, you must use AJAX, rather than JSONP."); } var callbackName = context.nextAuthCallbackID.toString(); context.nextAuthCallbackID++; var document = context.getDocument(); var script = document.createElement("script"); context.auth_callbacks[callbackName] = function (data) { callback(false, data); }; var callback_name = "Pusher.auth_callbacks['" + callbackName + "']"; script.src = this.options.authEndpoint + '?callback=' + encodeURIComponent(callback_name) + '&' + this.composeQuery(socketId); var head = document.getElementsByTagName("head")[0] || document.documentElement; head.insertBefore(script, head.firstChild); }; exports.__esModule = true; exports["default"] = jsonp; /***/ }, /* 15 */ /***/ function(module, exports) { "use strict"; var ScriptRequest = (function () { function ScriptRequest(src) { this.src = src; } ScriptRequest.prototype.send = function (receiver) { var self = this; var errorString = "Error loading " + self.src; self.script = document.createElement("script"); self.script.id = receiver.id; self.script.src = self.src; self.script.type = "text/javascript"; self.script.charset = "UTF-8"; if (self.script.addEventListener) { self.script.onerror = function () { receiver.callback(errorString); }; self.script.onload = function () { receiver.callback(null); }; } else { self.script.onreadystatechange = function () { if (self.script.readyState === 'loaded' || self.script.readyState === 'complete') { receiver.callback(null); } }; } if (self.script.async === undefined && document.attachEvent && /opera/i.test(navigator.userAgent)) { self.errorScript = document.createElement("script"); self.errorScript.id = receiver.id + "_error"; self.errorScript.text = receiver.name + "('" + errorString + "');"; self.script.async = self.errorScript.async = false; } else { self.script.async = true; } var head = document.getElementsByTagName('head')[0]; head.insertBefore(self.script, head.firstChild); if (self.errorScript) { head.insertBefore(self.errorScript, self.script.nextSibling); } }; ScriptRequest.prototype.cleanup = function () { if (this.script) { this.script.onload = this.script.onerror = null; this.script.onreadystatechange = null; } if (this.script && this.script.parentNode) { this.script.parentNode.removeChild(this.script); } if (this.errorScript && this.errorScript.parentNode) { this.errorScript.parentNode.removeChild(this.errorScript); } this.script = null; this.errorScript = null; }; return ScriptRequest; }()); exports.__esModule = true; exports["default"] = ScriptRequest; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var Collections = __webpack_require__(9); var runtime_1 = __webpack_require__(2); var JSONPRequest = (function () { function JSONPRequest(url, data) { this.url = url; this.data = data; } JSONPRequest.prototype.send = function (receiver) { if (this.request) { return; } var query = Collections.buildQueryString(this.data); var url = this.url + "/" + receiver.number + "?" + query; this.request = runtime_1["default"].createScriptRequest(url); this.request.send(receiver); }; JSONPRequest.prototype.cleanup = function () { if (this.request) { this.request.cleanup(); } }; return JSONPRequest; }()); exports.__esModule = true; exports["default"] = JSONPRequest; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var runtime_1 = __webpack_require__(2); var script_receiver_factory_1 = __webpack_require__(4); var getAgent = function (sender, encrypted) { return function (data, callback) { var scheme = "http" + (encrypted ? "s" : "") + "://"; var url = scheme + (sender.host || sender.options.host) + sender.options.path; var request = runtime_1["default"].createJSONPRequest(url, data); var receiver = runtime_1["default"].ScriptReceivers.create(function (error, result) { script_receiver_factory_1.ScriptReceivers.remove(receiver); request.cleanup(); if (result && result.host) { sender.host = result.host; } if (callback) { callback(error, result); } }); request.send(receiver); }; }; var jsonp = { name: 'jsonp', getAgent: getAgent }; exports.__esModule = true; exports["default"] = jsonp; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var transports_1 = __webpack_require__(19); var transport_1 = __webpack_require__(21); var URLSchemes = __webpack_require__(20); var runtime_1 = __webpack_require__(2); var dependencies_1 = __webpack_require__(3); var Collections = __webpack_require__(9); var SockJSTransport = new transport_1["default"]({ file: "sockjs", urls: URLSchemes.sockjs, handlesActivityChecks: true, supportsPing: false, isSupported: function () { return true; }, isInitialized: function () { return window.SockJS !== undefined; }, getSocket: function (url, options) { return new window.SockJS(url, null, { js_path: dependencies_1.Dependencies.getPath("sockjs", { encrypted: options.encrypted }), ignore_null_origin: options.ignoreNullOrigin }); }, beforeOpen: function (socket, path) { socket.send(JSON.stringify({ path: path })); } }); var xdrConfiguration = { isSupported: function (environment) { var yes = runtime_1["default"].isXDRSupported(environment.encrypted); return yes; } }; var XDRStreamingTransport = new transport_1["default"](Collections.extend({}, transports_1.streamingConfiguration, xdrConfiguration)); var XDRPollingTransport = new transport_1["default"](Collections.extend({}, transports_1.pollingConfiguration, xdrConfiguration)); transports_1["default"].xdr_streaming = XDRStreamingTransport; transports_1["default"].xdr_polling = XDRPollingTransport; transports_1["default"].sockjs = SockJSTransport; exports.__esModule = true; exports["default"] = transports_1["default"]; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var URLSchemes = __webpack_require__(20); var transport_1 = __webpack_require__(21); var Collections = __webpack_require__(9); var runtime_1 = __webpack_require__(2); var WSTransport = new transport_1["default"]({ urls: URLSchemes.ws, handlesActivityChecks: false, supportsPing: false, isInitialized: function () { return Boolean(runtime_1["default"].getWebSocketAPI()); }, isSupported: function () { return Boolean(runtime_1["default"].getWebSocketAPI()); }, getSocket: function (url) { return runtime_1["default"].createWebSocket(url); } }); var httpConfiguration = { urls: URLSchemes.http, handlesActivityChecks: false, supportsPing: true, isInitialized: function () { return true; } }; exports.streamingConfiguration = Collections.extend({ getSocket: function (url) { return runtime_1["default"].HTTPFactory.createStreamingSocket(url); } }, httpConfiguration); exports.pollingConfiguration = Collections.extend({ getSocket: function (url) { return runtime_1["default"].HTTPFactory.createPollingSocket(url); } }, httpConfiguration); var xhrConfiguration = { isSupported: function () { return runtime_1["default"].isXHRSupported(); } }; var XHRStreamingTransport = new transport_1["default"](Collections.extend({}, exports.streamingConfiguration, xhrConfiguration)); var XHRPollingTransport = new transport_1["default"](Collections.extend({}, exports.pollingConfiguration, xhrConfiguration)); var Transports = { ws: WSTransport, xhr_streaming: XHRStreamingTransport, xhr_polling: XHRPollingTransport }; exports.__esModule = true; exports["default"] = Transports; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var defaults_1 = __webpack_require__(5); function getGenericURL(baseScheme, params, path) { var scheme = baseScheme + (params.encrypted ? "s" : ""); var host = params.encrypted ? params.hostEncrypted : params.hostUnencrypted; return scheme + "://" + host + path; } function getGenericPath(key, queryString) { var path = "/app/" + key; var query = "?protocol=" + defaults_1["default"].PROTOCOL + "&client=js" + "&version=" + defaults_1["default"].VERSION + (queryString ? ("&" + queryString) : ""); return path + query; } exports.ws = { getInitial: function (key, params) { return getGenericURL("ws", params, getGenericPath(key, "flash=false")); } }; exports.http = { getInitial: function (key, params) { var path = (params.httpPath || "/pusher") + getGenericPath(key); return getGenericURL("http", params, path); } }; exports.sockjs = { getInitial: function (key, params) { return getGenericURL("http", params, params.httpPath || "/pusher"); }, getPath: function (key, params) { return getGenericPath(key); } }; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var transport_connection_1 = __webpack_require__(22); var Transport = (function () { function Transport(hooks) { this.hooks = hooks; } Transport.prototype.isSupported = function (environment) { return this.hooks.isSupported(environment); }; Transport.prototype.createConnection = function (name, priority, key, options) { return new transport_connection_1["default"](this.hooks, name, priority, key, options); }; return Transport; }()); exports.__esModule = true; exports["default"] = Transport; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var util_1 = __webpack_require__(11); var Collections = __webpack_require__(9); var dispatcher_1 = __webpack_require__(23); var logger_1 = __webpack_require__(8); var runtime_1 = __webpack_require__(2); var TransportConnection = (function (_super) { __extends(TransportConnection, _super); function TransportConnection(hooks, name, priority, key, options) { _super.call(this); this.initialize = runtime_1["default"].transportConnectionInitializer; this.hooks = hooks; this.name = name; this.priority = priority; this.key = key; this.options = options; this.state = "new"; this.timeline = options.timeline; this.activityTimeout = options.activityTimeout; this.id = this.timeline.generateUniqueID(); } TransportConnection.prototype.handlesActivityChecks = function () { return Boolean(this.hooks.handlesActivityChecks); }; TransportConnection.prototype.supportsPing = function () { return Boolean(this.hooks.supportsPing); }; TransportConnection.prototype.connect = function () { var _this = this; if (this.socket || this.state !== "initialized") { return false; } var url = this.hooks.urls.getInitial(this.key, this.options); try { this.socket = this.hooks.getSocket(url, this.options); } catch (e) { util_1["default"].defer(function () { _this.onError(e); _this.changeState("closed"); }); return false; } this.bindListeners(); logger_1["default"].debug("Connecting", { transport: this.name, url: url }); this.changeState("connecting"); return true; }; TransportConnection.prototype.close = function () { if (this.socket) { this.socket.close(); return true; } else { return false; } }; TransportConnection.prototype.send = function (data) { var _this = this; if (this.state === "open") { util_1["default"].defer(function () { if (_this.socket) { _this.socket.send(data); } }); return true; } else { return false; } }; TransportConnection.prototype.ping = function () { if (this.state === "open" && this.supportsPing()) { this.socket.ping(); } }; TransportConnection.prototype.onOpen = function () { if (this.hooks.beforeOpen) { this.hooks.beforeOpen(this.socket, this.hooks.urls.getPath(this.key, this.options)); } this.changeState("open"); this.socket.onopen = undefined; }; TransportConnection.prototype.onError = function (error) { this.emit("error", { type: 'WebSocketError', error: error }); this.timeline.error(this.buildTimelineMessage({ error: error.toString() })); }; TransportConnection.prototype.onClose = function (closeEvent) { if (closeEvent) { this.changeState("closed", { code: closeEvent.code, reason: closeEvent.reason, wasClean: closeEvent.wasClean }); } else { this.changeState("closed"); } this.unbindListeners(); this.socket = undefined; }; TransportConnection.prototype.onMessage = function (message) { this.emit("message", message); }; TransportConnection.prototype.onActivity = function () { this.emit("activity"); }; TransportConnection.prototype.bindListeners = function () { var _this = this; this.socket.onopen = function () { _this.onOpen(); }; this.socket.onerror = function (error) { _this.onError(error); }; this.socket.onclose = function (closeEvent) { _this.onClose(closeEvent); }; this.socket.onmessage = function (message) { _this.onMessage(message); }; if (this.supportsPing()) { this.socket.onactivity = function () { _this.onActivity(); }; } }; TransportConnection.prototype.unbindListeners = function () { if (this.socket) { this.socket.onopen = undefined; this.socket.onerror = undefined; this.socket.onclose = undefined; this.socket.onmessage = undefined; if (this.supportsPing()) { this.socket.onactivity = undefined; } } }; TransportConnection.prototype.changeState = function (state, params) { this.state = state; this.timeline.info(this.buildTimelineMessage({ state: state, params: params })); this.emit(state, params); }; TransportConnection.prototype.buildTimelineMessage = function (message) { return Collections.extend({ cid: this.id }, message); }; return TransportConnection; }(dispatcher_1["default"])); exports.__esModule = true; exports["default"] = TransportConnection; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var callback_registry_1 = __webpack_require__(24); var global = Function("return this")(); var Dispatcher = (function () { function Dispatcher(failThrough) { this.callbacks = new callback_registry_1["default"](); this.global_callbacks = []; this.failThrough = failThrough; } Dispatcher.prototype.bind = function (eventName, callback, context) { this.callbacks.add(eventName, callback, context); return this; }; Dispatcher.prototype.bind_all = function (callback) { this.global_callbacks.push(callback); return this; }; Dispatcher.prototype.unbind = function (eventName, callback, context) { this.callbacks.remove(eventName, callback, context); return this; }; Dispatcher.prototype.unbind_all = function (eventName, callback) { this.callbacks.remove(eventName, callback); return this; }; Dispatcher.prototype.emit = function (eventName, data) { var i; for (i = 0; i < this.global_callbacks.length; i++) { this.global_callbacks[i](eventName, data); } var callbacks = this.callbacks.get(eventName); if (callbacks && callbacks.length > 0) { for (i = 0; i < callbacks.length; i++) { callbacks[i].fn.call(callbacks[i].context || global, data); } } else if (this.failThrough) { this.failThrough(eventName, data); } return this; }; return Dispatcher; }()); exports.__esModule = true; exports["default"] = Dispatcher; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var Collections = __webpack_require__(9); var CallbackRegistry = (function () { function CallbackRegistry() { this._callbacks = {}; } CallbackRegistry.prototype.get = function (name) { return this._callbacks[prefi