pusher-js
Version:
Pusher JavaScript library for browser, React Native, NodeJS and web workers
1,514 lines (1,438 loc) • 120 kB
JavaScript
/*!
* Pusher JavaScript Library v3.1.0-pre11
* http://pusher.com/
*
* Copyright 2016, Pusher
* Released under the MIT licence.
*/
var Pusher =
/******/ (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__(4);
var dispatcher_1 = __webpack_require__(14);
var timeline_1 = __webpack_require__(29);
var level_1 = __webpack_require__(30);
var StrategyBuilder = __webpack_require__(31);
var timers_1 = __webpack_require__(7);
var defaults_1 = __webpack_require__(11);
var DefaultConfig = __webpack_require__(54);
var logger_1 = __webpack_require__(16);
var factory_1 = __webpack_require__(33);
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 runtime_1 = __webpack_require__(3);
var net_info_1 = __webpack_require__(26);
var fetch_auth_1 = __webpack_require__(27);
var fetch_timeline_1 = __webpack_require__(28);
var getDefaultStrategy = runtime_1["default"].getDefaultStrategy, Transports = runtime_1["default"].Transports, setup = runtime_1["default"].setup, getProtocol = runtime_1["default"].getProtocol, isXHRSupported = runtime_1["default"].isXHRSupported, getGlobal = runtime_1["default"].getGlobal, getLocalStorage = runtime_1["default"].getLocalStorage, createXHR = runtime_1["default"].createXHR, createWebSocket = runtime_1["default"].createWebSocket, addUnloadListener = runtime_1["default"].addUnloadListener, removeUnloadListener = runtime_1["default"].removeUnloadListener, transportConnectionInitializer = runtime_1["default"].transportConnectionInitializer, createSocketRequest = runtime_1["default"].createSocketRequest, HTTPFactory = runtime_1["default"].HTTPFactory;
var Worker = {
getDefaultStrategy: getDefaultStrategy,
Transports: Transports,
setup: setup,
getProtocol: getProtocol,
isXHRSupported: isXHRSupported,
getGlobal: getGlobal,
getLocalStorage: getLocalStorage,
createXHR: createXHR,
createWebSocket: createWebSocket,
addUnloadListener: addUnloadListener,
removeUnloadListener: removeUnloadListener,
transportConnectionInitializer: transportConnectionInitializer,
createSocketRequest: createSocketRequest,
HTTPFactory: HTTPFactory,
TimelineTransport: fetch_timeline_1["default"],
getAuthorizers: function () {
return { ajax: fetch_auth_1["default"] };
},
getWebSocketAPI: function () {
return WebSocket;
},
getXHRAPI: function () {
return XMLHttpRequest;
},
getNetwork: function () {
return net_info_1.Network;
}
};
exports.__esModule = true;
exports["default"] = Worker;
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var Collections = __webpack_require__(4);
var transports_1 = __webpack_require__(9);
var default_strategy_1 = __webpack_require__(17);
var transport_connection_initializer_1 = __webpack_require__(18);
var http_1 = __webpack_require__(19);
var Isomorphic = {
getDefaultStrategy: default_strategy_1["default"],
Transports: transports_1["default"],
transportConnectionInitializer: transport_connection_initializer_1["default"],
HTTPFactory: http_1["default"],
setup: function (PusherClass) {
PusherClass.ready();
},
getGlobal: function () {
return Function("return this")();
},
getLocalStorage: function () {
return undefined;
},
getClientFeatures: function () {
return Collections.keys(Collections.filterObject({ "ws": transports_1["default"].ws }, function (t) { return t.isSupported({}); }));
},
getProtocol: function () {
return "http:";
},
isXHRSupported: function () {
return true;
},
createSocketRequest: function (method, url) {
if (this.isXHRSupported()) {
return this.HTTPFactory.createXHR(method, url);
}
else {
throw "Cross-origin HTTP requests are not supported";
}
},
createXHR: function () {
var Constructor = this.getXHRAPI();
return new Constructor();
},
createWebSocket: function (url) {
var Constructor = this.getWebSocketAPI();
return new Constructor(url);
},
addUnloadListener: function (listener) { },
removeUnloadListener: function (listener) { }
};
exports.__esModule = true;
exports["default"] = Isomorphic;
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var base64_1 = __webpack_require__(5);
var util_1 = __webpack_require__(6);
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;
/***/ },
/* 5 */
/***/ 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);
};
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var timers_1 = __webpack_require__(7);
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;
/***/ },
/* 7 */
/***/ 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__(8);
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;
/***/ },
/* 8 */
/***/ 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;
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var URLSchemes = __webpack_require__(10);
var transport_1 = __webpack_require__(12);
var Collections = __webpack_require__(4);
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;
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var defaults_1 = __webpack_require__(11);
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);
}
};
/***/ },
/* 11 */
/***/ 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;
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var transport_connection_1 = __webpack_require__(13);
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;
/***/ },
/* 13 */
/***/ 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__(6);
var Collections = __webpack_require__(4);
var dispatcher_1 = __webpack_require__(14);
var logger_1 = __webpack_require__(16);
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;
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var callback_registry_1 = __webpack_require__(15);
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;
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var Collections = __webpack_require__(4);
var CallbackRegistry = (function () {
function CallbackRegistry() {
this._callbacks = {};
}
CallbackRegistry.prototype.get = function (name) {
return this._callbacks[prefix(name)];
};
CallbackRegistry.prototype.add = function (name, callback, context) {
var prefixedEventName = prefix(name);
this._callbacks[prefixedEventName] = this._callbacks[prefixedEventName] || [];
this._callbacks[prefixedEventName].push({
fn: callback,
context: context
});
};
CallbackRegistry.prototype.remove = function (name, callback, context) {
if (!name && !callback && !context) {
this._callbacks = {};
return;
}
var names = name ? [prefix(name)] : Collections.keys(this._callbacks);
if (callback || context) {
this.removeCallback(names, callback, context);
}
else {
this.removeAllCallbacks(names);
}
};
CallbackRegistry.prototype.removeCallback = function (names, callback, context) {
Collections.apply(names, function (name) {
this._callbacks[name] = Collections.filter(this._callbacks[name] || [], function (binding) {
return (callback && callback !== binding.fn) ||
(context && context !== binding.context);
});
if (this._callbacks[name].length === 0) {
delete this._callbacks[name];
}
}, this);
};
CallbackRegistry.prototype.removeAllCallbacks = function (names) {
Collections.apply(names, function (name) {
delete this._callbacks[name];
}, this);
};
return CallbackRegistry;
}());
exports.__esModule = true;
exports["default"] = CallbackRegistry;
function prefix(name) {
return "_" + name;
}
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var collections_1 = __webpack_require__(4);
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;
/***/ },
/* 17 */
/***/ function(module, exports) {
"use strict";
var getDefaultStrategy = function (config) {
var wsStrategy;
if (config.encrypted) {
wsStrategy = [
":best_connected_ever",
":ws_loop",
[":delayed", 2000, [":http_loop"]]
];
}
else {
wsStrategy = [
":best_connected_ever",
":ws_loop",
[":delayed", 2000, [":wss_loop"]],
[":delayed", 5000, [":http_loop"]]
];
}
return [
[":def", "ws_options", {
hostUnencrypted: config.wsHost + ":" + config.wsPort,
hostEncrypted: config.wsHost + ":" + config.wssPort
}],
[":def", "wss_options", [":extend", ":ws_options", {
encrypted: true
}]],
[":def", "http_options", {
hostUnencrypted: config.httpHost + ":" + config.httpPort,
hostEncrypted: config.httpHost + ":" + config.httpsPort,
httpPath: config.httpPath
}],
[":def", "timeouts", {
loop: true,
timeout: 15000,
timeoutLimit: 60000
}],
[":def", "ws_manager", [":transport_manager", {
lives: 2,
minPingDelay: 10000,
maxPingDelay: config.activity_timeout
}]],
[":def", "streaming_manager", [":transport_manager", {
lives: 2,
minPingDelay: 10000,
maxPingDelay: config.activity_timeout
}]],
[":def_transport", "ws", "ws", 3, ":ws_options", ":ws_manager"],
[":def_transport", "wss", "ws", 3, ":wss_options", ":ws_manager"],
[":def_transport", "xhr_streaming", "xhr_streaming", 1, ":http_options", ":streaming_manager"],
[":def_transport", "xhr_polling", "xhr_polling", 1, ":http_options"],
[":def", "ws_loop", [":sequential", ":timeouts", ":ws"]],
[":def", "wss_loop", [":sequential", ":timeouts", ":wss"]],
[":def", "streaming_loop", [":sequential", ":timeouts", ":xhr_streaming"]],
[":def", "polling_loop", [":sequential", ":timeouts", ":xhr_polling"]],
[":def", "http_loop", [":if", [":is_supported", ":streaming_loop"], [
":best_connected_ever",
":streaming_loop",
[":delayed", 4000, [":polling_loop"]]
], [
":polling_loop"
]]],
[":def", "strategy",
[":cached", 1800000,
[":first_connected",
[":if", [":is_supported", ":ws"],
wsStrategy,
":http_loop"
]
]
]
]
];
};
exports.__esModule = true;
exports["default"] = getDefaultStrategy;
/***/ },
/* 18 */
/***/ function(module, exports) {
"use strict";
function default_1() {
var self = this;
self.timeline.info(self.buildTimelineMessage({
transport: self.name + (self.options.encrypted ? "s" : "")
}));
if (self.hooks.isInitialized()) {
self.changeState("initialized");
}
else {
self.onClose();
}
}
exports.__esModule = true;
exports["default"] = default_1;
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var http_request_1 = __webpack_require__(20);
var http_socket_1 = __webpack_require__(21);
var http_streaming_socket_1 = __webpack_require__(23);
var http_polling_socket_1 = __webpack_require__(24);
var http_xhr_request_1 = __webpack_require__(25);
var HTTP = {
createStreamingSocket: function (url) {
return this.createSocket(http_streaming_socket_1["default"], url);
},
createPollingSocket: function (url) {
return this.createSocket(http_polling_socket_1["default"], url);
},
createSocket: function (hooks, url) {
return new http_socket_1["default"](hooks, url);
},
createXHR: function (method, url) {
return this.createRequest(http_xhr_request_1["default"], method, url);
},
createRequest: function (hooks, method, url) {
return new http_request_1["default"](hooks, method, url);
}
};
exports.__esModule = true;
exports["default"] = HTTP;
/***/ },
/* 20 */
/***/ 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 runtime_1 = __webpack_require__(2);
var dispatcher_1 = __webpack_require__(14);
var MAX_BUFFER_LENGTH = 256 * 1024;
var HTTPRequest = (function (_super) {
__extends(HTTPRequest, _super);
function HTTPRequest(hooks, method, url) {
_super.call(this);
this.hooks = hooks;
this.method = method;
this.url = url;
}
HTTPRequest.prototype.start = function (payload) {
var _this = this;
this.position = 0;
this.xhr = this.hooks.getRequest(this);
this.unloader = function () {
_this.close();
};
runtime_1["default"].addUnloadListener(this.unloader);
this.xhr.open(this.method, this.url, true);
if (this.xhr.setRequestHeader) {
this.xhr.setRequestHeader("Content-Type", "application/json");
}
this.xhr.send(payload);
};
HTTPRequest.prototype.close = function () {
if (this.unloader) {
runtime_1["default"].removeUnloadListener(this.unloader);
this.unloader = null;
}
if (this.xhr) {
this.hooks.abortRequest(this.xhr);
this.xhr = null;
}
};
HTTPRequest.prototype.onChunk = function (status, data) {
while (true) {
var chunk = this.advanceBuffer(data);
if (chunk) {
this.emit("chunk", { status: status, data: chunk });
}
else {
break;
}
}
if (this.isBufferTooLong(data)) {
this.emit("buffer_too_long");
}
};
HTTPRequest.prototype.advanceBuffer = function (buffer) {
var unreadData = buffer.slice(this.position);
var endOfLinePosition = unreadData.indexOf("\n");
if (endOfLinePosition !== -1) {
this.position += endOfLinePosition + 1;
return unreadData.slice(0, endOfLinePosition);
}
else {
return null;
}
};
HTTPRequest.prototype.isBufferTooLong = function (buffer) {
return this.position === buffer.length && buffer.length > MAX_BUFFER_LENGTH;
};
return HTTPRequest;
}(dispatcher_1["default"]));
exports.__esModule = true;
exports["default"] = HTTPRequest;
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var state_1 = __webpack_require__(22);
var util_1 = __webpack_require__(6);
var runtime_1 = __webpack_require__(2);
var autoIncrement = 1;
var HTTPSocket = (function () {
function HTTPSocket(hooks, url) {
this.hooks = hooks;
this.session = randomNumber(1000) + "/" + randomString(8);
this.location = getLocation(url);
this.readyState = state_1["default"].CONNECTING;
this.openStream();
}
HTTPSocket.prototype.send = function (payload) {
return this.sendRaw(JSON.stringify([payload]));
};
HTTPSocket.prototype.ping = function () {
this.hooks.sendHeartbeat(this);
};
HTTPSocket.prototype.close = function (code, reason) {
this.onClose(code, reason, true);
};
HTTPSocket.prototype.sendRaw = function (payload) {
if (this.readyState === state_1["default"].OPEN) {
try {
runtime_1["default"].createSocketRequest("POST", getUniqueURL(getSendURL(this.location, this.session))).start(payload);
return true;
}
catch (e) {
return false;
}
}
else {
return false;
}
};
HTTPSocket.prototype.reconnect = function () {
this.closeStream();
this.openStream();
};
;
HTTPSocket.prototype.onClose = function (code, reason, wasClean) {
this.closeStream();
this.readyState = state_1["default"].CLOSED;
if (this.onclose) {
this.onclose({
code: code,
reason: reason,
wasClean: wasClean
});
}
};
HTTPSocket.prototype.onChunk = function (chunk) {
if (chunk.status !== 200) {
return;
}
if (this.readyState === state_1["default"].OPEN) {
this.onActivity();
}
var payload;
var type = chunk.data.slice(0, 1);
switch (type) {
case 'o':
payload = JSON.parse(chunk.data.slice(1) || '{}');
this.onOpen(payload);
break;
case 'a':
payload = JSON.parse(chunk.data.slice(1) || '[]');
for (var i = 0; i < payload.length; i++) {
this.onEvent(payload[i]);
}
break;
case 'm':
payload = JSON.parse(chunk.data.slice(1) || 'null');
this.onEvent(payload);
break;
case 'h':
this.hooks.onHeartbeat(this);
break;
case 'c':
payload = JSON.parse(chunk.data.slice(1) || '[]');
this.onClose(payload[0], payload[1], true);
break;
}
};
HTTPSocket.prototype.onOpen = function (options) {
if (this.readyState === state_1["default"].CONNECTING) {
if (options && options.hostname) {
this.location.base = replaceHost(this.location.base, options.hostname);
}
this.readyState = state_1["default"].OPEN;
if (this.onopen) {
this.onopen();
}
}
else {
this.onClose(1006, "Server lost session", true);
}
};
HTTPSocket.prototype.onEvent = function (event) {
if (this.readyState === state_1["default"].OPEN && this.onmessage) {
this.onmessage({ data: event });
}
};
HTTPSocket.prototype.onActivity = function () {
if (this.onactivity) {
this.onactivity();
}
};
HTTPSocket.prototype.onError = function (error) {
if (this.onerror) {
this.onerror(error);
}
};
HTTPSocket.prototype.openStream = function () {
var _this = this;
this.stream = runtime_1["default"].createSocketRequest("POST", getUniqueURL(this.hooks.getReceiveURL(this.location, this.session)));
this.stream.bind("chunk", function (chunk) {
_this.onChunk(chunk);
});
this.stream.bind("finished", function (status) {
_this.hooks.onFinished(_this, status);
});
this.stream.bind("buffer_too_long", function () {
_this.reconnect();
});
try {
this.stream.start();
}
catch (error) {
util_1["default"].defer(function () {
_this.onError(error);
_this.onClose(1006, "Could not start streaming", false);
});
}
};
HTTPSocket.prototype.closeStream = function () {
if (this.stream) {
this.stream.unbind_all();
this.stream.close();
this.stream = null;
}
};
return HTTPSocket;
}());
function getLocation(url) {
var parts = /([^\?]*)\/*(\??.*)/.exec(url);
return {
base: parts[1],
queryString: parts[2]
};
}
function getSendURL(url, session) {
return url.base + "/" + session + "/xhr_send";
}
function getUniqueURL(url) {
var separator = (url.indexOf('?') === -1) ? "?" : "&";
return url + separator + "t=" + (+new Date()) + "&n=" + autoIncrement++;
}
function replaceHost(url, hostname) {
var url