diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 7e8adc3f0..003bf6d03 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -53,4 +53,4 @@ jobs: needs: [tests] steps: - name: Tests summary - run: echo -e "\033[38;2;95;215;0m\033[1mAll tests successfully passed" + run: echo -e "\033[38;2;95;215;0m\033[1mAll tests successfully passed" \ No newline at end of file diff --git a/.pubnub.yml b/.pubnub.yml index c9d019e0a..96fb55bb4 100644 --- a/.pubnub.yml +++ b/.pubnub.yml @@ -1,5 +1,10 @@ --- changelog: + - date: 2024-02-21 + version: v7.6.0 + changes: + - type: feature + text: "Adding channel, channelGroup, channelMetadata and userMetadata entities to be first-class citizens to access APIs related to them. Currently, access is provided only for subscription API." - date: 2024-01-16 version: v7.5.0 changes: @@ -938,7 +943,7 @@ supported-platforms: - 'Ubuntu 14.04 and up' - 'Windows 7 and up' version: 'Pubnub Javascript for Node' -version: '7.5.0' +version: '7.6.0' sdks: - full-name: PubNub Javascript SDK short-name: Javascript @@ -954,7 +959,7 @@ sdks: - distribution-type: source distribution-repository: GitHub release package-name: pubnub.js - location: https://github.com/pubnub/javascript/archive/refs/tags/v7.5.0.zip + location: https://github.com/pubnub/javascript/archive/refs/tags/v7.6.0.zip requires: - name: 'agentkeepalive' min-version: '3.5.2' @@ -1625,7 +1630,7 @@ sdks: - distribution-type: library distribution-repository: GitHub release package-name: pubnub.js - location: https://github.com/pubnub/javascript/releases/download/v7.5.0/pubnub.7.5.0.js + location: https://github.com/pubnub/javascript/releases/download/v7.6.0/pubnub.7.6.0.js requires: - name: 'agentkeepalive' min-version: '3.5.2' diff --git a/CHANGELOG.md b/CHANGELOG.md index cdce7699f..bf8d08de1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +## v7.6.0 +February 21 2024 + +#### Added +- Adding channel, channelGroup, channelMetadata and userMetadata entities to be first-class citizens to access APIs related to them. Currently, access is provided only for subscription API. + ## v7.5.0 January 16 2024 diff --git a/README.md b/README.md index 1dc2eb8d9..23b76595e 100644 --- a/README.md +++ b/README.md @@ -28,8 +28,8 @@ Watch [Getting Started with PubNub JS SDK](https://app.dashcam.io/replay/64ee0d2 npm install pubnub ``` * or download one of our builds from our CDN: - * https://cdn.pubnub.com/sdk/javascript/pubnub.7.5.0.js - * https://cdn.pubnub.com/sdk/javascript/pubnub.7.5.0.min.js + * https://cdn.pubnub.com/sdk/javascript/pubnub.7.6.0.js + * https://cdn.pubnub.com/sdk/javascript/pubnub.7.6.0.min.js 2. Configure your keys: diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index 1c0eca8fc..112124b0c 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -108,7 +108,7 @@ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } - function __read(o, n) { + function __read$1(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; @@ -125,7 +125,7 @@ return ar; } - function __spreadArray(to, from, pack) { + function __spreadArray$1(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); @@ -794,7 +794,7 @@ return this; }; default_1.prototype.getVersion = function () { - return '7.5.0'; + return '7.6.0'; }; default_1.prototype._setRetryConfiguration = function (configuration) { if (configuration.minimumdelay < 2) { @@ -1802,49 +1802,6 @@ return default_1; }()); - function objectToList(o) { - var l = []; - Object.keys(o).forEach(function (key) { return l.push(key); }); - return l; - } - function encodeString(input) { - return encodeURIComponent(input).replace(/[!~*'()]/g, function (x) { return "%".concat(x.charCodeAt(0).toString(16).toUpperCase()); }); - } - function objectToListSorted(o) { - return objectToList(o).sort(); - } - function signPamFromParams(params) { - var l = objectToListSorted(params); - return l.map(function (paramKey) { return "".concat(paramKey, "=").concat(encodeString(params[paramKey])); }).join('&'); - } - function endsWith(searchString, suffix) { - return searchString.indexOf(suffix, this.length - suffix.length) !== -1; - } - function createPromise() { - var successResolve; - var failureResolve; - var promise = new Promise(function (fulfill, reject) { - successResolve = fulfill; - failureResolve = reject; - }); - return { promise: promise, reject: failureResolve, fulfill: successResolve }; - } - function stringToArrayBuffer(str) { - var buf = new ArrayBuffer(str.length * 2); - var bufView = new Uint16Array(buf); - for (var i = 0, strLen = str.length; i < strLen; i++) { - bufView[i] = str.charCodeAt(i); - } - return buf; - } - var utils$5 = { - signPamFromParams: signPamFromParams, - endsWith: endsWith, - createPromise: createPromise, - encodeString: encodeString, - stringToArrayBuffer: stringToArrayBuffer, - }; - /* */ var categories = { // SDK will announce when the network appears to be connected again. @@ -1872,7 +1829,7 @@ var default_1$7 = /** @class */ (function () { function default_1(_a) { - var subscribeEndpoint = _a.subscribeEndpoint, leaveEndpoint = _a.leaveEndpoint, heartbeatEndpoint = _a.heartbeatEndpoint, setStateEndpoint = _a.setStateEndpoint, timeEndpoint = _a.timeEndpoint, getFileUrl = _a.getFileUrl, config = _a.config, crypto = _a.crypto, listenerManager = _a.listenerManager, cryptoModule = _a.cryptoModule; + var subscribeEndpoint = _a.subscribeEndpoint, leaveEndpoint = _a.leaveEndpoint, heartbeatEndpoint = _a.heartbeatEndpoint, setStateEndpoint = _a.setStateEndpoint, timeEndpoint = _a.timeEndpoint, getFileUrl = _a.getFileUrl, config = _a.config, crypto = _a.crypto, listenerManager = _a.listenerManager, cryptoModule = _a.cryptoModule, eventEmitter = _a.eventEmitter; this._listenerManager = listenerManager; this._config = config; this._leaveEndpoint = leaveEndpoint; @@ -1899,6 +1856,7 @@ this._dedupingManager = new default_1$8({ config: config }); if (this._cryptoModule) this._decoder = new TextDecoder(); + this._eventEmitter = eventEmitter; } default_1.prototype.adaptStateChange = function (args, callback) { var _this = this; @@ -2249,191 +2207,15 @@ this._listenerManager.announceStatus(countAnnouncement); } messages.forEach(function (message) { - var channel = message.channel; - var subscriptionMatch = message.subscriptionMatch; - var publishMetaData = message.publishMetaData; - if (channel === subscriptionMatch) { - subscriptionMatch = null; - } + message.channel; + message.subscriptionMatch; if (dedupeOnSubscribe) { if (_this._dedupingManager.isDuplicate(message)) { return; } _this._dedupingManager.addEntry(message); } - if (utils$5.endsWith(message.channel, '-pnpres')) { - var announce = {}; - announce.channel = null; - announce.subscription = null; - // deprecated --> - announce.actualChannel = subscriptionMatch != null ? channel : null; - announce.subscribedChannel = subscriptionMatch != null ? subscriptionMatch : channel; - // <-- deprecated - if (channel) { - announce.channel = channel.substring(0, channel.lastIndexOf('-pnpres')); - } - if (subscriptionMatch) { - announce.subscription = subscriptionMatch.substring(0, subscriptionMatch.lastIndexOf('-pnpres')); - } - announce.action = message.payload.action; - announce.state = message.payload.data; - announce.timetoken = publishMetaData.publishTimetoken; - announce.occupancy = message.payload.occupancy; - announce.uuid = message.payload.uuid; - announce.timestamp = message.payload.timestamp; - if (message.payload.join) { - announce.join = message.payload.join; - } - if (message.payload.leave) { - announce.leave = message.payload.leave; - } - if (message.payload.timeout) { - announce.timeout = message.payload.timeout; - } - _this._listenerManager.announcePresence(announce); - } - else if (message.messageType === 1) { - // this is a signal message - var announce = {}; - announce.channel = null; - announce.subscription = null; - announce.channel = channel; - announce.subscription = subscriptionMatch; - announce.timetoken = publishMetaData.publishTimetoken; - announce.publisher = message.issuingClientId; - if (message.userMetadata) { - announce.userMetadata = message.userMetadata; - } - announce.message = message.payload; - _this._listenerManager.announceSignal(announce); - } - else if (message.messageType === 2) { - // this is an object message - var announce = {}; - announce.channel = null; - announce.subscription = null; - announce.channel = channel; - announce.subscription = subscriptionMatch; - announce.timetoken = publishMetaData.publishTimetoken; - announce.publisher = message.issuingClientId; - if (message.userMetadata) { - announce.userMetadata = message.userMetadata; - } - announce.message = { - event: message.payload.event, - type: message.payload.type, - data: message.payload.data, - }; - _this._listenerManager.announceObjects(announce); - if (message.payload.type === 'uuid') { - var eventData = _this._renameChannelField(announce); - _this._listenerManager.announceUser(__assign(__assign({}, eventData), { message: __assign(__assign({}, eventData.message), { event: _this._renameEvent(eventData.message.event), type: 'user' }) })); - } - else if (message.payload.type === 'channel') { - var eventData = _this._renameChannelField(announce); - _this._listenerManager.announceSpace(__assign(__assign({}, eventData), { message: __assign(__assign({}, eventData.message), { event: _this._renameEvent(eventData.message.event), type: 'space' }) })); - } - else if (message.payload.type === 'membership') { - var eventData = _this._renameChannelField(announce); - var _a = eventData.message.data, user = _a.uuid, space = _a.channel, membershipData = __rest(_a, ["uuid", "channel"]); - membershipData.user = user; - membershipData.space = space; - _this._listenerManager.announceMembership(__assign(__assign({}, eventData), { message: __assign(__assign({}, eventData.message), { event: _this._renameEvent(eventData.message.event), data: membershipData }) })); - } - } - else if (message.messageType === 3) { - // this is a message action - var announce = {}; - announce.channel = channel; - announce.subscription = subscriptionMatch; - announce.timetoken = publishMetaData.publishTimetoken; - announce.publisher = message.issuingClientId; - announce.data = { - messageTimetoken: message.payload.data.messageTimetoken, - actionTimetoken: message.payload.data.actionTimetoken, - type: message.payload.data.type, - uuid: message.issuingClientId, - value: message.payload.data.value, - }; - announce.event = message.payload.event; - _this._listenerManager.announceMessageAction(announce); - } - else if (message.messageType === 4) { - // this is a file message - var announce = {}; - announce.channel = channel; - announce.subscription = subscriptionMatch; - announce.timetoken = publishMetaData.publishTimetoken; - announce.publisher = message.issuingClientId; - var msgPayload = message.payload; - if (_this._cryptoModule) { - var decryptedPayload = void 0; - try { - var decryptedData = _this._cryptoModule.decrypt(message.payload); - decryptedPayload = - decryptedData instanceof ArrayBuffer ? JSON.parse(_this._decoder.decode(decryptedData)) : decryptedData; - } - catch (e) { - decryptedPayload = null; - announce.error = "Error while decrypting message content: ".concat(e.message); - } - if (decryptedPayload !== null) { - msgPayload = decryptedPayload; - } - } - if (message.userMetadata) { - announce.userMetadata = message.userMetadata; - } - announce.message = msgPayload.message; - announce.file = { - id: msgPayload.file.id, - name: msgPayload.file.name, - url: _this._getFileUrl({ - id: msgPayload.file.id, - name: msgPayload.file.name, - channel: channel, - }), - }; - _this._listenerManager.announceFile(announce); - } - else { - var announce = {}; - announce.channel = null; - announce.subscription = null; - // deprecated --> - announce.actualChannel = subscriptionMatch != null ? channel : null; - announce.subscribedChannel = subscriptionMatch != null ? subscriptionMatch : channel; - // <-- deprecated - announce.channel = channel; - announce.subscription = subscriptionMatch; - announce.timetoken = publishMetaData.publishTimetoken; - announce.publisher = message.issuingClientId; - if (message.userMetadata) { - announce.userMetadata = message.userMetadata; - } - if (_this._cryptoModule) { - var decryptedPayload = void 0; - try { - var decryptedData = _this._cryptoModule.decrypt(message.payload); - decryptedPayload = - decryptedData instanceof ArrayBuffer ? JSON.parse(_this._decoder.decode(decryptedData)) : decryptedData; - } - catch (e) { - decryptedPayload = null; - announce.error = "Error while decrypting message content: ".concat(e.message); - } - if (decryptedPayload != null) { - announce.message = decryptedPayload; - } - else { - announce.message = message.payload; - } - } - else { - announce.message = message.payload; - } - _this._listenerManager.announceMessage(announce); - } + _this._eventEmitter.emitEvent(message); }); this._region = payload.metadata.region; this._startSubscribeLoop(); @@ -2545,6 +2327,11 @@ this._maximumSamplesCount = 100; this._trackedLatencies = {}; this._latencies = {}; + this._telemetryExcludeOperations = [ + OPERATIONS.PNSubscribeOperation, + OPERATIONS.PNReceiveMessagesOperation, + OPERATIONS.PNHandshakeOperation, + ]; this._maximumSamplesCount = configuration.maximumSamplesCount || this._maximumSamplesCount; } /** @@ -2565,13 +2352,13 @@ return latencies; }; default_1.prototype.startLatencyMeasure = function (operationType, identifier) { - if (operationType === OPERATIONS.PNSubscribeOperation || !identifier) { + if (this._telemetryExcludeOperations.includes(operationType) || !identifier) { return; } this._trackedLatencies[identifier] = Date.now(); }; default_1.prototype.stopLatencyMeasure = function (operationType, identifier) { - if (operationType === OPERATIONS.PNSubscribeOperation || !identifier) { + if (this._telemetryExcludeOperations.includes(operationType) || !identifier) { return; } var endpointName = this._endpointName(operationType); @@ -3439,6 +3226,66 @@ return default_1; }()); + function objectToList(o) { + var l = []; + Object.keys(o).forEach(function (key) { return l.push(key); }); + return l; + } + function encodeString(input) { + return encodeURIComponent(input).replace(/[!~*'()]/g, function (x) { return "%".concat(x.charCodeAt(0).toString(16).toUpperCase()); }); + } + function objectToListSorted(o) { + return objectToList(o).sort(); + } + function signPamFromParams(params) { + var l = objectToListSorted(params); + return l.map(function (paramKey) { return "".concat(paramKey, "=").concat(encodeString(params[paramKey])); }).join('&'); + } + function endsWith(searchString, suffix) { + return searchString.indexOf(suffix, this.length - suffix.length) !== -1; + } + function createPromise() { + var successResolve; + var failureResolve; + var promise = new Promise(function (fulfill, reject) { + successResolve = fulfill; + failureResolve = reject; + }); + return { promise: promise, reject: failureResolve, fulfill: successResolve }; + } + function stringToArrayBuffer(str) { + var buf = new ArrayBuffer(str.length * 2); + var bufView = new Uint16Array(buf); + for (var i = 0, strLen = str.length; i < strLen; i++) { + bufView[i] = str.charCodeAt(i); + } + return buf; + } + function removeSingleOccurance(source, elementsToRemove) { + var removed = Object.fromEntries(elementsToRemove.map(function (prop) { return [prop, false]; })); + return source.filter(function (e) { + if (elementsToRemove.includes(e) && !removed[e]) { + removed[e] = true; + return false; + } + return true; + }); + } + function findUniqueCommonElements(a, b) { + return __spreadArray([], __read(a), false).filter(function (value) { + return b.includes(value) && a.indexOf(value) === a.lastIndexOf(value) && b.indexOf(value) === b.lastIndexOf(value); + }); + } + var utils$5 = { + signPamFromParams: signPamFromParams, + endsWith: endsWith, + createPromise: createPromise, + encodeString: encodeString, + stringToArrayBuffer: stringToArrayBuffer, + removeSingleOccurance: removeSingleOccurance, + findUniqueCommonElements: findUniqueCommonElements, + }; + var PubNubError = /** @class */ (function (_super) { __extends(PubNubError, _super); function PubNubError(message, status) { @@ -5106,7 +4953,7 @@ queryParams.limit = (_h = params === null || params === void 0 ? void 0 : params.limit) !== null && _h !== void 0 ? _h : 100; if (params === null || params === void 0 ? void 0 : params.sort) { queryParams.sort = Object.entries((_j = params.sort) !== null && _j !== void 0 ? _j : {}).map(function (_a) { - var _b = __read(_a, 2), key = _b[0], value = _b[1]; + var _b = __read$1(_a, 2), key = _b[0], value = _b[1]; if (value === 'asc' || value === 'desc') { return "".concat(key, ":").concat(value); } @@ -5269,7 +5116,7 @@ queryParams.limit = (_h = params === null || params === void 0 ? void 0 : params.limit) !== null && _h !== void 0 ? _h : 100; if (params === null || params === void 0 ? void 0 : params.sort) { queryParams.sort = Object.entries((_j = params.sort) !== null && _j !== void 0 ? _j : {}).map(function (_a) { - var _b = __read(_a, 2), key = _b[0], value = _b[1]; + var _b = __read$1(_a, 2), key = _b[0], value = _b[1]; if (value === 'asc' || value === 'desc') { return "".concat(key, ":").concat(value); } @@ -5443,7 +5290,7 @@ queryParams.limit = (_o = params === null || params === void 0 ? void 0 : params.limit) !== null && _o !== void 0 ? _o : 100; if (params === null || params === void 0 ? void 0 : params.sort) { queryParams.sort = Object.entries((_p = params.sort) !== null && _p !== void 0 ? _p : {}).map(function (_a) { - var _b = __read(_a, 2), key = _b[0], value = _b[1]; + var _b = __read$1(_a, 2), key = _b[0], value = _b[1]; if (value === 'asc' || value === 'desc') { return "".concat(key, ":").concat(value); } @@ -5536,7 +5383,7 @@ } if (params === null || params === void 0 ? void 0 : params.sort) { queryParams.sort = Object.entries((_j = params.sort) !== null && _j !== void 0 ? _j : {}).map(function (_a) { - var _b = __read(_a, 2), key = _b[0], value = _b[1]; + var _b = __read$1(_a, 2), key = _b[0], value = _b[1]; if (value === 'asc' || value === 'desc') { return "".concat(key, ":").concat(value); } @@ -5609,7 +5456,7 @@ queryParams.limit = (_o = params === null || params === void 0 ? void 0 : params.limit) !== null && _o !== void 0 ? _o : 100; if (params === null || params === void 0 ? void 0 : params.sort) { queryParams.sort = Object.entries((_p = params.sort) !== null && _p !== void 0 ? _p : {}).map(function (_a) { - var _b = __read(_a, 2), key = _b[0], value = _b[1]; + var _b = __read$1(_a, 2), key = _b[0], value = _b[1]; if (value === 'asc' || value === 'desc') { return "".concat(key, ":").concat(value); } @@ -5701,7 +5548,7 @@ } if (params === null || params === void 0 ? void 0 : params.sort) { queryParams.sort = Object.entries((_j = params.sort) !== null && _j !== void 0 ? _j : {}).map(function (_a) { - var _b = __read(_a, 2), key = _b[0], value = _b[1]; + var _b = __read$1(_a, 2), key = _b[0], value = _b[1]; if (value === 'asc' || value === 'desc') { return "".concat(key, ":").concat(value); } @@ -6457,7 +6304,7 @@ var timetoken = incomingParams.timetoken, channelTimetokens = incomingParams.channelTimetokens; var outgoingParams = {}; if (channelTimetokens && channelTimetokens.length === 1) { - var _a = __read(channelTimetokens, 1), tt = _a[0]; + var _a = __read$1(channelTimetokens, 1), tt = _a[0]; outgoingParams.timetoken = tt; } else if (channelTimetokens) { @@ -6731,8 +6578,9 @@ }, getURL: function (_a, params) { var config = _a.config; - var channelsString = params.channels ? params.channels.join(',') : ','; - return "/v2/subscribe/".concat(config.subscribeKey, "/").concat(utils$5.encodeString(channelsString), "/0"); + var _b = params.channels, channels = _b === void 0 ? [] : _b; + var stringifiedChannels = channels.length > 0 ? channels.join(',') : ','; + return "/v2/subscribe/".concat(config.subscribeKey, "/").concat(utils$5.encodeString(stringifiedChannels), "/0"); }, getRequestTimeout: function (_a) { var config = _a.config; @@ -6775,8 +6623,9 @@ }, getURL: function (_a, params) { var config = _a.config; - var channelsString = params.channels ? params.channels.join(',') : ','; - return "/v2/subscribe/".concat(config.subscribeKey, "/").concat(utils$5.encodeString(channelsString), "/0"); + var _b = params.channels, channels = _b === void 0 ? [] : _b; + var stringifiedChannels = channels.length > 0 ? channels.join(',') : ','; + return "/v2/subscribe/".concat(config.subscribeKey, "/").concat(utils$5.encodeString(stringifiedChannels), "/0"); }, getRequestTimeout: function (_a) { var config = _a.config; @@ -6920,7 +6769,7 @@ }); var transition = this.currentState.transition(this.currentContext, event); if (transition) { - var _d = __read(transition, 3), newState = _d[0], newContext = _d[1], effects = _d[2]; + var _d = __read$1(transition, 3), newState = _d[0], newContext = _d[1], effects = _d[2]; try { for (var _e = __values(this.currentState.exitEffects), _f = _e.next(); !_f.done; _f = _e.next()) { var effect = _f.value; @@ -7019,7 +6868,7 @@ var e_1, _a; try { for (var _b = __values(this.instances.entries()), _c = _b.next(); !_c.done; _c = _b.next()) { - var _d = __read(_c.value, 2), key = _d[0], instance = _d[1]; + var _d = __read$1(_c.value, 2), key = _d[0], instance = _d[1]; instance.cancel(); this.instances.delete(key); } @@ -7044,7 +6893,7 @@ } return { type: type, - payload: fn === null || fn === void 0 ? void 0 : fn.apply(void 0, __spreadArray([], __read(args), false)), + payload: fn === null || fn === void 0 ? void 0 : fn.apply(void 0, __spreadArray$1([], __read$1(args), false)), }; }; creator.type = type; @@ -7056,7 +6905,7 @@ for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } - return { type: type, payload: fn.apply(void 0, __spreadArray([], __read(args), false)), managed: false }; + return { type: type, payload: fn.apply(void 0, __spreadArray$1([], __read$1(args), false)), managed: false }; }; creator.type = type; return creator; @@ -7067,7 +6916,7 @@ for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } - return { type: type, payload: fn.apply(void 0, __spreadArray([], __read(args), false)), managed: true }; + return { type: type, payload: fn.apply(void 0, __spreadArray$1([], __read$1(args), false)), managed: true }; }; creator.type = type; creator.cancel = { type: 'CANCEL', payload: type, managed: false }; @@ -7726,44 +7575,47 @@ EventEngine.prototype.subscribe = function (_a) { var _this = this; var channels = _a.channels, channelGroups = _a.channelGroups, timetoken = _a.timetoken, withPresence = _a.withPresence; - this.channels = __spreadArray(__spreadArray([], __read(this.channels), false), __read((channels !== null && channels !== void 0 ? channels : [])), false); - this.groups = __spreadArray(__spreadArray([], __read(this.groups), false), __read((channelGroups !== null && channelGroups !== void 0 ? channelGroups : [])), false); + this.channels = __spreadArray$1(__spreadArray$1([], __read$1(this.channels), false), __read$1((channels !== null && channels !== void 0 ? channels : [])), false); + this.groups = __spreadArray$1(__spreadArray$1([], __read$1(this.groups), false), __read$1((channelGroups !== null && channelGroups !== void 0 ? channelGroups : [])), false); if (withPresence) { this.channels.map(function (c) { return _this.channels.push("".concat(c, "-pnpres")); }); this.groups.map(function (g) { return _this.groups.push("".concat(g, "-pnpres")); }); } if (timetoken) { - this.engine.transition(restore(this.channels, this.groups, timetoken)); + this.engine.transition(restore(Array.from(new Set(__spreadArray$1(__spreadArray$1([], __read$1(this.channels), false), __read$1((channels !== null && channels !== void 0 ? channels : [])), false))), Array.from(new Set(__spreadArray$1(__spreadArray$1([], __read$1(this.groups), false), __read$1((channelGroups !== null && channelGroups !== void 0 ? channelGroups : [])), false))), timetoken)); } else { - this.engine.transition(subscriptionChange(this.channels, this.groups)); + this.engine.transition(subscriptionChange(Array.from(new Set(__spreadArray$1(__spreadArray$1([], __read$1(this.channels), false), __read$1((channels !== null && channels !== void 0 ? channels : [])), false))), Array.from(new Set(__spreadArray$1(__spreadArray$1([], __read$1(this.groups), false), __read$1((channelGroups !== null && channelGroups !== void 0 ? channelGroups : [])), false))))); } if (this.dependencies.join) { this.dependencies.join({ - channels: this.channels.filter(function (c) { return !c.endsWith('-pnpres'); }), - groups: this.groups.filter(function (g) { return !g.endsWith('-pnpres'); }), + channels: Array.from(new Set(this.channels.filter(function (c) { return !c.endsWith('-pnpres'); }))), + groups: Array.from(new Set(this.groups.filter(function (g) { return !g.endsWith('-pnpres'); }))), }); } }; EventEngine.prototype.unsubscribe = function (_a) { var _this = this; - var channels = _a.channels, groups = _a.groups; - var channlesWithPres = channels === null || channels === void 0 ? void 0 : channels.slice(0); - channels === null || channels === void 0 ? void 0 : channels.map(function (c) { return channlesWithPres.push("".concat(c, "-pnpres")); }); - this.channels = this.channels.filter(function (channel) { return !(channlesWithPres === null || channlesWithPres === void 0 ? void 0 : channlesWithPres.includes(channel)); }); - var groupsWithPres = groups === null || groups === void 0 ? void 0 : groups.slice(0); - groups === null || groups === void 0 ? void 0 : groups.map(function (g) { return groupsWithPres.push("".concat(g, "-pnpres")); }); - this.groups = this.groups.filter(function (group) { return !(groupsWithPres === null || groupsWithPres === void 0 ? void 0 : groupsWithPres.includes(group)); }); - if (this.dependencies.presenceState) { - channels === null || channels === void 0 ? void 0 : channels.forEach(function (c) { return delete _this.dependencies.presenceState[c]; }); - groups === null || groups === void 0 ? void 0 : groups.forEach(function (g) { return delete _this.dependencies.presenceState[g]; }); - } - this.engine.transition(subscriptionChange(this.channels.slice(0), this.groups.slice(0))); - if (this.dependencies.leave) { - this.dependencies.leave({ - channels: channels, - groups: groups, - }); + var _b = _a.channels, channels = _b === void 0 ? [] : _b, _c = _a.channelGroups, channelGroups = _c === void 0 ? [] : _c; + var filteredChannels = utils$5.removeSingleOccurance(this.channels, __spreadArray$1(__spreadArray$1([], __read$1(channels), false), __read$1(channels.map(function (c) { return "".concat(c, "-pnpres"); })), false)); + var filteredGroups = utils$5.removeSingleOccurance(this.groups, __spreadArray$1(__spreadArray$1([], __read$1(channelGroups), false), __read$1(channelGroups.map(function (c) { return "".concat(c, "-pnpres"); })), false)); + if (new Set(this.channels).size !== new Set(filteredChannels).size || + new Set(this.groups).size !== new Set(filteredGroups).size) { + var channelsToLeave = utils$5.findUniqueCommonElements(this.channels, channels); + var groupstoLeave = utils$5.findUniqueCommonElements(this.groups, channelGroups); + if (this.dependencies.presenceState) { + channelsToLeave === null || channelsToLeave === void 0 ? void 0 : channelsToLeave.forEach(function (c) { return delete _this.dependencies.presenceState[c]; }); + groupstoLeave === null || groupstoLeave === void 0 ? void 0 : groupstoLeave.forEach(function (g) { return delete _this.dependencies.presenceState[g]; }); + } + this.channels = filteredChannels; + this.groups = filteredGroups; + this.engine.transition(subscriptionChange(Array.from(new Set(this.channels.slice(0))), Array.from(new Set(this.groups.slice(0))))); + if (this.dependencies.leave) { + this.dependencies.leave({ + channels: channelsToLeave.slice(0), + groups: groupstoLeave.slice(0), + }); + } } }; EventEngine.prototype.unsubscribeAll = function () { @@ -7957,8 +7809,8 @@ var HeartbeatStoppedState = new State('HEARTBEAT_STOPPED'); HeartbeatStoppedState.on(joined.type, function (context, event) { return HeartbeatStoppedState.with({ - channels: __spreadArray(__spreadArray([], __read(context.channels), false), __read(event.payload.channels), false), - groups: __spreadArray(__spreadArray([], __read(context.groups), false), __read(event.payload.groups), false), + channels: __spreadArray$1(__spreadArray$1([], __read$1(context.channels), false), __read$1(event.payload.channels), false), + groups: __spreadArray$1(__spreadArray$1([], __read$1(context.groups), false), __read$1(event.payload.groups), false), }); }); HeartbeatStoppedState.on(left.type, function (context, event) { @@ -7986,8 +7838,8 @@ }); HeartbeatCooldownState.on(joined.type, function (context, event) { return HeartbeatingState.with({ - channels: __spreadArray(__spreadArray([], __read(context.channels), false), __read(event.payload.channels), false), - groups: __spreadArray(__spreadArray([], __read(context.groups), false), __read(event.payload.groups), false), + channels: __spreadArray$1(__spreadArray$1([], __read$1(context.channels), false), __read$1(event.payload.channels), false), + groups: __spreadArray$1(__spreadArray$1([], __read$1(context.groups), false), __read$1(event.payload.groups), false), }); }); HeartbeatCooldownState.on(left.type, function (context, event) { @@ -8009,8 +7861,8 @@ var HeartbeatFailedState = new State('HEARTBEAT_FAILED'); HeartbeatFailedState.on(joined.type, function (context, event) { return HeartbeatingState.with({ - channels: __spreadArray(__spreadArray([], __read(context.channels), false), __read(event.payload.channels), false), - groups: __spreadArray(__spreadArray([], __read(context.groups), false), __read(event.payload.groups), false), + channels: __spreadArray$1(__spreadArray$1([], __read$1(context.channels), false), __read$1(event.payload.channels), false), + groups: __spreadArray$1(__spreadArray$1([], __read$1(context.groups), false), __read$1(event.payload.groups), false), }); }); HeartbeatFailedState.on(left.type, function (context, event) { @@ -8040,8 +7892,8 @@ HearbeatReconnectingState.onExit(function () { return delayedHeartbeat.cancel; }); HearbeatReconnectingState.on(joined.type, function (context, event) { return HeartbeatingState.with({ - channels: __spreadArray(__spreadArray([], __read(context.channels), false), __read(event.payload.channels), false), - groups: __spreadArray(__spreadArray([], __read(context.groups), false), __read(event.payload.groups), false), + channels: __spreadArray$1(__spreadArray$1([], __read$1(context.channels), false), __read$1(event.payload.channels), false), + groups: __spreadArray$1(__spreadArray$1([], __read$1(context.groups), false), __read$1(event.payload.groups), false), }); }); HearbeatReconnectingState.on(left.type, function (context, event) { @@ -8085,8 +7937,8 @@ }); HeartbeatingState.on(joined.type, function (context, event) { return HeartbeatingState.with({ - channels: __spreadArray(__spreadArray([], __read(context.channels), false), __read(event.payload.channels), false), - groups: __spreadArray(__spreadArray([], __read(context.groups), false), __read(event.payload.groups), false), + channels: __spreadArray$1(__spreadArray$1([], __read$1(context.channels), false), __read$1(event.payload.channels), false), + groups: __spreadArray$1(__spreadArray$1([], __read$1(context.groups), false), __read$1(event.payload.groups), false), }); }); HeartbeatingState.on(left.type, function (context, event) { @@ -8140,8 +7992,8 @@ }); PresenceEventEngine.prototype.join = function (_a) { var channels = _a.channels, groups = _a.groups; - this.channels = __spreadArray(__spreadArray([], __read(this.channels), false), __read((channels !== null && channels !== void 0 ? channels : [])), false); - this.groups = __spreadArray(__spreadArray([], __read(this.groups), false), __read((groups !== null && groups !== void 0 ? groups : [])), false); + this.channels = __spreadArray$1(__spreadArray$1([], __read$1(this.channels), false), __read$1((channels !== null && channels !== void 0 ? channels : [])), false); + this.groups = __spreadArray$1(__spreadArray$1([], __read$1(this.groups), false), __read$1((groups !== null && groups !== void 0 ? groups : [])), false); this.engine.transition(joined(this.channels.slice(0), this.groups.slice(0))); }; PresenceEventEngine.prototype.leave = function (_a) { @@ -8232,6 +8084,8 @@ this.modules = modules; this.listenerManager = listenerManager; this.getFileUrl = getFileUrl; + this._channelListenerMap = new Map(); + this._groupListenerMap = new Map(); if (modules.cryptoModule) this._decoder = new TextDecoder(); } @@ -8266,7 +8120,12 @@ if (e.payload.timeout) { announce.timeout = e.payload.timeout; } + // deprecated --> + announce.actualChannel = subscriptionMatch != null ? channel : null; + announce.subscribedChannel = subscriptionMatch != null ? subscriptionMatch : channel; + // <-- deprecated this.listenerManager.announcePresence(announce); + this._announce('presence', announce, announce.channel, announce.subscription); } else if (e.messageType === 1) { var announce = {}; @@ -8281,6 +8140,7 @@ } announce.message = e.payload; this.listenerManager.announceSignal(announce); + this._announce('signal', announce, announce.channel, announce.subscription); } else if (e.messageType === 2) { var announce = {}; @@ -8299,20 +8159,27 @@ data: e.payload.data, }; this.listenerManager.announceObjects(announce); + this._announce('objects', announce, announce.channel, announce.subscription); if (e.payload.type === 'uuid') { var eventData = this._renameChannelField(announce); - this.listenerManager.announceUser(__assign(__assign({}, eventData), { message: __assign(__assign({}, eventData.message), { event: this._renameEvent(eventData.message.event), type: 'user' }) })); + var userEvent = __assign(__assign({}, eventData), { message: __assign(__assign({}, eventData.message), { event: this._renameEvent(eventData.message.event), type: 'user' }) }); + this.listenerManager.announceUser(userEvent); + this._announce('user', userEvent, announce.channel, announce.subscription); } else if (message.payload.type === 'channel') { var eventData = this._renameChannelField(announce); - this.listenerManager.announceSpace(__assign(__assign({}, eventData), { message: __assign(__assign({}, eventData.message), { event: this._renameEvent(eventData.message.event), type: 'space' }) })); + var spaceEvent = __assign(__assign({}, eventData), { message: __assign(__assign({}, eventData.message), { event: this._renameEvent(eventData.message.event), type: 'space' }) }); + this.listenerManager.announceSpace(spaceEvent); + this._announce('space', spaceEvent, announce.channel, announce.subscription); } else if (message.payload.type === 'membership') { var eventData = this._renameChannelField(announce); var _a = eventData.message.data, user = _a.uuid, space = _a.channel, membershipData = __rest(_a, ["uuid", "channel"]); membershipData.user = user; membershipData.space = space; - this.listenerManager.announceMembership(__assign(__assign({}, eventData), { message: __assign(__assign({}, eventData.message), { event: this._renameEvent(eventData.message.event), data: membershipData }) })); + var membershipEvent = __assign(__assign({}, eventData), { message: __assign(__assign({}, eventData.message), { event: this._renameEvent(eventData.message.event), data: membershipData }) }); + this.listenerManager.announceMembership(membershipEvent); + this._announce('membership', membershipEvent, announce.channel, announce.subscription); } } else if (e.messageType === 3) { @@ -8330,6 +8197,7 @@ }; announce.event = e.payload.event; this.listenerManager.announceMessageAction(announce); + this._announce('messageAction', announce, announce.channel, announce.subscription); } else if (e.messageType === 4) { var announce = {}; @@ -8367,6 +8235,7 @@ }), }; this.listenerManager.announceFile(announce); + this._announce('file', announce, announce.channel, announce.subscription); } else { var announce = {}; @@ -8400,9 +8269,59 @@ else { announce.message = e.payload; } + // deprecated --> + announce.actualChannel = subscriptionMatch != null ? channel : null; + announce.subscribedChannel = subscriptionMatch != null ? subscriptionMatch : channel; + // <-- deprecated this.listenerManager.announceMessage(announce); + this._announce('message', announce, announce.channel, announce.subscription); } }; + EventEmitter.prototype.addListener = function (l, channels, groups) { + var _this = this; + if (!(channels && groups)) { + this.listenerManager.addListener(l); + } + else { + channels === null || channels === void 0 ? void 0 : channels.forEach(function (c) { + if (_this._channelListenerMap[c]) { + if (!_this._channelListenerMap[c].includes(l)) + _this._channelListenerMap[c].push(l); + } + else { + _this._channelListenerMap[c] = [l]; + } + }); + groups === null || groups === void 0 ? void 0 : groups.forEach(function (g) { + if (_this._groupListenerMap[g]) { + if (!_this._groupListenerMap[g].includes(l)) + _this._groupListenerMap[g].push(l); + } + else { + _this._groupListenerMap[g] = [l]; + } + }); + } + }; + EventEmitter.prototype.removeListener = function (listener, channels, groups) { + var _this = this; + if (!(channels && groups)) { + this.listenerManager.removeListener(listener); + } + else { + channels === null || channels === void 0 ? void 0 : channels.forEach(function (c) { + var _a; + _this._channelListenerMap[c] = (_a = _this._channelListenerMap[c]) === null || _a === void 0 ? void 0 : _a.filter(function (l) { return l !== listener; }); + }); + groups === null || groups === void 0 ? void 0 : groups.forEach(function (g) { + var _a; + _this._groupListenerMap[g] = (_a = _this._groupListenerMap[g]) === null || _a === void 0 ? void 0 : _a.filter(function (l) { return l !== listener; }); + }); + } + }; + EventEmitter.prototype.removeAllListeners = function () { + this.listenerManager.removeAllListeners(); + }; EventEmitter.prototype._renameEvent = function (e) { return e === 'set' ? 'updated' : 'removed'; }; @@ -8411,9 +8330,251 @@ eventData.spaceId = channel; return eventData; }; + EventEmitter.prototype._announce = function (type, event, channel, group) { + var _a, _b; + (_a = this._channelListenerMap[channel]) === null || _a === void 0 ? void 0 : _a.forEach(function (l) { return l[type] && l[type](event); }); + (_b = this._groupListenerMap[group]) === null || _b === void 0 ? void 0 : _b.forEach(function (l) { return l[type] && l[type](event); }); + }; return EventEmitter; }()); + var SubscribeCapable = /** @class */ (function () { + function SubscribeCapable() { + } + SubscribeCapable.prototype.subscribe = function () { + var _a, _b; + this.pubnub.subscribe(__assign({ channels: this.channelNames, channelGroups: this.groupNames }, (((_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.cursor) === null || _b === void 0 ? void 0 : _b.timetoken) && { timetoken: this.options.cursor.timetoken }))); + }; + SubscribeCapable.prototype.unsubscribe = function () { + this.pubnub.unsubscribe({ + channels: this.channelNames.filter(function (c) { return !c.endsWith('-pnpres'); }), + channelGroups: this.groupNames.filter(function (cg) { return !cg.endsWith('-pnpres'); }), + }); + }; + Object.defineProperty(SubscribeCapable.prototype, "onMessage", { + set: function (onMessagelistener) { + this.listener.message = onMessagelistener; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(SubscribeCapable.prototype, "onPresence", { + set: function (onPresencelistener) { + this.listener.presence = onPresencelistener; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(SubscribeCapable.prototype, "onSignal", { + set: function (onSignalListener) { + this.listener.signal = onSignalListener; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(SubscribeCapable.prototype, "onObjects", { + set: function (onObjectsListener) { + this.listener.objects = onObjectsListener; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(SubscribeCapable.prototype, "onMessageAction", { + set: function (messageActionEventListener) { + this.listener.messageAction = messageActionEventListener; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(SubscribeCapable.prototype, "onFile", { + set: function (fileEventListener) { + this.listener.file = fileEventListener; + }, + enumerable: false, + configurable: true + }); + SubscribeCapable.prototype.addListener = function (listener) { + this.eventEmitter.addListener(listener, this.channelNames.filter(function (c) { return !c.endsWith('-pnpres'); }), this.groupNames.filter(function (cg) { return !cg.endsWith('-pnpres'); })); + }; + SubscribeCapable.prototype.removeListener = function (listener) { + this.eventEmitter.removeListener(listener, this.channelNames, this.groupNames); + }; + Object.defineProperty(SubscribeCapable.prototype, "channels", { + get: function () { + return this.channelNames.slice(0); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(SubscribeCapable.prototype, "channelGroups", { + get: function () { + return this.groupNames.slice(0); + }, + enumerable: false, + configurable: true + }); + return SubscribeCapable; + }()); + + var SubscriptionSet = /** @class */ (function (_super) { + __extends(SubscriptionSet, _super); + function SubscriptionSet(_a) { + var _b = _a.channels, channels = _b === void 0 ? [] : _b, _c = _a.channelGroups, channelGroups = _c === void 0 ? [] : _c, subscriptionOptions = _a.subscriptionOptions, eventEmitter = _a.eventEmitter, pubnub = _a.pubnub; + var _this = _super.call(this) || this; + _this.channelNames = []; + _this.groupNames = []; + _this.subscriptionList = []; + _this.options = subscriptionOptions; + _this.eventEmitter = eventEmitter; + _this.pubnub = pubnub; + channels.forEach(function (c) { + var subscription = _this.pubnub.channel(c).subscription(_this.options); + _this.channelNames = __spreadArray$1(__spreadArray$1([], __read$1(_this.channelNames), false), __read$1(subscription.channels), false); + _this.subscriptionList.push(subscription); + }); + channelGroups.forEach(function (cg) { + var subscription = _this.pubnub.channelGroup(cg).subscription(_this.options); + _this.groupNames = __spreadArray$1(__spreadArray$1([], __read$1(_this.groupNames), false), __read$1(subscription.channelGroups), false); + _this.subscriptionList.push(subscription); + }); + _this.listener = {}; + eventEmitter.addListener(_this.listener, _this.channelNames.filter(function (c) { return !c.endsWith('-pnpres'); }), _this.groupNames.filter(function (cg) { return !cg.endsWith('-pnpres'); })); + return _this; + } + SubscriptionSet.prototype.addSubscription = function (subscription) { + this.subscriptionList.push(subscription); + this.channelNames = __spreadArray$1(__spreadArray$1([], __read$1(this.channelNames), false), __read$1(subscription.channels), false); + this.groupNames = __spreadArray$1(__spreadArray$1([], __read$1(this.groupNames), false), __read$1(subscription.channelGroups), false); + }; + SubscriptionSet.prototype.removeSubscription = function (subscription) { + var channelsToRemove = subscription.channels; + var groupsToRemove = subscription.channelGroups; + this.channelNames = this.channelNames.filter(function (c) { return !channelsToRemove.includes(c); }); + this.groupNames = this.groupNames.filter(function (cg) { return !groupsToRemove.includes(cg); }); + this.subscriptionList = this.subscriptionList.filter(function (s) { return s !== subscription; }); + }; + SubscriptionSet.prototype.addSubscriptionSet = function (subscriptionSet) { + this.subscriptionList = __spreadArray$1(__spreadArray$1([], __read$1(this.subscriptionList), false), __read$1(subscriptionSet.subscriptions), false); + this.channelNames = __spreadArray$1(__spreadArray$1([], __read$1(this.channelNames), false), __read$1(subscriptionSet.channels), false); + this.groupNames = __spreadArray$1(__spreadArray$1([], __read$1(this.groupNames), false), __read$1(subscriptionSet.channelGroups), false); + }; + SubscriptionSet.prototype.removeSubscriptionSet = function (subscriptionSet) { + var channelsToRemove = subscriptionSet.channels; + var groupsToRemove = subscriptionSet.channelGroups; + this.channelNames = this.channelNames.filter(function (c) { return !channelsToRemove.includes(c); }); + this.groupNames = this.groupNames.filter(function (cg) { return !groupsToRemove.includes(cg); }); + this.subscriptionList = this.subscriptionList.filter(function (s) { return !subscriptionSet.subscriptions.includes(s); }); + }; + Object.defineProperty(SubscriptionSet.prototype, "subscriptions", { + get: function () { + return this.subscriptionList.slice(0); + }, + enumerable: false, + configurable: true + }); + return SubscriptionSet; + }(SubscribeCapable)); + + var Subscription = /** @class */ (function (_super) { + __extends(Subscription, _super); + function Subscription(_a) { + var channels = _a.channels, channelGroups = _a.channelGroups, subscriptionOptions = _a.subscriptionOptions, eventEmitter = _a.eventEmitter, pubnub = _a.pubnub; + var _this = _super.call(this) || this; + _this.channelNames = []; + _this.groupNames = []; + _this.channelNames = channels; + _this.groupNames = channelGroups; + _this.options = subscriptionOptions; + _this.pubnub = pubnub; + _this.eventEmitter = eventEmitter; + _this.listener = {}; + eventEmitter.addListener(_this.listener, _this.channelNames.filter(function (c) { return !c.endsWith('-pnpres'); }), _this.groupNames.filter(function (cg) { return !cg.endsWith('-pnpres'); })); + return _this; + } + Subscription.prototype.addSubscription = function (subscription) { + return new SubscriptionSet({ + channels: __spreadArray$1(__spreadArray$1([], __read$1(this.channelNames), false), __read$1(subscription.channels), false), + channelGroups: __spreadArray$1(__spreadArray$1([], __read$1(this.groupNames), false), __read$1(subscription.channelGroups), false), + subscriptionOptions: __assign(__assign({}, this.options), subscription === null || subscription === void 0 ? void 0 : subscription.options), + eventEmitter: this.eventEmitter, + pubnub: this.pubnub, + }); + }; + return Subscription; + }(SubscribeCapable)); + + var Channel = /** @class */ (function () { + function Channel(channelName, eventEmitter, pubnub) { + this.name = channelName; + this.eventEmitter = eventEmitter; + this.pubnub = pubnub; + } + Channel.prototype.subscription = function (subscriptionOptions) { + return new Subscription({ + channels: (subscriptionOptions === null || subscriptionOptions === void 0 ? void 0 : subscriptionOptions.receivePresenceEvents) ? [this.name, "".concat(this.name, "-pnpres")] : [this.name], + channelGroups: [], + subscriptionOptions: subscriptionOptions, + eventEmitter: this.eventEmitter, + pubnub: this.pubnub, + }); + }; + return Channel; + }()); + + var ChannelGroup = /** @class */ (function () { + function ChannelGroup(channelGroup, eventEmitter, pubnub) { + this.name = channelGroup; + this.eventEmitter = eventEmitter; + this.pubnub = pubnub; + } + ChannelGroup.prototype.subscription = function (subscriptionOptions) { + return new Subscription({ + channels: [], + channelGroups: (subscriptionOptions === null || subscriptionOptions === void 0 ? void 0 : subscriptionOptions.receivePresenceEvents) ? [this.name, "".concat(this.name, "-pnpres")] : [this.name], + subscriptionOptions: subscriptionOptions, + eventEmitter: this.eventEmitter, + pubnub: this.pubnub, + }); + }; + return ChannelGroup; + }()); + + var ChannelMetadata = /** @class */ (function () { + function ChannelMetadata(id, eventEmitter, pubnub) { + this.id = id; + this.eventEmitter = eventEmitter; + this.pubnub = pubnub; + } + ChannelMetadata.prototype.subscription = function (subscriptionOptions) { + return new Subscription({ + channels: [this.id], + channelGroups: [], + subscriptionOptions: subscriptionOptions, + eventEmitter: this.eventEmitter, + pubnub: this.pubnub, + }); + }; + return ChannelMetadata; + }()); + + var UserMetadata = /** @class */ (function () { + function UserMetadata(id, eventEmitter, pubnub) { + this.id = id; + this.eventEmitter = eventEmitter; + this.pubnub = pubnub; + } + UserMetadata.prototype.subscription = function (subscriptionOptions) { + return new Subscription({ + channels: [this.id], + channelGroups: [], + subscriptionOptions: subscriptionOptions, + eventEmitter: this.eventEmitter, + pubnub: this.pubnub, + }); + }; + return UserMetadata; + }()); + var default_1$3 = /** @class */ (function () { function default_1(setup) { var _this = this; @@ -8468,12 +8629,12 @@ this.setPresenceState = endpointCreator.bind(this, modules, presenceSetStateConfig); this.handshake = endpointCreator.bind(this, modules, endpoint$1); this.receiveMessages = endpointCreator.bind(this, modules, endpoint); + this._eventEmitter = new EventEmitter({ + modules: modules, + listenerManager: this._listenerManager, + getFileUrl: function (params) { return getFileUrlFunction(modules, params); }, + }); if (config.enableEventEngine === true) { - this._eventEmitter = new EventEmitter({ - modules: modules, - listenerManager: this._listenerManager, - getFileUrl: function (params) { return getFileUrlFunction(modules, params); }, - }); if (config.maintainPresenceState) { this.presenceState = {}; this.setState = function (args) { @@ -8557,6 +8718,7 @@ listenerManager: listenerManager, getFileUrl: function (params) { return getFileUrlFunction(modules, params); }, cryptoModule: modules.cryptoModule, + eventEmitter: this._eventEmitter, }); this.subscribe = subscriptionManager_1.adaptSubscribeChange.bind(subscriptionManager_1); this.unsubscribe = subscriptionManager_1.adaptUnsubscribeChange.bind(subscriptionManager_1); @@ -8572,9 +8734,9 @@ subscriptionManager_1.disconnect(); }; } - this.addListener = listenerManager.addListener.bind(listenerManager); - this.removeListener = listenerManager.removeListener.bind(listenerManager); - this.removeAllListeners = listenerManager.removeAllListeners.bind(listenerManager); + this.addListener = this._eventEmitter.addListener.bind(this._eventEmitter); + this.removeListener = this._eventEmitter.removeListener.bind(this._eventEmitter); + this.removeAllListeners = this._eventEmitter.removeAllListeners.bind(this._eventEmitter); this.parseToken = tokenManager.parseToken.bind(tokenManager); this.setToken = tokenManager.setToken.bind(tokenManager); this.getToken = tokenManager.getToken.bind(tokenManager); @@ -8629,6 +8791,20 @@ this.getFileUrl = function (params) { return getFileUrlFunction(modules, params); }; this.downloadFile = endpointCreator.bind(this, modules, endpoint$g); this.deleteFile = endpointCreator.bind(this, modules, endpoint$f); + // entities + this.channel = function (name) { return new Channel(name, _this._eventEmitter, _this); }; + this.channelGroup = function (name) { return new ChannelGroup(name, _this._eventEmitter, _this); }; + this.channelMetadata = function (id) { return new ChannelMetadata(id, _this._eventEmitter, _this); }; + this.userMetadata = function (id) { return new UserMetadata(id, _this._eventEmitter, _this); }; + this.subscriptionSet = function (args) { + return new SubscriptionSet({ + channels: args.channels, + channelGroups: args.channelGroups, + subscriptionOptions: args.subscriptionOptions, + eventEmitter: _this._eventEmitter, + pubnub: _this, + }); + }; // Objects API v2 this.objects = { getAllUUIDMetadata: endpointCreator.bind(this, modules, endpoint$e), @@ -8645,18 +8821,18 @@ for (var _i = 1; _i < arguments.length; _i++) { rest[_i - 1] = arguments[_i]; } - return endpointCreator.call.apply(endpointCreator, __spreadArray([_this, + return endpointCreator.call.apply(endpointCreator, __spreadArray$1([_this, modules, - endpoint$5, __assign({ type: 'set' }, parameters)], __read(rest), false)); + endpoint$5, __assign({ type: 'set' }, parameters)], __read$1(rest), false)); }, removeChannelMembers: function (parameters) { var rest = []; for (var _i = 1; _i < arguments.length; _i++) { rest[_i - 1] = arguments[_i]; } - return endpointCreator.call.apply(endpointCreator, __spreadArray([_this, + return endpointCreator.call.apply(endpointCreator, __spreadArray$1([_this, modules, - endpoint$5, __assign({ type: 'delete' }, parameters)], __read(rest), false)); + endpoint$5, __assign({ type: 'delete' }, parameters)], __read$1(rest), false)); }, getMemberships: endpointCreator.bind(this, modules, endpoint$4), setMemberships: function (parameters) { @@ -8664,18 +8840,18 @@ for (var _i = 1; _i < arguments.length; _i++) { rest[_i - 1] = arguments[_i]; } - return endpointCreator.call.apply(endpointCreator, __spreadArray([_this, + return endpointCreator.call.apply(endpointCreator, __spreadArray$1([_this, modules, - endpoint$3, __assign({ type: 'set' }, parameters)], __read(rest), false)); + endpoint$3, __assign({ type: 'set' }, parameters)], __read$1(rest), false)); }, removeMemberships: function (parameters) { var rest = []; for (var _i = 1; _i < arguments.length; _i++) { rest[_i - 1] = arguments[_i]; } - return endpointCreator.call.apply(endpointCreator, __spreadArray([_this, + return endpointCreator.call.apply(endpointCreator, __spreadArray$1([_this, modules, - endpoint$3, __assign({ type: 'delete' }, parameters)], __read(rest), false)); + endpoint$3, __assign({ type: 'delete' }, parameters)], __read$1(rest), false)); }, }; // User Apis @@ -8792,7 +8968,7 @@ }, sort: params.sort != null ? Object.fromEntries(Object.entries(params.sort).map(function (_a) { - var _b = __read(_a, 2), k = _b[0], v = _b[1]; + var _b = __read$1(_a, 2), k = _b[0], v = _b[1]; return [k.replace('user', 'uuid'), v]; })) : null, @@ -8828,7 +9004,7 @@ }, sort: params.sort != null ? Object.fromEntries(Object.entries(params.sort).map(function (_a) { - var _b = __read(_a, 2), k = _b[0], v = _b[1]; + var _b = __read$1(_a, 2), k = _b[0], v = _b[1]; return [k.replace('space', 'channel'), v]; })) : null, @@ -14135,7 +14311,7 @@ return new this({ default: defaultCryptor }); }; CryptoModule.prototype.getAllCryptors = function () { - return __spreadArray([this.defaultCryptor], __read(this.cryptors), false); + return __spreadArray$1([this.defaultCryptor], __read$1(this.cryptors), false); }; CryptoModule.prototype.encrypt = function (data) { var encrypted = this.defaultCryptor.encrypt(data); diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index bc8818dc5..97c551cf2 100644 --- a/dist/web/pubnub.min.js +++ b/dist/web/pubnub.min.js @@ -12,6 +12,6 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},e(t,n)};function t(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var n=function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function s(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a}function u(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o>2,c=0;c>6),o.push(128|63&a)):a<55296?(o.push(224|a>>12),o.push(128|a>>6&63),o.push(128|63&a)):(a=(1023&a)<<10,a|=1023&t.charCodeAt(++r),a+=65536,o.push(240|a>>18),o.push(128|a>>12&63),o.push(128|a>>6&63),o.push(128|63&a))}return h(3,o.length),p(o);default:var f;if(Array.isArray(t))for(h(4,f=t.length),r=0;r>5!==e)throw"Invalid indefinite length element";return n}function g(e,t){for(var n=0;n>10),e.push(56320|1023&r))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof i&&(i=function(){return n});var m=function e(){var o,h,m=l(),v=m>>5,b=31&m;if(7===v)switch(b){case 25:return function(){var e=new ArrayBuffer(4),t=new DataView(e),n=p(),o=32768&n,i=31744&n,a=1023&n;if(31744===i)i=261120;else if(0!==i)i+=114688;else if(0!==a)return a*r;return t.setUint32(0,o<<16|i<<13|a<<13),t.getFloat32(0)}();case 26:return u(a.getFloat32(s),4);case 27:return u(a.getFloat64(s),8)}if((h=d(b))<0&&(v<2||6=0;)S+=h,_.push(c(h));var w=new Uint8Array(S),O=0;for(o=0;o<_.length;++o)w.set(_[o],O),O+=_[o].length;return w}return c(h);case 3:var P=[];if(h<0)for(;(h=y(v))>=0;)g(P,h);else g(P,h);return String.fromCharCode.apply(null,P);case 4:var E;if(h<0)for(E=[];!f();)E.push(e());else for(E=new Array(h),o=0;o0&&o[o.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function a(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}function u(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o>2,c=0;c>6),o.push(128|63&s)):s<55296?(o.push(224|s>>12),o.push(128|s>>6&63),o.push(128|63&s)):(s=(1023&s)<<10,s|=1023&t.charCodeAt(++r),s+=65536,o.push(240|s>>18),o.push(128|s>>12&63),o.push(128|s>>6&63),o.push(128|63&s))}return h(3,o.length),p(o);default:var f;if(Array.isArray(t))for(h(4,f=t.length),r=0;r>5!==e)throw"Invalid indefinite length element";return n}function g(e,t){for(var n=0;n>10),e.push(56320|1023&r))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof i&&(i=function(){return n});var m=function e(){var o,h,m=l(),b=m>>5,v=31&m;if(7===b)switch(v){case 25:return function(){var e=new ArrayBuffer(4),t=new DataView(e),n=p(),o=32768&n,i=31744&n,s=1023&n;if(31744===i)i=261120;else if(0!==i)i+=114688;else if(0!==s)return s*r;return t.setUint32(0,o<<16|i<<13|s<<13),t.getFloat32(0)}();case 26:return u(s.getFloat32(a),4);case 27:return u(s.getFloat64(a),8)}if((h=d(v))<0&&(b<2||6=0;)S+=h,_.push(c(h));var w=new Uint8Array(S),O=0;for(o=0;o<_.length;++o)w.set(_[o],O),O+=_[o].length;return w}return c(h);case 3:var P=[];if(h<0)for(;(h=y(b))>=0;)g(P,h);else g(P,h);return String.fromCharCode.apply(null,P);case 4:var E;if(h<0)for(E=[];!f();)E.push(e());else for(E=new Array(h),o=0;o=20?this._presenceTimeout=e:(this._presenceTimeout=20,console.log("WARNING: Presence timeout is less than the minimum. Using minimum value: ",this._presenceTimeout)),this.setHeartbeatInterval(this._presenceTimeout/2-1),this},e.prototype.setProxy=function(e){this.proxy=e},e.prototype.getHeartbeatInterval=function(){return this._heartbeatInterval},e.prototype.setHeartbeatInterval=function(e){return this._heartbeatInterval=e,this},e.prototype.getSubscribeTimeout=function(){return this._subscribeRequestTimeout},e.prototype.setSubscribeTimeout=function(e){return this._subscribeRequestTimeout=e,this},e.prototype.getTransactionTimeout=function(){return this._transactionalRequestTimeout},e.prototype.setTransactionTimeout=function(e){return this._transactionalRequestTimeout=e,this},e.prototype.isSendBeaconEnabled=function(){return this._useSendBeacon},e.prototype.setSendBeaconConfig=function(e){return this._useSendBeacon=e,this},e.prototype.getVersion=function(){return"7.5.0"},e.prototype._setRetryConfiguration=function(e){if(e.minimumdelay<2)throw new Error("Minimum delay can not be set less than 2 seconds for retry");if(e.maximumDelay>150)throw new Error("Maximum delay can not be set more than 150 seconds for retry");if(e.maximumDelay&&maximumRetry>6)throw new Error("Maximum retry for exponential retry policy can not be more than 6");if(e.maximumRetry>10)throw new Error("Maximum retry for linear retry policy can not be more than 10");this.retryConfiguration=e},e.prototype._addPnsdkSuffix=function(e,t){this._PNSDKSuffix[e]=t},e.prototype._getPnsdkSuffix=function(e){var t=this;return Object.keys(this._PNSDKSuffix).reduce((function(n,r){return n+e+t._PNSDKSuffix[r]}),"")},e}();function m(e){var t=e.replace(/==?$/,""),n=Math.floor(t.length/4*3),r=new ArrayBuffer(n),o=new Uint8Array(r),i=0;function a(){var e=t.charAt(i++),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e);if(-1===n)throw new Error("Illegal character at ".concat(i,": ").concat(t.charAt(i-1)));return n}for(var s=0;s>4,f=(15&c)<<4|l>>2,d=(3&l)<<6|p>>0;o[s]=h,64!=l&&(o[s+1]=f),64!=p&&(o[s+2]=d)}return r}function v(e){for(var t,n="",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=new Uint8Array(e),i=o.byteLength,a=i%3,s=i-a,u=0;u>18]+r[(258048&t)>>12]+r[(4032&t)>>6]+r[63&t];return 1==a?n+=r[(252&(t=o[s]))>>2]+r[(3&t)<<4]+"==":2==a&&(n+=r[(64512&(t=o[s]<<8|o[s+1]))>>10]+r[(1008&t)>>4]+r[(15&t)<<2]+"="),n}var b,_,S,w,O,P=P||function(e,t){var n={},r=n.lib={},o=function(){},i=r.Base={extend:function(e){o.prototype=this;var t=new o;return e&&t.mixIn(e),t.hasOwnProperty("init")||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},a=r.WordArray=i.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||u).stringify(this)},concat:function(e){var t=this.words,n=e.words,r=this.sigBytes;if(e=e.sigBytes,this.clamp(),r%4)for(var o=0;o>>2]|=(n[o>>>2]>>>24-o%4*8&255)<<24-(r+o)%4*8;else if(65535>>2]=n[o>>>2];else t.push.apply(t,n);return this.sigBytes+=e,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n=[],r=0;r>>2]>>>24-r%4*8&255;n.push((o>>>4).toString(16)),n.push((15&o).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new a.init(n,t/2)}},c=s.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],r=0;r>>2]>>>24-r%4*8&255));return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new a.init(n,t)}},l=s.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},p=r.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new a.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=l.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,r=n.words,o=n.sigBytes,i=this.blockSize,s=o/(4*i);if(t=(s=t?e.ceil(s):e.max((0|s)-this._minBufferSize,0))*i,o=e.min(4*t,o),t){for(var u=0;uc;){var l;e:{l=u;for(var p=e.sqrt(l),h=2;h<=p;h++)if(!(l%h)){l=!1;break e}l=!0}l&&(8>c&&(i[c]=s(e.pow(u,.5))),a[c]=s(e.pow(u,1/3)),c++),u++}var f=[];o=o.SHA256=r.extend({_doReset:function(){this._hash=new n.init(i.slice(0))},_doProcessBlock:function(e,t){for(var n=this._hash.words,r=n[0],o=n[1],i=n[2],s=n[3],u=n[4],c=n[5],l=n[6],p=n[7],h=0;64>h;h++){if(16>h)f[h]=0|e[t+h];else{var d=f[h-15],y=f[h-2];f[h]=((d<<25|d>>>7)^(d<<14|d>>>18)^d>>>3)+f[h-7]+((y<<15|y>>>17)^(y<<13|y>>>19)^y>>>10)+f[h-16]}d=p+((u<<26|u>>>6)^(u<<21|u>>>11)^(u<<7|u>>>25))+(u&c^~u&l)+a[h]+f[h],y=((r<<30|r>>>2)^(r<<19|r>>>13)^(r<<10|r>>>22))+(r&o^r&i^o&i),p=l,l=c,c=u,u=s+d|0,s=i,i=o,o=r,r=d+y|0}n[0]=n[0]+r|0,n[1]=n[1]+o|0,n[2]=n[2]+i|0,n[3]=n[3]+s|0,n[4]=n[4]+u|0,n[5]=n[5]+c|0,n[6]=n[6]+l|0,n[7]=n[7]+p|0},_doFinalize:function(){var t=this._data,n=t.words,r=8*this._nDataBytes,o=8*t.sigBytes;return n[o>>>5]|=128<<24-o%32,n[14+(o+64>>>9<<4)]=e.floor(r/4294967296),n[15+(o+64>>>9<<4)]=r,t.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=r._createHelper(o),t.HmacSHA256=r._createHmacHelper(o)}(Math),_=(b=P).enc.Utf8,b.algo.HMAC=b.lib.Base.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=_.parse(t));var n=e.blockSize,r=4*n;t.sigBytes>r&&(t=e.finalize(t)),t.clamp();for(var o=this._oKey=t.clone(),i=this._iKey=t.clone(),a=o.words,s=i.words,u=0;u>>2]>>>24-o%4*8&255)<<16|(t[o+1>>>2]>>>24-(o+1)%4*8&255)<<8|t[o+2>>>2]>>>24-(o+2)%4*8&255,a=0;4>a&&o+.75*a>>6*(3-a)&63));if(t=r.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var t=e.length,n=this._map;(r=n.charAt(64))&&-1!=(r=e.indexOf(r))&&(t=r);for(var r=[],o=0,i=0;i>>6-i%4*2;r[o>>>2]|=(a|s)<<24-o%4*8,o++}return w.create(r,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},function(e){function t(e,t,n,r,o,i,a){return((e=e+(t&n|~t&r)+o+a)<>>32-i)+t}function n(e,t,n,r,o,i,a){return((e=e+(t&r|n&~r)+o+a)<>>32-i)+t}function r(e,t,n,r,o,i,a){return((e=e+(t^n^r)+o+a)<>>32-i)+t}function o(e,t,n,r,o,i,a){return((e=e+(n^(t|~r))+o+a)<>>32-i)+t}for(var i=P,a=(u=i.lib).WordArray,s=u.Hasher,u=i.algo,c=[],l=0;64>l;l++)c[l]=4294967296*e.abs(e.sin(l+1))|0;u=u.MD5=s.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,i){for(var a=0;16>a;a++){var s=e[u=i+a];e[u]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8)}a=this._hash.words;var u=e[i+0],l=(s=e[i+1],e[i+2]),p=e[i+3],h=e[i+4],f=e[i+5],d=e[i+6],y=e[i+7],g=e[i+8],m=e[i+9],v=e[i+10],b=e[i+11],_=e[i+12],S=e[i+13],w=e[i+14],O=e[i+15],P=t(P=a[0],A=a[1],T=a[2],E=a[3],u,7,c[0]),E=t(E,P,A,T,s,12,c[1]),T=t(T,E,P,A,l,17,c[2]),A=t(A,T,E,P,p,22,c[3]);P=t(P,A,T,E,h,7,c[4]),E=t(E,P,A,T,f,12,c[5]),T=t(T,E,P,A,d,17,c[6]),A=t(A,T,E,P,y,22,c[7]),P=t(P,A,T,E,g,7,c[8]),E=t(E,P,A,T,m,12,c[9]),T=t(T,E,P,A,v,17,c[10]),A=t(A,T,E,P,b,22,c[11]),P=t(P,A,T,E,_,7,c[12]),E=t(E,P,A,T,S,12,c[13]),T=t(T,E,P,A,w,17,c[14]),P=n(P,A=t(A,T,E,P,O,22,c[15]),T,E,s,5,c[16]),E=n(E,P,A,T,d,9,c[17]),T=n(T,E,P,A,b,14,c[18]),A=n(A,T,E,P,u,20,c[19]),P=n(P,A,T,E,f,5,c[20]),E=n(E,P,A,T,v,9,c[21]),T=n(T,E,P,A,O,14,c[22]),A=n(A,T,E,P,h,20,c[23]),P=n(P,A,T,E,m,5,c[24]),E=n(E,P,A,T,w,9,c[25]),T=n(T,E,P,A,p,14,c[26]),A=n(A,T,E,P,g,20,c[27]),P=n(P,A,T,E,S,5,c[28]),E=n(E,P,A,T,l,9,c[29]),T=n(T,E,P,A,y,14,c[30]),P=r(P,A=n(A,T,E,P,_,20,c[31]),T,E,f,4,c[32]),E=r(E,P,A,T,g,11,c[33]),T=r(T,E,P,A,b,16,c[34]),A=r(A,T,E,P,w,23,c[35]),P=r(P,A,T,E,s,4,c[36]),E=r(E,P,A,T,h,11,c[37]),T=r(T,E,P,A,y,16,c[38]),A=r(A,T,E,P,v,23,c[39]),P=r(P,A,T,E,S,4,c[40]),E=r(E,P,A,T,u,11,c[41]),T=r(T,E,P,A,p,16,c[42]),A=r(A,T,E,P,d,23,c[43]),P=r(P,A,T,E,m,4,c[44]),E=r(E,P,A,T,_,11,c[45]),T=r(T,E,P,A,O,16,c[46]),P=o(P,A=r(A,T,E,P,l,23,c[47]),T,E,u,6,c[48]),E=o(E,P,A,T,y,10,c[49]),T=o(T,E,P,A,w,15,c[50]),A=o(A,T,E,P,f,21,c[51]),P=o(P,A,T,E,_,6,c[52]),E=o(E,P,A,T,p,10,c[53]),T=o(T,E,P,A,v,15,c[54]),A=o(A,T,E,P,s,21,c[55]),P=o(P,A,T,E,g,6,c[56]),E=o(E,P,A,T,O,10,c[57]),T=o(T,E,P,A,d,15,c[58]),A=o(A,T,E,P,S,21,c[59]),P=o(P,A,T,E,h,6,c[60]),E=o(E,P,A,T,b,10,c[61]),T=o(T,E,P,A,l,15,c[62]),A=o(A,T,E,P,m,21,c[63]);a[0]=a[0]+P|0,a[1]=a[1]+A|0,a[2]=a[2]+T|0,a[3]=a[3]+E|0},_doFinalize:function(){var t=this._data,n=t.words,r=8*this._nDataBytes,o=8*t.sigBytes;n[o>>>5]|=128<<24-o%32;var i=e.floor(r/4294967296);for(n[15+(o+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),n[14+(o+64>>>9<<4)]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8),t.sigBytes=4*(n.length+1),this._process(),n=(t=this._hash).words,r=0;4>r;r++)o=n[r],n[r]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8);return t},clone:function(){var e=s.clone.call(this);return e._hash=this._hash.clone(),e}}),i.MD5=s._createHelper(u),i.HmacMD5=s._createHmacHelper(u)}(Math),function(){var e,t=P,n=(e=t.lib).Base,r=e.WordArray,o=(e=t.algo).EvpKDF=n.extend({cfg:n.extend({keySize:4,hasher:e.MD5,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var n=(s=this.cfg).hasher.create(),o=r.create(),i=o.words,a=s.keySize,s=s.iterations;i.length>>2]}},t.BlockCipher=s.extend({cfg:s.cfg.extend({mode:u,padding:l}),reset:function(){s.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var n=t.createEncryptor;else n=t.createDecryptor,this._minBufferSize=1;this._mode=n.call(t,this,e&&e.words)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else t=this._process(!0),e.unpad(t);return t},blockSize:4});var p=t.CipherParams=n.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),h=(u=(f.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?r.create([1398893684,1701076831]).concat(e).concat(t):t).toString(i)},parse:function(e){var t=(e=i.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var n=r.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return p.create({ciphertext:e,salt:n})}},t.SerializableCipher=n.extend({cfg:n.extend({format:u}),encrypt:function(e,t,n,r){r=this.cfg.extend(r);var o=e.createEncryptor(n,r);return t=o.finalize(t),o=o.cfg,p.create({ciphertext:t,key:n,iv:o.iv,algorithm:e,mode:o.mode,padding:o.padding,blockSize:e.blockSize,formatter:r.format})},decrypt:function(e,t,n,r){return r=this.cfg.extend(r),t=this._parse(t,r.format),e.createDecryptor(n,r).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),f=(f.kdf={}).OpenSSL={execute:function(e,t,n,o){return o||(o=r.random(8)),e=a.create({keySize:t+n}).compute(e,o),n=r.create(e.words.slice(t),4*n),e.sigBytes=4*t,p.create({key:e,iv:n,salt:o})}},d=t.PasswordBasedCipher=h.extend({cfg:h.cfg.extend({kdf:f}),encrypt:function(e,t,n,r){return n=(r=this.cfg.extend(r)).kdf.execute(n,e.keySize,e.ivSize),r.iv=n.iv,(e=h.encrypt.call(this,e,t,n.key,r)).mixIn(n),e},decrypt:function(e,t,n,r){return r=this.cfg.extend(r),t=this._parse(t,r.format),n=r.kdf.execute(n,e.keySize,e.ivSize,t.salt),r.iv=n.iv,h.decrypt.call(this,e,t,n.key,r)}})}(),function(){for(var e=P,t=e.lib.BlockCipher,n=e.algo,r=[],o=[],i=[],a=[],s=[],u=[],c=[],l=[],p=[],h=[],f=[],d=0;256>d;d++)f[d]=128>d?d<<1:d<<1^283;var y=0,g=0;for(d=0;256>d;d++){var m=(m=g^g<<1^g<<2^g<<3^g<<4)>>>8^255&m^99;r[y]=m,o[m]=y;var v=f[y],b=f[v],_=f[b],S=257*f[m]^16843008*m;i[y]=S<<24|S>>>8,a[y]=S<<16|S>>>16,s[y]=S<<8|S>>>24,u[y]=S,S=16843009*_^65537*b^257*v^16843008*y,c[m]=S<<24|S>>>8,l[m]=S<<16|S>>>16,p[m]=S<<8|S>>>24,h[m]=S,y?(y=v^f[f[f[_^v]]],g^=f[f[g]]):y=g=1}var w=[0,1,2,4,8,16,32,64,128,27,54];n=n.AES=t.extend({_doReset:function(){for(var e=(n=this._key).words,t=n.sigBytes/4,n=4*((this._nRounds=t+6)+1),o=this._keySchedule=[],i=0;i>>24]<<24|r[a>>>16&255]<<16|r[a>>>8&255]<<8|r[255&a]):(a=r[(a=a<<8|a>>>24)>>>24]<<24|r[a>>>16&255]<<16|r[a>>>8&255]<<8|r[255&a],a^=w[i/t|0]<<24),o[i]=o[i-t]^a}for(e=this._invKeySchedule=[],t=0;tt||4>=i?a:c[r[a>>>24]]^l[r[a>>>16&255]]^p[r[a>>>8&255]]^h[r[255&a]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,i,a,s,u,r)},decryptBlock:function(e,t){var n=e[t+1];e[t+1]=e[t+3],e[t+3]=n,this._doCryptBlock(e,t,this._invKeySchedule,c,l,p,h,o),n=e[t+1],e[t+1]=e[t+3],e[t+3]=n},_doCryptBlock:function(e,t,n,r,o,i,a,s){for(var u=this._nRounds,c=e[t]^n[0],l=e[t+1]^n[1],p=e[t+2]^n[2],h=e[t+3]^n[3],f=4,d=1;d>>24]^o[l>>>16&255]^i[p>>>8&255]^a[255&h]^n[f++],g=r[l>>>24]^o[p>>>16&255]^i[h>>>8&255]^a[255&c]^n[f++],m=r[p>>>24]^o[h>>>16&255]^i[c>>>8&255]^a[255&l]^n[f++];h=r[h>>>24]^o[c>>>16&255]^i[l>>>8&255]^a[255&p]^n[f++],c=y,l=g,p=m}y=(s[c>>>24]<<24|s[l>>>16&255]<<16|s[p>>>8&255]<<8|s[255&h])^n[f++],g=(s[l>>>24]<<24|s[p>>>16&255]<<16|s[h>>>8&255]<<8|s[255&c])^n[f++],m=(s[p>>>24]<<24|s[h>>>16&255]<<16|s[c>>>8&255]<<8|s[255&l])^n[f++],h=(s[h>>>24]<<24|s[c>>>16&255]<<16|s[l>>>8&255]<<8|s[255&p])^n[f++],e[t]=y,e[t+1]=g,e[t+2]=m,e[t+3]=h},keySize:8});e.AES=t._createHelper(n)}(),P.mode.ECB=((O=P.lib.BlockCipherMode.extend()).Encryptor=O.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),O.Decryptor=O.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),O);var E=P;function T(e){var t,n=[];for(t=0;t=this._config.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))},e.prototype.clearHistory=function(){this.hashHistory=[]},e}();function N(e){return encodeURIComponent(e).replace(/[!~*'()]/g,(function(e){return"%".concat(e.charCodeAt(0).toString(16).toUpperCase())}))}function M(e){return function(e){var t=[];return Object.keys(e).forEach((function(e){return t.push(e)})),t}(e).sort()}var j={signPamFromParams:function(e){return M(e).map((function(t){return"".concat(t,"=").concat(N(e[t]))})).join("&")},endsWith:function(e,t){return-1!==e.indexOf(t,this.length-t.length)},createPromise:function(){var e,t;return{promise:new Promise((function(n,r){e=n,t=r})),reject:t,fulfill:e}},encodeString:N,stringToArrayBuffer:function(e){for(var t=new ArrayBuffer(2*e.length),n=new Uint16Array(t),r=0,o=e.length;r=u){var l={};l.category=R.PNRequestMessageCountExceededCategory,l.operation=e.operation,this._listenerManager.announceStatus(l)}a.forEach((function(e){var t=e.channel,i=e.subscriptionMatch,a=e.publishMetaData;if(t===i&&(i=null),c){if(o._dedupingManager.isDuplicate(e))return;o._dedupingManager.addEntry(e)}if(j.endsWith(e.channel,"-pnpres"))(y={channel:null,subscription:null}).actualChannel=null!=i?t:null,y.subscribedChannel=null!=i?i:t,t&&(y.channel=t.substring(0,t.lastIndexOf("-pnpres"))),i&&(y.subscription=i.substring(0,i.lastIndexOf("-pnpres"))),y.action=e.payload.action,y.state=e.payload.data,y.timetoken=a.publishTimetoken,y.occupancy=e.payload.occupancy,y.uuid=e.payload.uuid,y.timestamp=e.payload.timestamp,e.payload.join&&(y.join=e.payload.join),e.payload.leave&&(y.leave=e.payload.leave),e.payload.timeout&&(y.timeout=e.payload.timeout),o._listenerManager.announcePresence(y);else if(1===e.messageType){(y={channel:null,subscription:null}).channel=t,y.subscription=i,y.timetoken=a.publishTimetoken,y.publisher=e.issuingClientId,e.userMetadata&&(y.userMetadata=e.userMetadata),y.message=e.payload,o._listenerManager.announceSignal(y)}else if(2===e.messageType){if((y={channel:null,subscription:null}).channel=t,y.subscription=i,y.timetoken=a.publishTimetoken,y.publisher=e.issuingClientId,e.userMetadata&&(y.userMetadata=e.userMetadata),y.message={event:e.payload.event,type:e.payload.type,data:e.payload.data},o._listenerManager.announceObjects(y),"uuid"===e.payload.type){var s=o._renameChannelField(y);o._listenerManager.announceUser(n(n({},s),{message:n(n({},s.message),{event:o._renameEvent(s.message.event),type:"user"})}))}else if("channel"===e.payload.type){s=o._renameChannelField(y);o._listenerManager.announceSpace(n(n({},s),{message:n(n({},s.message),{event:o._renameEvent(s.message.event),type:"space"})}))}else if("membership"===e.payload.type){var u=(s=o._renameChannelField(y)).message.data,l=u.uuid,p=u.channel,h=r(u,["uuid","channel"]);h.user=l,h.space=p,o._listenerManager.announceMembership(n(n({},s),{message:n(n({},s.message),{event:o._renameEvent(s.message.event),data:h})}))}}else if(3===e.messageType){(y={}).channel=t,y.subscription=i,y.timetoken=a.publishTimetoken,y.publisher=e.issuingClientId,y.data={messageTimetoken:e.payload.data.messageTimetoken,actionTimetoken:e.payload.data.actionTimetoken,type:e.payload.data.type,uuid:e.issuingClientId,value:e.payload.data.value},y.event=e.payload.event,o._listenerManager.announceMessageAction(y)}else if(4===e.messageType){(y={}).channel=t,y.subscription=i,y.timetoken=a.publishTimetoken,y.publisher=e.issuingClientId;var f=e.payload;if(o._cryptoModule){var d=void 0;try{d=(g=o._cryptoModule.decrypt(e.payload))instanceof ArrayBuffer?JSON.parse(o._decoder.decode(g)):g}catch(e){d=null,y.error="Error while decrypting message content: ".concat(e.message)}null!==d&&(f=d)}e.userMetadata&&(y.userMetadata=e.userMetadata),y.message=f.message,y.file={id:f.file.id,name:f.file.name,url:o._getFileUrl({id:f.file.id,name:f.file.name,channel:t})},o._listenerManager.announceFile(y)}else{var y;if((y={channel:null,subscription:null}).actualChannel=null!=i?t:null,y.subscribedChannel=null!=i?i:t,y.channel=t,y.subscription=i,y.timetoken=a.publishTimetoken,y.publisher=e.issuingClientId,e.userMetadata&&(y.userMetadata=e.userMetadata),o._cryptoModule){d=void 0;try{var g;d=(g=o._cryptoModule.decrypt(e.payload))instanceof ArrayBuffer?JSON.parse(o._decoder.decode(g)):g}catch(e){d=null,y.error="Error while decrypting message content: ".concat(e.message)}y.message=null!=d?d:e.payload}else y.message=e.payload;o._listenerManager.announceMessage(y)}})),this._region=t.metadata.region,this._startSubscribeLoop()}},e.prototype._stopSubscribeLoop=function(){this._subscribeCall&&("function"==typeof this._subscribeCall.abort&&this._subscribeCall.abort(),this._subscribeCall=null)},e.prototype._renameEvent=function(e){return"set"===e?"updated":"removed"},e.prototype._renameChannelField=function(e){var t=e.channel,n=r(e,["channel"]);return n.spaceId=t,n},e}(),U={PNTimeOperation:"PNTimeOperation",PNHistoryOperation:"PNHistoryOperation",PNDeleteMessagesOperation:"PNDeleteMessagesOperation",PNFetchMessagesOperation:"PNFetchMessagesOperation",PNMessageCounts:"PNMessageCountsOperation",PNSubscribeOperation:"PNSubscribeOperation",PNUnsubscribeOperation:"PNUnsubscribeOperation",PNPublishOperation:"PNPublishOperation",PNSignalOperation:"PNSignalOperation",PNAddMessageActionOperation:"PNAddActionOperation",PNRemoveMessageActionOperation:"PNRemoveMessageActionOperation",PNGetMessageActionsOperation:"PNGetMessageActionsOperation",PNCreateUserOperation:"PNCreateUserOperation",PNUpdateUserOperation:"PNUpdateUserOperation",PNDeleteUserOperation:"PNDeleteUserOperation",PNGetUserOperation:"PNGetUsersOperation",PNGetUsersOperation:"PNGetUsersOperation",PNCreateSpaceOperation:"PNCreateSpaceOperation",PNUpdateSpaceOperation:"PNUpdateSpaceOperation",PNDeleteSpaceOperation:"PNDeleteSpaceOperation",PNGetSpaceOperation:"PNGetSpacesOperation",PNGetSpacesOperation:"PNGetSpacesOperation",PNGetMembersOperation:"PNGetMembersOperation",PNUpdateMembersOperation:"PNUpdateMembersOperation",PNGetMembershipsOperation:"PNGetMembershipsOperation",PNUpdateMembershipsOperation:"PNUpdateMembershipsOperation",PNListFilesOperation:"PNListFilesOperation",PNGenerateUploadUrlOperation:"PNGenerateUploadUrlOperation",PNPublishFileOperation:"PNPublishFileOperation",PNGetFileUrlOperation:"PNGetFileUrlOperation",PNDownloadFileOperation:"PNDownloadFileOperation",PNGetAllUUIDMetadataOperation:"PNGetAllUUIDMetadataOperation",PNGetUUIDMetadataOperation:"PNGetUUIDMetadataOperation",PNSetUUIDMetadataOperation:"PNSetUUIDMetadataOperation",PNRemoveUUIDMetadataOperation:"PNRemoveUUIDMetadataOperation",PNGetAllChannelMetadataOperation:"PNGetAllChannelMetadataOperation",PNGetChannelMetadataOperation:"PNGetChannelMetadataOperation",PNSetChannelMetadataOperation:"PNSetChannelMetadataOperation",PNRemoveChannelMetadataOperation:"PNRemoveChannelMetadataOperation",PNSetMembersOperation:"PNSetMembersOperation",PNSetMembershipsOperation:"PNSetMembershipsOperation",PNPushNotificationEnabledChannelsOperation:"PNPushNotificationEnabledChannelsOperation",PNRemoveAllPushNotificationsOperation:"PNRemoveAllPushNotificationsOperation",PNWhereNowOperation:"PNWhereNowOperation",PNSetStateOperation:"PNSetStateOperation",PNHereNowOperation:"PNHereNowOperation",PNGetStateOperation:"PNGetStateOperation",PNHeartbeatOperation:"PNHeartbeatOperation",PNChannelGroupsOperation:"PNChannelGroupsOperation",PNRemoveGroupOperation:"PNRemoveGroupOperation",PNChannelsForGroupOperation:"PNChannelsForGroupOperation",PNAddChannelsToGroupOperation:"PNAddChannelsToGroupOperation",PNRemoveChannelsFromGroupOperation:"PNRemoveChannelsFromGroupOperation",PNAccessManagerGrant:"PNAccessManagerGrant",PNAccessManagerGrantToken:"PNAccessManagerGrantToken",PNAccessManagerAudit:"PNAccessManagerAudit",PNAccessManagerRevokeToken:"PNAccessManagerRevokeToken",PNHandshakeOperation:"PNHandshakeOperation",PNReceiveMessagesOperation:"PNReceiveMessagesOperation"},I=function(){function e(e){this._maximumSamplesCount=100,this._trackedLatencies={},this._latencies={},this._maximumSamplesCount=e.maximumSamplesCount||this._maximumSamplesCount}return e.prototype.operationsLatencyForRequest=function(){var e=this,t={};return Object.keys(this._latencies).forEach((function(n){var r=e._latencies[n],o=e._averageLatency(r);o>0&&(t["l_".concat(n)]=o)})),t},e.prototype.startLatencyMeasure=function(e,t){e!==U.PNSubscribeOperation&&t&&(this._trackedLatencies[t]=Date.now())},e.prototype.stopLatencyMeasure=function(e,t){if(e!==U.PNSubscribeOperation&&t){var n=this._endpointName(e),r=this._latencies[n],o=this._trackedLatencies[t];r||(this._latencies[n]=[],r=this._latencies[n]),r.push(Date.now()-o),r.length>this._maximumSamplesCount&&r.splice(0,r.length-this._maximumSamplesCount),delete this._trackedLatencies[t]}},e.prototype._averageLatency=function(e){return Math.floor(e.reduce((function(e,t){return e+t}),0)/e.length)},e.prototype._endpointName=function(e){var t=null;switch(e){case U.PNPublishOperation:t="pub";break;case U.PNSignalOperation:t="sig";break;case U.PNHistoryOperation:case U.PNFetchMessagesOperation:case U.PNDeleteMessagesOperation:case U.PNMessageCounts:t="hist";break;case U.PNUnsubscribeOperation:case U.PNWhereNowOperation:case U.PNHereNowOperation:case U.PNHeartbeatOperation:case U.PNSetStateOperation:case U.PNGetStateOperation:t="pres";break;case U.PNAddChannelsToGroupOperation:case U.PNRemoveChannelsFromGroupOperation:case U.PNChannelGroupsOperation:case U.PNRemoveGroupOperation:case U.PNChannelsForGroupOperation:t="cg";break;case U.PNPushNotificationEnabledChannelsOperation:case U.PNRemoveAllPushNotificationsOperation:t="push";break;case U.PNCreateUserOperation:case U.PNUpdateUserOperation:case U.PNDeleteUserOperation:case U.PNGetUserOperation:case U.PNGetUsersOperation:case U.PNCreateSpaceOperation:case U.PNUpdateSpaceOperation:case U.PNDeleteSpaceOperation:case U.PNGetSpaceOperation:case U.PNGetSpacesOperation:case U.PNGetMembersOperation:case U.PNUpdateMembersOperation:case U.PNGetMembershipsOperation:case U.PNUpdateMembershipsOperation:t="obj";break;case U.PNAddMessageActionOperation:case U.PNRemoveMessageActionOperation:case U.PNGetMessageActionsOperation:t="msga";break;case U.PNAccessManagerGrant:case U.PNAccessManagerAudit:t="pam";break;case U.PNAccessManagerGrantToken:case U.PNAccessManagerRevokeToken:t="pamv3";break;default:t="time"}return t},e}(),D=function(){function e(e,t,n){this._payload=e,this._setDefaultPayloadStructure(),this.title=t,this.body=n}return Object.defineProperty(e.prototype,"payload",{get:function(){return this._payload},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"title",{set:function(e){this._title=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"subtitle",{set:function(e){this._subtitle=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"body",{set:function(e){this._body=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"badge",{set:function(e){this._badge=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sound",{set:function(e){this._sound=e},enumerable:!1,configurable:!0}),e.prototype._setDefaultPayloadStructure=function(){},e.prototype.toObject=function(){return{}},e}(),F=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return t(r,e),Object.defineProperty(r.prototype,"configurations",{set:function(e){e&&e.length&&(this._configurations=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"notification",{get:function(){return this._payload.aps},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"title",{get:function(){return this._title},set:function(e){e&&e.length&&(this._payload.aps.alert.title=e,this._title=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"subtitle",{get:function(){return this._subtitle},set:function(e){e&&e.length&&(this._payload.aps.alert.subtitle=e,this._subtitle=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"body",{get:function(){return this._body},set:function(e){e&&e.length&&(this._payload.aps.alert.body=e,this._body=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"badge",{get:function(){return this._badge},set:function(e){null!=e&&(this._payload.aps.badge=e,this._badge=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"sound",{get:function(){return this._sound},set:function(e){e&&e.length&&(this._payload.aps.sound=e,this._sound=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"silent",{set:function(e){this._isSilent=e},enumerable:!1,configurable:!0}),r.prototype._setDefaultPayloadStructure=function(){this._payload.aps={alert:{}}},r.prototype.toObject=function(){var e=this,t=n({},this._payload),r=t.aps,o=r.alert;if(this._isSilent&&(r["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");var i=[];this._configurations.forEach((function(t){i.push(e._objectFromAPNS2Configuration(t))})),i.length&&(t.pn_push=i)}return o&&Object.keys(o).length||delete r.alert,this._isSilent&&(delete r.alert,delete r.badge,delete r.sound,o={}),this._isSilent||Object.keys(o).length?t:null},r.prototype._objectFromAPNS2Configuration=function(e){var t=this;if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");var n=[];e.targets.forEach((function(e){n.push(t._objectFromAPNSTarget(e))}));var r=e.collapseId,o=e.expirationDate,i={auth_method:"token",targets:n,version:"v2"};return r&&r.length&&(i.collapse_id=r),o&&(i.expiration=o.toISOString()),i},r.prototype._objectFromAPNSTarget=function(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");var t=e.topic,n=e.environment,r=void 0===n?"development":n,o=e.excludedDevices,i=void 0===o?[]:o,a={topic:t,environment:r};return i.length&&(a.excluded_devices=i),a},r}(D),G=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return t(r,e),Object.defineProperty(r.prototype,"backContent",{get:function(){return this._backContent},set:function(e){e&&e.length&&(this._payload.back_content=e,this._backContent=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"backTitle",{get:function(){return this._backTitle},set:function(e){e&&e.length&&(this._payload.back_title=e,this._backTitle=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},set:function(e){null!=e&&(this._payload.count=e,this._count=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"title",{get:function(){return this._title},set:function(e){e&&e.length&&(this._payload.title=e,this._title=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"type",{get:function(){return this._type},set:function(e){e&&e.length&&(this._payload.type=e,this._type=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"subtitle",{get:function(){return this.backTitle},set:function(e){this.backTitle=e},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"body",{get:function(){return this.backContent},set:function(e){this.backContent=e},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"badge",{get:function(){return this.count},set:function(e){this.count=e},enumerable:!1,configurable:!0}),r.prototype.toObject=function(){return Object.keys(this._payload).length?n({},this._payload):null},r}(D),L=function(e){function o(){return null!==e&&e.apply(this,arguments)||this}return t(o,e),Object.defineProperty(o.prototype,"notification",{get:function(){return this._payload.notification},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"data",{get:function(){return this._payload.data},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"title",{get:function(){return this._title},set:function(e){e&&e.length&&(this._payload.notification.title=e,this._title=e)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"body",{get:function(){return this._body},set:function(e){e&&e.length&&(this._payload.notification.body=e,this._body=e)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"sound",{get:function(){return this._sound},set:function(e){e&&e.length&&(this._payload.notification.sound=e,this._sound=e)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"icon",{get:function(){return this._icon},set:function(e){e&&e.length&&(this._payload.notification.icon=e,this._icon=e)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"tag",{get:function(){return this._tag},set:function(e){e&&e.length&&(this._payload.notification.tag=e,this._tag=e)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"silent",{set:function(e){this._isSilent=e},enumerable:!1,configurable:!0}),o.prototype._setDefaultPayloadStructure=function(){this._payload.notification={},this._payload.data={}},o.prototype.toObject=function(){var e=n({},this._payload.data),t=null,o={};if(Object.keys(this._payload).length>2){var i=this._payload;i.notification,i.data;var a=r(i,["notification","data"]);e=n(n({},e),a)}return this._isSilent?e.notification=this._payload.notification:t=this._payload.notification,Object.keys(e).length&&(o.data=e),t&&Object.keys(t).length&&(o.notification=t),Object.keys(o).length?o:null},o}(D),K=function(){function e(e,t){this._payload={apns:{},mpns:{},fcm:{}},this._title=e,this._body=t,this.apns=new F(this._payload.apns,e,t),this.mpns=new G(this._payload.mpns,e,t),this.fcm=new L(this._payload.fcm,e,t)}return Object.defineProperty(e.prototype,"debugging",{set:function(e){this._debugging=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"title",{get:function(){return this._title},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"body",{get:function(){return this._body},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"subtitle",{get:function(){return this._subtitle},set:function(e){this._subtitle=e,this.apns.subtitle=e,this.mpns.subtitle=e,this.fcm.subtitle=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"badge",{get:function(){return this._badge},set:function(e){this._badge=e,this.apns.badge=e,this.mpns.badge=e,this.fcm.badge=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sound",{get:function(){return this._sound},set:function(e){this._sound=e,this.apns.sound=e,this.mpns.sound=e,this.fcm.sound=e},enumerable:!1,configurable:!0}),e.prototype.buildPayload=function(e){var t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";var n=this.apns.toObject();n&&Object.keys(n).length&&(t.pn_apns=n)}if(e.includes("mpns")){var r=this.mpns.toObject();r&&Object.keys(r).length&&(t.pn_mpns=r)}if(e.includes("fcm")){var o=this.fcm.toObject();o&&Object.keys(o).length&&(t.pn_gcm=o)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t},e}(),B=function(){function e(){this._listeners=[]}return e.prototype.addListener=function(e){this._listeners.includes(e)||this._listeners.push(e)},e.prototype.removeListener=function(e){var t=[];this._listeners.forEach((function(n){n!==e&&t.push(n)})),this._listeners=t},e.prototype.removeAllListeners=function(){this._listeners=[]},e.prototype.announcePresence=function(e){this._listeners.forEach((function(t){t.presence&&t.presence(e)}))},e.prototype.announceStatus=function(e){this._listeners.forEach((function(t){t.status&&t.status(e)}))},e.prototype.announceMessage=function(e){this._listeners.forEach((function(t){t.message&&t.message(e)}))},e.prototype.announceSignal=function(e){this._listeners.forEach((function(t){t.signal&&t.signal(e)}))},e.prototype.announceMessageAction=function(e){this._listeners.forEach((function(t){t.messageAction&&t.messageAction(e)}))},e.prototype.announceFile=function(e){this._listeners.forEach((function(t){t.file&&t.file(e)}))},e.prototype.announceObjects=function(e){this._listeners.forEach((function(t){t.objects&&t.objects(e)}))},e.prototype.announceUser=function(e){this._listeners.forEach((function(t){t.user&&t.user(e)}))},e.prototype.announceSpace=function(e){this._listeners.forEach((function(t){t.space&&t.space(e)}))},e.prototype.announceMembership=function(e){this._listeners.forEach((function(t){t.membership&&t.membership(e)}))},e.prototype.announceNetworkUp=function(){var e={};e.category=R.PNNetworkUpCategory,this.announceStatus(e)},e.prototype.announceNetworkDown=function(){var e={};e.category=R.PNNetworkDownCategory,this.announceStatus(e)},e}(),H=function(){function e(e,t){this._config=e,this._cbor=t}return e.prototype.setToken=function(e){e&&e.length>0?this._token=e:this._token=void 0},e.prototype.getToken=function(){return this._token},e.prototype.extractPermissions=function(e){var t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128==(128&e)&&(t.join=!0),64==(64&e)&&(t.update=!0),32==(32&e)&&(t.get=!0),8==(8&e)&&(t.delete=!0),4==(4&e)&&(t.manage=!0),2==(2&e)&&(t.write=!0),1==(1&e)&&(t.read=!0),t},e.prototype.parseToken=function(e){var t=this,n=this._cbor.decodeToken(e);if(void 0!==n){var r=n.res.uuid?Object.keys(n.res.uuid):[],o=Object.keys(n.res.chan),i=Object.keys(n.res.grp),a=n.pat.uuid?Object.keys(n.pat.uuid):[],s=Object.keys(n.pat.chan),u=Object.keys(n.pat.grp),c={version:n.v,timestamp:n.t,ttl:n.ttl,authorized_uuid:n.uuid},l=r.length>0,p=o.length>0,h=i.length>0;(l||p||h)&&(c.resources={},l&&(c.resources.uuids={},r.forEach((function(e){c.resources.uuids[e]=t.extractPermissions(n.res.uuid[e])}))),p&&(c.resources.channels={},o.forEach((function(e){c.resources.channels[e]=t.extractPermissions(n.res.chan[e])}))),h&&(c.resources.groups={},i.forEach((function(e){c.resources.groups[e]=t.extractPermissions(n.res.grp[e])}))));var f=a.length>0,d=s.length>0,y=u.length>0;return(f||d||y)&&(c.patterns={},f&&(c.patterns.uuids={},a.forEach((function(e){c.patterns.uuids[e]=t.extractPermissions(n.pat.uuid[e])}))),d&&(c.patterns.channels={},s.forEach((function(e){c.patterns.channels[e]=t.extractPermissions(n.pat.chan[e])}))),y&&(c.patterns.groups={},u.forEach((function(e){c.patterns.groups[e]=t.extractPermissions(n.pat.grp[e])})))),Object.keys(n.meta).length>0&&(c.meta=n.meta),c.signature=n.sig,c}},e}(),q=function(e){function n(t,n){var r=this.constructor,o=e.call(this,t)||this;return o.name=o.constructor.name,o.status=n,o.message=t,Object.setPrototypeOf(o,r.prototype),o}return t(n,e),n}(Error);function z(e){return(t={message:e}).type="validationError",t.error=!0,t;var t}function V(e,t,n){return e.usePost&&e.usePost(t,n)?e.postURL(t,n):e.usePatch&&e.usePatch(t,n)?e.patchURL(t,n):e.useGetFile&&e.useGetFile(t,n)?e.getFileURL(t,n):e.getURL(t,n)}function W(e){if(e.sdkName)return e.sdkName;var t="PubNub-JS-".concat(e.sdkFamily);e.partnerId&&(t+="-".concat(e.partnerId)),t+="/".concat(e.getVersion());var n=e._getPnsdkSuffix(" ");return n.length>0&&(t+=n),t}function J(e,t,n){return t.usePost&&t.usePost(e,n)?"POST":t.usePatch&&t.usePatch(e,n)?"PATCH":t.useDelete&&t.useDelete(e,n)?"DELETE":t.useGetFile&&t.useGetFile(e,n)?"GETFILE":"GET"}function $(e,t,n,r,o){var i=e.config,a=e.crypto,s=J(e,o,r);n.timestamp=Math.floor((new Date).getTime()/1e3),"PNPublishOperation"===o.getOperation()&&o.usePost&&o.usePost(e,r)&&(s="GET"),"GETFILE"===s&&(s="GET");var u="".concat(s,"\n").concat(i.publishKey,"\n").concat(t,"\n").concat(j.signPamFromParams(n),"\n");if("POST"===s)u+="string"==typeof(c=o.postPayload(e,r))?c:JSON.stringify(c);else if("PATCH"===s){var c;u+="string"==typeof(c=o.patchPayload(e,r))?c:JSON.stringify(c)}var l="v2.".concat(a.HMACSHA256(u));l=(l=(l=l.replace(/\+/g,"-")).replace(/\//g,"_")).replace(/=+$/,""),n.signature=l}function Q(e,t){for(var r=[],o=2;o0?o.join(","):",";return"/v2/presence/sub-key/".concat(n.subscribeKey,"/channel/").concat(j.encodeString(i),"/leave")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.channelGroups,r=void 0===n?[]:n,o={};return r.length>0&&(o["channel-group"]=r.join(",")),o},handleResponse:function(){return{}}});var se=Object.freeze({__proto__:null,getOperation:function(){return U.PNWhereNowOperation},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.uuid,o=void 0===r?n.UUID:r;return"/v2/presence/sub-key/".concat(n.subscribeKey,"/uuid/").concat(j.encodeString(o))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return t.payload?{channels:t.payload.channels}:{channels:[]}}});var ue=Object.freeze({__proto__:null,getOperation:function(){return U.PNHeartbeatOperation},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.channels,o=void 0===r?[]:r,i=o.length>0?o.join(","):",";return"/v2/presence/sub-key/".concat(n.subscribeKey,"/channel/").concat(j.encodeString(i),"/heartbeat")},isAuthSupported:function(){return!0},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},prepareParams:function(e,t){var n=t.channelGroups,r=void 0===n?[]:n,o=t.state,i=e.config,a={};return r.length>0&&(a["channel-group"]=r.join(",")),o&&(a.state=JSON.stringify(o)),a.heartbeat=i.getPresenceTimeout(),a},handleResponse:function(){return{}}});var ce=Object.freeze({__proto__:null,getOperation:function(){return U.PNGetStateOperation},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.uuid,o=void 0===r?n.UUID:r,i=t.channels,a=void 0===i?[]:i,s=a.length>0?a.join(","):",";return"/v2/presence/sub-key/".concat(n.subscribeKey,"/channel/").concat(j.encodeString(s),"/uuid/").concat(o)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.channelGroups,r=void 0===n?[]:n,o={};return r.length>0&&(o["channel-group"]=r.join(",")),o},handleResponse:function(e,t,n){var r=n.channels,o=void 0===r?[]:r,i=n.channelGroups,a=void 0===i?[]:i,s={};return 1===o.length&&0===a.length?s[o[0]]=t.payload:s=t.payload,{channels:s}}});var le=Object.freeze({__proto__:null,getOperation:function(){return U.PNSetStateOperation},validateParams:function(e,t){var n=e.config,r=t.state,o=t.channels,i=void 0===o?[]:o,a=t.channelGroups,s=void 0===a?[]:a;return r?n.subscribeKey?0===i.length&&0===s.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key":"Missing State"},getURL:function(e,t){var n=e.config,r=t.channels,o=void 0===r?[]:r,i=o.length>0?o.join(","):",";return"/v2/presence/sub-key/".concat(n.subscribeKey,"/channel/").concat(j.encodeString(i),"/uuid/").concat(j.encodeString(n.UUID),"/data")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.state,r=t.channelGroups,o=void 0===r?[]:r,i={};return i.state=JSON.stringify(n),o.length>0&&(i["channel-group"]=o.join(",")),i},handleResponse:function(e,t){return{state:t.payload}}});var pe=Object.freeze({__proto__:null,getOperation:function(){return U.PNHereNowOperation},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.channels,o=void 0===r?[]:r,i=t.channelGroups,a=void 0===i?[]:i,s="/v2/presence/sub-key/".concat(n.subscribeKey);if(o.length>0||a.length>0){var u=o.length>0?o.join(","):",";s+="/channel/".concat(j.encodeString(u))}return s},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var r=t.channelGroups,o=void 0===r?[]:r,i=t.includeUUIDs,a=void 0===i||i,s=t.includeState,u=void 0!==s&&s,c=t.queryParameters,l=void 0===c?{}:c,p={};return a||(p.disable_uuids=1),u&&(p.state=1),o.length>0&&(p["channel-group"]=o.join(",")),p=n(n({},p),l)},handleResponse:function(e,t,n){var r=n.channels,o=void 0===r?[]:r,i=n.channelGroups,a=void 0===i?[]:i,s=n.includeUUIDs,u=void 0===s||s,c=n.includeState,l=void 0!==c&&c;return o.length>1||a.length>0||0===a.length&&0===o.length?function(){var e={};return e.totalChannels=t.payload.total_channels,e.totalOccupancy=t.payload.total_occupancy,e.channels={},Object.keys(t.payload.channels).forEach((function(n){var r=t.payload.channels[n],o=[];return e.channels[n]={occupants:o,name:n,occupancy:r.occupancy},u&&r.uuids.forEach((function(e){l?o.push({state:e.state,uuid:e.uuid}):o.push({state:null,uuid:e})})),e})),e}():function(){var e={},n=[];return e.totalChannels=1,e.totalOccupancy=t.occupancy,e.channels={},e.channels[o[0]]={occupants:n,name:o[0],occupancy:t.occupancy},u&&t.uuids&&t.uuids.forEach((function(e){l?n.push({state:e.state,uuid:e.uuid}):n.push({state:null,uuid:e})})),e}()},handleError:function(e,t,n){402!==n.statusCode||this.getURL(e,t).includes("channel")||(n.errorData.message="You have tried to perform a Global Here Now operation, your keyset configuration does not support that. Please provide a channel, or enable the Global Here Now feature from the Portal.")}});var he=Object.freeze({__proto__:null,getOperation:function(){return U.PNAddMessageActionOperation},validateParams:function(e,t){var n=e.config,r=t.action,o=t.channel;return t.messageTimetoken?n.subscribeKey?o?r?r.value?r.type?r.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message channel":"Missing Subscribe Key":"Missing message timetoken"},usePost:function(){return!0},postURL:function(e,t){var n=e.config,r=t.channel,o=t.messageTimetoken;return"/v1/message-actions/".concat(n.subscribeKey,"/channel/").concat(j.encodeString(r),"/message/").concat(o)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},getRequestHeaders:function(){return{"Content-Type":"application/json"}},isAuthSupported:function(){return!0},prepareParams:function(){return{}},postPayload:function(e,t){return t.action},handleResponse:function(e,t){return{data:t.data}}});var fe=Object.freeze({__proto__:null,getOperation:function(){return U.PNRemoveMessageActionOperation},validateParams:function(e,t){var n=e.config,r=t.channel,o=t.actionTimetoken;return t.messageTimetoken?o?n.subscribeKey?r?void 0:"Missing message channel":"Missing Subscribe Key":"Missing action timetoken":"Missing message timetoken"},useDelete:function(){return!0},getURL:function(e,t){var n=e.config,r=t.channel,o=t.actionTimetoken,i=t.messageTimetoken;return"/v1/message-actions/".concat(n.subscribeKey,"/channel/").concat(j.encodeString(r),"/message/").concat(i,"/action/").concat(o)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{data:t.data}}});var de=Object.freeze({__proto__:null,getOperation:function(){return U.PNGetMessageActionsOperation},validateParams:function(e,t){var n=e.config,r=t.channel;return n.subscribeKey?r?void 0:"Missing message channel":"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.channel;return"/v1/message-actions/".concat(n.subscribeKey,"/channel/").concat(j.encodeString(r))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.limit,r=t.start,o=t.end,i={};return n&&(i.limit=n),r&&(i.start=r),o&&(i.end=o),i},handleResponse:function(e,t){var n={data:t.data,start:null,end:null};return n.data.length&&(n.end=n.data[n.data.length-1].actionTimetoken,n.start=n.data[0].actionTimetoken),n}}),ye={getOperation:function(){return U.PNListFilesOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channel))return"channel can't be empty"},getURL:function(e,t){var n=e.config;return"/v1/files/".concat(n.subscribeKey,"/channels/").concat(j.encodeString(t.channel),"/files")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n={};return t.limit&&(n.limit=t.limit),t.next&&(n.next=t.next),n},handleResponse:function(e,t){return{status:t.status,data:t.data,next:t.next,count:t.count}}},ge={getOperation:function(){return U.PNGenerateUploadUrlOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.name)?void 0:"name can't be empty":"channel can't be empty"},usePost:function(){return!0},postURL:function(e,t){var n=e.config;return"/v1/files/".concat(n.subscribeKey,"/channels/").concat(j.encodeString(t.channel),"/generate-upload-url")},postPayload:function(e,t){return{name:t.name}},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{status:t.status,data:t.data,file_upload_request:t.file_upload_request}}},me={getOperation:function(){return U.PNPublishFileOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.fileId)?(null==t?void 0:t.fileName)?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"},getURL:function(e,t){var n=e.config,r=n.publishKey,o=n.subscribeKey,i=function(e,t){var n=JSON.stringify(t);if(e.cryptoModule){var r=e.cryptoModule.encrypt(n);n="string"==typeof r?r:v(r),n=JSON.stringify(n)}return n||""}(e,{message:t.message,file:{name:t.fileName,id:t.fileId}});return"/v1/files/publish-file/".concat(r,"/").concat(o,"/0/").concat(j.encodeString(t.channel),"/0/").concat(j.encodeString(i))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n={};return t.ttl&&(n.ttl=t.ttl),void 0!==t.storeInHistory&&(n.store=t.storeInHistory?"1":"0"),t.meta&&"object"==typeof t.meta&&(n.meta=JSON.stringify(t.meta)),n},handleResponse:function(e,t){return{timetoken:t[2]}}},ve=function(e){var t=function(e){var t=this,n=e.generateUploadUrl,r=e.publishFile,a=e.modules,s=a.PubNubFile,u=a.config,c=a.cryptography,l=a.cryptoModule,p=a.networking;return function(e){var a=e.channel,h=e.file,f=e.message,d=e.cipherKey,y=e.meta,g=e.ttl,m=e.storeInHistory;return o(t,void 0,void 0,(function(){var e,t,o,v,b,_,S,w,O,P,E,T,A,C,k,N,M,j,R,x,U,I,D,F,G,L,K,B,H;return i(this,(function(i){switch(i.label){case 0:if(!a)throw new q("Validation failed, check status for details",z("channel can't be empty"));if(!h)throw new q("Validation failed, check status for details",z("file can't be empty"));return e=s.create(h),[4,n({channel:a,name:e.name})];case 1:return t=i.sent(),o=t.file_upload_request,v=o.url,b=o.form_fields,_=t.data,S=_.id,w=_.name,s.supportsEncryptFile&&(d||l)?null!=d?[3,3]:[4,l.encryptFile(e,s)]:[3,6];case 2:return O=i.sent(),[3,5];case 3:return[4,c.encryptFile(d,e,s)];case 4:O=i.sent(),i.label=5;case 5:e=O,i.label=6;case 6:P=b,e.mimeType&&(P=b.map((function(t){return"Content-Type"===t.key?{key:t.key,value:e.mimeType}:t}))),i.label=7;case 7:return i.trys.push([7,21,,22]),s.supportsFileUri&&h.uri?(A=(T=p).POSTFILE,C=[v,P],[4,e.toFileUri()]):[3,10];case 8:return[4,A.apply(T,C.concat([i.sent()]))];case 9:return E=i.sent(),[3,20];case 10:return s.supportsFile?(N=(k=p).POSTFILE,M=[v,P],[4,e.toFile()]):[3,13];case 11:return[4,N.apply(k,M.concat([i.sent()]))];case 12:return E=i.sent(),[3,20];case 13:return s.supportsBuffer?(R=(j=p).POSTFILE,x=[v,P],[4,e.toBuffer()]):[3,16];case 14:return[4,R.apply(j,x.concat([i.sent()]))];case 15:return E=i.sent(),[3,20];case 16:return s.supportsBlob?(I=(U=p).POSTFILE,D=[v,P],[4,e.toBlob()]):[3,19];case 17:return[4,I.apply(U,D.concat([i.sent()]))];case 18:return E=i.sent(),[3,20];case 19:throw new Error("Unsupported environment");case 20:return[3,22];case 21:throw(F=i.sent()).response&&"string"==typeof F.response.text?(G=F.response.text,L=/(.*)<\/Message>/gi.exec(G),new q(L?"Upload to bucket failed: ".concat(L[1]):"Upload to bucket failed.",F)):new q("Upload to bucket failed.",F);case 22:if(204!==E.status)throw new q("Upload to bucket was unsuccessful",E);K=u.fileUploadPublishRetryLimit,B=!1,H={timetoken:"0"},i.label=23;case 23:return i.trys.push([23,25,,26]),[4,r({channel:a,message:f,fileId:S,fileName:w,meta:y,storeInHistory:m,ttl:g})];case 24:return H=i.sent(),B=!0,[3,26];case 25:return i.sent(),K-=1,[3,26];case 26:if(!B&&K>0)return[3,23];i.label=27;case 27:if(B)return[2,{timetoken:H.timetoken,id:S,name:w}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:a,id:S,name:w})}}))}))}}(e);return function(e,n){var r=t(e);return"function"==typeof n?(r.then((function(e){return n(null,e)})).catch((function(e){return n(e,null)})),r):r}},be=function(e,t){var n=t.channel,r=t.id,o=t.name,i=e.config,a=e.networking,s=e.tokenManager;if(!n)throw new q("Validation failed, check status for details",z("channel can't be empty"));if(!r)throw new q("Validation failed, check status for details",z("file id can't be empty"));if(!o)throw new q("Validation failed, check status for details",z("file name can't be empty"));var u="/v1/files/".concat(i.subscribeKey,"/channels/").concat(j.encodeString(n),"/files/").concat(r,"/").concat(o),c={};c.uuid=i.getUUID(),c.pnsdk=W(i);var l=s.getToken()||i.getAuthKey();l&&(c.auth=l),i.secretKey&&$(e,u,c,{},{getOperation:function(){return"PubNubGetFileUrlOperation"}});var p=Object.keys(c).map((function(e){return"".concat(encodeURIComponent(e),"=").concat(encodeURIComponent(c[e]))})).join("&");return""!==p?"".concat(a.getStandardOrigin()).concat(u,"?").concat(p):"".concat(a.getStandardOrigin()).concat(u)},_e={getOperation:function(){return U.PNDownloadFileOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.name)?(null==t?void 0:t.id)?void 0:"id can't be empty":"name can't be empty":"channel can't be empty"},useGetFile:function(){return!0},getFileURL:function(e,t){var n=e.config;return"/v1/files/".concat(n.subscribeKey,"/channels/").concat(j.encodeString(t.channel),"/files/").concat(t.id,"/").concat(t.name)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},ignoreBody:function(){return!0},forceBuffered:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t,n){var r=e.PubNubFile,a=e.config,s=e.cryptography,u=e.cryptoModule;return o(void 0,void 0,void 0,(function(){var e,o,c,l;return i(this,(function(i){switch(i.label){case 0:return e=t.response.body,r.supportsEncryptFile&&(n.cipherKey||u)?null!=n.cipherKey?[3,2]:[4,u.decryptFile(r.create({data:e,name:n.name}),r)]:[3,5];case 1:return o=i.sent().data,[3,4];case 2:return[4,s.decrypt(null!==(c=n.cipherKey)&&void 0!==c?c:a.cipherKey,e)];case 3:o=i.sent(),i.label=4;case 4:e=o,i.label=5;case 5:return[2,r.create({data:e,name:null!==(l=t.response.name)&&void 0!==l?l:n.name,mimeType:t.response.type})]}}))}))}},Se={getOperation:function(){return U.PNListFilesOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.id)?(null==t?void 0:t.name)?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"},useDelete:function(){return!0},getURL:function(e,t){var n=e.config;return"/v1/files/".concat(n.subscribeKey,"/channels/").concat(j.encodeString(t.channel),"/files/").concat(t.id,"/").concat(t.name)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{status:t.status}}},we={getOperation:function(){return U.PNGetAllUUIDMetadataOperation},validateParams:function(){},getURL:function(e){var t=e.config;return"/v2/objects/".concat(t.subscribeKey,"/uuids")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o,i,a,u,c,l,p,h={include:["status","type"]};return(null==t?void 0:t.include)&&(null===(n=t.include)||void 0===n?void 0:n.customFields)&&h.include.push("custom"),h.include=h.include.join(","),(null===(r=null==t?void 0:t.include)||void 0===r?void 0:r.totalCount)&&(h.count=null===(o=t.include)||void 0===o?void 0:o.totalCount),(null===(i=null==t?void 0:t.page)||void 0===i?void 0:i.next)&&(h.start=null===(a=t.page)||void 0===a?void 0:a.next),(null===(u=null==t?void 0:t.page)||void 0===u?void 0:u.prev)&&(h.end=null===(c=t.page)||void 0===c?void 0:c.prev),(null==t?void 0:t.filter)&&(h.filter=t.filter),h.limit=null!==(l=null==t?void 0:t.limit)&&void 0!==l?l:100,(null==t?void 0:t.sort)&&(h.sort=Object.entries(null!==(p=t.sort)&&void 0!==p?p:{}).map((function(e){var t=s(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),h},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,next:t.next,prev:t.prev}}},Oe={getOperation:function(){return U.PNGetUUIDMetadataOperation},validateParams:function(){},getURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(j.encodeString(null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:r.getUUID()))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o=e.config,i={};return i.uuid=null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:o.getUUID(),i.include=["status","type","custom"],(null==t?void 0:t.include)&&!1===(null===(r=t.include)||void 0===r?void 0:r.customFields)&&i.include.pop(),i.include=i.include.join(","),i},handleResponse:function(e,t){return{status:t.status,data:t.data}}},Pe={getOperation:function(){return U.PNSetUUIDMetadataOperation},validateParams:function(e,t){if(!(null==t?void 0:t.data))return"Data cannot be empty"},usePatch:function(){return!0},patchURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(j.encodeString(null!==(n=t.uuid)&&void 0!==n?n:r.getUUID()))},patchPayload:function(e,t){return t.data},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o=e.config,i={};return i.uuid=null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:o.getUUID(),i.include=["status","type","custom"],(null==t?void 0:t.include)&&!1===(null===(r=t.include)||void 0===r?void 0:r.customFields)&&i.include.pop(),i.include=i.include.join(","),i},handleResponse:function(e,t){return{status:t.status,data:t.data}}},Ee={getOperation:function(){return U.PNRemoveUUIDMetadataOperation},validateParams:function(){},getURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(j.encodeString(null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:r.getUUID()))},useDelete:function(){return!0},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r=e.config;return{uuid:null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:r.getUUID()}},handleResponse:function(e,t){return{status:t.status,data:t.data}}},Te={getOperation:function(){return U.PNGetAllChannelMetadataOperation},validateParams:function(){},getURL:function(e){var t=e.config;return"/v2/objects/".concat(t.subscribeKey,"/channels")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o,i,a,u,c,l,p,h={include:["status","type"]};return(null==t?void 0:t.include)&&(null===(n=t.include)||void 0===n?void 0:n.customFields)&&h.include.push("custom"),h.include=h.include.join(","),(null===(r=null==t?void 0:t.include)||void 0===r?void 0:r.totalCount)&&(h.count=null===(o=t.include)||void 0===o?void 0:o.totalCount),(null===(i=null==t?void 0:t.page)||void 0===i?void 0:i.next)&&(h.start=null===(a=t.page)||void 0===a?void 0:a.next),(null===(u=null==t?void 0:t.page)||void 0===u?void 0:u.prev)&&(h.end=null===(c=t.page)||void 0===c?void 0:c.prev),(null==t?void 0:t.filter)&&(h.filter=t.filter),h.limit=null!==(l=null==t?void 0:t.limit)&&void 0!==l?l:100,(null==t?void 0:t.sort)&&(h.sort=Object.entries(null!==(p=t.sort)&&void 0!==p?p:{}).map((function(e){var t=s(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),h},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,prev:t.prev,next:t.next}}},Ae={getOperation:function(){return U.PNGetChannelMetadataOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channel))return"Channel cannot be empty"},getURL:function(e,t){var n=e.config;return"/v2/objects/".concat(n.subscribeKey,"/channels/").concat(j.encodeString(t.channel))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r={include:["status","type","custom"]};return(null==t?void 0:t.include)&&!1===(null===(n=t.include)||void 0===n?void 0:n.customFields)&&r.include.pop(),r.include=r.include.join(","),r},handleResponse:function(e,t){return{status:t.status,data:t.data}}},Ce={getOperation:function(){return U.PNSetChannelMetadataOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.data)?void 0:"Data cannot be empty":"Channel cannot be empty"},usePatch:function(){return!0},patchURL:function(e,t){var n=e.config;return"/v2/objects/".concat(n.subscribeKey,"/channels/").concat(j.encodeString(t.channel))},patchPayload:function(e,t){return t.data},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r={include:["status","type","custom"]};return(null==t?void 0:t.include)&&!1===(null===(n=t.include)||void 0===n?void 0:n.customFields)&&r.include.pop(),r.include=r.include.join(","),r},handleResponse:function(e,t){return{status:t.status,data:t.data}}},ke={getOperation:function(){return U.PNRemoveChannelMetadataOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channel))return"Channel cannot be empty"},getURL:function(e,t){var n=e.config;return"/v2/objects/".concat(n.subscribeKey,"/channels/").concat(j.encodeString(t.channel))},useDelete:function(){return!0},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{status:t.status,data:t.data}}},Ne={getOperation:function(){return U.PNGetMembersOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channel))return"channel cannot be empty"},getURL:function(e,t){var n=e.config;return"/v2/objects/".concat(n.subscribeKey,"/channels/").concat(j.encodeString(t.channel),"/uuids")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o,i,a,u,c,l,p,h,f,d,y,g,m={include:[]};return(null==t?void 0:t.include)&&((null===(n=t.include)||void 0===n?void 0:n.statusField)&&m.include.push("status"),(null===(r=t.include)||void 0===r?void 0:r.customFields)&&m.include.push("custom"),(null===(o=t.include)||void 0===o?void 0:o.UUIDFields)&&m.include.push("uuid"),(null===(i=t.include)||void 0===i?void 0:i.customUUIDFields)&&m.include.push("uuid.custom"),(null===(a=t.include)||void 0===a?void 0:a.UUIDStatusField)&&m.include.push("uuid.status"),(null===(u=t.include)||void 0===u?void 0:u.UUIDTypeField)&&m.include.push("uuid.type")),m.include=m.include.join(","),(null===(c=null==t?void 0:t.include)||void 0===c?void 0:c.totalCount)&&(m.count=null===(l=t.include)||void 0===l?void 0:l.totalCount),(null===(p=null==t?void 0:t.page)||void 0===p?void 0:p.next)&&(m.start=null===(h=t.page)||void 0===h?void 0:h.next),(null===(f=null==t?void 0:t.page)||void 0===f?void 0:f.prev)&&(m.end=null===(d=t.page)||void 0===d?void 0:d.prev),(null==t?void 0:t.filter)&&(m.filter=t.filter),m.limit=null!==(y=null==t?void 0:t.limit)&&void 0!==y?y:100,(null==t?void 0:t.sort)&&(m.sort=Object.entries(null!==(g=t.sort)&&void 0!==g?g:{}).map((function(e){var t=s(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),m},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,prev:t.prev,next:t.next}}},Me={getOperation:function(){return U.PNSetMembersOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.uuids)&&0!==(null==t?void 0:t.uuids.length)?void 0:"UUIDs cannot be empty":"Channel cannot be empty"},usePatch:function(){return!0},patchURL:function(e,t){var n=e.config;return"/v2/objects/".concat(n.subscribeKey,"/channels/").concat(j.encodeString(t.channel),"/uuids")},patchPayload:function(e,t){var n;return(n={set:[],delete:[]})[t.type]=t.uuids.map((function(e){return"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},custom:e.custom,status:e.status}})),n},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o,i,a,u,c,l,p,h={include:["uuid.status","uuid.type","type"]};return(null==t?void 0:t.include)&&((null===(n=t.include)||void 0===n?void 0:n.customFields)&&h.include.push("custom"),(null===(r=t.include)||void 0===r?void 0:r.customUUIDFields)&&h.include.push("uuid.custom"),(null===(o=t.include)||void 0===o?void 0:o.UUIDFields)&&h.include.push("uuid")),h.include=h.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(h.count=!0),(null===(a=null==t?void 0:t.page)||void 0===a?void 0:a.next)&&(h.start=null===(u=t.page)||void 0===u?void 0:u.next),(null===(c=null==t?void 0:t.page)||void 0===c?void 0:c.prev)&&(h.end=null===(l=t.page)||void 0===l?void 0:l.prev),(null==t?void 0:t.filter)&&(h.filter=t.filter),null!=t.limit&&(h.limit=t.limit),(null==t?void 0:t.sort)&&(h.sort=Object.entries(null!==(p=t.sort)&&void 0!==p?p:{}).map((function(e){var t=s(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),h},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,prev:t.prev,next:t.next}}},je={getOperation:function(){return U.PNGetMembershipsOperation},validateParams:function(){},getURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(j.encodeString(null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:r.getUUID()),"/channels")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o,i,a,u,c,l,p,h,f,d,y,g,m={include:[]};return(null==t?void 0:t.include)&&((null===(n=t.include)||void 0===n?void 0:n.statusField)&&m.include.push("status"),(null===(r=t.include)||void 0===r?void 0:r.customFields)&&m.include.push("custom"),(null===(o=t.include)||void 0===o?void 0:o.channelFields)&&m.include.push("channel"),(null===(i=t.include)||void 0===i?void 0:i.customChannelFields)&&m.include.push("channel.custom"),(null===(a=t.include)||void 0===a?void 0:a.channelStatusField)&&m.include.push("channel.status"),(null===(u=t.include)||void 0===u?void 0:u.channelTypeField)&&m.include.push("channel.type")),m.include=m.include.join(","),(null===(c=null==t?void 0:t.include)||void 0===c?void 0:c.totalCount)&&(m.count=null===(l=t.include)||void 0===l?void 0:l.totalCount),(null===(p=null==t?void 0:t.page)||void 0===p?void 0:p.next)&&(m.start=null===(h=t.page)||void 0===h?void 0:h.next),(null===(f=null==t?void 0:t.page)||void 0===f?void 0:f.prev)&&(m.end=null===(d=t.page)||void 0===d?void 0:d.prev),(null==t?void 0:t.filter)&&(m.filter=t.filter),m.limit=null!==(y=null==t?void 0:t.limit)&&void 0!==y?y:100,(null==t?void 0:t.sort)&&(m.sort=Object.entries(null!==(g=t.sort)&&void 0!==g?g:{}).map((function(e){var t=s(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),m},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,prev:t.prev,next:t.next}}},Re={getOperation:function(){return U.PNSetMembershipsOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channels)||0===(null==t?void 0:t.channels.length))return"Channels cannot be empty"},usePatch:function(){return!0},patchURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(j.encodeString(null!==(n=t.uuid)&&void 0!==n?n:r.getUUID()),"/channels")},patchPayload:function(e,t){var n;return(n={set:[],delete:[]})[t.type]=t.channels.map((function(e){return"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},custom:e.custom,status:e.status}})),n},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o,i,a,u,c,l,p,h={include:["channel.status","channel.type","status"]};return(null==t?void 0:t.include)&&((null===(n=t.include)||void 0===n?void 0:n.customFields)&&h.include.push("custom"),(null===(r=t.include)||void 0===r?void 0:r.customChannelFields)&&h.include.push("channel.custom"),(null===(o=t.include)||void 0===o?void 0:o.channelFields)&&h.include.push("channel")),h.include=h.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(h.count=!0),(null===(a=null==t?void 0:t.page)||void 0===a?void 0:a.next)&&(h.start=null===(u=t.page)||void 0===u?void 0:u.next),(null===(c=null==t?void 0:t.page)||void 0===c?void 0:c.prev)&&(h.end=null===(l=t.page)||void 0===l?void 0:l.prev),(null==t?void 0:t.filter)&&(h.filter=t.filter),null!=t.limit&&(h.limit=t.limit),(null==t?void 0:t.sort)&&(h.sort=Object.entries(null!==(p=t.sort)&&void 0!==p?p:{}).map((function(e){var t=s(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),h},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,prev:t.prev,next:t.next}}};var xe=Object.freeze({__proto__:null,getOperation:function(){return U.PNAccessManagerAudit},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e){var t=e.config;return"/v2/auth/audit/sub-key/".concat(t.subscribeKey)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!1},prepareParams:function(e,t){var n=t.channel,r=t.channelGroup,o=t.authKeys,i=void 0===o?[]:o,a={};return n&&(a.channel=n),r&&(a["channel-group"]=r),i.length>0&&(a.auth=i.join(",")),a},handleResponse:function(e,t){return t.payload}});var Ue=Object.freeze({__proto__:null,getOperation:function(){return U.PNAccessManagerGrant},validateParams:function(e,t){var n=e.config;return n.subscribeKey?n.publishKey?n.secretKey?null==t.uuids||t.authKeys?null==t.uuids||null==t.channels&&null==t.channelGroups?void 0:"Both channel/channelgroup and uuid cannot be used in the same request":"authKeys are required for grant request on uuids":"Missing Secret Key":"Missing Publish Key":"Missing Subscribe Key"},getURL:function(e){var t=e.config;return"/v2/auth/grant/sub-key/".concat(t.subscribeKey)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!1},prepareParams:function(e,t){var n=t.channels,r=void 0===n?[]:n,o=t.channelGroups,i=void 0===o?[]:o,a=t.uuids,s=void 0===a?[]:a,u=t.ttl,c=t.read,l=void 0!==c&&c,p=t.write,h=void 0!==p&&p,f=t.manage,d=void 0!==f&&f,y=t.get,g=void 0!==y&&y,m=t.join,v=void 0!==m&&m,b=t.update,_=void 0!==b&&b,S=t.authKeys,w=void 0===S?[]:S,O=t.delete,P={};return P.r=l?"1":"0",P.w=h?"1":"0",P.m=d?"1":"0",P.d=O?"1":"0",P.g=g?"1":"0",P.j=v?"1":"0",P.u=_?"1":"0",r.length>0&&(P.channel=r.join(",")),i.length>0&&(P["channel-group"]=i.join(",")),w.length>0&&(P.auth=w.join(",")),s.length>0&&(P["target-uuid"]=s.join(",")),(u||0===u)&&(P.ttl=u),P},handleResponse:function(){return{}}});function Ie(e){var t,n,r,o,i=void 0!==(null==e?void 0:e.authorizedUserId),a=void 0!==(null===(t=null==e?void 0:e.resources)||void 0===t?void 0:t.users),s=void 0!==(null===(n=null==e?void 0:e.resources)||void 0===n?void 0:n.spaces),u=void 0!==(null===(r=null==e?void 0:e.patterns)||void 0===r?void 0:r.users),c=void 0!==(null===(o=null==e?void 0:e.patterns)||void 0===o?void 0:o.spaces);return u||a||c||s||i}function De(e){var t=0;return e.join&&(t|=128),e.update&&(t|=64),e.get&&(t|=32),e.delete&&(t|=8),e.manage&&(t|=4),e.write&&(t|=2),e.read&&(t|=1),t}function Fe(e,t){if(Ie(t))return function(e,t){var n=t.ttl,r=t.resources,o=t.patterns,i=t.meta,a=t.authorizedUserId,s={ttl:0,permissions:{resources:{channels:{},groups:{},uuids:{},users:{},spaces:{}},patterns:{channels:{},groups:{},uuids:{},users:{},spaces:{}},meta:{}}};if(r){var u=r.users,c=r.spaces,l=r.groups;u&&Object.keys(u).forEach((function(e){s.permissions.resources.uuids[e]=De(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=De(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=De(l[e])}))}if(o){var p=o.users,h=o.spaces,f=o.groups;p&&Object.keys(p).forEach((function(e){s.permissions.patterns.uuids[e]=De(p[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.channels[e]=De(h[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.groups[e]=De(f[e])}))}return(n||0===n)&&(s.ttl=n),i&&(s.permissions.meta=i),a&&(s.permissions.uuid="".concat(a)),s}(0,t);var n=t.ttl,r=t.resources,o=t.patterns,i=t.meta,a=t.authorized_uuid,s={ttl:0,permissions:{resources:{channels:{},groups:{},uuids:{},users:{},spaces:{}},patterns:{channels:{},groups:{},uuids:{},users:{},spaces:{}},meta:{}}};if(r){var u=r.uuids,c=r.channels,l=r.groups;u&&Object.keys(u).forEach((function(e){s.permissions.resources.uuids[e]=De(u[e])})),c&&Object.keys(c).forEach((function(e){s.permissions.resources.channels[e]=De(c[e])})),l&&Object.keys(l).forEach((function(e){s.permissions.resources.groups[e]=De(l[e])}))}if(o){var p=o.uuids,h=o.channels,f=o.groups;p&&Object.keys(p).forEach((function(e){s.permissions.patterns.uuids[e]=De(p[e])})),h&&Object.keys(h).forEach((function(e){s.permissions.patterns.channels[e]=De(h[e])})),f&&Object.keys(f).forEach((function(e){s.permissions.patterns.groups[e]=De(f[e])}))}return(n||0===n)&&(s.ttl=n),i&&(s.permissions.meta=i),a&&(s.permissions.uuid="".concat(a)),s}var Ge=Object.freeze({__proto__:null,getOperation:function(){return U.PNAccessManagerGrantToken},extractPermissions:De,validateParams:function(e,t){var n,r,o,i,a,s,u=e.config;if(!u.subscribeKey)return"Missing Subscribe Key";if(!u.publishKey)return"Missing Publish Key";if(!u.secretKey)return"Missing Secret Key";if(!t.resources&&!t.patterns)return"Missing either Resources or Patterns.";var c=void 0!==(null==t?void 0:t.authorized_uuid),l=void 0!==(null===(n=null==t?void 0:t.resources)||void 0===n?void 0:n.uuids),p=void 0!==(null===(r=null==t?void 0:t.resources)||void 0===r?void 0:r.channels),h=void 0!==(null===(o=null==t?void 0:t.resources)||void 0===o?void 0:o.groups),f=void 0!==(null===(i=null==t?void 0:t.patterns)||void 0===i?void 0:i.uuids),d=void 0!==(null===(a=null==t?void 0:t.patterns)||void 0===a?void 0:a.channels),y=void 0!==(null===(s=null==t?void 0:t.patterns)||void 0===s?void 0:s.groups),g=c||l||f||p||d||h||y;return Ie(t)&&g?"Cannot mix `users`, `spaces` and `authorizedUserId` with `uuids`, `channels`, `groups` and `authorized_uuid`":(!t.resources||t.resources.uuids&&0!==Object.keys(t.resources.uuids).length||t.resources.channels&&0!==Object.keys(t.resources.channels).length||t.resources.groups&&0!==Object.keys(t.resources.groups).length||t.resources.users&&0!==Object.keys(t.resources.users).length||t.resources.spaces&&0!==Object.keys(t.resources.spaces).length)&&(!t.patterns||t.patterns.uuids&&0!==Object.keys(t.patterns.uuids).length||t.patterns.channels&&0!==Object.keys(t.patterns.channels).length||t.patterns.groups&&0!==Object.keys(t.patterns.groups).length||t.patterns.users&&0!==Object.keys(t.patterns.users).length||t.patterns.spaces&&0!==Object.keys(t.patterns.spaces).length)?void 0:"Missing values for either Resources or Patterns."},postURL:function(e){var t=e.config;return"/v3/pam/".concat(t.subscribeKey,"/grant")},usePost:function(){return!0},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!1},prepareParams:function(){return{}},postPayload:function(e,t){return Fe(0,t)},handleResponse:function(e,t){return t.data.token}}),Le={getOperation:function(){return U.PNAccessManagerRevokeToken},validateParams:function(e,t){return e.config.secretKey?t?void 0:"token can't be empty":"Missing Secret Key"},getURL:function(e,t){var n=e.config;return"/v3/pam/".concat(n.subscribeKey,"/grant/").concat(j.encodeString(t))},useDelete:function(){return!0},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!1},prepareParams:function(e){return{uuid:e.config.getUUID()}},handleResponse:function(e,t){return{status:t.status,data:t.data}}};function Ke(e,t){var n=JSON.stringify(t);if(e.cryptoModule){var r=e.cryptoModule.encrypt(n);n="string"==typeof r?r:v(r),n=JSON.stringify(n)}return n||""}var Be=Object.freeze({__proto__:null,getOperation:function(){return U.PNPublishOperation},validateParams:function(e,t){var n=e.config,r=t.message;return t.channel?r?n.subscribeKey?void 0:"Missing Subscribe Key":"Missing Message":"Missing Channel"},usePost:function(e,t){var n=t.sendByPost;return void 0!==n&&n},getURL:function(e,t){var n=e.config,r=t.channel,o=Ke(e,t.message);return"/publish/".concat(n.publishKey,"/").concat(n.subscribeKey,"/0/").concat(j.encodeString(r),"/0/").concat(j.encodeString(o))},postURL:function(e,t){var n=e.config,r=t.channel;return"/publish/".concat(n.publishKey,"/").concat(n.subscribeKey,"/0/").concat(j.encodeString(r),"/0")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},postPayload:function(e,t){return Ke(e,t.message)},prepareParams:function(e,t){var n=t.meta,r=t.replicate,o=void 0===r||r,i=t.storeInHistory,a=t.ttl,s={};return null!=i&&(s.store=i?"1":"0"),a&&(s.ttl=a),!1===o&&(s.norep="true"),n&&"object"==typeof n&&(s.meta=JSON.stringify(n)),s},handleResponse:function(e,t){return{timetoken:t[2]}}});var He=Object.freeze({__proto__:null,getOperation:function(){return U.PNSignalOperation},validateParams:function(e,t){var n=e.config,r=t.message;return t.channel?r?n.subscribeKey?void 0:"Missing Subscribe Key":"Missing Message":"Missing Channel"},getURL:function(e,t){var n,r=e.config,o=t.channel,i=t.message,a=(n=i,JSON.stringify(n));return"/signal/".concat(r.publishKey,"/").concat(r.subscribeKey,"/0/").concat(j.encodeString(o),"/0/").concat(j.encodeString(a))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{timetoken:t[2]}}});var qe=Object.freeze({__proto__:null,getOperation:function(){return U.PNHistoryOperation},validateParams:function(e,t){var n=t.channel,r=e.config;return n?r.subscribeKey?void 0:"Missing Subscribe Key":"Missing channel"},getURL:function(e,t){var n=t.channel,r=e.config;return"/v2/history/sub-key/".concat(r.subscribeKey,"/channel/").concat(j.encodeString(n))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.start,r=t.end,o=t.reverse,i=t.count,a=void 0===i?100:i,s=t.stringifiedTimeToken,u=void 0!==s&&s,c=t.includeMeta,l=void 0!==c&&c,p={include_token:"true"};return p.count=a,n&&(p.start=n),r&&(p.end=r),u&&(p.string_message_token="true"),null!=o&&(p.reverse=o.toString()),l&&(p.include_meta="true"),p},handleResponse:function(e,t){var n={messages:[],startTimeToken:t[1],endTimeToken:t[2]};return Array.isArray(t[0])&&t[0].forEach((function(t){var r=function(e,t){var n={};if(!e.cryptoModule)return n.payload=t,n;try{var r=e.cryptoModule.decrypt(t),o=r instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(r)):r;return n.payload=o,n}catch(r){e.config.logVerbosity&&console&&console.log&&console.log("decryption error",r.message),n.payload=t,n.error="Error while decrypting message content: ".concat(r.message)}return n}(e,t.message),o={timetoken:t.timetoken,entry:r.payload};t.meta&&(o.meta=t.meta),r.error&&(o.error=r.error),n.messages.push(o)})),n}});var ze=Object.freeze({__proto__:null,getOperation:function(){return U.PNDeleteMessagesOperation},validateParams:function(e,t){var n=t.channel,r=e.config;return n?r.subscribeKey?void 0:"Missing Subscribe Key":"Missing channel"},useDelete:function(){return!0},getURL:function(e,t){var n=t.channel,r=e.config;return"/v3/history/sub-key/".concat(r.subscribeKey,"/channel/").concat(j.encodeString(n))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.start,r=t.end,o={};return n&&(o.start=n),r&&(o.end=r),o},handleResponse:function(e,t){return t.payload}});var Ve=Object.freeze({__proto__:null,getOperation:function(){return U.PNMessageCounts},validateParams:function(e,t){var n=t.channels,r=t.timetoken,o=t.channelTimetokens,i=e.config;return n?r&&o?"timetoken and channelTimetokens are incompatible together":o&&o.length>1&&n.length!==o.length?"Length of channelTimetokens and channels do not match":i.subscribeKey?void 0:"Missing Subscribe Key":"Missing channel"},getURL:function(e,t){var n=t.channels,r=e.config,o=n.join(",");return"/v3/history/sub-key/".concat(r.subscribeKey,"/message-counts/").concat(j.encodeString(o))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.timetoken,r=t.channelTimetokens,o={};if(r&&1===r.length){var i=s(r,1)[0];o.timetoken=i}else r?o.channelsTimetoken=r.join(","):n&&(o.timetoken=n);return o},handleResponse:function(e,t){return{channels:t.channels}}});var We=Object.freeze({__proto__:null,getOperation:function(){return U.PNFetchMessagesOperation},validateParams:function(e,t){var n=t.channels,r=t.includeMessageActions,o=void 0!==r&&r,i=e.config;if(!n||0===n.length)return"Missing channels";if(!i.subscribeKey)return"Missing Subscribe Key";if(o&&n.length>1)throw new TypeError("History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.")},getURL:function(e,t){var n=t.channels,r=void 0===n?[]:n,o=t.includeMessageActions,i=void 0!==o&&o,a=e.config,s=i?"history-with-actions":"history",u=r.length>0?r.join(","):",";return"/v3/".concat(s,"/sub-key/").concat(a.subscribeKey,"/channel/").concat(j.encodeString(u))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.channels,r=t.start,o=t.end,i=t.includeMessageActions,a=t.count,s=t.stringifiedTimeToken,u=void 0!==s&&s,c=t.includeMeta,l=void 0!==c&&c,p=t.includeUuid,h=t.includeUUID,f=void 0===h||h,d=t.includeMessageType,y=void 0===d||d,g={};return g.max=a||(n.length>1||!0===i?25:100),r&&(g.start=r),o&&(g.end=o),u&&(g.string_message_token="true"),l&&(g.include_meta="true"),f&&!1!==p&&(g.include_uuid="true"),y&&(g.include_message_type="true"),g},handleResponse:function(e,t){var n={channels:{}};return Object.keys(t.channels||{}).forEach((function(r){n.channels[r]=[],(t.channels[r]||[]).forEach((function(t){var o={},i=function(e,t){var n={};if(!e.cryptoModule)return n.payload=t,n;try{var r=e.cryptoModule.decrypt(t),o=r instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(r)):r;return n.payload=o,n}catch(r){e.config.logVerbosity&&console&&console.log&&console.log("decryption error",r.message),n.payload=t,n.error="Error while decrypting message content: ".concat(r.message)}return n}(e,t.message);o.channel=r,o.timetoken=t.timetoken,o.message=i.payload,o.messageType=t.message_type,o.uuid=t.uuid,t.actions&&(o.actions=t.actions,o.data=t.actions),t.meta&&(o.meta=t.meta),i.error&&(o.error=i.error),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var Je=Object.freeze({__proto__:null,getOperation:function(){return U.PNTimeOperation},getURL:function(){return"/time/0"},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},prepareParams:function(){return{}},isAuthSupported:function(){return!1},handleResponse:function(e,t){return{timetoken:t[0]}},validateParams:function(){}});var $e=Object.freeze({__proto__:null,getOperation:function(){return U.PNSubscribeOperation},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.channels,o=void 0===r?[]:r,i=o.length>0?o.join(","):",";return"/v2/subscribe/".concat(n.subscribeKey,"/").concat(j.encodeString(i),"/0")},getRequestTimeout:function(e){return e.config.getSubscribeTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=e.config,r=t.state,o=t.channelGroups,i=void 0===o?[]:o,a=t.timetoken,s=t.filterExpression,u=t.region,c={heartbeat:n.getPresenceTimeout()};return i.length>0&&(c["channel-group"]=i.join(",")),s&&s.length>0&&(c["filter-expr"]=s),Object.keys(r).length&&(c.state=JSON.stringify(r)),a&&(c.tt=a),u&&(c.tr=u),c},handleResponse:function(e,t){var n=[];t.m.forEach((function(e){var t={publishTimetoken:e.p.t,region:e.p.r},r={shard:parseInt(e.a,10),subscriptionMatch:e.b,channel:e.c,messageType:e.e,payload:e.d,flags:e.f,issuingClientId:e.i,subscribeKey:e.k,originationTimetoken:e.o,userMetadata:e.u,publishMetaData:t};n.push(r)}));var r={timetoken:t.t.t,region:t.t.r};return{messages:n,metadata:r}}}),Qe={getOperation:function(){return U.PNHandshakeOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channels)&&!(null==t?void 0:t.channelGroups))return"channels and channleGroups both should not be empty"},getURL:function(e,t){var n=e.config,r=t.channels?t.channels.join(","):",";return"/v2/subscribe/".concat(n.subscribeKey,"/").concat(j.encodeString(r),"/0")},getRequestTimeout:function(e){return e.config.getSubscribeTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n={};return t.channelGroups&&t.channelGroups.length>0&&(n["channel-group"]=t.channelGroups.join(",")),n.tt=0,t.state&&(n.state=JSON.stringify(t.state)),t.filterExpression&&t.filterExpression.length>0&&(n["filter-expr"]=t.filterExpression),n.ee="",n},handleResponse:function(e,t){return{region:t.t.r,timetoken:t.t.t}}},Xe={getOperation:function(){return U.PNReceiveMessagesOperation},validateParams:function(e,t){return(null==t?void 0:t.channels)||(null==t?void 0:t.channelGroups)?(null==t?void 0:t.timetoken)?(null==t?void 0:t.region)?void 0:"region can not be empty":"timetoken can not be empty":"channels and channleGroups both should not be empty"},getURL:function(e,t){var n=e.config,r=t.channels?t.channels.join(","):",";return"/v2/subscribe/".concat(n.subscribeKey,"/").concat(j.encodeString(r),"/0")},getRequestTimeout:function(e){return e.config.getSubscribeTimeout()},isAuthSupported:function(){return!0},getAbortSignal:function(e,t){return t.abortSignal},prepareParams:function(e,t){var n={};return t.channelGroups&&t.channelGroups.length>0&&(n["channel-group"]=t.channelGroups.join(",")),t.filterExpression&&t.filterExpression.length>0&&(n["filter-expr"]=t.filterExpression),n.tt=t.timetoken,n.tr=t.region,n.ee="",n},handleResponse:function(e,t){var n=[];return t.m.forEach((function(e){var t={shard:parseInt(e.a,10),subscriptionMatch:e.b,channel:e.c,messageType:e.e,payload:e.d,flags:e.f,issuingClientId:e.i,subscribeKey:e.k,originationTimetoken:e.o,publishMetaData:{timetoken:e.p.t,region:e.p.r}};n.push(t)})),{messages:n,metadata:{region:t.t.r,timetoken:t.t.t}}}},Ye=function(){function e(e){void 0===e&&(e=!1),this.sync=e,this.listeners=new Set}return e.prototype.subscribe=function(e){var t=this;return this.listeners.add(e),function(){t.listeners.delete(e)}},e.prototype.notify=function(e){var t=this,n=function(){t.listeners.forEach((function(t){t(e)}))};this.sync?n():setTimeout(n,0)},e}(),Ze=function(){function e(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}return e.prototype.transition=function(e,t){var n;if(this.transitionMap.has(t.type))return null===(n=this.transitionMap.get(t.type))||void 0===n?void 0:n(e,t)},e.prototype.on=function(e,t){return this.transitionMap.set(e,t),this},e.prototype.with=function(e,t){return[this,e,null!=t?t:[]]},e.prototype.onEnter=function(e){return this.enterEffects.push(e),this},e.prototype.onExit=function(e){return this.exitEffects.push(e),this},e}(),et=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new Ze(e)},n.prototype.start=function(e,t){this.currentState=e,this.currentContext=t,this.notify({type:"engineStarted",state:e,context:t})},n.prototype.transition=function(e){var t,n,r,o,i,u;if(!this.currentState)throw new Error("Start the engine first");this.notify({type:"eventReceived",event:e});var c=this.currentState.transition(this.currentContext,e);if(c){var l=s(c,3),p=l[0],h=l[1],f=l[2];try{for(var d=a(this.currentState.exitEffects),y=d.next();!y.done;y=d.next()){var g=y.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){t={error:e}}finally{try{y&&!y.done&&(n=d.return)&&n.call(d)}finally{if(t)throw t.error}}var m=this.currentState;this.currentState=p;var v=this.currentContext;this.currentContext=h,this.notify({type:"transitionDone",fromState:m,fromContext:v,toState:p,toContext:h,event:e});try{for(var b=a(f),_=b.next();!_.done;_=b.next()){g=_.value;this.notify({type:"invocationDispatched",invocation:g})}}catch(e){r={error:e}}finally{try{_&&!_.done&&(o=b.return)&&o.call(b)}finally{if(r)throw r.error}}try{for(var S=a(this.currentState.enterEffects),w=S.next();!w.done;w=S.next()){g=w.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{w&&!w.done&&(u=S.return)&&u.call(S)}finally{if(i)throw i.error}}}},n}(Ye),tt=function(){function e(e){this.dependencies=e,this.instances=new Map,this.handlers=new Map}return e.prototype.on=function(e,t){this.handlers.set(e,t)},e.prototype.dispatch=function(e){if("CANCEL"!==e.type){var t=this.handlers.get(e.type);if(!t)throw new Error("Unhandled invocation '".concat(e.type,"'"));var n=t(e.payload,this.dependencies);e.managed&&this.instances.set(e.type,n),n.start()}else if(this.instances.has(e.payload)){var r=this.instances.get(e.payload);null==r||r.cancel(),this.instances.delete(e.payload)}},e.prototype.dispose=function(){var e,t;try{for(var n=a(this.instances.entries()),r=n.next();!r.done;r=n.next()){var o=s(r.value,2),i=o[0];o[1].cancel(),this.instances.delete(i)}}catch(t){e={error:t}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}},e}();function nt(e,t){var n=function(){for(var n=[],r=0;r0&&r(e),[2]}))}))}))),a.on(ht.type,ut((function(e,t,n){var r=n.emitStatus;return o(a,void 0,void 0,(function(){return i(this,(function(t){return r(e),[2]}))}))}))),a.on(ft.type,ut((function(e,n,r){var s=r.receiveMessages,u=r.delay,c=r.config;return o(a,void 0,void 0,(function(){var r,o;return i(this,(function(i){switch(i.label){case 0:return c.retryConfiguration&&c.retryConfiguration.shouldRetry(e.reason,e.attempts)?(n.throwIfAborted(),[4,u(c.retryConfiguration.getDelay(e.attempts,e.reason))]):[3,6];case 1:i.sent(),n.throwIfAborted(),i.label=2;case 2:return i.trys.push([2,4,,5]),[4,s({abortSignal:n,channels:e.channels,channelGroups:e.groups,timetoken:e.cursor.timetoken,region:e.cursor.region,filterExpression:c.filterExpression})];case 3:return r=i.sent(),[2,t.transition(Pt(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(Et(o))]:[3,5];case 5:return[3,7];case 6:return[2,t.transition(Tt(new q(c.retryConfiguration.getGiveupReason(e.reason,e.attempts))))];case 7:return[2]}}))}))}))),a.on(dt.type,ut((function(e,r,s){var u=s.handshake,c=s.delay,l=s.presenceState,p=s.config;return o(a,void 0,void 0,(function(){var o,a;return i(this,(function(i){switch(i.label){case 0:return p.retryConfiguration&&p.retryConfiguration.shouldRetry(e.reason,e.attempts)?(r.throwIfAborted(),[4,c(p.retryConfiguration.getDelay(e.attempts,e.reason))]):[3,6];case 1:i.sent(),r.throwIfAborted(),i.label=2;case 2:return i.trys.push([2,4,,5]),[4,u(n({abortSignal:r,channels:e.channels,channelGroups:e.groups,filterExpression:p.filterExpression},p.maintainPresenceState&&{state:l}))];case 3:return o=i.sent(),[2,t.transition(bt(o))];case 4:return(a=i.sent())instanceof Error&&"Aborted"===a.message?[2]:a instanceof q?[2,t.transition(_t(a))]:[3,5];case 5:return[3,7];case 6:return[2,t.transition(St(new q(p.retryConfiguration.getGiveupReason(e.reason,e.attempts))))];case 7:return[2]}}))}))}))),a}return t(r,e),r}(tt),Mt=new Ze("HANDSHAKE_FAILED");Mt.on(yt.type,(function(e,t){return Ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),Mt.on(Ct.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor||e.cursor})})),Mt.on(gt.type,(function(e,t){var n,r;return Ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region?t.payload.cursor.region:null!==(r=null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)&&void 0!==r?r:0}})})),Mt.on(kt.type,(function(e){return Gt.with()}));var jt=new Ze("HANDSHAKE_STOPPED");jt.on(yt.type,(function(e,t){return jt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),jt.on(Ct.type,(function(e,t){return Ft.with(n(n({},e),{cursor:t.payload.cursor||e.cursor}))})),jt.on(gt.type,(function(e,t){var n;return jt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)||0}})})),jt.on(kt.type,(function(e){return Gt.with()}));var Rt=new Ze("RECEIVE_FAILED");Rt.on(Ct.type,(function(e,t){var n;return Ft.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(n=t.payload.cursor)||void 0===n?void 0:n.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),Rt.on(yt.type,(function(e,t){return Ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),Rt.on(gt.type,(function(e,t){return Ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),Rt.on(kt.type,(function(e){return Gt.with(void 0)}));var xt=new Ze("RECEIVE_STOPPED");xt.on(yt.type,(function(e,t){return xt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),xt.on(gt.type,(function(e,t){return xt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),xt.on(Ct.type,(function(e,t){var n;return Ft.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(n=t.payload.cursor)||void 0===n?void 0:n.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),xt.on(kt.type,(function(){return Gt.with(void 0)}));var Ut=new Ze("RECEIVE_RECONNECTING");Ut.onEnter((function(e){return ft(e)})),Ut.onExit((function(){return ft.cancel})),Ut.on(Pt.type,(function(e,t){return It.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[pt(t.payload.events)])})),Ut.on(Et.type,(function(e,t){return Ut.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Ut.on(Tt.type,(function(e,t){var n;return Rt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[ht({category:R.PNDisconnectedUnexpectedlyCategory,error:null===(n=t.payload)||void 0===n?void 0:n.message})])})),Ut.on(At.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[ht({category:R.PNDisconnectedCategory})])})),Ut.on(gt.type,(function(e,t){return It.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),Ut.on(yt.type,(function(e,t){return It.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),Ut.on(kt.type,(function(e){return Gt.with(void 0,[ht({category:R.PNDisconnectedCategory})])}));var It=new Ze("RECEIVING");It.onEnter((function(e){return lt(e.channels,e.groups,e.cursor)})),It.onExit((function(){return lt.cancel})),It.on(wt.type,(function(e,t){return It.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[pt(t.payload.events)])})),It.on(yt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Gt.with(void 0):It.with({cursor:e.cursor,channels:t.payload.channels,groups:t.payload.groups})})),It.on(gt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Gt.with(void 0):It.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),It.on(Ot.type,(function(e,t){return Ut.with(n(n({},e),{attempts:0,reason:t.payload}))})),It.on(At.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[ht({category:R.PNDisconnectedCategory})])})),It.on(kt.type,(function(e){return Gt.with(void 0,[ht({category:R.PNDisconnectedCategory})])}));var Dt=new Ze("HANDSHAKE_RECONNECTING");Dt.onEnter((function(e){return dt(e)})),Dt.onExit((function(){return dt.cancel})),Dt.on(bt.type,(function(e,t){var n,r,o={timetoken:(null===(n=e.cursor)||void 0===n?void 0:n.timetoken)?null===(r=e.cursor)||void 0===r?void 0:r.timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region};return It.with({channels:e.channels,groups:e.groups,cursor:o},[ht({category:R.PNConnectedCategory})])})),Dt.on(_t.type,(function(e,t){return Dt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Dt.on(St.type,(function(e,t){var n;return Mt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[ht({category:R.PNConnectionErrorCategory,error:null===(n=t.payload)||void 0===n?void 0:n.message})])})),Dt.on(At.type,(function(e){return jt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})})),Dt.on(yt.type,(function(e,t){return Ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),Dt.on(gt.type,(function(e,t){var n,r;return Ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:(null===(n=t.payload.cursor)||void 0===n?void 0:n.region)||(null===(r=null==e?void 0:e.cursor)||void 0===r?void 0:r.region)||0}})})),Dt.on(kt.type,(function(e){return Gt.with(void 0)}));var Ft=new Ze("HANDSHAKING");Ft.onEnter((function(e){return ct(e.channels,e.groups)})),Ft.onExit((function(){return ct.cancel})),Ft.on(yt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Gt.with(void 0):Ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),Ft.on(mt.type,(function(e,t){var n,r;return It.with({channels:e.channels,groups:e.groups,cursor:{timetoken:(null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.timetoken)?null===(r=null==e?void 0:e.cursor)||void 0===r?void 0:r.timetoken:t.payload.timetoken,region:t.payload.region}},[ht({category:R.PNConnectedCategory})])})),Ft.on(vt.type,(function(e,t){return Dt.with({channels:e.channels,groups:e.groups,cursor:e.cursor,attempts:0,reason:t.payload})})),Ft.on(At.type,(function(e){return jt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})})),Ft.on(gt.type,(function(e,t){var n;return Ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)||0}})})),Ft.on(kt.type,(function(e){return Gt.with()}));var Gt=new Ze("UNSUBSCRIBED");Gt.on(yt.type,(function(e,t){return Ft.with({channels:t.payload.channels,groups:t.payload.groups})})),Gt.on(gt.type,(function(e,t){return Ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:t.payload.cursor})}));var Lt=function(){function e(e){var t=this;this.engine=new et,this.channels=[],this.groups=[],this.dependencies=e,this.dispatcher=new Nt(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((function(e){"invocationDispatched"===e.type&&t.dispatcher.dispatch(e.invocation)})),this.engine.start(Gt,void 0)}return Object.defineProperty(e.prototype,"_engine",{get:function(){return this.engine},enumerable:!1,configurable:!0}),e.prototype.subscribe=function(e){var t=this,n=e.channels,r=e.channelGroups,o=e.timetoken,i=e.withPresence;this.channels=u(u([],s(this.channels),!1),s(null!=n?n:[]),!1),this.groups=u(u([],s(this.groups),!1),s(null!=r?r:[]),!1),i&&(this.channels.map((function(e){return t.channels.push("".concat(e,"-pnpres"))})),this.groups.map((function(e){return t.groups.push("".concat(e,"-pnpres"))}))),o?this.engine.transition(gt(this.channels,this.groups,o)):this.engine.transition(yt(this.channels,this.groups)),this.dependencies.join&&this.dependencies.join({channels:this.channels.filter((function(e){return!e.endsWith("-pnpres")})),groups:this.groups.filter((function(e){return!e.endsWith("-pnpres")}))})},e.prototype.unsubscribe=function(e){var t=this,n=e.channels,r=e.groups,o=null==n?void 0:n.slice(0);null==n||n.map((function(e){return o.push("".concat(e,"-pnpres"))})),this.channels=this.channels.filter((function(e){return!(null==o?void 0:o.includes(e))}));var i=null==r?void 0:r.slice(0);null==r||r.map((function(e){return i.push("".concat(e,"-pnpres"))})),this.groups=this.groups.filter((function(e){return!(null==i?void 0:i.includes(e))})),this.dependencies.presenceState&&(null==n||n.forEach((function(e){return delete t.dependencies.presenceState[e]})),null==r||r.forEach((function(e){return delete t.dependencies.presenceState[e]}))),this.engine.transition(yt(this.channels.slice(0),this.groups.slice(0))),this.dependencies.leave&&this.dependencies.leave({channels:n,groups:r})},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.dependencies.presenceState&&(this.dependencies.presenceState={}),this.engine.transition(yt(this.channels.slice(0),this.groups.slice(0))),this.dependencies.leaveAll&&this.dependencies.leaveAll()},e.prototype.reconnect=function(e){var t=e.timetoken,n=e.region;this.engine.transition(Ct(t,n))},e.prototype.disconnect=function(){this.engine.transition(At()),this.dependencies.leaveAll&&this.dependencies.leaveAll()},e.prototype.getSubscribedChannels=function(){return this.channels.slice(0)},e.prototype.getSubscribedChannelGroups=function(){return this.groups.slice(0)},e.prototype.dispose=function(){this.disconnect(),this._unsubscribeEngine(),this.dispatcher.dispose()},e}(),Kt=nt("RECONNECT",(function(){return{}})),Bt=nt("DISCONNECT",(function(){return{}})),Ht=nt("JOINED",(function(e,t){return{channels:e,groups:t}})),qt=nt("LEFT",(function(e,t){return{channels:e,groups:t}})),zt=nt("LEFT_ALL",(function(){return{}})),Vt=nt("HEARTBEAT_SUCCESS",(function(e){return{statusCode:e}})),Wt=nt("HEARTBEAT_FAILURE",(function(e){return e})),Jt=nt("HEARTBEAT_GIVEUP",(function(){return{}})),$t=nt("TIMES_UP",(function(){return{}})),Qt=rt("HEARTBEAT",(function(e,t){return{channels:e,groups:t}})),Xt=rt("LEAVE",(function(e,t){return{channels:e,groups:t}})),Yt=rt("EMIT_STATUS",(function(e){return e})),Zt=ot("WAIT",(function(){return{}})),en=ot("DELAYED_HEARTBEAT",(function(e){return e})),tn=function(e){function r(t,r){var a=e.call(this,r)||this;return a.on(Qt.type,ut((function(e,r,s){var u=s.heartbeat,c=s.presenceState,l=s.config;return o(a,void 0,void 0,(function(){var r;return i(this,(function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),[4,u(n({channels:e.channels,channelGroups:e.groups},l.maintainPresenceState&&{state:c}))];case 1:return o.sent(),t.transition(Vt(200)),[3,3];case 2:return(r=o.sent())instanceof q?[2,t.transition(Wt(r))]:[3,3];case 3:return[2]}}))}))}))),a.on(Xt.type,ut((function(e,t,n){var r=n.leave,s=n.config;return o(a,void 0,void 0,(function(){return i(this,(function(t){switch(t.label){case 0:if(s.suppressLeaveEvents)return[3,4];t.label=1;case 1:return t.trys.push([1,3,,4]),[4,r({channels:e.channels,channelGroups:e.groups})];case 2:case 3:return t.sent(),[3,4];case 4:return[2]}}))}))}))),a.on(Zt.type,ut((function(e,n,r){var s=r.heartbeatDelay;return o(a,void 0,void 0,(function(){return i(this,(function(e){switch(e.label){case 0:return n.throwIfAborted(),[4,s()];case 1:return e.sent(),n.throwIfAborted(),[2,t.transition($t())]}}))}))}))),a.on(en.type,ut((function(e,r,s){var u=s.heartbeat,c=s.retryDelay,l=s.presenceState,p=s.config;return o(a,void 0,void 0,(function(){var o;return i(this,(function(i){switch(i.label){case 0:return p.retryConfiguration&&p.retryConfiguration.shouldRetry(e.reason,e.attempts)?(r.throwIfAborted(),[4,c(p.retryConfiguration.getDelay(e.attempts,e.reason))]):[3,6];case 1:i.sent(),r.throwIfAborted(),i.label=2;case 2:return i.trys.push([2,4,,5]),[4,u(n({channels:e.channels,channelGroups:e.groups},p.maintainPresenceState&&{state:l}))];case 3:return i.sent(),[2,t.transition(Vt(200))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(Wt(o))]:[3,5];case 5:return[3,7];case 6:return[2,t.transition(Jt())];case 7:return[2]}}))}))}))),a.on(Yt.type,ut((function(e,t,r){var s=r.emitStatus,u=r.config;return o(a,void 0,void 0,(function(){var t;return i(this,(function(r){return u.announceFailedHeartbeats&&!0===(null===(t=null==e?void 0:e.status)||void 0===t?void 0:t.error)?s(e.status):u.announceSuccessfulHeartbeats&&200===e.statusCode&&s(n(n({},e),{operation:U.PNHeartbeatOperation,error:!1})),[2]}))}))}))),a}return t(r,e),r}(tt),nn=new Ze("HEARTBEAT_STOPPED");nn.on(Ht.type,(function(e,t){return nn.with({channels:u(u([],s(e.channels),!1),s(t.payload.channels),!1),groups:u(u([],s(e.groups),!1),s(t.payload.groups),!1)})})),nn.on(qt.type,(function(e,t){return nn.with({channels:e.channels.filter((function(e){return!t.payload.channels.includes(e)})),groups:e.groups.filter((function(e){return!t.payload.groups.includes(e)}))})})),nn.on(Kt.type,(function(e,t){return sn.with({channels:e.channels,groups:e.groups})})),nn.on(zt.type,(function(e,t){return un.with(void 0)}));var rn=new Ze("HEARTBEAT_COOLDOWN");rn.onEnter((function(){return Zt()})),rn.onExit((function(){return Zt.cancel})),rn.on($t.type,(function(e,t){return sn.with({channels:e.channels,groups:e.groups})})),rn.on(Ht.type,(function(e,t){return sn.with({channels:u(u([],s(e.channels),!1),s(t.payload.channels),!1),groups:u(u([],s(e.groups),!1),s(t.payload.groups),!1)})})),rn.on(qt.type,(function(e,t){return sn.with({channels:e.channels.filter((function(e){return!t.payload.channels.includes(e)})),groups:e.groups.filter((function(e){return!t.payload.groups.includes(e)}))},[Xt(t.payload.channels,t.payload.groups)])})),rn.on(Bt.type,(function(e){return nn.with({channels:e.channels,groups:e.groups},[Xt(e.channels,e.groups)])})),rn.on(zt.type,(function(e,t){return un.with(void 0,[Xt(e.channels,e.groups)])}));var on=new Ze("HEARTBEAT_FAILED");on.on(Ht.type,(function(e,t){return sn.with({channels:u(u([],s(e.channels),!1),s(t.payload.channels),!1),groups:u(u([],s(e.groups),!1),s(t.payload.groups),!1)})})),on.on(qt.type,(function(e,t){return sn.with({channels:e.channels.filter((function(e){return!t.payload.channels.includes(e)})),groups:e.groups.filter((function(e){return!t.payload.groups.includes(e)}))},[Xt(t.payload.channels,t.payload.groups)])})),on.on(Kt.type,(function(e,t){return sn.with({channels:e.channels,groups:e.groups})})),on.on(Bt.type,(function(e,t){return nn.with({channels:e.channels,groups:e.groups},[Xt(e.channels,e.groups)])})),on.on(zt.type,(function(e,t){return un.with(void 0,[Xt(e.channels,e.groups)])}));var an=new Ze("HEARBEAT_RECONNECTING");an.onEnter((function(e){return en(e)})),an.onExit((function(){return en.cancel})),an.on(Ht.type,(function(e,t){return sn.with({channels:u(u([],s(e.channels),!1),s(t.payload.channels),!1),groups:u(u([],s(e.groups),!1),s(t.payload.groups),!1)})})),an.on(qt.type,(function(e,t){return sn.with({channels:e.channels.filter((function(e){return!t.payload.channels.includes(e)})),groups:e.groups.filter((function(e){return!t.payload.groups.includes(e)}))},[Xt(t.payload.channels,t.payload.groups)])})),an.on(Bt.type,(function(e,t){nn.with({channels:e.channels,groups:e.groups},[Xt(e.channels,e.groups)])})),an.on(Vt.type,(function(e,t){return rn.with({channels:e.channels,groups:e.groups})})),an.on(Wt.type,(function(e,t){return an.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),an.on(Jt.type,(function(e,t){return on.with({channels:e.channels,groups:e.groups})})),an.on(zt.type,(function(e,t){return un.with(void 0,[Xt(e.channels,e.groups)])}));var sn=new Ze("HEARTBEATING");sn.onEnter((function(e){return Qt(e.channels,e.groups)})),sn.on(Vt.type,(function(e,t){return rn.with({channels:e.channels,groups:e.groups})})),sn.on(Ht.type,(function(e,t){return sn.with({channels:u(u([],s(e.channels),!1),s(t.payload.channels),!1),groups:u(u([],s(e.groups),!1),s(t.payload.groups),!1)})})),sn.on(qt.type,(function(e,t){return sn.with({channels:e.channels.filter((function(e){return!t.payload.channels.includes(e)})),groups:e.groups.filter((function(e){return!t.payload.groups.includes(e)}))},[Xt(t.payload.channels,t.payload.groups)])})),sn.on(Wt.type,(function(e,t){return an.with(n(n({},e),{attempts:0,reason:t.payload}))})),sn.on(Bt.type,(function(e){return nn.with({channels:e.channels,groups:e.groups},[Xt(e.channels,e.groups)])})),sn.on(zt.type,(function(e,t){return un.with(void 0,[Xt(e.channels,e.groups)])}));var un=new Ze("HEARTBEAT_INACTIVE");un.on(Ht.type,(function(e,t){return sn.with({channels:t.payload.channels,groups:t.payload.groups})}));var cn=function(){function e(e){var t=this;this.engine=new et,this.channels=[],this.groups=[],this.dispatcher=new tn(this.engine,e),this.dependencies=e,this._unsubscribeEngine=this.engine.subscribe((function(e){"invocationDispatched"===e.type&&t.dispatcher.dispatch(e.invocation)})),this.engine.start(un,void 0)}return Object.defineProperty(e.prototype,"_engine",{get:function(){return this.engine},enumerable:!1,configurable:!0}),e.prototype.join=function(e){var t=e.channels,n=e.groups;this.channels=u(u([],s(this.channels),!1),s(null!=t?t:[]),!1),this.groups=u(u([],s(this.groups),!1),s(null!=n?n:[]),!1),this.engine.transition(Ht(this.channels.slice(0),this.groups.slice(0)))},e.prototype.leave=function(e){var t=this,n=e.channels,r=e.groups;this.dependencies.presenceState&&(null==n||n.forEach((function(e){return delete t.dependencies.presenceState[e]})),null==r||r.forEach((function(e){return delete t.dependencies.presenceState[e]}))),this.engine.transition(qt(null!=n?n:[],null!=r?r:[]))},e.prototype.leaveAll=function(){this.engine.transition(zt())},e.prototype.dispose=function(){this._unsubscribeEngine(),this.dispatcher.dispose()},e}(),ln=function(){function e(){}return e.LinearRetryPolicy=function(e){return{delay:e.delay,maximumRetry:e.maximumRetry,shouldRetry:function(e,t){var n;return 403!==(null===(n=null==e?void 0:e.status)||void 0===n?void 0:n.statusCode)&&this.maximumRetry>t},getDelay:function(e,t){var n;return 1e3*((null!==(n=t.retryAfter)&&void 0!==n?n:this.delay)+Math.random())},getGiveupReason:function(e,t){var n;return this.maximumRetry<=t?"retry attempts exhaused.":403===(null===(n=null==e?void 0:e.status)||void 0===n?void 0:n.statusCode)?"forbidden operation.":"unknown error"}}},e.ExponentialRetryPolicy=function(e){return{minimumDelay:e.minimumDelay,maximumDelay:e.maximumDelay,maximumRetry:e.maximumRetry,shouldRetry:function(e,t){var n;return 403!==(null===(n=null==e?void 0:e.status)||void 0===n?void 0:n.statusCode)&&this.maximumRetry>t},getDelay:function(e,t){var n;return 1e3*((null!==(n=t.retryAfter)&&void 0!==n?n:Math.min(Math.pow(2,e),this.maximumDelay))+Math.random())},getGiveupReason:function(e,t){var n;return this.maximumRetry<=t?"retry attempts exhaused.":403===(null===(n=null==e?void 0:e.status)||void 0===n?void 0:n.statusCode)?"forbidden operation.":"unknown error"}}},e}(),pn=function(){function e(e){var t=e.modules,n=e.listenerManager,r=e.getFileUrl;this.modules=t,this.listenerManager=n,this.getFileUrl=r,t.cryptoModule&&(this._decoder=new TextDecoder)}return e.prototype.emitEvent=function(e){var t=e.channel,o=e.publishMetaData,i=e.subscriptionMatch;if(t===i&&(i=null),e.channel.endsWith("-pnpres")){var a={channel:null,subscription:null};t&&(a.channel=t.substring(0,t.lastIndexOf("-pnpres"))),i&&(a.subscription=i.substring(0,i.lastIndexOf("-pnpres"))),a.action=e.payload.action,a.state=e.payload.data,a.timetoken=o.publishTimetoken,a.occupancy=e.payload.occupancy,a.uuid=e.payload.uuid,a.timestamp=e.payload.timestamp,e.payload.join&&(a.join=e.payload.join),e.payload.leave&&(a.leave=e.payload.leave),e.payload.timeout&&(a.timeout=e.payload.timeout),this.listenerManager.announcePresence(a)}else if(1===e.messageType){(a={channel:null,subscription:null}).channel=t,a.subscription=i,a.timetoken=o.publishTimetoken,a.publisher=e.issuingClientId,e.userMetadata&&(a.userMetadata=e.userMetadata),a.message=e.payload,this.listenerManager.announceSignal(a)}else if(2===e.messageType){if((a={channel:null,subscription:null}).channel=t,a.subscription=i,a.timetoken=o.publishTimetoken,a.publisher=e.issuingClientId,e.userMetadata&&(a.userMetadata=e.userMetadata),a.message={event:e.payload.event,type:e.payload.type,data:e.payload.data},this.listenerManager.announceObjects(a),"uuid"===e.payload.type){var s=this._renameChannelField(a);this.listenerManager.announceUser(n(n({},s),{message:n(n({},s.message),{event:this._renameEvent(s.message.event),type:"user"})}))}else if("channel"===message.payload.type){s=this._renameChannelField(a);this.listenerManager.announceSpace(n(n({},s),{message:n(n({},s.message),{event:this._renameEvent(s.message.event),type:"space"})}))}else if("membership"===message.payload.type){var u=(s=this._renameChannelField(a)).message.data,c=u.uuid,l=u.channel,p=r(u,["uuid","channel"]);p.user=c,p.space=l,this.listenerManager.announceMembership(n(n({},s),{message:n(n({},s.message),{event:this._renameEvent(s.message.event),data:p})}))}}else if(3===e.messageType){(a={}).channel=t,a.subscription=i,a.timetoken=o.publishTimetoken,a.publisher=e.issuingClientId,a.data={messageTimetoken:e.payload.data.messageTimetoken,actionTimetoken:e.payload.data.actionTimetoken,type:e.payload.data.type,uuid:e.issuingClientId,value:e.payload.data.value},a.event=e.payload.event,this.listenerManager.announceMessageAction(a)}else if(4===e.messageType){(a={}).channel=t,a.subscription=i,a.timetoken=o.publishTimetoken,a.publisher=e.issuingClientId;var h=e.payload;if(this.modules.cryptoModule){var f=void 0;try{f=(d=this.modules.cryptoModule.decrypt(e.payload))instanceof ArrayBuffer?JSON.parse(this._decoder.decode(d)):d}catch(e){f=null,a.error="Error while decrypting message content: ".concat(e.message)}null!==f&&(h=f)}e.userMetadata&&(a.userMetadata=e.userMetadata),a.message=h.message,a.file={id:h.file.id,name:h.file.name,url:this.getFileUrl({id:h.file.id,name:h.file.name,channel:t})},this.listenerManager.announceFile(a)}else{if((a={channel:null,subscription:null}).channel=t,a.subscription=i,a.timetoken=o.publishTimetoken,a.publisher=e.issuingClientId,e.userMetadata&&(a.userMetadata=e.userMetadata),this.modules.cryptoModule){f=void 0;try{var d;f=(d=this.modules.cryptoModule.decrypt(e.payload))instanceof ArrayBuffer?JSON.parse(this._decoder.decode(d)):d}catch(e){f=null,a.error="Error while decrypting message content: ".concat(e.message)}a.message=null!=f?f:e.payload}else a.message=e.payload;this.listenerManager.announceMessage(a)}},e.prototype._renameEvent=function(e){return"set"===e?"updated":"removed"},e.prototype._renameChannelField=function(e){var t=e.channel,n=r(e,["channel"]);return n.spaceId=t,n},e}(),hn=function(){function e(e){var t=this,r=e.networking,o=e.cbor,i=new g({setup:e});this._config=i;var c=new A({config:i}),l=e.cryptography;r.init(i);var p=new H(i,o);this._tokenManager=p;var h=new I({maximumSamplesCount:6e4});this._telemetryManager=h;var f=this._config.cryptoModule,d={config:i,networking:r,crypto:c,cryptography:l,tokenManager:p,telemetryManager:h,PubNubFile:e.PubNubFile,cryptoModule:f};this.File=e.PubNubFile,this.encryptFile=function(e,t){return 1==arguments.length&&"string"!=typeof e&&d.cryptoModule?(t=e,d.cryptoModule.encryptFile(t,this.File)):l.encryptFile(e,t,this.File)},this.decryptFile=function(e,t){return 1==arguments.length&&"string"!=typeof e&&d.cryptoModule?(t=e,d.cryptoModule.decryptFile(t,this.File)):l.decryptFile(e,t,this.File)};var y=Q.bind(this,d,Je),m=Q.bind(this,d,ae),b=Q.bind(this,d,ue),_=Q.bind(this,d,le),S=Q.bind(this,d,$e),w=new B;if(this._listenerManager=w,this.iAmHere=Q.bind(this,d,ue),this.iAmAway=Q.bind(this,d,ae),this.setPresenceState=Q.bind(this,d,le),this.handshake=Q.bind(this,d,Qe),this.receiveMessages=Q.bind(this,d,Xe),!0===i.enableEventEngine){if(this._eventEmitter=new pn({modules:d,listenerManager:this._listenerManager,getFileUrl:function(e){return be(d,e)}}),i.maintainPresenceState&&(this.presenceState={},this.setState=function(e){var n,r;return null===(n=e.channels)||void 0===n||n.forEach((function(n){return t.presenceState[n]=e.state})),null===(r=e.channelGroups)||void 0===r||r.forEach((function(n){return t.presenceState[n]=e.state})),t.setPresenceState({channels:e.channels,channelGroups:e.channelGroups,state:t.presenceState})}),i.getHeartbeatInterval()){var O=new cn({heartbeat:this.iAmHere,leave:this.iAmAway,heartbeatDelay:function(){return new Promise((function(e){return setTimeout(e,1e3*d.config.getHeartbeatInterval())}))},retryDelay:function(e){return new Promise((function(t){return setTimeout(t,e)}))},config:d.config,presenceState:this.presenceState,emitStatus:function(e){w.announceStatus(e)}});this.presenceEventEngine=O,this.join=this.presenceEventEngine.join.bind(O),this.leave=this.presenceEventEngine.leave.bind(O),this.leaveAll=this.presenceEventEngine.leaveAll.bind(O)}var P=new Lt({handshake:this.handshake,receiveMessages:this.receiveMessages,delay:function(e){return new Promise((function(t){return setTimeout(t,e)}))},join:this.join,leave:this.leave,leaveAll:this.leaveAll,presenceState:this.presenceState,config:d.config,emitMessages:function(e){var n,r;try{for(var o=a(e),i=o.next();!i.done;i=o.next()){var s=i.value;t._eventEmitter.emitEvent(s)}}catch(e){n={error:e}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}},emitStatus:function(e){w.announceStatus(e)}});this.subscribe=P.subscribe.bind(P),this.unsubscribe=P.unsubscribe.bind(P),this.unsubscribeAll=P.unsubscribeAll.bind(P),this.reconnect=P.reconnect.bind(P),this.disconnect=P.disconnect.bind(P),this.destroy=P.dispose.bind(P),this.getSubscribedChannels=P.getSubscribedChannels.bind(P),this.getSubscribedChannelGroups=P.getSubscribedChannelGroups.bind(P),this.eventEngine=P}else{var E=new x({timeEndpoint:y,leaveEndpoint:m,heartbeatEndpoint:b,setStateEndpoint:_,subscribeEndpoint:S,crypto:d.crypto,config:d.config,listenerManager:w,getFileUrl:function(e){return be(d,e)},cryptoModule:d.cryptoModule});this.subscribe=E.adaptSubscribeChange.bind(E),this.unsubscribe=E.adaptUnsubscribeChange.bind(E),this.disconnect=E.disconnect.bind(E),this.reconnect=E.reconnect.bind(E),this.unsubscribeAll=E.unsubscribeAll.bind(E),this.getSubscribedChannels=E.getSubscribedChannels.bind(E),this.getSubscribedChannelGroups=E.getSubscribedChannelGroups.bind(E),this.setState=E.adaptStateChange.bind(E),this.presence=E.adaptPresenceChange.bind(E),this.destroy=function(e){E.unsubscribeAll(e),E.disconnect()}}this.addListener=w.addListener.bind(w),this.removeListener=w.removeListener.bind(w),this.removeAllListeners=w.removeAllListeners.bind(w),this.parseToken=p.parseToken.bind(p),this.setToken=p.setToken.bind(p),this.getToken=p.getToken.bind(p),this.channelGroups={listGroups:Q.bind(this,d,ee),listChannels:Q.bind(this,d,te),addChannels:Q.bind(this,d,X),removeChannels:Q.bind(this,d,Y),deleteGroup:Q.bind(this,d,Z)},this.push={addChannels:Q.bind(this,d,ne),removeChannels:Q.bind(this,d,re),deleteDevice:Q.bind(this,d,ie),listChannels:Q.bind(this,d,oe)},this.hereNow=Q.bind(this,d,pe),this.whereNow=Q.bind(this,d,se),this.getState=Q.bind(this,d,ce),this.grant=Q.bind(this,d,Ue),this.grantToken=Q.bind(this,d,Ge),this.audit=Q.bind(this,d,xe),this.revokeToken=Q.bind(this,d,Le),this.publish=Q.bind(this,d,Be),this.fire=function(e,n){return e.replicate=!1,e.storeInHistory=!1,t.publish(e,n)},this.signal=Q.bind(this,d,He),this.history=Q.bind(this,d,qe),this.deleteMessages=Q.bind(this,d,ze),this.messageCounts=Q.bind(this,d,Ve),this.fetchMessages=Q.bind(this,d,We),this.addMessageAction=Q.bind(this,d,he),this.removeMessageAction=Q.bind(this,d,fe),this.getMessageActions=Q.bind(this,d,de),this.listFiles=Q.bind(this,d,ye);var T=Q.bind(this,d,ge);this.publishFile=Q.bind(this,d,me),this.sendFile=ve({generateUploadUrl:T,publishFile:this.publishFile,modules:d}),this.getFileUrl=function(e){return be(d,e)},this.downloadFile=Q.bind(this,d,_e),this.deleteFile=Q.bind(this,d,Se),this.objects={getAllUUIDMetadata:Q.bind(this,d,we),getUUIDMetadata:Q.bind(this,d,Oe),setUUIDMetadata:Q.bind(this,d,Pe),removeUUIDMetadata:Q.bind(this,d,Ee),getAllChannelMetadata:Q.bind(this,d,Te),getChannelMetadata:Q.bind(this,d,Ae),setChannelMetadata:Q.bind(this,d,Ce),removeChannelMetadata:Q.bind(this,d,ke),getChannelMembers:Q.bind(this,d,Ne),setChannelMembers:function(e){for(var r=[],o=1;o=this._config.origin.length&&(this._currentSubDomain=0);var t=this._config.origin[this._currentSubDomain];return"".concat(e).concat(t)},e.prototype.hasModule=function(e){return e in this._modules},e.prototype.shiftStandardOrigin=function(){return this._standardOrigin=this.nextOrigin(),this._standardOrigin},e.prototype.getStandardOrigin=function(){return this._standardOrigin},e.prototype.POSTFILE=function(e,t,n){return this._modules.postfile(e,t,n)},e.prototype.GETFILE=function(e,t,n){return this._modules.getfile(e,t,n)},e.prototype.POST=function(e,t,n,r){return this._modules.post(e,t,n,r)},e.prototype.PATCH=function(e,t,n,r){return this._modules.patch(e,t,n,r)},e.prototype.GET=function(e,t,n){return this._modules.get(e,t,n)},e.prototype.DELETE=function(e,t,n){return this._modules.del(e,t,n)},e.prototype._detectErrorCategory=function(e){if("ENOTFOUND"===e.code)return R.PNNetworkIssuesCategory;if("ECONNREFUSED"===e.code)return R.PNNetworkIssuesCategory;if("ECONNRESET"===e.code)return R.PNNetworkIssuesCategory;if("EAI_AGAIN"===e.code)return R.PNNetworkIssuesCategory;if(0===e.status||e.hasOwnProperty("status")&&void 0===e.status)return R.PNNetworkIssuesCategory;if(e.timeout)return R.PNTimeoutCategory;if("ETIMEDOUT"===e.code)return R.PNNetworkIssuesCategory;if(e.response){if(e.response.badRequest)return R.PNBadRequestCategory;if(e.response.forbidden)return R.PNAccessDeniedCategory}return R.PNUnknownCategory},e}();function dn(e){var t=function(e){return e&&"object"==typeof e&&e.constructor===Object};if(!t(e))return e;var n={};return Object.keys(e).forEach((function(r){var o=function(e){return"string"==typeof e||e instanceof String}(r),i=r,a=e[r];Array.isArray(r)||o&&r.indexOf(",")>=0?i=(o?r.split(","):r).reduce((function(e,t){return e+=String.fromCharCode(t)}),""):(function(e){return"number"==typeof e&&isFinite(e)}(r)||o&&!isNaN(r))&&(i=String.fromCharCode(o?parseInt(r,10):10));n[i]=t(a)?dn(a):a})),n}var yn=function(){function e(e,t){this._base64ToBinary=t,this._decode=e}return e.prototype.decodeToken=function(e){var t="";e.length%4==3?t="=":e.length%4==2&&(t="==");var n=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,r=this._decode(this._base64ToBinary(n));if("object"==typeof r)return r},e}(),gn={exports:{}},mn={exports:{}};!function(e){function t(e){if(e)return function(e){for(var n in t.prototype)e[n]=t.prototype[n];return e}(e)}e.exports=t,t.prototype.on=t.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},t.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},t.prototype.off=t.prototype.removeListener=t.prototype.removeAllListeners=t.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var o=0;oa.depthLimit)return void En(bn,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void En(bn,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;st?1:0}function Cn(e,t,n,r){void 0===r&&(r=On());var o,i=kn(e,"",0,[],void 0,0,r)||e;try{o=0===wn.length?JSON.stringify(i,t,n):JSON.stringify(i,Nn(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Sn.length;){var a=Sn.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return o}function kn(e,t,n,r,o,i,a){var s;if(i+=1,"object"==typeof e&&null!==e){for(s=0;sa.depthLimit)return void En(bn,e,t,o);if(void 0!==a.edgesLimit&&n+1>a.edgesLimit)return void En(bn,e,t,o);if(r.push(e),Array.isArray(e))for(s=0;s0)for(var r=0;r1&&"boolean"!=typeof t)throw new Hn('"allowMissing" argument must be a boolean');var n=cr(e),r=n.length>0?n[0]:"",o=lr("%"+r+"%",t),i=o.name,a=o.value,s=!1,u=o.alias;u&&(r=u[0],or(n,rr([0,1],u)));for(var c=1,l=!0;c=n.length){var d=zn(a,p);a=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:a[p]}else l=nr(a,p),a=a[p];l&&!s&&(Yn[i]=a)}}return a},hr={exports:{}};!function(e){var t=Gn,n=pr,r=n("%Function.prototype.apply%"),o=n("%Function.prototype.call%"),i=n("%Reflect.apply%",!0)||t.call(o,r),a=n("%Object.getOwnPropertyDescriptor%",!0),s=n("%Object.defineProperty%",!0),u=n("%Math.max%");if(s)try{s({},"a",{value:1})}catch(e){s=null}e.exports=function(e){var n=i(t,o,arguments);if(a&&s){var r=a(n,"length");r.configurable&&s(n,"length",{value:1+u(0,e.length-(arguments.length-1))})}return n};var c=function(){return i(t,r,arguments)};s?s(e.exports,"apply",{value:c}):e.exports.apply=c}(hr);var fr=pr,dr=hr.exports,yr=dr(fr("String.prototype.indexOf")),gr=l(Object.freeze({__proto__:null,default:{}})),mr="function"==typeof Map&&Map.prototype,vr=Object.getOwnPropertyDescriptor&&mr?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,br=mr&&vr&&"function"==typeof vr.get?vr.get:null,_r=mr&&Map.prototype.forEach,Sr="function"==typeof Set&&Set.prototype,wr=Object.getOwnPropertyDescriptor&&Sr?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,Or=Sr&&wr&&"function"==typeof wr.get?wr.get:null,Pr=Sr&&Set.prototype.forEach,Er="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,Tr="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,Ar="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,Cr=Boolean.prototype.valueOf,kr=Object.prototype.toString,Nr=Function.prototype.toString,Mr=String.prototype.match,jr=String.prototype.slice,Rr=String.prototype.replace,xr=String.prototype.toUpperCase,Ur=String.prototype.toLowerCase,Ir=RegExp.prototype.test,Dr=Array.prototype.concat,Fr=Array.prototype.join,Gr=Array.prototype.slice,Lr=Math.floor,Kr="function"==typeof BigInt?BigInt.prototype.valueOf:null,Br=Object.getOwnPropertySymbols,Hr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,qr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,zr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===qr||"symbol")?Symbol.toStringTag:null,Vr=Object.prototype.propertyIsEnumerable,Wr=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function Jr(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||Ir.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-Lr(-e):Lr(e);if(r!==e){var o=String(r),i=jr.call(t,o.length+1);return Rr.call(o,n,"$&_")+"."+Rr.call(Rr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return Rr.call(t,n,"$&_")}var $r=gr,Qr=$r.custom,Xr=no(Qr)?Qr:null;function Yr(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function Zr(e){return Rr.call(String(e),/"/g,""")}function eo(e){return!("[object Array]"!==io(e)||zr&&"object"==typeof e&&zr in e)}function to(e){return!("[object RegExp]"!==io(e)||zr&&"object"==typeof e&&zr in e)}function no(e){if(qr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Hr)return!1;try{return Hr.call(e),!0}catch(e){}return!1}var ro=Object.prototype.hasOwnProperty||function(e){return e in this};function oo(e,t){return ro.call(e,t)}function io(e){return kr.call(e)}function ao(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0,r=e.length;nt.maxStringLength){var n=e.length-t.maxStringLength,r="... "+n+" more character"+(n>1?"s":"");return so(jr.call(e,0,t.maxStringLength),t)+r}return Yr(Rr.call(Rr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,uo),"single",t)}function uo(e){var t=e.charCodeAt(0),n={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return n?"\\"+n:"\\x"+(t<16?"0":"")+xr.call(t.toString(16))}function co(e){return"Object("+e+")"}function lo(e){return e+" { ? }"}function po(e,t,n,r){return e+" ("+t+") {"+(r?ho(n,r):Fr.call(n,", "))+"}"}function ho(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+Fr.call(e,","+n)+"\n"+t.prev}function fo(e,t){var n=eo(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?dr(n):n},mo=function e(t,n,r,o){var i=n||{};if(oo(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(oo(i,"maxStringLength")&&("number"==typeof i.maxStringLength?i.maxStringLength<0&&i.maxStringLength!==1/0:null!==i.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var a=!oo(i,"customInspect")||i.customInspect;if("boolean"!=typeof a&&"symbol"!==a)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(oo(i,"indent")&&null!==i.indent&&"\t"!==i.indent&&!(parseInt(i.indent,10)===i.indent&&i.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(oo(i,"numericSeparator")&&"boolean"!=typeof i.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var s=i.numericSeparator;if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return so(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return s?Jr(t,u):u}if("bigint"==typeof t){var l=String(t)+"n";return s?Jr(t,l):l}var p=void 0===i.depth?5:i.depth;if(void 0===r&&(r=0),r>=p&&p>0&&"object"==typeof t)return eo(t)?"[Array]":"[Object]";var h=function(e,t){var n;if("\t"===e.indent)n="\t";else{if(!("number"==typeof e.indent&&e.indent>0))return null;n=Fr.call(Array(e.indent+1)," ")}return{base:n,prev:Fr.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(ao(o,t)>=0)return"[Circular]";function f(t,n,a){if(n&&(o=Gr.call(o)).push(n),a){var s={depth:i.depth};return oo(i,"quoteStyle")&&(s.quoteStyle=i.quoteStyle),e(t,s,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!to(t)){var d=function(e){if(e.name)return e.name;var t=Mr.call(Nr.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),y=fo(t,f);return"[Function"+(d?": "+d:" (anonymous)")+"]"+(y.length>0?" { "+Fr.call(y,", ")+" }":"")}if(no(t)){var g=qr?Rr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):Hr.call(t);return"object"!=typeof t||qr?g:co(g)}if(function(e){if(!e||"object"!=typeof e)return!1;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return!0;return"string"==typeof e.nodeName&&"function"==typeof e.getAttribute}(t)){for(var m="<"+Ur.call(String(t.nodeName)),v=t.attributes||[],b=0;b"}if(eo(t)){if(0===t.length)return"[]";var _=fo(t,f);return h&&!function(e){for(var t=0;t=0)return!1;return!0}(_)?"["+ho(_,h)+"]":"[ "+Fr.call(_,", ")+" ]"}if(function(e){return!("[object Error]"!==io(e)||zr&&"object"==typeof e&&zr in e)}(t)){var S=fo(t,f);return"cause"in Error.prototype||!("cause"in t)||Vr.call(t,"cause")?0===S.length?"["+String(t)+"]":"{ ["+String(t)+"] "+Fr.call(S,", ")+" }":"{ ["+String(t)+"] "+Fr.call(Dr.call("[cause]: "+f(t.cause),S),", ")+" }"}if("object"==typeof t&&a){if(Xr&&"function"==typeof t[Xr]&&$r)return $r(t,{depth:p-r});if("symbol"!==a&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!br||!e||"object"!=typeof e)return!1;try{br.call(e);try{Or.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var w=[];return _r&&_r.call(t,(function(e,n){w.push(f(n,t,!0)+" => "+f(e,t))})),po("Map",br.call(t),w,h)}if(function(e){if(!Or||!e||"object"!=typeof e)return!1;try{Or.call(e);try{br.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var O=[];return Pr&&Pr.call(t,(function(e){O.push(f(e,t))})),po("Set",Or.call(t),O,h)}if(function(e){if(!Er||!e||"object"!=typeof e)return!1;try{Er.call(e,Er);try{Tr.call(e,Tr)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return lo("WeakMap");if(function(e){if(!Tr||!e||"object"!=typeof e)return!1;try{Tr.call(e,Tr);try{Er.call(e,Er)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return lo("WeakSet");if(function(e){if(!Ar||!e||"object"!=typeof e)return!1;try{return Ar.call(e),!0}catch(e){}return!1}(t))return lo("WeakRef");if(function(e){return!("[object Number]"!==io(e)||zr&&"object"==typeof e&&zr in e)}(t))return co(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!Kr)return!1;try{return Kr.call(e),!0}catch(e){}return!1}(t))return co(f(Kr.call(t)));if(function(e){return!("[object Boolean]"!==io(e)||zr&&"object"==typeof e&&zr in e)}(t))return co(Cr.call(t));if(function(e){return!("[object String]"!==io(e)||zr&&"object"==typeof e&&zr in e)}(t))return co(f(String(t)));if("undefined"!=typeof window&&t===window)return"{ [object Window] }";if(t===c)return"{ [object globalThis] }";if(!function(e){return!("[object Date]"!==io(e)||zr&&"object"==typeof e&&zr in e)}(t)&&!to(t)){var P=fo(t,f),E=Wr?Wr(t)===Object.prototype:t instanceof Object||t.constructor===Object,T=t instanceof Object?"":"null prototype",A=!E&&zr&&Object(t)===t&&zr in t?jr.call(io(t),8,-1):T?"Object":"",C=(E||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(A||T?"["+Fr.call(Dr.call([],A||[],T||[]),": ")+"] ":"");return 0===P.length?C+"{}":h?C+"{"+ho(P,h)+"}":C+"{ "+Fr.call(P,", ")+" }"}return String(t)},vo=yo("%TypeError%"),bo=yo("%WeakMap%",!0),_o=yo("%Map%",!0),So=go("WeakMap.prototype.get",!0),wo=go("WeakMap.prototype.set",!0),Oo=go("WeakMap.prototype.has",!0),Po=go("Map.prototype.get",!0),Eo=go("Map.prototype.set",!0),To=go("Map.prototype.has",!0),Ao=function(e,t){for(var n,r=e;null!==(n=r.next);r=n)if(n.key===t)return r.next=n.next,n.next=e.next,e.next=n,n},Co=String.prototype.replace,ko=/%20/g,No="RFC3986",Mo={default:No,formatters:{RFC1738:function(e){return Co.call(e,ko,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:No},jo=Mo,Ro=Object.prototype.hasOwnProperty,xo=Array.isArray,Uo=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),Io=function(e,t){for(var n=t&&t.plainObjects?Object.create(null):{},r=0;r1;){var t=e.pop(),n=t.obj[t.prop];if(xo(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===jo.RFC1738&&(40===u||41===u)?a+=i.charAt(s):u<128?a+=Uo[u]:u<2048?a+=Uo[192|u>>6]+Uo[128|63&u]:u<55296||u>=57344?a+=Uo[224|u>>12]+Uo[128|u>>6&63]+Uo[128|63&u]:(s+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(s)),a+=Uo[240|u>>18]+Uo[128|u>>12&63]+Uo[128|u>>6&63]+Uo[128|63&u])}return a},isBuffer:function(e){return!(!e||"object"!=typeof e)&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))},isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},maybeMap:function(e,t){if(xo(e)){for(var n=[],r=0;r0?v.join(",")||null:void 0}];else if(Ho(u))O=u;else{var E=Object.keys(v);O=c?E.sort(c):E}for(var T=o&&Ho(v)&&1===v.length?n+"[]":n,A=0;A-1?e.split(","):e},ri=function(e,t,n,r){if(e){var o=n.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,i=/(\[[^[\]]*])/g,a=n.depth>0&&/(\[[^[\]]*])/.exec(o),s=a?o.slice(0,a.index):o,u=[];if(s){if(!n.plainObjects&&Yo.call(Object.prototype,s)&&!n.allowPrototypes)return;u.push(s)}for(var c=0;n.depth>0&&null!==(a=i.exec(o))&&c=0;--i){var a,s=e[i];if("[]"===s&&n.parseArrays)a=[].concat(o);else{a=n.plainObjects?Object.create(null):{};var u="["===s.charAt(0)&&"]"===s.charAt(s.length-1)?s.slice(1,-1):s,c=parseInt(u,10);n.parseArrays||""!==u?!isNaN(c)&&s!==u&&String(c)===u&&c>=0&&n.parseArrays&&c<=n.arrayLimit?(a=[])[c]=o:"__proto__"!==u&&(a[u]=o):a={0:o}}o=a}return o}(u,t,n,r)}},oi=function(e,t){var n,r=e,o=function(e){if(!e)return Jo;if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");var t=e.charset||Jo.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var n=Lo.default;if(void 0!==e.format){if(!Ko.call(Lo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=Lo.formatters[n],o=Jo.filter;return("function"==typeof e.filter||Ho(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:Jo.addQueryPrefix,allowDots:void 0===e.allowDots?Jo.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Jo.charsetSentinel,delimiter:void 0===e.delimiter?Jo.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:Jo.encode,encoder:"function"==typeof e.encoder?e.encoder:Jo.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:Jo.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:Jo.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:Jo.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Jo.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):Ho(o.filter)&&(n=o.filter);var i,a=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in Bo?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var s=Bo[i];if(t&&"commaRoundTrip"in t&&"boolean"!=typeof t.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var u="comma"===s&&t&&t.commaRoundTrip;n||(n=Object.keys(r)),o.sort&&n.sort(o.sort);for(var c=Fo(),l=0;l0?f+h:""},ii={formats:Mo,parse:function(e,t){var n=function(e){if(!e)return ei;if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var t=void 0===e.charset?ei.charset:e.charset;return{allowDots:void 0===e.allowDots?ei.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:ei.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:ei.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:ei.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:ei.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:ei.comma,decoder:"function"==typeof e.decoder?e.decoder:ei.decoder,delimiter:"string"==typeof e.delimiter||Xo.isRegExp(e.delimiter)?e.delimiter:ei.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:ei.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:ei.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:ei.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:ei.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:ei.strictNullHandling}}(t);if(""===e||null==e)return n.plainObjects?Object.create(null):{};for(var r="string"==typeof e?function(e,t){var n,r={__proto__:null},o=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,i=t.parameterLimit===1/0?void 0:t.parameterLimit,a=o.split(t.delimiter,i),s=-1,u=t.charset;if(t.charsetSentinel)for(n=0;n-1&&(l=Zo(l)?[l]:l),Yo.call(r,c)?r[c]=Xo.combine(r[c],l):r[c]=l}return r}(e,n):e,o=n.plainObjects?Object.create(null):{},i=Object.keys(r),a=0;a=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:i}}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 a,s=!0,u=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return s=e.done,e},e:function(e){u=!0,a=e},f:function(){try{s||null==r.return||r.return()}finally{if(u)throw a}}}}function n(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.split(/ *; */).shift(),e.params=e=>{const n={};var r,o=t(e.split(/ *; */));try{for(o.s();!(r=o.n()).done;){const e=r.value.split(/ *= */),t=e.shift(),o=e.shift();t&&o&&(n[t]=o)}}catch(e){o.e(e)}finally{o.f()}return n},e.parseLinks=e=>{const n={};var r,o=t(e.split(/ *, */));try{for(o.s();!(r=o.n()).done;){const e=r.value.split(/ *; */),t=e[0].slice(1,-1);n[e[1].split(/ *= */)[1].slice(1,-1)]=t}}catch(e){o.e(e)}finally{o.f()}return n},e.cleanHeader=(e,t)=>(delete e["content-type"],delete e["content-length"],delete e["transfer-encoding"],delete e.host,t&&(delete e.authorization,delete e.cookie),e),e.isObject=e=>null!==e&&"object"==typeof e,e.hasOwn=Object.hasOwn||function(e,t){if(null==e)throw new TypeError("Cannot convert undefined or null to object");return Object.prototype.hasOwnProperty.call(new Object(e),t)},e.mixin=(t,n)=>{for(const r in n)e.hasOwn(n,r)&&(t[r]=n[r])}}(ai);const si=gr,ui=ai.isObject,ci=ai.hasOwn;var li=pi;function pi(){}pi.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},pi.prototype.parse=function(e){return this._parser=e,this},pi.prototype.responseType=function(e){return this._responseType=e,this},pi.prototype.serialize=function(e){return this._serializer=e,this},pi.prototype.timeout=function(e){if(!e||"object"!=typeof e)return this._timeout=e,this._responseTimeout=0,this._uploadTimeout=0,this;for(const t in e)if(ci(e,t))switch(t){case"deadline":this._timeout=e.deadline;break;case"response":this._responseTimeout=e.response;break;case"upload":this._uploadTimeout=e.upload;break;default:console.warn("Unknown timeout option",t)}return this},pi.prototype.retry=function(e,t){return 0!==arguments.length&&!0!==e||(e=1),e<=0&&(e=0),this._maxRetries=e,this._retries=0,this._retryCallback=t,this};const hi=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),fi=new Set([408,413,429,500,502,503,504,521,522,524]);pi.prototype._shouldRetry=function(e,t){if(!this._maxRetries||this._retries++>=this._maxRetries)return!1;if(this._retryCallback)try{const n=this._retryCallback(e,t);if(!0===n)return!0;if(!1===n)return!1}catch(e){console.error(e)}if(t&&t.status&&fi.has(t.status))return!0;if(e){if(e.code&&hi.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},pi.prototype._retry=function(){return this.clearTimeout(),this.req&&(this.req=null,this.req=this.request()),this._aborted=!1,this.timedout=!1,this.timedoutError=null,this._end()},pi.prototype.then=function(e,t){if(!this._fullfilledPromise){const e=this;this._endCalled&&console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises"),this._fullfilledPromise=new Promise(((t,n)=>{e.on("abort",(()=>{if(this._maxRetries&&this._maxRetries>this._retries)return;if(this.timedout&&this.timedoutError)return void n(this.timedoutError);const e=new Error("Aborted");e.code="ABORTED",e.status=this.status,e.method=this.method,e.url=this.url,n(e)})),e.end(((e,r)=>{e?n(e):t(r)}))}))}return this._fullfilledPromise.then(e,t)},pi.prototype.catch=function(e){return this.then(void 0,e)},pi.prototype.use=function(e){return e(this),this},pi.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},pi.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},pi.prototype.get=function(e){return this._header[e.toLowerCase()]},pi.prototype.getHeader=pi.prototype.get,pi.prototype.set=function(e,t){if(ui(e)){for(const t in e)ci(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},pi.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},pi.prototype.field=function(e,t,n){if(null==e)throw new Error(".field(name, val) name can not be empty");if(this._data)throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()");if(ui(e)){for(const t in e)ci(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)ci(t,n)&&this.field(e,t[n]);return this}if(null==t)throw new Error(".field(name, val) val can not be empty");return"boolean"==typeof t&&(t=String(t)),n?this._getFormData().append(e,t,n):this._getFormData().append(e,t),this},pi.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(si.gte(process.version,"v13.0.0")&&si.lt(process.version,"v14.0.0"))throw new Error("Superagent does not work in v13 properly with abort() due to Node.js core changes");this.req.abort()}return this.clearTimeout(),this.emit("abort"),this},pi.prototype._auth=function(e,t,n,r){switch(n.type){case"basic":this.set("Authorization",`Basic ${r(`${e}:${t}`)}`);break;case"auto":this.username=e,this.password=t;break;case"bearer":this.set("Authorization",`Bearer ${e}`)}return this},pi.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},pi.prototype.redirects=function(e){return this._maxRedirects=e,this},pi.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},pi.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},pi.prototype.send=function(e){const t=ui(e);let n=this._header["content-type"];if(this._formData)throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()");if(t&&!this._data)Array.isArray(e)?this._data=[]:this._isHost(e)||(this._data={});else if(e&&this._data&&this._isHost(this._data))throw new Error("Can't merge these send calls");if(t&&ui(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");ci(e,t)&&(this._data[t]=e[t])}else{if("bigint"==typeof e)throw new Error("Cannot send value of type BigInt");"string"==typeof e?(n||this.type("form"),n=this._header["content-type"],n&&(n=n.toLowerCase().trim()),this._data="application/x-www-form-urlencoded"===n?this._data?`${this._data}&${e}`:e:(this._data||"")+e):this._data=e}return!t||this._isHost(e)||n||this.type("json"),this},pi.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},pi.prototype._finalizeQueryString=function(){const e=this._query.join("&");if(e&&(this.url+=(this.url.includes("?")?"&":"?")+e),this._query.length=0,this._sort){const e=this.url.indexOf("?");if(e>=0){const t=this.url.slice(e+1).split("&");"function"==typeof this._sort?t.sort(this._sort):t.sort(),this.url=this.url.slice(0,e)+"?"+t.join("&")}}},pi.prototype._appendQueryString=()=>{console.warn("Unsupported")},pi.prototype._timeoutError=function(e,t,n){if(this._aborted)return;const r=new Error(`${e+t}ms exceeded`);r.timeout=t,r.code="ECONNABORTED",r.errno=n,this.timedout=!0,this.timedoutError=r,this.abort(),this.callback(r)},pi.prototype._setTimeouts=function(){const e=this;this._timeout&&!this._timer&&(this._timer=setTimeout((()=>{e._timeoutError("Timeout of ",e._timeout,"ETIME")}),this._timeout)),this._responseTimeout&&!this._responseTimeoutTimer&&(this._responseTimeoutTimer=setTimeout((()=>{e._timeoutError("Response timeout of ",e._responseTimeout,"ETIMEDOUT")}),this._responseTimeout))};const di=ai;var yi=gi;function gi(){}function mi(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return vi(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return vi(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,o=function(){};return{s:o,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:o}}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 i,a=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){s=!0,i=e},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw i}}}}function vi(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:i}}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 a,s=!0,u=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){u=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(u)throw a}}}}function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n{if(o.XMLHttpRequest)return new o.XMLHttpRequest;throw new Error("Browser-only version of superagent could not find XHR")};const g="".trim?e=>e.trim():e=>e.replace(/(^\s*|\s*$)/g,"");function m(e){if(!c(e))return e;const t=[];for(const n in e)p(e,n)&&v(t,n,e[n]);return t.join("&")}function v(e,t,r){if(void 0!==r)if(null!==r)if(Array.isArray(r)){var o,i=n(r);try{for(i.s();!(o=i.n()).done;){v(e,t,o.value)}}catch(e){i.e(e)}finally{i.f()}}else if(c(r))for(const n in r)p(r,n)&&v(e,`${t}[${n}]`,r[n]);else e.push(encodeURI(t)+"="+encodeURIComponent(r));else e.push(encodeURI(t))}function b(e){const t={},n=e.split("&");let r,o;for(let e=0,i=n.length;e{let e,t=null,r=null;try{r=new S(n)}catch(e){return t=new Error("Parser is unable to parse the response"),t.parse=!0,t.original=e,n.xhr?(t.rawResponse=void 0===n.xhr.responseType?n.xhr.responseText:n.xhr.response,t.status=n.xhr.status?n.xhr.status:null,t.statusCode=t.status):(t.rawResponse=null,t.status=null),n.callback(t)}n.emit("response",r);try{n._isResponseOK(r)||(e=new Error(r.statusText||r.text||"Unsuccessful HTTP response"))}catch(t){e=t}e?(e.original=t,e.response=r,e.status=e.status||r.status,n.callback(e,r)):n.callback(null,r)}))}y.serializeObject=m,y.parseString=b,y.types={html:"text/html",json:"application/json",xml:"text/xml",urlencoded:"application/x-www-form-urlencoded",form:"application/x-www-form-urlencoded","form-data":"application/x-www-form-urlencoded"},y.serialize={"application/x-www-form-urlencoded":s.stringify,"application/json":a},y.parse={"application/x-www-form-urlencoded":b,"application/json":JSON.parse},l(S.prototype,h.prototype),S.prototype._parseBody=function(e){let t=y.parse[this.type];return this.req._parser?this.req._parser(this,e):(!t&&_(this.type)&&(t=y.parse["application/json"]),t&&e&&(e.length>0||e instanceof Object)?t(e):null)},S.prototype.toError=function(){const e=this.req,t=e.method,n=e.url,r=`cannot ${t} ${n} (${this.status})`,o=new Error(r);return o.status=this.status,o.method=t,o.url=n,o},y.Response=S,i(w.prototype),l(w.prototype,u.prototype),w.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},w.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},w.prototype.auth=function(e,t,n){1===arguments.length&&(t=""),"object"==typeof t&&null!==t&&(n=t,t=""),n||(n={type:"function"==typeof btoa?"basic":"auto"});const r=n.encoder?n.encoder:e=>{if("function"==typeof btoa)return btoa(e);throw new Error("Cannot use basic auth, btoa is not a function")};return this._auth(e,t,n,r)},w.prototype.query=function(e){return"string"!=typeof e&&(e=m(e)),e&&this._query.push(e),this},w.prototype.attach=function(e,t,n){if(t){if(this._data)throw new Error("superagent can't mix .send() and .attach()");this._getFormData().append(e,t,n||t.name)}return this},w.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},w.prototype.callback=function(e,t){if(this._shouldRetry(e,t))return this._retry();const n=this._callback;this.clearTimeout(),e&&(this._maxRetries&&(e.retries=this._retries-1),this.emit("error",e)),n(e,t)},w.prototype.crossDomainError=function(){const e=new Error("Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.");e.crossDomain=!0,e.status=this.status,e.method=this.method,e.url=this.url,this.callback(e)},w.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},w.prototype.ca=w.prototype.agent,w.prototype.buffer=w.prototype.ca,w.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},w.prototype.pipe=w.prototype.write,w.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},w.prototype.end=function(e){this._endCalled&&console.warn("Warning: .end() was called twice. This is not supported in superagent"),this._endCalled=!0,this._callback=e||d,this._finalizeQueryString(),this._end()},w.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},w.prototype._end=function(){if(this._aborted)return this.callback(new Error("The request has been aborted even before .end() was called"));const e=this;this.xhr=y.getXHR();const t=this.xhr;let n=this._formData||this._data;this._setTimeouts(),t.addEventListener("readystatechange",(()=>{const n=t.readyState;if(n>=2&&e._responseTimeoutTimer&&clearTimeout(e._responseTimeoutTimer),4!==n)return;let r;try{r=t.status}catch(e){r=0}if(!r){if(e.timedout||e._aborted)return;return e.crossDomainError()}e.emit("end")}));const r=(t,n)=>{n.total>0&&(n.percent=n.loaded/n.total*100,100===n.percent&&clearTimeout(e._uploadTimeoutTimer)),n.direction=t,e.emit("progress",n)};if(this.hasListeners("progress"))try{t.addEventListener("progress",r.bind(null,"download")),t.upload&&t.upload.addEventListener("progress",r.bind(null,"upload"))}catch(e){}t.upload&&this._setUploadTimeout();try{this.username&&this.password?t.open(this.method,this.url,!0,this.username,this.password):t.open(this.method,this.url,!0)}catch(e){return this.callback(e)}if(this._withCredentials&&(t.withCredentials=!0),!this._formData&&"GET"!==this.method&&"HEAD"!==this.method&&"string"!=typeof n&&!this._isHost(n)){const e=this._header["content-type"];let t=this._serializer||y.serialize[e?e.split(";")[0]:""];!t&&_(e)&&(t=y.serialize["application/json"]),t&&(n=t(n))}for(const e in this.header)null!==this.header[e]&&p(this.header,e)&&t.setRequestHeader(e,this.header[e]);this._responseType&&(t.responseType=this._responseType),this.emit("request",this),t.send(void 0===n?null:n)},y.agent=()=>new f;for(var O=0,P=["GET","POST","OPTIONS","PATCH","PUT","DELETE"];O{const r=y("GET",e);return"function"==typeof t&&(n=t,t=null),t&&r.query(t),n&&r.end(n),r},y.head=(e,t,n)=>{const r=y("HEAD",e);return"function"==typeof t&&(n=t,t=null),t&&r.query(t),n&&r.end(n),r},y.options=(e,t,n)=>{const r=y("OPTIONS",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},y.del=E,y.delete=E,y.patch=(e,t,n)=>{const r=y("PATCH",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},y.post=(e,t,n)=>{const r=y("POST",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},y.put=(e,t,n)=>{const r=y("PUT",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r}}(gn,gn.exports);var Oi=gn.exports;function Pi(e){var t=(new Date).getTime(),n=(new Date).toISOString(),r=console&&console.log?console:window&&window.console&&window.console.log?window.console:console;r.log("<<<<<"),r.log("[".concat(n,"]"),"\n",e.url,"\n",e.qs),r.log("-----"),e.on("response",(function(n){var o=(new Date).getTime()-t,i=(new Date).toISOString();r.log(">>>>>>"),r.log("[".concat(i," / ").concat(o,"]"),"\n",e.url,"\n",e.qs,"\n",n.text),r.log("-----")}))}function Ei(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(Pi)),this._config.proxy&&this._modules.proxy&&(e=this._modules.proxy.call(this,e)),this._config.keepAlive&&this._modules.keepAlive&&(e=this._modules.keepAlive(e));var o=e;if(t.abortSignal)var i=t.abortSignal.subscribe((function(){o.abort(),i()}));return!0===t.forceBuffered?o="undefined"==typeof Blob?o.buffer().responseType("arraybuffer"):o.responseType("arraybuffer"):!1===t.forceBuffered&&(o=o.buffer(!1)),(o=o.timeout(t.timeout)).on("abort",(function(){return n({category:R.PNUnknownCategory,error:!0,operation:t.operation,errorData:new Error("Aborted")},null)})),o.end((function(e,o){var i,a={};if(a.error=null!==e,a.operation=t.operation,o&&o.status&&(a.statusCode=o.status),e){if(e.response&&e.response.text&&!r._config.logVerbosity)try{a.errorData=JSON.parse(e.response.text)}catch(t){a.errorData=e}else a.errorData=e;return a.category=r._detectErrorCategory(e),n(a,null)}if(t.ignoreBody)i={headers:o.headers,redirects:o.redirects,response:o};else try{i=JSON.parse(o.text)}catch(e){return a.errorData=o,a.error=!0,n(a,null)}return i.error&&1===i.error&&i.status&&i.message&&i.service?(a.errorData=i,a.statusCode=i.status,a.error=!0,a.category=r._detectErrorCategory(a),n(a,null)):(i.error&&i.error.message&&(a.errorData=i.error),n(a,i))})),o}function Ti(e,t,n){return o(this,void 0,void 0,(function(){var r;return i(this,(function(o){switch(o.label){case 0:return r=Oi.post(e),t.forEach((function(e){var t=e.key,n=e.value;r=r.field(t,n)})),r.attach("file",n,{contentType:"application/octet-stream"}),[4,r];case 1:return[2,o.sent()]}}))}))}function Ai(e,t,n){var r=Oi.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return Ei.call(this,r,t,n)}function Ci(e,t,n){var r=Oi.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return Ei.call(this,r,t,n)}function ki(e,t,n,r){var o=Oi.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return Ei.call(this,o,n,r)}function Ni(e,t,n,r){var o=Oi.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return Ei.call(this,o,n,r)}function Mi(e,t,n){var r=Oi.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return Ei.call(this,r,t,n)}function ji(e,t){var n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}var Ri,xi=function(){function e(){}return Object.defineProperty(e.prototype,"algo",{get:function(){return"aes-256-cbc"},enumerable:!1,configurable:!0}),e.prototype.encrypt=function(e,t){return o(this,void 0,void 0,(function(){var n;return i(this,(function(r){switch(r.label){case 0:return[4,this.getKey(e)];case 1:if(n=r.sent(),t instanceof ArrayBuffer)return[2,this.encryptArrayBuffer(n,t)];if("string"==typeof t)return[2,this.encryptString(n,t)];throw new Error("Cannot encrypt this file. In browsers file encryption supports only string or ArrayBuffer")}}))}))},e.prototype.decrypt=function(e,t){return o(this,void 0,void 0,(function(){var n;return i(this,(function(r){switch(r.label){case 0:return[4,this.getKey(e)];case 1:if(n=r.sent(),t instanceof ArrayBuffer)return[2,this.decryptArrayBuffer(n,t)];if("string"==typeof t)return[2,this.decryptString(n,t)];throw new Error("Cannot decrypt this file. In browsers file decryption supports only string or ArrayBuffer")}}))}))},e.prototype.encryptFile=function(e,t,n){return o(this,void 0,void 0,(function(){var r,o,a;return i(this,(function(i){switch(i.label){case 0:if(t.data.byteLength<=0)throw new Error("encryption error. empty content");return[4,this.getKey(e)];case 1:return r=i.sent(),[4,t.data.arrayBuffer()];case 2:return o=i.sent(),[4,this.encryptArrayBuffer(r,o)];case 3:return a=i.sent(),[2,n.create({name:t.name,mimeType:"application/octet-stream",data:a})]}}))}))},e.prototype.decryptFile=function(e,t,n){return o(this,void 0,void 0,(function(){var r,o,a;return i(this,(function(i){switch(i.label){case 0:return[4,this.getKey(e)];case 1:return r=i.sent(),[4,t.data.arrayBuffer()];case 2:return o=i.sent(),[4,this.decryptArrayBuffer(r,o)];case 3:return a=i.sent(),[2,n.create({name:t.name,data:a})]}}))}))},e.prototype.getKey=function(t){return o(this,void 0,void 0,(function(){var n,r,o;return i(this,(function(i){switch(i.label){case 0:return[4,crypto.subtle.digest("SHA-256",e.encoder.encode(t))];case 1:return n=i.sent(),r=Array.from(new Uint8Array(n)).map((function(e){return e.toString(16).padStart(2,"0")})).join(""),o=e.encoder.encode(r.slice(0,32)).buffer,[2,crypto.subtle.importKey("raw",o,"AES-CBC",!0,["encrypt","decrypt"])]}}))}))},e.prototype.encryptArrayBuffer=function(e,t){return o(this,void 0,void 0,(function(){var n,r,o;return i(this,(function(i){switch(i.label){case 0:return n=crypto.getRandomValues(new Uint8Array(16)),r=ji,o=[n.buffer],[4,crypto.subtle.encrypt({name:"AES-CBC",iv:n},e,t)];case 1:return[2,r.apply(void 0,o.concat([i.sent()]))]}}))}))},e.prototype.decryptArrayBuffer=function(t,n){return o(this,void 0,void 0,(function(){var r;return i(this,(function(o){switch(o.label){case 0:if(r=n.slice(0,16),n.slice(e.IV_LENGTH).byteLength<=0)throw new Error("decryption error: empty content");return[4,crypto.subtle.decrypt({name:"AES-CBC",iv:r},t,n.slice(e.IV_LENGTH))];case 1:return[2,o.sent()]}}))}))},e.prototype.encryptString=function(t,n){return o(this,void 0,void 0,(function(){var r,o,a,s;return i(this,(function(i){switch(i.label){case 0:return r=crypto.getRandomValues(new Uint8Array(16)),o=e.encoder.encode(n).buffer,[4,crypto.subtle.encrypt({name:"AES-CBC",iv:r},t,o)];case 1:return a=i.sent(),s=ji(r.buffer,a),[2,e.decoder.decode(s)]}}))}))},e.prototype.decryptString=function(t,n){return o(this,void 0,void 0,(function(){var r,o,a,s;return i(this,(function(i){switch(i.label){case 0:return r=e.encoder.encode(n).buffer,o=r.slice(0,16),a=r.slice(16),[4,crypto.subtle.decrypt({name:"AES-CBC",iv:o},t,a)];case 1:return s=i.sent(),[2,e.decoder.decode(s)]}}))}))},e.IV_LENGTH=16,e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),Ui=(Ri=function(){function e(e){if(e instanceof File)this.data=e,this.name=this.data.name,this.mimeType=this.data.type;else if(e.data){var t=e.data;this.data=new File([t],e.name,{type:e.mimeType}),this.name=e.name,e.mimeType&&(this.mimeType=e.mimeType)}if(void 0===this.data)throw new Error("Couldn't construct a file out of supplied options.");if(void 0===this.name)throw new Error("Couldn't guess filename out of the options. Please provide one.")}return e.create=function(e){return new this(e)},e.prototype.toBuffer=function(){return o(this,void 0,void 0,(function(){return i(this,(function(e){throw new Error("This feature is only supported in Node.js environments.")}))}))},e.prototype.toStream=function(){return o(this,void 0,void 0,(function(){return i(this,(function(e){throw new Error("This feature is only supported in Node.js environments.")}))}))},e.prototype.toFileUri=function(){return o(this,void 0,void 0,(function(){return i(this,(function(e){throw new Error("This feature is only supported in react native environments.")}))}))},e.prototype.toBlob=function(){return o(this,void 0,void 0,(function(){return i(this,(function(e){return[2,this.data]}))}))},e.prototype.toArrayBuffer=function(){return o(this,void 0,void 0,(function(){var e=this;return i(this,(function(t){return[2,new Promise((function(t,n){var r=new FileReader;r.addEventListener("load",(function(){if(r.result instanceof ArrayBuffer)return t(r.result)})),r.addEventListener("error",(function(){n(r.error)})),r.readAsArrayBuffer(e.data)}))]}))}))},e.prototype.toString=function(){return o(this,void 0,void 0,(function(){var e=this;return i(this,(function(t){return[2,new Promise((function(t,n){var r=new FileReader;r.addEventListener("load",(function(){if("string"==typeof r.result)return t(r.result)})),r.addEventListener("error",(function(){n(r.error)})),r.readAsBinaryString(e.data)}))]}))}))},e.prototype.toFile=function(){return o(this,void 0,void 0,(function(){return i(this,(function(e){return[2,this.data]}))}))},e}(),Ri.supportsFile="undefined"!=typeof File,Ri.supportsBlob="undefined"!=typeof Blob,Ri.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,Ri.supportsBuffer=!1,Ri.supportsStream=!1,Ri.supportsString=!0,Ri.supportsEncryptFile=!0,Ri.supportsFileUri=!1,Ri),Ii=function(){function e(e){this.config=e,this.cryptor=new A({config:e}),this.fileCryptor=new xi}return Object.defineProperty(e.prototype,"identifier",{get:function(){return""},enumerable:!1,configurable:!0}),e.prototype.encrypt=function(e){var t="string"==typeof e?e:(new TextDecoder).decode(e);return{data:this.cryptor.encrypt(t),metadata:null}},e.prototype.decrypt=function(e){var t="string"==typeof e.data?e.data:v(e.data);return this.cryptor.decrypt(t)},e.prototype.encryptFile=function(e,t){var n;return o(this,void 0,void 0,(function(){return i(this,(function(r){return[2,this.fileCryptor.encryptFile(null===(n=this.config)||void 0===n?void 0:n.cipherKey,e,t)]}))}))},e.prototype.decryptFile=function(e,t){return o(this,void 0,void 0,(function(){return i(this,(function(n){return[2,this.fileCryptor.decryptFile(this.config.cipherKey,e,t)]}))}))},e}(),Di=function(){function e(e){this.cipherKey=e.cipherKey,this.CryptoJS=E,this.encryptedKey=this.CryptoJS.SHA256(this.cipherKey)}return Object.defineProperty(e.prototype,"algo",{get:function(){return"AES-CBC"},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"identifier",{get:function(){return"ACRH"},enumerable:!1,configurable:!0}),e.prototype.getIv=function(){return crypto.getRandomValues(new Uint8Array(e.BLOCK_SIZE))},e.prototype.getKey=function(){return o(this,void 0,void 0,(function(){var t,n;return i(this,(function(r){switch(r.label){case 0:return t=e.encoder.encode(this.cipherKey),[4,crypto.subtle.digest("SHA-256",t.buffer)];case 1:return n=r.sent(),[2,crypto.subtle.importKey("raw",n,this.algo,!0,["encrypt","decrypt"])]}}))}))},e.prototype.encrypt=function(t){if(0===("string"==typeof t?t:e.decoder.decode(t)).length)throw new Error("encryption error. empty content");var n=this.getIv();return{metadata:n,data:m(this.CryptoJS.AES.encrypt(t,this.encryptedKey,{iv:this.bufferToWordArray(n),mode:this.CryptoJS.mode.CBC}).ciphertext.toString(this.CryptoJS.enc.Base64))}},e.prototype.decrypt=function(t){var n=this.bufferToWordArray(new Uint8ClampedArray(t.metadata)),r=this.bufferToWordArray(new Uint8ClampedArray(t.data));return e.encoder.encode(this.CryptoJS.AES.decrypt({ciphertext:r},this.encryptedKey,{iv:n,mode:this.CryptoJS.mode.CBC}).toString(this.CryptoJS.enc.Utf8)).buffer},e.prototype.encryptFileData=function(e){return o(this,void 0,void 0,(function(){var t,n,r;return i(this,(function(o){switch(o.label){case 0:return[4,this.getKey()];case 1:return t=o.sent(),n=this.getIv(),r={},[4,crypto.subtle.encrypt({name:this.algo,iv:n},t,e)];case 2:return[2,(r.data=o.sent(),r.metadata=n,r)]}}))}))},e.prototype.decryptFileData=function(e){return o(this,void 0,void 0,(function(){var t;return i(this,(function(n){switch(n.label){case 0:return[4,this.getKey()];case 1:return t=n.sent(),[2,crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)]}}))}))},e.prototype.bufferToWordArray=function(e){var t,n=[];for(t=0;t0?t.slice(n.length-n.metadataLength,n.length):null;if(t.slice(n.length).byteLength<=0)throw new Error("decryption error. empty content");return r.decrypt({data:t.slice(n.length),metadata:o})},e.prototype.encryptFile=function(e,t){return o(this,void 0,void 0,(function(){var n,r;return i(this,(function(o){switch(o.label){case 0:return this.defaultCryptor.identifier===Gi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:[4,this.getFileData(e.data)];case 1:return n=o.sent(),[4,this.defaultCryptor.encryptFileData(n)];case 2:return r=o.sent(),[2,t.create({name:e.name,mimeType:"application/octet-stream",data:this.concatArrayBuffer(this.getHeaderData(r),r.data)})]}}))}))},e.prototype.decryptFile=function(t,n){return o(this,void 0,void 0,(function(){var r,o,a,s,u,c,l,p;return i(this,(function(i){switch(i.label){case 0:return[4,t.data.arrayBuffer()];case 1:return r=i.sent(),o=Gi.tryParse(r),(null==(a=this.getCryptor(o))?void 0:a.identifier)===e.LEGACY_IDENTIFIER?[2,a.decryptFile(t,n)]:[4,this.getFileData(r)];case 2:return s=i.sent(),u=s.slice(o.length-o.metadataLength,o.length),l=(c=n).create,p={name:t.name},[4,this.defaultCryptor.decryptFileData({data:r.slice(o.length),metadata:u})];case 3:return[2,l.apply(c,[(p.data=i.sent(),p)])]}}))}))},e.prototype.getCryptor=function(e){if(""===e){var t=this.getAllCryptors().find((function(e){return""===e.identifier}));if(t)return t;throw new Error("unknown cryptor error")}if(e instanceof Li)return this.getCryptorFromId(e.identifier)},e.prototype.getCryptorFromId=function(e){var t=this.getAllCryptors().find((function(t){return e===t.identifier}));if(t)return t;throw Error("unknown cryptor error")},e.prototype.concatArrayBuffer=function(e,t){var n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer},e.prototype.getHeaderData=function(e){if(e.metadata){var t=Gi.from(this.defaultCryptor.identifier,e.metadata),n=new Uint8Array(t.length),r=0;return n.set(t.data,r),r+=t.length-e.metadata.byteLength,n.set(new Uint8Array(e.metadata),r),n.buffer}},e.prototype.getFileData=function(t){return o(this,void 0,void 0,(function(){return i(this,(function(n){switch(n.label){case 0:return t instanceof Blob?[4,t.arrayBuffer()]:[3,2];case 1:return[2,n.sent()];case 2:if(t instanceof ArrayBuffer)return[2,t];if("string"==typeof t)return[2,e.encoder.encode(t)];throw new Error("Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob")}}))}))},e.LEGACY_IDENTIFIER="",e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),Gi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new Li(t,n.byteLength)},e.tryParse=function(t){var n=new Uint8Array(t),r="";if(n.byteLength>=4&&(r=n.slice(0,4),this.decoder.decode(r)!==e.SENTINEL))return"";if(!(n.byteLength>=5))throw new Error("decryption error. invalid header version");if(n[4]>e.MAX_VERSION)throw new Error("unknown cryptor error");var o="",i=5+e.IDENTIFIER_LENGTH;if(!(n.byteLength>=i))throw new Error("decryption error. invalid crypto identifier");o=n.slice(5,i);var a=null;if(!(n.byteLength>=i+1))throw new Error("decryption error. invalid metadata length");return a=n[i],i+=1,255===a&&n.byteLength>=i+2&&(a=new Uint16Array(n.slice(i,i+2)).reduce((function(e,t){return(e<<8)+t}),0),i+=2),new Li(this.decoder.decode(o),a)},e.SENTINEL="PNED",e.LEGACY_IDENTIFIER="",e.IDENTIFIER_LENGTH=4,e.VERSION=1,e.MAX_VERSION=1,e.decoder=new TextDecoder,e}(),Li=function(){function e(e,t){this._identifier=e,this._metadataLength=t}return Object.defineProperty(e.prototype,"identifier",{get:function(){return this._identifier},set:function(e){this._identifier=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"metadataLength",{get:function(){return this._metadataLength},set:function(e){this._metadataLength=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"version",{get:function(){return Gi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return Gi.SENTINEL.length+1+Gi.IDENTIFIER_LENGTH+(this.metadataLength<255?1:3)+this.metadataLength},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"data",{get:function(){var e=0,t=new Uint8Array(this.length),n=new TextEncoder;t.set(n.encode(Gi.SENTINEL)),t[e+=Gi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=Gi.IDENTIFIER_LENGTH;var r=this.metadataLength;return r<255?t[e]=r:t.set([255,r>>8,255&r],e),t},enumerable:!1,configurable:!0}),e.IDENTIFIER_LENGTH=4,e.SENTINEL="PNED",e}();function Ki(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var Bi=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new fn({del:Mi,get:Ci,post:ki,patch:Ni,sendBeacon:Ki,getfile:Ai,postfile:Ti}),t.cbor=new yn((function(e){return dn(h.decode(e))}),m),t.PubNubFile=Ui,t.cryptography=new xi,t.initCryptoModule=function(e){return new Fi({default:new Ii({cipherKey:e.cipherKey,useRandomIVs:e.useRandomIVs}),cryptors:[new Di({cipherKey:e.cipherKey})]})},n=e.call(this,t)||this,o&&(window.addEventListener("offline",(function(){n.networkDownDetected()})),window.addEventListener("online",(function(){n.networkUpDetected()}))),n}return t(n,e),n.CryptoModule=Fi,n}(hn);return Bi})); +!function(e,t){!function(e){var t="0.1.0",n={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};function r(){var e,t,n="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(n+="-"),n+=(12===e?4:16===e?3&t|8:t).toString(16);return n}function o(e,t){var r=n[t||"all"];return r&&r.test(e)||!1}r.isUUID=o,r.VERSION=t,e.uuid=r,e.isUUID=o}(t),null!==e&&(e.exports=t.uuid)}(f,f.exports);var d=f.exports,y=function(){return d.uuid?d.uuid():d()},g=function(){function e(e){var t,n,r,o,i=e.setup;if(this._PNSDKSuffix={},this.instanceId="pn-".concat(y()),this.secretKey=i.secretKey||i.secret_key,this.subscribeKey=i.subscribeKey||i.subscribe_key,this.publishKey=i.publishKey||i.publish_key,this.sdkName=i.sdkName,this.sdkFamily=i.sdkFamily,this.partnerId=i.partnerId,this.setAuthKey(i.authKey),this.cryptoModule=i.cryptoModule,this.setFilterExpression(i.filterExpression),"string"!=typeof i.origin&&!Array.isArray(i.origin)&&void 0!==i.origin)throw new Error("Origin must be either undefined, a string or a list of strings.");if(this.origin=i.origin||Array.from({length:20},(function(e,t){return"ps".concat(t+1,".pndsn.com")})),this.secure=i.ssl||!1,this.restore=i.restore||!1,this.proxy=i.proxy,this.keepAlive=i.keepAlive,this.keepAliveSettings=i.keepAliveSettings,this.autoNetworkDetection=i.autoNetworkDetection||!1,this.dedupeOnSubscribe=i.dedupeOnSubscribe||!1,this.maximumCacheSize=i.maximumCacheSize||100,this.customEncrypt=i.customEncrypt,this.customDecrypt=i.customDecrypt,this.fileUploadPublishRetryLimit=null!==(t=i.fileUploadPublishRetryLimit)&&void 0!==t?t:5,this.useRandomIVs=null===(n=i.useRandomIVs)||void 0===n||n,this.enableEventEngine=null!==(r=i.enableEventEngine)&&void 0!==r&&r,this.maintainPresenceState=null===(o=i.maintainPresenceState)||void 0===o||o,"undefined"!=typeof location&&"https:"===location.protocol&&(this.secure=!0),this.logVerbosity=i.logVerbosity||!1,this.suppressLeaveEvents=i.suppressLeaveEvents||!1,this.announceFailedHeartbeats=i.announceFailedHeartbeats||!0,this.announceSuccessfulHeartbeats=i.announceSuccessfulHeartbeats||!1,this.useInstanceId=i.useInstanceId||!1,this.useRequestId=i.useRequestId||!1,this.requestMessageCountThreshold=i.requestMessageCountThreshold,i.retryConfiguration&&this._setRetryConfiguration(i.retryConfiguration),this.setTransactionTimeout(i.transactionalRequestTimeout||15e3),this.setSubscribeTimeout(i.subscribeRequestTimeout||31e4),this.setSendBeaconConfig(i.useSendBeacon||!0),i.presenceTimeout?this.setPresenceTimeout(i.presenceTimeout):this._presenceTimeout=300,null!=i.heartbeatInterval&&this.setHeartbeatInterval(i.heartbeatInterval),"string"==typeof i.userId){if("string"==typeof i.uuid)throw new Error("Only one of the following configuration options has to be provided: `uuid` or `userId`");this.setUserId(i.userId)}else{if("string"!=typeof i.uuid)throw new Error("One of the following configuration options has to be provided: `uuid` or `userId`");this.setUUID(i.uuid)}this.setCipherKey(i.cipherKey,i)}return e.prototype.getAuthKey=function(){return this.authKey},e.prototype.setAuthKey=function(e){return this.authKey=e,this},e.prototype.setCipherKey=function(e,t,n){var r;return this.cipherKey=e,this.cipherKey&&(this.cryptoModule=null!==(r=t.cryptoModule)&&void 0!==r?r:t.initCryptoModule({cipherKey:this.cipherKey,useRandomIVs:this.useRandomIVs}),n&&(n.cryptoModule=this.cryptoModule)),this},e.prototype.getUUID=function(){return this.UUID},e.prototype.setUUID=function(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing uuid parameter. Provide a valid string uuid");return this.UUID=e,this},e.prototype.getUserId=function(){return this.UUID},e.prototype.setUserId=function(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");return this.UUID=e,this},e.prototype.getFilterExpression=function(){return this.filterExpression},e.prototype.setFilterExpression=function(e){return this.filterExpression=e,this},e.prototype.getPresenceTimeout=function(){return this._presenceTimeout},e.prototype.setPresenceTimeout=function(e){return e>=20?this._presenceTimeout=e:(this._presenceTimeout=20,console.log("WARNING: Presence timeout is less than the minimum. Using minimum value: ",this._presenceTimeout)),this.setHeartbeatInterval(this._presenceTimeout/2-1),this},e.prototype.setProxy=function(e){this.proxy=e},e.prototype.getHeartbeatInterval=function(){return this._heartbeatInterval},e.prototype.setHeartbeatInterval=function(e){return this._heartbeatInterval=e,this},e.prototype.getSubscribeTimeout=function(){return this._subscribeRequestTimeout},e.prototype.setSubscribeTimeout=function(e){return this._subscribeRequestTimeout=e,this},e.prototype.getTransactionTimeout=function(){return this._transactionalRequestTimeout},e.prototype.setTransactionTimeout=function(e){return this._transactionalRequestTimeout=e,this},e.prototype.isSendBeaconEnabled=function(){return this._useSendBeacon},e.prototype.setSendBeaconConfig=function(e){return this._useSendBeacon=e,this},e.prototype.getVersion=function(){return"7.6.0"},e.prototype._setRetryConfiguration=function(e){if(e.minimumdelay<2)throw new Error("Minimum delay can not be set less than 2 seconds for retry");if(e.maximumDelay>150)throw new Error("Maximum delay can not be set more than 150 seconds for retry");if(e.maximumDelay&&maximumRetry>6)throw new Error("Maximum retry for exponential retry policy can not be more than 6");if(e.maximumRetry>10)throw new Error("Maximum retry for linear retry policy can not be more than 10");this.retryConfiguration=e},e.prototype._addPnsdkSuffix=function(e,t){this._PNSDKSuffix[e]=t},e.prototype._getPnsdkSuffix=function(e){var t=this;return Object.keys(this._PNSDKSuffix).reduce((function(n,r){return n+e+t._PNSDKSuffix[r]}),"")},e}();function m(e){var t=e.replace(/==?$/,""),n=Math.floor(t.length/4*3),r=new ArrayBuffer(n),o=new Uint8Array(r),i=0;function s(){var e=t.charAt(i++),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e);if(-1===n)throw new Error("Illegal character at ".concat(i,": ").concat(t.charAt(i-1)));return n}for(var a=0;a>4,f=(15&c)<<4|l>>2,d=(3&l)<<6|p>>0;o[a]=h,64!=l&&(o[a+1]=f),64!=p&&(o[a+2]=d)}return r}function b(e){for(var t,n="",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=new Uint8Array(e),i=o.byteLength,s=i%3,a=i-s,u=0;u>18]+r[(258048&t)>>12]+r[(4032&t)>>6]+r[63&t];return 1==s?n+=r[(252&(t=o[a]))>>2]+r[(3&t)<<4]+"==":2==s&&(n+=r[(64512&(t=o[a]<<8|o[a+1]))>>10]+r[(1008&t)>>4]+r[(15&t)<<2]+"="),n}var v,_,S,w,O,P=P||function(e,t){var n={},r=n.lib={},o=function(){},i=r.Base={extend:function(e){o.prototype=this;var t=new o;return e&&t.mixIn(e),t.hasOwnProperty("init")||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},s=r.WordArray=i.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||u).stringify(this)},concat:function(e){var t=this.words,n=e.words,r=this.sigBytes;if(e=e.sigBytes,this.clamp(),r%4)for(var o=0;o>>2]|=(n[o>>>2]>>>24-o%4*8&255)<<24-(r+o)%4*8;else if(65535>>2]=n[o>>>2];else t.push.apply(t,n);return this.sigBytes+=e,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n=[],r=0;r>>2]>>>24-r%4*8&255;n.push((o>>>4).toString(16)),n.push((15&o).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new s.init(n,t/2)}},c=a.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],r=0;r>>2]>>>24-r%4*8&255));return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new s.init(n,t)}},l=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},p=r.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=l.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,r=n.words,o=n.sigBytes,i=this.blockSize,a=o/(4*i);if(t=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*i,o=e.min(4*t,o),t){for(var u=0;uc;){var l;e:{l=u;for(var p=e.sqrt(l),h=2;h<=p;h++)if(!(l%h)){l=!1;break e}l=!0}l&&(8>c&&(i[c]=a(e.pow(u,.5))),s[c]=a(e.pow(u,1/3)),c++),u++}var f=[];o=o.SHA256=r.extend({_doReset:function(){this._hash=new n.init(i.slice(0))},_doProcessBlock:function(e,t){for(var n=this._hash.words,r=n[0],o=n[1],i=n[2],a=n[3],u=n[4],c=n[5],l=n[6],p=n[7],h=0;64>h;h++){if(16>h)f[h]=0|e[t+h];else{var d=f[h-15],y=f[h-2];f[h]=((d<<25|d>>>7)^(d<<14|d>>>18)^d>>>3)+f[h-7]+((y<<15|y>>>17)^(y<<13|y>>>19)^y>>>10)+f[h-16]}d=p+((u<<26|u>>>6)^(u<<21|u>>>11)^(u<<7|u>>>25))+(u&c^~u&l)+s[h]+f[h],y=((r<<30|r>>>2)^(r<<19|r>>>13)^(r<<10|r>>>22))+(r&o^r&i^o&i),p=l,l=c,c=u,u=a+d|0,a=i,i=o,o=r,r=d+y|0}n[0]=n[0]+r|0,n[1]=n[1]+o|0,n[2]=n[2]+i|0,n[3]=n[3]+a|0,n[4]=n[4]+u|0,n[5]=n[5]+c|0,n[6]=n[6]+l|0,n[7]=n[7]+p|0},_doFinalize:function(){var t=this._data,n=t.words,r=8*this._nDataBytes,o=8*t.sigBytes;return n[o>>>5]|=128<<24-o%32,n[14+(o+64>>>9<<4)]=e.floor(r/4294967296),n[15+(o+64>>>9<<4)]=r,t.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=r._createHelper(o),t.HmacSHA256=r._createHmacHelper(o)}(Math),_=(v=P).enc.Utf8,v.algo.HMAC=v.lib.Base.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=_.parse(t));var n=e.blockSize,r=4*n;t.sigBytes>r&&(t=e.finalize(t)),t.clamp();for(var o=this._oKey=t.clone(),i=this._iKey=t.clone(),s=o.words,a=i.words,u=0;u>>2]>>>24-o%4*8&255)<<16|(t[o+1>>>2]>>>24-(o+1)%4*8&255)<<8|t[o+2>>>2]>>>24-(o+2)%4*8&255,s=0;4>s&&o+.75*s>>6*(3-s)&63));if(t=r.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var t=e.length,n=this._map;(r=n.charAt(64))&&-1!=(r=e.indexOf(r))&&(t=r);for(var r=[],o=0,i=0;i>>6-i%4*2;r[o>>>2]|=(s|a)<<24-o%4*8,o++}return w.create(r,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},function(e){function t(e,t,n,r,o,i,s){return((e=e+(t&n|~t&r)+o+s)<>>32-i)+t}function n(e,t,n,r,o,i,s){return((e=e+(t&r|n&~r)+o+s)<>>32-i)+t}function r(e,t,n,r,o,i,s){return((e=e+(t^n^r)+o+s)<>>32-i)+t}function o(e,t,n,r,o,i,s){return((e=e+(n^(t|~r))+o+s)<>>32-i)+t}for(var i=P,s=(u=i.lib).WordArray,a=u.Hasher,u=i.algo,c=[],l=0;64>l;l++)c[l]=4294967296*e.abs(e.sin(l+1))|0;u=u.MD5=a.extend({_doReset:function(){this._hash=new s.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,i){for(var s=0;16>s;s++){var a=e[u=i+s];e[u]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8)}s=this._hash.words;var u=e[i+0],l=(a=e[i+1],e[i+2]),p=e[i+3],h=e[i+4],f=e[i+5],d=e[i+6],y=e[i+7],g=e[i+8],m=e[i+9],b=e[i+10],v=e[i+11],_=e[i+12],S=e[i+13],w=e[i+14],O=e[i+15],P=t(P=s[0],T=s[1],A=s[2],E=s[3],u,7,c[0]),E=t(E,P,T,A,a,12,c[1]),A=t(A,E,P,T,l,17,c[2]),T=t(T,A,E,P,p,22,c[3]);P=t(P,T,A,E,h,7,c[4]),E=t(E,P,T,A,f,12,c[5]),A=t(A,E,P,T,d,17,c[6]),T=t(T,A,E,P,y,22,c[7]),P=t(P,T,A,E,g,7,c[8]),E=t(E,P,T,A,m,12,c[9]),A=t(A,E,P,T,b,17,c[10]),T=t(T,A,E,P,v,22,c[11]),P=t(P,T,A,E,_,7,c[12]),E=t(E,P,T,A,S,12,c[13]),A=t(A,E,P,T,w,17,c[14]),P=n(P,T=t(T,A,E,P,O,22,c[15]),A,E,a,5,c[16]),E=n(E,P,T,A,d,9,c[17]),A=n(A,E,P,T,v,14,c[18]),T=n(T,A,E,P,u,20,c[19]),P=n(P,T,A,E,f,5,c[20]),E=n(E,P,T,A,b,9,c[21]),A=n(A,E,P,T,O,14,c[22]),T=n(T,A,E,P,h,20,c[23]),P=n(P,T,A,E,m,5,c[24]),E=n(E,P,T,A,w,9,c[25]),A=n(A,E,P,T,p,14,c[26]),T=n(T,A,E,P,g,20,c[27]),P=n(P,T,A,E,S,5,c[28]),E=n(E,P,T,A,l,9,c[29]),A=n(A,E,P,T,y,14,c[30]),P=r(P,T=n(T,A,E,P,_,20,c[31]),A,E,f,4,c[32]),E=r(E,P,T,A,g,11,c[33]),A=r(A,E,P,T,v,16,c[34]),T=r(T,A,E,P,w,23,c[35]),P=r(P,T,A,E,a,4,c[36]),E=r(E,P,T,A,h,11,c[37]),A=r(A,E,P,T,y,16,c[38]),T=r(T,A,E,P,b,23,c[39]),P=r(P,T,A,E,S,4,c[40]),E=r(E,P,T,A,u,11,c[41]),A=r(A,E,P,T,p,16,c[42]),T=r(T,A,E,P,d,23,c[43]),P=r(P,T,A,E,m,4,c[44]),E=r(E,P,T,A,_,11,c[45]),A=r(A,E,P,T,O,16,c[46]),P=o(P,T=r(T,A,E,P,l,23,c[47]),A,E,u,6,c[48]),E=o(E,P,T,A,y,10,c[49]),A=o(A,E,P,T,w,15,c[50]),T=o(T,A,E,P,f,21,c[51]),P=o(P,T,A,E,_,6,c[52]),E=o(E,P,T,A,p,10,c[53]),A=o(A,E,P,T,b,15,c[54]),T=o(T,A,E,P,a,21,c[55]),P=o(P,T,A,E,g,6,c[56]),E=o(E,P,T,A,O,10,c[57]),A=o(A,E,P,T,d,15,c[58]),T=o(T,A,E,P,S,21,c[59]),P=o(P,T,A,E,h,6,c[60]),E=o(E,P,T,A,v,10,c[61]),A=o(A,E,P,T,l,15,c[62]),T=o(T,A,E,P,m,21,c[63]);s[0]=s[0]+P|0,s[1]=s[1]+T|0,s[2]=s[2]+A|0,s[3]=s[3]+E|0},_doFinalize:function(){var t=this._data,n=t.words,r=8*this._nDataBytes,o=8*t.sigBytes;n[o>>>5]|=128<<24-o%32;var i=e.floor(r/4294967296);for(n[15+(o+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),n[14+(o+64>>>9<<4)]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8),t.sigBytes=4*(n.length+1),this._process(),n=(t=this._hash).words,r=0;4>r;r++)o=n[r],n[r]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8);return t},clone:function(){var e=a.clone.call(this);return e._hash=this._hash.clone(),e}}),i.MD5=a._createHelper(u),i.HmacMD5=a._createHmacHelper(u)}(Math),function(){var e,t=P,n=(e=t.lib).Base,r=e.WordArray,o=(e=t.algo).EvpKDF=n.extend({cfg:n.extend({keySize:4,hasher:e.MD5,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var n=(a=this.cfg).hasher.create(),o=r.create(),i=o.words,s=a.keySize,a=a.iterations;i.length>>2]}},t.BlockCipher=a.extend({cfg:a.cfg.extend({mode:u,padding:l}),reset:function(){a.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var n=t.createEncryptor;else n=t.createDecryptor,this._minBufferSize=1;this._mode=n.call(t,this,e&&e.words)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else t=this._process(!0),e.unpad(t);return t},blockSize:4});var p=t.CipherParams=n.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),h=(u=(f.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?r.create([1398893684,1701076831]).concat(e).concat(t):t).toString(i)},parse:function(e){var t=(e=i.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var n=r.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return p.create({ciphertext:e,salt:n})}},t.SerializableCipher=n.extend({cfg:n.extend({format:u}),encrypt:function(e,t,n,r){r=this.cfg.extend(r);var o=e.createEncryptor(n,r);return t=o.finalize(t),o=o.cfg,p.create({ciphertext:t,key:n,iv:o.iv,algorithm:e,mode:o.mode,padding:o.padding,blockSize:e.blockSize,formatter:r.format})},decrypt:function(e,t,n,r){return r=this.cfg.extend(r),t=this._parse(t,r.format),e.createDecryptor(n,r).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),f=(f.kdf={}).OpenSSL={execute:function(e,t,n,o){return o||(o=r.random(8)),e=s.create({keySize:t+n}).compute(e,o),n=r.create(e.words.slice(t),4*n),e.sigBytes=4*t,p.create({key:e,iv:n,salt:o})}},d=t.PasswordBasedCipher=h.extend({cfg:h.cfg.extend({kdf:f}),encrypt:function(e,t,n,r){return n=(r=this.cfg.extend(r)).kdf.execute(n,e.keySize,e.ivSize),r.iv=n.iv,(e=h.encrypt.call(this,e,t,n.key,r)).mixIn(n),e},decrypt:function(e,t,n,r){return r=this.cfg.extend(r),t=this._parse(t,r.format),n=r.kdf.execute(n,e.keySize,e.ivSize,t.salt),r.iv=n.iv,h.decrypt.call(this,e,t,n.key,r)}})}(),function(){for(var e=P,t=e.lib.BlockCipher,n=e.algo,r=[],o=[],i=[],s=[],a=[],u=[],c=[],l=[],p=[],h=[],f=[],d=0;256>d;d++)f[d]=128>d?d<<1:d<<1^283;var y=0,g=0;for(d=0;256>d;d++){var m=(m=g^g<<1^g<<2^g<<3^g<<4)>>>8^255&m^99;r[y]=m,o[m]=y;var b=f[y],v=f[b],_=f[v],S=257*f[m]^16843008*m;i[y]=S<<24|S>>>8,s[y]=S<<16|S>>>16,a[y]=S<<8|S>>>24,u[y]=S,S=16843009*_^65537*v^257*b^16843008*y,c[m]=S<<24|S>>>8,l[m]=S<<16|S>>>16,p[m]=S<<8|S>>>24,h[m]=S,y?(y=b^f[f[f[_^b]]],g^=f[f[g]]):y=g=1}var w=[0,1,2,4,8,16,32,64,128,27,54];n=n.AES=t.extend({_doReset:function(){for(var e=(n=this._key).words,t=n.sigBytes/4,n=4*((this._nRounds=t+6)+1),o=this._keySchedule=[],i=0;i>>24]<<24|r[s>>>16&255]<<16|r[s>>>8&255]<<8|r[255&s]):(s=r[(s=s<<8|s>>>24)>>>24]<<24|r[s>>>16&255]<<16|r[s>>>8&255]<<8|r[255&s],s^=w[i/t|0]<<24),o[i]=o[i-t]^s}for(e=this._invKeySchedule=[],t=0;tt||4>=i?s:c[r[s>>>24]]^l[r[s>>>16&255]]^p[r[s>>>8&255]]^h[r[255&s]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,i,s,a,u,r)},decryptBlock:function(e,t){var n=e[t+1];e[t+1]=e[t+3],e[t+3]=n,this._doCryptBlock(e,t,this._invKeySchedule,c,l,p,h,o),n=e[t+1],e[t+1]=e[t+3],e[t+3]=n},_doCryptBlock:function(e,t,n,r,o,i,s,a){for(var u=this._nRounds,c=e[t]^n[0],l=e[t+1]^n[1],p=e[t+2]^n[2],h=e[t+3]^n[3],f=4,d=1;d>>24]^o[l>>>16&255]^i[p>>>8&255]^s[255&h]^n[f++],g=r[l>>>24]^o[p>>>16&255]^i[h>>>8&255]^s[255&c]^n[f++],m=r[p>>>24]^o[h>>>16&255]^i[c>>>8&255]^s[255&l]^n[f++];h=r[h>>>24]^o[c>>>16&255]^i[l>>>8&255]^s[255&p]^n[f++],c=y,l=g,p=m}y=(a[c>>>24]<<24|a[l>>>16&255]<<16|a[p>>>8&255]<<8|a[255&h])^n[f++],g=(a[l>>>24]<<24|a[p>>>16&255]<<16|a[h>>>8&255]<<8|a[255&c])^n[f++],m=(a[p>>>24]<<24|a[h>>>16&255]<<16|a[c>>>8&255]<<8|a[255&l])^n[f++],h=(a[h>>>24]<<24|a[c>>>16&255]<<16|a[l>>>8&255]<<8|a[255&p])^n[f++],e[t]=y,e[t+1]=g,e[t+2]=m,e[t+3]=h},keySize:8});e.AES=t._createHelper(n)}(),P.mode.ECB=((O=P.lib.BlockCipherMode.extend()).Encryptor=O.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),O.Decryptor=O.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),O);var E=P;function A(e){var t,n=[];for(t=0;t=this._config.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))},e.prototype.clearHistory=function(){this.hashHistory=[]},e}(),k={PNNetworkUpCategory:"PNNetworkUpCategory",PNNetworkDownCategory:"PNNetworkDownCategory",PNNetworkIssuesCategory:"PNNetworkIssuesCategory",PNTimeoutCategory:"PNTimeoutCategory",PNBadRequestCategory:"PNBadRequestCategory",PNAccessDeniedCategory:"PNAccessDeniedCategory",PNUnknownCategory:"PNUnknownCategory",PNReconnectedCategory:"PNReconnectedCategory",PNConnectedCategory:"PNConnectedCategory",PNRequestMessageCountExceededCategory:"PNRequestMessageCountExceededCategory",PNDisconnectedCategory:"PNDisconnectedCategory",PNConnectionErrorCategory:"PNConnectionErrorCategory",PNDisconnectedUnexpectedlyCategory:"PNDisconnectedUnexpectedlyCategory"},M=function(){function e(e){var t=e.subscribeEndpoint,n=e.leaveEndpoint,r=e.heartbeatEndpoint,o=e.setStateEndpoint,i=e.timeEndpoint,s=e.getFileUrl,a=e.config,u=e.crypto,c=e.listenerManager,l=e.cryptoModule,p=e.eventEmitter;this._listenerManager=c,this._config=a,this._leaveEndpoint=n,this._heartbeatEndpoint=r,this._setStateEndpoint=o,this._subscribeEndpoint=t,this._getFileUrl=s,this._crypto=u,this._cryptoModule=l,this._channels={},this._presenceChannels={},this._heartbeatChannels={},this._heartbeatChannelGroups={},this._channelGroups={},this._presenceChannelGroups={},this._pendingChannelSubscriptions=[],this._pendingChannelGroupSubscriptions=[],this._currentTimetoken=0,this._lastTimetoken=0,this._storedTimetoken=null,this._subscriptionStatusAnnounced=!1,this._isOnline=!0,this._reconnectionManager=new N({timeEndpoint:i}),this._dedupingManager=new C({config:a}),this._cryptoModule&&(this._decoder=new TextDecoder),this._eventEmitter=p}return e.prototype.adaptStateChange=function(e,t){var n=this,r=e.state,o=e.channels,i=void 0===o?[]:o,s=e.channelGroups,a=void 0===s?[]:s,u=e.withHeartbeat,c=void 0!==u&&u;if(i.forEach((function(e){e in n._channels&&(n._channels[e].state=r)})),a.forEach((function(e){e in n._channelGroups&&(n._channelGroups[e].state=r)})),c){var l={};return i.forEach((function(e){return l[e]=r})),a.forEach((function(e){return l[e]=r})),this._heartbeatEndpoint({channels:i,channelGroups:a,state:l},t)}return this._setStateEndpoint({state:r,channels:i,channelGroups:a},t)},e.prototype.adaptPresenceChange=function(e){var t=this,n=e.connected,r=e.channels,o=void 0===r?[]:r,i=e.channelGroups,s=void 0===i?[]:i;n?(o.forEach((function(e){t._heartbeatChannels[e]={state:{}}})),s.forEach((function(e){t._heartbeatChannelGroups[e]={state:{}}}))):(o.forEach((function(e){e in t._heartbeatChannels&&delete t._heartbeatChannels[e]})),s.forEach((function(e){e in t._heartbeatChannelGroups&&delete t._heartbeatChannelGroups[e]})),!1===this._config.suppressLeaveEvents&&this._leaveEndpoint({channels:o,channelGroups:s},(function(e){t._listenerManager.announceStatus(e)}))),this.reconnect()},e.prototype.adaptSubscribeChange=function(e){var t=this,n=e.timetoken,r=e.channels,o=void 0===r?[]:r,i=e.channelGroups,s=void 0===i?[]:i,a=e.withPresence,u=void 0!==a&&a,c=e.withHeartbeats,l=void 0!==c&&c;this._config.subscribeKey&&""!==this._config.subscribeKey?(n&&(this._lastTimetoken=this._currentTimetoken,this._currentTimetoken=n),"0"!==this._currentTimetoken&&0!==this._currentTimetoken&&(this._storedTimetoken=this._currentTimetoken,this._currentTimetoken=0),o.forEach((function(e){t._channels[e]={state:{}},u&&(t._presenceChannels[e]={}),(l||t._config.getHeartbeatInterval())&&(t._heartbeatChannels[e]={}),t._pendingChannelSubscriptions.push(e)})),s.forEach((function(e){t._channelGroups[e]={state:{}},u&&(t._presenceChannelGroups[e]={}),(l||t._config.getHeartbeatInterval())&&(t._heartbeatChannelGroups[e]={}),t._pendingChannelGroupSubscriptions.push(e)})),this._subscriptionStatusAnnounced=!1,this.reconnect()):console&&console.log&&console.log("subscribe key missing; aborting subscribe")},e.prototype.adaptUnsubscribeChange=function(e,t){var n=this,r=e.channels,o=void 0===r?[]:r,i=e.channelGroups,s=void 0===i?[]:i,a=[],u=[];o.forEach((function(e){e in n._channels&&(delete n._channels[e],a.push(e),e in n._heartbeatChannels&&delete n._heartbeatChannels[e]),e in n._presenceChannels&&(delete n._presenceChannels[e],a.push(e))})),s.forEach((function(e){e in n._channelGroups&&(delete n._channelGroups[e],u.push(e),e in n._heartbeatChannelGroups&&delete n._heartbeatChannelGroups[e]),e in n._presenceChannelGroups&&(delete n._presenceChannelGroups[e],u.push(e))})),0===a.length&&0===u.length||(!1!==this._config.suppressLeaveEvents||t||this._leaveEndpoint({channels:a,channelGroups:u},(function(e){e.affectedChannels=a,e.affectedChannelGroups=u,e.currentTimetoken=n._currentTimetoken,e.lastTimetoken=n._lastTimetoken,n._listenerManager.announceStatus(e)})),0===Object.keys(this._channels).length&&0===Object.keys(this._presenceChannels).length&&0===Object.keys(this._channelGroups).length&&0===Object.keys(this._presenceChannelGroups).length&&(this._lastTimetoken=0,this._currentTimetoken=0,this._storedTimetoken=null,this._region=null,this._reconnectionManager.stopPolling()),this.reconnect())},e.prototype.unsubscribeAll=function(e){this.adaptUnsubscribeChange({channels:this.getSubscribedChannels(),channelGroups:this.getSubscribedChannelGroups()},e)},e.prototype.getHeartbeatChannels=function(){return Object.keys(this._heartbeatChannels)},e.prototype.getHeartbeatChannelGroups=function(){return Object.keys(this._heartbeatChannelGroups)},e.prototype.getSubscribedChannels=function(){return Object.keys(this._channels)},e.prototype.getSubscribedChannelGroups=function(){return Object.keys(this._channelGroups)},e.prototype.reconnect=function(){this._startSubscribeLoop(),this._registerHeartbeatTimer()},e.prototype.disconnect=function(){this._stopSubscribeLoop(),this._stopHeartbeatTimer(),this._reconnectionManager.stopPolling()},e.prototype._registerHeartbeatTimer=function(){this._stopHeartbeatTimer(),0!==this._config.getHeartbeatInterval()&&void 0!==this._config.getHeartbeatInterval()&&(this._performHeartbeatLoop(),this._heartbeatTimer=setInterval(this._performHeartbeatLoop.bind(this),1e3*this._config.getHeartbeatInterval()))},e.prototype._stopHeartbeatTimer=function(){this._heartbeatTimer&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=null)},e.prototype._performHeartbeatLoop=function(){var e=this,t=this.getHeartbeatChannels(),n=this.getHeartbeatChannelGroups(),r={};if(0!==t.length||0!==n.length){this.getSubscribedChannels().forEach((function(t){var n=e._channels[t].state;Object.keys(n).length&&(r[t]=n)})),this.getSubscribedChannelGroups().forEach((function(t){var n=e._channelGroups[t].state;Object.keys(n).length&&(r[t]=n)}));this._heartbeatEndpoint({channels:t,channelGroups:n,state:r},function(t){t.error&&e._config.announceFailedHeartbeats&&e._listenerManager.announceStatus(t),t.error&&e._config.autoNetworkDetection&&e._isOnline&&(e._isOnline=!1,e.disconnect(),e._listenerManager.announceNetworkDown(),e.reconnect()),!t.error&&e._config.announceSuccessfulHeartbeats&&e._listenerManager.announceStatus(t)}.bind(this))}},e.prototype._startSubscribeLoop=function(){var e=this;this._stopSubscribeLoop();var t={},n=[],r=[];if(Object.keys(this._channels).forEach((function(r){var o=e._channels[r].state;Object.keys(o).length&&(t[r]=o),n.push(r)})),Object.keys(this._presenceChannels).forEach((function(e){n.push("".concat(e,"-pnpres"))})),Object.keys(this._channelGroups).forEach((function(n){var o=e._channelGroups[n].state;Object.keys(o).length&&(t[n]=o),r.push(n)})),Object.keys(this._presenceChannelGroups).forEach((function(e){r.push("".concat(e,"-pnpres"))})),0!==n.length||0!==r.length){var o={channels:n,channelGroups:r,state:t,timetoken:this._currentTimetoken,filterExpression:this._config.filterExpression,region:this._region};this._subscribeCall=this._subscribeEndpoint(o,this._processSubscribeResponse.bind(this))}},e.prototype._processSubscribeResponse=function(e,t){var n=this;if(e.error){if(e.errorData&&"Aborted"===e.errorData.message)return;e.category===k.PNTimeoutCategory?this._startSubscribeLoop():e.category===k.PNNetworkIssuesCategory?(this.disconnect(),e.error&&this._config.autoNetworkDetection&&this._isOnline&&(this._isOnline=!1,this._listenerManager.announceNetworkDown()),this._reconnectionManager.onReconnection((function(){n._config.autoNetworkDetection&&!n._isOnline&&(n._isOnline=!0,n._listenerManager.announceNetworkUp()),n.reconnect(),n._subscriptionStatusAnnounced=!0;var t={category:k.PNReconnectedCategory,operation:e.operation,lastTimetoken:n._lastTimetoken,currentTimetoken:n._currentTimetoken};n._listenerManager.announceStatus(t)})),this._reconnectionManager.startPolling(),this._listenerManager.announceStatus(e)):e.category===k.PNBadRequestCategory?(this._stopHeartbeatTimer(),this._listenerManager.announceStatus(e)):this._listenerManager.announceStatus(e)}else{if(this._storedTimetoken?(this._currentTimetoken=this._storedTimetoken,this._storedTimetoken=null):(this._lastTimetoken=this._currentTimetoken,this._currentTimetoken=t.metadata.timetoken),!this._subscriptionStatusAnnounced){var r={};r.category=k.PNConnectedCategory,r.operation=e.operation,r.affectedChannels=this._pendingChannelSubscriptions,r.subscribedChannels=this.getSubscribedChannels(),r.affectedChannelGroups=this._pendingChannelGroupSubscriptions,r.lastTimetoken=this._lastTimetoken,r.currentTimetoken=this._currentTimetoken,this._subscriptionStatusAnnounced=!0,this._listenerManager.announceStatus(r),this._pendingChannelSubscriptions=[],this._pendingChannelGroupSubscriptions=[]}var o=t.messages||[],i=this._config,s=i.requestMessageCountThreshold,a=i.dedupeOnSubscribe;if(s&&o.length>=s){var u={};u.category=k.PNRequestMessageCountExceededCategory,u.operation=e.operation,this._listenerManager.announceStatus(u)}o.forEach((function(e){if(e.channel,e.subscriptionMatch,a){if(n._dedupingManager.isDuplicate(e))return;n._dedupingManager.addEntry(e)}n._eventEmitter.emitEvent(e)})),this._region=t.metadata.region,this._startSubscribeLoop()}},e.prototype._stopSubscribeLoop=function(){this._subscribeCall&&("function"==typeof this._subscribeCall.abort&&this._subscribeCall.abort(),this._subscribeCall=null)},e.prototype._renameEvent=function(e){return"set"===e?"updated":"removed"},e.prototype._renameChannelField=function(e){var t=e.channel,n=r(e,["channel"]);return n.spaceId=t,n},e}(),j={PNTimeOperation:"PNTimeOperation",PNHistoryOperation:"PNHistoryOperation",PNDeleteMessagesOperation:"PNDeleteMessagesOperation",PNFetchMessagesOperation:"PNFetchMessagesOperation",PNMessageCounts:"PNMessageCountsOperation",PNSubscribeOperation:"PNSubscribeOperation",PNUnsubscribeOperation:"PNUnsubscribeOperation",PNPublishOperation:"PNPublishOperation",PNSignalOperation:"PNSignalOperation",PNAddMessageActionOperation:"PNAddActionOperation",PNRemoveMessageActionOperation:"PNRemoveMessageActionOperation",PNGetMessageActionsOperation:"PNGetMessageActionsOperation",PNCreateUserOperation:"PNCreateUserOperation",PNUpdateUserOperation:"PNUpdateUserOperation",PNDeleteUserOperation:"PNDeleteUserOperation",PNGetUserOperation:"PNGetUsersOperation",PNGetUsersOperation:"PNGetUsersOperation",PNCreateSpaceOperation:"PNCreateSpaceOperation",PNUpdateSpaceOperation:"PNUpdateSpaceOperation",PNDeleteSpaceOperation:"PNDeleteSpaceOperation",PNGetSpaceOperation:"PNGetSpacesOperation",PNGetSpacesOperation:"PNGetSpacesOperation",PNGetMembersOperation:"PNGetMembersOperation",PNUpdateMembersOperation:"PNUpdateMembersOperation",PNGetMembershipsOperation:"PNGetMembershipsOperation",PNUpdateMembershipsOperation:"PNUpdateMembershipsOperation",PNListFilesOperation:"PNListFilesOperation",PNGenerateUploadUrlOperation:"PNGenerateUploadUrlOperation",PNPublishFileOperation:"PNPublishFileOperation",PNGetFileUrlOperation:"PNGetFileUrlOperation",PNDownloadFileOperation:"PNDownloadFileOperation",PNGetAllUUIDMetadataOperation:"PNGetAllUUIDMetadataOperation",PNGetUUIDMetadataOperation:"PNGetUUIDMetadataOperation",PNSetUUIDMetadataOperation:"PNSetUUIDMetadataOperation",PNRemoveUUIDMetadataOperation:"PNRemoveUUIDMetadataOperation",PNGetAllChannelMetadataOperation:"PNGetAllChannelMetadataOperation",PNGetChannelMetadataOperation:"PNGetChannelMetadataOperation",PNSetChannelMetadataOperation:"PNSetChannelMetadataOperation",PNRemoveChannelMetadataOperation:"PNRemoveChannelMetadataOperation",PNSetMembersOperation:"PNSetMembersOperation",PNSetMembershipsOperation:"PNSetMembershipsOperation",PNPushNotificationEnabledChannelsOperation:"PNPushNotificationEnabledChannelsOperation",PNRemoveAllPushNotificationsOperation:"PNRemoveAllPushNotificationsOperation",PNWhereNowOperation:"PNWhereNowOperation",PNSetStateOperation:"PNSetStateOperation",PNHereNowOperation:"PNHereNowOperation",PNGetStateOperation:"PNGetStateOperation",PNHeartbeatOperation:"PNHeartbeatOperation",PNChannelGroupsOperation:"PNChannelGroupsOperation",PNRemoveGroupOperation:"PNRemoveGroupOperation",PNChannelsForGroupOperation:"PNChannelsForGroupOperation",PNAddChannelsToGroupOperation:"PNAddChannelsToGroupOperation",PNRemoveChannelsFromGroupOperation:"PNRemoveChannelsFromGroupOperation",PNAccessManagerGrant:"PNAccessManagerGrant",PNAccessManagerGrantToken:"PNAccessManagerGrantToken",PNAccessManagerAudit:"PNAccessManagerAudit",PNAccessManagerRevokeToken:"PNAccessManagerRevokeToken",PNHandshakeOperation:"PNHandshakeOperation",PNReceiveMessagesOperation:"PNReceiveMessagesOperation"},R=function(){function e(e){this._maximumSamplesCount=100,this._trackedLatencies={},this._latencies={},this._telemetryExcludeOperations=[j.PNSubscribeOperation,j.PNReceiveMessagesOperation,j.PNHandshakeOperation],this._maximumSamplesCount=e.maximumSamplesCount||this._maximumSamplesCount}return e.prototype.operationsLatencyForRequest=function(){var e=this,t={};return Object.keys(this._latencies).forEach((function(n){var r=e._latencies[n],o=e._averageLatency(r);o>0&&(t["l_".concat(n)]=o)})),t},e.prototype.startLatencyMeasure=function(e,t){!this._telemetryExcludeOperations.includes(e)&&t&&(this._trackedLatencies[t]=Date.now())},e.prototype.stopLatencyMeasure=function(e,t){if(!this._telemetryExcludeOperations.includes(e)&&t){var n=this._endpointName(e),r=this._latencies[n],o=this._trackedLatencies[t];r||(this._latencies[n]=[],r=this._latencies[n]),r.push(Date.now()-o),r.length>this._maximumSamplesCount&&r.splice(0,r.length-this._maximumSamplesCount),delete this._trackedLatencies[t]}},e.prototype._averageLatency=function(e){return Math.floor(e.reduce((function(e,t){return e+t}),0)/e.length)},e.prototype._endpointName=function(e){var t=null;switch(e){case j.PNPublishOperation:t="pub";break;case j.PNSignalOperation:t="sig";break;case j.PNHistoryOperation:case j.PNFetchMessagesOperation:case j.PNDeleteMessagesOperation:case j.PNMessageCounts:t="hist";break;case j.PNUnsubscribeOperation:case j.PNWhereNowOperation:case j.PNHereNowOperation:case j.PNHeartbeatOperation:case j.PNSetStateOperation:case j.PNGetStateOperation:t="pres";break;case j.PNAddChannelsToGroupOperation:case j.PNRemoveChannelsFromGroupOperation:case j.PNChannelGroupsOperation:case j.PNRemoveGroupOperation:case j.PNChannelsForGroupOperation:t="cg";break;case j.PNPushNotificationEnabledChannelsOperation:case j.PNRemoveAllPushNotificationsOperation:t="push";break;case j.PNCreateUserOperation:case j.PNUpdateUserOperation:case j.PNDeleteUserOperation:case j.PNGetUserOperation:case j.PNGetUsersOperation:case j.PNCreateSpaceOperation:case j.PNUpdateSpaceOperation:case j.PNDeleteSpaceOperation:case j.PNGetSpaceOperation:case j.PNGetSpacesOperation:case j.PNGetMembersOperation:case j.PNUpdateMembersOperation:case j.PNGetMembershipsOperation:case j.PNUpdateMembershipsOperation:t="obj";break;case j.PNAddMessageActionOperation:case j.PNRemoveMessageActionOperation:case j.PNGetMessageActionsOperation:t="msga";break;case j.PNAccessManagerGrant:case j.PNAccessManagerAudit:t="pam";break;case j.PNAccessManagerGrantToken:case j.PNAccessManagerRevokeToken:t="pamv3";break;default:t="time"}return t},e}(),x=function(){function e(e,t,n){this._payload=e,this._setDefaultPayloadStructure(),this.title=t,this.body=n}return Object.defineProperty(e.prototype,"payload",{get:function(){return this._payload},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"title",{set:function(e){this._title=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"subtitle",{set:function(e){this._subtitle=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"body",{set:function(e){this._body=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"badge",{set:function(e){this._badge=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sound",{set:function(e){this._sound=e},enumerable:!1,configurable:!0}),e.prototype._setDefaultPayloadStructure=function(){},e.prototype.toObject=function(){return{}},e}(),U=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return t(r,e),Object.defineProperty(r.prototype,"configurations",{set:function(e){e&&e.length&&(this._configurations=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"notification",{get:function(){return this._payload.aps},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"title",{get:function(){return this._title},set:function(e){e&&e.length&&(this._payload.aps.alert.title=e,this._title=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"subtitle",{get:function(){return this._subtitle},set:function(e){e&&e.length&&(this._payload.aps.alert.subtitle=e,this._subtitle=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"body",{get:function(){return this._body},set:function(e){e&&e.length&&(this._payload.aps.alert.body=e,this._body=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"badge",{get:function(){return this._badge},set:function(e){null!=e&&(this._payload.aps.badge=e,this._badge=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"sound",{get:function(){return this._sound},set:function(e){e&&e.length&&(this._payload.aps.sound=e,this._sound=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"silent",{set:function(e){this._isSilent=e},enumerable:!1,configurable:!0}),r.prototype._setDefaultPayloadStructure=function(){this._payload.aps={alert:{}}},r.prototype.toObject=function(){var e=this,t=n({},this._payload),r=t.aps,o=r.alert;if(this._isSilent&&(r["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");var i=[];this._configurations.forEach((function(t){i.push(e._objectFromAPNS2Configuration(t))})),i.length&&(t.pn_push=i)}return o&&Object.keys(o).length||delete r.alert,this._isSilent&&(delete r.alert,delete r.badge,delete r.sound,o={}),this._isSilent||Object.keys(o).length?t:null},r.prototype._objectFromAPNS2Configuration=function(e){var t=this;if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");var n=[];e.targets.forEach((function(e){n.push(t._objectFromAPNSTarget(e))}));var r=e.collapseId,o=e.expirationDate,i={auth_method:"token",targets:n,version:"v2"};return r&&r.length&&(i.collapse_id=r),o&&(i.expiration=o.toISOString()),i},r.prototype._objectFromAPNSTarget=function(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");var t=e.topic,n=e.environment,r=void 0===n?"development":n,o=e.excludedDevices,i=void 0===o?[]:o,s={topic:t,environment:r};return i.length&&(s.excluded_devices=i),s},r}(x),I=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return t(r,e),Object.defineProperty(r.prototype,"backContent",{get:function(){return this._backContent},set:function(e){e&&e.length&&(this._payload.back_content=e,this._backContent=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"backTitle",{get:function(){return this._backTitle},set:function(e){e&&e.length&&(this._payload.back_title=e,this._backTitle=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},set:function(e){null!=e&&(this._payload.count=e,this._count=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"title",{get:function(){return this._title},set:function(e){e&&e.length&&(this._payload.title=e,this._title=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"type",{get:function(){return this._type},set:function(e){e&&e.length&&(this._payload.type=e,this._type=e)},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"subtitle",{get:function(){return this.backTitle},set:function(e){this.backTitle=e},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"body",{get:function(){return this.backContent},set:function(e){this.backContent=e},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"badge",{get:function(){return this.count},set:function(e){this.count=e},enumerable:!1,configurable:!0}),r.prototype.toObject=function(){return Object.keys(this._payload).length?n({},this._payload):null},r}(x),D=function(e){function o(){return null!==e&&e.apply(this,arguments)||this}return t(o,e),Object.defineProperty(o.prototype,"notification",{get:function(){return this._payload.notification},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"data",{get:function(){return this._payload.data},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"title",{get:function(){return this._title},set:function(e){e&&e.length&&(this._payload.notification.title=e,this._title=e)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"body",{get:function(){return this._body},set:function(e){e&&e.length&&(this._payload.notification.body=e,this._body=e)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"sound",{get:function(){return this._sound},set:function(e){e&&e.length&&(this._payload.notification.sound=e,this._sound=e)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"icon",{get:function(){return this._icon},set:function(e){e&&e.length&&(this._payload.notification.icon=e,this._icon=e)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"tag",{get:function(){return this._tag},set:function(e){e&&e.length&&(this._payload.notification.tag=e,this._tag=e)},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"silent",{set:function(e){this._isSilent=e},enumerable:!1,configurable:!0}),o.prototype._setDefaultPayloadStructure=function(){this._payload.notification={},this._payload.data={}},o.prototype.toObject=function(){var e=n({},this._payload.data),t=null,o={};if(Object.keys(this._payload).length>2){var i=this._payload;i.notification,i.data;var s=r(i,["notification","data"]);e=n(n({},e),s)}return this._isSilent?e.notification=this._payload.notification:t=this._payload.notification,Object.keys(e).length&&(o.data=e),t&&Object.keys(t).length&&(o.notification=t),Object.keys(o).length?o:null},o}(x),F=function(){function e(e,t){this._payload={apns:{},mpns:{},fcm:{}},this._title=e,this._body=t,this.apns=new U(this._payload.apns,e,t),this.mpns=new I(this._payload.mpns,e,t),this.fcm=new D(this._payload.fcm,e,t)}return Object.defineProperty(e.prototype,"debugging",{set:function(e){this._debugging=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"title",{get:function(){return this._title},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"body",{get:function(){return this._body},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"subtitle",{get:function(){return this._subtitle},set:function(e){this._subtitle=e,this.apns.subtitle=e,this.mpns.subtitle=e,this.fcm.subtitle=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"badge",{get:function(){return this._badge},set:function(e){this._badge=e,this.apns.badge=e,this.mpns.badge=e,this.fcm.badge=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sound",{get:function(){return this._sound},set:function(e){this._sound=e,this.apns.sound=e,this.mpns.sound=e,this.fcm.sound=e},enumerable:!1,configurable:!0}),e.prototype.buildPayload=function(e){var t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";var n=this.apns.toObject();n&&Object.keys(n).length&&(t.pn_apns=n)}if(e.includes("mpns")){var r=this.mpns.toObject();r&&Object.keys(r).length&&(t.pn_mpns=r)}if(e.includes("fcm")){var o=this.fcm.toObject();o&&Object.keys(o).length&&(t.pn_gcm=o)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t},e}(),L=function(){function e(){this._listeners=[]}return e.prototype.addListener=function(e){this._listeners.includes(e)||this._listeners.push(e)},e.prototype.removeListener=function(e){var t=[];this._listeners.forEach((function(n){n!==e&&t.push(n)})),this._listeners=t},e.prototype.removeAllListeners=function(){this._listeners=[]},e.prototype.announcePresence=function(e){this._listeners.forEach((function(t){t.presence&&t.presence(e)}))},e.prototype.announceStatus=function(e){this._listeners.forEach((function(t){t.status&&t.status(e)}))},e.prototype.announceMessage=function(e){this._listeners.forEach((function(t){t.message&&t.message(e)}))},e.prototype.announceSignal=function(e){this._listeners.forEach((function(t){t.signal&&t.signal(e)}))},e.prototype.announceMessageAction=function(e){this._listeners.forEach((function(t){t.messageAction&&t.messageAction(e)}))},e.prototype.announceFile=function(e){this._listeners.forEach((function(t){t.file&&t.file(e)}))},e.prototype.announceObjects=function(e){this._listeners.forEach((function(t){t.objects&&t.objects(e)}))},e.prototype.announceUser=function(e){this._listeners.forEach((function(t){t.user&&t.user(e)}))},e.prototype.announceSpace=function(e){this._listeners.forEach((function(t){t.space&&t.space(e)}))},e.prototype.announceMembership=function(e){this._listeners.forEach((function(t){t.membership&&t.membership(e)}))},e.prototype.announceNetworkUp=function(){var e={};e.category=k.PNNetworkUpCategory,this.announceStatus(e)},e.prototype.announceNetworkDown=function(){var e={};e.category=k.PNNetworkDownCategory,this.announceStatus(e)},e}(),G=function(){function e(e,t){this._config=e,this._cbor=t}return e.prototype.setToken=function(e){e&&e.length>0?this._token=e:this._token=void 0},e.prototype.getToken=function(){return this._token},e.prototype.extractPermissions=function(e){var t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128==(128&e)&&(t.join=!0),64==(64&e)&&(t.update=!0),32==(32&e)&&(t.get=!0),8==(8&e)&&(t.delete=!0),4==(4&e)&&(t.manage=!0),2==(2&e)&&(t.write=!0),1==(1&e)&&(t.read=!0),t},e.prototype.parseToken=function(e){var t=this,n=this._cbor.decodeToken(e);if(void 0!==n){var r=n.res.uuid?Object.keys(n.res.uuid):[],o=Object.keys(n.res.chan),i=Object.keys(n.res.grp),s=n.pat.uuid?Object.keys(n.pat.uuid):[],a=Object.keys(n.pat.chan),u=Object.keys(n.pat.grp),c={version:n.v,timestamp:n.t,ttl:n.ttl,authorized_uuid:n.uuid},l=r.length>0,p=o.length>0,h=i.length>0;(l||p||h)&&(c.resources={},l&&(c.resources.uuids={},r.forEach((function(e){c.resources.uuids[e]=t.extractPermissions(n.res.uuid[e])}))),p&&(c.resources.channels={},o.forEach((function(e){c.resources.channels[e]=t.extractPermissions(n.res.chan[e])}))),h&&(c.resources.groups={},i.forEach((function(e){c.resources.groups[e]=t.extractPermissions(n.res.grp[e])}))));var f=s.length>0,d=a.length>0,y=u.length>0;return(f||d||y)&&(c.patterns={},f&&(c.patterns.uuids={},s.forEach((function(e){c.patterns.uuids[e]=t.extractPermissions(n.pat.uuid[e])}))),d&&(c.patterns.channels={},a.forEach((function(e){c.patterns.channels[e]=t.extractPermissions(n.pat.chan[e])}))),y&&(c.patterns.groups={},u.forEach((function(e){c.patterns.groups[e]=t.extractPermissions(n.pat.grp[e])})))),Object.keys(n.meta).length>0&&(c.meta=n.meta),c.signature=n.sig,c}},e}();function K(e){return encodeURIComponent(e).replace(/[!~*'()]/g,(function(e){return"%".concat(e.charCodeAt(0).toString(16).toUpperCase())}))}function B(e){return function(e){var t=[];return Object.keys(e).forEach((function(e){return t.push(e)})),t}(e).sort()}var H={signPamFromParams:function(e){return B(e).map((function(t){return"".concat(t,"=").concat(K(e[t]))})).join("&")},endsWith:function(e,t){return-1!==e.indexOf(t,this.length-t.length)},createPromise:function(){var e,t;return{promise:new Promise((function(n,r){e=n,t=r})),reject:t,fulfill:e}},encodeString:K,stringToArrayBuffer:function(e){for(var t=new ArrayBuffer(2*e.length),n=new Uint16Array(t),r=0,o=e.length;r0&&(t+=n),t}function J(e,t,n){return t.usePost&&t.usePost(e,n)?"POST":t.usePatch&&t.usePatch(e,n)?"PATCH":t.useDelete&&t.useDelete(e,n)?"DELETE":t.useGetFile&&t.useGetFile(e,n)?"GETFILE":"GET"}function $(e,t,n,r,o){var i=e.config,s=e.crypto,a=J(e,o,r);n.timestamp=Math.floor((new Date).getTime()/1e3),"PNPublishOperation"===o.getOperation()&&o.usePost&&o.usePost(e,r)&&(a="GET"),"GETFILE"===a&&(a="GET");var u="".concat(a,"\n").concat(i.publishKey,"\n").concat(t,"\n").concat(H.signPamFromParams(n),"\n");if("POST"===a)u+="string"==typeof(c=o.postPayload(e,r))?c:JSON.stringify(c);else if("PATCH"===a){var c;u+="string"==typeof(c=o.patchPayload(e,r))?c:JSON.stringify(c)}var l="v2.".concat(s.HMACSHA256(u));l=(l=(l=l.replace(/\+/g,"-")).replace(/\//g,"_")).replace(/=+$/,""),n.signature=l}function Q(e,t){for(var r=[],o=2;o0?o.join(","):",";return"/v2/presence/sub-key/".concat(n.subscribeKey,"/channel/").concat(H.encodeString(i),"/leave")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.channelGroups,r=void 0===n?[]:n,o={};return r.length>0&&(o["channel-group"]=r.join(",")),o},handleResponse:function(){return{}}});var ae=Object.freeze({__proto__:null,getOperation:function(){return j.PNWhereNowOperation},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.uuid,o=void 0===r?n.UUID:r;return"/v2/presence/sub-key/".concat(n.subscribeKey,"/uuid/").concat(H.encodeString(o))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return t.payload?{channels:t.payload.channels}:{channels:[]}}});var ue=Object.freeze({__proto__:null,getOperation:function(){return j.PNHeartbeatOperation},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.channels,o=void 0===r?[]:r,i=o.length>0?o.join(","):",";return"/v2/presence/sub-key/".concat(n.subscribeKey,"/channel/").concat(H.encodeString(i),"/heartbeat")},isAuthSupported:function(){return!0},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},prepareParams:function(e,t){var n=t.channelGroups,r=void 0===n?[]:n,o=t.state,i=e.config,s={};return r.length>0&&(s["channel-group"]=r.join(",")),o&&(s.state=JSON.stringify(o)),s.heartbeat=i.getPresenceTimeout(),s},handleResponse:function(){return{}}});var ce=Object.freeze({__proto__:null,getOperation:function(){return j.PNGetStateOperation},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.uuid,o=void 0===r?n.UUID:r,i=t.channels,s=void 0===i?[]:i,a=s.length>0?s.join(","):",";return"/v2/presence/sub-key/".concat(n.subscribeKey,"/channel/").concat(H.encodeString(a),"/uuid/").concat(o)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.channelGroups,r=void 0===n?[]:n,o={};return r.length>0&&(o["channel-group"]=r.join(",")),o},handleResponse:function(e,t,n){var r=n.channels,o=void 0===r?[]:r,i=n.channelGroups,s=void 0===i?[]:i,a={};return 1===o.length&&0===s.length?a[o[0]]=t.payload:a=t.payload,{channels:a}}});var le=Object.freeze({__proto__:null,getOperation:function(){return j.PNSetStateOperation},validateParams:function(e,t){var n=e.config,r=t.state,o=t.channels,i=void 0===o?[]:o,s=t.channelGroups,a=void 0===s?[]:s;return r?n.subscribeKey?0===i.length&&0===a.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key":"Missing State"},getURL:function(e,t){var n=e.config,r=t.channels,o=void 0===r?[]:r,i=o.length>0?o.join(","):",";return"/v2/presence/sub-key/".concat(n.subscribeKey,"/channel/").concat(H.encodeString(i),"/uuid/").concat(H.encodeString(n.UUID),"/data")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.state,r=t.channelGroups,o=void 0===r?[]:r,i={};return i.state=JSON.stringify(n),o.length>0&&(i["channel-group"]=o.join(",")),i},handleResponse:function(e,t){return{state:t.payload}}});var pe=Object.freeze({__proto__:null,getOperation:function(){return j.PNHereNowOperation},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.channels,o=void 0===r?[]:r,i=t.channelGroups,s=void 0===i?[]:i,a="/v2/presence/sub-key/".concat(n.subscribeKey);if(o.length>0||s.length>0){var u=o.length>0?o.join(","):",";a+="/channel/".concat(H.encodeString(u))}return a},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var r=t.channelGroups,o=void 0===r?[]:r,i=t.includeUUIDs,s=void 0===i||i,a=t.includeState,u=void 0!==a&&a,c=t.queryParameters,l=void 0===c?{}:c,p={};return s||(p.disable_uuids=1),u&&(p.state=1),o.length>0&&(p["channel-group"]=o.join(",")),p=n(n({},p),l)},handleResponse:function(e,t,n){var r=n.channels,o=void 0===r?[]:r,i=n.channelGroups,s=void 0===i?[]:i,a=n.includeUUIDs,u=void 0===a||a,c=n.includeState,l=void 0!==c&&c;return o.length>1||s.length>0||0===s.length&&0===o.length?function(){var e={};return e.totalChannels=t.payload.total_channels,e.totalOccupancy=t.payload.total_occupancy,e.channels={},Object.keys(t.payload.channels).forEach((function(n){var r=t.payload.channels[n],o=[];return e.channels[n]={occupants:o,name:n,occupancy:r.occupancy},u&&r.uuids.forEach((function(e){l?o.push({state:e.state,uuid:e.uuid}):o.push({state:null,uuid:e})})),e})),e}():function(){var e={},n=[];return e.totalChannels=1,e.totalOccupancy=t.occupancy,e.channels={},e.channels[o[0]]={occupants:n,name:o[0],occupancy:t.occupancy},u&&t.uuids&&t.uuids.forEach((function(e){l?n.push({state:e.state,uuid:e.uuid}):n.push({state:null,uuid:e})})),e}()},handleError:function(e,t,n){402!==n.statusCode||this.getURL(e,t).includes("channel")||(n.errorData.message="You have tried to perform a Global Here Now operation, your keyset configuration does not support that. Please provide a channel, or enable the Global Here Now feature from the Portal.")}});var he=Object.freeze({__proto__:null,getOperation:function(){return j.PNAddMessageActionOperation},validateParams:function(e,t){var n=e.config,r=t.action,o=t.channel;return t.messageTimetoken?n.subscribeKey?o?r?r.value?r.type?r.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message channel":"Missing Subscribe Key":"Missing message timetoken"},usePost:function(){return!0},postURL:function(e,t){var n=e.config,r=t.channel,o=t.messageTimetoken;return"/v1/message-actions/".concat(n.subscribeKey,"/channel/").concat(H.encodeString(r),"/message/").concat(o)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},getRequestHeaders:function(){return{"Content-Type":"application/json"}},isAuthSupported:function(){return!0},prepareParams:function(){return{}},postPayload:function(e,t){return t.action},handleResponse:function(e,t){return{data:t.data}}});var fe=Object.freeze({__proto__:null,getOperation:function(){return j.PNRemoveMessageActionOperation},validateParams:function(e,t){var n=e.config,r=t.channel,o=t.actionTimetoken;return t.messageTimetoken?o?n.subscribeKey?r?void 0:"Missing message channel":"Missing Subscribe Key":"Missing action timetoken":"Missing message timetoken"},useDelete:function(){return!0},getURL:function(e,t){var n=e.config,r=t.channel,o=t.actionTimetoken,i=t.messageTimetoken;return"/v1/message-actions/".concat(n.subscribeKey,"/channel/").concat(H.encodeString(r),"/message/").concat(i,"/action/").concat(o)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{data:t.data}}});var de=Object.freeze({__proto__:null,getOperation:function(){return j.PNGetMessageActionsOperation},validateParams:function(e,t){var n=e.config,r=t.channel;return n.subscribeKey?r?void 0:"Missing message channel":"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.channel;return"/v1/message-actions/".concat(n.subscribeKey,"/channel/").concat(H.encodeString(r))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.limit,r=t.start,o=t.end,i={};return n&&(i.limit=n),r&&(i.start=r),o&&(i.end=o),i},handleResponse:function(e,t){var n={data:t.data,start:null,end:null};return n.data.length&&(n.end=n.data[n.data.length-1].actionTimetoken,n.start=n.data[0].actionTimetoken),n}}),ye={getOperation:function(){return j.PNListFilesOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channel))return"channel can't be empty"},getURL:function(e,t){var n=e.config;return"/v1/files/".concat(n.subscribeKey,"/channels/").concat(H.encodeString(t.channel),"/files")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n={};return t.limit&&(n.limit=t.limit),t.next&&(n.next=t.next),n},handleResponse:function(e,t){return{status:t.status,data:t.data,next:t.next,count:t.count}}},ge={getOperation:function(){return j.PNGenerateUploadUrlOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.name)?void 0:"name can't be empty":"channel can't be empty"},usePost:function(){return!0},postURL:function(e,t){var n=e.config;return"/v1/files/".concat(n.subscribeKey,"/channels/").concat(H.encodeString(t.channel),"/generate-upload-url")},postPayload:function(e,t){return{name:t.name}},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{status:t.status,data:t.data,file_upload_request:t.file_upload_request}}},me={getOperation:function(){return j.PNPublishFileOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.fileId)?(null==t?void 0:t.fileName)?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"},getURL:function(e,t){var n=e.config,r=n.publishKey,o=n.subscribeKey,i=function(e,t){var n=JSON.stringify(t);if(e.cryptoModule){var r=e.cryptoModule.encrypt(n);n="string"==typeof r?r:b(r),n=JSON.stringify(n)}return n||""}(e,{message:t.message,file:{name:t.fileName,id:t.fileId}});return"/v1/files/publish-file/".concat(r,"/").concat(o,"/0/").concat(H.encodeString(t.channel),"/0/").concat(H.encodeString(i))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n={};return t.ttl&&(n.ttl=t.ttl),void 0!==t.storeInHistory&&(n.store=t.storeInHistory?"1":"0"),t.meta&&"object"==typeof t.meta&&(n.meta=JSON.stringify(t.meta)),n},handleResponse:function(e,t){return{timetoken:t[2]}}},be=function(e){var t=function(e){var t=this,n=e.generateUploadUrl,r=e.publishFile,s=e.modules,a=s.PubNubFile,u=s.config,c=s.cryptography,l=s.cryptoModule,p=s.networking;return function(e){var s=e.channel,h=e.file,f=e.message,d=e.cipherKey,y=e.meta,g=e.ttl,m=e.storeInHistory;return o(t,void 0,void 0,(function(){var e,t,o,b,v,_,S,w,O,P,E,A,T,N,C,k,M,j,R,x,U,I,D,F,L,G,K,B,H;return i(this,(function(i){switch(i.label){case 0:if(!s)throw new q("Validation failed, check status for details",z("channel can't be empty"));if(!h)throw new q("Validation failed, check status for details",z("file can't be empty"));return e=a.create(h),[4,n({channel:s,name:e.name})];case 1:return t=i.sent(),o=t.file_upload_request,b=o.url,v=o.form_fields,_=t.data,S=_.id,w=_.name,a.supportsEncryptFile&&(d||l)?null!=d?[3,3]:[4,l.encryptFile(e,a)]:[3,6];case 2:return O=i.sent(),[3,5];case 3:return[4,c.encryptFile(d,e,a)];case 4:O=i.sent(),i.label=5;case 5:e=O,i.label=6;case 6:P=v,e.mimeType&&(P=v.map((function(t){return"Content-Type"===t.key?{key:t.key,value:e.mimeType}:t}))),i.label=7;case 7:return i.trys.push([7,21,,22]),a.supportsFileUri&&h.uri?(T=(A=p).POSTFILE,N=[b,P],[4,e.toFileUri()]):[3,10];case 8:return[4,T.apply(A,N.concat([i.sent()]))];case 9:return E=i.sent(),[3,20];case 10:return a.supportsFile?(k=(C=p).POSTFILE,M=[b,P],[4,e.toFile()]):[3,13];case 11:return[4,k.apply(C,M.concat([i.sent()]))];case 12:return E=i.sent(),[3,20];case 13:return a.supportsBuffer?(R=(j=p).POSTFILE,x=[b,P],[4,e.toBuffer()]):[3,16];case 14:return[4,R.apply(j,x.concat([i.sent()]))];case 15:return E=i.sent(),[3,20];case 16:return a.supportsBlob?(I=(U=p).POSTFILE,D=[b,P],[4,e.toBlob()]):[3,19];case 17:return[4,I.apply(U,D.concat([i.sent()]))];case 18:return E=i.sent(),[3,20];case 19:throw new Error("Unsupported environment");case 20:return[3,22];case 21:throw(F=i.sent()).response&&"string"==typeof F.response.text?(L=F.response.text,G=/(.*)<\/Message>/gi.exec(L),new q(G?"Upload to bucket failed: ".concat(G[1]):"Upload to bucket failed.",F)):new q("Upload to bucket failed.",F);case 22:if(204!==E.status)throw new q("Upload to bucket was unsuccessful",E);K=u.fileUploadPublishRetryLimit,B=!1,H={timetoken:"0"},i.label=23;case 23:return i.trys.push([23,25,,26]),[4,r({channel:s,message:f,fileId:S,fileName:w,meta:y,storeInHistory:m,ttl:g})];case 24:return H=i.sent(),B=!0,[3,26];case 25:return i.sent(),K-=1,[3,26];case 26:if(!B&&K>0)return[3,23];i.label=27;case 27:if(B)return[2,{timetoken:H.timetoken,id:S,name:w}];throw new q("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{channel:s,id:S,name:w})}}))}))}}(e);return function(e,n){var r=t(e);return"function"==typeof n?(r.then((function(e){return n(null,e)})).catch((function(e){return n(e,null)})),r):r}},ve=function(e,t){var n=t.channel,r=t.id,o=t.name,i=e.config,s=e.networking,a=e.tokenManager;if(!n)throw new q("Validation failed, check status for details",z("channel can't be empty"));if(!r)throw new q("Validation failed, check status for details",z("file id can't be empty"));if(!o)throw new q("Validation failed, check status for details",z("file name can't be empty"));var u="/v1/files/".concat(i.subscribeKey,"/channels/").concat(H.encodeString(n),"/files/").concat(r,"/").concat(o),c={};c.uuid=i.getUUID(),c.pnsdk=W(i);var l=a.getToken()||i.getAuthKey();l&&(c.auth=l),i.secretKey&&$(e,u,c,{},{getOperation:function(){return"PubNubGetFileUrlOperation"}});var p=Object.keys(c).map((function(e){return"".concat(encodeURIComponent(e),"=").concat(encodeURIComponent(c[e]))})).join("&");return""!==p?"".concat(s.getStandardOrigin()).concat(u,"?").concat(p):"".concat(s.getStandardOrigin()).concat(u)},_e={getOperation:function(){return j.PNDownloadFileOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.name)?(null==t?void 0:t.id)?void 0:"id can't be empty":"name can't be empty":"channel can't be empty"},useGetFile:function(){return!0},getFileURL:function(e,t){var n=e.config;return"/v1/files/".concat(n.subscribeKey,"/channels/").concat(H.encodeString(t.channel),"/files/").concat(t.id,"/").concat(t.name)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},ignoreBody:function(){return!0},forceBuffered:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t,n){var r=e.PubNubFile,s=e.config,a=e.cryptography,u=e.cryptoModule;return o(void 0,void 0,void 0,(function(){var e,o,c,l;return i(this,(function(i){switch(i.label){case 0:return e=t.response.body,r.supportsEncryptFile&&(n.cipherKey||u)?null!=n.cipherKey?[3,2]:[4,u.decryptFile(r.create({data:e,name:n.name}),r)]:[3,5];case 1:return o=i.sent().data,[3,4];case 2:return[4,a.decrypt(null!==(c=n.cipherKey)&&void 0!==c?c:s.cipherKey,e)];case 3:o=i.sent(),i.label=4;case 4:e=o,i.label=5;case 5:return[2,r.create({data:e,name:null!==(l=t.response.name)&&void 0!==l?l:n.name,mimeType:t.response.type})]}}))}))}},Se={getOperation:function(){return j.PNListFilesOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.id)?(null==t?void 0:t.name)?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"},useDelete:function(){return!0},getURL:function(e,t){var n=e.config;return"/v1/files/".concat(n.subscribeKey,"/channels/").concat(H.encodeString(t.channel),"/files/").concat(t.id,"/").concat(t.name)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{status:t.status}}},we={getOperation:function(){return j.PNGetAllUUIDMetadataOperation},validateParams:function(){},getURL:function(e){var t=e.config;return"/v2/objects/".concat(t.subscribeKey,"/uuids")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o,i,s,u,c,l,p,h={include:["status","type"]};return(null==t?void 0:t.include)&&(null===(n=t.include)||void 0===n?void 0:n.customFields)&&h.include.push("custom"),h.include=h.include.join(","),(null===(r=null==t?void 0:t.include)||void 0===r?void 0:r.totalCount)&&(h.count=null===(o=t.include)||void 0===o?void 0:o.totalCount),(null===(i=null==t?void 0:t.page)||void 0===i?void 0:i.next)&&(h.start=null===(s=t.page)||void 0===s?void 0:s.next),(null===(u=null==t?void 0:t.page)||void 0===u?void 0:u.prev)&&(h.end=null===(c=t.page)||void 0===c?void 0:c.prev),(null==t?void 0:t.filter)&&(h.filter=t.filter),h.limit=null!==(l=null==t?void 0:t.limit)&&void 0!==l?l:100,(null==t?void 0:t.sort)&&(h.sort=Object.entries(null!==(p=t.sort)&&void 0!==p?p:{}).map((function(e){var t=a(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),h},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,next:t.next,prev:t.prev}}},Oe={getOperation:function(){return j.PNGetUUIDMetadataOperation},validateParams:function(){},getURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(H.encodeString(null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:r.getUUID()))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o=e.config,i={};return i.uuid=null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:o.getUUID(),i.include=["status","type","custom"],(null==t?void 0:t.include)&&!1===(null===(r=t.include)||void 0===r?void 0:r.customFields)&&i.include.pop(),i.include=i.include.join(","),i},handleResponse:function(e,t){return{status:t.status,data:t.data}}},Pe={getOperation:function(){return j.PNSetUUIDMetadataOperation},validateParams:function(e,t){if(!(null==t?void 0:t.data))return"Data cannot be empty"},usePatch:function(){return!0},patchURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(H.encodeString(null!==(n=t.uuid)&&void 0!==n?n:r.getUUID()))},patchPayload:function(e,t){return t.data},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o=e.config,i={};return i.uuid=null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:o.getUUID(),i.include=["status","type","custom"],(null==t?void 0:t.include)&&!1===(null===(r=t.include)||void 0===r?void 0:r.customFields)&&i.include.pop(),i.include=i.include.join(","),i},handleResponse:function(e,t){return{status:t.status,data:t.data}}},Ee={getOperation:function(){return j.PNRemoveUUIDMetadataOperation},validateParams:function(){},getURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(H.encodeString(null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:r.getUUID()))},useDelete:function(){return!0},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r=e.config;return{uuid:null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:r.getUUID()}},handleResponse:function(e,t){return{status:t.status,data:t.data}}},Ae={getOperation:function(){return j.PNGetAllChannelMetadataOperation},validateParams:function(){},getURL:function(e){var t=e.config;return"/v2/objects/".concat(t.subscribeKey,"/channels")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o,i,s,u,c,l,p,h={include:["status","type"]};return(null==t?void 0:t.include)&&(null===(n=t.include)||void 0===n?void 0:n.customFields)&&h.include.push("custom"),h.include=h.include.join(","),(null===(r=null==t?void 0:t.include)||void 0===r?void 0:r.totalCount)&&(h.count=null===(o=t.include)||void 0===o?void 0:o.totalCount),(null===(i=null==t?void 0:t.page)||void 0===i?void 0:i.next)&&(h.start=null===(s=t.page)||void 0===s?void 0:s.next),(null===(u=null==t?void 0:t.page)||void 0===u?void 0:u.prev)&&(h.end=null===(c=t.page)||void 0===c?void 0:c.prev),(null==t?void 0:t.filter)&&(h.filter=t.filter),h.limit=null!==(l=null==t?void 0:t.limit)&&void 0!==l?l:100,(null==t?void 0:t.sort)&&(h.sort=Object.entries(null!==(p=t.sort)&&void 0!==p?p:{}).map((function(e){var t=a(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),h},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,prev:t.prev,next:t.next}}},Te={getOperation:function(){return j.PNGetChannelMetadataOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channel))return"Channel cannot be empty"},getURL:function(e,t){var n=e.config;return"/v2/objects/".concat(n.subscribeKey,"/channels/").concat(H.encodeString(t.channel))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r={include:["status","type","custom"]};return(null==t?void 0:t.include)&&!1===(null===(n=t.include)||void 0===n?void 0:n.customFields)&&r.include.pop(),r.include=r.include.join(","),r},handleResponse:function(e,t){return{status:t.status,data:t.data}}},Ne={getOperation:function(){return j.PNSetChannelMetadataOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.data)?void 0:"Data cannot be empty":"Channel cannot be empty"},usePatch:function(){return!0},patchURL:function(e,t){var n=e.config;return"/v2/objects/".concat(n.subscribeKey,"/channels/").concat(H.encodeString(t.channel))},patchPayload:function(e,t){return t.data},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r={include:["status","type","custom"]};return(null==t?void 0:t.include)&&!1===(null===(n=t.include)||void 0===n?void 0:n.customFields)&&r.include.pop(),r.include=r.include.join(","),r},handleResponse:function(e,t){return{status:t.status,data:t.data}}},Ce={getOperation:function(){return j.PNRemoveChannelMetadataOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channel))return"Channel cannot be empty"},getURL:function(e,t){var n=e.config;return"/v2/objects/".concat(n.subscribeKey,"/channels/").concat(H.encodeString(t.channel))},useDelete:function(){return!0},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{status:t.status,data:t.data}}},ke={getOperation:function(){return j.PNGetMembersOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channel))return"channel cannot be empty"},getURL:function(e,t){var n=e.config;return"/v2/objects/".concat(n.subscribeKey,"/channels/").concat(H.encodeString(t.channel),"/uuids")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o,i,s,u,c,l,p,h,f,d,y,g,m={include:[]};return(null==t?void 0:t.include)&&((null===(n=t.include)||void 0===n?void 0:n.statusField)&&m.include.push("status"),(null===(r=t.include)||void 0===r?void 0:r.customFields)&&m.include.push("custom"),(null===(o=t.include)||void 0===o?void 0:o.UUIDFields)&&m.include.push("uuid"),(null===(i=t.include)||void 0===i?void 0:i.customUUIDFields)&&m.include.push("uuid.custom"),(null===(s=t.include)||void 0===s?void 0:s.UUIDStatusField)&&m.include.push("uuid.status"),(null===(u=t.include)||void 0===u?void 0:u.UUIDTypeField)&&m.include.push("uuid.type")),m.include=m.include.join(","),(null===(c=null==t?void 0:t.include)||void 0===c?void 0:c.totalCount)&&(m.count=null===(l=t.include)||void 0===l?void 0:l.totalCount),(null===(p=null==t?void 0:t.page)||void 0===p?void 0:p.next)&&(m.start=null===(h=t.page)||void 0===h?void 0:h.next),(null===(f=null==t?void 0:t.page)||void 0===f?void 0:f.prev)&&(m.end=null===(d=t.page)||void 0===d?void 0:d.prev),(null==t?void 0:t.filter)&&(m.filter=t.filter),m.limit=null!==(y=null==t?void 0:t.limit)&&void 0!==y?y:100,(null==t?void 0:t.sort)&&(m.sort=Object.entries(null!==(g=t.sort)&&void 0!==g?g:{}).map((function(e){var t=a(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),m},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,prev:t.prev,next:t.next}}},Me={getOperation:function(){return j.PNSetMembersOperation},validateParams:function(e,t){return(null==t?void 0:t.channel)?(null==t?void 0:t.uuids)&&0!==(null==t?void 0:t.uuids.length)?void 0:"UUIDs cannot be empty":"Channel cannot be empty"},usePatch:function(){return!0},patchURL:function(e,t){var n=e.config;return"/v2/objects/".concat(n.subscribeKey,"/channels/").concat(H.encodeString(t.channel),"/uuids")},patchPayload:function(e,t){var n;return(n={set:[],delete:[]})[t.type]=t.uuids.map((function(e){return"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},custom:e.custom,status:e.status}})),n},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o,i,s,u,c,l,p,h={include:["uuid.status","uuid.type","type"]};return(null==t?void 0:t.include)&&((null===(n=t.include)||void 0===n?void 0:n.customFields)&&h.include.push("custom"),(null===(r=t.include)||void 0===r?void 0:r.customUUIDFields)&&h.include.push("uuid.custom"),(null===(o=t.include)||void 0===o?void 0:o.UUIDFields)&&h.include.push("uuid")),h.include=h.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(h.count=!0),(null===(s=null==t?void 0:t.page)||void 0===s?void 0:s.next)&&(h.start=null===(u=t.page)||void 0===u?void 0:u.next),(null===(c=null==t?void 0:t.page)||void 0===c?void 0:c.prev)&&(h.end=null===(l=t.page)||void 0===l?void 0:l.prev),(null==t?void 0:t.filter)&&(h.filter=t.filter),null!=t.limit&&(h.limit=t.limit),(null==t?void 0:t.sort)&&(h.sort=Object.entries(null!==(p=t.sort)&&void 0!==p?p:{}).map((function(e){var t=a(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),h},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,prev:t.prev,next:t.next}}},je={getOperation:function(){return j.PNGetMembershipsOperation},validateParams:function(){},getURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(H.encodeString(null!==(n=null==t?void 0:t.uuid)&&void 0!==n?n:r.getUUID()),"/channels")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o,i,s,u,c,l,p,h,f,d,y,g,m={include:[]};return(null==t?void 0:t.include)&&((null===(n=t.include)||void 0===n?void 0:n.statusField)&&m.include.push("status"),(null===(r=t.include)||void 0===r?void 0:r.customFields)&&m.include.push("custom"),(null===(o=t.include)||void 0===o?void 0:o.channelFields)&&m.include.push("channel"),(null===(i=t.include)||void 0===i?void 0:i.customChannelFields)&&m.include.push("channel.custom"),(null===(s=t.include)||void 0===s?void 0:s.channelStatusField)&&m.include.push("channel.status"),(null===(u=t.include)||void 0===u?void 0:u.channelTypeField)&&m.include.push("channel.type")),m.include=m.include.join(","),(null===(c=null==t?void 0:t.include)||void 0===c?void 0:c.totalCount)&&(m.count=null===(l=t.include)||void 0===l?void 0:l.totalCount),(null===(p=null==t?void 0:t.page)||void 0===p?void 0:p.next)&&(m.start=null===(h=t.page)||void 0===h?void 0:h.next),(null===(f=null==t?void 0:t.page)||void 0===f?void 0:f.prev)&&(m.end=null===(d=t.page)||void 0===d?void 0:d.prev),(null==t?void 0:t.filter)&&(m.filter=t.filter),m.limit=null!==(y=null==t?void 0:t.limit)&&void 0!==y?y:100,(null==t?void 0:t.sort)&&(m.sort=Object.entries(null!==(g=t.sort)&&void 0!==g?g:{}).map((function(e){var t=a(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),m},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,prev:t.prev,next:t.next}}},Re={getOperation:function(){return j.PNSetMembershipsOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channels)||0===(null==t?void 0:t.channels.length))return"Channels cannot be empty"},usePatch:function(){return!0},patchURL:function(e,t){var n,r=e.config;return"/v2/objects/".concat(r.subscribeKey,"/uuids/").concat(H.encodeString(null!==(n=t.uuid)&&void 0!==n?n:r.getUUID()),"/channels")},patchPayload:function(e,t){var n;return(n={set:[],delete:[]})[t.type]=t.channels.map((function(e){return"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},custom:e.custom,status:e.status}})),n},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n,r,o,i,s,u,c,l,p,h={include:["channel.status","channel.type","status"]};return(null==t?void 0:t.include)&&((null===(n=t.include)||void 0===n?void 0:n.customFields)&&h.include.push("custom"),(null===(r=t.include)||void 0===r?void 0:r.customChannelFields)&&h.include.push("channel.custom"),(null===(o=t.include)||void 0===o?void 0:o.channelFields)&&h.include.push("channel")),h.include=h.include.join(","),(null===(i=null==t?void 0:t.include)||void 0===i?void 0:i.totalCount)&&(h.count=!0),(null===(s=null==t?void 0:t.page)||void 0===s?void 0:s.next)&&(h.start=null===(u=t.page)||void 0===u?void 0:u.next),(null===(c=null==t?void 0:t.page)||void 0===c?void 0:c.prev)&&(h.end=null===(l=t.page)||void 0===l?void 0:l.prev),(null==t?void 0:t.filter)&&(h.filter=t.filter),null!=t.limit&&(h.limit=t.limit),(null==t?void 0:t.sort)&&(h.sort=Object.entries(null!==(p=t.sort)&&void 0!==p?p:{}).map((function(e){var t=a(e,2),n=t[0],r=t[1];return"asc"===r||"desc"===r?"".concat(n,":").concat(r):n}))),h},handleResponse:function(e,t){return{status:t.status,data:t.data,totalCount:t.totalCount,prev:t.prev,next:t.next}}};var xe=Object.freeze({__proto__:null,getOperation:function(){return j.PNAccessManagerAudit},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e){var t=e.config;return"/v2/auth/audit/sub-key/".concat(t.subscribeKey)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!1},prepareParams:function(e,t){var n=t.channel,r=t.channelGroup,o=t.authKeys,i=void 0===o?[]:o,s={};return n&&(s.channel=n),r&&(s["channel-group"]=r),i.length>0&&(s.auth=i.join(",")),s},handleResponse:function(e,t){return t.payload}});var Ue=Object.freeze({__proto__:null,getOperation:function(){return j.PNAccessManagerGrant},validateParams:function(e,t){var n=e.config;return n.subscribeKey?n.publishKey?n.secretKey?null==t.uuids||t.authKeys?null==t.uuids||null==t.channels&&null==t.channelGroups?void 0:"Both channel/channelgroup and uuid cannot be used in the same request":"authKeys are required for grant request on uuids":"Missing Secret Key":"Missing Publish Key":"Missing Subscribe Key"},getURL:function(e){var t=e.config;return"/v2/auth/grant/sub-key/".concat(t.subscribeKey)},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!1},prepareParams:function(e,t){var n=t.channels,r=void 0===n?[]:n,o=t.channelGroups,i=void 0===o?[]:o,s=t.uuids,a=void 0===s?[]:s,u=t.ttl,c=t.read,l=void 0!==c&&c,p=t.write,h=void 0!==p&&p,f=t.manage,d=void 0!==f&&f,y=t.get,g=void 0!==y&&y,m=t.join,b=void 0!==m&&m,v=t.update,_=void 0!==v&&v,S=t.authKeys,w=void 0===S?[]:S,O=t.delete,P={};return P.r=l?"1":"0",P.w=h?"1":"0",P.m=d?"1":"0",P.d=O?"1":"0",P.g=g?"1":"0",P.j=b?"1":"0",P.u=_?"1":"0",r.length>0&&(P.channel=r.join(",")),i.length>0&&(P["channel-group"]=i.join(",")),w.length>0&&(P.auth=w.join(",")),a.length>0&&(P["target-uuid"]=a.join(",")),(u||0===u)&&(P.ttl=u),P},handleResponse:function(){return{}}});function Ie(e){var t,n,r,o,i=void 0!==(null==e?void 0:e.authorizedUserId),s=void 0!==(null===(t=null==e?void 0:e.resources)||void 0===t?void 0:t.users),a=void 0!==(null===(n=null==e?void 0:e.resources)||void 0===n?void 0:n.spaces),u=void 0!==(null===(r=null==e?void 0:e.patterns)||void 0===r?void 0:r.users),c=void 0!==(null===(o=null==e?void 0:e.patterns)||void 0===o?void 0:o.spaces);return u||s||c||a||i}function De(e){var t=0;return e.join&&(t|=128),e.update&&(t|=64),e.get&&(t|=32),e.delete&&(t|=8),e.manage&&(t|=4),e.write&&(t|=2),e.read&&(t|=1),t}function Fe(e,t){if(Ie(t))return function(e,t){var n=t.ttl,r=t.resources,o=t.patterns,i=t.meta,s=t.authorizedUserId,a={ttl:0,permissions:{resources:{channels:{},groups:{},uuids:{},users:{},spaces:{}},patterns:{channels:{},groups:{},uuids:{},users:{},spaces:{}},meta:{}}};if(r){var u=r.users,c=r.spaces,l=r.groups;u&&Object.keys(u).forEach((function(e){a.permissions.resources.uuids[e]=De(u[e])})),c&&Object.keys(c).forEach((function(e){a.permissions.resources.channels[e]=De(c[e])})),l&&Object.keys(l).forEach((function(e){a.permissions.resources.groups[e]=De(l[e])}))}if(o){var p=o.users,h=o.spaces,f=o.groups;p&&Object.keys(p).forEach((function(e){a.permissions.patterns.uuids[e]=De(p[e])})),h&&Object.keys(h).forEach((function(e){a.permissions.patterns.channels[e]=De(h[e])})),f&&Object.keys(f).forEach((function(e){a.permissions.patterns.groups[e]=De(f[e])}))}return(n||0===n)&&(a.ttl=n),i&&(a.permissions.meta=i),s&&(a.permissions.uuid="".concat(s)),a}(0,t);var n=t.ttl,r=t.resources,o=t.patterns,i=t.meta,s=t.authorized_uuid,a={ttl:0,permissions:{resources:{channels:{},groups:{},uuids:{},users:{},spaces:{}},patterns:{channels:{},groups:{},uuids:{},users:{},spaces:{}},meta:{}}};if(r){var u=r.uuids,c=r.channels,l=r.groups;u&&Object.keys(u).forEach((function(e){a.permissions.resources.uuids[e]=De(u[e])})),c&&Object.keys(c).forEach((function(e){a.permissions.resources.channels[e]=De(c[e])})),l&&Object.keys(l).forEach((function(e){a.permissions.resources.groups[e]=De(l[e])}))}if(o){var p=o.uuids,h=o.channels,f=o.groups;p&&Object.keys(p).forEach((function(e){a.permissions.patterns.uuids[e]=De(p[e])})),h&&Object.keys(h).forEach((function(e){a.permissions.patterns.channels[e]=De(h[e])})),f&&Object.keys(f).forEach((function(e){a.permissions.patterns.groups[e]=De(f[e])}))}return(n||0===n)&&(a.ttl=n),i&&(a.permissions.meta=i),s&&(a.permissions.uuid="".concat(s)),a}var Le=Object.freeze({__proto__:null,getOperation:function(){return j.PNAccessManagerGrantToken},extractPermissions:De,validateParams:function(e,t){var n,r,o,i,s,a,u=e.config;if(!u.subscribeKey)return"Missing Subscribe Key";if(!u.publishKey)return"Missing Publish Key";if(!u.secretKey)return"Missing Secret Key";if(!t.resources&&!t.patterns)return"Missing either Resources or Patterns.";var c=void 0!==(null==t?void 0:t.authorized_uuid),l=void 0!==(null===(n=null==t?void 0:t.resources)||void 0===n?void 0:n.uuids),p=void 0!==(null===(r=null==t?void 0:t.resources)||void 0===r?void 0:r.channels),h=void 0!==(null===(o=null==t?void 0:t.resources)||void 0===o?void 0:o.groups),f=void 0!==(null===(i=null==t?void 0:t.patterns)||void 0===i?void 0:i.uuids),d=void 0!==(null===(s=null==t?void 0:t.patterns)||void 0===s?void 0:s.channels),y=void 0!==(null===(a=null==t?void 0:t.patterns)||void 0===a?void 0:a.groups),g=c||l||f||p||d||h||y;return Ie(t)&&g?"Cannot mix `users`, `spaces` and `authorizedUserId` with `uuids`, `channels`, `groups` and `authorized_uuid`":(!t.resources||t.resources.uuids&&0!==Object.keys(t.resources.uuids).length||t.resources.channels&&0!==Object.keys(t.resources.channels).length||t.resources.groups&&0!==Object.keys(t.resources.groups).length||t.resources.users&&0!==Object.keys(t.resources.users).length||t.resources.spaces&&0!==Object.keys(t.resources.spaces).length)&&(!t.patterns||t.patterns.uuids&&0!==Object.keys(t.patterns.uuids).length||t.patterns.channels&&0!==Object.keys(t.patterns.channels).length||t.patterns.groups&&0!==Object.keys(t.patterns.groups).length||t.patterns.users&&0!==Object.keys(t.patterns.users).length||t.patterns.spaces&&0!==Object.keys(t.patterns.spaces).length)?void 0:"Missing values for either Resources or Patterns."},postURL:function(e){var t=e.config;return"/v3/pam/".concat(t.subscribeKey,"/grant")},usePost:function(){return!0},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!1},prepareParams:function(){return{}},postPayload:function(e,t){return Fe(0,t)},handleResponse:function(e,t){return t.data.token}}),Ge={getOperation:function(){return j.PNAccessManagerRevokeToken},validateParams:function(e,t){return e.config.secretKey?t?void 0:"token can't be empty":"Missing Secret Key"},getURL:function(e,t){var n=e.config;return"/v3/pam/".concat(n.subscribeKey,"/grant/").concat(H.encodeString(t))},useDelete:function(){return!0},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!1},prepareParams:function(e){return{uuid:e.config.getUUID()}},handleResponse:function(e,t){return{status:t.status,data:t.data}}};function Ke(e,t){var n=JSON.stringify(t);if(e.cryptoModule){var r=e.cryptoModule.encrypt(n);n="string"==typeof r?r:b(r),n=JSON.stringify(n)}return n||""}var Be=Object.freeze({__proto__:null,getOperation:function(){return j.PNPublishOperation},validateParams:function(e,t){var n=e.config,r=t.message;return t.channel?r?n.subscribeKey?void 0:"Missing Subscribe Key":"Missing Message":"Missing Channel"},usePost:function(e,t){var n=t.sendByPost;return void 0!==n&&n},getURL:function(e,t){var n=e.config,r=t.channel,o=Ke(e,t.message);return"/publish/".concat(n.publishKey,"/").concat(n.subscribeKey,"/0/").concat(H.encodeString(r),"/0/").concat(H.encodeString(o))},postURL:function(e,t){var n=e.config,r=t.channel;return"/publish/".concat(n.publishKey,"/").concat(n.subscribeKey,"/0/").concat(H.encodeString(r),"/0")},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},postPayload:function(e,t){return Ke(e,t.message)},prepareParams:function(e,t){var n=t.meta,r=t.replicate,o=void 0===r||r,i=t.storeInHistory,s=t.ttl,a={};return null!=i&&(a.store=i?"1":"0"),s&&(a.ttl=s),!1===o&&(a.norep="true"),n&&"object"==typeof n&&(a.meta=JSON.stringify(n)),a},handleResponse:function(e,t){return{timetoken:t[2]}}});var He=Object.freeze({__proto__:null,getOperation:function(){return j.PNSignalOperation},validateParams:function(e,t){var n=e.config,r=t.message;return t.channel?r?n.subscribeKey?void 0:"Missing Subscribe Key":"Missing Message":"Missing Channel"},getURL:function(e,t){var n,r=e.config,o=t.channel,i=t.message,s=(n=i,JSON.stringify(n));return"/signal/".concat(r.publishKey,"/").concat(r.subscribeKey,"/0/").concat(H.encodeString(o),"/0/").concat(H.encodeString(s))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(){return{}},handleResponse:function(e,t){return{timetoken:t[2]}}});var qe=Object.freeze({__proto__:null,getOperation:function(){return j.PNHistoryOperation},validateParams:function(e,t){var n=t.channel,r=e.config;return n?r.subscribeKey?void 0:"Missing Subscribe Key":"Missing channel"},getURL:function(e,t){var n=t.channel,r=e.config;return"/v2/history/sub-key/".concat(r.subscribeKey,"/channel/").concat(H.encodeString(n))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.start,r=t.end,o=t.reverse,i=t.count,s=void 0===i?100:i,a=t.stringifiedTimeToken,u=void 0!==a&&a,c=t.includeMeta,l=void 0!==c&&c,p={include_token:"true"};return p.count=s,n&&(p.start=n),r&&(p.end=r),u&&(p.string_message_token="true"),null!=o&&(p.reverse=o.toString()),l&&(p.include_meta="true"),p},handleResponse:function(e,t){var n={messages:[],startTimeToken:t[1],endTimeToken:t[2]};return Array.isArray(t[0])&&t[0].forEach((function(t){var r=function(e,t){var n={};if(!e.cryptoModule)return n.payload=t,n;try{var r=e.cryptoModule.decrypt(t),o=r instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(r)):r;return n.payload=o,n}catch(r){e.config.logVerbosity&&console&&console.log&&console.log("decryption error",r.message),n.payload=t,n.error="Error while decrypting message content: ".concat(r.message)}return n}(e,t.message),o={timetoken:t.timetoken,entry:r.payload};t.meta&&(o.meta=t.meta),r.error&&(o.error=r.error),n.messages.push(o)})),n}});var ze=Object.freeze({__proto__:null,getOperation:function(){return j.PNDeleteMessagesOperation},validateParams:function(e,t){var n=t.channel,r=e.config;return n?r.subscribeKey?void 0:"Missing Subscribe Key":"Missing channel"},useDelete:function(){return!0},getURL:function(e,t){var n=t.channel,r=e.config;return"/v3/history/sub-key/".concat(r.subscribeKey,"/channel/").concat(H.encodeString(n))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.start,r=t.end,o={};return n&&(o.start=n),r&&(o.end=r),o},handleResponse:function(e,t){return t.payload}});var Ve=Object.freeze({__proto__:null,getOperation:function(){return j.PNMessageCounts},validateParams:function(e,t){var n=t.channels,r=t.timetoken,o=t.channelTimetokens,i=e.config;return n?r&&o?"timetoken and channelTimetokens are incompatible together":o&&o.length>1&&n.length!==o.length?"Length of channelTimetokens and channels do not match":i.subscribeKey?void 0:"Missing Subscribe Key":"Missing channel"},getURL:function(e,t){var n=t.channels,r=e.config,o=n.join(",");return"/v3/history/sub-key/".concat(r.subscribeKey,"/message-counts/").concat(H.encodeString(o))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.timetoken,r=t.channelTimetokens,o={};if(r&&1===r.length){var i=a(r,1)[0];o.timetoken=i}else r?o.channelsTimetoken=r.join(","):n&&(o.timetoken=n);return o},handleResponse:function(e,t){return{channels:t.channels}}});var We=Object.freeze({__proto__:null,getOperation:function(){return j.PNFetchMessagesOperation},validateParams:function(e,t){var n=t.channels,r=t.includeMessageActions,o=void 0!==r&&r,i=e.config;if(!n||0===n.length)return"Missing channels";if(!i.subscribeKey)return"Missing Subscribe Key";if(o&&n.length>1)throw new TypeError("History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.")},getURL:function(e,t){var n=t.channels,r=void 0===n?[]:n,o=t.includeMessageActions,i=void 0!==o&&o,s=e.config,a=i?"history-with-actions":"history",u=r.length>0?r.join(","):",";return"/v3/".concat(a,"/sub-key/").concat(s.subscribeKey,"/channel/").concat(H.encodeString(u))},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=t.channels,r=t.start,o=t.end,i=t.includeMessageActions,s=t.count,a=t.stringifiedTimeToken,u=void 0!==a&&a,c=t.includeMeta,l=void 0!==c&&c,p=t.includeUuid,h=t.includeUUID,f=void 0===h||h,d=t.includeMessageType,y=void 0===d||d,g={};return g.max=s||(n.length>1||!0===i?25:100),r&&(g.start=r),o&&(g.end=o),u&&(g.string_message_token="true"),l&&(g.include_meta="true"),f&&!1!==p&&(g.include_uuid="true"),y&&(g.include_message_type="true"),g},handleResponse:function(e,t){var n={channels:{}};return Object.keys(t.channels||{}).forEach((function(r){n.channels[r]=[],(t.channels[r]||[]).forEach((function(t){var o={},i=function(e,t){var n={};if(!e.cryptoModule)return n.payload=t,n;try{var r=e.cryptoModule.decrypt(t),o=r instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(r)):r;return n.payload=o,n}catch(r){e.config.logVerbosity&&console&&console.log&&console.log("decryption error",r.message),n.payload=t,n.error="Error while decrypting message content: ".concat(r.message)}return n}(e,t.message);o.channel=r,o.timetoken=t.timetoken,o.message=i.payload,o.messageType=t.message_type,o.uuid=t.uuid,t.actions&&(o.actions=t.actions,o.data=t.actions),t.meta&&(o.meta=t.meta),i.error&&(o.error=i.error),n.channels[r].push(o)}))})),t.more&&(n.more=t.more),n}});var Je=Object.freeze({__proto__:null,getOperation:function(){return j.PNTimeOperation},getURL:function(){return"/time/0"},getRequestTimeout:function(e){return e.config.getTransactionTimeout()},prepareParams:function(){return{}},isAuthSupported:function(){return!1},handleResponse:function(e,t){return{timetoken:t[0]}},validateParams:function(){}});var $e=Object.freeze({__proto__:null,getOperation:function(){return j.PNSubscribeOperation},validateParams:function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},getURL:function(e,t){var n=e.config,r=t.channels,o=void 0===r?[]:r,i=o.length>0?o.join(","):",";return"/v2/subscribe/".concat(n.subscribeKey,"/").concat(H.encodeString(i),"/0")},getRequestTimeout:function(e){return e.config.getSubscribeTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n=e.config,r=t.state,o=t.channelGroups,i=void 0===o?[]:o,s=t.timetoken,a=t.filterExpression,u=t.region,c={heartbeat:n.getPresenceTimeout()};return i.length>0&&(c["channel-group"]=i.join(",")),a&&a.length>0&&(c["filter-expr"]=a),Object.keys(r).length&&(c.state=JSON.stringify(r)),s&&(c.tt=s),u&&(c.tr=u),c},handleResponse:function(e,t){var n=[];t.m.forEach((function(e){var t={publishTimetoken:e.p.t,region:e.p.r},r={shard:parseInt(e.a,10),subscriptionMatch:e.b,channel:e.c,messageType:e.e,payload:e.d,flags:e.f,issuingClientId:e.i,subscribeKey:e.k,originationTimetoken:e.o,userMetadata:e.u,publishMetaData:t};n.push(r)}));var r={timetoken:t.t.t,region:t.t.r};return{messages:n,metadata:r}}}),Qe={getOperation:function(){return j.PNHandshakeOperation},validateParams:function(e,t){if(!(null==t?void 0:t.channels)&&!(null==t?void 0:t.channelGroups))return"channels and channleGroups both should not be empty"},getURL:function(e,t){var n=e.config,r=t.channels,o=void 0===r?[]:r,i=o.length>0?o.join(","):",";return"/v2/subscribe/".concat(n.subscribeKey,"/").concat(H.encodeString(i),"/0")},getRequestTimeout:function(e){return e.config.getSubscribeTimeout()},isAuthSupported:function(){return!0},prepareParams:function(e,t){var n={};return t.channelGroups&&t.channelGroups.length>0&&(n["channel-group"]=t.channelGroups.join(",")),n.tt=0,t.state&&(n.state=JSON.stringify(t.state)),t.filterExpression&&t.filterExpression.length>0&&(n["filter-expr"]=t.filterExpression),n.ee="",n},handleResponse:function(e,t){return{region:t.t.r,timetoken:t.t.t}}},Xe={getOperation:function(){return j.PNReceiveMessagesOperation},validateParams:function(e,t){return(null==t?void 0:t.channels)||(null==t?void 0:t.channelGroups)?(null==t?void 0:t.timetoken)?(null==t?void 0:t.region)?void 0:"region can not be empty":"timetoken can not be empty":"channels and channleGroups both should not be empty"},getURL:function(e,t){var n=e.config,r=t.channels,o=void 0===r?[]:r,i=o.length>0?o.join(","):",";return"/v2/subscribe/".concat(n.subscribeKey,"/").concat(H.encodeString(i),"/0")},getRequestTimeout:function(e){return e.config.getSubscribeTimeout()},isAuthSupported:function(){return!0},getAbortSignal:function(e,t){return t.abortSignal},prepareParams:function(e,t){var n={};return t.channelGroups&&t.channelGroups.length>0&&(n["channel-group"]=t.channelGroups.join(",")),t.filterExpression&&t.filterExpression.length>0&&(n["filter-expr"]=t.filterExpression),n.tt=t.timetoken,n.tr=t.region,n.ee="",n},handleResponse:function(e,t){var n=[];return t.m.forEach((function(e){var t={shard:parseInt(e.a,10),subscriptionMatch:e.b,channel:e.c,messageType:e.e,payload:e.d,flags:e.f,issuingClientId:e.i,subscribeKey:e.k,originationTimetoken:e.o,publishMetaData:{timetoken:e.p.t,region:e.p.r}};n.push(t)})),{messages:n,metadata:{region:t.t.r,timetoken:t.t.t}}}},Ye=function(){function e(e){void 0===e&&(e=!1),this.sync=e,this.listeners=new Set}return e.prototype.subscribe=function(e){var t=this;return this.listeners.add(e),function(){t.listeners.delete(e)}},e.prototype.notify=function(e){var t=this,n=function(){t.listeners.forEach((function(t){t(e)}))};this.sync?n():setTimeout(n,0)},e}(),Ze=function(){function e(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}return e.prototype.transition=function(e,t){var n;if(this.transitionMap.has(t.type))return null===(n=this.transitionMap.get(t.type))||void 0===n?void 0:n(e,t)},e.prototype.on=function(e,t){return this.transitionMap.set(e,t),this},e.prototype.with=function(e,t){return[this,e,null!=t?t:[]]},e.prototype.onEnter=function(e){return this.enterEffects.push(e),this},e.prototype.onExit=function(e){return this.exitEffects.push(e),this},e}(),et=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return t(n,e),n.prototype.describe=function(e){return new Ze(e)},n.prototype.start=function(e,t){this.currentState=e,this.currentContext=t,this.notify({type:"engineStarted",state:e,context:t})},n.prototype.transition=function(e){var t,n,r,o,i,u;if(!this.currentState)throw new Error("Start the engine first");this.notify({type:"eventReceived",event:e});var c=this.currentState.transition(this.currentContext,e);if(c){var l=a(c,3),p=l[0],h=l[1],f=l[2];try{for(var d=s(this.currentState.exitEffects),y=d.next();!y.done;y=d.next()){var g=y.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){t={error:e}}finally{try{y&&!y.done&&(n=d.return)&&n.call(d)}finally{if(t)throw t.error}}var m=this.currentState;this.currentState=p;var b=this.currentContext;this.currentContext=h,this.notify({type:"transitionDone",fromState:m,fromContext:b,toState:p,toContext:h,event:e});try{for(var v=s(f),_=v.next();!_.done;_=v.next()){g=_.value;this.notify({type:"invocationDispatched",invocation:g})}}catch(e){r={error:e}}finally{try{_&&!_.done&&(o=v.return)&&o.call(v)}finally{if(r)throw r.error}}try{for(var S=s(this.currentState.enterEffects),w=S.next();!w.done;w=S.next()){g=w.value;this.notify({type:"invocationDispatched",invocation:g(this.currentContext)})}}catch(e){i={error:e}}finally{try{w&&!w.done&&(u=S.return)&&u.call(S)}finally{if(i)throw i.error}}}},n}(Ye),tt=function(){function e(e){this.dependencies=e,this.instances=new Map,this.handlers=new Map}return e.prototype.on=function(e,t){this.handlers.set(e,t)},e.prototype.dispatch=function(e){if("CANCEL"!==e.type){var t=this.handlers.get(e.type);if(!t)throw new Error("Unhandled invocation '".concat(e.type,"'"));var n=t(e.payload,this.dependencies);e.managed&&this.instances.set(e.type,n),n.start()}else if(this.instances.has(e.payload)){var r=this.instances.get(e.payload);null==r||r.cancel(),this.instances.delete(e.payload)}},e.prototype.dispose=function(){var e,t;try{for(var n=s(this.instances.entries()),r=n.next();!r.done;r=n.next()){var o=a(r.value,2),i=o[0];o[1].cancel(),this.instances.delete(i)}}catch(t){e={error:t}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}},e}();function nt(e,t){var n=function(){for(var n=[],r=0;r0&&r(e),[2]}))}))}))),s.on(ht.type,ut((function(e,t,n){var r=n.emitStatus;return o(s,void 0,void 0,(function(){return i(this,(function(t){return r(e),[2]}))}))}))),s.on(ft.type,ut((function(e,n,r){var a=r.receiveMessages,u=r.delay,c=r.config;return o(s,void 0,void 0,(function(){var r,o;return i(this,(function(i){switch(i.label){case 0:return c.retryConfiguration&&c.retryConfiguration.shouldRetry(e.reason,e.attempts)?(n.throwIfAborted(),[4,u(c.retryConfiguration.getDelay(e.attempts,e.reason))]):[3,6];case 1:i.sent(),n.throwIfAborted(),i.label=2;case 2:return i.trys.push([2,4,,5]),[4,a({abortSignal:n,channels:e.channels,channelGroups:e.groups,timetoken:e.cursor.timetoken,region:e.cursor.region,filterExpression:c.filterExpression})];case 3:return r=i.sent(),[2,t.transition(Pt(r.metadata,r.messages))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(Et(o))]:[3,5];case 5:return[3,7];case 6:return[2,t.transition(At(new q(c.retryConfiguration.getGiveupReason(e.reason,e.attempts))))];case 7:return[2]}}))}))}))),s.on(dt.type,ut((function(e,r,a){var u=a.handshake,c=a.delay,l=a.presenceState,p=a.config;return o(s,void 0,void 0,(function(){var o,s;return i(this,(function(i){switch(i.label){case 0:return p.retryConfiguration&&p.retryConfiguration.shouldRetry(e.reason,e.attempts)?(r.throwIfAborted(),[4,c(p.retryConfiguration.getDelay(e.attempts,e.reason))]):[3,6];case 1:i.sent(),r.throwIfAborted(),i.label=2;case 2:return i.trys.push([2,4,,5]),[4,u(n({abortSignal:r,channels:e.channels,channelGroups:e.groups,filterExpression:p.filterExpression},p.maintainPresenceState&&{state:l}))];case 3:return o=i.sent(),[2,t.transition(vt(o))];case 4:return(s=i.sent())instanceof Error&&"Aborted"===s.message?[2]:s instanceof q?[2,t.transition(_t(s))]:[3,5];case 5:return[3,7];case 6:return[2,t.transition(St(new q(p.retryConfiguration.getGiveupReason(e.reason,e.attempts))))];case 7:return[2]}}))}))}))),s}return t(r,e),r}(tt),Mt=new Ze("HANDSHAKE_FAILED");Mt.on(yt.type,(function(e,t){return Ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),Mt.on(Nt.type,(function(e,t){return Ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor||e.cursor})})),Mt.on(gt.type,(function(e,t){var n,r;return Ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region?t.payload.cursor.region:null!==(r=null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)&&void 0!==r?r:0}})})),Mt.on(Ct.type,(function(e){return Lt.with()}));var jt=new Ze("HANDSHAKE_STOPPED");jt.on(yt.type,(function(e,t){return jt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),jt.on(Nt.type,(function(e,t){return Ft.with(n(n({},e),{cursor:t.payload.cursor||e.cursor}))})),jt.on(gt.type,(function(e,t){var n;return jt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)||0}})})),jt.on(Ct.type,(function(e){return Lt.with()}));var Rt=new Ze("RECEIVE_FAILED");Rt.on(Nt.type,(function(e,t){var n;return Ft.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(n=t.payload.cursor)||void 0===n?void 0:n.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),Rt.on(yt.type,(function(e,t){return Ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),Rt.on(gt.type,(function(e,t){return Ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),Rt.on(Ct.type,(function(e){return Lt.with(void 0)}));var xt=new Ze("RECEIVE_STOPPED");xt.on(yt.type,(function(e,t){return xt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),xt.on(gt.type,(function(e,t){return xt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),xt.on(Nt.type,(function(e,t){var n;return Ft.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(n=t.payload.cursor)||void 0===n?void 0:n.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),xt.on(Ct.type,(function(){return Lt.with(void 0)}));var Ut=new Ze("RECEIVE_RECONNECTING");Ut.onEnter((function(e){return ft(e)})),Ut.onExit((function(){return ft.cancel})),Ut.on(Pt.type,(function(e,t){return It.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[pt(t.payload.events)])})),Ut.on(Et.type,(function(e,t){return Ut.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Ut.on(At.type,(function(e,t){var n;return Rt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[ht({category:k.PNDisconnectedUnexpectedlyCategory,error:null===(n=t.payload)||void 0===n?void 0:n.message})])})),Ut.on(Tt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[ht({category:k.PNDisconnectedCategory})])})),Ut.on(gt.type,(function(e,t){return It.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),Ut.on(yt.type,(function(e,t){return It.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),Ut.on(Ct.type,(function(e){return Lt.with(void 0,[ht({category:k.PNDisconnectedCategory})])}));var It=new Ze("RECEIVING");It.onEnter((function(e){return lt(e.channels,e.groups,e.cursor)})),It.onExit((function(){return lt.cancel})),It.on(wt.type,(function(e,t){return It.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[pt(t.payload.events)])})),It.on(yt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Lt.with(void 0):It.with({cursor:e.cursor,channels:t.payload.channels,groups:t.payload.groups})})),It.on(gt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Lt.with(void 0):It.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),It.on(Ot.type,(function(e,t){return Ut.with(n(n({},e),{attempts:0,reason:t.payload}))})),It.on(Tt.type,(function(e){return xt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[ht({category:k.PNDisconnectedCategory})])})),It.on(Ct.type,(function(e){return Lt.with(void 0,[ht({category:k.PNDisconnectedCategory})])}));var Dt=new Ze("HANDSHAKE_RECONNECTING");Dt.onEnter((function(e){return dt(e)})),Dt.onExit((function(){return dt.cancel})),Dt.on(vt.type,(function(e,t){var n,r,o={timetoken:(null===(n=e.cursor)||void 0===n?void 0:n.timetoken)?null===(r=e.cursor)||void 0===r?void 0:r.timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region};return It.with({channels:e.channels,groups:e.groups,cursor:o},[ht({category:k.PNConnectedCategory})])})),Dt.on(_t.type,(function(e,t){return Dt.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),Dt.on(St.type,(function(e,t){var n;return Mt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[ht({category:k.PNConnectionErrorCategory,error:null===(n=t.payload)||void 0===n?void 0:n.message})])})),Dt.on(Tt.type,(function(e){return jt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})})),Dt.on(yt.type,(function(e,t){return Ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),Dt.on(gt.type,(function(e,t){var n,r;return Ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:(null===(n=t.payload.cursor)||void 0===n?void 0:n.region)||(null===(r=null==e?void 0:e.cursor)||void 0===r?void 0:r.region)||0}})})),Dt.on(Ct.type,(function(e){return Lt.with(void 0)}));var Ft=new Ze("HANDSHAKING");Ft.onEnter((function(e){return ct(e.channels,e.groups)})),Ft.onExit((function(){return ct.cancel})),Ft.on(yt.type,(function(e,t){return 0===t.payload.channels.length&&0===t.payload.groups.length?Lt.with(void 0):Ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor})})),Ft.on(mt.type,(function(e,t){var n,r;return It.with({channels:e.channels,groups:e.groups,cursor:{timetoken:(null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.timetoken)?null===(r=null==e?void 0:e.cursor)||void 0===r?void 0:r.timetoken:t.payload.timetoken,region:t.payload.region}},[ht({category:k.PNConnectedCategory})])})),Ft.on(bt.type,(function(e,t){return Dt.with({channels:e.channels,groups:e.groups,cursor:e.cursor,attempts:0,reason:t.payload})})),Ft.on(Tt.type,(function(e){return jt.with({channels:e.channels,groups:e.groups,cursor:e.cursor})})),Ft.on(gt.type,(function(e,t){var n;return Ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)||0}})})),Ft.on(Ct.type,(function(e){return Lt.with()}));var Lt=new Ze("UNSUBSCRIBED");Lt.on(yt.type,(function(e,t){return Ft.with({channels:t.payload.channels,groups:t.payload.groups})})),Lt.on(gt.type,(function(e,t){return Ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:t.payload.cursor})}));var Gt=function(){function e(e){var t=this;this.engine=new et,this.channels=[],this.groups=[],this.dependencies=e,this.dispatcher=new kt(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((function(e){"invocationDispatched"===e.type&&t.dispatcher.dispatch(e.invocation)})),this.engine.start(Lt,void 0)}return Object.defineProperty(e.prototype,"_engine",{get:function(){return this.engine},enumerable:!1,configurable:!0}),e.prototype.subscribe=function(e){var t=this,n=e.channels,r=e.channelGroups,o=e.timetoken,i=e.withPresence;this.channels=u(u([],a(this.channels),!1),a(null!=n?n:[]),!1),this.groups=u(u([],a(this.groups),!1),a(null!=r?r:[]),!1),i&&(this.channels.map((function(e){return t.channels.push("".concat(e,"-pnpres"))})),this.groups.map((function(e){return t.groups.push("".concat(e,"-pnpres"))}))),o?this.engine.transition(gt(Array.from(new Set(u(u([],a(this.channels),!1),a(null!=n?n:[]),!1))),Array.from(new Set(u(u([],a(this.groups),!1),a(null!=r?r:[]),!1))),o)):this.engine.transition(yt(Array.from(new Set(u(u([],a(this.channels),!1),a(null!=n?n:[]),!1))),Array.from(new Set(u(u([],a(this.groups),!1),a(null!=r?r:[]),!1))))),this.dependencies.join&&this.dependencies.join({channels:Array.from(new Set(this.channels.filter((function(e){return!e.endsWith("-pnpres")})))),groups:Array.from(new Set(this.groups.filter((function(e){return!e.endsWith("-pnpres")}))))})},e.prototype.unsubscribe=function(e){var t=this,n=e.channels,r=void 0===n?[]:n,o=e.channelGroups,i=void 0===o?[]:o,s=H.removeSingleOccurance(this.channels,u(u([],a(r),!1),a(r.map((function(e){return"".concat(e,"-pnpres")}))),!1)),c=H.removeSingleOccurance(this.groups,u(u([],a(i),!1),a(i.map((function(e){return"".concat(e,"-pnpres")}))),!1));if(new Set(this.channels).size!==new Set(s).size||new Set(this.groups).size!==new Set(c).size){var l=H.findUniqueCommonElements(this.channels,r),p=H.findUniqueCommonElements(this.groups,i);this.dependencies.presenceState&&(null==l||l.forEach((function(e){return delete t.dependencies.presenceState[e]})),null==p||p.forEach((function(e){return delete t.dependencies.presenceState[e]}))),this.channels=s,this.groups=c,this.engine.transition(yt(Array.from(new Set(this.channels.slice(0))),Array.from(new Set(this.groups.slice(0))))),this.dependencies.leave&&this.dependencies.leave({channels:l.slice(0),groups:p.slice(0)})}},e.prototype.unsubscribeAll=function(){this.channels=[],this.groups=[],this.dependencies.presenceState&&(this.dependencies.presenceState={}),this.engine.transition(yt(this.channels.slice(0),this.groups.slice(0))),this.dependencies.leaveAll&&this.dependencies.leaveAll()},e.prototype.reconnect=function(e){var t=e.timetoken,n=e.region;this.engine.transition(Nt(t,n))},e.prototype.disconnect=function(){this.engine.transition(Tt()),this.dependencies.leaveAll&&this.dependencies.leaveAll()},e.prototype.getSubscribedChannels=function(){return this.channels.slice(0)},e.prototype.getSubscribedChannelGroups=function(){return this.groups.slice(0)},e.prototype.dispose=function(){this.disconnect(),this._unsubscribeEngine(),this.dispatcher.dispose()},e}(),Kt=nt("RECONNECT",(function(){return{}})),Bt=nt("DISCONNECT",(function(){return{}})),Ht=nt("JOINED",(function(e,t){return{channels:e,groups:t}})),qt=nt("LEFT",(function(e,t){return{channels:e,groups:t}})),zt=nt("LEFT_ALL",(function(){return{}})),Vt=nt("HEARTBEAT_SUCCESS",(function(e){return{statusCode:e}})),Wt=nt("HEARTBEAT_FAILURE",(function(e){return e})),Jt=nt("HEARTBEAT_GIVEUP",(function(){return{}})),$t=nt("TIMES_UP",(function(){return{}})),Qt=rt("HEARTBEAT",(function(e,t){return{channels:e,groups:t}})),Xt=rt("LEAVE",(function(e,t){return{channels:e,groups:t}})),Yt=rt("EMIT_STATUS",(function(e){return e})),Zt=ot("WAIT",(function(){return{}})),en=ot("DELAYED_HEARTBEAT",(function(e){return e})),tn=function(e){function r(t,r){var s=e.call(this,r)||this;return s.on(Qt.type,ut((function(e,r,a){var u=a.heartbeat,c=a.presenceState,l=a.config;return o(s,void 0,void 0,(function(){var r;return i(this,(function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),[4,u(n({channels:e.channels,channelGroups:e.groups},l.maintainPresenceState&&{state:c}))];case 1:return o.sent(),t.transition(Vt(200)),[3,3];case 2:return(r=o.sent())instanceof q?[2,t.transition(Wt(r))]:[3,3];case 3:return[2]}}))}))}))),s.on(Xt.type,ut((function(e,t,n){var r=n.leave,a=n.config;return o(s,void 0,void 0,(function(){return i(this,(function(t){switch(t.label){case 0:if(a.suppressLeaveEvents)return[3,4];t.label=1;case 1:return t.trys.push([1,3,,4]),[4,r({channels:e.channels,channelGroups:e.groups})];case 2:case 3:return t.sent(),[3,4];case 4:return[2]}}))}))}))),s.on(Zt.type,ut((function(e,n,r){var a=r.heartbeatDelay;return o(s,void 0,void 0,(function(){return i(this,(function(e){switch(e.label){case 0:return n.throwIfAborted(),[4,a()];case 1:return e.sent(),n.throwIfAborted(),[2,t.transition($t())]}}))}))}))),s.on(en.type,ut((function(e,r,a){var u=a.heartbeat,c=a.retryDelay,l=a.presenceState,p=a.config;return o(s,void 0,void 0,(function(){var o;return i(this,(function(i){switch(i.label){case 0:return p.retryConfiguration&&p.retryConfiguration.shouldRetry(e.reason,e.attempts)?(r.throwIfAborted(),[4,c(p.retryConfiguration.getDelay(e.attempts,e.reason))]):[3,6];case 1:i.sent(),r.throwIfAborted(),i.label=2;case 2:return i.trys.push([2,4,,5]),[4,u(n({channels:e.channels,channelGroups:e.groups},p.maintainPresenceState&&{state:l}))];case 3:return i.sent(),[2,t.transition(Vt(200))];case 4:return(o=i.sent())instanceof Error&&"Aborted"===o.message?[2]:o instanceof q?[2,t.transition(Wt(o))]:[3,5];case 5:return[3,7];case 6:return[2,t.transition(Jt())];case 7:return[2]}}))}))}))),s.on(Yt.type,ut((function(e,t,r){var a=r.emitStatus,u=r.config;return o(s,void 0,void 0,(function(){var t;return i(this,(function(r){return u.announceFailedHeartbeats&&!0===(null===(t=null==e?void 0:e.status)||void 0===t?void 0:t.error)?a(e.status):u.announceSuccessfulHeartbeats&&200===e.statusCode&&a(n(n({},e),{operation:j.PNHeartbeatOperation,error:!1})),[2]}))}))}))),s}return t(r,e),r}(tt),nn=new Ze("HEARTBEAT_STOPPED");nn.on(Ht.type,(function(e,t){return nn.with({channels:u(u([],a(e.channels),!1),a(t.payload.channels),!1),groups:u(u([],a(e.groups),!1),a(t.payload.groups),!1)})})),nn.on(qt.type,(function(e,t){return nn.with({channels:e.channels.filter((function(e){return!t.payload.channels.includes(e)})),groups:e.groups.filter((function(e){return!t.payload.groups.includes(e)}))})})),nn.on(Kt.type,(function(e,t){return an.with({channels:e.channels,groups:e.groups})})),nn.on(zt.type,(function(e,t){return un.with(void 0)}));var rn=new Ze("HEARTBEAT_COOLDOWN");rn.onEnter((function(){return Zt()})),rn.onExit((function(){return Zt.cancel})),rn.on($t.type,(function(e,t){return an.with({channels:e.channels,groups:e.groups})})),rn.on(Ht.type,(function(e,t){return an.with({channels:u(u([],a(e.channels),!1),a(t.payload.channels),!1),groups:u(u([],a(e.groups),!1),a(t.payload.groups),!1)})})),rn.on(qt.type,(function(e,t){return an.with({channels:e.channels.filter((function(e){return!t.payload.channels.includes(e)})),groups:e.groups.filter((function(e){return!t.payload.groups.includes(e)}))},[Xt(t.payload.channels,t.payload.groups)])})),rn.on(Bt.type,(function(e){return nn.with({channels:e.channels,groups:e.groups},[Xt(e.channels,e.groups)])})),rn.on(zt.type,(function(e,t){return un.with(void 0,[Xt(e.channels,e.groups)])}));var on=new Ze("HEARTBEAT_FAILED");on.on(Ht.type,(function(e,t){return an.with({channels:u(u([],a(e.channels),!1),a(t.payload.channels),!1),groups:u(u([],a(e.groups),!1),a(t.payload.groups),!1)})})),on.on(qt.type,(function(e,t){return an.with({channels:e.channels.filter((function(e){return!t.payload.channels.includes(e)})),groups:e.groups.filter((function(e){return!t.payload.groups.includes(e)}))},[Xt(t.payload.channels,t.payload.groups)])})),on.on(Kt.type,(function(e,t){return an.with({channels:e.channels,groups:e.groups})})),on.on(Bt.type,(function(e,t){return nn.with({channels:e.channels,groups:e.groups},[Xt(e.channels,e.groups)])})),on.on(zt.type,(function(e,t){return un.with(void 0,[Xt(e.channels,e.groups)])}));var sn=new Ze("HEARBEAT_RECONNECTING");sn.onEnter((function(e){return en(e)})),sn.onExit((function(){return en.cancel})),sn.on(Ht.type,(function(e,t){return an.with({channels:u(u([],a(e.channels),!1),a(t.payload.channels),!1),groups:u(u([],a(e.groups),!1),a(t.payload.groups),!1)})})),sn.on(qt.type,(function(e,t){return an.with({channels:e.channels.filter((function(e){return!t.payload.channels.includes(e)})),groups:e.groups.filter((function(e){return!t.payload.groups.includes(e)}))},[Xt(t.payload.channels,t.payload.groups)])})),sn.on(Bt.type,(function(e,t){nn.with({channels:e.channels,groups:e.groups},[Xt(e.channels,e.groups)])})),sn.on(Vt.type,(function(e,t){return rn.with({channels:e.channels,groups:e.groups})})),sn.on(Wt.type,(function(e,t){return sn.with(n(n({},e),{attempts:e.attempts+1,reason:t.payload}))})),sn.on(Jt.type,(function(e,t){return on.with({channels:e.channels,groups:e.groups})})),sn.on(zt.type,(function(e,t){return un.with(void 0,[Xt(e.channels,e.groups)])}));var an=new Ze("HEARTBEATING");an.onEnter((function(e){return Qt(e.channels,e.groups)})),an.on(Vt.type,(function(e,t){return rn.with({channels:e.channels,groups:e.groups})})),an.on(Ht.type,(function(e,t){return an.with({channels:u(u([],a(e.channels),!1),a(t.payload.channels),!1),groups:u(u([],a(e.groups),!1),a(t.payload.groups),!1)})})),an.on(qt.type,(function(e,t){return an.with({channels:e.channels.filter((function(e){return!t.payload.channels.includes(e)})),groups:e.groups.filter((function(e){return!t.payload.groups.includes(e)}))},[Xt(t.payload.channels,t.payload.groups)])})),an.on(Wt.type,(function(e,t){return sn.with(n(n({},e),{attempts:0,reason:t.payload}))})),an.on(Bt.type,(function(e){return nn.with({channels:e.channels,groups:e.groups},[Xt(e.channels,e.groups)])})),an.on(zt.type,(function(e,t){return un.with(void 0,[Xt(e.channels,e.groups)])}));var un=new Ze("HEARTBEAT_INACTIVE");un.on(Ht.type,(function(e,t){return an.with({channels:t.payload.channels,groups:t.payload.groups})}));var cn=function(){function e(e){var t=this;this.engine=new et,this.channels=[],this.groups=[],this.dispatcher=new tn(this.engine,e),this.dependencies=e,this._unsubscribeEngine=this.engine.subscribe((function(e){"invocationDispatched"===e.type&&t.dispatcher.dispatch(e.invocation)})),this.engine.start(un,void 0)}return Object.defineProperty(e.prototype,"_engine",{get:function(){return this.engine},enumerable:!1,configurable:!0}),e.prototype.join=function(e){var t=e.channels,n=e.groups;this.channels=u(u([],a(this.channels),!1),a(null!=t?t:[]),!1),this.groups=u(u([],a(this.groups),!1),a(null!=n?n:[]),!1),this.engine.transition(Ht(this.channels.slice(0),this.groups.slice(0)))},e.prototype.leave=function(e){var t=this,n=e.channels,r=e.groups;this.dependencies.presenceState&&(null==n||n.forEach((function(e){return delete t.dependencies.presenceState[e]})),null==r||r.forEach((function(e){return delete t.dependencies.presenceState[e]}))),this.engine.transition(qt(null!=n?n:[],null!=r?r:[]))},e.prototype.leaveAll=function(){this.engine.transition(zt())},e.prototype.dispose=function(){this._unsubscribeEngine(),this.dispatcher.dispose()},e}(),ln=function(){function e(){}return e.LinearRetryPolicy=function(e){return{delay:e.delay,maximumRetry:e.maximumRetry,shouldRetry:function(e,t){var n;return 403!==(null===(n=null==e?void 0:e.status)||void 0===n?void 0:n.statusCode)&&this.maximumRetry>t},getDelay:function(e,t){var n;return 1e3*((null!==(n=t.retryAfter)&&void 0!==n?n:this.delay)+Math.random())},getGiveupReason:function(e,t){var n;return this.maximumRetry<=t?"retry attempts exhaused.":403===(null===(n=null==e?void 0:e.status)||void 0===n?void 0:n.statusCode)?"forbidden operation.":"unknown error"}}},e.ExponentialRetryPolicy=function(e){return{minimumDelay:e.minimumDelay,maximumDelay:e.maximumDelay,maximumRetry:e.maximumRetry,shouldRetry:function(e,t){var n;return 403!==(null===(n=null==e?void 0:e.status)||void 0===n?void 0:n.statusCode)&&this.maximumRetry>t},getDelay:function(e,t){var n;return 1e3*((null!==(n=t.retryAfter)&&void 0!==n?n:Math.min(Math.pow(2,e),this.maximumDelay))+Math.random())},getGiveupReason:function(e,t){var n;return this.maximumRetry<=t?"retry attempts exhaused.":403===(null===(n=null==e?void 0:e.status)||void 0===n?void 0:n.statusCode)?"forbidden operation.":"unknown error"}}},e}(),pn=function(){function e(e){var t=e.modules,n=e.listenerManager,r=e.getFileUrl;this.modules=t,this.listenerManager=n,this.getFileUrl=r,this._channelListenerMap=new Map,this._groupListenerMap=new Map,t.cryptoModule&&(this._decoder=new TextDecoder)}return e.prototype.emitEvent=function(e){var t=e.channel,o=e.publishMetaData,i=e.subscriptionMatch;if(t===i&&(i=null),e.channel.endsWith("-pnpres")){var s={channel:null,subscription:null};t&&(s.channel=t.substring(0,t.lastIndexOf("-pnpres"))),i&&(s.subscription=i.substring(0,i.lastIndexOf("-pnpres"))),s.action=e.payload.action,s.state=e.payload.data,s.timetoken=o.publishTimetoken,s.occupancy=e.payload.occupancy,s.uuid=e.payload.uuid,s.timestamp=e.payload.timestamp,e.payload.join&&(s.join=e.payload.join),e.payload.leave&&(s.leave=e.payload.leave),e.payload.timeout&&(s.timeout=e.payload.timeout),s.actualChannel=null!=i?t:null,s.subscribedChannel=null!=i?i:t,this.listenerManager.announcePresence(s),this._announce("presence",s,s.channel,s.subscription)}else if(1===e.messageType){(s={channel:null,subscription:null}).channel=t,s.subscription=i,s.timetoken=o.publishTimetoken,s.publisher=e.issuingClientId,e.userMetadata&&(s.userMetadata=e.userMetadata),s.message=e.payload,this.listenerManager.announceSignal(s),this._announce("signal",s,s.channel,s.subscription)}else if(2===e.messageType){if((s={channel:null,subscription:null}).channel=t,s.subscription=i,s.timetoken=o.publishTimetoken,s.publisher=e.issuingClientId,e.userMetadata&&(s.userMetadata=e.userMetadata),s.message={event:e.payload.event,type:e.payload.type,data:e.payload.data},this.listenerManager.announceObjects(s),this._announce("objects",s,s.channel,s.subscription),"uuid"===e.payload.type){var a=this._renameChannelField(s),u=n(n({},a),{message:n(n({},a.message),{event:this._renameEvent(a.message.event),type:"user"})});this.listenerManager.announceUser(u),this._announce("user",u,s.channel,s.subscription)}else if("channel"===message.payload.type){a=this._renameChannelField(s);var c=n(n({},a),{message:n(n({},a.message),{event:this._renameEvent(a.message.event),type:"space"})});this.listenerManager.announceSpace(c),this._announce("space",c,s.channel,s.subscription)}else if("membership"===message.payload.type){var l=(a=this._renameChannelField(s)).message.data,p=l.uuid,h=l.channel,f=r(l,["uuid","channel"]);f.user=p,f.space=h;var d=n(n({},a),{message:n(n({},a.message),{event:this._renameEvent(a.message.event),data:f})});this.listenerManager.announceMembership(d),this._announce("membership",d,s.channel,s.subscription)}}else if(3===e.messageType){(s={}).channel=t,s.subscription=i,s.timetoken=o.publishTimetoken,s.publisher=e.issuingClientId,s.data={messageTimetoken:e.payload.data.messageTimetoken,actionTimetoken:e.payload.data.actionTimetoken,type:e.payload.data.type,uuid:e.issuingClientId,value:e.payload.data.value},s.event=e.payload.event,this.listenerManager.announceMessageAction(s),this._announce("messageAction",s,s.channel,s.subscription)}else if(4===e.messageType){(s={}).channel=t,s.subscription=i,s.timetoken=o.publishTimetoken,s.publisher=e.issuingClientId;var y=e.payload;if(this.modules.cryptoModule){var g=void 0;try{g=(m=this.modules.cryptoModule.decrypt(e.payload))instanceof ArrayBuffer?JSON.parse(this._decoder.decode(m)):m}catch(e){g=null,s.error="Error while decrypting message content: ".concat(e.message)}null!==g&&(y=g)}e.userMetadata&&(s.userMetadata=e.userMetadata),s.message=y.message,s.file={id:y.file.id,name:y.file.name,url:this.getFileUrl({id:y.file.id,name:y.file.name,channel:t})},this.listenerManager.announceFile(s),this._announce("file",s,s.channel,s.subscription)}else{if((s={channel:null,subscription:null}).channel=t,s.subscription=i,s.timetoken=o.publishTimetoken,s.publisher=e.issuingClientId,e.userMetadata&&(s.userMetadata=e.userMetadata),this.modules.cryptoModule){g=void 0;try{var m;g=(m=this.modules.cryptoModule.decrypt(e.payload))instanceof ArrayBuffer?JSON.parse(this._decoder.decode(m)):m}catch(e){g=null,s.error="Error while decrypting message content: ".concat(e.message)}s.message=null!=g?g:e.payload}else s.message=e.payload;s.actualChannel=null!=i?t:null,s.subscribedChannel=null!=i?i:t,this.listenerManager.announceMessage(s),this._announce("message",s,s.channel,s.subscription)}},e.prototype.addListener=function(e,t,n){var r=this;t&&n?(null==t||t.forEach((function(t){r._channelListenerMap[t]?r._channelListenerMap[t].includes(e)||r._channelListenerMap[t].push(e):r._channelListenerMap[t]=[e]})),null==n||n.forEach((function(t){r._groupListenerMap[t]?r._groupListenerMap[t].includes(e)||r._groupListenerMap[t].push(e):r._groupListenerMap[t]=[e]}))):this.listenerManager.addListener(e)},e.prototype.removeListener=function(e,t,n){var r=this;t&&n?(null==t||t.forEach((function(t){var n;r._channelListenerMap[t]=null===(n=r._channelListenerMap[t])||void 0===n?void 0:n.filter((function(t){return t!==e}))})),null==n||n.forEach((function(t){var n;r._groupListenerMap[t]=null===(n=r._groupListenerMap[t])||void 0===n?void 0:n.filter((function(t){return t!==e}))}))):this.listenerManager.removeListener(e)},e.prototype.removeAllListeners=function(){this.listenerManager.removeAllListeners()},e.prototype._renameEvent=function(e){return"set"===e?"updated":"removed"},e.prototype._renameChannelField=function(e){var t=e.channel,n=r(e,["channel"]);return n.spaceId=t,n},e.prototype._announce=function(e,t,n,r){var o,i;null===(o=this._channelListenerMap[n])||void 0===o||o.forEach((function(n){return n[e]&&n[e](t)})),null===(i=this._groupListenerMap[r])||void 0===i||i.forEach((function(n){return n[e]&&n[e](t)}))},e}(),hn=function(){function e(){}return e.prototype.subscribe=function(){var e,t;this.pubnub.subscribe(n({channels:this.channelNames,channelGroups:this.groupNames},(null===(t=null===(e=this.options)||void 0===e?void 0:e.cursor)||void 0===t?void 0:t.timetoken)&&{timetoken:this.options.cursor.timetoken}))},e.prototype.unsubscribe=function(){this.pubnub.unsubscribe({channels:this.channelNames.filter((function(e){return!e.endsWith("-pnpres")})),channelGroups:this.groupNames.filter((function(e){return!e.endsWith("-pnpres")}))})},Object.defineProperty(e.prototype,"onMessage",{set:function(e){this.listener.message=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onPresence",{set:function(e){this.listener.presence=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onSignal",{set:function(e){this.listener.signal=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onObjects",{set:function(e){this.listener.objects=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onMessageAction",{set:function(e){this.listener.messageAction=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onFile",{set:function(e){this.listener.file=e},enumerable:!1,configurable:!0}),e.prototype.addListener=function(e){this.eventEmitter.addListener(e,this.channelNames.filter((function(e){return!e.endsWith("-pnpres")})),this.groupNames.filter((function(e){return!e.endsWith("-pnpres")})))},e.prototype.removeListener=function(e){this.eventEmitter.removeListener(e,this.channelNames,this.groupNames)},Object.defineProperty(e.prototype,"channels",{get:function(){return this.channelNames.slice(0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"channelGroups",{get:function(){return this.groupNames.slice(0)},enumerable:!1,configurable:!0}),e}(),fn=function(e){function n(t){var n=t.channels,r=void 0===n?[]:n,o=t.channelGroups,i=void 0===o?[]:o,s=t.subscriptionOptions,c=t.eventEmitter,l=t.pubnub,p=e.call(this)||this;return p.channelNames=[],p.groupNames=[],p.subscriptionList=[],p.options=s,p.eventEmitter=c,p.pubnub=l,r.forEach((function(e){var t=p.pubnub.channel(e).subscription(p.options);p.channelNames=u(u([],a(p.channelNames),!1),a(t.channels),!1),p.subscriptionList.push(t)})),i.forEach((function(e){var t=p.pubnub.channelGroup(e).subscription(p.options);p.groupNames=u(u([],a(p.groupNames),!1),a(t.channelGroups),!1),p.subscriptionList.push(t)})),p.listener={},c.addListener(p.listener,p.channelNames.filter((function(e){return!e.endsWith("-pnpres")})),p.groupNames.filter((function(e){return!e.endsWith("-pnpres")}))),p}return t(n,e),n.prototype.addSubscription=function(e){this.subscriptionList.push(e),this.channelNames=u(u([],a(this.channelNames),!1),a(e.channels),!1),this.groupNames=u(u([],a(this.groupNames),!1),a(e.channelGroups),!1)},n.prototype.removeSubscription=function(e){var t=e.channels,n=e.channelGroups;this.channelNames=this.channelNames.filter((function(e){return!t.includes(e)})),this.groupNames=this.groupNames.filter((function(e){return!n.includes(e)})),this.subscriptionList=this.subscriptionList.filter((function(t){return t!==e}))},n.prototype.addSubscriptionSet=function(e){this.subscriptionList=u(u([],a(this.subscriptionList),!1),a(e.subscriptions),!1),this.channelNames=u(u([],a(this.channelNames),!1),a(e.channels),!1),this.groupNames=u(u([],a(this.groupNames),!1),a(e.channelGroups),!1)},n.prototype.removeSubscriptionSet=function(e){var t=e.channels,n=e.channelGroups;this.channelNames=this.channelNames.filter((function(e){return!t.includes(e)})),this.groupNames=this.groupNames.filter((function(e){return!n.includes(e)})),this.subscriptionList=this.subscriptionList.filter((function(t){return!e.subscriptions.includes(t)}))},Object.defineProperty(n.prototype,"subscriptions",{get:function(){return this.subscriptionList.slice(0)},enumerable:!1,configurable:!0}),n}(hn),dn=function(e){function r(t){var n=t.channels,r=t.channelGroups,o=t.subscriptionOptions,i=t.eventEmitter,s=t.pubnub,a=e.call(this)||this;return a.channelNames=[],a.groupNames=[],a.channelNames=n,a.groupNames=r,a.options=o,a.pubnub=s,a.eventEmitter=i,a.listener={},i.addListener(a.listener,a.channelNames.filter((function(e){return!e.endsWith("-pnpres")})),a.groupNames.filter((function(e){return!e.endsWith("-pnpres")}))),a}return t(r,e),r.prototype.addSubscription=function(e){return new fn({channels:u(u([],a(this.channelNames),!1),a(e.channels),!1),channelGroups:u(u([],a(this.groupNames),!1),a(e.channelGroups),!1),subscriptionOptions:n(n({},this.options),null==e?void 0:e.options),eventEmitter:this.eventEmitter,pubnub:this.pubnub})},r}(hn),yn=function(){function e(e,t,n){this.name=e,this.eventEmitter=t,this.pubnub=n}return e.prototype.subscription=function(e){return new dn({channels:(null==e?void 0:e.receivePresenceEvents)?[this.name,"".concat(this.name,"-pnpres")]:[this.name],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})},e}(),gn=function(){function e(e,t,n){this.name=e,this.eventEmitter=t,this.pubnub=n}return e.prototype.subscription=function(e){return new dn({channels:[],channelGroups:(null==e?void 0:e.receivePresenceEvents)?[this.name,"".concat(this.name,"-pnpres")]:[this.name],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})},e}(),mn=function(){function e(e,t,n){this.id=e,this.eventEmitter=t,this.pubnub=n}return e.prototype.subscription=function(e){return new dn({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})},e}(),bn=function(){function e(e,t,n){this.id=e,this.eventEmitter=t,this.pubnub=n}return e.prototype.subscription=function(e){return new dn({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})},e}(),vn=function(){function e(e){var t=this,r=e.networking,o=e.cbor,i=new g({setup:e});this._config=i;var c=new T({config:i}),l=e.cryptography;r.init(i);var p=new G(i,o);this._tokenManager=p;var h=new R({maximumSamplesCount:6e4});this._telemetryManager=h;var f=this._config.cryptoModule,d={config:i,networking:r,crypto:c,cryptography:l,tokenManager:p,telemetryManager:h,PubNubFile:e.PubNubFile,cryptoModule:f};this.File=e.PubNubFile,this.encryptFile=function(e,t){return 1==arguments.length&&"string"!=typeof e&&d.cryptoModule?(t=e,d.cryptoModule.encryptFile(t,this.File)):l.encryptFile(e,t,this.File)},this.decryptFile=function(e,t){return 1==arguments.length&&"string"!=typeof e&&d.cryptoModule?(t=e,d.cryptoModule.decryptFile(t,this.File)):l.decryptFile(e,t,this.File)};var y=Q.bind(this,d,Je),m=Q.bind(this,d,se),v=Q.bind(this,d,ue),_=Q.bind(this,d,le),S=Q.bind(this,d,$e),w=new L;if(this._listenerManager=w,this.iAmHere=Q.bind(this,d,ue),this.iAmAway=Q.bind(this,d,se),this.setPresenceState=Q.bind(this,d,le),this.handshake=Q.bind(this,d,Qe),this.receiveMessages=Q.bind(this,d,Xe),this._eventEmitter=new pn({modules:d,listenerManager:this._listenerManager,getFileUrl:function(e){return ve(d,e)}}),!0===i.enableEventEngine){if(i.maintainPresenceState&&(this.presenceState={},this.setState=function(e){var n,r;return null===(n=e.channels)||void 0===n||n.forEach((function(n){return t.presenceState[n]=e.state})),null===(r=e.channelGroups)||void 0===r||r.forEach((function(n){return t.presenceState[n]=e.state})),t.setPresenceState({channels:e.channels,channelGroups:e.channelGroups,state:t.presenceState})}),i.getHeartbeatInterval()){var O=new cn({heartbeat:this.iAmHere,leave:this.iAmAway,heartbeatDelay:function(){return new Promise((function(e){return setTimeout(e,1e3*d.config.getHeartbeatInterval())}))},retryDelay:function(e){return new Promise((function(t){return setTimeout(t,e)}))},config:d.config,presenceState:this.presenceState,emitStatus:function(e){w.announceStatus(e)}});this.presenceEventEngine=O,this.join=this.presenceEventEngine.join.bind(O),this.leave=this.presenceEventEngine.leave.bind(O),this.leaveAll=this.presenceEventEngine.leaveAll.bind(O)}var P=new Gt({handshake:this.handshake,receiveMessages:this.receiveMessages,delay:function(e){return new Promise((function(t){return setTimeout(t,e)}))},join:this.join,leave:this.leave,leaveAll:this.leaveAll,presenceState:this.presenceState,config:d.config,emitMessages:function(e){var n,r;try{for(var o=s(e),i=o.next();!i.done;i=o.next()){var a=i.value;t._eventEmitter.emitEvent(a)}}catch(e){n={error:e}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}},emitStatus:function(e){w.announceStatus(e)}});this.subscribe=P.subscribe.bind(P),this.unsubscribe=P.unsubscribe.bind(P),this.unsubscribeAll=P.unsubscribeAll.bind(P),this.reconnect=P.reconnect.bind(P),this.disconnect=P.disconnect.bind(P),this.destroy=P.dispose.bind(P),this.getSubscribedChannels=P.getSubscribedChannels.bind(P),this.getSubscribedChannelGroups=P.getSubscribedChannelGroups.bind(P),this.eventEngine=P}else{var E=new M({timeEndpoint:y,leaveEndpoint:m,heartbeatEndpoint:v,setStateEndpoint:_,subscribeEndpoint:S,crypto:d.crypto,config:d.config,listenerManager:w,getFileUrl:function(e){return ve(d,e)},cryptoModule:d.cryptoModule,eventEmitter:this._eventEmitter});this.subscribe=E.adaptSubscribeChange.bind(E),this.unsubscribe=E.adaptUnsubscribeChange.bind(E),this.disconnect=E.disconnect.bind(E),this.reconnect=E.reconnect.bind(E),this.unsubscribeAll=E.unsubscribeAll.bind(E),this.getSubscribedChannels=E.getSubscribedChannels.bind(E),this.getSubscribedChannelGroups=E.getSubscribedChannelGroups.bind(E),this.setState=E.adaptStateChange.bind(E),this.presence=E.adaptPresenceChange.bind(E),this.destroy=function(e){E.unsubscribeAll(e),E.disconnect()}}this.addListener=this._eventEmitter.addListener.bind(this._eventEmitter),this.removeListener=this._eventEmitter.removeListener.bind(this._eventEmitter),this.removeAllListeners=this._eventEmitter.removeAllListeners.bind(this._eventEmitter),this.parseToken=p.parseToken.bind(p),this.setToken=p.setToken.bind(p),this.getToken=p.getToken.bind(p),this.channelGroups={listGroups:Q.bind(this,d,ee),listChannels:Q.bind(this,d,te),addChannels:Q.bind(this,d,X),removeChannels:Q.bind(this,d,Y),deleteGroup:Q.bind(this,d,Z)},this.push={addChannels:Q.bind(this,d,ne),removeChannels:Q.bind(this,d,re),deleteDevice:Q.bind(this,d,ie),listChannels:Q.bind(this,d,oe)},this.hereNow=Q.bind(this,d,pe),this.whereNow=Q.bind(this,d,ae),this.getState=Q.bind(this,d,ce),this.grant=Q.bind(this,d,Ue),this.grantToken=Q.bind(this,d,Le),this.audit=Q.bind(this,d,xe),this.revokeToken=Q.bind(this,d,Ge),this.publish=Q.bind(this,d,Be),this.fire=function(e,n){return e.replicate=!1,e.storeInHistory=!1,t.publish(e,n)},this.signal=Q.bind(this,d,He),this.history=Q.bind(this,d,qe),this.deleteMessages=Q.bind(this,d,ze),this.messageCounts=Q.bind(this,d,Ve),this.fetchMessages=Q.bind(this,d,We),this.addMessageAction=Q.bind(this,d,he),this.removeMessageAction=Q.bind(this,d,fe),this.getMessageActions=Q.bind(this,d,de),this.listFiles=Q.bind(this,d,ye);var A=Q.bind(this,d,ge);this.publishFile=Q.bind(this,d,me),this.sendFile=be({generateUploadUrl:A,publishFile:this.publishFile,modules:d}),this.getFileUrl=function(e){return ve(d,e)},this.downloadFile=Q.bind(this,d,_e),this.deleteFile=Q.bind(this,d,Se),this.channel=function(e){return new yn(e,t._eventEmitter,t)},this.channelGroup=function(e){return new gn(e,t._eventEmitter,t)},this.channelMetadata=function(e){return new mn(e,t._eventEmitter,t)},this.userMetadata=function(e){return new bn(e,t._eventEmitter,t)},this.subscriptionSet=function(e){return new fn({channels:e.channels,channelGroups:e.channelGroups,subscriptionOptions:e.subscriptionOptions,eventEmitter:t._eventEmitter,pubnub:t})},this.objects={getAllUUIDMetadata:Q.bind(this,d,we),getUUIDMetadata:Q.bind(this,d,Oe),setUUIDMetadata:Q.bind(this,d,Pe),removeUUIDMetadata:Q.bind(this,d,Ee),getAllChannelMetadata:Q.bind(this,d,Ae),getChannelMetadata:Q.bind(this,d,Te),setChannelMetadata:Q.bind(this,d,Ne),removeChannelMetadata:Q.bind(this,d,Ce),getChannelMembers:Q.bind(this,d,ke),setChannelMembers:function(e){for(var r=[],o=1;o=this._config.origin.length&&(this._currentSubDomain=0);var t=this._config.origin[this._currentSubDomain];return"".concat(e).concat(t)},e.prototype.hasModule=function(e){return e in this._modules},e.prototype.shiftStandardOrigin=function(){return this._standardOrigin=this.nextOrigin(),this._standardOrigin},e.prototype.getStandardOrigin=function(){return this._standardOrigin},e.prototype.POSTFILE=function(e,t,n){return this._modules.postfile(e,t,n)},e.prototype.GETFILE=function(e,t,n){return this._modules.getfile(e,t,n)},e.prototype.POST=function(e,t,n,r){return this._modules.post(e,t,n,r)},e.prototype.PATCH=function(e,t,n,r){return this._modules.patch(e,t,n,r)},e.prototype.GET=function(e,t,n){return this._modules.get(e,t,n)},e.prototype.DELETE=function(e,t,n){return this._modules.del(e,t,n)},e.prototype._detectErrorCategory=function(e){if("ENOTFOUND"===e.code)return k.PNNetworkIssuesCategory;if("ECONNREFUSED"===e.code)return k.PNNetworkIssuesCategory;if("ECONNRESET"===e.code)return k.PNNetworkIssuesCategory;if("EAI_AGAIN"===e.code)return k.PNNetworkIssuesCategory;if(0===e.status||e.hasOwnProperty("status")&&void 0===e.status)return k.PNNetworkIssuesCategory;if(e.timeout)return k.PNTimeoutCategory;if("ETIMEDOUT"===e.code)return k.PNNetworkIssuesCategory;if(e.response){if(e.response.badRequest)return k.PNBadRequestCategory;if(e.response.forbidden)return k.PNAccessDeniedCategory}return k.PNUnknownCategory},e}();function Sn(e){var t=function(e){return e&&"object"==typeof e&&e.constructor===Object};if(!t(e))return e;var n={};return Object.keys(e).forEach((function(r){var o=function(e){return"string"==typeof e||e instanceof String}(r),i=r,s=e[r];Array.isArray(r)||o&&r.indexOf(",")>=0?i=(o?r.split(","):r).reduce((function(e,t){return e+=String.fromCharCode(t)}),""):(function(e){return"number"==typeof e&&isFinite(e)}(r)||o&&!isNaN(r))&&(i=String.fromCharCode(o?parseInt(r,10):10));n[i]=t(s)?Sn(s):s})),n}var wn=function(){function e(e,t){this._base64ToBinary=t,this._decode=e}return e.prototype.decodeToken=function(e){var t="";e.length%4==3?t="=":e.length%4==2&&(t="==");var n=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,r=this._decode(this._base64ToBinary(n));if("object"==typeof r)return r},e}(),On={exports:{}},Pn={exports:{}};!function(e){function t(e){if(e)return function(e){for(var n in t.prototype)e[n]=t.prototype[n];return e}(e)}e.exports=t,t.prototype.on=t.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},t.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},t.prototype.off=t.prototype.removeListener=t.prototype.removeAllListeners=t.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var o=0;os.depthLimit)return void jn(An,e,t,o);if(void 0!==s.edgesLimit&&n+1>s.edgesLimit)return void jn(An,e,t,o);if(r.push(e),Array.isArray(e))for(a=0;at?1:0}function Un(e,t,n,r){void 0===r&&(r=kn());var o,i=In(e,"",0,[],void 0,0,r)||e;try{o=0===Cn.length?JSON.stringify(i,t,n):JSON.stringify(i,Dn(t),n)}catch(e){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Nn.length;){var s=Nn.pop();4===s.length?Object.defineProperty(s[0],s[1],s[3]):s[0][s[1]]=s[2]}}return o}function In(e,t,n,r,o,i,s){var a;if(i+=1,"object"==typeof e&&null!==e){for(a=0;as.depthLimit)return void jn(An,e,t,o);if(void 0!==s.edgesLimit&&n+1>s.edgesLimit)return void jn(An,e,t,o);if(r.push(e),Array.isArray(e))for(a=0;a0)for(var r=0;r1&&"boolean"!=typeof t)throw new Qn('"allowMissing" argument must be a boolean');var n=gr(e),r=n.length>0?n[0]:"",o=mr("%"+r+"%",t),i=o.name,s=o.value,a=!1,u=o.alias;u&&(r=u[0],pr(n,lr([0,1],u)));for(var c=1,l=!0;c=n.length){var d=Yn(s,p);s=(l=!!d)&&"get"in d&&!("originalValue"in d.get)?d.get:s[p]}else l=cr(s,p),s=s[p];l&&!a&&(ir[i]=s)}}return s},vr={exports:{}};!function(e){var t=Vn,n=br,r=n("%Function.prototype.apply%"),o=n("%Function.prototype.call%"),i=n("%Reflect.apply%",!0)||t.call(o,r),s=n("%Object.getOwnPropertyDescriptor%",!0),a=n("%Object.defineProperty%",!0),u=n("%Math.max%");if(a)try{a({},"a",{value:1})}catch(e){a=null}e.exports=function(e){var n=i(t,o,arguments);if(s&&a){var r=s(n,"length");r.configurable&&a(n,"length",{value:1+u(0,e.length-(arguments.length-1))})}return n};var c=function(){return i(t,r,arguments)};a?a(e.exports,"apply",{value:c}):e.exports.apply=c}(vr);var _r=br,Sr=vr.exports,wr=Sr(_r("String.prototype.indexOf")),Or=l(Object.freeze({__proto__:null,default:{}})),Pr="function"==typeof Map&&Map.prototype,Er=Object.getOwnPropertyDescriptor&&Pr?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,Ar=Pr&&Er&&"function"==typeof Er.get?Er.get:null,Tr=Pr&&Map.prototype.forEach,Nr="function"==typeof Set&&Set.prototype,Cr=Object.getOwnPropertyDescriptor&&Nr?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,kr=Nr&&Cr&&"function"==typeof Cr.get?Cr.get:null,Mr=Nr&&Set.prototype.forEach,jr="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,Rr="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,xr="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,Ur=Boolean.prototype.valueOf,Ir=Object.prototype.toString,Dr=Function.prototype.toString,Fr=String.prototype.match,Lr=String.prototype.slice,Gr=String.prototype.replace,Kr=String.prototype.toUpperCase,Br=String.prototype.toLowerCase,Hr=RegExp.prototype.test,qr=Array.prototype.concat,zr=Array.prototype.join,Vr=Array.prototype.slice,Wr=Math.floor,Jr="function"==typeof BigInt?BigInt.prototype.valueOf:null,$r=Object.getOwnPropertySymbols,Qr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,Xr="function"==typeof Symbol&&"object"==typeof Symbol.iterator,Yr="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===Xr||"symbol")?Symbol.toStringTag:null,Zr=Object.prototype.propertyIsEnumerable,eo=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function to(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||Hr.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-Wr(-e):Wr(e);if(r!==e){var o=String(r),i=Lr.call(t,o.length+1);return Gr.call(o,n,"$&_")+"."+Gr.call(Gr.call(i,/([0-9]{3})/g,"$&_"),/_$/,"")}}return Gr.call(t,n,"$&_")}var no=Or,ro=no.custom,oo=co(ro)?ro:null;function io(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function so(e){return Gr.call(String(e),/"/g,""")}function ao(e){return!("[object Array]"!==ho(e)||Yr&&"object"==typeof e&&Yr in e)}function uo(e){return!("[object RegExp]"!==ho(e)||Yr&&"object"==typeof e&&Yr in e)}function co(e){if(Xr)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Qr)return!1;try{return Qr.call(e),!0}catch(e){}return!1}var lo=Object.prototype.hasOwnProperty||function(e){return e in this};function po(e,t){return lo.call(e,t)}function ho(e){return Ir.call(e)}function fo(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0,r=e.length;nt.maxStringLength){var n=e.length-t.maxStringLength,r="... "+n+" more character"+(n>1?"s":"");return yo(Lr.call(e,0,t.maxStringLength),t)+r}return io(Gr.call(Gr.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,go),"single",t)}function go(e){var t=e.charCodeAt(0),n={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return n?"\\"+n:"\\x"+(t<16?"0":"")+Kr.call(t.toString(16))}function mo(e){return"Object("+e+")"}function bo(e){return e+" { ? }"}function vo(e,t,n,r){return e+" ("+t+") {"+(r?_o(n,r):zr.call(n,", "))+"}"}function _o(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+zr.call(e,","+n)+"\n"+t.prev}function So(e,t){var n=ao(e),r=[];if(n){r.length=e.length;for(var o=0;o-1?Sr(n):n},Po=function e(t,n,r,o){var i=n||{};if(po(i,"quoteStyle")&&"single"!==i.quoteStyle&&"double"!==i.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(po(i,"maxStringLength")&&("number"==typeof i.maxStringLength?i.maxStringLength<0&&i.maxStringLength!==1/0:null!==i.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var s=!po(i,"customInspect")||i.customInspect;if("boolean"!=typeof s&&"symbol"!==s)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(po(i,"indent")&&null!==i.indent&&"\t"!==i.indent&&!(parseInt(i.indent,10)===i.indent&&i.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(po(i,"numericSeparator")&&"boolean"!=typeof i.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var a=i.numericSeparator;if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return yo(t,i);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var u=String(t);return a?to(t,u):u}if("bigint"==typeof t){var l=String(t)+"n";return a?to(t,l):l}var p=void 0===i.depth?5:i.depth;if(void 0===r&&(r=0),r>=p&&p>0&&"object"==typeof t)return ao(t)?"[Array]":"[Object]";var h=function(e,t){var n;if("\t"===e.indent)n="\t";else{if(!("number"==typeof e.indent&&e.indent>0))return null;n=zr.call(Array(e.indent+1)," ")}return{base:n,prev:zr.call(Array(t+1),n)}}(i,r);if(void 0===o)o=[];else if(fo(o,t)>=0)return"[Circular]";function f(t,n,s){if(n&&(o=Vr.call(o)).push(n),s){var a={depth:i.depth};return po(i,"quoteStyle")&&(a.quoteStyle=i.quoteStyle),e(t,a,r+1,o)}return e(t,i,r+1,o)}if("function"==typeof t&&!uo(t)){var d=function(e){if(e.name)return e.name;var t=Fr.call(Dr.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),y=So(t,f);return"[Function"+(d?": "+d:" (anonymous)")+"]"+(y.length>0?" { "+zr.call(y,", ")+" }":"")}if(co(t)){var g=Xr?Gr.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):Qr.call(t);return"object"!=typeof t||Xr?g:mo(g)}if(function(e){if(!e||"object"!=typeof e)return!1;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return!0;return"string"==typeof e.nodeName&&"function"==typeof e.getAttribute}(t)){for(var m="<"+Br.call(String(t.nodeName)),b=t.attributes||[],v=0;v"}if(ao(t)){if(0===t.length)return"[]";var _=So(t,f);return h&&!function(e){for(var t=0;t=0)return!1;return!0}(_)?"["+_o(_,h)+"]":"[ "+zr.call(_,", ")+" ]"}if(function(e){return!("[object Error]"!==ho(e)||Yr&&"object"==typeof e&&Yr in e)}(t)){var S=So(t,f);return"cause"in Error.prototype||!("cause"in t)||Zr.call(t,"cause")?0===S.length?"["+String(t)+"]":"{ ["+String(t)+"] "+zr.call(S,", ")+" }":"{ ["+String(t)+"] "+zr.call(qr.call("[cause]: "+f(t.cause),S),", ")+" }"}if("object"==typeof t&&s){if(oo&&"function"==typeof t[oo]&&no)return no(t,{depth:p-r});if("symbol"!==s&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!Ar||!e||"object"!=typeof e)return!1;try{Ar.call(e);try{kr.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var w=[];return Tr&&Tr.call(t,(function(e,n){w.push(f(n,t,!0)+" => "+f(e,t))})),vo("Map",Ar.call(t),w,h)}if(function(e){if(!kr||!e||"object"!=typeof e)return!1;try{kr.call(e);try{Ar.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var O=[];return Mr&&Mr.call(t,(function(e){O.push(f(e,t))})),vo("Set",kr.call(t),O,h)}if(function(e){if(!jr||!e||"object"!=typeof e)return!1;try{jr.call(e,jr);try{Rr.call(e,Rr)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return bo("WeakMap");if(function(e){if(!Rr||!e||"object"!=typeof e)return!1;try{Rr.call(e,Rr);try{jr.call(e,jr)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return bo("WeakSet");if(function(e){if(!xr||!e||"object"!=typeof e)return!1;try{return xr.call(e),!0}catch(e){}return!1}(t))return bo("WeakRef");if(function(e){return!("[object Number]"!==ho(e)||Yr&&"object"==typeof e&&Yr in e)}(t))return mo(f(Number(t)));if(function(e){if(!e||"object"!=typeof e||!Jr)return!1;try{return Jr.call(e),!0}catch(e){}return!1}(t))return mo(f(Jr.call(t)));if(function(e){return!("[object Boolean]"!==ho(e)||Yr&&"object"==typeof e&&Yr in e)}(t))return mo(Ur.call(t));if(function(e){return!("[object String]"!==ho(e)||Yr&&"object"==typeof e&&Yr in e)}(t))return mo(f(String(t)));if("undefined"!=typeof window&&t===window)return"{ [object Window] }";if(t===c)return"{ [object globalThis] }";if(!function(e){return!("[object Date]"!==ho(e)||Yr&&"object"==typeof e&&Yr in e)}(t)&&!uo(t)){var P=So(t,f),E=eo?eo(t)===Object.prototype:t instanceof Object||t.constructor===Object,A=t instanceof Object?"":"null prototype",T=!E&&Yr&&Object(t)===t&&Yr in t?Lr.call(ho(t),8,-1):A?"Object":"",N=(E||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(T||A?"["+zr.call(qr.call([],T||[],A||[]),": ")+"] ":"");return 0===P.length?N+"{}":h?N+"{"+_o(P,h)+"}":N+"{ "+zr.call(P,", ")+" }"}return String(t)},Eo=wo("%TypeError%"),Ao=wo("%WeakMap%",!0),To=wo("%Map%",!0),No=Oo("WeakMap.prototype.get",!0),Co=Oo("WeakMap.prototype.set",!0),ko=Oo("WeakMap.prototype.has",!0),Mo=Oo("Map.prototype.get",!0),jo=Oo("Map.prototype.set",!0),Ro=Oo("Map.prototype.has",!0),xo=function(e,t){for(var n,r=e;null!==(n=r.next);r=n)if(n.key===t)return r.next=n.next,n.next=e.next,e.next=n,n},Uo=String.prototype.replace,Io=/%20/g,Do="RFC3986",Fo={default:Do,formatters:{RFC1738:function(e){return Uo.call(e,Io,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:Do},Lo=Fo,Go=Object.prototype.hasOwnProperty,Ko=Array.isArray,Bo=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),Ho=function(e,t){for(var n=t&&t.plainObjects?Object.create(null):{},r=0;r1;){var t=e.pop(),n=t.obj[t.prop];if(Ko(n)){for(var r=[],o=0;o=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||o===Lo.RFC1738&&(40===u||41===u)?s+=i.charAt(a):u<128?s+=Bo[u]:u<2048?s+=Bo[192|u>>6]+Bo[128|63&u]:u<55296||u>=57344?s+=Bo[224|u>>12]+Bo[128|u>>6&63]+Bo[128|63&u]:(a+=1,u=65536+((1023&u)<<10|1023&i.charCodeAt(a)),s+=Bo[240|u>>18]+Bo[128|u>>12&63]+Bo[128|u>>6&63]+Bo[128|63&u])}return s},isBuffer:function(e){return!(!e||"object"!=typeof e)&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))},isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},maybeMap:function(e,t){if(Ko(e)){for(var n=[],r=0;r0?b.join(",")||null:void 0}];else if(Qo(u))O=u;else{var E=Object.keys(b);O=c?E.sort(c):E}for(var A=o&&Qo(b)&&1===b.length?n+"[]":n,T=0;T-1?e.split(","):e},li=function(e,t,n,r){if(e){var o=n.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,i=/(\[[^[\]]*])/g,s=n.depth>0&&/(\[[^[\]]*])/.exec(o),a=s?o.slice(0,s.index):o,u=[];if(a){if(!n.plainObjects&&ii.call(Object.prototype,a)&&!n.allowPrototypes)return;u.push(a)}for(var c=0;n.depth>0&&null!==(s=i.exec(o))&&c=0;--i){var s,a=e[i];if("[]"===a&&n.parseArrays)s=[].concat(o);else{s=n.plainObjects?Object.create(null):{};var u="["===a.charAt(0)&&"]"===a.charAt(a.length-1)?a.slice(1,-1):a,c=parseInt(u,10);n.parseArrays||""!==u?!isNaN(c)&&a!==u&&String(c)===u&&c>=0&&n.parseArrays&&c<=n.arrayLimit?(s=[])[c]=o:"__proto__"!==u&&(s[u]=o):s={0:o}}o=s}return o}(u,t,n,r)}},pi=function(e,t){var n,r=e,o=function(e){if(!e)return ti;if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");var t=e.charset||ti.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var n=Wo.default;if(void 0!==e.format){if(!Jo.call(Wo.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=Wo.formatters[n],o=ti.filter;return("function"==typeof e.filter||Qo(e.filter))&&(o=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:ti.addQueryPrefix,allowDots:void 0===e.allowDots?ti.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:ti.charsetSentinel,delimiter:void 0===e.delimiter?ti.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:ti.encode,encoder:"function"==typeof e.encoder?e.encoder:ti.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:ti.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:ti.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:ti.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:ti.strictNullHandling}}(t);"function"==typeof o.filter?r=(0,o.filter)("",r):Qo(o.filter)&&(n=o.filter);var i,s=[];if("object"!=typeof r||null===r)return"";i=t&&t.arrayFormat in $o?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var a=$o[i];if(t&&"commaRoundTrip"in t&&"boolean"!=typeof t.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var u="comma"===a&&t&&t.commaRoundTrip;n||(n=Object.keys(r)),o.sort&&n.sort(o.sort);for(var c=zo(),l=0;l0?f+h:""},hi={formats:Fo,parse:function(e,t){var n=function(e){if(!e)return ai;if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var t=void 0===e.charset?ai.charset:e.charset;return{allowDots:void 0===e.allowDots?ai.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:ai.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:ai.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:ai.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:ai.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:ai.comma,decoder:"function"==typeof e.decoder?e.decoder:ai.decoder,delimiter:"string"==typeof e.delimiter||oi.isRegExp(e.delimiter)?e.delimiter:ai.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:ai.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:ai.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:ai.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:ai.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:ai.strictNullHandling}}(t);if(""===e||null==e)return n.plainObjects?Object.create(null):{};for(var r="string"==typeof e?function(e,t){var n,r={__proto__:null},o=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,i=t.parameterLimit===1/0?void 0:t.parameterLimit,s=o.split(t.delimiter,i),a=-1,u=t.charset;if(t.charsetSentinel)for(n=0;n-1&&(l=si(l)?[l]:l),ii.call(r,c)?r[c]=oi.combine(r[c],l):r[c]=l}return r}(e,n):e,o=n.plainObjects?Object.create(null):{},i=Object.keys(r),s=0;s=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:i}}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 s,a=!0,u=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){u=!0,s=e},f:function(){try{a||null==r.return||r.return()}finally{if(u)throw s}}}}function n(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.split(/ *; */).shift(),e.params=e=>{const n={};var r,o=t(e.split(/ *; */));try{for(o.s();!(r=o.n()).done;){const e=r.value.split(/ *= */),t=e.shift(),o=e.shift();t&&o&&(n[t]=o)}}catch(e){o.e(e)}finally{o.f()}return n},e.parseLinks=e=>{const n={};var r,o=t(e.split(/ *, */));try{for(o.s();!(r=o.n()).done;){const e=r.value.split(/ *; */),t=e[0].slice(1,-1);n[e[1].split(/ *= */)[1].slice(1,-1)]=t}}catch(e){o.e(e)}finally{o.f()}return n},e.cleanHeader=(e,t)=>(delete e["content-type"],delete e["content-length"],delete e["transfer-encoding"],delete e.host,t&&(delete e.authorization,delete e.cookie),e),e.isObject=e=>null!==e&&"object"==typeof e,e.hasOwn=Object.hasOwn||function(e,t){if(null==e)throw new TypeError("Cannot convert undefined or null to object");return Object.prototype.hasOwnProperty.call(new Object(e),t)},e.mixin=(t,n)=>{for(const r in n)e.hasOwn(n,r)&&(t[r]=n[r])}}(fi);const di=Or,yi=fi.isObject,gi=fi.hasOwn;var mi=bi;function bi(){}bi.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},bi.prototype.parse=function(e){return this._parser=e,this},bi.prototype.responseType=function(e){return this._responseType=e,this},bi.prototype.serialize=function(e){return this._serializer=e,this},bi.prototype.timeout=function(e){if(!e||"object"!=typeof e)return this._timeout=e,this._responseTimeout=0,this._uploadTimeout=0,this;for(const t in e)if(gi(e,t))switch(t){case"deadline":this._timeout=e.deadline;break;case"response":this._responseTimeout=e.response;break;case"upload":this._uploadTimeout=e.upload;break;default:console.warn("Unknown timeout option",t)}return this},bi.prototype.retry=function(e,t){return 0!==arguments.length&&!0!==e||(e=1),e<=0&&(e=0),this._maxRetries=e,this._retries=0,this._retryCallback=t,this};const vi=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),_i=new Set([408,413,429,500,502,503,504,521,522,524]);bi.prototype._shouldRetry=function(e,t){if(!this._maxRetries||this._retries++>=this._maxRetries)return!1;if(this._retryCallback)try{const n=this._retryCallback(e,t);if(!0===n)return!0;if(!1===n)return!1}catch(e){console.error(e)}if(t&&t.status&&_i.has(t.status))return!0;if(e){if(e.code&&vi.has(e.code))return!0;if(e.timeout&&"ECONNABORTED"===e.code)return!0;if(e.crossDomain)return!0}return!1},bi.prototype._retry=function(){return this.clearTimeout(),this.req&&(this.req=null,this.req=this.request()),this._aborted=!1,this.timedout=!1,this.timedoutError=null,this._end()},bi.prototype.then=function(e,t){if(!this._fullfilledPromise){const e=this;this._endCalled&&console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises"),this._fullfilledPromise=new Promise(((t,n)=>{e.on("abort",(()=>{if(this._maxRetries&&this._maxRetries>this._retries)return;if(this.timedout&&this.timedoutError)return void n(this.timedoutError);const e=new Error("Aborted");e.code="ABORTED",e.status=this.status,e.method=this.method,e.url=this.url,n(e)})),e.end(((e,r)=>{e?n(e):t(r)}))}))}return this._fullfilledPromise.then(e,t)},bi.prototype.catch=function(e){return this.then(void 0,e)},bi.prototype.use=function(e){return e(this),this},bi.prototype.ok=function(e){if("function"!=typeof e)throw new Error("Callback required");return this._okCallback=e,this},bi.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},bi.prototype.get=function(e){return this._header[e.toLowerCase()]},bi.prototype.getHeader=bi.prototype.get,bi.prototype.set=function(e,t){if(yi(e)){for(const t in e)gi(e,t)&&this.set(t,e[t]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},bi.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},bi.prototype.field=function(e,t,n){if(null==e)throw new Error(".field(name, val) name can not be empty");if(this._data)throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()");if(yi(e)){for(const t in e)gi(e,t)&&this.field(t,e[t]);return this}if(Array.isArray(t)){for(const n in t)gi(t,n)&&this.field(e,t[n]);return this}if(null==t)throw new Error(".field(name, val) val can not be empty");return"boolean"==typeof t&&(t=String(t)),n?this._getFormData().append(e,t,n):this._getFormData().append(e,t),this},bi.prototype.abort=function(){if(this._aborted)return this;if(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req){if(di.gte(process.version,"v13.0.0")&&di.lt(process.version,"v14.0.0"))throw new Error("Superagent does not work in v13 properly with abort() due to Node.js core changes");this.req.abort()}return this.clearTimeout(),this.emit("abort"),this},bi.prototype._auth=function(e,t,n,r){switch(n.type){case"basic":this.set("Authorization",`Basic ${r(`${e}:${t}`)}`);break;case"auto":this.username=e,this.password=t;break;case"bearer":this.set("Authorization",`Bearer ${e}`)}return this},bi.prototype.withCredentials=function(e){return void 0===e&&(e=!0),this._withCredentials=e,this},bi.prototype.redirects=function(e){return this._maxRedirects=e,this},bi.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw new TypeError("Invalid argument");return this._maxResponseSize=e,this},bi.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},bi.prototype.send=function(e){const t=yi(e);let n=this._header["content-type"];if(this._formData)throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()");if(t&&!this._data)Array.isArray(e)?this._data=[]:this._isHost(e)||(this._data={});else if(e&&this._data&&this._isHost(this._data))throw new Error("Can't merge these send calls");if(t&&yi(this._data))for(const t in e){if("bigint"==typeof e[t]&&!e[t].toJSON)throw new Error("Cannot serialize BigInt value to json");gi(e,t)&&(this._data[t]=e[t])}else{if("bigint"==typeof e)throw new Error("Cannot send value of type BigInt");"string"==typeof e?(n||this.type("form"),n=this._header["content-type"],n&&(n=n.toLowerCase().trim()),this._data="application/x-www-form-urlencoded"===n?this._data?`${this._data}&${e}`:e:(this._data||"")+e):this._data=e}return!t||this._isHost(e)||n||this.type("json"),this},bi.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},bi.prototype._finalizeQueryString=function(){const e=this._query.join("&");if(e&&(this.url+=(this.url.includes("?")?"&":"?")+e),this._query.length=0,this._sort){const e=this.url.indexOf("?");if(e>=0){const t=this.url.slice(e+1).split("&");"function"==typeof this._sort?t.sort(this._sort):t.sort(),this.url=this.url.slice(0,e)+"?"+t.join("&")}}},bi.prototype._appendQueryString=()=>{console.warn("Unsupported")},bi.prototype._timeoutError=function(e,t,n){if(this._aborted)return;const r=new Error(`${e+t}ms exceeded`);r.timeout=t,r.code="ECONNABORTED",r.errno=n,this.timedout=!0,this.timedoutError=r,this.abort(),this.callback(r)},bi.prototype._setTimeouts=function(){const e=this;this._timeout&&!this._timer&&(this._timer=setTimeout((()=>{e._timeoutError("Timeout of ",e._timeout,"ETIME")}),this._timeout)),this._responseTimeout&&!this._responseTimeoutTimer&&(this._responseTimeoutTimer=setTimeout((()=>{e._timeoutError("Response timeout of ",e._responseTimeout,"ETIMEDOUT")}),this._responseTimeout))};const Si=fi;var wi=Oi;function Oi(){}function Pi(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return Ei(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Ei(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,o=function(){};return{s:o,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:o}}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 i,s=!0,a=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){a=!0,i=e},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw i}}}}function Ei(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:i}}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 s,a=!0,u=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){u=!0,s=e},f:function(){try{a||null==n.return||n.return()}finally{if(u)throw s}}}}function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n{if(o.XMLHttpRequest)return new o.XMLHttpRequest;throw new Error("Browser-only version of superagent could not find XHR")};const g="".trim?e=>e.trim():e=>e.replace(/(^\s*|\s*$)/g,"");function m(e){if(!c(e))return e;const t=[];for(const n in e)p(e,n)&&b(t,n,e[n]);return t.join("&")}function b(e,t,r){if(void 0!==r)if(null!==r)if(Array.isArray(r)){var o,i=n(r);try{for(i.s();!(o=i.n()).done;){b(e,t,o.value)}}catch(e){i.e(e)}finally{i.f()}}else if(c(r))for(const n in r)p(r,n)&&b(e,`${t}[${n}]`,r[n]);else e.push(encodeURI(t)+"="+encodeURIComponent(r));else e.push(encodeURI(t))}function v(e){const t={},n=e.split("&");let r,o;for(let e=0,i=n.length;e{let e,t=null,r=null;try{r=new S(n)}catch(e){return t=new Error("Parser is unable to parse the response"),t.parse=!0,t.original=e,n.xhr?(t.rawResponse=void 0===n.xhr.responseType?n.xhr.responseText:n.xhr.response,t.status=n.xhr.status?n.xhr.status:null,t.statusCode=t.status):(t.rawResponse=null,t.status=null),n.callback(t)}n.emit("response",r);try{n._isResponseOK(r)||(e=new Error(r.statusText||r.text||"Unsuccessful HTTP response"))}catch(t){e=t}e?(e.original=t,e.response=r,e.status=e.status||r.status,n.callback(e,r)):n.callback(null,r)}))}y.serializeObject=m,y.parseString=v,y.types={html:"text/html",json:"application/json",xml:"text/xml",urlencoded:"application/x-www-form-urlencoded",form:"application/x-www-form-urlencoded","form-data":"application/x-www-form-urlencoded"},y.serialize={"application/x-www-form-urlencoded":a.stringify,"application/json":s},y.parse={"application/x-www-form-urlencoded":v,"application/json":JSON.parse},l(S.prototype,h.prototype),S.prototype._parseBody=function(e){let t=y.parse[this.type];return this.req._parser?this.req._parser(this,e):(!t&&_(this.type)&&(t=y.parse["application/json"]),t&&e&&(e.length>0||e instanceof Object)?t(e):null)},S.prototype.toError=function(){const e=this.req,t=e.method,n=e.url,r=`cannot ${t} ${n} (${this.status})`,o=new Error(r);return o.status=this.status,o.method=t,o.url=n,o},y.Response=S,i(w.prototype),l(w.prototype,u.prototype),w.prototype.type=function(e){return this.set("Content-Type",y.types[e]||e),this},w.prototype.accept=function(e){return this.set("Accept",y.types[e]||e),this},w.prototype.auth=function(e,t,n){1===arguments.length&&(t=""),"object"==typeof t&&null!==t&&(n=t,t=""),n||(n={type:"function"==typeof btoa?"basic":"auto"});const r=n.encoder?n.encoder:e=>{if("function"==typeof btoa)return btoa(e);throw new Error("Cannot use basic auth, btoa is not a function")};return this._auth(e,t,n,r)},w.prototype.query=function(e){return"string"!=typeof e&&(e=m(e)),e&&this._query.push(e),this},w.prototype.attach=function(e,t,n){if(t){if(this._data)throw new Error("superagent can't mix .send() and .attach()");this._getFormData().append(e,t,n||t.name)}return this},w.prototype._getFormData=function(){return this._formData||(this._formData=new o.FormData),this._formData},w.prototype.callback=function(e,t){if(this._shouldRetry(e,t))return this._retry();const n=this._callback;this.clearTimeout(),e&&(this._maxRetries&&(e.retries=this._retries-1),this.emit("error",e)),n(e,t)},w.prototype.crossDomainError=function(){const e=new Error("Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.");e.crossDomain=!0,e.status=this.status,e.method=this.method,e.url=this.url,this.callback(e)},w.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},w.prototype.ca=w.prototype.agent,w.prototype.buffer=w.prototype.ca,w.prototype.write=()=>{throw new Error("Streaming is not supported in browser version of superagent")},w.prototype.pipe=w.prototype.write,w.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},w.prototype.end=function(e){this._endCalled&&console.warn("Warning: .end() was called twice. This is not supported in superagent"),this._endCalled=!0,this._callback=e||d,this._finalizeQueryString(),this._end()},w.prototype._setUploadTimeout=function(){const e=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((()=>{e._timeoutError("Upload timeout of ",e._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},w.prototype._end=function(){if(this._aborted)return this.callback(new Error("The request has been aborted even before .end() was called"));const e=this;this.xhr=y.getXHR();const t=this.xhr;let n=this._formData||this._data;this._setTimeouts(),t.addEventListener("readystatechange",(()=>{const n=t.readyState;if(n>=2&&e._responseTimeoutTimer&&clearTimeout(e._responseTimeoutTimer),4!==n)return;let r;try{r=t.status}catch(e){r=0}if(!r){if(e.timedout||e._aborted)return;return e.crossDomainError()}e.emit("end")}));const r=(t,n)=>{n.total>0&&(n.percent=n.loaded/n.total*100,100===n.percent&&clearTimeout(e._uploadTimeoutTimer)),n.direction=t,e.emit("progress",n)};if(this.hasListeners("progress"))try{t.addEventListener("progress",r.bind(null,"download")),t.upload&&t.upload.addEventListener("progress",r.bind(null,"upload"))}catch(e){}t.upload&&this._setUploadTimeout();try{this.username&&this.password?t.open(this.method,this.url,!0,this.username,this.password):t.open(this.method,this.url,!0)}catch(e){return this.callback(e)}if(this._withCredentials&&(t.withCredentials=!0),!this._formData&&"GET"!==this.method&&"HEAD"!==this.method&&"string"!=typeof n&&!this._isHost(n)){const e=this._header["content-type"];let t=this._serializer||y.serialize[e?e.split(";")[0]:""];!t&&_(e)&&(t=y.serialize["application/json"]),t&&(n=t(n))}for(const e in this.header)null!==this.header[e]&&p(this.header,e)&&t.setRequestHeader(e,this.header[e]);this._responseType&&(t.responseType=this._responseType),this.emit("request",this),t.send(void 0===n?null:n)},y.agent=()=>new f;for(var O=0,P=["GET","POST","OPTIONS","PATCH","PUT","DELETE"];O{const r=y("GET",e);return"function"==typeof t&&(n=t,t=null),t&&r.query(t),n&&r.end(n),r},y.head=(e,t,n)=>{const r=y("HEAD",e);return"function"==typeof t&&(n=t,t=null),t&&r.query(t),n&&r.end(n),r},y.options=(e,t,n)=>{const r=y("OPTIONS",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},y.del=E,y.delete=E,y.patch=(e,t,n)=>{const r=y("PATCH",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},y.post=(e,t,n)=>{const r=y("POST",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},y.put=(e,t,n)=>{const r=y("PUT",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r}}(On,On.exports);var ki=On.exports;function Mi(e){var t=(new Date).getTime(),n=(new Date).toISOString(),r=console&&console.log?console:window&&window.console&&window.console.log?window.console:console;r.log("<<<<<"),r.log("[".concat(n,"]"),"\n",e.url,"\n",e.qs),r.log("-----"),e.on("response",(function(n){var o=(new Date).getTime()-t,i=(new Date).toISOString();r.log(">>>>>>"),r.log("[".concat(i," / ").concat(o,"]"),"\n",e.url,"\n",e.qs,"\n",n.text),r.log("-----")}))}function ji(e,t,n){var r=this;this._config.logVerbosity&&(e=e.use(Mi)),this._config.proxy&&this._modules.proxy&&(e=this._modules.proxy.call(this,e)),this._config.keepAlive&&this._modules.keepAlive&&(e=this._modules.keepAlive(e));var o=e;if(t.abortSignal)var i=t.abortSignal.subscribe((function(){o.abort(),i()}));return!0===t.forceBuffered?o="undefined"==typeof Blob?o.buffer().responseType("arraybuffer"):o.responseType("arraybuffer"):!1===t.forceBuffered&&(o=o.buffer(!1)),(o=o.timeout(t.timeout)).on("abort",(function(){return n({category:k.PNUnknownCategory,error:!0,operation:t.operation,errorData:new Error("Aborted")},null)})),o.end((function(e,o){var i,s={};if(s.error=null!==e,s.operation=t.operation,o&&o.status&&(s.statusCode=o.status),e){if(e.response&&e.response.text&&!r._config.logVerbosity)try{s.errorData=JSON.parse(e.response.text)}catch(t){s.errorData=e}else s.errorData=e;return s.category=r._detectErrorCategory(e),n(s,null)}if(t.ignoreBody)i={headers:o.headers,redirects:o.redirects,response:o};else try{i=JSON.parse(o.text)}catch(e){return s.errorData=o,s.error=!0,n(s,null)}return i.error&&1===i.error&&i.status&&i.message&&i.service?(s.errorData=i,s.statusCode=i.status,s.error=!0,s.category=r._detectErrorCategory(s),n(s,null)):(i.error&&i.error.message&&(s.errorData=i.error),n(s,i))})),o}function Ri(e,t,n){return o(this,void 0,void 0,(function(){var r;return i(this,(function(o){switch(o.label){case 0:return r=ki.post(e),t.forEach((function(e){var t=e.key,n=e.value;r=r.field(t,n)})),r.attach("file",n,{contentType:"application/octet-stream"}),[4,r];case 1:return[2,o.sent()]}}))}))}function xi(e,t,n){var r=ki.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ji.call(this,r,t,n)}function Ui(e,t,n){var r=ki.get(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ji.call(this,r,t,n)}function Ii(e,t,n,r){var o=ki.post(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ji.call(this,o,n,r)}function Di(e,t,n,r){var o=ki.patch(this.getStandardOrigin()+n.url).query(e).set(n.headers).send(t);return ji.call(this,o,n,r)}function Fi(e,t,n){var r=ki.delete(this.getStandardOrigin()+t.url).set(t.headers).query(e);return ji.call(this,r,t,n)}function Li(e,t){var n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}var Gi,Ki=function(){function e(){}return Object.defineProperty(e.prototype,"algo",{get:function(){return"aes-256-cbc"},enumerable:!1,configurable:!0}),e.prototype.encrypt=function(e,t){return o(this,void 0,void 0,(function(){var n;return i(this,(function(r){switch(r.label){case 0:return[4,this.getKey(e)];case 1:if(n=r.sent(),t instanceof ArrayBuffer)return[2,this.encryptArrayBuffer(n,t)];if("string"==typeof t)return[2,this.encryptString(n,t)];throw new Error("Cannot encrypt this file. In browsers file encryption supports only string or ArrayBuffer")}}))}))},e.prototype.decrypt=function(e,t){return o(this,void 0,void 0,(function(){var n;return i(this,(function(r){switch(r.label){case 0:return[4,this.getKey(e)];case 1:if(n=r.sent(),t instanceof ArrayBuffer)return[2,this.decryptArrayBuffer(n,t)];if("string"==typeof t)return[2,this.decryptString(n,t)];throw new Error("Cannot decrypt this file. In browsers file decryption supports only string or ArrayBuffer")}}))}))},e.prototype.encryptFile=function(e,t,n){return o(this,void 0,void 0,(function(){var r,o,s;return i(this,(function(i){switch(i.label){case 0:if(t.data.byteLength<=0)throw new Error("encryption error. empty content");return[4,this.getKey(e)];case 1:return r=i.sent(),[4,t.data.arrayBuffer()];case 2:return o=i.sent(),[4,this.encryptArrayBuffer(r,o)];case 3:return s=i.sent(),[2,n.create({name:t.name,mimeType:"application/octet-stream",data:s})]}}))}))},e.prototype.decryptFile=function(e,t,n){return o(this,void 0,void 0,(function(){var r,o,s;return i(this,(function(i){switch(i.label){case 0:return[4,this.getKey(e)];case 1:return r=i.sent(),[4,t.data.arrayBuffer()];case 2:return o=i.sent(),[4,this.decryptArrayBuffer(r,o)];case 3:return s=i.sent(),[2,n.create({name:t.name,data:s})]}}))}))},e.prototype.getKey=function(t){return o(this,void 0,void 0,(function(){var n,r,o;return i(this,(function(i){switch(i.label){case 0:return[4,crypto.subtle.digest("SHA-256",e.encoder.encode(t))];case 1:return n=i.sent(),r=Array.from(new Uint8Array(n)).map((function(e){return e.toString(16).padStart(2,"0")})).join(""),o=e.encoder.encode(r.slice(0,32)).buffer,[2,crypto.subtle.importKey("raw",o,"AES-CBC",!0,["encrypt","decrypt"])]}}))}))},e.prototype.encryptArrayBuffer=function(e,t){return o(this,void 0,void 0,(function(){var n,r,o;return i(this,(function(i){switch(i.label){case 0:return n=crypto.getRandomValues(new Uint8Array(16)),r=Li,o=[n.buffer],[4,crypto.subtle.encrypt({name:"AES-CBC",iv:n},e,t)];case 1:return[2,r.apply(void 0,o.concat([i.sent()]))]}}))}))},e.prototype.decryptArrayBuffer=function(t,n){return o(this,void 0,void 0,(function(){var r;return i(this,(function(o){switch(o.label){case 0:if(r=n.slice(0,16),n.slice(e.IV_LENGTH).byteLength<=0)throw new Error("decryption error: empty content");return[4,crypto.subtle.decrypt({name:"AES-CBC",iv:r},t,n.slice(e.IV_LENGTH))];case 1:return[2,o.sent()]}}))}))},e.prototype.encryptString=function(t,n){return o(this,void 0,void 0,(function(){var r,o,s,a;return i(this,(function(i){switch(i.label){case 0:return r=crypto.getRandomValues(new Uint8Array(16)),o=e.encoder.encode(n).buffer,[4,crypto.subtle.encrypt({name:"AES-CBC",iv:r},t,o)];case 1:return s=i.sent(),a=Li(r.buffer,s),[2,e.decoder.decode(a)]}}))}))},e.prototype.decryptString=function(t,n){return o(this,void 0,void 0,(function(){var r,o,s,a;return i(this,(function(i){switch(i.label){case 0:return r=e.encoder.encode(n).buffer,o=r.slice(0,16),s=r.slice(16),[4,crypto.subtle.decrypt({name:"AES-CBC",iv:o},t,s)];case 1:return a=i.sent(),[2,e.decoder.decode(a)]}}))}))},e.IV_LENGTH=16,e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),Bi=(Gi=function(){function e(e){if(e instanceof File)this.data=e,this.name=this.data.name,this.mimeType=this.data.type;else if(e.data){var t=e.data;this.data=new File([t],e.name,{type:e.mimeType}),this.name=e.name,e.mimeType&&(this.mimeType=e.mimeType)}if(void 0===this.data)throw new Error("Couldn't construct a file out of supplied options.");if(void 0===this.name)throw new Error("Couldn't guess filename out of the options. Please provide one.")}return e.create=function(e){return new this(e)},e.prototype.toBuffer=function(){return o(this,void 0,void 0,(function(){return i(this,(function(e){throw new Error("This feature is only supported in Node.js environments.")}))}))},e.prototype.toStream=function(){return o(this,void 0,void 0,(function(){return i(this,(function(e){throw new Error("This feature is only supported in Node.js environments.")}))}))},e.prototype.toFileUri=function(){return o(this,void 0,void 0,(function(){return i(this,(function(e){throw new Error("This feature is only supported in react native environments.")}))}))},e.prototype.toBlob=function(){return o(this,void 0,void 0,(function(){return i(this,(function(e){return[2,this.data]}))}))},e.prototype.toArrayBuffer=function(){return o(this,void 0,void 0,(function(){var e=this;return i(this,(function(t){return[2,new Promise((function(t,n){var r=new FileReader;r.addEventListener("load",(function(){if(r.result instanceof ArrayBuffer)return t(r.result)})),r.addEventListener("error",(function(){n(r.error)})),r.readAsArrayBuffer(e.data)}))]}))}))},e.prototype.toString=function(){return o(this,void 0,void 0,(function(){var e=this;return i(this,(function(t){return[2,new Promise((function(t,n){var r=new FileReader;r.addEventListener("load",(function(){if("string"==typeof r.result)return t(r.result)})),r.addEventListener("error",(function(){n(r.error)})),r.readAsBinaryString(e.data)}))]}))}))},e.prototype.toFile=function(){return o(this,void 0,void 0,(function(){return i(this,(function(e){return[2,this.data]}))}))},e}(),Gi.supportsFile="undefined"!=typeof File,Gi.supportsBlob="undefined"!=typeof Blob,Gi.supportsArrayBuffer="undefined"!=typeof ArrayBuffer,Gi.supportsBuffer=!1,Gi.supportsStream=!1,Gi.supportsString=!0,Gi.supportsEncryptFile=!0,Gi.supportsFileUri=!1,Gi),Hi=function(){function e(e){this.config=e,this.cryptor=new T({config:e}),this.fileCryptor=new Ki}return Object.defineProperty(e.prototype,"identifier",{get:function(){return""},enumerable:!1,configurable:!0}),e.prototype.encrypt=function(e){var t="string"==typeof e?e:(new TextDecoder).decode(e);return{data:this.cryptor.encrypt(t),metadata:null}},e.prototype.decrypt=function(e){var t="string"==typeof e.data?e.data:b(e.data);return this.cryptor.decrypt(t)},e.prototype.encryptFile=function(e,t){var n;return o(this,void 0,void 0,(function(){return i(this,(function(r){return[2,this.fileCryptor.encryptFile(null===(n=this.config)||void 0===n?void 0:n.cipherKey,e,t)]}))}))},e.prototype.decryptFile=function(e,t){return o(this,void 0,void 0,(function(){return i(this,(function(n){return[2,this.fileCryptor.decryptFile(this.config.cipherKey,e,t)]}))}))},e}(),qi=function(){function e(e){this.cipherKey=e.cipherKey,this.CryptoJS=E,this.encryptedKey=this.CryptoJS.SHA256(this.cipherKey)}return Object.defineProperty(e.prototype,"algo",{get:function(){return"AES-CBC"},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"identifier",{get:function(){return"ACRH"},enumerable:!1,configurable:!0}),e.prototype.getIv=function(){return crypto.getRandomValues(new Uint8Array(e.BLOCK_SIZE))},e.prototype.getKey=function(){return o(this,void 0,void 0,(function(){var t,n;return i(this,(function(r){switch(r.label){case 0:return t=e.encoder.encode(this.cipherKey),[4,crypto.subtle.digest("SHA-256",t.buffer)];case 1:return n=r.sent(),[2,crypto.subtle.importKey("raw",n,this.algo,!0,["encrypt","decrypt"])]}}))}))},e.prototype.encrypt=function(t){if(0===("string"==typeof t?t:e.decoder.decode(t)).length)throw new Error("encryption error. empty content");var n=this.getIv();return{metadata:n,data:m(this.CryptoJS.AES.encrypt(t,this.encryptedKey,{iv:this.bufferToWordArray(n),mode:this.CryptoJS.mode.CBC}).ciphertext.toString(this.CryptoJS.enc.Base64))}},e.prototype.decrypt=function(t){var n=this.bufferToWordArray(new Uint8ClampedArray(t.metadata)),r=this.bufferToWordArray(new Uint8ClampedArray(t.data));return e.encoder.encode(this.CryptoJS.AES.decrypt({ciphertext:r},this.encryptedKey,{iv:n,mode:this.CryptoJS.mode.CBC}).toString(this.CryptoJS.enc.Utf8)).buffer},e.prototype.encryptFileData=function(e){return o(this,void 0,void 0,(function(){var t,n,r;return i(this,(function(o){switch(o.label){case 0:return[4,this.getKey()];case 1:return t=o.sent(),n=this.getIv(),r={},[4,crypto.subtle.encrypt({name:this.algo,iv:n},t,e)];case 2:return[2,(r.data=o.sent(),r.metadata=n,r)]}}))}))},e.prototype.decryptFileData=function(e){return o(this,void 0,void 0,(function(){var t;return i(this,(function(n){switch(n.label){case 0:return[4,this.getKey()];case 1:return t=n.sent(),[2,crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)]}}))}))},e.prototype.bufferToWordArray=function(e){var t,n=[];for(t=0;t0?t.slice(n.length-n.metadataLength,n.length):null;if(t.slice(n.length).byteLength<=0)throw new Error("decryption error. empty content");return r.decrypt({data:t.slice(n.length),metadata:o})},e.prototype.encryptFile=function(e,t){return o(this,void 0,void 0,(function(){var n,r;return i(this,(function(o){switch(o.label){case 0:return this.defaultCryptor.identifier===Vi.LEGACY_IDENTIFIER?[2,this.defaultCryptor.encryptFile(e,t)]:[4,this.getFileData(e.data)];case 1:return n=o.sent(),[4,this.defaultCryptor.encryptFileData(n)];case 2:return r=o.sent(),[2,t.create({name:e.name,mimeType:"application/octet-stream",data:this.concatArrayBuffer(this.getHeaderData(r),r.data)})]}}))}))},e.prototype.decryptFile=function(t,n){return o(this,void 0,void 0,(function(){var r,o,s,a,u,c,l,p;return i(this,(function(i){switch(i.label){case 0:return[4,t.data.arrayBuffer()];case 1:return r=i.sent(),o=Vi.tryParse(r),(null==(s=this.getCryptor(o))?void 0:s.identifier)===e.LEGACY_IDENTIFIER?[2,s.decryptFile(t,n)]:[4,this.getFileData(r)];case 2:return a=i.sent(),u=a.slice(o.length-o.metadataLength,o.length),l=(c=n).create,p={name:t.name},[4,this.defaultCryptor.decryptFileData({data:r.slice(o.length),metadata:u})];case 3:return[2,l.apply(c,[(p.data=i.sent(),p)])]}}))}))},e.prototype.getCryptor=function(e){if(""===e){var t=this.getAllCryptors().find((function(e){return""===e.identifier}));if(t)return t;throw new Error("unknown cryptor error")}if(e instanceof Wi)return this.getCryptorFromId(e.identifier)},e.prototype.getCryptorFromId=function(e){var t=this.getAllCryptors().find((function(t){return e===t.identifier}));if(t)return t;throw Error("unknown cryptor error")},e.prototype.concatArrayBuffer=function(e,t){var n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer},e.prototype.getHeaderData=function(e){if(e.metadata){var t=Vi.from(this.defaultCryptor.identifier,e.metadata),n=new Uint8Array(t.length),r=0;return n.set(t.data,r),r+=t.length-e.metadata.byteLength,n.set(new Uint8Array(e.metadata),r),n.buffer}},e.prototype.getFileData=function(t){return o(this,void 0,void 0,(function(){return i(this,(function(n){switch(n.label){case 0:return t instanceof Blob?[4,t.arrayBuffer()]:[3,2];case 1:return[2,n.sent()];case 2:if(t instanceof ArrayBuffer)return[2,t];if("string"==typeof t)return[2,e.encoder.encode(t)];throw new Error("Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob")}}))}))},e.LEGACY_IDENTIFIER="",e.encoder=new TextEncoder,e.decoder=new TextDecoder,e}(),Vi=function(){function e(){}return e.from=function(t,n){if(t!==e.LEGACY_IDENTIFIER)return new Wi(t,n.byteLength)},e.tryParse=function(t){var n=new Uint8Array(t),r="";if(n.byteLength>=4&&(r=n.slice(0,4),this.decoder.decode(r)!==e.SENTINEL))return"";if(!(n.byteLength>=5))throw new Error("decryption error. invalid header version");if(n[4]>e.MAX_VERSION)throw new Error("unknown cryptor error");var o="",i=5+e.IDENTIFIER_LENGTH;if(!(n.byteLength>=i))throw new Error("decryption error. invalid crypto identifier");o=n.slice(5,i);var s=null;if(!(n.byteLength>=i+1))throw new Error("decryption error. invalid metadata length");return s=n[i],i+=1,255===s&&n.byteLength>=i+2&&(s=new Uint16Array(n.slice(i,i+2)).reduce((function(e,t){return(e<<8)+t}),0),i+=2),new Wi(this.decoder.decode(o),s)},e.SENTINEL="PNED",e.LEGACY_IDENTIFIER="",e.IDENTIFIER_LENGTH=4,e.VERSION=1,e.MAX_VERSION=1,e.decoder=new TextDecoder,e}(),Wi=function(){function e(e,t){this._identifier=e,this._metadataLength=t}return Object.defineProperty(e.prototype,"identifier",{get:function(){return this._identifier},set:function(e){this._identifier=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"metadataLength",{get:function(){return this._metadataLength},set:function(e){this._metadataLength=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"version",{get:function(){return Vi.VERSION},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return Vi.SENTINEL.length+1+Vi.IDENTIFIER_LENGTH+(this.metadataLength<255?1:3)+this.metadataLength},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"data",{get:function(){var e=0,t=new Uint8Array(this.length),n=new TextEncoder;t.set(n.encode(Vi.SENTINEL)),t[e+=Vi.SENTINEL.length]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e),e+=Vi.IDENTIFIER_LENGTH;var r=this.metadataLength;return r<255?t[e]=r:t.set([255,r>>8,255&r],e),t},enumerable:!1,configurable:!0}),e.IDENTIFIER_LENGTH=4,e.SENTINEL="PNED",e}();function Ji(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var $i=function(e){function n(t){var n=this,r=t.listenToBrowserNetworkEvents,o=void 0===r||r;return t.sdkFamily="Web",t.networking=new _n({del:Fi,get:Ui,post:Ii,patch:Di,sendBeacon:Ji,getfile:xi,postfile:Ri}),t.cbor=new wn((function(e){return Sn(h.decode(e))}),m),t.PubNubFile=Bi,t.cryptography=new Ki,t.initCryptoModule=function(e){return new zi({default:new Hi({cipherKey:e.cipherKey,useRandomIVs:e.useRandomIVs}),cryptors:[new qi({cipherKey:e.cipherKey})]})},n=e.call(this,t)||this,o&&(window.addEventListener("offline",(function(){n.networkDownDetected()})),window.addEventListener("online",(function(){n.networkUpDetected()}))),n}return t(n,e),n.CryptoModule=zi,n}(vn);return $i})); diff --git a/lib/core/components/config.js b/lib/core/components/config.js index f6dcceb4e..0b7786537 100644 --- a/lib/core/components/config.js +++ b/lib/core/components/config.js @@ -180,7 +180,7 @@ var default_1 = /** @class */ (function () { return this; }; default_1.prototype.getVersion = function () { - return '7.5.0'; + return '7.6.0'; }; default_1.prototype._setRetryConfiguration = function (configuration) { if (configuration.minimumdelay < 2) { diff --git a/lib/core/components/eventEmitter.js b/lib/core/components/eventEmitter.js index d9f6def25..06c8dc8eb 100644 --- a/lib/core/components/eventEmitter.js +++ b/lib/core/components/eventEmitter.js @@ -28,6 +28,8 @@ var EventEmitter = /** @class */ (function () { this.modules = modules; this.listenerManager = listenerManager; this.getFileUrl = getFileUrl; + this._channelListenerMap = new Map(); + this._groupListenerMap = new Map(); if (modules.cryptoModule) this._decoder = new TextDecoder(); } @@ -62,7 +64,12 @@ var EventEmitter = /** @class */ (function () { if (e.payload.timeout) { announce.timeout = e.payload.timeout; } + // deprecated --> + announce.actualChannel = subscriptionMatch != null ? channel : null; + announce.subscribedChannel = subscriptionMatch != null ? subscriptionMatch : channel; + // <-- deprecated this.listenerManager.announcePresence(announce); + this._announce('presence', announce, announce.channel, announce.subscription); } else if (e.messageType === 1) { var announce = {}; @@ -77,6 +84,7 @@ var EventEmitter = /** @class */ (function () { } announce.message = e.payload; this.listenerManager.announceSignal(announce); + this._announce('signal', announce, announce.channel, announce.subscription); } else if (e.messageType === 2) { var announce = {}; @@ -95,20 +103,27 @@ var EventEmitter = /** @class */ (function () { data: e.payload.data, }; this.listenerManager.announceObjects(announce); + this._announce('objects', announce, announce.channel, announce.subscription); if (e.payload.type === 'uuid') { var eventData = this._renameChannelField(announce); - this.listenerManager.announceUser(__assign(__assign({}, eventData), { message: __assign(__assign({}, eventData.message), { event: this._renameEvent(eventData.message.event), type: 'user' }) })); + var userEvent = __assign(__assign({}, eventData), { message: __assign(__assign({}, eventData.message), { event: this._renameEvent(eventData.message.event), type: 'user' }) }); + this.listenerManager.announceUser(userEvent); + this._announce('user', userEvent, announce.channel, announce.subscription); } else if (message.payload.type === 'channel') { var eventData = this._renameChannelField(announce); - this.listenerManager.announceSpace(__assign(__assign({}, eventData), { message: __assign(__assign({}, eventData.message), { event: this._renameEvent(eventData.message.event), type: 'space' }) })); + var spaceEvent = __assign(__assign({}, eventData), { message: __assign(__assign({}, eventData.message), { event: this._renameEvent(eventData.message.event), type: 'space' }) }); + this.listenerManager.announceSpace(spaceEvent); + this._announce('space', spaceEvent, announce.channel, announce.subscription); } else if (message.payload.type === 'membership') { var eventData = this._renameChannelField(announce); var _a = eventData.message.data, user = _a.uuid, space = _a.channel, membershipData = __rest(_a, ["uuid", "channel"]); membershipData.user = user; membershipData.space = space; - this.listenerManager.announceMembership(__assign(__assign({}, eventData), { message: __assign(__assign({}, eventData.message), { event: this._renameEvent(eventData.message.event), data: membershipData }) })); + var membershipEvent = __assign(__assign({}, eventData), { message: __assign(__assign({}, eventData.message), { event: this._renameEvent(eventData.message.event), data: membershipData }) }); + this.listenerManager.announceMembership(membershipEvent); + this._announce('membership', membershipEvent, announce.channel, announce.subscription); } } else if (e.messageType === 3) { @@ -126,6 +141,7 @@ var EventEmitter = /** @class */ (function () { }; announce.event = e.payload.event; this.listenerManager.announceMessageAction(announce); + this._announce('messageAction', announce, announce.channel, announce.subscription); } else if (e.messageType === 4) { var announce = {}; @@ -163,6 +179,7 @@ var EventEmitter = /** @class */ (function () { }), }; this.listenerManager.announceFile(announce); + this._announce('file', announce, announce.channel, announce.subscription); } else { var announce = {}; @@ -196,9 +213,59 @@ var EventEmitter = /** @class */ (function () { else { announce.message = e.payload; } + // deprecated --> + announce.actualChannel = subscriptionMatch != null ? channel : null; + announce.subscribedChannel = subscriptionMatch != null ? subscriptionMatch : channel; + // <-- deprecated this.listenerManager.announceMessage(announce); + this._announce('message', announce, announce.channel, announce.subscription); } }; + EventEmitter.prototype.addListener = function (l, channels, groups) { + var _this = this; + if (!(channels && groups)) { + this.listenerManager.addListener(l); + } + else { + channels === null || channels === void 0 ? void 0 : channels.forEach(function (c) { + if (_this._channelListenerMap[c]) { + if (!_this._channelListenerMap[c].includes(l)) + _this._channelListenerMap[c].push(l); + } + else { + _this._channelListenerMap[c] = [l]; + } + }); + groups === null || groups === void 0 ? void 0 : groups.forEach(function (g) { + if (_this._groupListenerMap[g]) { + if (!_this._groupListenerMap[g].includes(l)) + _this._groupListenerMap[g].push(l); + } + else { + _this._groupListenerMap[g] = [l]; + } + }); + } + }; + EventEmitter.prototype.removeListener = function (listener, channels, groups) { + var _this = this; + if (!(channels && groups)) { + this.listenerManager.removeListener(listener); + } + else { + channels === null || channels === void 0 ? void 0 : channels.forEach(function (c) { + var _a; + _this._channelListenerMap[c] = (_a = _this._channelListenerMap[c]) === null || _a === void 0 ? void 0 : _a.filter(function (l) { return l !== listener; }); + }); + groups === null || groups === void 0 ? void 0 : groups.forEach(function (g) { + var _a; + _this._groupListenerMap[g] = (_a = _this._groupListenerMap[g]) === null || _a === void 0 ? void 0 : _a.filter(function (l) { return l !== listener; }); + }); + } + }; + EventEmitter.prototype.removeAllListeners = function () { + this.listenerManager.removeAllListeners(); + }; EventEmitter.prototype._renameEvent = function (e) { return e === 'set' ? 'updated' : 'removed'; }; @@ -207,6 +274,11 @@ var EventEmitter = /** @class */ (function () { eventData.spaceId = channel; return eventData; }; + EventEmitter.prototype._announce = function (type, event, channel, group) { + var _a, _b; + (_a = this._channelListenerMap[channel]) === null || _a === void 0 ? void 0 : _a.forEach(function (l) { return l[type] && l[type](event); }); + (_b = this._groupListenerMap[group]) === null || _b === void 0 ? void 0 : _b.forEach(function (l) { return l[type] && l[type](event); }); + }; return EventEmitter; }()); exports.default = EventEmitter; diff --git a/lib/core/components/subscription_manager.js b/lib/core/components/subscription_manager.js index 28166718e..077bb4a1b 100644 --- a/lib/core/components/subscription_manager.js +++ b/lib/core/components/subscription_manager.js @@ -1,15 +1,4 @@ "use strict"; -var __assign = (this && this.__assign) || function () { - __assign = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); -}; var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) @@ -27,11 +16,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) { Object.defineProperty(exports, "__esModule", { value: true }); var reconnection_manager_1 = __importDefault(require("./reconnection_manager")); var deduping_manager_1 = __importDefault(require("./deduping_manager")); -var utils_1 = __importDefault(require("../utils")); var categories_1 = __importDefault(require("../constants/categories")); var default_1 = /** @class */ (function () { function default_1(_a) { - var subscribeEndpoint = _a.subscribeEndpoint, leaveEndpoint = _a.leaveEndpoint, heartbeatEndpoint = _a.heartbeatEndpoint, setStateEndpoint = _a.setStateEndpoint, timeEndpoint = _a.timeEndpoint, getFileUrl = _a.getFileUrl, config = _a.config, crypto = _a.crypto, listenerManager = _a.listenerManager, cryptoModule = _a.cryptoModule; + var subscribeEndpoint = _a.subscribeEndpoint, leaveEndpoint = _a.leaveEndpoint, heartbeatEndpoint = _a.heartbeatEndpoint, setStateEndpoint = _a.setStateEndpoint, timeEndpoint = _a.timeEndpoint, getFileUrl = _a.getFileUrl, config = _a.config, crypto = _a.crypto, listenerManager = _a.listenerManager, cryptoModule = _a.cryptoModule, eventEmitter = _a.eventEmitter; this._listenerManager = listenerManager; this._config = config; this._leaveEndpoint = leaveEndpoint; @@ -58,6 +46,7 @@ var default_1 = /** @class */ (function () { this._dedupingManager = new deduping_manager_1.default({ config: config }); if (this._cryptoModule) this._decoder = new TextDecoder(); + this._eventEmitter = eventEmitter; } default_1.prototype.adaptStateChange = function (args, callback) { var _this = this; @@ -410,7 +399,6 @@ var default_1 = /** @class */ (function () { messages.forEach(function (message) { var channel = message.channel; var subscriptionMatch = message.subscriptionMatch; - var publishMetaData = message.publishMetaData; if (channel === subscriptionMatch) { subscriptionMatch = null; } @@ -420,179 +408,7 @@ var default_1 = /** @class */ (function () { } _this._dedupingManager.addEntry(message); } - if (utils_1.default.endsWith(message.channel, '-pnpres')) { - var announce = {}; - announce.channel = null; - announce.subscription = null; - // deprecated --> - announce.actualChannel = subscriptionMatch != null ? channel : null; - announce.subscribedChannel = subscriptionMatch != null ? subscriptionMatch : channel; - // <-- deprecated - if (channel) { - announce.channel = channel.substring(0, channel.lastIndexOf('-pnpres')); - } - if (subscriptionMatch) { - announce.subscription = subscriptionMatch.substring(0, subscriptionMatch.lastIndexOf('-pnpres')); - } - announce.action = message.payload.action; - announce.state = message.payload.data; - announce.timetoken = publishMetaData.publishTimetoken; - announce.occupancy = message.payload.occupancy; - announce.uuid = message.payload.uuid; - announce.timestamp = message.payload.timestamp; - if (message.payload.join) { - announce.join = message.payload.join; - } - if (message.payload.leave) { - announce.leave = message.payload.leave; - } - if (message.payload.timeout) { - announce.timeout = message.payload.timeout; - } - _this._listenerManager.announcePresence(announce); - } - else if (message.messageType === 1) { - // this is a signal message - var announce = {}; - announce.channel = null; - announce.subscription = null; - announce.channel = channel; - announce.subscription = subscriptionMatch; - announce.timetoken = publishMetaData.publishTimetoken; - announce.publisher = message.issuingClientId; - if (message.userMetadata) { - announce.userMetadata = message.userMetadata; - } - announce.message = message.payload; - _this._listenerManager.announceSignal(announce); - } - else if (message.messageType === 2) { - // this is an object message - var announce = {}; - announce.channel = null; - announce.subscription = null; - announce.channel = channel; - announce.subscription = subscriptionMatch; - announce.timetoken = publishMetaData.publishTimetoken; - announce.publisher = message.issuingClientId; - if (message.userMetadata) { - announce.userMetadata = message.userMetadata; - } - announce.message = { - event: message.payload.event, - type: message.payload.type, - data: message.payload.data, - }; - _this._listenerManager.announceObjects(announce); - if (message.payload.type === 'uuid') { - var eventData = _this._renameChannelField(announce); - _this._listenerManager.announceUser(__assign(__assign({}, eventData), { message: __assign(__assign({}, eventData.message), { event: _this._renameEvent(eventData.message.event), type: 'user' }) })); - } - else if (message.payload.type === 'channel') { - var eventData = _this._renameChannelField(announce); - _this._listenerManager.announceSpace(__assign(__assign({}, eventData), { message: __assign(__assign({}, eventData.message), { event: _this._renameEvent(eventData.message.event), type: 'space' }) })); - } - else if (message.payload.type === 'membership') { - var eventData = _this._renameChannelField(announce); - var _a = eventData.message.data, user = _a.uuid, space = _a.channel, membershipData = __rest(_a, ["uuid", "channel"]); - membershipData.user = user; - membershipData.space = space; - _this._listenerManager.announceMembership(__assign(__assign({}, eventData), { message: __assign(__assign({}, eventData.message), { event: _this._renameEvent(eventData.message.event), data: membershipData }) })); - } - } - else if (message.messageType === 3) { - // this is a message action - var announce = {}; - announce.channel = channel; - announce.subscription = subscriptionMatch; - announce.timetoken = publishMetaData.publishTimetoken; - announce.publisher = message.issuingClientId; - announce.data = { - messageTimetoken: message.payload.data.messageTimetoken, - actionTimetoken: message.payload.data.actionTimetoken, - type: message.payload.data.type, - uuid: message.issuingClientId, - value: message.payload.data.value, - }; - announce.event = message.payload.event; - _this._listenerManager.announceMessageAction(announce); - } - else if (message.messageType === 4) { - // this is a file message - var announce = {}; - announce.channel = channel; - announce.subscription = subscriptionMatch; - announce.timetoken = publishMetaData.publishTimetoken; - announce.publisher = message.issuingClientId; - var msgPayload = message.payload; - if (_this._cryptoModule) { - var decryptedPayload = void 0; - try { - var decryptedData = _this._cryptoModule.decrypt(message.payload); - decryptedPayload = - decryptedData instanceof ArrayBuffer ? JSON.parse(_this._decoder.decode(decryptedData)) : decryptedData; - } - catch (e) { - decryptedPayload = null; - announce.error = "Error while decrypting message content: ".concat(e.message); - } - if (decryptedPayload !== null) { - msgPayload = decryptedPayload; - } - } - if (message.userMetadata) { - announce.userMetadata = message.userMetadata; - } - announce.message = msgPayload.message; - announce.file = { - id: msgPayload.file.id, - name: msgPayload.file.name, - url: _this._getFileUrl({ - id: msgPayload.file.id, - name: msgPayload.file.name, - channel: channel, - }), - }; - _this._listenerManager.announceFile(announce); - } - else { - var announce = {}; - announce.channel = null; - announce.subscription = null; - // deprecated --> - announce.actualChannel = subscriptionMatch != null ? channel : null; - announce.subscribedChannel = subscriptionMatch != null ? subscriptionMatch : channel; - // <-- deprecated - announce.channel = channel; - announce.subscription = subscriptionMatch; - announce.timetoken = publishMetaData.publishTimetoken; - announce.publisher = message.issuingClientId; - if (message.userMetadata) { - announce.userMetadata = message.userMetadata; - } - if (_this._cryptoModule) { - var decryptedPayload = void 0; - try { - var decryptedData = _this._cryptoModule.decrypt(message.payload); - decryptedPayload = - decryptedData instanceof ArrayBuffer ? JSON.parse(_this._decoder.decode(decryptedData)) : decryptedData; - } - catch (e) { - decryptedPayload = null; - announce.error = "Error while decrypting message content: ".concat(e.message); - } - if (decryptedPayload != null) { - announce.message = decryptedPayload; - } - else { - announce.message = message.payload; - } - } - else { - announce.message = message.payload; - } - _this._listenerManager.announceMessage(announce); - } + _this._eventEmitter.emitEvent(message); }); this._region = payload.metadata.region; this._startSubscribeLoop(); diff --git a/lib/core/components/telemetry_manager.js b/lib/core/components/telemetry_manager.js index d5d9a7d40..f63405121 100644 --- a/lib/core/components/telemetry_manager.js +++ b/lib/core/components/telemetry_manager.js @@ -10,6 +10,11 @@ var default_1 = /** @class */ (function () { this._maximumSamplesCount = 100; this._trackedLatencies = {}; this._latencies = {}; + this._telemetryExcludeOperations = [ + operations_1.default.PNSubscribeOperation, + operations_1.default.PNReceiveMessagesOperation, + operations_1.default.PNHandshakeOperation, + ]; this._maximumSamplesCount = configuration.maximumSamplesCount || this._maximumSamplesCount; } /** @@ -30,13 +35,13 @@ var default_1 = /** @class */ (function () { return latencies; }; default_1.prototype.startLatencyMeasure = function (operationType, identifier) { - if (operationType === operations_1.default.PNSubscribeOperation || !identifier) { + if (this._telemetryExcludeOperations.includes(operationType) || !identifier) { return; } this._trackedLatencies[identifier] = Date.now(); }; default_1.prototype.stopLatencyMeasure = function (operationType, identifier) { - if (operationType === operations_1.default.PNSubscribeOperation || !identifier) { + if (this._telemetryExcludeOperations.includes(operationType) || !identifier) { return; } var endpointName = this._endpointName(operationType); diff --git a/lib/core/endpoints/subscriptionUtils/handshake.js b/lib/core/endpoints/subscriptionUtils/handshake.js index 6eb2f5333..c30834e5b 100644 --- a/lib/core/endpoints/subscriptionUtils/handshake.js +++ b/lib/core/endpoints/subscriptionUtils/handshake.js @@ -14,8 +14,9 @@ var endpoint = { }, getURL: function (_a, params) { var config = _a.config; - var channelsString = params.channels ? params.channels.join(',') : ','; - return "/v2/subscribe/".concat(config.subscribeKey, "/").concat(utils_1.default.encodeString(channelsString), "/0"); + var _b = params.channels, channels = _b === void 0 ? [] : _b; + var stringifiedChannels = channels.length > 0 ? channels.join(',') : ','; + return "/v2/subscribe/".concat(config.subscribeKey, "/").concat(utils_1.default.encodeString(stringifiedChannels), "/0"); }, getRequestTimeout: function (_a) { var config = _a.config; diff --git a/lib/core/endpoints/subscriptionUtils/receiveMessages.js b/lib/core/endpoints/subscriptionUtils/receiveMessages.js index 0bf41a38c..e9d07554a 100644 --- a/lib/core/endpoints/subscriptionUtils/receiveMessages.js +++ b/lib/core/endpoints/subscriptionUtils/receiveMessages.js @@ -20,8 +20,9 @@ var endpoint = { }, getURL: function (_a, params) { var config = _a.config; - var channelsString = params.channels ? params.channels.join(',') : ','; - return "/v2/subscribe/".concat(config.subscribeKey, "/").concat(utils_1.default.encodeString(channelsString), "/0"); + var _b = params.channels, channels = _b === void 0 ? [] : _b; + var stringifiedChannels = channels.length > 0 ? channels.join(',') : ','; + return "/v2/subscribe/".concat(config.subscribeKey, "/").concat(utils_1.default.encodeString(stringifiedChannels), "/0"); }, getRequestTimeout: function (_a) { var config = _a.config; diff --git a/lib/core/pubnub-common.js b/lib/core/pubnub-common.js index 80e6d8562..9a145cdc7 100644 --- a/lib/core/pubnub-common.js +++ b/lib/core/pubnub-common.js @@ -144,6 +144,11 @@ var event_engine_1 = require("../event-engine"); var presence_1 = require("../event-engine/presence/presence"); var retryPolicy_1 = require("../event-engine/core/retryPolicy"); var eventEmitter_1 = __importDefault(require("./components/eventEmitter")); +var Channel_1 = require("../entities/Channel"); +var ChannelGroup_1 = require("../entities/ChannelGroup"); +var ChannelMetadata_1 = require("../entities/ChannelMetadata"); +var UserMetadata_1 = require("../entities/UserMetadata"); +var SubscriptionSet_1 = require("../entities/SubscriptionSet"); var default_1 = /** @class */ (function () { function default_1(setup) { var _this = this; @@ -198,12 +203,12 @@ var default_1 = /** @class */ (function () { this.setPresenceState = endpoint_1.default.bind(this, modules, presenceSetStateConfig); this.handshake = endpoint_1.default.bind(this, modules, handshake_1.default); this.receiveMessages = endpoint_1.default.bind(this, modules, receiveMessages_1.default); + this._eventEmitter = new eventEmitter_1.default({ + modules: modules, + listenerManager: this._listenerManager, + getFileUrl: function (params) { return (0, get_file_url_1.default)(modules, params); }, + }); if (config.enableEventEngine === true) { - this._eventEmitter = new eventEmitter_1.default({ - modules: modules, - listenerManager: this._listenerManager, - getFileUrl: function (params) { return (0, get_file_url_1.default)(modules, params); }, - }); if (config.maintainPresenceState) { this.presenceState = {}; this.setState = function (args) { @@ -287,6 +292,7 @@ var default_1 = /** @class */ (function () { listenerManager: listenerManager, getFileUrl: function (params) { return (0, get_file_url_1.default)(modules, params); }, cryptoModule: modules.cryptoModule, + eventEmitter: this._eventEmitter, }); this.subscribe = subscriptionManager_1.adaptSubscribeChange.bind(subscriptionManager_1); this.unsubscribe = subscriptionManager_1.adaptUnsubscribeChange.bind(subscriptionManager_1); @@ -302,9 +308,9 @@ var default_1 = /** @class */ (function () { subscriptionManager_1.disconnect(); }; } - this.addListener = listenerManager.addListener.bind(listenerManager); - this.removeListener = listenerManager.removeListener.bind(listenerManager); - this.removeAllListeners = listenerManager.removeAllListeners.bind(listenerManager); + this.addListener = this._eventEmitter.addListener.bind(this._eventEmitter); + this.removeListener = this._eventEmitter.removeListener.bind(this._eventEmitter); + this.removeAllListeners = this._eventEmitter.removeAllListeners.bind(this._eventEmitter); this.parseToken = tokenManager.parseToken.bind(tokenManager); this.setToken = tokenManager.setToken.bind(tokenManager); this.getToken = tokenManager.getToken.bind(tokenManager); @@ -359,6 +365,20 @@ var default_1 = /** @class */ (function () { this.getFileUrl = function (params) { return (0, get_file_url_1.default)(modules, params); }; this.downloadFile = endpoint_1.default.bind(this, modules, download_file_1.default); this.deleteFile = endpoint_1.default.bind(this, modules, delete_file_1.default); + // entities + this.channel = function (name) { return new Channel_1.Channel(name, _this._eventEmitter, _this); }; + this.channelGroup = function (name) { return new ChannelGroup_1.ChannelGroup(name, _this._eventEmitter, _this); }; + this.channelMetadata = function (id) { return new ChannelMetadata_1.ChannelMetadata(id, _this._eventEmitter, _this); }; + this.userMetadata = function (id) { return new UserMetadata_1.UserMetadata(id, _this._eventEmitter, _this); }; + this.subscriptionSet = function (args) { + return new SubscriptionSet_1.SubscriptionSet({ + channels: args.channels, + channelGroups: args.channelGroups, + subscriptionOptions: args.subscriptionOptions, + eventEmitter: _this._eventEmitter, + pubnub: _this, + }); + }; // Objects API v2 this.objects = { getAllUUIDMetadata: endpoint_1.default.bind(this, modules, get_all_1.default), diff --git a/lib/core/utils.js b/lib/core/utils.js index 3859102bc..51f97541f 100644 --- a/lib/core/utils.js +++ b/lib/core/utils.js @@ -1,4 +1,29 @@ "use strict"; +var __read = (this && this.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +}; +var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +}; function objectToList(o) { var l = []; Object.keys(o).forEach(function (key) { return l.push(key); }); @@ -34,10 +59,27 @@ function stringToArrayBuffer(str) { } return buf; } +function removeSingleOccurance(source, elementsToRemove) { + var removed = Object.fromEntries(elementsToRemove.map(function (prop) { return [prop, false]; })); + return source.filter(function (e) { + if (elementsToRemove.includes(e) && !removed[e]) { + removed[e] = true; + return false; + } + return true; + }); +} +function findUniqueCommonElements(a, b) { + return __spreadArray([], __read(a), false).filter(function (value) { + return b.includes(value) && a.indexOf(value) === a.lastIndexOf(value) && b.indexOf(value) === b.lastIndexOf(value); + }); +} module.exports = { signPamFromParams: signPamFromParams, endsWith: endsWith, createPromise: createPromise, encodeString: encodeString, stringToArrayBuffer: stringToArrayBuffer, + removeSingleOccurance: removeSingleOccurance, + findUniqueCommonElements: findUniqueCommonElements, }; diff --git a/lib/entities/Channel.js b/lib/entities/Channel.js new file mode 100644 index 000000000..0043f20dc --- /dev/null +++ b/lib/entities/Channel.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Channel = void 0; +var Subscription_1 = require("./Subscription"); +var Channel = /** @class */ (function () { + function Channel(channelName, eventEmitter, pubnub) { + this.name = channelName; + this.eventEmitter = eventEmitter; + this.pubnub = pubnub; + } + Channel.prototype.subscription = function (subscriptionOptions) { + return new Subscription_1.Subscription({ + channels: (subscriptionOptions === null || subscriptionOptions === void 0 ? void 0 : subscriptionOptions.receivePresenceEvents) ? [this.name, "".concat(this.name, "-pnpres")] : [this.name], + channelGroups: [], + subscriptionOptions: subscriptionOptions, + eventEmitter: this.eventEmitter, + pubnub: this.pubnub, + }); + }; + return Channel; +}()); +exports.Channel = Channel; diff --git a/lib/entities/ChannelGroup.js b/lib/entities/ChannelGroup.js new file mode 100644 index 000000000..07a0bea48 --- /dev/null +++ b/lib/entities/ChannelGroup.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChannelGroup = void 0; +var Subscription_1 = require("./Subscription"); +var ChannelGroup = /** @class */ (function () { + function ChannelGroup(channelGroup, eventEmitter, pubnub) { + this.name = channelGroup; + this.eventEmitter = eventEmitter; + this.pubnub = pubnub; + } + ChannelGroup.prototype.subscription = function (subscriptionOptions) { + return new Subscription_1.Subscription({ + channels: [], + channelGroups: (subscriptionOptions === null || subscriptionOptions === void 0 ? void 0 : subscriptionOptions.receivePresenceEvents) ? [this.name, "".concat(this.name, "-pnpres")] : [this.name], + subscriptionOptions: subscriptionOptions, + eventEmitter: this.eventEmitter, + pubnub: this.pubnub, + }); + }; + return ChannelGroup; +}()); +exports.ChannelGroup = ChannelGroup; diff --git a/lib/entities/ChannelMetadata.js b/lib/entities/ChannelMetadata.js new file mode 100644 index 000000000..5345f4ed8 --- /dev/null +++ b/lib/entities/ChannelMetadata.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChannelMetadata = void 0; +var Subscription_1 = require("./Subscription"); +var ChannelMetadata = /** @class */ (function () { + function ChannelMetadata(id, eventEmitter, pubnub) { + this.id = id; + this.eventEmitter = eventEmitter; + this.pubnub = pubnub; + } + ChannelMetadata.prototype.subscription = function (subscriptionOptions) { + return new Subscription_1.Subscription({ + channels: [this.id], + channelGroups: [], + subscriptionOptions: subscriptionOptions, + eventEmitter: this.eventEmitter, + pubnub: this.pubnub, + }); + }; + return ChannelMetadata; +}()); +exports.ChannelMetadata = ChannelMetadata; diff --git a/lib/entities/SubscribeCapable.js b/lib/entities/SubscribeCapable.js new file mode 100644 index 000000000..554527544 --- /dev/null +++ b/lib/entities/SubscribeCapable.js @@ -0,0 +1,92 @@ +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SubscribeCapable = void 0; +var SubscribeCapable = /** @class */ (function () { + function SubscribeCapable() { + } + SubscribeCapable.prototype.subscribe = function () { + var _a, _b; + this.pubnub.subscribe(__assign({ channels: this.channelNames, channelGroups: this.groupNames }, (((_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.cursor) === null || _b === void 0 ? void 0 : _b.timetoken) && { timetoken: this.options.cursor.timetoken }))); + }; + SubscribeCapable.prototype.unsubscribe = function () { + this.pubnub.unsubscribe({ + channels: this.channelNames.filter(function (c) { return !c.endsWith('-pnpres'); }), + channelGroups: this.groupNames.filter(function (cg) { return !cg.endsWith('-pnpres'); }), + }); + }; + Object.defineProperty(SubscribeCapable.prototype, "onMessage", { + set: function (onMessagelistener) { + this.listener.message = onMessagelistener; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(SubscribeCapable.prototype, "onPresence", { + set: function (onPresencelistener) { + this.listener.presence = onPresencelistener; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(SubscribeCapable.prototype, "onSignal", { + set: function (onSignalListener) { + this.listener.signal = onSignalListener; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(SubscribeCapable.prototype, "onObjects", { + set: function (onObjectsListener) { + this.listener.objects = onObjectsListener; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(SubscribeCapable.prototype, "onMessageAction", { + set: function (messageActionEventListener) { + this.listener.messageAction = messageActionEventListener; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(SubscribeCapable.prototype, "onFile", { + set: function (fileEventListener) { + this.listener.file = fileEventListener; + }, + enumerable: false, + configurable: true + }); + SubscribeCapable.prototype.addListener = function (listener) { + this.eventEmitter.addListener(listener, this.channelNames.filter(function (c) { return !c.endsWith('-pnpres'); }), this.groupNames.filter(function (cg) { return !cg.endsWith('-pnpres'); })); + }; + SubscribeCapable.prototype.removeListener = function (listener) { + this.eventEmitter.removeListener(listener, this.channelNames, this.groupNames); + }; + Object.defineProperty(SubscribeCapable.prototype, "channels", { + get: function () { + return this.channelNames.slice(0); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(SubscribeCapable.prototype, "channelGroups", { + get: function () { + return this.groupNames.slice(0); + }, + enumerable: false, + configurable: true + }); + return SubscribeCapable; +}()); +exports.SubscribeCapable = SubscribeCapable; diff --git a/lib/entities/Subscription.js b/lib/entities/Subscription.js new file mode 100644 index 000000000..586f8d3c3 --- /dev/null +++ b/lib/entities/Subscription.js @@ -0,0 +1,84 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __read = (this && this.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +}; +var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Subscription = void 0; +var SubscriptionSet_1 = require("./SubscriptionSet"); +var SubscribeCapable_1 = require("./SubscribeCapable"); +var Subscription = /** @class */ (function (_super) { + __extends(Subscription, _super); + function Subscription(_a) { + var channels = _a.channels, channelGroups = _a.channelGroups, subscriptionOptions = _a.subscriptionOptions, eventEmitter = _a.eventEmitter, pubnub = _a.pubnub; + var _this = _super.call(this) || this; + _this.channelNames = []; + _this.groupNames = []; + _this.channelNames = channels; + _this.groupNames = channelGroups; + _this.options = subscriptionOptions; + _this.pubnub = pubnub; + _this.eventEmitter = eventEmitter; + _this.listener = {}; + eventEmitter.addListener(_this.listener, _this.channelNames.filter(function (c) { return !c.endsWith('-pnpres'); }), _this.groupNames.filter(function (cg) { return !cg.endsWith('-pnpres'); })); + return _this; + } + Subscription.prototype.addSubscription = function (subscription) { + return new SubscriptionSet_1.SubscriptionSet({ + channels: __spreadArray(__spreadArray([], __read(this.channelNames), false), __read(subscription.channels), false), + channelGroups: __spreadArray(__spreadArray([], __read(this.groupNames), false), __read(subscription.channelGroups), false), + subscriptionOptions: __assign(__assign({}, this.options), subscription === null || subscription === void 0 ? void 0 : subscription.options), + eventEmitter: this.eventEmitter, + pubnub: this.pubnub, + }); + }; + return Subscription; +}(SubscribeCapable_1.SubscribeCapable)); +exports.Subscription = Subscription; diff --git a/lib/entities/SubscriptionSet.js b/lib/entities/SubscriptionSet.js new file mode 100644 index 000000000..bc1417e61 --- /dev/null +++ b/lib/entities/SubscriptionSet.js @@ -0,0 +1,103 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __read = (this && this.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +}; +var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SubscriptionSet = void 0; +var SubscribeCapable_1 = require("./SubscribeCapable"); +var SubscriptionSet = /** @class */ (function (_super) { + __extends(SubscriptionSet, _super); + function SubscriptionSet(_a) { + var _b = _a.channels, channels = _b === void 0 ? [] : _b, _c = _a.channelGroups, channelGroups = _c === void 0 ? [] : _c, subscriptionOptions = _a.subscriptionOptions, eventEmitter = _a.eventEmitter, pubnub = _a.pubnub; + var _this = _super.call(this) || this; + _this.channelNames = []; + _this.groupNames = []; + _this.subscriptionList = []; + _this.options = subscriptionOptions; + _this.eventEmitter = eventEmitter; + _this.pubnub = pubnub; + channels.forEach(function (c) { + var subscription = _this.pubnub.channel(c).subscription(_this.options); + _this.channelNames = __spreadArray(__spreadArray([], __read(_this.channelNames), false), __read(subscription.channels), false); + _this.subscriptionList.push(subscription); + }); + channelGroups.forEach(function (cg) { + var subscription = _this.pubnub.channelGroup(cg).subscription(_this.options); + _this.groupNames = __spreadArray(__spreadArray([], __read(_this.groupNames), false), __read(subscription.channelGroups), false); + _this.subscriptionList.push(subscription); + }); + _this.listener = {}; + eventEmitter.addListener(_this.listener, _this.channelNames.filter(function (c) { return !c.endsWith('-pnpres'); }), _this.groupNames.filter(function (cg) { return !cg.endsWith('-pnpres'); })); + return _this; + } + SubscriptionSet.prototype.addSubscription = function (subscription) { + this.subscriptionList.push(subscription); + this.channelNames = __spreadArray(__spreadArray([], __read(this.channelNames), false), __read(subscription.channels), false); + this.groupNames = __spreadArray(__spreadArray([], __read(this.groupNames), false), __read(subscription.channelGroups), false); + }; + SubscriptionSet.prototype.removeSubscription = function (subscription) { + var channelsToRemove = subscription.channels; + var groupsToRemove = subscription.channelGroups; + this.channelNames = this.channelNames.filter(function (c) { return !channelsToRemove.includes(c); }); + this.groupNames = this.groupNames.filter(function (cg) { return !groupsToRemove.includes(cg); }); + this.subscriptionList = this.subscriptionList.filter(function (s) { return s !== subscription; }); + }; + SubscriptionSet.prototype.addSubscriptionSet = function (subscriptionSet) { + this.subscriptionList = __spreadArray(__spreadArray([], __read(this.subscriptionList), false), __read(subscriptionSet.subscriptions), false); + this.channelNames = __spreadArray(__spreadArray([], __read(this.channelNames), false), __read(subscriptionSet.channels), false); + this.groupNames = __spreadArray(__spreadArray([], __read(this.groupNames), false), __read(subscriptionSet.channelGroups), false); + }; + SubscriptionSet.prototype.removeSubscriptionSet = function (subscriptionSet) { + var channelsToRemove = subscriptionSet.channels; + var groupsToRemove = subscriptionSet.channelGroups; + this.channelNames = this.channelNames.filter(function (c) { return !channelsToRemove.includes(c); }); + this.groupNames = this.groupNames.filter(function (cg) { return !groupsToRemove.includes(cg); }); + this.subscriptionList = this.subscriptionList.filter(function (s) { return !subscriptionSet.subscriptions.includes(s); }); + }; + Object.defineProperty(SubscriptionSet.prototype, "subscriptions", { + get: function () { + return this.subscriptionList.slice(0); + }, + enumerable: false, + configurable: true + }); + return SubscriptionSet; +}(SubscribeCapable_1.SubscribeCapable)); +exports.SubscriptionSet = SubscriptionSet; diff --git a/lib/entities/UserMetadata.js b/lib/entities/UserMetadata.js new file mode 100644 index 000000000..8989b01f3 --- /dev/null +++ b/lib/entities/UserMetadata.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UserMetadata = void 0; +var Subscription_1 = require("./Subscription"); +var UserMetadata = /** @class */ (function () { + function UserMetadata(id, eventEmitter, pubnub) { + this.id = id; + this.eventEmitter = eventEmitter; + this.pubnub = pubnub; + } + UserMetadata.prototype.subscription = function (subscriptionOptions) { + return new Subscription_1.Subscription({ + channels: [this.id], + channelGroups: [], + subscriptionOptions: subscriptionOptions, + eventEmitter: this.eventEmitter, + pubnub: this.pubnub, + }); + }; + return UserMetadata; +}()); +exports.UserMetadata = UserMetadata; diff --git a/lib/entities/common.js b/lib/entities/common.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/entities/common.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/entities/commonTypes.js b/lib/entities/commonTypes.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/entities/commonTypes.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/event-engine/index.js b/lib/event-engine/index.js index 1cd5fa289..7d8811c25 100644 --- a/lib/event-engine/index.js +++ b/lib/event-engine/index.js @@ -53,6 +53,7 @@ var core_1 = require("./core"); var dispatcher_1 = require("./dispatcher"); var events = __importStar(require("./events")); var unsubscribed_1 = require("./states/unsubscribed"); +var utils = __importStar(require("../core/utils")); var EventEngine = /** @class */ (function () { function EventEngine(dependencies) { var _this = this; @@ -85,37 +86,40 @@ var EventEngine = /** @class */ (function () { this.groups.map(function (g) { return _this.groups.push("".concat(g, "-pnpres")); }); } if (timetoken) { - this.engine.transition(events.restore(this.channels, this.groups, timetoken)); + this.engine.transition(events.restore(Array.from(new Set(__spreadArray(__spreadArray([], __read(this.channels), false), __read((channels !== null && channels !== void 0 ? channels : [])), false))), Array.from(new Set(__spreadArray(__spreadArray([], __read(this.groups), false), __read((channelGroups !== null && channelGroups !== void 0 ? channelGroups : [])), false))), timetoken)); } else { - this.engine.transition(events.subscriptionChange(this.channels, this.groups)); + this.engine.transition(events.subscriptionChange(Array.from(new Set(__spreadArray(__spreadArray([], __read(this.channels), false), __read((channels !== null && channels !== void 0 ? channels : [])), false))), Array.from(new Set(__spreadArray(__spreadArray([], __read(this.groups), false), __read((channelGroups !== null && channelGroups !== void 0 ? channelGroups : [])), false))))); } if (this.dependencies.join) { this.dependencies.join({ - channels: this.channels.filter(function (c) { return !c.endsWith('-pnpres'); }), - groups: this.groups.filter(function (g) { return !g.endsWith('-pnpres'); }), + channels: Array.from(new Set(this.channels.filter(function (c) { return !c.endsWith('-pnpres'); }))), + groups: Array.from(new Set(this.groups.filter(function (g) { return !g.endsWith('-pnpres'); }))), }); } }; EventEngine.prototype.unsubscribe = function (_a) { var _this = this; - var channels = _a.channels, groups = _a.groups; - var channlesWithPres = channels === null || channels === void 0 ? void 0 : channels.slice(0); - channels === null || channels === void 0 ? void 0 : channels.map(function (c) { return channlesWithPres.push("".concat(c, "-pnpres")); }); - this.channels = this.channels.filter(function (channel) { return !(channlesWithPres === null || channlesWithPres === void 0 ? void 0 : channlesWithPres.includes(channel)); }); - var groupsWithPres = groups === null || groups === void 0 ? void 0 : groups.slice(0); - groups === null || groups === void 0 ? void 0 : groups.map(function (g) { return groupsWithPres.push("".concat(g, "-pnpres")); }); - this.groups = this.groups.filter(function (group) { return !(groupsWithPres === null || groupsWithPres === void 0 ? void 0 : groupsWithPres.includes(group)); }); - if (this.dependencies.presenceState) { - channels === null || channels === void 0 ? void 0 : channels.forEach(function (c) { return delete _this.dependencies.presenceState[c]; }); - groups === null || groups === void 0 ? void 0 : groups.forEach(function (g) { return delete _this.dependencies.presenceState[g]; }); - } - this.engine.transition(events.subscriptionChange(this.channels.slice(0), this.groups.slice(0))); - if (this.dependencies.leave) { - this.dependencies.leave({ - channels: channels, - groups: groups, - }); + var _b = _a.channels, channels = _b === void 0 ? [] : _b, _c = _a.channelGroups, channelGroups = _c === void 0 ? [] : _c; + var filteredChannels = utils.removeSingleOccurance(this.channels, __spreadArray(__spreadArray([], __read(channels), false), __read(channels.map(function (c) { return "".concat(c, "-pnpres"); })), false)); + var filteredGroups = utils.removeSingleOccurance(this.groups, __spreadArray(__spreadArray([], __read(channelGroups), false), __read(channelGroups.map(function (c) { return "".concat(c, "-pnpres"); })), false)); + if (new Set(this.channels).size !== new Set(filteredChannels).size || + new Set(this.groups).size !== new Set(filteredGroups).size) { + var channelsToLeave = utils.findUniqueCommonElements(this.channels, channels); + var groupstoLeave = utils.findUniqueCommonElements(this.groups, channelGroups); + if (this.dependencies.presenceState) { + channelsToLeave === null || channelsToLeave === void 0 ? void 0 : channelsToLeave.forEach(function (c) { return delete _this.dependencies.presenceState[c]; }); + groupstoLeave === null || groupstoLeave === void 0 ? void 0 : groupstoLeave.forEach(function (g) { return delete _this.dependencies.presenceState[g]; }); + } + this.channels = filteredChannels; + this.groups = filteredGroups; + this.engine.transition(events.subscriptionChange(Array.from(new Set(this.channels.slice(0))), Array.from(new Set(this.groups.slice(0))))); + if (this.dependencies.leave) { + this.dependencies.leave({ + channels: channelsToLeave.slice(0), + groups: groupstoLeave.slice(0), + }); + } } }; EventEngine.prototype.unsubscribeAll = function () { diff --git a/package.json b/package.json index 82ffad741..da6bd4c2c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "pubnub", - "version": "7.5.0", + "version": "7.6.0", "author": "PubNub ", "description": "Publish & Subscribe Real-time Messaging with PubNub", "scripts": { diff --git a/src/core/components/config.js b/src/core/components/config.js index ab9050acc..69bef414a 100644 --- a/src/core/components/config.js +++ b/src/core/components/config.js @@ -358,7 +358,7 @@ export default class { } getVersion() { - return '7.5.0'; + return '7.6.0'; } _setRetryConfiguration(configuration) { diff --git a/src/core/components/eventEmitter.js b/src/core/components/eventEmitter.js index 05a39972f..2157569de 100644 --- a/src/core/components/eventEmitter.js +++ b/src/core/components/eventEmitter.js @@ -3,11 +3,15 @@ export default class EventEmitter { listenerManager; getFileUrl; + _channelListenerMap; + _groupListenerMap; _decoder; constructor({ modules, listenerManager, getFileUrl }) { this.modules = modules; this.listenerManager = listenerManager; this.getFileUrl = getFileUrl; + this._channelListenerMap = new Map(); + this._groupListenerMap = new Map(); if (modules.cryptoModule) this._decoder = new TextDecoder(); } emitEvent(e) { @@ -48,8 +52,13 @@ export default class EventEmitter { if (e.payload.timeout) { announce.timeout = e.payload.timeout; } + // deprecated --> + announce.actualChannel = subscriptionMatch != null ? channel : null; + announce.subscribedChannel = subscriptionMatch != null ? subscriptionMatch : channel; + // <-- deprecated this.listenerManager.announcePresence(announce); + this._announce('presence', announce, announce.channel, announce.subscription); } else if (e.messageType === 1) { const announce = {}; announce.channel = null; @@ -66,6 +75,7 @@ export default class EventEmitter { announce.message = e.payload; this.listenerManager.announceSignal(announce); + this._announce('signal', announce, announce.channel, announce.subscription); } else if (e.messageType === 2) { const announce = {}; announce.channel = null; @@ -83,39 +93,46 @@ export default class EventEmitter { data: e.payload.data, }; this.listenerManager.announceObjects(announce); + this._announce('objects', announce, announce.channel, announce.subscription); if (e.payload.type === 'uuid') { const eventData = this._renameChannelField(announce); - this.listenerManager.announceUser({ + const userEvent = { ...eventData, message: { ...eventData.message, event: this._renameEvent(eventData.message.event), type: 'user', }, - }); + }; + this.listenerManager.announceUser(userEvent); + this._announce('user', userEvent, announce.channel, announce.subscription); } else if (message.payload.type === 'channel') { const eventData = this._renameChannelField(announce); - this.listenerManager.announceSpace({ + const spaceEvent = { ...eventData, message: { ...eventData.message, event: this._renameEvent(eventData.message.event), type: 'space', }, - }); + }; + this.listenerManager.announceSpace(spaceEvent); + this._announce('space', spaceEvent, announce.channel, announce.subscription); } else if (message.payload.type === 'membership') { const eventData = this._renameChannelField(announce); const { uuid: user, channel: space, ...membershipData } = eventData.message.data; membershipData.user = user; membershipData.space = space; - this.listenerManager.announceMembership({ + const membershipEvent = { ...eventData, message: { ...eventData.message, event: this._renameEvent(eventData.message.event), data: membershipData, }, - }); + }; + this.listenerManager.announceMembership(membershipEvent); + this._announce('membership', membershipEvent, announce.channel, announce.subscription); } } else if (e.messageType === 3) { const announce = {}; @@ -132,6 +149,7 @@ export default class EventEmitter { }; announce.event = e.payload.event; this.listenerManager.announceMessageAction(announce); + this._announce('messageAction', announce, announce.channel, announce.subscription); } else if (e.messageType === 4) { const announce = {}; announce.channel = channel; @@ -173,6 +191,7 @@ export default class EventEmitter { }; this.listenerManager.announceFile(announce); + this._announce('file', announce, announce.channel, announce.subscription); } else { const announce = {}; announce.channel = null; @@ -205,11 +224,54 @@ export default class EventEmitter { } else { announce.message = e.payload; } + // deprecated --> + announce.actualChannel = subscriptionMatch != null ? channel : null; + announce.subscribedChannel = subscriptionMatch != null ? subscriptionMatch : channel; + // <-- deprecated this.listenerManager.announceMessage(announce); + this._announce('message', announce, announce.channel, announce.subscription); } } + addListener(l, channels, groups) { + if (!(channels && groups)) { + this.listenerManager.addListener(l); + } else { + channels?.forEach((c) => { + if (this._channelListenerMap[c]) { + if (!this._channelListenerMap[c].includes(l)) this._channelListenerMap[c].push(l); + } else { + this._channelListenerMap[c] = [l]; + } + }); + groups?.forEach((g) => { + if (this._groupListenerMap[g]) { + if (!this._groupListenerMap[g].includes(l)) this._groupListenerMap[g].push(l); + } else { + this._groupListenerMap[g] = [l]; + } + }); + } + } + + removeListener(listener, channels, groups) { + if (!(channels && groups)) { + this.listenerManager.removeListener(listener); + } else { + channels?.forEach((c) => { + this._channelListenerMap[c] = this._channelListenerMap[c]?.filter((l) => l !== listener); + }); + groups?.forEach((g) => { + this._groupListenerMap[g] = this._groupListenerMap[g]?.filter((l) => l !== listener); + }); + } + } + + removeAllListeners() { + this.listenerManager.removeAllListeners(); + } + _renameEvent(e) { return e === 'set' ? 'updated' : 'removed'; } @@ -219,4 +281,9 @@ export default class EventEmitter { eventData.spaceId = channel; return eventData; } + + _announce(type, event, channel, group) { + this._channelListenerMap[channel]?.forEach((l) => l[type] && l[type](event)); + this._groupListenerMap[group]?.forEach((l) => l[type] && l[type](event)); + } } diff --git a/src/core/components/subscription_manager.js b/src/core/components/subscription_manager.js index 3480eca7a..1dd6fbed2 100644 --- a/src/core/components/subscription_manager.js +++ b/src/core/components/subscription_manager.js @@ -64,6 +64,8 @@ export default class { _dedupingManager; + _eventEmitter; + constructor({ subscribeEndpoint, leaveEndpoint, @@ -75,6 +77,7 @@ export default class { crypto, listenerManager, cryptoModule, + eventEmitter, }) { this._listenerManager = listenerManager; this._config = config; @@ -112,6 +115,8 @@ export default class { this._dedupingManager = new DedupingManager({ config }); if (this._cryptoModule) this._decoder = new TextDecoder(); + + this._eventEmitter = eventEmitter; } adaptStateChange(args, callback) { @@ -534,7 +539,6 @@ export default class { messages.forEach((message) => { const { channel } = message; let { subscriptionMatch } = message; - const { publishMetaData } = message; if (channel === subscriptionMatch) { subscriptionMatch = null; @@ -547,222 +551,7 @@ export default class { this._dedupingManager.addEntry(message); } - if (utils.endsWith(message.channel, '-pnpres')) { - const announce = {}; - announce.channel = null; - announce.subscription = null; - - // deprecated --> - announce.actualChannel = subscriptionMatch != null ? channel : null; - announce.subscribedChannel = subscriptionMatch != null ? subscriptionMatch : channel; - // <-- deprecated - - if (channel) { - announce.channel = channel.substring(0, channel.lastIndexOf('-pnpres')); - } - - if (subscriptionMatch) { - announce.subscription = subscriptionMatch.substring(0, subscriptionMatch.lastIndexOf('-pnpres')); - } - - announce.action = message.payload.action; - announce.state = message.payload.data; - announce.timetoken = publishMetaData.publishTimetoken; - announce.occupancy = message.payload.occupancy; - announce.uuid = message.payload.uuid; - announce.timestamp = message.payload.timestamp; - - if (message.payload.join) { - announce.join = message.payload.join; - } - - if (message.payload.leave) { - announce.leave = message.payload.leave; - } - - if (message.payload.timeout) { - announce.timeout = message.payload.timeout; - } - - this._listenerManager.announcePresence(announce); - } else if (message.messageType === 1) { - // this is a signal message - const announce = {}; - announce.channel = null; - announce.subscription = null; - - announce.channel = channel; - announce.subscription = subscriptionMatch; - announce.timetoken = publishMetaData.publishTimetoken; - announce.publisher = message.issuingClientId; - - if (message.userMetadata) { - announce.userMetadata = message.userMetadata; - } - - announce.message = message.payload; - - this._listenerManager.announceSignal(announce); - } else if (message.messageType === 2) { - // this is an object message - - const announce = {}; - - announce.channel = null; - announce.subscription = null; - - announce.channel = channel; - announce.subscription = subscriptionMatch; - announce.timetoken = publishMetaData.publishTimetoken; - announce.publisher = message.issuingClientId; - - if (message.userMetadata) { - announce.userMetadata = message.userMetadata; - } - - announce.message = { - event: message.payload.event, - type: message.payload.type, - data: message.payload.data, - }; - - this._listenerManager.announceObjects(announce); - - if (message.payload.type === 'uuid') { - const eventData = this._renameChannelField(announce); - this._listenerManager.announceUser({ - ...eventData, - message: { - ...eventData.message, - event: this._renameEvent(eventData.message.event), - type: 'user', - }, - }); - } else if (message.payload.type === 'channel') { - const eventData = this._renameChannelField(announce); - this._listenerManager.announceSpace({ - ...eventData, - message: { - ...eventData.message, - event: this._renameEvent(eventData.message.event), - type: 'space', - }, - }); - } else if (message.payload.type === 'membership') { - const eventData = this._renameChannelField(announce); - const { uuid: user, channel: space, ...membershipData } = eventData.message.data; - membershipData.user = user; - membershipData.space = space; - this._listenerManager.announceMembership({ - ...eventData, - message: { - ...eventData.message, - event: this._renameEvent(eventData.message.event), - data: membershipData, - }, - }); - } - } else if (message.messageType === 3) { - // this is a message action - const announce = {}; - announce.channel = channel; - announce.subscription = subscriptionMatch; - announce.timetoken = publishMetaData.publishTimetoken; - announce.publisher = message.issuingClientId; - - announce.data = { - messageTimetoken: message.payload.data.messageTimetoken, - actionTimetoken: message.payload.data.actionTimetoken, - type: message.payload.data.type, - uuid: message.issuingClientId, - value: message.payload.data.value, - }; - - announce.event = message.payload.event; - - this._listenerManager.announceMessageAction(announce); - } else if (message.messageType === 4) { - // this is a file message - const announce = {}; - announce.channel = channel; - announce.subscription = subscriptionMatch; - announce.timetoken = publishMetaData.publishTimetoken; - announce.publisher = message.issuingClientId; - - let msgPayload = message.payload; - - if (this._cryptoModule) { - let decryptedPayload; - try { - const decryptedData = this._cryptoModule.decrypt(message.payload); - decryptedPayload = - decryptedData instanceof ArrayBuffer ? JSON.parse(this._decoder.decode(decryptedData)) : decryptedData; - } catch (e) { - decryptedPayload = null; - announce.error = `Error while decrypting message content: ${e.message}`; - } - if (decryptedPayload !== null) { - msgPayload = decryptedPayload; - } - } - - if (message.userMetadata) { - announce.userMetadata = message.userMetadata; - } - - announce.message = msgPayload.message; - - announce.file = { - id: msgPayload.file.id, - name: msgPayload.file.name, - url: this._getFileUrl({ - id: msgPayload.file.id, - name: msgPayload.file.name, - channel, - }), - }; - - this._listenerManager.announceFile(announce); - } else { - const announce = {}; - announce.channel = null; - announce.subscription = null; - - // deprecated --> - announce.actualChannel = subscriptionMatch != null ? channel : null; - announce.subscribedChannel = subscriptionMatch != null ? subscriptionMatch : channel; - // <-- deprecated - - announce.channel = channel; - announce.subscription = subscriptionMatch; - announce.timetoken = publishMetaData.publishTimetoken; - announce.publisher = message.issuingClientId; - - if (message.userMetadata) { - announce.userMetadata = message.userMetadata; - } - - if (this._cryptoModule) { - let decryptedPayload; - try { - const decryptedData = this._cryptoModule.decrypt(message.payload); - decryptedPayload = - decryptedData instanceof ArrayBuffer ? JSON.parse(this._decoder.decode(decryptedData)) : decryptedData; - } catch (e) { - decryptedPayload = null; - announce.error = `Error while decrypting message content: ${e.message}`; - } - if (decryptedPayload != null) { - announce.message = decryptedPayload; - } else { - announce.message = message.payload; - } - } else { - announce.message = message.payload; - } - - this._listenerManager.announceMessage(announce); - } + this._eventEmitter.emitEvent(message); }); this._region = payload.metadata.region; diff --git a/src/core/components/telemetry_manager.js b/src/core/components/telemetry_manager.js index 474b5f206..fa4392df4 100644 --- a/src/core/components/telemetry_manager.js +++ b/src/core/components/telemetry_manager.js @@ -8,6 +8,12 @@ export default class { _latencies = {}; + _telemetryExcludeOperations = [ + operationConstants.PNSubscribeOperation, + operationConstants.PNReceiveMessagesOperation, + operationConstants.PNHandshakeOperation, + ]; + constructor(configuration) { this._maximumSamplesCount = configuration.maximumSamplesCount || this._maximumSamplesCount; } @@ -33,7 +39,7 @@ export default class { } startLatencyMeasure(operationType, identifier) { - if (operationType === operationConstants.PNSubscribeOperation || !identifier) { + if (this._telemetryExcludeOperations.includes(operationType) || !identifier) { return; } @@ -41,7 +47,7 @@ export default class { } stopLatencyMeasure(operationType, identifier) { - if (operationType === operationConstants.PNSubscribeOperation || !identifier) { + if (this._telemetryExcludeOperations.includes(operationType) || !identifier) { return; } diff --git a/src/core/endpoints/subscriptionUtils/handshake.js b/src/core/endpoints/subscriptionUtils/handshake.js index 84fd489fc..68487c68d 100644 --- a/src/core/endpoints/subscriptionUtils/handshake.js +++ b/src/core/endpoints/subscriptionUtils/handshake.js @@ -11,8 +11,9 @@ const endpoint = { }, getURL: ({ config }, params) => { - const channelsString = params.channels ? params.channels.join(',') : ','; - return `/v2/subscribe/${config.subscribeKey}/${utils.encodeString(channelsString)}/0`; + const { channels = [] } = params; + const stringifiedChannels = channels.length > 0 ? channels.join(',') : ','; + return `/v2/subscribe/${config.subscribeKey}/${utils.encodeString(stringifiedChannels)}/0`; }, getRequestTimeout: ({ config }) => config.getSubscribeTimeout(), diff --git a/src/core/endpoints/subscriptionUtils/receiveMessages.js b/src/core/endpoints/subscriptionUtils/receiveMessages.js index b62c3acb3..c85a52ab5 100644 --- a/src/core/endpoints/subscriptionUtils/receiveMessages.js +++ b/src/core/endpoints/subscriptionUtils/receiveMessages.js @@ -17,8 +17,9 @@ const endpoint = { }, getURL: ({ config }, params) => { - const channelsString = params.channels ? params.channels.join(',') : ','; - return `/v2/subscribe/${config.subscribeKey}/${utils.encodeString(channelsString)}/0`; + const { channels = [] } = params; + const stringifiedChannels = channels.length > 0 ? channels.join(',') : ','; + return `/v2/subscribe/${config.subscribeKey}/${utils.encodeString(stringifiedChannels)}/0`; }, getRequestTimeout: ({ config }) => config.getSubscribeTimeout(), diff --git a/src/core/pubnub-common.js b/src/core/pubnub-common.js index e187a1995..3aa12932e 100644 --- a/src/core/pubnub-common.js +++ b/src/core/pubnub-common.js @@ -95,6 +95,12 @@ import { PresenceEventEngine } from '../event-engine/presence/presence'; import { RetryPolicy } from '../event-engine/core/retryPolicy'; import EventEmitter from './components/eventEmitter'; +import { Channel } from '../entities/Channel'; +import { ChannelGroup } from '../entities/ChannelGroup'; +import { ChannelMetadata } from '../entities/ChannelMetadata'; +import { UserMetadata } from '../entities/UserMetadata'; +import { SubscriptionSet } from '../entities/SubscriptionSet'; + export default class { _config; @@ -341,12 +347,12 @@ export default class { this.handshake = endpointCreator.bind(this, modules, handshakeEndpointConfig); this.receiveMessages = endpointCreator.bind(this, modules, receiveMessagesConfig); + this._eventEmitter = new EventEmitter({ + modules: modules, + listenerManager: this._listenerManager, + getFileUrl: (params) => getFileUrlFunction(modules, params), + }); if (config.enableEventEngine === true) { - this._eventEmitter = new EventEmitter({ - modules: modules, - listenerManager: this._listenerManager, - getFileUrl: (params) => getFileUrlFunction(modules, params), - }); if (config.maintainPresenceState) { this.presenceState = {}; this.setState = (args) => { @@ -418,6 +424,7 @@ export default class { listenerManager, getFileUrl: (params) => getFileUrlFunction(modules, params), cryptoModule: modules.cryptoModule, + eventEmitter: this._eventEmitter, }); this.subscribe = subscriptionManager.adaptSubscribeChange.bind(subscriptionManager); @@ -437,9 +444,9 @@ export default class { }; } - this.addListener = listenerManager.addListener.bind(listenerManager); - this.removeListener = listenerManager.removeListener.bind(listenerManager); - this.removeAllListeners = listenerManager.removeAllListeners.bind(listenerManager); + this.addListener = this._eventEmitter.addListener.bind(this._eventEmitter); + this.removeListener = this._eventEmitter.removeListener.bind(this._eventEmitter); + this.removeAllListeners = this._eventEmitter.removeAllListeners.bind(this._eventEmitter); this.parseToken = tokenManager.parseToken.bind(tokenManager); this.setToken = tokenManager.setToken.bind(tokenManager); @@ -511,6 +518,21 @@ export default class { this.deleteFile = endpointCreator.bind(this, modules, deleteFileEndpointConfig); + // entities + + this.channel = (name) => new Channel(name, this._eventEmitter, this); + this.channelGroup = (name) => new ChannelGroup(name, this._eventEmitter, this); + this.channelMetadata = (id) => new ChannelMetadata(id, this._eventEmitter, this); + this.userMetadata = (id) => new UserMetadata(id, this._eventEmitter, this); + this.subscriptionSet = (args) => + new SubscriptionSet({ + channels: args.channels, + channelGroups: args.channelGroups, + subscriptionOptions: args.subscriptionOptions, + eventEmitter: this._eventEmitter, + pubnub: this, + }); + // Objects API v2 this.objects = { diff --git a/src/core/utils.js b/src/core/utils.js index 5f88aeccc..668845dd6 100644 --- a/src/core/utils.js +++ b/src/core/utils.js @@ -41,10 +41,31 @@ function stringToArrayBuffer(str) { return buf; } +function removeSingleOccurance(source, elementsToRemove) { + let removed = Object.fromEntries(elementsToRemove.map((prop) => [prop, false])); + + return source.filter((e) => { + if (elementsToRemove.includes(e) && !removed[e]) { + removed[e] = true; + return false; + } + return true; + }); +} + +function findUniqueCommonElements(a, b) { + return [...a].filter( + (value) => + b.includes(value) && a.indexOf(value) === a.lastIndexOf(value) && b.indexOf(value) === b.lastIndexOf(value), + ); +} + module.exports = { signPamFromParams, endsWith, createPromise, encodeString, stringToArrayBuffer, + removeSingleOccurance, + findUniqueCommonElements, }; diff --git a/src/entities/Channel.ts b/src/entities/Channel.ts new file mode 100644 index 000000000..e3ad72904 --- /dev/null +++ b/src/entities/Channel.ts @@ -0,0 +1,24 @@ +import { Subscription } from './Subscription'; +import { SubscriptionOptions, EventEmitter } from './commonTypes'; +import type PubNub from '../core/pubnub-common'; + +export class Channel { + private name: string; + private eventEmitter: EventEmitter; + private pubnub: PubNub; + + constructor(channelName: string, eventEmitter: EventEmitter, pubnub: PubNub) { + this.name = channelName; + this.eventEmitter = eventEmitter; + this.pubnub = pubnub; + } + subscription(subscriptionOptions?: SubscriptionOptions) { + return new Subscription({ + channels: subscriptionOptions?.receivePresenceEvents ? [this.name, `${this.name}-pnpres`] : [this.name], + channelGroups: [], + subscriptionOptions: subscriptionOptions, + eventEmitter: this.eventEmitter, + pubnub: this.pubnub, + }); + } +} diff --git a/src/entities/ChannelGroup.ts b/src/entities/ChannelGroup.ts new file mode 100644 index 000000000..f668e79c9 --- /dev/null +++ b/src/entities/ChannelGroup.ts @@ -0,0 +1,24 @@ +import { Subscription } from './Subscription'; +import { SubscriptionOptions, EventEmitter } from './commonTypes'; +import type PubNub from '../core/pubnub-common'; + +export class ChannelGroup { + private name: string; + private eventEmitter: EventEmitter; + private pubnub: PubNub; + + constructor(channelGroup: string, eventEmitter: EventEmitter, pubnub: PubNub) { + this.name = channelGroup; + this.eventEmitter = eventEmitter; + this.pubnub = pubnub; + } + subscription(subscriptionOptions?: SubscriptionOptions) { + return new Subscription({ + channels: [], + channelGroups: subscriptionOptions?.receivePresenceEvents ? [this.name, `${this.name}-pnpres`] : [this.name], + subscriptionOptions: subscriptionOptions, + eventEmitter: this.eventEmitter, + pubnub: this.pubnub, + }); + } +} diff --git a/src/entities/ChannelMetadata.ts b/src/entities/ChannelMetadata.ts new file mode 100644 index 000000000..78020d988 --- /dev/null +++ b/src/entities/ChannelMetadata.ts @@ -0,0 +1,24 @@ +import { Subscription } from './Subscription'; +import { SubscriptionOptions, EventEmitter } from './commonTypes'; +import type PubNub from '../core/pubnub-common'; + +export class ChannelMetadata { + private id: string; + private eventEmitter: EventEmitter; + private pubnub: PubNub; + + constructor(id: string, eventEmitter: EventEmitter, pubnub: PubNub) { + this.id = id; + this.eventEmitter = eventEmitter; + this.pubnub = pubnub; + } + subscription(subscriptionOptions?: SubscriptionOptions) { + return new Subscription({ + channels: [this.id], + channelGroups: [], + subscriptionOptions: subscriptionOptions, + eventEmitter: this.eventEmitter, + pubnub: this.pubnub, + }); + } +} diff --git a/src/entities/SubscribeCapable.ts b/src/entities/SubscribeCapable.ts new file mode 100644 index 000000000..93d2e7ebf --- /dev/null +++ b/src/entities/SubscribeCapable.ts @@ -0,0 +1,68 @@ +import { EventEmitter, Listener, SubscriptionOptions } from './commonTypes'; +import PubNubType from 'pubnub'; +import type PubNub from '../core/pubnub-common'; + +export abstract class SubscribeCapable { + protected abstract channelNames: string[]; + protected abstract groupNames: string[]; + protected abstract listener: Listener; + protected abstract eventEmitter: EventEmitter; + protected abstract pubnub: PubNub; + protected abstract options?: SubscriptionOptions; + + subscribe() { + this.pubnub.subscribe({ + channels: this.channelNames, + channelGroups: this.groupNames, + ...(this.options?.cursor?.timetoken && { timetoken: this.options.cursor.timetoken }), + }); + } + unsubscribe() { + this.pubnub.unsubscribe({ + channels: this.channelNames.filter((c) => !c.endsWith('-pnpres')), + channelGroups: this.groupNames.filter((cg) => !cg.endsWith('-pnpres')), + }); + } + + set onMessage(onMessagelistener: (messageEvent: PubNubType.MessageEvent) => void) { + this.listener.message = onMessagelistener; + } + + set onPresence(onPresencelistener: (presenceEvent: PubNubType.PresenceEvent) => void) { + this.listener.presence = onPresencelistener; + } + + set onSignal(onSignalListener: (signalEvent: PubNubType.SignalEvent) => void) { + this.listener.signal = onSignalListener; + } + + set onObjects(onObjectsListener: (objectsEvent: PubNubType.ObjectsEvent) => void) { + this.listener.objects = onObjectsListener; + } + + set onMessageAction(messageActionEventListener: (messageActionEvent: PubNubType.MessageActionEvent) => void) { + this.listener.messageAction = messageActionEventListener; + } + + set onFile(fileEventListener: (fileEvent: PubNubType.FileEvent) => void) { + this.listener.file = fileEventListener; + } + + addListener(listener: Listener) { + this.eventEmitter.addListener( + listener, + this.channelNames.filter((c) => !c.endsWith('-pnpres')), + this.groupNames.filter((cg) => !cg.endsWith('-pnpres')), + ); + } + removeListener(listener: Listener) { + this.eventEmitter.removeListener(listener, this.channelNames, this.groupNames); + } + + get channels(): string[] { + return this.channelNames.slice(0); + } + get channelGroups(): string[] { + return this.groupNames.slice(0); + } +} diff --git a/src/entities/Subscription.ts b/src/entities/Subscription.ts new file mode 100644 index 000000000..6e2a17aa3 --- /dev/null +++ b/src/entities/Subscription.ts @@ -0,0 +1,49 @@ +import { SubscriptionSet } from './SubscriptionSet'; +import { SubscriptionOptions, EventEmitter, Listener } from './commonTypes'; +import type PubNub from '../core/pubnub-common'; +import { SubscribeCapable } from './SubscribeCapable'; + +export class Subscription extends SubscribeCapable { + protected channelNames: string[] = []; + protected groupNames: string[] = []; + protected options?: SubscriptionOptions; + protected pubnub: PubNub; + protected eventEmitter: EventEmitter; + protected listener: Listener; + + constructor({ + channels, + channelGroups, + subscriptionOptions, + eventEmitter, + pubnub, + }: { + channels: string[]; + channelGroups: string[]; + subscriptionOptions?: SubscriptionOptions; + eventEmitter: EventEmitter; + pubnub: PubNub; + }) { + super(); + this.channelNames = channels; + this.groupNames = channelGroups; + this.options = subscriptionOptions; + this.pubnub = pubnub; + this.eventEmitter = eventEmitter; + this.listener = {}; + eventEmitter.addListener( + this.listener, + this.channelNames.filter((c) => !c.endsWith('-pnpres')), + this.groupNames.filter((cg) => !cg.endsWith('-pnpres')), + ); + } + addSubscription(subscription: Subscription) { + return new SubscriptionSet({ + channels: [...this.channelNames, ...subscription.channels], + channelGroups: [...this.groupNames, ...subscription.channelGroups], + subscriptionOptions: { ...this.options, ...subscription?.options }, + eventEmitter: this.eventEmitter, + pubnub: this.pubnub, + }); + } +} diff --git a/src/entities/SubscriptionSet.ts b/src/entities/SubscriptionSet.ts new file mode 100644 index 000000000..83eedff14 --- /dev/null +++ b/src/entities/SubscriptionSet.ts @@ -0,0 +1,81 @@ +import { Subscription } from './Subscription'; +import { SubscriptionOptions, EventEmitter, Listener } from './commonTypes'; +import type PubNub from '../core/pubnub-common'; +import { SubscribeCapable } from './SubscribeCapable'; + +export class SubscriptionSet extends SubscribeCapable { + protected channelNames: string[] = []; + protected groupNames: string[] = []; + protected options: SubscriptionOptions; + protected pubnub: PubNub; + protected eventEmitter: EventEmitter; + protected subscriptionList: Subscription[] = []; + protected listener: Listener; + + constructor({ + channels = [], + channelGroups = [], + subscriptionOptions, + eventEmitter, + pubnub, + }: { + channels: string[]; + channelGroups: string[]; + subscriptionOptions: SubscriptionOptions; + eventEmitter: EventEmitter; + pubnub: PubNub; + }) { + super(); + this.options = subscriptionOptions; + this.eventEmitter = eventEmitter; + this.pubnub = pubnub; + channels.forEach((c) => { + const subscription = this.pubnub.channel(c).subscription(this.options); + this.channelNames = [...this.channelNames, ...subscription.channels]; + this.subscriptionList.push(subscription); + }); + channelGroups.forEach((cg) => { + const subscription = this.pubnub.channelGroup(cg).subscription(this.options); + this.groupNames = [...this.groupNames, ...subscription.channelGroups]; + this.subscriptionList.push(subscription); + }); + this.listener = {}; + eventEmitter.addListener( + this.listener, + this.channelNames.filter((c) => !c.endsWith('-pnpres')), + this.groupNames.filter((cg) => !cg.endsWith('-pnpres')), + ); + } + + addSubscription(subscription: Subscription) { + this.subscriptionList.push(subscription); + this.channelNames = [...this.channelNames, ...subscription.channels]; + this.groupNames = [...this.groupNames, ...subscription.channelGroups]; + } + + removeSubscription(subscription: Subscription) { + const channelsToRemove = subscription.channels; + const groupsToRemove = subscription.channelGroups; + this.channelNames = this.channelNames.filter((c) => !channelsToRemove.includes(c)); + this.groupNames = this.groupNames.filter((cg) => !groupsToRemove.includes(cg)); + this.subscriptionList = this.subscriptionList.filter((s) => s !== subscription); + } + + addSubscriptionSet(subscriptionSet: SubscriptionSet) { + this.subscriptionList = [...this.subscriptionList, ...subscriptionSet.subscriptions]; + this.channelNames = [...this.channelNames, ...subscriptionSet.channels]; + this.groupNames = [...this.groupNames, ...subscriptionSet.channelGroups]; + } + + removeSubscriptionSet(subscriptionSet: SubscriptionSet) { + const channelsToRemove = subscriptionSet.channels; + const groupsToRemove = subscriptionSet.channelGroups; + this.channelNames = this.channelNames.filter((c) => !channelsToRemove.includes(c)); + this.groupNames = this.groupNames.filter((cg) => !groupsToRemove.includes(cg)); + this.subscriptionList = this.subscriptionList.filter((s) => !subscriptionSet.subscriptions.includes(s)); + } + + get subscriptions(): Subscription[] { + return this.subscriptionList.slice(0); + } +} diff --git a/src/entities/UserMetadata.ts b/src/entities/UserMetadata.ts new file mode 100644 index 000000000..3364374f0 --- /dev/null +++ b/src/entities/UserMetadata.ts @@ -0,0 +1,24 @@ +import { Subscription } from './Subscription'; +import { SubscriptionOptions, EventEmitter } from './commonTypes'; +import type PubNub from '../core/pubnub-common'; + +export class UserMetadata { + private id: string; + private eventEmitter: EventEmitter; + private pubnub: PubNub; + + constructor(id: string, eventEmitter: EventEmitter, pubnub: PubNub) { + this.id = id; + this.eventEmitter = eventEmitter; + this.pubnub = pubnub; + } + subscription(subscriptionOptions?: SubscriptionOptions) { + return new Subscription({ + channels: [this.id], + channelGroups: [], + subscriptionOptions: subscriptionOptions, + eventEmitter: this.eventEmitter, + pubnub: this.pubnub, + }); + } +} diff --git a/src/entities/commonTypes.ts b/src/entities/commonTypes.ts new file mode 100644 index 000000000..496d5047d --- /dev/null +++ b/src/entities/commonTypes.ts @@ -0,0 +1,31 @@ +import PubNub from 'pubnub'; + +export type SubscriptionOptions = { + cursor?: { timetoken?: string; region?: number }; + receivePresenceEvents?: boolean; +}; + +export type EventEmitter = { + emitEvent(e: Event): void; + addListener(l: Listener, channels?: string[], groups?: string[]): void; + removeListener(listener: Listener, channels?: string[], groups?: string[]): void; + removeAllListeners(): void; +}; + +export type Listener = { + message?(m: PubNub.MessageEvent): void; + presence?(p: PubNub.PresenceEvent): void; + signal?(s: PubNub.SignalEvent): void; + objects?(o: PubNub.ObjectsEvent): void; + messageAction?(ma: PubNub.MessageActionEvent): void; + file?(f: PubNub.FileEvent): void; + status?(s: PubNub.StatusEvent): void; +}; + +type Event = + | PubNub.MessageEvent + | PubNub.PresenceEvent + | PubNub.SignalEvent + | PubNub.ObjectsEvent + | PubNub.MessageActionEvent + | PubNub.FileEvent; diff --git a/src/event-engine/index.ts b/src/event-engine/index.ts index 18b9cb9d4..c4fb5a0a1 100644 --- a/src/event-engine/index.ts +++ b/src/event-engine/index.ts @@ -2,13 +2,14 @@ import { Dispatcher, Engine } from './core'; import { Dependencies, EventEngineDispatcher } from './dispatcher'; import * as effects from './effects'; import * as events from './events'; - import { UnsubscribedState } from './states/unsubscribed'; +import * as utils from '../core/utils'; + export class EventEngine { private engine: Engine = new Engine(); private dispatcher: Dispatcher; - private dependencies: any; + private dependencies: Dependencies; get _engine() { return this.engine; @@ -42,7 +43,7 @@ export class EventEngine { channelGroups?: string[]; timetoken?: string; withPresence?: boolean; - }) { + }): void { this.channels = [...this.channels, ...(channels ?? [])]; this.groups = [...this.groups, ...(channelGroups ?? [])]; if (withPresence) { @@ -50,41 +51,67 @@ export class EventEngine { this.groups.map((g) => this.groups.push(`${g}-pnpres`)); } if (timetoken) { - this.engine.transition(events.restore(this.channels, this.groups, timetoken)); + this.engine.transition( + events.restore( + Array.from(new Set([...this.channels, ...(channels ?? [])])), + Array.from(new Set([...this.groups, ...(channelGroups ?? [])])), + timetoken, + ), + ); } else { - this.engine.transition(events.subscriptionChange(this.channels, this.groups)); + this.engine.transition( + events.subscriptionChange( + Array.from(new Set([...this.channels, ...(channels ?? [])])), + Array.from(new Set([...this.groups, ...(channelGroups ?? [])])), + ), + ); } if (this.dependencies.join) { this.dependencies.join({ - channels: this.channels.filter((c) => !c.endsWith('-pnpres')), - groups: this.groups.filter((g) => !g.endsWith('-pnpres')), + channels: Array.from(new Set(this.channels.filter((c) => !c.endsWith('-pnpres')))), + groups: Array.from(new Set(this.groups.filter((g) => !g.endsWith('-pnpres')))), }); } } - unsubscribe({ channels, groups }: { channels?: string[]; groups?: string[] }) { - const channlesWithPres: any = channels?.slice(0); - channels?.map((c) => channlesWithPres.push(`${c}-pnpres`)); - this.channels = this.channels.filter((channel) => !channlesWithPres?.includes(channel)); - - const groupsWithPres: any = groups?.slice(0); - groups?.map((g) => groupsWithPres.push(`${g}-pnpres`)); - this.groups = this.groups.filter((group) => !groupsWithPres?.includes(group)); - - if (this.dependencies.presenceState) { - channels?.forEach((c) => delete this.dependencies.presenceState[c]); - groups?.forEach((g) => delete this.dependencies.presenceState[g]); - } - this.engine.transition(events.subscriptionChange(this.channels.slice(0), this.groups.slice(0))); - if (this.dependencies.leave) { - this.dependencies.leave({ - channels: channels, - groups: groups, - }); + unsubscribe({ channels = [], channelGroups = [] }: { channels?: string[]; channelGroups?: string[] }): void { + const filteredChannels = utils.removeSingleOccurance(this.channels, [ + ...channels, + ...channels.map((c) => `${c}-pnpres`), + ]); + const filteredGroups = utils.removeSingleOccurance(this.groups, [ + ...channelGroups, + ...channelGroups.map((c) => `${c}-pnpres`), + ]); + + if ( + new Set(this.channels).size !== new Set(filteredChannels).size || + new Set(this.groups).size !== new Set(filteredGroups).size + ) { + const channelsToLeave = utils.findUniqueCommonElements(this.channels, channels); + const groupstoLeave = utils.findUniqueCommonElements(this.groups, channelGroups); + if (this.dependencies.presenceState) { + channelsToLeave?.forEach((c) => delete this.dependencies.presenceState[c]); + groupstoLeave?.forEach((g) => delete this.dependencies.presenceState[g]); + } + this.channels = filteredChannels; + this.groups = filteredGroups; + this.engine.transition( + events.subscriptionChange( + Array.from(new Set(this.channels.slice(0))), + Array.from(new Set(this.groups.slice(0))), + ), + ); + if (this.dependencies.leave) { + this.dependencies.leave({ + channels: channelsToLeave.slice(0), + groups: groupstoLeave.slice(0), + }); + } } } - unsubscribeAll() { + unsubscribeAll(): void { this.channels = []; this.groups = []; @@ -97,26 +124,26 @@ export class EventEngine { } } - reconnect({ timetoken, region }: { timetoken?: string; region?: number }) { + reconnect({ timetoken, region }: { timetoken?: string; region?: number }): void { this.engine.transition(events.reconnect(timetoken, region)); } - disconnect() { + disconnect(): void { this.engine.transition(events.disconnect()); if (this.dependencies.leaveAll) { this.dependencies.leaveAll(); } } - getSubscribedChannels() { + getSubscribedChannels(): string[] { return this.channels.slice(0); } - getSubscribedChannelGroups() { + getSubscribedChannelGroups(): string[] { return this.groups.slice(0); } - dispose() { + dispose(): void { this.disconnect(); this._unsubscribeEngine(); this.dispatcher.dispose(); diff --git a/test/integration/components/listeners.test.js b/test/integration/components/listeners.test.js new file mode 100644 index 000000000..77e676f64 --- /dev/null +++ b/test/integration/components/listeners.test.js @@ -0,0 +1,544 @@ +import nock from 'nock'; +import _ from 'underscore'; + +import utils from '../../utils'; +import PubNub from '../../../src/node/index'; + +let pubnub; + +describe('#listeners', () => { + before(() => { + nock.disableNetConnect(); + }); + + after(() => { + nock.enableNetConnect(); + }); + + beforeEach(() => { + nock.cleanAll(); + pubnub = new PubNub({ + subscribeKey: 'mySubKey', + publishKey: 'myPublishKey', + uuid: 'myUUID', + enableEventEngine: true, + autoNetworkDetection: false, + }); + }); + + afterEach(() => { + pubnub.stop(); + pubnub.destroy(); + }); + + it('should pass messages of subscribed channel to its listener', async () => { + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + state: '{}', + tt: 0, + }) + .reply(200, '{"t":{"t":"3","r":1},"m":[]}'); + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + tt: '3', + tr: 1, + }) + .reply( + 200, + '{"t":{"t":"10","r":1},"m":[{"a":"3","f":514,"i":"demo","p":{"t":"17069673079697201","r":33},"k":"demo","c":"ch1","d":{"message":"My message!"}}]}', + ); + var channel = pubnub.channel('ch1'); + var subscription = channel.subscription(); + var messagePromise = new Promise((resolveMessage) => + subscription.addListener({ + message: (m) => resolveMessage(m), + }), + ); + subscription.subscribe(); + const actual = await messagePromise; + expect(JSON.stringify(actual.message)).to.equal('{"message":"My message!"}'); + }); + it('should subscribed to channel and presence channels', async () => { + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1%2Cch1-pnpres/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + state: '{}', + tt: 0, + }) + .reply(200, '{"t":{"t":"3","r":1},"m":[]}'); + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1%2Cch1-pnpres/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + tt: '3', + tr: 1, + }) + .reply( + 200, + '{"t":{"t":"10","r":1},"m":[{"a":"3","f":514,"i":"demo","p":{"t":"17069673079697201","r":33},"k":"demo","c":"ch1","d":{"message":"My message!"}}]}', + ); + + const channel = pubnub.channel('ch1'); + const subscription = channel.subscription({ receivePresenceEvents: true }); + const messagePromise = new Promise((resolveMessage) => + subscription.addListener({ + message: (m) => resolveMessage(m), + }), + ); + subscription.subscribe(); + const actual = await messagePromise; + expect(JSON.stringify(actual.message)).to.equal('{"message":"My message!"}'); + }); + + it('should work with subscriptionSet', async () => { + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1%2Cch2/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + state: '{}', + tt: 0, + }) + .reply(200, '{"t":{"t":"3","r":1},"m":[]}'); + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1%2Cch2/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + tt: '3', + tr: 1, + }) + .reply( + 200, + '{"t":{"t":"10","r":1},"m":[{"a":"3","f":514,"i":"demo","p":{"t":"17069673079697201","r":33},"k":"demo","c":"ch1","d":{"message":"My message!"}}]}', + ); + + const channel = pubnub.channel('ch1'); + const subscription = channel.subscription(); + const subscriptionSet = subscription.addSubscription(pubnub.channel('ch2').subscription()); + const messagePromise = new Promise((resolveMessage) => + subscriptionSet.addListener({ + message: (m) => resolveMessage(m), + }), + ); + subscriptionSet.subscribe(); + const actual = await messagePromise; + expect(JSON.stringify(actual.message)).to.equal('{"message":"My message!"}'); + }); + + it('should able to create subscriptionSet', async () => { + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1%2Cch2/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + state: '{}', + tt: 0, + }) + .reply(200, '{"t":{"t":"3","r":1},"m":[]}'); + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1%2Cch2/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + tt: '3', + tr: 1, + }) + .reply( + 200, + '{"t":{"t":"10","r":1},"m":[{"a":"3","f":514,"i":"demo","p":{"t":"17069673079697201","r":33},"k":"demo","c":"ch1","d":{"message":"My message!"}}]}', + ); + + const subscriptionSet = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] }); + + const messagePromise = new Promise((resolveMessage) => + subscriptionSet.addListener({ + message: (m) => resolveMessage(m), + }), + ); + subscriptionSet.subscribe(); + const actual = await messagePromise; + expect(JSON.stringify(actual.message)).to.equal('{"message":"My message!"}'); + }); + + it('subscriptionSet works with add/remove with set', async () => { + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch3%2Cch4/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + state: '{}', + tt: 0, + }) + .reply(200, '{"t":{"t":"3","r":1},"m":[]}'); + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch3%2Cch4/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + tt: '3', + tr: 1, + }) + .reply( + 200, + '{"t":{"t":"10","r":1},"m":[{"a":"3","f":514,"i":"demo","p":{"t":"17069673079697201","r":33},"k":"demo","c":"ch3","d":{"message":"My message!"}}]}', + ); + + const subscriptionSetCh34 = pubnub.subscriptionSet({ channels: ['ch3', 'ch4'] }); + + const subscriptionSetCh12 = pubnub + .channel('ch1') + .subscription() + .addSubscription(pubnub.channel('ch2').subscription()); + + subscriptionSetCh34.addSubscriptionSet(subscriptionSetCh12); + subscriptionSetCh34.removeSubscriptionSet(subscriptionSetCh12); + + const messagePromise = new Promise((resolveMessage) => + subscriptionSetCh34.addListener({ + message: (m) => resolveMessage(m), + }), + ); + subscriptionSetCh34.subscribe(); + const actual = await messagePromise; + expect(JSON.stringify(actual.message)).to.equal('{"message":"My message!"}'); + }); + it('listener should route presence event to registered handler', async () => { + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1%2Cch1-pnpres/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + state: '{}', + tt: 0, + }) + .reply(200, '{"t":{"t":"3","r":1},"m":[]}'); + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1%2Cch1-pnpres/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + tt: '3', + tr: 1, + }) + .reply( + 200, + '{"t":{"t":"17070458535164862","r":31},"m":[{"a":"0","f":0,"p":{"t":"17070458535164862","r":31},"k":"mySubKey","c":"ch1-pnpres","u":{"pn_action":"join","pn_uuid":"dartClient","pn_timestamp":1707045853,"pn_precise_timestamp":1707045853513,"pn_occupancy":2,"pn_ispresence":1,"pn_channel":"ch1"},"d":{"action":"join","uuid":"p2","timestamp":1707045853,"precise_timestamp":1707045853513,"occupancy":2},"b":"ch1-pnpres"}]}', + ); + + const channel = pubnub.channel('ch1'); + const subscription = channel.subscription({ receivePresenceEvents: true }); + const presencePromise = new Promise((resolvePresence) => + subscription.addListener({ + presence: (p) => resolvePresence(p), + }), + ); + subscription.subscribe(); + const actual = await presencePromise; + expect(actual.action).to.equal('join'); + expect(actual.occupancy).to.equal(2); + }); + + it('add/remove listener should work on subscription', async () => { + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + state: '{}', + tt: 0, + }) + .reply(200, '{"t":{"t":"3","r":1},"m":[]}'); + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + tt: '3', + tr: 1, + }) + .reply( + 200, + '{"t":{"t":"10","r":1},"m":[{"a":"3","f":514,"i":"demo","p":{"t":"17069673079697201","r":33},"k":"demo","c":"ch1","d":{"message":"My message!"}}]}', + ); + const messages = []; + const channel = pubnub.channel('ch1'); + const subscription = channel.subscription(); + const listener = { message: (m) => messages.push(m) }; + subscription.addListener(listener); + const messagePromise = new Promise((resolveMessage) => + subscription.addListener({ + message: (m) => resolveMessage(m), + }), + ); + subscription.removeListener(listener); + subscription.subscribe(); + const actual = await messagePromise; + expect(JSON.stringify(actual.message)).to.equal('{"message":"My message!"}'); + expect(messages.length).to.equal(0); + }); + + it('should work with channel groups and their presence', async () => { + utils + .createNock() + .get('/v2/subscribe/mySubKey/%2C/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + state: '{}', + tt: 0, + 'channel-group': 'cg1,cg1-pnpres', + }) + .reply(200, '{"t":{"t":"3","r":1},"m":[]}'); + utils + .createNock() + .get('/v2/subscribe/mySubKey/%2C/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + tt: '3', + tr: 1, + 'channel-group': 'cg1,cg1-pnpres', + }) + .reply( + 200, + '{"t":{"t":"17070655215847224","r":33},"m":[{"a":"0","f":0,"i":"cl1","p":{"t":"17070655215847224","r":31},"k":"mySubKey","c":"ch1","d":{"message":"My message!"},"b":"cg1"}]}', + ); + var channelGroup = pubnub.channelGroup('cg1'); + var subscription = channelGroup.subscription({ receivePresenceEvents: true }); + var messagePromise = new Promise((resolveMessage) => + subscription.addListener({ + message: (m) => resolveMessage(m), + }), + ); + subscription.subscribe(); + const actual = await messagePromise; + expect(JSON.stringify(actual.message)).to.equal('{"message":"My message!"}'); + }); + + it('subscribe/unsubscribe handle edge case of having overlaping channel/group set', async () => { + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + state: '{}', + tt: 0, + }) + .reply(200, '{"t":{"t":"3","r":1},"m":[]}'); + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + tt: '3', + tr: 1, + }) + .reply( + 200, + '{"t":{"t":"10","r":1},"m":[{"a":"3","f":514,"i":"demo","p":{"t":"17069673079697201","r":33},"k":"demo","c":"ch1","d":{"message":"My message!"}}]}', + ); + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + tt: '10', + tr: 1, + }) + .reply( + 200, + '{"t":{"t":"10","r":1},"m":[{"a":"3","f":514,"i":"demo","p":{"t":"17069673079697201","r":33},"k":"demo","c":"ch1","d":{"message":"My message!"}}]}', + ); + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1%2Cch2/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + tt: '10', + tr: 1, + }) + .reply( + 200, + '{"t":{"t":"10","r":1},"m":[{"a":"3","f":514,"i":"demo","p":{"t":"17069673079697201","r":33},"k":"demo","c":"ch1","d":{"message":"My message!"}}]}', + ); + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1%2Cch2%2Cch3/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + tt: '10', + tr: 1, + }) + .reply( + 200, + '{"t":{"t":"10","r":1},"m":[{"a":"3","f":514,"i":"demo","p":{"t":"17069673079697201","r":33},"k":"demo","c":"ch1","d":{"message":"My message!"}}]}', + ); + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch2%2Cch3/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + tt: '10', + tr: 1, + }) + .reply( + 200, + '{"t":{"t":"12","r":1},"m":[{"a":"3","f":514,"i":"demo","p":{"t":"17069673079697201","r":33},"k":"demo","c":"ch2","d":{"ch2":"My message!"}}]}', + ); + const messages = []; + const channel = pubnub.channel('ch1'); + const subscription = channel.subscription(); + const listener = { message: (m) => messages.push(m) }; + subscription.addListener(listener); + const messagePromise = new Promise((resolveMessage) => + subscription.addListener({ + message: (m) => resolveMessage(m), + }), + ); + subscription.removeListener(listener); + subscription.subscribe(); + const actual = await messagePromise; + expect(JSON.stringify(actual.message)).to.equal('{"message":"My message!"}'); + expect(messages.length).to.equal(0); + const subscriptionCh2 = pubnub.channel('ch2').subscription(); + subscriptionCh2.subscribe(); + const subscriptionCh3 = pubnub.channel('ch3').subscription(); + const subscriptionSetCh23 = subscriptionCh3.addSubscription(pubnub.channel('ch2').subscription()); + const messagePromiseChannel2 = new Promise((resolveMessage) => + subscriptionSetCh23.addListener({ + message: (m) => resolveMessage(m), + }), + ); + subscriptionSetCh23.subscribe(); + subscription.unsubscribe(); + subscriptionCh2.unsubscribe(); + const actualChannel2MessageAfterOneUnsubCh2 = await messagePromiseChannel2; + pubnub.destroy(); + expect(JSON.stringify(actualChannel2MessageAfterOneUnsubCh2.message)).to.equal('{"ch2":"My message!"}'); + }); + + it('should work with event type specific listener registraction', async () => { + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + state: '{}', + tt: 0, + }) + .reply(200, '{"t":{"t":"3","r":1},"m":[]}'); + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + tt: '3', + tr: 1, + }) + .reply( + 200, + '{"t":{"t":"10","r":1},"m":[{"a":"3","f":514,"i":"demo","p":{"t":"17069673079697201","r":33},"k":"demo","c":"ch1","d":{"message":"My message!"}}]}', + ); + var channel = pubnub.channel('ch1'); + var subscription = channel.subscription(); + var messagePromise = new Promise((resolveMessage) => (subscription.onMessage = (m) => resolveMessage(m))); + subscription.subscribe(); + const actual = await messagePromise; + expect(JSON.stringify(actual.message)).to.equal('{"message":"My message!"}'); + }); + + it('with presence should work with event type specific listener registraction', async () => { + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1%2Cch1-pnpres/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + state: '{}', + tt: 0, + }) + .reply(200, '{"t":{"t":"3","r":1},"m":[]}'); + utils + .createNock() + .get('/v2/subscribe/mySubKey/ch1%2Cch1-pnpres/0') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + ee: '', + tt: '3', + tr: 1, + }) + .reply( + 200, + '{"t":{"t":"10","r":1},"m":[{"a":"4","f":0,"p":{"t":"8","r":2},"k":"subKey","c":"ch1-pnpres","d":{"action": "join", "timestamp": 1461451222, "uuid": "testid", "occupancy": 1},"b":"ch1-pnpres"}]}', + ); + + const channel = pubnub.channel('ch1'); + const subscription = channel.subscription({ receivePresenceEvents: true }); + const presencePromise = new Promise( + (resolvePresenceEvent) => (subscription.onPresence = (p) => resolvePresenceEvent(p)), + ); + subscription.subscribe(); + const actual = await presencePromise; + expect(JSON.stringify(actual)).to.equal( + '{"channel":"ch1","subscription":null,"action":"join","occupancy":1,"uuid":"testid","timestamp":1461451222,"actualChannel":null,"subscribedChannel":"ch1-pnpres"}', + ); + }); +}); diff --git a/test/integration/components/subscription_manager.test.js b/test/integration/components/subscription_manager.test.js index 56990f990..dfc871aaf 100644 --- a/test/integration/components/subscription_manager.test.js +++ b/test/integration/components/subscription_manager.test.js @@ -722,7 +722,6 @@ describe('#components/subscription_manager', () => { pubnubWithCrypto.addListener({ message(messagePayload) { incomingPayloads.push(messagePayload); - console.log('\n\n\n incomingpayload = ', JSON.stringify(incomingPayloads)); if (incomingPayloads.length === 1) { assert.equal(scope.isDone(), true); assert.deepEqual(incomingPayloads, [