From a14fd4947c519202833299e4d88b1717b255a366 Mon Sep 17 00:00:00 2001 From: Serhii Mamontov Date: Tue, 18 Feb 2025 02:11:58 +0200 Subject: [PATCH 1/2] feat(subscribe): emit `PNDisconnectedUnexpectedlyCategory` Emit 'PNDisconnectedUnexpectedlyCategory' in cases when client receives bad request or unexpected / malformed service response. refactor(request): move deserialized error parse into abstract request Move error / malformed response handling into `AbstractRequest` to simplify actual endpoint classes. --- dist/web/pubnub.js | 501 ++++++------------ dist/web/pubnub.min.js | 4 +- dist/web/pubnub.worker.js | 18 +- dist/web/pubnub.worker.min.js | 4 +- lib/core/components/request.js | 34 +- lib/core/components/subscription-manager.js | 14 +- lib/core/constants/categories.js | 8 + lib/core/endpoints/access_manager/audit.js | 10 +- lib/core/endpoints/access_manager/grant.js | 10 +- .../endpoints/access_manager/grant_token.js | 10 +- .../endpoints/access_manager/revoke_token.js | 13 +- .../endpoints/actions/add_message_action.js | 13 +- .../endpoints/actions/get_message_actions.js | 7 - .../actions/remove_message_action.js | 13 +- .../endpoints/channel_groups/add_channels.js | 13 +- .../endpoints/channel_groups/delete_group.js | 13 +- .../endpoints/channel_groups/list_channels.js | 10 +- .../endpoints/channel_groups/list_groups.js | 10 +- .../channel_groups/remove_channels.js | 13 +- lib/core/endpoints/fetch_messages.js | 7 - lib/core/endpoints/file_upload/delete_file.js | 22 - .../file_upload/generate_upload_url.js | 7 - lib/core/endpoints/file_upload/list_files.js | 22 - .../endpoints/file_upload/publish_file.js | 6 +- lib/core/endpoints/file_upload/send_file.js | 4 +- lib/core/endpoints/history/delete_messages.js | 13 +- lib/core/endpoints/history/get_history.js | 3 - lib/core/endpoints/history/message_counts.js | 10 +- lib/core/endpoints/objects/channel/get.js | 22 - lib/core/endpoints/objects/channel/get_all.js | 22 - lib/core/endpoints/objects/channel/remove.js | 22 - lib/core/endpoints/objects/channel/set.js | 22 - lib/core/endpoints/objects/member/get.js | 22 - lib/core/endpoints/objects/member/set.js | 22 - lib/core/endpoints/objects/membership/get.js | 22 - lib/core/endpoints/objects/membership/set.js | 22 - lib/core/endpoints/objects/uuid/get.js | 22 - lib/core/endpoints/objects/uuid/get_all.js | 22 - lib/core/endpoints/objects/uuid/remove.js | 22 - lib/core/endpoints/objects/uuid/set.js | 22 - lib/core/endpoints/presence/get_state.js | 7 - lib/core/endpoints/presence/heartbeat.js | 13 +- lib/core/endpoints/presence/here_now.js | 7 - lib/core/endpoints/presence/leave.js | 13 +- lib/core/endpoints/presence/set_state.js | 10 +- lib/core/endpoints/presence/where_now.js | 7 - lib/core/endpoints/publish.js | 8 +- lib/core/endpoints/push/add_push_channels.js | 9 +- lib/core/endpoints/push/list_push_channels.js | 6 +- lib/core/endpoints/push/push.js | 14 - lib/core/endpoints/push/remove_device.js | 9 +- .../endpoints/push/remove_push_channels.js | 9 +- lib/core/endpoints/signal.js | 6 +- lib/core/endpoints/subscribe.js | 7 +- lib/core/endpoints/time.js | 6 +- lib/core/pubnub-common.js | 15 +- lib/errors/pubnub-api-error.js | 35 +- lib/errors/pubnub-error.js | 17 +- lib/transport/node-transport.js | 16 +- lib/transport/react-native-transport.js | 14 +- lib/types/index.d.ts | 10 +- package-lock.json | 4 +- src/core/components/request.ts | 48 +- src/core/components/subscription-manager.ts | 23 +- src/core/constants/categories.ts | 9 + src/core/endpoints/access_manager/audit.ts | 15 +- src/core/endpoints/access_manager/grant.ts | 15 +- .../endpoints/access_manager/grant_token.ts | 15 +- .../endpoints/access_manager/revoke_token.ts | 15 +- .../endpoints/actions/add_message_action.ts | 15 +- .../endpoints/actions/get_message_actions.ts | 17 +- .../actions/remove_message_action.ts | 15 +- .../endpoints/channel_groups/add_channels.ts | 18 +- .../endpoints/channel_groups/delete_group.ts | 20 +- .../endpoints/channel_groups/list_channels.ts | 18 +- .../endpoints/channel_groups/list_groups.ts | 18 +- .../channel_groups/remove_channels.ts | 16 +- src/core/endpoints/fetch_messages.ts | 14 +- src/core/endpoints/file_upload/delete_file.ts | 18 +- .../endpoints/file_upload/download_file.ts | 2 +- .../file_upload/generate_upload_url.ts | 16 +- .../endpoints/file_upload/get_file_url.ts | 2 +- src/core/endpoints/file_upload/list_files.ts | 18 +- .../endpoints/file_upload/publish_file.ts | 16 +- src/core/endpoints/file_upload/send_file.ts | 6 +- src/core/endpoints/file_upload/upload-file.ts | 4 +- src/core/endpoints/history/delete_messages.ts | 15 +- src/core/endpoints/history/get_history.ts | 12 +- src/core/endpoints/history/message_counts.ts | 15 +- src/core/endpoints/objects/channel/get.ts | 18 +- src/core/endpoints/objects/channel/get_all.ts | 18 +- src/core/endpoints/objects/channel/remove.ts | 18 +- src/core/endpoints/objects/channel/set.ts | 18 +- src/core/endpoints/objects/member/get.ts | 18 +- src/core/endpoints/objects/member/set.ts | 18 +- src/core/endpoints/objects/membership/get.ts | 18 +- src/core/endpoints/objects/membership/set.ts | 18 +- src/core/endpoints/objects/uuid/get.ts | 18 +- src/core/endpoints/objects/uuid/get_all.ts | 18 +- src/core/endpoints/objects/uuid/remove.ts | 23 +- src/core/endpoints/objects/uuid/set.ts | 18 +- src/core/endpoints/presence/get_state.ts | 14 +- src/core/endpoints/presence/heartbeat.ts | 15 +- src/core/endpoints/presence/here_now.ts | 14 +- src/core/endpoints/presence/leave.ts | 15 +- src/core/endpoints/presence/set_state.ts | 15 +- src/core/endpoints/presence/where_now.ts | 14 +- src/core/endpoints/publish.ts | 14 +- src/core/endpoints/push/add_push_channels.ts | 14 +- src/core/endpoints/push/list_push_channels.ts | 14 +- src/core/endpoints/push/push.ts | 7 +- src/core/endpoints/push/remove_device.ts | 14 +- .../endpoints/push/remove_push_channels.ts | 14 +- src/core/endpoints/signal.ts | 13 +- src/core/endpoints/subscribe.ts | 11 +- src/core/endpoints/time.ts | 13 +- src/core/pubnub-channel-groups.ts | 4 +- src/core/pubnub-common.ts | 32 +- src/core/pubnub-objects.ts | 4 +- src/core/pubnub-push.ts | 4 +- src/core/types/api/index.ts | 4 +- src/core/types/transport-request.ts | 2 +- src/errors/pubnub-api-error.ts | 35 +- src/errors/pubnub-error.ts | 33 +- src/transport/node-transport.ts | 17 +- src/transport/react-native-transport.ts | 17 +- .../subscription-worker.ts | 17 +- src/transport/web-transport.ts | 14 +- test/dist/web-titanium.test.js | 12 +- 129 files changed, 664 insertions(+), 1686 deletions(-) diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index 3db1a262a..f9636ceb5 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -835,6 +835,14 @@ * Some API endpoints respond with request processing status w/o useful data. */ StatusCategory["PNAcknowledgmentCategory"] = "PNAcknowledgmentCategory"; + /** + * PubNub service or intermediate "actor" returned unexpected response. + * + * There can be few sources of unexpected return with success code: + * - proxy server / VPN; + * - Wi-Fi hotspot authorization page. + */ + StatusCategory["PNMalformedResponseCategory"] = "PNMalformedResponseCategory"; /** * Something strange happened; please check the logs. */ @@ -914,15 +922,16 @@ * Create error status object. * * @param errorPayload - Additional information which should be attached to the error status object. + * @param category - Occurred error category. * * @returns Error status object. * * @internal */ - function createError(errorPayload) { + function createError(errorPayload, category) { var _a; (_a = errorPayload.statusCode) !== null && _a !== void 0 ? _a : (errorPayload.statusCode = 0); - return Object.assign(Object.assign({}, errorPayload), { statusCode: errorPayload.statusCode, category: StatusCategory$1.PNValidationErrorCategory, error: true }); + return Object.assign(Object.assign({}, errorPayload), { statusCode: errorPayload.statusCode, category, error: true }); } /** * Create operation arguments validation error status object. @@ -935,7 +944,16 @@ * @internal */ function createValidationError(message, statusCode) { - return createError(Object.assign({ message }, ({}))); + return createError(Object.assign({ message }, ({})), StatusCategory$1.PNValidationErrorCategory); + } + /** + * Create malformed service response error status object. + * + * @param [responseText] - Stringified original service response. + * @param [statusCode] - Operation HTTP status code. + */ + function createMalformedResponseError(responseText, statusCode) { + return createError(Object.assign(Object.assign({ message: 'Unable to deserialize service response' }, (responseText !== undefined ? { responseText } : {})), (statusCode !== undefined ? { statusCode } : {})), StatusCategory$1.PNMalformedResponseCategory); } /** @@ -2979,20 +2997,29 @@ response.headers['content-type'].indexOf('application/json') !== -1) { try { const errorResponse = JSON.parse(decoded); - if (typeof errorResponse === 'object' && !Array.isArray(errorResponse)) { - if ('error' in errorResponse && - (errorResponse.error === 1 || errorResponse.error === true) && - 'status' in errorResponse && - typeof errorResponse.status === 'number' && - 'message' in errorResponse && - 'service' in errorResponse) { - errorData = errorResponse; - status = errorResponse.status; + if (typeof errorResponse === 'object') { + if (!Array.isArray(errorResponse)) { + if ('error' in errorResponse && + (errorResponse.error === 1 || errorResponse.error === true) && + 'status' in errorResponse && + typeof errorResponse.status === 'number' && + 'message' in errorResponse && + 'service' in errorResponse) { + errorData = errorResponse; + status = errorResponse.status; + } + else + errorData = errorResponse; + if ('error' in errorResponse && errorResponse.error instanceof Error) + errorData = errorResponse.error; + } + else { + // Handling Publish API payload error. + if (typeof errorResponse[0] === 'number' && errorResponse[0] === 0) { + if (errorResponse.length > 1 && typeof errorResponse[1] === 'string') + errorData = errorResponse[1]; + } } - else - errorData = errorResponse; - if ('error' in errorResponse && errorResponse.error instanceof Error) - errorData = errorResponse.error; } } catch (_) { @@ -4217,7 +4244,7 @@ const abortController = new AbortController(); const cancellation = { abortController, - abort: () => !abortController.signal.aborted && abortController.abort(), + abort: (reason) => !abortController.signal.aborted && abortController.abort(reason), }; return [ this.webTransportRequestFromTransportRequest(req).then((request) => { @@ -4243,7 +4270,15 @@ return transportResponse; }) .catch((error) => { - throw PubNubAPIError.create(error); + let fetchError = error; + if (typeof error === 'string') { + const errorMessage = error.toLowerCase(); + if (errorMessage.includes('timeout') || !errorMessage.includes('cancel')) + fetchError = new Error(error); + else if (errorMessage.includes('cancel')) + fetchError = new DOMException('Aborted', 'AbortError'); + } + throw PubNubAPIError.create(fetchError); }); }), cancellation, @@ -4286,7 +4321,7 @@ timeoutId = setTimeout(() => { clearTimeout(timeoutId); reject(new Error('Request timeout')); - controller.abort(); + controller.abort('Cancel because of timeout'); }, req.timeout * 1000); }); const request = new Request(req.url, { @@ -5025,13 +5060,15 @@ this.reconnectionManager.startPolling(); this.listenerManager.announceStatus(status); } - else if (status.category === StatusCategory$1.PNBadRequestCategory) { - this.stopHeartbeatTimer(); - this.listenerManager.announceStatus(status); + else if (status.category === StatusCategory$1.PNBadRequestCategory || + status.category == StatusCategory$1.PNMalformedResponseCategory) { + const category = this.isOnline ? StatusCategory$1.PNDisconnectedUnexpectedlyCategory : status.category; + this.isOnline = false; + this.disconnect(); + this.listenerManager.announceStatus(Object.assign(Object.assign({}, status), { category })); } - else { + else this.listenerManager.announceStatus(status); - } return; } if (this.storedTimetoken) { @@ -5828,10 +5865,12 @@ } /** * Abort request if possible. + * + * @param [reason] Information about why request has been cancelled. */ - abort() { + abort(reason) { if (this && this.cancellationController) - this.cancellationController.abort(); + this.cancellationController.abort(reason); } /** * Target REST API endpoint operation type. @@ -5850,11 +5889,11 @@ /** * Parse service response. * - * @param _response - Raw service response which should be parsed. + * @param response - Raw service response which should be parsed. */ - parse(_response) { + parse(response) { return __awaiter(this, void 0, void 0, function* () { - throw Error('Should be implemented by subclass.'); + return this.deserializeResponse(response); }); } /** @@ -5926,21 +5965,29 @@ * * @param response - Transparent response object with headers and body information. * - * @returns Deserialized data or `undefined` in case of `JSON.parse(..)` error. + * @returns Deserialized service response data. + * + * @throws {Error} if received service response can't be processed (has unexpected content-type or can't be parsed as + * JSON). */ deserializeResponse(response) { + const responseText = AbstractRequest.decoder.decode(response.body); const contentType = response.headers['content-type']; + let parsedJson; if (!contentType || (contentType.indexOf('javascript') === -1 && contentType.indexOf('json') === -1)) - return undefined; - const json = AbstractRequest.decoder.decode(response.body); + throw new PubNubError('Service response error, check status for details', createMalformedResponseError(responseText, response.status)); try { - const parsedJson = JSON.parse(json); - return parsedJson; + parsedJson = JSON.parse(responseText); } catch (error) { console.error('Error parsing JSON response:', error); - return undefined; + throw new PubNubError('Service response error, check status for details', createMalformedResponseError(responseText, response.status)); + } + // Throw and exception in case of client / server error. + if ('status' in parsedJson && typeof parsedJson.status === 'number' && parsedJson.status >= 400) { + throw PubNubAPIError.create(response); } + return parsedJson; } } /** @@ -6282,16 +6329,17 @@ parse(response) { return __awaiter(this, void 0, void 0, function* () { let serviceResponse; + let responseText; try { - const json = AbstractRequest.decoder.decode(response.body); - const parsedJson = JSON.parse(json); + responseText = AbstractRequest.decoder.decode(response.body); + const parsedJson = JSON.parse(responseText); serviceResponse = parsedJson; } catch (error) { console.error('Error parsing JSON response:', error); } if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); + throw new PubNubError('Service response error, check status for details', createMalformedResponseError(responseText, response.status)); } const events = serviceResponse.m .filter((envelope) => { @@ -8474,10 +8522,7 @@ } parse(response) { return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - return { timetoken: serviceResponse[2] }; + return { timetoken: this.deserializeResponse(response)[2] }; }); } get path() { @@ -8501,6 +8546,8 @@ return query; } get headers() { + if (!this.parameters.sendByPost) + return undefined; return { 'Content-Type': 'application/json' }; } get body() { @@ -8554,10 +8601,7 @@ } parse(response) { return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - return { timetoken: serviceResponse[2] }; + return { timetoken: this.deserializeResponse(response)[2] }; }); } get path() { @@ -8685,11 +8729,6 @@ parse(response) { return __awaiter(this, void 0, void 0, function* () { const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); const { channels = [], channelGroups = [] } = this.parameters; const state = { channels: {} }; if (channels.length === 1 && channelGroups.length === 0) @@ -8741,13 +8780,7 @@ } parse(response) { return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return { state: serviceResponse.payload }; + return { state: this.deserializeResponse(response).payload }; }); } get path() { @@ -8790,14 +8823,11 @@ return 'Please provide a list of channels and/or channel-groups'; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return {}; + return _super.parse.call(this, response).then((_) => ({})); }); } get path() { @@ -8846,14 +8876,11 @@ return 'At least one `channel` or `channel group` should be provided.'; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return {}; + return _super.parse.call(this, response).then((_) => ({})); }); } get path() { @@ -8895,11 +8922,6 @@ parse(response) { return __awaiter(this, void 0, void 0, function* () { const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); if (!serviceResponse.payload) return { channels: [] }; return { channels: serviceResponse.payload.channels }; @@ -8959,11 +8981,6 @@ return __awaiter(this, void 0, void 0, function* () { var _a, _b; const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); // Extract general presence information. const totalChannels = 'occupancy' in serviceResponse ? 1 : serviceResponse.payload.total_channels; const totalOccupancy = 'occupancy' in serviceResponse ? serviceResponse.occupancy : serviceResponse.payload.total_occupancy; @@ -9036,14 +9053,11 @@ return 'Missing channel'; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return {}; + return _super.parse.call(this, response).then((_) => ({})); }); } get path() { @@ -9090,13 +9104,7 @@ } parse(response) { return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return { channels: serviceResponse.channels }; + return { channels: this.deserializeResponse(response).channels }; }); } get path() { @@ -9167,8 +9175,6 @@ parse(response) { return __awaiter(this, void 0, void 0, function* () { const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); const messages = serviceResponse[0]; const startTimeToken = serviceResponse[1]; const endTimeToken = serviceResponse[2]; @@ -9329,11 +9335,6 @@ return __awaiter(this, void 0, void 0, function* () { var _a; const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); const responseChannels = (_a = serviceResponse.channels) !== null && _a !== void 0 ? _a : {}; const channels = {}; Object.keys(responseChannels).forEach((channel) => { @@ -9457,11 +9458,6 @@ parse(response) { return __awaiter(this, void 0, void 0, function* () { const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); let start = null; let end = null; if (serviceResponse.data.length > 0) { @@ -9523,14 +9519,11 @@ return 'Action.type value exceed maximum length of 15'; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return { data: serviceResponse.data }; + return _super.parse.call(this, response).then(({ data }) => ({ data })); }); } get path() { @@ -9576,14 +9569,11 @@ return 'Missing action timetoken'; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return { data: serviceResponse.data }; + return _super.parse.call(this, response).then(({ data }) => ({ data })); }); } get path() { @@ -9634,10 +9624,7 @@ } parse(response) { return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - return { timetoken: serviceResponse[2] }; + return { timetoken: this.deserializeResponse(response)[2] }; }); } get path() { @@ -9746,17 +9733,6 @@ if (!name) return "file name can't be empty"; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, id, channel, name, } = this.parameters; return `/v1/files/${subscribeKey}/channels/${encodeString(channel)}/files/${id}/${name}`; @@ -9798,17 +9774,6 @@ if (!this.parameters.channel) return "channel can't be empty"; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, channel, } = this.parameters; return `/v1/files/${subscribeKey}/channels/${encodeString(channel)}/files`; @@ -9847,11 +9812,6 @@ parse(response) { return __awaiter(this, void 0, void 0, function* () { const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); return { id: serviceResponse.data.id, name: serviceResponse.data.name, @@ -10602,14 +10562,11 @@ return 'Missing channels'; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return {}; + return _super.parse.call(this, response).then((_) => ({})); }); } get path() { @@ -10650,14 +10607,11 @@ return 'Missing channels'; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return {}; + return _super.parse.call(this, response).then((_) => ({})); }); } get path() { @@ -10696,13 +10650,7 @@ } parse(response) { return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return { channels: serviceResponse.payload.channels }; + return { channels: this.deserializeResponse(response).payload.channels }; }); } get path() { @@ -10737,14 +10685,11 @@ return 'Missing Channel Group'; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return {}; + return _super.parse.call(this, response).then((_) => ({})); }); } get path() { @@ -10778,13 +10723,7 @@ } parse(response) { return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return { groups: serviceResponse.payload.groups }; + return { groups: this.deserializeResponse(response).payload.groups }; }); } get path() { @@ -10951,11 +10890,6 @@ if (this.parameters.pushGateway === 'apns2' && !this.parameters.topic) return 'Missing APNS2 topic'; } - parse(_response) { - return __awaiter(this, void 0, void 0, function* () { - throw Error('Should be implemented in subclass.'); - }); - } get path() { const { keySet: { subscribeKey }, action, device, pushGateway, } = this.parameters; let path = pushGateway === 'apns2' @@ -10998,11 +10932,11 @@ return RequestOperation$1.PNRemovePushNotificationEnabledChannelsOperation; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - return {}; + return _super.parse.call(this, response).then((_) => ({})); }); } } @@ -11028,10 +10962,7 @@ } parse(response) { return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - return { channels: serviceResponse }; + return { channels: this.deserializeResponse(response) }; }); } } @@ -11056,11 +10987,11 @@ return RequestOperation$1.PNAddPushNotificationEnabledChannelsOperation; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - return {}; + return _super.parse.call(this, response).then((_) => ({})); }); } } @@ -11085,11 +11016,11 @@ return RequestOperation$1.PNRemoveAllPushNotificationsOperation; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - return {}; + return _super.parse.call(this, response).then((_) => ({})); }); } } @@ -11217,17 +11148,6 @@ operation() { return RequestOperation$1.PNGetAllChannelMetadataOperation; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { return `/v2/objects/${this.parameters.keySet.subscribeKey}/channels`; } @@ -11265,17 +11185,6 @@ if (!this.parameters.channel) return 'Channel cannot be empty'; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, channel, } = this.parameters; return `/v2/objects/${subscribeKey}/channels/${encodeString(channel)}`; @@ -11361,17 +11270,6 @@ if (!this.parameters.uuid) return "'uuid' cannot be empty"; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, uuid, } = this.parameters; return `/v2/objects/${subscribeKey}/uuids/${encodeString(uuid)}/channels`; @@ -11484,17 +11382,6 @@ if (!channels || channels.length === 0) return 'Channels cannot be empty'; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, uuid, } = this.parameters; return `/v2/objects/${subscribeKey}/uuids/${encodeString(uuid)}/channels`; @@ -11575,17 +11462,6 @@ operation() { return RequestOperation$1.PNGetAllUUIDMetadataOperation; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { return `/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`; } @@ -11636,17 +11512,6 @@ if (!this.parameters.channel) return 'Channel cannot be empty'; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, channel, } = this.parameters; return `/v2/objects/${subscribeKey}/channels/${encodeString(channel)}`; @@ -11704,17 +11569,6 @@ return undefined; } } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, channel, } = this.parameters; return `/v2/objects/${subscribeKey}/channels/${encodeString(channel)}`; @@ -11755,17 +11609,6 @@ if (!this.parameters.uuid) return "'uuid' cannot be empty"; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, uuid, } = this.parameters; return `/v2/objects/${subscribeKey}/uuids/${encodeString(uuid)}`; @@ -11848,17 +11691,6 @@ if (!this.parameters.channel) return 'Channel cannot be empty'; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, channel, } = this.parameters; return `/v2/objects/${subscribeKey}/channels/${encodeString(channel)}/uuids`; @@ -11968,17 +11800,6 @@ if (!uuids || uuids.length === 0) return 'UUIDs cannot be empty'; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, channel, } = this.parameters; return `/v2/objects/${subscribeKey}/channels/${encodeString(channel)}/uuids`; @@ -12061,17 +11882,6 @@ if (!this.parameters.uuid) return "'uuid' cannot be empty"; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, uuid, } = this.parameters; return `/v2/objects/${subscribeKey}/uuids/${encodeString(uuid)}`; @@ -12131,17 +11941,6 @@ return undefined; } } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, uuid, } = this.parameters; return `/v2/objects/${subscribeKey}/uuids/${encodeString(uuid)}`; @@ -12718,10 +12517,7 @@ } parse(response) { return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) - throw new PubNubError('Service response error, check status for details', createValidationError('Unable to deserialize service response')); - return { timetoken: serviceResponse[0] }; + return { timetoken: this.deserializeResponse(response)[0] }; }); } get path() { @@ -13242,12 +13038,15 @@ status.statusCode = response.status; // Handle special case when request completed but not fully processed by PubNub service. if (response.status !== 200 && response.status !== 204) { + const responseText = PubNubCore.decoder.decode(response.body); const contentType = response.headers['content-type']; if (contentType || contentType.indexOf('javascript') !== -1 || contentType.indexOf('json') !== -1) { - const json = JSON.parse(PubNubCore.decoder.decode(response.body)); + const json = JSON.parse(responseText); if (typeof json === 'object' && 'error' in json && json.error && typeof json.error === 'object') status.errorData = json.error; } + else + status.responseText = responseText; } return request.parse(response); }) @@ -13490,7 +13289,7 @@ */ if (this.subscriptionManager) { // Creating identifiable abort caller. - const callableAbort = () => request.abort(); + const callableAbort = () => request.abort('Cancel long-poll subscribe request'); callableAbort.identifier = request.requestIdentifier; this.subscriptionManager.abort = callableAbort; } @@ -13574,7 +13373,7 @@ { const request = new HandshakeSubscribeRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet, crypto: this._configuration.getCryptoModule(), getFileUrl: this.getFileUrl.bind(this) })); const abortUnsubscribe = parameters.abortSignal.subscribe((err) => { - request.abort(); + request.abort('Cancel subscribe handshake request'); }); /** * Allow subscription cancellation. @@ -13602,7 +13401,7 @@ { const request = new ReceiveMessagesSubscribeRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet, crypto: this._configuration.getCryptoModule(), getFileUrl: this.getFileUrl.bind(this) })); const abortUnsubscribe = parameters.abortSignal.subscribe((err) => { - request.abort(); + request.abort('Cancel long-poll subscribe request'); }); /** * Allow subscription cancellation. @@ -13610,8 +13409,8 @@ * **Note:** Had to be done after scheduling because transport provider return cancellation * controller only when schedule new request. */ - const handshakeResponse = this.sendRequest(request); - return handshakeResponse.then((response) => { + const receiveResponse = this.sendRequest(request); + return receiveResponse.then((response) => { abortUnsubscribe(); return response; }); diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index 9c4f63683..e0a374578 100644 --- a/dist/web/pubnub.min.js +++ b/dist/web/pubnub.min.js @@ -1,2 +1,2 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).PubNub=t()}(this,(function(){"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var s={exports:{}};!function(t){!function(e,s){var n=Math.pow(2,-24),r=Math.pow(2,32),i=Math.pow(2,53);var o={encode:function(e){var t,n=new ArrayBuffer(256),o=new DataView(n),a=0;function c(e){for(var s=n.byteLength,r=a+e;s>2,u=0;u>6),r.push(128|63&o)):o<55296?(r.push(224|o>>12),r.push(128|o>>6&63),r.push(128|63&o)):(o=(1023&o)<<10,o|=1023&t.charCodeAt(++n),o+=65536,r.push(240|o>>18),r.push(128|o>>12&63),r.push(128|o>>6&63),r.push(128|63&o))}return d(3,r.length),h(r);default:var p;if(Array.isArray(t))for(d(4,p=t.length),n=0;n>5!==e)throw"Invalid indefinite length element";return s}function f(e,t){for(var s=0;s>10),e.push(56320|1023&n))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof i&&(i=function(){return s});var m=function e(){var r,d,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),s=h(),r=32768&s,i=31744&s,o=1023&s;if(31744===i)i=261120;else if(0!==i)i+=114688;else if(0!==o)return o*n;return t.setUint32(0,r<<16|i<<13|o<<13),t.getFloat32(0)}();case 26:return c(o.getFloat32(a),4);case 27:return c(o.getFloat64(a),8)}if((d=g(v))<0&&(b<2||6=0;)S+=d,w.push(u(d));var k=new Uint8Array(S),E=0;for(r=0;r=0;)f(O,d);else f(O,d);return String.fromCharCode.apply(null,O);case 4:var C;if(d<0)for(C=[];!p();)C.push(e());else for(C=new Array(d),r=0;r{const s=new FileReader;s.addEventListener("load",(()=>{if(s.result instanceof ArrayBuffer)return e(s.result)})),s.addEventListener("error",(()=>t(s.error))),s.readAsArrayBuffer(this.data)}))}))}toString(){return i(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const s=new FileReader;s.addEventListener("load",(()=>{if("string"==typeof s.result)return e(s.result)})),s.addEventListener("error",(()=>{t(s.error)})),s.readAsBinaryString(this.data)}))}))}toStream(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in Node.js environments.")}))}toFile(){return i(this,void 0,void 0,(function*(){return this.data}))}toFileUri(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in React Native environments.")}))}toBlob(){return i(this,void 0,void 0,(function*(){return this.data}))}}a.supportsBlob="undefined"!=typeof Blob,a.supportsFile="undefined"!=typeof File,a.supportsBuffer=!1,a.supportsStream=!1,a.supportsString=!0,a.supportsArrayBuffer=!0,a.supportsEncryptFile=!0,a.supportsFileUri=!1;function c(e){const t=e.replace(/==?$/,""),s=Math.floor(t.length/4*3),n=new ArrayBuffer(s),r=new Uint8Array(n);let i=0;function o(){const e=t.charAt(i++),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e);if(-1===s)throw new Error(`Illegal character at ${i}: ${t.charAt(i-1)}`);return s}for(let e=0;e>4,c=(15&s)<<4|n>>2,u=(3&n)<<6|i;r[e]=a,64!=n&&(r[e+1]=c),64!=i&&(r[e+2]=u)}return n}function u(e){let t="";const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=new Uint8Array(e),r=n.byteLength,i=r%3,o=r-i;let a,c,u,l,h;for(let e=0;e>18,c=(258048&h)>>12,u=(4032&h)>>6,l=63&h,t+=s[a]+s[c]+s[u]+s[l];return 1==i?(h=n[o],a=(252&h)>>2,c=(3&h)<<4,t+=s[a]+s[c]+"=="):2==i&&(h=n[o]<<8|n[o+1],a=(64512&h)>>10,c=(1008&h)>>4,u=(15&h)<<2,t+=s[a]+s[c]+s[u]+"="),t}var l;!function(e){e.PNNetworkIssuesCategory="PNNetworkIssuesCategory",e.PNTimeoutCategory="PNTimeoutCategory",e.PNCancelledCategory="PNCancelledCategory",e.PNBadRequestCategory="PNBadRequestCategory",e.PNAccessDeniedCategory="PNAccessDeniedCategory",e.PNValidationErrorCategory="PNValidationErrorCategory",e.PNAcknowledgmentCategory="PNAcknowledgmentCategory",e.PNUnknownCategory="PNUnknownCategory",e.PNNetworkUpCategory="PNNetworkUpCategory",e.PNNetworkDownCategory="PNNetworkDownCategory",e.PNReconnectedCategory="PNReconnectedCategory",e.PNConnectedCategory="PNConnectedCategory",e.PNRequestMessageCountExceededCategory="PNRequestMessageCountExceededCategory",e.PNDisconnectedCategory="PNDisconnectedCategory",e.PNConnectionErrorCategory="PNConnectionErrorCategory",e.PNDisconnectedUnexpectedlyCategory="PNDisconnectedUnexpectedlyCategory"}(l||(l={}));var h=l;class d extends Error{constructor(e,t){super(e),this.status=t,this.name="PubNubError",this.message=e,Object.setPrototypeOf(this,new.target.prototype)}}function p(e,t){return s=Object.assign({message:e},{}),null!==(n=s.statusCode)&&void 0!==n||(s.statusCode=0),Object.assign(Object.assign({},s),{statusCode:s.statusCode,category:h.PNValidationErrorCategory,error:!0});var s,n}var g,y,f,m,b,v=v||function(e){var t={},s=t.lib={},n=function(){},r=s.Base={extend:function(e){n.prototype=this;var t=new n;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)}},i=s.WordArray=r.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||a).stringify(this)},concat:function(e){var t=this.words,s=e.words,n=this.sigBytes;if(e=e.sigBytes,this.clamp(),n%4)for(var r=0;r>>2]|=(s[r>>>2]>>>24-r%4*8&255)<<24-(n+r)%4*8;else if(65535>>2]=s[r>>>2];else t.push.apply(t,s);return this.sigBytes+=e,this},clamp:function(){var t=this.words,s=this.sigBytes;t[s>>>2]&=4294967295<<32-s%4*8,t.length=e.ceil(s/4)},clone:function(){var e=r.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var s=[],n=0;n>>2]>>>24-n%4*8&255;s.push((r>>>4).toString(16)),s.push((15&r).toString(16))}return s.join("")},parse:function(e){for(var t=e.length,s=[],n=0;n>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new i.init(s,t/2)}},c=o.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var s=[],n=0;n>>2]>>>24-n%4*8&255));return s.join("")},parse:function(e){for(var t=e.length,s=[],n=0;n>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new i.init(s,t)}},u=o.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)))}},l=s.BufferedBlockAlgorithm=r.extend({reset:function(){this._data=new i.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=u.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var s=this._data,n=s.words,r=s.sigBytes,o=this.blockSize,a=r/(4*o);if(t=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*o,r=e.min(4*t,r),t){for(var c=0;cu;){var l;e:{l=c;for(var h=e.sqrt(l),d=2;d<=h;d++)if(!(l%d)){l=!1;break e}l=!0}l&&(8>u&&(i[u]=a(e.pow(c,.5))),o[u]=a(e.pow(c,1/3)),u++),c++}var p=[];r=r.SHA256=n.extend({_doReset:function(){this._hash=new s.init(i.slice(0))},_doProcessBlock:function(e,t){for(var s=this._hash.words,n=s[0],r=s[1],i=s[2],a=s[3],c=s[4],u=s[5],l=s[6],h=s[7],d=0;64>d;d++){if(16>d)p[d]=0|e[t+d];else{var g=p[d-15],y=p[d-2];p[d]=((g<<25|g>>>7)^(g<<14|g>>>18)^g>>>3)+p[d-7]+((y<<15|y>>>17)^(y<<13|y>>>19)^y>>>10)+p[d-16]}g=h+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&u^~c&l)+o[d]+p[d],y=((n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22))+(n&r^n&i^r&i),h=l,l=u,u=c,c=a+g|0,a=i,i=r,r=n,n=g+y|0}s[0]=s[0]+n|0,s[1]=s[1]+r|0,s[2]=s[2]+i|0,s[3]=s[3]+a|0,s[4]=s[4]+c|0,s[5]=s[5]+u|0,s[6]=s[6]+l|0,s[7]=s[7]+h|0},_doFinalize:function(){var t=this._data,s=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;return s[r>>>5]|=128<<24-r%32,s[14+(r+64>>>9<<4)]=e.floor(n/4294967296),s[15+(r+64>>>9<<4)]=n,t.sigBytes=4*s.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=n._createHelper(r),t.HmacSHA256=n._createHmacHelper(r)}(Math),y=(g=v).enc.Utf8,g.algo.HMAC=g.lib.Base.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=y.parse(t));var s=e.blockSize,n=4*s;t.sigBytes>n&&(t=e.finalize(t)),t.clamp();for(var r=this._oKey=t.clone(),i=this._iKey=t.clone(),o=r.words,a=i.words,c=0;c>>2]>>>24-r%4*8&255)<<16|(t[r+1>>>2]>>>24-(r+1)%4*8&255)<<8|t[r+2>>>2]>>>24-(r+2)%4*8&255,o=0;4>o&&r+.75*o>>6*(3-o)&63));if(t=n.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var t=e.length,s=this._map;(n=s.charAt(64))&&-1!=(n=e.indexOf(n))&&(t=n);for(var n=[],r=0,i=0;i>>6-i%4*2;n[r>>>2]|=(o|a)<<24-r%4*8,r++}return m.create(n,r)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},function(e){function t(e,t,s,n,r,i,o){return((e=e+(t&s|~t&n)+r+o)<>>32-i)+t}function s(e,t,s,n,r,i,o){return((e=e+(t&n|s&~n)+r+o)<>>32-i)+t}function n(e,t,s,n,r,i,o){return((e=e+(t^s^n)+r+o)<>>32-i)+t}function r(e,t,s,n,r,i,o){return((e=e+(s^(t|~n))+r+o)<>>32-i)+t}for(var i=v,o=(c=i.lib).WordArray,a=c.Hasher,c=i.algo,u=[],l=0;64>l;l++)u[l]=4294967296*e.abs(e.sin(l+1))|0;c=c.MD5=a.extend({_doReset:function(){this._hash=new o.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,i){for(var o=0;16>o;o++){var a=e[c=i+o];e[c]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8)}o=this._hash.words;var c=e[i+0],l=(a=e[i+1],e[i+2]),h=e[i+3],d=e[i+4],p=e[i+5],g=e[i+6],y=e[i+7],f=e[i+8],m=e[i+9],b=e[i+10],v=e[i+11],w=e[i+12],S=e[i+13],k=e[i+14],E=e[i+15],O=t(O=o[0],P=o[1],N=o[2],C=o[3],c,7,u[0]),C=t(C,O,P,N,a,12,u[1]),N=t(N,C,O,P,l,17,u[2]),P=t(P,N,C,O,h,22,u[3]);O=t(O,P,N,C,d,7,u[4]),C=t(C,O,P,N,p,12,u[5]),N=t(N,C,O,P,g,17,u[6]),P=t(P,N,C,O,y,22,u[7]),O=t(O,P,N,C,f,7,u[8]),C=t(C,O,P,N,m,12,u[9]),N=t(N,C,O,P,b,17,u[10]),P=t(P,N,C,O,v,22,u[11]),O=t(O,P,N,C,w,7,u[12]),C=t(C,O,P,N,S,12,u[13]),N=t(N,C,O,P,k,17,u[14]),O=s(O,P=t(P,N,C,O,E,22,u[15]),N,C,a,5,u[16]),C=s(C,O,P,N,g,9,u[17]),N=s(N,C,O,P,v,14,u[18]),P=s(P,N,C,O,c,20,u[19]),O=s(O,P,N,C,p,5,u[20]),C=s(C,O,P,N,b,9,u[21]),N=s(N,C,O,P,E,14,u[22]),P=s(P,N,C,O,d,20,u[23]),O=s(O,P,N,C,m,5,u[24]),C=s(C,O,P,N,k,9,u[25]),N=s(N,C,O,P,h,14,u[26]),P=s(P,N,C,O,f,20,u[27]),O=s(O,P,N,C,S,5,u[28]),C=s(C,O,P,N,l,9,u[29]),N=s(N,C,O,P,y,14,u[30]),O=n(O,P=s(P,N,C,O,w,20,u[31]),N,C,p,4,u[32]),C=n(C,O,P,N,f,11,u[33]),N=n(N,C,O,P,v,16,u[34]),P=n(P,N,C,O,k,23,u[35]),O=n(O,P,N,C,a,4,u[36]),C=n(C,O,P,N,d,11,u[37]),N=n(N,C,O,P,y,16,u[38]),P=n(P,N,C,O,b,23,u[39]),O=n(O,P,N,C,S,4,u[40]),C=n(C,O,P,N,c,11,u[41]),N=n(N,C,O,P,h,16,u[42]),P=n(P,N,C,O,g,23,u[43]),O=n(O,P,N,C,m,4,u[44]),C=n(C,O,P,N,w,11,u[45]),N=n(N,C,O,P,E,16,u[46]),O=r(O,P=n(P,N,C,O,l,23,u[47]),N,C,c,6,u[48]),C=r(C,O,P,N,y,10,u[49]),N=r(N,C,O,P,k,15,u[50]),P=r(P,N,C,O,p,21,u[51]),O=r(O,P,N,C,w,6,u[52]),C=r(C,O,P,N,h,10,u[53]),N=r(N,C,O,P,b,15,u[54]),P=r(P,N,C,O,a,21,u[55]),O=r(O,P,N,C,f,6,u[56]),C=r(C,O,P,N,E,10,u[57]),N=r(N,C,O,P,g,15,u[58]),P=r(P,N,C,O,S,21,u[59]),O=r(O,P,N,C,d,6,u[60]),C=r(C,O,P,N,v,10,u[61]),N=r(N,C,O,P,l,15,u[62]),P=r(P,N,C,O,m,21,u[63]);o[0]=o[0]+O|0,o[1]=o[1]+P|0,o[2]=o[2]+N|0,o[3]=o[3]+C|0},_doFinalize:function(){var t=this._data,s=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;s[r>>>5]|=128<<24-r%32;var i=e.floor(n/4294967296);for(s[15+(r+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),s[14+(r+64>>>9<<4)]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),t.sigBytes=4*(s.length+1),this._process(),s=(t=this._hash).words,n=0;4>n;n++)r=s[n],s[n]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8);return t},clone:function(){var e=a.clone.call(this);return e._hash=this._hash.clone(),e}}),i.MD5=a._createHelper(c),i.HmacMD5=a._createHmacHelper(c)}(Math),function(){var e,t=v,s=(e=t.lib).Base,n=e.WordArray,r=(e=t.algo).EvpKDF=s.extend({cfg:s.extend({keySize:4,hasher:e.MD5,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var s=(a=this.cfg).hasher.create(),r=n.create(),i=r.words,o=a.keySize,a=a.iterations;i.length>>2]}},e.BlockCipher=o.extend({cfg:o.cfg.extend({mode:a,padding:u}),reset:function(){o.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var s=t.createEncryptor;else s=t.createDecryptor,this._minBufferSize=1;this._mode=s.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 l=e.CipherParams=t.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),h=(a=(d.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?s.create([1398893684,1701076831]).concat(e).concat(t):t).toString(r)},parse:function(e){var t=(e=r.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var n=s.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return l.create({ciphertext:e,salt:n})}},e.SerializableCipher=t.extend({cfg:t.extend({format:a}),encrypt:function(e,t,s,n){n=this.cfg.extend(n);var r=e.createEncryptor(s,n);return t=r.finalize(t),r=r.cfg,l.create({ciphertext:t,key:s,iv:r.iv,algorithm:e,mode:r.mode,padding:r.padding,blockSize:e.blockSize,formatter:n.format})},decrypt:function(e,t,s,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),e.createDecryptor(s,n).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),d=(d.kdf={}).OpenSSL={execute:function(e,t,n,r){return r||(r=s.random(8)),e=i.create({keySize:t+n}).compute(e,r),n=s.create(e.words.slice(t),4*n),e.sigBytes=4*t,l.create({key:e,iv:n,salt:r})}},p=e.PasswordBasedCipher=h.extend({cfg:h.cfg.extend({kdf:d}),encrypt:function(e,t,s,n){return s=(n=this.cfg.extend(n)).kdf.execute(s,e.keySize,e.ivSize),n.iv=s.iv,(e=h.encrypt.call(this,e,t,s.key,n)).mixIn(s),e},decrypt:function(e,t,s,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),s=n.kdf.execute(s,e.keySize,e.ivSize,t.salt),n.iv=s.iv,h.decrypt.call(this,e,t,s.key,n)}})}(),function(){for(var e=v,t=e.lib.BlockCipher,s=e.algo,n=[],r=[],i=[],o=[],a=[],c=[],u=[],l=[],h=[],d=[],p=[],g=0;256>g;g++)p[g]=128>g?g<<1:g<<1^283;var y=0,f=0;for(g=0;256>g;g++){var m=(m=f^f<<1^f<<2^f<<3^f<<4)>>>8^255&m^99;n[y]=m,r[m]=y;var b=p[y],w=p[b],S=p[w],k=257*p[m]^16843008*m;i[y]=k<<24|k>>>8,o[y]=k<<16|k>>>16,a[y]=k<<8|k>>>24,c[y]=k,k=16843009*S^65537*w^257*b^16843008*y,u[m]=k<<24|k>>>8,l[m]=k<<16|k>>>16,h[m]=k<<8|k>>>24,d[m]=k,y?(y=b^p[p[p[S^b]]],f^=p[p[f]]):y=f=1}var E=[0,1,2,4,8,16,32,64,128,27,54];s=s.AES=t.extend({_doReset:function(){for(var e=(s=this._key).words,t=s.sigBytes/4,s=4*((this._nRounds=t+6)+1),r=this._keySchedule=[],i=0;i>>24]<<24|n[o>>>16&255]<<16|n[o>>>8&255]<<8|n[255&o]):(o=n[(o=o<<8|o>>>24)>>>24]<<24|n[o>>>16&255]<<16|n[o>>>8&255]<<8|n[255&o],o^=E[i/t|0]<<24),r[i]=r[i-t]^o}for(e=this._invKeySchedule=[],t=0;tt||4>=i?o:u[n[o>>>24]]^l[n[o>>>16&255]]^h[n[o>>>8&255]]^d[n[255&o]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,i,o,a,c,n)},decryptBlock:function(e,t){var s=e[t+1];e[t+1]=e[t+3],e[t+3]=s,this._doCryptBlock(e,t,this._invKeySchedule,u,l,h,d,r),s=e[t+1],e[t+1]=e[t+3],e[t+3]=s},_doCryptBlock:function(e,t,s,n,r,i,o,a){for(var c=this._nRounds,u=e[t]^s[0],l=e[t+1]^s[1],h=e[t+2]^s[2],d=e[t+3]^s[3],p=4,g=1;g>>24]^r[l>>>16&255]^i[h>>>8&255]^o[255&d]^s[p++],f=n[l>>>24]^r[h>>>16&255]^i[d>>>8&255]^o[255&u]^s[p++],m=n[h>>>24]^r[d>>>16&255]^i[u>>>8&255]^o[255&l]^s[p++];d=n[d>>>24]^r[u>>>16&255]^i[l>>>8&255]^o[255&h]^s[p++],u=y,l=f,h=m}y=(a[u>>>24]<<24|a[l>>>16&255]<<16|a[h>>>8&255]<<8|a[255&d])^s[p++],f=(a[l>>>24]<<24|a[h>>>16&255]<<16|a[d>>>8&255]<<8|a[255&u])^s[p++],m=(a[h>>>24]<<24|a[d>>>16&255]<<16|a[u>>>8&255]<<8|a[255&l])^s[p++],d=(a[d>>>24]<<24|a[u>>>16&255]<<16|a[l>>>8&255]<<8|a[255&h])^s[p++],e[t]=y,e[t+1]=f,e[t+2]=m,e[t+3]=d},keySize:8});e.AES=t._createHelper(s)}(),v.mode.ECB=((b=v.lib.BlockCipherMode.extend()).Encryptor=b.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),b.Decryptor=b.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),b);var w=t(v);class S{constructor({cipherKey:e}){this.cipherKey=e,this.CryptoJS=w,this.encryptedKey=this.CryptoJS.SHA256(e)}encrypt(e){if(0===("string"==typeof e?e:S.decoder.decode(e)).length)throw new Error("encryption error. empty content");const t=this.getIv();return{metadata:t,data:c(this.CryptoJS.AES.encrypt(e,this.encryptedKey,{iv:this.bufferToWordArray(t),mode:this.CryptoJS.mode.CBC}).ciphertext.toString(this.CryptoJS.enc.Base64))}}encryptFileData(e){return i(this,void 0,void 0,(function*(){const t=yield this.getKey(),s=this.getIv();return{data:yield crypto.subtle.encrypt({name:this.algo,iv:s},t,e),metadata:s}}))}decrypt(e){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=this.bufferToWordArray(new Uint8ClampedArray(e.metadata)),s=this.bufferToWordArray(new Uint8ClampedArray(e.data));return S.encoder.encode(this.CryptoJS.AES.decrypt({ciphertext:s},this.encryptedKey,{iv:t,mode:this.CryptoJS.mode.CBC}).toString(this.CryptoJS.enc.Utf8)).buffer}decryptFileData(e){return i(this,void 0,void 0,(function*(){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=yield this.getKey();return crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)}))}get identifier(){return"ACRH"}get algo(){return"AES-CBC"}getIv(){return crypto.getRandomValues(new Uint8Array(S.BLOCK_SIZE))}getKey(){return i(this,void 0,void 0,(function*(){const e=S.encoder.encode(this.cipherKey),t=yield crypto.subtle.digest("SHA-256",e.buffer);return crypto.subtle.importKey("raw",t,this.algo,!0,["encrypt","decrypt"])}))}bufferToWordArray(e){const t=[];let s;for(s=0;se.toString(16).padStart(2,"0"))).join(""),n=O.encoder.encode(s.slice(0,32)).buffer;return crypto.subtle.importKey("raw",n,"AES-CBC",!0,["encrypt","decrypt"])}))}concatArrayBuffer(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(new Uint8Array(e),0),s.set(new Uint8Array(t),e.byteLength),s.buffer}}O.IV_LENGTH=16,O.encoder=new TextEncoder,O.decoder=new TextDecoder;class C{constructor(e){this.config=e,this.cryptor=new E(Object.assign({},e)),this.fileCryptor=new O}encrypt(e){const t="string"==typeof e?e:C.decoder.decode(e);return{data:this.cryptor.encrypt(t),metadata:null}}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.encryptFile(null===(s=this.config)||void 0===s?void 0:s.cipherKey,e,t)}))}decrypt(e){const t="string"==typeof e.data?e.data:u(e.data);return this.cryptor.decrypt(t)}decryptFile(e,t){return i(this,void 0,void 0,(function*(){if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.decryptFile(this.config.cipherKey,e,t)}))}get identifier(){return""}}C.encoder=new TextEncoder,C.decoder=new TextDecoder;class N extends o{static legacyCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new N({default:new C(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t})),cryptors:[new S({cipherKey:e.cipherKey})]})}static aesCbcCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new N({default:new S({cipherKey:e.cipherKey}),cryptors:[new C(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t}))]})}static withDefaultCryptor(e){return new this({default:e})}encrypt(e){const t=e instanceof ArrayBuffer&&this.defaultCryptor.identifier===N.LEGACY_IDENTIFIER?this.defaultCryptor.encrypt(N.decoder.decode(e)):this.defaultCryptor.encrypt(e);if(!t.metadata)return t.data;if("string"==typeof t.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");const s=this.getHeaderData(t);return this.concatArrayBuffer(s,t.data)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){if(this.defaultCryptor.identifier===P.LEGACY_IDENTIFIER)return this.defaultCryptor.encryptFile(e,t);const s=yield this.getFileData(e),n=yield this.defaultCryptor.encryptFileData(s);if("string"==typeof n.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");return t.create({name:e.name,mimeType:"application/octet-stream",data:this.concatArrayBuffer(this.getHeaderData(n),n.data)})}))}decrypt(e){const t="string"==typeof e?c(e):e,s=P.tryParse(t),n=this.getCryptor(s),r=s.length>0?t.slice(s.length-s.metadataLength,s.length):null;if(t.slice(s.length).byteLength<=0)throw new Error("Decryption error: empty content");return n.decrypt({data:t.slice(s.length),metadata:r})}decryptFile(e,t){return i(this,void 0,void 0,(function*(){const s=yield e.data.arrayBuffer(),n=P.tryParse(s),r=this.getCryptor(n);if((null==r?void 0:r.identifier)===P.LEGACY_IDENTIFIER)return r.decryptFile(e,t);const i=(yield this.getFileData(s)).slice(n.length-n.metadataLength,n.length);return t.create({name:e.name,data:yield this.defaultCryptor.decryptFileData({data:s.slice(n.length),metadata:i})})}))}getCryptorFromId(e){const t=this.getAllCryptors().find((t=>e===t.identifier));if(t)return t;throw Error("Unknown cryptor error")}getCryptor(e){if("string"==typeof e){const t=this.getAllCryptors().find((t=>t.identifier===e));if(t)return t;throw new Error("Unknown cryptor error")}if(e instanceof M)return this.getCryptorFromId(e.identifier)}getHeaderData(e){if(!e.metadata)return;const t=P.from(this.defaultCryptor.identifier,e.metadata),s=new Uint8Array(t.length);let n=0;return s.set(t.data,n),n+=t.length-e.metadata.byteLength,s.set(new Uint8Array(e.metadata),n),s.buffer}concatArrayBuffer(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(new Uint8Array(e),0),s.set(new Uint8Array(t),e.byteLength),s.buffer}getFileData(e){return i(this,void 0,void 0,(function*(){if(e instanceof ArrayBuffer)return e;if(e instanceof a)return e.toArrayBuffer();throw new Error("Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob")}))}}N.LEGACY_IDENTIFIER="";class P{static from(e,t){if(e!==P.LEGACY_IDENTIFIER)return new M(e,t.byteLength)}static tryParse(e){const t=new Uint8Array(e);let s,n,r=null;if(t.byteLength>=4&&(s=t.slice(0,4),this.decoder.decode(s)!==P.SENTINEL))return N.LEGACY_IDENTIFIER;if(!(t.byteLength>=5))throw new Error("Decryption error: invalid header version");if(r=t[4],r>P.MAX_VERSION)throw new Error("Decryption error: Unknown cryptor error");let i=5+P.IDENTIFIER_LENGTH;if(!(t.byteLength>=i))throw new Error("Decryption error: invalid crypto identifier");n=t.slice(5,i);let o=null;if(!(t.byteLength>=i+1))throw new Error("Decryption error: invalid metadata length");return o=t[i],i+=1,255===o&&t.byteLength>=i+2&&(o=new Uint16Array(t.slice(i,i+2)).reduce(((e,t)=>(e<<8)+t),0)),new M(this.decoder.decode(n),o)}}P.SENTINEL="PNED",P.LEGACY_IDENTIFIER="",P.IDENTIFIER_LENGTH=4,P.VERSION=1,P.MAX_VERSION=1,P.decoder=new TextDecoder;class M{constructor(e,t){this._identifier=e,this._metadataLength=t}get identifier(){return this._identifier}set identifier(e){this._identifier=e}get metadataLength(){return this._metadataLength}set metadataLength(e){this._metadataLength=e}get version(){return P.VERSION}get length(){return P.SENTINEL.length+1+P.IDENTIFIER_LENGTH+(this.metadataLength<255?1:3)+this.metadataLength}get data(){let e=0;const t=new Uint8Array(this.length),s=new TextEncoder;t.set(s.encode(P.SENTINEL)),e+=P.SENTINEL.length,t[e]=this.version,e++,this.identifier&&t.set(s.encode(this.identifier),e);const n=this.metadataLength;return e+=P.IDENTIFIER_LENGTH,n<255?t[e]=n:t.set([255,n>>8,255&n],e),t}}M.IDENTIFIER_LENGTH=4,M.SENTINEL="PNED";class _ extends Error{static create(e,t){return e instanceof Error?_.createFromError(e):_.createFromServiceResponse(e,t)}static createFromError(e){let t=h.PNUnknownCategory,s="Unknown error",n="Error";if(!e)return new _(s,t,0);if(e instanceof _)return e;if(e instanceof Error&&(s=e.message,n=e.name),"AbortError"===n||-1!==s.indexOf("Aborted"))t=h.PNCancelledCategory,s="Request cancelled";else if(-1!==s.toLowerCase().indexOf("timeout"))t=h.PNTimeoutCategory,s="Request timeout";else if(-1!==s.toLowerCase().indexOf("network"))t=h.PNNetworkIssuesCategory,s="Network issues";else if("TypeError"===n)t=-1!==s.indexOf("Load failed")||-1!=s.indexOf("Failed to fetch")?h.PNNetworkIssuesCategory:h.PNBadRequestCategory;else if("FetchError"===n){const n=e.code;["ECONNREFUSED","ENETUNREACH","ENOTFOUND","ECONNRESET","EAI_AGAIN"].includes(n)&&(t=h.PNNetworkIssuesCategory),"ECONNREFUSED"===n?s="Connection refused":"ENETUNREACH"===n?s="Network not reachable":"ENOTFOUND"===n?s="Server not found":"ECONNRESET"===n?s="Connection reset by peer":"EAI_AGAIN"===n?s="Name resolution error":"ETIMEDOUT"===n?(t=h.PNTimeoutCategory,s="Request timeout"):s=`Unknown system error: ${e}`}else"Request timeout"===s&&(t=h.PNTimeoutCategory);return new _(s,t,0,e)}static createFromServiceResponse(e,t){let s,n=h.PNUnknownCategory,r="Unknown error",{status:i}=e;if(null!=t||(t=e.body),402===i?r="Not available for used key set. Contact support@pubnub.com":400===i?(n=h.PNBadRequestCategory,r="Bad request"):403===i&&(n=h.PNAccessDeniedCategory,r="Access denied"),t&&t.byteLength>0){const n=(new TextDecoder).decode(t);if(-1!==e.headers["content-type"].indexOf("text/javascript")||-1!==e.headers["content-type"].indexOf("application/json"))try{const e=JSON.parse(n);"object"!=typeof e||Array.isArray(e)||("error"in e&&(1===e.error||!0===e.error)&&"status"in e&&"number"==typeof e.status&&"message"in e&&"service"in e?(s=e,i=e.status):s=e,"error"in e&&e.error instanceof Error&&(s=e.error))}catch(e){s=n}else if(-1!==e.headers["content-type"].indexOf("xml")){const e=/(.*)<\/Message>/gi.exec(n);r=e?`Upload to bucket failed: ${e[1]}`:"Upload to bucket failed."}else s=n}return new _(r,n,i,s)}constructor(e,t,s,n){super(e),this.category=t,this.statusCode=s,this.errorData=n,this.name="PubNubAPIError"}toStatus(e){return{error:!0,category:this.category,operation:e,statusCode:this.statusCode,errorData:this.errorData}}toPubNubError(e,t){return new d(null!=t?t:this.message,this.toStatus(e))}}class A{constructor(e){this.configuration=e,this.subscriptionWorkerReady=!1,this.workerEventsQueue=[],this.callbacks=new Map,this.setupSubscriptionWorker()}makeSendable(e){if(!e.path.startsWith("/v2/subscribe")&&!e.path.endsWith("/heartbeat")&&!e.path.endsWith("/leave"))return this.configuration.transport.makeSendable(e);let t;const s={type:"send-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,request:e};return e.cancellable&&(t={abort:()=>{const t={type:"cancel-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,identifier:e.identifier};this.scheduleEventPost(t)}}),[new Promise(((t,n)=>{this.callbacks.set(e.identifier,{resolve:t,reject:n}),this.scheduleEventPost(s)})),t]}request(e){return e}scheduleEventPost(e,t=!1){const s=this.sharedSubscriptionWorker;s?s.port.postMessage(e):t?this.workerEventsQueue.splice(0,0,e):this.workerEventsQueue.push(e)}flushScheduledEvents(){const e=this.sharedSubscriptionWorker;if(!e||0===this.workerEventsQueue.length)return;const t=[];for(let e=0;e!t.includes(e))),this.workerEventsQueue.forEach((t=>e.port.postMessage(t))),this.workerEventsQueue=[]}get sharedSubscriptionWorker(){return this.subscriptionWorkerReady?this.subscriptionWorker:null}setupSubscriptionWorker(){"undefined"!=typeof SharedWorker&&(this.subscriptionWorker=new SharedWorker(this.configuration.workerUrl,`/pubnub-${this.configuration.sdkVersion}`),this.subscriptionWorker.port.start(),this.scheduleEventPost({type:"client-register",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,heartbeatInterval:this.configuration.heartbeatInterval,logVerbosity:this.configuration.logVerbosity,workerLogVerbosity:this.configuration.workerLogVerbosity},!0),this.subscriptionWorker.port.onmessage=e=>this.handleWorkerEvent(e))}handleWorkerEvent(e){const{data:t}=e;if("shared-worker-ping"===t.type||"shared-worker-connected"===t.type||"shared-worker-console-log"===t.type||"shared-worker-console-dir"===t.type||t.clientIdentifier===this.configuration.clientIdentifier)if("shared-worker-connected"===t.type)this.subscriptionWorkerReady=!0,this.flushScheduledEvents();else if("shared-worker-console-log"===t.type)console.log(`[SharedWorker] ${t.message}`);else if("shared-worker-console-dir"===t.type)t.message&&console.log(`[SharedWorker] ${t.message}`),console.dir(t.data,{depth:10});else if("shared-worker-ping"===t.type){const{logVerbosity:e,subscriptionKey:t,clientIdentifier:s}=this.configuration;this.scheduleEventPost({type:"client-pong",subscriptionKey:t,clientIdentifier:s,logVerbosity:e})}else if("request-progress-start"===t.type||"request-progress-end"===t.type)this.logRequestProgress(t);else if("request-process-success"===t.type||"request-process-error"===t.type){const{resolve:e,reject:s}=this.callbacks.get(t.identifier);if("request-process-success"===t.type)e({status:t.response.status,url:t.url,headers:t.response.headers,body:t.response.body});else{let e=h.PNUnknownCategory,n="Unknown error";if(t.error)"NETWORK_ISSUE"===t.error.type?e=h.PNNetworkIssuesCategory:"TIMEOUT"===t.error.type?e=h.PNTimeoutCategory:"ABORTED"===t.error.type&&(e=h.PNCancelledCategory),n=`${t.error.message} (${t.identifier})`;else if(t.response)return s(_.create({url:t.url,headers:t.response.headers,body:t.response.body,status:t.response.status},t.response.body));s(new _(n,e,0,new Error(n)))}}}logRequestProgress(e){var t,s;"request-progress-start"===e.type?(console.log("<<<<<"),console.log(`[${e.timestamp}] ${e.url}\n${JSON.stringify(null!==(t=e.query)&&void 0!==t?t:{})}`),console.log("-----")):(console.log(">>>>>>"),console.log(`[${e.timestamp} / ${e.duration}] ${e.url}\n${JSON.stringify(null!==(s=e.query)&&void 0!==s?s:{})}\n${e.response}`),console.log("-----"))}}function j(e){const t=e=>"object"==typeof e&&null!==e&&e.constructor===Object,s=e=>"number"==typeof e&&isFinite(e);if(!t(e))return e;const n={};return Object.keys(e).forEach((r=>{const i=(e=>"string"==typeof e||e instanceof String)(r);let o=r;const a=e[r];if(i&&r.indexOf(",")>=0){o=r.split(",").map(Number).reduce(((e,t)=>e+String.fromCharCode(t)),"")}else(s(r)||i&&!isNaN(Number(r)))&&(o=String.fromCharCode(s(r)?r:parseInt(r,10)));n[o]=t(a)?j(a):a})),n}const I=e=>{var t,s,n,r;return e.subscriptionWorkerUrl&&"undefined"==typeof SharedWorker&&(e.subscriptionWorkerUrl=null),Object.assign(Object.assign({},(e=>{var t,s,n,r,i,o,a,c,u,l,h,p,g,y,f;const m=Object.assign({},e);if(null!==(t=m.logVerbosity)&&void 0!==t||(m.logVerbosity=!1),null!==(s=m.ssl)&&void 0!==s||(m.ssl=!0),null!==(n=m.transactionalRequestTimeout)&&void 0!==n||(m.transactionalRequestTimeout=15),null!==(r=m.subscribeRequestTimeout)&&void 0!==r||(m.subscribeRequestTimeout=310),null!==(i=m.fileRequestTimeout)&&void 0!==i||(m.fileRequestTimeout=300),null!==(o=m.restore)&&void 0!==o||(m.restore=!1),null!==(a=m.useInstanceId)&&void 0!==a||(m.useInstanceId=!1),null!==(c=m.suppressLeaveEvents)&&void 0!==c||(m.suppressLeaveEvents=!1),null!==(u=m.requestMessageCountThreshold)&&void 0!==u||(m.requestMessageCountThreshold=100),null!==(l=m.autoNetworkDetection)&&void 0!==l||(m.autoNetworkDetection=!1),null!==(h=m.enableEventEngine)&&void 0!==h||(m.enableEventEngine=!1),null!==(p=m.maintainPresenceState)&&void 0!==p||(m.maintainPresenceState=!0),null!==(g=m.keepAlive)&&void 0!==g||(m.keepAlive=!1),m.userId&&m.uuid)throw new d("PubNub client configuration error: use only 'userId'");if(null!==(y=m.userId)&&void 0!==y||(m.userId=m.uuid),!m.userId)throw new d("PubNub client configuration error: 'userId' not set");if(0===(null===(f=m.userId)||void 0===f?void 0:f.trim().length))throw new d("PubNub client configuration error: 'userId' is empty");m.origin||(m.origin=Array.from({length:20},((e,t)=>`ps${t+1}.pndsn.com`)));const b={subscribeKey:m.subscribeKey,publishKey:m.publishKey,secretKey:m.secretKey};void 0!==m.presenceTimeout&&m.presenceTimeout<20&&(m.presenceTimeout=20,console.log("WARNING: Presence timeout is less than the minimum. Using minimum value: ",20)),void 0!==m.presenceTimeout?m.heartbeatInterval=m.presenceTimeout/2-1:m.presenceTimeout=300;let v=!1,w=!0,S=5,k=!1,E=100,O=!0;return void 0!==m.dedupeOnSubscribe&&"boolean"==typeof m.dedupeOnSubscribe&&(k=m.dedupeOnSubscribe),void 0!==m.maximumCacheSize&&"number"==typeof m.maximumCacheSize&&(E=m.maximumCacheSize),void 0!==m.useRequestId&&"boolean"==typeof m.useRequestId&&(O=m.useRequestId),void 0!==m.announceSuccessfulHeartbeats&&"boolean"==typeof m.announceSuccessfulHeartbeats&&(v=m.announceSuccessfulHeartbeats),void 0!==m.announceFailedHeartbeats&&"boolean"==typeof m.announceFailedHeartbeats&&(w=m.announceFailedHeartbeats),void 0!==m.fileUploadPublishRetryLimit&&"number"==typeof m.fileUploadPublishRetryLimit&&(S=m.fileUploadPublishRetryLimit),Object.assign(Object.assign({},m),{keySet:b,dedupeOnSubscribe:k,maximumCacheSize:E,useRequestId:O,announceSuccessfulHeartbeats:v,announceFailedHeartbeats:w,fileUploadPublishRetryLimit:S})})(e)),{listenToBrowserNetworkEvents:null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t,subscriptionWorkerUrl:e.subscriptionWorkerUrl,subscriptionWorkerLogVerbosity:null!==(s=e.subscriptionWorkerLogVerbosity)&&void 0!==s&&s,transport:null!==(n=e.transport)&&void 0!==n?n:"fetch",keepAlive:null===(r=e.keepAlive)||void 0===r||r})};var R={exports:{}}; -/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */!function(e,t){!function(e){var t="0.1.0",s={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 n(){var e,t,s="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(s+="-"),s+=(12===e?4:16===e?3&t|8:t).toString(16);return s}function r(e,t){var n=s[t||"all"];return n&&n.test(e)||!1}n.isUUID=r,n.VERSION=t,e.uuid=n,e.isUUID=r}(t),null!==e&&(e.exports=t.uuid)}(R,R.exports);var F=t(R.exports),T={createUUID:()=>F.uuid?F.uuid():F()};const U=(e,t)=>{var s,n,r;null===(s=e.retryConfiguration)||void 0===s||s.validate(),null!==(n=e.useRandomIVs)&&void 0!==n||(e.useRandomIVs=true),e.origin=x(null!==(r=e.ssl)&&void 0!==r&&r,e.origin);const i=e.cryptoModule;i&&delete e.cryptoModule;const o=Object.assign(Object.assign({},e),{_pnsdkSuffix:{},_instanceId:`pn-${T.createUUID()}`,_cryptoModule:void 0,_cipherKey:void 0,_setupCryptoModule:t,get instanceId(){if(this.useInstanceId)return this._instanceId},getInstanceId(){if(this.useInstanceId)return this._instanceId},getUserId(){return this.userId},setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this.userId=e},getAuthKey(){return this.authKey},setAuthKey(e){this.authKey=e},getFilterExpression(){return this.filterExpression},setFilterExpression(e){this.filterExpression=e},getCipherKey(){return this._cipherKey},setCipherKey(t){this._cipherKey=t,t||!this._cryptoModule?t&&this._setupCryptoModule&&(this._cryptoModule=this._setupCryptoModule({cipherKey:t,useRandomIVs:e.useRandomIVs,customEncrypt:this.getCustomEncrypt(),customDecrypt:this.getCustomDecrypt()})):this._cryptoModule=void 0},getCryptoModule(){return this._cryptoModule},getUseRandomIVs:()=>e.useRandomIVs,setPresenceTimeout(e){this.heartbeatInterval=e/2-1,this.presenceTimeout=e},getPresenceTimeout(){return this.presenceTimeout},getHeartbeatInterval(){return this.heartbeatInterval},setHeartbeatInterval(e){this.heartbeatInterval=e},getTransactionTimeout(){return this.transactionalRequestTimeout},getSubscribeTimeout(){return this.subscribeRequestTimeout},getFileTimeout(){return this.fileRequestTimeout},get PubNubFile(){return e.PubNubFile},get version(){return"8.8.1"},getVersion(){return this.version},_addPnsdkSuffix(e,t){this._pnsdkSuffix[e]=`${t}`},_getPnsdkSuffix(e){const t=Object.values(this._pnsdkSuffix).join(e);return t.length>0?e+t:""},getUUID(){return this.getUserId()},setUUID(e){this.setUserId(e)},getCustomEncrypt:()=>e.customEncrypt,getCustomDecrypt:()=>e.customDecrypt});return e.cipherKey?o.setCipherKey(e.cipherKey):i&&(o._cryptoModule=i),o},x=(e,t)=>{const s=e?"https://":"http://";return"string"==typeof t?`${s}${t}`:`${s}${t[Math.floor(Math.random()*t.length)]}`};class D{constructor(e){this.cbor=e}setToken(e){e&&e.length>0?this.token=e:this.token=void 0}getToken(){return this.token}parseToken(e){const t=this.cbor.decodeToken(e);if(void 0!==t){const e=t.res.uuid?Object.keys(t.res.uuid):[],s=Object.keys(t.res.chan),n=Object.keys(t.res.grp),r=t.pat.uuid?Object.keys(t.pat.uuid):[],i=Object.keys(t.pat.chan),o=Object.keys(t.pat.grp),a={version:t.v,timestamp:t.t,ttl:t.ttl,authorized_uuid:t.uuid,signature:t.sig},c=e.length>0,u=s.length>0,l=n.length>0;if(c||u||l){if(a.resources={},c){const s=a.resources.uuids={};e.forEach((e=>s[e]=this.extractPermissions(t.res.uuid[e])))}if(u){const e=a.resources.channels={};s.forEach((s=>e[s]=this.extractPermissions(t.res.chan[s])))}if(l){const e=a.resources.groups={};n.forEach((s=>e[s]=this.extractPermissions(t.res.grp[s])))}}const h=r.length>0,d=i.length>0,p=o.length>0;if(h||d||p){if(a.patterns={},h){const e=a.patterns.uuids={};r.forEach((s=>e[s]=this.extractPermissions(t.pat.uuid[s])))}if(d){const e=a.patterns.channels={};i.forEach((s=>e[s]=this.extractPermissions(t.pat.chan[s])))}if(p){const e=a.patterns.groups={};o.forEach((s=>e[s]=this.extractPermissions(t.pat.grp[s])))}}return t.meta&&Object.keys(t.meta).length>0&&(a.meta=t.meta),a}}extractPermissions(e){const t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128&~e||(t.join=!0),64&~e||(t.update=!0),32&~e||(t.get=!0),8&~e||(t.delete=!0),4&~e||(t.manage=!0),2&~e||(t.write=!0),1&~e||(t.read=!0),t}}var q;!function(e){e.GET="GET",e.POST="POST",e.PATCH="PATCH",e.DELETE="DELETE",e.LOCAL="LOCAL"}(q||(q={}));const G=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),K=(e,t)=>{const s=e.map((e=>G(e)));return s.length?s.join(","):null!=t?t:""},$=(e,t)=>{const s=Object.fromEntries(t.map((e=>[e,!1])));return e.filter((e=>!(t.includes(e)&&!s[e])||(s[e]=!0,!1)))},L=(e,t)=>[...e].filter((s=>t.includes(s)&&e.indexOf(s)===e.lastIndexOf(s)&&t.indexOf(s)===t.lastIndexOf(s)));class B{constructor(e,t,s){this.publishKey=e,this.secretKey=t,this.hasher=s}signature(e){const t=e.path.startsWith("/publish")?q.GET:e.method;let s=`${t}\n${this.publishKey}\n${e.path}\n${this.queryParameters(e.queryParameters)}\n`;if(t===q.POST||t===q.PATCH){const t=e.body;let n;t&&t instanceof ArrayBuffer?n=B.textDecoder.decode(t):t&&"object"!=typeof t&&(n=t),n&&(s+=n)}return`v2.${this.hasher(s,this.secretKey)}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}queryParameters(e){return Object.keys(e).sort().map((t=>{const s=e[t];return Array.isArray(s)?s.sort().map((e=>`${t}=${G(e)}`)).join("&"):`${t}=${G(s)}`})).join("&")}}B.textDecoder=new TextDecoder("utf-8");class H{constructor(e){this.configuration=e;const{clientConfiguration:{keySet:t},shaHMAC:s}=e;t.secretKey&&s&&(this.signatureGenerator=new B(t.publishKey,t.secretKey,s))}makeSendable(e){return this.configuration.transport.makeSendable(this.request(e))}request(e){var t;const{clientConfiguration:s}=this.configuration;return(e=this.configuration.transport.request(e)).queryParameters||(e.queryParameters={}),s.useInstanceId&&(e.queryParameters.instanceid=s.getInstanceId()),e.queryParameters.uuid||(e.queryParameters.uuid=s.userId),s.useRequestId&&(e.queryParameters.requestid=e.identifier),e.queryParameters.pnsdk=this.generatePNSDK(),null!==(t=e.origin)&&void 0!==t||(e.origin=s.origin),this.authenticateRequest(e),this.signRequest(e),e}authenticateRequest(e){var t;if(e.path.startsWith("/v2/auth/")||e.path.startsWith("/v3/pam/")||e.path.startsWith("/time"))return;const{clientConfiguration:s,tokenManager:n}=this.configuration,r=null!==(t=n&&n.getToken())&&void 0!==t?t:s.authKey;r&&(e.queryParameters.auth=r)}signRequest(e){this.signatureGenerator&&!e.path.startsWith("/time")&&(e.queryParameters.timestamp=String(Math.floor((new Date).getTime()/1e3)),e.queryParameters.signature=this.signatureGenerator.signature(e))}generatePNSDK(){const{clientConfiguration:e}=this.configuration;if(e.sdkName)return e.sdkName;let t=`PubNub-JS-${e.sdkFamily}`;e.partnerId&&(t+=`-${e.partnerId}`),t+=`/${e.getVersion()}`;const s=e._getPnsdkSuffix(" ");return s.length>0&&(t+=s),t}}class z{constructor(e="fetch",t=!1,s=!1){if(this.transport=e,this.keepAlive=t,this.logVerbosity=s,"fetch"!==e||window&&window.fetch||(this.transport="xhr"),"fetch"===this.transport&&(z.originalFetch=fetch.bind(window),this.isFetchMonkeyPatched())){if(z.originalFetch=z.getOriginalFetch(),!s)return;console.warn("[PubNub] Native Web Fetch API 'fetch' function monkey patched."),this.isFetchMonkeyPatched(z.originalFetch)?console.warn("[PubNub] Unable receive native Web Fetch API. There can be issues with subscribe long-poll cancellation"):console.info("[PubNub] Use native Web Fetch API 'fetch' implementation from iframe as APM workaround.")}}makeSendable(e){const t=new AbortController,s={abortController:t,abort:()=>!t.signal.aborted&&t.abort()};return[this.webTransportRequestFromTransportRequest(e).then((t=>{const n=(new Date).getTime();return this.logRequestProcessProgress(t,e.body),this.sendRequest(t,s).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>{const s=e[1].byteLength>0?e[1]:void 0,{status:r,headers:i}=e[0],o={};i.forEach(((e,t)=>o[t]=e.toLowerCase()));const a={status:r,url:t.url,headers:o,body:s};if(r>=400)throw _.create(a);return this.logRequestProcessProgress(t,void 0,(new Date).getTime()-n,s),a})).catch((e=>{throw _.create(e)}))})),s]}request(e){return e}sendRequest(e,t){return i(this,void 0,void 0,(function*(){return"fetch"===this.transport?this.sendFetchRequest(e,t):this.sendXHRRequest(e,t)}))}sendFetchRequest(e,t){return i(this,void 0,void 0,(function*(){let s;const n=new Promise(((n,r)=>{s=setTimeout((()=>{clearTimeout(s),r(new Error("Request timeout")),t.abort()}),1e3*e.timeout)})),r=new Request(e.url,{method:e.method,headers:e.headers,redirect:"follow",body:e.body});return Promise.race([z.originalFetch(r,{signal:t.abortController.signal,credentials:"omit",cache:"no-cache"}).then((e=>(s&&clearTimeout(s),e))),n])}))}sendXHRRequest(e,t){return i(this,void 0,void 0,(function*(){return new Promise(((s,n)=>{var r;const i=new XMLHttpRequest;i.open(e.method,e.url,!0),i.responseType="arraybuffer",i.timeout=1e3*e.timeout,t.abortController.signal.onabort=()=>{i.readyState!=XMLHttpRequest.DONE&&i.readyState!=XMLHttpRequest.UNSENT&&i.abort()},Object.entries(null!==(r=e.headers)&&void 0!==r?r:{}).forEach((([e,t])=>i.setRequestHeader(e,t))),i.onabort=()=>n(new Error("Aborted")),i.ontimeout=()=>n(new Error("Request timeout")),i.onerror=()=>n(new Error("Request timeout")),i.onload=()=>{const e=new Headers;i.getAllResponseHeaders().split("\r\n").forEach((t=>{const[s,n]=t.split(": ");s.length>1&&n.length>1&&e.append(s,n)})),s(new Response(i.response,{status:i.status,headers:e,statusText:i.statusText}))},i.send(e.body)}))}))}webTransportRequestFromTransportRequest(e){return i(this,void 0,void 0,(function*(){let t,s=e.path;if(e.formData&&e.formData.length>0){e.queryParameters={};const s=e.body,n=new FormData;for(const{key:t,value:s}of e.formData)n.append(t,s);try{const e=yield s.toArrayBuffer();n.append("file",new Blob([e],{type:"application/octet-stream"}),s.name)}catch(e){try{const e=yield s.toFileUri();n.append("file",e,s.name)}catch(e){}}t=n}else e.body&&("string"==typeof e.body||e.body instanceof ArrayBuffer)&&(t=e.body);var n;return e.queryParameters&&0!==Object.keys(e.queryParameters).length&&(s=`${s}?${n=e.queryParameters,Object.keys(n).map((e=>{const t=n[e];return Array.isArray(t)?t.map((t=>`${e}=${G(t)}`)).join("&"):`${e}=${G(t)}`})).join("&")}`),{url:`${e.origin}${s}`,method:e.method,headers:e.headers,timeout:e.timeout,body:t}}))}logRequestProcessProgress(e,t,s,n){if(!this.logVerbosity)return;const{protocol:r,host:i,pathname:o,search:a}=new URL(e.url),c=(new Date).toISOString();if(s){let e=`[${c} / ${s}]\n${r}//${i}${o}\n${a}`;n&&(e+=`\n\n${z.decoder.decode(n)}`),console.log(">>>>>>"),console.log(e),console.log("-----")}else{let e=`[${c}]\n${r}//${i}${o}\n${a}`;t&&("string"==typeof t||t instanceof ArrayBuffer)&&(e+="string"==typeof t?`\n\n${t}`:`\n\n${z.decoder.decode(t)}`),console.log("<<<<<"),console.log(e),console.log("-----")}}isFetchMonkeyPatched(e){return!(null!=e?e:fetch).toString().includes("[native code]")&&"fetch"!==fetch.name}static getOriginalFetch(){let e=document.querySelector('iframe[name="pubnub-context-unpatched-fetch"]');return e||(e=document.createElement("iframe"),e.style.display="none",e.name="pubnub-context-unpatched-fetch",e.src="about:blank",document.body.appendChild(e)),e.contentWindow?e.contentWindow.fetch.bind(e.contentWindow):fetch}}z.decoder=new TextDecoder;class V{constructor(){this.listeners=[]}addListener(e){this.listeners.includes(e)||this.listeners.push(e)}removeListener(e){this.listeners=this.listeners.filter((t=>t!==e))}removeAllListeners(){this.listeners=[]}announceStatus(e){this.listeners.forEach((t=>{t.status&&t.status(e)}))}announcePresence(e){this.listeners.forEach((t=>{t.presence&&t.presence(e)}))}announceMessage(e){this.listeners.forEach((t=>{t.message&&t.message(e)}))}announceSignal(e){this.listeners.forEach((t=>{t.signal&&t.signal(e)}))}announceMessageAction(e){this.listeners.forEach((t=>{t.messageAction&&t.messageAction(e)}))}announceFile(e){this.listeners.forEach((t=>{t.file&&t.file(e)}))}announceObjects(e){this.listeners.forEach((t=>{t.objects&&t.objects(e)}))}announceNetworkUp(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkUpCategory})}))}announceNetworkDown(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkDownCategory})}))}announceUser(e){this.listeners.forEach((t=>{t.user&&t.user(e)}))}announceSpace(e){this.listeners.forEach((t=>{t.space&&t.space(e)}))}announceMembership(e){this.listeners.forEach((t=>{t.membership&&t.membership(e)}))}}class W{constructor(e){this.time=e}onReconnect(e){this.callback=e}startPolling(){this.timeTimer=setInterval((()=>this.callTime()),3e3)}stopPolling(){this.timeTimer&&clearInterval(this.timeTimer),this.timeTimer=null}callTime(){this.time((e=>{e.error||(this.stopPolling(),this.callback&&this.callback())}))}}class J{constructor({maximumCacheSize:e}){this.maximumCacheSize=e,this.hashHistory=[]}getKey(e){var t;return`${e.timetoken}-${this.hashCode(JSON.stringify(null!==(t=e.message)&&void 0!==t?t:"")).toString()}`}isDuplicate(e){return this.hashHistory.includes(this.getKey(e))}addEntry(e){this.hashHistory.length>=this.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}clearHistory(){this.hashHistory=[]}hashCode(e){let t=0;if(0===e.length)return t;for(let s=0;s{this.pendingChannelSubscriptions.add(e),this.channels[e]={},r&&(this.presenceChannels[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannels[e]={})})),null==s||s.forEach((e=>{this.pendingChannelGroupSubscriptions.add(e),this.channelGroups[e]={},r&&(this.presenceChannelGroups[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannelGroups[e]={})})),this.subscriptionStatusAnnounced=!1,this.reconnect()}unsubscribe(e,t){let{channels:s,channelGroups:n}=e;const i=new Set,o=new Set;null==s||s.forEach((e=>{e in this.channels&&(delete this.channels[e],o.add(e),e in this.heartbeatChannels&&delete this.heartbeatChannels[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannels&&(delete this.presenceChannels[e],o.add(e))})),null==n||n.forEach((e=>{e in this.channelGroups&&(delete this.channelGroups[e],i.add(e),e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannelGroups&&(delete this.presenceChannelGroups[e],i.add(e))})),0===o.size&&0===i.size||(!1!==this.configuration.suppressLeaveEvents||t||(n=Array.from(i),s=Array.from(o),this.leaveCall({channels:s,channelGroups:n},(e=>{const{error:t}=e,i=r(e,["error"]);let o;t&&(e.errorData&&"object"==typeof e.errorData&&"message"in e.errorData&&"string"==typeof e.errorData.message?o=e.errorData.message:"message"in e&&"string"==typeof e.message&&(o=e.message)),this.listenerManager.announceStatus(Object.assign(Object.assign({},i),{error:null!=o&&o,affectedChannels:s,affectedChannelGroups:n,currentTimetoken:this.currentTimetoken,lastTimetoken:this.lastTimetoken}))}))),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(!0))}unsubscribeAll(e){this.unsubscribe({channels:this.subscribedChannels,channelGroups:this.subscribedChannelGroups},e)}startSubscribeLoop(){this.stopSubscribeLoop();const e=[...Object.keys(this.channelGroups)],t=[...Object.keys(this.channels)];Object.keys(this.presenceChannelGroups).forEach((t=>e.push(`${t}-pnpres`))),Object.keys(this.presenceChannels).forEach((e=>t.push(`${e}-pnpres`))),0===t.length&&0===e.length||this.subscribeCall({channels:t,channelGroups:e,state:this.presenceState,heartbeat:this.configuration.getPresenceTimeout(),timetoken:this.currentTimetoken,region:null!==this.region?this.region:void 0,filterExpression:this.configuration.filterExpression},((e,t)=>{this.processSubscribeResponse(e,t)}))}stopSubscribeLoop(){this._subscribeAbort&&(this._subscribeAbort(),this._subscribeAbort=null)}processSubscribeResponse(e,t){if(e.error){if("object"==typeof e.errorData&&"name"in e.errorData&&"AbortError"===e.errorData.name||e.category===h.PNCancelledCategory)return;return void(e.category===h.PNTimeoutCategory?this.startSubscribeLoop():e.category===h.PNNetworkIssuesCategory?(this.disconnect(),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.listenerManager.announceNetworkDown()),this.reconnectionManager.onReconnect((()=>{this.configuration.autoNetworkDetection&&!this.isOnline&&(this.isOnline=!0,this.listenerManager.announceNetworkUp()),this.reconnect(),this.subscriptionStatusAnnounced=!0;const t={category:h.PNReconnectedCategory,operation:e.operation,lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.listenerManager.announceStatus(t)})),this.reconnectionManager.startPolling(),this.listenerManager.announceStatus(e)):e.category===h.PNBadRequestCategory?(this.stopHeartbeatTimer(),this.listenerManager.announceStatus(e)):this.listenerManager.announceStatus(e))}if(this.storedTimetoken?(this.currentTimetoken=this.storedTimetoken,this.storedTimetoken=null):(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=t.cursor.timetoken),!this.subscriptionStatusAnnounced){const t={category:h.PNConnectedCategory,operation:e.operation,affectedChannels:Array.from(this.pendingChannelSubscriptions),subscribedChannels:this.subscribedChannels,affectedChannelGroups:Array.from(this.pendingChannelGroupSubscriptions),lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.subscriptionStatusAnnounced=!0,this.listenerManager.announceStatus(t),this.pendingChannelGroupSubscriptions.clear(),this.pendingChannelSubscriptions.clear()}const{messages:s}=t,{requestMessageCountThreshold:n,dedupeOnSubscribe:r}=this.configuration;n&&s.length>=n&&this.listenerManager.announceStatus({category:h.PNRequestMessageCountExceededCategory,operation:e.operation});try{s.forEach((e=>{if(r&&"message"in e.data&&"timetoken"in e.data){if(this.dedupingManager.isDuplicate(e.data))return;this.dedupingManager.addEntry(e.data)}this.eventEmitter.emitEvent(e)}))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}this.region=t.cursor.region,this.startSubscribeLoop()}setState(e){const{state:t,channels:s,channelGroups:n}=e;null==s||s.forEach((e=>e in this.channels&&(this.presenceState[e]=t))),null==n||n.forEach((e=>e in this.channelGroups&&(this.presenceState[e]=t)))}changePresence(e){const{connected:t,channels:s,channelGroups:n}=e;t?(null==s||s.forEach((e=>this.heartbeatChannels[e]={})),null==n||n.forEach((e=>this.heartbeatChannelGroups[e]={}))):(null==s||s.forEach((e=>{e in this.heartbeatChannels&&delete this.heartbeatChannels[e]})),null==n||n.forEach((e=>{e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]})),!1===this.configuration.suppressLeaveEvents&&this.leaveCall({channels:s,channelGroups:n},(e=>this.listenerManager.announceStatus(e)))),this.reconnect()}startHeartbeatTimer(){this.stopHeartbeatTimer();const e=this.configuration.getHeartbeatInterval();e&&0!==e&&(this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>this.sendHeartbeat()),1e3*e))}stopHeartbeatTimer(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}sendHeartbeat(){const e=Object.keys(this.heartbeatChannelGroups),t=Object.keys(this.heartbeatChannels);0===t.length&&0===e.length||this.heartbeatCall({channels:t,channelGroups:e,heartbeat:this.configuration.getPresenceTimeout(),state:this.presenceState},(e=>{e.error&&this.configuration.announceFailedHeartbeats&&this.listenerManager.announceStatus(e),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.disconnect(),this.listenerManager.announceNetworkDown(),this.reconnect()),!e.error&&this.configuration.announceSuccessfulHeartbeats&&this.listenerManager.announceStatus(e)}))}}class Q{constructor(e,t,s){this._payload=e,this.setDefaultPayloadStructure(),this.title=t,this.body=s}get payload(){return this._payload}set title(e){this._title=e}set subtitle(e){this._subtitle=e}set body(e){this._body=e}set badge(e){this._badge=e}set sound(e){this._sound=e}setDefaultPayloadStructure(){}toObject(){return{}}}class Y extends Q{constructor(){super(...arguments),this._apnsPushType="apns",this._isSilent=!1}get payload(){return this._payload}set configurations(e){e&&e.length&&(this._configurations=e)}get notification(){return this.payload.aps}get title(){return this._title}set title(e){e&&e.length&&(this.payload.aps.alert.title=e,this._title=e)}get subtitle(){return this._subtitle}set subtitle(e){e&&e.length&&(this.payload.aps.alert.subtitle=e,this._subtitle=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.aps.alert.body=e,this._body=e)}get badge(){return this._badge}set badge(e){null!=e&&(this.payload.aps.badge=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.aps.sound=e,this._sound=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.aps={alert:{}}}toObject(){const e=Object.assign({},this.payload),{aps:t}=e;let{alert:s}=t;if(this._isSilent&&(t["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");const t=[];this._configurations.forEach((e=>{t.push(this.objectFromAPNS2Configuration(e))})),t.length&&(e.pn_push=t)}return s&&Object.keys(s).length||delete t.alert,this._isSilent&&(delete t.alert,delete t.badge,delete t.sound,s={}),this._isSilent||s&&Object.keys(s).length?e:null}objectFromAPNS2Configuration(e){if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");const{collapseId:t,expirationDate:s}=e,n={auth_method:"token",targets:e.targets.map((e=>this.objectFromAPNSTarget(e))),version:"v2"};return t&&t.length&&(n.collapse_id=t),s&&(n.expiration=s.toISOString()),n}objectFromAPNSTarget(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");const{topic:t,environment:s="development",excludedDevices:n=[]}=e,r={topic:t,environment:s};return n.length&&(r.excluded_devices=n),r}}class Z extends Q{get payload(){return this._payload}get notification(){return this.payload.notification}get data(){return this.payload.data}get title(){return this._title}set title(e){e&&e.length&&(this.payload.notification.title=e,this._title=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.notification.body=e,this._body=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.notification.sound=e,this._sound=e)}get icon(){return this._icon}set icon(e){e&&e.length&&(this.payload.notification.icon=e,this._icon=e)}get tag(){return this._tag}set tag(e){e&&e.length&&(this.payload.notification.tag=e,this._tag=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.notification={},this.payload.data={}}toObject(){let e=Object.assign({},this.payload.data),t=null;const s={};if(Object.keys(this.payload).length>2){const t=r(this.payload,["notification","data"]);e=Object.assign(Object.assign({},e),t)}return this._isSilent?e.notification=this.payload.notification:t=this.payload.notification,Object.keys(e).length&&(s.data=e),t&&Object.keys(t).length&&(s.notification=t),Object.keys(s).length?s:null}}class ee{constructor(e,t){this._payload={apns:{},fcm:{}},this._title=e,this._body=t,this.apns=new Y(this._payload.apns,e,t),this.fcm=new Z(this._payload.fcm,e,t)}set debugging(e){this._debugging=e}get title(){return this._title}get subtitle(){return this._subtitle}set subtitle(e){this._subtitle=e,this.apns.subtitle=e,this.fcm.subtitle=e}get body(){return this._body}get badge(){return this._badge}set badge(e){this._badge=e,this.apns.badge=e,this.fcm.badge=e}get sound(){return this._sound}set sound(e){this._sound=e,this.apns.sound=e,this.fcm.sound=e}buildPayload(e){const t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";const s=this.apns.toObject();s&&Object.keys(s).length&&(t.pn_apns=s)}if(e.includes("fcm")){const e=this.fcm.toObject();e&&Object.keys(e).length&&(t.pn_gcm=e)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t}}class te{constructor(e){this.params=e,this.requestIdentifier=T.createUUID(),this._cancellationController=null}get cancellationController(){return this._cancellationController}set cancellationController(e){this._cancellationController=e}abort(){this&&this.cancellationController&&this.cancellationController.abort()}operation(){throw Error("Should be implemented by subclass.")}validate(){}parse(e){return i(this,void 0,void 0,(function*(){throw Error("Should be implemented by subclass.")}))}request(){var e,t,s,n;const r={method:null!==(t=null===(e=this.params)||void 0===e?void 0:e.method)&&void 0!==t?t:q.GET,path:this.path,queryParameters:this.queryParameters,cancellable:null!==(n=null===(s=this.params)||void 0===s?void 0:s.cancellable)&&void 0!==n&&n,timeout:10,identifier:this.requestIdentifier},i=this.headers;if(i&&(r.headers=i),r.method===q.POST||r.method===q.PATCH){const[e,t]=[this.body,this.formData];t&&(r.formData=t),e&&(r.body=e)}return r}get headers(){}get path(){throw Error("`path` getter should be implemented by subclass.")}get queryParameters(){return{}}get formData(){}get body(){}deserializeResponse(e){const t=e.headers["content-type"];if(!t||-1===t.indexOf("javascript")&&-1===t.indexOf("json"))return;const s=te.decoder.decode(e.body);try{return JSON.parse(s)}catch(e){return void console.error("Error parsing JSON response:",e)}}}var se;te.decoder=new TextDecoder,function(e){e.PNPublishOperation="PNPublishOperation",e.PNSignalOperation="PNSignalOperation",e.PNSubscribeOperation="PNSubscribeOperation",e.PNUnsubscribeOperation="PNUnsubscribeOperation",e.PNWhereNowOperation="PNWhereNowOperation",e.PNHereNowOperation="PNHereNowOperation",e.PNGlobalHereNowOperation="PNGlobalHereNowOperation",e.PNSetStateOperation="PNSetStateOperation",e.PNGetStateOperation="PNGetStateOperation",e.PNHeartbeatOperation="PNHeartbeatOperation",e.PNAddMessageActionOperation="PNAddActionOperation",e.PNRemoveMessageActionOperation="PNRemoveMessageActionOperation",e.PNGetMessageActionsOperation="PNGetMessageActionsOperation",e.PNTimeOperation="PNTimeOperation",e.PNHistoryOperation="PNHistoryOperation",e.PNDeleteMessagesOperation="PNDeleteMessagesOperation",e.PNFetchMessagesOperation="PNFetchMessagesOperation",e.PNMessageCounts="PNMessageCountsOperation",e.PNGetAllUUIDMetadataOperation="PNGetAllUUIDMetadataOperation",e.PNGetUUIDMetadataOperation="PNGetUUIDMetadataOperation",e.PNSetUUIDMetadataOperation="PNSetUUIDMetadataOperation",e.PNRemoveUUIDMetadataOperation="PNRemoveUUIDMetadataOperation",e.PNGetAllChannelMetadataOperation="PNGetAllChannelMetadataOperation",e.PNGetChannelMetadataOperation="PNGetChannelMetadataOperation",e.PNSetChannelMetadataOperation="PNSetChannelMetadataOperation",e.PNRemoveChannelMetadataOperation="PNRemoveChannelMetadataOperation",e.PNGetMembersOperation="PNGetMembersOperation",e.PNSetMembersOperation="PNSetMembersOperation",e.PNGetMembershipsOperation="PNGetMembershipsOperation",e.PNSetMembershipsOperation="PNSetMembershipsOperation",e.PNListFilesOperation="PNListFilesOperation",e.PNGenerateUploadUrlOperation="PNGenerateUploadUrlOperation",e.PNPublishFileOperation="PNPublishFileOperation",e.PNPublishFileMessageOperation="PNPublishFileMessageOperation",e.PNGetFileUrlOperation="PNGetFileUrlOperation",e.PNDownloadFileOperation="PNDownloadFileOperation",e.PNDeleteFileOperation="PNDeleteFileOperation",e.PNAddPushNotificationEnabledChannelsOperation="PNAddPushNotificationEnabledChannelsOperation",e.PNRemovePushNotificationEnabledChannelsOperation="PNRemovePushNotificationEnabledChannelsOperation",e.PNPushNotificationEnabledChannelsOperation="PNPushNotificationEnabledChannelsOperation",e.PNRemoveAllPushNotificationsOperation="PNRemoveAllPushNotificationsOperation",e.PNChannelGroupsOperation="PNChannelGroupsOperation",e.PNRemoveGroupOperation="PNRemoveGroupOperation",e.PNChannelsForGroupOperation="PNChannelsForGroupOperation",e.PNAddChannelsToGroupOperation="PNAddChannelsToGroupOperation",e.PNRemoveChannelsFromGroupOperation="PNRemoveChannelsFromGroupOperation",e.PNAccessManagerGrant="PNAccessManagerGrant",e.PNAccessManagerGrantToken="PNAccessManagerGrantToken",e.PNAccessManagerAudit="PNAccessManagerAudit",e.PNAccessManagerRevokeToken="PNAccessManagerRevokeToken",e.PNHandshakeOperation="PNHandshakeOperation",e.PNReceiveMessagesOperation="PNReceiveMessagesOperation"}(se||(se={}));var ne=se;var re;!function(e){e[e.Presence=-2]="Presence",e[e.Message=-1]="Message",e[e.Signal=1]="Signal",e[e.AppContext=2]="AppContext",e[e.MessageAction=3]="MessageAction",e[e.Files=4]="Files"}(re||(re={}));class ie extends te{constructor(e){var t,s,n,r,i,o;super({cancellable:!0}),this.parameters=e,null!==(t=(r=this.parameters).withPresence)&&void 0!==t||(r.withPresence=false),null!==(s=(i=this.parameters).channelGroups)&&void 0!==s||(i.channelGroups=[]),null!==(n=(o=this.parameters).channels)&&void 0!==n||(o.channels=[])}operation(){return ne.PNSubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;return e?t||s?void 0:"`channels` and `channelGroups` both should not be empty":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){let t;try{const s=te.decoder.decode(e.body);t=JSON.parse(s)}catch(e){console.error("Error parsing JSON response:",e)}if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));const s=t.m.filter((e=>{const t=void 0===e.b?e.c:e.b;return this.parameters.channels&&this.parameters.channels.includes(t)||this.parameters.channelGroups&&this.parameters.channelGroups.includes(t)})).map((e=>{let{e:t}=e;return null!=t||(t=e.c.endsWith("-pnpres")?re.Presence:re.Message),t!=re.Signal&&"string"==typeof e.d?t==re.Message?{type:re.Message,data:this.messageFromEnvelope(e)}:{type:re.Files,data:this.fileFromEnvelope(e)}:t==re.Message?{type:re.Message,data:this.messageFromEnvelope(e)}:t===re.Presence?{type:re.Presence,data:this.presenceEventFromEnvelope(e)}:t==re.Signal?{type:re.Signal,data:this.signalFromEnvelope(e)}:t===re.AppContext?{type:re.AppContext,data:this.appContextFromEnvelope(e)}:t===re.MessageAction?{type:re.MessageAction,data:this.messageActionFromEnvelope(e)}:{type:re.Files,data:this.fileFromEnvelope(e)}}));return{cursor:{timetoken:t.t.t,region:t.t.r},messages:s}}))}get headers(){return{accept:"text/javascript"}}presenceEventFromEnvelope(e){var t;const{d:s}=e,[n,r]=this.subscriptionChannelFromEnvelope(e),i=n.replace("-pnpres",""),o=null!==r?i:null,a=null!==r?r:i;return"string"!=typeof s&&("data"in s?(s.state=s.data,delete s.data):"action"in s&&"interval"===s.action&&(s.hereNowRefresh=null!==(t=s.here_now_refresh)&&void 0!==t&&t,delete s.here_now_refresh)),Object.assign({channel:i,subscription:r,actualChannel:o,subscribedChannel:a,timetoken:e.p.t},s)}messageFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d),i={channel:t,subscription:s,actualChannel:null!==s?t:null,subscribedChannel:null!==s?s:t,timetoken:e.p.t,publisher:e.i,message:n};return e.u&&(i.userMetadata=e.u),e.cmt&&(i.customMessageType=e.cmt),r&&(i.error=r),i}signalFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,message:e.d};return e.u&&(n.userMetadata=e.u),e.cmt&&(n.customMessageType=e.cmt),n}messageActionFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,event:n.event,data:Object.assign(Object.assign({},n.data),{uuid:e.i})}}appContextFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,message:n}}fileFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d);let i=r;const o={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i};return e.u&&(o.userMetadata=e.u),n?"string"==typeof n?null!=i||(i="Unexpected file information payload data type."):(o.message=n.message,n.file&&(o.file={id:n.file.id,name:n.file.name,url:this.parameters.getFileUrl({id:n.file.id,name:n.file.name,channel:t})})):null!=i||(i="File information payload is missing."),e.cmt&&(o.customMessageType=e.cmt),i&&(o.error=i),o}subscriptionChannelFromEnvelope(e){return[e.c,void 0===e.b?e.c:e.b]}decryptedData(e){if(!this.parameters.crypto||"string"!=typeof e)return[e,void 0];let t,s;try{const s=this.parameters.crypto.decrypt(e);t=s instanceof ArrayBuffer?JSON.parse(oe.decoder.decode(s)):s}catch(e){t=null,s=`Error while decrypting message content: ${e.message}`}return[null!=t?t:e,s]}}class oe extends ie{get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/subscribe/${t}/${K(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,heartbeat:s,state:n,timetoken:r,region:i}=this.parameters,o={};return e&&e.length>0&&(o["channel-group"]=e.sort().join(",")),t&&t.length>0&&(o["filter-expr"]=t),s&&(o.heartbeat=s),n&&Object.keys(n).length>0&&(o.state=JSON.stringify(n)),void 0!==r&&"string"==typeof r?r.length>0&&"0"!==r&&(o.tt=r):void 0!==r&&r>0&&(o.tt=r),i&&(o.tr=i),o}}class ae{constructor(e){this.listenerManager=e,this.channelListenerMap=new Map,this.groupListenerMap=new Map}emitEvent(e){var t;if(e.type===re.Message)this.listenerManager.announceMessage(e.data),this.announce("message",e.data,e.data.channel,e.data.subscription);else if(e.type===re.Signal)this.listenerManager.announceSignal(e.data),this.announce("signal",e.data,e.data.channel,e.data.subscription);else if(e.type===re.Presence)this.listenerManager.announcePresence(e.data),this.announce("presence",e.data,null!==(t=e.data.subscription)&&void 0!==t?t:e.data.channel,e.data.subscription);else if(e.type===re.AppContext){const{data:t}=e,{message:s}=t;if(this.listenerManager.announceObjects(t),this.announce("objects",t,t.channel,t.subscription),"uuid"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,type:a}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",type:"user"})});this.listenerManager.announceUser(u),this.announce("user",u,u.spaceId,u.subscription)}else if("channel"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,type:a}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",type:"space"})});this.listenerManager.announceSpace(u),this.announce("space",u,u.spaceId,u.subscription)}else if("membership"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,data:a}=s,c=r(s,["event","data"]),{uuid:u,channel:l}=a,h=r(a,["uuid","channel"]),d=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",data:Object.assign(Object.assign({},h),{user:u,space:l})})});this.listenerManager.announceMembership(d),this.announce("membership",d,d.spaceId,d.subscription)}}else e.type===re.MessageAction?(this.listenerManager.announceMessageAction(e.data),this.announce("messageAction",e.data,e.data.channel,e.data.subscription)):e.type===re.Files&&(this.listenerManager.announceFile(e.data),this.announce("file",e.data,e.data.channel,e.data.subscription))}addListener(e,t,s){t&&s?(null==t||t.forEach((t=>{if(this.channelListenerMap.has(t)){const s=this.channelListenerMap.get(t);s.includes(e)||s.push(e)}else this.channelListenerMap.set(t,[e])})),null==s||s.forEach((t=>{if(this.groupListenerMap.has(t)){const s=this.groupListenerMap.get(t);s.includes(e)||s.push(e)}else this.groupListenerMap.set(t,[e])}))):this.listenerManager.addListener(e)}removeListener(e,t,s){t&&s?(null==t||t.forEach((t=>{this.channelListenerMap.has(t)&&this.channelListenerMap.set(t,this.channelListenerMap.get(t).filter((t=>t!==e)))})),null==s||s.forEach((t=>{this.groupListenerMap.has(t)&&this.groupListenerMap.set(t,this.groupListenerMap.get(t).filter((t=>t!==e)))}))):this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners(),this.channelListenerMap.clear(),this.groupListenerMap.clear()}announce(e,t,s,n){t&&this.channelListenerMap.has(s)&&this.channelListenerMap.get(s).forEach((s=>{const n=s[e];n&&n(t)})),n&&this.groupListenerMap.has(n)&&this.groupListenerMap.get(n).forEach((s=>{const n=s[e];n&&n(t)}))}}class ce{constructor(e=!1){this.sync=e,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){const t=()=>{this.listeners.forEach((t=>{t(e)}))};this.sync?t():setTimeout(t,0)}}class ue{transition(e,t){var s;if(this.transitionMap.has(t.type))return null===(s=this.transitionMap.get(t.type))||void 0===s?void 0:s(e,t)}constructor(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}on(e,t){return this.transitionMap.set(e,t),this}with(e,t){return[this,e,null!=t?t:[]]}onEnter(e){return this.enterEffects.push(e),this}onExit(e){return this.exitEffects.push(e),this}}class le extends ce{describe(e){return new ue(e)}start(e,t){this.currentState=e,this.currentContext=t,this.notify({type:"engineStarted",state:e,context:t})}transition(e){if(!this.currentState)throw new Error("Start the engine first");this.notify({type:"eventReceived",event:e});const t=this.currentState.transition(this.currentContext,e);if(t){const[s,n,r]=t;for(const e of this.currentState.exitEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)});const i=this.currentState;this.currentState=s;const o=this.currentContext;this.currentContext=n,this.notify({type:"transitionDone",fromState:i,fromContext:o,toState:s,toContext:n,event:e});for(const e of r)this.notify({type:"invocationDispatched",invocation:e});for(const e of this.currentState.enterEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)})}}}class he{constructor(e){this.dependencies=e,this.instances=new Map,this.handlers=new Map}on(e,t){this.handlers.set(e,t)}dispatch(e){if("CANCEL"===e.type){if(this.instances.has(e.payload)){const t=this.instances.get(e.payload);null==t||t.cancel(),this.instances.delete(e.payload)}return}const t=this.handlers.get(e.type);if(!t)throw new Error(`Unhandled invocation '${e.type}'`);const s=t(e.payload,this.dependencies);e.managed&&this.instances.set(e.type,s),s.start()}dispose(){for(const[e,t]of this.instances.entries())t.cancel(),this.instances.delete(e)}}function de(e,t){const s=function(...s){return{type:e,payload:null==t?void 0:t(...s)}};return s.type=e,s}function pe(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!1});return s.type=e,s}function ge(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!0});return s.type=e,s.cancel={type:"CANCEL",payload:e,managed:!1},s}class ye extends Error{constructor(){super("The operation was aborted."),this.name="AbortError",Object.setPrototypeOf(this,new.target.prototype)}}class fe extends ce{constructor(){super(...arguments),this._aborted=!1}get aborted(){return this._aborted}throwIfAborted(){if(this._aborted)throw new ye}abort(){this._aborted=!0,this.notify(new ye)}}class me{constructor(e,t){this.payload=e,this.dependencies=t}}class be extends me{constructor(e,t,s){super(e,t),this.asyncFunction=s,this.abortSignal=new fe}start(){this.asyncFunction(this.payload,this.abortSignal,this.dependencies).catch((e=>{}))}cancel(){this.abortSignal.abort()}}const ve=e=>(t,s)=>new be(t,s,e),we=de("RECONNECT",(()=>({}))),Se=de("DISCONNECT",(()=>({}))),ke=de("JOINED",((e,t)=>({channels:e,groups:t}))),Ee=de("LEFT",((e,t)=>({channels:e,groups:t}))),Oe=de("LEFT_ALL",(()=>({}))),Ce=de("HEARTBEAT_SUCCESS",(e=>({statusCode:e}))),Ne=de("HEARTBEAT_FAILURE",(e=>e)),Pe=de("HEARTBEAT_GIVEUP",(()=>({}))),Me=de("TIMES_UP",(()=>({}))),_e=pe("HEARTBEAT",((e,t)=>({channels:e,groups:t}))),Ae=pe("LEAVE",((e,t)=>({channels:e,groups:t}))),je=pe("EMIT_STATUS",(e=>e)),Ie=ge("WAIT",(()=>({}))),Re=ge("DELAYED_HEARTBEAT",(e=>e));class Fe extends he{constructor(e,t){super(t),this.on(_e.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,presenceState:r,config:i}){try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},i.maintainPresenceState&&{state:r}),{heartbeat:i.presenceTimeout}));e.transition(Ce(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Ne(t))}}}))))),this.on(Ae.type,ve(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{leave:s,config:n}){if(!n.suppressLeaveEvents)try{s({channels:e.channels,channelGroups:e.groups})}catch(e){}}))))),this.on(Ie.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeatDelay:n}){return s.throwIfAborted(),yield n(),s.throwIfAborted(),e.transition(Me())}))))),this.on(Re.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,retryDelay:r,presenceState:i,config:o}){if(!o.retryConfiguration||!o.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(Pe());s.throwIfAborted(),yield r(o.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},o.maintainPresenceState&&{state:i}),{heartbeat:o.presenceTimeout}));return e.transition(Ce(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Ne(t))}}}))))),this.on(je.type,ve(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s,config:n}){var r;n.announceFailedHeartbeats&&!0===(null===(r=null==e?void 0:e.status)||void 0===r?void 0:r.error)?s(e.status):n.announceSuccessfulHeartbeats&&200===e.statusCode&&s(Object.assign(Object.assign({},e),{operation:ne.PNHeartbeatOperation,error:!1}))})))))}}const Te=new ue("HEARTBEAT_STOPPED");Te.on(ke.type,((e,t)=>Te.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Te.on(Ee.type,((e,t)=>Te.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))}))),Te.on(we.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),Te.on(Oe.type,((e,t)=>Ge.with(void 0)));const Ue=new ue("HEARTBEAT_COOLDOWN");Ue.onEnter((()=>Ie())),Ue.onExit((()=>Ie.cancel)),Ue.on(Me.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),Ue.on(ke.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Ue.on(Ee.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),Ue.on(Se.type,(e=>Te.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),Ue.on(Oe.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const xe=new ue("HEARTBEAT_FAILED");xe.on(ke.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),xe.on(Ee.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),xe.on(we.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),xe.on(Se.type,((e,t)=>Te.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),xe.on(Oe.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const De=new ue("HEARBEAT_RECONNECTING");De.onEnter((e=>Re(e))),De.onExit((()=>Re.cancel)),De.on(ke.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),De.on(Ee.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),De.on(Se.type,((e,t)=>{Te.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)])})),De.on(Ce.type,((e,t)=>Ue.with({channels:e.channels,groups:e.groups}))),De.on(Ne.type,((e,t)=>De.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),De.on(Pe.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups}))),De.on(Oe.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const qe=new ue("HEARTBEATING");qe.onEnter((e=>_e(e.channels,e.groups))),qe.on(Ce.type,((e,t)=>Ue.with({channels:e.channels,groups:e.groups}))),qe.on(ke.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),qe.on(Ee.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),qe.on(Ne.type,((e,t)=>De.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),qe.on(Se.type,(e=>Te.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),qe.on(Oe.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const Ge=new ue("HEARTBEAT_INACTIVE");Ge.on(ke.type,((e,t)=>qe.with({channels:t.payload.channels,groups:t.payload.groups})));class Ke{get _engine(){return this.engine}constructor(e){this.dependencies=e,this.engine=new le,this.channels=[],this.groups=[],this.dispatcher=new Fe(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(Ge,void 0)}join({channels:e,groups:t}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],this.engine.transition(ke(this.channels.slice(0),this.groups.slice(0)))}leave({channels:e,groups:t}){this.dependencies.presenceState&&(null==e||e.forEach((e=>delete this.dependencies.presenceState[e])),null==t||t.forEach((e=>delete this.dependencies.presenceState[e]))),this.engine.transition(Ee(null!=e?e:[],null!=t?t:[]))}leaveAll(){this.engine.transition(Oe())}dispose(){this._unsubscribeEngine(),this.dispatcher.dispose()}}class $e{static LinearRetryPolicy(e){return{delay:e.delay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var s;return 403!==(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)&&this.maximumRetry>t},getDelay(e,t){var s;return 1e3*((null!==(s=t.retryAfter)&&void 0!==s?s:this.delay)+Math.random())},getGiveupReason(e,t){var s;return this.maximumRetry<=t?"retry attempts exhaused.":403===(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.maximumRetry>10)throw new Error("Maximum retry for linear retry policy can not be more than 10")}}}static ExponentialRetryPolicy(e){return{minimumDelay:e.minimumDelay,maximumDelay:e.maximumDelay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var s;return 403!==(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)&&this.maximumRetry>t},getDelay(e,t){var s;return 1e3*((null!==(s=t.retryAfter)&&void 0!==s?s:Math.min(Math.pow(2,e),this.maximumDelay))+Math.random())},getGiveupReason(e,t){var s;return this.maximumRetry<=t?"retry attempts exhausted.":403===(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.minimumDelay<2)throw new Error("Minimum delay can not be set less than 2 seconds for retry");if(this.maximumDelay)throw new Error("Maximum delay can not be set more than 150 seconds for retry");if(this.maximumRetry>6)throw new Error("Maximum retry for exponential retry policy can not be more than 6")}}}}const Le=ge("HANDSHAKE",((e,t)=>({channels:e,groups:t}))),Be=ge("RECEIVE_MESSAGES",((e,t,s)=>({channels:e,groups:t,cursor:s}))),He=pe("EMIT_MESSAGES",(e=>e)),ze=pe("EMIT_STATUS",(e=>e)),Ve=ge("RECEIVE_RECONNECT",(e=>e)),We=ge("HANDSHAKE_RECONNECT",(e=>e)),Je=de("SUBSCRIPTION_CHANGED",((e,t)=>({channels:e,groups:t}))),Xe=de("SUBSCRIPTION_RESTORED",((e,t,s,n)=>({channels:e,groups:t,cursor:{timetoken:s,region:null!=n?n:0}}))),Qe=de("HANDSHAKE_SUCCESS",(e=>e)),Ye=de("HANDSHAKE_FAILURE",(e=>e)),Ze=de("HANDSHAKE_RECONNECT_SUCCESS",(e=>({cursor:e}))),et=de("HANDSHAKE_RECONNECT_FAILURE",(e=>e)),tt=de("HANDSHAKE_RECONNECT_GIVEUP",(e=>e)),st=de("RECEIVE_SUCCESS",((e,t)=>({cursor:e,events:t}))),nt=de("RECEIVE_FAILURE",(e=>e)),rt=de("RECEIVE_RECONNECT_SUCCESS",((e,t)=>({cursor:e,events:t}))),it=de("RECEIVE_RECONNECT_FAILURE",(e=>e)),ot=de("RECEIVING_RECONNECT_GIVEUP",(e=>e)),at=de("DISCONNECT",(()=>({}))),ct=de("RECONNECT",((e,t)=>({cursor:{timetoken:null!=e?e:"",region:null!=t?t:0}}))),ut=de("UNSUBSCRIBE_ALL",(()=>({})));class lt extends he{constructor(e,t){super(t),this.on(Le.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{handshake:n,presenceState:r,config:i}){s.throwIfAborted();try{const o=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:i.filterExpression},i.maintainPresenceState&&{state:r}));return e.transition(Qe(o))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Ye(t))}}}))))),this.on(Be.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,config:r}){s.throwIfAborted();try{const i=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:r.filterExpression});e.transition(st(i.cursor,i.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;if(!s.aborted)return e.transition(nt(t))}}}))))),this.on(He.type,ve(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitMessages:s}){e.length>0&&s(e)}))))),this.on(ze.type,ve(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s}){s(e)}))))),this.on(Ve.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,delay:r,config:i}){if(!i.retryConfiguration||!i.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(ot(new d(i.retryConfiguration?i.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe messages receive.")));s.throwIfAborted(),yield r(i.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{const r=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:i.filterExpression});return e.transition(rt(r.cursor,r.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(it(t))}}}))))),this.on(We.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{handshake:n,delay:r,presenceState:i,config:o}){if(!o.retryConfiguration||!o.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(tt(new d(o.retryConfiguration?o.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe handshake")));s.throwIfAborted(),yield r(o.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{const r=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:o.filterExpression},o.maintainPresenceState&&{state:i}));return e.transition(Ze(r))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(et(t))}}})))))}}const ht=new ue("HANDSHAKE_FAILED");ht.on(Je.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),ht.on(ct.type,((e,t)=>bt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor||e.cursor}))),ht.on(Xe.type,((e,t)=>{var s,n;return bt.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!==(n=null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)&&void 0!==n?n:0}})})),ht.on(ut.type,(e=>vt.with()));const dt=new ue("HANDSHAKE_STOPPED");dt.on(Je.type,((e,t)=>dt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),dt.on(ct.type,((e,t)=>bt.with(Object.assign(Object.assign({},e),{cursor:t.payload.cursor||e.cursor})))),dt.on(Xe.type,((e,t)=>{var s;return dt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),dt.on(ut.type,(e=>vt.with()));const pt=new ue("RECEIVE_FAILED");pt.on(ct.type,((e,t)=>{var s;return bt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(s=t.payload.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),pt.on(Je.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),pt.on(Xe.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),pt.on(ut.type,(e=>vt.with(void 0)));const gt=new ue("RECEIVE_STOPPED");gt.on(Je.type,((e,t)=>gt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),gt.on(Xe.type,((e,t)=>gt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),gt.on(ct.type,((e,t)=>{var s;return bt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(s=t.payload.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),gt.on(ut.type,(()=>vt.with(void 0)));const yt=new ue("RECEIVE_RECONNECTING");yt.onEnter((e=>Ve(e))),yt.onExit((()=>Ve.cancel)),yt.on(rt.type,((e,t)=>ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[He(t.payload.events)]))),yt.on(it.type,((e,t)=>yt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),yt.on(ot.type,((e,t)=>{var s;return pt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[ze({category:h.PNDisconnectedUnexpectedlyCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),yt.on(at.type,(e=>gt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[ze({category:h.PNDisconnectedCategory})]))),yt.on(Xe.type,((e,t)=>ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),yt.on(Je.type,((e,t)=>ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),yt.on(ut.type,(e=>vt.with(void 0,[ze({category:h.PNDisconnectedCategory})])));const ft=new ue("RECEIVING");ft.onEnter((e=>Be(e.channels,e.groups,e.cursor))),ft.onExit((()=>Be.cancel)),ft.on(st.type,((e,t)=>ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[He(t.payload.events)]))),ft.on(Je.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?vt.with(void 0):ft.with({cursor:e.cursor,channels:t.payload.channels,groups:t.payload.groups}))),ft.on(Xe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?vt.with(void 0):ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),ft.on(nt.type,((e,t)=>yt.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),ft.on(at.type,(e=>gt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[ze({category:h.PNDisconnectedCategory})]))),ft.on(ut.type,(e=>vt.with(void 0,[ze({category:h.PNDisconnectedCategory})])));const mt=new ue("HANDSHAKE_RECONNECTING");mt.onEnter((e=>We(e))),mt.onExit((()=>We.cancel)),mt.on(Ze.type,((e,t)=>{var s,n;const r={timetoken:(null===(s=e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=e.cursor)||void 0===n?void 0:n.timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region};return ft.with({channels:e.channels,groups:e.groups,cursor:r},[ze({category:h.PNConnectedCategory})])})),mt.on(et.type,((e,t)=>mt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),mt.on(tt.type,((e,t)=>{var s;return ht.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[ze({category:h.PNConnectionErrorCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),mt.on(at.type,(e=>dt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),mt.on(Je.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),mt.on(Xe.type,((e,t)=>{var s,n;return bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:(null===(s=t.payload.cursor)||void 0===s?void 0:s.region)||(null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)||0}})})),mt.on(ut.type,(e=>vt.with(void 0)));const bt=new ue("HANDSHAKING");bt.onEnter((e=>Le(e.channels,e.groups))),bt.onExit((()=>Le.cancel)),bt.on(Je.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?vt.with(void 0):bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),bt.on(Qe.type,((e,t)=>{var s,n;return ft.with({channels:e.channels,groups:e.groups,cursor:{timetoken:(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.timetoken:t.payload.timetoken,region:t.payload.region}},[ze({category:h.PNConnectedCategory})])})),bt.on(Ye.type,((e,t)=>mt.with({channels:e.channels,groups:e.groups,cursor:e.cursor,attempts:0,reason:t.payload}))),bt.on(at.type,(e=>dt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),bt.on(Xe.type,((e,t)=>{var s;return bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),bt.on(ut.type,(e=>vt.with()));const vt=new ue("UNSUBSCRIBED");vt.on(Je.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups}))),vt.on(Xe.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:t.payload.cursor})));class wt{get _engine(){return this.engine}constructor(e){this.engine=new le,this.channels=[],this.groups=[],this.dependencies=e,this.dispatcher=new lt(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(vt,void 0)}subscribe({channels:e,channelGroups:t,timetoken:s,withPresence:n}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],n&&(this.channels.map((e=>this.channels.push(`${e}-pnpres`))),this.groups.map((e=>this.groups.push(`${e}-pnpres`)))),s?this.engine.transition(Xe(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])),s)):this.engine.transition(Je(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])))),this.dependencies.join&&this.dependencies.join({channels:Array.from(new Set(this.channels.filter((e=>!e.endsWith("-pnpres"))))),groups:Array.from(new Set(this.groups.filter((e=>!e.endsWith("-pnpres")))))})}unsubscribe({channels:e=[],channelGroups:t=[]}){const s=$(this.channels,[...e,...e.map((e=>`${e}-pnpres`))]),n=$(this.groups,[...t,...t.map((e=>`${e}-pnpres`))]);if(new Set(this.channels).size!==new Set(s).size||new Set(this.groups).size!==new Set(n).size){const r=L(this.channels,e),i=L(this.groups,t);this.dependencies.presenceState&&(null==r||r.forEach((e=>delete this.dependencies.presenceState[e])),null==i||i.forEach((e=>delete this.dependencies.presenceState[e]))),this.channels=s,this.groups=n,this.engine.transition(Je(Array.from(new Set(this.channels.slice(0))),Array.from(new Set(this.groups.slice(0))))),this.dependencies.leave&&this.dependencies.leave({channels:r.slice(0),groups:i.slice(0)})}}unsubscribeAll(){this.channels=[],this.groups=[],this.dependencies.presenceState&&Object.keys(this.dependencies.presenceState).forEach((e=>{delete this.dependencies.presenceState[e]})),this.engine.transition(Je(this.channels.slice(0),this.groups.slice(0))),this.dependencies.leaveAll&&this.dependencies.leaveAll()}reconnect({timetoken:e,region:t}){this.engine.transition(ct(e,t))}disconnect(){this.engine.transition(at()),this.dependencies.leaveAll&&this.dependencies.leaveAll()}getSubscribedChannels(){return Array.from(new Set(this.channels.slice(0)))}getSubscribedChannelGroups(){return Array.from(new Set(this.groups.slice(0)))}dispose(){this.disconnect(),this._unsubscribeEngine(),this.dispatcher.dispose()}}class St extends te{constructor(e){var t,s;super({method:e.sendByPost?q.POST:q.GET}),this.parameters=e,null!==(t=(s=this.parameters).sendByPost)&&void 0!==t||(s.sendByPost=false)}operation(){return ne.PNPublishOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{message:e,channel:t,keySet:s}=this.parameters,n=this.prepareMessagePayload(e);return`/publish/${s.publishKey}/${s.subscribeKey}/0/${G(t)}/0${this.parameters.sendByPost?"":`/${G(n)}`}`}get queryParameters(){const{customMessageType:e,meta:t,replicate:s,storeInHistory:n,ttl:r}=this.parameters,i={};return e&&(i.custom_message_type=e),void 0!==n&&(i.store=n?"1":"0"),void 0!==r&&(i.ttl=r),void 0===s||s||(i.norep="true"),t&&"object"==typeof t&&(i.meta=JSON.stringify(t)),i}get headers(){return{"Content-Type":"application/json"}}get body(){return this.prepareMessagePayload(this.parameters.message)}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class kt extends te{constructor(e){super(),this.parameters=e}operation(){return ne.PNSignalOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{keySet:{publishKey:e,subscribeKey:t},channel:s,message:n}=this.parameters,r=JSON.stringify(n);return`/signal/${e}/${t}/0/${G(s)}/0/${G(r)}`}get queryParameters(){const{customMessageType:e}=this.parameters,t={};return e&&(t.custom_message_type=e),t}}class Et extends ie{operation(){return ne.PNReceiveMessagesOperation}validate(){const e=super.validate();return e||(this.parameters.timetoken?this.parameters.region?void 0:"region can not be empty":"timetoken can not be empty")}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${K(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,timetoken:s,region:n}=this.parameters,r={ee:""};return e&&e.length>0&&(r["channel-group"]=e.sort().join(",")),t&&t.length>0&&(r["filter-expr"]=t),"string"==typeof s?s&&s.length>0&&(r.tt=s):s&&s>0&&(r.tt=s),n&&(r.tr=n),r}}class Ot extends ie{operation(){return ne.PNHandshakeOperation}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${K(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,state:s}=this.parameters,n={tt:0,ee:""};return e&&e.length>0&&(n["channel-group"]=e.sort().join(",")),t&&t.length>0&&(n["filter-expr"]=t),s&&Object.keys(s).length>0&&(n.state=JSON.stringify(s)),n}}class Ct extends te{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=(n=this.parameters).channels)&&void 0!==t||(n.channels=[]),null!==(s=(r=this.parameters).channelGroups)&&void 0!==s||(r.channelGroups=[])}operation(){return ne.PNGetStateOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;if(!e)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);const{channels:s=[],channelGroups:n=[]}=this.parameters,r={channels:{}};return 1===s.length&&0===n.length?r.channels[s[0]]=t.payload:r.channels=t.payload,r}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${K(null!=s?s:[],",")}/uuid/${t}`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.join(",")}:{}}}class Nt extends te{constructor(e){super(),this.parameters=e}operation(){return ne.PNSetStateOperation}validate(){const{keySet:{subscribeKey:e},state:t,channels:s=[],channelGroups:n=[]}=this.parameters;return e?t?0===(null==s?void 0:s.length)&&0===(null==n?void 0:n.length)?"Please provide a list of channels and/or channel-groups":void 0:"Missing State":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{state:t.payload}}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${K(null!=s?s:[],",")}/uuid/${G(t)}/data`}get queryParameters(){const{channelGroups:e,state:t}=this.parameters,s={state:JSON.stringify(t)};return e&&0!==e.length&&(s["channel-group"]=e.join(",")),s}}class Pt extends te{constructor(e){super(),this.parameters=e}operation(){return ne.PNHeartbeatOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channels:t}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${K(null!=t?t:[],",")}/heartbeat`}get queryParameters(){const{channelGroups:e,state:t,heartbeat:s}=this.parameters,n={heartbeat:`${s}`};return e&&0!==e.length&&(n["channel-group"]=e.join(",")),t&&(n.state=JSON.stringify(t)),n}}class Mt extends te{constructor(e){super(),this.parameters=e,this.parameters.channelGroups&&(this.parameters.channelGroups=Array.from(new Set(this.parameters.channelGroups))),this.parameters.channels&&(this.parameters.channels=Array.from(new Set(this.parameters.channels)))}operation(){return ne.PNUnsubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"At least one `channel` or `channel group` should be provided.":void 0:"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/presence/sub-key/${t}/channel/${K(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/leave`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.sort().join(",")}:{}}}class _t extends te{constructor(e){super(),this.parameters=e}operation(){return ne.PNWhereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t.payload?{channels:t.payload.channels}:{channels:[]}}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/presence/sub-key/${e}/uuid/${G(t)}`}}class At extends te{constructor(e){var t,s,n,r,i,o;super(),this.parameters=e,null!==(t=(r=this.parameters).queryParameters)&&void 0!==t||(r.queryParameters={}),null!==(s=(i=this.parameters).includeUUIDs)&&void 0!==s||(i.includeUUIDs=true),null!==(n=(o=this.parameters).includeState)&&void 0!==n||(o.includeState=false)}operation(){const{channels:e=[],channelGroups:t=[]}=this.parameters;return 0===e.length&&0===t.length?ne.PNGlobalHereNowOperation:ne.PNHereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t,s;const n=this.deserializeResponse(e);if(!n)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(n.status>=400)throw _.create(e);const r="occupancy"in n?1:n.payload.total_channels,i="occupancy"in n?n.occupancy:n.payload.total_occupancy,o={};let a={};if("occupancy"in n){const e=this.parameters.channels[0];a[e]={uuids:null!==(t=n.uuids)&&void 0!==t?t:[],occupancy:i}}else a=null!==(s=n.payload.channels)&&void 0!==s?s:{};return Object.keys(a).forEach((e=>{const t=a[e];o[e]={occupants:this.parameters.includeUUIDs?t.uuids.map((e=>"string"==typeof e?{uuid:e,state:null}:e)):[],name:e,occupancy:t.occupancy}})),{totalChannels:r,totalOccupancy:i,channels:o}}))}get path(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;let n=`/v2/presence/sub-key/${e}`;return(t&&t.length>0||s&&s.length>0)&&(n+=`/channel/${K(null!=t?t:[],",")}`),n}get queryParameters(){const{channelGroups:e,includeUUIDs:t,includeState:s,queryParameters:n}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign({},t?{}:{disable_uuids:"1"}),null!=s&&s?{state:"1"}:{}),e&&e.length>0?{"channel-group":e.join(",")}:{}),n)}}class jt extends te{constructor(e){super({method:q.DELETE}),this.parameters=e}operation(){return ne.PNDeleteMessagesOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v3/history/sub-key/${e}/channel/${G(t)}`}get queryParameters(){const{start:e,end:t}=this.parameters;return Object.assign(Object.assign({},e?{start:e}:{}),t?{end:t}:{})}}class It extends te{constructor(e){super(),this.parameters=e}operation(){return ne.PNMessageCounts}validate(){const{keySet:{subscribeKey:e},channels:t,timetoken:s,channelTimetokens:n}=this.parameters;return e?t?s&&n?"`timetoken` and `channelTimetokens` are incompatible together":s||n?n&&n.length>1&&n.length!==t.length?"Length of `channelTimetokens` and `channels` do not match":void 0:"`timetoken` or `channelTimetokens` need to be set":"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{channels:t.channels}}))}get path(){return`/v3/history/sub-key/${this.parameters.keySet.subscribeKey}/message-counts/${K(this.parameters.channels)}`}get queryParameters(){let{channelTimetokens:e}=this.parameters;return this.parameters.timetoken&&(e=[this.parameters.timetoken]),Object.assign(Object.assign({},1===e.length?{timetoken:e[0]}:{}),e.length>1?{channelsTimetoken:e.join(",")}:{})}}class Rt extends te{constructor(e){var t,s,n;super(),this.parameters=e,e.count?e.count=Math.min(e.count,100):e.count=100,null!==(t=e.stringifiedTimeToken)&&void 0!==t||(e.stringifiedTimeToken=false),null!==(s=e.includeMeta)&&void 0!==s||(e.includeMeta=false),null!==(n=e.logVerbosity)&&void 0!==n||(e.logVerbosity=false)}operation(){return ne.PNHistoryOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));const s=t[0],n=t[1],r=t[2];return Array.isArray(s)?{messages:s.map((e=>{const t=this.processPayload(e.message),s={entry:t.payload,timetoken:e.timetoken};return t.error&&(s.error=t.error),e.meta&&(s.meta=e.meta),s})),startTimeToken:n,endTimeToken:r}:{messages:[],startTimeToken:n,endTimeToken:r}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/history/sub-key/${e}/channel/${G(t)}`}get queryParameters(){const{start:e,end:t,reverse:s,count:n,stringifiedTimeToken:r,includeMeta:i}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:n,include_token:"true"},e?{start:e}:{}),t?{end:t}:{}),r?{string_message_token:"true"}:{}),null!=s?{reverse:s.toString()}:{}),i?{include_meta:"true"}:{})}processPayload(e){const{crypto:t,logVerbosity:s}=this.parameters;if(!t||"string"!=typeof e)return{payload:e};let n,r;try{const s=t.decrypt(e);n=s instanceof ArrayBuffer?JSON.parse(Rt.decoder.decode(s)):s}catch(t){s&&console.log("decryption error",t.message),n=e,r=`Error while decrypting message content: ${t.message}`}return{payload:n,error:r}}}var Ft;!function(e){e[e.Message=-1]="Message",e[e.Files=4]="Files"}(Ft||(Ft={}));class Tt extends te{constructor(e){var t,s,n,r,i;super(),this.parameters=e;const o=null!==(t=e.includeMessageActions)&&void 0!==t&&t,a=e.channels.length>1||o?25:100;e.count?e.count=Math.min(e.count,a):e.count=a,e.includeUuid?e.includeUUID=e.includeUuid:null!==(s=e.includeUUID)&&void 0!==s||(e.includeUUID=true),null!==(n=e.stringifiedTimeToken)&&void 0!==n||(e.stringifiedTimeToken=false),null!==(r=e.includeMessageType)&&void 0!==r||(e.includeMessageType=true),null!==(i=e.logVerbosity)&&void 0!==i||(e.logVerbosity=false)}operation(){return ne.PNFetchMessagesOperation}validate(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return e?t?void 0!==s&&s&&t.length>1?"History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.":void 0:"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t;const s=this.deserializeResponse(e);if(!s)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(s.status>=400)throw _.create(e);const n=null!==(t=s.channels)&&void 0!==t?t:{},r={};return Object.keys(n).forEach((e=>{r[e]=n[e].map((t=>{null===t.message_type&&(t.message_type=Ft.Message);const s=this.processPayload(e,t),n=Object.assign(Object.assign({channel:e,timetoken:t.timetoken,message:s.payload,messageType:t.message_type},t.custom_message_type?{customMessageType:t.custom_message_type}:{}),{uuid:t.uuid});if(t.actions){const e=n;e.actions=t.actions,e.data=t.actions}return t.meta&&(n.meta=t.meta),s.error&&(n.error=s.error),n}))})),s.more?{channels:r,more:s.more}:{channels:r}}))}get path(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return`/v3/${s?"history-with-actions":"history"}/sub-key/${e}/channel/${K(t)}`}get queryParameters(){const{start:e,end:t,count:s,includeCustomMessageType:n,includeMessageType:r,includeMeta:i,includeUUID:o,stringifiedTimeToken:a}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({max:s},e?{start:e}:{}),t?{end:t}:{}),a?{string_message_token:"true"}:{}),void 0!==i&&i?{include_meta:"true"}:{}),o?{include_uuid:"true"}:{}),null!=n?{include_custom_message_type:n?"true":"false"}:{}),r?{include_message_type:"true"}:{})}processPayload(e,t){const{crypto:s,logVerbosity:n}=this.parameters;if(!s||"string"!=typeof t.message)return{payload:t.message};let r,i;try{const e=s.decrypt(t.message);r=e instanceof ArrayBuffer?JSON.parse(Tt.decoder.decode(e)):e}catch(e){n&&console.log("decryption error",e.message),r=t.message,i=`Error while decrypting message content: ${e.message}`}if(!i&&r&&t.message_type==Ft.Files&&"object"==typeof r&&this.isFileMessage(r)){const t=r;return{payload:{message:t.message,file:Object.assign(Object.assign({},t.file),{url:this.parameters.getFileUrl({channel:e,id:t.file.id,name:t.file.name})})},error:i}}return{payload:r,error:i}}isFileMessage(e){return void 0!==e.file}}class Ut extends te{constructor(e){super(),this.parameters=e}operation(){return ne.PNGetMessageActionsOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);let s=null,n=null;return t.data.length>0&&(s=t.data[0].actionTimetoken,n=t.data[t.data.length-1].actionTimetoken),{data:t.data,more:t.more,start:s,end:n}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/message-actions/${e}/channel/${G(t)}`}get queryParameters(){const{limit:e,start:t,end:s}=this.parameters;return Object.assign(Object.assign(Object.assign({},t?{start:t}:{}),s?{end:s}:{}),e?{limit:e}:{})}}class xt extends te{constructor(e){super({method:q.POST}),this.parameters=e}operation(){return ne.PNAddMessageActionOperation}validate(){const{keySet:{subscribeKey:e},action:t,channel:s,messageTimetoken:n}=this.parameters;return e?s?n?t?t.value?t.type?t.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message timetoken":"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{data:t.data}}))}get path(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s}=this.parameters;return`/v1/message-actions/${e}/channel/${G(t)}/message/${s}`}get headers(){return{"Content-Type":"application/json"}}get body(){return JSON.stringify(this.parameters.action)}}class Dt extends te{constructor(e){super({method:q.DELETE}),this.parameters=e}operation(){return ne.PNRemoveMessageActionOperation}validate(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s,actionTimetoken:n}=this.parameters;return e?t?s?n?void 0:"Missing action timetoken":"Missing message timetoken":"Missing message action channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{data:t.data}}))}get path(){const{keySet:{subscribeKey:e},channel:t,actionTimetoken:s,messageTimetoken:n}=this.parameters;return`/v1/message-actions/${e}/channel/${G(t)}/message/${n}/action/${s}`}}class qt extends te{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).storeInHistory)&&void 0!==t||(s.storeInHistory=true)}operation(){return ne.PNPublishFileMessageOperation}validate(){const{channel:e,fileId:t,fileName:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{message:e,channel:t,keySet:{publishKey:s,subscribeKey:n},fileId:r,fileName:i}=this.parameters,o=Object.assign({file:{name:i,id:r}},e?{message:e}:{});return`/v1/files/publish-file/${s}/${n}/0/${G(t)}/0/${G(this.prepareMessagePayload(o))}`}get queryParameters(){const{customMessageType:e,storeInHistory:t,ttl:s,meta:n}=this.parameters;return Object.assign(Object.assign(Object.assign({store:t?"1":"0"},e?{custom_message_type:e}:{}),s?{ttl:s}:{}),n&&"object"==typeof n?{meta:JSON.stringify(n)}:{})}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class Gt extends te{constructor(e){super({method:q.LOCAL}),this.parameters=e}operation(){return ne.PNGetFileUrlOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return e.url}))}get path(){const{channel:e,id:t,name:s,keySet:{subscribeKey:n}}=this.parameters;return`/v1/files/${n}/channels/${G(e)}/files/${t}/${s}`}}class Kt extends te{constructor(e){super({method:q.DELETE}),this.parameters=e}operation(){return ne.PNDeleteFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},id:t,channel:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${G(s)}/files/${t}/${n}`}}class $t extends te{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).limit)&&void 0!==t||(s.limit=100)}operation(){return ne.PNListFilesOperation}validate(){if(!this.parameters.channel)return"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${G(t)}/files`}get queryParameters(){const{limit:e,next:t}=this.parameters;return Object.assign({limit:e},t?{next:t}:{})}}class Lt extends te{constructor(e){super({method:q.POST}),this.parameters=e}operation(){return ne.PNGenerateUploadUrlOperation}validate(){return this.parameters.channel?this.parameters.name?void 0:"'name' can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{id:t.data.id,name:t.data.name,url:t.file_upload_request.url,formFields:t.file_upload_request.form_fields}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${G(t)}/generate-upload-url`}get headers(){return{"Content-Type":"application/json"}}get body(){return JSON.stringify({name:this.parameters.name})}}class Bt extends te{constructor(e){super({method:q.POST}),this.parameters=e;const t=e.file.mimeType;t&&(e.formFields=e.formFields.map((e=>"Content-Type"===e.name?{name:e.name,value:t}:e)))}operation(){return ne.PNPublishFileOperation}validate(){const{fileId:e,fileName:t,file:s,uploadUrl:n}=this.parameters;return e?t?s?n?void 0:"Validation failed: file upload 'url' can't be empty":"Validation failed: 'file' can't be empty":"Validation failed: file 'name' can't be empty":"Validation failed: file 'id' can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{status:e.status,message:e.body?Bt.decoder.decode(e.body):"OK"}}))}request(){return Object.assign(Object.assign({},super.request()),{origin:new URL(this.parameters.uploadUrl).origin,timeout:300})}get path(){const{pathname:e,search:t}=new URL(this.parameters.uploadUrl);return`${e}${t}`}get body(){return this.parameters.file}get formData(){return this.parameters.formFields}}class Ht{constructor(e){var t;if(this.parameters=e,this.file=null===(t=this.parameters.PubNubFile)||void 0===t?void 0:t.create(e.file),!this.file)throw new Error("File upload error: unable to create File object.")}process(){return i(this,void 0,void 0,(function*(){let e,t;return this.generateFileUploadUrl().then((s=>(e=s.name,t=s.id,this.uploadFile(s)))).then((e=>{if(204!==e.status)throw new d("Upload to bucket was unsuccessful",{error:!0,statusCode:e.status,category:h.PNUnknownCategory,operation:ne.PNPublishFileOperation,errorData:{message:e.message}})})).then((()=>this.publishFileMessage(t,e))).catch((e=>{if(e instanceof d)throw e;const t=e instanceof _?e:_.create(e);throw new d("File upload error.",t.toStatus(ne.PNPublishFileOperation))}))}))}generateFileUploadUrl(){return i(this,void 0,void 0,(function*(){const e=new Lt(Object.assign(Object.assign({},this.parameters),{name:this.file.name,keySet:this.parameters.keySet}));return this.parameters.sendRequest(e)}))}uploadFile(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,PubNubFile:s,crypto:n,cryptography:r}=this.parameters,{id:i,name:o,url:a,formFields:c}=e;return this.parameters.PubNubFile.supportsEncryptFile&&(!t&&n?this.file=yield n.encryptFile(this.file,s):t&&r&&(this.file=yield r.encryptFile(t,this.file,s))),this.parameters.sendRequest(new Bt({fileId:i,fileName:o,file:this.file,uploadUrl:a,formFields:c}))}))}publishFileMessage(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i;let o,a={timetoken:"0"},c=this.parameters.fileUploadPublishRetryLimit,u=!1;do{try{a=yield this.parameters.publishFile(Object.assign(Object.assign({},this.parameters),{fileId:e,fileName:t})),u=!0}catch(e){e instanceof d&&(o=e),c-=1}}while(!u&&c>0);if(u)return{status:200,timetoken:a.timetoken,id:e,name:t};throw new d("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{error:!0,category:null!==(n=null===(s=o.status)||void 0===s?void 0:s.category)&&void 0!==n?n:h.PNUnknownCategory,statusCode:null!==(i=null===(r=o.status)||void 0===r?void 0:r.statusCode)&&void 0!==i?i:0,channel:this.parameters.channel,id:e,name:t})}))}}class zt{subscribe(e){const t=null==e?void 0:e.timetoken;this.pubnub.registerSubscribeCapable(this),this.pubnub.subscribe(Object.assign({channels:this.channelNames,channelGroups:this.groupNames},null!==t&&""!==t&&{timetoken:t}))}unsubscribe(){this.pubnub.unregisterSubscribeCapable(this);const{channels:e,channelGroups:t}=this.pubnub.getSubscribeCapableEntities(),s=this.groupNames.filter((e=>!t.includes(e))),n=this.channelNames.filter((t=>!e.includes(t)));0===n.length&&0===s.length||this.pubnub.unsubscribe({channels:n,channelGroups:s})}set onMessage(e){this.listener.message=e}set onPresence(e){this.listener.presence=e}set onSignal(e){this.listener.signal=e}set onObjects(e){this.listener.objects=e}set onMessageAction(e){this.listener.messageAction=e}set onFile(e){this.listener.file=e}addListener(e){this.eventEmitter.addListener(e,this.channelNames,this.groupNames)}removeListener(e){this.eventEmitter.removeListener(e,this.channelNames,this.groupNames)}get channels(){return this.channelNames.slice(0)}get channelGroups(){return this.groupNames.slice(0)}}class Vt extends zt{constructor({channels:e=[],channelGroups:t=[],subscriptionOptions:s,eventEmitter:n,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.subscriptionList=[],this.options=s,this.eventEmitter=n,this.pubnub=r,e.forEach((e=>{const t=this.pubnub.channel(e).subscription(this.options);this.channelNames=[...this.channelNames,...t.channels],this.subscriptionList.push(t)})),t.forEach((e=>{const t=this.pubnub.channelGroup(e).subscription(this.options);this.groupNames=[...this.groupNames,...t.channelGroups],this.subscriptionList.push(t)})),this.listener={},n.addListener(this.listener,this.channelNames,this.groupNames)}addSubscription(e){this.subscriptionList.push(e),this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscription(e){const t=e.channels,s=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!s.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>t!==e)),this.eventEmitter.removeListener(this.listener,t,s)}addSubscriptionSet(e){this.subscriptionList=[...this.subscriptionList,...e.subscriptions],this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscriptionSet(e){const t=e.channels,s=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!s.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>!e.subscriptions.includes(t))),this.eventEmitter.removeListener(this.listener,t,s)}get subscriptions(){return this.subscriptionList.slice(0)}}class Wt extends zt{constructor({channels:e,channelGroups:t,subscriptionOptions:s,eventEmitter:n,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.channelNames=e,this.groupNames=t,this.options=s,this.pubnub=r,this.eventEmitter=n,this.listener={},n.addListener(this.listener,this.channelNames,this.groupNames)}addSubscription(e){return new Vt({channels:[...this.channelNames,...e.channels],channelGroups:[...this.groupNames,...e.channelGroups],subscriptionOptions:Object.assign(Object.assign({},this.options),null==e?void 0:e.options),eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Jt{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.id=e}subscription(e){return new Wt({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Xt{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){{const t=[this.name];return(null==e?void 0:e.receivePresenceEvents)&&!this.name.endsWith("-pnpres")&&t.push(`${this.name}-pnpres`),new Wt({channels:[],channelGroups:t,subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}}class Qt{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.id=e}subscription(e){return new Wt({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Yt{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){{const t=[this.name];return(null==e?void 0:e.receivePresenceEvents)&&!this.name.endsWith("-pnpres")&&t.push(`${this.name}-pnpres`),new Wt({channels:t,channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}}class Zt extends te{constructor(e){super(),this.parameters=e}operation(){return ne.PNRemoveChannelsFromGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${G(t)}`}get queryParameters(){return{remove:this.parameters.channels.join(",")}}}class es extends te{constructor(e){super(),this.parameters=e}operation(){return ne.PNAddChannelsToGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${G(t)}`}get queryParameters(){return{add:this.parameters.channels.join(",")}}}class ts extends te{constructor(e){super(),this.parameters=e}operation(){return ne.PNChannelsForGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{channels:t.payload.channels}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${G(t)}`}}class ss extends te{constructor(e){super(),this.parameters=e}operation(){return ne.PNRemoveGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${G(t)}/remove`}}class ns extends te{constructor(e){super(),this.parameters=e}operation(){return ne.PNChannelGroupsOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{groups:t.payload.groups}}))}get path(){return`/v1/channel-registration/sub-key/${this.parameters.keySet.subscribeKey}/channel-group`}}class rs{constructor(e,t){this.sendRequest=t,this.keySet=e}listChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new ts(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}listGroups(e){return i(this,void 0,void 0,(function*(){const t=new ns({keySet:this.keySet});return e?this.sendRequest(t,e):this.sendRequest(t)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new es(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new Zt(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteGroup(e,t){return i(this,void 0,void 0,(function*(){const s=new ss(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class is extends te{constructor(e){var t,s;super(),this.parameters=e,"apns2"===this.parameters.pushGateway&&(null!==(t=(s=this.parameters).environment)&&void 0!==t||(s.environment="development")),this.parameters.count&&this.parameters.count>1e3&&(this.parameters.count=1e3)}operation(){throw Error("Should be implemented in subclass.")}validate(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;return e?s?"add"!==t&&"remove"!==t||"channels"in this.parameters&&0!==this.parameters.channels.length?n?"apns2"!==this.parameters.pushGateway||this.parameters.topic?void 0:"Missing APNS2 topic":"Missing GW Type (pushGateway: gcm or apns2)":"Missing Channels":"Missing Device ID (device)":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){throw Error("Should be implemented in subclass.")}))}get path(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;let r="apns2"===n?`/v2/push/sub-key/${e}/devices-apns2/${s}`:`/v1/push/sub-key/${e}/devices/${s}`;return"remove-device"===t&&(r=`${r}/remove`),r}get queryParameters(){const{start:e,count:t}=this.parameters;let s=Object.assign(Object.assign({type:this.parameters.pushGateway},e?{start:e}:{}),t&&t>0?{count:t}:{});if("channels"in this.parameters&&(s[this.parameters.action]=this.parameters.channels.join(",")),"apns2"===this.parameters.pushGateway){const{environment:e,topic:t}=this.parameters;s=Object.assign(Object.assign({},s),{environment:e,topic:t})}return s}}class os extends is{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove"}))}operation(){return ne.PNRemovePushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class as extends is{constructor(e){super(Object.assign(Object.assign({},e),{action:"list"}))}operation(){return ne.PNPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{channels:t}}))}}class cs extends is{constructor(e){super(Object.assign(Object.assign({},e),{action:"add"}))}operation(){return ne.PNAddPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class us extends is{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove-device"}))}operation(){return ne.PNRemoveAllPushNotificationsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class ls{constructor(e,t){this.sendRequest=t,this.keySet=e}listChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new as(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new cs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new os(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteDevice(e,t){return i(this,void 0,void 0,(function*(){const s=new us(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class hs extends te{constructor(e){var t,s,n,r,i,o;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(i=e.include).customFields)&&void 0!==s||(i.customFields=false),null!==(n=(o=e.include).totalCount)&&void 0!==n||(o.totalCount=false),null!==(r=e.limit)&&void 0!==r||(e.limit=100)}operation(){return ne.PNGetAllChannelMetadataOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";return i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(","),count:`${e.totalCount}`},s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class ds extends te{constructor(e){super({method:q.DELETE}),this.parameters=e}operation(){return ne.PNRemoveChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${G(t)}`}}class ps extends te{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f,m,b;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(h=e.include).customFields)&&void 0!==s||(h.customFields=false),null!==(n=(d=e.include).totalCount)&&void 0!==n||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(o=(y=e.include).channelFields)&&void 0!==o||(y.channelFields=false),null!==(a=(f=e.include).customChannelFields)&&void 0!==a||(f.customChannelFields=false),null!==(c=(m=e.include).channelStatusField)&&void 0!==c||(m.channelStatusField=false),null!==(u=(b=e.include).channelTypeField)&&void 0!==u||(b.channelTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ne.PNGetMembershipsOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${G(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const o=[];return e.statusField&&o.push("status"),e.typeField&&o.push("type"),e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),e.channelStatusField&&o.push("channel.status"),e.channelTypeField&&o.push("channel.type"),e.customChannelFields&&o.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class gs extends te{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f,m,b;super({method:q.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(h=e.include).customFields)&&void 0!==s||(h.customFields=false),null!==(n=(d=e.include).totalCount)&&void 0!==n||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(o=(y=e.include).channelFields)&&void 0!==o||(y.channelFields=false),null!==(a=(f=e.include).customChannelFields)&&void 0!==a||(f.customChannelFields=false),null!==(c=(m=e.include).channelStatusField)&&void 0!==c||(m.channelStatusField=false),null!==(u=(b=e.include).channelTypeField)&&void 0!==u||(b.channelTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ne.PNSetMembershipsOperation}validate(){const{uuid:e,channels:t}=this.parameters;return e?t&&0!==t.length?void 0:"Channels cannot be empty":"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${G(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const o=["channel.status","channel.type","status"];return e.statusField&&o.push("status"),e.typeField&&o.push("type"),e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),e.channelStatusField&&o.push("channel.status"),e.channelTypeField&&o.push("channel.type"),e.customChannelFields&&o.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{channels:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},status:e.status,type:e.type,custom:e.custom}))})}}class ys extends te{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(r=e.include).customFields)&&void 0!==s||(r.customFields=false),null!==(n=e.limit)&&void 0!==n||(e.limit=100)}operation(){return ne.PNGetAllUUIDMetadataOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";return i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(",")},void 0!==e.totalCount?{count:`${e.totalCount}`}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class fs extends te{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return ne.PNGetChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${G(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}}class ms extends te{constructor(e){var t,s,n;super({method:q.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return ne.PNSetChannelMetadataOperation}validate(){return this.parameters.channel?this.parameters.data?void 0:"Data cannot be empty":"Channel cannot be empty"}get headers(){return this.parameters.ifMatchesEtag?{"If-Match":this.parameters.ifMatchesEtag}:void 0}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${G(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class bs extends te{constructor(e){super({method:q.DELETE}),this.parameters=e,this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ne.PNRemoveUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${G(t)}`}}class vs extends te{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f,m,b;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(h=e.include).customFields)&&void 0!==s||(h.customFields=false),null!==(n=(d=e.include).totalCount)&&void 0!==n||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(o=(y=e.include).UUIDFields)&&void 0!==o||(y.UUIDFields=false),null!==(a=(f=e.include).customUUIDFields)&&void 0!==a||(f.customUUIDFields=false),null!==(c=(m=e.include).UUIDStatusField)&&void 0!==c||(m.UUIDStatusField=false),null!==(u=(b=e.include).UUIDTypeField)&&void 0!==u||(b.UUIDTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100)}operation(){return ne.PNSetMembersOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${G(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const o=[];return e.statusField&&o.push("status"),e.typeField&&o.push("type"),e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),e.UUIDStatusField&&o.push("uuid.status"),e.UUIDTypeField&&o.push("uuid.type"),e.customUUIDFields&&o.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class ws extends te{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f,m,b;super({method:q.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(h=e.include).customFields)&&void 0!==s||(h.customFields=false),null!==(n=(d=e.include).totalCount)&&void 0!==n||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(o=(y=e.include).UUIDFields)&&void 0!==o||(y.UUIDFields=false),null!==(a=(f=e.include).customUUIDFields)&&void 0!==a||(f.customUUIDFields=false),null!==(c=(m=e.include).UUIDStatusField)&&void 0!==c||(m.UUIDStatusField=false),null!==(u=(b=e.include).UUIDTypeField)&&void 0!==u||(b.UUIDTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100)}operation(){return ne.PNSetMembersOperation}validate(){const{channel:e,uuids:t}=this.parameters;return e?t&&0!==t.length?void 0:"UUIDs cannot be empty":"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${G(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const o=["uuid.status","uuid.type","type"];return e.statusField&&o.push("status"),e.typeField&&o.push("type"),e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),e.UUIDStatusField&&o.push("uuid.status"),e.UUIDTypeField&&o.push("uuid.type"),e.customUUIDFields&&o.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{uuids:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},status:e.status,type:e.type,custom:e.custom}))})}}class Ss extends te{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ne.PNGetUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${G(t)}`}get queryParameters(){const{include:e}=this.parameters;return{include:["status","type",...e.customFields?["custom"]:[]].join(",")}}}class ks extends te{constructor(e){var t,s,n;super({method:q.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ne.PNSetUUIDMetadataOperation}validate(){return this.parameters.uuid?this.parameters.data?void 0:"Data cannot be empty":"'uuid' cannot be empty"}get headers(){return this.parameters.ifMatchesEtag?{"If-Match":this.parameters.ifMatchesEtag}:void 0}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${G(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Es{constructor(e,t){this.keySet=e.keySet,this.configuration=e,this.sendRequest=t}getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllUUIDMetadata(e,t)}))}_getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new ys(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getUUIDMetadata(e,t)}))}_getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new Ss(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setUUIDMetadata(e,t)}))}_setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new ks(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeUUIDMetadata(e,t)}))}_removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new bs(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllChannelMetadata(e,t)}))}_getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new hs(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getChannelMetadata(e,t)}))}_getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new fs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setChannelMetadata(e,t)}))}_setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new ms(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeChannelMetadata(e,t)}))}_removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new ds(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new vs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new ws(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new ws(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new ps(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new gs(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new gs(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n;if("spaceId"in e){const n=e,r={channel:null!==(s=n.spaceId)&&void 0!==s?s:n.channel,filter:n.filter,limit:n.limit,page:n.page,include:Object.assign({},n.include),sort:n.sort?Object.fromEntries(Object.entries(n.sort).map((([e,t])=>[e.replace("user","uuid"),t]))):void 0},i=e=>({status:e.status,data:e.data.map((e=>({user:e.uuid,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getChannelMembers(r,((e,s)=>{t(e,s?i(s):s)})):this.getChannelMembers(r).then(i)}const r=e,i={uuid:null!==(n=r.userId)&&void 0!==n?n:r.uuid,filter:r.filter,limit:r.limit,page:r.page,include:Object.assign({},r.include),sort:r.sort?Object.fromEntries(Object.entries(r.sort).map((([e,t])=>[e.replace("space","channel"),t]))):void 0},o=e=>({status:e.status,data:e.data.map((e=>({space:e.channel,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getMemberships(i,((e,s)=>{t(e,s?o(s):s)})):this.getMemberships(i).then(o)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i,o,a;if("spaceId"in e){const i=e,o={channel:null!==(s=i.spaceId)&&void 0!==s?s:i.channel,uuids:null!==(r=null===(n=i.users)||void 0===n?void 0:n.map((e=>"string"==typeof e?e:{id:e.userId,custom:e.custom})))&&void 0!==r?r:i.uuids,limit:0};return t?this.setChannelMembers(o,t):this.setChannelMembers(o)}const c=e,u={uuid:null!==(i=c.userId)&&void 0!==i?i:c.uuid,channels:null!==(a=null===(o=c.spaces)||void 0===o?void 0:o.map((e=>"string"==typeof e?e:{id:e.spaceId,custom:e.custom})))&&void 0!==a?a:c.channels,limit:0};return t?this.setMemberships(u,t):this.setMemberships(u)}))}}class Os extends te{constructor(){super()}operation(){return ne.PNTimeOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[0]}}))}get path(){return"/time/0"}}class Cs extends te{constructor(e){super(),this.parameters=e}operation(){return ne.PNDownloadFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,crypto:s,cryptography:n,name:r,PubNubFile:i}=this.parameters,o=e.headers["content-type"];let a,c=e.body;return i.supportsEncryptFile&&(t||s)&&(t&&n?c=yield n.decrypt(t,c):!t&&s&&(a=yield s.decryptFile(i.create({data:c,name:r,mimeType:o}),i))),a||i.create({data:c,name:r,mimeType:o})}))}get path(){const{keySet:{subscribeKey:e},channel:t,id:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${G(t)}/files/${s}/${n}`}}class Ns{static notificationPayload(e,t){return new ee(e,t)}static generateUUID(){return T.createUUID()}constructor(e){if(this._configuration=e.configuration,this.cryptography=e.cryptography,this.tokenManager=e.tokenManager,this.transport=e.transport,this.crypto=e.crypto,this._objects=new Es(this._configuration,this.sendRequest.bind(this)),this._channelGroups=new rs(this._configuration.keySet,this.sendRequest.bind(this)),this._push=new ls(this._configuration.keySet,this.sendRequest.bind(this)),this.listenerManager=new V,this.eventEmitter=new ae(this.listenerManager),this.subscribeCapable=new Set,this._configuration.enableEventEngine){let e=this._configuration.getHeartbeatInterval();this.presenceState={},e&&(this.presenceEventEngine=new Ke({heartbeat:this.heartbeat.bind(this),leave:e=>this.makeUnsubscribe(e,(()=>{})),heartbeatDelay:()=>new Promise(((t,s)=>{e=this._configuration.getHeartbeatInterval(),e?setTimeout(t,1e3*e):s(new d("Heartbeat interval has been reset."))})),retryDelay:e=>new Promise((t=>setTimeout(t,e))),emitStatus:e=>this.listenerManager.announceStatus(e),config:this._configuration,presenceState:this.presenceState})),this.eventEngine=new wt({handshake:this.subscribeHandshake.bind(this),receiveMessages:this.subscribeReceiveMessages.bind(this),delay:e=>new Promise((t=>setTimeout(t,e))),join:this.join.bind(this),leave:this.leave.bind(this),leaveAll:this.leaveAll.bind(this),presenceState:this.presenceState,config:this._configuration,emitMessages:e=>{try{e.forEach((e=>this.eventEmitter.emitEvent(e)))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}},emitStatus:e=>this.listenerManager.announceStatus(e)})}else this.subscriptionManager=new X(this._configuration,this.listenerManager,this.eventEmitter,this.makeSubscribe.bind(this),this.heartbeat.bind(this),this.makeUnsubscribe.bind(this),this.time.bind(this))}get configuration(){return this._configuration}get _config(){return this.configuration}get authKey(){var e;return null!==(e=this._configuration.authKey)&&void 0!==e?e:void 0}getAuthKey(){return this.authKey}setAuthKey(e){this._configuration.setAuthKey(e)}get userId(){return this._configuration.userId}set userId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}getUserId(){return this._configuration.userId}setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}get filterExpression(){var e;return null!==(e=this._configuration.getFilterExpression())&&void 0!==e?e:void 0}getFilterExpression(){return this.filterExpression}set filterExpression(e){this._configuration.setFilterExpression(e)}setFilterExpression(e){this.filterExpression=e}get cipherKey(){return this._configuration.getCipherKey()}set cipherKey(e){this._configuration.setCipherKey(e)}setCipherKey(e){this.cipherKey=e}set heartbeatInterval(e){this._configuration.setHeartbeatInterval(e)}setHeartbeatInterval(e){this.heartbeatInterval=e}getVersion(){return this._configuration.getVersion()}_addPnsdkSuffix(e,t){this._configuration._addPnsdkSuffix(e,t)}getUUID(){return this.userId}setUUID(e){this.userId=e}get customEncrypt(){return this._configuration.getCustomEncrypt()}get customDecrypt(){return this._configuration.getCustomDecrypt()}channel(e){return new Yt(e,this.eventEmitter,this)}channelGroup(e){return new Xt(e,this.eventEmitter,this)}channelMetadata(e){return new Jt(e,this.eventEmitter,this)}userMetadata(e){return new Qt(e,this.eventEmitter,this)}subscriptionSet(e){return new Vt(Object.assign(Object.assign({},e),{eventEmitter:this.eventEmitter,pubnub:this}))}sendRequest(e,t){return i(this,void 0,void 0,(function*(){const s=e.validate();if(s){if(t)return t(p(s),null);throw new d("Validation failed, check status for details",p(s))}const n=e.request(),r=e.operation();n.formData&&n.formData.length>0||r===ne.PNDownloadFileOperation?n.timeout=this._configuration.getFileTimeout():r===ne.PNSubscribeOperation||r===ne.PNReceiveMessagesOperation?n.timeout=this._configuration.getSubscribeTimeout():n.timeout=this._configuration.getTransactionTimeout();const i={error:!1,operation:r,category:h.PNAcknowledgmentCategory,statusCode:0},[o,a]=this.transport.makeSendable(n);return e.cancellationController=a||null,o.then((t=>{if(i.statusCode=t.status,200!==t.status&&204!==t.status){const e=t.headers["content-type"];if(e||-1!==e.indexOf("javascript")||-1!==e.indexOf("json")){const e=JSON.parse(Ns.decoder.decode(t.body));"object"==typeof e&&"error"in e&&e.error&&"object"==typeof e.error&&(i.errorData=e.error)}}return e.parse(t)})).then((e=>t?t(i,e):e)).catch((e=>{const s=e instanceof _?e:_.create(e);if(t)return t(s.toStatus(r),null);throw s.toPubNubError(r,"REST API request processing error, check status for details")}))}))}destroy(e){var t;null===(t=this.subscribeCapable)||void 0===t||t.clear(),this.subscriptionManager?(this.subscriptionManager.unsubscribeAll(e),this.subscriptionManager.disconnect()):this.eventEngine&&this.eventEngine.dispose()}stop(){this.destroy()}addListener(e){this.listenerManager.addListener(e)}removeListener(e){this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners()}publish(e,t){return i(this,void 0,void 0,(function*(){{const s=new St(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}signal(e,t){return i(this,void 0,void 0,(function*(){{const s=new kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}fire(e,t){return i(this,void 0,void 0,(function*(){return null!=t||(t=()=>{}),this.publish(Object.assign(Object.assign({},e),{replicate:!1,storeInHistory:!1}),t)}))}getSubscribedChannels(){return this.subscriptionManager?this.subscriptionManager.subscribedChannels:this.eventEngine?this.eventEngine.getSubscribedChannels():[]}getSubscribedChannelGroups(){return this.subscriptionManager?this.subscriptionManager.subscribedChannelGroups:this.eventEngine?this.eventEngine.getSubscribedChannelGroups():[]}registerSubscribeCapable(e){this.subscribeCapable&&!this.subscribeCapable.has(e)&&this.subscribeCapable.add(e)}unregisterSubscribeCapable(e){this.subscribeCapable&&this.subscribeCapable.has(e)&&this.subscribeCapable.delete(e)}getSubscribeCapableEntities(){{const e={channels:[],channelGroups:[]};if(!this.subscribeCapable)return e;for(const t of this.subscribeCapable)e.channelGroups.push(...t.channelGroups),e.channels.push(...t.channels);return e}}subscribe(e){this.subscriptionManager?this.subscriptionManager.subscribe(e):this.eventEngine&&this.eventEngine.subscribe(e)}makeSubscribe(e,t){{const s=new oe(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));if(this.sendRequest(s,((e,n)=>{var r;this.subscriptionManager&&(null===(r=this.subscriptionManager.abort)||void 0===r?void 0:r.identifier)===s.requestIdentifier&&(this.subscriptionManager.abort=null),t(e,n)})),this.subscriptionManager){const e=()=>s.abort();e.identifier=s.requestIdentifier,this.subscriptionManager.abort=e}}}unsubscribe(e){this.subscriptionManager?this.subscriptionManager.unsubscribe(e):this.eventEngine&&this.eventEngine.unsubscribe(e)}makeUnsubscribe(e,t){this.sendRequest(new Mt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),t)}unsubscribeAll(){var e;null===(e=this.subscribeCapable)||void 0===e||e.clear(),this.subscriptionManager?this.subscriptionManager.unsubscribeAll():this.eventEngine&&this.eventEngine.unsubscribeAll()}disconnect(){this.subscriptionManager?this.subscriptionManager.disconnect():this.eventEngine&&this.eventEngine.disconnect()}reconnect(e){this.subscriptionManager?this.subscriptionManager.reconnect():this.eventEngine&&this.eventEngine.reconnect(null!=e?e:{})}subscribeHandshake(e){return i(this,void 0,void 0,(function*(){{const t=new Ot(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort()}));return this.sendRequest(t).then((e=>(s(),e.cursor)))}}))}subscribeReceiveMessages(e){return i(this,void 0,void 0,(function*(){{const t=new Et(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort()}));return this.sendRequest(t).then((e=>(s(),e)))}}))}getMessageActions(e,t){return i(this,void 0,void 0,(function*(){{const s=new Ut(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}addMessageAction(e,t){return i(this,void 0,void 0,(function*(){{const s=new xt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}removeMessageAction(e,t){return i(this,void 0,void 0,(function*(){{const s=new Dt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}fetchMessages(e,t){return i(this,void 0,void 0,(function*(){{const s=new Tt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}deleteMessages(e,t){return i(this,void 0,void 0,(function*(){{const s=new jt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}messageCounts(e,t){return i(this,void 0,void 0,(function*(){{const s=new It(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}history(e,t){return i(this,void 0,void 0,(function*(){{const s=new Rt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}hereNow(e,t){return i(this,void 0,void 0,(function*(){{const s=new At(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}whereNow(e,t){return i(this,void 0,void 0,(function*(){var s;{const n=new _t({uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet});return t?this.sendRequest(n,t):this.sendRequest(n)}}))}getState(e,t){return i(this,void 0,void 0,(function*(){var s;{const n=new Ct(Object.assign(Object.assign({},e),{uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}setState(e,t){return i(this,void 0,void 0,(function*(){var s,n;{const{keySet:r,userId:i}=this._configuration,o=this._configuration.getPresenceTimeout();let a;if(this._configuration.enableEventEngine&&this.presenceState){const t=this.presenceState;null===(s=e.channels)||void 0===s||s.forEach((s=>t[s]=e.state)),"channelGroups"in e&&(null===(n=e.channelGroups)||void 0===n||n.forEach((s=>t[s]=e.state)))}return a="withHeartbeat"in e?new Pt(Object.assign(Object.assign({},e),{keySet:r,heartbeat:o})):new Nt(Object.assign(Object.assign({},e),{keySet:r,uuid:i})),this.subscriptionManager&&this.subscriptionManager.setState(e),t?this.sendRequest(a,t):this.sendRequest(a)}}))}presence(e){var t;null===(t=this.subscriptionManager)||void 0===t||t.changePresence(e)}heartbeat(e,t){return i(this,void 0,void 0,(function*(){{const s=new Pt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}join(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.join(e)}leave(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.leave(e)}leaveAll(){var e;null===(e=this.presenceEventEngine)||void 0===e||e.leaveAll()}grantToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Token error: PAM module disabled")}))}revokeToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Revoke Token error: PAM module disabled")}))}get token(){return this.tokenManager&&this.tokenManager.getToken()}getToken(){return this.token}set token(e){this.tokenManager&&this.tokenManager.setToken(e)}setToken(e){this.token=e}parseToken(e){return this.tokenManager&&this.tokenManager.parseToken(e)}grant(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant error: PAM module disabled")}))}audit(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Permissions error: PAM module disabled")}))}get objects(){return this._objects}fetchUsers(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllUUIDMetadata(e,t)}))}fetchUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getUUIDMetadata(e,t)}))}createUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}updateUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}removeUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeUUIDMetadata(e,t)}))}fetchSpaces(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllChannelMetadata(e,t)}))}fetchSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getChannelMetadata(e,t)}))}createSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}updateSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}removeSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeChannelMetadata(e,t)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.fetchMemberships(e,t)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}updateMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r;{if("spaceId"in e){const r=e,i={channel:null!==(s=r.spaceId)&&void 0!==s?s:r.channel,uuids:null!==(n=r.userIds)&&void 0!==n?n:r.uuids,limit:0};return t?this.objects.removeChannelMembers(i,t):this.objects.removeChannelMembers(i)}const i=e,o={uuid:i.userId,channels:null!==(r=i.spaceIds)&&void 0!==r?r:i.channels,limit:0};return t?this.objects.removeMemberships(o,t):this.objects.removeMemberships(o)}}))}get channelGroups(){return this._channelGroups}get push(){return this._push}sendFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new Ht(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,fileUploadPublishRetryLimit:this._configuration.fileUploadPublishRetryLimit,file:e.file,sendRequest:this.sendRequest.bind(this),publishFile:this.publishFile.bind(this),crypto:this._configuration.getCryptoModule(),cryptography:this.cryptography?this.cryptography:void 0})),n={error:!1,operation:ne.PNPublishFileOperation,category:h.PNAcknowledgmentCategory,statusCode:0};return s.process().then((e=>(n.statusCode=e.status,t?t(n,e):e))).catch((e=>{let s;throw e instanceof d?s=e.status:e instanceof _&&(s=e.toStatus(n.operation)),t&&s&&t(s,null),new d("REST API request processing error, check status for details",s)}))}}))}publishFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new qt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}listFiles(e,t){return i(this,void 0,void 0,(function*(){{const s=new $t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}getFileUrl(e){var t;{const s=this.transport.request(new Gt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})).request()),n=null!==(t=s.queryParameters)&&void 0!==t?t:{},r=Object.keys(n).map((e=>{const t=n[e];return Array.isArray(t)?t.map((t=>`${e}=${G(t)}`)).join("&"):`${e}=${G(t)}`})).join("&");return`${s.origin}${s.path}?${r}`}}downloadFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new Cs(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,cryptography:this.cryptography?this.cryptography:void 0,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):yield this.sendRequest(s)}}))}deleteFile(e,t){return i(this,void 0,void 0,(function*(){{const s=new Kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}time(e){return i(this,void 0,void 0,(function*(){const t=new Os;return e?this.sendRequest(t,e):this.sendRequest(t)}))}encrypt(e,t){const s=this._configuration.getCryptoModule();if(!t&&s&&"string"==typeof e){const t=s.encrypt(e);return"string"==typeof t?t:u(t)}if(!this.crypto)throw new Error("Encryption error: cypher key not set");return this.crypto.encrypt(e,t)}decrypt(e,t){const s=this._configuration.getCryptoModule();if(!t&&s){const t=s.decrypt(e);return t instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(t)):t}if(!this.crypto)throw new Error("Decryption error: cypher key not set");return this.crypto.decrypt(e,t)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File encryption error. File constructor not configured.");if("string"!=typeof e&&!this._configuration.getCryptoModule())throw new Error("File encryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File encryption error. File encryption not available");return this.cryptography.encryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.encryptFile(t,this._configuration.PubNubFile)}))}decryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File decryption error. File constructor not configured.");if("string"==typeof e&&!this._configuration.getCryptoModule())throw new Error("File decryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File decryption error. File decryption not available");return this.cryptography.decryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.decryptFile(t,this._configuration.PubNubFile)}))}}Ns.decoder=new TextDecoder,Ns.OPERATIONS=ne,Ns.CATEGORIES=h,Ns.ExponentialRetryPolicy=$e.ExponentialRetryPolicy,Ns.LinearRetryPolicy=$e.LinearRetryPolicy;class Ps{constructor(e,t){this.decode=e,this.base64ToBinary=t}decodeToken(e){let t="";e.length%4==3?t="=":e.length%4==2&&(t="==");const s=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,n=this.decode(this.base64ToBinary(s));return"object"==typeof n?n:void 0}}class Ms extends Ns{constructor(e){var t;const s=I(e),r=Object.assign(Object.assign({},s),{sdkFamily:"Web"});r.PubNubFile=a;const i=U(r,(e=>{if(e.cipherKey)return new N({default:new C(Object.assign({},e)),cryptors:[new S({cipherKey:e.cipherKey})]})}));let o,u,l;o=new D(new Ps((e=>j(n.decode(e))),c)),(i.getCipherKey()||i.secretKey)&&(u=new E({secretKey:i.secretKey,cipherKey:i.getCipherKey(),useRandomIVs:i.getUseRandomIVs(),customEncrypt:i.getCustomEncrypt(),customDecrypt:i.getCustomDecrypt()})),l=new O;let h=new z(r.transport,i.keepAlive,i.logVerbosity);s.subscriptionWorkerUrl&&(h=new A({clientIdentifier:i._instanceId,subscriptionKey:i.subscribeKey,userId:i.getUserId(),workerUrl:s.subscriptionWorkerUrl,sdkVersion:i.getVersion(),heartbeatInterval:i.getHeartbeatInterval(),logVerbosity:i.logVerbosity,workerLogVerbosity:r.subscriptionWorkerLogVerbosity,transport:h}));super({configuration:i,transport:new H({clientConfiguration:i,tokenManager:o,transport:h}),cryptography:l,tokenManager:o,crypto:u}),(null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t)&&(window.addEventListener("offline",(()=>{this.networkDownDetected()})),window.addEventListener("online",(()=>{this.networkUpDetected()})))}networkDownDetected(){this.listenerManager.announceNetworkDown(),this._configuration.restore?this.disconnect():this.destroy(!0)}networkUpDetected(){this.listenerManager.announceNetworkUp(),this.reconnect()}}return Ms.CryptoModule=N,Ms})); +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).PubNub=t()}(this,(function(){"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n={exports:{}};!function(t){!function(e,n){var s=Math.pow(2,-24),r=Math.pow(2,32),i=Math.pow(2,53);var a={encode:function(e){var t,s=new ArrayBuffer(256),a=new DataView(s),o=0;function c(e){for(var n=s.byteLength,r=o+e;n>2,u=0;u>6),r.push(128|63&a)):a<55296?(r.push(224|a>>12),r.push(128|a>>6&63),r.push(128|63&a)):(a=(1023&a)<<10,a|=1023&t.charCodeAt(++s),a+=65536,r.push(240|a>>18),r.push(128|a>>12&63),r.push(128|a>>6&63),r.push(128|63&a))}return d(3,r.length),h(r);default:var p;if(Array.isArray(t))for(d(4,p=t.length),s=0;s>5!==e)throw"Invalid indefinite length element";return n}function f(e,t){for(var n=0;n>10),e.push(56320|1023&s))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof i&&(i=function(){return n});var m=function e(){var r,d,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=h(),r=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*s;return t.setUint32(0,r<<16|i<<13|a<<13),t.getFloat32(0)}();case 26:return c(a.getFloat32(o),4);case 27:return c(a.getFloat64(o),8)}if((d=g(v))<0&&(b<2||6=0;)S+=d,w.push(u(d));var E=new Uint8Array(S),O=0;for(r=0;r=0;)f(k,d);else f(k,d);return String.fromCharCode.apply(null,k);case 4:var C;if(d<0)for(C=[];!p();)C.push(e());else for(C=new Array(d),r=0;r{const n=new FileReader;n.addEventListener("load",(()=>{if(n.result instanceof ArrayBuffer)return e(n.result)})),n.addEventListener("error",(()=>t(n.error))),n.readAsArrayBuffer(this.data)}))}))}toString(){return i(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const n=new FileReader;n.addEventListener("load",(()=>{if("string"==typeof n.result)return e(n.result)})),n.addEventListener("error",(()=>{t(n.error)})),n.readAsBinaryString(this.data)}))}))}toStream(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in Node.js environments.")}))}toFile(){return i(this,void 0,void 0,(function*(){return this.data}))}toFileUri(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in React Native environments.")}))}toBlob(){return i(this,void 0,void 0,(function*(){return this.data}))}}o.supportsBlob="undefined"!=typeof Blob,o.supportsFile="undefined"!=typeof File,o.supportsBuffer=!1,o.supportsStream=!1,o.supportsString=!0,o.supportsArrayBuffer=!0,o.supportsEncryptFile=!0,o.supportsFileUri=!1;function c(e){const t=e.replace(/==?$/,""),n=Math.floor(t.length/4*3),s=new ArrayBuffer(n),r=new Uint8Array(s);let i=0;function a(){const e=t.charAt(i++),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e);if(-1===n)throw new Error(`Illegal character at ${i}: ${t.charAt(i-1)}`);return n}for(let e=0;e>4,c=(15&n)<<4|s>>2,u=(3&s)<<6|i;r[e]=o,64!=s&&(r[e+1]=c),64!=i&&(r[e+2]=u)}return s}function u(e){let t="";const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=new Uint8Array(e),r=s.byteLength,i=r%3,a=r-i;let o,c,u,l,h;for(let e=0;e>18,c=(258048&h)>>12,u=(4032&h)>>6,l=63&h,t+=n[o]+n[c]+n[u]+n[l];return 1==i?(h=s[a],o=(252&h)>>2,c=(3&h)<<4,t+=n[o]+n[c]+"=="):2==i&&(h=s[a]<<8|s[a+1],o=(64512&h)>>10,c=(1008&h)>>4,u=(15&h)<<2,t+=n[o]+n[c]+n[u]+"="),t}var l;!function(e){e.PNNetworkIssuesCategory="PNNetworkIssuesCategory",e.PNTimeoutCategory="PNTimeoutCategory",e.PNCancelledCategory="PNCancelledCategory",e.PNBadRequestCategory="PNBadRequestCategory",e.PNAccessDeniedCategory="PNAccessDeniedCategory",e.PNValidationErrorCategory="PNValidationErrorCategory",e.PNAcknowledgmentCategory="PNAcknowledgmentCategory",e.PNMalformedResponseCategory="PNMalformedResponseCategory",e.PNUnknownCategory="PNUnknownCategory",e.PNNetworkUpCategory="PNNetworkUpCategory",e.PNNetworkDownCategory="PNNetworkDownCategory",e.PNReconnectedCategory="PNReconnectedCategory",e.PNConnectedCategory="PNConnectedCategory",e.PNRequestMessageCountExceededCategory="PNRequestMessageCountExceededCategory",e.PNDisconnectedCategory="PNDisconnectedCategory",e.PNConnectionErrorCategory="PNConnectionErrorCategory",e.PNDisconnectedUnexpectedlyCategory="PNDisconnectedUnexpectedlyCategory"}(l||(l={}));var h=l;class d extends Error{constructor(e,t){super(e),this.status=t,this.name="PubNubError",this.message=e,Object.setPrototypeOf(this,new.target.prototype)}}function p(e,t){var n;return null!==(n=e.statusCode)&&void 0!==n||(e.statusCode=0),Object.assign(Object.assign({},e),{statusCode:e.statusCode,category:t,error:!0})}function g(e,t){return p(Object.assign({message:e},{}),h.PNValidationErrorCategory)}function y(e,t){return p(Object.assign(Object.assign({message:"Unable to deserialize service response"},void 0!==e?{responseText:e}:{}),void 0!==t?{statusCode:t}:{}),h.PNMalformedResponseCategory)}var f,m,b,v,w,S=S||function(e){var t={},n=t.lib={},s=function(){},r=n.Base={extend:function(e){s.prototype=this;var t=new s;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)}},i=n.WordArray=r.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||o).stringify(this)},concat:function(e){var t=this.words,n=e.words,s=this.sigBytes;if(e=e.sigBytes,this.clamp(),s%4)for(var r=0;r>>2]|=(n[r>>>2]>>>24-r%4*8&255)<<24-(s+r)%4*8;else if(65535>>2]=n[r>>>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=r.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n=[],s=0;s>>2]>>>24-s%4*8&255;n.push((r>>>4).toString(16)),n.push((15&r).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,n=[],s=0;s>>3]|=parseInt(e.substr(s,2),16)<<24-s%8*4;return new i.init(n,t/2)}},c=a.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],s=0;s>>2]>>>24-s%4*8&255));return n.join("")},parse:function(e){for(var t=e.length,n=[],s=0;s>>2]|=(255&e.charCodeAt(s))<<24-s%4*8;return new i.init(n,t)}},u=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)))}},l=n.BufferedBlockAlgorithm=r.extend({reset:function(){this._data=new i.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=u.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,s=n.words,r=n.sigBytes,a=this.blockSize,o=r/(4*a);if(t=(o=t?e.ceil(o):e.max((0|o)-this._minBufferSize,0))*a,r=e.min(4*t,r),t){for(var c=0;cu;){var l;e:{l=c;for(var h=e.sqrt(l),d=2;d<=h;d++)if(!(l%d)){l=!1;break e}l=!0}l&&(8>u&&(i[u]=o(e.pow(c,.5))),a[u]=o(e.pow(c,1/3)),u++),c++}var p=[];r=r.SHA256=s.extend({_doReset:function(){this._hash=new n.init(i.slice(0))},_doProcessBlock:function(e,t){for(var n=this._hash.words,s=n[0],r=n[1],i=n[2],o=n[3],c=n[4],u=n[5],l=n[6],h=n[7],d=0;64>d;d++){if(16>d)p[d]=0|e[t+d];else{var g=p[d-15],y=p[d-2];p[d]=((g<<25|g>>>7)^(g<<14|g>>>18)^g>>>3)+p[d-7]+((y<<15|y>>>17)^(y<<13|y>>>19)^y>>>10)+p[d-16]}g=h+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&u^~c&l)+a[d]+p[d],y=((s<<30|s>>>2)^(s<<19|s>>>13)^(s<<10|s>>>22))+(s&r^s&i^r&i),h=l,l=u,u=c,c=o+g|0,o=i,i=r,r=s,s=g+y|0}n[0]=n[0]+s|0,n[1]=n[1]+r|0,n[2]=n[2]+i|0,n[3]=n[3]+o|0,n[4]=n[4]+c|0,n[5]=n[5]+u|0,n[6]=n[6]+l|0,n[7]=n[7]+h|0},_doFinalize:function(){var t=this._data,n=t.words,s=8*this._nDataBytes,r=8*t.sigBytes;return n[r>>>5]|=128<<24-r%32,n[14+(r+64>>>9<<4)]=e.floor(s/4294967296),n[15+(r+64>>>9<<4)]=s,t.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var e=s.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=s._createHelper(r),t.HmacSHA256=s._createHmacHelper(r)}(Math),m=(f=S).enc.Utf8,f.algo.HMAC=f.lib.Base.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=m.parse(t));var n=e.blockSize,s=4*n;t.sigBytes>s&&(t=e.finalize(t)),t.clamp();for(var r=this._oKey=t.clone(),i=this._iKey=t.clone(),a=r.words,o=i.words,c=0;c>>2]>>>24-r%4*8&255)<<16|(t[r+1>>>2]>>>24-(r+1)%4*8&255)<<8|t[r+2>>>2]>>>24-(r+2)%4*8&255,a=0;4>a&&r+.75*a>>6*(3-a)&63));if(t=s.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var t=e.length,n=this._map;(s=n.charAt(64))&&-1!=(s=e.indexOf(s))&&(t=s);for(var s=[],r=0,i=0;i>>6-i%4*2;s[r>>>2]|=(a|o)<<24-r%4*8,r++}return v.create(s,r)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},function(e){function t(e,t,n,s,r,i,a){return((e=e+(t&n|~t&s)+r+a)<>>32-i)+t}function n(e,t,n,s,r,i,a){return((e=e+(t&s|n&~s)+r+a)<>>32-i)+t}function s(e,t,n,s,r,i,a){return((e=e+(t^n^s)+r+a)<>>32-i)+t}function r(e,t,n,s,r,i,a){return((e=e+(n^(t|~s))+r+a)<>>32-i)+t}for(var i=S,a=(c=i.lib).WordArray,o=c.Hasher,c=i.algo,u=[],l=0;64>l;l++)u[l]=4294967296*e.abs(e.sin(l+1))|0;c=c.MD5=o.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,i){for(var a=0;16>a;a++){var o=e[c=i+a];e[c]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8)}a=this._hash.words;var c=e[i+0],l=(o=e[i+1],e[i+2]),h=e[i+3],d=e[i+4],p=e[i+5],g=e[i+6],y=e[i+7],f=e[i+8],m=e[i+9],b=e[i+10],v=e[i+11],w=e[i+12],S=e[i+13],E=e[i+14],O=e[i+15],k=t(k=a[0],P=a[1],N=a[2],C=a[3],c,7,u[0]),C=t(C,k,P,N,o,12,u[1]),N=t(N,C,k,P,l,17,u[2]),P=t(P,N,C,k,h,22,u[3]);k=t(k,P,N,C,d,7,u[4]),C=t(C,k,P,N,p,12,u[5]),N=t(N,C,k,P,g,17,u[6]),P=t(P,N,C,k,y,22,u[7]),k=t(k,P,N,C,f,7,u[8]),C=t(C,k,P,N,m,12,u[9]),N=t(N,C,k,P,b,17,u[10]),P=t(P,N,C,k,v,22,u[11]),k=t(k,P,N,C,w,7,u[12]),C=t(C,k,P,N,S,12,u[13]),N=t(N,C,k,P,E,17,u[14]),k=n(k,P=t(P,N,C,k,O,22,u[15]),N,C,o,5,u[16]),C=n(C,k,P,N,g,9,u[17]),N=n(N,C,k,P,v,14,u[18]),P=n(P,N,C,k,c,20,u[19]),k=n(k,P,N,C,p,5,u[20]),C=n(C,k,P,N,b,9,u[21]),N=n(N,C,k,P,O,14,u[22]),P=n(P,N,C,k,d,20,u[23]),k=n(k,P,N,C,m,5,u[24]),C=n(C,k,P,N,E,9,u[25]),N=n(N,C,k,P,h,14,u[26]),P=n(P,N,C,k,f,20,u[27]),k=n(k,P,N,C,S,5,u[28]),C=n(C,k,P,N,l,9,u[29]),N=n(N,C,k,P,y,14,u[30]),k=s(k,P=n(P,N,C,k,w,20,u[31]),N,C,p,4,u[32]),C=s(C,k,P,N,f,11,u[33]),N=s(N,C,k,P,v,16,u[34]),P=s(P,N,C,k,E,23,u[35]),k=s(k,P,N,C,o,4,u[36]),C=s(C,k,P,N,d,11,u[37]),N=s(N,C,k,P,y,16,u[38]),P=s(P,N,C,k,b,23,u[39]),k=s(k,P,N,C,S,4,u[40]),C=s(C,k,P,N,c,11,u[41]),N=s(N,C,k,P,h,16,u[42]),P=s(P,N,C,k,g,23,u[43]),k=s(k,P,N,C,m,4,u[44]),C=s(C,k,P,N,w,11,u[45]),N=s(N,C,k,P,O,16,u[46]),k=r(k,P=s(P,N,C,k,l,23,u[47]),N,C,c,6,u[48]),C=r(C,k,P,N,y,10,u[49]),N=r(N,C,k,P,E,15,u[50]),P=r(P,N,C,k,p,21,u[51]),k=r(k,P,N,C,w,6,u[52]),C=r(C,k,P,N,h,10,u[53]),N=r(N,C,k,P,b,15,u[54]),P=r(P,N,C,k,o,21,u[55]),k=r(k,P,N,C,f,6,u[56]),C=r(C,k,P,N,O,10,u[57]),N=r(N,C,k,P,g,15,u[58]),P=r(P,N,C,k,S,21,u[59]),k=r(k,P,N,C,d,6,u[60]),C=r(C,k,P,N,v,10,u[61]),N=r(N,C,k,P,l,15,u[62]),P=r(P,N,C,k,m,21,u[63]);a[0]=a[0]+k|0,a[1]=a[1]+P|0,a[2]=a[2]+N|0,a[3]=a[3]+C|0},_doFinalize:function(){var t=this._data,n=t.words,s=8*this._nDataBytes,r=8*t.sigBytes;n[r>>>5]|=128<<24-r%32;var i=e.floor(s/4294967296);for(n[15+(r+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),n[14+(r+64>>>9<<4)]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),t.sigBytes=4*(n.length+1),this._process(),n=(t=this._hash).words,s=0;4>s;s++)r=n[s],n[s]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8);return t},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}}),i.MD5=o._createHelper(c),i.HmacMD5=o._createHmacHelper(c)}(Math),function(){var e,t=S,n=(e=t.lib).Base,s=e.WordArray,r=(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=(o=this.cfg).hasher.create(),r=s.create(),i=r.words,a=o.keySize,o=o.iterations;i.length>>2]}},e.BlockCipher=a.extend({cfg:a.cfg.extend({mode:o,padding:u}),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 l=e.CipherParams=t.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),h=(o=(d.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?n.create([1398893684,1701076831]).concat(e).concat(t):t).toString(r)},parse:function(e){var t=(e=r.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var s=n.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return l.create({ciphertext:e,salt:s})}},e.SerializableCipher=t.extend({cfg:t.extend({format:o}),encrypt:function(e,t,n,s){s=this.cfg.extend(s);var r=e.createEncryptor(n,s);return t=r.finalize(t),r=r.cfg,l.create({ciphertext:t,key:n,iv:r.iv,algorithm:e,mode:r.mode,padding:r.padding,blockSize:e.blockSize,formatter:s.format})},decrypt:function(e,t,n,s){return s=this.cfg.extend(s),t=this._parse(t,s.format),e.createDecryptor(n,s).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),d=(d.kdf={}).OpenSSL={execute:function(e,t,s,r){return r||(r=n.random(8)),e=i.create({keySize:t+s}).compute(e,r),s=n.create(e.words.slice(t),4*s),e.sigBytes=4*t,l.create({key:e,iv:s,salt:r})}},p=e.PasswordBasedCipher=h.extend({cfg:h.cfg.extend({kdf:d}),encrypt:function(e,t,n,s){return n=(s=this.cfg.extend(s)).kdf.execute(n,e.keySize,e.ivSize),s.iv=n.iv,(e=h.encrypt.call(this,e,t,n.key,s)).mixIn(n),e},decrypt:function(e,t,n,s){return s=this.cfg.extend(s),t=this._parse(t,s.format),n=s.kdf.execute(n,e.keySize,e.ivSize,t.salt),s.iv=n.iv,h.decrypt.call(this,e,t,n.key,s)}})}(),function(){for(var e=S,t=e.lib.BlockCipher,n=e.algo,s=[],r=[],i=[],a=[],o=[],c=[],u=[],l=[],h=[],d=[],p=[],g=0;256>g;g++)p[g]=128>g?g<<1:g<<1^283;var y=0,f=0;for(g=0;256>g;g++){var m=(m=f^f<<1^f<<2^f<<3^f<<4)>>>8^255&m^99;s[y]=m,r[m]=y;var b=p[y],v=p[b],w=p[v],E=257*p[m]^16843008*m;i[y]=E<<24|E>>>8,a[y]=E<<16|E>>>16,o[y]=E<<8|E>>>24,c[y]=E,E=16843009*w^65537*v^257*b^16843008*y,u[m]=E<<24|E>>>8,l[m]=E<<16|E>>>16,h[m]=E<<8|E>>>24,d[m]=E,y?(y=b^p[p[p[w^b]]],f^=p[p[f]]):y=f=1}var O=[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),r=this._keySchedule=[],i=0;i>>24]<<24|s[a>>>16&255]<<16|s[a>>>8&255]<<8|s[255&a]):(a=s[(a=a<<8|a>>>24)>>>24]<<24|s[a>>>16&255]<<16|s[a>>>8&255]<<8|s[255&a],a^=O[i/t|0]<<24),r[i]=r[i-t]^a}for(e=this._invKeySchedule=[],t=0;tt||4>=i?a:u[s[a>>>24]]^l[s[a>>>16&255]]^h[s[a>>>8&255]]^d[s[255&a]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,i,a,o,c,s)},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,u,l,h,d,r),n=e[t+1],e[t+1]=e[t+3],e[t+3]=n},_doCryptBlock:function(e,t,n,s,r,i,a,o){for(var c=this._nRounds,u=e[t]^n[0],l=e[t+1]^n[1],h=e[t+2]^n[2],d=e[t+3]^n[3],p=4,g=1;g>>24]^r[l>>>16&255]^i[h>>>8&255]^a[255&d]^n[p++],f=s[l>>>24]^r[h>>>16&255]^i[d>>>8&255]^a[255&u]^n[p++],m=s[h>>>24]^r[d>>>16&255]^i[u>>>8&255]^a[255&l]^n[p++];d=s[d>>>24]^r[u>>>16&255]^i[l>>>8&255]^a[255&h]^n[p++],u=y,l=f,h=m}y=(o[u>>>24]<<24|o[l>>>16&255]<<16|o[h>>>8&255]<<8|o[255&d])^n[p++],f=(o[l>>>24]<<24|o[h>>>16&255]<<16|o[d>>>8&255]<<8|o[255&u])^n[p++],m=(o[h>>>24]<<24|o[d>>>16&255]<<16|o[u>>>8&255]<<8|o[255&l])^n[p++],d=(o[d>>>24]<<24|o[u>>>16&255]<<16|o[l>>>8&255]<<8|o[255&h])^n[p++],e[t]=y,e[t+1]=f,e[t+2]=m,e[t+3]=d},keySize:8});e.AES=t._createHelper(n)}(),S.mode.ECB=((w=S.lib.BlockCipherMode.extend()).Encryptor=w.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),w.Decryptor=w.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),w);var E=t(S);class O{constructor({cipherKey:e}){this.cipherKey=e,this.CryptoJS=E,this.encryptedKey=this.CryptoJS.SHA256(e)}encrypt(e){if(0===("string"==typeof e?e:O.decoder.decode(e)).length)throw new Error("encryption error. empty content");const t=this.getIv();return{metadata:t,data:c(this.CryptoJS.AES.encrypt(e,this.encryptedKey,{iv:this.bufferToWordArray(t),mode:this.CryptoJS.mode.CBC}).ciphertext.toString(this.CryptoJS.enc.Base64))}}encryptFileData(e){return i(this,void 0,void 0,(function*(){const t=yield this.getKey(),n=this.getIv();return{data:yield crypto.subtle.encrypt({name:this.algo,iv:n},t,e),metadata:n}}))}decrypt(e){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=this.bufferToWordArray(new Uint8ClampedArray(e.metadata)),n=this.bufferToWordArray(new Uint8ClampedArray(e.data));return O.encoder.encode(this.CryptoJS.AES.decrypt({ciphertext:n},this.encryptedKey,{iv:t,mode:this.CryptoJS.mode.CBC}).toString(this.CryptoJS.enc.Utf8)).buffer}decryptFileData(e){return i(this,void 0,void 0,(function*(){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=yield this.getKey();return crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)}))}get identifier(){return"ACRH"}get algo(){return"AES-CBC"}getIv(){return crypto.getRandomValues(new Uint8Array(O.BLOCK_SIZE))}getKey(){return i(this,void 0,void 0,(function*(){const e=O.encoder.encode(this.cipherKey),t=yield crypto.subtle.digest("SHA-256",e.buffer);return crypto.subtle.importKey("raw",t,this.algo,!0,["encrypt","decrypt"])}))}bufferToWordArray(e){const t=[];let n;for(n=0;ne.toString(16).padStart(2,"0"))).join(""),s=N.encoder.encode(n.slice(0,32)).buffer;return crypto.subtle.importKey("raw",s,"AES-CBC",!0,["encrypt","decrypt"])}))}concatArrayBuffer(e,t){const n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}}N.IV_LENGTH=16,N.encoder=new TextEncoder,N.decoder=new TextDecoder;class P{constructor(e){this.config=e,this.cryptor=new C(Object.assign({},e)),this.fileCryptor=new N}encrypt(e){const t="string"==typeof e?e:P.decoder.decode(e);return{data:this.cryptor.encrypt(t),metadata:null}}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var n;if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.encryptFile(null===(n=this.config)||void 0===n?void 0:n.cipherKey,e,t)}))}decrypt(e){const t="string"==typeof e.data?e.data:u(e.data);return this.cryptor.decrypt(t)}decryptFile(e,t){return i(this,void 0,void 0,(function*(){if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.decryptFile(this.config.cipherKey,e,t)}))}get identifier(){return""}}P.encoder=new TextEncoder,P.decoder=new TextDecoder;class M extends a{static legacyCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new M({default:new P(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t})),cryptors:[new O({cipherKey:e.cipherKey})]})}static aesCbcCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new M({default:new O({cipherKey:e.cipherKey}),cryptors:[new P(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t}))]})}static withDefaultCryptor(e){return new this({default:e})}encrypt(e){const t=e instanceof ArrayBuffer&&this.defaultCryptor.identifier===M.LEGACY_IDENTIFIER?this.defaultCryptor.encrypt(M.decoder.decode(e)):this.defaultCryptor.encrypt(e);if(!t.metadata)return t.data;if("string"==typeof t.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");const n=this.getHeaderData(t);return this.concatArrayBuffer(n,t.data)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){if(this.defaultCryptor.identifier===_.LEGACY_IDENTIFIER)return this.defaultCryptor.encryptFile(e,t);const n=yield this.getFileData(e),s=yield this.defaultCryptor.encryptFileData(n);if("string"==typeof s.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");return t.create({name:e.name,mimeType:"application/octet-stream",data:this.concatArrayBuffer(this.getHeaderData(s),s.data)})}))}decrypt(e){const t="string"==typeof e?c(e):e,n=_.tryParse(t),s=this.getCryptor(n),r=n.length>0?t.slice(n.length-n.metadataLength,n.length):null;if(t.slice(n.length).byteLength<=0)throw new Error("Decryption error: empty content");return s.decrypt({data:t.slice(n.length),metadata:r})}decryptFile(e,t){return i(this,void 0,void 0,(function*(){const n=yield e.data.arrayBuffer(),s=_.tryParse(n),r=this.getCryptor(s);if((null==r?void 0:r.identifier)===_.LEGACY_IDENTIFIER)return r.decryptFile(e,t);const i=(yield this.getFileData(n)).slice(s.length-s.metadataLength,s.length);return t.create({name:e.name,data:yield this.defaultCryptor.decryptFileData({data:n.slice(s.length),metadata:i})})}))}getCryptorFromId(e){const t=this.getAllCryptors().find((t=>e===t.identifier));if(t)return t;throw Error("Unknown cryptor error")}getCryptor(e){if("string"==typeof e){const t=this.getAllCryptors().find((t=>t.identifier===e));if(t)return t;throw new Error("Unknown cryptor error")}if(e instanceof A)return this.getCryptorFromId(e.identifier)}getHeaderData(e){if(!e.metadata)return;const t=_.from(this.defaultCryptor.identifier,e.metadata),n=new Uint8Array(t.length);let s=0;return n.set(t.data,s),s+=t.length-e.metadata.byteLength,n.set(new Uint8Array(e.metadata),s),n.buffer}concatArrayBuffer(e,t){const n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}getFileData(e){return i(this,void 0,void 0,(function*(){if(e instanceof ArrayBuffer)return e;if(e instanceof o)return e.toArrayBuffer();throw new Error("Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob")}))}}M.LEGACY_IDENTIFIER="";class _{static from(e,t){if(e!==_.LEGACY_IDENTIFIER)return new A(e,t.byteLength)}static tryParse(e){const t=new Uint8Array(e);let n,s,r=null;if(t.byteLength>=4&&(n=t.slice(0,4),this.decoder.decode(n)!==_.SENTINEL))return M.LEGACY_IDENTIFIER;if(!(t.byteLength>=5))throw new Error("Decryption error: invalid header version");if(r=t[4],r>_.MAX_VERSION)throw new Error("Decryption error: Unknown cryptor error");let i=5+_.IDENTIFIER_LENGTH;if(!(t.byteLength>=i))throw new Error("Decryption error: invalid crypto identifier");s=t.slice(5,i);let a=null;if(!(t.byteLength>=i+1))throw new Error("Decryption error: invalid metadata length");return a=t[i],i+=1,255===a&&t.byteLength>=i+2&&(a=new Uint16Array(t.slice(i,i+2)).reduce(((e,t)=>(e<<8)+t),0)),new A(this.decoder.decode(s),a)}}_.SENTINEL="PNED",_.LEGACY_IDENTIFIER="",_.IDENTIFIER_LENGTH=4,_.VERSION=1,_.MAX_VERSION=1,_.decoder=new TextDecoder;class A{constructor(e,t){this._identifier=e,this._metadataLength=t}get identifier(){return this._identifier}set identifier(e){this._identifier=e}get metadataLength(){return this._metadataLength}set metadataLength(e){this._metadataLength=e}get version(){return _.VERSION}get length(){return _.SENTINEL.length+1+_.IDENTIFIER_LENGTH+(this.metadataLength<255?1:3)+this.metadataLength}get data(){let e=0;const t=new Uint8Array(this.length),n=new TextEncoder;t.set(n.encode(_.SENTINEL)),e+=_.SENTINEL.length,t[e]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e);const s=this.metadataLength;return e+=_.IDENTIFIER_LENGTH,s<255?t[e]=s:t.set([255,s>>8,255&s],e),t}}A.IDENTIFIER_LENGTH=4,A.SENTINEL="PNED";class j extends Error{static create(e,t){return e instanceof Error?j.createFromError(e):j.createFromServiceResponse(e,t)}static createFromError(e){let t=h.PNUnknownCategory,n="Unknown error",s="Error";if(!e)return new j(n,t,0);if(e instanceof j)return e;if(e instanceof Error&&(n=e.message,s=e.name),"AbortError"===s||-1!==n.indexOf("Aborted"))t=h.PNCancelledCategory,n="Request cancelled";else if(-1!==n.toLowerCase().indexOf("timeout"))t=h.PNTimeoutCategory,n="Request timeout";else if(-1!==n.toLowerCase().indexOf("network"))t=h.PNNetworkIssuesCategory,n="Network issues";else if("TypeError"===s)t=-1!==n.indexOf("Load failed")||-1!=n.indexOf("Failed to fetch")?h.PNNetworkIssuesCategory:h.PNBadRequestCategory;else if("FetchError"===s){const s=e.code;["ECONNREFUSED","ENETUNREACH","ENOTFOUND","ECONNRESET","EAI_AGAIN"].includes(s)&&(t=h.PNNetworkIssuesCategory),"ECONNREFUSED"===s?n="Connection refused":"ENETUNREACH"===s?n="Network not reachable":"ENOTFOUND"===s?n="Server not found":"ECONNRESET"===s?n="Connection reset by peer":"EAI_AGAIN"===s?n="Name resolution error":"ETIMEDOUT"===s?(t=h.PNTimeoutCategory,n="Request timeout"):n=`Unknown system error: ${e}`}else"Request timeout"===n&&(t=h.PNTimeoutCategory);return new j(n,t,0,e)}static createFromServiceResponse(e,t){let n,s=h.PNUnknownCategory,r="Unknown error",{status:i}=e;if(null!=t||(t=e.body),402===i?r="Not available for used key set. Contact support@pubnub.com":400===i?(s=h.PNBadRequestCategory,r="Bad request"):403===i&&(s=h.PNAccessDeniedCategory,r="Access denied"),t&&t.byteLength>0){const s=(new TextDecoder).decode(t);if(-1!==e.headers["content-type"].indexOf("text/javascript")||-1!==e.headers["content-type"].indexOf("application/json"))try{const e=JSON.parse(s);"object"==typeof e&&(Array.isArray(e)?"number"==typeof e[0]&&0===e[0]&&e.length>1&&"string"==typeof e[1]&&(n=e[1]):("error"in e&&(1===e.error||!0===e.error)&&"status"in e&&"number"==typeof e.status&&"message"in e&&"service"in e?(n=e,i=e.status):n=e,"error"in e&&e.error instanceof Error&&(n=e.error)))}catch(e){n=s}else if(-1!==e.headers["content-type"].indexOf("xml")){const e=/(.*)<\/Message>/gi.exec(s);r=e?`Upload to bucket failed: ${e[1]}`:"Upload to bucket failed."}else n=s}return new j(r,s,i,n)}constructor(e,t,n,s){super(e),this.category=t,this.statusCode=n,this.errorData=s,this.name="PubNubAPIError"}toStatus(e){return{error:!0,category:this.category,operation:e,statusCode:this.statusCode,errorData:this.errorData}}toPubNubError(e,t){return new d(null!=t?t:this.message,this.toStatus(e))}}class I{constructor(e){this.configuration=e,this.subscriptionWorkerReady=!1,this.workerEventsQueue=[],this.callbacks=new Map,this.setupSubscriptionWorker()}makeSendable(e){if(!e.path.startsWith("/v2/subscribe")&&!e.path.endsWith("/heartbeat")&&!e.path.endsWith("/leave"))return this.configuration.transport.makeSendable(e);let t;const n={type:"send-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,request:e};return e.cancellable&&(t={abort:()=>{const t={type:"cancel-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,identifier:e.identifier};this.scheduleEventPost(t)}}),[new Promise(((t,s)=>{this.callbacks.set(e.identifier,{resolve:t,reject:s}),this.scheduleEventPost(n)})),t]}request(e){return e}scheduleEventPost(e,t=!1){const n=this.sharedSubscriptionWorker;n?n.port.postMessage(e):t?this.workerEventsQueue.splice(0,0,e):this.workerEventsQueue.push(e)}flushScheduledEvents(){const e=this.sharedSubscriptionWorker;if(!e||0===this.workerEventsQueue.length)return;const t=[];for(let e=0;e!t.includes(e))),this.workerEventsQueue.forEach((t=>e.port.postMessage(t))),this.workerEventsQueue=[]}get sharedSubscriptionWorker(){return this.subscriptionWorkerReady?this.subscriptionWorker:null}setupSubscriptionWorker(){"undefined"!=typeof SharedWorker&&(this.subscriptionWorker=new SharedWorker(this.configuration.workerUrl,`/pubnub-${this.configuration.sdkVersion}`),this.subscriptionWorker.port.start(),this.scheduleEventPost({type:"client-register",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,heartbeatInterval:this.configuration.heartbeatInterval,logVerbosity:this.configuration.logVerbosity,workerLogVerbosity:this.configuration.workerLogVerbosity},!0),this.subscriptionWorker.port.onmessage=e=>this.handleWorkerEvent(e))}handleWorkerEvent(e){const{data:t}=e;if("shared-worker-ping"===t.type||"shared-worker-connected"===t.type||"shared-worker-console-log"===t.type||"shared-worker-console-dir"===t.type||t.clientIdentifier===this.configuration.clientIdentifier)if("shared-worker-connected"===t.type)this.subscriptionWorkerReady=!0,this.flushScheduledEvents();else if("shared-worker-console-log"===t.type)console.log(`[SharedWorker] ${t.message}`);else if("shared-worker-console-dir"===t.type)t.message&&console.log(`[SharedWorker] ${t.message}`),console.dir(t.data,{depth:10});else if("shared-worker-ping"===t.type){const{logVerbosity:e,subscriptionKey:t,clientIdentifier:n}=this.configuration;this.scheduleEventPost({type:"client-pong",subscriptionKey:t,clientIdentifier:n,logVerbosity:e})}else if("request-progress-start"===t.type||"request-progress-end"===t.type)this.logRequestProgress(t);else if("request-process-success"===t.type||"request-process-error"===t.type){const{resolve:e,reject:n}=this.callbacks.get(t.identifier);if("request-process-success"===t.type)e({status:t.response.status,url:t.url,headers:t.response.headers,body:t.response.body});else{let e=h.PNUnknownCategory,s="Unknown error";if(t.error)"NETWORK_ISSUE"===t.error.type?e=h.PNNetworkIssuesCategory:"TIMEOUT"===t.error.type?e=h.PNTimeoutCategory:"ABORTED"===t.error.type&&(e=h.PNCancelledCategory),s=`${t.error.message} (${t.identifier})`;else if(t.response)return n(j.create({url:t.url,headers:t.response.headers,body:t.response.body,status:t.response.status},t.response.body));n(new j(s,e,0,new Error(s)))}}}logRequestProgress(e){var t,n;"request-progress-start"===e.type?(console.log("<<<<<"),console.log(`[${e.timestamp}] ${e.url}\n${JSON.stringify(null!==(t=e.query)&&void 0!==t?t:{})}`),console.log("-----")):(console.log(">>>>>>"),console.log(`[${e.timestamp} / ${e.duration}] ${e.url}\n${JSON.stringify(null!==(n=e.query)&&void 0!==n?n:{})}\n${e.response}`),console.log("-----"))}}function F(e){const t=e=>"object"==typeof e&&null!==e&&e.constructor===Object,n=e=>"number"==typeof e&&isFinite(e);if(!t(e))return e;const s={};return Object.keys(e).forEach((r=>{const i=(e=>"string"==typeof e||e instanceof String)(r);let a=r;const o=e[r];if(i&&r.indexOf(",")>=0){a=r.split(",").map(Number).reduce(((e,t)=>e+String.fromCharCode(t)),"")}else(n(r)||i&&!isNaN(Number(r)))&&(a=String.fromCharCode(n(r)?r:parseInt(r,10)));s[a]=t(o)?F(o):o})),s}const T=e=>{var t,n,s,r;return e.subscriptionWorkerUrl&&"undefined"==typeof SharedWorker&&(e.subscriptionWorkerUrl=null),Object.assign(Object.assign({},(e=>{var t,n,s,r,i,a,o,c,u,l,h,p,g,y,f;const m=Object.assign({},e);if(null!==(t=m.logVerbosity)&&void 0!==t||(m.logVerbosity=!1),null!==(n=m.ssl)&&void 0!==n||(m.ssl=!0),null!==(s=m.transactionalRequestTimeout)&&void 0!==s||(m.transactionalRequestTimeout=15),null!==(r=m.subscribeRequestTimeout)&&void 0!==r||(m.subscribeRequestTimeout=310),null!==(i=m.fileRequestTimeout)&&void 0!==i||(m.fileRequestTimeout=300),null!==(a=m.restore)&&void 0!==a||(m.restore=!1),null!==(o=m.useInstanceId)&&void 0!==o||(m.useInstanceId=!1),null!==(c=m.suppressLeaveEvents)&&void 0!==c||(m.suppressLeaveEvents=!1),null!==(u=m.requestMessageCountThreshold)&&void 0!==u||(m.requestMessageCountThreshold=100),null!==(l=m.autoNetworkDetection)&&void 0!==l||(m.autoNetworkDetection=!1),null!==(h=m.enableEventEngine)&&void 0!==h||(m.enableEventEngine=!1),null!==(p=m.maintainPresenceState)&&void 0!==p||(m.maintainPresenceState=!0),null!==(g=m.keepAlive)&&void 0!==g||(m.keepAlive=!1),m.userId&&m.uuid)throw new d("PubNub client configuration error: use only 'userId'");if(null!==(y=m.userId)&&void 0!==y||(m.userId=m.uuid),!m.userId)throw new d("PubNub client configuration error: 'userId' not set");if(0===(null===(f=m.userId)||void 0===f?void 0:f.trim().length))throw new d("PubNub client configuration error: 'userId' is empty");m.origin||(m.origin=Array.from({length:20},((e,t)=>`ps${t+1}.pndsn.com`)));const b={subscribeKey:m.subscribeKey,publishKey:m.publishKey,secretKey:m.secretKey};void 0!==m.presenceTimeout&&m.presenceTimeout<20&&(m.presenceTimeout=20,console.log("WARNING: Presence timeout is less than the minimum. Using minimum value: ",20)),void 0!==m.presenceTimeout?m.heartbeatInterval=m.presenceTimeout/2-1:m.presenceTimeout=300;let v=!1,w=!0,S=5,E=!1,O=100,k=!0;return void 0!==m.dedupeOnSubscribe&&"boolean"==typeof m.dedupeOnSubscribe&&(E=m.dedupeOnSubscribe),void 0!==m.maximumCacheSize&&"number"==typeof m.maximumCacheSize&&(O=m.maximumCacheSize),void 0!==m.useRequestId&&"boolean"==typeof m.useRequestId&&(k=m.useRequestId),void 0!==m.announceSuccessfulHeartbeats&&"boolean"==typeof m.announceSuccessfulHeartbeats&&(v=m.announceSuccessfulHeartbeats),void 0!==m.announceFailedHeartbeats&&"boolean"==typeof m.announceFailedHeartbeats&&(w=m.announceFailedHeartbeats),void 0!==m.fileUploadPublishRetryLimit&&"number"==typeof m.fileUploadPublishRetryLimit&&(S=m.fileUploadPublishRetryLimit),Object.assign(Object.assign({},m),{keySet:b,dedupeOnSubscribe:E,maximumCacheSize:O,useRequestId:k,announceSuccessfulHeartbeats:v,announceFailedHeartbeats:w,fileUploadPublishRetryLimit:S})})(e)),{listenToBrowserNetworkEvents:null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t,subscriptionWorkerUrl:e.subscriptionWorkerUrl,subscriptionWorkerLogVerbosity:null!==(n=e.subscriptionWorkerLogVerbosity)&&void 0!==n&&n,transport:null!==(s=e.transport)&&void 0!==s?s:"fetch",keepAlive:null===(r=e.keepAlive)||void 0===r||r})};var R={exports:{}}; +/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */!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 s(){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 r(e,t){var s=n[t||"all"];return s&&s.test(e)||!1}s.isUUID=r,s.VERSION=t,e.uuid=s,e.isUUID=r}(t),null!==e&&(e.exports=t.uuid)}(R,R.exports);var U=t(R.exports),x={createUUID:()=>U.uuid?U.uuid():U()};const D=(e,t)=>{var n,s,r;null===(n=e.retryConfiguration)||void 0===n||n.validate(),null!==(s=e.useRandomIVs)&&void 0!==s||(e.useRandomIVs=true),e.origin=q(null!==(r=e.ssl)&&void 0!==r&&r,e.origin);const i=e.cryptoModule;i&&delete e.cryptoModule;const a=Object.assign(Object.assign({},e),{_pnsdkSuffix:{},_instanceId:`pn-${x.createUUID()}`,_cryptoModule:void 0,_cipherKey:void 0,_setupCryptoModule:t,get instanceId(){if(this.useInstanceId)return this._instanceId},getInstanceId(){if(this.useInstanceId)return this._instanceId},getUserId(){return this.userId},setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this.userId=e},getAuthKey(){return this.authKey},setAuthKey(e){this.authKey=e},getFilterExpression(){return this.filterExpression},setFilterExpression(e){this.filterExpression=e},getCipherKey(){return this._cipherKey},setCipherKey(t){this._cipherKey=t,t||!this._cryptoModule?t&&this._setupCryptoModule&&(this._cryptoModule=this._setupCryptoModule({cipherKey:t,useRandomIVs:e.useRandomIVs,customEncrypt:this.getCustomEncrypt(),customDecrypt:this.getCustomDecrypt()})):this._cryptoModule=void 0},getCryptoModule(){return this._cryptoModule},getUseRandomIVs:()=>e.useRandomIVs,setPresenceTimeout(e){this.heartbeatInterval=e/2-1,this.presenceTimeout=e},getPresenceTimeout(){return this.presenceTimeout},getHeartbeatInterval(){return this.heartbeatInterval},setHeartbeatInterval(e){this.heartbeatInterval=e},getTransactionTimeout(){return this.transactionalRequestTimeout},getSubscribeTimeout(){return this.subscribeRequestTimeout},getFileTimeout(){return this.fileRequestTimeout},get PubNubFile(){return e.PubNubFile},get version(){return"8.8.1"},getVersion(){return this.version},_addPnsdkSuffix(e,t){this._pnsdkSuffix[e]=`${t}`},_getPnsdkSuffix(e){const t=Object.values(this._pnsdkSuffix).join(e);return t.length>0?e+t:""},getUUID(){return this.getUserId()},setUUID(e){this.setUserId(e)},getCustomEncrypt:()=>e.customEncrypt,getCustomDecrypt:()=>e.customDecrypt});return e.cipherKey?a.setCipherKey(e.cipherKey):i&&(a._cryptoModule=i),a},q=(e,t)=>{const n=e?"https://":"http://";return"string"==typeof t?`${n}${t}`:`${n}${t[Math.floor(Math.random()*t.length)]}`};class G{constructor(e){this.cbor=e}setToken(e){e&&e.length>0?this.token=e:this.token=void 0}getToken(){return this.token}parseToken(e){const t=this.cbor.decodeToken(e);if(void 0!==t){const e=t.res.uuid?Object.keys(t.res.uuid):[],n=Object.keys(t.res.chan),s=Object.keys(t.res.grp),r=t.pat.uuid?Object.keys(t.pat.uuid):[],i=Object.keys(t.pat.chan),a=Object.keys(t.pat.grp),o={version:t.v,timestamp:t.t,ttl:t.ttl,authorized_uuid:t.uuid,signature:t.sig},c=e.length>0,u=n.length>0,l=s.length>0;if(c||u||l){if(o.resources={},c){const n=o.resources.uuids={};e.forEach((e=>n[e]=this.extractPermissions(t.res.uuid[e])))}if(u){const e=o.resources.channels={};n.forEach((n=>e[n]=this.extractPermissions(t.res.chan[n])))}if(l){const e=o.resources.groups={};s.forEach((n=>e[n]=this.extractPermissions(t.res.grp[n])))}}const h=r.length>0,d=i.length>0,p=a.length>0;if(h||d||p){if(o.patterns={},h){const e=o.patterns.uuids={};r.forEach((n=>e[n]=this.extractPermissions(t.pat.uuid[n])))}if(d){const e=o.patterns.channels={};i.forEach((n=>e[n]=this.extractPermissions(t.pat.chan[n])))}if(p){const e=o.patterns.groups={};a.forEach((n=>e[n]=this.extractPermissions(t.pat.grp[n])))}}return t.meta&&Object.keys(t.meta).length>0&&(o.meta=t.meta),o}}extractPermissions(e){const t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128&~e||(t.join=!0),64&~e||(t.update=!0),32&~e||(t.get=!0),8&~e||(t.delete=!0),4&~e||(t.manage=!0),2&~e||(t.write=!0),1&~e||(t.read=!0),t}}var K;!function(e){e.GET="GET",e.POST="POST",e.PATCH="PATCH",e.DELETE="DELETE",e.LOCAL="LOCAL"}(K||(K={}));const $=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),L=(e,t)=>{const n=e.map((e=>$(e)));return n.length?n.join(","):null!=t?t:""},B=(e,t)=>{const n=Object.fromEntries(t.map((e=>[e,!1])));return e.filter((e=>!(t.includes(e)&&!n[e])||(n[e]=!0,!1)))},H=(e,t)=>[...e].filter((n=>t.includes(n)&&e.indexOf(n)===e.lastIndexOf(n)&&t.indexOf(n)===t.lastIndexOf(n)));class V{constructor(e,t,n){this.publishKey=e,this.secretKey=t,this.hasher=n}signature(e){const t=e.path.startsWith("/publish")?K.GET:e.method;let n=`${t}\n${this.publishKey}\n${e.path}\n${this.queryParameters(e.queryParameters)}\n`;if(t===K.POST||t===K.PATCH){const t=e.body;let s;t&&t instanceof ArrayBuffer?s=V.textDecoder.decode(t):t&&"object"!=typeof t&&(s=t),s&&(n+=s)}return`v2.${this.hasher(n,this.secretKey)}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}queryParameters(e){return Object.keys(e).sort().map((t=>{const n=e[t];return Array.isArray(n)?n.sort().map((e=>`${t}=${$(e)}`)).join("&"):`${t}=${$(n)}`})).join("&")}}V.textDecoder=new TextDecoder("utf-8");class z{constructor(e){this.configuration=e;const{clientConfiguration:{keySet:t},shaHMAC:n}=e;t.secretKey&&n&&(this.signatureGenerator=new V(t.publishKey,t.secretKey,n))}makeSendable(e){return this.configuration.transport.makeSendable(this.request(e))}request(e){var t;const{clientConfiguration:n}=this.configuration;return(e=this.configuration.transport.request(e)).queryParameters||(e.queryParameters={}),n.useInstanceId&&(e.queryParameters.instanceid=n.getInstanceId()),e.queryParameters.uuid||(e.queryParameters.uuid=n.userId),n.useRequestId&&(e.queryParameters.requestid=e.identifier),e.queryParameters.pnsdk=this.generatePNSDK(),null!==(t=e.origin)&&void 0!==t||(e.origin=n.origin),this.authenticateRequest(e),this.signRequest(e),e}authenticateRequest(e){var t;if(e.path.startsWith("/v2/auth/")||e.path.startsWith("/v3/pam/")||e.path.startsWith("/time"))return;const{clientConfiguration:n,tokenManager:s}=this.configuration,r=null!==(t=s&&s.getToken())&&void 0!==t?t:n.authKey;r&&(e.queryParameters.auth=r)}signRequest(e){this.signatureGenerator&&!e.path.startsWith("/time")&&(e.queryParameters.timestamp=String(Math.floor((new Date).getTime()/1e3)),e.queryParameters.signature=this.signatureGenerator.signature(e))}generatePNSDK(){const{clientConfiguration:e}=this.configuration;if(e.sdkName)return e.sdkName;let t=`PubNub-JS-${e.sdkFamily}`;e.partnerId&&(t+=`-${e.partnerId}`),t+=`/${e.getVersion()}`;const n=e._getPnsdkSuffix(" ");return n.length>0&&(t+=n),t}}class W{constructor(e="fetch",t=!1,n=!1){if(this.transport=e,this.keepAlive=t,this.logVerbosity=n,"fetch"!==e||window&&window.fetch||(this.transport="xhr"),"fetch"===this.transport&&(W.originalFetch=fetch.bind(window),this.isFetchMonkeyPatched())){if(W.originalFetch=W.getOriginalFetch(),!n)return;console.warn("[PubNub] Native Web Fetch API 'fetch' function monkey patched."),this.isFetchMonkeyPatched(W.originalFetch)?console.warn("[PubNub] Unable receive native Web Fetch API. There can be issues with subscribe long-poll cancellation"):console.info("[PubNub] Use native Web Fetch API 'fetch' implementation from iframe as APM workaround.")}}makeSendable(e){const t=new AbortController,n={abortController:t,abort:e=>!t.signal.aborted&&t.abort(e)};return[this.webTransportRequestFromTransportRequest(e).then((t=>{const s=(new Date).getTime();return this.logRequestProcessProgress(t,e.body),this.sendRequest(t,n).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>{const n=e[1].byteLength>0?e[1]:void 0,{status:r,headers:i}=e[0],a={};i.forEach(((e,t)=>a[t]=e.toLowerCase()));const o={status:r,url:t.url,headers:a,body:n};if(r>=400)throw j.create(o);return this.logRequestProcessProgress(t,void 0,(new Date).getTime()-s,n),o})).catch((e=>{let t=e;if("string"==typeof e){const n=e.toLowerCase();n.includes("timeout")||!n.includes("cancel")?t=new Error(e):n.includes("cancel")&&(t=new DOMException("Aborted","AbortError"))}throw j.create(t)}))})),n]}request(e){return e}sendRequest(e,t){return i(this,void 0,void 0,(function*(){return"fetch"===this.transport?this.sendFetchRequest(e,t):this.sendXHRRequest(e,t)}))}sendFetchRequest(e,t){return i(this,void 0,void 0,(function*(){let n;const s=new Promise(((s,r)=>{n=setTimeout((()=>{clearTimeout(n),r(new Error("Request timeout")),t.abort("Cancel because of timeout")}),1e3*e.timeout)})),r=new Request(e.url,{method:e.method,headers:e.headers,redirect:"follow",body:e.body});return Promise.race([W.originalFetch(r,{signal:t.abortController.signal,credentials:"omit",cache:"no-cache"}).then((e=>(n&&clearTimeout(n),e))),s])}))}sendXHRRequest(e,t){return i(this,void 0,void 0,(function*(){return new Promise(((n,s)=>{var r;const i=new XMLHttpRequest;i.open(e.method,e.url,!0),i.responseType="arraybuffer",i.timeout=1e3*e.timeout,t.abortController.signal.onabort=()=>{i.readyState!=XMLHttpRequest.DONE&&i.readyState!=XMLHttpRequest.UNSENT&&i.abort()},Object.entries(null!==(r=e.headers)&&void 0!==r?r:{}).forEach((([e,t])=>i.setRequestHeader(e,t))),i.onabort=()=>s(new Error("Aborted")),i.ontimeout=()=>s(new Error("Request timeout")),i.onerror=()=>s(new Error("Request timeout")),i.onload=()=>{const e=new Headers;i.getAllResponseHeaders().split("\r\n").forEach((t=>{const[n,s]=t.split(": ");n.length>1&&s.length>1&&e.append(n,s)})),n(new Response(i.response,{status:i.status,headers:e,statusText:i.statusText}))},i.send(e.body)}))}))}webTransportRequestFromTransportRequest(e){return i(this,void 0,void 0,(function*(){let t,n=e.path;if(e.formData&&e.formData.length>0){e.queryParameters={};const n=e.body,s=new FormData;for(const{key:t,value:n}of e.formData)s.append(t,n);try{const e=yield n.toArrayBuffer();s.append("file",new Blob([e],{type:"application/octet-stream"}),n.name)}catch(e){try{const e=yield n.toFileUri();s.append("file",e,n.name)}catch(e){}}t=s}else e.body&&("string"==typeof e.body||e.body instanceof ArrayBuffer)&&(t=e.body);var s;return e.queryParameters&&0!==Object.keys(e.queryParameters).length&&(n=`${n}?${s=e.queryParameters,Object.keys(s).map((e=>{const t=s[e];return Array.isArray(t)?t.map((t=>`${e}=${$(t)}`)).join("&"):`${e}=${$(t)}`})).join("&")}`),{url:`${e.origin}${n}`,method:e.method,headers:e.headers,timeout:e.timeout,body:t}}))}logRequestProcessProgress(e,t,n,s){if(!this.logVerbosity)return;const{protocol:r,host:i,pathname:a,search:o}=new URL(e.url),c=(new Date).toISOString();if(n){let e=`[${c} / ${n}]\n${r}//${i}${a}\n${o}`;s&&(e+=`\n\n${W.decoder.decode(s)}`),console.log(">>>>>>"),console.log(e),console.log("-----")}else{let e=`[${c}]\n${r}//${i}${a}\n${o}`;t&&("string"==typeof t||t instanceof ArrayBuffer)&&(e+="string"==typeof t?`\n\n${t}`:`\n\n${W.decoder.decode(t)}`),console.log("<<<<<"),console.log(e),console.log("-----")}}isFetchMonkeyPatched(e){return!(null!=e?e:fetch).toString().includes("[native code]")&&"fetch"!==fetch.name}static getOriginalFetch(){let e=document.querySelector('iframe[name="pubnub-context-unpatched-fetch"]');return e||(e=document.createElement("iframe"),e.style.display="none",e.name="pubnub-context-unpatched-fetch",e.src="about:blank",document.body.appendChild(e)),e.contentWindow?e.contentWindow.fetch.bind(e.contentWindow):fetch}}W.decoder=new TextDecoder;class J{constructor(){this.listeners=[]}addListener(e){this.listeners.includes(e)||this.listeners.push(e)}removeListener(e){this.listeners=this.listeners.filter((t=>t!==e))}removeAllListeners(){this.listeners=[]}announceStatus(e){this.listeners.forEach((t=>{t.status&&t.status(e)}))}announcePresence(e){this.listeners.forEach((t=>{t.presence&&t.presence(e)}))}announceMessage(e){this.listeners.forEach((t=>{t.message&&t.message(e)}))}announceSignal(e){this.listeners.forEach((t=>{t.signal&&t.signal(e)}))}announceMessageAction(e){this.listeners.forEach((t=>{t.messageAction&&t.messageAction(e)}))}announceFile(e){this.listeners.forEach((t=>{t.file&&t.file(e)}))}announceObjects(e){this.listeners.forEach((t=>{t.objects&&t.objects(e)}))}announceNetworkUp(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkUpCategory})}))}announceNetworkDown(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkDownCategory})}))}announceUser(e){this.listeners.forEach((t=>{t.user&&t.user(e)}))}announceSpace(e){this.listeners.forEach((t=>{t.space&&t.space(e)}))}announceMembership(e){this.listeners.forEach((t=>{t.membership&&t.membership(e)}))}}class X{constructor(e){this.time=e}onReconnect(e){this.callback=e}startPolling(){this.timeTimer=setInterval((()=>this.callTime()),3e3)}stopPolling(){this.timeTimer&&clearInterval(this.timeTimer),this.timeTimer=null}callTime(){this.time((e=>{e.error||(this.stopPolling(),this.callback&&this.callback())}))}}class Q{constructor({maximumCacheSize:e}){this.maximumCacheSize=e,this.hashHistory=[]}getKey(e){var t;return`${e.timetoken}-${this.hashCode(JSON.stringify(null!==(t=e.message)&&void 0!==t?t:"")).toString()}`}isDuplicate(e){return this.hashHistory.includes(this.getKey(e))}addEntry(e){this.hashHistory.length>=this.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}clearHistory(){this.hashHistory=[]}hashCode(e){let t=0;if(0===e.length)return t;for(let n=0;n{this.pendingChannelSubscriptions.add(e),this.channels[e]={},r&&(this.presenceChannels[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannels[e]={})})),null==n||n.forEach((e=>{this.pendingChannelGroupSubscriptions.add(e),this.channelGroups[e]={},r&&(this.presenceChannelGroups[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannelGroups[e]={})})),this.subscriptionStatusAnnounced=!1,this.reconnect()}unsubscribe(e,t){let{channels:n,channelGroups:s}=e;const i=new Set,a=new Set;null==n||n.forEach((e=>{e in this.channels&&(delete this.channels[e],a.add(e),e in this.heartbeatChannels&&delete this.heartbeatChannels[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannels&&(delete this.presenceChannels[e],a.add(e))})),null==s||s.forEach((e=>{e in this.channelGroups&&(delete this.channelGroups[e],i.add(e),e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannelGroups&&(delete this.presenceChannelGroups[e],i.add(e))})),0===a.size&&0===i.size||(!1!==this.configuration.suppressLeaveEvents||t||(s=Array.from(i),n=Array.from(a),this.leaveCall({channels:n,channelGroups:s},(e=>{const{error:t}=e,i=r(e,["error"]);let a;t&&(e.errorData&&"object"==typeof e.errorData&&"message"in e.errorData&&"string"==typeof e.errorData.message?a=e.errorData.message:"message"in e&&"string"==typeof e.message&&(a=e.message)),this.listenerManager.announceStatus(Object.assign(Object.assign({},i),{error:null!=a&&a,affectedChannels:n,affectedChannelGroups:s,currentTimetoken:this.currentTimetoken,lastTimetoken:this.lastTimetoken}))}))),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(!0))}unsubscribeAll(e){this.unsubscribe({channels:this.subscribedChannels,channelGroups:this.subscribedChannelGroups},e)}startSubscribeLoop(){this.stopSubscribeLoop();const e=[...Object.keys(this.channelGroups)],t=[...Object.keys(this.channels)];Object.keys(this.presenceChannelGroups).forEach((t=>e.push(`${t}-pnpres`))),Object.keys(this.presenceChannels).forEach((e=>t.push(`${e}-pnpres`))),0===t.length&&0===e.length||this.subscribeCall({channels:t,channelGroups:e,state:this.presenceState,heartbeat:this.configuration.getPresenceTimeout(),timetoken:this.currentTimetoken,region:null!==this.region?this.region:void 0,filterExpression:this.configuration.filterExpression},((e,t)=>{this.processSubscribeResponse(e,t)}))}stopSubscribeLoop(){this._subscribeAbort&&(this._subscribeAbort(),this._subscribeAbort=null)}processSubscribeResponse(e,t){if(e.error){if("object"==typeof e.errorData&&"name"in e.errorData&&"AbortError"===e.errorData.name||e.category===h.PNCancelledCategory)return;if(e.category===h.PNTimeoutCategory)this.startSubscribeLoop();else if(e.category===h.PNNetworkIssuesCategory)this.disconnect(),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.listenerManager.announceNetworkDown()),this.reconnectionManager.onReconnect((()=>{this.configuration.autoNetworkDetection&&!this.isOnline&&(this.isOnline=!0,this.listenerManager.announceNetworkUp()),this.reconnect(),this.subscriptionStatusAnnounced=!0;const t={category:h.PNReconnectedCategory,operation:e.operation,lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.listenerManager.announceStatus(t)})),this.reconnectionManager.startPolling(),this.listenerManager.announceStatus(e);else if(e.category===h.PNBadRequestCategory||e.category==h.PNMalformedResponseCategory){const t=this.isOnline?h.PNDisconnectedUnexpectedlyCategory:e.category;this.isOnline=!1,this.disconnect(),this.listenerManager.announceStatus(Object.assign(Object.assign({},e),{category:t}))}else this.listenerManager.announceStatus(e);return}if(this.storedTimetoken?(this.currentTimetoken=this.storedTimetoken,this.storedTimetoken=null):(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=t.cursor.timetoken),!this.subscriptionStatusAnnounced){const t={category:h.PNConnectedCategory,operation:e.operation,affectedChannels:Array.from(this.pendingChannelSubscriptions),subscribedChannels:this.subscribedChannels,affectedChannelGroups:Array.from(this.pendingChannelGroupSubscriptions),lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.subscriptionStatusAnnounced=!0,this.listenerManager.announceStatus(t),this.pendingChannelGroupSubscriptions.clear(),this.pendingChannelSubscriptions.clear()}const{messages:n}=t,{requestMessageCountThreshold:s,dedupeOnSubscribe:r}=this.configuration;s&&n.length>=s&&this.listenerManager.announceStatus({category:h.PNRequestMessageCountExceededCategory,operation:e.operation});try{n.forEach((e=>{if(r&&"message"in e.data&&"timetoken"in e.data){if(this.dedupingManager.isDuplicate(e.data))return;this.dedupingManager.addEntry(e.data)}this.eventEmitter.emitEvent(e)}))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}this.region=t.cursor.region,this.startSubscribeLoop()}setState(e){const{state:t,channels:n,channelGroups:s}=e;null==n||n.forEach((e=>e in this.channels&&(this.presenceState[e]=t))),null==s||s.forEach((e=>e in this.channelGroups&&(this.presenceState[e]=t)))}changePresence(e){const{connected:t,channels:n,channelGroups:s}=e;t?(null==n||n.forEach((e=>this.heartbeatChannels[e]={})),null==s||s.forEach((e=>this.heartbeatChannelGroups[e]={}))):(null==n||n.forEach((e=>{e in this.heartbeatChannels&&delete this.heartbeatChannels[e]})),null==s||s.forEach((e=>{e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]})),!1===this.configuration.suppressLeaveEvents&&this.leaveCall({channels:n,channelGroups:s},(e=>this.listenerManager.announceStatus(e)))),this.reconnect()}startHeartbeatTimer(){this.stopHeartbeatTimer();const e=this.configuration.getHeartbeatInterval();e&&0!==e&&(this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>this.sendHeartbeat()),1e3*e))}stopHeartbeatTimer(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}sendHeartbeat(){const e=Object.keys(this.heartbeatChannelGroups),t=Object.keys(this.heartbeatChannels);0===t.length&&0===e.length||this.heartbeatCall({channels:t,channelGroups:e,heartbeat:this.configuration.getPresenceTimeout(),state:this.presenceState},(e=>{e.error&&this.configuration.announceFailedHeartbeats&&this.listenerManager.announceStatus(e),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.disconnect(),this.listenerManager.announceNetworkDown(),this.reconnect()),!e.error&&this.configuration.announceSuccessfulHeartbeats&&this.listenerManager.announceStatus(e)}))}}class Z{constructor(e,t,n){this._payload=e,this.setDefaultPayloadStructure(),this.title=t,this.body=n}get payload(){return this._payload}set title(e){this._title=e}set subtitle(e){this._subtitle=e}set body(e){this._body=e}set badge(e){this._badge=e}set sound(e){this._sound=e}setDefaultPayloadStructure(){}toObject(){return{}}}class ee extends Z{constructor(){super(...arguments),this._apnsPushType="apns",this._isSilent=!1}get payload(){return this._payload}set configurations(e){e&&e.length&&(this._configurations=e)}get notification(){return this.payload.aps}get title(){return this._title}set title(e){e&&e.length&&(this.payload.aps.alert.title=e,this._title=e)}get subtitle(){return this._subtitle}set subtitle(e){e&&e.length&&(this.payload.aps.alert.subtitle=e,this._subtitle=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.aps.alert.body=e,this._body=e)}get badge(){return this._badge}set badge(e){null!=e&&(this.payload.aps.badge=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.aps.sound=e,this._sound=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.aps={alert:{}}}toObject(){const e=Object.assign({},this.payload),{aps:t}=e;let{alert:n}=t;if(this._isSilent&&(t["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");const t=[];this._configurations.forEach((e=>{t.push(this.objectFromAPNS2Configuration(e))})),t.length&&(e.pn_push=t)}return n&&Object.keys(n).length||delete t.alert,this._isSilent&&(delete t.alert,delete t.badge,delete t.sound,n={}),this._isSilent||n&&Object.keys(n).length?e:null}objectFromAPNS2Configuration(e){if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");const{collapseId:t,expirationDate:n}=e,s={auth_method:"token",targets:e.targets.map((e=>this.objectFromAPNSTarget(e))),version:"v2"};return t&&t.length&&(s.collapse_id=t),n&&(s.expiration=n.toISOString()),s}objectFromAPNSTarget(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");const{topic:t,environment:n="development",excludedDevices:s=[]}=e,r={topic:t,environment:n};return s.length&&(r.excluded_devices=s),r}}class te extends Z{get payload(){return this._payload}get notification(){return this.payload.notification}get data(){return this.payload.data}get title(){return this._title}set title(e){e&&e.length&&(this.payload.notification.title=e,this._title=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.notification.body=e,this._body=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.notification.sound=e,this._sound=e)}get icon(){return this._icon}set icon(e){e&&e.length&&(this.payload.notification.icon=e,this._icon=e)}get tag(){return this._tag}set tag(e){e&&e.length&&(this.payload.notification.tag=e,this._tag=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.notification={},this.payload.data={}}toObject(){let e=Object.assign({},this.payload.data),t=null;const n={};if(Object.keys(this.payload).length>2){const t=r(this.payload,["notification","data"]);e=Object.assign(Object.assign({},e),t)}return this._isSilent?e.notification=this.payload.notification:t=this.payload.notification,Object.keys(e).length&&(n.data=e),t&&Object.keys(t).length&&(n.notification=t),Object.keys(n).length?n:null}}class ne{constructor(e,t){this._payload={apns:{},fcm:{}},this._title=e,this._body=t,this.apns=new ee(this._payload.apns,e,t),this.fcm=new te(this._payload.fcm,e,t)}set debugging(e){this._debugging=e}get title(){return this._title}get subtitle(){return this._subtitle}set subtitle(e){this._subtitle=e,this.apns.subtitle=e,this.fcm.subtitle=e}get body(){return this._body}get badge(){return this._badge}set badge(e){this._badge=e,this.apns.badge=e,this.fcm.badge=e}get sound(){return this._sound}set sound(e){this._sound=e,this.apns.sound=e,this.fcm.sound=e}buildPayload(e){const t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";const n=this.apns.toObject();n&&Object.keys(n).length&&(t.pn_apns=n)}if(e.includes("fcm")){const e=this.fcm.toObject();e&&Object.keys(e).length&&(t.pn_gcm=e)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t}}class se{constructor(e){this.params=e,this.requestIdentifier=x.createUUID(),this._cancellationController=null}get cancellationController(){return this._cancellationController}set cancellationController(e){this._cancellationController=e}abort(e){this&&this.cancellationController&&this.cancellationController.abort(e)}operation(){throw Error("Should be implemented by subclass.")}validate(){}parse(e){return i(this,void 0,void 0,(function*(){return this.deserializeResponse(e)}))}request(){var e,t,n,s;const r={method:null!==(t=null===(e=this.params)||void 0===e?void 0:e.method)&&void 0!==t?t:K.GET,path:this.path,queryParameters:this.queryParameters,cancellable:null!==(s=null===(n=this.params)||void 0===n?void 0:n.cancellable)&&void 0!==s&&s,timeout:10,identifier:this.requestIdentifier},i=this.headers;if(i&&(r.headers=i),r.method===K.POST||r.method===K.PATCH){const[e,t]=[this.body,this.formData];t&&(r.formData=t),e&&(r.body=e)}return r}get headers(){}get path(){throw Error("`path` getter should be implemented by subclass.")}get queryParameters(){return{}}get formData(){}get body(){}deserializeResponse(e){const t=se.decoder.decode(e.body),n=e.headers["content-type"];let s;if(!n||-1===n.indexOf("javascript")&&-1===n.indexOf("json"))throw new d("Service response error, check status for details",y(t,e.status));try{s=JSON.parse(t)}catch(n){throw console.error("Error parsing JSON response:",n),new d("Service response error, check status for details",y(t,e.status))}if("status"in s&&"number"==typeof s.status&&s.status>=400)throw j.create(e);return s}}var re;se.decoder=new TextDecoder,function(e){e.PNPublishOperation="PNPublishOperation",e.PNSignalOperation="PNSignalOperation",e.PNSubscribeOperation="PNSubscribeOperation",e.PNUnsubscribeOperation="PNUnsubscribeOperation",e.PNWhereNowOperation="PNWhereNowOperation",e.PNHereNowOperation="PNHereNowOperation",e.PNGlobalHereNowOperation="PNGlobalHereNowOperation",e.PNSetStateOperation="PNSetStateOperation",e.PNGetStateOperation="PNGetStateOperation",e.PNHeartbeatOperation="PNHeartbeatOperation",e.PNAddMessageActionOperation="PNAddActionOperation",e.PNRemoveMessageActionOperation="PNRemoveMessageActionOperation",e.PNGetMessageActionsOperation="PNGetMessageActionsOperation",e.PNTimeOperation="PNTimeOperation",e.PNHistoryOperation="PNHistoryOperation",e.PNDeleteMessagesOperation="PNDeleteMessagesOperation",e.PNFetchMessagesOperation="PNFetchMessagesOperation",e.PNMessageCounts="PNMessageCountsOperation",e.PNGetAllUUIDMetadataOperation="PNGetAllUUIDMetadataOperation",e.PNGetUUIDMetadataOperation="PNGetUUIDMetadataOperation",e.PNSetUUIDMetadataOperation="PNSetUUIDMetadataOperation",e.PNRemoveUUIDMetadataOperation="PNRemoveUUIDMetadataOperation",e.PNGetAllChannelMetadataOperation="PNGetAllChannelMetadataOperation",e.PNGetChannelMetadataOperation="PNGetChannelMetadataOperation",e.PNSetChannelMetadataOperation="PNSetChannelMetadataOperation",e.PNRemoveChannelMetadataOperation="PNRemoveChannelMetadataOperation",e.PNGetMembersOperation="PNGetMembersOperation",e.PNSetMembersOperation="PNSetMembersOperation",e.PNGetMembershipsOperation="PNGetMembershipsOperation",e.PNSetMembershipsOperation="PNSetMembershipsOperation",e.PNListFilesOperation="PNListFilesOperation",e.PNGenerateUploadUrlOperation="PNGenerateUploadUrlOperation",e.PNPublishFileOperation="PNPublishFileOperation",e.PNPublishFileMessageOperation="PNPublishFileMessageOperation",e.PNGetFileUrlOperation="PNGetFileUrlOperation",e.PNDownloadFileOperation="PNDownloadFileOperation",e.PNDeleteFileOperation="PNDeleteFileOperation",e.PNAddPushNotificationEnabledChannelsOperation="PNAddPushNotificationEnabledChannelsOperation",e.PNRemovePushNotificationEnabledChannelsOperation="PNRemovePushNotificationEnabledChannelsOperation",e.PNPushNotificationEnabledChannelsOperation="PNPushNotificationEnabledChannelsOperation",e.PNRemoveAllPushNotificationsOperation="PNRemoveAllPushNotificationsOperation",e.PNChannelGroupsOperation="PNChannelGroupsOperation",e.PNRemoveGroupOperation="PNRemoveGroupOperation",e.PNChannelsForGroupOperation="PNChannelsForGroupOperation",e.PNAddChannelsToGroupOperation="PNAddChannelsToGroupOperation",e.PNRemoveChannelsFromGroupOperation="PNRemoveChannelsFromGroupOperation",e.PNAccessManagerGrant="PNAccessManagerGrant",e.PNAccessManagerGrantToken="PNAccessManagerGrantToken",e.PNAccessManagerAudit="PNAccessManagerAudit",e.PNAccessManagerRevokeToken="PNAccessManagerRevokeToken",e.PNHandshakeOperation="PNHandshakeOperation",e.PNReceiveMessagesOperation="PNReceiveMessagesOperation"}(re||(re={}));var ie=re;var ae;!function(e){e[e.Presence=-2]="Presence",e[e.Message=-1]="Message",e[e.Signal=1]="Signal",e[e.AppContext=2]="AppContext",e[e.MessageAction=3]="MessageAction",e[e.Files=4]="Files"}(ae||(ae={}));class oe extends se{constructor(e){var t,n,s,r,i,a;super({cancellable:!0}),this.parameters=e,null!==(t=(r=this.parameters).withPresence)&&void 0!==t||(r.withPresence=false),null!==(n=(i=this.parameters).channelGroups)&&void 0!==n||(i.channelGroups=[]),null!==(s=(a=this.parameters).channels)&&void 0!==s||(a.channels=[])}operation(){return ie.PNSubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:n}=this.parameters;return e?t||n?void 0:"`channels` and `channelGroups` both should not be empty":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){let t,n;try{n=se.decoder.decode(e.body);t=JSON.parse(n)}catch(e){console.error("Error parsing JSON response:",e)}if(!t)throw new d("Service response error, check status for details",y(n,e.status));const s=t.m.filter((e=>{const t=void 0===e.b?e.c:e.b;return this.parameters.channels&&this.parameters.channels.includes(t)||this.parameters.channelGroups&&this.parameters.channelGroups.includes(t)})).map((e=>{let{e:t}=e;return null!=t||(t=e.c.endsWith("-pnpres")?ae.Presence:ae.Message),t!=ae.Signal&&"string"==typeof e.d?t==ae.Message?{type:ae.Message,data:this.messageFromEnvelope(e)}:{type:ae.Files,data:this.fileFromEnvelope(e)}:t==ae.Message?{type:ae.Message,data:this.messageFromEnvelope(e)}:t===ae.Presence?{type:ae.Presence,data:this.presenceEventFromEnvelope(e)}:t==ae.Signal?{type:ae.Signal,data:this.signalFromEnvelope(e)}:t===ae.AppContext?{type:ae.AppContext,data:this.appContextFromEnvelope(e)}:t===ae.MessageAction?{type:ae.MessageAction,data:this.messageActionFromEnvelope(e)}:{type:ae.Files,data:this.fileFromEnvelope(e)}}));return{cursor:{timetoken:t.t.t,region:t.t.r},messages:s}}))}get headers(){return{accept:"text/javascript"}}presenceEventFromEnvelope(e){var t;const{d:n}=e,[s,r]=this.subscriptionChannelFromEnvelope(e),i=s.replace("-pnpres",""),a=null!==r?i:null,o=null!==r?r:i;return"string"!=typeof n&&("data"in n?(n.state=n.data,delete n.data):"action"in n&&"interval"===n.action&&(n.hereNowRefresh=null!==(t=n.here_now_refresh)&&void 0!==t&&t,delete n.here_now_refresh)),Object.assign({channel:i,subscription:r,actualChannel:a,subscribedChannel:o,timetoken:e.p.t},n)}messageFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),[s,r]=this.decryptedData(e.d),i={channel:t,subscription:n,actualChannel:null!==n?t:null,subscribedChannel:null!==n?n:t,timetoken:e.p.t,publisher:e.i,message:s};return e.u&&(i.userMetadata=e.u),e.cmt&&(i.customMessageType=e.cmt),r&&(i.error=r),i}signalFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),s={channel:t,subscription:n,timetoken:e.p.t,publisher:e.i,message:e.d};return e.u&&(s.userMetadata=e.u),e.cmt&&(s.customMessageType=e.cmt),s}messageActionFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),s=e.d;return{channel:t,subscription:n,timetoken:e.p.t,publisher:e.i,event:s.event,data:Object.assign(Object.assign({},s.data),{uuid:e.i})}}appContextFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),s=e.d;return{channel:t,subscription:n,timetoken:e.p.t,message:s}}fileFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),[s,r]=this.decryptedData(e.d);let i=r;const a={channel:t,subscription:n,timetoken:e.p.t,publisher:e.i};return e.u&&(a.userMetadata=e.u),s?"string"==typeof s?null!=i||(i="Unexpected file information payload data type."):(a.message=s.message,s.file&&(a.file={id:s.file.id,name:s.file.name,url:this.parameters.getFileUrl({id:s.file.id,name:s.file.name,channel:t})})):null!=i||(i="File information payload is missing."),e.cmt&&(a.customMessageType=e.cmt),i&&(a.error=i),a}subscriptionChannelFromEnvelope(e){return[e.c,void 0===e.b?e.c:e.b]}decryptedData(e){if(!this.parameters.crypto||"string"!=typeof e)return[e,void 0];let t,n;try{const n=this.parameters.crypto.decrypt(e);t=n instanceof ArrayBuffer?JSON.parse(ce.decoder.decode(n)):n}catch(e){t=null,n=`Error while decrypting message content: ${e.message}`}return[null!=t?t:e,n]}}class ce extends oe{get path(){var e;const{keySet:{subscribeKey:t},channels:n}=this.parameters;return`/v2/subscribe/${t}/${L(null!==(e=null==n?void 0:n.sort())&&void 0!==e?e:[],",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,heartbeat:n,state:s,timetoken:r,region:i}=this.parameters,a={};return e&&e.length>0&&(a["channel-group"]=e.sort().join(",")),t&&t.length>0&&(a["filter-expr"]=t),n&&(a.heartbeat=n),s&&Object.keys(s).length>0&&(a.state=JSON.stringify(s)),void 0!==r&&"string"==typeof r?r.length>0&&"0"!==r&&(a.tt=r):void 0!==r&&r>0&&(a.tt=r),i&&(a.tr=i),a}}class ue{constructor(e){this.listenerManager=e,this.channelListenerMap=new Map,this.groupListenerMap=new Map}emitEvent(e){var t;if(e.type===ae.Message)this.listenerManager.announceMessage(e.data),this.announce("message",e.data,e.data.channel,e.data.subscription);else if(e.type===ae.Signal)this.listenerManager.announceSignal(e.data),this.announce("signal",e.data,e.data.channel,e.data.subscription);else if(e.type===ae.Presence)this.listenerManager.announcePresence(e.data),this.announce("presence",e.data,null!==(t=e.data.subscription)&&void 0!==t?t:e.data.channel,e.data.subscription);else if(e.type===ae.AppContext){const{data:t}=e,{message:n}=t;if(this.listenerManager.announceObjects(t),this.announce("objects",t,t.channel,t.subscription),"uuid"===n.type){const{message:e,channel:s}=t,i=r(t,["message","channel"]),{event:a,type:o}=n,c=r(n,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:s,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",type:"user"})});this.listenerManager.announceUser(u),this.announce("user",u,u.spaceId,u.subscription)}else if("channel"===n.type){const{message:e,channel:s}=t,i=r(t,["message","channel"]),{event:a,type:o}=n,c=r(n,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:s,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",type:"space"})});this.listenerManager.announceSpace(u),this.announce("space",u,u.spaceId,u.subscription)}else if("membership"===n.type){const{message:e,channel:s}=t,i=r(t,["message","channel"]),{event:a,data:o}=n,c=r(n,["event","data"]),{uuid:u,channel:l}=o,h=r(o,["uuid","channel"]),d=Object.assign(Object.assign({},i),{spaceId:s,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",data:Object.assign(Object.assign({},h),{user:u,space:l})})});this.listenerManager.announceMembership(d),this.announce("membership",d,d.spaceId,d.subscription)}}else e.type===ae.MessageAction?(this.listenerManager.announceMessageAction(e.data),this.announce("messageAction",e.data,e.data.channel,e.data.subscription)):e.type===ae.Files&&(this.listenerManager.announceFile(e.data),this.announce("file",e.data,e.data.channel,e.data.subscription))}addListener(e,t,n){t&&n?(null==t||t.forEach((t=>{if(this.channelListenerMap.has(t)){const n=this.channelListenerMap.get(t);n.includes(e)||n.push(e)}else this.channelListenerMap.set(t,[e])})),null==n||n.forEach((t=>{if(this.groupListenerMap.has(t)){const n=this.groupListenerMap.get(t);n.includes(e)||n.push(e)}else this.groupListenerMap.set(t,[e])}))):this.listenerManager.addListener(e)}removeListener(e,t,n){t&&n?(null==t||t.forEach((t=>{this.channelListenerMap.has(t)&&this.channelListenerMap.set(t,this.channelListenerMap.get(t).filter((t=>t!==e)))})),null==n||n.forEach((t=>{this.groupListenerMap.has(t)&&this.groupListenerMap.set(t,this.groupListenerMap.get(t).filter((t=>t!==e)))}))):this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners(),this.channelListenerMap.clear(),this.groupListenerMap.clear()}announce(e,t,n,s){t&&this.channelListenerMap.has(n)&&this.channelListenerMap.get(n).forEach((n=>{const s=n[e];s&&s(t)})),s&&this.groupListenerMap.has(s)&&this.groupListenerMap.get(s).forEach((n=>{const s=n[e];s&&s(t)}))}}class le{constructor(e=!1){this.sync=e,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){const t=()=>{this.listeners.forEach((t=>{t(e)}))};this.sync?t():setTimeout(t,0)}}class he{transition(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)}constructor(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}on(e,t){return this.transitionMap.set(e,t),this}with(e,t){return[this,e,null!=t?t:[]]}onEnter(e){return this.enterEffects.push(e),this}onExit(e){return this.exitEffects.push(e),this}}class de extends le{describe(e){return new he(e)}start(e,t){this.currentState=e,this.currentContext=t,this.notify({type:"engineStarted",state:e,context:t})}transition(e){if(!this.currentState)throw new Error("Start the engine first");this.notify({type:"eventReceived",event:e});const t=this.currentState.transition(this.currentContext,e);if(t){const[n,s,r]=t;for(const e of this.currentState.exitEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)});const i=this.currentState;this.currentState=n;const a=this.currentContext;this.currentContext=s,this.notify({type:"transitionDone",fromState:i,fromContext:a,toState:n,toContext:s,event:e});for(const e of r)this.notify({type:"invocationDispatched",invocation:e});for(const e of this.currentState.enterEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)})}}}class pe{constructor(e){this.dependencies=e,this.instances=new Map,this.handlers=new Map}on(e,t){this.handlers.set(e,t)}dispatch(e){if("CANCEL"===e.type){if(this.instances.has(e.payload)){const t=this.instances.get(e.payload);null==t||t.cancel(),this.instances.delete(e.payload)}return}const t=this.handlers.get(e.type);if(!t)throw new Error(`Unhandled invocation '${e.type}'`);const n=t(e.payload,this.dependencies);e.managed&&this.instances.set(e.type,n),n.start()}dispose(){for(const[e,t]of this.instances.entries())t.cancel(),this.instances.delete(e)}}function ge(e,t){const n=function(...n){return{type:e,payload:null==t?void 0:t(...n)}};return n.type=e,n}function ye(e,t){const n=(...n)=>({type:e,payload:t(...n),managed:!1});return n.type=e,n}function fe(e,t){const n=(...n)=>({type:e,payload:t(...n),managed:!0});return n.type=e,n.cancel={type:"CANCEL",payload:e,managed:!1},n}class me extends Error{constructor(){super("The operation was aborted."),this.name="AbortError",Object.setPrototypeOf(this,new.target.prototype)}}class be extends le{constructor(){super(...arguments),this._aborted=!1}get aborted(){return this._aborted}throwIfAborted(){if(this._aborted)throw new me}abort(){this._aborted=!0,this.notify(new me)}}class ve{constructor(e,t){this.payload=e,this.dependencies=t}}class we extends ve{constructor(e,t,n){super(e,t),this.asyncFunction=n,this.abortSignal=new be}start(){this.asyncFunction(this.payload,this.abortSignal,this.dependencies).catch((e=>{}))}cancel(){this.abortSignal.abort()}}const Se=e=>(t,n)=>new we(t,n,e),Ee=ge("RECONNECT",(()=>({}))),Oe=ge("DISCONNECT",(()=>({}))),ke=ge("JOINED",((e,t)=>({channels:e,groups:t}))),Ce=ge("LEFT",((e,t)=>({channels:e,groups:t}))),Ne=ge("LEFT_ALL",(()=>({}))),Pe=ge("HEARTBEAT_SUCCESS",(e=>({statusCode:e}))),Me=ge("HEARTBEAT_FAILURE",(e=>e)),_e=ge("HEARTBEAT_GIVEUP",(()=>({}))),Ae=ge("TIMES_UP",(()=>({}))),je=ye("HEARTBEAT",((e,t)=>({channels:e,groups:t}))),Ie=ye("LEAVE",((e,t)=>({channels:e,groups:t}))),Fe=ye("EMIT_STATUS",(e=>e)),Te=fe("WAIT",(()=>({}))),Re=fe("DELAYED_HEARTBEAT",(e=>e));class Ue extends pe{constructor(e,t){super(t),this.on(je.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{heartbeat:s,presenceState:r,config:i}){try{yield s(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},i.maintainPresenceState&&{state:r}),{heartbeat:i.presenceTimeout}));e.transition(Pe(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Me(t))}}}))))),this.on(Ie.type,Se(((e,t,n)=>i(this,[e,t,n],void 0,(function*(e,t,{leave:n,config:s}){if(!s.suppressLeaveEvents)try{n({channels:e.channels,channelGroups:e.groups})}catch(e){}}))))),this.on(Te.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{heartbeatDelay:s}){return n.throwIfAborted(),yield s(),n.throwIfAborted(),e.transition(Ae())}))))),this.on(Re.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{heartbeat:s,retryDelay:r,presenceState:i,config:a}){if(!a.retryConfiguration||!a.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(_e());n.throwIfAborted(),yield r(a.retryConfiguration.getDelay(t.attempts,t.reason)),n.throwIfAborted();try{yield s(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},a.maintainPresenceState&&{state:i}),{heartbeat:a.presenceTimeout}));return e.transition(Pe(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Me(t))}}}))))),this.on(Fe.type,Se(((e,t,n)=>i(this,[e,t,n],void 0,(function*(e,t,{emitStatus:n,config:s}){var r;s.announceFailedHeartbeats&&!0===(null===(r=null==e?void 0:e.status)||void 0===r?void 0:r.error)?n(e.status):s.announceSuccessfulHeartbeats&&200===e.statusCode&&n(Object.assign(Object.assign({},e),{operation:ie.PNHeartbeatOperation,error:!1}))})))))}}const xe=new he("HEARTBEAT_STOPPED");xe.on(ke.type,((e,t)=>xe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),xe.on(Ce.type,((e,t)=>xe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))}))),xe.on(Ee.type,((e,t)=>Ke.with({channels:e.channels,groups:e.groups}))),xe.on(Ne.type,((e,t)=>$e.with(void 0)));const De=new he("HEARTBEAT_COOLDOWN");De.onEnter((()=>Te())),De.onExit((()=>Te.cancel)),De.on(Ae.type,((e,t)=>Ke.with({channels:e.channels,groups:e.groups}))),De.on(ke.type,((e,t)=>Ke.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),De.on(Ce.type,((e,t)=>Ke.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ie(t.payload.channels,t.payload.groups)]))),De.on(Oe.type,(e=>xe.with({channels:e.channels,groups:e.groups},[Ie(e.channels,e.groups)]))),De.on(Ne.type,((e,t)=>$e.with(void 0,[Ie(e.channels,e.groups)])));const qe=new he("HEARTBEAT_FAILED");qe.on(ke.type,((e,t)=>Ke.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),qe.on(Ce.type,((e,t)=>Ke.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ie(t.payload.channels,t.payload.groups)]))),qe.on(Ee.type,((e,t)=>Ke.with({channels:e.channels,groups:e.groups}))),qe.on(Oe.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups},[Ie(e.channels,e.groups)]))),qe.on(Ne.type,((e,t)=>$e.with(void 0,[Ie(e.channels,e.groups)])));const Ge=new he("HEARBEAT_RECONNECTING");Ge.onEnter((e=>Re(e))),Ge.onExit((()=>Re.cancel)),Ge.on(ke.type,((e,t)=>Ke.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Ge.on(Ce.type,((e,t)=>Ke.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ie(t.payload.channels,t.payload.groups)]))),Ge.on(Oe.type,((e,t)=>{xe.with({channels:e.channels,groups:e.groups},[Ie(e.channels,e.groups)])})),Ge.on(Pe.type,((e,t)=>De.with({channels:e.channels,groups:e.groups}))),Ge.on(Me.type,((e,t)=>Ge.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),Ge.on(_e.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),Ge.on(Ne.type,((e,t)=>$e.with(void 0,[Ie(e.channels,e.groups)])));const Ke=new he("HEARTBEATING");Ke.onEnter((e=>je(e.channels,e.groups))),Ke.on(Pe.type,((e,t)=>De.with({channels:e.channels,groups:e.groups}))),Ke.on(ke.type,((e,t)=>Ke.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Ke.on(Ce.type,((e,t)=>Ke.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ie(t.payload.channels,t.payload.groups)]))),Ke.on(Me.type,((e,t)=>Ge.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),Ke.on(Oe.type,(e=>xe.with({channels:e.channels,groups:e.groups},[Ie(e.channels,e.groups)]))),Ke.on(Ne.type,((e,t)=>$e.with(void 0,[Ie(e.channels,e.groups)])));const $e=new he("HEARTBEAT_INACTIVE");$e.on(ke.type,((e,t)=>Ke.with({channels:t.payload.channels,groups:t.payload.groups})));class Le{get _engine(){return this.engine}constructor(e){this.dependencies=e,this.engine=new de,this.channels=[],this.groups=[],this.dispatcher=new Ue(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start($e,void 0)}join({channels:e,groups:t}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],this.engine.transition(ke(this.channels.slice(0),this.groups.slice(0)))}leave({channels:e,groups:t}){this.dependencies.presenceState&&(null==e||e.forEach((e=>delete this.dependencies.presenceState[e])),null==t||t.forEach((e=>delete this.dependencies.presenceState[e]))),this.engine.transition(Ce(null!=e?e:[],null!=t?t:[]))}leaveAll(){this.engine.transition(Ne())}dispose(){this._unsubscribeEngine(),this.dispatcher.dispose()}}class Be{static LinearRetryPolicy(e){return{delay:e.delay,maximumRetry:e.maximumRetry,shouldRetry(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(e,t){var n;return 1e3*((null!==(n=t.retryAfter)&&void 0!==n?n:this.delay)+Math.random())},getGiveupReason(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"},validate(){if(this.maximumRetry>10)throw new Error("Maximum retry for linear retry policy can not be more than 10")}}}static ExponentialRetryPolicy(e){return{minimumDelay:e.minimumDelay,maximumDelay:e.maximumDelay,maximumRetry:e.maximumRetry,shouldRetry(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(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(e,t){var n;return this.maximumRetry<=t?"retry attempts exhausted.":403===(null===(n=null==e?void 0:e.status)||void 0===n?void 0:n.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.minimumDelay<2)throw new Error("Minimum delay can not be set less than 2 seconds for retry");if(this.maximumDelay)throw new Error("Maximum delay can not be set more than 150 seconds for retry");if(this.maximumRetry>6)throw new Error("Maximum retry for exponential retry policy can not be more than 6")}}}}const He=fe("HANDSHAKE",((e,t)=>({channels:e,groups:t}))),Ve=fe("RECEIVE_MESSAGES",((e,t,n)=>({channels:e,groups:t,cursor:n}))),ze=ye("EMIT_MESSAGES",(e=>e)),We=ye("EMIT_STATUS",(e=>e)),Je=fe("RECEIVE_RECONNECT",(e=>e)),Xe=fe("HANDSHAKE_RECONNECT",(e=>e)),Qe=ge("SUBSCRIPTION_CHANGED",((e,t)=>({channels:e,groups:t}))),Ye=ge("SUBSCRIPTION_RESTORED",((e,t,n,s)=>({channels:e,groups:t,cursor:{timetoken:n,region:null!=s?s:0}}))),Ze=ge("HANDSHAKE_SUCCESS",(e=>e)),et=ge("HANDSHAKE_FAILURE",(e=>e)),tt=ge("HANDSHAKE_RECONNECT_SUCCESS",(e=>({cursor:e}))),nt=ge("HANDSHAKE_RECONNECT_FAILURE",(e=>e)),st=ge("HANDSHAKE_RECONNECT_GIVEUP",(e=>e)),rt=ge("RECEIVE_SUCCESS",((e,t)=>({cursor:e,events:t}))),it=ge("RECEIVE_FAILURE",(e=>e)),at=ge("RECEIVE_RECONNECT_SUCCESS",((e,t)=>({cursor:e,events:t}))),ot=ge("RECEIVE_RECONNECT_FAILURE",(e=>e)),ct=ge("RECEIVING_RECONNECT_GIVEUP",(e=>e)),ut=ge("DISCONNECT",(()=>({}))),lt=ge("RECONNECT",((e,t)=>({cursor:{timetoken:null!=e?e:"",region:null!=t?t:0}}))),ht=ge("UNSUBSCRIBE_ALL",(()=>({})));class dt extends pe{constructor(e,t){super(t),this.on(He.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{handshake:s,presenceState:r,config:i}){n.throwIfAborted();try{const a=yield s(Object.assign({abortSignal:n,channels:t.channels,channelGroups:t.groups,filterExpression:i.filterExpression},i.maintainPresenceState&&{state:r}));return e.transition(Ze(a))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(et(t))}}}))))),this.on(Ve.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{receiveMessages:s,config:r}){n.throwIfAborted();try{const i=yield s({abortSignal:n,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:r.filterExpression});e.transition(rt(i.cursor,i.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;if(!n.aborted)return e.transition(it(t))}}}))))),this.on(ze.type,Se(((e,t,n)=>i(this,[e,t,n],void 0,(function*(e,t,{emitMessages:n}){e.length>0&&n(e)}))))),this.on(We.type,Se(((e,t,n)=>i(this,[e,t,n],void 0,(function*(e,t,{emitStatus:n}){n(e)}))))),this.on(Je.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{receiveMessages:s,delay:r,config:i}){if(!i.retryConfiguration||!i.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(ct(new d(i.retryConfiguration?i.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe messages receive.")));n.throwIfAborted(),yield r(i.retryConfiguration.getDelay(t.attempts,t.reason)),n.throwIfAborted();try{const r=yield s({abortSignal:n,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:i.filterExpression});return e.transition(at(r.cursor,r.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(ot(t))}}}))))),this.on(Xe.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{handshake:s,delay:r,presenceState:i,config:a}){if(!a.retryConfiguration||!a.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(st(new d(a.retryConfiguration?a.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe handshake")));n.throwIfAborted(),yield r(a.retryConfiguration.getDelay(t.attempts,t.reason)),n.throwIfAborted();try{const r=yield s(Object.assign({abortSignal:n,channels:t.channels,channelGroups:t.groups,filterExpression:a.filterExpression},a.maintainPresenceState&&{state:i}));return e.transition(tt(r))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(nt(t))}}})))))}}const pt=new he("HANDSHAKE_FAILED");pt.on(Qe.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),pt.on(lt.type,((e,t)=>wt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor||e.cursor}))),pt.on(Ye.type,((e,t)=>{var n,s;return wt.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!==(s=null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)&&void 0!==s?s:0}})})),pt.on(ht.type,(e=>St.with()));const gt=new he("HANDSHAKE_STOPPED");gt.on(Qe.type,((e,t)=>gt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),gt.on(lt.type,((e,t)=>wt.with(Object.assign(Object.assign({},e),{cursor:t.payload.cursor||e.cursor})))),gt.on(Ye.type,((e,t)=>{var n;return gt.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}})})),gt.on(ht.type,(e=>St.with()));const yt=new he("RECEIVE_FAILED");yt.on(lt.type,((e,t)=>{var n;return wt.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}})})),yt.on(Qe.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),yt.on(Ye.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),yt.on(ht.type,(e=>St.with(void 0)));const ft=new he("RECEIVE_STOPPED");ft.on(Qe.type,((e,t)=>ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),ft.on(Ye.type,((e,t)=>ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),ft.on(lt.type,((e,t)=>{var n;return wt.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}})})),ft.on(ht.type,(()=>St.with(void 0)));const mt=new he("RECEIVE_RECONNECTING");mt.onEnter((e=>Je(e))),mt.onExit((()=>Je.cancel)),mt.on(at.type,((e,t)=>bt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),mt.on(ot.type,((e,t)=>mt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),mt.on(ct.type,((e,t)=>{var n;return yt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[We({category:h.PNDisconnectedUnexpectedlyCategory,error:null===(n=t.payload)||void 0===n?void 0:n.message})])})),mt.on(ut.type,(e=>ft.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[We({category:h.PNDisconnectedCategory})]))),mt.on(Ye.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),mt.on(Qe.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),mt.on(ht.type,(e=>St.with(void 0,[We({category:h.PNDisconnectedCategory})])));const bt=new he("RECEIVING");bt.onEnter((e=>Ve(e.channels,e.groups,e.cursor))),bt.onExit((()=>Ve.cancel)),bt.on(rt.type,((e,t)=>bt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),bt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?St.with(void 0):bt.with({cursor:e.cursor,channels:t.payload.channels,groups:t.payload.groups}))),bt.on(Ye.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?St.with(void 0):bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),bt.on(it.type,((e,t)=>mt.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),bt.on(ut.type,(e=>ft.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[We({category:h.PNDisconnectedCategory})]))),bt.on(ht.type,(e=>St.with(void 0,[We({category:h.PNDisconnectedCategory})])));const vt=new he("HANDSHAKE_RECONNECTING");vt.onEnter((e=>Xe(e))),vt.onExit((()=>Xe.cancel)),vt.on(tt.type,((e,t)=>{var n,s;const r={timetoken:(null===(n=e.cursor)||void 0===n?void 0:n.timetoken)?null===(s=e.cursor)||void 0===s?void 0:s.timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region};return bt.with({channels:e.channels,groups:e.groups,cursor:r},[We({category:h.PNConnectedCategory})])})),vt.on(nt.type,((e,t)=>vt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),vt.on(st.type,((e,t)=>{var n;return pt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[We({category:h.PNConnectionErrorCategory,error:null===(n=t.payload)||void 0===n?void 0:n.message})])})),vt.on(ut.type,(e=>gt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),vt.on(Qe.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),vt.on(Ye.type,((e,t)=>{var n,s;return wt.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===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),vt.on(ht.type,(e=>St.with(void 0)));const wt=new he("HANDSHAKING");wt.onEnter((e=>He(e.channels,e.groups))),wt.onExit((()=>He.cancel)),wt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?St.with(void 0):wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),wt.on(Ze.type,((e,t)=>{var n,s;return bt.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===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.timetoken:t.payload.timetoken,region:t.payload.region}},[We({category:h.PNConnectedCategory})])})),wt.on(et.type,((e,t)=>vt.with({channels:e.channels,groups:e.groups,cursor:e.cursor,attempts:0,reason:t.payload}))),wt.on(ut.type,(e=>gt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),wt.on(Ye.type,((e,t)=>{var n;return wt.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}})})),wt.on(ht.type,(e=>St.with()));const St=new he("UNSUBSCRIBED");St.on(Qe.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups}))),St.on(Ye.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:t.payload.cursor})));class Et{get _engine(){return this.engine}constructor(e){this.engine=new de,this.channels=[],this.groups=[],this.dependencies=e,this.dispatcher=new dt(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(St,void 0)}subscribe({channels:e,channelGroups:t,timetoken:n,withPresence:s}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],s&&(this.channels.map((e=>this.channels.push(`${e}-pnpres`))),this.groups.map((e=>this.groups.push(`${e}-pnpres`)))),n?this.engine.transition(Ye(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])),n)):this.engine.transition(Qe(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])))),this.dependencies.join&&this.dependencies.join({channels:Array.from(new Set(this.channels.filter((e=>!e.endsWith("-pnpres"))))),groups:Array.from(new Set(this.groups.filter((e=>!e.endsWith("-pnpres")))))})}unsubscribe({channels:e=[],channelGroups:t=[]}){const n=B(this.channels,[...e,...e.map((e=>`${e}-pnpres`))]),s=B(this.groups,[...t,...t.map((e=>`${e}-pnpres`))]);if(new Set(this.channels).size!==new Set(n).size||new Set(this.groups).size!==new Set(s).size){const r=H(this.channels,e),i=H(this.groups,t);this.dependencies.presenceState&&(null==r||r.forEach((e=>delete this.dependencies.presenceState[e])),null==i||i.forEach((e=>delete this.dependencies.presenceState[e]))),this.channels=n,this.groups=s,this.engine.transition(Qe(Array.from(new Set(this.channels.slice(0))),Array.from(new Set(this.groups.slice(0))))),this.dependencies.leave&&this.dependencies.leave({channels:r.slice(0),groups:i.slice(0)})}}unsubscribeAll(){this.channels=[],this.groups=[],this.dependencies.presenceState&&Object.keys(this.dependencies.presenceState).forEach((e=>{delete this.dependencies.presenceState[e]})),this.engine.transition(Qe(this.channels.slice(0),this.groups.slice(0))),this.dependencies.leaveAll&&this.dependencies.leaveAll()}reconnect({timetoken:e,region:t}){this.engine.transition(lt(e,t))}disconnect(){this.engine.transition(ut()),this.dependencies.leaveAll&&this.dependencies.leaveAll()}getSubscribedChannels(){return Array.from(new Set(this.channels.slice(0)))}getSubscribedChannelGroups(){return Array.from(new Set(this.groups.slice(0)))}dispose(){this.disconnect(),this._unsubscribeEngine(),this.dispatcher.dispose()}}class Ot extends se{constructor(e){var t,n;super({method:e.sendByPost?K.POST:K.GET}),this.parameters=e,null!==(t=(n=this.parameters).sendByPost)&&void 0!==t||(n.sendByPost=false)}operation(){return ie.PNPublishOperation}validate(){const{message:e,channel:t,keySet:{publishKey:n}}=this.parameters;return t?e?n?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{message:e,channel:t,keySet:n}=this.parameters,s=this.prepareMessagePayload(e);return`/publish/${n.publishKey}/${n.subscribeKey}/0/${$(t)}/0${this.parameters.sendByPost?"":`/${$(s)}`}`}get queryParameters(){const{customMessageType:e,meta:t,replicate:n,storeInHistory:s,ttl:r}=this.parameters,i={};return e&&(i.custom_message_type=e),void 0!==s&&(i.store=s?"1":"0"),void 0!==r&&(i.ttl=r),void 0===n||n||(i.norep="true"),t&&"object"==typeof t&&(i.meta=JSON.stringify(t)),i}get headers(){if(this.parameters.sendByPost)return{"Content-Type":"application/json"}}get body(){return this.prepareMessagePayload(this.parameters.message)}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const n=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof n?n:u(n))}}class kt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNSignalOperation}validate(){const{message:e,channel:t,keySet:{publishKey:n}}=this.parameters;return t?e?n?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{keySet:{publishKey:e,subscribeKey:t},channel:n,message:s}=this.parameters,r=JSON.stringify(s);return`/signal/${e}/${t}/0/${$(n)}/0/${$(r)}`}get queryParameters(){const{customMessageType:e}=this.parameters,t={};return e&&(t.custom_message_type=e),t}}class Ct extends oe{operation(){return ie.PNReceiveMessagesOperation}validate(){const e=super.validate();return e||(this.parameters.timetoken?this.parameters.region?void 0:"region can not be empty":"timetoken can not be empty")}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${L(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,timetoken:n,region:s}=this.parameters,r={ee:""};return e&&e.length>0&&(r["channel-group"]=e.sort().join(",")),t&&t.length>0&&(r["filter-expr"]=t),"string"==typeof n?n&&n.length>0&&(r.tt=n):n&&n>0&&(r.tt=n),s&&(r.tr=s),r}}class Nt extends oe{operation(){return ie.PNHandshakeOperation}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${L(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,state:n}=this.parameters,s={tt:0,ee:""};return e&&e.length>0&&(s["channel-group"]=e.sort().join(",")),t&&t.length>0&&(s["filter-expr"]=t),n&&Object.keys(n).length>0&&(s.state=JSON.stringify(n)),s}}class Pt extends se{constructor(e){var t,n,s,r;super(),this.parameters=e,null!==(t=(s=this.parameters).channels)&&void 0!==t||(s.channels=[]),null!==(n=(r=this.parameters).channelGroups)&&void 0!==n||(r.channelGroups=[])}operation(){return ie.PNGetStateOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:n}=this.parameters;if(!e)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e),{channels:n=[],channelGroups:s=[]}=this.parameters,r={channels:{}};return 1===n.length&&0===s.length?r.channels[n[0]]=t.payload:r.channels=t.payload,r}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:n}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${L(null!=n?n:[],",")}/uuid/${t}`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.join(",")}:{}}}class Mt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNSetStateOperation}validate(){const{keySet:{subscribeKey:e},state:t,channels:n=[],channelGroups:s=[]}=this.parameters;return e?t?0===(null==n?void 0:n.length)&&0===(null==s?void 0:s.length)?"Please provide a list of channels and/or channel-groups":void 0:"Missing State":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{state:this.deserializeResponse(e).payload}}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:n}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${L(null!=n?n:[],",")}/uuid/${$(t)}/data`}get queryParameters(){const{channelGroups:e,state:t}=this.parameters,n={state:JSON.stringify(t)};return e&&0!==e.length&&(n["channel-group"]=e.join(",")),n}}class _t extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNHeartbeatOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:n=[]}=this.parameters;return e?0===t.length&&0===n.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channels:t}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${L(null!=t?t:[],",")}/heartbeat`}get queryParameters(){const{channelGroups:e,state:t,heartbeat:n}=this.parameters,s={heartbeat:`${n}`};return e&&0!==e.length&&(s["channel-group"]=e.join(",")),t&&(s.state=JSON.stringify(t)),s}}class At extends se{constructor(e){super(),this.parameters=e,this.parameters.channelGroups&&(this.parameters.channelGroups=Array.from(new Set(this.parameters.channelGroups))),this.parameters.channels&&(this.parameters.channels=Array.from(new Set(this.parameters.channels)))}operation(){return ie.PNUnsubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:n=[]}=this.parameters;return e?0===t.length&&0===n.length?"At least one `channel` or `channel group` should be provided.":void 0:"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){var e;const{keySet:{subscribeKey:t},channels:n}=this.parameters;return`/v2/presence/sub-key/${t}/channel/${L(null!==(e=null==n?void 0:n.sort())&&void 0!==e?e:[],",")}/leave`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.sort().join(",")}:{}}}class jt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNWhereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return t.payload?{channels:t.payload.channels}:{channels:[]}}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/presence/sub-key/${e}/uuid/${$(t)}`}}class It extends se{constructor(e){var t,n,s,r,i,a;super(),this.parameters=e,null!==(t=(r=this.parameters).queryParameters)&&void 0!==t||(r.queryParameters={}),null!==(n=(i=this.parameters).includeUUIDs)&&void 0!==n||(i.includeUUIDs=true),null!==(s=(a=this.parameters).includeState)&&void 0!==s||(a.includeState=false)}operation(){const{channels:e=[],channelGroups:t=[]}=this.parameters;return 0===e.length&&0===t.length?ie.PNGlobalHereNowOperation:ie.PNHereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t,n;const s=this.deserializeResponse(e),r="occupancy"in s?1:s.payload.total_channels,i="occupancy"in s?s.occupancy:s.payload.total_occupancy,a={};let o={};if("occupancy"in s){const e=this.parameters.channels[0];o[e]={uuids:null!==(t=s.uuids)&&void 0!==t?t:[],occupancy:i}}else o=null!==(n=s.payload.channels)&&void 0!==n?n:{};return Object.keys(o).forEach((e=>{const t=o[e];a[e]={occupants:this.parameters.includeUUIDs?t.uuids.map((e=>"string"==typeof e?{uuid:e,state:null}:e)):[],name:e,occupancy:t.occupancy}})),{totalChannels:r,totalOccupancy:i,channels:a}}))}get path(){const{keySet:{subscribeKey:e},channels:t,channelGroups:n}=this.parameters;let s=`/v2/presence/sub-key/${e}`;return(t&&t.length>0||n&&n.length>0)&&(s+=`/channel/${L(null!=t?t:[],",")}`),s}get queryParameters(){const{channelGroups:e,includeUUIDs:t,includeState:n,queryParameters:s}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign({},t?{}:{disable_uuids:"1"}),null!=n&&n?{state:"1"}:{}),e&&e.length>0?{"channel-group":e.join(",")}:{}),s)}}class Ft extends se{constructor(e){super({method:K.DELETE}),this.parameters=e}operation(){return ie.PNDeleteMessagesOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v3/history/sub-key/${e}/channel/${$(t)}`}get queryParameters(){const{start:e,end:t}=this.parameters;return Object.assign(Object.assign({},e?{start:e}:{}),t?{end:t}:{})}}class Tt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNMessageCounts}validate(){const{keySet:{subscribeKey:e},channels:t,timetoken:n,channelTimetokens:s}=this.parameters;return e?t?n&&s?"`timetoken` and `channelTimetokens` are incompatible together":n||s?s&&s.length>1&&s.length!==t.length?"Length of `channelTimetokens` and `channels` do not match":void 0:"`timetoken` or `channelTimetokens` need to be set":"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e).channels}}))}get path(){return`/v3/history/sub-key/${this.parameters.keySet.subscribeKey}/message-counts/${L(this.parameters.channels)}`}get queryParameters(){let{channelTimetokens:e}=this.parameters;return this.parameters.timetoken&&(e=[this.parameters.timetoken]),Object.assign(Object.assign({},1===e.length?{timetoken:e[0]}:{}),e.length>1?{channelsTimetoken:e.join(",")}:{})}}class Rt extends se{constructor(e){var t,n,s;super(),this.parameters=e,e.count?e.count=Math.min(e.count,100):e.count=100,null!==(t=e.stringifiedTimeToken)&&void 0!==t||(e.stringifiedTimeToken=false),null!==(n=e.includeMeta)&&void 0!==n||(e.includeMeta=false),null!==(s=e.logVerbosity)&&void 0!==s||(e.logVerbosity=false)}operation(){return ie.PNHistoryOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e),n=t[0],s=t[1],r=t[2];return Array.isArray(n)?{messages:n.map((e=>{const t=this.processPayload(e.message),n={entry:t.payload,timetoken:e.timetoken};return t.error&&(n.error=t.error),e.meta&&(n.meta=e.meta),n})),startTimeToken:s,endTimeToken:r}:{messages:[],startTimeToken:s,endTimeToken:r}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/history/sub-key/${e}/channel/${$(t)}`}get queryParameters(){const{start:e,end:t,reverse:n,count:s,stringifiedTimeToken:r,includeMeta:i}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:s,include_token:"true"},e?{start:e}:{}),t?{end:t}:{}),r?{string_message_token:"true"}:{}),null!=n?{reverse:n.toString()}:{}),i?{include_meta:"true"}:{})}processPayload(e){const{crypto:t,logVerbosity:n}=this.parameters;if(!t||"string"!=typeof e)return{payload:e};let s,r;try{const n=t.decrypt(e);s=n instanceof ArrayBuffer?JSON.parse(Rt.decoder.decode(n)):n}catch(t){n&&console.log("decryption error",t.message),s=e,r=`Error while decrypting message content: ${t.message}`}return{payload:s,error:r}}}var Ut;!function(e){e[e.Message=-1]="Message",e[e.Files=4]="Files"}(Ut||(Ut={}));class xt extends se{constructor(e){var t,n,s,r,i;super(),this.parameters=e;const a=null!==(t=e.includeMessageActions)&&void 0!==t&&t,o=e.channels.length>1||a?25:100;e.count?e.count=Math.min(e.count,o):e.count=o,e.includeUuid?e.includeUUID=e.includeUuid:null!==(n=e.includeUUID)&&void 0!==n||(e.includeUUID=true),null!==(s=e.stringifiedTimeToken)&&void 0!==s||(e.stringifiedTimeToken=false),null!==(r=e.includeMessageType)&&void 0!==r||(e.includeMessageType=true),null!==(i=e.logVerbosity)&&void 0!==i||(e.logVerbosity=false)}operation(){return ie.PNFetchMessagesOperation}validate(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:n}=this.parameters;return e?t?void 0!==n&&n&&t.length>1?"History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.":void 0:"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t;const n=this.deserializeResponse(e),s=null!==(t=n.channels)&&void 0!==t?t:{},r={};return Object.keys(s).forEach((e=>{r[e]=s[e].map((t=>{null===t.message_type&&(t.message_type=Ut.Message);const n=this.processPayload(e,t),s=Object.assign(Object.assign({channel:e,timetoken:t.timetoken,message:n.payload,messageType:t.message_type},t.custom_message_type?{customMessageType:t.custom_message_type}:{}),{uuid:t.uuid});if(t.actions){const e=s;e.actions=t.actions,e.data=t.actions}return t.meta&&(s.meta=t.meta),n.error&&(s.error=n.error),s}))})),n.more?{channels:r,more:n.more}:{channels:r}}))}get path(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:n}=this.parameters;return`/v3/${n?"history-with-actions":"history"}/sub-key/${e}/channel/${L(t)}`}get queryParameters(){const{start:e,end:t,count:n,includeCustomMessageType:s,includeMessageType:r,includeMeta:i,includeUUID:a,stringifiedTimeToken:o}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({max:n},e?{start:e}:{}),t?{end:t}:{}),o?{string_message_token:"true"}:{}),void 0!==i&&i?{include_meta:"true"}:{}),a?{include_uuid:"true"}:{}),null!=s?{include_custom_message_type:s?"true":"false"}:{}),r?{include_message_type:"true"}:{})}processPayload(e,t){const{crypto:n,logVerbosity:s}=this.parameters;if(!n||"string"!=typeof t.message)return{payload:t.message};let r,i;try{const e=n.decrypt(t.message);r=e instanceof ArrayBuffer?JSON.parse(xt.decoder.decode(e)):e}catch(e){s&&console.log("decryption error",e.message),r=t.message,i=`Error while decrypting message content: ${e.message}`}if(!i&&r&&t.message_type==Ut.Files&&"object"==typeof r&&this.isFileMessage(r)){const t=r;return{payload:{message:t.message,file:Object.assign(Object.assign({},t.file),{url:this.parameters.getFileUrl({channel:e,id:t.file.id,name:t.file.name})})},error:i}}return{payload:r,error:i}}isFileMessage(e){return void 0!==e.file}}class Dt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNGetMessageActionsOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);let n=null,s=null;return t.data.length>0&&(n=t.data[0].actionTimetoken,s=t.data[t.data.length-1].actionTimetoken),{data:t.data,more:t.more,start:n,end:s}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/message-actions/${e}/channel/${$(t)}`}get queryParameters(){const{limit:e,start:t,end:n}=this.parameters;return Object.assign(Object.assign(Object.assign({},t?{start:t}:{}),n?{end:n}:{}),e?{limit:e}:{})}}class qt extends se{constructor(e){super({method:K.POST}),this.parameters=e}operation(){return ie.PNAddMessageActionOperation}validate(){const{keySet:{subscribeKey:e},action:t,channel:n,messageTimetoken:s}=this.parameters;return e?n?s?t?t.value?t.type?t.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message timetoken":"Missing message channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((({data:e})=>({data:e})))}))}get path(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:n}=this.parameters;return`/v1/message-actions/${e}/channel/${$(t)}/message/${n}`}get headers(){return{"Content-Type":"application/json"}}get body(){return JSON.stringify(this.parameters.action)}}class Gt extends se{constructor(e){super({method:K.DELETE}),this.parameters=e}operation(){return ie.PNRemoveMessageActionOperation}validate(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:n,actionTimetoken:s}=this.parameters;return e?t?n?s?void 0:"Missing action timetoken":"Missing message timetoken":"Missing message action channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((({data:e})=>({data:e})))}))}get path(){const{keySet:{subscribeKey:e},channel:t,actionTimetoken:n,messageTimetoken:s}=this.parameters;return`/v1/message-actions/${e}/channel/${$(t)}/message/${s}/action/${n}`}}class Kt extends se{constructor(e){var t,n;super(),this.parameters=e,null!==(t=(n=this.parameters).storeInHistory)&&void 0!==t||(n.storeInHistory=true)}operation(){return ie.PNPublishFileMessageOperation}validate(){const{channel:e,fileId:t,fileName:n}=this.parameters;return e?t?n?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{message:e,channel:t,keySet:{publishKey:n,subscribeKey:s},fileId:r,fileName:i}=this.parameters,a=Object.assign({file:{name:i,id:r}},e?{message:e}:{});return`/v1/files/publish-file/${n}/${s}/0/${$(t)}/0/${$(this.prepareMessagePayload(a))}`}get queryParameters(){const{customMessageType:e,storeInHistory:t,ttl:n,meta:s}=this.parameters;return Object.assign(Object.assign(Object.assign({store:t?"1":"0"},e?{custom_message_type:e}:{}),n?{ttl:n}:{}),s&&"object"==typeof s?{meta:JSON.stringify(s)}:{})}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const n=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof n?n:u(n))}}class $t extends se{constructor(e){super({method:K.LOCAL}),this.parameters=e}operation(){return ie.PNGetFileUrlOperation}validate(){const{channel:e,id:t,name:n}=this.parameters;return e?t?n?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return e.url}))}get path(){const{channel:e,id:t,name:n,keySet:{subscribeKey:s}}=this.parameters;return`/v1/files/${s}/channels/${$(e)}/files/${t}/${n}`}}class Lt extends se{constructor(e){super({method:K.DELETE}),this.parameters=e}operation(){return ie.PNDeleteFileOperation}validate(){const{channel:e,id:t,name:n}=this.parameters;return e?t?n?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}get path(){const{keySet:{subscribeKey:e},id:t,channel:n,name:s}=this.parameters;return`/v1/files/${e}/channels/${$(n)}/files/${t}/${s}`}}class Bt extends se{constructor(e){var t,n;super(),this.parameters=e,null!==(t=(n=this.parameters).limit)&&void 0!==t||(n.limit=100)}operation(){return ie.PNListFilesOperation}validate(){if(!this.parameters.channel)return"channel can't be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${$(t)}/files`}get queryParameters(){const{limit:e,next:t}=this.parameters;return Object.assign({limit:e},t?{next:t}:{})}}class Ht extends se{constructor(e){super({method:K.POST}),this.parameters=e}operation(){return ie.PNGenerateUploadUrlOperation}validate(){return this.parameters.channel?this.parameters.name?void 0:"'name' can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return{id:t.data.id,name:t.data.name,url:t.file_upload_request.url,formFields:t.file_upload_request.form_fields}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${$(t)}/generate-upload-url`}get headers(){return{"Content-Type":"application/json"}}get body(){return JSON.stringify({name:this.parameters.name})}}class Vt extends se{constructor(e){super({method:K.POST}),this.parameters=e;const t=e.file.mimeType;t&&(e.formFields=e.formFields.map((e=>"Content-Type"===e.name?{name:e.name,value:t}:e)))}operation(){return ie.PNPublishFileOperation}validate(){const{fileId:e,fileName:t,file:n,uploadUrl:s}=this.parameters;return e?t?n?s?void 0:"Validation failed: file upload 'url' can't be empty":"Validation failed: 'file' can't be empty":"Validation failed: file 'name' can't be empty":"Validation failed: file 'id' can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{status:e.status,message:e.body?Vt.decoder.decode(e.body):"OK"}}))}request(){return Object.assign(Object.assign({},super.request()),{origin:new URL(this.parameters.uploadUrl).origin,timeout:300})}get path(){const{pathname:e,search:t}=new URL(this.parameters.uploadUrl);return`${e}${t}`}get body(){return this.parameters.file}get formData(){return this.parameters.formFields}}class zt{constructor(e){var t;if(this.parameters=e,this.file=null===(t=this.parameters.PubNubFile)||void 0===t?void 0:t.create(e.file),!this.file)throw new Error("File upload error: unable to create File object.")}process(){return i(this,void 0,void 0,(function*(){let e,t;return this.generateFileUploadUrl().then((n=>(e=n.name,t=n.id,this.uploadFile(n)))).then((e=>{if(204!==e.status)throw new d("Upload to bucket was unsuccessful",{error:!0,statusCode:e.status,category:h.PNUnknownCategory,operation:ie.PNPublishFileOperation,errorData:{message:e.message}})})).then((()=>this.publishFileMessage(t,e))).catch((e=>{if(e instanceof d)throw e;const t=e instanceof j?e:j.create(e);throw new d("File upload error.",t.toStatus(ie.PNPublishFileOperation))}))}))}generateFileUploadUrl(){return i(this,void 0,void 0,(function*(){const e=new Ht(Object.assign(Object.assign({},this.parameters),{name:this.file.name,keySet:this.parameters.keySet}));return this.parameters.sendRequest(e)}))}uploadFile(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,PubNubFile:n,crypto:s,cryptography:r}=this.parameters,{id:i,name:a,url:o,formFields:c}=e;return this.parameters.PubNubFile.supportsEncryptFile&&(!t&&s?this.file=yield s.encryptFile(this.file,n):t&&r&&(this.file=yield r.encryptFile(t,this.file,n))),this.parameters.sendRequest(new Vt({fileId:i,fileName:a,file:this.file,uploadUrl:o,formFields:c}))}))}publishFileMessage(e,t){return i(this,void 0,void 0,(function*(){var n,s,r,i;let a,o={timetoken:"0"},c=this.parameters.fileUploadPublishRetryLimit,u=!1;do{try{o=yield this.parameters.publishFile(Object.assign(Object.assign({},this.parameters),{fileId:e,fileName:t})),u=!0}catch(e){e instanceof d&&(a=e),c-=1}}while(!u&&c>0);if(u)return{status:200,timetoken:o.timetoken,id:e,name:t};throw new d("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{error:!0,category:null!==(s=null===(n=a.status)||void 0===n?void 0:n.category)&&void 0!==s?s:h.PNUnknownCategory,statusCode:null!==(i=null===(r=a.status)||void 0===r?void 0:r.statusCode)&&void 0!==i?i:0,channel:this.parameters.channel,id:e,name:t})}))}}class Wt{subscribe(e){const t=null==e?void 0:e.timetoken;this.pubnub.registerSubscribeCapable(this),this.pubnub.subscribe(Object.assign({channels:this.channelNames,channelGroups:this.groupNames},null!==t&&""!==t&&{timetoken:t}))}unsubscribe(){this.pubnub.unregisterSubscribeCapable(this);const{channels:e,channelGroups:t}=this.pubnub.getSubscribeCapableEntities(),n=this.groupNames.filter((e=>!t.includes(e))),s=this.channelNames.filter((t=>!e.includes(t)));0===s.length&&0===n.length||this.pubnub.unsubscribe({channels:s,channelGroups:n})}set onMessage(e){this.listener.message=e}set onPresence(e){this.listener.presence=e}set onSignal(e){this.listener.signal=e}set onObjects(e){this.listener.objects=e}set onMessageAction(e){this.listener.messageAction=e}set onFile(e){this.listener.file=e}addListener(e){this.eventEmitter.addListener(e,this.channelNames,this.groupNames)}removeListener(e){this.eventEmitter.removeListener(e,this.channelNames,this.groupNames)}get channels(){return this.channelNames.slice(0)}get channelGroups(){return this.groupNames.slice(0)}}class Jt extends Wt{constructor({channels:e=[],channelGroups:t=[],subscriptionOptions:n,eventEmitter:s,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.subscriptionList=[],this.options=n,this.eventEmitter=s,this.pubnub=r,e.forEach((e=>{const t=this.pubnub.channel(e).subscription(this.options);this.channelNames=[...this.channelNames,...t.channels],this.subscriptionList.push(t)})),t.forEach((e=>{const t=this.pubnub.channelGroup(e).subscription(this.options);this.groupNames=[...this.groupNames,...t.channelGroups],this.subscriptionList.push(t)})),this.listener={},s.addListener(this.listener,this.channelNames,this.groupNames)}addSubscription(e){this.subscriptionList.push(e),this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscription(e){const t=e.channels,n=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!n.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>t!==e)),this.eventEmitter.removeListener(this.listener,t,n)}addSubscriptionSet(e){this.subscriptionList=[...this.subscriptionList,...e.subscriptions],this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscriptionSet(e){const t=e.channels,n=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!n.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>!e.subscriptions.includes(t))),this.eventEmitter.removeListener(this.listener,t,n)}get subscriptions(){return this.subscriptionList.slice(0)}}class Xt extends Wt{constructor({channels:e,channelGroups:t,subscriptionOptions:n,eventEmitter:s,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.channelNames=e,this.groupNames=t,this.options=n,this.pubnub=r,this.eventEmitter=s,this.listener={},s.addListener(this.listener,this.channelNames,this.groupNames)}addSubscription(e){return new Jt({channels:[...this.channelNames,...e.channels],channelGroups:[...this.groupNames,...e.channelGroups],subscriptionOptions:Object.assign(Object.assign({},this.options),null==e?void 0:e.options),eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Qt{constructor(e,t,n){this.eventEmitter=t,this.pubnub=n,this.id=e}subscription(e){return new Xt({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Yt{constructor(e,t,n){this.eventEmitter=t,this.pubnub=n,this.name=e}subscription(e){{const t=[this.name];return(null==e?void 0:e.receivePresenceEvents)&&!this.name.endsWith("-pnpres")&&t.push(`${this.name}-pnpres`),new Xt({channels:[],channelGroups:t,subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}}class Zt{constructor(e,t,n){this.eventEmitter=t,this.pubnub=n,this.id=e}subscription(e){return new Xt({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class en{constructor(e,t,n){this.eventEmitter=t,this.pubnub=n,this.name=e}subscription(e){{const t=[this.name];return(null==e?void 0:e.receivePresenceEvents)&&!this.name.endsWith("-pnpres")&&t.push(`${this.name}-pnpres`),new Xt({channels:t,channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}}class tn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNRemoveChannelsFromGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:n}=this.parameters;return e?n?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${$(t)}`}get queryParameters(){return{remove:this.parameters.channels.join(",")}}}class nn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNAddChannelsToGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:n}=this.parameters;return e?n?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${$(t)}`}get queryParameters(){return{add:this.parameters.channels.join(",")}}}class sn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNChannelsForGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e).payload.channels}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${$(t)}`}}class rn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNRemoveGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${$(t)}/remove`}}class an extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNChannelGroupsOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{groups:this.deserializeResponse(e).payload.groups}}))}get path(){return`/v1/channel-registration/sub-key/${this.parameters.keySet.subscribeKey}/channel-group`}}class on{constructor(e,t){this.sendRequest=t,this.keySet=e}listChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new sn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}listGroups(e){return i(this,void 0,void 0,(function*(){const t=new an({keySet:this.keySet});return e?this.sendRequest(t,e):this.sendRequest(t)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new nn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new tn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}deleteGroup(e,t){return i(this,void 0,void 0,(function*(){const n=new rn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}}class cn extends se{constructor(e){var t,n;super(),this.parameters=e,"apns2"===this.parameters.pushGateway&&(null!==(t=(n=this.parameters).environment)&&void 0!==t||(n.environment="development")),this.parameters.count&&this.parameters.count>1e3&&(this.parameters.count=1e3)}operation(){throw Error("Should be implemented in subclass.")}validate(){const{keySet:{subscribeKey:e},action:t,device:n,pushGateway:s}=this.parameters;return e?n?"add"!==t&&"remove"!==t||"channels"in this.parameters&&0!==this.parameters.channels.length?s?"apns2"!==this.parameters.pushGateway||this.parameters.topic?void 0:"Missing APNS2 topic":"Missing GW Type (pushGateway: gcm or apns2)":"Missing Channels":"Missing Device ID (device)":"Missing Subscribe Key"}get path(){const{keySet:{subscribeKey:e},action:t,device:n,pushGateway:s}=this.parameters;let r="apns2"===s?`/v2/push/sub-key/${e}/devices-apns2/${n}`:`/v1/push/sub-key/${e}/devices/${n}`;return"remove-device"===t&&(r=`${r}/remove`),r}get queryParameters(){const{start:e,count:t}=this.parameters;let n=Object.assign(Object.assign({type:this.parameters.pushGateway},e?{start:e}:{}),t&&t>0?{count:t}:{});if("channels"in this.parameters&&(n[this.parameters.action]=this.parameters.channels.join(",")),"apns2"===this.parameters.pushGateway){const{environment:e,topic:t}=this.parameters;n=Object.assign(Object.assign({},n),{environment:e,topic:t})}return n}}class un extends cn{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove"}))}operation(){return ie.PNRemovePushNotificationEnabledChannelsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class ln extends cn{constructor(e){super(Object.assign(Object.assign({},e),{action:"list"}))}operation(){return ie.PNPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e)}}))}}class hn extends cn{constructor(e){super(Object.assign(Object.assign({},e),{action:"add"}))}operation(){return ie.PNAddPushNotificationEnabledChannelsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class dn extends cn{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove-device"}))}operation(){return ie.PNRemoveAllPushNotificationsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class pn{constructor(e,t){this.sendRequest=t,this.keySet=e}listChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new ln(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new hn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new un(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}deleteDevice(e,t){return i(this,void 0,void 0,(function*(){const n=new dn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}}class gn extends se{constructor(e){var t,n,s,r,i,a;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(i=e.include).customFields)&&void 0!==n||(i.customFields=false),null!==(s=(a=e.include).totalCount)&&void 0!==s||(a.totalCount=false),null!==(r=e.limit)&&void 0!==r||(e.limit=100)}operation(){return ie.PNGetAllChannelMetadataOperation}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";return i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(","),count:`${e.totalCount}`},n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class yn extends se{constructor(e){super({method:K.DELETE}),this.parameters=e}operation(){return ie.PNRemoveChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}`}}class fn extends se{constructor(e){var t,n,s,r,i,a,o,c,u,l,h,d,p,g,y,f,m,b;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(h=e.include).customFields)&&void 0!==n||(h.customFields=false),null!==(s=(d=e.include).totalCount)&&void 0!==s||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(y=e.include).channelFields)&&void 0!==a||(y.channelFields=false),null!==(o=(f=e.include).customChannelFields)&&void 0!==o||(f.customChannelFields=false),null!==(c=(m=e.include).channelStatusField)&&void 0!==c||(m.channelStatusField=false),null!==(u=(b=e.include).channelTypeField)&&void 0!==u||(b.channelTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNGetMembershipsOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=[];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.channelFields&&a.push("channel"),e.channelStatusField&&a.push("channel.status"),e.channelTypeField&&a.push("channel.type"),e.customChannelFields&&a.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class mn extends se{constructor(e){var t,n,s,r,i,a,o,c,u,l,h,d,p,g,y,f,m,b;super({method:K.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(h=e.include).customFields)&&void 0!==n||(h.customFields=false),null!==(s=(d=e.include).totalCount)&&void 0!==s||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(y=e.include).channelFields)&&void 0!==a||(y.channelFields=false),null!==(o=(f=e.include).customChannelFields)&&void 0!==o||(f.customChannelFields=false),null!==(c=(m=e.include).channelStatusField)&&void 0!==c||(m.channelStatusField=false),null!==(u=(b=e.include).channelTypeField)&&void 0!==u||(b.channelTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNSetMembershipsOperation}validate(){const{uuid:e,channels:t}=this.parameters;return e?t&&0!==t.length?void 0:"Channels cannot be empty":"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=["channel.status","channel.type","status"];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.channelFields&&a.push("channel"),e.channelStatusField&&a.push("channel.status"),e.channelTypeField&&a.push("channel.type"),e.customChannelFields&&a.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{channels:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},status:e.status,type:e.type,custom:e.custom}))})}}class bn extends se{constructor(e){var t,n,s,r;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(r=e.include).customFields)&&void 0!==n||(r.customFields=false),null!==(s=e.limit)&&void 0!==s||(e.limit=100)}operation(){return ie.PNGetAllUUIDMetadataOperation}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";return i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(",")},void 0!==e.totalCount?{count:`${e.totalCount}`}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class vn extends se{constructor(e){var t,n,s;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(s=e.include).customFields)&&void 0!==n||(s.customFields=true)}operation(){return ie.PNGetChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}}class wn extends se{constructor(e){var t,n,s;super({method:K.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(s=e.include).customFields)&&void 0!==n||(s.customFields=true)}operation(){return ie.PNSetChannelMetadataOperation}validate(){return this.parameters.channel?this.parameters.data?void 0:"Data cannot be empty":"Channel cannot be empty"}get headers(){return this.parameters.ifMatchesEtag?{"If-Match":this.parameters.ifMatchesEtag}:void 0}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Sn extends se{constructor(e){super({method:K.DELETE}),this.parameters=e,this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNRemoveUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}`}}class En extends se{constructor(e){var t,n,s,r,i,a,o,c,u,l,h,d,p,g,y,f,m,b;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(h=e.include).customFields)&&void 0!==n||(h.customFields=false),null!==(s=(d=e.include).totalCount)&&void 0!==s||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(y=e.include).UUIDFields)&&void 0!==a||(y.UUIDFields=false),null!==(o=(f=e.include).customUUIDFields)&&void 0!==o||(f.customUUIDFields=false),null!==(c=(m=e.include).UUIDStatusField)&&void 0!==c||(m.UUIDStatusField=false),null!==(u=(b=e.include).UUIDTypeField)&&void 0!==u||(b.UUIDTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100)}operation(){return ie.PNSetMembersOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=[];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.UUIDFields&&a.push("uuid"),e.UUIDStatusField&&a.push("uuid.status"),e.UUIDTypeField&&a.push("uuid.type"),e.customUUIDFields&&a.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class On extends se{constructor(e){var t,n,s,r,i,a,o,c,u,l,h,d,p,g,y,f,m,b;super({method:K.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(h=e.include).customFields)&&void 0!==n||(h.customFields=false),null!==(s=(d=e.include).totalCount)&&void 0!==s||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(y=e.include).UUIDFields)&&void 0!==a||(y.UUIDFields=false),null!==(o=(f=e.include).customUUIDFields)&&void 0!==o||(f.customUUIDFields=false),null!==(c=(m=e.include).UUIDStatusField)&&void 0!==c||(m.UUIDStatusField=false),null!==(u=(b=e.include).UUIDTypeField)&&void 0!==u||(b.UUIDTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100)}operation(){return ie.PNSetMembersOperation}validate(){const{channel:e,uuids:t}=this.parameters;return e?t&&0!==t.length?void 0:"UUIDs cannot be empty":"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=["uuid.status","uuid.type","type"];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.UUIDFields&&a.push("uuid"),e.UUIDStatusField&&a.push("uuid.status"),e.UUIDTypeField&&a.push("uuid.type"),e.customUUIDFields&&a.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{uuids:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},status:e.status,type:e.type,custom:e.custom}))})}}class kn extends se{constructor(e){var t,n,s;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(s=e.include).customFields)&&void 0!==n||(s.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNGetUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}`}get queryParameters(){const{include:e}=this.parameters;return{include:["status","type",...e.customFields?["custom"]:[]].join(",")}}}class Cn extends se{constructor(e){var t,n,s;super({method:K.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(s=e.include).customFields)&&void 0!==n||(s.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNSetUUIDMetadataOperation}validate(){return this.parameters.uuid?this.parameters.data?void 0:"Data cannot be empty":"'uuid' cannot be empty"}get headers(){return this.parameters.ifMatchesEtag?{"If-Match":this.parameters.ifMatchesEtag}:void 0}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Nn{constructor(e,t){this.keySet=e.keySet,this.configuration=e,this.sendRequest=t}getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllUUIDMetadata(e,t)}))}_getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const s=new bn(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getUUIDMetadata(e,t)}))}_getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var n;const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),s.userId&&(s.uuid=s.userId),null!==(n=s.uuid)&&void 0!==n||(s.uuid=this.configuration.userId);const r=new kn(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setUUIDMetadata(e,t)}))}_setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var n;e.userId&&(e.uuid=e.userId),null!==(n=e.uuid)&&void 0!==n||(e.uuid=this.configuration.userId);const s=new Cn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeUUIDMetadata(e,t)}))}_removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var n;const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),s.userId&&(s.uuid=s.userId),null!==(n=s.uuid)&&void 0!==n||(s.uuid=this.configuration.userId);const r=new Sn(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllChannelMetadata(e,t)}))}_getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const s=new gn(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getChannelMetadata(e,t)}))}_getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=new vn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setChannelMetadata(e,t)}))}_setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=new wn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeChannelMetadata(e,t)}))}_removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=new yn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const n=new En(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const n=new On(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const n=new On(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getMemberships(e,t){return i(this,void 0,void 0,(function*(){var n;const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),s.userId&&(s.uuid=s.userId),null!==(n=s.uuid)&&void 0!==n||(s.uuid=this.configuration.userId);const r=new fn(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setMemberships(e,t){return i(this,void 0,void 0,(function*(){var n;e.userId&&(e.uuid=e.userId),null!==(n=e.uuid)&&void 0!==n||(e.uuid=this.configuration.userId);const s=new mn(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var n;e.userId&&(e.uuid=e.userId),null!==(n=e.uuid)&&void 0!==n||(e.uuid=this.configuration.userId);const s=new mn(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){var n,s;if("spaceId"in e){const s=e,r={channel:null!==(n=s.spaceId)&&void 0!==n?n:s.channel,filter:s.filter,limit:s.limit,page:s.page,include:Object.assign({},s.include),sort:s.sort?Object.fromEntries(Object.entries(s.sort).map((([e,t])=>[e.replace("user","uuid"),t]))):void 0},i=e=>({status:e.status,data:e.data.map((e=>({user:e.uuid,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getChannelMembers(r,((e,n)=>{t(e,n?i(n):n)})):this.getChannelMembers(r).then(i)}const r=e,i={uuid:null!==(s=r.userId)&&void 0!==s?s:r.uuid,filter:r.filter,limit:r.limit,page:r.page,include:Object.assign({},r.include),sort:r.sort?Object.fromEntries(Object.entries(r.sort).map((([e,t])=>[e.replace("space","channel"),t]))):void 0},a=e=>({status:e.status,data:e.data.map((e=>({space:e.channel,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getMemberships(i,((e,n)=>{t(e,n?a(n):n)})):this.getMemberships(i).then(a)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){var n,s,r,i,a,o;if("spaceId"in e){const i=e,a={channel:null!==(n=i.spaceId)&&void 0!==n?n:i.channel,uuids:null!==(r=null===(s=i.users)||void 0===s?void 0:s.map((e=>"string"==typeof e?e:{id:e.userId,custom:e.custom})))&&void 0!==r?r:i.uuids,limit:0};return t?this.setChannelMembers(a,t):this.setChannelMembers(a)}const c=e,u={uuid:null!==(i=c.userId)&&void 0!==i?i:c.uuid,channels:null!==(o=null===(a=c.spaces)||void 0===a?void 0:a.map((e=>"string"==typeof e?e:{id:e.spaceId,custom:e.custom})))&&void 0!==o?o:c.channels,limit:0};return t?this.setMemberships(u,t):this.setMemberships(u)}))}}class Pn extends se{constructor(){super()}operation(){return ie.PNTimeOperation}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[0]}}))}get path(){return"/time/0"}}class Mn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNDownloadFileOperation}validate(){const{channel:e,id:t,name:n}=this.parameters;return e?t?n?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,crypto:n,cryptography:s,name:r,PubNubFile:i}=this.parameters,a=e.headers["content-type"];let o,c=e.body;return i.supportsEncryptFile&&(t||n)&&(t&&s?c=yield s.decrypt(t,c):!t&&n&&(o=yield n.decryptFile(i.create({data:c,name:r,mimeType:a}),i))),o||i.create({data:c,name:r,mimeType:a})}))}get path(){const{keySet:{subscribeKey:e},channel:t,id:n,name:s}=this.parameters;return`/v1/files/${e}/channels/${$(t)}/files/${n}/${s}`}}class _n{static notificationPayload(e,t){return new ne(e,t)}static generateUUID(){return x.createUUID()}constructor(e){if(this._configuration=e.configuration,this.cryptography=e.cryptography,this.tokenManager=e.tokenManager,this.transport=e.transport,this.crypto=e.crypto,this._objects=new Nn(this._configuration,this.sendRequest.bind(this)),this._channelGroups=new on(this._configuration.keySet,this.sendRequest.bind(this)),this._push=new pn(this._configuration.keySet,this.sendRequest.bind(this)),this.listenerManager=new J,this.eventEmitter=new ue(this.listenerManager),this.subscribeCapable=new Set,this._configuration.enableEventEngine){let e=this._configuration.getHeartbeatInterval();this.presenceState={},e&&(this.presenceEventEngine=new Le({heartbeat:this.heartbeat.bind(this),leave:e=>this.makeUnsubscribe(e,(()=>{})),heartbeatDelay:()=>new Promise(((t,n)=>{e=this._configuration.getHeartbeatInterval(),e?setTimeout(t,1e3*e):n(new d("Heartbeat interval has been reset."))})),retryDelay:e=>new Promise((t=>setTimeout(t,e))),emitStatus:e=>this.listenerManager.announceStatus(e),config:this._configuration,presenceState:this.presenceState})),this.eventEngine=new Et({handshake:this.subscribeHandshake.bind(this),receiveMessages:this.subscribeReceiveMessages.bind(this),delay:e=>new Promise((t=>setTimeout(t,e))),join:this.join.bind(this),leave:this.leave.bind(this),leaveAll:this.leaveAll.bind(this),presenceState:this.presenceState,config:this._configuration,emitMessages:e=>{try{e.forEach((e=>this.eventEmitter.emitEvent(e)))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}},emitStatus:e=>this.listenerManager.announceStatus(e)})}else this.subscriptionManager=new Y(this._configuration,this.listenerManager,this.eventEmitter,this.makeSubscribe.bind(this),this.heartbeat.bind(this),this.makeUnsubscribe.bind(this),this.time.bind(this))}get configuration(){return this._configuration}get _config(){return this.configuration}get authKey(){var e;return null!==(e=this._configuration.authKey)&&void 0!==e?e:void 0}getAuthKey(){return this.authKey}setAuthKey(e){this._configuration.setAuthKey(e)}get userId(){return this._configuration.userId}set userId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}getUserId(){return this._configuration.userId}setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}get filterExpression(){var e;return null!==(e=this._configuration.getFilterExpression())&&void 0!==e?e:void 0}getFilterExpression(){return this.filterExpression}set filterExpression(e){this._configuration.setFilterExpression(e)}setFilterExpression(e){this.filterExpression=e}get cipherKey(){return this._configuration.getCipherKey()}set cipherKey(e){this._configuration.setCipherKey(e)}setCipherKey(e){this.cipherKey=e}set heartbeatInterval(e){this._configuration.setHeartbeatInterval(e)}setHeartbeatInterval(e){this.heartbeatInterval=e}getVersion(){return this._configuration.getVersion()}_addPnsdkSuffix(e,t){this._configuration._addPnsdkSuffix(e,t)}getUUID(){return this.userId}setUUID(e){this.userId=e}get customEncrypt(){return this._configuration.getCustomEncrypt()}get customDecrypt(){return this._configuration.getCustomDecrypt()}channel(e){return new en(e,this.eventEmitter,this)}channelGroup(e){return new Yt(e,this.eventEmitter,this)}channelMetadata(e){return new Qt(e,this.eventEmitter,this)}userMetadata(e){return new Zt(e,this.eventEmitter,this)}subscriptionSet(e){return new Jt(Object.assign(Object.assign({},e),{eventEmitter:this.eventEmitter,pubnub:this}))}sendRequest(e,t){return i(this,void 0,void 0,(function*(){const n=e.validate();if(n){if(t)return t(g(n),null);throw new d("Validation failed, check status for details",g(n))}const s=e.request(),r=e.operation();s.formData&&s.formData.length>0||r===ie.PNDownloadFileOperation?s.timeout=this._configuration.getFileTimeout():r===ie.PNSubscribeOperation||r===ie.PNReceiveMessagesOperation?s.timeout=this._configuration.getSubscribeTimeout():s.timeout=this._configuration.getTransactionTimeout();const i={error:!1,operation:r,category:h.PNAcknowledgmentCategory,statusCode:0},[a,o]=this.transport.makeSendable(s);return e.cancellationController=o||null,a.then((t=>{if(i.statusCode=t.status,200!==t.status&&204!==t.status){const e=_n.decoder.decode(t.body),n=t.headers["content-type"];if(n||-1!==n.indexOf("javascript")||-1!==n.indexOf("json")){const t=JSON.parse(e);"object"==typeof t&&"error"in t&&t.error&&"object"==typeof t.error&&(i.errorData=t.error)}else i.responseText=e}return e.parse(t)})).then((e=>t?t(i,e):e)).catch((e=>{const n=e instanceof j?e:j.create(e);if(t)return t(n.toStatus(r),null);throw n.toPubNubError(r,"REST API request processing error, check status for details")}))}))}destroy(e){var t;null===(t=this.subscribeCapable)||void 0===t||t.clear(),this.subscriptionManager?(this.subscriptionManager.unsubscribeAll(e),this.subscriptionManager.disconnect()):this.eventEngine&&this.eventEngine.dispose()}stop(){this.destroy()}addListener(e){this.listenerManager.addListener(e)}removeListener(e){this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners()}publish(e,t){return i(this,void 0,void 0,(function*(){{const n=new Ot(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}signal(e,t){return i(this,void 0,void 0,(function*(){{const n=new kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}fire(e,t){return i(this,void 0,void 0,(function*(){return null!=t||(t=()=>{}),this.publish(Object.assign(Object.assign({},e),{replicate:!1,storeInHistory:!1}),t)}))}getSubscribedChannels(){return this.subscriptionManager?this.subscriptionManager.subscribedChannels:this.eventEngine?this.eventEngine.getSubscribedChannels():[]}getSubscribedChannelGroups(){return this.subscriptionManager?this.subscriptionManager.subscribedChannelGroups:this.eventEngine?this.eventEngine.getSubscribedChannelGroups():[]}registerSubscribeCapable(e){this.subscribeCapable&&!this.subscribeCapable.has(e)&&this.subscribeCapable.add(e)}unregisterSubscribeCapable(e){this.subscribeCapable&&this.subscribeCapable.has(e)&&this.subscribeCapable.delete(e)}getSubscribeCapableEntities(){{const e={channels:[],channelGroups:[]};if(!this.subscribeCapable)return e;for(const t of this.subscribeCapable)e.channelGroups.push(...t.channelGroups),e.channels.push(...t.channels);return e}}subscribe(e){this.subscriptionManager?this.subscriptionManager.subscribe(e):this.eventEngine&&this.eventEngine.subscribe(e)}makeSubscribe(e,t){{const n=new ce(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));if(this.sendRequest(n,((e,s)=>{var r;this.subscriptionManager&&(null===(r=this.subscriptionManager.abort)||void 0===r?void 0:r.identifier)===n.requestIdentifier&&(this.subscriptionManager.abort=null),t(e,s)})),this.subscriptionManager){const e=()=>n.abort("Cancel long-poll subscribe request");e.identifier=n.requestIdentifier,this.subscriptionManager.abort=e}}}unsubscribe(e){this.subscriptionManager?this.subscriptionManager.unsubscribe(e):this.eventEngine&&this.eventEngine.unsubscribe(e)}makeUnsubscribe(e,t){this.sendRequest(new At(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),t)}unsubscribeAll(){var e;null===(e=this.subscribeCapable)||void 0===e||e.clear(),this.subscriptionManager?this.subscriptionManager.unsubscribeAll():this.eventEngine&&this.eventEngine.unsubscribeAll()}disconnect(){this.subscriptionManager?this.subscriptionManager.disconnect():this.eventEngine&&this.eventEngine.disconnect()}reconnect(e){this.subscriptionManager?this.subscriptionManager.reconnect():this.eventEngine&&this.eventEngine.reconnect(null!=e?e:{})}subscribeHandshake(e){return i(this,void 0,void 0,(function*(){{const t=new Nt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),n=e.abortSignal.subscribe((e=>{t.abort("Cancel subscribe handshake request")}));return this.sendRequest(t).then((e=>(n(),e.cursor)))}}))}subscribeReceiveMessages(e){return i(this,void 0,void 0,(function*(){{const t=new Ct(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),n=e.abortSignal.subscribe((e=>{t.abort("Cancel long-poll subscribe request")}));return this.sendRequest(t).then((e=>(n(),e)))}}))}getMessageActions(e,t){return i(this,void 0,void 0,(function*(){{const n=new Dt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}addMessageAction(e,t){return i(this,void 0,void 0,(function*(){{const n=new qt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}removeMessageAction(e,t){return i(this,void 0,void 0,(function*(){{const n=new Gt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}fetchMessages(e,t){return i(this,void 0,void 0,(function*(){{const n=new xt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}deleteMessages(e,t){return i(this,void 0,void 0,(function*(){{const n=new Ft(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}messageCounts(e,t){return i(this,void 0,void 0,(function*(){{const n=new Tt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}history(e,t){return i(this,void 0,void 0,(function*(){{const n=new Rt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}hereNow(e,t){return i(this,void 0,void 0,(function*(){{const n=new It(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}whereNow(e,t){return i(this,void 0,void 0,(function*(){var n;{const s=new jt({uuid:null!==(n=e.uuid)&&void 0!==n?n:this._configuration.userId,keySet:this._configuration.keySet});return t?this.sendRequest(s,t):this.sendRequest(s)}}))}getState(e,t){return i(this,void 0,void 0,(function*(){var n;{const s=new Pt(Object.assign(Object.assign({},e),{uuid:null!==(n=e.uuid)&&void 0!==n?n:this._configuration.userId,keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}setState(e,t){return i(this,void 0,void 0,(function*(){var n,s;{const{keySet:r,userId:i}=this._configuration,a=this._configuration.getPresenceTimeout();let o;if(this._configuration.enableEventEngine&&this.presenceState){const t=this.presenceState;null===(n=e.channels)||void 0===n||n.forEach((n=>t[n]=e.state)),"channelGroups"in e&&(null===(s=e.channelGroups)||void 0===s||s.forEach((n=>t[n]=e.state)))}return o="withHeartbeat"in e?new _t(Object.assign(Object.assign({},e),{keySet:r,heartbeat:a})):new Mt(Object.assign(Object.assign({},e),{keySet:r,uuid:i})),this.subscriptionManager&&this.subscriptionManager.setState(e),t?this.sendRequest(o,t):this.sendRequest(o)}}))}presence(e){var t;null===(t=this.subscriptionManager)||void 0===t||t.changePresence(e)}heartbeat(e,t){return i(this,void 0,void 0,(function*(){{const n=new _t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}join(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.join(e)}leave(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.leave(e)}leaveAll(){var e;null===(e=this.presenceEventEngine)||void 0===e||e.leaveAll()}grantToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Token error: PAM module disabled")}))}revokeToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Revoke Token error: PAM module disabled")}))}get token(){return this.tokenManager&&this.tokenManager.getToken()}getToken(){return this.token}set token(e){this.tokenManager&&this.tokenManager.setToken(e)}setToken(e){this.token=e}parseToken(e){return this.tokenManager&&this.tokenManager.parseToken(e)}grant(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant error: PAM module disabled")}))}audit(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Permissions error: PAM module disabled")}))}get objects(){return this._objects}fetchUsers(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllUUIDMetadata(e,t)}))}fetchUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getUUIDMetadata(e,t)}))}createUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}updateUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}removeUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeUUIDMetadata(e,t)}))}fetchSpaces(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllChannelMetadata(e,t)}))}fetchSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getChannelMetadata(e,t)}))}createSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}updateSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}removeSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeChannelMetadata(e,t)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.fetchMemberships(e,t)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}updateMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var n,s,r;{if("spaceId"in e){const r=e,i={channel:null!==(n=r.spaceId)&&void 0!==n?n:r.channel,uuids:null!==(s=r.userIds)&&void 0!==s?s:r.uuids,limit:0};return t?this.objects.removeChannelMembers(i,t):this.objects.removeChannelMembers(i)}const i=e,a={uuid:i.userId,channels:null!==(r=i.spaceIds)&&void 0!==r?r:i.channels,limit:0};return t?this.objects.removeMemberships(a,t):this.objects.removeMemberships(a)}}))}get channelGroups(){return this._channelGroups}get push(){return this._push}sendFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const n=new zt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,fileUploadPublishRetryLimit:this._configuration.fileUploadPublishRetryLimit,file:e.file,sendRequest:this.sendRequest.bind(this),publishFile:this.publishFile.bind(this),crypto:this._configuration.getCryptoModule(),cryptography:this.cryptography?this.cryptography:void 0})),s={error:!1,operation:ie.PNPublishFileOperation,category:h.PNAcknowledgmentCategory,statusCode:0};return n.process().then((e=>(s.statusCode=e.status,t?t(s,e):e))).catch((e=>{let n;throw e instanceof d?n=e.status:e instanceof j&&(n=e.toStatus(s.operation)),t&&n&&t(n,null),new d("REST API request processing error, check status for details",n)}))}}))}publishFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const n=new Kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}listFiles(e,t){return i(this,void 0,void 0,(function*(){{const n=new Bt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}getFileUrl(e){var t;{const n=this.transport.request(new $t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})).request()),s=null!==(t=n.queryParameters)&&void 0!==t?t:{},r=Object.keys(s).map((e=>{const t=s[e];return Array.isArray(t)?t.map((t=>`${e}=${$(t)}`)).join("&"):`${e}=${$(t)}`})).join("&");return`${n.origin}${n.path}?${r}`}}downloadFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const n=new Mn(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,cryptography:this.cryptography?this.cryptography:void 0,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(n,t):yield this.sendRequest(n)}}))}deleteFile(e,t){return i(this,void 0,void 0,(function*(){{const n=new Lt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}time(e){return i(this,void 0,void 0,(function*(){const t=new Pn;return e?this.sendRequest(t,e):this.sendRequest(t)}))}encrypt(e,t){const n=this._configuration.getCryptoModule();if(!t&&n&&"string"==typeof e){const t=n.encrypt(e);return"string"==typeof t?t:u(t)}if(!this.crypto)throw new Error("Encryption error: cypher key not set");return this.crypto.encrypt(e,t)}decrypt(e,t){const n=this._configuration.getCryptoModule();if(!t&&n){const t=n.decrypt(e);return t instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(t)):t}if(!this.crypto)throw new Error("Decryption error: cypher key not set");return this.crypto.decrypt(e,t)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var n;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File encryption error. File constructor not configured.");if("string"!=typeof e&&!this._configuration.getCryptoModule())throw new Error("File encryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File encryption error. File encryption not available");return this.cryptography.encryptFile(e,t,this._configuration.PubNubFile)}return null===(n=this._configuration.getCryptoModule())||void 0===n?void 0:n.encryptFile(t,this._configuration.PubNubFile)}))}decryptFile(e,t){return i(this,void 0,void 0,(function*(){var n;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File decryption error. File constructor not configured.");if("string"==typeof e&&!this._configuration.getCryptoModule())throw new Error("File decryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File decryption error. File decryption not available");return this.cryptography.decryptFile(e,t,this._configuration.PubNubFile)}return null===(n=this._configuration.getCryptoModule())||void 0===n?void 0:n.decryptFile(t,this._configuration.PubNubFile)}))}}_n.decoder=new TextDecoder,_n.OPERATIONS=ie,_n.CATEGORIES=h,_n.ExponentialRetryPolicy=Be.ExponentialRetryPolicy,_n.LinearRetryPolicy=Be.LinearRetryPolicy;class An{constructor(e,t){this.decode=e,this.base64ToBinary=t}decodeToken(e){let t="";e.length%4==3?t="=":e.length%4==2&&(t="==");const n=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,s=this.decode(this.base64ToBinary(n));return"object"==typeof s?s:void 0}}class jn extends _n{constructor(e){var t;const n=T(e),r=Object.assign(Object.assign({},n),{sdkFamily:"Web"});r.PubNubFile=o;const i=D(r,(e=>{if(e.cipherKey)return new M({default:new P(Object.assign({},e)),cryptors:[new O({cipherKey:e.cipherKey})]})}));let a,u,l;a=new G(new An((e=>F(s.decode(e))),c)),(i.getCipherKey()||i.secretKey)&&(u=new C({secretKey:i.secretKey,cipherKey:i.getCipherKey(),useRandomIVs:i.getUseRandomIVs(),customEncrypt:i.getCustomEncrypt(),customDecrypt:i.getCustomDecrypt()})),l=new N;let h=new W(r.transport,i.keepAlive,i.logVerbosity);n.subscriptionWorkerUrl&&(h=new I({clientIdentifier:i._instanceId,subscriptionKey:i.subscribeKey,userId:i.getUserId(),workerUrl:n.subscriptionWorkerUrl,sdkVersion:i.getVersion(),heartbeatInterval:i.getHeartbeatInterval(),logVerbosity:i.logVerbosity,workerLogVerbosity:r.subscriptionWorkerLogVerbosity,transport:h}));super({configuration:i,transport:new z({clientConfiguration:i,tokenManager:a,transport:h}),cryptography:l,tokenManager:a,crypto:u}),(null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t)&&(window.addEventListener("offline",(()=>{this.networkDownDetected()})),window.addEventListener("online",(()=>{this.networkUpDetected()})))}networkDownDetected(){this.listenerManager.announceNetworkDown(),this._configuration.restore?this.disconnect():this.destroy(!0)}networkUpDetected(){this.listenerManager.announceNetworkUp(),this.reconnect()}}return jn.CryptoModule=M,jn})); diff --git a/dist/web/pubnub.worker.js b/dist/web/pubnub.worker.js index b3a5f56b5..0c5b6a43b 100644 --- a/dist/web/pubnub.worker.js +++ b/dist/web/pubnub.worker.js @@ -547,7 +547,15 @@ const clients = getClients(); if (clients.length === 0) return; - failure(clients, error); + let fetchError = error; + if (typeof error === 'string') { + const errorMessage = error.toLowerCase(); + if (errorMessage.includes('timeout') || !errorMessage.includes('cancel')) + fetchError = new Error(error); + else if (errorMessage.includes('cancel')) + fetchError = new DOMException('Aborted', 'AbortError'); + } + failure(clients, fetchError); }); }))(); }; @@ -564,7 +572,7 @@ delete serviceRequests[requestId]; // Abort request if possible. if (controller) - controller.abort(); + controller.abort('Cancel request'); } }; /** @@ -1081,12 +1089,12 @@ message = error.message; name = error.name; } - if (name === 'AbortError') { + if (message.toLowerCase().includes('timeout')) + type = 'TIMEOUT'; + else if (name === 'AbortError' || message.toLowerCase().includes('cancel')) { message = 'Request aborted'; type = 'ABORTED'; } - else if (message === 'Request timeout') - type = 'TIMEOUT'; return { type: 'request-process-error', clientIdentifier: '', diff --git a/dist/web/pubnub.worker.min.js b/dist/web/pubnub.worker.min.js index 9c9f4f1cd..494438463 100644 --- a/dist/web/pubnub.worker.min.js +++ b/dist/web/pubnub.worker.min.js @@ -1,2 +1,2 @@ -!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";function e(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{u(r.next(e))}catch(e){s(e)}}function c(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,c)}u((r=r.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n,r,i={exports:{}}; -/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */n=i,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 i(e,t){var r=n[t||"all"];return r&&r.test(e)||!1}r.isUUID=i,r.VERSION=t,e.uuid=r,e.isUUID=i}(r=i.exports),null!==n&&(n.exports=r.uuid);var s=t(i.exports),o={createUUID:()=>s.uuid?s.uuid():s()};const c=1e4,u=new Map,l=new TextDecoder;let a,d=!1;const h=o.createUUID(),p=new Map,f={},b={},g={},v={},y={},q={};self.onconnect=e=>{ee("New PubNub Client connected to the Subscription Shared Worker."),e.ports.forEach((e=>{e.start(),e.onmessage=t=>{if(!J(t))return;const n=t.data;if("client-register"===n.type)!d&&n.workerLogVerbosity&&(d=!0),n.port=e,U(n),ee(`Client '${n.clientIdentifier}' registered with '${h}' shared worker`);else if("client-pong"===n.type)V(n);else if("send-request"===n.type)if(n.request.path.startsWith("/v2/subscribe")){L(n);const e=f[n.clientIdentifier];if(e){const t=`${e.userId}-${e.subscriptionKey}`;if(!u.has(t)){const e=setTimeout((()=>{I(n),u.delete(t)}),50);u.set(t,e)}}}else n.request.path.endsWith("/heartbeat")?(N(n),j(n)):O(n);else"cancel-request"===n.type&&$(n)},e.postMessage({type:"shared-worker-connected"})}))};const I=e=>{var t;const n=R(e),r=f[e.clientIdentifier];let i=!1;if(r&&(r.subscription&&(i="0"===r.subscription.timetoken),F("start",[r],(new Date).toISOString(),e.request)),"string"==typeof n){const s=q[n];if(r){if(r.subscription&&(r.subscription.timetoken=s.timetoken,r.subscription.region=s.region,r.subscription.serviceRequestId=n),!i)return;const o=(new TextEncoder).encode(`{"t":{"t":"${s.timetoken}","r":${null!==(t=s.region)&&void 0!==t?t:"0"}},"m":[]}`),c=new Headers({"Content-Type":'text/javascript; charset="UTF-8"',"Content-Length":`${o.length}`}),u=new Response(o,{status:200,headers:c}),l=C([u,o]);l.url=`${e.request.origin}${e.request.path}`,l.clientIdentifier=e.clientIdentifier,l.identifier=e.request.identifier,F("end",[r],(new Date).toISOString(),e.request,o,c.get("Content-Type"),0),A(r,l)}return}e.request.cancellable&&p.set(n.identifier,new AbortController);const s=q[n.identifier],{timetokenOverride:o,regionOverride:c}=s;S(n,(()=>G(n.identifier)),((t,r)=>{W(t,r,e.request),T(t,n.identifier)}),((t,r)=>{W(t,null,e.request,D(r)),T(t,n.identifier)}),(e=>{let t=e;return i&&o&&"0"!==o&&(q[n.identifier],t=m(t,o,c)),t})),ee(`'${Object.keys(q).length}' subscription request currently active.`)},m=(e,t,n)=>{if(void 0===t||"0"===t||e[0].status>=400)return e;let r;const i=e[0];let s=i,o=e[1];try{r=JSON.parse((new TextDecoder).decode(o))}catch(t){return ee(`Subscribe response parse error: ${t}`),e}r.t.t=t,n&&(r.t.r=parseInt(n,10));try{if(o=(new TextEncoder).encode(JSON.stringify(r)).buffer,o.byteLength){const e=new Headers(i.headers);e.set("Content-Length",`${o.byteLength}`),s=new Response(o,{status:i.status,statusText:i.statusText,headers:e})}}catch(t){return ee(`Subscribe serialization error: ${t}`),e}return o.byteLength>0?[s,o]:e},j=e=>{var t;const n=f[e.clientIdentifier],r=K(e);if(!n)return;const i=`${n.userId}_${null!==(t=n.authKey)&&void 0!==t?t:""}`,s=g[n.subscriptionKey],o=(null!=s?s:{})[i];if(F("start",[n],(new Date).toISOString(),r),!r){let t,r;if(ee(`Previous heartbeat request has been sent less than ${n.heartbeatInterval} seconds ago. Skipping...`),o&&o.response&&([t,r]=o.response),!t){r=(new TextEncoder).encode('{ "status": 200, "message": "OK", "service": "Presence" }').buffer;const e=new Headers({"Content-Type":'text/javascript; charset="UTF-8"',"Content-Length":`${r.byteLength}`});t=new Response(r,{status:200,headers:e})}const i=C([t,r]);return i.url=`${e.request.origin}${e.request.path}`,i.clientIdentifier=e.clientIdentifier,i.identifier=e.request.identifier,F("end",[n],(new Date).toISOString(),e.request,r,t.headers.get("Content-Type"),0),void A(n,i)}S(r,(()=>[n]),((t,n)=>{o&&(o.response=n),W(t,n,e.request)}),((t,n)=>{W(t,null,e.request,D(n))})),ee("Started heartbeat request.",n)},O=e=>{const t=f[e.clientIdentifier],n=x(e);if(!t)return;const{subscription:r}=t,i=null==r?void 0:r.serviceRequestId;if(r&&0===r.channels.length&&0===r.channelGroups.length&&(r.channelGroupQuery="",r.path="",r.previousTimetoken="0",r.timetoken="0",delete r.region,delete r.serviceRequestId,delete r.request),!n){const n=(new TextEncoder).encode('{"status": 200, "action": "leave", "message": "OK", "service":"Presence"}'),r=new Headers({"Content-Type":'text/javascript; charset="UTF-8"',"Content-Length":`${n.length}`}),i=new Response(n,{status:200,headers:r}),s=C([i,n]);return s.url=`${e.request.origin}${e.request.path}`,s.clientIdentifier=e.clientIdentifier,s.identifier=e.request.identifier,void A(t,s)}if(S(n,(()=>[t]),((t,n)=>{W(t,n,e.request)}),((t,n)=>{W(t,null,e.request,D(n))})),ee("Started leave request.",t),void 0===i)return;const s=G(i);s.forEach((e=>{e&&e.subscription&&delete e.subscription.serviceRequestId})),k(i),w(s)},$=e=>{const t=f[e.clientIdentifier];if(!t||!t.subscription)return;const n=t.subscription.serviceRequestId;t&&n&&(delete t.subscription.serviceRequestId,t.subscription.request&&t.subscription.request.identifier===e.identifier&&delete t.subscription.request,k(n))},w=e=>{let t,n;for(const r of e)if(r.subscription&&r.subscription.request){n=r.subscription.request,t=r;break}n&&t&&I({type:"send-request",clientIdentifier:t.clientIdentifier,subscriptionKey:t.subscriptionKey,logVerbosity:t.logVerbosity,request:n})},S=(t,n,r,i,s)=>{e(void 0,void 0,void 0,(function*(){var e;const o=(new Date).getTime();Promise.race([fetch(E(t),{signal:null===(e=p.get(t.identifier))||void 0===e?void 0:e.signal,keepalive:!0}),P(t.identifier,t.timeout)]).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>s?s(e):e)).then((e=>{const i=e[1].byteLength>0?e[1]:void 0,s=n();0!==s.length&&(F("end",s,(new Date).toISOString(),t,i,e[0].headers.get("Content-Type"),(new Date).getTime()-o),r(s,e))})).catch((e=>{const t=n();0!==t.length&&i(t,e)}))}))},k=e=>{if(0===G(e).length){const t=p.get(e);p.delete(e),delete q[e],t&&t.abort()}},P=(e,t)=>new Promise(((n,r)=>{const i=setTimeout((()=>{p.delete(e),clearTimeout(i),r(new Error("Request timeout"))}),1e3*t)})),G=e=>Object.values(f).filter((t=>void 0!==t&&void 0!==t.subscription&&t.subscription.serviceRequestId===e)),T=(e,t)=>{delete q[t],e.forEach((e=>{e.subscription&&(delete e.subscription.request,delete e.subscription.serviceRequestId)}))},E=e=>{let t;const n=e.queryParameters;let r=e.path;if(e.headers){t={};for(const[n,r]of Object.entries(e.headers))t[n]=r}return n&&0!==Object.keys(n).length&&(r=`${r}?${ne(n)}`),new Request(`${e.origin}${r}`,{method:e.method,headers:t,redirect:"follow"})},R=e=>{var t,n,r,i,s;const c=f[e.clientIdentifier],u=c.subscription,l=Q(u.timetoken,e),a=o.createUUID(),h=Object.assign({},e.request);let p,b;if(l.length>1){const s=_(l,e);if(s){const e=q[s],{channels:n,channelGroups:r}=null!==(t=c.subscription)&&void 0!==t?t:{channels:[],channelGroups:[]};if((!(n.length>0)||Y(e.channels,n))&&(!(r.length>0)||Y(e.channelGroups,r)))return s}const o=(null!==(n=v[c.subscriptionKey])&&void 0!==n?n:{})[c.userId],d={},f=new Set(u.channelGroups),g=new Set(u.channels);o&&u.objectsWithState.length&&u.objectsWithState.forEach((e=>{const t=o[e];t&&(d[e]=t)}));for(const e of l){const{subscription:t}=e;if(!t)continue;1!==l.length&&e.clientIdentifier===c.clientIdentifier||!t.timetoken||(p=t.timetoken,b=t.region),t.channelGroups.forEach(f.add,f),t.channels.forEach(g.add,g);const n=t.serviceRequestId;t.serviceRequestId=a,n&&q[n]&&k(n),o&&t.objectsWithState.forEach((e=>{const t=o[e];t&&!d[e]&&(d[e]=t)}))}const y=null!==(r=q[a])&&void 0!==r?r:q[a]={requestId:a,timetoken:null!==(i=h.queryParameters.tt)&&void 0!==i?i:"0",channelGroups:[],channels:[]};if(g.size){y.channels=Array.from(g).sort();const e=h.path.split("/");e[4]=y.channels.join(","),h.path=e.join("/")}f.size&&(y.channelGroups=Array.from(f).sort(),h.queryParameters["channel-group"]=y.channelGroups.join(",")),Object.keys(d).length&&(h.queryParameters.state=JSON.stringify(d))}else q[a]={requestId:a,timetoken:null!==(s=h.queryParameters.tt)&&void 0!==s?s:"0",channelGroups:u.channelGroups,channels:u.channels};if(q[a]&&(h.queryParameters&&void 0!==h.queryParameters.tt&&void 0!==h.queryParameters.tr&&(q[a].region=h.queryParameters.tr),q[a].timetokenOverride=p,q[a].regionOverride=b),u.serviceRequestId=a,h.identifier=a,d){const e=l.reduce(((e,{clientIdentifier:t})=>(e.push(t),e)),[]).join(",");te(q[a],`Started aggregated request for clients: ${e}`)}return h},K=e=>{var t,n,r,i,s;const o=f[e.clientIdentifier],c=B(e),u=Object.assign({},e.request);if(!o||!o.heartbeat)return;const l=null!==(t=g[s=o.subscriptionKey])&&void 0!==t?t:g[s]={},a=`${o.userId}_${null!==(n=o.authKey)&&void 0!==n?n:""}`,d=o.heartbeat.channelGroups,h=o.heartbeat.channels;let p={},b=!1,v=!0;if(l[a]){const{channels:e,channelGroups:t,response:n}=l[a];p=null!==(i=o.heartbeat.presenceState)&&void 0!==i?i:{},v=Y(e,o.heartbeat.channels)&&Y(t,o.heartbeat.channelGroups),n&&(b=n[0].status>=400)}else l[a]={channels:h,channelGroups:d,timestamp:Date.now()},p=null!==(r=o.heartbeat.presenceState)&&void 0!==r?r:{},v=!1;if(v){const t=l[a].timestamp+1e3*o.heartbeatInterval,n=Date.now();if(!b&&n5e3)return;delete l[a].response;for(const t of c){const{heartbeat:n}=t;void 0!==n&&t.clientIdentifier!==e.clientIdentifier&&(n.presenceState&&(p=Object.assign(Object.assign({},p),n.presenceState)),d.push(...n.channelGroups.filter((e=>!d.includes(e)))),h.push(...n.channels.filter((e=>!h.includes(e)))))}}l[a].channels=h,l[a].channelGroups=d,l[a].timestamp=Date.now();for(const e in Object.keys(p))h.includes(e)||d.includes(e)||delete p[e];if(h.length){const e=u.path.split("/");e[6]=h.join(","),u.path=e.join("/")}return d.length&&(u.queryParameters["channel-group"]=d.join(",")),Object.keys(p).length?u.queryParameters.state=JSON.stringify(p):delete u.queryParameters.state,u},x=e=>{const t=f[e.clientIdentifier],n=H(e);let r=X(e.request),i=z(e.request);const s=Object.assign({},e.request);if(t&&t.subscription){const{subscription:e}=t;i.length&&(e.channels=e.channels.filter((e=>!i.includes(e)))),r.length&&(e.channelGroups=e.channelGroups.filter((e=>!r.includes(e))))}if(t&&t.heartbeat){const{heartbeat:e}=t;i.length&&(e.channels=e.channels.filter((e=>!i.includes(e)))),r.length&&(e.channelGroups=e.channelGroups.filter((e=>!r.includes(e))))}for(const t of n){const n=t.subscription;void 0!==n&&(t.clientIdentifier!==e.clientIdentifier&&(i.length&&(i=i.filter((e=>!n.channels.includes(e)))),r.length&&(r=r.filter((e=>!n.channelGroups.includes(e))))))}if(0!==i.length||0!==r.length){if(i.length){const e=s.path.split("/");e[6]=i.join(","),s.path=e.join("/")}return r.length&&(s.queryParameters["channel-group"]=r.join(",")),s}if(d&&t){const e=n.reduce(((e,{clientIdentifier:t})=>(e.push(t),e)),[]).join(",");ee(`Specified channels and groups still in use by other clients: ${e}. Ignoring leave request.`,t)}},A=(e,t)=>{var n;const r=(null!==(n=y[e.subscriptionKey])&&void 0!==n?n:{})[e.clientIdentifier];if(!r)return!1;try{return r.postMessage(t),!0}catch(e){}return!1},F=(e,t,n,r,i,s,o)=>{var c,u;if(0===t.length)return;const a=null!==(c=y[t[0].subscriptionKey])&&void 0!==c?c:{},d=r&&r.path.startsWith("/v2/subscribe");let h;if("start"===e)h={type:"request-progress-start",clientIdentifier:"",url:"",timestamp:n};else{let e;i&&s&&(-1!==s.indexOf("text/javascript")||-1!==s.indexOf("application/json")||-1!==s.indexOf("text/plain")||-1!==s.indexOf("text/html"))&&(e=l.decode(i)),h={type:"request-progress-end",clientIdentifier:"",url:"",response:e,timestamp:n,duration:o}}for(const e of t){if(d&&!e.subscription)continue;const t=a[e.clientIdentifier],{request:n}=null!==(u=e.subscription)&&void 0!==u?u:{};let i=null!=n?n:r;if(d||(i=r),e.logVerbosity&&t&&i){const t=Object.assign(Object.assign({},h),{clientIdentifier:e.clientIdentifier,url:`${i.origin}${i.path}`,query:i.queryParameters});A(e,t)}}},W=(e,t,n,r)=>{var i,s;if(0===e.length)return;if(!r&&!t)return;const o=null!==(i=y[e[0].subscriptionKey])&&void 0!==i?i:{},c=n&&n.path.startsWith("/v2/subscribe");!r&&t&&(r=t[0].status>=400?D(void 0,t):C(t));for(const t of e){if(c&&!t.subscription)continue;const e=o[t.clientIdentifier],{request:i}=null!==(s=t.subscription)&&void 0!==s?s:{};let u=null!=i?i:n;if(c||(u=n),e&&u){const e=Object.assign(Object.assign({},r),{clientIdentifier:t.clientIdentifier,identifier:u.identifier,url:`${u.origin}${u.path}`});A(t,e)}}},C=e=>{var t;const[n,r]=e,i=r.byteLength>0?r:void 0,s=parseInt(null!==(t=n.headers.get("Content-Length"))&&void 0!==t?t:"0",10),o=n.headers.get("Content-Type"),c={};return n.headers.forEach(((e,t)=>c[t]=e.toLowerCase())),{type:"request-process-success",clientIdentifier:"",identifier:"",url:"",response:{contentLength:s,contentType:o,headers:c,status:n.status,body:i}}},D=(e,t)=>{if(t)return Object.assign(Object.assign({},C(t)),{type:"request-process-error"});let n="NETWORK_ISSUE",r="Unknown error",i="Error";return e&&e instanceof Error&&(r=e.message,i=e.name),"AbortError"===i?(r="Request aborted",n="ABORTED"):"Request timeout"===r&&(n="TIMEOUT"),{type:"request-process-error",clientIdentifier:"",identifier:"",url:"",error:{name:i,type:n,message:r}}},U=e=>{var t,n,r,i;const{clientIdentifier:s}=e;if(f[s])return;const o=f[s]={clientIdentifier:s,subscriptionKey:e.subscriptionKey,userId:e.userId,heartbeatInterval:e.heartbeatInterval,logVerbosity:e.logVerbosity},u=null!==(t=b[r=e.subscriptionKey])&&void 0!==t?t:b[r]=[];u.every((e=>e.clientIdentifier!==s))&&u.push(o),(null!==(n=y[i=e.subscriptionKey])&&void 0!==n?n:y[i]={})[s]=e.port,ee(`Registered PubNub client with '${s}' identifier. '${Object.keys(f).length}' clients currently active.`),!a&&Object.keys(f).length>0&&(ee("Setup PubNub client ping event 10 seconds"),a=setInterval((()=>Z()),c))},L=e=>{var t,n,r,i,s,o,c,u,l,a,d,h,p,b,g,y,q,I,m,j;const O=e.request.queryParameters,{clientIdentifier:$}=e,w=f[$];if(!w)return;const S=null!==(t=O["channel-group"])&&void 0!==t?t:"",k=null!==(n=O.state)&&void 0!==n?n:"";let P=w.subscription;if(P){if(k.length>0){const e=JSON.parse(k),t=null!==(o=(y=null!==(s=v[g=w.subscriptionKey])&&void 0!==s?s:v[g]={})[q=w.userId])&&void 0!==o?o:y[q]={};Object.entries(e).forEach((([e,n])=>t[e]=n));for(const n of P.objectsWithState)e[n]||delete t[n];P.objectsWithState=Object.keys(e)}else if(P.objectsWithState.length){const e=null!==(u=(m=null!==(c=v[I=w.subscriptionKey])&&void 0!==c?c:v[I]={})[j=w.userId])&&void 0!==u?u:m[j]={};for(const t of P.objectsWithState)delete e[t];P.objectsWithState=[]}}else{if(P={path:"",channelGroupQuery:"",channels:[],channelGroups:[],previousTimetoken:"0",timetoken:"0",objectsWithState:[]},k.length>0){const e=JSON.parse(k),t=null!==(i=(p=null!==(r=v[h=w.subscriptionKey])&&void 0!==r?r:v[h]={})[b=w.userId])&&void 0!==i?i:p[b]={};Object.entries(e).forEach((([e,n])=>t[e]=n)),P.objectsWithState=Object.keys(e)}w.subscription=P}P.path!==e.request.path&&(P.path=e.request.path,P.channels=z(e.request)),P.channelGroupQuery!==S&&(P.channelGroupQuery=S,P.channelGroups=X(e.request));const{authKey:G,userId:T}=w;P.request=e.request,P.filterExpression=null!==(l=O["filter-expr"])&&void 0!==l?l:"",P.timetoken=null!==(a=O.tt)&&void 0!==a?a:"0",void 0!==O.tr&&(P.region=O.tr),w.authKey=null!==(d=O.auth)&&void 0!==d?d:"",w.userId=O.uuid,M(w,T,G)},N=e=>{var t,n;const r=f[e.clientIdentifier],{request:i}=e;if(!r)return;const s=null!==(t=r.heartbeat)&&void 0!==t?t:r.heartbeat={channels:[],channelGroups:[]};s.channelGroups=X(i).filter((e=>!e.endsWith("-pnpres"))),s.channels=z(i).filter((e=>!e.endsWith("-pnpres")));const o=null!==(n=i.queryParameters.state)&&void 0!==n?n:"";if(o.length>0){const e=JSON.parse(o);for(const t of Object.keys(e))s.channels.includes(t)||s.channelGroups.includes(t)||delete e[t];s.presenceState=e}},M=(e,t,n)=>{var r,i;if(!e||t===e.userId&&(null!=n?n:"")===(null!==(r=e.authKey)&&void 0!==r?r:""))return;const s=null!==(i=g[e.subscriptionKey])&&void 0!==i?i:{},o=`${t}_${null!=n?n:""}`;void 0!==s[o]&&delete s[o]},V=e=>{const t=f[e.clientIdentifier];t&&(t.lastPongEvent=(new Date).getTime()/1e3)},J=e=>{const{clientIdentifier:t,subscriptionKey:n,logVerbosity:r}=e.data;return void 0!==r&&"boolean"==typeof r&&(!(!t||"string"!=typeof t)&&!(!n||"string"!=typeof n))},_=(e,t)=>{var n;const r=null!==(n=t.request.queryParameters["channel-group"])&&void 0!==n?n:"",i=t.request.path;let s,o;for(const n of e){const{subscription:e}=n;if(!e||!e.serviceRequestId)continue;const c=f[t.clientIdentifier],u=e.serviceRequestId;if(e.path===i&&e.channelGroupQuery===r)return ee(`Found identical request started by '${n.clientIdentifier}' client. \nWaiting for existing '${u}' request completion.`,c),e.serviceRequestId;{const r=q[e.serviceRequestId];if(s||(s=X(t.request)),o||(o=z(t.request)),o.length&&!Y(r.channels,o))continue;if(s.length&&!Y(r.channelGroups,s))continue;return te(r,`'${t.request.identifier}' request channels and groups are subset of ongoing '${u}' request \nwhich has started by '${n.clientIdentifier}' client. Waiting for existing '${u}' request completion.`,c),e.serviceRequestId}}},Q=(e,t)=>{var n,r,i;const s=t.request.queryParameters,o=null!==(n=s["filter-expr"])&&void 0!==n?n:"",c=null!==(r=s.auth)&&void 0!==r?r:"",u=s.uuid;return(null!==(i=b[t.subscriptionKey])&&void 0!==i?i:[]).filter((t=>t.userId===u&&t.authKey===c&&t.subscription&&(0!==t.subscription.channels.length||0!==t.subscription.channelGroups.length)&&t.subscription.filterExpression===o&&("0"===e||"0"===t.subscription.timetoken||t.subscription.timetoken===e)))},B=e=>H(e),H=e=>{var t,n;const r=e.request.queryParameters,i=null!==(t=r.auth)&&void 0!==t?t:"",s=r.uuid;return(null!==(n=b[e.subscriptionKey])&&void 0!==n?n:[]).filter((e=>e.userId===s&&e.authKey===i))},z=e=>{const t=e.path.split("/")[e.path.startsWith("/v2/subscribe/")?4:6];return","===t?[]:t.split(",").filter((e=>e.length>0))},X=e=>{var t;const n=null!==(t=e.queryParameters["channel-group"])&&void 0!==t?t:"";return 0===n.length?[]:n.split(",").filter((e=>e.length>0))},Y=(e,t)=>{const n=new Set(e);return t.every(n.has,n)},Z=()=>{ee("Pinging clients...");const e={type:"shared-worker-ping"};Object.values(f).forEach((t=>{let n=!1;t&&t.lastPingRequest&&(ee(`Checking whether ${t.clientIdentifier} ping has been sent too long ago...`),(!t.lastPongEvent||Math.abs(t.lastPongEvent-t.lastPingRequest)>5)&&(n=!0,ee(`'${t.clientIdentifier}' client is inactive. Invalidating.`),((e,t)=>{delete f[t];let n=b[e];if(n)if(n=n.filter((e=>e.clientIdentifier!==t)),n.length>0?b[e]=n:(delete b[e],delete g[e]),0===n.length&&delete v[e],n.length>0){const n=y[e];n&&(delete n[t],0===Object.keys(n).length&&delete y[e])}else delete y[e];ee(`Invalidate '${t}' client. '${Object.keys(f).length}' clients currently active.`)})(t.subscriptionKey,t.clientIdentifier))),t&&!n&&(ee(`Sending ping to ${t.clientIdentifier}...`),t.lastPingRequest=(new Date).getTime()/1e3,A(t,e))})),0===Object.keys(f).length&&a&&clearInterval(a)},ee=(e,t)=>{if(!d)return;const n=t?[t]:Object.values(f),r={type:"shared-worker-console-log",message:e};n.forEach((e=>{e&&A(e,r)}))},te=(e,t,n)=>{if(!d)return;const r=n?[n]:Object.values(f),i={type:"shared-worker-console-dir",message:t,data:e};r.forEach((e=>{e&&A(e,i)}))},ne=e=>Object.keys(e).map((t=>{const n=e[t];return Array.isArray(n)?n.map((e=>`${t}=${re(e)}`)).join("&"):`${t}=${re(n)}`})).join("&"),re=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`))})); +!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";function e(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{l(r.next(e))}catch(e){s(e)}}function c(e){try{l(r.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,c)}l((r=r.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n,r,i={exports:{}}; +/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */n=i,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 i(e,t){var r=n[t||"all"];return r&&r.test(e)||!1}r.isUUID=i,r.VERSION=t,e.uuid=r,e.isUUID=i}(r=i.exports),null!==n&&(n.exports=r.uuid);var s=t(i.exports),o={createUUID:()=>s.uuid?s.uuid():s()};const c=1e4,l=new Map,u=new TextDecoder;let a,d=!1;const h=o.createUUID(),p=new Map,f={},b={},g={},v={},y={},q={};self.onconnect=e=>{ee("New PubNub Client connected to the Subscription Shared Worker."),e.ports.forEach((e=>{e.start(),e.onmessage=t=>{if(!J(t))return;const n=t.data;if("client-register"===n.type)!d&&n.workerLogVerbosity&&(d=!0),n.port=e,U(n),ee(`Client '${n.clientIdentifier}' registered with '${h}' shared worker`);else if("client-pong"===n.type)V(n);else if("send-request"===n.type)if(n.request.path.startsWith("/v2/subscribe")){L(n);const e=f[n.clientIdentifier];if(e){const t=`${e.userId}-${e.subscriptionKey}`;if(!l.has(t)){const e=setTimeout((()=>{I(n),l.delete(t)}),50);l.set(t,e)}}}else n.request.path.endsWith("/heartbeat")?(N(n),w(n)):j(n);else"cancel-request"===n.type&&O(n)},e.postMessage({type:"shared-worker-connected"})}))};const I=e=>{var t;const n=A(e),r=f[e.clientIdentifier];let i=!1;if(r&&(r.subscription&&(i="0"===r.subscription.timetoken),C("start",[r],(new Date).toISOString(),e.request)),"string"==typeof n){const s=q[n];if(r){if(r.subscription&&(r.subscription.timetoken=s.timetoken,r.subscription.region=s.region,r.subscription.serviceRequestId=n),!i)return;const o=(new TextEncoder).encode(`{"t":{"t":"${s.timetoken}","r":${null!==(t=s.region)&&void 0!==t?t:"0"}},"m":[]}`),c=new Headers({"Content-Type":'text/javascript; charset="UTF-8"',"Content-Length":`${o.length}`}),l=new Response(o,{status:200,headers:c}),u=D([l,o]);u.url=`${e.request.origin}${e.request.path}`,u.clientIdentifier=e.clientIdentifier,u.identifier=e.request.identifier,C("end",[r],(new Date).toISOString(),e.request,o,c.get("Content-Type"),0),R(r,u)}return}e.request.cancellable&&p.set(n.identifier,new AbortController);const s=q[n.identifier],{timetokenOverride:o,regionOverride:c}=s;S(n,(()=>E(n.identifier)),((t,r)=>{F(t,r,e.request),G(t,n.identifier)}),((t,r)=>{F(t,null,e.request,W(r)),G(t,n.identifier)}),(e=>{let t=e;return i&&o&&"0"!==o&&(q[n.identifier],t=m(t,o,c)),t})),ee(`'${Object.keys(q).length}' subscription request currently active.`)},m=(e,t,n)=>{if(void 0===t||"0"===t||e[0].status>=400)return e;let r;const i=e[0];let s=i,o=e[1];try{r=JSON.parse((new TextDecoder).decode(o))}catch(t){return ee(`Subscribe response parse error: ${t}`),e}r.t.t=t,n&&(r.t.r=parseInt(n,10));try{if(o=(new TextEncoder).encode(JSON.stringify(r)).buffer,o.byteLength){const e=new Headers(i.headers);e.set("Content-Length",`${o.byteLength}`),s=new Response(o,{status:i.status,statusText:i.statusText,headers:e})}}catch(t){return ee(`Subscribe serialization error: ${t}`),e}return o.byteLength>0?[s,o]:e},w=e=>{var t;const n=f[e.clientIdentifier],r=x(e);if(!n)return;const i=`${n.userId}_${null!==(t=n.authKey)&&void 0!==t?t:""}`,s=g[n.subscriptionKey],o=(null!=s?s:{})[i];if(C("start",[n],(new Date).toISOString(),r),!r){let t,r;if(ee(`Previous heartbeat request has been sent less than ${n.heartbeatInterval} seconds ago. Skipping...`),o&&o.response&&([t,r]=o.response),!t){r=(new TextEncoder).encode('{ "status": 200, "message": "OK", "service": "Presence" }').buffer;const e=new Headers({"Content-Type":'text/javascript; charset="UTF-8"',"Content-Length":`${r.byteLength}`});t=new Response(r,{status:200,headers:e})}const i=D([t,r]);return i.url=`${e.request.origin}${e.request.path}`,i.clientIdentifier=e.clientIdentifier,i.identifier=e.request.identifier,C("end",[n],(new Date).toISOString(),e.request,r,t.headers.get("Content-Type"),0),void R(n,i)}S(r,(()=>[n]),((t,n)=>{o&&(o.response=n),F(t,n,e.request)}),((t,n)=>{F(t,null,e.request,W(n))})),ee("Started heartbeat request.",n)},j=e=>{const t=f[e.clientIdentifier],n=K(e);if(!t)return;const{subscription:r}=t,i=null==r?void 0:r.serviceRequestId;if(r&&0===r.channels.length&&0===r.channelGroups.length&&(r.channelGroupQuery="",r.path="",r.previousTimetoken="0",r.timetoken="0",delete r.region,delete r.serviceRequestId,delete r.request),!n){const n=(new TextEncoder).encode('{"status": 200, "action": "leave", "message": "OK", "service":"Presence"}'),r=new Headers({"Content-Type":'text/javascript; charset="UTF-8"',"Content-Length":`${n.length}`}),i=new Response(n,{status:200,headers:r}),s=D([i,n]);return s.url=`${e.request.origin}${e.request.path}`,s.clientIdentifier=e.clientIdentifier,s.identifier=e.request.identifier,void R(t,s)}if(S(n,(()=>[t]),((t,n)=>{F(t,n,e.request)}),((t,n)=>{F(t,null,e.request,W(n))})),ee("Started leave request.",t),void 0===i)return;const s=E(i);s.forEach((e=>{e&&e.subscription&&delete e.subscription.serviceRequestId})),k(i),$(s)},O=e=>{const t=f[e.clientIdentifier];if(!t||!t.subscription)return;const n=t.subscription.serviceRequestId;t&&n&&(delete t.subscription.serviceRequestId,t.subscription.request&&t.subscription.request.identifier===e.identifier&&delete t.subscription.request,k(n))},$=e=>{let t,n;for(const r of e)if(r.subscription&&r.subscription.request){n=r.subscription.request,t=r;break}n&&t&&I({type:"send-request",clientIdentifier:t.clientIdentifier,subscriptionKey:t.subscriptionKey,logVerbosity:t.logVerbosity,request:n})},S=(t,n,r,i,s)=>{e(void 0,void 0,void 0,(function*(){var e;const o=(new Date).getTime();Promise.race([fetch(T(t),{signal:null===(e=p.get(t.identifier))||void 0===e?void 0:e.signal,keepalive:!0}),P(t.identifier,t.timeout)]).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>s?s(e):e)).then((e=>{const i=e[1].byteLength>0?e[1]:void 0,s=n();0!==s.length&&(C("end",s,(new Date).toISOString(),t,i,e[0].headers.get("Content-Type"),(new Date).getTime()-o),r(s,e))})).catch((e=>{const t=n();if(0===t.length)return;let r=e;if("string"==typeof e){const t=e.toLowerCase();t.includes("timeout")||!t.includes("cancel")?r=new Error(e):t.includes("cancel")&&(r=new DOMException("Aborted","AbortError"))}i(t,r)}))}))},k=e=>{if(0===E(e).length){const t=p.get(e);p.delete(e),delete q[e],t&&t.abort("Cancel request")}},P=(e,t)=>new Promise(((n,r)=>{const i=setTimeout((()=>{p.delete(e),clearTimeout(i),r(new Error("Request timeout"))}),1e3*t)})),E=e=>Object.values(f).filter((t=>void 0!==t&&void 0!==t.subscription&&t.subscription.serviceRequestId===e)),G=(e,t)=>{delete q[t],e.forEach((e=>{e.subscription&&(delete e.subscription.request,delete e.subscription.serviceRequestId)}))},T=e=>{let t;const n=e.queryParameters;let r=e.path;if(e.headers){t={};for(const[n,r]of Object.entries(e.headers))t[n]=r}return n&&0!==Object.keys(n).length&&(r=`${r}?${ne(n)}`),new Request(`${e.origin}${r}`,{method:e.method,headers:t,redirect:"follow"})},A=e=>{var t,n,r,i,s;const c=f[e.clientIdentifier],l=c.subscription,u=Q(l.timetoken,e),a=o.createUUID(),h=Object.assign({},e.request);let p,b;if(u.length>1){const s=_(u,e);if(s){const e=q[s],{channels:n,channelGroups:r}=null!==(t=c.subscription)&&void 0!==t?t:{channels:[],channelGroups:[]};if((!(n.length>0)||Y(e.channels,n))&&(!(r.length>0)||Y(e.channelGroups,r)))return s}const o=(null!==(n=v[c.subscriptionKey])&&void 0!==n?n:{})[c.userId],d={},f=new Set(l.channelGroups),g=new Set(l.channels);o&&l.objectsWithState.length&&l.objectsWithState.forEach((e=>{const t=o[e];t&&(d[e]=t)}));for(const e of u){const{subscription:t}=e;if(!t)continue;1!==u.length&&e.clientIdentifier===c.clientIdentifier||!t.timetoken||(p=t.timetoken,b=t.region),t.channelGroups.forEach(f.add,f),t.channels.forEach(g.add,g);const n=t.serviceRequestId;t.serviceRequestId=a,n&&q[n]&&k(n),o&&t.objectsWithState.forEach((e=>{const t=o[e];t&&!d[e]&&(d[e]=t)}))}const y=null!==(r=q[a])&&void 0!==r?r:q[a]={requestId:a,timetoken:null!==(i=h.queryParameters.tt)&&void 0!==i?i:"0",channelGroups:[],channels:[]};if(g.size){y.channels=Array.from(g).sort();const e=h.path.split("/");e[4]=y.channels.join(","),h.path=e.join("/")}f.size&&(y.channelGroups=Array.from(f).sort(),h.queryParameters["channel-group"]=y.channelGroups.join(",")),Object.keys(d).length&&(h.queryParameters.state=JSON.stringify(d))}else q[a]={requestId:a,timetoken:null!==(s=h.queryParameters.tt)&&void 0!==s?s:"0",channelGroups:l.channelGroups,channels:l.channels};if(q[a]&&(h.queryParameters&&void 0!==h.queryParameters.tt&&void 0!==h.queryParameters.tr&&(q[a].region=h.queryParameters.tr),q[a].timetokenOverride=p,q[a].regionOverride=b),l.serviceRequestId=a,h.identifier=a,d){const e=u.reduce(((e,{clientIdentifier:t})=>(e.push(t),e)),[]).join(",");te(q[a],`Started aggregated request for clients: ${e}`)}return h},x=e=>{var t,n,r,i,s;const o=f[e.clientIdentifier],c=B(e),l=Object.assign({},e.request);if(!o||!o.heartbeat)return;const u=null!==(t=g[s=o.subscriptionKey])&&void 0!==t?t:g[s]={},a=`${o.userId}_${null!==(n=o.authKey)&&void 0!==n?n:""}`,d=o.heartbeat.channelGroups,h=o.heartbeat.channels;let p={},b=!1,v=!0;if(u[a]){const{channels:e,channelGroups:t,response:n}=u[a];p=null!==(i=o.heartbeat.presenceState)&&void 0!==i?i:{},v=Y(e,o.heartbeat.channels)&&Y(t,o.heartbeat.channelGroups),n&&(b=n[0].status>=400)}else u[a]={channels:h,channelGroups:d,timestamp:Date.now()},p=null!==(r=o.heartbeat.presenceState)&&void 0!==r?r:{},v=!1;if(v){const t=u[a].timestamp+1e3*o.heartbeatInterval,n=Date.now();if(!b&&n5e3)return;delete u[a].response;for(const t of c){const{heartbeat:n}=t;void 0!==n&&t.clientIdentifier!==e.clientIdentifier&&(n.presenceState&&(p=Object.assign(Object.assign({},p),n.presenceState)),d.push(...n.channelGroups.filter((e=>!d.includes(e)))),h.push(...n.channels.filter((e=>!h.includes(e)))))}}u[a].channels=h,u[a].channelGroups=d,u[a].timestamp=Date.now();for(const e in Object.keys(p))h.includes(e)||d.includes(e)||delete p[e];if(h.length){const e=l.path.split("/");e[6]=h.join(","),l.path=e.join("/")}return d.length&&(l.queryParameters["channel-group"]=d.join(",")),Object.keys(p).length?l.queryParameters.state=JSON.stringify(p):delete l.queryParameters.state,l},K=e=>{const t=f[e.clientIdentifier],n=H(e);let r=X(e.request),i=z(e.request);const s=Object.assign({},e.request);if(t&&t.subscription){const{subscription:e}=t;i.length&&(e.channels=e.channels.filter((e=>!i.includes(e)))),r.length&&(e.channelGroups=e.channelGroups.filter((e=>!r.includes(e))))}if(t&&t.heartbeat){const{heartbeat:e}=t;i.length&&(e.channels=e.channels.filter((e=>!i.includes(e)))),r.length&&(e.channelGroups=e.channelGroups.filter((e=>!r.includes(e))))}for(const t of n){const n=t.subscription;void 0!==n&&(t.clientIdentifier!==e.clientIdentifier&&(i.length&&(i=i.filter((e=>!n.channels.includes(e)))),r.length&&(r=r.filter((e=>!n.channelGroups.includes(e))))))}if(0!==i.length||0!==r.length){if(i.length){const e=s.path.split("/");e[6]=i.join(","),s.path=e.join("/")}return r.length&&(s.queryParameters["channel-group"]=r.join(",")),s}if(d&&t){const e=n.reduce(((e,{clientIdentifier:t})=>(e.push(t),e)),[]).join(",");ee(`Specified channels and groups still in use by other clients: ${e}. Ignoring leave request.`,t)}},R=(e,t)=>{var n;const r=(null!==(n=y[e.subscriptionKey])&&void 0!==n?n:{})[e.clientIdentifier];if(!r)return!1;try{return r.postMessage(t),!0}catch(e){}return!1},C=(e,t,n,r,i,s,o)=>{var c,l;if(0===t.length)return;const a=null!==(c=y[t[0].subscriptionKey])&&void 0!==c?c:{},d=r&&r.path.startsWith("/v2/subscribe");let h;if("start"===e)h={type:"request-progress-start",clientIdentifier:"",url:"",timestamp:n};else{let e;i&&s&&(-1!==s.indexOf("text/javascript")||-1!==s.indexOf("application/json")||-1!==s.indexOf("text/plain")||-1!==s.indexOf("text/html"))&&(e=u.decode(i)),h={type:"request-progress-end",clientIdentifier:"",url:"",response:e,timestamp:n,duration:o}}for(const e of t){if(d&&!e.subscription)continue;const t=a[e.clientIdentifier],{request:n}=null!==(l=e.subscription)&&void 0!==l?l:{};let i=null!=n?n:r;if(d||(i=r),e.logVerbosity&&t&&i){const t=Object.assign(Object.assign({},h),{clientIdentifier:e.clientIdentifier,url:`${i.origin}${i.path}`,query:i.queryParameters});R(e,t)}}},F=(e,t,n,r)=>{var i,s;if(0===e.length)return;if(!r&&!t)return;const o=null!==(i=y[e[0].subscriptionKey])&&void 0!==i?i:{},c=n&&n.path.startsWith("/v2/subscribe");!r&&t&&(r=t[0].status>=400?W(void 0,t):D(t));for(const t of e){if(c&&!t.subscription)continue;const e=o[t.clientIdentifier],{request:i}=null!==(s=t.subscription)&&void 0!==s?s:{};let l=null!=i?i:n;if(c||(l=n),e&&l){const e=Object.assign(Object.assign({},r),{clientIdentifier:t.clientIdentifier,identifier:l.identifier,url:`${l.origin}${l.path}`});R(t,e)}}},D=e=>{var t;const[n,r]=e,i=r.byteLength>0?r:void 0,s=parseInt(null!==(t=n.headers.get("Content-Length"))&&void 0!==t?t:"0",10),o=n.headers.get("Content-Type"),c={};return n.headers.forEach(((e,t)=>c[t]=e.toLowerCase())),{type:"request-process-success",clientIdentifier:"",identifier:"",url:"",response:{contentLength:s,contentType:o,headers:c,status:n.status,body:i}}},W=(e,t)=>{if(t)return Object.assign(Object.assign({},D(t)),{type:"request-process-error"});let n="NETWORK_ISSUE",r="Unknown error",i="Error";return e&&e instanceof Error&&(r=e.message,i=e.name),r.toLowerCase().includes("timeout")?n="TIMEOUT":("AbortError"===i||r.toLowerCase().includes("cancel"))&&(r="Request aborted",n="ABORTED"),{type:"request-process-error",clientIdentifier:"",identifier:"",url:"",error:{name:i,type:n,message:r}}},U=e=>{var t,n,r,i;const{clientIdentifier:s}=e;if(f[s])return;const o=f[s]={clientIdentifier:s,subscriptionKey:e.subscriptionKey,userId:e.userId,heartbeatInterval:e.heartbeatInterval,logVerbosity:e.logVerbosity},l=null!==(t=b[r=e.subscriptionKey])&&void 0!==t?t:b[r]=[];l.every((e=>e.clientIdentifier!==s))&&l.push(o),(null!==(n=y[i=e.subscriptionKey])&&void 0!==n?n:y[i]={})[s]=e.port,ee(`Registered PubNub client with '${s}' identifier. '${Object.keys(f).length}' clients currently active.`),!a&&Object.keys(f).length>0&&(ee("Setup PubNub client ping event 10 seconds"),a=setInterval((()=>Z()),c))},L=e=>{var t,n,r,i,s,o,c,l,u,a,d,h,p,b,g,y,q,I,m,w;const j=e.request.queryParameters,{clientIdentifier:O}=e,$=f[O];if(!$)return;const S=null!==(t=j["channel-group"])&&void 0!==t?t:"",k=null!==(n=j.state)&&void 0!==n?n:"";let P=$.subscription;if(P){if(k.length>0){const e=JSON.parse(k),t=null!==(o=(y=null!==(s=v[g=$.subscriptionKey])&&void 0!==s?s:v[g]={})[q=$.userId])&&void 0!==o?o:y[q]={};Object.entries(e).forEach((([e,n])=>t[e]=n));for(const n of P.objectsWithState)e[n]||delete t[n];P.objectsWithState=Object.keys(e)}else if(P.objectsWithState.length){const e=null!==(l=(m=null!==(c=v[I=$.subscriptionKey])&&void 0!==c?c:v[I]={})[w=$.userId])&&void 0!==l?l:m[w]={};for(const t of P.objectsWithState)delete e[t];P.objectsWithState=[]}}else{if(P={path:"",channelGroupQuery:"",channels:[],channelGroups:[],previousTimetoken:"0",timetoken:"0",objectsWithState:[]},k.length>0){const e=JSON.parse(k),t=null!==(i=(p=null!==(r=v[h=$.subscriptionKey])&&void 0!==r?r:v[h]={})[b=$.userId])&&void 0!==i?i:p[b]={};Object.entries(e).forEach((([e,n])=>t[e]=n)),P.objectsWithState=Object.keys(e)}$.subscription=P}P.path!==e.request.path&&(P.path=e.request.path,P.channels=z(e.request)),P.channelGroupQuery!==S&&(P.channelGroupQuery=S,P.channelGroups=X(e.request));const{authKey:E,userId:G}=$;P.request=e.request,P.filterExpression=null!==(u=j["filter-expr"])&&void 0!==u?u:"",P.timetoken=null!==(a=j.tt)&&void 0!==a?a:"0",void 0!==j.tr&&(P.region=j.tr),$.authKey=null!==(d=j.auth)&&void 0!==d?d:"",$.userId=j.uuid,M($,G,E)},N=e=>{var t,n;const r=f[e.clientIdentifier],{request:i}=e;if(!r)return;const s=null!==(t=r.heartbeat)&&void 0!==t?t:r.heartbeat={channels:[],channelGroups:[]};s.channelGroups=X(i).filter((e=>!e.endsWith("-pnpres"))),s.channels=z(i).filter((e=>!e.endsWith("-pnpres")));const o=null!==(n=i.queryParameters.state)&&void 0!==n?n:"";if(o.length>0){const e=JSON.parse(o);for(const t of Object.keys(e))s.channels.includes(t)||s.channelGroups.includes(t)||delete e[t];s.presenceState=e}},M=(e,t,n)=>{var r,i;if(!e||t===e.userId&&(null!=n?n:"")===(null!==(r=e.authKey)&&void 0!==r?r:""))return;const s=null!==(i=g[e.subscriptionKey])&&void 0!==i?i:{},o=`${t}_${null!=n?n:""}`;void 0!==s[o]&&delete s[o]},V=e=>{const t=f[e.clientIdentifier];t&&(t.lastPongEvent=(new Date).getTime()/1e3)},J=e=>{const{clientIdentifier:t,subscriptionKey:n,logVerbosity:r}=e.data;return void 0!==r&&"boolean"==typeof r&&(!(!t||"string"!=typeof t)&&!(!n||"string"!=typeof n))},_=(e,t)=>{var n;const r=null!==(n=t.request.queryParameters["channel-group"])&&void 0!==n?n:"",i=t.request.path;let s,o;for(const n of e){const{subscription:e}=n;if(!e||!e.serviceRequestId)continue;const c=f[t.clientIdentifier],l=e.serviceRequestId;if(e.path===i&&e.channelGroupQuery===r)return ee(`Found identical request started by '${n.clientIdentifier}' client. \nWaiting for existing '${l}' request completion.`,c),e.serviceRequestId;{const r=q[e.serviceRequestId];if(s||(s=X(t.request)),o||(o=z(t.request)),o.length&&!Y(r.channels,o))continue;if(s.length&&!Y(r.channelGroups,s))continue;return te(r,`'${t.request.identifier}' request channels and groups are subset of ongoing '${l}' request \nwhich has started by '${n.clientIdentifier}' client. Waiting for existing '${l}' request completion.`,c),e.serviceRequestId}}},Q=(e,t)=>{var n,r,i;const s=t.request.queryParameters,o=null!==(n=s["filter-expr"])&&void 0!==n?n:"",c=null!==(r=s.auth)&&void 0!==r?r:"",l=s.uuid;return(null!==(i=b[t.subscriptionKey])&&void 0!==i?i:[]).filter((t=>t.userId===l&&t.authKey===c&&t.subscription&&(0!==t.subscription.channels.length||0!==t.subscription.channelGroups.length)&&t.subscription.filterExpression===o&&("0"===e||"0"===t.subscription.timetoken||t.subscription.timetoken===e)))},B=e=>H(e),H=e=>{var t,n;const r=e.request.queryParameters,i=null!==(t=r.auth)&&void 0!==t?t:"",s=r.uuid;return(null!==(n=b[e.subscriptionKey])&&void 0!==n?n:[]).filter((e=>e.userId===s&&e.authKey===i))},z=e=>{const t=e.path.split("/")[e.path.startsWith("/v2/subscribe/")?4:6];return","===t?[]:t.split(",").filter((e=>e.length>0))},X=e=>{var t;const n=null!==(t=e.queryParameters["channel-group"])&&void 0!==t?t:"";return 0===n.length?[]:n.split(",").filter((e=>e.length>0))},Y=(e,t)=>{const n=new Set(e);return t.every(n.has,n)},Z=()=>{ee("Pinging clients...");const e={type:"shared-worker-ping"};Object.values(f).forEach((t=>{let n=!1;t&&t.lastPingRequest&&(ee(`Checking whether ${t.clientIdentifier} ping has been sent too long ago...`),(!t.lastPongEvent||Math.abs(t.lastPongEvent-t.lastPingRequest)>5)&&(n=!0,ee(`'${t.clientIdentifier}' client is inactive. Invalidating.`),((e,t)=>{delete f[t];let n=b[e];if(n)if(n=n.filter((e=>e.clientIdentifier!==t)),n.length>0?b[e]=n:(delete b[e],delete g[e]),0===n.length&&delete v[e],n.length>0){const n=y[e];n&&(delete n[t],0===Object.keys(n).length&&delete y[e])}else delete y[e];ee(`Invalidate '${t}' client. '${Object.keys(f).length}' clients currently active.`)})(t.subscriptionKey,t.clientIdentifier))),t&&!n&&(ee(`Sending ping to ${t.clientIdentifier}...`),t.lastPingRequest=(new Date).getTime()/1e3,R(t,e))})),0===Object.keys(f).length&&a&&clearInterval(a)},ee=(e,t)=>{if(!d)return;const n=t?[t]:Object.values(f),r={type:"shared-worker-console-log",message:e};n.forEach((e=>{e&&R(e,r)}))},te=(e,t,n)=>{if(!d)return;const r=n?[n]:Object.values(f),i={type:"shared-worker-console-dir",message:t,data:e};r.forEach((e=>{e&&R(e,i)}))},ne=e=>Object.keys(e).map((t=>{const n=e[t];return Array.isArray(n)?n.map((e=>`${t}=${re(e)}`)).join("&"):`${t}=${re(n)}`})).join("&"),re=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`))})); diff --git a/lib/core/components/request.js b/lib/core/components/request.js index b3d050940..7196b965d 100644 --- a/lib/core/components/request.js +++ b/lib/core/components/request.js @@ -19,7 +19,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) { Object.defineProperty(exports, "__esModule", { value: true }); exports.AbstractRequest = void 0; const transport_request_1 = require("../types/transport-request"); +const pubnub_error_1 = require("../../errors/pubnub-error"); const uuid_1 = __importDefault(require("./uuid")); +const pubnub_api_error_1 = require("../../errors/pubnub-api-error"); /** * Base REST API request class. * @@ -62,10 +64,12 @@ class AbstractRequest { } /** * Abort request if possible. + * + * @param [reason] Information about why request has been cancelled. */ - abort() { + abort(reason) { if (this && this.cancellationController) - this.cancellationController.abort(); + this.cancellationController.abort(reason); } /** * Target REST API endpoint operation type. @@ -84,11 +88,11 @@ class AbstractRequest { /** * Parse service response. * - * @param _response - Raw service response which should be parsed. + * @param response - Raw service response which should be parsed. */ - parse(_response) { + parse(response) { return __awaiter(this, void 0, void 0, function* () { - throw Error('Should be implemented by subclass.'); + return this.deserializeResponse(response); }); } /** @@ -160,21 +164,29 @@ class AbstractRequest { * * @param response - Transparent response object with headers and body information. * - * @returns Deserialized data or `undefined` in case of `JSON.parse(..)` error. + * @returns Deserialized service response data. + * + * @throws {Error} if received service response can't be processed (has unexpected content-type or can't be parsed as + * JSON). */ deserializeResponse(response) { + const responseText = AbstractRequest.decoder.decode(response.body); const contentType = response.headers['content-type']; + let parsedJson; if (!contentType || (contentType.indexOf('javascript') === -1 && contentType.indexOf('json') === -1)) - return undefined; - const json = AbstractRequest.decoder.decode(response.body); + throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createMalformedResponseError)(responseText, response.status)); try { - const parsedJson = JSON.parse(json); - return parsedJson; + parsedJson = JSON.parse(responseText); } catch (error) { console.error('Error parsing JSON response:', error); - return undefined; + throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createMalformedResponseError)(responseText, response.status)); + } + // Throw and exception in case of client / server error. + if ('status' in parsedJson && typeof parsedJson.status === 'number' && parsedJson.status >= 400) { + throw pubnub_api_error_1.PubNubAPIError.create(response); } + return parsedJson; } } exports.AbstractRequest = AbstractRequest; diff --git a/lib/core/components/subscription-manager.js b/lib/core/components/subscription-manager.js index d8b1dcd49..ae58f99fe 100644 --- a/lib/core/components/subscription-manager.js +++ b/lib/core/components/subscription-manager.js @@ -22,8 +22,8 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.SubscriptionManager = void 0; const reconnection_manager_1 = require("./reconnection_manager"); const categories_1 = __importDefault(require("../constants/categories")); -const deduping_manager_1 = require("./deduping_manager"); const categories_2 = __importDefault(require("../constants/categories")); +const deduping_manager_1 = require("./deduping_manager"); /** * Subscription loop manager. * @@ -256,13 +256,15 @@ class SubscriptionManager { this.reconnectionManager.startPolling(); this.listenerManager.announceStatus(status); } - else if (status.category === categories_2.default.PNBadRequestCategory) { - this.stopHeartbeatTimer(); - this.listenerManager.announceStatus(status); + else if (status.category === categories_2.default.PNBadRequestCategory || + status.category == categories_2.default.PNMalformedResponseCategory) { + const category = this.isOnline ? categories_1.default.PNDisconnectedUnexpectedlyCategory : status.category; + this.isOnline = false; + this.disconnect(); + this.listenerManager.announceStatus(Object.assign(Object.assign({}, status), { category })); } - else { + else this.listenerManager.announceStatus(status); - } return; } if (this.storedTimetoken) { diff --git a/lib/core/constants/categories.js b/lib/core/constants/categories.js index faab584be..cffeb25aa 100644 --- a/lib/core/constants/categories.js +++ b/lib/core/constants/categories.js @@ -35,6 +35,14 @@ var StatusCategory; * Some API endpoints respond with request processing status w/o useful data. */ StatusCategory["PNAcknowledgmentCategory"] = "PNAcknowledgmentCategory"; + /** + * PubNub service or intermediate "actor" returned unexpected response. + * + * There can be few sources of unexpected return with success code: + * - proxy server / VPN; + * - Wi-Fi hotspot authorization page. + */ + StatusCategory["PNMalformedResponseCategory"] = "PNMalformedResponseCategory"; /** * Something strange happened; please check the logs. */ diff --git a/lib/core/endpoints/access_manager/audit.js b/lib/core/endpoints/access_manager/audit.js index e3a78d4bb..929eb1d8d 100644 --- a/lib/core/endpoints/access_manager/audit.js +++ b/lib/core/endpoints/access_manager/audit.js @@ -18,8 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.AuditRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); // -------------------------------------------------------- @@ -54,13 +52,7 @@ class AuditRequest extends request_1.AbstractRequest { } parse(response) { return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return serviceResponse.payload; + return this.deserializeResponse(response).payload; }); } get path() { diff --git a/lib/core/endpoints/access_manager/grant.js b/lib/core/endpoints/access_manager/grant.js index d1b0735f8..e1a3ab37f 100644 --- a/lib/core/endpoints/access_manager/grant.js +++ b/lib/core/endpoints/access_manager/grant.js @@ -18,8 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.GrantRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); // -------------------------------------------------------- @@ -96,13 +94,7 @@ class GrantRequest extends request_1.AbstractRequest { } parse(response) { return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return serviceResponse.payload; + return this.deserializeResponse(response).payload; }); } get path() { diff --git a/lib/core/endpoints/access_manager/grant_token.js b/lib/core/endpoints/access_manager/grant_token.js index 5440ccc4e..1ad1d5151 100644 --- a/lib/core/endpoints/access_manager/grant_token.js +++ b/lib/core/endpoints/access_manager/grant_token.js @@ -18,8 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.GrantTokenRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const transport_request_1 = require("../../types/transport-request"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); @@ -77,13 +75,7 @@ class GrantTokenRequest extends request_1.AbstractRequest { } parse(response) { return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return serviceResponse.data.token; + return this.deserializeResponse(response).data.token; }); } get path() { diff --git a/lib/core/endpoints/access_manager/revoke_token.js b/lib/core/endpoints/access_manager/revoke_token.js index 270365fda..71565caf6 100644 --- a/lib/core/endpoints/access_manager/revoke_token.js +++ b/lib/core/endpoints/access_manager/revoke_token.js @@ -18,8 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.RevokeTokenRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const transport_request_1 = require("../../types/transport-request"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); @@ -47,14 +45,11 @@ class RevokeTokenRequest extends request_1.AbstractRequest { return "token can't be empty"; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return {}; + return _super.parse.call(this, response).then(() => ({})); }); } get path() { diff --git a/lib/core/endpoints/actions/add_message_action.js b/lib/core/endpoints/actions/add_message_action.js index e9b368f9b..4be106070 100644 --- a/lib/core/endpoints/actions/add_message_action.js +++ b/lib/core/endpoints/actions/add_message_action.js @@ -18,8 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.AddMessageActionRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const transport_request_1 = require("../../types/transport-request"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); @@ -56,14 +54,11 @@ class AddMessageActionRequest extends request_1.AbstractRequest { return 'Action.type value exceed maximum length of 15'; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return { data: serviceResponse.data }; + return _super.parse.call(this, response).then(({ data }) => ({ data })); }); } get path() { diff --git a/lib/core/endpoints/actions/get_message_actions.js b/lib/core/endpoints/actions/get_message_actions.js index e4f0eb11e..f6f28fbde 100644 --- a/lib/core/endpoints/actions/get_message_actions.js +++ b/lib/core/endpoints/actions/get_message_actions.js @@ -18,8 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.GetMessageActionsRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); @@ -46,11 +44,6 @@ class GetMessageActionsRequest extends request_1.AbstractRequest { parse(response) { return __awaiter(this, void 0, void 0, function* () { const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); let start = null; let end = null; if (serviceResponse.data.length > 0) { diff --git a/lib/core/endpoints/actions/remove_message_action.js b/lib/core/endpoints/actions/remove_message_action.js index 648d06159..b138ba376 100644 --- a/lib/core/endpoints/actions/remove_message_action.js +++ b/lib/core/endpoints/actions/remove_message_action.js @@ -18,8 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.RemoveMessageAction = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const transport_request_1 = require("../../types/transport-request"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); @@ -50,14 +48,11 @@ class RemoveMessageAction extends request_1.AbstractRequest { return 'Missing action timetoken'; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return { data: serviceResponse.data }; + return _super.parse.call(this, response).then(({ data }) => ({ data })); }); } get path() { diff --git a/lib/core/endpoints/channel_groups/add_channels.js b/lib/core/endpoints/channel_groups/add_channels.js index 23468abe8..ec42b5c61 100644 --- a/lib/core/endpoints/channel_groups/add_channels.js +++ b/lib/core/endpoints/channel_groups/add_channels.js @@ -18,8 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.AddChannelGroupChannelsRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); @@ -47,14 +45,11 @@ class AddChannelGroupChannelsRequest extends request_1.AbstractRequest { return 'Missing channels'; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return {}; + return _super.parse.call(this, response).then((_) => ({})); }); } get path() { diff --git a/lib/core/endpoints/channel_groups/delete_group.js b/lib/core/endpoints/channel_groups/delete_group.js index adbb517f5..95339166a 100644 --- a/lib/core/endpoints/channel_groups/delete_group.js +++ b/lib/core/endpoints/channel_groups/delete_group.js @@ -18,8 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.DeleteChannelGroupRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); @@ -44,14 +42,11 @@ class DeleteChannelGroupRequest extends request_1.AbstractRequest { return 'Missing Channel Group'; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return {}; + return _super.parse.call(this, response).then((_) => ({})); }); } get path() { diff --git a/lib/core/endpoints/channel_groups/list_channels.js b/lib/core/endpoints/channel_groups/list_channels.js index 1b0450c9e..fa585a3b2 100644 --- a/lib/core/endpoints/channel_groups/list_channels.js +++ b/lib/core/endpoints/channel_groups/list_channels.js @@ -18,8 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ListChannelGroupChannels = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); @@ -45,13 +43,7 @@ class ListChannelGroupChannels extends request_1.AbstractRequest { } parse(response) { return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return { channels: serviceResponse.payload.channels }; + return { channels: this.deserializeResponse(response).payload.channels }; }); } get path() { diff --git a/lib/core/endpoints/channel_groups/list_groups.js b/lib/core/endpoints/channel_groups/list_groups.js index 405a9a9aa..5455884e2 100644 --- a/lib/core/endpoints/channel_groups/list_groups.js +++ b/lib/core/endpoints/channel_groups/list_groups.js @@ -18,8 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ListChannelGroupsRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); // endregion @@ -42,13 +40,7 @@ class ListChannelGroupsRequest extends request_1.AbstractRequest { } parse(response) { return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return { groups: serviceResponse.payload.groups }; + return { groups: this.deserializeResponse(response).payload.groups }; }); } get path() { diff --git a/lib/core/endpoints/channel_groups/remove_channels.js b/lib/core/endpoints/channel_groups/remove_channels.js index b4472116b..f748b0dd0 100644 --- a/lib/core/endpoints/channel_groups/remove_channels.js +++ b/lib/core/endpoints/channel_groups/remove_channels.js @@ -18,8 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.RemoveChannelGroupChannelsRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); @@ -48,14 +46,11 @@ class RemoveChannelGroupChannelsRequest extends request_1.AbstractRequest { return 'Missing channels'; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return {}; + return _super.parse.call(this, response).then((_) => ({})); }); } get path() { diff --git a/lib/core/endpoints/fetch_messages.js b/lib/core/endpoints/fetch_messages.js index 758894a70..3d65d7d06 100644 --- a/lib/core/endpoints/fetch_messages.js +++ b/lib/core/endpoints/fetch_messages.js @@ -41,8 +41,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.FetchMessagesRequest = void 0; -const pubnub_error_1 = require("../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../errors/pubnub-api-error"); const request_1 = require("../components/request"); const operations_1 = __importDefault(require("../constants/operations")); const History = __importStar(require("../types/api/history")); @@ -121,11 +119,6 @@ class FetchMessagesRequest extends request_1.AbstractRequest { return __awaiter(this, void 0, void 0, function* () { var _a; const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); const responseChannels = (_a = serviceResponse.channels) !== null && _a !== void 0 ? _a : {}; const channels = {}; Object.keys(responseChannels).forEach((channel) => { diff --git a/lib/core/endpoints/file_upload/delete_file.js b/lib/core/endpoints/file_upload/delete_file.js index f916e6653..ba9a038b2 100644 --- a/lib/core/endpoints/file_upload/delete_file.js +++ b/lib/core/endpoints/file_upload/delete_file.js @@ -4,22 +4,11 @@ * * @internal */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.DeleteFileRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const transport_request_1 = require("../../types/transport-request"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); @@ -47,17 +36,6 @@ class DeleteFileRequest extends request_1.AbstractRequest { if (!name) return "file name can't be empty"; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, id, channel, name, } = this.parameters; return `/v1/files/${subscribeKey}/channels/${(0, utils_1.encodeString)(channel)}/files/${id}/${name}`; diff --git a/lib/core/endpoints/file_upload/generate_upload_url.js b/lib/core/endpoints/file_upload/generate_upload_url.js index 5c621f062..57416cea1 100644 --- a/lib/core/endpoints/file_upload/generate_upload_url.js +++ b/lib/core/endpoints/file_upload/generate_upload_url.js @@ -18,8 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.GenerateFileUploadUrlRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const transport_request_1 = require("../../types/transport-request"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); @@ -47,11 +45,6 @@ class GenerateFileUploadUrlRequest extends request_1.AbstractRequest { parse(response) { return __awaiter(this, void 0, void 0, function* () { const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); return { id: serviceResponse.data.id, name: serviceResponse.data.name, diff --git a/lib/core/endpoints/file_upload/list_files.js b/lib/core/endpoints/file_upload/list_files.js index 614de6471..bccdbec40 100644 --- a/lib/core/endpoints/file_upload/list_files.js +++ b/lib/core/endpoints/file_upload/list_files.js @@ -4,22 +4,11 @@ * * @internal */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.FilesListRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); @@ -53,17 +42,6 @@ class FilesListRequest extends request_1.AbstractRequest { if (!this.parameters.channel) return "channel can't be empty"; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, channel, } = this.parameters; return `/v1/files/${subscribeKey}/channels/${(0, utils_1.encodeString)(channel)}/files`; diff --git a/lib/core/endpoints/file_upload/publish_file.js b/lib/core/endpoints/file_upload/publish_file.js index 82af6dc76..ea75057aa 100644 --- a/lib/core/endpoints/file_upload/publish_file.js +++ b/lib/core/endpoints/file_upload/publish_file.js @@ -18,7 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.PublishFileMessageRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const base64_codec_1 = require("../../components/base64_codec"); @@ -60,10 +59,7 @@ class PublishFileMessageRequest extends request_1.AbstractRequest { } parse(response) { return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - return { timetoken: serviceResponse[2] }; + return { timetoken: this.deserializeResponse(response)[2] }; }); } get path() { diff --git a/lib/core/endpoints/file_upload/send_file.js b/lib/core/endpoints/file_upload/send_file.js index 2f4512ea6..9d4ebeb1d 100644 --- a/lib/core/endpoints/file_upload/send_file.js +++ b/lib/core/endpoints/file_upload/send_file.js @@ -19,11 +19,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) { Object.defineProperty(exports, "__esModule", { value: true }); exports.SendFileRequest = void 0; const generate_upload_url_1 = require("./generate_upload_url"); +const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const pubnub_error_1 = require("../../../errors/pubnub-error"); const operations_1 = __importDefault(require("../../constants/operations")); -const upload_file_1 = require("./upload-file"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const categories_1 = __importDefault(require("../../constants/categories")); +const upload_file_1 = require("./upload-file"); // endregion /** * Send file composed request. diff --git a/lib/core/endpoints/history/delete_messages.js b/lib/core/endpoints/history/delete_messages.js index 2ded57b82..fb72cdd50 100644 --- a/lib/core/endpoints/history/delete_messages.js +++ b/lib/core/endpoints/history/delete_messages.js @@ -18,8 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.DeleteMessageRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const transport_request_1 = require("../../types/transport-request"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); @@ -45,14 +43,11 @@ class DeleteMessageRequest extends request_1.AbstractRequest { return 'Missing channel'; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return {}; + return _super.parse.call(this, response).then((_) => ({})); }); } get path() { diff --git a/lib/core/endpoints/history/get_history.js b/lib/core/endpoints/history/get_history.js index 7a8ac874e..388598710 100644 --- a/lib/core/endpoints/history/get_history.js +++ b/lib/core/endpoints/history/get_history.js @@ -18,7 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.GetHistoryRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); @@ -74,8 +73,6 @@ class GetHistoryRequest extends request_1.AbstractRequest { parse(response) { return __awaiter(this, void 0, void 0, function* () { const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); const messages = serviceResponse[0]; const startTimeToken = serviceResponse[1]; const endTimeToken = serviceResponse[2]; diff --git a/lib/core/endpoints/history/message_counts.js b/lib/core/endpoints/history/message_counts.js index 07f236743..04c485958 100644 --- a/lib/core/endpoints/history/message_counts.js +++ b/lib/core/endpoints/history/message_counts.js @@ -18,8 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.MessageCountRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); @@ -52,13 +50,7 @@ class MessageCountRequest extends request_1.AbstractRequest { } parse(response) { return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return { channels: serviceResponse.channels }; + return { channels: this.deserializeResponse(response).channels }; }); } get path() { diff --git a/lib/core/endpoints/objects/channel/get.js b/lib/core/endpoints/objects/channel/get.js index 56caa61d1..c2fe425a7 100644 --- a/lib/core/endpoints/objects/channel/get.js +++ b/lib/core/endpoints/objects/channel/get.js @@ -4,22 +4,11 @@ * * @internal */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.GetChannelMetadataRequest = void 0; -const pubnub_error_1 = require("../../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../../errors/pubnub-api-error"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); const utils_1 = require("../../../utils"); @@ -54,17 +43,6 @@ class GetChannelMetadataRequest extends request_1.AbstractRequest { if (!this.parameters.channel) return 'Channel cannot be empty'; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, channel, } = this.parameters; return `/v2/objects/${subscribeKey}/channels/${(0, utils_1.encodeString)(channel)}`; diff --git a/lib/core/endpoints/objects/channel/get_all.js b/lib/core/endpoints/objects/channel/get_all.js index d5decf2d9..cf6003fb7 100644 --- a/lib/core/endpoints/objects/channel/get_all.js +++ b/lib/core/endpoints/objects/channel/get_all.js @@ -4,22 +4,11 @@ * * @internal */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.GetAllChannelsMetadataRequest = void 0; -const pubnub_error_1 = require("../../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../../errors/pubnub-api-error"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); // -------------------------------------------------------- @@ -59,17 +48,6 @@ class GetAllChannelsMetadataRequest extends request_1.AbstractRequest { operation() { return operations_1.default.PNGetAllChannelMetadataOperation; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { return `/v2/objects/${this.parameters.keySet.subscribeKey}/channels`; } diff --git a/lib/core/endpoints/objects/channel/remove.js b/lib/core/endpoints/objects/channel/remove.js index 3b5a3cdb3..b54d2a7aa 100644 --- a/lib/core/endpoints/objects/channel/remove.js +++ b/lib/core/endpoints/objects/channel/remove.js @@ -4,22 +4,11 @@ * * @internal */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.RemoveChannelMetadataRequest = void 0; -const pubnub_error_1 = require("../../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../../errors/pubnub-api-error"); const transport_request_1 = require("../../../types/transport-request"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); @@ -42,17 +31,6 @@ class RemoveChannelMetadataRequest extends request_1.AbstractRequest { if (!this.parameters.channel) return 'Channel cannot be empty'; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, channel, } = this.parameters; return `/v2/objects/${subscribeKey}/channels/${(0, utils_1.encodeString)(channel)}`; diff --git a/lib/core/endpoints/objects/channel/set.js b/lib/core/endpoints/objects/channel/set.js index 9868323f0..74a89c36e 100644 --- a/lib/core/endpoints/objects/channel/set.js +++ b/lib/core/endpoints/objects/channel/set.js @@ -4,22 +4,11 @@ * * @internal */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SetChannelMetadataRequest = void 0; -const pubnub_error_1 = require("../../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../../errors/pubnub-api-error"); const transport_request_1 = require("../../../types/transport-request"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); @@ -65,17 +54,6 @@ class SetChannelMetadataRequest extends request_1.AbstractRequest { return undefined; } } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, channel, } = this.parameters; return `/v2/objects/${subscribeKey}/channels/${(0, utils_1.encodeString)(channel)}`; diff --git a/lib/core/endpoints/objects/member/get.js b/lib/core/endpoints/objects/member/get.js index 170817a08..95fa842be 100644 --- a/lib/core/endpoints/objects/member/get.js +++ b/lib/core/endpoints/objects/member/get.js @@ -4,22 +4,11 @@ * * @internal */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.GetChannelMembersRequest = void 0; -const pubnub_error_1 = require("../../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../../errors/pubnub-api-error"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); const utils_1 = require("../../../utils"); @@ -94,17 +83,6 @@ class GetChannelMembersRequest extends request_1.AbstractRequest { if (!this.parameters.channel) return 'Channel cannot be empty'; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, channel, } = this.parameters; return `/v2/objects/${subscribeKey}/channels/${(0, utils_1.encodeString)(channel)}/uuids`; diff --git a/lib/core/endpoints/objects/member/set.js b/lib/core/endpoints/objects/member/set.js index 45682cb0c..705b8f188 100644 --- a/lib/core/endpoints/objects/member/set.js +++ b/lib/core/endpoints/objects/member/set.js @@ -4,22 +4,11 @@ * * @internal */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SetChannelMembersRequest = void 0; -const pubnub_error_1 = require("../../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../../errors/pubnub-api-error"); const transport_request_1 = require("../../../types/transport-request"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); @@ -98,17 +87,6 @@ class SetChannelMembersRequest extends request_1.AbstractRequest { if (!uuids || uuids.length === 0) return 'UUIDs cannot be empty'; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, channel, } = this.parameters; return `/v2/objects/${subscribeKey}/channels/${(0, utils_1.encodeString)(channel)}/uuids`; diff --git a/lib/core/endpoints/objects/membership/get.js b/lib/core/endpoints/objects/membership/get.js index 5b333955b..519c343db 100644 --- a/lib/core/endpoints/objects/membership/get.js +++ b/lib/core/endpoints/objects/membership/get.js @@ -4,22 +4,11 @@ * * @internal */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.GetUUIDMembershipsRequest = void 0; -const pubnub_error_1 = require("../../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../../errors/pubnub-api-error"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); const utils_1 = require("../../../utils"); @@ -97,17 +86,6 @@ class GetUUIDMembershipsRequest extends request_1.AbstractRequest { if (!this.parameters.uuid) return "'uuid' cannot be empty"; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, uuid, } = this.parameters; return `/v2/objects/${subscribeKey}/uuids/${(0, utils_1.encodeString)(uuid)}/channels`; diff --git a/lib/core/endpoints/objects/membership/set.js b/lib/core/endpoints/objects/membership/set.js index f4e6f8039..1cb8ea4d8 100644 --- a/lib/core/endpoints/objects/membership/set.js +++ b/lib/core/endpoints/objects/membership/set.js @@ -4,22 +4,11 @@ * * @internal */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SetUUIDMembershipsRequest = void 0; -const pubnub_error_1 = require("../../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../../errors/pubnub-api-error"); const transport_request_1 = require("../../../types/transport-request"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); @@ -101,17 +90,6 @@ class SetUUIDMembershipsRequest extends request_1.AbstractRequest { if (!channels || channels.length === 0) return 'Channels cannot be empty'; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, uuid, } = this.parameters; return `/v2/objects/${subscribeKey}/uuids/${(0, utils_1.encodeString)(uuid)}/channels`; diff --git a/lib/core/endpoints/objects/uuid/get.js b/lib/core/endpoints/objects/uuid/get.js index 2f9705040..db83b7e6a 100644 --- a/lib/core/endpoints/objects/uuid/get.js +++ b/lib/core/endpoints/objects/uuid/get.js @@ -4,22 +4,11 @@ * * @internal */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.GetUUIDMetadataRequest = void 0; -const pubnub_error_1 = require("../../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../../errors/pubnub-api-error"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); const utils_1 = require("../../../utils"); @@ -57,17 +46,6 @@ class GetUUIDMetadataRequest extends request_1.AbstractRequest { if (!this.parameters.uuid) return "'uuid' cannot be empty"; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, uuid, } = this.parameters; return `/v2/objects/${subscribeKey}/uuids/${(0, utils_1.encodeString)(uuid)}`; diff --git a/lib/core/endpoints/objects/uuid/get_all.js b/lib/core/endpoints/objects/uuid/get_all.js index e95a18b9a..7fe3baf2e 100644 --- a/lib/core/endpoints/objects/uuid/get_all.js +++ b/lib/core/endpoints/objects/uuid/get_all.js @@ -4,22 +4,11 @@ * * @internal */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.GetAllUUIDMetadataRequest = void 0; -const pubnub_error_1 = require("../../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../../errors/pubnub-api-error"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); // -------------------------------------------------------- @@ -54,17 +43,6 @@ class GetAllUUIDMetadataRequest extends request_1.AbstractRequest { operation() { return operations_1.default.PNGetAllUUIDMetadataOperation; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { return `/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`; } diff --git a/lib/core/endpoints/objects/uuid/remove.js b/lib/core/endpoints/objects/uuid/remove.js index c97245691..b42fd4f48 100644 --- a/lib/core/endpoints/objects/uuid/remove.js +++ b/lib/core/endpoints/objects/uuid/remove.js @@ -4,22 +4,11 @@ * * @internal */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.RemoveUUIDMetadataRequest = void 0; -const pubnub_error_1 = require("../../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../../errors/pubnub-api-error"); const transport_request_1 = require("../../../types/transport-request"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); @@ -45,17 +34,6 @@ class RemoveUUIDMetadataRequest extends request_1.AbstractRequest { if (!this.parameters.uuid) return "'uuid' cannot be empty"; } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, uuid, } = this.parameters; return `/v2/objects/${subscribeKey}/uuids/${(0, utils_1.encodeString)(uuid)}`; diff --git a/lib/core/endpoints/objects/uuid/set.js b/lib/core/endpoints/objects/uuid/set.js index 48680a812..17669ca9b 100644 --- a/lib/core/endpoints/objects/uuid/set.js +++ b/lib/core/endpoints/objects/uuid/set.js @@ -4,22 +4,11 @@ * * @internal */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SetUUIDMetadataRequest = void 0; -const pubnub_error_1 = require("../../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../../errors/pubnub-api-error"); const transport_request_1 = require("../../../types/transport-request"); const request_1 = require("../../../components/request"); const operations_1 = __importDefault(require("../../../constants/operations")); @@ -68,17 +57,6 @@ class SetUUIDMetadataRequest extends request_1.AbstractRequest { return undefined; } } - parse(response) { - return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return serviceResponse; - }); - } get path() { const { keySet: { subscribeKey }, uuid, } = this.parameters; return `/v2/objects/${subscribeKey}/uuids/${(0, utils_1.encodeString)(uuid)}`; diff --git a/lib/core/endpoints/presence/get_state.js b/lib/core/endpoints/presence/get_state.js index ee37ee086..a38d4a65a 100644 --- a/lib/core/endpoints/presence/get_state.js +++ b/lib/core/endpoints/presence/get_state.js @@ -18,8 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.GetPresenceStateRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); @@ -50,11 +48,6 @@ class GetPresenceStateRequest extends request_1.AbstractRequest { parse(response) { return __awaiter(this, void 0, void 0, function* () { const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); const { channels = [], channelGroups = [] } = this.parameters; const state = { channels: {} }; if (channels.length === 1 && channelGroups.length === 0) diff --git a/lib/core/endpoints/presence/heartbeat.js b/lib/core/endpoints/presence/heartbeat.js index 51bd2497c..8c34211bc 100644 --- a/lib/core/endpoints/presence/heartbeat.js +++ b/lib/core/endpoints/presence/heartbeat.js @@ -18,8 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.HeartbeatRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); @@ -45,14 +43,11 @@ class HeartbeatRequest extends request_1.AbstractRequest { return 'Please provide a list of channels and/or channel-groups'; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return {}; + return _super.parse.call(this, response).then((_) => ({})); }); } get path() { diff --git a/lib/core/endpoints/presence/here_now.js b/lib/core/endpoints/presence/here_now.js index 7a2a464c4..2beb6656d 100644 --- a/lib/core/endpoints/presence/here_now.js +++ b/lib/core/endpoints/presence/here_now.js @@ -18,8 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.HereNowRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); @@ -66,11 +64,6 @@ class HereNowRequest extends request_1.AbstractRequest { return __awaiter(this, void 0, void 0, function* () { var _a, _b; const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); // Extract general presence information. const totalChannels = 'occupancy' in serviceResponse ? 1 : serviceResponse.payload.total_channels; const totalOccupancy = 'occupancy' in serviceResponse ? serviceResponse.occupancy : serviceResponse.payload.total_occupancy; diff --git a/lib/core/endpoints/presence/leave.js b/lib/core/endpoints/presence/leave.js index 7ed6e2f62..5a2bd09d2 100644 --- a/lib/core/endpoints/presence/leave.js +++ b/lib/core/endpoints/presence/leave.js @@ -18,8 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.PresenceLeaveRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); @@ -49,14 +47,11 @@ class PresenceLeaveRequest extends request_1.AbstractRequest { return 'At least one `channel` or `channel group` should be provided.'; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return {}; + return _super.parse.call(this, response).then((_) => ({})); }); } get path() { diff --git a/lib/core/endpoints/presence/set_state.js b/lib/core/endpoints/presence/set_state.js index eb7648474..ade901f85 100644 --- a/lib/core/endpoints/presence/set_state.js +++ b/lib/core/endpoints/presence/set_state.js @@ -18,8 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SetPresenceStateRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); @@ -48,13 +46,7 @@ class SetPresenceStateRequest extends request_1.AbstractRequest { } parse(response) { return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); - return { state: serviceResponse.payload }; + return { state: this.deserializeResponse(response).payload }; }); } get path() { diff --git a/lib/core/endpoints/presence/where_now.js b/lib/core/endpoints/presence/where_now.js index f2f5a7724..0c8ce6c30 100644 --- a/lib/core/endpoints/presence/where_now.js +++ b/lib/core/endpoints/presence/where_now.js @@ -18,8 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.WhereNowRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); -const pubnub_api_error_1 = require("../../../errors/pubnub-api-error"); const request_1 = require("../../components/request"); const operations_1 = __importDefault(require("../../constants/operations")); const utils_1 = require("../../utils"); @@ -44,11 +42,6 @@ class WhereNowRequest extends request_1.AbstractRequest { parse(response) { return __awaiter(this, void 0, void 0, function* () { const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - } - else if (serviceResponse.status >= 400) - throw pubnub_api_error_1.PubNubAPIError.create(response); if (!serviceResponse.payload) return { channels: [] }; return { channels: serviceResponse.payload.channels }; diff --git a/lib/core/endpoints/publish.js b/lib/core/endpoints/publish.js index 3cdedc0a8..1bffd8ed6 100644 --- a/lib/core/endpoints/publish.js +++ b/lib/core/endpoints/publish.js @@ -16,7 +16,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.PublishRequest = void 0; -const pubnub_error_1 = require("../../errors/pubnub-error"); const transport_request_1 = require("../types/transport-request"); const request_1 = require("../components/request"); const operations_1 = __importDefault(require("../constants/operations")); @@ -67,10 +66,7 @@ class PublishRequest extends request_1.AbstractRequest { } parse(response) { return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - return { timetoken: serviceResponse[2] }; + return { timetoken: this.deserializeResponse(response)[2] }; }); } get path() { @@ -94,6 +90,8 @@ class PublishRequest extends request_1.AbstractRequest { return query; } get headers() { + if (!this.parameters.sendByPost) + return undefined; return { 'Content-Type': 'application/json' }; } get body() { diff --git a/lib/core/endpoints/push/add_push_channels.js b/lib/core/endpoints/push/add_push_channels.js index 8396d1d91..eee7e2bbb 100644 --- a/lib/core/endpoints/push/add_push_channels.js +++ b/lib/core/endpoints/push/add_push_channels.js @@ -18,7 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.AddDevicePushNotificationChannelsRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); const push_1 = require("./push"); const operations_1 = __importDefault(require("../../constants/operations")); // endregion @@ -36,11 +35,11 @@ class AddDevicePushNotificationChannelsRequest extends push_1.BasePushNotificati return operations_1.default.PNAddPushNotificationEnabledChannelsOperation; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - return {}; + return _super.parse.call(this, response).then((_) => ({})); }); } } diff --git a/lib/core/endpoints/push/list_push_channels.js b/lib/core/endpoints/push/list_push_channels.js index 1f62c8ff4..c1f1ba679 100644 --- a/lib/core/endpoints/push/list_push_channels.js +++ b/lib/core/endpoints/push/list_push_channels.js @@ -18,7 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ListDevicePushNotificationChannelsRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); const push_1 = require("./push"); const operations_1 = __importDefault(require("../../constants/operations")); // endregion @@ -37,10 +36,7 @@ class ListDevicePushNotificationChannelsRequest extends push_1.BasePushNotificat } parse(response) { return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - return { channels: serviceResponse }; + return { channels: this.deserializeResponse(response) }; }); } } diff --git a/lib/core/endpoints/push/push.js b/lib/core/endpoints/push/push.js index 5d12c31c5..93867ffd5 100644 --- a/lib/core/endpoints/push/push.js +++ b/lib/core/endpoints/push/push.js @@ -4,15 +4,6 @@ * * @internal */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; Object.defineProperty(exports, "__esModule", { value: true }); exports.BasePushNotificationChannelsRequest = void 0; const request_1 = require("../../components/request"); @@ -63,11 +54,6 @@ class BasePushNotificationChannelsRequest extends request_1.AbstractRequest { if (this.parameters.pushGateway === 'apns2' && !this.parameters.topic) return 'Missing APNS2 topic'; } - parse(_response) { - return __awaiter(this, void 0, void 0, function* () { - throw Error('Should be implemented in subclass.'); - }); - } get path() { const { keySet: { subscribeKey }, action, device, pushGateway, } = this.parameters; let path = pushGateway === 'apns2' diff --git a/lib/core/endpoints/push/remove_device.js b/lib/core/endpoints/push/remove_device.js index 563e091d6..6a870e110 100644 --- a/lib/core/endpoints/push/remove_device.js +++ b/lib/core/endpoints/push/remove_device.js @@ -18,7 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.RemoveDevicePushNotificationRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); const push_1 = require("./push"); const operations_1 = __importDefault(require("../../constants/operations")); // endregion @@ -36,11 +35,11 @@ class RemoveDevicePushNotificationRequest extends push_1.BasePushNotificationCha return operations_1.default.PNRemoveAllPushNotificationsOperation; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - return {}; + return _super.parse.call(this, response).then((_) => ({})); }); } } diff --git a/lib/core/endpoints/push/remove_push_channels.js b/lib/core/endpoints/push/remove_push_channels.js index 8d7455b4a..d60200e1b 100644 --- a/lib/core/endpoints/push/remove_push_channels.js +++ b/lib/core/endpoints/push/remove_push_channels.js @@ -18,7 +18,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.RemoveDevicePushNotificationChannelsRequest = void 0; -const pubnub_error_1 = require("../../../errors/pubnub-error"); const push_1 = require("./push"); const operations_1 = __importDefault(require("../../constants/operations")); // endregion @@ -36,11 +35,11 @@ class RemoveDevicePushNotificationChannelsRequest extends push_1.BasePushNotific return operations_1.default.PNRemovePushNotificationEnabledChannelsOperation; } parse(response) { + const _super = Object.create(null, { + parse: { get: () => super.parse } + }); return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - return {}; + return _super.parse.call(this, response).then((_) => ({})); }); } } diff --git a/lib/core/endpoints/signal.js b/lib/core/endpoints/signal.js index a6f34181e..8bdad1b80 100644 --- a/lib/core/endpoints/signal.js +++ b/lib/core/endpoints/signal.js @@ -16,7 +16,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SignalRequest = void 0; -const pubnub_error_1 = require("../../errors/pubnub-error"); const request_1 = require("../components/request"); const operations_1 = __importDefault(require("../constants/operations")); const utils_1 = require("../utils"); @@ -45,10 +44,7 @@ class SignalRequest extends request_1.AbstractRequest { } parse(response) { return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - return { timetoken: serviceResponse[2] }; + return { timetoken: this.deserializeResponse(response)[2] }; }); } get path() { diff --git a/lib/core/endpoints/subscribe.js b/lib/core/endpoints/subscribe.js index 401ebbda5..03b9c1533 100644 --- a/lib/core/endpoints/subscribe.js +++ b/lib/core/endpoints/subscribe.js @@ -99,16 +99,17 @@ class BaseSubscribeRequest extends request_1.AbstractRequest { parse(response) { return __awaiter(this, void 0, void 0, function* () { let serviceResponse; + let responseText; try { - const json = request_1.AbstractRequest.decoder.decode(response.body); - const parsedJson = JSON.parse(json); + responseText = request_1.AbstractRequest.decoder.decode(response.body); + const parsedJson = JSON.parse(responseText); serviceResponse = parsedJson; } catch (error) { console.error('Error parsing JSON response:', error); } if (!serviceResponse) { - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); + throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createMalformedResponseError)(responseText, response.status)); } const events = serviceResponse.m .filter((envelope) => { diff --git a/lib/core/endpoints/time.js b/lib/core/endpoints/time.js index ce2e5a3a6..4b0ad61f4 100644 --- a/lib/core/endpoints/time.js +++ b/lib/core/endpoints/time.js @@ -16,7 +16,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.TimeRequest = void 0; -const pubnub_error_1 = require("../../errors/pubnub-error"); const request_1 = require("../components/request"); const operations_1 = __importDefault(require("../constants/operations")); // endregion @@ -34,10 +33,7 @@ class TimeRequest extends request_1.AbstractRequest { } parse(response) { return __awaiter(this, void 0, void 0, function* () { - const serviceResponse = this.deserializeResponse(response); - if (!serviceResponse) - throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createValidationError)('Unable to deserialize service response')); - return { timetoken: serviceResponse[0] }; + return { timetoken: this.deserializeResponse(response)[0] }; }); } get path() { diff --git a/lib/core/pubnub-common.js b/lib/core/pubnub-common.js index 6059ec9fc..c90337f70 100644 --- a/lib/core/pubnub-common.js +++ b/lib/core/pubnub-common.js @@ -583,12 +583,15 @@ class PubNubCore { status.statusCode = response.status; // Handle special case when request completed but not fully processed by PubNub service. if (response.status !== 200 && response.status !== 204) { + const responseText = PubNubCore.decoder.decode(response.body); const contentType = response.headers['content-type']; if (contentType || contentType.indexOf('javascript') !== -1 || contentType.indexOf('json') !== -1) { - const json = JSON.parse(PubNubCore.decoder.decode(response.body)); + const json = JSON.parse(responseText); if (typeof json === 'object' && 'error' in json && json.error && typeof json.error === 'object') status.errorData = json.error; } + else + status.responseText = responseText; } return request.parse(response); }) @@ -857,7 +860,7 @@ class PubNubCore { */ if (this.subscriptionManager) { // Creating identifiable abort caller. - const callableAbort = () => request.abort(); + const callableAbort = () => request.abort('Cancel long-poll subscribe request'); callableAbort.identifier = request.requestIdentifier; this.subscriptionManager.abort = callableAbort; } @@ -954,7 +957,7 @@ class PubNubCore { if (process.env.SUBSCRIBE_EVENT_ENGINE_MODULE !== 'disabled') { const request = new handshake_1.HandshakeSubscribeRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet, crypto: this._configuration.getCryptoModule(), getFileUrl: this.getFileUrl.bind(this) })); const abortUnsubscribe = parameters.abortSignal.subscribe((err) => { - request.abort(); + request.abort('Cancel subscribe handshake request'); }); /** * Allow subscription cancellation. @@ -984,7 +987,7 @@ class PubNubCore { if (process.env.SUBSCRIBE_EVENT_ENGINE_MODULE !== 'disabled') { const request = new receiveMessages_1.ReceiveMessagesSubscribeRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet, crypto: this._configuration.getCryptoModule(), getFileUrl: this.getFileUrl.bind(this) })); const abortUnsubscribe = parameters.abortSignal.subscribe((err) => { - request.abort(); + request.abort('Cancel long-poll subscribe request'); }); /** * Allow subscription cancellation. @@ -992,8 +995,8 @@ class PubNubCore { * **Note:** Had to be done after scheduling because transport provider return cancellation * controller only when schedule new request. */ - const handshakeResponse = this.sendRequest(request); - return handshakeResponse.then((response) => { + const receiveResponse = this.sendRequest(request); + return receiveResponse.then((response) => { abortUnsubscribe(); return response; }); diff --git a/lib/errors/pubnub-api-error.js b/lib/errors/pubnub-api-error.js index 1a9b41e2e..c9ad14517 100644 --- a/lib/errors/pubnub-api-error.js +++ b/lib/errors/pubnub-api-error.js @@ -129,20 +129,29 @@ class PubNubAPIError extends Error { response.headers['content-type'].indexOf('application/json') !== -1) { try { const errorResponse = JSON.parse(decoded); - if (typeof errorResponse === 'object' && !Array.isArray(errorResponse)) { - if ('error' in errorResponse && - (errorResponse.error === 1 || errorResponse.error === true) && - 'status' in errorResponse && - typeof errorResponse.status === 'number' && - 'message' in errorResponse && - 'service' in errorResponse) { - errorData = errorResponse; - status = errorResponse.status; + if (typeof errorResponse === 'object') { + if (!Array.isArray(errorResponse)) { + if ('error' in errorResponse && + (errorResponse.error === 1 || errorResponse.error === true) && + 'status' in errorResponse && + typeof errorResponse.status === 'number' && + 'message' in errorResponse && + 'service' in errorResponse) { + errorData = errorResponse; + status = errorResponse.status; + } + else + errorData = errorResponse; + if ('error' in errorResponse && errorResponse.error instanceof Error) + errorData = errorResponse.error; + } + else { + // Handling Publish API payload error. + if (typeof errorResponse[0] === 'number' && errorResponse[0] === 0) { + if (errorResponse.length > 1 && typeof errorResponse[1] === 'string') + errorData = errorResponse[1]; + } } - else - errorData = errorResponse; - if ('error' in errorResponse && errorResponse.error instanceof Error) - errorData = errorResponse.error; } } catch (_) { diff --git a/lib/errors/pubnub-error.js b/lib/errors/pubnub-error.js index 97c5938c4..e4c30fd64 100644 --- a/lib/errors/pubnub-error.js +++ b/lib/errors/pubnub-error.js @@ -8,6 +8,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { Object.defineProperty(exports, "__esModule", { value: true }); exports.PubNubError = void 0; exports.createValidationError = createValidationError; +exports.createMalformedResponseError = createMalformedResponseError; const categories_1 = __importDefault(require("../core/constants/categories")); /** * PubNub operation error. @@ -38,15 +39,16 @@ exports.PubNubError = PubNubError; * Create error status object. * * @param errorPayload - Additional information which should be attached to the error status object. + * @param category - Occurred error category. * * @returns Error status object. * * @internal */ -function createError(errorPayload) { +function createError(errorPayload, category) { var _a; (_a = errorPayload.statusCode) !== null && _a !== void 0 ? _a : (errorPayload.statusCode = 0); - return Object.assign(Object.assign({}, errorPayload), { statusCode: errorPayload.statusCode, category: categories_1.default.PNValidationErrorCategory, error: true }); + return Object.assign(Object.assign({}, errorPayload), { statusCode: errorPayload.statusCode, category, error: true }); } /** * Create operation arguments validation error status object. @@ -59,5 +61,14 @@ function createError(errorPayload) { * @internal */ function createValidationError(message, statusCode) { - return createError(Object.assign({ message }, (statusCode !== undefined ? { statusCode } : {}))); + return createError(Object.assign({ message }, (statusCode !== undefined ? { statusCode } : {})), categories_1.default.PNValidationErrorCategory); +} +/** + * Create malformed service response error status object. + * + * @param [responseText] - Stringified original service response. + * @param [statusCode] - Operation HTTP status code. + */ +function createMalformedResponseError(responseText, statusCode) { + return createError(Object.assign(Object.assign({ message: 'Unable to deserialize service response' }, (responseText !== undefined ? { responseText } : {})), (statusCode !== undefined ? { statusCode } : {})), categories_1.default.PNMalformedResponseCategory); } diff --git a/lib/transport/node-transport.js b/lib/transport/node-transport.js index ea2aae6b0..3a62bfb38 100644 --- a/lib/transport/node-transport.js +++ b/lib/transport/node-transport.js @@ -89,7 +89,11 @@ class NodeTransport { controller = { // Storing controller inside to prolong object lifetime. abortController, - abort: () => abortController === null || abortController === void 0 ? void 0 : abortController.abort(), + abort: (reason) => { + if (!abortController || abortController.signal.aborted) + return; + abortController === null || abortController === void 0 ? void 0 : abortController.abort(reason); + }, }; } return [ @@ -119,7 +123,15 @@ class NodeTransport { return transportResponse; }) .catch((error) => { - throw pubnub_api_error_1.PubNubAPIError.create(error); + let fetchError = error; + if (typeof error === 'string') { + const errorMessage = error.toLowerCase(); + if (errorMessage.includes('timeout') || !errorMessage.includes('cancel')) + fetchError = new Error(error); + else if (errorMessage.includes('cancel')) + fetchError = new DOMException('Aborted', 'AbortError'); + } + throw pubnub_api_error_1.PubNubAPIError.create(fetchError); }); }), controller, diff --git a/lib/transport/react-native-transport.js b/lib/transport/react-native-transport.js index d738dbde8..dfb5ddcb1 100644 --- a/lib/transport/react-native-transport.js +++ b/lib/transport/react-native-transport.js @@ -40,7 +40,7 @@ class ReactNativeTransport { const controller = { // Storing controller inside to prolong object lifetime. abortController, - abort: () => !abortController.signal.aborted && abortController.abort(), + abort: (reason) => !abortController.signal.aborted && abortController.abort(reason), }; return [ this.requestFromTransportRequest(req).then((request) => { @@ -56,7 +56,7 @@ class ReactNativeTransport { timeoutId = setTimeout(() => { clearTimeout(timeoutId); reject(new Error('Request timeout')); - controller.abort(); + controller.abort('Cancel because of timeout'); }, req.timeout * 1000); }); return Promise.race([ @@ -91,7 +91,15 @@ class ReactNativeTransport { return transportResponse; }) .catch((error) => { - throw pubnub_api_error_1.PubNubAPIError.create(error); + let fetchError = error; + if (typeof error === 'string') { + const errorMessage = error.toLowerCase(); + if (errorMessage.includes('timeout') || !errorMessage.includes('cancel')) + fetchError = new Error(error); + else if (errorMessage.includes('cancel')) + fetchError = new DOMException('Aborted', 'AbortError'); + } + throw pubnub_api_error_1.PubNubAPIError.create(fetchError); }); }), controller, diff --git a/lib/types/index.d.ts b/lib/types/index.d.ts index 7730d19b3..cbfb2fb6d 100644 --- a/lib/types/index.d.ts +++ b/lib/types/index.d.ts @@ -2043,6 +2043,14 @@ declare namespace PubNub { * Some API endpoints respond with request processing status w/o useful data. */ PNAcknowledgmentCategory = 'PNAcknowledgmentCategory', + /** + * PubNub service or intermediate "actor" returned unexpected response. + * + * There can be few sources of unexpected return with success code: + * - proxy server / VPN; + * - Wi-Fi hotspot authorization page. + */ + PNMalformedResponseCategory = 'PNMalformedResponseCategory', /** * Something strange happened; please check the logs. */ @@ -2892,7 +2900,7 @@ declare namespace PubNub { /** * Request cancellation / abort function. */ - abort: () => void; + abort: (reason?: string) => void; }; /** diff --git a/package-lock.json b/package-lock.json index 4b12108a1..187770ec6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "pubnub", - "version": "8.3.2", + "version": "8.8.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "pubnub", - "version": "8.3.2", + "version": "8.8.1", "license": "SEE LICENSE IN LICENSE", "dependencies": { "agentkeepalive": "^3.5.2", diff --git a/src/core/components/request.ts b/src/core/components/request.ts index 50b028140..8863e5a07 100644 --- a/src/core/components/request.ts +++ b/src/core/components/request.ts @@ -5,7 +5,9 @@ */ import { CancellationController, TransportMethod, TransportRequest } from '../types/transport-request'; +import { createMalformedResponseError, PubNubError } from '../../errors/pubnub-error'; import { TransportResponse } from '../types/transport-response'; +import { PubNubAPIError } from '../../errors/pubnub-api-error'; import RequestOperation from '../constants/operations'; import { PubNubFileInterface } from '../types/file'; import { Request } from '../interfaces/request'; @@ -17,7 +19,7 @@ import uuidGenerator from './uuid'; * * @internal */ -export abstract class AbstractRequest implements Request { +export abstract class AbstractRequest implements Request { /** * Service `ArrayBuffer` response decoder. */ @@ -66,9 +68,11 @@ export abstract class AbstractRequest implements Request implements Request { - throw Error('Should be implemented by subclass.'); + async parse(response: TransportResponse): Promise { + return this.deserializeResponse(response) as unknown as ResponseType; } /** @@ -170,21 +174,37 @@ export abstract class AbstractRequest implements Request(response: TransportResponse): ServiceResponse | undefined { + protected deserializeResponse(response: TransportResponse): ServiceResponse { + const responseText = AbstractRequest.decoder.decode(response.body); const contentType = response.headers['content-type']; - if (!contentType || (contentType.indexOf('javascript') === -1 && contentType.indexOf('json') === -1)) - return undefined; + let parsedJson: ServiceResponse; - const json = AbstractRequest.decoder.decode(response.body); + if (!contentType || (contentType.indexOf('javascript') === -1 && contentType.indexOf('json') === -1)) + throw new PubNubError( + 'Service response error, check status for details', + createMalformedResponseError(responseText, response.status), + ); try { - const parsedJson = JSON.parse(json); - return parsedJson as ServiceResponse; + parsedJson = JSON.parse(responseText); } catch (error) { console.error('Error parsing JSON response:', error); - return undefined; + + throw new PubNubError( + 'Service response error, check status for details', + createMalformedResponseError(responseText, response.status), + ); } + + // Throw and exception in case of client / server error. + if ('status' in parsedJson && typeof parsedJson.status === 'number' && parsedJson.status >= 400) + throw PubNubAPIError.create(response); + + return parsedJson; } } diff --git a/src/core/components/subscription-manager.ts b/src/core/components/subscription-manager.ts index df0db8bc4..3dcca2727 100644 --- a/src/core/components/subscription-manager.ts +++ b/src/core/components/subscription-manager.ts @@ -13,7 +13,6 @@ import * as Subscription from '../types/api/subscription'; import { ListenerManager } from './listener_manager'; import StatusCategory from '../constants/categories'; import { DedupingManager } from './deduping_manager'; -import Categories from '../constants/categories'; import * as Presence from '../types/api/presence'; import { PubNubCore } from '../pubnub-common'; import EventEmitter from './eventEmitter'; @@ -382,9 +381,9 @@ export class SubscriptionManager { ) return; - if (status.category === Categories.PNTimeoutCategory) { + if (status.category === StatusCategory.PNTimeoutCategory) { this.startSubscribeLoop(); - } else if (status.category === Categories.PNNetworkIssuesCategory) { + } else if (status.category === StatusCategory.PNNetworkIssuesCategory) { this.disconnect(); if (status.error && this.configuration.autoNetworkDetection && this.isOnline) { @@ -402,7 +401,7 @@ export class SubscriptionManager { this.subscriptionStatusAnnounced = true; const reconnectedAnnounce = { - category: Categories.PNReconnectedCategory, + category: StatusCategory.PNReconnectedCategory, operation: status.operation, lastTimetoken: this.lastTimetoken, currentTimetoken: this.currentTimetoken, @@ -412,12 +411,16 @@ export class SubscriptionManager { this.reconnectionManager.startPolling(); this.listenerManager.announceStatus(status); - } else if (status.category === Categories.PNBadRequestCategory) { - this.stopHeartbeatTimer(); - this.listenerManager.announceStatus(status); - } else { - this.listenerManager.announceStatus(status); - } + } else if ( + status.category === StatusCategory.PNBadRequestCategory || + status.category == StatusCategory.PNMalformedResponseCategory + ) { + const category = this.isOnline ? StatusCategory.PNDisconnectedUnexpectedlyCategory : status.category; + this.isOnline = false; + this.disconnect(); + + this.listenerManager.announceStatus({ ...status, category }); + } else this.listenerManager.announceStatus(status); return; } diff --git a/src/core/constants/categories.ts b/src/core/constants/categories.ts index 6550b4538..54ead3e4e 100644 --- a/src/core/constants/categories.ts +++ b/src/core/constants/categories.ts @@ -39,6 +39,15 @@ enum StatusCategory { */ PNAcknowledgmentCategory = 'PNAcknowledgmentCategory', + /** + * PubNub service or intermediate "actor" returned unexpected response. + * + * There can be few sources of unexpected return with success code: + * - proxy server / VPN; + * - Wi-Fi hotspot authorization page. + */ + PNMalformedResponseCategory = 'PNMalformedResponseCategory', + /** * Something strange happened; please check the logs. */ diff --git a/src/core/endpoints/access_manager/audit.ts b/src/core/endpoints/access_manager/audit.ts index 30aef5bfc..ec30dc018 100644 --- a/src/core/endpoints/access_manager/audit.ts +++ b/src/core/endpoints/access_manager/audit.ts @@ -4,9 +4,7 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import { AbstractRequest } from '../../components/request'; import RequestOperation from '../../constants/operations'; import * as PAM from '../../types/api/access-manager'; @@ -69,7 +67,7 @@ type ServiceResponse = { * * @internal */ -export class AuditRequest extends AbstractRequest { +export class AuditRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); @@ -86,16 +84,7 @@ export class AuditRequest extends AbstractRequest { } async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return serviceResponse.payload; + return this.deserializeResponse(response).payload; } protected get path(): string { diff --git a/src/core/endpoints/access_manager/grant.ts b/src/core/endpoints/access_manager/grant.ts index a6eff8629..731c68091 100644 --- a/src/core/endpoints/access_manager/grant.ts +++ b/src/core/endpoints/access_manager/grant.ts @@ -4,9 +4,7 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import { AbstractRequest } from '../../components/request'; import RequestOperation from '../../constants/operations'; import * as PAM from '../../types/api/access-manager'; @@ -99,7 +97,7 @@ type ServiceResponse = { * * @internal */ -export class GrantRequest extends AbstractRequest { +export class GrantRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); @@ -140,16 +138,7 @@ export class GrantRequest extends AbstractRequest { } async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return serviceResponse.payload; + return this.deserializeResponse(response).payload; } protected get path(): string { diff --git a/src/core/endpoints/access_manager/grant_token.ts b/src/core/endpoints/access_manager/grant_token.ts index 0a6fd0df9..329faaca9 100644 --- a/src/core/endpoints/access_manager/grant_token.ts +++ b/src/core/endpoints/access_manager/grant_token.ts @@ -4,9 +4,7 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import { TransportMethod } from '../../types/transport-request'; import { AbstractRequest } from '../../components/request'; import RequestOperation from '../../constants/operations'; @@ -93,7 +91,7 @@ type ServiceResponse = { * * @internal */ -export class GrantTokenRequest extends AbstractRequest { +export class GrantTokenRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super({ method: TransportMethod.POST }); @@ -146,16 +144,7 @@ export class GrantTokenRequest extends AbstractRequest { } async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return serviceResponse.data.token; + return this.deserializeResponse(response).data.token; } protected get path(): string { diff --git a/src/core/endpoints/access_manager/revoke_token.ts b/src/core/endpoints/access_manager/revoke_token.ts index 600e350e8..cdce6ecae 100644 --- a/src/core/endpoints/access_manager/revoke_token.ts +++ b/src/core/endpoints/access_manager/revoke_token.ts @@ -4,9 +4,7 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import { TransportMethod } from '../../types/transport-request'; import { AbstractRequest } from '../../components/request'; import RequestOperation from '../../constants/operations'; @@ -62,7 +60,7 @@ type ServiceResponse = { * * @internal */ -export class RevokeTokenRequest extends AbstractRequest { +export class RevokeTokenRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super({ method: TransportMethod.DELETE }); } @@ -77,16 +75,7 @@ export class RevokeTokenRequest extends AbstractRequest } async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return {}; + return super.parse(response).then((_) => ({})); } protected get path(): string { diff --git a/src/core/endpoints/actions/add_message_action.ts b/src/core/endpoints/actions/add_message_action.ts index 75d3488e2..10f06e8f4 100644 --- a/src/core/endpoints/actions/add_message_action.ts +++ b/src/core/endpoints/actions/add_message_action.ts @@ -4,9 +4,7 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import { TransportMethod } from '../../types/transport-request'; import * as MessageAction from '../../types/api/message-action'; import { AbstractRequest } from '../../components/request'; @@ -50,7 +48,7 @@ type ServiceResponse = { * * @internal */ -export class AddMessageActionRequest extends AbstractRequest { +export class AddMessageActionRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super({ method: TransportMethod.POST }); } @@ -77,16 +75,7 @@ export class AddMessageActionRequest extends AbstractRequest { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return { data: serviceResponse.data }; + return super.parse(response).then(({ data }) => ({ data })); } protected get path(): string { diff --git a/src/core/endpoints/actions/get_message_actions.ts b/src/core/endpoints/actions/get_message_actions.ts index 5c72a63fc..66b12ac17 100644 --- a/src/core/endpoints/actions/get_message_actions.ts +++ b/src/core/endpoints/actions/get_message_actions.ts @@ -4,9 +4,7 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import * as MessageAction from '../../types/api/message-action'; import { AbstractRequest } from '../../components/request'; import RequestOperation from '../../constants/operations'; @@ -54,7 +52,10 @@ type ServiceResponse = { * * @internal */ -export class GetMessageActionsRequest extends AbstractRequest { +export class GetMessageActionsRequest extends AbstractRequest< + MessageAction.GetMessageActionsResponse, + ServiceResponse +> { constructor(private readonly parameters: RequestParameters) { super(); } @@ -69,15 +70,7 @@ export class GetMessageActionsRequest extends AbstractRequest { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - + const serviceResponse = this.deserializeResponse(response); let start: string | null = null; let end: string | null = null; diff --git a/src/core/endpoints/actions/remove_message_action.ts b/src/core/endpoints/actions/remove_message_action.ts index f6d6ee8ca..f17a7c916 100644 --- a/src/core/endpoints/actions/remove_message_action.ts +++ b/src/core/endpoints/actions/remove_message_action.ts @@ -4,9 +4,7 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import { TransportMethod } from '../../types/transport-request'; import * as MessageAction from '../../types/api/message-action'; import { AbstractRequest } from '../../components/request'; @@ -50,7 +48,7 @@ type ServiceResponse = { * * @internal */ -export class RemoveMessageAction extends AbstractRequest { +export class RemoveMessageAction extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super({ method: TransportMethod.DELETE }); } @@ -74,16 +72,7 @@ export class RemoveMessageAction extends AbstractRequest { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return { data: serviceResponse.data }; + return super.parse(response).then(({ data }) => ({ data })); } protected get path(): string { diff --git a/src/core/endpoints/channel_groups/add_channels.ts b/src/core/endpoints/channel_groups/add_channels.ts index 49be453f2..32b1cce76 100644 --- a/src/core/endpoints/channel_groups/add_channels.ts +++ b/src/core/endpoints/channel_groups/add_channels.ts @@ -4,9 +4,7 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import * as ChannelGroups from '../../types/api/channel-groups'; import { AbstractRequest } from '../../components/request'; import RequestOperation from '../../constants/operations'; @@ -59,7 +57,10 @@ type ServiceResponse = { * * @internal */ -export class AddChannelGroupChannelsRequest extends AbstractRequest { +export class AddChannelGroupChannelsRequest extends AbstractRequest< + ChannelGroups.ManageChannelGroupChannelsResponse, + ServiceResponse +> { constructor(private readonly parameters: RequestParameters) { super(); } @@ -81,16 +82,7 @@ export class AddChannelGroupChannelsRequest extends AbstractRequest { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return {}; + return super.parse(response).then((_) => ({})); } protected get path(): string { diff --git a/src/core/endpoints/channel_groups/delete_group.ts b/src/core/endpoints/channel_groups/delete_group.ts index 6426177c9..9d2259733 100644 --- a/src/core/endpoints/channel_groups/delete_group.ts +++ b/src/core/endpoints/channel_groups/delete_group.ts @@ -4,14 +4,12 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import * as ChannelGroups from '../../types/api/channel-groups'; import { AbstractRequest } from '../../components/request'; import RequestOperation from '../../constants/operations'; -import { KeySet } from '../../types/api'; import { encodeString } from '../../utils'; +import { KeySet } from '../../types/api'; // -------------------------------------------------------- // ------------------------ Types ------------------------- @@ -59,7 +57,10 @@ type ServiceResponse = { * * @internal */ -export class DeleteChannelGroupRequest extends AbstractRequest { +export class DeleteChannelGroupRequest extends AbstractRequest< + ChannelGroups.DeleteChannelGroupResponse, + ServiceResponse +> { constructor(private readonly parameters: RequestParameters) { super(); } @@ -74,16 +75,7 @@ export class DeleteChannelGroupRequest extends AbstractRequest { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return {}; + return super.parse(response).then((_) => ({})); } protected get path(): string { diff --git a/src/core/endpoints/channel_groups/list_channels.ts b/src/core/endpoints/channel_groups/list_channels.ts index 470594660..848c5b373 100644 --- a/src/core/endpoints/channel_groups/list_channels.ts +++ b/src/core/endpoints/channel_groups/list_channels.ts @@ -4,9 +4,7 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import * as ChannelGroups from '../../types/api/channel-groups'; import { AbstractRequest } from '../../components/request'; import RequestOperation from '../../constants/operations'; @@ -74,7 +72,10 @@ type ServiceResponse = { * * @internal */ -export class ListChannelGroupChannels extends AbstractRequest { +export class ListChannelGroupChannels extends AbstractRequest< + ChannelGroups.ListChannelGroupChannelsResponse, + ServiceResponse +> { constructor(private readonly parameters: RequestParameters) { super(); } @@ -89,16 +90,7 @@ export class ListChannelGroupChannels extends AbstractRequest { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return { channels: serviceResponse.payload.channels }; + return { channels: this.deserializeResponse(response).payload.channels }; } protected get path(): string { diff --git a/src/core/endpoints/channel_groups/list_groups.ts b/src/core/endpoints/channel_groups/list_groups.ts index 1b3659e23..598793b59 100644 --- a/src/core/endpoints/channel_groups/list_groups.ts +++ b/src/core/endpoints/channel_groups/list_groups.ts @@ -4,9 +4,7 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import * as ChannelGroups from '../../types/api/channel-groups'; import { AbstractRequest } from '../../components/request'; import RequestOperation from '../../constants/operations'; @@ -73,7 +71,10 @@ type ServiceResponse = { * * @internal */ -export class ListChannelGroupsRequest extends AbstractRequest { +export class ListChannelGroupsRequest extends AbstractRequest< + ChannelGroups.ListAllChannelGroupsResponse, + ServiceResponse +> { constructor(private readonly parameters: RequestParameters) { super(); } @@ -87,16 +88,7 @@ export class ListChannelGroupsRequest extends AbstractRequest { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return { groups: serviceResponse.payload.groups }; + return { groups: this.deserializeResponse(response).payload.groups }; } protected get path(): string { diff --git a/src/core/endpoints/channel_groups/remove_channels.ts b/src/core/endpoints/channel_groups/remove_channels.ts index d960f9275..ecbb76489 100644 --- a/src/core/endpoints/channel_groups/remove_channels.ts +++ b/src/core/endpoints/channel_groups/remove_channels.ts @@ -4,9 +4,7 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import * as ChannelGroups from '../../types/api/channel-groups'; import { AbstractRequest } from '../../components/request'; import RequestOperation from '../../constants/operations'; @@ -61,7 +59,8 @@ type ServiceResponse = { */ // prettier-ignore export class RemoveChannelGroupChannelsRequest extends AbstractRequest< - ChannelGroups.ManageChannelGroupChannelsResponse + ChannelGroups.ManageChannelGroupChannelsResponse, + ServiceResponse > { constructor(private readonly parameters: RequestParameters) { super(); @@ -84,16 +83,7 @@ export class RemoveChannelGroupChannelsRequest extends AbstractRequest< } async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return {}; + return super.parse(response).then((_) => ({})); } protected get path(): string { diff --git a/src/core/endpoints/fetch_messages.ts b/src/core/endpoints/fetch_messages.ts index 0ec208996..da9963882 100644 --- a/src/core/endpoints/fetch_messages.ts +++ b/src/core/endpoints/fetch_messages.ts @@ -4,9 +4,7 @@ * @internal */ -import { createValidationError, PubNubError } from '../../errors/pubnub-error'; import { TransportResponse } from '../types/transport-response'; -import { PubNubAPIError } from '../../errors/pubnub-api-error'; import { ICryptoModule } from '../interfaces/crypto-module'; import { AbstractRequest } from '../components/request'; import * as FileSharing from '../types/api/file-sharing'; @@ -172,7 +170,7 @@ type ServiceResponse = { * * @internal */ -export class FetchMessagesRequest extends AbstractRequest { +export class FetchMessagesRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); @@ -213,15 +211,7 @@ export class FetchMessagesRequest extends AbstractRequest { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - + const serviceResponse = this.deserializeResponse(response); const responseChannels = serviceResponse.channels ?? {}; const channels: History.FetchMessagesResponse['channels'] = {}; diff --git a/src/core/endpoints/file_upload/delete_file.ts b/src/core/endpoints/file_upload/delete_file.ts index 71617b36a..e740a8e75 100644 --- a/src/core/endpoints/file_upload/delete_file.ts +++ b/src/core/endpoints/file_upload/delete_file.ts @@ -4,9 +4,6 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; -import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import { TransportMethod } from '../../types/transport-request'; import { AbstractRequest } from '../../components/request'; import * as FileSharing from '../../types/api/file-sharing'; @@ -45,7 +42,7 @@ type ServiceResponse = { * * @internal */ -export class DeleteFileRequest extends AbstractRequest { +export class DeleteFileRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super({ method: TransportMethod.DELETE }); } @@ -62,19 +59,6 @@ export class DeleteFileRequest extends AbstractRequest { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return serviceResponse; - } - protected get path(): string { const { keySet: { subscribeKey }, diff --git a/src/core/endpoints/file_upload/download_file.ts b/src/core/endpoints/file_upload/download_file.ts index 90055d25d..4a0674d38 100644 --- a/src/core/endpoints/file_upload/download_file.ts +++ b/src/core/endpoints/file_upload/download_file.ts @@ -52,7 +52,7 @@ type RequestParameters = FileSharing.DownloadFileParameters & { */ export class DownloadFileRequest< PlatformFile extends Partial = Record, -> extends AbstractRequest { +> extends AbstractRequest> { constructor(private readonly parameters: RequestParameters) { super(); } diff --git a/src/core/endpoints/file_upload/generate_upload_url.ts b/src/core/endpoints/file_upload/generate_upload_url.ts index b71ebf798..66c87379a 100644 --- a/src/core/endpoints/file_upload/generate_upload_url.ts +++ b/src/core/endpoints/file_upload/generate_upload_url.ts @@ -4,9 +4,7 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import { TransportMethod } from '../../types/transport-request'; import { AbstractRequest } from '../../components/request'; import * as FileSharing from '../../types/api/file-sharing'; @@ -105,7 +103,10 @@ type ServiceResponse = { * * @internal */ -export class GenerateFileUploadUrlRequest extends AbstractRequest { +export class GenerateFileUploadUrlRequest extends AbstractRequest< + FileSharing.GenerateFileUploadUrlResponse, + ServiceResponse +> { constructor(private readonly parameters: RequestParameters) { super({ method: TransportMethod.POST }); } @@ -120,14 +121,7 @@ export class GenerateFileUploadUrlRequest extends AbstractRequest { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); + const serviceResponse = this.deserializeResponse(response); return { id: serviceResponse.data.id, diff --git a/src/core/endpoints/file_upload/get_file_url.ts b/src/core/endpoints/file_upload/get_file_url.ts index b81f4c91b..754109f52 100644 --- a/src/core/endpoints/file_upload/get_file_url.ts +++ b/src/core/endpoints/file_upload/get_file_url.ts @@ -35,7 +35,7 @@ type RequestParameters = FileSharing.FileUrlParameters & { * * @internal */ -export class GetFileDownloadUrlRequest extends AbstractRequest { +export class GetFileDownloadUrlRequest extends AbstractRequest> { /** * Construct file download Url generation request. * diff --git a/src/core/endpoints/file_upload/list_files.ts b/src/core/endpoints/file_upload/list_files.ts index 3949e05a4..091c7a9b1 100644 --- a/src/core/endpoints/file_upload/list_files.ts +++ b/src/core/endpoints/file_upload/list_files.ts @@ -4,9 +4,6 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; -import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import { AbstractRequest } from '../../components/request'; import * as FileSharing from '../../types/api/file-sharing'; import RequestOperation from '../../constants/operations'; @@ -70,7 +67,7 @@ type ServiceResponse = { * * @internal */ -export class FilesListRequest extends AbstractRequest { +export class FilesListRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); @@ -86,19 +83,6 @@ export class FilesListRequest extends AbstractRequest { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return serviceResponse; - } - protected get path(): string { const { keySet: { subscribeKey }, diff --git a/src/core/endpoints/file_upload/publish_file.ts b/src/core/endpoints/file_upload/publish_file.ts index 21784b89b..c836638bd 100644 --- a/src/core/endpoints/file_upload/publish_file.ts +++ b/src/core/endpoints/file_upload/publish_file.ts @@ -4,7 +4,6 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; import { ICryptoModule } from '../../interfaces/crypto-module'; import { AbstractRequest } from '../../components/request'; @@ -56,7 +55,10 @@ type ServiceResponse = [0 | 1, string, string]; * * @internal */ -export class PublishFileMessageRequest extends AbstractRequest { +export class PublishFileMessageRequest extends AbstractRequest< + FileSharing.PublishFileMessageResponse, + ServiceResponse +> { constructor(private readonly parameters: RequestParameters) { super(); @@ -77,15 +79,7 @@ export class PublishFileMessageRequest extends AbstractRequest { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - - return { timetoken: serviceResponse[2] }; + return { timetoken: this.deserializeResponse(response)[2] }; } protected get path(): string { diff --git a/src/core/endpoints/file_upload/send_file.ts b/src/core/endpoints/file_upload/send_file.ts index 177dcba73..b991c4742 100644 --- a/src/core/endpoints/file_upload/send_file.ts +++ b/src/core/endpoints/file_upload/send_file.ts @@ -6,16 +6,16 @@ import { PubNubFileConstructor, PubNubFileInterface } from '../../types/file'; import { GenerateFileUploadUrlRequest } from './generate_upload_url'; +import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import { ICryptoModule } from '../../interfaces/crypto-module'; import { Cryptography } from '../../interfaces/cryptography'; import { AbstractRequest } from '../../components/request'; import * as FileSharing from '../../types/api/file-sharing'; import { PubNubError } from '../../../errors/pubnub-error'; import RequestOperation from '../../constants/operations'; +import StatusCategory from '../../constants/categories'; import { UploadFileRequest } from './upload-file'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import { KeySet } from '../../types/api'; -import StatusCategory from '../../constants/categories'; // -------------------------------------------------------- // ------------------------ Types ------------------------- @@ -46,7 +46,7 @@ type RequestParameters = FileSharing.SendFileParameters(request: AbstractRequest) => Promise; + sendRequest: (request: AbstractRequest>) => Promise; /** * File message publish method. diff --git a/src/core/endpoints/file_upload/upload-file.ts b/src/core/endpoints/file_upload/upload-file.ts index 7c2b0e0b8..a1ef99507 100644 --- a/src/core/endpoints/file_upload/upload-file.ts +++ b/src/core/endpoints/file_upload/upload-file.ts @@ -4,8 +4,8 @@ * @internal */ -import { TransportResponse } from '../../types/transport-response'; import { TransportMethod, TransportRequest } from '../../types/transport-request'; +import { TransportResponse } from '../../types/transport-response'; import { AbstractRequest } from '../../components/request'; import * as FileSharing from '../../types/api/file-sharing'; import RequestOperation from '../../constants/operations'; @@ -16,7 +16,7 @@ import { PubNubFileInterface } from '../../types/file'; * * @internal */ -export class UploadFileRequest extends AbstractRequest { +export class UploadFileRequest extends AbstractRequest> { constructor(private readonly parameters: FileSharing.UploadFileParameters) { super({ method: TransportMethod.POST }); diff --git a/src/core/endpoints/history/delete_messages.ts b/src/core/endpoints/history/delete_messages.ts index 1964d982f..e4639fc2a 100644 --- a/src/core/endpoints/history/delete_messages.ts +++ b/src/core/endpoints/history/delete_messages.ts @@ -4,9 +4,7 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import type { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import { TransportMethod } from '../../types/transport-request'; import { AbstractRequest } from '../../components/request'; import RequestOperation from '../../constants/operations'; @@ -55,7 +53,7 @@ type ServiceResponse = { * * @internal */ -export class DeleteMessageRequest extends AbstractRequest { +export class DeleteMessageRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super({ method: TransportMethod.DELETE }); } @@ -70,16 +68,7 @@ export class DeleteMessageRequest extends AbstractRequest { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return {}; + return super.parse(response).then((_) => ({})); } protected get path(): string { diff --git a/src/core/endpoints/history/get_history.ts b/src/core/endpoints/history/get_history.ts index a8d82043a..99c970c96 100644 --- a/src/core/endpoints/history/get_history.ts +++ b/src/core/endpoints/history/get_history.ts @@ -4,7 +4,6 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; import { ICryptoModule } from '../../interfaces/crypto-module'; import { AbstractRequest } from '../../components/request'; @@ -108,7 +107,7 @@ type ServiceResponse = [ * * @internal */ -export class GetHistoryRequest extends AbstractRequest { +export class GetHistoryRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); @@ -131,14 +130,7 @@ export class GetHistoryRequest extends AbstractRequest { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - + const serviceResponse = this.deserializeResponse(response); const messages = serviceResponse[0]; const startTimeToken = serviceResponse[1]; const endTimeToken = serviceResponse[2]; diff --git a/src/core/endpoints/history/message_counts.ts b/src/core/endpoints/history/message_counts.ts index 43d92d0bc..6e1c32d3d 100644 --- a/src/core/endpoints/history/message_counts.ts +++ b/src/core/endpoints/history/message_counts.ts @@ -4,9 +4,7 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import { AbstractRequest } from '../../components/request'; import RequestOperation from '../../constants/operations'; import * as History from '../../types/api/history'; @@ -75,7 +73,7 @@ type ServiceResponse = { * * @internal */ -export class MessageCountRequest extends AbstractRequest { +export class MessageCountRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); } @@ -101,16 +99,7 @@ export class MessageCountRequest extends AbstractRequest { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return { channels: serviceResponse.channels }; + return { channels: this.deserializeResponse(response).channels }; } protected get path(): string { diff --git a/src/core/endpoints/objects/channel/get.ts b/src/core/endpoints/objects/channel/get.ts index 9748609e6..d2b37378e 100644 --- a/src/core/endpoints/objects/channel/get.ts +++ b/src/core/endpoints/objects/channel/get.ts @@ -4,9 +4,6 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../../errors/pubnub-error'; -import { TransportResponse } from '../../../types/transport-response'; -import { PubNubAPIError } from '../../../../errors/pubnub-api-error'; import { AbstractRequest } from '../../../components/request'; import RequestOperation from '../../../constants/operations'; import * as AppContext from '../../../types/api/app-context'; @@ -48,7 +45,7 @@ type RequestParameters = AppContext.GetChannelMetadataParameters & { export class GetChannelMetadataRequest< Response extends AppContext.GetChannelMetadataResponse, Custom extends AppContext.CustomData = AppContext.CustomData, -> extends AbstractRequest { +> extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); @@ -65,19 +62,6 @@ export class GetChannelMetadataRequest< if (!this.parameters.channel) return 'Channel cannot be empty'; } - async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return serviceResponse; - } - protected get path(): string { const { keySet: { subscribeKey }, diff --git a/src/core/endpoints/objects/channel/get_all.ts b/src/core/endpoints/objects/channel/get_all.ts index 8adaf8f42..f7af5889e 100644 --- a/src/core/endpoints/objects/channel/get_all.ts +++ b/src/core/endpoints/objects/channel/get_all.ts @@ -4,9 +4,6 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../../errors/pubnub-error'; -import { TransportResponse } from '../../../types/transport-response'; -import { PubNubAPIError } from '../../../../errors/pubnub-api-error'; import { AbstractRequest } from '../../../components/request'; import RequestOperation from '../../../constants/operations'; import * as AppContext from '../../../types/api/app-context'; @@ -58,7 +55,7 @@ type RequestParameters, Custom extends AppContext.CustomData = AppContext.CustomData, -> extends AbstractRequest { +> extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); @@ -73,19 +70,6 @@ export class GetAllChannelsMetadataRequest< return RequestOperation.PNGetAllChannelMetadataOperation; } - async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return serviceResponse; - } - protected get path(): string { return `/v2/objects/${this.parameters.keySet.subscribeKey}/channels`; } diff --git a/src/core/endpoints/objects/channel/remove.ts b/src/core/endpoints/objects/channel/remove.ts index 440517d7d..79c2bad7c 100644 --- a/src/core/endpoints/objects/channel/remove.ts +++ b/src/core/endpoints/objects/channel/remove.ts @@ -4,9 +4,6 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../../errors/pubnub-error'; -import { TransportResponse } from '../../../types/transport-response'; -import { PubNubAPIError } from '../../../../errors/pubnub-api-error'; import { TransportMethod } from '../../../types/transport-request'; import { AbstractRequest } from '../../../components/request'; import RequestOperation from '../../../constants/operations'; @@ -37,7 +34,7 @@ type RequestParameters = AppContext.RemoveChannelMetadataParameters & { */ export class RemoveChannelMetadataRequest< Response extends AppContext.RemoveChannelMetadataResponse, -> extends AbstractRequest { +> extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super({ method: TransportMethod.DELETE }); } @@ -50,19 +47,6 @@ export class RemoveChannelMetadataRequest< if (!this.parameters.channel) return 'Channel cannot be empty'; } - async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return serviceResponse; - } - protected get path(): string { const { keySet: { subscribeKey }, diff --git a/src/core/endpoints/objects/channel/set.ts b/src/core/endpoints/objects/channel/set.ts index dd82075b6..65a96cfc6 100644 --- a/src/core/endpoints/objects/channel/set.ts +++ b/src/core/endpoints/objects/channel/set.ts @@ -4,9 +4,6 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../../errors/pubnub-error'; -import { TransportResponse } from '../../../types/transport-response'; -import { PubNubAPIError } from '../../../../errors/pubnub-api-error'; import { TransportMethod } from '../../../types/transport-request'; import { AbstractRequest } from '../../../components/request'; import RequestOperation from '../../../constants/operations'; @@ -49,7 +46,7 @@ type RequestParameters = AppContext.SetChannelMetadataParameters, Custom extends AppContext.CustomData = AppContext.CustomData, -> extends AbstractRequest { +> extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super({ method: TransportMethod.PATCH }); @@ -75,19 +72,6 @@ export class SetChannelMetadataRequest< } } - async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return serviceResponse; - } - protected get path(): string { const { keySet: { subscribeKey }, diff --git a/src/core/endpoints/objects/member/get.ts b/src/core/endpoints/objects/member/get.ts index da0ffecc5..04a96826a 100644 --- a/src/core/endpoints/objects/member/get.ts +++ b/src/core/endpoints/objects/member/get.ts @@ -4,9 +4,6 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../../errors/pubnub-error'; -import { TransportResponse } from '../../../types/transport-response'; -import { PubNubAPIError } from '../../../../errors/pubnub-api-error'; import { AbstractRequest } from '../../../components/request'; import RequestOperation from '../../../constants/operations'; import * as AppContext from '../../../types/api/app-context'; @@ -89,7 +86,7 @@ export class GetChannelMembersRequest< Response extends AppContext.GetMembersResponse, MembersCustom extends AppContext.CustomData = AppContext.CustomData, UUIDCustom extends AppContext.CustomData = AppContext.CustomData, -> extends AbstractRequest { +> extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); @@ -114,19 +111,6 @@ export class GetChannelMembersRequest< if (!this.parameters.channel) return 'Channel cannot be empty'; } - async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return serviceResponse; - } - protected get path(): string { const { keySet: { subscribeKey }, diff --git a/src/core/endpoints/objects/member/set.ts b/src/core/endpoints/objects/member/set.ts index f29889a8a..56a5ccc5f 100644 --- a/src/core/endpoints/objects/member/set.ts +++ b/src/core/endpoints/objects/member/set.ts @@ -4,9 +4,6 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../../errors/pubnub-error'; -import { TransportResponse } from '../../../types/transport-response'; -import { PubNubAPIError } from '../../../../errors/pubnub-api-error'; import { TransportMethod } from '../../../types/transport-request'; import { AbstractRequest } from '../../../components/request'; import RequestOperation from '../../../constants/operations'; @@ -95,7 +92,7 @@ export class SetChannelMembersRequest< Response extends AppContext.SetMembersResponse, MembersCustom extends AppContext.CustomData = AppContext.CustomData, UUIDCustom extends AppContext.CustomData = AppContext.CustomData, -> extends AbstractRequest { +> extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super({ method: TransportMethod.PATCH }); @@ -123,19 +120,6 @@ export class SetChannelMembersRequest< if (!uuids || uuids.length === 0) return 'UUIDs cannot be empty'; } - async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return serviceResponse; - } - protected get path(): string { const { keySet: { subscribeKey }, diff --git a/src/core/endpoints/objects/membership/get.ts b/src/core/endpoints/objects/membership/get.ts index 89850ec1f..6a647862f 100644 --- a/src/core/endpoints/objects/membership/get.ts +++ b/src/core/endpoints/objects/membership/get.ts @@ -4,9 +4,6 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../../errors/pubnub-error'; -import { TransportResponse } from '../../../types/transport-response'; -import { PubNubAPIError } from '../../../../errors/pubnub-api-error'; import { AbstractRequest } from '../../../components/request'; import RequestOperation from '../../../constants/operations'; import * as AppContext from '../../../types/api/app-context'; @@ -89,7 +86,7 @@ export class GetUUIDMembershipsRequest< Response extends AppContext.GetMembershipsResponse, MembersCustom extends AppContext.CustomData = AppContext.CustomData, UUIDCustom extends AppContext.CustomData = AppContext.CustomData, -> extends AbstractRequest { +> extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); @@ -117,19 +114,6 @@ export class GetUUIDMembershipsRequest< if (!this.parameters.uuid) return "'uuid' cannot be empty"; } - async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return serviceResponse; - } - protected get path(): string { const { keySet: { subscribeKey }, diff --git a/src/core/endpoints/objects/membership/set.ts b/src/core/endpoints/objects/membership/set.ts index fa2cecc73..9971c5e58 100644 --- a/src/core/endpoints/objects/membership/set.ts +++ b/src/core/endpoints/objects/membership/set.ts @@ -4,9 +4,6 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../../errors/pubnub-error'; -import { TransportResponse } from '../../../types/transport-response'; -import { PubNubAPIError } from '../../../../errors/pubnub-api-error'; import { TransportMethod } from '../../../types/transport-request'; import { AbstractRequest } from '../../../components/request'; import RequestOperation from '../../../constants/operations'; @@ -95,7 +92,7 @@ export class SetUUIDMembershipsRequest< Response extends AppContext.SetMembershipsResponse, MembersCustom extends AppContext.CustomData = AppContext.CustomData, UUIDCustom extends AppContext.CustomData = AppContext.CustomData, -> extends AbstractRequest { +> extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super({ method: TransportMethod.PATCH }); @@ -126,19 +123,6 @@ export class SetUUIDMembershipsRequest< if (!channels || channels.length === 0) return 'Channels cannot be empty'; } - async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return serviceResponse; - } - protected get path(): string { const { keySet: { subscribeKey }, diff --git a/src/core/endpoints/objects/uuid/get.ts b/src/core/endpoints/objects/uuid/get.ts index 9c3e22781..6642574c4 100644 --- a/src/core/endpoints/objects/uuid/get.ts +++ b/src/core/endpoints/objects/uuid/get.ts @@ -4,9 +4,6 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../../errors/pubnub-error'; -import { TransportResponse } from '../../../types/transport-response'; -import { PubNubAPIError } from '../../../../errors/pubnub-api-error'; import { AbstractRequest } from '../../../components/request'; import RequestOperation from '../../../constants/operations'; import * as AppContext from '../../../types/api/app-context'; @@ -48,7 +45,7 @@ type RequestParameters = AppContext.GetUUIDMetadataParameters & { export class GetUUIDMetadataRequest< Response extends AppContext.GetUUIDMetadataResponse, Custom extends AppContext.CustomData = AppContext.CustomData, -> extends AbstractRequest { +> extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); @@ -68,19 +65,6 @@ export class GetUUIDMetadataRequest< if (!this.parameters.uuid) return "'uuid' cannot be empty"; } - async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return serviceResponse; - } - protected get path(): string { const { keySet: { subscribeKey }, diff --git a/src/core/endpoints/objects/uuid/get_all.ts b/src/core/endpoints/objects/uuid/get_all.ts index e2b86be3c..a637a1279 100644 --- a/src/core/endpoints/objects/uuid/get_all.ts +++ b/src/core/endpoints/objects/uuid/get_all.ts @@ -4,9 +4,6 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../../errors/pubnub-error'; -import { TransportResponse } from '../../../types/transport-response'; -import { PubNubAPIError } from '../../../../errors/pubnub-api-error'; import { AbstractRequest } from '../../../components/request'; import RequestOperation from '../../../constants/operations'; import * as AppContext from '../../../types/api/app-context'; @@ -53,7 +50,7 @@ type RequestParameters, Custom extends AppContext.CustomData = AppContext.CustomData, -> extends AbstractRequest { +> extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); @@ -67,19 +64,6 @@ export class GetAllUUIDMetadataRequest< return RequestOperation.PNGetAllUUIDMetadataOperation; } - async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return serviceResponse; - } - protected get path(): string { return `/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`; } diff --git a/src/core/endpoints/objects/uuid/remove.ts b/src/core/endpoints/objects/uuid/remove.ts index 09afb9b2b..7d1f817bb 100644 --- a/src/core/endpoints/objects/uuid/remove.ts +++ b/src/core/endpoints/objects/uuid/remove.ts @@ -4,9 +4,6 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../../errors/pubnub-error'; -import { TransportResponse } from '../../../types/transport-response'; -import { PubNubAPIError } from '../../../../errors/pubnub-api-error'; import { TransportMethod } from '../../../types/transport-request'; import { AbstractRequest } from '../../../components/request'; import RequestOperation from '../../../constants/operations'; @@ -35,9 +32,10 @@ type RequestParameters = AppContext.RemoveUUIDMetadataParameters & { * * @internal */ -export class RemoveUUIDMetadataRequest< - Response extends AppContext.RemoveUUIDMetadataResponse, -> extends AbstractRequest { +export class RemoveUUIDMetadataRequest extends AbstractRequest< + Response, + Response +> { constructor(private readonly parameters: RequestParameters) { super({ method: TransportMethod.DELETE }); @@ -53,19 +51,6 @@ export class RemoveUUIDMetadataRequest< if (!this.parameters.uuid) return "'uuid' cannot be empty"; } - async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return serviceResponse; - } - protected get path(): string { const { keySet: { subscribeKey }, diff --git a/src/core/endpoints/objects/uuid/set.ts b/src/core/endpoints/objects/uuid/set.ts index 879689a76..17be16d55 100644 --- a/src/core/endpoints/objects/uuid/set.ts +++ b/src/core/endpoints/objects/uuid/set.ts @@ -4,9 +4,6 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../../errors/pubnub-error'; -import { TransportResponse } from '../../../types/transport-response'; -import { PubNubAPIError } from '../../../../errors/pubnub-api-error'; import { TransportMethod } from '../../../types/transport-request'; import { AbstractRequest } from '../../../components/request'; import RequestOperation from '../../../constants/operations'; @@ -49,7 +46,7 @@ type RequestParameters = AppContext.SetUUIDMetadataParameters, Custom extends AppContext.CustomData = AppContext.CustomData, -> extends AbstractRequest { +> extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super({ method: TransportMethod.PATCH }); @@ -78,19 +75,6 @@ export class SetUUIDMetadataRequest< } } - async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return serviceResponse; - } - protected get path(): string { const { keySet: { subscribeKey }, diff --git a/src/core/endpoints/presence/get_state.ts b/src/core/endpoints/presence/get_state.ts index 496f5e471..ab7905ad3 100644 --- a/src/core/endpoints/presence/get_state.ts +++ b/src/core/endpoints/presence/get_state.ts @@ -4,9 +4,7 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import { AbstractRequest } from '../../components/request'; import RequestOperation from '../../constants/operations'; import { KeySet, Payload, Query } from '../../types/api'; @@ -64,7 +62,7 @@ type ServiceResponse = { * * @internal */ -export class GetPresenceStateRequest extends AbstractRequest { +export class GetPresenceStateRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); @@ -88,15 +86,7 @@ export class GetPresenceStateRequest extends AbstractRequest { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - + const serviceResponse = this.deserializeResponse(response); const { channels = [], channelGroups = [] } = this.parameters; const state: { channels: Record } = { channels: {} }; diff --git a/src/core/endpoints/presence/heartbeat.ts b/src/core/endpoints/presence/heartbeat.ts index 76eeb903a..ab4513fff 100644 --- a/src/core/endpoints/presence/heartbeat.ts +++ b/src/core/endpoints/presence/heartbeat.ts @@ -4,9 +4,7 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import { AbstractRequest } from '../../components/request'; import RequestOperation from '../../constants/operations'; import * as Presence from '../../types/api/presence'; @@ -54,7 +52,7 @@ type ServiceResponse = { * * @internal */ -export class HeartbeatRequest extends AbstractRequest { +export class HeartbeatRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); } @@ -76,16 +74,7 @@ export class HeartbeatRequest extends AbstractRequest { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return {}; + return super.parse(response).then((_) => ({})); } protected get path(): string { diff --git a/src/core/endpoints/presence/here_now.ts b/src/core/endpoints/presence/here_now.ts index a8dacb4d9..e4bea8ade 100644 --- a/src/core/endpoints/presence/here_now.ts +++ b/src/core/endpoints/presence/here_now.ts @@ -4,9 +4,7 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import { AbstractRequest } from '../../components/request'; import RequestOperation from '../../constants/operations'; import { KeySet, Payload, Query } from '../../types/api'; @@ -131,7 +129,7 @@ type ServiceResponse = SingleChannelServiceResponse | MultipleChannelServiceResp * * @internal */ -export class HereNowRequest extends AbstractRequest { +export class HereNowRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); @@ -153,15 +151,7 @@ export class HereNowRequest extends AbstractRequest { } async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - + const serviceResponse = this.deserializeResponse(response); // Extract general presence information. const totalChannels = 'occupancy' in serviceResponse ? 1 : serviceResponse.payload.total_channels; const totalOccupancy = diff --git a/src/core/endpoints/presence/leave.ts b/src/core/endpoints/presence/leave.ts index 471354028..0fd4c9894 100644 --- a/src/core/endpoints/presence/leave.ts +++ b/src/core/endpoints/presence/leave.ts @@ -4,9 +4,7 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import { AbstractRequest } from '../../components/request'; import RequestOperation from '../../constants/operations'; import * as Presence from '../../types/api/presence'; @@ -59,7 +57,7 @@ type ServiceResponse = { * * @internal */ -export class PresenceLeaveRequest extends AbstractRequest { +export class PresenceLeaveRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); @@ -85,16 +83,7 @@ export class PresenceLeaveRequest extends AbstractRequest { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return {}; + return super.parse(response).then((_) => ({})); } protected get path(): string { diff --git a/src/core/endpoints/presence/set_state.ts b/src/core/endpoints/presence/set_state.ts index 989ddbf1c..2bd2aec08 100644 --- a/src/core/endpoints/presence/set_state.ts +++ b/src/core/endpoints/presence/set_state.ts @@ -4,9 +4,7 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import { AbstractRequest } from '../../components/request'; import RequestOperation from '../../constants/operations'; import { KeySet, Payload, Query } from '../../types/api'; @@ -64,7 +62,7 @@ type ServiceResponse = { * * @internal */ -export class SetPresenceStateRequest extends AbstractRequest { +export class SetPresenceStateRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); } @@ -88,16 +86,7 @@ export class SetPresenceStateRequest extends AbstractRequest { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); - - return { state: serviceResponse.payload }; + return { state: this.deserializeResponse(response).payload }; } protected get path(): string { diff --git a/src/core/endpoints/presence/where_now.ts b/src/core/endpoints/presence/where_now.ts index dfd12e8d8..828ec5e0b 100644 --- a/src/core/endpoints/presence/where_now.ts +++ b/src/core/endpoints/presence/where_now.ts @@ -4,9 +4,7 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; -import { PubNubAPIError } from '../../../errors/pubnub-api-error'; import { AbstractRequest } from '../../components/request'; import RequestOperation from '../../constants/operations'; import * as Presence from '../../types/api/presence'; @@ -64,7 +62,7 @@ type ServiceResponse = { * * @internal */ -export class WhereNowRequest extends AbstractRequest { +export class WhereNowRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); } @@ -78,19 +76,13 @@ export class WhereNowRequest extends AbstractRequest } async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) { - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - } else if (serviceResponse.status >= 400) throw PubNubAPIError.create(response); + const serviceResponse = this.deserializeResponse(response); if (!serviceResponse.payload) return { channels: [] }; return { channels: serviceResponse.payload.channels }; } + protected get path(): string { const { keySet: { subscribeKey }, diff --git a/src/core/endpoints/publish.ts b/src/core/endpoints/publish.ts index 6d0bfb3b5..14683c025 100644 --- a/src/core/endpoints/publish.ts +++ b/src/core/endpoints/publish.ts @@ -2,7 +2,6 @@ * Publish REST API module. */ -import { createValidationError, PubNubError } from '../../errors/pubnub-error'; import { TransportResponse } from '../types/transport-response'; import { TransportMethod } from '../types/transport-request'; import { ICryptoModule } from '../interfaces/crypto-module'; @@ -133,7 +132,7 @@ type ServiceResponse = [0 | 1, string, string]; * * @internal */ -export class PublishRequest extends AbstractRequest { +export class PublishRequest extends AbstractRequest { /** * Construct data publish request. * @@ -163,15 +162,7 @@ export class PublishRequest extends AbstractRequest { } async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - - return { timetoken: serviceResponse[2] }; + return { timetoken: this.deserializeResponse(response)[2] }; } protected get path(): string { @@ -197,6 +188,7 @@ export class PublishRequest extends AbstractRequest { } protected get headers(): Record | undefined { + if (!this.parameters.sendByPost) return undefined; return { 'Content-Type': 'application/json' }; } diff --git a/src/core/endpoints/push/add_push_channels.ts b/src/core/endpoints/push/add_push_channels.ts index 9f665b5b3..fcad65603 100644 --- a/src/core/endpoints/push/add_push_channels.ts +++ b/src/core/endpoints/push/add_push_channels.ts @@ -4,7 +4,6 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; import { BasePushNotificationChannelsRequest } from './push'; import RequestOperation from '../../constants/operations'; @@ -39,7 +38,8 @@ type ServiceResponse = [0 | 1, string]; */ // prettier-ignore export class AddDevicePushNotificationChannelsRequest extends BasePushNotificationChannelsRequest< - Push.ManageDeviceChannelsResponse + Push.ManageDeviceChannelsResponse, + ServiceResponse > { constructor(parameters: RequestParameters) { super({ ...parameters, action: 'add' }); @@ -50,14 +50,6 @@ export class AddDevicePushNotificationChannelsRequest extends BasePushNotificati } async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - - return {}; + return super.parse(response).then((_) => ({})); } } diff --git a/src/core/endpoints/push/list_push_channels.ts b/src/core/endpoints/push/list_push_channels.ts index f1ad59b02..0362511eb 100644 --- a/src/core/endpoints/push/list_push_channels.ts +++ b/src/core/endpoints/push/list_push_channels.ts @@ -4,7 +4,6 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; import { BasePushNotificationChannelsRequest } from './push'; import RequestOperation from '../../constants/operations'; @@ -39,7 +38,8 @@ type ServiceResponse = string[]; */ // prettier-ignore export class ListDevicePushNotificationChannelsRequest extends BasePushNotificationChannelsRequest< - Push.ListDeviceChannelsResponse + Push.ListDeviceChannelsResponse, + ServiceResponse > { constructor(parameters: RequestParameters) { super({ ...parameters, action: 'list' }); @@ -50,14 +50,6 @@ export class ListDevicePushNotificationChannelsRequest extends BasePushNotificat } async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - - return { channels: serviceResponse }; + return { channels: this.deserializeResponse(response) }; } } diff --git a/src/core/endpoints/push/push.ts b/src/core/endpoints/push/push.ts index fdbe36d3d..f7c64e67f 100644 --- a/src/core/endpoints/push/push.ts +++ b/src/core/endpoints/push/push.ts @@ -4,7 +4,6 @@ * @internal */ -import { TransportResponse } from '../../types/transport-response'; import { AbstractRequest } from '../../components/request'; import RequestOperation from '../../constants/operations'; import { KeySet, Query } from '../../types/api'; @@ -52,7 +51,7 @@ type RequestParameters = (Push.ManageDeviceChannelsParameters | Push.RemoveDevic * * @internal */ -export class BasePushNotificationChannelsRequest extends AbstractRequest { +export class BasePushNotificationChannelsRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); @@ -85,10 +84,6 @@ export class BasePushNotificationChannelsRequest extends AbstractRequest { if (this.parameters.pushGateway === 'apns2' && !this.parameters.topic) return 'Missing APNS2 topic'; } - async parse(_response: TransportResponse): Promise { - throw Error('Should be implemented in subclass.'); - } - protected get path(): string { const { keySet: { subscribeKey }, diff --git a/src/core/endpoints/push/remove_device.ts b/src/core/endpoints/push/remove_device.ts index b1150eeea..e099f53a8 100644 --- a/src/core/endpoints/push/remove_device.ts +++ b/src/core/endpoints/push/remove_device.ts @@ -4,7 +4,6 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; import { BasePushNotificationChannelsRequest } from './push'; import RequestOperation from '../../constants/operations'; @@ -39,7 +38,8 @@ type ServiceResponse = [0 | 1, string]; */ // prettier-ignore export class RemoveDevicePushNotificationRequest extends BasePushNotificationChannelsRequest< - Push.RemoveDeviceResponse + Push.RemoveDeviceResponse, + ServiceResponse > { constructor(parameters: RequestParameters) { super({ ...parameters, action: 'remove-device' }); @@ -50,14 +50,6 @@ export class RemoveDevicePushNotificationRequest extends BasePushNotificationCha } async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - - return {}; + return super.parse(response).then((_) =>({})); } } diff --git a/src/core/endpoints/push/remove_push_channels.ts b/src/core/endpoints/push/remove_push_channels.ts index 88648952b..c43923bfd 100644 --- a/src/core/endpoints/push/remove_push_channels.ts +++ b/src/core/endpoints/push/remove_push_channels.ts @@ -4,7 +4,6 @@ * @internal */ -import { createValidationError, PubNubError } from '../../../errors/pubnub-error'; import { TransportResponse } from '../../types/transport-response'; import { BasePushNotificationChannelsRequest } from './push'; import RequestOperation from '../../constants/operations'; @@ -39,7 +38,8 @@ type ServiceResponse = [0 | 1, string]; */ // prettier-ignore export class RemoveDevicePushNotificationChannelsRequest extends BasePushNotificationChannelsRequest< - Push.ManageDeviceChannelsResponse + Push.ManageDeviceChannelsResponse, + ServiceResponse > { constructor(parameters: RequestParameters) { super({ ...parameters, action: 'remove' }); @@ -50,14 +50,6 @@ export class RemoveDevicePushNotificationChannelsRequest extends BasePushNotific } async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - - return {}; + return super.parse(response).then((_) =>({})); } } diff --git a/src/core/endpoints/signal.ts b/src/core/endpoints/signal.ts index 7015c17ae..58d683b55 100644 --- a/src/core/endpoints/signal.ts +++ b/src/core/endpoints/signal.ts @@ -2,7 +2,6 @@ * Signal REST API module. */ -import { createValidationError, PubNubError } from '../../errors/pubnub-error'; import { TransportResponse } from '../types/transport-response'; import { AbstractRequest } from '../components/request'; import RequestOperation from '../constants/operations'; @@ -70,7 +69,7 @@ type ServiceResponse = [0 | 1, string, string]; * * @internal */ -export class SignalRequest extends AbstractRequest { +export class SignalRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); } @@ -92,15 +91,7 @@ export class SignalRequest extends AbstractRequest { } async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - - return { timetoken: serviceResponse[2] }; + return { timetoken: this.deserializeResponse(response)[2] }; } protected get path(): string { diff --git a/src/core/endpoints/subscribe.ts b/src/core/endpoints/subscribe.ts index 4af64fc70..f972115ac 100644 --- a/src/core/endpoints/subscribe.ts +++ b/src/core/endpoints/subscribe.ts @@ -2,7 +2,7 @@ * Subscription REST API module. */ -import { createValidationError, PubNubError } from '../../errors/pubnub-error'; +import { createMalformedResponseError, createValidationError, PubNubError } from '../../errors/pubnub-error'; import { TransportResponse } from '../types/transport-response'; import { ICryptoModule } from '../interfaces/crypto-module'; import * as Subscription from '../types/api/subscription'; @@ -603,7 +603,7 @@ export type SubscribeRequestParameters = Subscription.SubscribeParameters & { * * @internal */ -export class BaseSubscribeRequest extends AbstractRequest { +export class BaseSubscribeRequest extends AbstractRequest { constructor(protected readonly parameters: SubscribeRequestParameters) { super({ cancellable: true }); @@ -630,10 +630,11 @@ export class BaseSubscribeRequest extends AbstractRequest { let serviceResponse: ServiceResponse | undefined; + let responseText: string | undefined; try { - const json = AbstractRequest.decoder.decode(response.body); - const parsedJson = JSON.parse(json); + responseText = AbstractRequest.decoder.decode(response.body); + const parsedJson = JSON.parse(responseText); serviceResponse = parsedJson as ServiceResponse; } catch (error) { console.error('Error parsing JSON response:', error); @@ -642,7 +643,7 @@ export class BaseSubscribeRequest extends AbstractRequest { +export class TimeRequest extends AbstractRequest { constructor() { super(); } @@ -43,15 +42,7 @@ export class TimeRequest extends AbstractRequest { } async parse(response: TransportResponse): Promise { - const serviceResponse = this.deserializeResponse(response); - - if (!serviceResponse) - throw new PubNubError( - 'Service response error, check status for details', - createValidationError('Unable to deserialize service response'), - ); - - return { timetoken: serviceResponse[0] }; + return { timetoken: this.deserializeResponse(response)[0] }; } protected get path(): string { diff --git a/src/core/pubnub-channel-groups.ts b/src/core/pubnub-channel-groups.ts index 908c60d54..870763a2f 100644 --- a/src/core/pubnub-channel-groups.ts +++ b/src/core/pubnub-channel-groups.ts @@ -27,7 +27,7 @@ export default class PubNubChannelGroups { * * @internal */ - private readonly sendRequest: SendRequestFunction; + private readonly sendRequest: SendRequestFunction; /** * Create stream / channel group API access object. @@ -40,7 +40,7 @@ export default class PubNubChannelGroups { constructor( keySet: KeySet, /* eslint-disable @typescript-eslint/no-explicit-any */ - sendRequest: SendRequestFunction, + sendRequest: SendRequestFunction, ) { this.sendRequest = sendRequest; this.keySet = keySet; diff --git a/src/core/pubnub-common.ts b/src/core/pubnub-common.ts index fad5a3a75..0fc402dc0 100644 --- a/src/core/pubnub-common.ts +++ b/src/core/pubnub-common.ts @@ -764,8 +764,8 @@ export class PubNubCore< * * @internal */ - private sendRequest( - request: AbstractRequest, + private sendRequest( + request: AbstractRequest, callback: ResultCallback, ): void; @@ -778,7 +778,9 @@ export class PubNubCore< * * @returns Asynchronous request execution and response parsing result. */ - private async sendRequest(request: AbstractRequest): Promise; + private async sendRequest( + request: AbstractRequest, + ): Promise; /** * Schedule request execution. @@ -793,8 +795,8 @@ export class PubNubCore< * * @throws PubNubError in case of request processing error. */ - private async sendRequest( - request: AbstractRequest, + private async sendRequest( + request: AbstractRequest, callback?: ResultCallback, ): Promise { // Validate user-input. @@ -846,12 +848,13 @@ export class PubNubCore< // Handle special case when request completed but not fully processed by PubNub service. if (response.status !== 200 && response.status !== 204) { + const responseText = PubNubCore.decoder.decode(response.body); const contentType = response.headers['content-type']; if (contentType || contentType.indexOf('javascript') !== -1 || contentType.indexOf('json') !== -1) { - const json = JSON.parse(PubNubCore.decoder.decode(response.body)) as Payload; + const json = JSON.parse(responseText) as Payload; if (typeof json === 'object' && 'error' in json && json.error && typeof json.error === 'object') status.errorData = json.error; - } + } else status.responseText = responseText; } return request.parse(response); @@ -1203,7 +1206,7 @@ export class PubNubCore< */ if (this.subscriptionManager) { // Creating identifiable abort caller. - const callableAbort = () => request.abort(); + const callableAbort = () => request.abort('Cancel long-poll subscribe request'); callableAbort.identifier = request.requestIdentifier; this.subscriptionManager.abort = callableAbort; @@ -1297,7 +1300,7 @@ export class PubNubCore< }); const abortUnsubscribe = parameters.abortSignal.subscribe((err) => { - request.abort(); + request.abort('Cancel subscribe handshake request'); }); /** @@ -1331,7 +1334,7 @@ export class PubNubCore< }); const abortUnsubscribe = parameters.abortSignal.subscribe((err) => { - request.abort(); + request.abort('Cancel long-poll subscribe request'); }); /** @@ -1340,8 +1343,8 @@ export class PubNubCore< * **Note:** Had to be done after scheduling because transport provider return cancellation * controller only when schedule new request. */ - const handshakeResponse = this.sendRequest(request); - return handshakeResponse.then((response) => { + const receiveResponse = this.sendRequest(request); + return receiveResponse.then((response) => { abortUnsubscribe(); return response; }); @@ -1857,7 +1860,10 @@ export class PubNubCore< if (process.env.PRESENCE_MODULE !== 'disabled') { const { keySet, userId: userId } = this._configuration; const heartbeat = this._configuration.getPresenceTimeout(); - let request: AbstractRequest; + let request: AbstractRequest< + Presence.PresenceHeartbeatResponse | Presence.SetPresenceStateResponse, + Record + >; // Maintain presence information (if required). if (this._configuration.enableEventEngine && this.presenceState) { diff --git a/src/core/pubnub-objects.ts b/src/core/pubnub-objects.ts index b4587f76f..7113bdced 100644 --- a/src/core/pubnub-objects.ts +++ b/src/core/pubnub-objects.ts @@ -36,7 +36,7 @@ export default class PubNubObjects { * * @internal */ - private readonly sendRequest: SendRequestFunction; + private readonly sendRequest: SendRequestFunction; /** * REST API endpoints access credentials. * @@ -55,7 +55,7 @@ export default class PubNubObjects { constructor( configuration: PrivateClientConfiguration, /* eslint-disable @typescript-eslint/no-explicit-any */ - sendRequest: SendRequestFunction, + sendRequest: SendRequestFunction, ) { this.keySet = configuration.keySet; this.configuration = configuration; diff --git a/src/core/pubnub-push.ts b/src/core/pubnub-push.ts index c994533ac..eb53d2fc7 100644 --- a/src/core/pubnub-push.ts +++ b/src/core/pubnub-push.ts @@ -27,7 +27,7 @@ export default class PubNubPushNotifications { * * @internal */ - private readonly sendRequest: SendRequestFunction; + private readonly sendRequest: SendRequestFunction; /** * Create mobile push notifications API access object. @@ -40,7 +40,7 @@ export default class PubNubPushNotifications { constructor( keySet: KeySet, /* eslint-disable @typescript-eslint/no-explicit-any */ - sendRequest: SendRequestFunction, + sendRequest: SendRequestFunction, ) { this.sendRequest = sendRequest; this.keySet = keySet; diff --git a/src/core/types/api/index.ts b/src/core/types/api/index.ts index 0f85c95f8..172660476 100644 --- a/src/core/types/api/index.ts +++ b/src/core/types/api/index.ts @@ -31,8 +31,8 @@ export type KeySet = { * * @internal */ -export type SendRequestFunction = ( - request: AbstractRequest, +export type SendRequestFunction = ( + request: AbstractRequest, callback?: ResultCallback, ) => Promise; diff --git a/src/core/types/transport-request.ts b/src/core/types/transport-request.ts index 582dc640c..e2bcc62e7 100644 --- a/src/core/types/transport-request.ts +++ b/src/core/types/transport-request.ts @@ -39,7 +39,7 @@ export type CancellationController = { /** * Request cancellation / abort function. */ - abort: () => void; + abort: (reason?: string) => void; }; /** diff --git a/src/errors/pubnub-api-error.ts b/src/errors/pubnub-api-error.ts index 6f7c4d3de..2b948be64 100644 --- a/src/errors/pubnub-api-error.ts +++ b/src/errors/pubnub-api-error.ts @@ -121,20 +121,27 @@ export class PubNubAPIError extends Error { try { const errorResponse: Payload = JSON.parse(decoded); - if (typeof errorResponse === 'object' && !Array.isArray(errorResponse)) { - if ( - 'error' in errorResponse && - (errorResponse.error === 1 || errorResponse.error === true) && - 'status' in errorResponse && - typeof errorResponse.status === 'number' && - 'message' in errorResponse && - 'service' in errorResponse - ) { - errorData = errorResponse; - status = errorResponse.status; - } else errorData = errorResponse; - - if ('error' in errorResponse && errorResponse.error instanceof Error) errorData = errorResponse.error; + if (typeof errorResponse === 'object') { + if (!Array.isArray(errorResponse)) { + if ( + 'error' in errorResponse && + (errorResponse.error === 1 || errorResponse.error === true) && + 'status' in errorResponse && + typeof errorResponse.status === 'number' && + 'message' in errorResponse && + 'service' in errorResponse + ) { + errorData = errorResponse; + status = errorResponse.status; + } else errorData = errorResponse; + + if ('error' in errorResponse && errorResponse.error instanceof Error) errorData = errorResponse.error; + } else { + // Handling Publish API payload error. + if (typeof errorResponse[0] === 'number' && errorResponse[0] === 0) { + if (errorResponse.length > 1 && typeof errorResponse[1] === 'string') errorData = errorResponse[1]; + } + } } } catch (_) { errorData = decoded; diff --git a/src/errors/pubnub-error.ts b/src/errors/pubnub-error.ts index b3fee4d9b..69c1b174a 100644 --- a/src/errors/pubnub-error.ts +++ b/src/errors/pubnub-error.ts @@ -37,20 +37,15 @@ export class PubNubError extends Error { * Create error status object. * * @param errorPayload - Additional information which should be attached to the error status object. + * @param category - Occurred error category. * * @returns Error status object. * * @internal */ -function createError(errorPayload: { message: string; statusCode?: number }): Status { +function createError(errorPayload: { message: string; statusCode?: number }, category: StatusCategory): Status { errorPayload.statusCode ??= 0; - - return { - ...errorPayload, - statusCode: errorPayload.statusCode!, - category: StatusCategory.PNValidationErrorCategory, - error: true, - }; + return { ...errorPayload, statusCode: errorPayload.statusCode!, category, error: true }; } /** @@ -64,5 +59,25 @@ function createError(errorPayload: { message: string; statusCode?: number }): St * @internal */ export function createValidationError(message: string, statusCode?: number) { - return createError({ message, ...(statusCode !== undefined ? { statusCode } : {}) }); + return createError( + { message, ...(statusCode !== undefined ? { statusCode } : {}) }, + StatusCategory.PNValidationErrorCategory, + ); +} + +/** + * Create malformed service response error status object. + * + * @param [responseText] - Stringified original service response. + * @param [statusCode] - Operation HTTP status code. + */ +export function createMalformedResponseError(responseText?: string, statusCode?: number) { + return createError( + { + message: 'Unable to deserialize service response', + ...(responseText !== undefined ? { responseText } : {}), + ...(statusCode !== undefined ? { statusCode } : {}), + }, + StatusCategory.PNMalformedResponseCategory, + ); } diff --git a/src/transport/node-transport.ts b/src/transport/node-transport.ts index 2759f622b..a09f0b381 100644 --- a/src/transport/node-transport.ts +++ b/src/transport/node-transport.ts @@ -4,7 +4,7 @@ * @internal */ -import fetch, { Request, Response, RequestInit } from 'node-fetch'; +import fetch, { Request, Response, RequestInit, AbortError } from 'node-fetch'; import { ProxyAgent, ProxyAgentOptions } from 'proxy-agent'; import { Agent as HttpsAgent } from 'https'; import { Agent as HttpAgent } from 'http'; @@ -82,7 +82,10 @@ export class NodeTransport implements Transport { controller = { // Storing controller inside to prolong object lifetime. abortController, - abort: () => abortController?.abort(), + abort: (reason) => { + if (!abortController || abortController.signal.aborted) return; + abortController?.abort(reason); + }, } as CancellationController; } @@ -121,7 +124,15 @@ export class NodeTransport implements Transport { return transportResponse; }) .catch((error) => { - throw PubNubAPIError.create(error); + let fetchError = error; + + if (typeof error === 'string') { + const errorMessage = error.toLowerCase(); + if (errorMessage.includes('timeout') || !errorMessage.includes('cancel')) fetchError = new Error(error); + else if (errorMessage.includes('cancel')) fetchError = new AbortError('Aborted'); + } + + throw PubNubAPIError.create(fetchError); }); }), controller, diff --git a/src/transport/react-native-transport.ts b/src/transport/react-native-transport.ts index a6fd22e42..492787ad7 100644 --- a/src/transport/react-native-transport.ts +++ b/src/transport/react-native-transport.ts @@ -42,7 +42,7 @@ export class ReactNativeTransport implements Transport { const controller = { // Storing controller inside to prolong object lifetime. abortController, - abort: () => !abortController.signal.aborted && abortController.abort(), + abort: (reason) => !abortController.signal.aborted && abortController.abort(reason), } as CancellationController; return [ @@ -63,7 +63,7 @@ export class ReactNativeTransport implements Transport { clearTimeout(timeoutId); reject(new Error('Request timeout')); - controller.abort(); + controller.abort('Cancel because of timeout'); }, req.timeout * 1000); }); @@ -104,7 +104,18 @@ export class ReactNativeTransport implements Transport { return transportResponse; }) .catch((error) => { - throw PubNubAPIError.create(error); + let fetchError = error; + + if (typeof error === 'string') { + const errorMessage = error.toLowerCase(); + if (errorMessage.includes('timeout') || !errorMessage.includes('cancel')) fetchError = new Error(error); + else if (errorMessage.includes('cancel')) { + fetchError = new Error('Aborted'); + fetchError.name = 'AbortError'; + } + } + + throw PubNubAPIError.create(fetchError); }); }), controller, diff --git a/src/transport/subscription-worker/subscription-worker.ts b/src/transport/subscription-worker/subscription-worker.ts index 8b3b2d358..13bf73f1a 100644 --- a/src/transport/subscription-worker/subscription-worker.ts +++ b/src/transport/subscription-worker/subscription-worker.ts @@ -1097,7 +1097,15 @@ const sendRequest = ( const clients = getClients(); if (clients.length === 0) return; - failure(clients, error); + let fetchError = error; + + if (typeof error === 'string') { + const errorMessage = error.toLowerCase(); + if (errorMessage.includes('timeout') || !errorMessage.includes('cancel')) fetchError = new Error(error); + else if (errorMessage.includes('cancel')) fetchError = new DOMException('Aborted', 'AbortError'); + } + + failure(clients, fetchError); }); })(); }; @@ -1116,7 +1124,7 @@ const cancelRequest = (requestId: string) => { delete serviceRequests[requestId]; // Abort request if possible. - if (controller) controller.abort(); + if (controller) controller.abort('Cancel request'); } }; @@ -1722,10 +1730,11 @@ const requestProcessingError = (error?: unknown, res?: [Response, ArrayBuffer]): name = error.name; } - if (name === 'AbortError') { + if (message.toLowerCase().includes('timeout')) type = 'TIMEOUT'; + else if (name === 'AbortError' || message.toLowerCase().includes('cancel')) { message = 'Request aborted'; type = 'ABORTED'; - } else if (message === 'Request timeout') type = 'TIMEOUT'; + } return { type: 'request-process-error', diff --git a/src/transport/web-transport.ts b/src/transport/web-transport.ts index 1fac8c14f..c82a3ceab 100644 --- a/src/transport/web-transport.ts +++ b/src/transport/web-transport.ts @@ -116,7 +116,7 @@ export class WebTransport implements Transport { const abortController = new AbortController(); const cancellation: WebCancellationController = { abortController, - abort: () => !abortController.signal.aborted && abortController.abort(), + abort: (reason) => !abortController.signal.aborted && abortController.abort(reason), }; return [ @@ -151,7 +151,15 @@ export class WebTransport implements Transport { return transportResponse; }) .catch((error) => { - throw PubNubAPIError.create(error); + let fetchError = error; + + if (typeof error === 'string') { + const errorMessage = error.toLowerCase(); + if (errorMessage.includes('timeout') || !errorMessage.includes('cancel')) fetchError = new Error(error); + else if (errorMessage.includes('cancel')) fetchError = new DOMException('Aborted', 'AbortError'); + } + + throw PubNubAPIError.create(fetchError); }); }), cancellation, @@ -195,7 +203,7 @@ export class WebTransport implements Transport { clearTimeout(timeoutId); reject(new Error('Request timeout')); - controller.abort(); + controller.abort('Cancel because of timeout'); }, req.timeout * 1000); }); diff --git a/test/dist/web-titanium.test.js b/test/dist/web-titanium.test.js index 862a4bf68..e7cb57ccc 100644 --- a/test/dist/web-titanium.test.js +++ b/test/dist/web-titanium.test.js @@ -29,7 +29,7 @@ describe('#distribution test (titanium)', function () { listener = { status: function (st) { try { - expect(st.operation).to.be.equal("PNSubscribeOperation"); + expect(st.operation).to.be.equal('PNSubscribeOperation'); done(); } catch (error) { done(error); @@ -50,7 +50,7 @@ describe('#distribution test (titanium)', function () { message: function (m) { try { expect(m.channel).to.be.equal(myChannel2); - expect(m.message.text).to.be.equal("hello Titanium SDK"); + expect(m.message.text).to.be.equal('hello Titanium SDK'); done(); } catch (error) { done(error); @@ -68,7 +68,7 @@ describe('#distribution test (titanium)', function () { pubnub.setState({ channels: [myChannel1], state: { hello: 'there' } }, function (status, response) { try { expect(status.error).to.be.equal(false); - expect(response.state.hello).to.be.equal("there"); + expect(response.state.hello).to.be.equal('there'); done(); } catch (error) { done(error); @@ -79,7 +79,7 @@ describe('#distribution test (titanium)', function () { it('should have to get the time', function (done) { pubnub.time(function (status) { try { - expect(status.operation).to.be.equal("PNTimeOperation"); + expect(status.operation).to.be.equal('PNTimeOperation'); expect(status.statusCode).to.be.equal(200); done(); } catch (error) { @@ -142,7 +142,7 @@ describe('#distribution test (titanium)', function () { pubnub.setUUID('CustomUUID'); try { - expect(pubnub.getUUID()).to.be.equal("CustomUUID"); + expect(pubnub.getUUID()).to.be.equal('CustomUUID'); done(); } catch (error) { done(error); @@ -159,7 +159,7 @@ describe('#distribution test (titanium)', function () { pubnub.addListener({ status: function (st) { try { - expect(st.operation).to.be.equal("PNUnsubscribeOperation"); + expect(st.operation).to.be.equal('PNUnsubscribeOperation'); if (!finished) { // prevent calling done twice From e5bf466271f16629e60b8310002cf32f4309358f Mon Sep 17 00:00:00 2001 From: PubNub Release Bot <120067856+pubnub-release-bot@users.noreply.github.com> Date: Tue, 18 Feb 2025 11:59:28 +0000 Subject: [PATCH 2/2] PubNub SDK v8.9.0 release. --- .pubnub.yml | 13 ++++++++++--- CHANGELOG.md | 9 +++++++++ README.md | 4 ++-- dist/web/pubnub.js | 5 ++--- dist/web/pubnub.min.js | 2 +- lib/core/components/configuration.js | 2 +- lib/core/components/request.js | 5 ++--- lib/core/components/subscription-manager.js | 11 +++++------ lib/core/endpoints/access_manager/revoke_token.js | 2 +- lib/transport/node-transport.js | 2 +- lib/transport/react-native-transport.js | 6 ++++-- package.json | 2 +- src/core/components/configuration.ts | 2 +- 13 files changed, 40 insertions(+), 25 deletions(-) diff --git a/.pubnub.yml b/.pubnub.yml index ee947b1e8..4345ec7b6 100644 --- a/.pubnub.yml +++ b/.pubnub.yml @@ -1,5 +1,12 @@ --- changelog: + - date: 2025-02-18 + version: v8.9.0 + changes: + - type: feature + text: "Emit 'PNDisconnectedUnexpectedlyCategory' in cases when client receives bad request or unexpected / malformed service response." + - type: improvement + text: "Move error / malformed response handling into `AbstractRequest` to simplify actual endpoint classes." - date: 2025-02-10 version: v8.8.1 changes: @@ -1137,7 +1144,7 @@ supported-platforms: - 'Ubuntu 14.04 and up' - 'Windows 7 and up' version: 'Pubnub Javascript for Node' -version: '8.8.1' +version: '8.9.0' sdks: - full-name: PubNub Javascript SDK short-name: Javascript @@ -1153,7 +1160,7 @@ sdks: - distribution-type: source distribution-repository: GitHub release package-name: pubnub.js - location: https://github.com/pubnub/javascript/archive/refs/tags/v8.8.1.zip + location: https://github.com/pubnub/javascript/archive/refs/tags/v8.9.0.zip requires: - name: 'agentkeepalive' min-version: '3.5.2' @@ -1824,7 +1831,7 @@ sdks: - distribution-type: library distribution-repository: GitHub release package-name: pubnub.js - location: https://github.com/pubnub/javascript/releases/download/v8.8.1/pubnub.8.8.1.js + location: https://github.com/pubnub/javascript/releases/download/v8.9.0/pubnub.8.9.0.js requires: - name: 'agentkeepalive' min-version: '3.5.2' diff --git a/CHANGELOG.md b/CHANGELOG.md index 7fcecbabf..57065e5b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,12 @@ +## v8.9.0 +February 18 2025 + +#### Added +- Emit 'PNDisconnectedUnexpectedlyCategory' in cases when client receives bad request or unexpected / malformed service response. + +#### Modified +- Move error / malformed response handling into `AbstractRequest` to simplify actual endpoint classes. + ## v8.8.1 February 10 2025 diff --git a/README.md b/README.md index d998aaa07..5c6f82a1f 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.8.8.1.js - * https://cdn.pubnub.com/sdk/javascript/pubnub.8.8.1.min.js + * https://cdn.pubnub.com/sdk/javascript/pubnub.8.9.0.js + * https://cdn.pubnub.com/sdk/javascript/pubnub.8.9.0.min.js 2. Configure your keys: diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index f9636ceb5..e9957c248 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -3759,7 +3759,7 @@ return base.PubNubFile; }, get version() { - return '8.8.1'; + return '8.9.0'; }, getVersion() { return this.version; @@ -5984,9 +5984,8 @@ throw new PubNubError('Service response error, check status for details', createMalformedResponseError(responseText, response.status)); } // Throw and exception in case of client / server error. - if ('status' in parsedJson && typeof parsedJson.status === 'number' && parsedJson.status >= 400) { + if ('status' in parsedJson && typeof parsedJson.status === 'number' && parsedJson.status >= 400) throw PubNubAPIError.create(response); - } return parsedJson; } } diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index e0a374578..6ec372c60 100644 --- a/dist/web/pubnub.min.js +++ b/dist/web/pubnub.min.js @@ -1,2 +1,2 @@ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).PubNub=t()}(this,(function(){"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n={exports:{}};!function(t){!function(e,n){var s=Math.pow(2,-24),r=Math.pow(2,32),i=Math.pow(2,53);var a={encode:function(e){var t,s=new ArrayBuffer(256),a=new DataView(s),o=0;function c(e){for(var n=s.byteLength,r=o+e;n>2,u=0;u>6),r.push(128|63&a)):a<55296?(r.push(224|a>>12),r.push(128|a>>6&63),r.push(128|63&a)):(a=(1023&a)<<10,a|=1023&t.charCodeAt(++s),a+=65536,r.push(240|a>>18),r.push(128|a>>12&63),r.push(128|a>>6&63),r.push(128|63&a))}return d(3,r.length),h(r);default:var p;if(Array.isArray(t))for(d(4,p=t.length),s=0;s>5!==e)throw"Invalid indefinite length element";return n}function f(e,t){for(var n=0;n>10),e.push(56320|1023&s))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof i&&(i=function(){return n});var m=function e(){var r,d,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=h(),r=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*s;return t.setUint32(0,r<<16|i<<13|a<<13),t.getFloat32(0)}();case 26:return c(a.getFloat32(o),4);case 27:return c(a.getFloat64(o),8)}if((d=g(v))<0&&(b<2||6=0;)S+=d,w.push(u(d));var E=new Uint8Array(S),O=0;for(r=0;r=0;)f(k,d);else f(k,d);return String.fromCharCode.apply(null,k);case 4:var C;if(d<0)for(C=[];!p();)C.push(e());else for(C=new Array(d),r=0;r{const n=new FileReader;n.addEventListener("load",(()=>{if(n.result instanceof ArrayBuffer)return e(n.result)})),n.addEventListener("error",(()=>t(n.error))),n.readAsArrayBuffer(this.data)}))}))}toString(){return i(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const n=new FileReader;n.addEventListener("load",(()=>{if("string"==typeof n.result)return e(n.result)})),n.addEventListener("error",(()=>{t(n.error)})),n.readAsBinaryString(this.data)}))}))}toStream(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in Node.js environments.")}))}toFile(){return i(this,void 0,void 0,(function*(){return this.data}))}toFileUri(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in React Native environments.")}))}toBlob(){return i(this,void 0,void 0,(function*(){return this.data}))}}o.supportsBlob="undefined"!=typeof Blob,o.supportsFile="undefined"!=typeof File,o.supportsBuffer=!1,o.supportsStream=!1,o.supportsString=!0,o.supportsArrayBuffer=!0,o.supportsEncryptFile=!0,o.supportsFileUri=!1;function c(e){const t=e.replace(/==?$/,""),n=Math.floor(t.length/4*3),s=new ArrayBuffer(n),r=new Uint8Array(s);let i=0;function a(){const e=t.charAt(i++),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e);if(-1===n)throw new Error(`Illegal character at ${i}: ${t.charAt(i-1)}`);return n}for(let e=0;e>4,c=(15&n)<<4|s>>2,u=(3&s)<<6|i;r[e]=o,64!=s&&(r[e+1]=c),64!=i&&(r[e+2]=u)}return s}function u(e){let t="";const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=new Uint8Array(e),r=s.byteLength,i=r%3,a=r-i;let o,c,u,l,h;for(let e=0;e>18,c=(258048&h)>>12,u=(4032&h)>>6,l=63&h,t+=n[o]+n[c]+n[u]+n[l];return 1==i?(h=s[a],o=(252&h)>>2,c=(3&h)<<4,t+=n[o]+n[c]+"=="):2==i&&(h=s[a]<<8|s[a+1],o=(64512&h)>>10,c=(1008&h)>>4,u=(15&h)<<2,t+=n[o]+n[c]+n[u]+"="),t}var l;!function(e){e.PNNetworkIssuesCategory="PNNetworkIssuesCategory",e.PNTimeoutCategory="PNTimeoutCategory",e.PNCancelledCategory="PNCancelledCategory",e.PNBadRequestCategory="PNBadRequestCategory",e.PNAccessDeniedCategory="PNAccessDeniedCategory",e.PNValidationErrorCategory="PNValidationErrorCategory",e.PNAcknowledgmentCategory="PNAcknowledgmentCategory",e.PNMalformedResponseCategory="PNMalformedResponseCategory",e.PNUnknownCategory="PNUnknownCategory",e.PNNetworkUpCategory="PNNetworkUpCategory",e.PNNetworkDownCategory="PNNetworkDownCategory",e.PNReconnectedCategory="PNReconnectedCategory",e.PNConnectedCategory="PNConnectedCategory",e.PNRequestMessageCountExceededCategory="PNRequestMessageCountExceededCategory",e.PNDisconnectedCategory="PNDisconnectedCategory",e.PNConnectionErrorCategory="PNConnectionErrorCategory",e.PNDisconnectedUnexpectedlyCategory="PNDisconnectedUnexpectedlyCategory"}(l||(l={}));var h=l;class d extends Error{constructor(e,t){super(e),this.status=t,this.name="PubNubError",this.message=e,Object.setPrototypeOf(this,new.target.prototype)}}function p(e,t){var n;return null!==(n=e.statusCode)&&void 0!==n||(e.statusCode=0),Object.assign(Object.assign({},e),{statusCode:e.statusCode,category:t,error:!0})}function g(e,t){return p(Object.assign({message:e},{}),h.PNValidationErrorCategory)}function y(e,t){return p(Object.assign(Object.assign({message:"Unable to deserialize service response"},void 0!==e?{responseText:e}:{}),void 0!==t?{statusCode:t}:{}),h.PNMalformedResponseCategory)}var f,m,b,v,w,S=S||function(e){var t={},n=t.lib={},s=function(){},r=n.Base={extend:function(e){s.prototype=this;var t=new s;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)}},i=n.WordArray=r.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||o).stringify(this)},concat:function(e){var t=this.words,n=e.words,s=this.sigBytes;if(e=e.sigBytes,this.clamp(),s%4)for(var r=0;r>>2]|=(n[r>>>2]>>>24-r%4*8&255)<<24-(s+r)%4*8;else if(65535>>2]=n[r>>>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=r.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n=[],s=0;s>>2]>>>24-s%4*8&255;n.push((r>>>4).toString(16)),n.push((15&r).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,n=[],s=0;s>>3]|=parseInt(e.substr(s,2),16)<<24-s%8*4;return new i.init(n,t/2)}},c=a.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],s=0;s>>2]>>>24-s%4*8&255));return n.join("")},parse:function(e){for(var t=e.length,n=[],s=0;s>>2]|=(255&e.charCodeAt(s))<<24-s%4*8;return new i.init(n,t)}},u=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)))}},l=n.BufferedBlockAlgorithm=r.extend({reset:function(){this._data=new i.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=u.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,s=n.words,r=n.sigBytes,a=this.blockSize,o=r/(4*a);if(t=(o=t?e.ceil(o):e.max((0|o)-this._minBufferSize,0))*a,r=e.min(4*t,r),t){for(var c=0;cu;){var l;e:{l=c;for(var h=e.sqrt(l),d=2;d<=h;d++)if(!(l%d)){l=!1;break e}l=!0}l&&(8>u&&(i[u]=o(e.pow(c,.5))),a[u]=o(e.pow(c,1/3)),u++),c++}var p=[];r=r.SHA256=s.extend({_doReset:function(){this._hash=new n.init(i.slice(0))},_doProcessBlock:function(e,t){for(var n=this._hash.words,s=n[0],r=n[1],i=n[2],o=n[3],c=n[4],u=n[5],l=n[6],h=n[7],d=0;64>d;d++){if(16>d)p[d]=0|e[t+d];else{var g=p[d-15],y=p[d-2];p[d]=((g<<25|g>>>7)^(g<<14|g>>>18)^g>>>3)+p[d-7]+((y<<15|y>>>17)^(y<<13|y>>>19)^y>>>10)+p[d-16]}g=h+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&u^~c&l)+a[d]+p[d],y=((s<<30|s>>>2)^(s<<19|s>>>13)^(s<<10|s>>>22))+(s&r^s&i^r&i),h=l,l=u,u=c,c=o+g|0,o=i,i=r,r=s,s=g+y|0}n[0]=n[0]+s|0,n[1]=n[1]+r|0,n[2]=n[2]+i|0,n[3]=n[3]+o|0,n[4]=n[4]+c|0,n[5]=n[5]+u|0,n[6]=n[6]+l|0,n[7]=n[7]+h|0},_doFinalize:function(){var t=this._data,n=t.words,s=8*this._nDataBytes,r=8*t.sigBytes;return n[r>>>5]|=128<<24-r%32,n[14+(r+64>>>9<<4)]=e.floor(s/4294967296),n[15+(r+64>>>9<<4)]=s,t.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var e=s.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=s._createHelper(r),t.HmacSHA256=s._createHmacHelper(r)}(Math),m=(f=S).enc.Utf8,f.algo.HMAC=f.lib.Base.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=m.parse(t));var n=e.blockSize,s=4*n;t.sigBytes>s&&(t=e.finalize(t)),t.clamp();for(var r=this._oKey=t.clone(),i=this._iKey=t.clone(),a=r.words,o=i.words,c=0;c>>2]>>>24-r%4*8&255)<<16|(t[r+1>>>2]>>>24-(r+1)%4*8&255)<<8|t[r+2>>>2]>>>24-(r+2)%4*8&255,a=0;4>a&&r+.75*a>>6*(3-a)&63));if(t=s.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var t=e.length,n=this._map;(s=n.charAt(64))&&-1!=(s=e.indexOf(s))&&(t=s);for(var s=[],r=0,i=0;i>>6-i%4*2;s[r>>>2]|=(a|o)<<24-r%4*8,r++}return v.create(s,r)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},function(e){function t(e,t,n,s,r,i,a){return((e=e+(t&n|~t&s)+r+a)<>>32-i)+t}function n(e,t,n,s,r,i,a){return((e=e+(t&s|n&~s)+r+a)<>>32-i)+t}function s(e,t,n,s,r,i,a){return((e=e+(t^n^s)+r+a)<>>32-i)+t}function r(e,t,n,s,r,i,a){return((e=e+(n^(t|~s))+r+a)<>>32-i)+t}for(var i=S,a=(c=i.lib).WordArray,o=c.Hasher,c=i.algo,u=[],l=0;64>l;l++)u[l]=4294967296*e.abs(e.sin(l+1))|0;c=c.MD5=o.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,i){for(var a=0;16>a;a++){var o=e[c=i+a];e[c]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8)}a=this._hash.words;var c=e[i+0],l=(o=e[i+1],e[i+2]),h=e[i+3],d=e[i+4],p=e[i+5],g=e[i+6],y=e[i+7],f=e[i+8],m=e[i+9],b=e[i+10],v=e[i+11],w=e[i+12],S=e[i+13],E=e[i+14],O=e[i+15],k=t(k=a[0],P=a[1],N=a[2],C=a[3],c,7,u[0]),C=t(C,k,P,N,o,12,u[1]),N=t(N,C,k,P,l,17,u[2]),P=t(P,N,C,k,h,22,u[3]);k=t(k,P,N,C,d,7,u[4]),C=t(C,k,P,N,p,12,u[5]),N=t(N,C,k,P,g,17,u[6]),P=t(P,N,C,k,y,22,u[7]),k=t(k,P,N,C,f,7,u[8]),C=t(C,k,P,N,m,12,u[9]),N=t(N,C,k,P,b,17,u[10]),P=t(P,N,C,k,v,22,u[11]),k=t(k,P,N,C,w,7,u[12]),C=t(C,k,P,N,S,12,u[13]),N=t(N,C,k,P,E,17,u[14]),k=n(k,P=t(P,N,C,k,O,22,u[15]),N,C,o,5,u[16]),C=n(C,k,P,N,g,9,u[17]),N=n(N,C,k,P,v,14,u[18]),P=n(P,N,C,k,c,20,u[19]),k=n(k,P,N,C,p,5,u[20]),C=n(C,k,P,N,b,9,u[21]),N=n(N,C,k,P,O,14,u[22]),P=n(P,N,C,k,d,20,u[23]),k=n(k,P,N,C,m,5,u[24]),C=n(C,k,P,N,E,9,u[25]),N=n(N,C,k,P,h,14,u[26]),P=n(P,N,C,k,f,20,u[27]),k=n(k,P,N,C,S,5,u[28]),C=n(C,k,P,N,l,9,u[29]),N=n(N,C,k,P,y,14,u[30]),k=s(k,P=n(P,N,C,k,w,20,u[31]),N,C,p,4,u[32]),C=s(C,k,P,N,f,11,u[33]),N=s(N,C,k,P,v,16,u[34]),P=s(P,N,C,k,E,23,u[35]),k=s(k,P,N,C,o,4,u[36]),C=s(C,k,P,N,d,11,u[37]),N=s(N,C,k,P,y,16,u[38]),P=s(P,N,C,k,b,23,u[39]),k=s(k,P,N,C,S,4,u[40]),C=s(C,k,P,N,c,11,u[41]),N=s(N,C,k,P,h,16,u[42]),P=s(P,N,C,k,g,23,u[43]),k=s(k,P,N,C,m,4,u[44]),C=s(C,k,P,N,w,11,u[45]),N=s(N,C,k,P,O,16,u[46]),k=r(k,P=s(P,N,C,k,l,23,u[47]),N,C,c,6,u[48]),C=r(C,k,P,N,y,10,u[49]),N=r(N,C,k,P,E,15,u[50]),P=r(P,N,C,k,p,21,u[51]),k=r(k,P,N,C,w,6,u[52]),C=r(C,k,P,N,h,10,u[53]),N=r(N,C,k,P,b,15,u[54]),P=r(P,N,C,k,o,21,u[55]),k=r(k,P,N,C,f,6,u[56]),C=r(C,k,P,N,O,10,u[57]),N=r(N,C,k,P,g,15,u[58]),P=r(P,N,C,k,S,21,u[59]),k=r(k,P,N,C,d,6,u[60]),C=r(C,k,P,N,v,10,u[61]),N=r(N,C,k,P,l,15,u[62]),P=r(P,N,C,k,m,21,u[63]);a[0]=a[0]+k|0,a[1]=a[1]+P|0,a[2]=a[2]+N|0,a[3]=a[3]+C|0},_doFinalize:function(){var t=this._data,n=t.words,s=8*this._nDataBytes,r=8*t.sigBytes;n[r>>>5]|=128<<24-r%32;var i=e.floor(s/4294967296);for(n[15+(r+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),n[14+(r+64>>>9<<4)]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),t.sigBytes=4*(n.length+1),this._process(),n=(t=this._hash).words,s=0;4>s;s++)r=n[s],n[s]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8);return t},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}}),i.MD5=o._createHelper(c),i.HmacMD5=o._createHmacHelper(c)}(Math),function(){var e,t=S,n=(e=t.lib).Base,s=e.WordArray,r=(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=(o=this.cfg).hasher.create(),r=s.create(),i=r.words,a=o.keySize,o=o.iterations;i.length>>2]}},e.BlockCipher=a.extend({cfg:a.cfg.extend({mode:o,padding:u}),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 l=e.CipherParams=t.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),h=(o=(d.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?n.create([1398893684,1701076831]).concat(e).concat(t):t).toString(r)},parse:function(e){var t=(e=r.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var s=n.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return l.create({ciphertext:e,salt:s})}},e.SerializableCipher=t.extend({cfg:t.extend({format:o}),encrypt:function(e,t,n,s){s=this.cfg.extend(s);var r=e.createEncryptor(n,s);return t=r.finalize(t),r=r.cfg,l.create({ciphertext:t,key:n,iv:r.iv,algorithm:e,mode:r.mode,padding:r.padding,blockSize:e.blockSize,formatter:s.format})},decrypt:function(e,t,n,s){return s=this.cfg.extend(s),t=this._parse(t,s.format),e.createDecryptor(n,s).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),d=(d.kdf={}).OpenSSL={execute:function(e,t,s,r){return r||(r=n.random(8)),e=i.create({keySize:t+s}).compute(e,r),s=n.create(e.words.slice(t),4*s),e.sigBytes=4*t,l.create({key:e,iv:s,salt:r})}},p=e.PasswordBasedCipher=h.extend({cfg:h.cfg.extend({kdf:d}),encrypt:function(e,t,n,s){return n=(s=this.cfg.extend(s)).kdf.execute(n,e.keySize,e.ivSize),s.iv=n.iv,(e=h.encrypt.call(this,e,t,n.key,s)).mixIn(n),e},decrypt:function(e,t,n,s){return s=this.cfg.extend(s),t=this._parse(t,s.format),n=s.kdf.execute(n,e.keySize,e.ivSize,t.salt),s.iv=n.iv,h.decrypt.call(this,e,t,n.key,s)}})}(),function(){for(var e=S,t=e.lib.BlockCipher,n=e.algo,s=[],r=[],i=[],a=[],o=[],c=[],u=[],l=[],h=[],d=[],p=[],g=0;256>g;g++)p[g]=128>g?g<<1:g<<1^283;var y=0,f=0;for(g=0;256>g;g++){var m=(m=f^f<<1^f<<2^f<<3^f<<4)>>>8^255&m^99;s[y]=m,r[m]=y;var b=p[y],v=p[b],w=p[v],E=257*p[m]^16843008*m;i[y]=E<<24|E>>>8,a[y]=E<<16|E>>>16,o[y]=E<<8|E>>>24,c[y]=E,E=16843009*w^65537*v^257*b^16843008*y,u[m]=E<<24|E>>>8,l[m]=E<<16|E>>>16,h[m]=E<<8|E>>>24,d[m]=E,y?(y=b^p[p[p[w^b]]],f^=p[p[f]]):y=f=1}var O=[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),r=this._keySchedule=[],i=0;i>>24]<<24|s[a>>>16&255]<<16|s[a>>>8&255]<<8|s[255&a]):(a=s[(a=a<<8|a>>>24)>>>24]<<24|s[a>>>16&255]<<16|s[a>>>8&255]<<8|s[255&a],a^=O[i/t|0]<<24),r[i]=r[i-t]^a}for(e=this._invKeySchedule=[],t=0;tt||4>=i?a:u[s[a>>>24]]^l[s[a>>>16&255]]^h[s[a>>>8&255]]^d[s[255&a]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,i,a,o,c,s)},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,u,l,h,d,r),n=e[t+1],e[t+1]=e[t+3],e[t+3]=n},_doCryptBlock:function(e,t,n,s,r,i,a,o){for(var c=this._nRounds,u=e[t]^n[0],l=e[t+1]^n[1],h=e[t+2]^n[2],d=e[t+3]^n[3],p=4,g=1;g>>24]^r[l>>>16&255]^i[h>>>8&255]^a[255&d]^n[p++],f=s[l>>>24]^r[h>>>16&255]^i[d>>>8&255]^a[255&u]^n[p++],m=s[h>>>24]^r[d>>>16&255]^i[u>>>8&255]^a[255&l]^n[p++];d=s[d>>>24]^r[u>>>16&255]^i[l>>>8&255]^a[255&h]^n[p++],u=y,l=f,h=m}y=(o[u>>>24]<<24|o[l>>>16&255]<<16|o[h>>>8&255]<<8|o[255&d])^n[p++],f=(o[l>>>24]<<24|o[h>>>16&255]<<16|o[d>>>8&255]<<8|o[255&u])^n[p++],m=(o[h>>>24]<<24|o[d>>>16&255]<<16|o[u>>>8&255]<<8|o[255&l])^n[p++],d=(o[d>>>24]<<24|o[u>>>16&255]<<16|o[l>>>8&255]<<8|o[255&h])^n[p++],e[t]=y,e[t+1]=f,e[t+2]=m,e[t+3]=d},keySize:8});e.AES=t._createHelper(n)}(),S.mode.ECB=((w=S.lib.BlockCipherMode.extend()).Encryptor=w.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),w.Decryptor=w.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),w);var E=t(S);class O{constructor({cipherKey:e}){this.cipherKey=e,this.CryptoJS=E,this.encryptedKey=this.CryptoJS.SHA256(e)}encrypt(e){if(0===("string"==typeof e?e:O.decoder.decode(e)).length)throw new Error("encryption error. empty content");const t=this.getIv();return{metadata:t,data:c(this.CryptoJS.AES.encrypt(e,this.encryptedKey,{iv:this.bufferToWordArray(t),mode:this.CryptoJS.mode.CBC}).ciphertext.toString(this.CryptoJS.enc.Base64))}}encryptFileData(e){return i(this,void 0,void 0,(function*(){const t=yield this.getKey(),n=this.getIv();return{data:yield crypto.subtle.encrypt({name:this.algo,iv:n},t,e),metadata:n}}))}decrypt(e){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=this.bufferToWordArray(new Uint8ClampedArray(e.metadata)),n=this.bufferToWordArray(new Uint8ClampedArray(e.data));return O.encoder.encode(this.CryptoJS.AES.decrypt({ciphertext:n},this.encryptedKey,{iv:t,mode:this.CryptoJS.mode.CBC}).toString(this.CryptoJS.enc.Utf8)).buffer}decryptFileData(e){return i(this,void 0,void 0,(function*(){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=yield this.getKey();return crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)}))}get identifier(){return"ACRH"}get algo(){return"AES-CBC"}getIv(){return crypto.getRandomValues(new Uint8Array(O.BLOCK_SIZE))}getKey(){return i(this,void 0,void 0,(function*(){const e=O.encoder.encode(this.cipherKey),t=yield crypto.subtle.digest("SHA-256",e.buffer);return crypto.subtle.importKey("raw",t,this.algo,!0,["encrypt","decrypt"])}))}bufferToWordArray(e){const t=[];let n;for(n=0;ne.toString(16).padStart(2,"0"))).join(""),s=N.encoder.encode(n.slice(0,32)).buffer;return crypto.subtle.importKey("raw",s,"AES-CBC",!0,["encrypt","decrypt"])}))}concatArrayBuffer(e,t){const n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}}N.IV_LENGTH=16,N.encoder=new TextEncoder,N.decoder=new TextDecoder;class P{constructor(e){this.config=e,this.cryptor=new C(Object.assign({},e)),this.fileCryptor=new N}encrypt(e){const t="string"==typeof e?e:P.decoder.decode(e);return{data:this.cryptor.encrypt(t),metadata:null}}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var n;if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.encryptFile(null===(n=this.config)||void 0===n?void 0:n.cipherKey,e,t)}))}decrypt(e){const t="string"==typeof e.data?e.data:u(e.data);return this.cryptor.decrypt(t)}decryptFile(e,t){return i(this,void 0,void 0,(function*(){if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.decryptFile(this.config.cipherKey,e,t)}))}get identifier(){return""}}P.encoder=new TextEncoder,P.decoder=new TextDecoder;class M extends a{static legacyCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new M({default:new P(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t})),cryptors:[new O({cipherKey:e.cipherKey})]})}static aesCbcCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new M({default:new O({cipherKey:e.cipherKey}),cryptors:[new P(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t}))]})}static withDefaultCryptor(e){return new this({default:e})}encrypt(e){const t=e instanceof ArrayBuffer&&this.defaultCryptor.identifier===M.LEGACY_IDENTIFIER?this.defaultCryptor.encrypt(M.decoder.decode(e)):this.defaultCryptor.encrypt(e);if(!t.metadata)return t.data;if("string"==typeof t.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");const n=this.getHeaderData(t);return this.concatArrayBuffer(n,t.data)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){if(this.defaultCryptor.identifier===_.LEGACY_IDENTIFIER)return this.defaultCryptor.encryptFile(e,t);const n=yield this.getFileData(e),s=yield this.defaultCryptor.encryptFileData(n);if("string"==typeof s.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");return t.create({name:e.name,mimeType:"application/octet-stream",data:this.concatArrayBuffer(this.getHeaderData(s),s.data)})}))}decrypt(e){const t="string"==typeof e?c(e):e,n=_.tryParse(t),s=this.getCryptor(n),r=n.length>0?t.slice(n.length-n.metadataLength,n.length):null;if(t.slice(n.length).byteLength<=0)throw new Error("Decryption error: empty content");return s.decrypt({data:t.slice(n.length),metadata:r})}decryptFile(e,t){return i(this,void 0,void 0,(function*(){const n=yield e.data.arrayBuffer(),s=_.tryParse(n),r=this.getCryptor(s);if((null==r?void 0:r.identifier)===_.LEGACY_IDENTIFIER)return r.decryptFile(e,t);const i=(yield this.getFileData(n)).slice(s.length-s.metadataLength,s.length);return t.create({name:e.name,data:yield this.defaultCryptor.decryptFileData({data:n.slice(s.length),metadata:i})})}))}getCryptorFromId(e){const t=this.getAllCryptors().find((t=>e===t.identifier));if(t)return t;throw Error("Unknown cryptor error")}getCryptor(e){if("string"==typeof e){const t=this.getAllCryptors().find((t=>t.identifier===e));if(t)return t;throw new Error("Unknown cryptor error")}if(e instanceof A)return this.getCryptorFromId(e.identifier)}getHeaderData(e){if(!e.metadata)return;const t=_.from(this.defaultCryptor.identifier,e.metadata),n=new Uint8Array(t.length);let s=0;return n.set(t.data,s),s+=t.length-e.metadata.byteLength,n.set(new Uint8Array(e.metadata),s),n.buffer}concatArrayBuffer(e,t){const n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}getFileData(e){return i(this,void 0,void 0,(function*(){if(e instanceof ArrayBuffer)return e;if(e instanceof o)return e.toArrayBuffer();throw new Error("Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob")}))}}M.LEGACY_IDENTIFIER="";class _{static from(e,t){if(e!==_.LEGACY_IDENTIFIER)return new A(e,t.byteLength)}static tryParse(e){const t=new Uint8Array(e);let n,s,r=null;if(t.byteLength>=4&&(n=t.slice(0,4),this.decoder.decode(n)!==_.SENTINEL))return M.LEGACY_IDENTIFIER;if(!(t.byteLength>=5))throw new Error("Decryption error: invalid header version");if(r=t[4],r>_.MAX_VERSION)throw new Error("Decryption error: Unknown cryptor error");let i=5+_.IDENTIFIER_LENGTH;if(!(t.byteLength>=i))throw new Error("Decryption error: invalid crypto identifier");s=t.slice(5,i);let a=null;if(!(t.byteLength>=i+1))throw new Error("Decryption error: invalid metadata length");return a=t[i],i+=1,255===a&&t.byteLength>=i+2&&(a=new Uint16Array(t.slice(i,i+2)).reduce(((e,t)=>(e<<8)+t),0)),new A(this.decoder.decode(s),a)}}_.SENTINEL="PNED",_.LEGACY_IDENTIFIER="",_.IDENTIFIER_LENGTH=4,_.VERSION=1,_.MAX_VERSION=1,_.decoder=new TextDecoder;class A{constructor(e,t){this._identifier=e,this._metadataLength=t}get identifier(){return this._identifier}set identifier(e){this._identifier=e}get metadataLength(){return this._metadataLength}set metadataLength(e){this._metadataLength=e}get version(){return _.VERSION}get length(){return _.SENTINEL.length+1+_.IDENTIFIER_LENGTH+(this.metadataLength<255?1:3)+this.metadataLength}get data(){let e=0;const t=new Uint8Array(this.length),n=new TextEncoder;t.set(n.encode(_.SENTINEL)),e+=_.SENTINEL.length,t[e]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e);const s=this.metadataLength;return e+=_.IDENTIFIER_LENGTH,s<255?t[e]=s:t.set([255,s>>8,255&s],e),t}}A.IDENTIFIER_LENGTH=4,A.SENTINEL="PNED";class j extends Error{static create(e,t){return e instanceof Error?j.createFromError(e):j.createFromServiceResponse(e,t)}static createFromError(e){let t=h.PNUnknownCategory,n="Unknown error",s="Error";if(!e)return new j(n,t,0);if(e instanceof j)return e;if(e instanceof Error&&(n=e.message,s=e.name),"AbortError"===s||-1!==n.indexOf("Aborted"))t=h.PNCancelledCategory,n="Request cancelled";else if(-1!==n.toLowerCase().indexOf("timeout"))t=h.PNTimeoutCategory,n="Request timeout";else if(-1!==n.toLowerCase().indexOf("network"))t=h.PNNetworkIssuesCategory,n="Network issues";else if("TypeError"===s)t=-1!==n.indexOf("Load failed")||-1!=n.indexOf("Failed to fetch")?h.PNNetworkIssuesCategory:h.PNBadRequestCategory;else if("FetchError"===s){const s=e.code;["ECONNREFUSED","ENETUNREACH","ENOTFOUND","ECONNRESET","EAI_AGAIN"].includes(s)&&(t=h.PNNetworkIssuesCategory),"ECONNREFUSED"===s?n="Connection refused":"ENETUNREACH"===s?n="Network not reachable":"ENOTFOUND"===s?n="Server not found":"ECONNRESET"===s?n="Connection reset by peer":"EAI_AGAIN"===s?n="Name resolution error":"ETIMEDOUT"===s?(t=h.PNTimeoutCategory,n="Request timeout"):n=`Unknown system error: ${e}`}else"Request timeout"===n&&(t=h.PNTimeoutCategory);return new j(n,t,0,e)}static createFromServiceResponse(e,t){let n,s=h.PNUnknownCategory,r="Unknown error",{status:i}=e;if(null!=t||(t=e.body),402===i?r="Not available for used key set. Contact support@pubnub.com":400===i?(s=h.PNBadRequestCategory,r="Bad request"):403===i&&(s=h.PNAccessDeniedCategory,r="Access denied"),t&&t.byteLength>0){const s=(new TextDecoder).decode(t);if(-1!==e.headers["content-type"].indexOf("text/javascript")||-1!==e.headers["content-type"].indexOf("application/json"))try{const e=JSON.parse(s);"object"==typeof e&&(Array.isArray(e)?"number"==typeof e[0]&&0===e[0]&&e.length>1&&"string"==typeof e[1]&&(n=e[1]):("error"in e&&(1===e.error||!0===e.error)&&"status"in e&&"number"==typeof e.status&&"message"in e&&"service"in e?(n=e,i=e.status):n=e,"error"in e&&e.error instanceof Error&&(n=e.error)))}catch(e){n=s}else if(-1!==e.headers["content-type"].indexOf("xml")){const e=/(.*)<\/Message>/gi.exec(s);r=e?`Upload to bucket failed: ${e[1]}`:"Upload to bucket failed."}else n=s}return new j(r,s,i,n)}constructor(e,t,n,s){super(e),this.category=t,this.statusCode=n,this.errorData=s,this.name="PubNubAPIError"}toStatus(e){return{error:!0,category:this.category,operation:e,statusCode:this.statusCode,errorData:this.errorData}}toPubNubError(e,t){return new d(null!=t?t:this.message,this.toStatus(e))}}class I{constructor(e){this.configuration=e,this.subscriptionWorkerReady=!1,this.workerEventsQueue=[],this.callbacks=new Map,this.setupSubscriptionWorker()}makeSendable(e){if(!e.path.startsWith("/v2/subscribe")&&!e.path.endsWith("/heartbeat")&&!e.path.endsWith("/leave"))return this.configuration.transport.makeSendable(e);let t;const n={type:"send-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,request:e};return e.cancellable&&(t={abort:()=>{const t={type:"cancel-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,identifier:e.identifier};this.scheduleEventPost(t)}}),[new Promise(((t,s)=>{this.callbacks.set(e.identifier,{resolve:t,reject:s}),this.scheduleEventPost(n)})),t]}request(e){return e}scheduleEventPost(e,t=!1){const n=this.sharedSubscriptionWorker;n?n.port.postMessage(e):t?this.workerEventsQueue.splice(0,0,e):this.workerEventsQueue.push(e)}flushScheduledEvents(){const e=this.sharedSubscriptionWorker;if(!e||0===this.workerEventsQueue.length)return;const t=[];for(let e=0;e!t.includes(e))),this.workerEventsQueue.forEach((t=>e.port.postMessage(t))),this.workerEventsQueue=[]}get sharedSubscriptionWorker(){return this.subscriptionWorkerReady?this.subscriptionWorker:null}setupSubscriptionWorker(){"undefined"!=typeof SharedWorker&&(this.subscriptionWorker=new SharedWorker(this.configuration.workerUrl,`/pubnub-${this.configuration.sdkVersion}`),this.subscriptionWorker.port.start(),this.scheduleEventPost({type:"client-register",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,heartbeatInterval:this.configuration.heartbeatInterval,logVerbosity:this.configuration.logVerbosity,workerLogVerbosity:this.configuration.workerLogVerbosity},!0),this.subscriptionWorker.port.onmessage=e=>this.handleWorkerEvent(e))}handleWorkerEvent(e){const{data:t}=e;if("shared-worker-ping"===t.type||"shared-worker-connected"===t.type||"shared-worker-console-log"===t.type||"shared-worker-console-dir"===t.type||t.clientIdentifier===this.configuration.clientIdentifier)if("shared-worker-connected"===t.type)this.subscriptionWorkerReady=!0,this.flushScheduledEvents();else if("shared-worker-console-log"===t.type)console.log(`[SharedWorker] ${t.message}`);else if("shared-worker-console-dir"===t.type)t.message&&console.log(`[SharedWorker] ${t.message}`),console.dir(t.data,{depth:10});else if("shared-worker-ping"===t.type){const{logVerbosity:e,subscriptionKey:t,clientIdentifier:n}=this.configuration;this.scheduleEventPost({type:"client-pong",subscriptionKey:t,clientIdentifier:n,logVerbosity:e})}else if("request-progress-start"===t.type||"request-progress-end"===t.type)this.logRequestProgress(t);else if("request-process-success"===t.type||"request-process-error"===t.type){const{resolve:e,reject:n}=this.callbacks.get(t.identifier);if("request-process-success"===t.type)e({status:t.response.status,url:t.url,headers:t.response.headers,body:t.response.body});else{let e=h.PNUnknownCategory,s="Unknown error";if(t.error)"NETWORK_ISSUE"===t.error.type?e=h.PNNetworkIssuesCategory:"TIMEOUT"===t.error.type?e=h.PNTimeoutCategory:"ABORTED"===t.error.type&&(e=h.PNCancelledCategory),s=`${t.error.message} (${t.identifier})`;else if(t.response)return n(j.create({url:t.url,headers:t.response.headers,body:t.response.body,status:t.response.status},t.response.body));n(new j(s,e,0,new Error(s)))}}}logRequestProgress(e){var t,n;"request-progress-start"===e.type?(console.log("<<<<<"),console.log(`[${e.timestamp}] ${e.url}\n${JSON.stringify(null!==(t=e.query)&&void 0!==t?t:{})}`),console.log("-----")):(console.log(">>>>>>"),console.log(`[${e.timestamp} / ${e.duration}] ${e.url}\n${JSON.stringify(null!==(n=e.query)&&void 0!==n?n:{})}\n${e.response}`),console.log("-----"))}}function F(e){const t=e=>"object"==typeof e&&null!==e&&e.constructor===Object,n=e=>"number"==typeof e&&isFinite(e);if(!t(e))return e;const s={};return Object.keys(e).forEach((r=>{const i=(e=>"string"==typeof e||e instanceof String)(r);let a=r;const o=e[r];if(i&&r.indexOf(",")>=0){a=r.split(",").map(Number).reduce(((e,t)=>e+String.fromCharCode(t)),"")}else(n(r)||i&&!isNaN(Number(r)))&&(a=String.fromCharCode(n(r)?r:parseInt(r,10)));s[a]=t(o)?F(o):o})),s}const T=e=>{var t,n,s,r;return e.subscriptionWorkerUrl&&"undefined"==typeof SharedWorker&&(e.subscriptionWorkerUrl=null),Object.assign(Object.assign({},(e=>{var t,n,s,r,i,a,o,c,u,l,h,p,g,y,f;const m=Object.assign({},e);if(null!==(t=m.logVerbosity)&&void 0!==t||(m.logVerbosity=!1),null!==(n=m.ssl)&&void 0!==n||(m.ssl=!0),null!==(s=m.transactionalRequestTimeout)&&void 0!==s||(m.transactionalRequestTimeout=15),null!==(r=m.subscribeRequestTimeout)&&void 0!==r||(m.subscribeRequestTimeout=310),null!==(i=m.fileRequestTimeout)&&void 0!==i||(m.fileRequestTimeout=300),null!==(a=m.restore)&&void 0!==a||(m.restore=!1),null!==(o=m.useInstanceId)&&void 0!==o||(m.useInstanceId=!1),null!==(c=m.suppressLeaveEvents)&&void 0!==c||(m.suppressLeaveEvents=!1),null!==(u=m.requestMessageCountThreshold)&&void 0!==u||(m.requestMessageCountThreshold=100),null!==(l=m.autoNetworkDetection)&&void 0!==l||(m.autoNetworkDetection=!1),null!==(h=m.enableEventEngine)&&void 0!==h||(m.enableEventEngine=!1),null!==(p=m.maintainPresenceState)&&void 0!==p||(m.maintainPresenceState=!0),null!==(g=m.keepAlive)&&void 0!==g||(m.keepAlive=!1),m.userId&&m.uuid)throw new d("PubNub client configuration error: use only 'userId'");if(null!==(y=m.userId)&&void 0!==y||(m.userId=m.uuid),!m.userId)throw new d("PubNub client configuration error: 'userId' not set");if(0===(null===(f=m.userId)||void 0===f?void 0:f.trim().length))throw new d("PubNub client configuration error: 'userId' is empty");m.origin||(m.origin=Array.from({length:20},((e,t)=>`ps${t+1}.pndsn.com`)));const b={subscribeKey:m.subscribeKey,publishKey:m.publishKey,secretKey:m.secretKey};void 0!==m.presenceTimeout&&m.presenceTimeout<20&&(m.presenceTimeout=20,console.log("WARNING: Presence timeout is less than the minimum. Using minimum value: ",20)),void 0!==m.presenceTimeout?m.heartbeatInterval=m.presenceTimeout/2-1:m.presenceTimeout=300;let v=!1,w=!0,S=5,E=!1,O=100,k=!0;return void 0!==m.dedupeOnSubscribe&&"boolean"==typeof m.dedupeOnSubscribe&&(E=m.dedupeOnSubscribe),void 0!==m.maximumCacheSize&&"number"==typeof m.maximumCacheSize&&(O=m.maximumCacheSize),void 0!==m.useRequestId&&"boolean"==typeof m.useRequestId&&(k=m.useRequestId),void 0!==m.announceSuccessfulHeartbeats&&"boolean"==typeof m.announceSuccessfulHeartbeats&&(v=m.announceSuccessfulHeartbeats),void 0!==m.announceFailedHeartbeats&&"boolean"==typeof m.announceFailedHeartbeats&&(w=m.announceFailedHeartbeats),void 0!==m.fileUploadPublishRetryLimit&&"number"==typeof m.fileUploadPublishRetryLimit&&(S=m.fileUploadPublishRetryLimit),Object.assign(Object.assign({},m),{keySet:b,dedupeOnSubscribe:E,maximumCacheSize:O,useRequestId:k,announceSuccessfulHeartbeats:v,announceFailedHeartbeats:w,fileUploadPublishRetryLimit:S})})(e)),{listenToBrowserNetworkEvents:null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t,subscriptionWorkerUrl:e.subscriptionWorkerUrl,subscriptionWorkerLogVerbosity:null!==(n=e.subscriptionWorkerLogVerbosity)&&void 0!==n&&n,transport:null!==(s=e.transport)&&void 0!==s?s:"fetch",keepAlive:null===(r=e.keepAlive)||void 0===r||r})};var R={exports:{}}; -/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */!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 s(){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 r(e,t){var s=n[t||"all"];return s&&s.test(e)||!1}s.isUUID=r,s.VERSION=t,e.uuid=s,e.isUUID=r}(t),null!==e&&(e.exports=t.uuid)}(R,R.exports);var U=t(R.exports),x={createUUID:()=>U.uuid?U.uuid():U()};const D=(e,t)=>{var n,s,r;null===(n=e.retryConfiguration)||void 0===n||n.validate(),null!==(s=e.useRandomIVs)&&void 0!==s||(e.useRandomIVs=true),e.origin=q(null!==(r=e.ssl)&&void 0!==r&&r,e.origin);const i=e.cryptoModule;i&&delete e.cryptoModule;const a=Object.assign(Object.assign({},e),{_pnsdkSuffix:{},_instanceId:`pn-${x.createUUID()}`,_cryptoModule:void 0,_cipherKey:void 0,_setupCryptoModule:t,get instanceId(){if(this.useInstanceId)return this._instanceId},getInstanceId(){if(this.useInstanceId)return this._instanceId},getUserId(){return this.userId},setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this.userId=e},getAuthKey(){return this.authKey},setAuthKey(e){this.authKey=e},getFilterExpression(){return this.filterExpression},setFilterExpression(e){this.filterExpression=e},getCipherKey(){return this._cipherKey},setCipherKey(t){this._cipherKey=t,t||!this._cryptoModule?t&&this._setupCryptoModule&&(this._cryptoModule=this._setupCryptoModule({cipherKey:t,useRandomIVs:e.useRandomIVs,customEncrypt:this.getCustomEncrypt(),customDecrypt:this.getCustomDecrypt()})):this._cryptoModule=void 0},getCryptoModule(){return this._cryptoModule},getUseRandomIVs:()=>e.useRandomIVs,setPresenceTimeout(e){this.heartbeatInterval=e/2-1,this.presenceTimeout=e},getPresenceTimeout(){return this.presenceTimeout},getHeartbeatInterval(){return this.heartbeatInterval},setHeartbeatInterval(e){this.heartbeatInterval=e},getTransactionTimeout(){return this.transactionalRequestTimeout},getSubscribeTimeout(){return this.subscribeRequestTimeout},getFileTimeout(){return this.fileRequestTimeout},get PubNubFile(){return e.PubNubFile},get version(){return"8.8.1"},getVersion(){return this.version},_addPnsdkSuffix(e,t){this._pnsdkSuffix[e]=`${t}`},_getPnsdkSuffix(e){const t=Object.values(this._pnsdkSuffix).join(e);return t.length>0?e+t:""},getUUID(){return this.getUserId()},setUUID(e){this.setUserId(e)},getCustomEncrypt:()=>e.customEncrypt,getCustomDecrypt:()=>e.customDecrypt});return e.cipherKey?a.setCipherKey(e.cipherKey):i&&(a._cryptoModule=i),a},q=(e,t)=>{const n=e?"https://":"http://";return"string"==typeof t?`${n}${t}`:`${n}${t[Math.floor(Math.random()*t.length)]}`};class G{constructor(e){this.cbor=e}setToken(e){e&&e.length>0?this.token=e:this.token=void 0}getToken(){return this.token}parseToken(e){const t=this.cbor.decodeToken(e);if(void 0!==t){const e=t.res.uuid?Object.keys(t.res.uuid):[],n=Object.keys(t.res.chan),s=Object.keys(t.res.grp),r=t.pat.uuid?Object.keys(t.pat.uuid):[],i=Object.keys(t.pat.chan),a=Object.keys(t.pat.grp),o={version:t.v,timestamp:t.t,ttl:t.ttl,authorized_uuid:t.uuid,signature:t.sig},c=e.length>0,u=n.length>0,l=s.length>0;if(c||u||l){if(o.resources={},c){const n=o.resources.uuids={};e.forEach((e=>n[e]=this.extractPermissions(t.res.uuid[e])))}if(u){const e=o.resources.channels={};n.forEach((n=>e[n]=this.extractPermissions(t.res.chan[n])))}if(l){const e=o.resources.groups={};s.forEach((n=>e[n]=this.extractPermissions(t.res.grp[n])))}}const h=r.length>0,d=i.length>0,p=a.length>0;if(h||d||p){if(o.patterns={},h){const e=o.patterns.uuids={};r.forEach((n=>e[n]=this.extractPermissions(t.pat.uuid[n])))}if(d){const e=o.patterns.channels={};i.forEach((n=>e[n]=this.extractPermissions(t.pat.chan[n])))}if(p){const e=o.patterns.groups={};a.forEach((n=>e[n]=this.extractPermissions(t.pat.grp[n])))}}return t.meta&&Object.keys(t.meta).length>0&&(o.meta=t.meta),o}}extractPermissions(e){const t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128&~e||(t.join=!0),64&~e||(t.update=!0),32&~e||(t.get=!0),8&~e||(t.delete=!0),4&~e||(t.manage=!0),2&~e||(t.write=!0),1&~e||(t.read=!0),t}}var K;!function(e){e.GET="GET",e.POST="POST",e.PATCH="PATCH",e.DELETE="DELETE",e.LOCAL="LOCAL"}(K||(K={}));const $=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),L=(e,t)=>{const n=e.map((e=>$(e)));return n.length?n.join(","):null!=t?t:""},B=(e,t)=>{const n=Object.fromEntries(t.map((e=>[e,!1])));return e.filter((e=>!(t.includes(e)&&!n[e])||(n[e]=!0,!1)))},H=(e,t)=>[...e].filter((n=>t.includes(n)&&e.indexOf(n)===e.lastIndexOf(n)&&t.indexOf(n)===t.lastIndexOf(n)));class V{constructor(e,t,n){this.publishKey=e,this.secretKey=t,this.hasher=n}signature(e){const t=e.path.startsWith("/publish")?K.GET:e.method;let n=`${t}\n${this.publishKey}\n${e.path}\n${this.queryParameters(e.queryParameters)}\n`;if(t===K.POST||t===K.PATCH){const t=e.body;let s;t&&t instanceof ArrayBuffer?s=V.textDecoder.decode(t):t&&"object"!=typeof t&&(s=t),s&&(n+=s)}return`v2.${this.hasher(n,this.secretKey)}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}queryParameters(e){return Object.keys(e).sort().map((t=>{const n=e[t];return Array.isArray(n)?n.sort().map((e=>`${t}=${$(e)}`)).join("&"):`${t}=${$(n)}`})).join("&")}}V.textDecoder=new TextDecoder("utf-8");class z{constructor(e){this.configuration=e;const{clientConfiguration:{keySet:t},shaHMAC:n}=e;t.secretKey&&n&&(this.signatureGenerator=new V(t.publishKey,t.secretKey,n))}makeSendable(e){return this.configuration.transport.makeSendable(this.request(e))}request(e){var t;const{clientConfiguration:n}=this.configuration;return(e=this.configuration.transport.request(e)).queryParameters||(e.queryParameters={}),n.useInstanceId&&(e.queryParameters.instanceid=n.getInstanceId()),e.queryParameters.uuid||(e.queryParameters.uuid=n.userId),n.useRequestId&&(e.queryParameters.requestid=e.identifier),e.queryParameters.pnsdk=this.generatePNSDK(),null!==(t=e.origin)&&void 0!==t||(e.origin=n.origin),this.authenticateRequest(e),this.signRequest(e),e}authenticateRequest(e){var t;if(e.path.startsWith("/v2/auth/")||e.path.startsWith("/v3/pam/")||e.path.startsWith("/time"))return;const{clientConfiguration:n,tokenManager:s}=this.configuration,r=null!==(t=s&&s.getToken())&&void 0!==t?t:n.authKey;r&&(e.queryParameters.auth=r)}signRequest(e){this.signatureGenerator&&!e.path.startsWith("/time")&&(e.queryParameters.timestamp=String(Math.floor((new Date).getTime()/1e3)),e.queryParameters.signature=this.signatureGenerator.signature(e))}generatePNSDK(){const{clientConfiguration:e}=this.configuration;if(e.sdkName)return e.sdkName;let t=`PubNub-JS-${e.sdkFamily}`;e.partnerId&&(t+=`-${e.partnerId}`),t+=`/${e.getVersion()}`;const n=e._getPnsdkSuffix(" ");return n.length>0&&(t+=n),t}}class W{constructor(e="fetch",t=!1,n=!1){if(this.transport=e,this.keepAlive=t,this.logVerbosity=n,"fetch"!==e||window&&window.fetch||(this.transport="xhr"),"fetch"===this.transport&&(W.originalFetch=fetch.bind(window),this.isFetchMonkeyPatched())){if(W.originalFetch=W.getOriginalFetch(),!n)return;console.warn("[PubNub] Native Web Fetch API 'fetch' function monkey patched."),this.isFetchMonkeyPatched(W.originalFetch)?console.warn("[PubNub] Unable receive native Web Fetch API. There can be issues with subscribe long-poll cancellation"):console.info("[PubNub] Use native Web Fetch API 'fetch' implementation from iframe as APM workaround.")}}makeSendable(e){const t=new AbortController,n={abortController:t,abort:e=>!t.signal.aborted&&t.abort(e)};return[this.webTransportRequestFromTransportRequest(e).then((t=>{const s=(new Date).getTime();return this.logRequestProcessProgress(t,e.body),this.sendRequest(t,n).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>{const n=e[1].byteLength>0?e[1]:void 0,{status:r,headers:i}=e[0],a={};i.forEach(((e,t)=>a[t]=e.toLowerCase()));const o={status:r,url:t.url,headers:a,body:n};if(r>=400)throw j.create(o);return this.logRequestProcessProgress(t,void 0,(new Date).getTime()-s,n),o})).catch((e=>{let t=e;if("string"==typeof e){const n=e.toLowerCase();n.includes("timeout")||!n.includes("cancel")?t=new Error(e):n.includes("cancel")&&(t=new DOMException("Aborted","AbortError"))}throw j.create(t)}))})),n]}request(e){return e}sendRequest(e,t){return i(this,void 0,void 0,(function*(){return"fetch"===this.transport?this.sendFetchRequest(e,t):this.sendXHRRequest(e,t)}))}sendFetchRequest(e,t){return i(this,void 0,void 0,(function*(){let n;const s=new Promise(((s,r)=>{n=setTimeout((()=>{clearTimeout(n),r(new Error("Request timeout")),t.abort("Cancel because of timeout")}),1e3*e.timeout)})),r=new Request(e.url,{method:e.method,headers:e.headers,redirect:"follow",body:e.body});return Promise.race([W.originalFetch(r,{signal:t.abortController.signal,credentials:"omit",cache:"no-cache"}).then((e=>(n&&clearTimeout(n),e))),s])}))}sendXHRRequest(e,t){return i(this,void 0,void 0,(function*(){return new Promise(((n,s)=>{var r;const i=new XMLHttpRequest;i.open(e.method,e.url,!0),i.responseType="arraybuffer",i.timeout=1e3*e.timeout,t.abortController.signal.onabort=()=>{i.readyState!=XMLHttpRequest.DONE&&i.readyState!=XMLHttpRequest.UNSENT&&i.abort()},Object.entries(null!==(r=e.headers)&&void 0!==r?r:{}).forEach((([e,t])=>i.setRequestHeader(e,t))),i.onabort=()=>s(new Error("Aborted")),i.ontimeout=()=>s(new Error("Request timeout")),i.onerror=()=>s(new Error("Request timeout")),i.onload=()=>{const e=new Headers;i.getAllResponseHeaders().split("\r\n").forEach((t=>{const[n,s]=t.split(": ");n.length>1&&s.length>1&&e.append(n,s)})),n(new Response(i.response,{status:i.status,headers:e,statusText:i.statusText}))},i.send(e.body)}))}))}webTransportRequestFromTransportRequest(e){return i(this,void 0,void 0,(function*(){let t,n=e.path;if(e.formData&&e.formData.length>0){e.queryParameters={};const n=e.body,s=new FormData;for(const{key:t,value:n}of e.formData)s.append(t,n);try{const e=yield n.toArrayBuffer();s.append("file",new Blob([e],{type:"application/octet-stream"}),n.name)}catch(e){try{const e=yield n.toFileUri();s.append("file",e,n.name)}catch(e){}}t=s}else e.body&&("string"==typeof e.body||e.body instanceof ArrayBuffer)&&(t=e.body);var s;return e.queryParameters&&0!==Object.keys(e.queryParameters).length&&(n=`${n}?${s=e.queryParameters,Object.keys(s).map((e=>{const t=s[e];return Array.isArray(t)?t.map((t=>`${e}=${$(t)}`)).join("&"):`${e}=${$(t)}`})).join("&")}`),{url:`${e.origin}${n}`,method:e.method,headers:e.headers,timeout:e.timeout,body:t}}))}logRequestProcessProgress(e,t,n,s){if(!this.logVerbosity)return;const{protocol:r,host:i,pathname:a,search:o}=new URL(e.url),c=(new Date).toISOString();if(n){let e=`[${c} / ${n}]\n${r}//${i}${a}\n${o}`;s&&(e+=`\n\n${W.decoder.decode(s)}`),console.log(">>>>>>"),console.log(e),console.log("-----")}else{let e=`[${c}]\n${r}//${i}${a}\n${o}`;t&&("string"==typeof t||t instanceof ArrayBuffer)&&(e+="string"==typeof t?`\n\n${t}`:`\n\n${W.decoder.decode(t)}`),console.log("<<<<<"),console.log(e),console.log("-----")}}isFetchMonkeyPatched(e){return!(null!=e?e:fetch).toString().includes("[native code]")&&"fetch"!==fetch.name}static getOriginalFetch(){let e=document.querySelector('iframe[name="pubnub-context-unpatched-fetch"]');return e||(e=document.createElement("iframe"),e.style.display="none",e.name="pubnub-context-unpatched-fetch",e.src="about:blank",document.body.appendChild(e)),e.contentWindow?e.contentWindow.fetch.bind(e.contentWindow):fetch}}W.decoder=new TextDecoder;class J{constructor(){this.listeners=[]}addListener(e){this.listeners.includes(e)||this.listeners.push(e)}removeListener(e){this.listeners=this.listeners.filter((t=>t!==e))}removeAllListeners(){this.listeners=[]}announceStatus(e){this.listeners.forEach((t=>{t.status&&t.status(e)}))}announcePresence(e){this.listeners.forEach((t=>{t.presence&&t.presence(e)}))}announceMessage(e){this.listeners.forEach((t=>{t.message&&t.message(e)}))}announceSignal(e){this.listeners.forEach((t=>{t.signal&&t.signal(e)}))}announceMessageAction(e){this.listeners.forEach((t=>{t.messageAction&&t.messageAction(e)}))}announceFile(e){this.listeners.forEach((t=>{t.file&&t.file(e)}))}announceObjects(e){this.listeners.forEach((t=>{t.objects&&t.objects(e)}))}announceNetworkUp(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkUpCategory})}))}announceNetworkDown(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkDownCategory})}))}announceUser(e){this.listeners.forEach((t=>{t.user&&t.user(e)}))}announceSpace(e){this.listeners.forEach((t=>{t.space&&t.space(e)}))}announceMembership(e){this.listeners.forEach((t=>{t.membership&&t.membership(e)}))}}class X{constructor(e){this.time=e}onReconnect(e){this.callback=e}startPolling(){this.timeTimer=setInterval((()=>this.callTime()),3e3)}stopPolling(){this.timeTimer&&clearInterval(this.timeTimer),this.timeTimer=null}callTime(){this.time((e=>{e.error||(this.stopPolling(),this.callback&&this.callback())}))}}class Q{constructor({maximumCacheSize:e}){this.maximumCacheSize=e,this.hashHistory=[]}getKey(e){var t;return`${e.timetoken}-${this.hashCode(JSON.stringify(null!==(t=e.message)&&void 0!==t?t:"")).toString()}`}isDuplicate(e){return this.hashHistory.includes(this.getKey(e))}addEntry(e){this.hashHistory.length>=this.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}clearHistory(){this.hashHistory=[]}hashCode(e){let t=0;if(0===e.length)return t;for(let n=0;n{this.pendingChannelSubscriptions.add(e),this.channels[e]={},r&&(this.presenceChannels[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannels[e]={})})),null==n||n.forEach((e=>{this.pendingChannelGroupSubscriptions.add(e),this.channelGroups[e]={},r&&(this.presenceChannelGroups[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannelGroups[e]={})})),this.subscriptionStatusAnnounced=!1,this.reconnect()}unsubscribe(e,t){let{channels:n,channelGroups:s}=e;const i=new Set,a=new Set;null==n||n.forEach((e=>{e in this.channels&&(delete this.channels[e],a.add(e),e in this.heartbeatChannels&&delete this.heartbeatChannels[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannels&&(delete this.presenceChannels[e],a.add(e))})),null==s||s.forEach((e=>{e in this.channelGroups&&(delete this.channelGroups[e],i.add(e),e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannelGroups&&(delete this.presenceChannelGroups[e],i.add(e))})),0===a.size&&0===i.size||(!1!==this.configuration.suppressLeaveEvents||t||(s=Array.from(i),n=Array.from(a),this.leaveCall({channels:n,channelGroups:s},(e=>{const{error:t}=e,i=r(e,["error"]);let a;t&&(e.errorData&&"object"==typeof e.errorData&&"message"in e.errorData&&"string"==typeof e.errorData.message?a=e.errorData.message:"message"in e&&"string"==typeof e.message&&(a=e.message)),this.listenerManager.announceStatus(Object.assign(Object.assign({},i),{error:null!=a&&a,affectedChannels:n,affectedChannelGroups:s,currentTimetoken:this.currentTimetoken,lastTimetoken:this.lastTimetoken}))}))),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(!0))}unsubscribeAll(e){this.unsubscribe({channels:this.subscribedChannels,channelGroups:this.subscribedChannelGroups},e)}startSubscribeLoop(){this.stopSubscribeLoop();const e=[...Object.keys(this.channelGroups)],t=[...Object.keys(this.channels)];Object.keys(this.presenceChannelGroups).forEach((t=>e.push(`${t}-pnpres`))),Object.keys(this.presenceChannels).forEach((e=>t.push(`${e}-pnpres`))),0===t.length&&0===e.length||this.subscribeCall({channels:t,channelGroups:e,state:this.presenceState,heartbeat:this.configuration.getPresenceTimeout(),timetoken:this.currentTimetoken,region:null!==this.region?this.region:void 0,filterExpression:this.configuration.filterExpression},((e,t)=>{this.processSubscribeResponse(e,t)}))}stopSubscribeLoop(){this._subscribeAbort&&(this._subscribeAbort(),this._subscribeAbort=null)}processSubscribeResponse(e,t){if(e.error){if("object"==typeof e.errorData&&"name"in e.errorData&&"AbortError"===e.errorData.name||e.category===h.PNCancelledCategory)return;if(e.category===h.PNTimeoutCategory)this.startSubscribeLoop();else if(e.category===h.PNNetworkIssuesCategory)this.disconnect(),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.listenerManager.announceNetworkDown()),this.reconnectionManager.onReconnect((()=>{this.configuration.autoNetworkDetection&&!this.isOnline&&(this.isOnline=!0,this.listenerManager.announceNetworkUp()),this.reconnect(),this.subscriptionStatusAnnounced=!0;const t={category:h.PNReconnectedCategory,operation:e.operation,lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.listenerManager.announceStatus(t)})),this.reconnectionManager.startPolling(),this.listenerManager.announceStatus(e);else if(e.category===h.PNBadRequestCategory||e.category==h.PNMalformedResponseCategory){const t=this.isOnline?h.PNDisconnectedUnexpectedlyCategory:e.category;this.isOnline=!1,this.disconnect(),this.listenerManager.announceStatus(Object.assign(Object.assign({},e),{category:t}))}else this.listenerManager.announceStatus(e);return}if(this.storedTimetoken?(this.currentTimetoken=this.storedTimetoken,this.storedTimetoken=null):(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=t.cursor.timetoken),!this.subscriptionStatusAnnounced){const t={category:h.PNConnectedCategory,operation:e.operation,affectedChannels:Array.from(this.pendingChannelSubscriptions),subscribedChannels:this.subscribedChannels,affectedChannelGroups:Array.from(this.pendingChannelGroupSubscriptions),lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.subscriptionStatusAnnounced=!0,this.listenerManager.announceStatus(t),this.pendingChannelGroupSubscriptions.clear(),this.pendingChannelSubscriptions.clear()}const{messages:n}=t,{requestMessageCountThreshold:s,dedupeOnSubscribe:r}=this.configuration;s&&n.length>=s&&this.listenerManager.announceStatus({category:h.PNRequestMessageCountExceededCategory,operation:e.operation});try{n.forEach((e=>{if(r&&"message"in e.data&&"timetoken"in e.data){if(this.dedupingManager.isDuplicate(e.data))return;this.dedupingManager.addEntry(e.data)}this.eventEmitter.emitEvent(e)}))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}this.region=t.cursor.region,this.startSubscribeLoop()}setState(e){const{state:t,channels:n,channelGroups:s}=e;null==n||n.forEach((e=>e in this.channels&&(this.presenceState[e]=t))),null==s||s.forEach((e=>e in this.channelGroups&&(this.presenceState[e]=t)))}changePresence(e){const{connected:t,channels:n,channelGroups:s}=e;t?(null==n||n.forEach((e=>this.heartbeatChannels[e]={})),null==s||s.forEach((e=>this.heartbeatChannelGroups[e]={}))):(null==n||n.forEach((e=>{e in this.heartbeatChannels&&delete this.heartbeatChannels[e]})),null==s||s.forEach((e=>{e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]})),!1===this.configuration.suppressLeaveEvents&&this.leaveCall({channels:n,channelGroups:s},(e=>this.listenerManager.announceStatus(e)))),this.reconnect()}startHeartbeatTimer(){this.stopHeartbeatTimer();const e=this.configuration.getHeartbeatInterval();e&&0!==e&&(this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>this.sendHeartbeat()),1e3*e))}stopHeartbeatTimer(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}sendHeartbeat(){const e=Object.keys(this.heartbeatChannelGroups),t=Object.keys(this.heartbeatChannels);0===t.length&&0===e.length||this.heartbeatCall({channels:t,channelGroups:e,heartbeat:this.configuration.getPresenceTimeout(),state:this.presenceState},(e=>{e.error&&this.configuration.announceFailedHeartbeats&&this.listenerManager.announceStatus(e),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.disconnect(),this.listenerManager.announceNetworkDown(),this.reconnect()),!e.error&&this.configuration.announceSuccessfulHeartbeats&&this.listenerManager.announceStatus(e)}))}}class Z{constructor(e,t,n){this._payload=e,this.setDefaultPayloadStructure(),this.title=t,this.body=n}get payload(){return this._payload}set title(e){this._title=e}set subtitle(e){this._subtitle=e}set body(e){this._body=e}set badge(e){this._badge=e}set sound(e){this._sound=e}setDefaultPayloadStructure(){}toObject(){return{}}}class ee extends Z{constructor(){super(...arguments),this._apnsPushType="apns",this._isSilent=!1}get payload(){return this._payload}set configurations(e){e&&e.length&&(this._configurations=e)}get notification(){return this.payload.aps}get title(){return this._title}set title(e){e&&e.length&&(this.payload.aps.alert.title=e,this._title=e)}get subtitle(){return this._subtitle}set subtitle(e){e&&e.length&&(this.payload.aps.alert.subtitle=e,this._subtitle=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.aps.alert.body=e,this._body=e)}get badge(){return this._badge}set badge(e){null!=e&&(this.payload.aps.badge=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.aps.sound=e,this._sound=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.aps={alert:{}}}toObject(){const e=Object.assign({},this.payload),{aps:t}=e;let{alert:n}=t;if(this._isSilent&&(t["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");const t=[];this._configurations.forEach((e=>{t.push(this.objectFromAPNS2Configuration(e))})),t.length&&(e.pn_push=t)}return n&&Object.keys(n).length||delete t.alert,this._isSilent&&(delete t.alert,delete t.badge,delete t.sound,n={}),this._isSilent||n&&Object.keys(n).length?e:null}objectFromAPNS2Configuration(e){if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");const{collapseId:t,expirationDate:n}=e,s={auth_method:"token",targets:e.targets.map((e=>this.objectFromAPNSTarget(e))),version:"v2"};return t&&t.length&&(s.collapse_id=t),n&&(s.expiration=n.toISOString()),s}objectFromAPNSTarget(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");const{topic:t,environment:n="development",excludedDevices:s=[]}=e,r={topic:t,environment:n};return s.length&&(r.excluded_devices=s),r}}class te extends Z{get payload(){return this._payload}get notification(){return this.payload.notification}get data(){return this.payload.data}get title(){return this._title}set title(e){e&&e.length&&(this.payload.notification.title=e,this._title=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.notification.body=e,this._body=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.notification.sound=e,this._sound=e)}get icon(){return this._icon}set icon(e){e&&e.length&&(this.payload.notification.icon=e,this._icon=e)}get tag(){return this._tag}set tag(e){e&&e.length&&(this.payload.notification.tag=e,this._tag=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.notification={},this.payload.data={}}toObject(){let e=Object.assign({},this.payload.data),t=null;const n={};if(Object.keys(this.payload).length>2){const t=r(this.payload,["notification","data"]);e=Object.assign(Object.assign({},e),t)}return this._isSilent?e.notification=this.payload.notification:t=this.payload.notification,Object.keys(e).length&&(n.data=e),t&&Object.keys(t).length&&(n.notification=t),Object.keys(n).length?n:null}}class ne{constructor(e,t){this._payload={apns:{},fcm:{}},this._title=e,this._body=t,this.apns=new ee(this._payload.apns,e,t),this.fcm=new te(this._payload.fcm,e,t)}set debugging(e){this._debugging=e}get title(){return this._title}get subtitle(){return this._subtitle}set subtitle(e){this._subtitle=e,this.apns.subtitle=e,this.fcm.subtitle=e}get body(){return this._body}get badge(){return this._badge}set badge(e){this._badge=e,this.apns.badge=e,this.fcm.badge=e}get sound(){return this._sound}set sound(e){this._sound=e,this.apns.sound=e,this.fcm.sound=e}buildPayload(e){const t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";const n=this.apns.toObject();n&&Object.keys(n).length&&(t.pn_apns=n)}if(e.includes("fcm")){const e=this.fcm.toObject();e&&Object.keys(e).length&&(t.pn_gcm=e)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t}}class se{constructor(e){this.params=e,this.requestIdentifier=x.createUUID(),this._cancellationController=null}get cancellationController(){return this._cancellationController}set cancellationController(e){this._cancellationController=e}abort(e){this&&this.cancellationController&&this.cancellationController.abort(e)}operation(){throw Error("Should be implemented by subclass.")}validate(){}parse(e){return i(this,void 0,void 0,(function*(){return this.deserializeResponse(e)}))}request(){var e,t,n,s;const r={method:null!==(t=null===(e=this.params)||void 0===e?void 0:e.method)&&void 0!==t?t:K.GET,path:this.path,queryParameters:this.queryParameters,cancellable:null!==(s=null===(n=this.params)||void 0===n?void 0:n.cancellable)&&void 0!==s&&s,timeout:10,identifier:this.requestIdentifier},i=this.headers;if(i&&(r.headers=i),r.method===K.POST||r.method===K.PATCH){const[e,t]=[this.body,this.formData];t&&(r.formData=t),e&&(r.body=e)}return r}get headers(){}get path(){throw Error("`path` getter should be implemented by subclass.")}get queryParameters(){return{}}get formData(){}get body(){}deserializeResponse(e){const t=se.decoder.decode(e.body),n=e.headers["content-type"];let s;if(!n||-1===n.indexOf("javascript")&&-1===n.indexOf("json"))throw new d("Service response error, check status for details",y(t,e.status));try{s=JSON.parse(t)}catch(n){throw console.error("Error parsing JSON response:",n),new d("Service response error, check status for details",y(t,e.status))}if("status"in s&&"number"==typeof s.status&&s.status>=400)throw j.create(e);return s}}var re;se.decoder=new TextDecoder,function(e){e.PNPublishOperation="PNPublishOperation",e.PNSignalOperation="PNSignalOperation",e.PNSubscribeOperation="PNSubscribeOperation",e.PNUnsubscribeOperation="PNUnsubscribeOperation",e.PNWhereNowOperation="PNWhereNowOperation",e.PNHereNowOperation="PNHereNowOperation",e.PNGlobalHereNowOperation="PNGlobalHereNowOperation",e.PNSetStateOperation="PNSetStateOperation",e.PNGetStateOperation="PNGetStateOperation",e.PNHeartbeatOperation="PNHeartbeatOperation",e.PNAddMessageActionOperation="PNAddActionOperation",e.PNRemoveMessageActionOperation="PNRemoveMessageActionOperation",e.PNGetMessageActionsOperation="PNGetMessageActionsOperation",e.PNTimeOperation="PNTimeOperation",e.PNHistoryOperation="PNHistoryOperation",e.PNDeleteMessagesOperation="PNDeleteMessagesOperation",e.PNFetchMessagesOperation="PNFetchMessagesOperation",e.PNMessageCounts="PNMessageCountsOperation",e.PNGetAllUUIDMetadataOperation="PNGetAllUUIDMetadataOperation",e.PNGetUUIDMetadataOperation="PNGetUUIDMetadataOperation",e.PNSetUUIDMetadataOperation="PNSetUUIDMetadataOperation",e.PNRemoveUUIDMetadataOperation="PNRemoveUUIDMetadataOperation",e.PNGetAllChannelMetadataOperation="PNGetAllChannelMetadataOperation",e.PNGetChannelMetadataOperation="PNGetChannelMetadataOperation",e.PNSetChannelMetadataOperation="PNSetChannelMetadataOperation",e.PNRemoveChannelMetadataOperation="PNRemoveChannelMetadataOperation",e.PNGetMembersOperation="PNGetMembersOperation",e.PNSetMembersOperation="PNSetMembersOperation",e.PNGetMembershipsOperation="PNGetMembershipsOperation",e.PNSetMembershipsOperation="PNSetMembershipsOperation",e.PNListFilesOperation="PNListFilesOperation",e.PNGenerateUploadUrlOperation="PNGenerateUploadUrlOperation",e.PNPublishFileOperation="PNPublishFileOperation",e.PNPublishFileMessageOperation="PNPublishFileMessageOperation",e.PNGetFileUrlOperation="PNGetFileUrlOperation",e.PNDownloadFileOperation="PNDownloadFileOperation",e.PNDeleteFileOperation="PNDeleteFileOperation",e.PNAddPushNotificationEnabledChannelsOperation="PNAddPushNotificationEnabledChannelsOperation",e.PNRemovePushNotificationEnabledChannelsOperation="PNRemovePushNotificationEnabledChannelsOperation",e.PNPushNotificationEnabledChannelsOperation="PNPushNotificationEnabledChannelsOperation",e.PNRemoveAllPushNotificationsOperation="PNRemoveAllPushNotificationsOperation",e.PNChannelGroupsOperation="PNChannelGroupsOperation",e.PNRemoveGroupOperation="PNRemoveGroupOperation",e.PNChannelsForGroupOperation="PNChannelsForGroupOperation",e.PNAddChannelsToGroupOperation="PNAddChannelsToGroupOperation",e.PNRemoveChannelsFromGroupOperation="PNRemoveChannelsFromGroupOperation",e.PNAccessManagerGrant="PNAccessManagerGrant",e.PNAccessManagerGrantToken="PNAccessManagerGrantToken",e.PNAccessManagerAudit="PNAccessManagerAudit",e.PNAccessManagerRevokeToken="PNAccessManagerRevokeToken",e.PNHandshakeOperation="PNHandshakeOperation",e.PNReceiveMessagesOperation="PNReceiveMessagesOperation"}(re||(re={}));var ie=re;var ae;!function(e){e[e.Presence=-2]="Presence",e[e.Message=-1]="Message",e[e.Signal=1]="Signal",e[e.AppContext=2]="AppContext",e[e.MessageAction=3]="MessageAction",e[e.Files=4]="Files"}(ae||(ae={}));class oe extends se{constructor(e){var t,n,s,r,i,a;super({cancellable:!0}),this.parameters=e,null!==(t=(r=this.parameters).withPresence)&&void 0!==t||(r.withPresence=false),null!==(n=(i=this.parameters).channelGroups)&&void 0!==n||(i.channelGroups=[]),null!==(s=(a=this.parameters).channels)&&void 0!==s||(a.channels=[])}operation(){return ie.PNSubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:n}=this.parameters;return e?t||n?void 0:"`channels` and `channelGroups` both should not be empty":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){let t,n;try{n=se.decoder.decode(e.body);t=JSON.parse(n)}catch(e){console.error("Error parsing JSON response:",e)}if(!t)throw new d("Service response error, check status for details",y(n,e.status));const s=t.m.filter((e=>{const t=void 0===e.b?e.c:e.b;return this.parameters.channels&&this.parameters.channels.includes(t)||this.parameters.channelGroups&&this.parameters.channelGroups.includes(t)})).map((e=>{let{e:t}=e;return null!=t||(t=e.c.endsWith("-pnpres")?ae.Presence:ae.Message),t!=ae.Signal&&"string"==typeof e.d?t==ae.Message?{type:ae.Message,data:this.messageFromEnvelope(e)}:{type:ae.Files,data:this.fileFromEnvelope(e)}:t==ae.Message?{type:ae.Message,data:this.messageFromEnvelope(e)}:t===ae.Presence?{type:ae.Presence,data:this.presenceEventFromEnvelope(e)}:t==ae.Signal?{type:ae.Signal,data:this.signalFromEnvelope(e)}:t===ae.AppContext?{type:ae.AppContext,data:this.appContextFromEnvelope(e)}:t===ae.MessageAction?{type:ae.MessageAction,data:this.messageActionFromEnvelope(e)}:{type:ae.Files,data:this.fileFromEnvelope(e)}}));return{cursor:{timetoken:t.t.t,region:t.t.r},messages:s}}))}get headers(){return{accept:"text/javascript"}}presenceEventFromEnvelope(e){var t;const{d:n}=e,[s,r]=this.subscriptionChannelFromEnvelope(e),i=s.replace("-pnpres",""),a=null!==r?i:null,o=null!==r?r:i;return"string"!=typeof n&&("data"in n?(n.state=n.data,delete n.data):"action"in n&&"interval"===n.action&&(n.hereNowRefresh=null!==(t=n.here_now_refresh)&&void 0!==t&&t,delete n.here_now_refresh)),Object.assign({channel:i,subscription:r,actualChannel:a,subscribedChannel:o,timetoken:e.p.t},n)}messageFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),[s,r]=this.decryptedData(e.d),i={channel:t,subscription:n,actualChannel:null!==n?t:null,subscribedChannel:null!==n?n:t,timetoken:e.p.t,publisher:e.i,message:s};return e.u&&(i.userMetadata=e.u),e.cmt&&(i.customMessageType=e.cmt),r&&(i.error=r),i}signalFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),s={channel:t,subscription:n,timetoken:e.p.t,publisher:e.i,message:e.d};return e.u&&(s.userMetadata=e.u),e.cmt&&(s.customMessageType=e.cmt),s}messageActionFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),s=e.d;return{channel:t,subscription:n,timetoken:e.p.t,publisher:e.i,event:s.event,data:Object.assign(Object.assign({},s.data),{uuid:e.i})}}appContextFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),s=e.d;return{channel:t,subscription:n,timetoken:e.p.t,message:s}}fileFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),[s,r]=this.decryptedData(e.d);let i=r;const a={channel:t,subscription:n,timetoken:e.p.t,publisher:e.i};return e.u&&(a.userMetadata=e.u),s?"string"==typeof s?null!=i||(i="Unexpected file information payload data type."):(a.message=s.message,s.file&&(a.file={id:s.file.id,name:s.file.name,url:this.parameters.getFileUrl({id:s.file.id,name:s.file.name,channel:t})})):null!=i||(i="File information payload is missing."),e.cmt&&(a.customMessageType=e.cmt),i&&(a.error=i),a}subscriptionChannelFromEnvelope(e){return[e.c,void 0===e.b?e.c:e.b]}decryptedData(e){if(!this.parameters.crypto||"string"!=typeof e)return[e,void 0];let t,n;try{const n=this.parameters.crypto.decrypt(e);t=n instanceof ArrayBuffer?JSON.parse(ce.decoder.decode(n)):n}catch(e){t=null,n=`Error while decrypting message content: ${e.message}`}return[null!=t?t:e,n]}}class ce extends oe{get path(){var e;const{keySet:{subscribeKey:t},channels:n}=this.parameters;return`/v2/subscribe/${t}/${L(null!==(e=null==n?void 0:n.sort())&&void 0!==e?e:[],",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,heartbeat:n,state:s,timetoken:r,region:i}=this.parameters,a={};return e&&e.length>0&&(a["channel-group"]=e.sort().join(",")),t&&t.length>0&&(a["filter-expr"]=t),n&&(a.heartbeat=n),s&&Object.keys(s).length>0&&(a.state=JSON.stringify(s)),void 0!==r&&"string"==typeof r?r.length>0&&"0"!==r&&(a.tt=r):void 0!==r&&r>0&&(a.tt=r),i&&(a.tr=i),a}}class ue{constructor(e){this.listenerManager=e,this.channelListenerMap=new Map,this.groupListenerMap=new Map}emitEvent(e){var t;if(e.type===ae.Message)this.listenerManager.announceMessage(e.data),this.announce("message",e.data,e.data.channel,e.data.subscription);else if(e.type===ae.Signal)this.listenerManager.announceSignal(e.data),this.announce("signal",e.data,e.data.channel,e.data.subscription);else if(e.type===ae.Presence)this.listenerManager.announcePresence(e.data),this.announce("presence",e.data,null!==(t=e.data.subscription)&&void 0!==t?t:e.data.channel,e.data.subscription);else if(e.type===ae.AppContext){const{data:t}=e,{message:n}=t;if(this.listenerManager.announceObjects(t),this.announce("objects",t,t.channel,t.subscription),"uuid"===n.type){const{message:e,channel:s}=t,i=r(t,["message","channel"]),{event:a,type:o}=n,c=r(n,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:s,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",type:"user"})});this.listenerManager.announceUser(u),this.announce("user",u,u.spaceId,u.subscription)}else if("channel"===n.type){const{message:e,channel:s}=t,i=r(t,["message","channel"]),{event:a,type:o}=n,c=r(n,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:s,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",type:"space"})});this.listenerManager.announceSpace(u),this.announce("space",u,u.spaceId,u.subscription)}else if("membership"===n.type){const{message:e,channel:s}=t,i=r(t,["message","channel"]),{event:a,data:o}=n,c=r(n,["event","data"]),{uuid:u,channel:l}=o,h=r(o,["uuid","channel"]),d=Object.assign(Object.assign({},i),{spaceId:s,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",data:Object.assign(Object.assign({},h),{user:u,space:l})})});this.listenerManager.announceMembership(d),this.announce("membership",d,d.spaceId,d.subscription)}}else e.type===ae.MessageAction?(this.listenerManager.announceMessageAction(e.data),this.announce("messageAction",e.data,e.data.channel,e.data.subscription)):e.type===ae.Files&&(this.listenerManager.announceFile(e.data),this.announce("file",e.data,e.data.channel,e.data.subscription))}addListener(e,t,n){t&&n?(null==t||t.forEach((t=>{if(this.channelListenerMap.has(t)){const n=this.channelListenerMap.get(t);n.includes(e)||n.push(e)}else this.channelListenerMap.set(t,[e])})),null==n||n.forEach((t=>{if(this.groupListenerMap.has(t)){const n=this.groupListenerMap.get(t);n.includes(e)||n.push(e)}else this.groupListenerMap.set(t,[e])}))):this.listenerManager.addListener(e)}removeListener(e,t,n){t&&n?(null==t||t.forEach((t=>{this.channelListenerMap.has(t)&&this.channelListenerMap.set(t,this.channelListenerMap.get(t).filter((t=>t!==e)))})),null==n||n.forEach((t=>{this.groupListenerMap.has(t)&&this.groupListenerMap.set(t,this.groupListenerMap.get(t).filter((t=>t!==e)))}))):this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners(),this.channelListenerMap.clear(),this.groupListenerMap.clear()}announce(e,t,n,s){t&&this.channelListenerMap.has(n)&&this.channelListenerMap.get(n).forEach((n=>{const s=n[e];s&&s(t)})),s&&this.groupListenerMap.has(s)&&this.groupListenerMap.get(s).forEach((n=>{const s=n[e];s&&s(t)}))}}class le{constructor(e=!1){this.sync=e,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){const t=()=>{this.listeners.forEach((t=>{t(e)}))};this.sync?t():setTimeout(t,0)}}class he{transition(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)}constructor(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}on(e,t){return this.transitionMap.set(e,t),this}with(e,t){return[this,e,null!=t?t:[]]}onEnter(e){return this.enterEffects.push(e),this}onExit(e){return this.exitEffects.push(e),this}}class de extends le{describe(e){return new he(e)}start(e,t){this.currentState=e,this.currentContext=t,this.notify({type:"engineStarted",state:e,context:t})}transition(e){if(!this.currentState)throw new Error("Start the engine first");this.notify({type:"eventReceived",event:e});const t=this.currentState.transition(this.currentContext,e);if(t){const[n,s,r]=t;for(const e of this.currentState.exitEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)});const i=this.currentState;this.currentState=n;const a=this.currentContext;this.currentContext=s,this.notify({type:"transitionDone",fromState:i,fromContext:a,toState:n,toContext:s,event:e});for(const e of r)this.notify({type:"invocationDispatched",invocation:e});for(const e of this.currentState.enterEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)})}}}class pe{constructor(e){this.dependencies=e,this.instances=new Map,this.handlers=new Map}on(e,t){this.handlers.set(e,t)}dispatch(e){if("CANCEL"===e.type){if(this.instances.has(e.payload)){const t=this.instances.get(e.payload);null==t||t.cancel(),this.instances.delete(e.payload)}return}const t=this.handlers.get(e.type);if(!t)throw new Error(`Unhandled invocation '${e.type}'`);const n=t(e.payload,this.dependencies);e.managed&&this.instances.set(e.type,n),n.start()}dispose(){for(const[e,t]of this.instances.entries())t.cancel(),this.instances.delete(e)}}function ge(e,t){const n=function(...n){return{type:e,payload:null==t?void 0:t(...n)}};return n.type=e,n}function ye(e,t){const n=(...n)=>({type:e,payload:t(...n),managed:!1});return n.type=e,n}function fe(e,t){const n=(...n)=>({type:e,payload:t(...n),managed:!0});return n.type=e,n.cancel={type:"CANCEL",payload:e,managed:!1},n}class me extends Error{constructor(){super("The operation was aborted."),this.name="AbortError",Object.setPrototypeOf(this,new.target.prototype)}}class be extends le{constructor(){super(...arguments),this._aborted=!1}get aborted(){return this._aborted}throwIfAborted(){if(this._aborted)throw new me}abort(){this._aborted=!0,this.notify(new me)}}class ve{constructor(e,t){this.payload=e,this.dependencies=t}}class we extends ve{constructor(e,t,n){super(e,t),this.asyncFunction=n,this.abortSignal=new be}start(){this.asyncFunction(this.payload,this.abortSignal,this.dependencies).catch((e=>{}))}cancel(){this.abortSignal.abort()}}const Se=e=>(t,n)=>new we(t,n,e),Ee=ge("RECONNECT",(()=>({}))),Oe=ge("DISCONNECT",(()=>({}))),ke=ge("JOINED",((e,t)=>({channels:e,groups:t}))),Ce=ge("LEFT",((e,t)=>({channels:e,groups:t}))),Ne=ge("LEFT_ALL",(()=>({}))),Pe=ge("HEARTBEAT_SUCCESS",(e=>({statusCode:e}))),Me=ge("HEARTBEAT_FAILURE",(e=>e)),_e=ge("HEARTBEAT_GIVEUP",(()=>({}))),Ae=ge("TIMES_UP",(()=>({}))),je=ye("HEARTBEAT",((e,t)=>({channels:e,groups:t}))),Ie=ye("LEAVE",((e,t)=>({channels:e,groups:t}))),Fe=ye("EMIT_STATUS",(e=>e)),Te=fe("WAIT",(()=>({}))),Re=fe("DELAYED_HEARTBEAT",(e=>e));class Ue extends pe{constructor(e,t){super(t),this.on(je.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{heartbeat:s,presenceState:r,config:i}){try{yield s(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},i.maintainPresenceState&&{state:r}),{heartbeat:i.presenceTimeout}));e.transition(Pe(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Me(t))}}}))))),this.on(Ie.type,Se(((e,t,n)=>i(this,[e,t,n],void 0,(function*(e,t,{leave:n,config:s}){if(!s.suppressLeaveEvents)try{n({channels:e.channels,channelGroups:e.groups})}catch(e){}}))))),this.on(Te.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{heartbeatDelay:s}){return n.throwIfAborted(),yield s(),n.throwIfAborted(),e.transition(Ae())}))))),this.on(Re.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{heartbeat:s,retryDelay:r,presenceState:i,config:a}){if(!a.retryConfiguration||!a.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(_e());n.throwIfAborted(),yield r(a.retryConfiguration.getDelay(t.attempts,t.reason)),n.throwIfAborted();try{yield s(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},a.maintainPresenceState&&{state:i}),{heartbeat:a.presenceTimeout}));return e.transition(Pe(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Me(t))}}}))))),this.on(Fe.type,Se(((e,t,n)=>i(this,[e,t,n],void 0,(function*(e,t,{emitStatus:n,config:s}){var r;s.announceFailedHeartbeats&&!0===(null===(r=null==e?void 0:e.status)||void 0===r?void 0:r.error)?n(e.status):s.announceSuccessfulHeartbeats&&200===e.statusCode&&n(Object.assign(Object.assign({},e),{operation:ie.PNHeartbeatOperation,error:!1}))})))))}}const xe=new he("HEARTBEAT_STOPPED");xe.on(ke.type,((e,t)=>xe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),xe.on(Ce.type,((e,t)=>xe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))}))),xe.on(Ee.type,((e,t)=>Ke.with({channels:e.channels,groups:e.groups}))),xe.on(Ne.type,((e,t)=>$e.with(void 0)));const De=new he("HEARTBEAT_COOLDOWN");De.onEnter((()=>Te())),De.onExit((()=>Te.cancel)),De.on(Ae.type,((e,t)=>Ke.with({channels:e.channels,groups:e.groups}))),De.on(ke.type,((e,t)=>Ke.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),De.on(Ce.type,((e,t)=>Ke.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ie(t.payload.channels,t.payload.groups)]))),De.on(Oe.type,(e=>xe.with({channels:e.channels,groups:e.groups},[Ie(e.channels,e.groups)]))),De.on(Ne.type,((e,t)=>$e.with(void 0,[Ie(e.channels,e.groups)])));const qe=new he("HEARTBEAT_FAILED");qe.on(ke.type,((e,t)=>Ke.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),qe.on(Ce.type,((e,t)=>Ke.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ie(t.payload.channels,t.payload.groups)]))),qe.on(Ee.type,((e,t)=>Ke.with({channels:e.channels,groups:e.groups}))),qe.on(Oe.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups},[Ie(e.channels,e.groups)]))),qe.on(Ne.type,((e,t)=>$e.with(void 0,[Ie(e.channels,e.groups)])));const Ge=new he("HEARBEAT_RECONNECTING");Ge.onEnter((e=>Re(e))),Ge.onExit((()=>Re.cancel)),Ge.on(ke.type,((e,t)=>Ke.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Ge.on(Ce.type,((e,t)=>Ke.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ie(t.payload.channels,t.payload.groups)]))),Ge.on(Oe.type,((e,t)=>{xe.with({channels:e.channels,groups:e.groups},[Ie(e.channels,e.groups)])})),Ge.on(Pe.type,((e,t)=>De.with({channels:e.channels,groups:e.groups}))),Ge.on(Me.type,((e,t)=>Ge.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),Ge.on(_e.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),Ge.on(Ne.type,((e,t)=>$e.with(void 0,[Ie(e.channels,e.groups)])));const Ke=new he("HEARTBEATING");Ke.onEnter((e=>je(e.channels,e.groups))),Ke.on(Pe.type,((e,t)=>De.with({channels:e.channels,groups:e.groups}))),Ke.on(ke.type,((e,t)=>Ke.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Ke.on(Ce.type,((e,t)=>Ke.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ie(t.payload.channels,t.payload.groups)]))),Ke.on(Me.type,((e,t)=>Ge.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),Ke.on(Oe.type,(e=>xe.with({channels:e.channels,groups:e.groups},[Ie(e.channels,e.groups)]))),Ke.on(Ne.type,((e,t)=>$e.with(void 0,[Ie(e.channels,e.groups)])));const $e=new he("HEARTBEAT_INACTIVE");$e.on(ke.type,((e,t)=>Ke.with({channels:t.payload.channels,groups:t.payload.groups})));class Le{get _engine(){return this.engine}constructor(e){this.dependencies=e,this.engine=new de,this.channels=[],this.groups=[],this.dispatcher=new Ue(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start($e,void 0)}join({channels:e,groups:t}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],this.engine.transition(ke(this.channels.slice(0),this.groups.slice(0)))}leave({channels:e,groups:t}){this.dependencies.presenceState&&(null==e||e.forEach((e=>delete this.dependencies.presenceState[e])),null==t||t.forEach((e=>delete this.dependencies.presenceState[e]))),this.engine.transition(Ce(null!=e?e:[],null!=t?t:[]))}leaveAll(){this.engine.transition(Ne())}dispose(){this._unsubscribeEngine(),this.dispatcher.dispose()}}class Be{static LinearRetryPolicy(e){return{delay:e.delay,maximumRetry:e.maximumRetry,shouldRetry(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(e,t){var n;return 1e3*((null!==(n=t.retryAfter)&&void 0!==n?n:this.delay)+Math.random())},getGiveupReason(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"},validate(){if(this.maximumRetry>10)throw new Error("Maximum retry for linear retry policy can not be more than 10")}}}static ExponentialRetryPolicy(e){return{minimumDelay:e.minimumDelay,maximumDelay:e.maximumDelay,maximumRetry:e.maximumRetry,shouldRetry(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(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(e,t){var n;return this.maximumRetry<=t?"retry attempts exhausted.":403===(null===(n=null==e?void 0:e.status)||void 0===n?void 0:n.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.minimumDelay<2)throw new Error("Minimum delay can not be set less than 2 seconds for retry");if(this.maximumDelay)throw new Error("Maximum delay can not be set more than 150 seconds for retry");if(this.maximumRetry>6)throw new Error("Maximum retry for exponential retry policy can not be more than 6")}}}}const He=fe("HANDSHAKE",((e,t)=>({channels:e,groups:t}))),Ve=fe("RECEIVE_MESSAGES",((e,t,n)=>({channels:e,groups:t,cursor:n}))),ze=ye("EMIT_MESSAGES",(e=>e)),We=ye("EMIT_STATUS",(e=>e)),Je=fe("RECEIVE_RECONNECT",(e=>e)),Xe=fe("HANDSHAKE_RECONNECT",(e=>e)),Qe=ge("SUBSCRIPTION_CHANGED",((e,t)=>({channels:e,groups:t}))),Ye=ge("SUBSCRIPTION_RESTORED",((e,t,n,s)=>({channels:e,groups:t,cursor:{timetoken:n,region:null!=s?s:0}}))),Ze=ge("HANDSHAKE_SUCCESS",(e=>e)),et=ge("HANDSHAKE_FAILURE",(e=>e)),tt=ge("HANDSHAKE_RECONNECT_SUCCESS",(e=>({cursor:e}))),nt=ge("HANDSHAKE_RECONNECT_FAILURE",(e=>e)),st=ge("HANDSHAKE_RECONNECT_GIVEUP",(e=>e)),rt=ge("RECEIVE_SUCCESS",((e,t)=>({cursor:e,events:t}))),it=ge("RECEIVE_FAILURE",(e=>e)),at=ge("RECEIVE_RECONNECT_SUCCESS",((e,t)=>({cursor:e,events:t}))),ot=ge("RECEIVE_RECONNECT_FAILURE",(e=>e)),ct=ge("RECEIVING_RECONNECT_GIVEUP",(e=>e)),ut=ge("DISCONNECT",(()=>({}))),lt=ge("RECONNECT",((e,t)=>({cursor:{timetoken:null!=e?e:"",region:null!=t?t:0}}))),ht=ge("UNSUBSCRIBE_ALL",(()=>({})));class dt extends pe{constructor(e,t){super(t),this.on(He.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{handshake:s,presenceState:r,config:i}){n.throwIfAborted();try{const a=yield s(Object.assign({abortSignal:n,channels:t.channels,channelGroups:t.groups,filterExpression:i.filterExpression},i.maintainPresenceState&&{state:r}));return e.transition(Ze(a))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(et(t))}}}))))),this.on(Ve.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{receiveMessages:s,config:r}){n.throwIfAborted();try{const i=yield s({abortSignal:n,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:r.filterExpression});e.transition(rt(i.cursor,i.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;if(!n.aborted)return e.transition(it(t))}}}))))),this.on(ze.type,Se(((e,t,n)=>i(this,[e,t,n],void 0,(function*(e,t,{emitMessages:n}){e.length>0&&n(e)}))))),this.on(We.type,Se(((e,t,n)=>i(this,[e,t,n],void 0,(function*(e,t,{emitStatus:n}){n(e)}))))),this.on(Je.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{receiveMessages:s,delay:r,config:i}){if(!i.retryConfiguration||!i.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(ct(new d(i.retryConfiguration?i.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe messages receive.")));n.throwIfAborted(),yield r(i.retryConfiguration.getDelay(t.attempts,t.reason)),n.throwIfAborted();try{const r=yield s({abortSignal:n,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:i.filterExpression});return e.transition(at(r.cursor,r.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(ot(t))}}}))))),this.on(Xe.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{handshake:s,delay:r,presenceState:i,config:a}){if(!a.retryConfiguration||!a.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(st(new d(a.retryConfiguration?a.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe handshake")));n.throwIfAborted(),yield r(a.retryConfiguration.getDelay(t.attempts,t.reason)),n.throwIfAborted();try{const r=yield s(Object.assign({abortSignal:n,channels:t.channels,channelGroups:t.groups,filterExpression:a.filterExpression},a.maintainPresenceState&&{state:i}));return e.transition(tt(r))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(nt(t))}}})))))}}const pt=new he("HANDSHAKE_FAILED");pt.on(Qe.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),pt.on(lt.type,((e,t)=>wt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor||e.cursor}))),pt.on(Ye.type,((e,t)=>{var n,s;return wt.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!==(s=null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)&&void 0!==s?s:0}})})),pt.on(ht.type,(e=>St.with()));const gt=new he("HANDSHAKE_STOPPED");gt.on(Qe.type,((e,t)=>gt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),gt.on(lt.type,((e,t)=>wt.with(Object.assign(Object.assign({},e),{cursor:t.payload.cursor||e.cursor})))),gt.on(Ye.type,((e,t)=>{var n;return gt.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}})})),gt.on(ht.type,(e=>St.with()));const yt=new he("RECEIVE_FAILED");yt.on(lt.type,((e,t)=>{var n;return wt.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}})})),yt.on(Qe.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),yt.on(Ye.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),yt.on(ht.type,(e=>St.with(void 0)));const ft=new he("RECEIVE_STOPPED");ft.on(Qe.type,((e,t)=>ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),ft.on(Ye.type,((e,t)=>ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),ft.on(lt.type,((e,t)=>{var n;return wt.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}})})),ft.on(ht.type,(()=>St.with(void 0)));const mt=new he("RECEIVE_RECONNECTING");mt.onEnter((e=>Je(e))),mt.onExit((()=>Je.cancel)),mt.on(at.type,((e,t)=>bt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),mt.on(ot.type,((e,t)=>mt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),mt.on(ct.type,((e,t)=>{var n;return yt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[We({category:h.PNDisconnectedUnexpectedlyCategory,error:null===(n=t.payload)||void 0===n?void 0:n.message})])})),mt.on(ut.type,(e=>ft.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[We({category:h.PNDisconnectedCategory})]))),mt.on(Ye.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),mt.on(Qe.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),mt.on(ht.type,(e=>St.with(void 0,[We({category:h.PNDisconnectedCategory})])));const bt=new he("RECEIVING");bt.onEnter((e=>Ve(e.channels,e.groups,e.cursor))),bt.onExit((()=>Ve.cancel)),bt.on(rt.type,((e,t)=>bt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),bt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?St.with(void 0):bt.with({cursor:e.cursor,channels:t.payload.channels,groups:t.payload.groups}))),bt.on(Ye.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?St.with(void 0):bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),bt.on(it.type,((e,t)=>mt.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),bt.on(ut.type,(e=>ft.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[We({category:h.PNDisconnectedCategory})]))),bt.on(ht.type,(e=>St.with(void 0,[We({category:h.PNDisconnectedCategory})])));const vt=new he("HANDSHAKE_RECONNECTING");vt.onEnter((e=>Xe(e))),vt.onExit((()=>Xe.cancel)),vt.on(tt.type,((e,t)=>{var n,s;const r={timetoken:(null===(n=e.cursor)||void 0===n?void 0:n.timetoken)?null===(s=e.cursor)||void 0===s?void 0:s.timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region};return bt.with({channels:e.channels,groups:e.groups,cursor:r},[We({category:h.PNConnectedCategory})])})),vt.on(nt.type,((e,t)=>vt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),vt.on(st.type,((e,t)=>{var n;return pt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[We({category:h.PNConnectionErrorCategory,error:null===(n=t.payload)||void 0===n?void 0:n.message})])})),vt.on(ut.type,(e=>gt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),vt.on(Qe.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),vt.on(Ye.type,((e,t)=>{var n,s;return wt.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===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),vt.on(ht.type,(e=>St.with(void 0)));const wt=new he("HANDSHAKING");wt.onEnter((e=>He(e.channels,e.groups))),wt.onExit((()=>He.cancel)),wt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?St.with(void 0):wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),wt.on(Ze.type,((e,t)=>{var n,s;return bt.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===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.timetoken:t.payload.timetoken,region:t.payload.region}},[We({category:h.PNConnectedCategory})])})),wt.on(et.type,((e,t)=>vt.with({channels:e.channels,groups:e.groups,cursor:e.cursor,attempts:0,reason:t.payload}))),wt.on(ut.type,(e=>gt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),wt.on(Ye.type,((e,t)=>{var n;return wt.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}})})),wt.on(ht.type,(e=>St.with()));const St=new he("UNSUBSCRIBED");St.on(Qe.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups}))),St.on(Ye.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:t.payload.cursor})));class Et{get _engine(){return this.engine}constructor(e){this.engine=new de,this.channels=[],this.groups=[],this.dependencies=e,this.dispatcher=new dt(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(St,void 0)}subscribe({channels:e,channelGroups:t,timetoken:n,withPresence:s}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],s&&(this.channels.map((e=>this.channels.push(`${e}-pnpres`))),this.groups.map((e=>this.groups.push(`${e}-pnpres`)))),n?this.engine.transition(Ye(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])),n)):this.engine.transition(Qe(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])))),this.dependencies.join&&this.dependencies.join({channels:Array.from(new Set(this.channels.filter((e=>!e.endsWith("-pnpres"))))),groups:Array.from(new Set(this.groups.filter((e=>!e.endsWith("-pnpres")))))})}unsubscribe({channels:e=[],channelGroups:t=[]}){const n=B(this.channels,[...e,...e.map((e=>`${e}-pnpres`))]),s=B(this.groups,[...t,...t.map((e=>`${e}-pnpres`))]);if(new Set(this.channels).size!==new Set(n).size||new Set(this.groups).size!==new Set(s).size){const r=H(this.channels,e),i=H(this.groups,t);this.dependencies.presenceState&&(null==r||r.forEach((e=>delete this.dependencies.presenceState[e])),null==i||i.forEach((e=>delete this.dependencies.presenceState[e]))),this.channels=n,this.groups=s,this.engine.transition(Qe(Array.from(new Set(this.channels.slice(0))),Array.from(new Set(this.groups.slice(0))))),this.dependencies.leave&&this.dependencies.leave({channels:r.slice(0),groups:i.slice(0)})}}unsubscribeAll(){this.channels=[],this.groups=[],this.dependencies.presenceState&&Object.keys(this.dependencies.presenceState).forEach((e=>{delete this.dependencies.presenceState[e]})),this.engine.transition(Qe(this.channels.slice(0),this.groups.slice(0))),this.dependencies.leaveAll&&this.dependencies.leaveAll()}reconnect({timetoken:e,region:t}){this.engine.transition(lt(e,t))}disconnect(){this.engine.transition(ut()),this.dependencies.leaveAll&&this.dependencies.leaveAll()}getSubscribedChannels(){return Array.from(new Set(this.channels.slice(0)))}getSubscribedChannelGroups(){return Array.from(new Set(this.groups.slice(0)))}dispose(){this.disconnect(),this._unsubscribeEngine(),this.dispatcher.dispose()}}class Ot extends se{constructor(e){var t,n;super({method:e.sendByPost?K.POST:K.GET}),this.parameters=e,null!==(t=(n=this.parameters).sendByPost)&&void 0!==t||(n.sendByPost=false)}operation(){return ie.PNPublishOperation}validate(){const{message:e,channel:t,keySet:{publishKey:n}}=this.parameters;return t?e?n?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{message:e,channel:t,keySet:n}=this.parameters,s=this.prepareMessagePayload(e);return`/publish/${n.publishKey}/${n.subscribeKey}/0/${$(t)}/0${this.parameters.sendByPost?"":`/${$(s)}`}`}get queryParameters(){const{customMessageType:e,meta:t,replicate:n,storeInHistory:s,ttl:r}=this.parameters,i={};return e&&(i.custom_message_type=e),void 0!==s&&(i.store=s?"1":"0"),void 0!==r&&(i.ttl=r),void 0===n||n||(i.norep="true"),t&&"object"==typeof t&&(i.meta=JSON.stringify(t)),i}get headers(){if(this.parameters.sendByPost)return{"Content-Type":"application/json"}}get body(){return this.prepareMessagePayload(this.parameters.message)}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const n=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof n?n:u(n))}}class kt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNSignalOperation}validate(){const{message:e,channel:t,keySet:{publishKey:n}}=this.parameters;return t?e?n?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{keySet:{publishKey:e,subscribeKey:t},channel:n,message:s}=this.parameters,r=JSON.stringify(s);return`/signal/${e}/${t}/0/${$(n)}/0/${$(r)}`}get queryParameters(){const{customMessageType:e}=this.parameters,t={};return e&&(t.custom_message_type=e),t}}class Ct extends oe{operation(){return ie.PNReceiveMessagesOperation}validate(){const e=super.validate();return e||(this.parameters.timetoken?this.parameters.region?void 0:"region can not be empty":"timetoken can not be empty")}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${L(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,timetoken:n,region:s}=this.parameters,r={ee:""};return e&&e.length>0&&(r["channel-group"]=e.sort().join(",")),t&&t.length>0&&(r["filter-expr"]=t),"string"==typeof n?n&&n.length>0&&(r.tt=n):n&&n>0&&(r.tt=n),s&&(r.tr=s),r}}class Nt extends oe{operation(){return ie.PNHandshakeOperation}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${L(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,state:n}=this.parameters,s={tt:0,ee:""};return e&&e.length>0&&(s["channel-group"]=e.sort().join(",")),t&&t.length>0&&(s["filter-expr"]=t),n&&Object.keys(n).length>0&&(s.state=JSON.stringify(n)),s}}class Pt extends se{constructor(e){var t,n,s,r;super(),this.parameters=e,null!==(t=(s=this.parameters).channels)&&void 0!==t||(s.channels=[]),null!==(n=(r=this.parameters).channelGroups)&&void 0!==n||(r.channelGroups=[])}operation(){return ie.PNGetStateOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:n}=this.parameters;if(!e)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e),{channels:n=[],channelGroups:s=[]}=this.parameters,r={channels:{}};return 1===n.length&&0===s.length?r.channels[n[0]]=t.payload:r.channels=t.payload,r}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:n}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${L(null!=n?n:[],",")}/uuid/${t}`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.join(",")}:{}}}class Mt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNSetStateOperation}validate(){const{keySet:{subscribeKey:e},state:t,channels:n=[],channelGroups:s=[]}=this.parameters;return e?t?0===(null==n?void 0:n.length)&&0===(null==s?void 0:s.length)?"Please provide a list of channels and/or channel-groups":void 0:"Missing State":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{state:this.deserializeResponse(e).payload}}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:n}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${L(null!=n?n:[],",")}/uuid/${$(t)}/data`}get queryParameters(){const{channelGroups:e,state:t}=this.parameters,n={state:JSON.stringify(t)};return e&&0!==e.length&&(n["channel-group"]=e.join(",")),n}}class _t extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNHeartbeatOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:n=[]}=this.parameters;return e?0===t.length&&0===n.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channels:t}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${L(null!=t?t:[],",")}/heartbeat`}get queryParameters(){const{channelGroups:e,state:t,heartbeat:n}=this.parameters,s={heartbeat:`${n}`};return e&&0!==e.length&&(s["channel-group"]=e.join(",")),t&&(s.state=JSON.stringify(t)),s}}class At extends se{constructor(e){super(),this.parameters=e,this.parameters.channelGroups&&(this.parameters.channelGroups=Array.from(new Set(this.parameters.channelGroups))),this.parameters.channels&&(this.parameters.channels=Array.from(new Set(this.parameters.channels)))}operation(){return ie.PNUnsubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:n=[]}=this.parameters;return e?0===t.length&&0===n.length?"At least one `channel` or `channel group` should be provided.":void 0:"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){var e;const{keySet:{subscribeKey:t},channels:n}=this.parameters;return`/v2/presence/sub-key/${t}/channel/${L(null!==(e=null==n?void 0:n.sort())&&void 0!==e?e:[],",")}/leave`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.sort().join(",")}:{}}}class jt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNWhereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return t.payload?{channels:t.payload.channels}:{channels:[]}}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/presence/sub-key/${e}/uuid/${$(t)}`}}class It extends se{constructor(e){var t,n,s,r,i,a;super(),this.parameters=e,null!==(t=(r=this.parameters).queryParameters)&&void 0!==t||(r.queryParameters={}),null!==(n=(i=this.parameters).includeUUIDs)&&void 0!==n||(i.includeUUIDs=true),null!==(s=(a=this.parameters).includeState)&&void 0!==s||(a.includeState=false)}operation(){const{channels:e=[],channelGroups:t=[]}=this.parameters;return 0===e.length&&0===t.length?ie.PNGlobalHereNowOperation:ie.PNHereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t,n;const s=this.deserializeResponse(e),r="occupancy"in s?1:s.payload.total_channels,i="occupancy"in s?s.occupancy:s.payload.total_occupancy,a={};let o={};if("occupancy"in s){const e=this.parameters.channels[0];o[e]={uuids:null!==(t=s.uuids)&&void 0!==t?t:[],occupancy:i}}else o=null!==(n=s.payload.channels)&&void 0!==n?n:{};return Object.keys(o).forEach((e=>{const t=o[e];a[e]={occupants:this.parameters.includeUUIDs?t.uuids.map((e=>"string"==typeof e?{uuid:e,state:null}:e)):[],name:e,occupancy:t.occupancy}})),{totalChannels:r,totalOccupancy:i,channels:a}}))}get path(){const{keySet:{subscribeKey:e},channels:t,channelGroups:n}=this.parameters;let s=`/v2/presence/sub-key/${e}`;return(t&&t.length>0||n&&n.length>0)&&(s+=`/channel/${L(null!=t?t:[],",")}`),s}get queryParameters(){const{channelGroups:e,includeUUIDs:t,includeState:n,queryParameters:s}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign({},t?{}:{disable_uuids:"1"}),null!=n&&n?{state:"1"}:{}),e&&e.length>0?{"channel-group":e.join(",")}:{}),s)}}class Ft extends se{constructor(e){super({method:K.DELETE}),this.parameters=e}operation(){return ie.PNDeleteMessagesOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v3/history/sub-key/${e}/channel/${$(t)}`}get queryParameters(){const{start:e,end:t}=this.parameters;return Object.assign(Object.assign({},e?{start:e}:{}),t?{end:t}:{})}}class Tt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNMessageCounts}validate(){const{keySet:{subscribeKey:e},channels:t,timetoken:n,channelTimetokens:s}=this.parameters;return e?t?n&&s?"`timetoken` and `channelTimetokens` are incompatible together":n||s?s&&s.length>1&&s.length!==t.length?"Length of `channelTimetokens` and `channels` do not match":void 0:"`timetoken` or `channelTimetokens` need to be set":"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e).channels}}))}get path(){return`/v3/history/sub-key/${this.parameters.keySet.subscribeKey}/message-counts/${L(this.parameters.channels)}`}get queryParameters(){let{channelTimetokens:e}=this.parameters;return this.parameters.timetoken&&(e=[this.parameters.timetoken]),Object.assign(Object.assign({},1===e.length?{timetoken:e[0]}:{}),e.length>1?{channelsTimetoken:e.join(",")}:{})}}class Rt extends se{constructor(e){var t,n,s;super(),this.parameters=e,e.count?e.count=Math.min(e.count,100):e.count=100,null!==(t=e.stringifiedTimeToken)&&void 0!==t||(e.stringifiedTimeToken=false),null!==(n=e.includeMeta)&&void 0!==n||(e.includeMeta=false),null!==(s=e.logVerbosity)&&void 0!==s||(e.logVerbosity=false)}operation(){return ie.PNHistoryOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e),n=t[0],s=t[1],r=t[2];return Array.isArray(n)?{messages:n.map((e=>{const t=this.processPayload(e.message),n={entry:t.payload,timetoken:e.timetoken};return t.error&&(n.error=t.error),e.meta&&(n.meta=e.meta),n})),startTimeToken:s,endTimeToken:r}:{messages:[],startTimeToken:s,endTimeToken:r}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/history/sub-key/${e}/channel/${$(t)}`}get queryParameters(){const{start:e,end:t,reverse:n,count:s,stringifiedTimeToken:r,includeMeta:i}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:s,include_token:"true"},e?{start:e}:{}),t?{end:t}:{}),r?{string_message_token:"true"}:{}),null!=n?{reverse:n.toString()}:{}),i?{include_meta:"true"}:{})}processPayload(e){const{crypto:t,logVerbosity:n}=this.parameters;if(!t||"string"!=typeof e)return{payload:e};let s,r;try{const n=t.decrypt(e);s=n instanceof ArrayBuffer?JSON.parse(Rt.decoder.decode(n)):n}catch(t){n&&console.log("decryption error",t.message),s=e,r=`Error while decrypting message content: ${t.message}`}return{payload:s,error:r}}}var Ut;!function(e){e[e.Message=-1]="Message",e[e.Files=4]="Files"}(Ut||(Ut={}));class xt extends se{constructor(e){var t,n,s,r,i;super(),this.parameters=e;const a=null!==(t=e.includeMessageActions)&&void 0!==t&&t,o=e.channels.length>1||a?25:100;e.count?e.count=Math.min(e.count,o):e.count=o,e.includeUuid?e.includeUUID=e.includeUuid:null!==(n=e.includeUUID)&&void 0!==n||(e.includeUUID=true),null!==(s=e.stringifiedTimeToken)&&void 0!==s||(e.stringifiedTimeToken=false),null!==(r=e.includeMessageType)&&void 0!==r||(e.includeMessageType=true),null!==(i=e.logVerbosity)&&void 0!==i||(e.logVerbosity=false)}operation(){return ie.PNFetchMessagesOperation}validate(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:n}=this.parameters;return e?t?void 0!==n&&n&&t.length>1?"History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.":void 0:"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t;const n=this.deserializeResponse(e),s=null!==(t=n.channels)&&void 0!==t?t:{},r={};return Object.keys(s).forEach((e=>{r[e]=s[e].map((t=>{null===t.message_type&&(t.message_type=Ut.Message);const n=this.processPayload(e,t),s=Object.assign(Object.assign({channel:e,timetoken:t.timetoken,message:n.payload,messageType:t.message_type},t.custom_message_type?{customMessageType:t.custom_message_type}:{}),{uuid:t.uuid});if(t.actions){const e=s;e.actions=t.actions,e.data=t.actions}return t.meta&&(s.meta=t.meta),n.error&&(s.error=n.error),s}))})),n.more?{channels:r,more:n.more}:{channels:r}}))}get path(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:n}=this.parameters;return`/v3/${n?"history-with-actions":"history"}/sub-key/${e}/channel/${L(t)}`}get queryParameters(){const{start:e,end:t,count:n,includeCustomMessageType:s,includeMessageType:r,includeMeta:i,includeUUID:a,stringifiedTimeToken:o}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({max:n},e?{start:e}:{}),t?{end:t}:{}),o?{string_message_token:"true"}:{}),void 0!==i&&i?{include_meta:"true"}:{}),a?{include_uuid:"true"}:{}),null!=s?{include_custom_message_type:s?"true":"false"}:{}),r?{include_message_type:"true"}:{})}processPayload(e,t){const{crypto:n,logVerbosity:s}=this.parameters;if(!n||"string"!=typeof t.message)return{payload:t.message};let r,i;try{const e=n.decrypt(t.message);r=e instanceof ArrayBuffer?JSON.parse(xt.decoder.decode(e)):e}catch(e){s&&console.log("decryption error",e.message),r=t.message,i=`Error while decrypting message content: ${e.message}`}if(!i&&r&&t.message_type==Ut.Files&&"object"==typeof r&&this.isFileMessage(r)){const t=r;return{payload:{message:t.message,file:Object.assign(Object.assign({},t.file),{url:this.parameters.getFileUrl({channel:e,id:t.file.id,name:t.file.name})})},error:i}}return{payload:r,error:i}}isFileMessage(e){return void 0!==e.file}}class Dt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNGetMessageActionsOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);let n=null,s=null;return t.data.length>0&&(n=t.data[0].actionTimetoken,s=t.data[t.data.length-1].actionTimetoken),{data:t.data,more:t.more,start:n,end:s}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/message-actions/${e}/channel/${$(t)}`}get queryParameters(){const{limit:e,start:t,end:n}=this.parameters;return Object.assign(Object.assign(Object.assign({},t?{start:t}:{}),n?{end:n}:{}),e?{limit:e}:{})}}class qt extends se{constructor(e){super({method:K.POST}),this.parameters=e}operation(){return ie.PNAddMessageActionOperation}validate(){const{keySet:{subscribeKey:e},action:t,channel:n,messageTimetoken:s}=this.parameters;return e?n?s?t?t.value?t.type?t.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message timetoken":"Missing message channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((({data:e})=>({data:e})))}))}get path(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:n}=this.parameters;return`/v1/message-actions/${e}/channel/${$(t)}/message/${n}`}get headers(){return{"Content-Type":"application/json"}}get body(){return JSON.stringify(this.parameters.action)}}class Gt extends se{constructor(e){super({method:K.DELETE}),this.parameters=e}operation(){return ie.PNRemoveMessageActionOperation}validate(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:n,actionTimetoken:s}=this.parameters;return e?t?n?s?void 0:"Missing action timetoken":"Missing message timetoken":"Missing message action channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((({data:e})=>({data:e})))}))}get path(){const{keySet:{subscribeKey:e},channel:t,actionTimetoken:n,messageTimetoken:s}=this.parameters;return`/v1/message-actions/${e}/channel/${$(t)}/message/${s}/action/${n}`}}class Kt extends se{constructor(e){var t,n;super(),this.parameters=e,null!==(t=(n=this.parameters).storeInHistory)&&void 0!==t||(n.storeInHistory=true)}operation(){return ie.PNPublishFileMessageOperation}validate(){const{channel:e,fileId:t,fileName:n}=this.parameters;return e?t?n?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{message:e,channel:t,keySet:{publishKey:n,subscribeKey:s},fileId:r,fileName:i}=this.parameters,a=Object.assign({file:{name:i,id:r}},e?{message:e}:{});return`/v1/files/publish-file/${n}/${s}/0/${$(t)}/0/${$(this.prepareMessagePayload(a))}`}get queryParameters(){const{customMessageType:e,storeInHistory:t,ttl:n,meta:s}=this.parameters;return Object.assign(Object.assign(Object.assign({store:t?"1":"0"},e?{custom_message_type:e}:{}),n?{ttl:n}:{}),s&&"object"==typeof s?{meta:JSON.stringify(s)}:{})}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const n=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof n?n:u(n))}}class $t extends se{constructor(e){super({method:K.LOCAL}),this.parameters=e}operation(){return ie.PNGetFileUrlOperation}validate(){const{channel:e,id:t,name:n}=this.parameters;return e?t?n?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return e.url}))}get path(){const{channel:e,id:t,name:n,keySet:{subscribeKey:s}}=this.parameters;return`/v1/files/${s}/channels/${$(e)}/files/${t}/${n}`}}class Lt extends se{constructor(e){super({method:K.DELETE}),this.parameters=e}operation(){return ie.PNDeleteFileOperation}validate(){const{channel:e,id:t,name:n}=this.parameters;return e?t?n?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}get path(){const{keySet:{subscribeKey:e},id:t,channel:n,name:s}=this.parameters;return`/v1/files/${e}/channels/${$(n)}/files/${t}/${s}`}}class Bt extends se{constructor(e){var t,n;super(),this.parameters=e,null!==(t=(n=this.parameters).limit)&&void 0!==t||(n.limit=100)}operation(){return ie.PNListFilesOperation}validate(){if(!this.parameters.channel)return"channel can't be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${$(t)}/files`}get queryParameters(){const{limit:e,next:t}=this.parameters;return Object.assign({limit:e},t?{next:t}:{})}}class Ht extends se{constructor(e){super({method:K.POST}),this.parameters=e}operation(){return ie.PNGenerateUploadUrlOperation}validate(){return this.parameters.channel?this.parameters.name?void 0:"'name' can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return{id:t.data.id,name:t.data.name,url:t.file_upload_request.url,formFields:t.file_upload_request.form_fields}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${$(t)}/generate-upload-url`}get headers(){return{"Content-Type":"application/json"}}get body(){return JSON.stringify({name:this.parameters.name})}}class Vt extends se{constructor(e){super({method:K.POST}),this.parameters=e;const t=e.file.mimeType;t&&(e.formFields=e.formFields.map((e=>"Content-Type"===e.name?{name:e.name,value:t}:e)))}operation(){return ie.PNPublishFileOperation}validate(){const{fileId:e,fileName:t,file:n,uploadUrl:s}=this.parameters;return e?t?n?s?void 0:"Validation failed: file upload 'url' can't be empty":"Validation failed: 'file' can't be empty":"Validation failed: file 'name' can't be empty":"Validation failed: file 'id' can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{status:e.status,message:e.body?Vt.decoder.decode(e.body):"OK"}}))}request(){return Object.assign(Object.assign({},super.request()),{origin:new URL(this.parameters.uploadUrl).origin,timeout:300})}get path(){const{pathname:e,search:t}=new URL(this.parameters.uploadUrl);return`${e}${t}`}get body(){return this.parameters.file}get formData(){return this.parameters.formFields}}class zt{constructor(e){var t;if(this.parameters=e,this.file=null===(t=this.parameters.PubNubFile)||void 0===t?void 0:t.create(e.file),!this.file)throw new Error("File upload error: unable to create File object.")}process(){return i(this,void 0,void 0,(function*(){let e,t;return this.generateFileUploadUrl().then((n=>(e=n.name,t=n.id,this.uploadFile(n)))).then((e=>{if(204!==e.status)throw new d("Upload to bucket was unsuccessful",{error:!0,statusCode:e.status,category:h.PNUnknownCategory,operation:ie.PNPublishFileOperation,errorData:{message:e.message}})})).then((()=>this.publishFileMessage(t,e))).catch((e=>{if(e instanceof d)throw e;const t=e instanceof j?e:j.create(e);throw new d("File upload error.",t.toStatus(ie.PNPublishFileOperation))}))}))}generateFileUploadUrl(){return i(this,void 0,void 0,(function*(){const e=new Ht(Object.assign(Object.assign({},this.parameters),{name:this.file.name,keySet:this.parameters.keySet}));return this.parameters.sendRequest(e)}))}uploadFile(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,PubNubFile:n,crypto:s,cryptography:r}=this.parameters,{id:i,name:a,url:o,formFields:c}=e;return this.parameters.PubNubFile.supportsEncryptFile&&(!t&&s?this.file=yield s.encryptFile(this.file,n):t&&r&&(this.file=yield r.encryptFile(t,this.file,n))),this.parameters.sendRequest(new Vt({fileId:i,fileName:a,file:this.file,uploadUrl:o,formFields:c}))}))}publishFileMessage(e,t){return i(this,void 0,void 0,(function*(){var n,s,r,i;let a,o={timetoken:"0"},c=this.parameters.fileUploadPublishRetryLimit,u=!1;do{try{o=yield this.parameters.publishFile(Object.assign(Object.assign({},this.parameters),{fileId:e,fileName:t})),u=!0}catch(e){e instanceof d&&(a=e),c-=1}}while(!u&&c>0);if(u)return{status:200,timetoken:o.timetoken,id:e,name:t};throw new d("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{error:!0,category:null!==(s=null===(n=a.status)||void 0===n?void 0:n.category)&&void 0!==s?s:h.PNUnknownCategory,statusCode:null!==(i=null===(r=a.status)||void 0===r?void 0:r.statusCode)&&void 0!==i?i:0,channel:this.parameters.channel,id:e,name:t})}))}}class Wt{subscribe(e){const t=null==e?void 0:e.timetoken;this.pubnub.registerSubscribeCapable(this),this.pubnub.subscribe(Object.assign({channels:this.channelNames,channelGroups:this.groupNames},null!==t&&""!==t&&{timetoken:t}))}unsubscribe(){this.pubnub.unregisterSubscribeCapable(this);const{channels:e,channelGroups:t}=this.pubnub.getSubscribeCapableEntities(),n=this.groupNames.filter((e=>!t.includes(e))),s=this.channelNames.filter((t=>!e.includes(t)));0===s.length&&0===n.length||this.pubnub.unsubscribe({channels:s,channelGroups:n})}set onMessage(e){this.listener.message=e}set onPresence(e){this.listener.presence=e}set onSignal(e){this.listener.signal=e}set onObjects(e){this.listener.objects=e}set onMessageAction(e){this.listener.messageAction=e}set onFile(e){this.listener.file=e}addListener(e){this.eventEmitter.addListener(e,this.channelNames,this.groupNames)}removeListener(e){this.eventEmitter.removeListener(e,this.channelNames,this.groupNames)}get channels(){return this.channelNames.slice(0)}get channelGroups(){return this.groupNames.slice(0)}}class Jt extends Wt{constructor({channels:e=[],channelGroups:t=[],subscriptionOptions:n,eventEmitter:s,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.subscriptionList=[],this.options=n,this.eventEmitter=s,this.pubnub=r,e.forEach((e=>{const t=this.pubnub.channel(e).subscription(this.options);this.channelNames=[...this.channelNames,...t.channels],this.subscriptionList.push(t)})),t.forEach((e=>{const t=this.pubnub.channelGroup(e).subscription(this.options);this.groupNames=[...this.groupNames,...t.channelGroups],this.subscriptionList.push(t)})),this.listener={},s.addListener(this.listener,this.channelNames,this.groupNames)}addSubscription(e){this.subscriptionList.push(e),this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscription(e){const t=e.channels,n=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!n.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>t!==e)),this.eventEmitter.removeListener(this.listener,t,n)}addSubscriptionSet(e){this.subscriptionList=[...this.subscriptionList,...e.subscriptions],this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscriptionSet(e){const t=e.channels,n=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!n.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>!e.subscriptions.includes(t))),this.eventEmitter.removeListener(this.listener,t,n)}get subscriptions(){return this.subscriptionList.slice(0)}}class Xt extends Wt{constructor({channels:e,channelGroups:t,subscriptionOptions:n,eventEmitter:s,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.channelNames=e,this.groupNames=t,this.options=n,this.pubnub=r,this.eventEmitter=s,this.listener={},s.addListener(this.listener,this.channelNames,this.groupNames)}addSubscription(e){return new Jt({channels:[...this.channelNames,...e.channels],channelGroups:[...this.groupNames,...e.channelGroups],subscriptionOptions:Object.assign(Object.assign({},this.options),null==e?void 0:e.options),eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Qt{constructor(e,t,n){this.eventEmitter=t,this.pubnub=n,this.id=e}subscription(e){return new Xt({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Yt{constructor(e,t,n){this.eventEmitter=t,this.pubnub=n,this.name=e}subscription(e){{const t=[this.name];return(null==e?void 0:e.receivePresenceEvents)&&!this.name.endsWith("-pnpres")&&t.push(`${this.name}-pnpres`),new Xt({channels:[],channelGroups:t,subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}}class Zt{constructor(e,t,n){this.eventEmitter=t,this.pubnub=n,this.id=e}subscription(e){return new Xt({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class en{constructor(e,t,n){this.eventEmitter=t,this.pubnub=n,this.name=e}subscription(e){{const t=[this.name];return(null==e?void 0:e.receivePresenceEvents)&&!this.name.endsWith("-pnpres")&&t.push(`${this.name}-pnpres`),new Xt({channels:t,channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}}class tn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNRemoveChannelsFromGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:n}=this.parameters;return e?n?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${$(t)}`}get queryParameters(){return{remove:this.parameters.channels.join(",")}}}class nn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNAddChannelsToGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:n}=this.parameters;return e?n?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${$(t)}`}get queryParameters(){return{add:this.parameters.channels.join(",")}}}class sn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNChannelsForGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e).payload.channels}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${$(t)}`}}class rn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNRemoveGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${$(t)}/remove`}}class an extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNChannelGroupsOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{groups:this.deserializeResponse(e).payload.groups}}))}get path(){return`/v1/channel-registration/sub-key/${this.parameters.keySet.subscribeKey}/channel-group`}}class on{constructor(e,t){this.sendRequest=t,this.keySet=e}listChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new sn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}listGroups(e){return i(this,void 0,void 0,(function*(){const t=new an({keySet:this.keySet});return e?this.sendRequest(t,e):this.sendRequest(t)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new nn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new tn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}deleteGroup(e,t){return i(this,void 0,void 0,(function*(){const n=new rn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}}class cn extends se{constructor(e){var t,n;super(),this.parameters=e,"apns2"===this.parameters.pushGateway&&(null!==(t=(n=this.parameters).environment)&&void 0!==t||(n.environment="development")),this.parameters.count&&this.parameters.count>1e3&&(this.parameters.count=1e3)}operation(){throw Error("Should be implemented in subclass.")}validate(){const{keySet:{subscribeKey:e},action:t,device:n,pushGateway:s}=this.parameters;return e?n?"add"!==t&&"remove"!==t||"channels"in this.parameters&&0!==this.parameters.channels.length?s?"apns2"!==this.parameters.pushGateway||this.parameters.topic?void 0:"Missing APNS2 topic":"Missing GW Type (pushGateway: gcm or apns2)":"Missing Channels":"Missing Device ID (device)":"Missing Subscribe Key"}get path(){const{keySet:{subscribeKey:e},action:t,device:n,pushGateway:s}=this.parameters;let r="apns2"===s?`/v2/push/sub-key/${e}/devices-apns2/${n}`:`/v1/push/sub-key/${e}/devices/${n}`;return"remove-device"===t&&(r=`${r}/remove`),r}get queryParameters(){const{start:e,count:t}=this.parameters;let n=Object.assign(Object.assign({type:this.parameters.pushGateway},e?{start:e}:{}),t&&t>0?{count:t}:{});if("channels"in this.parameters&&(n[this.parameters.action]=this.parameters.channels.join(",")),"apns2"===this.parameters.pushGateway){const{environment:e,topic:t}=this.parameters;n=Object.assign(Object.assign({},n),{environment:e,topic:t})}return n}}class un extends cn{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove"}))}operation(){return ie.PNRemovePushNotificationEnabledChannelsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class ln extends cn{constructor(e){super(Object.assign(Object.assign({},e),{action:"list"}))}operation(){return ie.PNPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e)}}))}}class hn extends cn{constructor(e){super(Object.assign(Object.assign({},e),{action:"add"}))}operation(){return ie.PNAddPushNotificationEnabledChannelsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class dn extends cn{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove-device"}))}operation(){return ie.PNRemoveAllPushNotificationsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class pn{constructor(e,t){this.sendRequest=t,this.keySet=e}listChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new ln(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new hn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new un(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}deleteDevice(e,t){return i(this,void 0,void 0,(function*(){const n=new dn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}}class gn extends se{constructor(e){var t,n,s,r,i,a;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(i=e.include).customFields)&&void 0!==n||(i.customFields=false),null!==(s=(a=e.include).totalCount)&&void 0!==s||(a.totalCount=false),null!==(r=e.limit)&&void 0!==r||(e.limit=100)}operation(){return ie.PNGetAllChannelMetadataOperation}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";return i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(","),count:`${e.totalCount}`},n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class yn extends se{constructor(e){super({method:K.DELETE}),this.parameters=e}operation(){return ie.PNRemoveChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}`}}class fn extends se{constructor(e){var t,n,s,r,i,a,o,c,u,l,h,d,p,g,y,f,m,b;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(h=e.include).customFields)&&void 0!==n||(h.customFields=false),null!==(s=(d=e.include).totalCount)&&void 0!==s||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(y=e.include).channelFields)&&void 0!==a||(y.channelFields=false),null!==(o=(f=e.include).customChannelFields)&&void 0!==o||(f.customChannelFields=false),null!==(c=(m=e.include).channelStatusField)&&void 0!==c||(m.channelStatusField=false),null!==(u=(b=e.include).channelTypeField)&&void 0!==u||(b.channelTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNGetMembershipsOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=[];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.channelFields&&a.push("channel"),e.channelStatusField&&a.push("channel.status"),e.channelTypeField&&a.push("channel.type"),e.customChannelFields&&a.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class mn extends se{constructor(e){var t,n,s,r,i,a,o,c,u,l,h,d,p,g,y,f,m,b;super({method:K.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(h=e.include).customFields)&&void 0!==n||(h.customFields=false),null!==(s=(d=e.include).totalCount)&&void 0!==s||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(y=e.include).channelFields)&&void 0!==a||(y.channelFields=false),null!==(o=(f=e.include).customChannelFields)&&void 0!==o||(f.customChannelFields=false),null!==(c=(m=e.include).channelStatusField)&&void 0!==c||(m.channelStatusField=false),null!==(u=(b=e.include).channelTypeField)&&void 0!==u||(b.channelTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNSetMembershipsOperation}validate(){const{uuid:e,channels:t}=this.parameters;return e?t&&0!==t.length?void 0:"Channels cannot be empty":"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=["channel.status","channel.type","status"];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.channelFields&&a.push("channel"),e.channelStatusField&&a.push("channel.status"),e.channelTypeField&&a.push("channel.type"),e.customChannelFields&&a.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{channels:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},status:e.status,type:e.type,custom:e.custom}))})}}class bn extends se{constructor(e){var t,n,s,r;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(r=e.include).customFields)&&void 0!==n||(r.customFields=false),null!==(s=e.limit)&&void 0!==s||(e.limit=100)}operation(){return ie.PNGetAllUUIDMetadataOperation}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";return i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(",")},void 0!==e.totalCount?{count:`${e.totalCount}`}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class vn extends se{constructor(e){var t,n,s;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(s=e.include).customFields)&&void 0!==n||(s.customFields=true)}operation(){return ie.PNGetChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}}class wn extends se{constructor(e){var t,n,s;super({method:K.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(s=e.include).customFields)&&void 0!==n||(s.customFields=true)}operation(){return ie.PNSetChannelMetadataOperation}validate(){return this.parameters.channel?this.parameters.data?void 0:"Data cannot be empty":"Channel cannot be empty"}get headers(){return this.parameters.ifMatchesEtag?{"If-Match":this.parameters.ifMatchesEtag}:void 0}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Sn extends se{constructor(e){super({method:K.DELETE}),this.parameters=e,this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNRemoveUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}`}}class En extends se{constructor(e){var t,n,s,r,i,a,o,c,u,l,h,d,p,g,y,f,m,b;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(h=e.include).customFields)&&void 0!==n||(h.customFields=false),null!==(s=(d=e.include).totalCount)&&void 0!==s||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(y=e.include).UUIDFields)&&void 0!==a||(y.UUIDFields=false),null!==(o=(f=e.include).customUUIDFields)&&void 0!==o||(f.customUUIDFields=false),null!==(c=(m=e.include).UUIDStatusField)&&void 0!==c||(m.UUIDStatusField=false),null!==(u=(b=e.include).UUIDTypeField)&&void 0!==u||(b.UUIDTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100)}operation(){return ie.PNSetMembersOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=[];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.UUIDFields&&a.push("uuid"),e.UUIDStatusField&&a.push("uuid.status"),e.UUIDTypeField&&a.push("uuid.type"),e.customUUIDFields&&a.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class On extends se{constructor(e){var t,n,s,r,i,a,o,c,u,l,h,d,p,g,y,f,m,b;super({method:K.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(h=e.include).customFields)&&void 0!==n||(h.customFields=false),null!==(s=(d=e.include).totalCount)&&void 0!==s||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(y=e.include).UUIDFields)&&void 0!==a||(y.UUIDFields=false),null!==(o=(f=e.include).customUUIDFields)&&void 0!==o||(f.customUUIDFields=false),null!==(c=(m=e.include).UUIDStatusField)&&void 0!==c||(m.UUIDStatusField=false),null!==(u=(b=e.include).UUIDTypeField)&&void 0!==u||(b.UUIDTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100)}operation(){return ie.PNSetMembersOperation}validate(){const{channel:e,uuids:t}=this.parameters;return e?t&&0!==t.length?void 0:"UUIDs cannot be empty":"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=["uuid.status","uuid.type","type"];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.UUIDFields&&a.push("uuid"),e.UUIDStatusField&&a.push("uuid.status"),e.UUIDTypeField&&a.push("uuid.type"),e.customUUIDFields&&a.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{uuids:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},status:e.status,type:e.type,custom:e.custom}))})}}class kn extends se{constructor(e){var t,n,s;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(s=e.include).customFields)&&void 0!==n||(s.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNGetUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}`}get queryParameters(){const{include:e}=this.parameters;return{include:["status","type",...e.customFields?["custom"]:[]].join(",")}}}class Cn extends se{constructor(e){var t,n,s;super({method:K.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(s=e.include).customFields)&&void 0!==n||(s.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNSetUUIDMetadataOperation}validate(){return this.parameters.uuid?this.parameters.data?void 0:"Data cannot be empty":"'uuid' cannot be empty"}get headers(){return this.parameters.ifMatchesEtag?{"If-Match":this.parameters.ifMatchesEtag}:void 0}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Nn{constructor(e,t){this.keySet=e.keySet,this.configuration=e,this.sendRequest=t}getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllUUIDMetadata(e,t)}))}_getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const s=new bn(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getUUIDMetadata(e,t)}))}_getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var n;const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),s.userId&&(s.uuid=s.userId),null!==(n=s.uuid)&&void 0!==n||(s.uuid=this.configuration.userId);const r=new kn(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setUUIDMetadata(e,t)}))}_setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var n;e.userId&&(e.uuid=e.userId),null!==(n=e.uuid)&&void 0!==n||(e.uuid=this.configuration.userId);const s=new Cn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeUUIDMetadata(e,t)}))}_removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var n;const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),s.userId&&(s.uuid=s.userId),null!==(n=s.uuid)&&void 0!==n||(s.uuid=this.configuration.userId);const r=new Sn(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllChannelMetadata(e,t)}))}_getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const s=new gn(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getChannelMetadata(e,t)}))}_getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=new vn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setChannelMetadata(e,t)}))}_setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=new wn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeChannelMetadata(e,t)}))}_removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=new yn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const n=new En(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const n=new On(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const n=new On(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getMemberships(e,t){return i(this,void 0,void 0,(function*(){var n;const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),s.userId&&(s.uuid=s.userId),null!==(n=s.uuid)&&void 0!==n||(s.uuid=this.configuration.userId);const r=new fn(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setMemberships(e,t){return i(this,void 0,void 0,(function*(){var n;e.userId&&(e.uuid=e.userId),null!==(n=e.uuid)&&void 0!==n||(e.uuid=this.configuration.userId);const s=new mn(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var n;e.userId&&(e.uuid=e.userId),null!==(n=e.uuid)&&void 0!==n||(e.uuid=this.configuration.userId);const s=new mn(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){var n,s;if("spaceId"in e){const s=e,r={channel:null!==(n=s.spaceId)&&void 0!==n?n:s.channel,filter:s.filter,limit:s.limit,page:s.page,include:Object.assign({},s.include),sort:s.sort?Object.fromEntries(Object.entries(s.sort).map((([e,t])=>[e.replace("user","uuid"),t]))):void 0},i=e=>({status:e.status,data:e.data.map((e=>({user:e.uuid,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getChannelMembers(r,((e,n)=>{t(e,n?i(n):n)})):this.getChannelMembers(r).then(i)}const r=e,i={uuid:null!==(s=r.userId)&&void 0!==s?s:r.uuid,filter:r.filter,limit:r.limit,page:r.page,include:Object.assign({},r.include),sort:r.sort?Object.fromEntries(Object.entries(r.sort).map((([e,t])=>[e.replace("space","channel"),t]))):void 0},a=e=>({status:e.status,data:e.data.map((e=>({space:e.channel,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getMemberships(i,((e,n)=>{t(e,n?a(n):n)})):this.getMemberships(i).then(a)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){var n,s,r,i,a,o;if("spaceId"in e){const i=e,a={channel:null!==(n=i.spaceId)&&void 0!==n?n:i.channel,uuids:null!==(r=null===(s=i.users)||void 0===s?void 0:s.map((e=>"string"==typeof e?e:{id:e.userId,custom:e.custom})))&&void 0!==r?r:i.uuids,limit:0};return t?this.setChannelMembers(a,t):this.setChannelMembers(a)}const c=e,u={uuid:null!==(i=c.userId)&&void 0!==i?i:c.uuid,channels:null!==(o=null===(a=c.spaces)||void 0===a?void 0:a.map((e=>"string"==typeof e?e:{id:e.spaceId,custom:e.custom})))&&void 0!==o?o:c.channels,limit:0};return t?this.setMemberships(u,t):this.setMemberships(u)}))}}class Pn extends se{constructor(){super()}operation(){return ie.PNTimeOperation}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[0]}}))}get path(){return"/time/0"}}class Mn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNDownloadFileOperation}validate(){const{channel:e,id:t,name:n}=this.parameters;return e?t?n?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,crypto:n,cryptography:s,name:r,PubNubFile:i}=this.parameters,a=e.headers["content-type"];let o,c=e.body;return i.supportsEncryptFile&&(t||n)&&(t&&s?c=yield s.decrypt(t,c):!t&&n&&(o=yield n.decryptFile(i.create({data:c,name:r,mimeType:a}),i))),o||i.create({data:c,name:r,mimeType:a})}))}get path(){const{keySet:{subscribeKey:e},channel:t,id:n,name:s}=this.parameters;return`/v1/files/${e}/channels/${$(t)}/files/${n}/${s}`}}class _n{static notificationPayload(e,t){return new ne(e,t)}static generateUUID(){return x.createUUID()}constructor(e){if(this._configuration=e.configuration,this.cryptography=e.cryptography,this.tokenManager=e.tokenManager,this.transport=e.transport,this.crypto=e.crypto,this._objects=new Nn(this._configuration,this.sendRequest.bind(this)),this._channelGroups=new on(this._configuration.keySet,this.sendRequest.bind(this)),this._push=new pn(this._configuration.keySet,this.sendRequest.bind(this)),this.listenerManager=new J,this.eventEmitter=new ue(this.listenerManager),this.subscribeCapable=new Set,this._configuration.enableEventEngine){let e=this._configuration.getHeartbeatInterval();this.presenceState={},e&&(this.presenceEventEngine=new Le({heartbeat:this.heartbeat.bind(this),leave:e=>this.makeUnsubscribe(e,(()=>{})),heartbeatDelay:()=>new Promise(((t,n)=>{e=this._configuration.getHeartbeatInterval(),e?setTimeout(t,1e3*e):n(new d("Heartbeat interval has been reset."))})),retryDelay:e=>new Promise((t=>setTimeout(t,e))),emitStatus:e=>this.listenerManager.announceStatus(e),config:this._configuration,presenceState:this.presenceState})),this.eventEngine=new Et({handshake:this.subscribeHandshake.bind(this),receiveMessages:this.subscribeReceiveMessages.bind(this),delay:e=>new Promise((t=>setTimeout(t,e))),join:this.join.bind(this),leave:this.leave.bind(this),leaveAll:this.leaveAll.bind(this),presenceState:this.presenceState,config:this._configuration,emitMessages:e=>{try{e.forEach((e=>this.eventEmitter.emitEvent(e)))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}},emitStatus:e=>this.listenerManager.announceStatus(e)})}else this.subscriptionManager=new Y(this._configuration,this.listenerManager,this.eventEmitter,this.makeSubscribe.bind(this),this.heartbeat.bind(this),this.makeUnsubscribe.bind(this),this.time.bind(this))}get configuration(){return this._configuration}get _config(){return this.configuration}get authKey(){var e;return null!==(e=this._configuration.authKey)&&void 0!==e?e:void 0}getAuthKey(){return this.authKey}setAuthKey(e){this._configuration.setAuthKey(e)}get userId(){return this._configuration.userId}set userId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}getUserId(){return this._configuration.userId}setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}get filterExpression(){var e;return null!==(e=this._configuration.getFilterExpression())&&void 0!==e?e:void 0}getFilterExpression(){return this.filterExpression}set filterExpression(e){this._configuration.setFilterExpression(e)}setFilterExpression(e){this.filterExpression=e}get cipherKey(){return this._configuration.getCipherKey()}set cipherKey(e){this._configuration.setCipherKey(e)}setCipherKey(e){this.cipherKey=e}set heartbeatInterval(e){this._configuration.setHeartbeatInterval(e)}setHeartbeatInterval(e){this.heartbeatInterval=e}getVersion(){return this._configuration.getVersion()}_addPnsdkSuffix(e,t){this._configuration._addPnsdkSuffix(e,t)}getUUID(){return this.userId}setUUID(e){this.userId=e}get customEncrypt(){return this._configuration.getCustomEncrypt()}get customDecrypt(){return this._configuration.getCustomDecrypt()}channel(e){return new en(e,this.eventEmitter,this)}channelGroup(e){return new Yt(e,this.eventEmitter,this)}channelMetadata(e){return new Qt(e,this.eventEmitter,this)}userMetadata(e){return new Zt(e,this.eventEmitter,this)}subscriptionSet(e){return new Jt(Object.assign(Object.assign({},e),{eventEmitter:this.eventEmitter,pubnub:this}))}sendRequest(e,t){return i(this,void 0,void 0,(function*(){const n=e.validate();if(n){if(t)return t(g(n),null);throw new d("Validation failed, check status for details",g(n))}const s=e.request(),r=e.operation();s.formData&&s.formData.length>0||r===ie.PNDownloadFileOperation?s.timeout=this._configuration.getFileTimeout():r===ie.PNSubscribeOperation||r===ie.PNReceiveMessagesOperation?s.timeout=this._configuration.getSubscribeTimeout():s.timeout=this._configuration.getTransactionTimeout();const i={error:!1,operation:r,category:h.PNAcknowledgmentCategory,statusCode:0},[a,o]=this.transport.makeSendable(s);return e.cancellationController=o||null,a.then((t=>{if(i.statusCode=t.status,200!==t.status&&204!==t.status){const e=_n.decoder.decode(t.body),n=t.headers["content-type"];if(n||-1!==n.indexOf("javascript")||-1!==n.indexOf("json")){const t=JSON.parse(e);"object"==typeof t&&"error"in t&&t.error&&"object"==typeof t.error&&(i.errorData=t.error)}else i.responseText=e}return e.parse(t)})).then((e=>t?t(i,e):e)).catch((e=>{const n=e instanceof j?e:j.create(e);if(t)return t(n.toStatus(r),null);throw n.toPubNubError(r,"REST API request processing error, check status for details")}))}))}destroy(e){var t;null===(t=this.subscribeCapable)||void 0===t||t.clear(),this.subscriptionManager?(this.subscriptionManager.unsubscribeAll(e),this.subscriptionManager.disconnect()):this.eventEngine&&this.eventEngine.dispose()}stop(){this.destroy()}addListener(e){this.listenerManager.addListener(e)}removeListener(e){this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners()}publish(e,t){return i(this,void 0,void 0,(function*(){{const n=new Ot(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}signal(e,t){return i(this,void 0,void 0,(function*(){{const n=new kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}fire(e,t){return i(this,void 0,void 0,(function*(){return null!=t||(t=()=>{}),this.publish(Object.assign(Object.assign({},e),{replicate:!1,storeInHistory:!1}),t)}))}getSubscribedChannels(){return this.subscriptionManager?this.subscriptionManager.subscribedChannels:this.eventEngine?this.eventEngine.getSubscribedChannels():[]}getSubscribedChannelGroups(){return this.subscriptionManager?this.subscriptionManager.subscribedChannelGroups:this.eventEngine?this.eventEngine.getSubscribedChannelGroups():[]}registerSubscribeCapable(e){this.subscribeCapable&&!this.subscribeCapable.has(e)&&this.subscribeCapable.add(e)}unregisterSubscribeCapable(e){this.subscribeCapable&&this.subscribeCapable.has(e)&&this.subscribeCapable.delete(e)}getSubscribeCapableEntities(){{const e={channels:[],channelGroups:[]};if(!this.subscribeCapable)return e;for(const t of this.subscribeCapable)e.channelGroups.push(...t.channelGroups),e.channels.push(...t.channels);return e}}subscribe(e){this.subscriptionManager?this.subscriptionManager.subscribe(e):this.eventEngine&&this.eventEngine.subscribe(e)}makeSubscribe(e,t){{const n=new ce(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));if(this.sendRequest(n,((e,s)=>{var r;this.subscriptionManager&&(null===(r=this.subscriptionManager.abort)||void 0===r?void 0:r.identifier)===n.requestIdentifier&&(this.subscriptionManager.abort=null),t(e,s)})),this.subscriptionManager){const e=()=>n.abort("Cancel long-poll subscribe request");e.identifier=n.requestIdentifier,this.subscriptionManager.abort=e}}}unsubscribe(e){this.subscriptionManager?this.subscriptionManager.unsubscribe(e):this.eventEngine&&this.eventEngine.unsubscribe(e)}makeUnsubscribe(e,t){this.sendRequest(new At(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),t)}unsubscribeAll(){var e;null===(e=this.subscribeCapable)||void 0===e||e.clear(),this.subscriptionManager?this.subscriptionManager.unsubscribeAll():this.eventEngine&&this.eventEngine.unsubscribeAll()}disconnect(){this.subscriptionManager?this.subscriptionManager.disconnect():this.eventEngine&&this.eventEngine.disconnect()}reconnect(e){this.subscriptionManager?this.subscriptionManager.reconnect():this.eventEngine&&this.eventEngine.reconnect(null!=e?e:{})}subscribeHandshake(e){return i(this,void 0,void 0,(function*(){{const t=new Nt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),n=e.abortSignal.subscribe((e=>{t.abort("Cancel subscribe handshake request")}));return this.sendRequest(t).then((e=>(n(),e.cursor)))}}))}subscribeReceiveMessages(e){return i(this,void 0,void 0,(function*(){{const t=new Ct(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),n=e.abortSignal.subscribe((e=>{t.abort("Cancel long-poll subscribe request")}));return this.sendRequest(t).then((e=>(n(),e)))}}))}getMessageActions(e,t){return i(this,void 0,void 0,(function*(){{const n=new Dt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}addMessageAction(e,t){return i(this,void 0,void 0,(function*(){{const n=new qt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}removeMessageAction(e,t){return i(this,void 0,void 0,(function*(){{const n=new Gt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}fetchMessages(e,t){return i(this,void 0,void 0,(function*(){{const n=new xt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}deleteMessages(e,t){return i(this,void 0,void 0,(function*(){{const n=new Ft(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}messageCounts(e,t){return i(this,void 0,void 0,(function*(){{const n=new Tt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}history(e,t){return i(this,void 0,void 0,(function*(){{const n=new Rt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}hereNow(e,t){return i(this,void 0,void 0,(function*(){{const n=new It(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}whereNow(e,t){return i(this,void 0,void 0,(function*(){var n;{const s=new jt({uuid:null!==(n=e.uuid)&&void 0!==n?n:this._configuration.userId,keySet:this._configuration.keySet});return t?this.sendRequest(s,t):this.sendRequest(s)}}))}getState(e,t){return i(this,void 0,void 0,(function*(){var n;{const s=new Pt(Object.assign(Object.assign({},e),{uuid:null!==(n=e.uuid)&&void 0!==n?n:this._configuration.userId,keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}setState(e,t){return i(this,void 0,void 0,(function*(){var n,s;{const{keySet:r,userId:i}=this._configuration,a=this._configuration.getPresenceTimeout();let o;if(this._configuration.enableEventEngine&&this.presenceState){const t=this.presenceState;null===(n=e.channels)||void 0===n||n.forEach((n=>t[n]=e.state)),"channelGroups"in e&&(null===(s=e.channelGroups)||void 0===s||s.forEach((n=>t[n]=e.state)))}return o="withHeartbeat"in e?new _t(Object.assign(Object.assign({},e),{keySet:r,heartbeat:a})):new Mt(Object.assign(Object.assign({},e),{keySet:r,uuid:i})),this.subscriptionManager&&this.subscriptionManager.setState(e),t?this.sendRequest(o,t):this.sendRequest(o)}}))}presence(e){var t;null===(t=this.subscriptionManager)||void 0===t||t.changePresence(e)}heartbeat(e,t){return i(this,void 0,void 0,(function*(){{const n=new _t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}join(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.join(e)}leave(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.leave(e)}leaveAll(){var e;null===(e=this.presenceEventEngine)||void 0===e||e.leaveAll()}grantToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Token error: PAM module disabled")}))}revokeToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Revoke Token error: PAM module disabled")}))}get token(){return this.tokenManager&&this.tokenManager.getToken()}getToken(){return this.token}set token(e){this.tokenManager&&this.tokenManager.setToken(e)}setToken(e){this.token=e}parseToken(e){return this.tokenManager&&this.tokenManager.parseToken(e)}grant(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant error: PAM module disabled")}))}audit(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Permissions error: PAM module disabled")}))}get objects(){return this._objects}fetchUsers(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllUUIDMetadata(e,t)}))}fetchUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getUUIDMetadata(e,t)}))}createUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}updateUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}removeUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeUUIDMetadata(e,t)}))}fetchSpaces(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllChannelMetadata(e,t)}))}fetchSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getChannelMetadata(e,t)}))}createSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}updateSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}removeSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeChannelMetadata(e,t)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.fetchMemberships(e,t)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}updateMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var n,s,r;{if("spaceId"in e){const r=e,i={channel:null!==(n=r.spaceId)&&void 0!==n?n:r.channel,uuids:null!==(s=r.userIds)&&void 0!==s?s:r.uuids,limit:0};return t?this.objects.removeChannelMembers(i,t):this.objects.removeChannelMembers(i)}const i=e,a={uuid:i.userId,channels:null!==(r=i.spaceIds)&&void 0!==r?r:i.channels,limit:0};return t?this.objects.removeMemberships(a,t):this.objects.removeMemberships(a)}}))}get channelGroups(){return this._channelGroups}get push(){return this._push}sendFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const n=new zt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,fileUploadPublishRetryLimit:this._configuration.fileUploadPublishRetryLimit,file:e.file,sendRequest:this.sendRequest.bind(this),publishFile:this.publishFile.bind(this),crypto:this._configuration.getCryptoModule(),cryptography:this.cryptography?this.cryptography:void 0})),s={error:!1,operation:ie.PNPublishFileOperation,category:h.PNAcknowledgmentCategory,statusCode:0};return n.process().then((e=>(s.statusCode=e.status,t?t(s,e):e))).catch((e=>{let n;throw e instanceof d?n=e.status:e instanceof j&&(n=e.toStatus(s.operation)),t&&n&&t(n,null),new d("REST API request processing error, check status for details",n)}))}}))}publishFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const n=new Kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}listFiles(e,t){return i(this,void 0,void 0,(function*(){{const n=new Bt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}getFileUrl(e){var t;{const n=this.transport.request(new $t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})).request()),s=null!==(t=n.queryParameters)&&void 0!==t?t:{},r=Object.keys(s).map((e=>{const t=s[e];return Array.isArray(t)?t.map((t=>`${e}=${$(t)}`)).join("&"):`${e}=${$(t)}`})).join("&");return`${n.origin}${n.path}?${r}`}}downloadFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const n=new Mn(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,cryptography:this.cryptography?this.cryptography:void 0,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(n,t):yield this.sendRequest(n)}}))}deleteFile(e,t){return i(this,void 0,void 0,(function*(){{const n=new Lt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}time(e){return i(this,void 0,void 0,(function*(){const t=new Pn;return e?this.sendRequest(t,e):this.sendRequest(t)}))}encrypt(e,t){const n=this._configuration.getCryptoModule();if(!t&&n&&"string"==typeof e){const t=n.encrypt(e);return"string"==typeof t?t:u(t)}if(!this.crypto)throw new Error("Encryption error: cypher key not set");return this.crypto.encrypt(e,t)}decrypt(e,t){const n=this._configuration.getCryptoModule();if(!t&&n){const t=n.decrypt(e);return t instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(t)):t}if(!this.crypto)throw new Error("Decryption error: cypher key not set");return this.crypto.decrypt(e,t)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var n;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File encryption error. File constructor not configured.");if("string"!=typeof e&&!this._configuration.getCryptoModule())throw new Error("File encryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File encryption error. File encryption not available");return this.cryptography.encryptFile(e,t,this._configuration.PubNubFile)}return null===(n=this._configuration.getCryptoModule())||void 0===n?void 0:n.encryptFile(t,this._configuration.PubNubFile)}))}decryptFile(e,t){return i(this,void 0,void 0,(function*(){var n;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File decryption error. File constructor not configured.");if("string"==typeof e&&!this._configuration.getCryptoModule())throw new Error("File decryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File decryption error. File decryption not available");return this.cryptography.decryptFile(e,t,this._configuration.PubNubFile)}return null===(n=this._configuration.getCryptoModule())||void 0===n?void 0:n.decryptFile(t,this._configuration.PubNubFile)}))}}_n.decoder=new TextDecoder,_n.OPERATIONS=ie,_n.CATEGORIES=h,_n.ExponentialRetryPolicy=Be.ExponentialRetryPolicy,_n.LinearRetryPolicy=Be.LinearRetryPolicy;class An{constructor(e,t){this.decode=e,this.base64ToBinary=t}decodeToken(e){let t="";e.length%4==3?t="=":e.length%4==2&&(t="==");const n=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,s=this.decode(this.base64ToBinary(n));return"object"==typeof s?s:void 0}}class jn extends _n{constructor(e){var t;const n=T(e),r=Object.assign(Object.assign({},n),{sdkFamily:"Web"});r.PubNubFile=o;const i=D(r,(e=>{if(e.cipherKey)return new M({default:new P(Object.assign({},e)),cryptors:[new O({cipherKey:e.cipherKey})]})}));let a,u,l;a=new G(new An((e=>F(s.decode(e))),c)),(i.getCipherKey()||i.secretKey)&&(u=new C({secretKey:i.secretKey,cipherKey:i.getCipherKey(),useRandomIVs:i.getUseRandomIVs(),customEncrypt:i.getCustomEncrypt(),customDecrypt:i.getCustomDecrypt()})),l=new N;let h=new W(r.transport,i.keepAlive,i.logVerbosity);n.subscriptionWorkerUrl&&(h=new I({clientIdentifier:i._instanceId,subscriptionKey:i.subscribeKey,userId:i.getUserId(),workerUrl:n.subscriptionWorkerUrl,sdkVersion:i.getVersion(),heartbeatInterval:i.getHeartbeatInterval(),logVerbosity:i.logVerbosity,workerLogVerbosity:r.subscriptionWorkerLogVerbosity,transport:h}));super({configuration:i,transport:new z({clientConfiguration:i,tokenManager:a,transport:h}),cryptography:l,tokenManager:a,crypto:u}),(null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t)&&(window.addEventListener("offline",(()=>{this.networkDownDetected()})),window.addEventListener("online",(()=>{this.networkUpDetected()})))}networkDownDetected(){this.listenerManager.announceNetworkDown(),this._configuration.restore?this.disconnect():this.destroy(!0)}networkUpDetected(){this.listenerManager.announceNetworkUp(),this.reconnect()}}return jn.CryptoModule=M,jn})); +/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */!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 s(){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 r(e,t){var s=n[t||"all"];return s&&s.test(e)||!1}s.isUUID=r,s.VERSION=t,e.uuid=s,e.isUUID=r}(t),null!==e&&(e.exports=t.uuid)}(R,R.exports);var U=t(R.exports),x={createUUID:()=>U.uuid?U.uuid():U()};const D=(e,t)=>{var n,s,r;null===(n=e.retryConfiguration)||void 0===n||n.validate(),null!==(s=e.useRandomIVs)&&void 0!==s||(e.useRandomIVs=true),e.origin=q(null!==(r=e.ssl)&&void 0!==r&&r,e.origin);const i=e.cryptoModule;i&&delete e.cryptoModule;const a=Object.assign(Object.assign({},e),{_pnsdkSuffix:{},_instanceId:`pn-${x.createUUID()}`,_cryptoModule:void 0,_cipherKey:void 0,_setupCryptoModule:t,get instanceId(){if(this.useInstanceId)return this._instanceId},getInstanceId(){if(this.useInstanceId)return this._instanceId},getUserId(){return this.userId},setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this.userId=e},getAuthKey(){return this.authKey},setAuthKey(e){this.authKey=e},getFilterExpression(){return this.filterExpression},setFilterExpression(e){this.filterExpression=e},getCipherKey(){return this._cipherKey},setCipherKey(t){this._cipherKey=t,t||!this._cryptoModule?t&&this._setupCryptoModule&&(this._cryptoModule=this._setupCryptoModule({cipherKey:t,useRandomIVs:e.useRandomIVs,customEncrypt:this.getCustomEncrypt(),customDecrypt:this.getCustomDecrypt()})):this._cryptoModule=void 0},getCryptoModule(){return this._cryptoModule},getUseRandomIVs:()=>e.useRandomIVs,setPresenceTimeout(e){this.heartbeatInterval=e/2-1,this.presenceTimeout=e},getPresenceTimeout(){return this.presenceTimeout},getHeartbeatInterval(){return this.heartbeatInterval},setHeartbeatInterval(e){this.heartbeatInterval=e},getTransactionTimeout(){return this.transactionalRequestTimeout},getSubscribeTimeout(){return this.subscribeRequestTimeout},getFileTimeout(){return this.fileRequestTimeout},get PubNubFile(){return e.PubNubFile},get version(){return"8.9.0"},getVersion(){return this.version},_addPnsdkSuffix(e,t){this._pnsdkSuffix[e]=`${t}`},_getPnsdkSuffix(e){const t=Object.values(this._pnsdkSuffix).join(e);return t.length>0?e+t:""},getUUID(){return this.getUserId()},setUUID(e){this.setUserId(e)},getCustomEncrypt:()=>e.customEncrypt,getCustomDecrypt:()=>e.customDecrypt});return e.cipherKey?a.setCipherKey(e.cipherKey):i&&(a._cryptoModule=i),a},q=(e,t)=>{const n=e?"https://":"http://";return"string"==typeof t?`${n}${t}`:`${n}${t[Math.floor(Math.random()*t.length)]}`};class G{constructor(e){this.cbor=e}setToken(e){e&&e.length>0?this.token=e:this.token=void 0}getToken(){return this.token}parseToken(e){const t=this.cbor.decodeToken(e);if(void 0!==t){const e=t.res.uuid?Object.keys(t.res.uuid):[],n=Object.keys(t.res.chan),s=Object.keys(t.res.grp),r=t.pat.uuid?Object.keys(t.pat.uuid):[],i=Object.keys(t.pat.chan),a=Object.keys(t.pat.grp),o={version:t.v,timestamp:t.t,ttl:t.ttl,authorized_uuid:t.uuid,signature:t.sig},c=e.length>0,u=n.length>0,l=s.length>0;if(c||u||l){if(o.resources={},c){const n=o.resources.uuids={};e.forEach((e=>n[e]=this.extractPermissions(t.res.uuid[e])))}if(u){const e=o.resources.channels={};n.forEach((n=>e[n]=this.extractPermissions(t.res.chan[n])))}if(l){const e=o.resources.groups={};s.forEach((n=>e[n]=this.extractPermissions(t.res.grp[n])))}}const h=r.length>0,d=i.length>0,p=a.length>0;if(h||d||p){if(o.patterns={},h){const e=o.patterns.uuids={};r.forEach((n=>e[n]=this.extractPermissions(t.pat.uuid[n])))}if(d){const e=o.patterns.channels={};i.forEach((n=>e[n]=this.extractPermissions(t.pat.chan[n])))}if(p){const e=o.patterns.groups={};a.forEach((n=>e[n]=this.extractPermissions(t.pat.grp[n])))}}return t.meta&&Object.keys(t.meta).length>0&&(o.meta=t.meta),o}}extractPermissions(e){const t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128&~e||(t.join=!0),64&~e||(t.update=!0),32&~e||(t.get=!0),8&~e||(t.delete=!0),4&~e||(t.manage=!0),2&~e||(t.write=!0),1&~e||(t.read=!0),t}}var K;!function(e){e.GET="GET",e.POST="POST",e.PATCH="PATCH",e.DELETE="DELETE",e.LOCAL="LOCAL"}(K||(K={}));const $=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),L=(e,t)=>{const n=e.map((e=>$(e)));return n.length?n.join(","):null!=t?t:""},B=(e,t)=>{const n=Object.fromEntries(t.map((e=>[e,!1])));return e.filter((e=>!(t.includes(e)&&!n[e])||(n[e]=!0,!1)))},H=(e,t)=>[...e].filter((n=>t.includes(n)&&e.indexOf(n)===e.lastIndexOf(n)&&t.indexOf(n)===t.lastIndexOf(n)));class V{constructor(e,t,n){this.publishKey=e,this.secretKey=t,this.hasher=n}signature(e){const t=e.path.startsWith("/publish")?K.GET:e.method;let n=`${t}\n${this.publishKey}\n${e.path}\n${this.queryParameters(e.queryParameters)}\n`;if(t===K.POST||t===K.PATCH){const t=e.body;let s;t&&t instanceof ArrayBuffer?s=V.textDecoder.decode(t):t&&"object"!=typeof t&&(s=t),s&&(n+=s)}return`v2.${this.hasher(n,this.secretKey)}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}queryParameters(e){return Object.keys(e).sort().map((t=>{const n=e[t];return Array.isArray(n)?n.sort().map((e=>`${t}=${$(e)}`)).join("&"):`${t}=${$(n)}`})).join("&")}}V.textDecoder=new TextDecoder("utf-8");class z{constructor(e){this.configuration=e;const{clientConfiguration:{keySet:t},shaHMAC:n}=e;t.secretKey&&n&&(this.signatureGenerator=new V(t.publishKey,t.secretKey,n))}makeSendable(e){return this.configuration.transport.makeSendable(this.request(e))}request(e){var t;const{clientConfiguration:n}=this.configuration;return(e=this.configuration.transport.request(e)).queryParameters||(e.queryParameters={}),n.useInstanceId&&(e.queryParameters.instanceid=n.getInstanceId()),e.queryParameters.uuid||(e.queryParameters.uuid=n.userId),n.useRequestId&&(e.queryParameters.requestid=e.identifier),e.queryParameters.pnsdk=this.generatePNSDK(),null!==(t=e.origin)&&void 0!==t||(e.origin=n.origin),this.authenticateRequest(e),this.signRequest(e),e}authenticateRequest(e){var t;if(e.path.startsWith("/v2/auth/")||e.path.startsWith("/v3/pam/")||e.path.startsWith("/time"))return;const{clientConfiguration:n,tokenManager:s}=this.configuration,r=null!==(t=s&&s.getToken())&&void 0!==t?t:n.authKey;r&&(e.queryParameters.auth=r)}signRequest(e){this.signatureGenerator&&!e.path.startsWith("/time")&&(e.queryParameters.timestamp=String(Math.floor((new Date).getTime()/1e3)),e.queryParameters.signature=this.signatureGenerator.signature(e))}generatePNSDK(){const{clientConfiguration:e}=this.configuration;if(e.sdkName)return e.sdkName;let t=`PubNub-JS-${e.sdkFamily}`;e.partnerId&&(t+=`-${e.partnerId}`),t+=`/${e.getVersion()}`;const n=e._getPnsdkSuffix(" ");return n.length>0&&(t+=n),t}}class W{constructor(e="fetch",t=!1,n=!1){if(this.transport=e,this.keepAlive=t,this.logVerbosity=n,"fetch"!==e||window&&window.fetch||(this.transport="xhr"),"fetch"===this.transport&&(W.originalFetch=fetch.bind(window),this.isFetchMonkeyPatched())){if(W.originalFetch=W.getOriginalFetch(),!n)return;console.warn("[PubNub] Native Web Fetch API 'fetch' function monkey patched."),this.isFetchMonkeyPatched(W.originalFetch)?console.warn("[PubNub] Unable receive native Web Fetch API. There can be issues with subscribe long-poll cancellation"):console.info("[PubNub] Use native Web Fetch API 'fetch' implementation from iframe as APM workaround.")}}makeSendable(e){const t=new AbortController,n={abortController:t,abort:e=>!t.signal.aborted&&t.abort(e)};return[this.webTransportRequestFromTransportRequest(e).then((t=>{const s=(new Date).getTime();return this.logRequestProcessProgress(t,e.body),this.sendRequest(t,n).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>{const n=e[1].byteLength>0?e[1]:void 0,{status:r,headers:i}=e[0],a={};i.forEach(((e,t)=>a[t]=e.toLowerCase()));const o={status:r,url:t.url,headers:a,body:n};if(r>=400)throw j.create(o);return this.logRequestProcessProgress(t,void 0,(new Date).getTime()-s,n),o})).catch((e=>{let t=e;if("string"==typeof e){const n=e.toLowerCase();n.includes("timeout")||!n.includes("cancel")?t=new Error(e):n.includes("cancel")&&(t=new DOMException("Aborted","AbortError"))}throw j.create(t)}))})),n]}request(e){return e}sendRequest(e,t){return i(this,void 0,void 0,(function*(){return"fetch"===this.transport?this.sendFetchRequest(e,t):this.sendXHRRequest(e,t)}))}sendFetchRequest(e,t){return i(this,void 0,void 0,(function*(){let n;const s=new Promise(((s,r)=>{n=setTimeout((()=>{clearTimeout(n),r(new Error("Request timeout")),t.abort("Cancel because of timeout")}),1e3*e.timeout)})),r=new Request(e.url,{method:e.method,headers:e.headers,redirect:"follow",body:e.body});return Promise.race([W.originalFetch(r,{signal:t.abortController.signal,credentials:"omit",cache:"no-cache"}).then((e=>(n&&clearTimeout(n),e))),s])}))}sendXHRRequest(e,t){return i(this,void 0,void 0,(function*(){return new Promise(((n,s)=>{var r;const i=new XMLHttpRequest;i.open(e.method,e.url,!0),i.responseType="arraybuffer",i.timeout=1e3*e.timeout,t.abortController.signal.onabort=()=>{i.readyState!=XMLHttpRequest.DONE&&i.readyState!=XMLHttpRequest.UNSENT&&i.abort()},Object.entries(null!==(r=e.headers)&&void 0!==r?r:{}).forEach((([e,t])=>i.setRequestHeader(e,t))),i.onabort=()=>s(new Error("Aborted")),i.ontimeout=()=>s(new Error("Request timeout")),i.onerror=()=>s(new Error("Request timeout")),i.onload=()=>{const e=new Headers;i.getAllResponseHeaders().split("\r\n").forEach((t=>{const[n,s]=t.split(": ");n.length>1&&s.length>1&&e.append(n,s)})),n(new Response(i.response,{status:i.status,headers:e,statusText:i.statusText}))},i.send(e.body)}))}))}webTransportRequestFromTransportRequest(e){return i(this,void 0,void 0,(function*(){let t,n=e.path;if(e.formData&&e.formData.length>0){e.queryParameters={};const n=e.body,s=new FormData;for(const{key:t,value:n}of e.formData)s.append(t,n);try{const e=yield n.toArrayBuffer();s.append("file",new Blob([e],{type:"application/octet-stream"}),n.name)}catch(e){try{const e=yield n.toFileUri();s.append("file",e,n.name)}catch(e){}}t=s}else e.body&&("string"==typeof e.body||e.body instanceof ArrayBuffer)&&(t=e.body);var s;return e.queryParameters&&0!==Object.keys(e.queryParameters).length&&(n=`${n}?${s=e.queryParameters,Object.keys(s).map((e=>{const t=s[e];return Array.isArray(t)?t.map((t=>`${e}=${$(t)}`)).join("&"):`${e}=${$(t)}`})).join("&")}`),{url:`${e.origin}${n}`,method:e.method,headers:e.headers,timeout:e.timeout,body:t}}))}logRequestProcessProgress(e,t,n,s){if(!this.logVerbosity)return;const{protocol:r,host:i,pathname:a,search:o}=new URL(e.url),c=(new Date).toISOString();if(n){let e=`[${c} / ${n}]\n${r}//${i}${a}\n${o}`;s&&(e+=`\n\n${W.decoder.decode(s)}`),console.log(">>>>>>"),console.log(e),console.log("-----")}else{let e=`[${c}]\n${r}//${i}${a}\n${o}`;t&&("string"==typeof t||t instanceof ArrayBuffer)&&(e+="string"==typeof t?`\n\n${t}`:`\n\n${W.decoder.decode(t)}`),console.log("<<<<<"),console.log(e),console.log("-----")}}isFetchMonkeyPatched(e){return!(null!=e?e:fetch).toString().includes("[native code]")&&"fetch"!==fetch.name}static getOriginalFetch(){let e=document.querySelector('iframe[name="pubnub-context-unpatched-fetch"]');return e||(e=document.createElement("iframe"),e.style.display="none",e.name="pubnub-context-unpatched-fetch",e.src="about:blank",document.body.appendChild(e)),e.contentWindow?e.contentWindow.fetch.bind(e.contentWindow):fetch}}W.decoder=new TextDecoder;class J{constructor(){this.listeners=[]}addListener(e){this.listeners.includes(e)||this.listeners.push(e)}removeListener(e){this.listeners=this.listeners.filter((t=>t!==e))}removeAllListeners(){this.listeners=[]}announceStatus(e){this.listeners.forEach((t=>{t.status&&t.status(e)}))}announcePresence(e){this.listeners.forEach((t=>{t.presence&&t.presence(e)}))}announceMessage(e){this.listeners.forEach((t=>{t.message&&t.message(e)}))}announceSignal(e){this.listeners.forEach((t=>{t.signal&&t.signal(e)}))}announceMessageAction(e){this.listeners.forEach((t=>{t.messageAction&&t.messageAction(e)}))}announceFile(e){this.listeners.forEach((t=>{t.file&&t.file(e)}))}announceObjects(e){this.listeners.forEach((t=>{t.objects&&t.objects(e)}))}announceNetworkUp(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkUpCategory})}))}announceNetworkDown(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkDownCategory})}))}announceUser(e){this.listeners.forEach((t=>{t.user&&t.user(e)}))}announceSpace(e){this.listeners.forEach((t=>{t.space&&t.space(e)}))}announceMembership(e){this.listeners.forEach((t=>{t.membership&&t.membership(e)}))}}class X{constructor(e){this.time=e}onReconnect(e){this.callback=e}startPolling(){this.timeTimer=setInterval((()=>this.callTime()),3e3)}stopPolling(){this.timeTimer&&clearInterval(this.timeTimer),this.timeTimer=null}callTime(){this.time((e=>{e.error||(this.stopPolling(),this.callback&&this.callback())}))}}class Q{constructor({maximumCacheSize:e}){this.maximumCacheSize=e,this.hashHistory=[]}getKey(e){var t;return`${e.timetoken}-${this.hashCode(JSON.stringify(null!==(t=e.message)&&void 0!==t?t:"")).toString()}`}isDuplicate(e){return this.hashHistory.includes(this.getKey(e))}addEntry(e){this.hashHistory.length>=this.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}clearHistory(){this.hashHistory=[]}hashCode(e){let t=0;if(0===e.length)return t;for(let n=0;n{this.pendingChannelSubscriptions.add(e),this.channels[e]={},r&&(this.presenceChannels[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannels[e]={})})),null==n||n.forEach((e=>{this.pendingChannelGroupSubscriptions.add(e),this.channelGroups[e]={},r&&(this.presenceChannelGroups[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannelGroups[e]={})})),this.subscriptionStatusAnnounced=!1,this.reconnect()}unsubscribe(e,t){let{channels:n,channelGroups:s}=e;const i=new Set,a=new Set;null==n||n.forEach((e=>{e in this.channels&&(delete this.channels[e],a.add(e),e in this.heartbeatChannels&&delete this.heartbeatChannels[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannels&&(delete this.presenceChannels[e],a.add(e))})),null==s||s.forEach((e=>{e in this.channelGroups&&(delete this.channelGroups[e],i.add(e),e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannelGroups&&(delete this.presenceChannelGroups[e],i.add(e))})),0===a.size&&0===i.size||(!1!==this.configuration.suppressLeaveEvents||t||(s=Array.from(i),n=Array.from(a),this.leaveCall({channels:n,channelGroups:s},(e=>{const{error:t}=e,i=r(e,["error"]);let a;t&&(e.errorData&&"object"==typeof e.errorData&&"message"in e.errorData&&"string"==typeof e.errorData.message?a=e.errorData.message:"message"in e&&"string"==typeof e.message&&(a=e.message)),this.listenerManager.announceStatus(Object.assign(Object.assign({},i),{error:null!=a&&a,affectedChannels:n,affectedChannelGroups:s,currentTimetoken:this.currentTimetoken,lastTimetoken:this.lastTimetoken}))}))),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(!0))}unsubscribeAll(e){this.unsubscribe({channels:this.subscribedChannels,channelGroups:this.subscribedChannelGroups},e)}startSubscribeLoop(){this.stopSubscribeLoop();const e=[...Object.keys(this.channelGroups)],t=[...Object.keys(this.channels)];Object.keys(this.presenceChannelGroups).forEach((t=>e.push(`${t}-pnpres`))),Object.keys(this.presenceChannels).forEach((e=>t.push(`${e}-pnpres`))),0===t.length&&0===e.length||this.subscribeCall({channels:t,channelGroups:e,state:this.presenceState,heartbeat:this.configuration.getPresenceTimeout(),timetoken:this.currentTimetoken,region:null!==this.region?this.region:void 0,filterExpression:this.configuration.filterExpression},((e,t)=>{this.processSubscribeResponse(e,t)}))}stopSubscribeLoop(){this._subscribeAbort&&(this._subscribeAbort(),this._subscribeAbort=null)}processSubscribeResponse(e,t){if(e.error){if("object"==typeof e.errorData&&"name"in e.errorData&&"AbortError"===e.errorData.name||e.category===h.PNCancelledCategory)return;if(e.category===h.PNTimeoutCategory)this.startSubscribeLoop();else if(e.category===h.PNNetworkIssuesCategory)this.disconnect(),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.listenerManager.announceNetworkDown()),this.reconnectionManager.onReconnect((()=>{this.configuration.autoNetworkDetection&&!this.isOnline&&(this.isOnline=!0,this.listenerManager.announceNetworkUp()),this.reconnect(),this.subscriptionStatusAnnounced=!0;const t={category:h.PNReconnectedCategory,operation:e.operation,lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.listenerManager.announceStatus(t)})),this.reconnectionManager.startPolling(),this.listenerManager.announceStatus(e);else if(e.category===h.PNBadRequestCategory||e.category==h.PNMalformedResponseCategory){const t=this.isOnline?h.PNDisconnectedUnexpectedlyCategory:e.category;this.isOnline=!1,this.disconnect(),this.listenerManager.announceStatus(Object.assign(Object.assign({},e),{category:t}))}else this.listenerManager.announceStatus(e);return}if(this.storedTimetoken?(this.currentTimetoken=this.storedTimetoken,this.storedTimetoken=null):(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=t.cursor.timetoken),!this.subscriptionStatusAnnounced){const t={category:h.PNConnectedCategory,operation:e.operation,affectedChannels:Array.from(this.pendingChannelSubscriptions),subscribedChannels:this.subscribedChannels,affectedChannelGroups:Array.from(this.pendingChannelGroupSubscriptions),lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.subscriptionStatusAnnounced=!0,this.listenerManager.announceStatus(t),this.pendingChannelGroupSubscriptions.clear(),this.pendingChannelSubscriptions.clear()}const{messages:n}=t,{requestMessageCountThreshold:s,dedupeOnSubscribe:r}=this.configuration;s&&n.length>=s&&this.listenerManager.announceStatus({category:h.PNRequestMessageCountExceededCategory,operation:e.operation});try{n.forEach((e=>{if(r&&"message"in e.data&&"timetoken"in e.data){if(this.dedupingManager.isDuplicate(e.data))return;this.dedupingManager.addEntry(e.data)}this.eventEmitter.emitEvent(e)}))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}this.region=t.cursor.region,this.startSubscribeLoop()}setState(e){const{state:t,channels:n,channelGroups:s}=e;null==n||n.forEach((e=>e in this.channels&&(this.presenceState[e]=t))),null==s||s.forEach((e=>e in this.channelGroups&&(this.presenceState[e]=t)))}changePresence(e){const{connected:t,channels:n,channelGroups:s}=e;t?(null==n||n.forEach((e=>this.heartbeatChannels[e]={})),null==s||s.forEach((e=>this.heartbeatChannelGroups[e]={}))):(null==n||n.forEach((e=>{e in this.heartbeatChannels&&delete this.heartbeatChannels[e]})),null==s||s.forEach((e=>{e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]})),!1===this.configuration.suppressLeaveEvents&&this.leaveCall({channels:n,channelGroups:s},(e=>this.listenerManager.announceStatus(e)))),this.reconnect()}startHeartbeatTimer(){this.stopHeartbeatTimer();const e=this.configuration.getHeartbeatInterval();e&&0!==e&&(this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>this.sendHeartbeat()),1e3*e))}stopHeartbeatTimer(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}sendHeartbeat(){const e=Object.keys(this.heartbeatChannelGroups),t=Object.keys(this.heartbeatChannels);0===t.length&&0===e.length||this.heartbeatCall({channels:t,channelGroups:e,heartbeat:this.configuration.getPresenceTimeout(),state:this.presenceState},(e=>{e.error&&this.configuration.announceFailedHeartbeats&&this.listenerManager.announceStatus(e),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.disconnect(),this.listenerManager.announceNetworkDown(),this.reconnect()),!e.error&&this.configuration.announceSuccessfulHeartbeats&&this.listenerManager.announceStatus(e)}))}}class Z{constructor(e,t,n){this._payload=e,this.setDefaultPayloadStructure(),this.title=t,this.body=n}get payload(){return this._payload}set title(e){this._title=e}set subtitle(e){this._subtitle=e}set body(e){this._body=e}set badge(e){this._badge=e}set sound(e){this._sound=e}setDefaultPayloadStructure(){}toObject(){return{}}}class ee extends Z{constructor(){super(...arguments),this._apnsPushType="apns",this._isSilent=!1}get payload(){return this._payload}set configurations(e){e&&e.length&&(this._configurations=e)}get notification(){return this.payload.aps}get title(){return this._title}set title(e){e&&e.length&&(this.payload.aps.alert.title=e,this._title=e)}get subtitle(){return this._subtitle}set subtitle(e){e&&e.length&&(this.payload.aps.alert.subtitle=e,this._subtitle=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.aps.alert.body=e,this._body=e)}get badge(){return this._badge}set badge(e){null!=e&&(this.payload.aps.badge=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.aps.sound=e,this._sound=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.aps={alert:{}}}toObject(){const e=Object.assign({},this.payload),{aps:t}=e;let{alert:n}=t;if(this._isSilent&&(t["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");const t=[];this._configurations.forEach((e=>{t.push(this.objectFromAPNS2Configuration(e))})),t.length&&(e.pn_push=t)}return n&&Object.keys(n).length||delete t.alert,this._isSilent&&(delete t.alert,delete t.badge,delete t.sound,n={}),this._isSilent||n&&Object.keys(n).length?e:null}objectFromAPNS2Configuration(e){if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");const{collapseId:t,expirationDate:n}=e,s={auth_method:"token",targets:e.targets.map((e=>this.objectFromAPNSTarget(e))),version:"v2"};return t&&t.length&&(s.collapse_id=t),n&&(s.expiration=n.toISOString()),s}objectFromAPNSTarget(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");const{topic:t,environment:n="development",excludedDevices:s=[]}=e,r={topic:t,environment:n};return s.length&&(r.excluded_devices=s),r}}class te extends Z{get payload(){return this._payload}get notification(){return this.payload.notification}get data(){return this.payload.data}get title(){return this._title}set title(e){e&&e.length&&(this.payload.notification.title=e,this._title=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.notification.body=e,this._body=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.notification.sound=e,this._sound=e)}get icon(){return this._icon}set icon(e){e&&e.length&&(this.payload.notification.icon=e,this._icon=e)}get tag(){return this._tag}set tag(e){e&&e.length&&(this.payload.notification.tag=e,this._tag=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.notification={},this.payload.data={}}toObject(){let e=Object.assign({},this.payload.data),t=null;const n={};if(Object.keys(this.payload).length>2){const t=r(this.payload,["notification","data"]);e=Object.assign(Object.assign({},e),t)}return this._isSilent?e.notification=this.payload.notification:t=this.payload.notification,Object.keys(e).length&&(n.data=e),t&&Object.keys(t).length&&(n.notification=t),Object.keys(n).length?n:null}}class ne{constructor(e,t){this._payload={apns:{},fcm:{}},this._title=e,this._body=t,this.apns=new ee(this._payload.apns,e,t),this.fcm=new te(this._payload.fcm,e,t)}set debugging(e){this._debugging=e}get title(){return this._title}get subtitle(){return this._subtitle}set subtitle(e){this._subtitle=e,this.apns.subtitle=e,this.fcm.subtitle=e}get body(){return this._body}get badge(){return this._badge}set badge(e){this._badge=e,this.apns.badge=e,this.fcm.badge=e}get sound(){return this._sound}set sound(e){this._sound=e,this.apns.sound=e,this.fcm.sound=e}buildPayload(e){const t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";const n=this.apns.toObject();n&&Object.keys(n).length&&(t.pn_apns=n)}if(e.includes("fcm")){const e=this.fcm.toObject();e&&Object.keys(e).length&&(t.pn_gcm=e)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t}}class se{constructor(e){this.params=e,this.requestIdentifier=x.createUUID(),this._cancellationController=null}get cancellationController(){return this._cancellationController}set cancellationController(e){this._cancellationController=e}abort(e){this&&this.cancellationController&&this.cancellationController.abort(e)}operation(){throw Error("Should be implemented by subclass.")}validate(){}parse(e){return i(this,void 0,void 0,(function*(){return this.deserializeResponse(e)}))}request(){var e,t,n,s;const r={method:null!==(t=null===(e=this.params)||void 0===e?void 0:e.method)&&void 0!==t?t:K.GET,path:this.path,queryParameters:this.queryParameters,cancellable:null!==(s=null===(n=this.params)||void 0===n?void 0:n.cancellable)&&void 0!==s&&s,timeout:10,identifier:this.requestIdentifier},i=this.headers;if(i&&(r.headers=i),r.method===K.POST||r.method===K.PATCH){const[e,t]=[this.body,this.formData];t&&(r.formData=t),e&&(r.body=e)}return r}get headers(){}get path(){throw Error("`path` getter should be implemented by subclass.")}get queryParameters(){return{}}get formData(){}get body(){}deserializeResponse(e){const t=se.decoder.decode(e.body),n=e.headers["content-type"];let s;if(!n||-1===n.indexOf("javascript")&&-1===n.indexOf("json"))throw new d("Service response error, check status for details",y(t,e.status));try{s=JSON.parse(t)}catch(n){throw console.error("Error parsing JSON response:",n),new d("Service response error, check status for details",y(t,e.status))}if("status"in s&&"number"==typeof s.status&&s.status>=400)throw j.create(e);return s}}var re;se.decoder=new TextDecoder,function(e){e.PNPublishOperation="PNPublishOperation",e.PNSignalOperation="PNSignalOperation",e.PNSubscribeOperation="PNSubscribeOperation",e.PNUnsubscribeOperation="PNUnsubscribeOperation",e.PNWhereNowOperation="PNWhereNowOperation",e.PNHereNowOperation="PNHereNowOperation",e.PNGlobalHereNowOperation="PNGlobalHereNowOperation",e.PNSetStateOperation="PNSetStateOperation",e.PNGetStateOperation="PNGetStateOperation",e.PNHeartbeatOperation="PNHeartbeatOperation",e.PNAddMessageActionOperation="PNAddActionOperation",e.PNRemoveMessageActionOperation="PNRemoveMessageActionOperation",e.PNGetMessageActionsOperation="PNGetMessageActionsOperation",e.PNTimeOperation="PNTimeOperation",e.PNHistoryOperation="PNHistoryOperation",e.PNDeleteMessagesOperation="PNDeleteMessagesOperation",e.PNFetchMessagesOperation="PNFetchMessagesOperation",e.PNMessageCounts="PNMessageCountsOperation",e.PNGetAllUUIDMetadataOperation="PNGetAllUUIDMetadataOperation",e.PNGetUUIDMetadataOperation="PNGetUUIDMetadataOperation",e.PNSetUUIDMetadataOperation="PNSetUUIDMetadataOperation",e.PNRemoveUUIDMetadataOperation="PNRemoveUUIDMetadataOperation",e.PNGetAllChannelMetadataOperation="PNGetAllChannelMetadataOperation",e.PNGetChannelMetadataOperation="PNGetChannelMetadataOperation",e.PNSetChannelMetadataOperation="PNSetChannelMetadataOperation",e.PNRemoveChannelMetadataOperation="PNRemoveChannelMetadataOperation",e.PNGetMembersOperation="PNGetMembersOperation",e.PNSetMembersOperation="PNSetMembersOperation",e.PNGetMembershipsOperation="PNGetMembershipsOperation",e.PNSetMembershipsOperation="PNSetMembershipsOperation",e.PNListFilesOperation="PNListFilesOperation",e.PNGenerateUploadUrlOperation="PNGenerateUploadUrlOperation",e.PNPublishFileOperation="PNPublishFileOperation",e.PNPublishFileMessageOperation="PNPublishFileMessageOperation",e.PNGetFileUrlOperation="PNGetFileUrlOperation",e.PNDownloadFileOperation="PNDownloadFileOperation",e.PNDeleteFileOperation="PNDeleteFileOperation",e.PNAddPushNotificationEnabledChannelsOperation="PNAddPushNotificationEnabledChannelsOperation",e.PNRemovePushNotificationEnabledChannelsOperation="PNRemovePushNotificationEnabledChannelsOperation",e.PNPushNotificationEnabledChannelsOperation="PNPushNotificationEnabledChannelsOperation",e.PNRemoveAllPushNotificationsOperation="PNRemoveAllPushNotificationsOperation",e.PNChannelGroupsOperation="PNChannelGroupsOperation",e.PNRemoveGroupOperation="PNRemoveGroupOperation",e.PNChannelsForGroupOperation="PNChannelsForGroupOperation",e.PNAddChannelsToGroupOperation="PNAddChannelsToGroupOperation",e.PNRemoveChannelsFromGroupOperation="PNRemoveChannelsFromGroupOperation",e.PNAccessManagerGrant="PNAccessManagerGrant",e.PNAccessManagerGrantToken="PNAccessManagerGrantToken",e.PNAccessManagerAudit="PNAccessManagerAudit",e.PNAccessManagerRevokeToken="PNAccessManagerRevokeToken",e.PNHandshakeOperation="PNHandshakeOperation",e.PNReceiveMessagesOperation="PNReceiveMessagesOperation"}(re||(re={}));var ie=re;var ae;!function(e){e[e.Presence=-2]="Presence",e[e.Message=-1]="Message",e[e.Signal=1]="Signal",e[e.AppContext=2]="AppContext",e[e.MessageAction=3]="MessageAction",e[e.Files=4]="Files"}(ae||(ae={}));class oe extends se{constructor(e){var t,n,s,r,i,a;super({cancellable:!0}),this.parameters=e,null!==(t=(r=this.parameters).withPresence)&&void 0!==t||(r.withPresence=false),null!==(n=(i=this.parameters).channelGroups)&&void 0!==n||(i.channelGroups=[]),null!==(s=(a=this.parameters).channels)&&void 0!==s||(a.channels=[])}operation(){return ie.PNSubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:n}=this.parameters;return e?t||n?void 0:"`channels` and `channelGroups` both should not be empty":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){let t,n;try{n=se.decoder.decode(e.body);t=JSON.parse(n)}catch(e){console.error("Error parsing JSON response:",e)}if(!t)throw new d("Service response error, check status for details",y(n,e.status));const s=t.m.filter((e=>{const t=void 0===e.b?e.c:e.b;return this.parameters.channels&&this.parameters.channels.includes(t)||this.parameters.channelGroups&&this.parameters.channelGroups.includes(t)})).map((e=>{let{e:t}=e;return null!=t||(t=e.c.endsWith("-pnpres")?ae.Presence:ae.Message),t!=ae.Signal&&"string"==typeof e.d?t==ae.Message?{type:ae.Message,data:this.messageFromEnvelope(e)}:{type:ae.Files,data:this.fileFromEnvelope(e)}:t==ae.Message?{type:ae.Message,data:this.messageFromEnvelope(e)}:t===ae.Presence?{type:ae.Presence,data:this.presenceEventFromEnvelope(e)}:t==ae.Signal?{type:ae.Signal,data:this.signalFromEnvelope(e)}:t===ae.AppContext?{type:ae.AppContext,data:this.appContextFromEnvelope(e)}:t===ae.MessageAction?{type:ae.MessageAction,data:this.messageActionFromEnvelope(e)}:{type:ae.Files,data:this.fileFromEnvelope(e)}}));return{cursor:{timetoken:t.t.t,region:t.t.r},messages:s}}))}get headers(){return{accept:"text/javascript"}}presenceEventFromEnvelope(e){var t;const{d:n}=e,[s,r]=this.subscriptionChannelFromEnvelope(e),i=s.replace("-pnpres",""),a=null!==r?i:null,o=null!==r?r:i;return"string"!=typeof n&&("data"in n?(n.state=n.data,delete n.data):"action"in n&&"interval"===n.action&&(n.hereNowRefresh=null!==(t=n.here_now_refresh)&&void 0!==t&&t,delete n.here_now_refresh)),Object.assign({channel:i,subscription:r,actualChannel:a,subscribedChannel:o,timetoken:e.p.t},n)}messageFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),[s,r]=this.decryptedData(e.d),i={channel:t,subscription:n,actualChannel:null!==n?t:null,subscribedChannel:null!==n?n:t,timetoken:e.p.t,publisher:e.i,message:s};return e.u&&(i.userMetadata=e.u),e.cmt&&(i.customMessageType=e.cmt),r&&(i.error=r),i}signalFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),s={channel:t,subscription:n,timetoken:e.p.t,publisher:e.i,message:e.d};return e.u&&(s.userMetadata=e.u),e.cmt&&(s.customMessageType=e.cmt),s}messageActionFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),s=e.d;return{channel:t,subscription:n,timetoken:e.p.t,publisher:e.i,event:s.event,data:Object.assign(Object.assign({},s.data),{uuid:e.i})}}appContextFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),s=e.d;return{channel:t,subscription:n,timetoken:e.p.t,message:s}}fileFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),[s,r]=this.decryptedData(e.d);let i=r;const a={channel:t,subscription:n,timetoken:e.p.t,publisher:e.i};return e.u&&(a.userMetadata=e.u),s?"string"==typeof s?null!=i||(i="Unexpected file information payload data type."):(a.message=s.message,s.file&&(a.file={id:s.file.id,name:s.file.name,url:this.parameters.getFileUrl({id:s.file.id,name:s.file.name,channel:t})})):null!=i||(i="File information payload is missing."),e.cmt&&(a.customMessageType=e.cmt),i&&(a.error=i),a}subscriptionChannelFromEnvelope(e){return[e.c,void 0===e.b?e.c:e.b]}decryptedData(e){if(!this.parameters.crypto||"string"!=typeof e)return[e,void 0];let t,n;try{const n=this.parameters.crypto.decrypt(e);t=n instanceof ArrayBuffer?JSON.parse(ce.decoder.decode(n)):n}catch(e){t=null,n=`Error while decrypting message content: ${e.message}`}return[null!=t?t:e,n]}}class ce extends oe{get path(){var e;const{keySet:{subscribeKey:t},channels:n}=this.parameters;return`/v2/subscribe/${t}/${L(null!==(e=null==n?void 0:n.sort())&&void 0!==e?e:[],",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,heartbeat:n,state:s,timetoken:r,region:i}=this.parameters,a={};return e&&e.length>0&&(a["channel-group"]=e.sort().join(",")),t&&t.length>0&&(a["filter-expr"]=t),n&&(a.heartbeat=n),s&&Object.keys(s).length>0&&(a.state=JSON.stringify(s)),void 0!==r&&"string"==typeof r?r.length>0&&"0"!==r&&(a.tt=r):void 0!==r&&r>0&&(a.tt=r),i&&(a.tr=i),a}}class ue{constructor(e){this.listenerManager=e,this.channelListenerMap=new Map,this.groupListenerMap=new Map}emitEvent(e){var t;if(e.type===ae.Message)this.listenerManager.announceMessage(e.data),this.announce("message",e.data,e.data.channel,e.data.subscription);else if(e.type===ae.Signal)this.listenerManager.announceSignal(e.data),this.announce("signal",e.data,e.data.channel,e.data.subscription);else if(e.type===ae.Presence)this.listenerManager.announcePresence(e.data),this.announce("presence",e.data,null!==(t=e.data.subscription)&&void 0!==t?t:e.data.channel,e.data.subscription);else if(e.type===ae.AppContext){const{data:t}=e,{message:n}=t;if(this.listenerManager.announceObjects(t),this.announce("objects",t,t.channel,t.subscription),"uuid"===n.type){const{message:e,channel:s}=t,i=r(t,["message","channel"]),{event:a,type:o}=n,c=r(n,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:s,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",type:"user"})});this.listenerManager.announceUser(u),this.announce("user",u,u.spaceId,u.subscription)}else if("channel"===n.type){const{message:e,channel:s}=t,i=r(t,["message","channel"]),{event:a,type:o}=n,c=r(n,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:s,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",type:"space"})});this.listenerManager.announceSpace(u),this.announce("space",u,u.spaceId,u.subscription)}else if("membership"===n.type){const{message:e,channel:s}=t,i=r(t,["message","channel"]),{event:a,data:o}=n,c=r(n,["event","data"]),{uuid:u,channel:l}=o,h=r(o,["uuid","channel"]),d=Object.assign(Object.assign({},i),{spaceId:s,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",data:Object.assign(Object.assign({},h),{user:u,space:l})})});this.listenerManager.announceMembership(d),this.announce("membership",d,d.spaceId,d.subscription)}}else e.type===ae.MessageAction?(this.listenerManager.announceMessageAction(e.data),this.announce("messageAction",e.data,e.data.channel,e.data.subscription)):e.type===ae.Files&&(this.listenerManager.announceFile(e.data),this.announce("file",e.data,e.data.channel,e.data.subscription))}addListener(e,t,n){t&&n?(null==t||t.forEach((t=>{if(this.channelListenerMap.has(t)){const n=this.channelListenerMap.get(t);n.includes(e)||n.push(e)}else this.channelListenerMap.set(t,[e])})),null==n||n.forEach((t=>{if(this.groupListenerMap.has(t)){const n=this.groupListenerMap.get(t);n.includes(e)||n.push(e)}else this.groupListenerMap.set(t,[e])}))):this.listenerManager.addListener(e)}removeListener(e,t,n){t&&n?(null==t||t.forEach((t=>{this.channelListenerMap.has(t)&&this.channelListenerMap.set(t,this.channelListenerMap.get(t).filter((t=>t!==e)))})),null==n||n.forEach((t=>{this.groupListenerMap.has(t)&&this.groupListenerMap.set(t,this.groupListenerMap.get(t).filter((t=>t!==e)))}))):this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners(),this.channelListenerMap.clear(),this.groupListenerMap.clear()}announce(e,t,n,s){t&&this.channelListenerMap.has(n)&&this.channelListenerMap.get(n).forEach((n=>{const s=n[e];s&&s(t)})),s&&this.groupListenerMap.has(s)&&this.groupListenerMap.get(s).forEach((n=>{const s=n[e];s&&s(t)}))}}class le{constructor(e=!1){this.sync=e,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){const t=()=>{this.listeners.forEach((t=>{t(e)}))};this.sync?t():setTimeout(t,0)}}class he{transition(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)}constructor(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}on(e,t){return this.transitionMap.set(e,t),this}with(e,t){return[this,e,null!=t?t:[]]}onEnter(e){return this.enterEffects.push(e),this}onExit(e){return this.exitEffects.push(e),this}}class de extends le{describe(e){return new he(e)}start(e,t){this.currentState=e,this.currentContext=t,this.notify({type:"engineStarted",state:e,context:t})}transition(e){if(!this.currentState)throw new Error("Start the engine first");this.notify({type:"eventReceived",event:e});const t=this.currentState.transition(this.currentContext,e);if(t){const[n,s,r]=t;for(const e of this.currentState.exitEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)});const i=this.currentState;this.currentState=n;const a=this.currentContext;this.currentContext=s,this.notify({type:"transitionDone",fromState:i,fromContext:a,toState:n,toContext:s,event:e});for(const e of r)this.notify({type:"invocationDispatched",invocation:e});for(const e of this.currentState.enterEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)})}}}class pe{constructor(e){this.dependencies=e,this.instances=new Map,this.handlers=new Map}on(e,t){this.handlers.set(e,t)}dispatch(e){if("CANCEL"===e.type){if(this.instances.has(e.payload)){const t=this.instances.get(e.payload);null==t||t.cancel(),this.instances.delete(e.payload)}return}const t=this.handlers.get(e.type);if(!t)throw new Error(`Unhandled invocation '${e.type}'`);const n=t(e.payload,this.dependencies);e.managed&&this.instances.set(e.type,n),n.start()}dispose(){for(const[e,t]of this.instances.entries())t.cancel(),this.instances.delete(e)}}function ge(e,t){const n=function(...n){return{type:e,payload:null==t?void 0:t(...n)}};return n.type=e,n}function ye(e,t){const n=(...n)=>({type:e,payload:t(...n),managed:!1});return n.type=e,n}function fe(e,t){const n=(...n)=>({type:e,payload:t(...n),managed:!0});return n.type=e,n.cancel={type:"CANCEL",payload:e,managed:!1},n}class me extends Error{constructor(){super("The operation was aborted."),this.name="AbortError",Object.setPrototypeOf(this,new.target.prototype)}}class be extends le{constructor(){super(...arguments),this._aborted=!1}get aborted(){return this._aborted}throwIfAborted(){if(this._aborted)throw new me}abort(){this._aborted=!0,this.notify(new me)}}class ve{constructor(e,t){this.payload=e,this.dependencies=t}}class we extends ve{constructor(e,t,n){super(e,t),this.asyncFunction=n,this.abortSignal=new be}start(){this.asyncFunction(this.payload,this.abortSignal,this.dependencies).catch((e=>{}))}cancel(){this.abortSignal.abort()}}const Se=e=>(t,n)=>new we(t,n,e),Ee=ge("RECONNECT",(()=>({}))),Oe=ge("DISCONNECT",(()=>({}))),ke=ge("JOINED",((e,t)=>({channels:e,groups:t}))),Ce=ge("LEFT",((e,t)=>({channels:e,groups:t}))),Ne=ge("LEFT_ALL",(()=>({}))),Pe=ge("HEARTBEAT_SUCCESS",(e=>({statusCode:e}))),Me=ge("HEARTBEAT_FAILURE",(e=>e)),_e=ge("HEARTBEAT_GIVEUP",(()=>({}))),Ae=ge("TIMES_UP",(()=>({}))),je=ye("HEARTBEAT",((e,t)=>({channels:e,groups:t}))),Ie=ye("LEAVE",((e,t)=>({channels:e,groups:t}))),Fe=ye("EMIT_STATUS",(e=>e)),Te=fe("WAIT",(()=>({}))),Re=fe("DELAYED_HEARTBEAT",(e=>e));class Ue extends pe{constructor(e,t){super(t),this.on(je.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{heartbeat:s,presenceState:r,config:i}){try{yield s(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},i.maintainPresenceState&&{state:r}),{heartbeat:i.presenceTimeout}));e.transition(Pe(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Me(t))}}}))))),this.on(Ie.type,Se(((e,t,n)=>i(this,[e,t,n],void 0,(function*(e,t,{leave:n,config:s}){if(!s.suppressLeaveEvents)try{n({channels:e.channels,channelGroups:e.groups})}catch(e){}}))))),this.on(Te.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{heartbeatDelay:s}){return n.throwIfAborted(),yield s(),n.throwIfAborted(),e.transition(Ae())}))))),this.on(Re.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{heartbeat:s,retryDelay:r,presenceState:i,config:a}){if(!a.retryConfiguration||!a.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(_e());n.throwIfAborted(),yield r(a.retryConfiguration.getDelay(t.attempts,t.reason)),n.throwIfAborted();try{yield s(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},a.maintainPresenceState&&{state:i}),{heartbeat:a.presenceTimeout}));return e.transition(Pe(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Me(t))}}}))))),this.on(Fe.type,Se(((e,t,n)=>i(this,[e,t,n],void 0,(function*(e,t,{emitStatus:n,config:s}){var r;s.announceFailedHeartbeats&&!0===(null===(r=null==e?void 0:e.status)||void 0===r?void 0:r.error)?n(e.status):s.announceSuccessfulHeartbeats&&200===e.statusCode&&n(Object.assign(Object.assign({},e),{operation:ie.PNHeartbeatOperation,error:!1}))})))))}}const xe=new he("HEARTBEAT_STOPPED");xe.on(ke.type,((e,t)=>xe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),xe.on(Ce.type,((e,t)=>xe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))}))),xe.on(Ee.type,((e,t)=>Ke.with({channels:e.channels,groups:e.groups}))),xe.on(Ne.type,((e,t)=>$e.with(void 0)));const De=new he("HEARTBEAT_COOLDOWN");De.onEnter((()=>Te())),De.onExit((()=>Te.cancel)),De.on(Ae.type,((e,t)=>Ke.with({channels:e.channels,groups:e.groups}))),De.on(ke.type,((e,t)=>Ke.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),De.on(Ce.type,((e,t)=>Ke.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ie(t.payload.channels,t.payload.groups)]))),De.on(Oe.type,(e=>xe.with({channels:e.channels,groups:e.groups},[Ie(e.channels,e.groups)]))),De.on(Ne.type,((e,t)=>$e.with(void 0,[Ie(e.channels,e.groups)])));const qe=new he("HEARTBEAT_FAILED");qe.on(ke.type,((e,t)=>Ke.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),qe.on(Ce.type,((e,t)=>Ke.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ie(t.payload.channels,t.payload.groups)]))),qe.on(Ee.type,((e,t)=>Ke.with({channels:e.channels,groups:e.groups}))),qe.on(Oe.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups},[Ie(e.channels,e.groups)]))),qe.on(Ne.type,((e,t)=>$e.with(void 0,[Ie(e.channels,e.groups)])));const Ge=new he("HEARBEAT_RECONNECTING");Ge.onEnter((e=>Re(e))),Ge.onExit((()=>Re.cancel)),Ge.on(ke.type,((e,t)=>Ke.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Ge.on(Ce.type,((e,t)=>Ke.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ie(t.payload.channels,t.payload.groups)]))),Ge.on(Oe.type,((e,t)=>{xe.with({channels:e.channels,groups:e.groups},[Ie(e.channels,e.groups)])})),Ge.on(Pe.type,((e,t)=>De.with({channels:e.channels,groups:e.groups}))),Ge.on(Me.type,((e,t)=>Ge.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),Ge.on(_e.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),Ge.on(Ne.type,((e,t)=>$e.with(void 0,[Ie(e.channels,e.groups)])));const Ke=new he("HEARTBEATING");Ke.onEnter((e=>je(e.channels,e.groups))),Ke.on(Pe.type,((e,t)=>De.with({channels:e.channels,groups:e.groups}))),Ke.on(ke.type,((e,t)=>Ke.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Ke.on(Ce.type,((e,t)=>Ke.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ie(t.payload.channels,t.payload.groups)]))),Ke.on(Me.type,((e,t)=>Ge.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),Ke.on(Oe.type,(e=>xe.with({channels:e.channels,groups:e.groups},[Ie(e.channels,e.groups)]))),Ke.on(Ne.type,((e,t)=>$e.with(void 0,[Ie(e.channels,e.groups)])));const $e=new he("HEARTBEAT_INACTIVE");$e.on(ke.type,((e,t)=>Ke.with({channels:t.payload.channels,groups:t.payload.groups})));class Le{get _engine(){return this.engine}constructor(e){this.dependencies=e,this.engine=new de,this.channels=[],this.groups=[],this.dispatcher=new Ue(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start($e,void 0)}join({channels:e,groups:t}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],this.engine.transition(ke(this.channels.slice(0),this.groups.slice(0)))}leave({channels:e,groups:t}){this.dependencies.presenceState&&(null==e||e.forEach((e=>delete this.dependencies.presenceState[e])),null==t||t.forEach((e=>delete this.dependencies.presenceState[e]))),this.engine.transition(Ce(null!=e?e:[],null!=t?t:[]))}leaveAll(){this.engine.transition(Ne())}dispose(){this._unsubscribeEngine(),this.dispatcher.dispose()}}class Be{static LinearRetryPolicy(e){return{delay:e.delay,maximumRetry:e.maximumRetry,shouldRetry(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(e,t){var n;return 1e3*((null!==(n=t.retryAfter)&&void 0!==n?n:this.delay)+Math.random())},getGiveupReason(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"},validate(){if(this.maximumRetry>10)throw new Error("Maximum retry for linear retry policy can not be more than 10")}}}static ExponentialRetryPolicy(e){return{minimumDelay:e.minimumDelay,maximumDelay:e.maximumDelay,maximumRetry:e.maximumRetry,shouldRetry(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(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(e,t){var n;return this.maximumRetry<=t?"retry attempts exhausted.":403===(null===(n=null==e?void 0:e.status)||void 0===n?void 0:n.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.minimumDelay<2)throw new Error("Minimum delay can not be set less than 2 seconds for retry");if(this.maximumDelay)throw new Error("Maximum delay can not be set more than 150 seconds for retry");if(this.maximumRetry>6)throw new Error("Maximum retry for exponential retry policy can not be more than 6")}}}}const He=fe("HANDSHAKE",((e,t)=>({channels:e,groups:t}))),Ve=fe("RECEIVE_MESSAGES",((e,t,n)=>({channels:e,groups:t,cursor:n}))),ze=ye("EMIT_MESSAGES",(e=>e)),We=ye("EMIT_STATUS",(e=>e)),Je=fe("RECEIVE_RECONNECT",(e=>e)),Xe=fe("HANDSHAKE_RECONNECT",(e=>e)),Qe=ge("SUBSCRIPTION_CHANGED",((e,t)=>({channels:e,groups:t}))),Ye=ge("SUBSCRIPTION_RESTORED",((e,t,n,s)=>({channels:e,groups:t,cursor:{timetoken:n,region:null!=s?s:0}}))),Ze=ge("HANDSHAKE_SUCCESS",(e=>e)),et=ge("HANDSHAKE_FAILURE",(e=>e)),tt=ge("HANDSHAKE_RECONNECT_SUCCESS",(e=>({cursor:e}))),nt=ge("HANDSHAKE_RECONNECT_FAILURE",(e=>e)),st=ge("HANDSHAKE_RECONNECT_GIVEUP",(e=>e)),rt=ge("RECEIVE_SUCCESS",((e,t)=>({cursor:e,events:t}))),it=ge("RECEIVE_FAILURE",(e=>e)),at=ge("RECEIVE_RECONNECT_SUCCESS",((e,t)=>({cursor:e,events:t}))),ot=ge("RECEIVE_RECONNECT_FAILURE",(e=>e)),ct=ge("RECEIVING_RECONNECT_GIVEUP",(e=>e)),ut=ge("DISCONNECT",(()=>({}))),lt=ge("RECONNECT",((e,t)=>({cursor:{timetoken:null!=e?e:"",region:null!=t?t:0}}))),ht=ge("UNSUBSCRIBE_ALL",(()=>({})));class dt extends pe{constructor(e,t){super(t),this.on(He.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{handshake:s,presenceState:r,config:i}){n.throwIfAborted();try{const a=yield s(Object.assign({abortSignal:n,channels:t.channels,channelGroups:t.groups,filterExpression:i.filterExpression},i.maintainPresenceState&&{state:r}));return e.transition(Ze(a))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(et(t))}}}))))),this.on(Ve.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{receiveMessages:s,config:r}){n.throwIfAborted();try{const i=yield s({abortSignal:n,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:r.filterExpression});e.transition(rt(i.cursor,i.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;if(!n.aborted)return e.transition(it(t))}}}))))),this.on(ze.type,Se(((e,t,n)=>i(this,[e,t,n],void 0,(function*(e,t,{emitMessages:n}){e.length>0&&n(e)}))))),this.on(We.type,Se(((e,t,n)=>i(this,[e,t,n],void 0,(function*(e,t,{emitStatus:n}){n(e)}))))),this.on(Je.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{receiveMessages:s,delay:r,config:i}){if(!i.retryConfiguration||!i.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(ct(new d(i.retryConfiguration?i.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe messages receive.")));n.throwIfAborted(),yield r(i.retryConfiguration.getDelay(t.attempts,t.reason)),n.throwIfAborted();try{const r=yield s({abortSignal:n,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:i.filterExpression});return e.transition(at(r.cursor,r.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(ot(t))}}}))))),this.on(Xe.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{handshake:s,delay:r,presenceState:i,config:a}){if(!a.retryConfiguration||!a.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(st(new d(a.retryConfiguration?a.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe handshake")));n.throwIfAborted(),yield r(a.retryConfiguration.getDelay(t.attempts,t.reason)),n.throwIfAborted();try{const r=yield s(Object.assign({abortSignal:n,channels:t.channels,channelGroups:t.groups,filterExpression:a.filterExpression},a.maintainPresenceState&&{state:i}));return e.transition(tt(r))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(nt(t))}}})))))}}const pt=new he("HANDSHAKE_FAILED");pt.on(Qe.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),pt.on(lt.type,((e,t)=>wt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor||e.cursor}))),pt.on(Ye.type,((e,t)=>{var n,s;return wt.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!==(s=null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)&&void 0!==s?s:0}})})),pt.on(ht.type,(e=>St.with()));const gt=new he("HANDSHAKE_STOPPED");gt.on(Qe.type,((e,t)=>gt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),gt.on(lt.type,((e,t)=>wt.with(Object.assign(Object.assign({},e),{cursor:t.payload.cursor||e.cursor})))),gt.on(Ye.type,((e,t)=>{var n;return gt.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}})})),gt.on(ht.type,(e=>St.with()));const yt=new he("RECEIVE_FAILED");yt.on(lt.type,((e,t)=>{var n;return wt.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}})})),yt.on(Qe.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),yt.on(Ye.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),yt.on(ht.type,(e=>St.with(void 0)));const ft=new he("RECEIVE_STOPPED");ft.on(Qe.type,((e,t)=>ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),ft.on(Ye.type,((e,t)=>ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),ft.on(lt.type,((e,t)=>{var n;return wt.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}})})),ft.on(ht.type,(()=>St.with(void 0)));const mt=new he("RECEIVE_RECONNECTING");mt.onEnter((e=>Je(e))),mt.onExit((()=>Je.cancel)),mt.on(at.type,((e,t)=>bt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),mt.on(ot.type,((e,t)=>mt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),mt.on(ct.type,((e,t)=>{var n;return yt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[We({category:h.PNDisconnectedUnexpectedlyCategory,error:null===(n=t.payload)||void 0===n?void 0:n.message})])})),mt.on(ut.type,(e=>ft.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[We({category:h.PNDisconnectedCategory})]))),mt.on(Ye.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),mt.on(Qe.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),mt.on(ht.type,(e=>St.with(void 0,[We({category:h.PNDisconnectedCategory})])));const bt=new he("RECEIVING");bt.onEnter((e=>Ve(e.channels,e.groups,e.cursor))),bt.onExit((()=>Ve.cancel)),bt.on(rt.type,((e,t)=>bt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),bt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?St.with(void 0):bt.with({cursor:e.cursor,channels:t.payload.channels,groups:t.payload.groups}))),bt.on(Ye.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?St.with(void 0):bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),bt.on(it.type,((e,t)=>mt.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),bt.on(ut.type,(e=>ft.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[We({category:h.PNDisconnectedCategory})]))),bt.on(ht.type,(e=>St.with(void 0,[We({category:h.PNDisconnectedCategory})])));const vt=new he("HANDSHAKE_RECONNECTING");vt.onEnter((e=>Xe(e))),vt.onExit((()=>Xe.cancel)),vt.on(tt.type,((e,t)=>{var n,s;const r={timetoken:(null===(n=e.cursor)||void 0===n?void 0:n.timetoken)?null===(s=e.cursor)||void 0===s?void 0:s.timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region};return bt.with({channels:e.channels,groups:e.groups,cursor:r},[We({category:h.PNConnectedCategory})])})),vt.on(nt.type,((e,t)=>vt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),vt.on(st.type,((e,t)=>{var n;return pt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[We({category:h.PNConnectionErrorCategory,error:null===(n=t.payload)||void 0===n?void 0:n.message})])})),vt.on(ut.type,(e=>gt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),vt.on(Qe.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),vt.on(Ye.type,((e,t)=>{var n,s;return wt.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===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),vt.on(ht.type,(e=>St.with(void 0)));const wt=new he("HANDSHAKING");wt.onEnter((e=>He(e.channels,e.groups))),wt.onExit((()=>He.cancel)),wt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?St.with(void 0):wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),wt.on(Ze.type,((e,t)=>{var n,s;return bt.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===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.timetoken:t.payload.timetoken,region:t.payload.region}},[We({category:h.PNConnectedCategory})])})),wt.on(et.type,((e,t)=>vt.with({channels:e.channels,groups:e.groups,cursor:e.cursor,attempts:0,reason:t.payload}))),wt.on(ut.type,(e=>gt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),wt.on(Ye.type,((e,t)=>{var n;return wt.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}})})),wt.on(ht.type,(e=>St.with()));const St=new he("UNSUBSCRIBED");St.on(Qe.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups}))),St.on(Ye.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:t.payload.cursor})));class Et{get _engine(){return this.engine}constructor(e){this.engine=new de,this.channels=[],this.groups=[],this.dependencies=e,this.dispatcher=new dt(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(St,void 0)}subscribe({channels:e,channelGroups:t,timetoken:n,withPresence:s}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],s&&(this.channels.map((e=>this.channels.push(`${e}-pnpres`))),this.groups.map((e=>this.groups.push(`${e}-pnpres`)))),n?this.engine.transition(Ye(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])),n)):this.engine.transition(Qe(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])))),this.dependencies.join&&this.dependencies.join({channels:Array.from(new Set(this.channels.filter((e=>!e.endsWith("-pnpres"))))),groups:Array.from(new Set(this.groups.filter((e=>!e.endsWith("-pnpres")))))})}unsubscribe({channels:e=[],channelGroups:t=[]}){const n=B(this.channels,[...e,...e.map((e=>`${e}-pnpres`))]),s=B(this.groups,[...t,...t.map((e=>`${e}-pnpres`))]);if(new Set(this.channels).size!==new Set(n).size||new Set(this.groups).size!==new Set(s).size){const r=H(this.channels,e),i=H(this.groups,t);this.dependencies.presenceState&&(null==r||r.forEach((e=>delete this.dependencies.presenceState[e])),null==i||i.forEach((e=>delete this.dependencies.presenceState[e]))),this.channels=n,this.groups=s,this.engine.transition(Qe(Array.from(new Set(this.channels.slice(0))),Array.from(new Set(this.groups.slice(0))))),this.dependencies.leave&&this.dependencies.leave({channels:r.slice(0),groups:i.slice(0)})}}unsubscribeAll(){this.channels=[],this.groups=[],this.dependencies.presenceState&&Object.keys(this.dependencies.presenceState).forEach((e=>{delete this.dependencies.presenceState[e]})),this.engine.transition(Qe(this.channels.slice(0),this.groups.slice(0))),this.dependencies.leaveAll&&this.dependencies.leaveAll()}reconnect({timetoken:e,region:t}){this.engine.transition(lt(e,t))}disconnect(){this.engine.transition(ut()),this.dependencies.leaveAll&&this.dependencies.leaveAll()}getSubscribedChannels(){return Array.from(new Set(this.channels.slice(0)))}getSubscribedChannelGroups(){return Array.from(new Set(this.groups.slice(0)))}dispose(){this.disconnect(),this._unsubscribeEngine(),this.dispatcher.dispose()}}class Ot extends se{constructor(e){var t,n;super({method:e.sendByPost?K.POST:K.GET}),this.parameters=e,null!==(t=(n=this.parameters).sendByPost)&&void 0!==t||(n.sendByPost=false)}operation(){return ie.PNPublishOperation}validate(){const{message:e,channel:t,keySet:{publishKey:n}}=this.parameters;return t?e?n?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{message:e,channel:t,keySet:n}=this.parameters,s=this.prepareMessagePayload(e);return`/publish/${n.publishKey}/${n.subscribeKey}/0/${$(t)}/0${this.parameters.sendByPost?"":`/${$(s)}`}`}get queryParameters(){const{customMessageType:e,meta:t,replicate:n,storeInHistory:s,ttl:r}=this.parameters,i={};return e&&(i.custom_message_type=e),void 0!==s&&(i.store=s?"1":"0"),void 0!==r&&(i.ttl=r),void 0===n||n||(i.norep="true"),t&&"object"==typeof t&&(i.meta=JSON.stringify(t)),i}get headers(){if(this.parameters.sendByPost)return{"Content-Type":"application/json"}}get body(){return this.prepareMessagePayload(this.parameters.message)}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const n=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof n?n:u(n))}}class kt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNSignalOperation}validate(){const{message:e,channel:t,keySet:{publishKey:n}}=this.parameters;return t?e?n?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{keySet:{publishKey:e,subscribeKey:t},channel:n,message:s}=this.parameters,r=JSON.stringify(s);return`/signal/${e}/${t}/0/${$(n)}/0/${$(r)}`}get queryParameters(){const{customMessageType:e}=this.parameters,t={};return e&&(t.custom_message_type=e),t}}class Ct extends oe{operation(){return ie.PNReceiveMessagesOperation}validate(){const e=super.validate();return e||(this.parameters.timetoken?this.parameters.region?void 0:"region can not be empty":"timetoken can not be empty")}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${L(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,timetoken:n,region:s}=this.parameters,r={ee:""};return e&&e.length>0&&(r["channel-group"]=e.sort().join(",")),t&&t.length>0&&(r["filter-expr"]=t),"string"==typeof n?n&&n.length>0&&(r.tt=n):n&&n>0&&(r.tt=n),s&&(r.tr=s),r}}class Nt extends oe{operation(){return ie.PNHandshakeOperation}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${L(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,state:n}=this.parameters,s={tt:0,ee:""};return e&&e.length>0&&(s["channel-group"]=e.sort().join(",")),t&&t.length>0&&(s["filter-expr"]=t),n&&Object.keys(n).length>0&&(s.state=JSON.stringify(n)),s}}class Pt extends se{constructor(e){var t,n,s,r;super(),this.parameters=e,null!==(t=(s=this.parameters).channels)&&void 0!==t||(s.channels=[]),null!==(n=(r=this.parameters).channelGroups)&&void 0!==n||(r.channelGroups=[])}operation(){return ie.PNGetStateOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:n}=this.parameters;if(!e)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e),{channels:n=[],channelGroups:s=[]}=this.parameters,r={channels:{}};return 1===n.length&&0===s.length?r.channels[n[0]]=t.payload:r.channels=t.payload,r}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:n}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${L(null!=n?n:[],",")}/uuid/${t}`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.join(",")}:{}}}class Mt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNSetStateOperation}validate(){const{keySet:{subscribeKey:e},state:t,channels:n=[],channelGroups:s=[]}=this.parameters;return e?t?0===(null==n?void 0:n.length)&&0===(null==s?void 0:s.length)?"Please provide a list of channels and/or channel-groups":void 0:"Missing State":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{state:this.deserializeResponse(e).payload}}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:n}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${L(null!=n?n:[],",")}/uuid/${$(t)}/data`}get queryParameters(){const{channelGroups:e,state:t}=this.parameters,n={state:JSON.stringify(t)};return e&&0!==e.length&&(n["channel-group"]=e.join(",")),n}}class _t extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNHeartbeatOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:n=[]}=this.parameters;return e?0===t.length&&0===n.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channels:t}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${L(null!=t?t:[],",")}/heartbeat`}get queryParameters(){const{channelGroups:e,state:t,heartbeat:n}=this.parameters,s={heartbeat:`${n}`};return e&&0!==e.length&&(s["channel-group"]=e.join(",")),t&&(s.state=JSON.stringify(t)),s}}class At extends se{constructor(e){super(),this.parameters=e,this.parameters.channelGroups&&(this.parameters.channelGroups=Array.from(new Set(this.parameters.channelGroups))),this.parameters.channels&&(this.parameters.channels=Array.from(new Set(this.parameters.channels)))}operation(){return ie.PNUnsubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:n=[]}=this.parameters;return e?0===t.length&&0===n.length?"At least one `channel` or `channel group` should be provided.":void 0:"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){var e;const{keySet:{subscribeKey:t},channels:n}=this.parameters;return`/v2/presence/sub-key/${t}/channel/${L(null!==(e=null==n?void 0:n.sort())&&void 0!==e?e:[],",")}/leave`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.sort().join(",")}:{}}}class jt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNWhereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return t.payload?{channels:t.payload.channels}:{channels:[]}}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/presence/sub-key/${e}/uuid/${$(t)}`}}class It extends se{constructor(e){var t,n,s,r,i,a;super(),this.parameters=e,null!==(t=(r=this.parameters).queryParameters)&&void 0!==t||(r.queryParameters={}),null!==(n=(i=this.parameters).includeUUIDs)&&void 0!==n||(i.includeUUIDs=true),null!==(s=(a=this.parameters).includeState)&&void 0!==s||(a.includeState=false)}operation(){const{channels:e=[],channelGroups:t=[]}=this.parameters;return 0===e.length&&0===t.length?ie.PNGlobalHereNowOperation:ie.PNHereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t,n;const s=this.deserializeResponse(e),r="occupancy"in s?1:s.payload.total_channels,i="occupancy"in s?s.occupancy:s.payload.total_occupancy,a={};let o={};if("occupancy"in s){const e=this.parameters.channels[0];o[e]={uuids:null!==(t=s.uuids)&&void 0!==t?t:[],occupancy:i}}else o=null!==(n=s.payload.channels)&&void 0!==n?n:{};return Object.keys(o).forEach((e=>{const t=o[e];a[e]={occupants:this.parameters.includeUUIDs?t.uuids.map((e=>"string"==typeof e?{uuid:e,state:null}:e)):[],name:e,occupancy:t.occupancy}})),{totalChannels:r,totalOccupancy:i,channels:a}}))}get path(){const{keySet:{subscribeKey:e},channels:t,channelGroups:n}=this.parameters;let s=`/v2/presence/sub-key/${e}`;return(t&&t.length>0||n&&n.length>0)&&(s+=`/channel/${L(null!=t?t:[],",")}`),s}get queryParameters(){const{channelGroups:e,includeUUIDs:t,includeState:n,queryParameters:s}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign({},t?{}:{disable_uuids:"1"}),null!=n&&n?{state:"1"}:{}),e&&e.length>0?{"channel-group":e.join(",")}:{}),s)}}class Ft extends se{constructor(e){super({method:K.DELETE}),this.parameters=e}operation(){return ie.PNDeleteMessagesOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v3/history/sub-key/${e}/channel/${$(t)}`}get queryParameters(){const{start:e,end:t}=this.parameters;return Object.assign(Object.assign({},e?{start:e}:{}),t?{end:t}:{})}}class Tt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNMessageCounts}validate(){const{keySet:{subscribeKey:e},channels:t,timetoken:n,channelTimetokens:s}=this.parameters;return e?t?n&&s?"`timetoken` and `channelTimetokens` are incompatible together":n||s?s&&s.length>1&&s.length!==t.length?"Length of `channelTimetokens` and `channels` do not match":void 0:"`timetoken` or `channelTimetokens` need to be set":"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e).channels}}))}get path(){return`/v3/history/sub-key/${this.parameters.keySet.subscribeKey}/message-counts/${L(this.parameters.channels)}`}get queryParameters(){let{channelTimetokens:e}=this.parameters;return this.parameters.timetoken&&(e=[this.parameters.timetoken]),Object.assign(Object.assign({},1===e.length?{timetoken:e[0]}:{}),e.length>1?{channelsTimetoken:e.join(",")}:{})}}class Rt extends se{constructor(e){var t,n,s;super(),this.parameters=e,e.count?e.count=Math.min(e.count,100):e.count=100,null!==(t=e.stringifiedTimeToken)&&void 0!==t||(e.stringifiedTimeToken=false),null!==(n=e.includeMeta)&&void 0!==n||(e.includeMeta=false),null!==(s=e.logVerbosity)&&void 0!==s||(e.logVerbosity=false)}operation(){return ie.PNHistoryOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e),n=t[0],s=t[1],r=t[2];return Array.isArray(n)?{messages:n.map((e=>{const t=this.processPayload(e.message),n={entry:t.payload,timetoken:e.timetoken};return t.error&&(n.error=t.error),e.meta&&(n.meta=e.meta),n})),startTimeToken:s,endTimeToken:r}:{messages:[],startTimeToken:s,endTimeToken:r}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/history/sub-key/${e}/channel/${$(t)}`}get queryParameters(){const{start:e,end:t,reverse:n,count:s,stringifiedTimeToken:r,includeMeta:i}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:s,include_token:"true"},e?{start:e}:{}),t?{end:t}:{}),r?{string_message_token:"true"}:{}),null!=n?{reverse:n.toString()}:{}),i?{include_meta:"true"}:{})}processPayload(e){const{crypto:t,logVerbosity:n}=this.parameters;if(!t||"string"!=typeof e)return{payload:e};let s,r;try{const n=t.decrypt(e);s=n instanceof ArrayBuffer?JSON.parse(Rt.decoder.decode(n)):n}catch(t){n&&console.log("decryption error",t.message),s=e,r=`Error while decrypting message content: ${t.message}`}return{payload:s,error:r}}}var Ut;!function(e){e[e.Message=-1]="Message",e[e.Files=4]="Files"}(Ut||(Ut={}));class xt extends se{constructor(e){var t,n,s,r,i;super(),this.parameters=e;const a=null!==(t=e.includeMessageActions)&&void 0!==t&&t,o=e.channels.length>1||a?25:100;e.count?e.count=Math.min(e.count,o):e.count=o,e.includeUuid?e.includeUUID=e.includeUuid:null!==(n=e.includeUUID)&&void 0!==n||(e.includeUUID=true),null!==(s=e.stringifiedTimeToken)&&void 0!==s||(e.stringifiedTimeToken=false),null!==(r=e.includeMessageType)&&void 0!==r||(e.includeMessageType=true),null!==(i=e.logVerbosity)&&void 0!==i||(e.logVerbosity=false)}operation(){return ie.PNFetchMessagesOperation}validate(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:n}=this.parameters;return e?t?void 0!==n&&n&&t.length>1?"History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.":void 0:"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t;const n=this.deserializeResponse(e),s=null!==(t=n.channels)&&void 0!==t?t:{},r={};return Object.keys(s).forEach((e=>{r[e]=s[e].map((t=>{null===t.message_type&&(t.message_type=Ut.Message);const n=this.processPayload(e,t),s=Object.assign(Object.assign({channel:e,timetoken:t.timetoken,message:n.payload,messageType:t.message_type},t.custom_message_type?{customMessageType:t.custom_message_type}:{}),{uuid:t.uuid});if(t.actions){const e=s;e.actions=t.actions,e.data=t.actions}return t.meta&&(s.meta=t.meta),n.error&&(s.error=n.error),s}))})),n.more?{channels:r,more:n.more}:{channels:r}}))}get path(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:n}=this.parameters;return`/v3/${n?"history-with-actions":"history"}/sub-key/${e}/channel/${L(t)}`}get queryParameters(){const{start:e,end:t,count:n,includeCustomMessageType:s,includeMessageType:r,includeMeta:i,includeUUID:a,stringifiedTimeToken:o}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({max:n},e?{start:e}:{}),t?{end:t}:{}),o?{string_message_token:"true"}:{}),void 0!==i&&i?{include_meta:"true"}:{}),a?{include_uuid:"true"}:{}),null!=s?{include_custom_message_type:s?"true":"false"}:{}),r?{include_message_type:"true"}:{})}processPayload(e,t){const{crypto:n,logVerbosity:s}=this.parameters;if(!n||"string"!=typeof t.message)return{payload:t.message};let r,i;try{const e=n.decrypt(t.message);r=e instanceof ArrayBuffer?JSON.parse(xt.decoder.decode(e)):e}catch(e){s&&console.log("decryption error",e.message),r=t.message,i=`Error while decrypting message content: ${e.message}`}if(!i&&r&&t.message_type==Ut.Files&&"object"==typeof r&&this.isFileMessage(r)){const t=r;return{payload:{message:t.message,file:Object.assign(Object.assign({},t.file),{url:this.parameters.getFileUrl({channel:e,id:t.file.id,name:t.file.name})})},error:i}}return{payload:r,error:i}}isFileMessage(e){return void 0!==e.file}}class Dt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNGetMessageActionsOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);let n=null,s=null;return t.data.length>0&&(n=t.data[0].actionTimetoken,s=t.data[t.data.length-1].actionTimetoken),{data:t.data,more:t.more,start:n,end:s}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/message-actions/${e}/channel/${$(t)}`}get queryParameters(){const{limit:e,start:t,end:n}=this.parameters;return Object.assign(Object.assign(Object.assign({},t?{start:t}:{}),n?{end:n}:{}),e?{limit:e}:{})}}class qt extends se{constructor(e){super({method:K.POST}),this.parameters=e}operation(){return ie.PNAddMessageActionOperation}validate(){const{keySet:{subscribeKey:e},action:t,channel:n,messageTimetoken:s}=this.parameters;return e?n?s?t?t.value?t.type?t.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message timetoken":"Missing message channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((({data:e})=>({data:e})))}))}get path(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:n}=this.parameters;return`/v1/message-actions/${e}/channel/${$(t)}/message/${n}`}get headers(){return{"Content-Type":"application/json"}}get body(){return JSON.stringify(this.parameters.action)}}class Gt extends se{constructor(e){super({method:K.DELETE}),this.parameters=e}operation(){return ie.PNRemoveMessageActionOperation}validate(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:n,actionTimetoken:s}=this.parameters;return e?t?n?s?void 0:"Missing action timetoken":"Missing message timetoken":"Missing message action channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((({data:e})=>({data:e})))}))}get path(){const{keySet:{subscribeKey:e},channel:t,actionTimetoken:n,messageTimetoken:s}=this.parameters;return`/v1/message-actions/${e}/channel/${$(t)}/message/${s}/action/${n}`}}class Kt extends se{constructor(e){var t,n;super(),this.parameters=e,null!==(t=(n=this.parameters).storeInHistory)&&void 0!==t||(n.storeInHistory=true)}operation(){return ie.PNPublishFileMessageOperation}validate(){const{channel:e,fileId:t,fileName:n}=this.parameters;return e?t?n?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{message:e,channel:t,keySet:{publishKey:n,subscribeKey:s},fileId:r,fileName:i}=this.parameters,a=Object.assign({file:{name:i,id:r}},e?{message:e}:{});return`/v1/files/publish-file/${n}/${s}/0/${$(t)}/0/${$(this.prepareMessagePayload(a))}`}get queryParameters(){const{customMessageType:e,storeInHistory:t,ttl:n,meta:s}=this.parameters;return Object.assign(Object.assign(Object.assign({store:t?"1":"0"},e?{custom_message_type:e}:{}),n?{ttl:n}:{}),s&&"object"==typeof s?{meta:JSON.stringify(s)}:{})}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const n=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof n?n:u(n))}}class $t extends se{constructor(e){super({method:K.LOCAL}),this.parameters=e}operation(){return ie.PNGetFileUrlOperation}validate(){const{channel:e,id:t,name:n}=this.parameters;return e?t?n?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return e.url}))}get path(){const{channel:e,id:t,name:n,keySet:{subscribeKey:s}}=this.parameters;return`/v1/files/${s}/channels/${$(e)}/files/${t}/${n}`}}class Lt extends se{constructor(e){super({method:K.DELETE}),this.parameters=e}operation(){return ie.PNDeleteFileOperation}validate(){const{channel:e,id:t,name:n}=this.parameters;return e?t?n?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}get path(){const{keySet:{subscribeKey:e},id:t,channel:n,name:s}=this.parameters;return`/v1/files/${e}/channels/${$(n)}/files/${t}/${s}`}}class Bt extends se{constructor(e){var t,n;super(),this.parameters=e,null!==(t=(n=this.parameters).limit)&&void 0!==t||(n.limit=100)}operation(){return ie.PNListFilesOperation}validate(){if(!this.parameters.channel)return"channel can't be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${$(t)}/files`}get queryParameters(){const{limit:e,next:t}=this.parameters;return Object.assign({limit:e},t?{next:t}:{})}}class Ht extends se{constructor(e){super({method:K.POST}),this.parameters=e}operation(){return ie.PNGenerateUploadUrlOperation}validate(){return this.parameters.channel?this.parameters.name?void 0:"'name' can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return{id:t.data.id,name:t.data.name,url:t.file_upload_request.url,formFields:t.file_upload_request.form_fields}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${$(t)}/generate-upload-url`}get headers(){return{"Content-Type":"application/json"}}get body(){return JSON.stringify({name:this.parameters.name})}}class Vt extends se{constructor(e){super({method:K.POST}),this.parameters=e;const t=e.file.mimeType;t&&(e.formFields=e.formFields.map((e=>"Content-Type"===e.name?{name:e.name,value:t}:e)))}operation(){return ie.PNPublishFileOperation}validate(){const{fileId:e,fileName:t,file:n,uploadUrl:s}=this.parameters;return e?t?n?s?void 0:"Validation failed: file upload 'url' can't be empty":"Validation failed: 'file' can't be empty":"Validation failed: file 'name' can't be empty":"Validation failed: file 'id' can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{status:e.status,message:e.body?Vt.decoder.decode(e.body):"OK"}}))}request(){return Object.assign(Object.assign({},super.request()),{origin:new URL(this.parameters.uploadUrl).origin,timeout:300})}get path(){const{pathname:e,search:t}=new URL(this.parameters.uploadUrl);return`${e}${t}`}get body(){return this.parameters.file}get formData(){return this.parameters.formFields}}class zt{constructor(e){var t;if(this.parameters=e,this.file=null===(t=this.parameters.PubNubFile)||void 0===t?void 0:t.create(e.file),!this.file)throw new Error("File upload error: unable to create File object.")}process(){return i(this,void 0,void 0,(function*(){let e,t;return this.generateFileUploadUrl().then((n=>(e=n.name,t=n.id,this.uploadFile(n)))).then((e=>{if(204!==e.status)throw new d("Upload to bucket was unsuccessful",{error:!0,statusCode:e.status,category:h.PNUnknownCategory,operation:ie.PNPublishFileOperation,errorData:{message:e.message}})})).then((()=>this.publishFileMessage(t,e))).catch((e=>{if(e instanceof d)throw e;const t=e instanceof j?e:j.create(e);throw new d("File upload error.",t.toStatus(ie.PNPublishFileOperation))}))}))}generateFileUploadUrl(){return i(this,void 0,void 0,(function*(){const e=new Ht(Object.assign(Object.assign({},this.parameters),{name:this.file.name,keySet:this.parameters.keySet}));return this.parameters.sendRequest(e)}))}uploadFile(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,PubNubFile:n,crypto:s,cryptography:r}=this.parameters,{id:i,name:a,url:o,formFields:c}=e;return this.parameters.PubNubFile.supportsEncryptFile&&(!t&&s?this.file=yield s.encryptFile(this.file,n):t&&r&&(this.file=yield r.encryptFile(t,this.file,n))),this.parameters.sendRequest(new Vt({fileId:i,fileName:a,file:this.file,uploadUrl:o,formFields:c}))}))}publishFileMessage(e,t){return i(this,void 0,void 0,(function*(){var n,s,r,i;let a,o={timetoken:"0"},c=this.parameters.fileUploadPublishRetryLimit,u=!1;do{try{o=yield this.parameters.publishFile(Object.assign(Object.assign({},this.parameters),{fileId:e,fileName:t})),u=!0}catch(e){e instanceof d&&(a=e),c-=1}}while(!u&&c>0);if(u)return{status:200,timetoken:o.timetoken,id:e,name:t};throw new d("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{error:!0,category:null!==(s=null===(n=a.status)||void 0===n?void 0:n.category)&&void 0!==s?s:h.PNUnknownCategory,statusCode:null!==(i=null===(r=a.status)||void 0===r?void 0:r.statusCode)&&void 0!==i?i:0,channel:this.parameters.channel,id:e,name:t})}))}}class Wt{subscribe(e){const t=null==e?void 0:e.timetoken;this.pubnub.registerSubscribeCapable(this),this.pubnub.subscribe(Object.assign({channels:this.channelNames,channelGroups:this.groupNames},null!==t&&""!==t&&{timetoken:t}))}unsubscribe(){this.pubnub.unregisterSubscribeCapable(this);const{channels:e,channelGroups:t}=this.pubnub.getSubscribeCapableEntities(),n=this.groupNames.filter((e=>!t.includes(e))),s=this.channelNames.filter((t=>!e.includes(t)));0===s.length&&0===n.length||this.pubnub.unsubscribe({channels:s,channelGroups:n})}set onMessage(e){this.listener.message=e}set onPresence(e){this.listener.presence=e}set onSignal(e){this.listener.signal=e}set onObjects(e){this.listener.objects=e}set onMessageAction(e){this.listener.messageAction=e}set onFile(e){this.listener.file=e}addListener(e){this.eventEmitter.addListener(e,this.channelNames,this.groupNames)}removeListener(e){this.eventEmitter.removeListener(e,this.channelNames,this.groupNames)}get channels(){return this.channelNames.slice(0)}get channelGroups(){return this.groupNames.slice(0)}}class Jt extends Wt{constructor({channels:e=[],channelGroups:t=[],subscriptionOptions:n,eventEmitter:s,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.subscriptionList=[],this.options=n,this.eventEmitter=s,this.pubnub=r,e.forEach((e=>{const t=this.pubnub.channel(e).subscription(this.options);this.channelNames=[...this.channelNames,...t.channels],this.subscriptionList.push(t)})),t.forEach((e=>{const t=this.pubnub.channelGroup(e).subscription(this.options);this.groupNames=[...this.groupNames,...t.channelGroups],this.subscriptionList.push(t)})),this.listener={},s.addListener(this.listener,this.channelNames,this.groupNames)}addSubscription(e){this.subscriptionList.push(e),this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscription(e){const t=e.channels,n=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!n.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>t!==e)),this.eventEmitter.removeListener(this.listener,t,n)}addSubscriptionSet(e){this.subscriptionList=[...this.subscriptionList,...e.subscriptions],this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscriptionSet(e){const t=e.channels,n=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!n.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>!e.subscriptions.includes(t))),this.eventEmitter.removeListener(this.listener,t,n)}get subscriptions(){return this.subscriptionList.slice(0)}}class Xt extends Wt{constructor({channels:e,channelGroups:t,subscriptionOptions:n,eventEmitter:s,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.channelNames=e,this.groupNames=t,this.options=n,this.pubnub=r,this.eventEmitter=s,this.listener={},s.addListener(this.listener,this.channelNames,this.groupNames)}addSubscription(e){return new Jt({channels:[...this.channelNames,...e.channels],channelGroups:[...this.groupNames,...e.channelGroups],subscriptionOptions:Object.assign(Object.assign({},this.options),null==e?void 0:e.options),eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Qt{constructor(e,t,n){this.eventEmitter=t,this.pubnub=n,this.id=e}subscription(e){return new Xt({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Yt{constructor(e,t,n){this.eventEmitter=t,this.pubnub=n,this.name=e}subscription(e){{const t=[this.name];return(null==e?void 0:e.receivePresenceEvents)&&!this.name.endsWith("-pnpres")&&t.push(`${this.name}-pnpres`),new Xt({channels:[],channelGroups:t,subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}}class Zt{constructor(e,t,n){this.eventEmitter=t,this.pubnub=n,this.id=e}subscription(e){return new Xt({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class en{constructor(e,t,n){this.eventEmitter=t,this.pubnub=n,this.name=e}subscription(e){{const t=[this.name];return(null==e?void 0:e.receivePresenceEvents)&&!this.name.endsWith("-pnpres")&&t.push(`${this.name}-pnpres`),new Xt({channels:t,channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}}class tn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNRemoveChannelsFromGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:n}=this.parameters;return e?n?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${$(t)}`}get queryParameters(){return{remove:this.parameters.channels.join(",")}}}class nn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNAddChannelsToGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:n}=this.parameters;return e?n?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${$(t)}`}get queryParameters(){return{add:this.parameters.channels.join(",")}}}class sn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNChannelsForGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e).payload.channels}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${$(t)}`}}class rn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNRemoveGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${$(t)}/remove`}}class an extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNChannelGroupsOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{groups:this.deserializeResponse(e).payload.groups}}))}get path(){return`/v1/channel-registration/sub-key/${this.parameters.keySet.subscribeKey}/channel-group`}}class on{constructor(e,t){this.sendRequest=t,this.keySet=e}listChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new sn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}listGroups(e){return i(this,void 0,void 0,(function*(){const t=new an({keySet:this.keySet});return e?this.sendRequest(t,e):this.sendRequest(t)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new nn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new tn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}deleteGroup(e,t){return i(this,void 0,void 0,(function*(){const n=new rn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}}class cn extends se{constructor(e){var t,n;super(),this.parameters=e,"apns2"===this.parameters.pushGateway&&(null!==(t=(n=this.parameters).environment)&&void 0!==t||(n.environment="development")),this.parameters.count&&this.parameters.count>1e3&&(this.parameters.count=1e3)}operation(){throw Error("Should be implemented in subclass.")}validate(){const{keySet:{subscribeKey:e},action:t,device:n,pushGateway:s}=this.parameters;return e?n?"add"!==t&&"remove"!==t||"channels"in this.parameters&&0!==this.parameters.channels.length?s?"apns2"!==this.parameters.pushGateway||this.parameters.topic?void 0:"Missing APNS2 topic":"Missing GW Type (pushGateway: gcm or apns2)":"Missing Channels":"Missing Device ID (device)":"Missing Subscribe Key"}get path(){const{keySet:{subscribeKey:e},action:t,device:n,pushGateway:s}=this.parameters;let r="apns2"===s?`/v2/push/sub-key/${e}/devices-apns2/${n}`:`/v1/push/sub-key/${e}/devices/${n}`;return"remove-device"===t&&(r=`${r}/remove`),r}get queryParameters(){const{start:e,count:t}=this.parameters;let n=Object.assign(Object.assign({type:this.parameters.pushGateway},e?{start:e}:{}),t&&t>0?{count:t}:{});if("channels"in this.parameters&&(n[this.parameters.action]=this.parameters.channels.join(",")),"apns2"===this.parameters.pushGateway){const{environment:e,topic:t}=this.parameters;n=Object.assign(Object.assign({},n),{environment:e,topic:t})}return n}}class un extends cn{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove"}))}operation(){return ie.PNRemovePushNotificationEnabledChannelsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class ln extends cn{constructor(e){super(Object.assign(Object.assign({},e),{action:"list"}))}operation(){return ie.PNPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e)}}))}}class hn extends cn{constructor(e){super(Object.assign(Object.assign({},e),{action:"add"}))}operation(){return ie.PNAddPushNotificationEnabledChannelsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class dn extends cn{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove-device"}))}operation(){return ie.PNRemoveAllPushNotificationsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class pn{constructor(e,t){this.sendRequest=t,this.keySet=e}listChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new ln(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new hn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new un(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}deleteDevice(e,t){return i(this,void 0,void 0,(function*(){const n=new dn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}}class gn extends se{constructor(e){var t,n,s,r,i,a;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(i=e.include).customFields)&&void 0!==n||(i.customFields=false),null!==(s=(a=e.include).totalCount)&&void 0!==s||(a.totalCount=false),null!==(r=e.limit)&&void 0!==r||(e.limit=100)}operation(){return ie.PNGetAllChannelMetadataOperation}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";return i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(","),count:`${e.totalCount}`},n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class yn extends se{constructor(e){super({method:K.DELETE}),this.parameters=e}operation(){return ie.PNRemoveChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}`}}class fn extends se{constructor(e){var t,n,s,r,i,a,o,c,u,l,h,d,p,g,y,f,m,b;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(h=e.include).customFields)&&void 0!==n||(h.customFields=false),null!==(s=(d=e.include).totalCount)&&void 0!==s||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(y=e.include).channelFields)&&void 0!==a||(y.channelFields=false),null!==(o=(f=e.include).customChannelFields)&&void 0!==o||(f.customChannelFields=false),null!==(c=(m=e.include).channelStatusField)&&void 0!==c||(m.channelStatusField=false),null!==(u=(b=e.include).channelTypeField)&&void 0!==u||(b.channelTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNGetMembershipsOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=[];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.channelFields&&a.push("channel"),e.channelStatusField&&a.push("channel.status"),e.channelTypeField&&a.push("channel.type"),e.customChannelFields&&a.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class mn extends se{constructor(e){var t,n,s,r,i,a,o,c,u,l,h,d,p,g,y,f,m,b;super({method:K.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(h=e.include).customFields)&&void 0!==n||(h.customFields=false),null!==(s=(d=e.include).totalCount)&&void 0!==s||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(y=e.include).channelFields)&&void 0!==a||(y.channelFields=false),null!==(o=(f=e.include).customChannelFields)&&void 0!==o||(f.customChannelFields=false),null!==(c=(m=e.include).channelStatusField)&&void 0!==c||(m.channelStatusField=false),null!==(u=(b=e.include).channelTypeField)&&void 0!==u||(b.channelTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNSetMembershipsOperation}validate(){const{uuid:e,channels:t}=this.parameters;return e?t&&0!==t.length?void 0:"Channels cannot be empty":"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=["channel.status","channel.type","status"];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.channelFields&&a.push("channel"),e.channelStatusField&&a.push("channel.status"),e.channelTypeField&&a.push("channel.type"),e.customChannelFields&&a.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{channels:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},status:e.status,type:e.type,custom:e.custom}))})}}class bn extends se{constructor(e){var t,n,s,r;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(r=e.include).customFields)&&void 0!==n||(r.customFields=false),null!==(s=e.limit)&&void 0!==s||(e.limit=100)}operation(){return ie.PNGetAllUUIDMetadataOperation}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";return i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(",")},void 0!==e.totalCount?{count:`${e.totalCount}`}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class vn extends se{constructor(e){var t,n,s;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(s=e.include).customFields)&&void 0!==n||(s.customFields=true)}operation(){return ie.PNGetChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}}class wn extends se{constructor(e){var t,n,s;super({method:K.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(s=e.include).customFields)&&void 0!==n||(s.customFields=true)}operation(){return ie.PNSetChannelMetadataOperation}validate(){return this.parameters.channel?this.parameters.data?void 0:"Data cannot be empty":"Channel cannot be empty"}get headers(){return this.parameters.ifMatchesEtag?{"If-Match":this.parameters.ifMatchesEtag}:void 0}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Sn extends se{constructor(e){super({method:K.DELETE}),this.parameters=e,this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNRemoveUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}`}}class En extends se{constructor(e){var t,n,s,r,i,a,o,c,u,l,h,d,p,g,y,f,m,b;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(h=e.include).customFields)&&void 0!==n||(h.customFields=false),null!==(s=(d=e.include).totalCount)&&void 0!==s||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(y=e.include).UUIDFields)&&void 0!==a||(y.UUIDFields=false),null!==(o=(f=e.include).customUUIDFields)&&void 0!==o||(f.customUUIDFields=false),null!==(c=(m=e.include).UUIDStatusField)&&void 0!==c||(m.UUIDStatusField=false),null!==(u=(b=e.include).UUIDTypeField)&&void 0!==u||(b.UUIDTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100)}operation(){return ie.PNSetMembersOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=[];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.UUIDFields&&a.push("uuid"),e.UUIDStatusField&&a.push("uuid.status"),e.UUIDTypeField&&a.push("uuid.type"),e.customUUIDFields&&a.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class On extends se{constructor(e){var t,n,s,r,i,a,o,c,u,l,h,d,p,g,y,f,m,b;super({method:K.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(h=e.include).customFields)&&void 0!==n||(h.customFields=false),null!==(s=(d=e.include).totalCount)&&void 0!==s||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(y=e.include).UUIDFields)&&void 0!==a||(y.UUIDFields=false),null!==(o=(f=e.include).customUUIDFields)&&void 0!==o||(f.customUUIDFields=false),null!==(c=(m=e.include).UUIDStatusField)&&void 0!==c||(m.UUIDStatusField=false),null!==(u=(b=e.include).UUIDTypeField)&&void 0!==u||(b.UUIDTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100)}operation(){return ie.PNSetMembersOperation}validate(){const{channel:e,uuids:t}=this.parameters;return e?t&&0!==t.length?void 0:"UUIDs cannot be empty":"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=["uuid.status","uuid.type","type"];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.UUIDFields&&a.push("uuid"),e.UUIDStatusField&&a.push("uuid.status"),e.UUIDTypeField&&a.push("uuid.type"),e.customUUIDFields&&a.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{uuids:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},status:e.status,type:e.type,custom:e.custom}))})}}class kn extends se{constructor(e){var t,n,s;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(s=e.include).customFields)&&void 0!==n||(s.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNGetUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}`}get queryParameters(){const{include:e}=this.parameters;return{include:["status","type",...e.customFields?["custom"]:[]].join(",")}}}class Cn extends se{constructor(e){var t,n,s;super({method:K.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(s=e.include).customFields)&&void 0!==n||(s.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNSetUUIDMetadataOperation}validate(){return this.parameters.uuid?this.parameters.data?void 0:"Data cannot be empty":"'uuid' cannot be empty"}get headers(){return this.parameters.ifMatchesEtag?{"If-Match":this.parameters.ifMatchesEtag}:void 0}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Nn{constructor(e,t){this.keySet=e.keySet,this.configuration=e,this.sendRequest=t}getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllUUIDMetadata(e,t)}))}_getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const s=new bn(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getUUIDMetadata(e,t)}))}_getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var n;const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),s.userId&&(s.uuid=s.userId),null!==(n=s.uuid)&&void 0!==n||(s.uuid=this.configuration.userId);const r=new kn(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setUUIDMetadata(e,t)}))}_setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var n;e.userId&&(e.uuid=e.userId),null!==(n=e.uuid)&&void 0!==n||(e.uuid=this.configuration.userId);const s=new Cn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeUUIDMetadata(e,t)}))}_removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var n;const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),s.userId&&(s.uuid=s.userId),null!==(n=s.uuid)&&void 0!==n||(s.uuid=this.configuration.userId);const r=new Sn(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllChannelMetadata(e,t)}))}_getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const s=new gn(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getChannelMetadata(e,t)}))}_getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=new vn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setChannelMetadata(e,t)}))}_setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=new wn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeChannelMetadata(e,t)}))}_removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=new yn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const n=new En(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const n=new On(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const n=new On(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getMemberships(e,t){return i(this,void 0,void 0,(function*(){var n;const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),s.userId&&(s.uuid=s.userId),null!==(n=s.uuid)&&void 0!==n||(s.uuid=this.configuration.userId);const r=new fn(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setMemberships(e,t){return i(this,void 0,void 0,(function*(){var n;e.userId&&(e.uuid=e.userId),null!==(n=e.uuid)&&void 0!==n||(e.uuid=this.configuration.userId);const s=new mn(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var n;e.userId&&(e.uuid=e.userId),null!==(n=e.uuid)&&void 0!==n||(e.uuid=this.configuration.userId);const s=new mn(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){var n,s;if("spaceId"in e){const s=e,r={channel:null!==(n=s.spaceId)&&void 0!==n?n:s.channel,filter:s.filter,limit:s.limit,page:s.page,include:Object.assign({},s.include),sort:s.sort?Object.fromEntries(Object.entries(s.sort).map((([e,t])=>[e.replace("user","uuid"),t]))):void 0},i=e=>({status:e.status,data:e.data.map((e=>({user:e.uuid,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getChannelMembers(r,((e,n)=>{t(e,n?i(n):n)})):this.getChannelMembers(r).then(i)}const r=e,i={uuid:null!==(s=r.userId)&&void 0!==s?s:r.uuid,filter:r.filter,limit:r.limit,page:r.page,include:Object.assign({},r.include),sort:r.sort?Object.fromEntries(Object.entries(r.sort).map((([e,t])=>[e.replace("space","channel"),t]))):void 0},a=e=>({status:e.status,data:e.data.map((e=>({space:e.channel,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getMemberships(i,((e,n)=>{t(e,n?a(n):n)})):this.getMemberships(i).then(a)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){var n,s,r,i,a,o;if("spaceId"in e){const i=e,a={channel:null!==(n=i.spaceId)&&void 0!==n?n:i.channel,uuids:null!==(r=null===(s=i.users)||void 0===s?void 0:s.map((e=>"string"==typeof e?e:{id:e.userId,custom:e.custom})))&&void 0!==r?r:i.uuids,limit:0};return t?this.setChannelMembers(a,t):this.setChannelMembers(a)}const c=e,u={uuid:null!==(i=c.userId)&&void 0!==i?i:c.uuid,channels:null!==(o=null===(a=c.spaces)||void 0===a?void 0:a.map((e=>"string"==typeof e?e:{id:e.spaceId,custom:e.custom})))&&void 0!==o?o:c.channels,limit:0};return t?this.setMemberships(u,t):this.setMemberships(u)}))}}class Pn extends se{constructor(){super()}operation(){return ie.PNTimeOperation}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[0]}}))}get path(){return"/time/0"}}class Mn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNDownloadFileOperation}validate(){const{channel:e,id:t,name:n}=this.parameters;return e?t?n?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,crypto:n,cryptography:s,name:r,PubNubFile:i}=this.parameters,a=e.headers["content-type"];let o,c=e.body;return i.supportsEncryptFile&&(t||n)&&(t&&s?c=yield s.decrypt(t,c):!t&&n&&(o=yield n.decryptFile(i.create({data:c,name:r,mimeType:a}),i))),o||i.create({data:c,name:r,mimeType:a})}))}get path(){const{keySet:{subscribeKey:e},channel:t,id:n,name:s}=this.parameters;return`/v1/files/${e}/channels/${$(t)}/files/${n}/${s}`}}class _n{static notificationPayload(e,t){return new ne(e,t)}static generateUUID(){return x.createUUID()}constructor(e){if(this._configuration=e.configuration,this.cryptography=e.cryptography,this.tokenManager=e.tokenManager,this.transport=e.transport,this.crypto=e.crypto,this._objects=new Nn(this._configuration,this.sendRequest.bind(this)),this._channelGroups=new on(this._configuration.keySet,this.sendRequest.bind(this)),this._push=new pn(this._configuration.keySet,this.sendRequest.bind(this)),this.listenerManager=new J,this.eventEmitter=new ue(this.listenerManager),this.subscribeCapable=new Set,this._configuration.enableEventEngine){let e=this._configuration.getHeartbeatInterval();this.presenceState={},e&&(this.presenceEventEngine=new Le({heartbeat:this.heartbeat.bind(this),leave:e=>this.makeUnsubscribe(e,(()=>{})),heartbeatDelay:()=>new Promise(((t,n)=>{e=this._configuration.getHeartbeatInterval(),e?setTimeout(t,1e3*e):n(new d("Heartbeat interval has been reset."))})),retryDelay:e=>new Promise((t=>setTimeout(t,e))),emitStatus:e=>this.listenerManager.announceStatus(e),config:this._configuration,presenceState:this.presenceState})),this.eventEngine=new Et({handshake:this.subscribeHandshake.bind(this),receiveMessages:this.subscribeReceiveMessages.bind(this),delay:e=>new Promise((t=>setTimeout(t,e))),join:this.join.bind(this),leave:this.leave.bind(this),leaveAll:this.leaveAll.bind(this),presenceState:this.presenceState,config:this._configuration,emitMessages:e=>{try{e.forEach((e=>this.eventEmitter.emitEvent(e)))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}},emitStatus:e=>this.listenerManager.announceStatus(e)})}else this.subscriptionManager=new Y(this._configuration,this.listenerManager,this.eventEmitter,this.makeSubscribe.bind(this),this.heartbeat.bind(this),this.makeUnsubscribe.bind(this),this.time.bind(this))}get configuration(){return this._configuration}get _config(){return this.configuration}get authKey(){var e;return null!==(e=this._configuration.authKey)&&void 0!==e?e:void 0}getAuthKey(){return this.authKey}setAuthKey(e){this._configuration.setAuthKey(e)}get userId(){return this._configuration.userId}set userId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}getUserId(){return this._configuration.userId}setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}get filterExpression(){var e;return null!==(e=this._configuration.getFilterExpression())&&void 0!==e?e:void 0}getFilterExpression(){return this.filterExpression}set filterExpression(e){this._configuration.setFilterExpression(e)}setFilterExpression(e){this.filterExpression=e}get cipherKey(){return this._configuration.getCipherKey()}set cipherKey(e){this._configuration.setCipherKey(e)}setCipherKey(e){this.cipherKey=e}set heartbeatInterval(e){this._configuration.setHeartbeatInterval(e)}setHeartbeatInterval(e){this.heartbeatInterval=e}getVersion(){return this._configuration.getVersion()}_addPnsdkSuffix(e,t){this._configuration._addPnsdkSuffix(e,t)}getUUID(){return this.userId}setUUID(e){this.userId=e}get customEncrypt(){return this._configuration.getCustomEncrypt()}get customDecrypt(){return this._configuration.getCustomDecrypt()}channel(e){return new en(e,this.eventEmitter,this)}channelGroup(e){return new Yt(e,this.eventEmitter,this)}channelMetadata(e){return new Qt(e,this.eventEmitter,this)}userMetadata(e){return new Zt(e,this.eventEmitter,this)}subscriptionSet(e){return new Jt(Object.assign(Object.assign({},e),{eventEmitter:this.eventEmitter,pubnub:this}))}sendRequest(e,t){return i(this,void 0,void 0,(function*(){const n=e.validate();if(n){if(t)return t(g(n),null);throw new d("Validation failed, check status for details",g(n))}const s=e.request(),r=e.operation();s.formData&&s.formData.length>0||r===ie.PNDownloadFileOperation?s.timeout=this._configuration.getFileTimeout():r===ie.PNSubscribeOperation||r===ie.PNReceiveMessagesOperation?s.timeout=this._configuration.getSubscribeTimeout():s.timeout=this._configuration.getTransactionTimeout();const i={error:!1,operation:r,category:h.PNAcknowledgmentCategory,statusCode:0},[a,o]=this.transport.makeSendable(s);return e.cancellationController=o||null,a.then((t=>{if(i.statusCode=t.status,200!==t.status&&204!==t.status){const e=_n.decoder.decode(t.body),n=t.headers["content-type"];if(n||-1!==n.indexOf("javascript")||-1!==n.indexOf("json")){const t=JSON.parse(e);"object"==typeof t&&"error"in t&&t.error&&"object"==typeof t.error&&(i.errorData=t.error)}else i.responseText=e}return e.parse(t)})).then((e=>t?t(i,e):e)).catch((e=>{const n=e instanceof j?e:j.create(e);if(t)return t(n.toStatus(r),null);throw n.toPubNubError(r,"REST API request processing error, check status for details")}))}))}destroy(e){var t;null===(t=this.subscribeCapable)||void 0===t||t.clear(),this.subscriptionManager?(this.subscriptionManager.unsubscribeAll(e),this.subscriptionManager.disconnect()):this.eventEngine&&this.eventEngine.dispose()}stop(){this.destroy()}addListener(e){this.listenerManager.addListener(e)}removeListener(e){this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners()}publish(e,t){return i(this,void 0,void 0,(function*(){{const n=new Ot(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}signal(e,t){return i(this,void 0,void 0,(function*(){{const n=new kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}fire(e,t){return i(this,void 0,void 0,(function*(){return null!=t||(t=()=>{}),this.publish(Object.assign(Object.assign({},e),{replicate:!1,storeInHistory:!1}),t)}))}getSubscribedChannels(){return this.subscriptionManager?this.subscriptionManager.subscribedChannels:this.eventEngine?this.eventEngine.getSubscribedChannels():[]}getSubscribedChannelGroups(){return this.subscriptionManager?this.subscriptionManager.subscribedChannelGroups:this.eventEngine?this.eventEngine.getSubscribedChannelGroups():[]}registerSubscribeCapable(e){this.subscribeCapable&&!this.subscribeCapable.has(e)&&this.subscribeCapable.add(e)}unregisterSubscribeCapable(e){this.subscribeCapable&&this.subscribeCapable.has(e)&&this.subscribeCapable.delete(e)}getSubscribeCapableEntities(){{const e={channels:[],channelGroups:[]};if(!this.subscribeCapable)return e;for(const t of this.subscribeCapable)e.channelGroups.push(...t.channelGroups),e.channels.push(...t.channels);return e}}subscribe(e){this.subscriptionManager?this.subscriptionManager.subscribe(e):this.eventEngine&&this.eventEngine.subscribe(e)}makeSubscribe(e,t){{const n=new ce(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));if(this.sendRequest(n,((e,s)=>{var r;this.subscriptionManager&&(null===(r=this.subscriptionManager.abort)||void 0===r?void 0:r.identifier)===n.requestIdentifier&&(this.subscriptionManager.abort=null),t(e,s)})),this.subscriptionManager){const e=()=>n.abort("Cancel long-poll subscribe request");e.identifier=n.requestIdentifier,this.subscriptionManager.abort=e}}}unsubscribe(e){this.subscriptionManager?this.subscriptionManager.unsubscribe(e):this.eventEngine&&this.eventEngine.unsubscribe(e)}makeUnsubscribe(e,t){this.sendRequest(new At(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),t)}unsubscribeAll(){var e;null===(e=this.subscribeCapable)||void 0===e||e.clear(),this.subscriptionManager?this.subscriptionManager.unsubscribeAll():this.eventEngine&&this.eventEngine.unsubscribeAll()}disconnect(){this.subscriptionManager?this.subscriptionManager.disconnect():this.eventEngine&&this.eventEngine.disconnect()}reconnect(e){this.subscriptionManager?this.subscriptionManager.reconnect():this.eventEngine&&this.eventEngine.reconnect(null!=e?e:{})}subscribeHandshake(e){return i(this,void 0,void 0,(function*(){{const t=new Nt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),n=e.abortSignal.subscribe((e=>{t.abort("Cancel subscribe handshake request")}));return this.sendRequest(t).then((e=>(n(),e.cursor)))}}))}subscribeReceiveMessages(e){return i(this,void 0,void 0,(function*(){{const t=new Ct(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),n=e.abortSignal.subscribe((e=>{t.abort("Cancel long-poll subscribe request")}));return this.sendRequest(t).then((e=>(n(),e)))}}))}getMessageActions(e,t){return i(this,void 0,void 0,(function*(){{const n=new Dt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}addMessageAction(e,t){return i(this,void 0,void 0,(function*(){{const n=new qt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}removeMessageAction(e,t){return i(this,void 0,void 0,(function*(){{const n=new Gt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}fetchMessages(e,t){return i(this,void 0,void 0,(function*(){{const n=new xt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}deleteMessages(e,t){return i(this,void 0,void 0,(function*(){{const n=new Ft(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}messageCounts(e,t){return i(this,void 0,void 0,(function*(){{const n=new Tt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}history(e,t){return i(this,void 0,void 0,(function*(){{const n=new Rt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}hereNow(e,t){return i(this,void 0,void 0,(function*(){{const n=new It(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}whereNow(e,t){return i(this,void 0,void 0,(function*(){var n;{const s=new jt({uuid:null!==(n=e.uuid)&&void 0!==n?n:this._configuration.userId,keySet:this._configuration.keySet});return t?this.sendRequest(s,t):this.sendRequest(s)}}))}getState(e,t){return i(this,void 0,void 0,(function*(){var n;{const s=new Pt(Object.assign(Object.assign({},e),{uuid:null!==(n=e.uuid)&&void 0!==n?n:this._configuration.userId,keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}setState(e,t){return i(this,void 0,void 0,(function*(){var n,s;{const{keySet:r,userId:i}=this._configuration,a=this._configuration.getPresenceTimeout();let o;if(this._configuration.enableEventEngine&&this.presenceState){const t=this.presenceState;null===(n=e.channels)||void 0===n||n.forEach((n=>t[n]=e.state)),"channelGroups"in e&&(null===(s=e.channelGroups)||void 0===s||s.forEach((n=>t[n]=e.state)))}return o="withHeartbeat"in e?new _t(Object.assign(Object.assign({},e),{keySet:r,heartbeat:a})):new Mt(Object.assign(Object.assign({},e),{keySet:r,uuid:i})),this.subscriptionManager&&this.subscriptionManager.setState(e),t?this.sendRequest(o,t):this.sendRequest(o)}}))}presence(e){var t;null===(t=this.subscriptionManager)||void 0===t||t.changePresence(e)}heartbeat(e,t){return i(this,void 0,void 0,(function*(){{const n=new _t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}join(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.join(e)}leave(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.leave(e)}leaveAll(){var e;null===(e=this.presenceEventEngine)||void 0===e||e.leaveAll()}grantToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Token error: PAM module disabled")}))}revokeToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Revoke Token error: PAM module disabled")}))}get token(){return this.tokenManager&&this.tokenManager.getToken()}getToken(){return this.token}set token(e){this.tokenManager&&this.tokenManager.setToken(e)}setToken(e){this.token=e}parseToken(e){return this.tokenManager&&this.tokenManager.parseToken(e)}grant(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant error: PAM module disabled")}))}audit(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Permissions error: PAM module disabled")}))}get objects(){return this._objects}fetchUsers(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllUUIDMetadata(e,t)}))}fetchUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getUUIDMetadata(e,t)}))}createUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}updateUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}removeUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeUUIDMetadata(e,t)}))}fetchSpaces(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllChannelMetadata(e,t)}))}fetchSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getChannelMetadata(e,t)}))}createSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}updateSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}removeSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeChannelMetadata(e,t)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.fetchMemberships(e,t)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}updateMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var n,s,r;{if("spaceId"in e){const r=e,i={channel:null!==(n=r.spaceId)&&void 0!==n?n:r.channel,uuids:null!==(s=r.userIds)&&void 0!==s?s:r.uuids,limit:0};return t?this.objects.removeChannelMembers(i,t):this.objects.removeChannelMembers(i)}const i=e,a={uuid:i.userId,channels:null!==(r=i.spaceIds)&&void 0!==r?r:i.channels,limit:0};return t?this.objects.removeMemberships(a,t):this.objects.removeMemberships(a)}}))}get channelGroups(){return this._channelGroups}get push(){return this._push}sendFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const n=new zt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,fileUploadPublishRetryLimit:this._configuration.fileUploadPublishRetryLimit,file:e.file,sendRequest:this.sendRequest.bind(this),publishFile:this.publishFile.bind(this),crypto:this._configuration.getCryptoModule(),cryptography:this.cryptography?this.cryptography:void 0})),s={error:!1,operation:ie.PNPublishFileOperation,category:h.PNAcknowledgmentCategory,statusCode:0};return n.process().then((e=>(s.statusCode=e.status,t?t(s,e):e))).catch((e=>{let n;throw e instanceof d?n=e.status:e instanceof j&&(n=e.toStatus(s.operation)),t&&n&&t(n,null),new d("REST API request processing error, check status for details",n)}))}}))}publishFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const n=new Kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}listFiles(e,t){return i(this,void 0,void 0,(function*(){{const n=new Bt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}getFileUrl(e){var t;{const n=this.transport.request(new $t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})).request()),s=null!==(t=n.queryParameters)&&void 0!==t?t:{},r=Object.keys(s).map((e=>{const t=s[e];return Array.isArray(t)?t.map((t=>`${e}=${$(t)}`)).join("&"):`${e}=${$(t)}`})).join("&");return`${n.origin}${n.path}?${r}`}}downloadFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const n=new Mn(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,cryptography:this.cryptography?this.cryptography:void 0,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(n,t):yield this.sendRequest(n)}}))}deleteFile(e,t){return i(this,void 0,void 0,(function*(){{const n=new Lt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}time(e){return i(this,void 0,void 0,(function*(){const t=new Pn;return e?this.sendRequest(t,e):this.sendRequest(t)}))}encrypt(e,t){const n=this._configuration.getCryptoModule();if(!t&&n&&"string"==typeof e){const t=n.encrypt(e);return"string"==typeof t?t:u(t)}if(!this.crypto)throw new Error("Encryption error: cypher key not set");return this.crypto.encrypt(e,t)}decrypt(e,t){const n=this._configuration.getCryptoModule();if(!t&&n){const t=n.decrypt(e);return t instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(t)):t}if(!this.crypto)throw new Error("Decryption error: cypher key not set");return this.crypto.decrypt(e,t)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var n;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File encryption error. File constructor not configured.");if("string"!=typeof e&&!this._configuration.getCryptoModule())throw new Error("File encryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File encryption error. File encryption not available");return this.cryptography.encryptFile(e,t,this._configuration.PubNubFile)}return null===(n=this._configuration.getCryptoModule())||void 0===n?void 0:n.encryptFile(t,this._configuration.PubNubFile)}))}decryptFile(e,t){return i(this,void 0,void 0,(function*(){var n;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File decryption error. File constructor not configured.");if("string"==typeof e&&!this._configuration.getCryptoModule())throw new Error("File decryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File decryption error. File decryption not available");return this.cryptography.decryptFile(e,t,this._configuration.PubNubFile)}return null===(n=this._configuration.getCryptoModule())||void 0===n?void 0:n.decryptFile(t,this._configuration.PubNubFile)}))}}_n.decoder=new TextDecoder,_n.OPERATIONS=ie,_n.CATEGORIES=h,_n.ExponentialRetryPolicy=Be.ExponentialRetryPolicy,_n.LinearRetryPolicy=Be.LinearRetryPolicy;class An{constructor(e,t){this.decode=e,this.base64ToBinary=t}decodeToken(e){let t="";e.length%4==3?t="=":e.length%4==2&&(t="==");const n=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,s=this.decode(this.base64ToBinary(n));return"object"==typeof s?s:void 0}}class jn extends _n{constructor(e){var t;const n=T(e),r=Object.assign(Object.assign({},n),{sdkFamily:"Web"});r.PubNubFile=o;const i=D(r,(e=>{if(e.cipherKey)return new M({default:new P(Object.assign({},e)),cryptors:[new O({cipherKey:e.cipherKey})]})}));let a,u,l;a=new G(new An((e=>F(s.decode(e))),c)),(i.getCipherKey()||i.secretKey)&&(u=new C({secretKey:i.secretKey,cipherKey:i.getCipherKey(),useRandomIVs:i.getUseRandomIVs(),customEncrypt:i.getCustomEncrypt(),customDecrypt:i.getCustomDecrypt()})),l=new N;let h=new W(r.transport,i.keepAlive,i.logVerbosity);n.subscriptionWorkerUrl&&(h=new I({clientIdentifier:i._instanceId,subscriptionKey:i.subscribeKey,userId:i.getUserId(),workerUrl:n.subscriptionWorkerUrl,sdkVersion:i.getVersion(),heartbeatInterval:i.getHeartbeatInterval(),logVerbosity:i.logVerbosity,workerLogVerbosity:r.subscriptionWorkerLogVerbosity,transport:h}));super({configuration:i,transport:new z({clientConfiguration:i,tokenManager:a,transport:h}),cryptography:l,tokenManager:a,crypto:u}),(null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t)&&(window.addEventListener("offline",(()=>{this.networkDownDetected()})),window.addEventListener("online",(()=>{this.networkUpDetected()})))}networkDownDetected(){this.listenerManager.announceNetworkDown(),this._configuration.restore?this.disconnect():this.destroy(!0)}networkUpDetected(){this.listenerManager.announceNetworkUp(),this.reconnect()}}return jn.CryptoModule=M,jn})); diff --git a/lib/core/components/configuration.js b/lib/core/components/configuration.js index 7a695af9e..3340b856d 100644 --- a/lib/core/components/configuration.js +++ b/lib/core/components/configuration.js @@ -120,7 +120,7 @@ const makeConfiguration = (base, setupCryptoModule) => { return base.PubNubFile; }, get version() { - return '8.8.1'; + return '8.9.0'; }, getVersion() { return this.version; diff --git a/lib/core/components/request.js b/lib/core/components/request.js index 7196b965d..8ef292d73 100644 --- a/lib/core/components/request.js +++ b/lib/core/components/request.js @@ -20,8 +20,8 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.AbstractRequest = void 0; const transport_request_1 = require("../types/transport-request"); const pubnub_error_1 = require("../../errors/pubnub-error"); -const uuid_1 = __importDefault(require("./uuid")); const pubnub_api_error_1 = require("../../errors/pubnub-api-error"); +const uuid_1 = __importDefault(require("./uuid")); /** * Base REST API request class. * @@ -183,9 +183,8 @@ class AbstractRequest { throw new pubnub_error_1.PubNubError('Service response error, check status for details', (0, pubnub_error_1.createMalformedResponseError)(responseText, response.status)); } // Throw and exception in case of client / server error. - if ('status' in parsedJson && typeof parsedJson.status === 'number' && parsedJson.status >= 400) { + if ('status' in parsedJson && typeof parsedJson.status === 'number' && parsedJson.status >= 400) throw pubnub_api_error_1.PubNubAPIError.create(response); - } return parsedJson; } } diff --git a/lib/core/components/subscription-manager.js b/lib/core/components/subscription-manager.js index ae58f99fe..a40977e7f 100644 --- a/lib/core/components/subscription-manager.js +++ b/lib/core/components/subscription-manager.js @@ -22,7 +22,6 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.SubscriptionManager = void 0; const reconnection_manager_1 = require("./reconnection_manager"); const categories_1 = __importDefault(require("../constants/categories")); -const categories_2 = __importDefault(require("../constants/categories")); const deduping_manager_1 = require("./deduping_manager"); /** * Subscription loop manager. @@ -229,10 +228,10 @@ class SubscriptionManager { status.errorData.name === 'AbortError') || status.category === categories_1.default.PNCancelledCategory) return; - if (status.category === categories_2.default.PNTimeoutCategory) { + if (status.category === categories_1.default.PNTimeoutCategory) { this.startSubscribeLoop(); } - else if (status.category === categories_2.default.PNNetworkIssuesCategory) { + else if (status.category === categories_1.default.PNNetworkIssuesCategory) { this.disconnect(); if (status.error && this.configuration.autoNetworkDetection && this.isOnline) { this.isOnline = false; @@ -246,7 +245,7 @@ class SubscriptionManager { this.reconnect(); this.subscriptionStatusAnnounced = true; const reconnectedAnnounce = { - category: categories_2.default.PNReconnectedCategory, + category: categories_1.default.PNReconnectedCategory, operation: status.operation, lastTimetoken: this.lastTimetoken, currentTimetoken: this.currentTimetoken, @@ -256,8 +255,8 @@ class SubscriptionManager { this.reconnectionManager.startPolling(); this.listenerManager.announceStatus(status); } - else if (status.category === categories_2.default.PNBadRequestCategory || - status.category == categories_2.default.PNMalformedResponseCategory) { + else if (status.category === categories_1.default.PNBadRequestCategory || + status.category == categories_1.default.PNMalformedResponseCategory) { const category = this.isOnline ? categories_1.default.PNDisconnectedUnexpectedlyCategory : status.category; this.isOnline = false; this.disconnect(); diff --git a/lib/core/endpoints/access_manager/revoke_token.js b/lib/core/endpoints/access_manager/revoke_token.js index 71565caf6..745230e39 100644 --- a/lib/core/endpoints/access_manager/revoke_token.js +++ b/lib/core/endpoints/access_manager/revoke_token.js @@ -49,7 +49,7 @@ class RevokeTokenRequest extends request_1.AbstractRequest { parse: { get: () => super.parse } }); return __awaiter(this, void 0, void 0, function* () { - return _super.parse.call(this, response).then(() => ({})); + return _super.parse.call(this, response).then((_) => ({})); }); } get path() { diff --git a/lib/transport/node-transport.js b/lib/transport/node-transport.js index 3a62bfb38..91884f872 100644 --- a/lib/transport/node-transport.js +++ b/lib/transport/node-transport.js @@ -129,7 +129,7 @@ class NodeTransport { if (errorMessage.includes('timeout') || !errorMessage.includes('cancel')) fetchError = new Error(error); else if (errorMessage.includes('cancel')) - fetchError = new DOMException('Aborted', 'AbortError'); + fetchError = new node_fetch_1.AbortError('Aborted'); } throw pubnub_api_error_1.PubNubAPIError.create(fetchError); }); diff --git a/lib/transport/react-native-transport.js b/lib/transport/react-native-transport.js index dfb5ddcb1..4372dcdd1 100644 --- a/lib/transport/react-native-transport.js +++ b/lib/transport/react-native-transport.js @@ -96,8 +96,10 @@ class ReactNativeTransport { const errorMessage = error.toLowerCase(); if (errorMessage.includes('timeout') || !errorMessage.includes('cancel')) fetchError = new Error(error); - else if (errorMessage.includes('cancel')) - fetchError = new DOMException('Aborted', 'AbortError'); + else if (errorMessage.includes('cancel')) { + fetchError = new Error('Aborted'); + fetchError.name = 'AbortError'; + } } throw pubnub_api_error_1.PubNubAPIError.create(fetchError); }); diff --git a/package.json b/package.json index 504b4d8ca..41fc4a0c1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "pubnub", - "version": "8.8.1", + "version": "8.9.0", "author": "PubNub ", "description": "Publish & Subscribe Real-time Messaging with PubNub", "scripts": { diff --git a/src/core/components/configuration.ts b/src/core/components/configuration.ts index e53d26192..e66e67c05 100644 --- a/src/core/components/configuration.ts +++ b/src/core/components/configuration.ts @@ -178,7 +178,7 @@ export const makeConfiguration = ( return base.PubNubFile; }, get version(): string { - return '8.8.1'; + return '8.9.0'; }, getVersion(): string { return this.version;