btrz-seatmaps
Version:
Betterez Seatmaps
1,420 lines (1,406 loc) • 109 kB
JavaScript
"use strict";
var _SeatmapSection;
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _classPrivateMethodInitSpec(e, a) { _checkPrivateRedeclaration(e, a), a.add(e); }
function _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
// 👇️ named export
var Phoenix = function () {
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = function __export(target, all) {
for (var name in all) __defProp(target, name, {
get: all[name],
enumerable: true
});
};
var __copyProps = function __copyProps(to, from, except, desc) {
if (from && _typeof(from) === "object" || typeof from === "function") {
var _iterator = _createForOfIteratorHelper(__getOwnPropNames(from)),
_step;
try {
var _loop = function _loop() {
var key = _step.value;
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: function get() {
return from[key];
},
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
};
for (_iterator.s(); !(_step = _iterator.n()).done;) {
_loop();
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
return to;
};
var __toCommonJS = function __toCommonJS(mod) {
return __copyProps(__defProp({}, "__esModule", {
value: true
}), mod);
};
// js/phoenix/index.js
var phoenix_exports = {};
__export(phoenix_exports, {
Channel: function Channel() {
return _Channel;
},
LongPoll: function LongPoll() {
return _LongPoll;
},
Presence: function Presence() {
return _Presence2;
},
Serializer: function Serializer() {
return serializer_default;
},
Socket: function Socket() {
return _Socket;
}
});
// js/phoenix/utils.js
var closure = function closure(value) {
if (typeof value === "function") {
return value;
} else {
var closure2 = function closure2() {
return value;
};
return closure2;
}
};
// js/phoenix/constants.js
var globalSelf = typeof self !== "undefined" ? self : null;
var phxWindow = typeof window !== "undefined" ? window : null;
var global = globalSelf || phxWindow || global;
var DEFAULT_VSN = "2.0.0";
var SOCKET_STATES = {
connecting: 0,
open: 1,
closing: 2,
closed: 3
};
var DEFAULT_TIMEOUT = 1e4;
var WS_CLOSE_NORMAL = 1e3;
var CHANNEL_STATES = {
closed: "closed",
errored: "errored",
joined: "joined",
joining: "joining",
leaving: "leaving"
};
var CHANNEL_EVENTS = {
close: "phx_close",
error: "phx_error",
join: "phx_join",
reply: "phx_reply",
leave: "phx_leave"
};
var TRANSPORTS = {
longpoll: "longpoll",
websocket: "websocket"
};
var XHR_STATES = {
complete: 4
};
// js/phoenix/push.js
var Push = /*#__PURE__*/function () {
function Push(channel, event, payload, timeout) {
this.channel = channel;
this.event = event;
this.payload = payload || function () {
return {};
};
this.receivedResp = null;
this.timeout = timeout;
this.timeoutTimer = null;
this.recHooks = [];
this.sent = false;
}
return _createClass(Push, [{
key: "resend",
value: function resend(timeout) {
this.timeout = timeout;
this.reset();
this.send();
}
}, {
key: "send",
value: function send() {
if (this.hasReceived("timeout")) {
return;
}
this.startTimeout();
this.sent = true;
this.channel.socket.push({
topic: this.channel.topic,
event: this.event,
payload: this.payload(),
ref: this.ref,
join_ref: this.channel.joinRef()
});
}
}, {
key: "receive",
value: function receive(status, callback) {
if (this.hasReceived(status)) {
callback(this.receivedResp.response);
}
this.recHooks.push({
status: status,
callback: callback
});
return this;
}
}, {
key: "reset",
value: function reset() {
this.cancelRefEvent();
this.ref = null;
this.refEvent = null;
this.receivedResp = null;
this.sent = false;
}
}, {
key: "matchReceive",
value: function matchReceive(_ref2) {
var status = _ref2.status,
response = _ref2.response,
_ref = _ref2._ref;
this.recHooks.filter(function (h) {
return h.status === status;
}).forEach(function (h) {
return h.callback(response);
});
}
}, {
key: "cancelRefEvent",
value: function cancelRefEvent() {
if (!this.refEvent) {
return;
}
this.channel.off(this.refEvent);
}
}, {
key: "cancelTimeout",
value: function cancelTimeout() {
clearTimeout(this.timeoutTimer);
this.timeoutTimer = null;
}
}, {
key: "startTimeout",
value: function startTimeout() {
var _this = this;
if (this.timeoutTimer) {
this.cancelTimeout();
}
this.ref = this.channel.socket.makeRef();
this.refEvent = this.channel.replyEventName(this.ref);
this.channel.on(this.refEvent, function (payload) {
_this.cancelRefEvent();
_this.cancelTimeout();
_this.receivedResp = payload;
_this.matchReceive(payload);
});
this.timeoutTimer = setTimeout(function () {
_this.trigger("timeout", {});
}, this.timeout);
}
}, {
key: "hasReceived",
value: function hasReceived(status) {
return this.receivedResp && this.receivedResp.status === status;
}
}, {
key: "trigger",
value: function trigger(status, response) {
this.channel.trigger(this.refEvent, {
status: status,
response: response
});
}
}]);
}();
// js/phoenix/timer.js
var Timer = /*#__PURE__*/function () {
function Timer(callback, timerCalc) {
this.callback = callback;
this.timerCalc = timerCalc;
this.timer = null;
this.tries = 0;
}
return _createClass(Timer, [{
key: "reset",
value: function reset() {
this.tries = 0;
clearTimeout(this.timer);
}
}, {
key: "scheduleTimeout",
value: function scheduleTimeout() {
var _this2 = this;
clearTimeout(this.timer);
this.timer = setTimeout(function () {
_this2.tries = _this2.tries + 1;
_this2.callback();
}, this.timerCalc(this.tries + 1));
}
}]);
}();
// js/phoenix/channel.js
var _Channel = /*#__PURE__*/function () {
function _Channel(topic, params, socket) {
var _this3 = this;
this.state = CHANNEL_STATES.closed;
this.topic = topic;
this.params = closure(params || {});
this.socket = socket;
this.bindings = [];
this.bindingRef = 0;
this.timeout = this.socket.timeout;
this.joinedOnce = false;
this.joinPush = new Push(this, CHANNEL_EVENTS.join, this.params, this.timeout);
this.pushBuffer = [];
this.stateChangeRefs = [];
this.rejoinTimer = new Timer(function () {
if (_this3.socket.isConnected()) {
_this3.rejoin();
}
}, this.socket.rejoinAfterMs);
this.stateChangeRefs.push(this.socket.onError(function () {
return _this3.rejoinTimer.reset();
}));
this.stateChangeRefs.push(this.socket.onOpen(function () {
_this3.rejoinTimer.reset();
if (_this3.isErrored()) {
_this3.rejoin();
}
}));
this.joinPush.receive("ok", function () {
_this3.state = CHANNEL_STATES.joined;
_this3.rejoinTimer.reset();
_this3.pushBuffer.forEach(function (pushEvent) {
return pushEvent.send();
});
_this3.pushBuffer = [];
});
this.joinPush.receive("error", function () {
_this3.state = CHANNEL_STATES.errored;
if (_this3.socket.isConnected()) {
_this3.rejoinTimer.scheduleTimeout();
}
});
this.onClose(function () {
_this3.rejoinTimer.reset();
if (_this3.socket.hasLogger()) _this3.socket.log("channel", "close ".concat(_this3.topic, " ").concat(_this3.joinRef()));
_this3.state = CHANNEL_STATES.closed;
_this3.socket.remove(_this3);
});
this.onError(function (reason) {
if (_this3.socket.hasLogger()) _this3.socket.log("channel", "error ".concat(_this3.topic), reason);
if (_this3.isJoining()) {
_this3.joinPush.reset();
}
_this3.state = CHANNEL_STATES.errored;
if (_this3.socket.isConnected()) {
_this3.rejoinTimer.scheduleTimeout();
}
});
this.joinPush.receive("timeout", function () {
if (_this3.socket.hasLogger()) _this3.socket.log("channel", "timeout ".concat(_this3.topic, " (").concat(_this3.joinRef(), ")"), _this3.joinPush.timeout);
var leavePush = new Push(_this3, CHANNEL_EVENTS.leave, closure({}), _this3.timeout);
leavePush.send();
_this3.state = CHANNEL_STATES.errored;
_this3.joinPush.reset();
if (_this3.socket.isConnected()) {
_this3.rejoinTimer.scheduleTimeout();
}
});
this.on(CHANNEL_EVENTS.reply, function (payload, ref) {
_this3.trigger(_this3.replyEventName(ref), payload);
});
}
return _createClass(_Channel, [{
key: "join",
value: function join() {
var timeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.timeout;
if (this.joinedOnce) {
throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");
} else {
this.timeout = timeout;
this.joinedOnce = true;
this.rejoin();
return this.joinPush;
}
}
}, {
key: "onClose",
value: function onClose(callback) {
this.on(CHANNEL_EVENTS.close, callback);
}
}, {
key: "onError",
value: function onError(callback) {
return this.on(CHANNEL_EVENTS.error, function (reason) {
return callback(reason);
});
}
}, {
key: "on",
value: function on(event, callback) {
var ref = this.bindingRef++;
this.bindings.push({
event: event,
ref: ref,
callback: callback
});
return ref;
}
}, {
key: "off",
value: function off(event, ref) {
this.bindings = this.bindings.filter(function (bind) {
return !(bind.event === event && (typeof ref === "undefined" || ref === bind.ref));
});
}
}, {
key: "canPush",
value: function canPush() {
return this.socket.isConnected() && this.isJoined();
}
}, {
key: "push",
value: function push(event, payload) {
var timeout = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.timeout;
payload = payload || {};
if (!this.joinedOnce) {
throw new Error("tried to push '".concat(event, "' to '").concat(this.topic, "' before joining. Use channel.join() before pushing events"));
}
var pushEvent = new Push(this, event, function () {
return payload;
}, timeout);
if (this.canPush()) {
pushEvent.send();
} else {
pushEvent.startTimeout();
this.pushBuffer.push(pushEvent);
}
return pushEvent;
}
}, {
key: "leave",
value: function leave() {
var _this4 = this;
var timeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.timeout;
this.rejoinTimer.reset();
this.joinPush.cancelTimeout();
this.state = CHANNEL_STATES.leaving;
var onClose = function onClose() {
if (_this4.socket.hasLogger()) _this4.socket.log("channel", "leave ".concat(_this4.topic));
_this4.trigger(CHANNEL_EVENTS.close, "leave");
};
var leavePush = new Push(this, CHANNEL_EVENTS.leave, closure({}), timeout);
leavePush.receive("ok", function () {
return onClose();
}).receive("timeout", function () {
return onClose();
});
leavePush.send();
if (!this.canPush()) {
leavePush.trigger("ok", {});
}
return leavePush;
}
}, {
key: "onMessage",
value: function onMessage(_event, payload, _ref) {
return payload;
}
}, {
key: "isMember",
value: function isMember(topic, event, payload, joinRef) {
if (this.topic !== topic) {
return false;
}
if (joinRef && joinRef !== this.joinRef()) {
if (this.socket.hasLogger()) this.socket.log("channel", "dropping outdated message", {
topic: topic,
event: event,
payload: payload,
joinRef: joinRef
});
return false;
} else {
return true;
}
}
}, {
key: "joinRef",
value: function joinRef() {
return this.joinPush.ref;
}
}, {
key: "rejoin",
value: function rejoin() {
var timeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.timeout;
if (this.isLeaving()) {
return;
}
this.socket.leaveOpenTopic(this.topic);
this.state = CHANNEL_STATES.joining;
this.joinPush.resend(timeout);
}
}, {
key: "trigger",
value: function trigger(event, payload, ref, joinRef) {
var handledPayload = this.onMessage(event, payload, ref, joinRef);
if (payload && !handledPayload) {
throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");
}
var eventBindings = this.bindings.filter(function (bind) {
return bind.event === event;
});
for (var i = 0; i < eventBindings.length; i++) {
var bind = eventBindings[i];
bind.callback(handledPayload, ref, joinRef || this.joinRef());
}
}
}, {
key: "replyEventName",
value: function replyEventName(ref) {
return "chan_reply_".concat(ref);
}
}, {
key: "isClosed",
value: function isClosed() {
return this.state === CHANNEL_STATES.closed;
}
}, {
key: "isErrored",
value: function isErrored() {
return this.state === CHANNEL_STATES.errored;
}
}, {
key: "isJoined",
value: function isJoined() {
return this.state === CHANNEL_STATES.joined;
}
}, {
key: "isJoining",
value: function isJoining() {
return this.state === CHANNEL_STATES.joining;
}
}, {
key: "isLeaving",
value: function isLeaving() {
return this.state === CHANNEL_STATES.leaving;
}
}]);
}();
// js/phoenix/ajax.js
var Ajax = /*#__PURE__*/function () {
function Ajax() {}
return _createClass(Ajax, null, [{
key: "request",
value: function request(method, endPoint, accept, body, timeout, ontimeout, callback) {
if (global.XDomainRequest) {
var req = new global.XDomainRequest();
return this.xdomainRequest(req, method, endPoint, body, timeout, ontimeout, callback);
} else {
var _req = new global.XMLHttpRequest();
return this.xhrRequest(_req, method, endPoint, accept, body, timeout, ontimeout, callback);
}
}
}, {
key: "xdomainRequest",
value: function xdomainRequest(req, method, endPoint, body, timeout, ontimeout, callback) {
var _this5 = this;
req.timeout = timeout;
req.open(method, endPoint);
req.onload = function () {
var response = _this5.parseJSON(req.responseText);
callback && callback(response);
};
if (ontimeout) {
req.ontimeout = ontimeout;
}
req.onprogress = function () {};
req.send(body);
return req;
}
}, {
key: "xhrRequest",
value: function xhrRequest(req, method, endPoint, accept, body, timeout, ontimeout, callback) {
var _this6 = this;
req.open(method, endPoint, true);
req.timeout = timeout;
req.setRequestHeader("Content-Type", accept);
req.onerror = function () {
return callback && callback(null);
};
req.onreadystatechange = function () {
if (req.readyState === XHR_STATES.complete && callback) {
var response = _this6.parseJSON(req.responseText);
callback(response);
}
};
if (ontimeout) {
req.ontimeout = ontimeout;
}
req.send(body);
return req;
}
}, {
key: "parseJSON",
value: function parseJSON(resp) {
if (!resp || resp === "") {
return null;
}
try {
return JSON.parse(resp);
} catch (e) {
console && console.log("failed to parse JSON response", resp);
return null;
}
}
}, {
key: "serialize",
value: function serialize(obj, parentKey) {
var queryStr = [];
for (var key in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, key)) {
continue;
}
var paramKey = parentKey ? "".concat(parentKey, "[").concat(key, "]") : key;
var paramVal = obj[key];
if (_typeof(paramVal) === "object") {
queryStr.push(this.serialize(paramVal, paramKey));
} else {
queryStr.push(encodeURIComponent(paramKey) + "=" + encodeURIComponent(paramVal));
}
}
return queryStr.join("&");
}
}, {
key: "appendParams",
value: function appendParams(url, params) {
if (Object.keys(params).length === 0) {
return url;
}
var prefix = url.match(/\?/) ? "&" : "?";
return "".concat(url).concat(prefix).concat(this.serialize(params));
}
}]);
}();
// js/phoenix/longpoll.js
var arrayBufferToBase64 = function arrayBufferToBase64(buffer) {
var binary = "";
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
};
var _LongPoll = /*#__PURE__*/function () {
function _LongPoll(endPoint) {
this.endPoint = null;
this.token = null;
this.skipHeartbeat = true;
this.reqs = /* @__PURE__ */new Set();
this.awaitingBatchAck = false;
this.currentBatch = null;
this.currentBatchTimer = null;
this.batchBuffer = [];
this.onopen = function () {};
this.onerror = function () {};
this.onmessage = function () {};
this.onclose = function () {};
this.pollEndpoint = this.normalizeEndpoint(endPoint);
this.readyState = SOCKET_STATES.connecting;
this.poll();
}
return _createClass(_LongPoll, [{
key: "normalizeEndpoint",
value: function normalizeEndpoint(endPoint) {
return endPoint.replace("ws://", "http://").replace("wss://", "https://").replace(new RegExp("(.*)/" + TRANSPORTS.websocket), "$1/" + TRANSPORTS.longpoll);
}
}, {
key: "endpointURL",
value: function endpointURL() {
return Ajax.appendParams(this.pollEndpoint, {
token: this.token
});
}
}, {
key: "closeAndRetry",
value: function closeAndRetry(code, reason, wasClean) {
this.close(code, reason, wasClean);
this.readyState = SOCKET_STATES.connecting;
}
}, {
key: "ontimeout",
value: function ontimeout() {
this.onerror("timeout");
this.closeAndRetry(1005, "timeout", false);
}
}, {
key: "isActive",
value: function isActive() {
return this.readyState === SOCKET_STATES.open || this.readyState === SOCKET_STATES.connecting;
}
}, {
key: "poll",
value: function poll() {
var _this7 = this;
this.ajax("GET", "application/json", null, function () {
return _this7.ontimeout();
}, function (resp) {
if (resp) {
var status = resp.status,
token = resp.token,
messages = resp.messages;
_this7.token = token;
} else {
status = 0;
}
switch (status) {
case 200:
messages.forEach(function (msg) {
setTimeout(function () {
return _this7.onmessage({
data: msg
});
}, 0);
});
_this7.poll();
break;
case 204:
_this7.poll();
break;
case 410:
_this7.readyState = SOCKET_STATES.open;
_this7.onopen({});
_this7.poll();
break;
case 403:
_this7.onerror(403);
_this7.close(1008, "forbidden", false);
break;
case 0:
case 500:
_this7.onerror(500);
_this7.closeAndRetry(1011, "internal server error", 500);
break;
default:
throw new Error("unhandled poll status ".concat(status));
}
});
}
}, {
key: "send",
value: function send(body) {
var _this8 = this;
if (typeof body !== "string") {
body = arrayBufferToBase64(body);
}
if (this.currentBatch) {
this.currentBatch.push(body);
} else if (this.awaitingBatchAck) {
this.batchBuffer.push(body);
} else {
this.currentBatch = [body];
this.currentBatchTimer = setTimeout(function () {
_this8.batchSend(_this8.currentBatch);
_this8.currentBatch = null;
}, 0);
}
}
}, {
key: "batchSend",
value: function batchSend(messages) {
var _this9 = this;
this.awaitingBatchAck = true;
this.ajax("POST", "application/x-ndjson", messages.join("\n"), function () {
return _this9.onerror("timeout");
}, function (resp) {
_this9.awaitingBatchAck = false;
if (!resp || resp.status !== 200) {
_this9.onerror(resp && resp.status);
_this9.closeAndRetry(1011, "internal server error", false);
} else if (_this9.batchBuffer.length > 0) {
_this9.batchSend(_this9.batchBuffer);
_this9.batchBuffer = [];
}
});
}
}, {
key: "close",
value: function close(code, reason, wasClean) {
var _iterator2 = _createForOfIteratorHelper(this.reqs),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var req = _step2.value;
req.abort();
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
this.readyState = SOCKET_STATES.closed;
var opts = Object.assign({
code: 1e3,
reason: void 0,
wasClean: true
}, {
code: code,
reason: reason,
wasClean: wasClean
});
this.batchBuffer = [];
clearTimeout(this.currentBatchTimer);
this.currentBatchTimer = null;
if (typeof CloseEvent !== "undefined") {
this.onclose(new CloseEvent("close", opts));
} else {
this.onclose(opts);
}
}
}, {
key: "ajax",
value: function ajax(method, contentType, body, onCallerTimeout, callback) {
var _this0 = this;
var req;
var ontimeout = function ontimeout() {
_this0.reqs["delete"](req);
onCallerTimeout();
};
req = Ajax.request(method, this.endpointURL(), contentType, body, this.timeout, ontimeout, function (resp) {
_this0.reqs["delete"](req);
if (_this0.isActive()) {
callback(resp);
}
});
this.reqs.add(req);
}
}]);
}();
// js/phoenix/presence.js
var _Presence2 = /*#__PURE__*/function () {
function _Presence(channel) {
var _this1 = this;
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var events = opts.events || {
state: "presence_state",
diff: "presence_diff"
};
this.state = {};
this.pendingDiffs = [];
this.channel = channel;
this.joinRef = null;
this.caller = {
onJoin: function onJoin() {},
onLeave: function onLeave() {},
onSync: function onSync() {}
};
this.channel.on(events.state, function (newState) {
var _this1$caller = _this1.caller,
onJoin = _this1$caller.onJoin,
onLeave = _this1$caller.onLeave,
onSync = _this1$caller.onSync;
_this1.joinRef = _this1.channel.joinRef();
_this1.state = _Presence2.syncState(_this1.state, newState, onJoin, onLeave);
_this1.pendingDiffs.forEach(function (diff) {
_this1.state = _Presence2.syncDiff(_this1.state, diff, onJoin, onLeave);
});
_this1.pendingDiffs = [];
onSync();
});
this.channel.on(events.diff, function (diff) {
var _this1$caller2 = _this1.caller,
onJoin = _this1$caller2.onJoin,
onLeave = _this1$caller2.onLeave,
onSync = _this1$caller2.onSync;
if (_this1.inPendingSyncState()) {
_this1.pendingDiffs.push(diff);
} else {
_this1.state = _Presence2.syncDiff(_this1.state, diff, onJoin, onLeave);
onSync();
}
});
}
return _createClass(_Presence, [{
key: "onJoin",
value: function onJoin(callback) {
this.caller.onJoin = callback;
}
}, {
key: "onLeave",
value: function onLeave(callback) {
this.caller.onLeave = callback;
}
}, {
key: "onSync",
value: function onSync(callback) {
this.caller.onSync = callback;
}
}, {
key: "list",
value: function list(by) {
return _Presence2.list(this.state, by);
}
}, {
key: "inPendingSyncState",
value: function inPendingSyncState() {
return !this.joinRef || this.joinRef !== this.channel.joinRef();
}
}], [{
key: "syncState",
value: function syncState(currentState, newState, onJoin, onLeave) {
var _this10 = this;
var state = this.clone(currentState);
var joins = {};
var leaves = {};
this.map(state, function (key, presence) {
if (!newState[key]) {
leaves[key] = presence;
}
});
this.map(newState, function (key, newPresence) {
var currentPresence = state[key];
if (currentPresence) {
var newRefs = newPresence.metas.map(function (m) {
return m.phx_ref;
});
var curRefs = currentPresence.metas.map(function (m) {
return m.phx_ref;
});
var joinedMetas = newPresence.metas.filter(function (m) {
return curRefs.indexOf(m.phx_ref) < 0;
});
var leftMetas = currentPresence.metas.filter(function (m) {
return newRefs.indexOf(m.phx_ref) < 0;
});
if (joinedMetas.length > 0) {
joins[key] = newPresence;
joins[key].metas = joinedMetas;
}
if (leftMetas.length > 0) {
leaves[key] = _this10.clone(currentPresence);
leaves[key].metas = leftMetas;
}
} else {
joins[key] = newPresence;
}
});
return this.syncDiff(state, {
joins: joins,
leaves: leaves
}, onJoin, onLeave);
}
}, {
key: "syncDiff",
value: function syncDiff(state, diff, onJoin, onLeave) {
var _this11 = this;
var _this$clone = this.clone(diff),
joins = _this$clone.joins,
leaves = _this$clone.leaves;
if (!onJoin) {
onJoin = function onJoin() {};
}
if (!onLeave) {
onLeave = function onLeave() {};
}
this.map(joins, function (key, newPresence) {
var currentPresence = state[key];
state[key] = _this11.clone(newPresence);
if (currentPresence) {
var _state$key$metas;
var joinedRefs = state[key].metas.map(function (m) {
return m.phx_ref;
});
var curMetas = currentPresence.metas.filter(function (m) {
return joinedRefs.indexOf(m.phx_ref) < 0;
});
(_state$key$metas = state[key].metas).unshift.apply(_state$key$metas, _toConsumableArray(curMetas));
}
onJoin(key, currentPresence, newPresence);
});
this.map(leaves, function (key, leftPresence) {
var currentPresence = state[key];
if (!currentPresence) {
return;
}
var refsToRemove = leftPresence.metas.map(function (m) {
return m.phx_ref;
});
currentPresence.metas = currentPresence.metas.filter(function (p) {
return refsToRemove.indexOf(p.phx_ref) < 0;
});
onLeave(key, currentPresence, leftPresence);
if (currentPresence.metas.length === 0) {
delete state[key];
}
});
return state;
}
}, {
key: "list",
value: function list(presences, chooser) {
if (!chooser) {
chooser = function chooser(key, pres) {
return pres;
};
}
return this.map(presences, function (key, presence) {
return chooser(key, presence);
});
}
}, {
key: "map",
value: function map(obj, func) {
return Object.getOwnPropertyNames(obj).map(function (key) {
return func(key, obj[key]);
});
}
}, {
key: "clone",
value: function clone(obj) {
return JSON.parse(JSON.stringify(obj));
}
}]);
}();
// js/phoenix/serializer.js
var serializer_default = {
HEADER_LENGTH: 1,
META_LENGTH: 4,
KINDS: {
push: 0,
reply: 1,
broadcast: 2
},
encode: function encode(msg, callback) {
if (msg.payload.constructor === ArrayBuffer) {
return callback(this.binaryEncode(msg));
} else {
var payload = [msg.join_ref, msg.ref, msg.topic, msg.event, msg.payload];
return callback(JSON.stringify(payload));
}
},
decode: function decode(rawPayload, callback) {
if (rawPayload.constructor === ArrayBuffer) {
return callback(this.binaryDecode(rawPayload));
} else {
var _JSON$parse = JSON.parse(rawPayload),
_JSON$parse2 = _slicedToArray(_JSON$parse, 5),
join_ref = _JSON$parse2[0],
ref = _JSON$parse2[1],
topic = _JSON$parse2[2],
event = _JSON$parse2[3],
payload = _JSON$parse2[4];
return callback({
join_ref: join_ref,
ref: ref,
topic: topic,
event: event,
payload: payload
});
}
},
binaryEncode: function binaryEncode(message) {
var join_ref = message.join_ref,
ref = message.ref,
event = message.event,
topic = message.topic,
payload = message.payload;
var metaLength = this.META_LENGTH + join_ref.length + ref.length + topic.length + event.length;
var header = new ArrayBuffer(this.HEADER_LENGTH + metaLength);
var view = new DataView(header);
var offset = 0;
view.setUint8(offset++, this.KINDS.push);
view.setUint8(offset++, join_ref.length);
view.setUint8(offset++, ref.length);
view.setUint8(offset++, topic.length);
view.setUint8(offset++, event.length);
Array.from(join_ref, function (_char) {
return view.setUint8(offset++, _char.charCodeAt(0));
});
Array.from(ref, function (_char2) {
return view.setUint8(offset++, _char2.charCodeAt(0));
});
Array.from(topic, function (_char3) {
return view.setUint8(offset++, _char3.charCodeAt(0));
});
Array.from(event, function (_char4) {
return view.setUint8(offset++, _char4.charCodeAt(0));
});
var combined = new Uint8Array(header.byteLength + payload.byteLength);
combined.set(new Uint8Array(header), 0);
combined.set(new Uint8Array(payload), header.byteLength);
return combined.buffer;
},
binaryDecode: function binaryDecode(buffer) {
var view = new DataView(buffer);
var kind = view.getUint8(0);
var decoder = new TextDecoder();
switch (kind) {
case this.KINDS.push:
return this.decodePush(buffer, view, decoder);
case this.KINDS.reply:
return this.decodeReply(buffer, view, decoder);
case this.KINDS.broadcast:
return this.decodeBroadcast(buffer, view, decoder);
}
},
decodePush: function decodePush(buffer, view, decoder) {
var joinRefSize = view.getUint8(1);
var topicSize = view.getUint8(2);
var eventSize = view.getUint8(3);
var offset = this.HEADER_LENGTH + this.META_LENGTH - 1;
var joinRef = decoder.decode(buffer.slice(offset, offset + joinRefSize));
offset = offset + joinRefSize;
var topic = decoder.decode(buffer.slice(offset, offset + topicSize));
offset = offset + topicSize;
var event = decoder.decode(buffer.slice(offset, offset + eventSize));
offset = offset + eventSize;
var data = buffer.slice(offset, buffer.byteLength);
return {
join_ref: joinRef,
ref: null,
topic: topic,
event: event,
payload: data
};
},
decodeReply: function decodeReply(buffer, view, decoder) {
var joinRefSize = view.getUint8(1);
var refSize = view.getUint8(2);
var topicSize = view.getUint8(3);
var eventSize = view.getUint8(4);
var offset = this.HEADER_LENGTH + this.META_LENGTH;
var joinRef = decoder.decode(buffer.slice(offset, offset + joinRefSize));
offset = offset + joinRefSize;
var ref = decoder.decode(buffer.slice(offset, offset + refSize));
offset = offset + refSize;
var topic = decoder.decode(buffer.slice(offset, offset + topicSize));
offset = offset + topicSize;
var event = decoder.decode(buffer.slice(offset, offset + eventSize));
offset = offset + eventSize;
var data = buffer.slice(offset, buffer.byteLength);
var payload = {
status: event,
response: data
};
return {
join_ref: joinRef,
ref: ref,
topic: topic,
event: CHANNEL_EVENTS.reply,
payload: payload
};
},
decodeBroadcast: function decodeBroadcast(buffer, view, decoder) {
var topicSize = view.getUint8(1);
var eventSize = view.getUint8(2);
var offset = this.HEADER_LENGTH + 2;
var topic = decoder.decode(buffer.slice(offset, offset + topicSize));
offset = offset + topicSize;
var event = decoder.decode(buffer.slice(offset, offset + eventSize));
offset = offset + eventSize;
var data = buffer.slice(offset, buffer.byteLength);
return {
join_ref: null,
ref: null,
topic: topic,
event: event,
payload: data
};
}
};
// js/phoenix/socket.js
var _Socket = /*#__PURE__*/function () {
function _Socket(endPoint) {
var _this12 = this;
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
this.stateChangeCallbacks = {
open: [],
close: [],
error: [],
message: []
};
this.channels = [];
this.sendBuffer = [];
this.ref = 0;
this.timeout = opts.timeout || DEFAULT_TIMEOUT;
this.transport = opts.transport || global.WebSocket || _LongPoll;
this.establishedConnections = 0;
this.defaultEncoder = serializer_default.encode.bind(serializer_default);
this.defaultDecoder = serializer_default.decode.bind(serializer_default);
this.closeWasClean = false;
this.binaryType = opts.binaryType || "arraybuffer";
this.connectClock = 1;
if (this.transport !== _LongPoll) {
this.encode = opts.encode || this.defaultEncoder;
this.decode = opts.decode || this.defaultDecoder;
} else {
this.encode = this.defaultEncoder;
this.decode = this.defaultDecoder;
}
var awaitingConnectionOnPageShow = null;
if (phxWindow && phxWindow.addEventListener) {
phxWindow.addEventListener("pagehide", function (_e) {
if (_this12.conn) {
_this12.disconnect();
awaitingConnectionOnPageShow = _this12.connectClock;
}
});
phxWindow.addEventListener("pageshow", function (_e) {
if (awaitingConnectionOnPageShow === _this12.connectClock) {
awaitingConnectionOnPageShow = null;
_this12.connect();
}
});
}
this.heartbeatIntervalMs = opts.heartbeatIntervalMs || 3e4;
this.rejoinAfterMs = function (tries) {
if (opts.rejoinAfterMs) {
return opts.rejoinAfterMs(tries);
} else {
return [1e3, 2e3, 5e3][tries - 1] || 1e4;
}
};
this.reconnectAfterMs = function (tries) {
if (opts.reconnectAfterMs) {
return opts.reconnectAfterMs(tries);
} else {
return [10, 50, 100, 150, 200, 250, 500, 1e3, 2e3][tries - 1] || 5e3;
}
};
this.logger = opts.logger || null;
this.longpollerTimeout = opts.longpollerTimeout || 2e4;
this.params = closure(opts.params || {});
this.endPoint = "".concat(endPoint, "/").concat(TRANSPORTS.websocket);
this.vsn = opts.vsn || DEFAULT_VSN;
this.heartbeatTimeoutTimer = null;
this.heartbeatTimer = null;
this.pendingHeartbeatRef = null;
this.reconnectTimer = new Timer(function () {
_this12.teardown(function () {
return _this12.connect();
});
}, this.reconnectAfterMs);
}
return _createClass(_Socket, [{
key: "getLongPollTransport",
value: function getLongPollTransport() {
return _LongPoll;
}
}, {
key: "replaceTransport",
value: function replaceTransport(newTransport) {
this.connectClock++;
this.closeWasClean = true;
this.reconnectTimer.reset();
this.sendBuffer = [];
if (this.conn) {
this.conn.close();
this.conn = null;
}
this.transport = newTransport;
}
}, {
key: "protocol",
value: function protocol() {
return location.protocol.match(/^https/) ? "wss" : "ws";
}
}, {
key: "endPointURL",
value: function endPointURL() {
var uri = Ajax.appendParams(Ajax.appendParams(this.endPoint, this.params()), {
vsn: this.vsn
});
if (uri.charAt(0) !== "/") {
return uri;
}
if (uri.charAt(1) === "/") {
return "".concat(this.protocol(), ":").concat(uri);
}
return "".concat(this.protocol(), "://").concat(location.host).concat(uri);
}
}, {
key: "disconnect",
value: function disconnect(callback, code, reason) {
this.connectClock++;
this.closeWasClean = true;
this.reconnectTimer.reset();
this.teardown(callback, code, reason);
}
}, {
key: "connect",
value: function connect(params) {
var _this13 = this;
if (params) {
console && console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor");
this.params = closure(params);
}
if (this.conn) {
return;
}
this.connectClock++;
this.closeWasClean = false;
this.conn = new this.transport(this.endPointURL());
this.conn.binaryType = this.binaryType;
this.conn.timeout = this.longpollerTimeout;
this.conn.onopen = function () {
return _this13.onConnOpen();
};
this.conn.onerror = function (error) {
return _this13.onConnError(error);
};
this.conn.onmessage = function (event) {
return _this13.onConnMessage(event);
};
this.conn.onclose = function (event) {
return _this13.onConnClose(event);
};
}
}, {
key: "log",
value: function log(kind, msg, data) {
this.logger(kind, msg, data);
}
}, {
key: "hasLogger",
value: function hasLogger() {
return this.logger !== null;
}
}, {
key: "onOpen",
value: function onOpen(callback) {
var ref = this.makeRef();
this.stateChangeCallbacks.open.push([ref, callback]);
return ref;
}
}, {
key: "onClose",
value: function onClose(callback) {
var ref = this.makeRef();
this.stateChangeCallbacks.close.push([ref, callback]);
return ref;
}
}, {
key: "onError",
value: function onError(callback) {
var ref = this.makeRef();
this.stateChangeCallbacks.error.push([ref, callback]);
return ref;
}
}, {
key: "onMessage",
value: function onMessage(callback) {
var ref = this.makeRef();
this.stateChangeCallbacks.message.push([ref, callback]);
return ref;
}
}, {
key: "ping",
value: function ping(callback) {
var _this14 = this;
if (!this.isConnected()) {
return false;
}
var ref = this.makeRef();
var startTime = Date.now();
this.push({
topic: "phoenix",
event: "heartbeat",
payload: {},
ref: ref
});
var onMsgRef = this.onMessage(function (msg) {
if (msg.ref === ref) {
_this14.off([onMsgRef]);
callback(Date.now() - startTime);
}
});
return true;
}
}, {
key: "clearHeartbeats",
value: function clearHeartbeats() {
clearTimeout(this.heartbeatTimer);
clearTimeout(this.heartbeatTimeoutTimer);
}
}, {
key: "onConnOpen",
value: function onConnOpen() {
if (this.hasLogger()) this.log("transport", "connected to ".concat(this.endPointURL()));
this.closeWasClean = false;
this.establishedConnections++;
this.flushSendBuffer();
this.reconnectTimer.reset();
this.resetHeartbeat();
this.stateChangeCallbacks.open.forEach(function (_ref3) {
var _ref4 = _slicedToArray(_ref3, 2),
callback = _ref4[1];
return callback();
});
}
}, {
key: "heartbeatTimeout",
value: function heartbeatTimeout() {
var _this15 = this;
if (this.pendingHeartbeatRef) {
this.pendingHeartbeatRef = null;
if (this.hasLogger()) {
this.log("transport", "heartbeat timeout. Attempting to re-establish connection");
}
this.triggerChanError();
this.closeWasClean = false;
this.teardown(function () {
return _this15.reconnectTimer.scheduleTimeout();
}, WS_CLOSE_NORMAL, "heartbeat timeout");
}
}
}, {
key: "resetHeartbeat",
value: function resetHeartbeat() {
var _this16 = this;
if (this.conn && this.conn.skipHeartbeat) {
return;
}
this.pendingHeartbeatRef = null;
this.clearHeartbeats();
this.heartbeatTimer = setTimeout(function () {
return _this16.sendHeartbeat();
}, this.heartbeatIntervalMs);
}
}, {
key: "teardown",