diff --git a/.prettierrc b/.prettierrc index cb71e61f6..2eccbc62e 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,4 +1,5 @@ { + "parser" : "typescript", "semi": true, "printWidth": 120, "singleQuote": true, diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index 7ba541855..5ee09af9b 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -423,522 +423,6 @@ var cborExports = cbor.exports; var CborReader = /*@__PURE__*/getDefaultExportFromCjs(cborExports); - /** - * Request processing status categories. - */ - var StatusCategory; - (function (StatusCategory) { - /** - * Call failed when network was unable to complete the call. - */ - StatusCategory["PNNetworkIssuesCategory"] = "PNNetworkIssuesCategory"; - /** - * Network call timed out. - */ - StatusCategory["PNTimeoutCategory"] = "PNTimeoutCategory"; - /** - * Request has been cancelled. - */ - StatusCategory["PNCancelledCategory"] = "PNCancelledCategory"; - /** - * Server responded with bad response. - */ - StatusCategory["PNBadRequestCategory"] = "PNBadRequestCategory"; - /** - * Server responded with access denied. - */ - StatusCategory["PNAccessDeniedCategory"] = "PNAccessDeniedCategory"; - /** - * Incomplete parameters provided for used endpoint. - */ - StatusCategory["PNValidationErrorCategory"] = "PNValidationErrorCategory"; - /** - * PubNub request acknowledgment status. - * - * Some API endpoints respond with request processing status w/o useful data. - */ - StatusCategory["PNAcknowledgmentCategory"] = "PNAcknowledgmentCategory"; - /** - * Something strange happened; please check the logs. - */ - StatusCategory["PNUnknownCategory"] = "PNUnknownCategory"; - // -------------------------------------------------------- - // --------------------- Network status ------------------- - // -------------------------------------------------------- - /** - * SDK will announce when the network appears to be connected again. - */ - StatusCategory["PNNetworkUpCategory"] = "PNNetworkUpCategory"; - /** - * SDK will announce when the network appears to down. - */ - StatusCategory["PNNetworkDownCategory"] = "PNNetworkDownCategory"; - // -------------------------------------------------------- - // -------------------- Real-time events ------------------ - // -------------------------------------------------------- - /** - * PubNub client reconnected to the real-time updates stream. - */ - StatusCategory["PNReconnectedCategory"] = "PNReconnectedCategory"; - /** - * PubNub client connected to the real-time updates stream. - */ - StatusCategory["PNConnectedCategory"] = "PNConnectedCategory"; - /** - * Received real-time updates exceed specified threshold. - * - * After temporary disconnection and catchup, this category means that potentially some - * real-time updates have been pushed into `storage` and need to be requested separately. - */ - StatusCategory["PNRequestMessageCountExceededCategory"] = "PNRequestMessageCountExceededCategory"; - /** - * PubNub client disconnected from the real-time updates streams. - */ - StatusCategory["PNDisconnectedCategory"] = "PNDisconnectedCategory"; - /** - * PubNub client wasn't able to connect to the real-time updates streams. - */ - StatusCategory["PNConnectionErrorCategory"] = "PNConnectionErrorCategory"; - /** - * PubNub client unexpectedly disconnected from the real-time updates streams. - */ - StatusCategory["PNDisconnectedUnexpectedlyCategory"] = "PNDisconnectedUnexpectedlyCategory"; - })(StatusCategory || (StatusCategory = {})); - var StatusCategory$1 = StatusCategory; - - class PubNubError extends Error { - constructor(message, status) { - super(message); - this.status = status; - this.name = 'PubNubError'; - this.message = message; - Object.setPrototypeOf(this, new.target.prototype); - } - } - function createError(errorPayload) { - 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 }); - } - function createValidationError(message, statusCode) { - return createError(Object.assign({ message }, (statusCode !== undefined ? { statusCode } : {}))); - } - - /** - * REST API endpoint use error module. - */ - /** - * PubNub REST API call error. - */ - class PubNubAPIError extends Error { - /** - * Construct API from known error object or {@link PubNub} service error response. - * - * @param errorOrResponse - `Error` or service error response object from which error information - * should be extracted. - * @param data - Preprocessed service error response. - * - * @returns `PubNubAPIError` object with known error category and additional information (if - * available). - */ - static create(errorOrResponse, data) { - if (errorOrResponse instanceof Error) - return PubNubAPIError.createFromError(errorOrResponse); - else - return PubNubAPIError.createFromServiceResponse(errorOrResponse, data); - } - /** - * Create API error instance from other error object. - * - * @param error - `Error` object provided by network provider (mostly) or other {@link PubNub} client components. - * - * @returns `PubNubAPIError` object with known error category and additional information (if - * available). - */ - static createFromError(error) { - let category = StatusCategory$1.PNUnknownCategory; - let message = 'Unknown error'; - let errorName = 'Error'; - if (!error) - return new PubNubAPIError(message, category, 0); - else if (error instanceof PubNubAPIError) - return error; - if (error instanceof Error) { - message = error.message; - errorName = error.name; - } - if (errorName === 'AbortError' || message.indexOf('Aborted') !== -1) { - category = StatusCategory$1.PNCancelledCategory; - message = 'Request cancelled'; - } - else if (message.indexOf('timeout') !== -1) { - category = StatusCategory$1.PNTimeoutCategory; - message = 'Request timeout'; - } - else if (message.indexOf('network') !== -1) { - category = StatusCategory$1.PNNetworkIssuesCategory; - message = 'Network issues'; - } - else if (errorName === 'TypeError') { - category = StatusCategory$1.PNBadRequestCategory; - } - else if (errorName === 'FetchError') { - const errorCode = error.code; - if (['ECONNREFUSED', 'ENETUNREACH', 'ENOTFOUND', 'ECONNRESET', 'EAI_AGAIN'].includes(errorCode)) - category = StatusCategory$1.PNNetworkIssuesCategory; - if (errorCode === 'ECONNREFUSED') - message = 'Connection refused'; - else if (errorCode === 'ENETUNREACH') - message = 'Network not reachable'; - else if (errorCode === 'ENOTFOUND') - message = 'Server not found'; - else if (errorCode === 'ECONNRESET') - message = 'Connection reset by peer'; - else if (errorCode === 'EAI_AGAIN') - message = 'Name resolution error'; - else if (errorCode === 'ETIMEDOUT') { - category = StatusCategory$1.PNTimeoutCategory; - message = 'Request timeout'; - } - else - message = `Unknown system error: ${error}`; - } - else if (message === 'Request timeout') - category = StatusCategory$1.PNTimeoutCategory; - return new PubNubAPIError(message, category, 0, error); - } - /** - * Construct API from known {@link PubNub} service error response. - * - * @param response - Service error response object from which error information should be - * extracted. - * @param data - Preprocessed service error response. - * - * @returns `PubNubAPIError` object with known error category and additional information (if - * available). - */ - static createFromServiceResponse(response, data) { - let category = StatusCategory$1.PNUnknownCategory; - let errorData; - let message = 'Unknown error'; - let { status } = response; - data !== null && data !== void 0 ? data : (data = response.body); - if (status === 402) - message = 'Not available for used key set. Contact support@pubnub.com'; - else if (status === 400) { - category = StatusCategory$1.PNBadRequestCategory; - message = 'Bad request'; - } - else if (status === 403) { - category = StatusCategory$1.PNAccessDeniedCategory; - message = 'Access denied'; - } - // Try to get more information about error from service response. - if (data && data.byteLength > 0) { - const decoded = new TextDecoder().decode(data); - if (response.headers['content-type'].indexOf('text/javascript') !== -1 || - 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; - } - else - errorData = errorResponse; - if ('error' in errorResponse && errorResponse.error instanceof Error) - errorData = errorResponse.error; - } - } - catch (_) { - errorData = decoded; - } - } - else if (response.headers['content-type'].indexOf('xml') !== -1) { - const reason = /(.*)<\/Message>/gi.exec(decoded); - message = reason ? `Upload to bucket failed: ${reason[1]}` : 'Upload to bucket failed.'; - } - else { - errorData = decoded; - } - } - return new PubNubAPIError(message, category, status, errorData); - } - /** - * Construct PubNub endpoint error. - * - * @param message - Short API call error description. - * @param category - Error category. - * @param statusCode - Response HTTP status code. - * @param errorData - Error information. - */ - constructor(message, category, statusCode, errorData) { - super(message); - this.category = category; - this.statusCode = statusCode; - this.errorData = errorData; - this.name = 'PubNubAPIError'; - } - /** - * Convert API error object to API callback status object. - * - * @param operation - Request operation during which error happened. - * - * @returns Pre-formatted API callback status object. - */ - toStatus(operation) { - return { - error: true, - category: this.category, - operation, - statusCode: this.statusCode, - errorData: this.errorData, - }; - } - /** - * Convert API error object to PubNub client error object. - * - * @param operation - Request operation during which error happened. - * @param message - Custom error message. - * - * @returns Client-facing pre-formatted endpoint call error. - */ - toPubNubError(operation, message) { - return new PubNubError(message !== null && message !== void 0 ? message : this.message, this.toStatus(operation)); - } - } - - /** - * Subscription Service Worker transport middleware module. - * - * Middleware optimize subscription feature requests utilizing `Subscription Service Worker` if available and not - * disabled by user. - */ - // endregion - /** - * Subscription Service Worker transport middleware. - */ - class SubscriptionServiceWorkerMiddleware { - constructor(configuration) { - this.configuration = configuration; - this.serviceWorkerEventsQueue = []; - this.callbacks = new Map(); - this.setupServiceWorker(); - } - makeSendable(req) { - // Use default request flow for non-subscribe / presence leave requests. - if (!req.path.startsWith('/v2/subscribe') && !req.path.endsWith('/leave')) - return this.configuration.transport.makeSendable(req); - let controller; - const sendRequestEvent = { - type: 'send-request', - clientIdentifier: this.configuration.clientIdentifier, - subscriptionKey: this.configuration.subscriptionKey, - logVerbosity: this.configuration.logVerbosity, - request: req, - }; - if (req.cancellable) { - controller = { - abort: () => { - const cancelRequest = { - type: 'cancel-request', - clientIdentifier: this.configuration.clientIdentifier, - subscriptionKey: this.configuration.subscriptionKey, - logVerbosity: this.configuration.logVerbosity, - identifier: req.identifier, - }; - // Cancel active request with specified identifier. - this.scheduleEventPost(cancelRequest); - }, - }; - } - return [ - new Promise((resolve, reject) => { - // Associate Promise resolution / reject with request identifier for future usage in - // `onmessage` handler block to return results. - this.callbacks.set(req.identifier, { resolve, reject }); - // Trigger request processing by Service Worker. - this.scheduleEventPost(sendRequestEvent); - }), - controller, - ]; - } - request(req) { - return req; - } - /** - * Schedule {@link event} publish to the service worker. - * - * Service worker may not be ready for events processing and this method build queue for the time when worker will be - * ready. - * - * @param event - Event payload for service worker. - * @param outOfOrder - Whether event should be processed first then enqueued queue. - */ - scheduleEventPost(event, outOfOrder = false) { - // Trigger request processing by Web Worker. - const serviceWorker = this.serviceWorker; - if (serviceWorker) - serviceWorker.postMessage(event); - else { - if (outOfOrder) - this.serviceWorkerEventsQueue.splice(0, 0, event); - else - this.serviceWorkerEventsQueue.push(event); - } - } - /** - * Dequeue and post events from the queue to the service worker. - */ - flushScheduledEvents() { - // Trigger request processing by Web Worker. - const serviceWorker = this.serviceWorker; - if (!serviceWorker || this.serviceWorkerEventsQueue.length === 0) - return; - // Clean up from cancelled events. - const outdatedEvents = []; - for (let i = 0; i < this.serviceWorkerEventsQueue.length; i++) { - const event = this.serviceWorkerEventsQueue[i]; - // Check whether found request cancel event to search for request send event it cancels. - if (event.type !== 'cancel-request' || i === 0) - continue; - for (let j = 0; j < i; j++) { - const otherEvent = this.serviceWorkerEventsQueue[j]; - if (otherEvent.type !== 'send-request') - continue; - // Collect outdated events if identifiers match. - if (otherEvent.request.identifier === event.identifier) { - outdatedEvents.push(event, otherEvent); - break; - } - } - } - // Actualizing events queue. - this.serviceWorkerEventsQueue = this.serviceWorkerEventsQueue.filter((event) => !outdatedEvents.includes(event)); - this.serviceWorkerEventsQueue.forEach((event) => serviceWorker.postMessage(event)); - this.serviceWorkerEventsQueue = []; - } - /** - * Subscription service worker. - * - * @returns Service worker which has been registered by the PubNub SDK. - */ - get serviceWorker() { - return this.serviceWorkerRegistration ? this.serviceWorkerRegistration.active : null; - } - setupServiceWorker() { - if (!('serviceWorker' in navigator)) - return; - const serviceWorkerContainer = navigator.serviceWorker; - serviceWorkerContainer - .register(this.configuration.serviceWorkerUrl, { - scope: `/pubnub-${this.configuration.sdkVersion}`, - }) - .then((registration) => { - this.serviceWorkerRegistration = registration; - // Flush any pending service worker events. - if (registration.active) - this.flushScheduledEvents(); - /** - * Listening for service worker code update. - * - * It is possible that one of the tabs will open with newer SDK version and Subscription Service Worker - * will be re-installed - in this case we need to "rehydrate" it. - * - * After re-installation of new service worker it will lose all accumulated state and client need to - * re-introduce itself and its state. - */ - this.serviceWorkerRegistration.addEventListener('updatefound', () => { - if (!this.serviceWorkerRegistration) - return; - // New service installing right now. - const serviceWorker = this.serviceWorkerRegistration.installing; - const stateChangeListener = () => { - // Flush any pending service worker events. - if (serviceWorker.state === 'activated') { - // Flush any pending service worker events. - this.flushScheduledEvents(); - } - else if (serviceWorker.state === 'redundant') { - // Clean up listener from deprecated service worker version. - serviceWorker.removeEventListener('statechange', stateChangeListener); - } - }; - serviceWorker.addEventListener('statechange', stateChangeListener); - }); - }); - serviceWorkerContainer.addEventListener('message', (event) => this.handleServiceWorkerEvent(event)); - } - handleServiceWorkerEvent(event) { - const { data } = event; - // Ignoring updates not related to this instance. - if (data.clientIdentifier !== this.configuration.clientIdentifier) - return; - if (data.type === 'request-progress-start' || data.type === 'request-progress-end') { - this.logRequestProgress(data); - } - else if (data.type === 'request-process-success' || data.type === 'request-process-error') { - const { resolve, reject } = this.callbacks.get(data.identifier); - if (data.type === 'request-process-success') { - resolve({ - status: data.response.status, - url: data.url, - headers: data.response.headers, - body: data.response.body, - }); - } - else { - let category = StatusCategory$1.PNUnknownCategory; - let message = 'Unknown error'; - // Handle client-side issues (if any). - if (data.error) { - if (data.error.type === 'NETWORK_ISSUE') - category = StatusCategory$1.PNNetworkIssuesCategory; - else if (data.error.type === 'TIMEOUT') - category = StatusCategory$1.PNTimeoutCategory; - else if (data.error.type === 'ABORTED') - category = StatusCategory$1.PNCancelledCategory; - message = `${data.error.message} (${data.identifier})`; - } - // Handle service error response. - else if (data.response) { - return reject(PubNubAPIError.create({ - url: data.url, - headers: data.response.headers, - body: data.response.body, - status: data.response.status, - }, data.response.body)); - } - reject(new PubNubAPIError(message, category, 0, new Error(message))); - } - } - } - /** - * Print request progress information. - * - * @param information - Request progress information from Web Worker. - */ - logRequestProgress(information) { - var _a, _b; - if (information.type === 'request-progress-start') { - console.log('<<<<<'); - console.log(`[${information.timestamp}] ${information.url}\n${JSON.stringify((_a = information.query) !== null && _a !== void 0 ? _a : {})}`); - console.log('-----'); - } - else { - console.log('>>>>>>'); - console.log(`[${information.timestamp} / ${information.duration}] ${information.url}\n${JSON.stringify((_b = information.query) !== null && _b !== void 0 ? _b : {})}\n${information.response}`); - console.log('-----'); - } - } - } - /****************************************************************************** Copyright (c) Microsoft Corporation. @@ -1217,6 +701,8 @@ * * @param paddedInput Base64 string with padding * @returns ArrayBuffer with decoded data + * + * @internal */ function decode(paddedInput) { // Remove up to last two equal signs. @@ -1255,46 +741,155 @@ if (sx4 != 64) view[i + 2] = oc3; } - return data; + return data; + } + /** + * Encode `ArrayBuffer` as a Base64 encoded string. + * + * @param input ArrayBuffer with source data. + * @returns Base64 string with padding. + * + * @internal + */ + function encode(input) { + let base64 = ''; + const encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + const bytes = new Uint8Array(input); + const byteLength = bytes.byteLength; + const byteRemainder = byteLength % 3; + const mainLength = byteLength - byteRemainder; + let a, b, c, d; + let chunk; + // Main loop deals with bytes in chunks of 3 + for (let i = 0; i < mainLength; i = i + 3) { + // Combine the three bytes into a single integer + chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; + // Use bitmasks to extract 6-bit segments from the triplet + a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18 + b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12 + c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6 + d = chunk & 63; // 63 = 2^6 - 1 + // Convert the raw binary segments to the appropriate ASCII encoding + base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]; + } + // Deal with the remaining bytes and padding + if (byteRemainder == 1) { + chunk = bytes[mainLength]; + a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2 + // Set the 4 least significant bits to zero + b = (chunk & 3) << 4; // 3 = 2^2 - 1 + base64 += encodings[a] + encodings[b] + '=='; + } + else if (byteRemainder == 2) { + chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]; + a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10 + b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4 + // Set the 2 least significant bits to zero + c = (chunk & 15) << 2; // 15 = 2^4 - 1 + base64 += encodings[a] + encodings[b] + encodings[c] + '='; + } + return base64; + } + + /** + * Request processing status categories. + */ + var StatusCategory; + (function (StatusCategory) { + /** + * Call failed when network was unable to complete the call. + */ + StatusCategory["PNNetworkIssuesCategory"] = "PNNetworkIssuesCategory"; + /** + * Network call timed out. + */ + StatusCategory["PNTimeoutCategory"] = "PNTimeoutCategory"; + /** + * Request has been cancelled. + */ + StatusCategory["PNCancelledCategory"] = "PNCancelledCategory"; + /** + * Server responded with bad response. + */ + StatusCategory["PNBadRequestCategory"] = "PNBadRequestCategory"; + /** + * Server responded with access denied. + */ + StatusCategory["PNAccessDeniedCategory"] = "PNAccessDeniedCategory"; + /** + * Incomplete parameters provided for used endpoint. + */ + StatusCategory["PNValidationErrorCategory"] = "PNValidationErrorCategory"; + /** + * PubNub request acknowledgment status. + * + * Some API endpoints respond with request processing status w/o useful data. + */ + StatusCategory["PNAcknowledgmentCategory"] = "PNAcknowledgmentCategory"; + /** + * Something strange happened; please check the logs. + */ + StatusCategory["PNUnknownCategory"] = "PNUnknownCategory"; + // -------------------------------------------------------- + // --------------------- Network status ------------------- + // -------------------------------------------------------- + /** + * SDK will announce when the network appears to be connected again. + */ + StatusCategory["PNNetworkUpCategory"] = "PNNetworkUpCategory"; + /** + * SDK will announce when the network appears to down. + */ + StatusCategory["PNNetworkDownCategory"] = "PNNetworkDownCategory"; + // -------------------------------------------------------- + // -------------------- Real-time events ------------------ + // -------------------------------------------------------- + /** + * PubNub client reconnected to the real-time updates stream. + */ + StatusCategory["PNReconnectedCategory"] = "PNReconnectedCategory"; + /** + * PubNub client connected to the real-time updates stream. + */ + StatusCategory["PNConnectedCategory"] = "PNConnectedCategory"; + /** + * Received real-time updates exceed specified threshold. + * + * After temporary disconnection and catchup, this category means that potentially some + * real-time updates have been pushed into `storage` and need to be requested separately. + */ + StatusCategory["PNRequestMessageCountExceededCategory"] = "PNRequestMessageCountExceededCategory"; + /** + * PubNub client disconnected from the real-time updates streams. + */ + StatusCategory["PNDisconnectedCategory"] = "PNDisconnectedCategory"; + /** + * PubNub client wasn't able to connect to the real-time updates streams. + */ + StatusCategory["PNConnectionErrorCategory"] = "PNConnectionErrorCategory"; + /** + * PubNub client unexpectedly disconnected from the real-time updates streams. + */ + StatusCategory["PNDisconnectedUnexpectedlyCategory"] = "PNDisconnectedUnexpectedlyCategory"; + })(StatusCategory || (StatusCategory = {})); + var StatusCategory$1 = StatusCategory; + + class PubNubError extends Error { + constructor(message, status) { + super(message); + this.status = status; + this.name = 'PubNubError'; + this.message = message; + Object.setPrototypeOf(this, new.target.prototype); + } } - function encode(input) { - let base64 = ''; - const encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - const bytes = new Uint8Array(input); - const byteLength = bytes.byteLength; - const byteRemainder = byteLength % 3; - const mainLength = byteLength - byteRemainder; - let a, b, c, d; - let chunk; - // Main loop deals with bytes in chunks of 3 - for (let i = 0; i < mainLength; i = i + 3) { - // Combine the three bytes into a single integer - chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; - // Use bitmasks to extract 6-bit segments from the triplet - a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18 - b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12 - c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6 - d = chunk & 63; // 63 = 2^6 - 1 - // Convert the raw binary segments to the appropriate ASCII encoding - base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]; - } - // Deal with the remaining bytes and padding - if (byteRemainder == 1) { - chunk = bytes[mainLength]; - a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2 - // Set the 4 least significant bits to zero - b = (chunk & 3) << 4; // 3 = 2^2 - 1 - base64 += encodings[a] + encodings[b] + '=='; - } - else if (byteRemainder == 2) { - chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]; - a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10 - b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4 - // Set the 2 least significant bits to zero - c = (chunk & 15) << 2; // 15 = 2^4 - 1 - base64 += encodings[a] + encodings[b] + encodings[c] + '='; - } - return base64; + function createError(errorPayload) { + 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 }); + } + function createValidationError(message, statusCode) { + return createError(Object.assign({ message }, (statusCode !== undefined ? { statusCode } : {}))); } /*eslint-disable */ @@ -3020,173 +2615,590 @@ throw Error('Unknown cryptor error'); } /** - * Retrieve cryptor by its identifier. + * Retrieve cryptor by its identifier. + * + * @param header - Header with cryptor-defined data or raw cryptor identifier. + * + * @returns Cryptor which correspond to provided {@link header}. + */ + getCryptor(header) { + if (typeof header === 'string') { + const cryptor = this.getAllCryptors().find((cryptor) => cryptor.identifier === header); + if (cryptor) + return cryptor; + throw new Error('Unknown cryptor error'); + } + else if (header instanceof CryptorHeaderV1) { + return this.getCryptorFromId(header.identifier); + } + } + /** + * Create cryptor header data. + * + * @param encrypted - Encryption data object as source for header data. + * + * @returns Binary representation of the cryptor header data. + */ + getHeaderData(encrypted) { + if (!encrypted.metadata) + return; + const header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); + const headerData = new Uint8Array(header.length); + let pos = 0; + headerData.set(header.data, pos); + pos += header.length - encrypted.metadata.byteLength; + headerData.set(new Uint8Array(encrypted.metadata), pos); + return headerData.buffer; + } + /** + * Merge two {@link ArrayBuffer} instances. + * + * @param ab1 - First {@link ArrayBuffer}. + * @param ab2 - Second {@link ArrayBuffer}. + * + * @returns Merged data as {@link ArrayBuffer}. + */ + concatArrayBuffer(ab1, ab2) { + const tmp = new Uint8Array(ab1.byteLength + ab2.byteLength); + tmp.set(new Uint8Array(ab1), 0); + tmp.set(new Uint8Array(ab2), ab1.byteLength); + return tmp.buffer; + } + /** + * Retrieve file content. + * + * @param file - Content of the {@link PubNub} File object. + * + * @returns Normalized file {@link data} as {@link ArrayBuffer}; + */ + getFileData(file) { + return __awaiter(this, void 0, void 0, function* () { + if (file instanceof ArrayBuffer) + return file; + else if (file instanceof PubNubFile) + return file.toArrayBuffer(); + throw new Error('Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob'); + }); + } + } + /** + * {@link LegacyCryptor|Legacy} cryptor identifier. + */ + WebCryptoModule.LEGACY_IDENTIFIER = ''; + /** + * CryptorHeader Utility + */ + class CryptorHeader { + static from(id, metadata) { + if (id === CryptorHeader.LEGACY_IDENTIFIER) + return; + return new CryptorHeaderV1(id, metadata.byteLength); + } + static tryParse(data) { + const encryptedData = new Uint8Array(data); + let sentinel; + let version = null; + if (encryptedData.byteLength >= 4) { + sentinel = encryptedData.slice(0, 4); + if (this.decoder.decode(sentinel) !== CryptorHeader.SENTINEL) + return WebCryptoModule.LEGACY_IDENTIFIER; + } + if (encryptedData.byteLength >= 5) + version = encryptedData[4]; + else + throw new Error('Decryption error: invalid header version'); + if (version > CryptorHeader.MAX_VERSION) + throw new Error('Decryption error: Unknown cryptor error'); + let identifier; + let pos = 5 + CryptorHeader.IDENTIFIER_LENGTH; + if (encryptedData.byteLength >= pos) + identifier = encryptedData.slice(5, pos); + else + throw new Error('Decryption error: invalid crypto identifier'); + let metadataLength = null; + if (encryptedData.byteLength >= pos + 1) + metadataLength = encryptedData[pos]; + else + throw new Error('Decryption error: invalid metadata length'); + pos += 1; + if (metadataLength === 255 && encryptedData.byteLength >= pos + 2) { + metadataLength = new Uint16Array(encryptedData.slice(pos, pos + 2)).reduce((acc, val) => (acc << 8) + val, 0); + } + return new CryptorHeaderV1(this.decoder.decode(identifier), metadataLength); + } + } + CryptorHeader.SENTINEL = 'PNED'; + CryptorHeader.LEGACY_IDENTIFIER = ''; + CryptorHeader.IDENTIFIER_LENGTH = 4; + CryptorHeader.VERSION = 1; + CryptorHeader.MAX_VERSION = 1; + CryptorHeader.decoder = new TextDecoder(); + // v1 CryptorHeader + class CryptorHeaderV1 { + constructor(id, metadataLength) { + this._identifier = id; + this._metadataLength = metadataLength; + } + get identifier() { + return this._identifier; + } + set identifier(value) { + this._identifier = value; + } + get metadataLength() { + return this._metadataLength; + } + set metadataLength(value) { + this._metadataLength = value; + } + get version() { + return CryptorHeader.VERSION; + } + get length() { + return (CryptorHeader.SENTINEL.length + + 1 + + CryptorHeader.IDENTIFIER_LENGTH + + (this.metadataLength < 255 ? 1 : 3) + + this.metadataLength); + } + get data() { + let pos = 0; + const header = new Uint8Array(this.length); + const encoder = new TextEncoder(); + header.set(encoder.encode(CryptorHeader.SENTINEL)); + pos += CryptorHeader.SENTINEL.length; + header[pos] = this.version; + pos++; + if (this.identifier) + header.set(encoder.encode(this.identifier), pos); + const metadataLength = this.metadataLength; + pos += CryptorHeader.IDENTIFIER_LENGTH; + if (metadataLength < 255) + header[pos] = metadataLength; + else + header.set([255, metadataLength >> 8, metadataLength & 0xff], pos); + return header; + } + } + CryptorHeaderV1.IDENTIFIER_LENGTH = 4; + CryptorHeaderV1.SENTINEL = 'PNED'; + + /** + * REST API endpoint use error module. + */ + /** + * PubNub REST API call error. + */ + class PubNubAPIError extends Error { + /** + * Construct API from known error object or {@link PubNub} service error response. + * + * @param errorOrResponse - `Error` or service error response object from which error information + * should be extracted. + * @param data - Preprocessed service error response. + * + * @returns `PubNubAPIError` object with known error category and additional information (if + * available). + */ + static create(errorOrResponse, data) { + if (errorOrResponse instanceof Error) + return PubNubAPIError.createFromError(errorOrResponse); + else + return PubNubAPIError.createFromServiceResponse(errorOrResponse, data); + } + /** + * Create API error instance from other error object. + * + * @param error - `Error` object provided by network provider (mostly) or other {@link PubNub} client components. + * + * @returns `PubNubAPIError` object with known error category and additional information (if + * available). + */ + static createFromError(error) { + let category = StatusCategory$1.PNUnknownCategory; + let message = 'Unknown error'; + let errorName = 'Error'; + if (!error) + return new PubNubAPIError(message, category, 0); + else if (error instanceof PubNubAPIError) + return error; + if (error instanceof Error) { + message = error.message; + errorName = error.name; + } + if (errorName === 'AbortError' || message.indexOf('Aborted') !== -1) { + category = StatusCategory$1.PNCancelledCategory; + message = 'Request cancelled'; + } + else if (message.indexOf('timeout') !== -1) { + category = StatusCategory$1.PNTimeoutCategory; + message = 'Request timeout'; + } + else if (message.indexOf('network') !== -1) { + category = StatusCategory$1.PNNetworkIssuesCategory; + message = 'Network issues'; + } + else if (errorName === 'TypeError') { + category = StatusCategory$1.PNBadRequestCategory; + } + else if (errorName === 'FetchError') { + const errorCode = error.code; + if (['ECONNREFUSED', 'ENETUNREACH', 'ENOTFOUND', 'ECONNRESET', 'EAI_AGAIN'].includes(errorCode)) + category = StatusCategory$1.PNNetworkIssuesCategory; + if (errorCode === 'ECONNREFUSED') + message = 'Connection refused'; + else if (errorCode === 'ENETUNREACH') + message = 'Network not reachable'; + else if (errorCode === 'ENOTFOUND') + message = 'Server not found'; + else if (errorCode === 'ECONNRESET') + message = 'Connection reset by peer'; + else if (errorCode === 'EAI_AGAIN') + message = 'Name resolution error'; + else if (errorCode === 'ETIMEDOUT') { + category = StatusCategory$1.PNTimeoutCategory; + message = 'Request timeout'; + } + else + message = `Unknown system error: ${error}`; + } + else if (message === 'Request timeout') + category = StatusCategory$1.PNTimeoutCategory; + return new PubNubAPIError(message, category, 0, error); + } + /** + * Construct API from known {@link PubNub} service error response. * - * @param header - Header with cryptor-defined data or raw cryptor identifier. + * @param response - Service error response object from which error information should be + * extracted. + * @param data - Preprocessed service error response. * - * @returns Cryptor which correspond to provided {@link header}. + * @returns `PubNubAPIError` object with known error category and additional information (if + * available). */ - getCryptor(header) { - if (typeof header === 'string') { - const cryptor = this.getAllCryptors().find((cryptor) => cryptor.identifier === header); - if (cryptor) - return cryptor; - throw new Error('Unknown cryptor error'); + static createFromServiceResponse(response, data) { + let category = StatusCategory$1.PNUnknownCategory; + let errorData; + let message = 'Unknown error'; + let { status } = response; + data !== null && data !== void 0 ? data : (data = response.body); + if (status === 402) + message = 'Not available for used key set. Contact support@pubnub.com'; + else if (status === 400) { + category = StatusCategory$1.PNBadRequestCategory; + message = 'Bad request'; } - else if (header instanceof CryptorHeaderV1) { - return this.getCryptorFromId(header.identifier); + else if (status === 403) { + category = StatusCategory$1.PNAccessDeniedCategory; + message = 'Access denied'; + } + // Try to get more information about error from service response. + if (data && data.byteLength > 0) { + const decoded = new TextDecoder().decode(data); + if (response.headers['content-type'].indexOf('text/javascript') !== -1 || + 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; + } + else + errorData = errorResponse; + if ('error' in errorResponse && errorResponse.error instanceof Error) + errorData = errorResponse.error; + } + } + catch (_) { + errorData = decoded; + } + } + else if (response.headers['content-type'].indexOf('xml') !== -1) { + const reason = /(.*)<\/Message>/gi.exec(decoded); + message = reason ? `Upload to bucket failed: ${reason[1]}` : 'Upload to bucket failed.'; + } + else { + errorData = decoded; + } } + return new PubNubAPIError(message, category, status, errorData); } /** - * Create cryptor header data. - * - * @param encrypted - Encryption data object as source for header data. + * Construct PubNub endpoint error. * - * @returns Binary representation of the cryptor header data. + * @param message - Short API call error description. + * @param category - Error category. + * @param statusCode - Response HTTP status code. + * @param errorData - Error information. */ - getHeaderData(encrypted) { - if (!encrypted.metadata) - return; - const header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata); - const headerData = new Uint8Array(header.length); - let pos = 0; - headerData.set(header.data, pos); - pos += header.length - encrypted.metadata.byteLength; - headerData.set(new Uint8Array(encrypted.metadata), pos); - return headerData.buffer; + constructor(message, category, statusCode, errorData) { + super(message); + this.category = category; + this.statusCode = statusCode; + this.errorData = errorData; + this.name = 'PubNubAPIError'; } /** - * Merge two {@link ArrayBuffer} instances. + * Convert API error object to API callback status object. * - * @param ab1 - First {@link ArrayBuffer}. - * @param ab2 - Second {@link ArrayBuffer}. + * @param operation - Request operation during which error happened. * - * @returns Merged data as {@link ArrayBuffer}. + * @returns Pre-formatted API callback status object. */ - concatArrayBuffer(ab1, ab2) { - const tmp = new Uint8Array(ab1.byteLength + ab2.byteLength); - tmp.set(new Uint8Array(ab1), 0); - tmp.set(new Uint8Array(ab2), ab1.byteLength); - return tmp.buffer; + toStatus(operation) { + return { + error: true, + category: this.category, + operation, + statusCode: this.statusCode, + errorData: this.errorData, + }; } /** - * Retrieve file content. + * Convert API error object to PubNub client error object. * - * @param file - Content of the {@link PubNub} File object. + * @param operation - Request operation during which error happened. + * @param message - Custom error message. * - * @returns Normalized file {@link data} as {@link ArrayBuffer}; + * @returns Client-facing pre-formatted endpoint call error. */ - getFileData(file) { - return __awaiter(this, void 0, void 0, function* () { - if (file instanceof ArrayBuffer) - return file; - else if (file instanceof PubNubFile) - return file.toArrayBuffer(); - throw new Error('Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob'); - }); + toPubNubError(operation, message) { + return new PubNubError(message !== null && message !== void 0 ? message : this.message, this.toStatus(operation)); } } + /** - * {@link LegacyCryptor|Legacy} cryptor identifier. + * Subscription Worker transport middleware module. + * + * Middleware optimize subscription feature requests utilizing `Subscription Worker` if available and not disabled + * by user. */ - WebCryptoModule.LEGACY_IDENTIFIER = ''; + // endregion /** - * CryptorHeader Utility + * Subscription Worker transport middleware. */ - class CryptorHeader { - static from(id, metadata) { - if (id === CryptorHeader.LEGACY_IDENTIFIER) - return; - return new CryptorHeaderV1(id, metadata.byteLength); - } - static tryParse(data) { - const encryptedData = new Uint8Array(data); - let sentinel; - let version = null; - if (encryptedData.byteLength >= 4) { - sentinel = encryptedData.slice(0, 4); - if (this.decoder.decode(sentinel) !== CryptorHeader.SENTINEL) - return WebCryptoModule.LEGACY_IDENTIFIER; - } - if (encryptedData.byteLength >= 5) - version = encryptedData[4]; - else - throw new Error('Decryption error: invalid header version'); - if (version > CryptorHeader.MAX_VERSION) - throw new Error('Decryption error: Unknown cryptor error'); - let identifier; - let pos = 5 + CryptorHeader.IDENTIFIER_LENGTH; - if (encryptedData.byteLength >= pos) - identifier = encryptedData.slice(5, pos); - else - throw new Error('Decryption error: invalid crypto identifier'); - let metadataLength = null; - if (encryptedData.byteLength >= pos + 1) - metadataLength = encryptedData[pos]; - else - throw new Error('Decryption error: invalid metadata length'); - pos += 1; - if (metadataLength === 255 && encryptedData.byteLength >= pos + 2) { - metadataLength = new Uint16Array(encryptedData.slice(pos, pos + 2)).reduce((acc, val) => (acc << 8) + val, 0); - } - return new CryptorHeaderV1(this.decoder.decode(identifier), metadataLength); + class SubscriptionWorkerMiddleware { + constructor(configuration) { + this.configuration = configuration; + /** + * Whether subscription worker has been initialized and ready to handle events. + */ + this.subscriptionWorkerReady = false; + this.workerEventsQueue = []; + this.callbacks = new Map(); + this.setupSubscriptionWorker(); } - } - CryptorHeader.SENTINEL = 'PNED'; - CryptorHeader.LEGACY_IDENTIFIER = ''; - CryptorHeader.IDENTIFIER_LENGTH = 4; - CryptorHeader.VERSION = 1; - CryptorHeader.MAX_VERSION = 1; - CryptorHeader.decoder = new TextDecoder(); - // v1 CryptorHeader - class CryptorHeaderV1 { - constructor(id, metadataLength) { - this._identifier = id; - this._metadataLength = metadataLength; + makeSendable(req) { + // Use default request flow for non-subscribe / presence leave requests. + if (!req.path.startsWith('/v2/subscribe') && !req.path.endsWith('/leave')) + return this.configuration.transport.makeSendable(req); + let controller; + const sendRequestEvent = { + type: 'send-request', + clientIdentifier: this.configuration.clientIdentifier, + subscriptionKey: this.configuration.subscriptionKey, + logVerbosity: this.configuration.logVerbosity, + request: req, + }; + if (req.cancellable) { + controller = { + abort: () => { + const cancelRequest = { + type: 'cancel-request', + clientIdentifier: this.configuration.clientIdentifier, + subscriptionKey: this.configuration.subscriptionKey, + logVerbosity: this.configuration.logVerbosity, + identifier: req.identifier, + }; + // Cancel active request with specified identifier. + this.scheduleEventPost(cancelRequest); + }, + }; + } + return [ + new Promise((resolve, reject) => { + // Associate Promise resolution / reject with request identifier for future usage in + // `onmessage` handler block to return results. + this.callbacks.set(req.identifier, { resolve, reject }); + // Trigger request processing by Service Worker. + this.scheduleEventPost(sendRequestEvent); + }), + controller, + ]; } - get identifier() { - return this._identifier; + request(req) { + return req; } - set identifier(value) { - this._identifier = value; + /** + * Schedule {@link event} publish to the subscription worker. + * + * Subscription worker may not be ready for events processing and this method build queue for the time when worker + * will be ready. + * + * @param event - Event payload for the subscription worker. + * @param outOfOrder - Whether event should be processed first then enqueued queue. + */ + scheduleEventPost(event, outOfOrder = false) { + // Trigger request processing by subscription worker. + const subscriptionWorker = this.sharedSubscriptionWorker; + if (subscriptionWorker) + subscriptionWorker.port.postMessage(event); + else { + if (outOfOrder) + this.workerEventsQueue.splice(0, 0, event); + else + this.workerEventsQueue.push(event); + } } - get metadataLength() { - return this._metadataLength; + /** + * Dequeue and post events from the queue to the subscription worker. + */ + flushScheduledEvents() { + // Trigger request processing by subscription worker. + const subscriptionWorker = this.sharedSubscriptionWorker; + if (!subscriptionWorker || this.workerEventsQueue.length === 0) + return; + // Clean up from cancelled events. + const outdatedEvents = []; + for (let i = 0; i < this.workerEventsQueue.length; i++) { + const event = this.workerEventsQueue[i]; + // Check whether found request cancel event to search for request send event it cancels. + if (event.type !== 'cancel-request' || i === 0) + continue; + for (let j = 0; j < i; j++) { + const otherEvent = this.workerEventsQueue[j]; + if (otherEvent.type !== 'send-request') + continue; + // Collect outdated events if identifiers match. + if (otherEvent.request.identifier === event.identifier) { + outdatedEvents.push(event, otherEvent); + break; + } + } + } + // Actualizing events queue. + this.workerEventsQueue = this.workerEventsQueue.filter((event) => !outdatedEvents.includes(event)); + this.workerEventsQueue.forEach((event) => subscriptionWorker.port.postMessage(event)); + this.workerEventsQueue = []; } - set metadataLength(value) { - this._metadataLength = value; + /** + * Subscription worker. + * + * @returns Worker which has been registered by the PubNub SDK. + */ + get sharedSubscriptionWorker() { + return this.subscriptionWorkerReady ? this.subscriptionWorker : null; } - get version() { - return CryptorHeader.VERSION; + setupSubscriptionWorker() { + if (typeof SharedWorker === 'undefined') + return; + this.subscriptionWorker = new SharedWorker(this.configuration.workerUrl, `/pubnub-${this.configuration.sdkVersion}`); + this.subscriptionWorker.port.start(); + // Register PubNub client within subscription worker. + this.scheduleEventPost({ + type: 'client-register', + clientIdentifier: this.configuration.clientIdentifier, + subscriptionKey: this.configuration.subscriptionKey, + userId: this.configuration.userId, + logVerbosity: this.configuration.logVerbosity, + workerLogVerbosity: this.configuration.workerLogVerbosity, + }, true); + this.subscriptionWorker.port.onmessage = (event) => this.handleWorkerEvent(event); } - get length() { - return (CryptorHeader.SENTINEL.length + - 1 + - CryptorHeader.IDENTIFIER_LENGTH + - (this.metadataLength < 255 ? 1 : 3) + - this.metadataLength); + handleWorkerEvent(event) { + const { data } = event; + // Ignoring updates not related to this instance. + if (data.type !== 'shared-worker-ping' && + data.type !== 'shared-worker-connected' && + data.type !== 'shared-worker-console-log' && + data.type !== 'shared-worker-console-dir' && + data.clientIdentifier !== this.configuration.clientIdentifier) + return; + if (data.type === 'shared-worker-connected') { + this.subscriptionWorkerReady = true; + this.flushScheduledEvents(); + } + else if (data.type === 'shared-worker-console-log') { + console.log(`[SharedWorker] ${data.message}`); + } + else if (data.type === 'shared-worker-console-dir') { + if (data.message) + console.log(`[SharedWorker] ${data.message}`); + console.dir(data.data); + } + else if (data.type === 'shared-worker-ping') { + const { logVerbosity, subscriptionKey, clientIdentifier } = this.configuration; + this.scheduleEventPost({ + type: 'client-pong', + subscriptionKey, + clientIdentifier, + logVerbosity, + }); + } + else if (data.type === 'request-progress-start' || data.type === 'request-progress-end') { + this.logRequestProgress(data); + } + else if (data.type === 'request-process-success' || data.type === 'request-process-error') { + const { resolve, reject } = this.callbacks.get(data.identifier); + if (data.type === 'request-process-success') { + resolve({ + status: data.response.status, + url: data.url, + headers: data.response.headers, + body: data.response.body, + }); + } + else { + let category = StatusCategory$1.PNUnknownCategory; + let message = 'Unknown error'; + // Handle client-side issues (if any). + if (data.error) { + if (data.error.type === 'NETWORK_ISSUE') + category = StatusCategory$1.PNNetworkIssuesCategory; + else if (data.error.type === 'TIMEOUT') + category = StatusCategory$1.PNTimeoutCategory; + else if (data.error.type === 'ABORTED') + category = StatusCategory$1.PNCancelledCategory; + message = `${data.error.message} (${data.identifier})`; + } + // Handle service error response. + else if (data.response) { + return reject(PubNubAPIError.create({ + url: data.url, + headers: data.response.headers, + body: data.response.body, + status: data.response.status, + }, data.response.body)); + } + reject(new PubNubAPIError(message, category, 0, new Error(message))); + } + } } - get data() { - let pos = 0; - const header = new Uint8Array(this.length); - const encoder = new TextEncoder(); - header.set(encoder.encode(CryptorHeader.SENTINEL)); - pos += CryptorHeader.SENTINEL.length; - header[pos] = this.version; - pos++; - if (this.identifier) - header.set(encoder.encode(this.identifier), pos); - const metadataLength = this.metadataLength; - pos += CryptorHeader.IDENTIFIER_LENGTH; - if (metadataLength < 255) - header[pos] = metadataLength; - else - header.set([255, metadataLength >> 8, metadataLength & 0xff], pos); - return header; + /** + * Print request progress information. + * + * @param information - Request progress information from worker. + */ + logRequestProgress(information) { + var _a, _b; + if (information.type === 'request-progress-start') { + console.log('<<<<<'); + console.log(`[${information.timestamp}] ${information.url}\n${JSON.stringify((_a = information.query) !== null && _a !== void 0 ? _a : {})}`); + console.log('-----'); + } + else { + console.log('>>>>>>'); + console.log(`[${information.timestamp} / ${information.duration}] ${information.url}\n${JSON.stringify((_b = information.query) !== null && _b !== void 0 ? _b : {})}\n${information.response}`); + console.log('-----'); + } } } - CryptorHeaderV1.IDENTIFIER_LENGTH = 4; - CryptorHeaderV1.SENTINEL = 'PNED'; /** * Percent-encode input string. @@ -3213,7 +3225,7 @@ const encodedNames = names.map((name) => encodeString(name)); return encodedNames.length ? encodedNames.join(',') : defaultString !== null && defaultString !== void 0 ? defaultString : ''; }; - const removeSingleOccurance = (source, elementsToRemove) => { + const removeSingleOccurrence = (source, elementsToRemove) => { const removed = Object.fromEntries(elementsToRemove.map((prop) => [prop, false])); return source.filter((e) => { if (elementsToRemove.includes(e) && !removed[e]) { @@ -3387,6 +3399,15 @@ */ WebReactNativeTransport.decoder = new TextDecoder(); + /** + * Re-map CBOR object keys from potentially C buffer strings to actual strings. + * + * @param obj CBOR which should be remapped to stringified keys. + * + * @returns Dictionary with stringified keys. + * + * @internal + */ function stringifyBufferKeys(obj) { const isObject = (value) => typeof value === 'object' && value !== null && value.constructor === Object; const isString = (value) => typeof value === 'string' || value instanceof String; @@ -3599,6 +3620,10 @@ * reconnection issues, set the flag to `false`. This allows the SDK reconnection logic to take over. */ const LISTEN_TO_BROWSER_NETWORK_EVENTS = true; + /** + * Whether verbose logging should be enabled for `Subscription` worker to print debug messages or not. + */ + const SUBSCRIPTION_WORKER_LOG_VERBOSITY = false; /** * Whether PubNub client should try to utilize existing TCP connection for new requests or not. */ @@ -3607,15 +3632,17 @@ * Apply configuration default values. * * @param configuration - User-provided configuration. + * + * @internal */ const setDefaults = (configuration) => { - var _a, _b; + var _a, _b, _c; // Force disable service workers if environment doesn't support them. - if (configuration.serviceWorkerUrl && !('serviceWorker' in navigator)) - configuration.serviceWorkerUrl = null; + if (configuration.subscriptionWorkerUrl && typeof SharedWorker === 'undefined') + configuration.subscriptionWorkerUrl = null; return Object.assign(Object.assign({}, setDefaults$1(configuration)), { // Set platform-specific options. - listenToBrowserNetworkEvents: (_a = configuration.listenToBrowserNetworkEvents) !== null && _a !== void 0 ? _a : LISTEN_TO_BROWSER_NETWORK_EVENTS, serviceWorkerUrl: configuration.serviceWorkerUrl, keepAlive: (_b = configuration.keepAlive) !== null && _b !== void 0 ? _b : KEEP_ALIVE }); + listenToBrowserNetworkEvents: (_a = configuration.listenToBrowserNetworkEvents) !== null && _a !== void 0 ? _a : LISTEN_TO_BROWSER_NETWORK_EVENTS, subscriptionWorkerUrl: configuration.subscriptionWorkerUrl, subscriptionWorkerLogVerbosity: (_b = configuration.subscriptionWorkerLogVerbosity) !== null && _b !== void 0 ? _b : SUBSCRIPTION_WORKER_LOG_VERBOSITY, keepAlive: (_c = configuration.keepAlive) !== null && _c !== void 0 ? _c : KEEP_ALIVE }); }; var uuid = {exports: {}}; @@ -3685,6 +3712,8 @@ // region Defaults /** * Whether encryption (if set) should use random initialization vector or not. + * + * @internal */ const USE_RANDOM_INITIALIZATION_VECTOR = true; /** @@ -3694,6 +3723,8 @@ * @param setupCryptoModule - Platform-provided {@link CryptoModule} configuration block. * * @returns `PubNub` client private configuration. + * + * @internal */ const makeConfiguration = (base, setupCryptoModule) => { var _a, _b, _c; @@ -3835,6 +3866,8 @@ * REST API access token manager. * * Manager maintains active access token and let parse it to get information about permissions. + * + * @internal */ class TokenManager { constructor(cbor) { @@ -4127,6 +4160,8 @@ */ /** * Real-time listeners' manager. + * + * @internal */ class ListenerManager { constructor() { @@ -4311,6 +4346,13 @@ * * **Note:** Reconnection manger rely on legacy time-based availability check. */ + /** + * Network "discovery" manager. + * + * Manager perform periodic `time` API calls to identify network availability. + * + * @internal + */ class ReconnectionManager { constructor(time) { this.time = time; @@ -4361,6 +4403,11 @@ return hash; }; + /** + * Real-time events deduplication manager. + * + * @internal + */ class DedupingManager { _config; @@ -4399,6 +4446,8 @@ */ /** * Subscription loop manager. + * + * @internal */ class SubscriptionManager { constructor(configuration, listenerManager, eventEmitter, subscribeCall, heartbeatCall, leaveCall, time) { @@ -5309,6 +5358,8 @@ /** * Base REST API request class. + * + * @internal */ class AbstractRequest { /** @@ -5725,6 +5776,8 @@ // region Types /** * PubNub-defined event types by payload. + * + * @internal */ var PubNubEventType; (function (PubNubEventType) { @@ -5762,6 +5815,8 @@ * Subscription request used in small variations in two cases: * - subscription manager * - event engine + * + * @internal */ class BaseSubscribeRequest extends AbstractRequest { constructor(parameters) { @@ -6000,6 +6055,8 @@ } /** * Subscribe request. + * + * @internal */ class SubscribeRequest extends BaseSubscribeRequest { get path() { @@ -6030,6 +6087,14 @@ } } + /** + * Real-time events' emitter. + * + * Emitter responsible for forwarding received real-time events to the closures which has been + * registered for specific events handling. + * + * @internal + */ class EventEmitter { constructor(listenerManager) { this.listenerManager = listenerManager; @@ -6190,6 +6255,9 @@ } } + /** + * @internal + */ class Subject { constructor(sync = false) { this.sync = sync; @@ -6379,6 +6447,11 @@ Object.setPrototypeOf(this, new.target.prototype); } } + /** + * Event Engine stored effect processing cancellation signal. + * + * @internal + */ class AbortSignal extends Subject { constructor() { super(...arguments); @@ -7234,11 +7307,11 @@ } } unsubscribe({ channels = [], channelGroups = [] }) { - const filteredChannels = removeSingleOccurance(this.channels, [ + const filteredChannels = removeSingleOccurrence(this.channels, [ ...channels, ...channels.map((c) => `${c}-pnpres`), ]); - const filteredGroups = removeSingleOccurance(this.groups, [ + const filteredGroups = removeSingleOccurrence(this.groups, [ ...channelGroups, ...channelGroups.map((c) => `${c}-pnpres`), ]); @@ -7313,6 +7386,8 @@ * * Request will normalize and encrypt (if required) provided data and push it to the specified * channel. + * + * @internal */ class PublishRequest extends AbstractRequest { /** @@ -7396,6 +7471,11 @@ * Signal REST API module. */ // endregion + /** + * Signal data (size-limited) publish request. + * + * @internal + */ class SignalRequest extends AbstractRequest { constructor(parameters) { super(); @@ -7433,6 +7513,8 @@ */ /** * Receive messages subscribe request. + * + * @internal */ class ReceiveMessagesSubscribeRequest extends BaseSubscribeRequest { operation() { @@ -7477,6 +7559,8 @@ * Handshake subscribe request. * * Separate subscribe request required by Event Engine. + * + * @internal */ class HandshakeSubscribeRequest extends BaseSubscribeRequest { operation() { @@ -7505,6 +7589,8 @@ // endregion /** * Get `uuid` presence state request. + * + * @internal */ class GetPresenceStateRequest extends AbstractRequest { constructor(parameters) { @@ -7559,6 +7645,8 @@ // endregion /** * Set `uuid` presence state request. + * + * @internal */ class SetPresenceStateRequest extends AbstractRequest { constructor(parameters) { @@ -7605,6 +7693,11 @@ * Announce heartbeat REST API module. */ // endregion + /** + * Announce `uuid` presence request. + * + * @internal + */ class HeartbeatRequest extends AbstractRequest { constructor(parameters) { super(); @@ -7650,6 +7743,11 @@ * Announce leave REST API module. */ // endregion + /** + * Announce user leave request. + * + * @internal + */ class PresenceLeaveRequest extends AbstractRequest { constructor(parameters) { super(); @@ -7697,6 +7795,11 @@ * `uuid` presence REST API module. */ // endregion + /** + * Get `uuid` presence request. + * + * @internal + */ class WhereNowRequest extends AbstractRequest { constructor(parameters) { super(); @@ -7744,6 +7847,11 @@ */ const INCLUDE_STATE = false; // endregion + /** + * Channel presence request. + * + * @internal + */ class HereNowRequest extends AbstractRequest { constructor(parameters) { var _a, _b, _c; @@ -7826,6 +7934,8 @@ // endregion /** * Delete messages from channel history. + * + * @internal */ class DeleteMessageRequest extends AbstractRequest { constructor(parameters) { @@ -7866,6 +7976,11 @@ * Messages count REST API module. */ // endregion + /** + * Count messages request. + * + * @internal + */ class MessageCountRequest extends AbstractRequest { constructor(parameters) { super(); @@ -7935,6 +8050,8 @@ // endregion /** * Get single channel messages request. + * + * @internal */ class GetHistoryRequest extends AbstractRequest { constructor(parameters) { @@ -8080,6 +8197,8 @@ // endregion /** * Fetch messages from channels request. + * + * @internal */ class FetchMessagesRequest extends AbstractRequest { constructor(parameters) { @@ -8230,6 +8349,8 @@ // endregion /** * Fetch channel message actions request. + * + * @internal */ class GetMessageActionsRequest extends AbstractRequest { constructor(parameters) { @@ -8283,6 +8404,8 @@ // endregion /** * Add Message Reaction request. + * + * @internal */ class AddMessageActionRequest extends AbstractRequest { constructor(parameters) { @@ -8338,6 +8461,8 @@ // endregion /** * Remove specific message action request. + * + * @internal */ class RemoveMessageAction extends AbstractRequest { constructor(parameters) { @@ -8387,6 +8512,11 @@ */ const STORE_IN_HISTORY = true; // endregion + /** + * Publish shared file information request. + * + * @internal + */ class PublishFileMessageRequest extends AbstractRequest { constructor(parameters) { var _a; @@ -8456,6 +8586,8 @@ * File download Url generation request. * * Local request which generates Url to download shared file from the specific channel. + * + * @internal */ class GetFileDownloadUrlRequest extends AbstractRequest { /** @@ -8496,6 +8628,8 @@ // endregion /** * Delete File request. + * + * @internal */ class DeleteFileRequest extends AbstractRequest { constructor(parameters) { @@ -8545,6 +8679,8 @@ // endregion /** * Files List request. + * + * @internal */ class FilesListRequest extends AbstractRequest { constructor(parameters) { @@ -8589,6 +8725,8 @@ // endregion /** * Generate File Upload Url request. + * + * @internal */ class GenerateFileUploadUrlRequest extends AbstractRequest { constructor(parameters) { @@ -8634,6 +8772,8 @@ */ /** * File Upload request. + * + * @internal */ class UploadFileRequest extends AbstractRequest { constructor(parameters) { @@ -8689,6 +8829,8 @@ // endregion /** * Send file composed request. + * + * @internal */ class SendFileRequest { constructor(parameters) { @@ -8813,6 +8955,8 @@ * Access token revoke request. * * Invalidate token and permissions which has been granted for it. + * + * @internal */ class RevokeTokenRequest extends AbstractRequest { constructor(parameters) { @@ -8851,6 +8995,8 @@ // endregion /** * Grant token permissions request. + * + * @internal */ class GrantTokenRequest extends AbstractRequest { constructor(parameters) { @@ -9049,6 +9195,8 @@ // endregion /** * Grant permissions request. + * + * @internal */ class GrantRequest extends AbstractRequest { constructor(parameters) { @@ -9118,6 +9266,8 @@ // endregion /** * Permissions audit request. + * + * @internal */ class AuditRequest extends AbstractRequest { constructor(parameters) { @@ -9355,6 +9505,8 @@ // endregion /** * Remove channel group channels request. + * + * @internal */ // prettier-ignore class RemoveChannelGroupChannelsRequest extends AbstractRequest { @@ -9400,6 +9552,8 @@ // endregion /** * Add channel group channels request. + * + * @internal */ class AddChannelGroupChannelsRequest extends AbstractRequest { constructor(parameters) { @@ -9444,6 +9598,8 @@ // endregion /** * List Channel Group Channels request. + * + * @internal */ class ListChannelGroupChannels extends AbstractRequest { constructor(parameters) { @@ -9482,6 +9638,8 @@ // endregion /** * Channel group delete request. + * + * @internal */ class DeleteChannelGroupRequest extends AbstractRequest { constructor(parameters) { @@ -9520,6 +9678,8 @@ // endregion /** * List all channel groups request. + * + * @internal */ class ListChannelGroupsRequest extends AbstractRequest { constructor(parameters) { @@ -9663,6 +9823,8 @@ // endregion /** * Base push notification request. + * + * @internal */ class BasePushNotificationChannelsRequest extends AbstractRequest { constructor(parameters) { @@ -9726,6 +9888,8 @@ // endregion /** * Unregister channels from device push request. + * + * @internal */ // prettier-ignore class RemoveDevicePushNotificationChannelsRequest extends BasePushNotificationChannelsRequest { @@ -9751,6 +9915,8 @@ // endregion /** * List device push enabled channels request. + * + * @internal */ // prettier-ignore class ListDevicePushNotificationChannelsRequest extends BasePushNotificationChannelsRequest { @@ -9776,6 +9942,8 @@ // endregion /** * Register channels with device push request. + * + * @internal */ // prettier-ignore class AddDevicePushNotificationChannelsRequest extends BasePushNotificationChannelsRequest { @@ -9801,6 +9969,8 @@ // endregion /** * Unregister device push notifications request. + * + * @internal */ // prettier-ignore class RemoveDevicePushNotificationRequest extends BasePushNotificationChannelsRequest { @@ -9912,6 +10082,8 @@ // endregion /** * Get All Channels Metadata request. + * + * @internal */ class GetAllChannelsMetadataRequest extends AbstractRequest { constructor(parameters) { @@ -9955,6 +10127,8 @@ // endregion /** * Remove Channel Metadata request. + * + * @internal */ class RemoveChannelMetadataRequest extends AbstractRequest { constructor(parameters) { @@ -10027,6 +10201,8 @@ // endregion /** * Get UUID Memberships request. + * + * @internal */ class GetUUIDMembershipsRequest extends AbstractRequest { constructor(parameters) { @@ -10120,6 +10296,8 @@ // endregion /** * Set UUID Memberships request. + * + * @internal */ class SetUUIDMembershipsRequest extends AbstractRequest { constructor(parameters) { @@ -10206,6 +10384,11 @@ */ const LIMIT$2 = 100; // endregion + /** + * Get All UUIDs Metadata request. + * + * @internal + */ class GetAllUUIDMetadataRequest extends AbstractRequest { constructor(parameters) { var _a, _b, _c; @@ -10255,6 +10438,8 @@ // endregion /** * Get Channel Metadata request. + * + * @internal */ class GetChannelMetadataRequest extends AbstractRequest { constructor(parameters) { @@ -10309,6 +10494,8 @@ // endregion /** * Set Channel Metadata request. + * + * @internal */ class SetChannelMetadataRequest extends AbstractRequest { constructor(parameters) { @@ -10360,6 +10547,8 @@ // endregion /** * Remove UUID Metadata request. + * + * @internal */ class RemoveUUIDMetadataRequest extends AbstractRequest { constructor(parameters) { @@ -10435,6 +10624,8 @@ // endregion /** * Get Channel Members request. + * + * @internal */ class GetChannelMembersRequest extends AbstractRequest { constructor(parameters) { @@ -10525,6 +10716,8 @@ // endregion /** * Set Channel Members request. + * + * @internal */ class SetChannelMembersRequest extends AbstractRequest { constructor(parameters) { @@ -10606,6 +10799,8 @@ // endregion /** * Get UUID Metadata request. + * + * @internal */ class GetUUIDMetadataRequest extends AbstractRequest { constructor(parameters) { @@ -10662,6 +10857,8 @@ // endregion /** * Set UUID Metadata request. + * + * @internal */ class SetUUIDMetadataRequest extends AbstractRequest { constructor(parameters) { @@ -11233,6 +11430,11 @@ * Time REST API module. */ // endregion + /** + * Get current PubNub high-precision time request. + * + * @internal + */ class TimeRequest extends AbstractRequest { constructor() { super(); @@ -11259,6 +11461,8 @@ // endregion /** * Download File request. + * + * @internal */ class DownloadFileRequest extends AbstractRequest { constructor(parameters) { @@ -12937,7 +13141,9 @@ } } /** - * {@link ArrayBuffer} to {@link string} decoder. + * {@link ArrayBuffer} to {@link string} decoder. + * + * @internal */ PubNubCore.decoder = new TextDecoder(); // -------------------------------------------------------- @@ -12966,6 +13172,8 @@ */ /** * CBOR data decoder. + * + * @internal */ class Cbor { constructor(decode, base64ToBinary) { @@ -13025,14 +13233,16 @@ } // Setup transport provider. let transport = new WebReactNativeTransport(clientConfiguration.keepAlive, clientConfiguration.logVerbosity); - if (configurationCopy.serviceWorkerUrl) { - // Inject subscription service worker into transport provider stack. - transport = new SubscriptionServiceWorkerMiddleware({ + if (configurationCopy.subscriptionWorkerUrl) { + // Inject subscription worker into transport provider stack. + transport = new SubscriptionWorkerMiddleware({ clientIdentifier: clientConfiguration._instanceId, subscriptionKey: clientConfiguration.subscribeKey, - serviceWorkerUrl: configurationCopy.serviceWorkerUrl, + userId: clientConfiguration.getUserId(), + workerUrl: configurationCopy.subscriptionWorkerUrl, sdkVersion: clientConfiguration.getVersion(), logVerbosity: clientConfiguration.logVerbosity, + workerLogVerbosity: platformConfiguration.subscriptionWorkerLogVerbosity, transport, }); } diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index 435b2833f..006cf471a 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;r0){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,o=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 c(r,n,o,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 o(null!=t?t:this.message,this.toStatus(e))}}class u{constructor(e){this.configuration=e,this.serviceWorkerEventsQueue=[],this.callbacks=new Map,this.setupServiceWorker()}makeSendable(e){if(!e.path.startsWith("/v2/subscribe")&&!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.serviceWorker;s?s.postMessage(e):t?this.serviceWorkerEventsQueue.splice(0,0,e):this.serviceWorkerEventsQueue.push(e)}flushScheduledEvents(){const e=this.serviceWorker;if(!e||0===this.serviceWorkerEventsQueue.length)return;const t=[];for(let e=0;e!t.includes(e))),this.serviceWorkerEventsQueue.forEach((t=>e.postMessage(t))),this.serviceWorkerEventsQueue=[]}get serviceWorker(){return this.serviceWorkerRegistration?this.serviceWorkerRegistration.active:null}setupServiceWorker(){if(!("serviceWorker"in navigator))return;const e=navigator.serviceWorker;e.register(this.configuration.serviceWorkerUrl,{scope:`/pubnub-${this.configuration.sdkVersion}`}).then((e=>{this.serviceWorkerRegistration=e,e.active&&this.flushScheduledEvents(),this.serviceWorkerRegistration.addEventListener("updatefound",(()=>{if(!this.serviceWorkerRegistration)return;const e=this.serviceWorkerRegistration.installing,t=()=>{"activated"===e.state?this.flushScheduledEvents():"redundant"===e.state&&e.removeEventListener("statechange",t)};e.addEventListener("statechange",t)}))})),e.addEventListener("message",(e=>this.handleServiceWorkerEvent(e)))}handleServiceWorkerEvent(e){const{data:t}=e;if(t.clientIdentifier===this.configuration.clientIdentifier)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=i.PNUnknownCategory,n="Unknown error";if(t.error)"NETWORK_ISSUE"===t.error.type?e=i.PNNetworkIssuesCategory:"TIMEOUT"===t.error.type?e=i.PNTimeoutCategory:"ABORTED"===t.error.type&&(e=i.PNCancelledCategory),n=`${t.error.message} (${t.identifier})`;else if(t.response)return s(c.create({url:t.url,headers:t.response.headers,body:t.response.body,status:t.response.status},t.response.body));s(new c(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 l(e,t){var s={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);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 h(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 h(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in Node.js environments.")}))}toFile(){return h(this,void 0,void 0,(function*(){return this.data}))}toFileUri(){return h(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in React Native environments.")}))}toBlob(){return h(this,void 0,void 0,(function*(){return this.data}))}}p.supportsBlob="undefined"!=typeof Blob,p.supportsFile="undefined"!=typeof File,p.supportsBuffer=!1,p.supportsStream=!1,p.supportsString=!0,p.supportsArrayBuffer=!0,p.supportsEncryptFile=!0,p.supportsFileUri=!1;function g(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 y(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 f,m,b,v,w,S=S||function(e,t){var s={},n=s.lib={},r=function(){},i=n.Base={extend:function(e){r.prototype=this;var t=new r;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)}},o=n.WordArray=i.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||c).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=i.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 o.init(s,t/2)}},u=a.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 o.init(s,t)}},l=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},h=n.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new o.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=l.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var s=this._data,n=s.words,r=s.sigBytes,i=this.blockSize,a=r/(4*i);if(t=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*i,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),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 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 v.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=S,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=S,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]}},t.BlockCipher=a.extend({cfg:a.cfg.extend({mode:c,padding:l}),reset:function(){a.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var 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 h=t.CipherParams=s.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),d=(c=(p.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?n.create([1398893684,1701076831]).concat(e).concat(t):t).toString(i)},parse:function(e){var t=(e=i.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var s=n.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return h.create({ciphertext:e,salt:s})}},t.SerializableCipher=s.extend({cfg:s.extend({format:c}),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,h.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}})),p=(p.kdf={}).OpenSSL={execute:function(e,t,s,r){return r||(r=n.random(8)),e=o.create({keySize:t+s}).compute(e,r),s=n.create(e.words.slice(t),4*s),e.sigBytes=4*t,h.create({key:e,iv:s,salt:r})}},g=t.PasswordBasedCipher=d.extend({cfg:d.cfg.extend({kdf:p}),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=d.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,d.decrypt.call(this,e,t,s.key,n)}})}(),function(){for(var e=S,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],v=p[b],w=p[v],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*w^65537*v^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[w^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)}(),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 k=t(S);class E{constructor({cipherKey:e}){this.cipherKey=e,this.CryptoJS=k,this.encryptedKey=this.CryptoJS.SHA256(e)}encrypt(e){if(0===("string"==typeof e?e:E.decoder.decode(e)).length)throw new Error("encryption error. empty content");const t=this.getIv();return{metadata:t,data:g(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 h(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 E.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 h(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(E.BLOCK_SIZE))}getKey(){return h(this,void 0,void 0,(function*(){const e=E.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=P.encoder.encode(s.slice(0,32)).buffer;return crypto.subtle.importKey("raw",n,"AES-CBC",!0,["encrypt","decrypt"])}))}}P.IV_LENGTH=16,P.encoder=new TextEncoder,P.decoder=new TextDecoder;class M{constructor(e){this.config=e,this.cryptor=new C(Object.assign({},e)),this.fileCryptor=new P}encrypt(e){const t="string"==typeof e?e:M.decoder.decode(e);return{data:this.cryptor.encrypt(t),metadata:null}}encryptFile(e,t){return h(this,void 0,void 0,(function*(){var s;if(!this.config.cipherKey)throw new o("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:y(e.data);return this.cryptor.decrypt(t)}decryptFile(e,t){return h(this,void 0,void 0,(function*(){if(!this.config.cipherKey)throw new o("File encryption error: cipher key not set.");return this.fileCryptor.decryptFile(this.config.cipherKey,e,t)}))}get identifier(){return""}}M.encoder=new TextEncoder,M.decoder=new TextDecoder;class j extends d{static legacyCryptoModule(e){var t;if(!e.cipherKey)throw new o("Crypto module error: cipher key not set.");return new j({default:new M(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t})),cryptors:[new E({cipherKey:e.cipherKey})]})}static aesCbcCryptoModule(e){var t;if(!e.cipherKey)throw new o("Crypto module error: cipher key not set.");return new j({default:new E({cipherKey:e.cipherKey}),cryptors:[new M(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===j.LEGACY_IDENTIFIER?this.defaultCryptor.encrypt(j.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 h(this,void 0,void 0,(function*(){if(this.defaultCryptor.identifier===_.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?g(e):e,s=_.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 h(this,void 0,void 0,(function*(){const s=yield e.data.arrayBuffer(),n=_.tryParse(s),r=this.getCryptor(n);if((null==r?void 0:r.identifier)===_.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 A)return this.getCryptorFromId(e.identifier)}getHeaderData(e){if(!e.metadata)return;const t=_.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 h(this,void 0,void 0,(function*(){if(e instanceof ArrayBuffer)return e;if(e instanceof p)return e.toArrayBuffer();throw new Error("Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob")}))}}j.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 s,n,r=null;if(t.byteLength>=4&&(s=t.slice(0,4),this.decoder.decode(s)!==_.SENTINEL))return j.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");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 A(this.decoder.decode(n),o)}}_.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),s=new TextEncoder;t.set(s.encode(_.SENTINEL)),e+=_.SENTINEL.length,t[e]=this.version,e++,this.identifier&&t.set(s.encode(this.identifier),e);const n=this.metadataLength;return e+=_.IDENTIFIER_LENGTH,n<255?t[e]=n:t.set([255,n>>8,255&n],e),t}}A.IDENTIFIER_LENGTH=4,A.SENTINEL="PNED";const R=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),I=(e,t)=>{const s=e.map((e=>R(e)));return s.length?s.join(","):null!=t?t:""},U=(e,t)=>{const s=Object.fromEntries(t.map((e=>[e,!1])));return e.filter((e=>!(t.includes(e)&&!s[e])||(s[e]=!0,!1)))},T=(e,t)=>[...e].filter((s=>t.includes(s)&&e.indexOf(s)===e.lastIndexOf(s)&&t.indexOf(s)===t.lastIndexOf(s)));class F{constructor(e=!1,t){this.keepAlive=e,this.logVerbosity=t}makeSendable(e){let t,s;return e.cancellable&&(s=new AbortController,t={abortController:s,abort:()=>null==s?void 0:s.abort()}),[this.requestFromTransportRequest(e).then((t=>{const n=(new Date).getTime();this.logRequestProcessProgress(t);const r=new Promise(((t,s)=>{const n=setTimeout((()=>{clearTimeout(n),s(new Error("Request timeout"))}),1e3*e.timeout)}));return Promise.race([fetch(t,{signal:null==s?void 0:s.signal}),r]).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 c.create(a);return this.logRequestProcessProgress(t,(new Date).getTime()-n,s),a})).catch((e=>{throw c.create(e)}))})),t]}request(e){return e}requestFromTransportRequest(e){return h(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}=${R(t)}`)).join("&"):`${e}=${R(t)}`})).join("&")}`),new Request(`${e.origin}${s}`,{method:e.method,headers:e.headers,redirect:"follow",body:t})}))}logRequestProcessProgress(e,t,s){if(!this.logVerbosity)return;const{protocol:n,host:r,pathname:i,search:o}=new URL(e.url),a=(new Date).toISOString();if(t){const e=s?F.decoder.decode(s):void 0;console.log(">>>>>>"),console.log(`[${a} / ${t}]`,`\n${n}//${r}${i}`,`\n${o}`,`\n${e}`),console.log("-----")}else console.log("<<<<<"),console.log(`[${a}]`,`\n${n}//${r}${i}`,`\n${o}`),console.log("-----")}}function x(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)?x(a):a})),n}F.decoder=new TextDecoder;const D=e=>{var t,s;return e.serviceWorkerUrl&&!("serviceWorker"in navigator)&&(e.serviceWorkerUrl=null),Object.assign(Object.assign({},(e=>{var t,s,n,r,i,a,c,u,l,h,d,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.restore)&&void 0!==i||(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!==(d=m.maintainPresenceState)&&void 0!==d||(m.maintainPresenceState=!0),null!==(p=m.keepAlive)&&void 0!==p||(m.keepAlive=!1),m.userId&&m.uuid)throw new o("PubNub client configuration error: use only 'userId'");if(null!==(g=m.userId)&&void 0!==g||(m.userId=m.uuid),!m.userId)throw new o("PubNub client configuration error: 'userId' not set");if(0===(null===(y=m.userId)||void 0===y?void 0:y.trim().length))throw new o("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)),null!==(f=m.presenceTimeout)&&void 0!==f||(m.presenceTimeout=300);let v=!1,w=!0,S=5,k=!1,E=!0;return void 0!==m.dedupeOnSubscribe&&"boolean"==typeof m.dedupeOnSubscribe&&(k=m.dedupeOnSubscribe),void 0!==m.useRequestId&&"boolean"==typeof m.useRequestId&&(E=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:100,useRequestId:E,announceSuccessfulHeartbeats:v,announceFailedHeartbeats:w,fileUploadPublishRetryLimit:S})})(e)),{listenToBrowserNetworkEvents:null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t,serviceWorkerUrl:e.serviceWorkerUrl,keepAlive:null===(s=e.keepAlive)||void 0===s||s})};var K={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)}(K,K.exports);var q=t(K.exports),G={createUUID:()=>q.uuid?q.uuid():q()};const $=(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=L(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-${G.createUUID()}`,_cryptoModule:void 0,_cipherKey:void 0,_setupCryptoModule:t,get instanceId(){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},get PubNubFile(){return e.PubNubFile},get version(){return"8.0.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},L=(e,t)=>{const s=e?"https://":"http://";return"string"==typeof t?`${s}${t}`:`${s}${t[Math.floor(Math.random()*t.length)]}`};class B{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 H;!function(e){e.GET="GET",e.POST="POST",e.PATCH="PATCH",e.DELETE="DELETE",e.LOCAL="LOCAL"}(H||(H={}));class z{constructor(e,t,s){this.publishKey=e,this.secretKey=t,this.hasher=s}signature(e){const t=e.path.startsWith("/publish")?H.GET:e.method;let s=`${t}\n${this.publishKey}\n${e.path}\n${this.queryParameters(e.queryParameters)}\n`;if(t===H.POST||t===H.PATCH){const t=e.body;let n;t&&t instanceof ArrayBuffer?n=z.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}=${R(e)}`)).join("&"):`${t}=${R(s)}`})).join("&")}}z.textDecoder=new TextDecoder("utf-8");class V{constructor(e){this.configuration=e;const{clientConfiguration:{keySet:t},shaHMAC:s}=e;t.secretKey&&s&&(this.signatureGenerator=new z(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.instanceId),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.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 W{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:i.PNNetworkUpCategory})}))}announceNetworkDown(){this.listeners.forEach((e=>{e.status&&e.status({category:i.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 J{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{_config;hashHistory;constructor({config:e}){this.hashHistory=[],this._config=e}getKey(e){const t=(e=>{let t=0;if(0===e.length)return t;for(let s=0;s=this._config.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}clearHistory(){this.hashHistory=[]}}class Y{constructor(e,t,s,n,r,i,o){this.configuration=e,this.listenerManager=t,this.eventEmitter=s,this.subscribeCall=n,this.heartbeatCall=r,this.leaveCall=i,this.reconnectionManager=new J(o),this.dedupingManager=new Q({config:this.configuration}),this.heartbeatChannelGroups={},this.heartbeatChannels={},this.presenceChannelGroups={},this.presenceChannels={},this.heartbeatTimer=null,this.presenceState={},this.pendingChannelGroupSubscriptions=new Set,this.pendingChannelSubscriptions=new Set,this.channelGroups={},this.channels={},this.currentTimetoken="0",this.lastTimetoken="0",this.storedTimetoken=null,this.subscriptionStatusAnnounced=!1,this.isOnline=!0}get subscribedChannels(){return Object.keys(this.channels)}get subscribedChannelGroups(){return Object.keys(this.channelGroups)}get abort(){return this._subscribeAbort}set abort(e){this._subscribeAbort=e}disconnect(){this.stopSubscribeLoop(),this.stopHeartbeatTimer(),this.reconnectionManager.stopPolling()}reconnect(){this.startSubscribeLoop(),this.startHeartbeatTimer()}subscribe(e){const{channels:t,channelGroups:s,timetoken:n,withPresence:r=!1,withHeartbeats:i=!1}=e;n&&(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=n),"0"!==this.currentTimetoken&&0!==this.currentTimetoken&&(this.storedTimetoken=this.currentTimetoken,this.currentTimetoken=0),null==t||t.forEach((e=>{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 r=new Set,i=new Set;null==s||s.forEach((e=>{e in this.channels&&(delete this.channels[e],i.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],i.add(e))})),null==n||n.forEach((e=>{e in this.channelGroups&&(delete this.channelGroups[e],r.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],r.add(e))})),0===i.size&&0===r.size||(!1!==this.configuration.suppressLeaveEvents||t||(n=Array.from(r),s=Array.from(i),this.leaveCall({channels:s,channelGroups:n},(e=>{const{error:t}=e,r=l(e,["error"]);let i;t&&(e.errorData&&"object"==typeof e.errorData&&"message"in e.errorData&&"string"==typeof e.errorData.message?i=e.errorData.message:"message"in e&&"string"==typeof e.message&&(i=e.message)),this.listenerManager.announceStatus(Object.assign(Object.assign({},r),{error:null!=i&&i,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())}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===i.PNCancelledCategory)return;return void(e.category===i.PNTimeoutCategory?this.startSubscribeLoop():e.category===i.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:i.PNReconnectedCategory,operation:e.operation,lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.listenerManager.announceStatus(t)})),this.reconnectionManager.startPolling(),this.listenerManager.announceStatus(e)):e.category===i.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:i.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:i.PNRequestMessageCountExceededCategory,operation:e.operation});try{s.forEach((e=>{if(r){if(this.dedupingManager.isDuplicate(e.data))return;this.dedupingManager.addEntry(e.data)}this.eventEmitter.emitEvent(e)}))}catch(e){const t={error:!0,category:i.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 X{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 Z extends X{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 ee extends X{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=l(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 te{constructor(e,t){this._payload={apns:{},fcm:{}},this._title=e,this._body=t,this.apns=new Z(this._payload.apns,e,t),this.fcm=new ee(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 se{constructor(e){this.params=e,this.requestIdentifier=G.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 h(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:H.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:1e4,identifier:this.requestIdentifier},i=this.headers;if(i&&(r.headers=i),r.method===H.POST||r.method===H.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=se.decoder.decode(e.body);try{return JSON.parse(s)}catch(e){return void console.error("Error parsing JSON response:",e)}}}var ne;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"}(ne||(ne={}));var re=ne;var ie;!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"}(ie||(ie={}));class oe extends se{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 re.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 h(this,void 0,void 0,(function*(){let t;try{const s=se.decoder.decode(e.body);t=JSON.parse(s)}catch(e){console.error("Error parsing JSON response:",e)}if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));const s=t.m.map((e=>{let{e:t}=e;return null!=t||(t=e.c.endsWith("-pnpres")?ie.Presence:ie.Message),"string"==typeof e.d?t==ie.Message?{type:ie.Message,data:this.messageFromEnvelope(e)}:{type:ie.Files,data:this.fileFromEnvelope(e)}:t==ie.Message?{type:ie.Message,data:this.messageFromEnvelope(e)}:t===ie.Presence?{type:ie.Presence,data:this.presenceEventFromEnvelope(e)}:t==ie.Signal?{type:ie.Signal,data:this.signalFromEnvelope(e)}:t===ie.AppContext?{type:ie.AppContext,data:this.appContextFromEnvelope(e)}:t===ie.MessageAction?{type:ie.MessageAction,data:this.messageActionFromEnvelope(e)}:{type:ie.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){const{d:t}=e,[s,n]=this.subscriptionChannelFromEnvelope(e),r=s.replace("-pnpres",""),i=null!==n?r:null,o=null!==n?n:r;return"string"!=typeof t&&"data"in t&&(t.state=t.data,delete t.data),Object.assign({channel:r,subscription:n,actualChannel:i,subscribedChannel:o,timetoken:e.p.t},t)}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),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),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."),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(ae.decoder.decode(s)):s}catch(e){t=null,s=`Error while decrypting message content: ${e.message}`}return[null!=t?t:e,s]}}class ae extends oe{get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/subscribe/${t}/${I(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 ce{constructor(e){this.listenerManager=e,this.channelListenerMap=new Map,this.groupListenerMap=new Map}emitEvent(e){if(e.type===ie.Message)this.listenerManager.announceMessage(e.data),this.announce("message",e.data,e.data.channel,e.data.subscription);else if(e.type===ie.Signal)this.listenerManager.announceSignal(e.data),this.announce("signal",e.data,e.data.channel,e.data.subscription);else if(e.type===ie.Presence)this.listenerManager.announcePresence(e.data),this.announce("presence",e.data,e.data.channel,e.data.subscription);else if(e.type===ie.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,r=l(t,["message","channel"]),{event:i,type:o}=s,a=l(s,["event","type"]),c=Object.assign(Object.assign({},r),{spaceId:n,message:Object.assign(Object.assign({},a),{event:"set"===i?"updated":"removed",type:"user"})});this.listenerManager.announceUser(c),this.announce("user",c,c.spaceId,c.subscription)}else if("channel"===s.type){const{message:e,channel:n}=t,r=l(t,["message","channel"]),{event:i,type:o}=s,a=l(s,["event","type"]),c=Object.assign(Object.assign({},r),{spaceId:n,message:Object.assign(Object.assign({},a),{event:"set"===i?"updated":"removed",type:"space"})});this.listenerManager.announceSpace(c),this.announce("space",c,c.spaceId,c.subscription)}else if("membership"===s.type){const{message:e,channel:n}=t,r=l(t,["message","channel"]),{event:i,data:o}=s,a=l(s,["event","data"]),{uuid:c,channel:u}=o,h=l(o,["uuid","channel"]),d=Object.assign(Object.assign({},r),{spaceId:n,message:Object.assign(Object.assign({},a),{event:"set"===i?"updated":"removed",data:Object.assign(Object.assign({},h),{user:c,space:u})})});this.listenerManager.announceMembership(d),this.announce("membership",d,d.spaceId,d.subscription)}}else e.type===ie.MessageAction?(this.listenerManager.announceMessageAction(e.data),this.announce("messageAction",e.data,e.data.channel,e.data.subscription)):e.type===ie.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 ue{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 le{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 he extends ue{describe(e){return new le(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 de{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 pe(e,t){const s=function(...s){return{type:e,payload:null==t?void 0:t(...s)}};return s.type=e,s}function ge(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!1});return s.type=e,s}function ye(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 fe extends Error{constructor(){super("The operation was aborted."),this.name="AbortError",Object.setPrototypeOf(this,new.target.prototype)}}class me extends ue{constructor(){super(...arguments),this._aborted=!1}get aborted(){return this._aborted}throwIfAborted(){if(this._aborted)throw new fe}abort(){this._aborted=!0,this.notify(new fe)}}class be{constructor(e,t){this.payload=e,this.dependencies=t}}class ve extends be{constructor(e,t,s){super(e,t),this.asyncFunction=s,this.abortSignal=new me}start(){this.asyncFunction(this.payload,this.abortSignal,this.dependencies).catch((e=>{}))}cancel(){this.abortSignal.abort()}}const we=e=>(t,s)=>new ve(t,s,e),Se=pe("RECONNECT",(()=>({}))),ke=pe("DISCONNECT",(()=>({}))),Ee=pe("JOINED",((e,t)=>({channels:e,groups:t}))),Oe=pe("LEFT",((e,t)=>({channels:e,groups:t}))),Ce=pe("LEFT_ALL",(()=>({}))),Ne=pe("HEARTBEAT_SUCCESS",(e=>({statusCode:e}))),Pe=pe("HEARTBEAT_FAILURE",(e=>e)),Me=pe("HEARTBEAT_GIVEUP",(()=>({}))),je=pe("TIMES_UP",(()=>({}))),_e=ge("HEARTBEAT",((e,t)=>({channels:e,groups:t}))),Ae=ge("LEAVE",((e,t)=>({channels:e,groups:t}))),Re=ge("EMIT_STATUS",(e=>e)),Ie=ye("WAIT",(()=>({}))),Ue=ye("DELAYED_HEARTBEAT",(e=>e));class Te extends de{constructor(e,t){super(t),this.on(_e.type,we(((t,s,n)=>h(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,presenceState:r,config:a}){try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},a.maintainPresenceState&&{state:r}),{heartbeat:a.presenceTimeout}));e.transition(Ne(200))}catch(t){if(t instanceof o){if(t.status&&t.status.category==i.PNCancelledCategory)return;return e.transition(Pe(t))}}}))))),this.on(Ae.type,we(((e,t,s)=>h(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,we(((t,s,n)=>h(this,[t,s,n],void 0,(function*(t,s,{heartbeatDelay:n}){return s.throwIfAborted(),yield n(),s.throwIfAborted(),e.transition(je())}))))),this.on(Ue.type,we(((t,s,n)=>h(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,retryDelay:r,presenceState:a,config:c}){if(!c.retryConfiguration||!c.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(Me());s.throwIfAborted(),yield r(c.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},c.maintainPresenceState&&{state:a}),{heartbeat:c.presenceTimeout}));return e.transition(Ne(200))}catch(t){if(t instanceof o){if(t.status&&t.status.category==i.PNCancelledCategory)return;return e.transition(Pe(t))}}}))))),this.on(Re.type,we(((e,t,s)=>h(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:re.PNHeartbeatOperation,error:!1}))})))))}}const Fe=new le("HEARTBEAT_STOPPED");Fe.on(Ee.type,((e,t)=>Fe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Fe.on(Oe.type,((e,t)=>Fe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))}))),Fe.on(Se.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),Fe.on(Ce.type,((e,t)=>Ge.with(void 0)));const xe=new le("HEARTBEAT_COOLDOWN");xe.onEnter((()=>Ie())),xe.onExit((()=>Ie.cancel)),xe.on(je.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),xe.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),xe.on(Oe.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(ke.type,(e=>Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),xe.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const De=new le("HEARTBEAT_FAILED");De.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),De.on(Oe.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)=>qe.with({channels:e.channels,groups:e.groups}))),De.on(ke.type,((e,t)=>Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),De.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const Ke=new le("HEARBEAT_RECONNECTING");Ke.onEnter((e=>Ue(e))),Ke.onExit((()=>Ue.cancel)),Ke.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Ke.on(Oe.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)]))),Ke.on(ke.type,((e,t)=>{Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)])})),Ke.on(Ne.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups}))),Ke.on(Pe.type,((e,t)=>Ke.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),Ke.on(Me.type,((e,t)=>De.with({channels:e.channels,groups:e.groups}))),Ke.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const qe=new le("HEARTBEATING");qe.onEnter((e=>_e(e.channels,e.groups))),qe.on(Ne.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups}))),qe.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),qe.on(Oe.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(Pe.type,((e,t)=>Ke.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),qe.on(ke.type,(e=>Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),qe.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const Ge=new le("HEARTBEAT_INACTIVE");Ge.on(Ee.type,((e,t)=>qe.with({channels:t.payload.channels,groups:t.payload.groups})));class $e{get _engine(){return this.engine}constructor(e){this.dependencies=e,this.engine=new he,this.channels=[],this.groups=[],this.dispatcher=new Te(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(Ee(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(Oe(null!=e?e:[],null!=t?t:[]))}leaveAll(){this.engine.transition(Ce())}dispose(){this._unsubscribeEngine(),this.dispatcher.dispose()}}class Le{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 Be=ye("HANDSHAKE",((e,t)=>({channels:e,groups:t}))),He=ye("RECEIVE_MESSAGES",((e,t,s)=>({channels:e,groups:t,cursor:s}))),ze=ge("EMIT_MESSAGES",(e=>e)),Ve=ge("EMIT_STATUS",(e=>e)),We=ye("RECEIVE_RECONNECT",(e=>e)),Je=ye("HANDSHAKE_RECONNECT",(e=>e)),Qe=pe("SUBSCRIPTION_CHANGED",((e,t)=>({channels:e,groups:t}))),Ye=pe("SUBSCRIPTION_RESTORED",((e,t,s,n)=>({channels:e,groups:t,cursor:{timetoken:s,region:null!=n?n:0}}))),Xe=pe("HANDSHAKE_SUCCESS",(e=>e)),Ze=pe("HANDSHAKE_FAILURE",(e=>e)),et=pe("HANDSHAKE_RECONNECT_SUCCESS",(e=>({cursor:e}))),tt=pe("HANDSHAKE_RECONNECT_FAILURE",(e=>e)),st=pe("HANDSHAKE_RECONNECT_GIVEUP",(e=>e)),nt=pe("RECEIVE_SUCCESS",((e,t)=>({cursor:e,events:t}))),rt=pe("RECEIVE_FAILURE",(e=>e)),it=pe("RECEIVE_RECONNECT_SUCCESS",((e,t)=>({cursor:e,events:t}))),ot=pe("RECEIVE_RECONNECT_FAILURE",(e=>e)),at=pe("RECEIVING_RECONNECT_GIVEUP",(e=>e)),ct=pe("DISCONNECT",(()=>({}))),ut=pe("RECONNECT",((e,t)=>({cursor:{timetoken:null!=e?e:"",region:null!=t?t:0}}))),lt=pe("UNSUBSCRIBE_ALL",(()=>({})));class ht extends de{constructor(e,t){super(t),this.on(Be.type,we(((t,s,n)=>h(this,[t,s,n],void 0,(function*(t,s,{handshake:n,presenceState:r,config:a}){s.throwIfAborted();try{const i=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:a.filterExpression},a.maintainPresenceState&&{state:r}));return e.transition(Xe(i))}catch(t){if(t instanceof o){if(t.status&&t.status.category==i.PNCancelledCategory)return;return e.transition(Ze(t))}}}))))),this.on(He.type,we(((t,s,n)=>h(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(nt(i.cursor,i.messages))}catch(t){if(t instanceof o){if(t.status&&t.status.category==i.PNCancelledCategory)return;if(!s.aborted)return e.transition(rt(t))}}}))))),this.on(ze.type,we(((e,t,s)=>h(this,[e,t,s],void 0,(function*(e,t,{emitMessages:s}){e.length>0&&s(e)}))))),this.on(Ve.type,we(((e,t,s)=>h(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s}){s(e)}))))),this.on(We.type,we(((t,s,n)=>h(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,delay:r,config:a}){if(!a.retryConfiguration||!a.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(at(new o(a.retryConfiguration?a.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe messages receive.")));s.throwIfAborted(),yield r(a.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:a.filterExpression});return e.transition(it(r.cursor,r.messages))}catch(t){if(t instanceof o){if(t.status&&t.status.category==i.PNCancelledCategory)return;return e.transition(ot(t))}}}))))),this.on(Je.type,we(((t,s,n)=>h(this,[t,s,n],void 0,(function*(t,s,{handshake:n,delay:r,presenceState:a,config:c}){if(!c.retryConfiguration||!c.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(st(new o(c.retryConfiguration?c.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe handshake")));s.throwIfAborted(),yield r(c.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{const r=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:c.filterExpression},c.maintainPresenceState&&{state:a}));return e.transition(et(r))}catch(t){if(t instanceof o){if(t.status&&t.status.category==i.PNCancelledCategory)return;return e.transition(tt(t))}}})))))}}const dt=new le("HANDSHAKE_FAILED");dt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),dt.on(ut.type,((e,t)=>vt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor||e.cursor}))),dt.on(Ye.type,((e,t)=>{var s,n;return vt.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}})})),dt.on(lt.type,(e=>wt.with()));const pt=new le("HANDSHAKE_STOPPED");pt.on(Qe.type,((e,t)=>pt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),pt.on(ut.type,((e,t)=>vt.with(Object.assign(Object.assign({},e),{cursor:t.payload.cursor||e.cursor})))),pt.on(Ye.type,((e,t)=>{var s;return pt.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}})})),pt.on(lt.type,(e=>wt.with()));const gt=new le("RECEIVE_FAILED");gt.on(ut.type,((e,t)=>{var s;return vt.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(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),gt.on(Ye.type,((e,t)=>vt.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(lt.type,(e=>wt.with(void 0)));const yt=new le("RECEIVE_STOPPED");yt.on(Qe.type,((e,t)=>yt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),yt.on(Ye.type,((e,t)=>yt.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(ut.type,((e,t)=>{var s;return vt.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}})})),yt.on(lt.type,(()=>wt.with(void 0)));const ft=new le("RECEIVE_RECONNECTING");ft.onEnter((e=>We(e))),ft.onExit((()=>We.cancel)),ft.on(it.type,((e,t)=>mt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),ft.on(ot.type,((e,t)=>ft.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),ft.on(at.type,((e,t)=>{var s;return gt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[Ve({category:i.PNDisconnectedUnexpectedlyCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),ft.on(ct.type,(e=>yt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[Ve({category:i.PNDisconnectedCategory})]))),ft.on(Ye.type,((e,t)=>mt.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(Qe.type,((e,t)=>mt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),ft.on(lt.type,(e=>wt.with(void 0,[Ve({category:i.PNDisconnectedCategory})])));const mt=new le("RECEIVING");mt.onEnter((e=>He(e.channels,e.groups,e.cursor))),mt.onExit((()=>He.cancel)),mt.on(nt.type,((e,t)=>mt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),mt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?wt.with(void 0):mt.with({cursor:e.cursor,channels:t.payload.channels,groups:t.payload.groups}))),mt.on(Ye.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?wt.with(void 0):mt.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(rt.type,((e,t)=>ft.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),mt.on(ct.type,(e=>yt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[Ve({category:i.PNDisconnectedCategory})]))),mt.on(lt.type,(e=>wt.with(void 0,[Ve({category:i.PNDisconnectedCategory})])));const bt=new le("HANDSHAKE_RECONNECTING");bt.onEnter((e=>Je(e))),bt.onExit((()=>Je.cancel)),bt.on(et.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 mt.with({channels:e.channels,groups:e.groups,cursor:r},[Ve({category:i.PNConnectedCategory})])})),bt.on(tt.type,((e,t)=>bt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),bt.on(st.type,((e,t)=>{var s;return dt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[Ve({category:i.PNConnectionErrorCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),bt.on(ct.type,(e=>pt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),bt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),bt.on(Ye.type,((e,t)=>{var s,n;return vt.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}})})),bt.on(lt.type,(e=>wt.with(void 0)));const vt=new le("HANDSHAKING");vt.onEnter((e=>Be(e.channels,e.groups))),vt.onExit((()=>Be.cancel)),vt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?wt.with(void 0):vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),vt.on(Xe.type,((e,t)=>{var s,n;return mt.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}},[Ve({category:i.PNConnectedCategory})])})),vt.on(Ze.type,((e,t)=>bt.with({channels:e.channels,groups:e.groups,cursor:e.cursor,attempts:0,reason:t.payload}))),vt.on(ct.type,(e=>pt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),vt.on(Ye.type,((e,t)=>{var s;return vt.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}})})),vt.on(lt.type,(e=>wt.with()));const wt=new le("UNSUBSCRIBED");wt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups}))),wt.on(Ye.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:t.payload.cursor})));class St{get _engine(){return this.engine}constructor(e){this.engine=new he,this.channels=[],this.groups=[],this.dependencies=e,this.dispatcher=new ht(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(wt,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(Ye(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])),s)):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 s=U(this.channels,[...e,...e.map((e=>`${e}-pnpres`))]),n=U(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=T(this.channels,e),i=T(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(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(ut(e,t))}disconnect(){this.engine.transition(ct()),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 kt extends se{constructor(e){var t,s;super({method:e.sendByPost?H.POST:H.GET}),this.parameters=e,null!==(t=(s=this.parameters).sendByPost)&&void 0!==t||(s.sendByPost=false)}operation(){return re.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 h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("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/${R(t)}/0${this.parameters.sendByPost?"":`/${R(n)}`}`}get queryParameters(){const{meta:e,replicate:t,storeInHistory:s,ttl:n}=this.parameters,r={};return void 0!==s&&(r.store=s?"1":"0"),void 0!==n&&(r.ttl=n),void 0===t||t||(r.norep="true"),e&&"object"==typeof e&&(r.meta=JSON.stringify(e)),r}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:y(s))}}class Et extends se{constructor(e){super(),this.parameters=e}operation(){return re.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 h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("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/${R(s)}/0/${R(r)}`}}class Ot extends oe{operation(){return re.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}/${I(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 Ct extends oe{operation(){return re.PNHandshakeOperation}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${I(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 Nt extends se{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 re.PNGetStateOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;if(!e)return"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.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/${I(null!=s?s:[],",")}/uuid/${t}`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.join(",")}:{}}}class Pt extends se{constructor(e){super(),this.parameters=e}operation(){return re.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 h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.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/${I(null!=s?s:[],",")}/uuid/${R(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 Mt extends se{constructor(e){super(),this.parameters=e}operation(){return re.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 h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channels:t}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${I(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 jt 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 re.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 h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{}}))}get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/presence/sub-key/${t}/channel/${I(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 se{constructor(e){super(),this.parameters=e}operation(){return re.PNWhereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.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/${R(t)}`}}class At extends se{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?re.PNGlobalHereNowOperation:re.PNHereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){var t,s;const n=this.deserializeResponse(e);if(!n)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(n.status>=400)throw c.create(e);const r="occupancy"in n?1:n.payload.total_channels,i="occupancy"in n?n.occupancy:n.payload.total_channels,u={};let l={};if("occupancy"in n){const e=this.parameters.channels[0];l[e]={uuids:null!==(t=n.uuids)&&void 0!==t?t:[],occupancy:i}}else l=null!==(s=n.payload.channels)&&void 0!==s?s:{};return Object.keys(l).forEach((e=>{const t=l[e];u[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:u}}))}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/${I(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 Rt extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNDeleteMessagesOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v3/history/sub-key/${e}/channel/${R(t)}`}get queryParameters(){const{start:e,end:t}=this.parameters;return Object.assign(Object.assign({},e?{start:e}:{}),t?{end:t}:{})}}class It extends se{constructor(e){super(),this.parameters=e}operation(){return re.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 h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{channels:t.channels}}))}get path(){return`/v3/history/sub-key/${this.parameters.keySet.subscribeKey}/message-counts/${I(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 Ut extends se{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 re.PNHistoryOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("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/${R(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(Ut.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 Tt;!function(e){e[e.Message=-1]="Message",e[e.Files=4]="Files"}(Tt||(Tt={}));class Ft extends se{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 re.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 h(this,void 0,void 0,(function*(){var t;const s=this.deserializeResponse(e);if(!s)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(s.status>=400)throw c.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=Tt.Message);const s=this.processPayload(e,t),n={channel:e,timetoken:t.timetoken,message:s.payload,messageType:t.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/${I(t)}`}get queryParameters(){const{start:e,end:t,count:s,includeMessageType:n,includeMeta:r,includeUUID:i,stringifiedTimeToken:o}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({max:s},e?{start:e}:{}),t?{end:t}:{}),o?{string_message_token:"true"}:{}),void 0!==r&&r?{include_meta:"true"}:{}),i?{include_uuid:"true"}:{}),n?{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(Ft.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==Tt.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 xt extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNGetMessageActionsOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing message channel":"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.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/${R(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 Dt extends se{constructor(e){super({method:H.POST}),this.parameters=e}operation(){return re.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 h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{data:t.data}}))}get headers(){return{"Content-Type":"application/json"}}get path(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s}=this.parameters;return`/v1/message-actions/${e}/channel/${R(t)}/message/${s}`}get body(){return JSON.stringify(this.parameters.action)}}class Kt extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.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 h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.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/${R(t)}/message/${n}/action/${s}`}}class qt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).storeInHistory)&&void 0!==t||(s.storeInHistory=true)}operation(){return re.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 h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("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/${R(t)}/0/${R(this.prepareMessagePayload(o))}`}get queryParameters(){const{storeInHistory:e,ttl:t,meta:s}=this.parameters;return Object.assign(Object.assign({store:e?"1":"0"},t?{ttl:t}:{}),s&&"object"==typeof s?{meta:JSON.stringify(s)}:{})}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:y(s))}}class Gt extends se{constructor(e){super({method:H.LOCAL}),this.parameters=e}operation(){return re.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 h(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/${R(e)}/files/${t}/${s}`}}class $t extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.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 h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},id:t,channel:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${R(s)}/files/${t}/${n}`}}class Lt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).limit)&&void 0!==t||(s.limit=100)}operation(){return re.PNListFilesOperation}validate(){if(!this.parameters.channel)return"channel can't be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${R(t)}/files`}get queryParameters(){const{limit:e,next:t}=this.parameters;return Object.assign({limit:e},t?{next:t}:{})}}class Bt extends se{constructor(e){super({method:H.POST}),this.parameters=e}operation(){return re.PNGenerateUploadUrlOperation}validate(){return this.parameters.channel?this.parameters.name?void 0:"'name' can't be empty":"channel can't be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.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/${R(t)}/generate-upload-url`}get body(){return JSON.stringify({name:this.parameters.name})}}class Ht extends se{constructor(e){super({method:H.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 re.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 h(this,void 0,void 0,(function*(){return{status:e.status,message:e.body?Ht.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 h(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 o("Upload to bucket was unsuccessful",{error:!0,statusCode:e.status,category:i.PNUnknownCategory,operation:re.PNPublishFileOperation,errorData:{message:e.message}})})).then((()=>this.publishFileMessage(t,e))).catch((e=>{if(e instanceof o)throw e;const t=e instanceof c?e:c.create(e);throw new o("File upload error.",t.toStatus(re.PNPublishFileOperation))}))}))}generateFileUploadUrl(){return h(this,void 0,void 0,(function*(){const e=new Bt(Object.assign(Object.assign({},this.parameters),{name:this.file.name,keySet:this.parameters.keySet}));return this.parameters.sendRequest(e)}))}uploadFile(e){return h(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 Ht({fileId:i,fileName:o,file:this.file,uploadUrl:a,formFields:c}))}))}publishFileMessage(e,t){return h(this,void 0,void 0,(function*(){var s,n,r,a;let c,u={timetoken:"0"},l=this.parameters.fileUploadPublishRetryLimit,h=!1;do{try{u=yield this.parameters.publishFile(Object.assign(Object.assign({},this.parameters),{fileId:e,fileName:t})),h=!0}catch(e){e instanceof o&&(c=e),l-=1}}while(!h&&l>0);if(h)return{status:200,timetoken:u.timetoken,id:e,name:t};throw new o("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{error:!0,category:null!==(n=null===(s=c.status)||void 0===s?void 0:s.category)&&void 0!==n?n:i.PNUnknownCategory,statusCode:null!==(a=null===(r=c.status)||void 0===r?void 0:r.statusCode)&&void 0!==a?a:0,channel:this.parameters.channel,id:e,name:t})}))}}class Vt extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNAccessManagerRevokeToken}validate(){return this.parameters.keySet.secretKey?this.parameters.token?void 0:"token can't be empty":"Missing Secret Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},token:t}=this.parameters;return`/v3/pam/${e}/grant/${R(t)}`}}class Wt extends se{constructor(e){var t,s,n,r;super({method:H.POST}),this.parameters=e,null!==(t=(n=this.parameters).resources)&&void 0!==t||(n.resources={}),null!==(s=(r=this.parameters).patterns)&&void 0!==s||(r.patterns={})}operation(){return re.PNAccessManagerGrantToken}validate(){var e,t,s,n,r,i;const{keySet:{subscribeKey:o,publishKey:a,secretKey:c},resources:u,patterns:l}=this.parameters;if(!o)return"Missing Subscribe Key";if(!a)return"Missing Publish Key";if(!c)return"Missing Secret Key";if(!u&&!l)return"Missing either Resources or Patterns";if(this.isVspPermissions(this.parameters)&&("channels"in(null!==(e=this.parameters.resources)&&void 0!==e?e:{})||"uuids"in(null!==(t=this.parameters.resources)&&void 0!==t?t:{})||"groups"in(null!==(s=this.parameters.resources)&&void 0!==s?s:{})||"channels"in(null!==(n=this.parameters.patterns)&&void 0!==n?n:{})||"uuids"in(null!==(r=this.parameters.patterns)&&void 0!==r?r:{})||"groups"in(null!==(i=this.parameters.patterns)&&void 0!==i?i:{})))return"Cannot mix `users`, `spaces` and `authorizedUserId` with `uuids`, `channels`, `groups` and `authorized_uuid`";let h=!0;return[this.parameters.resources,this.parameters.patterns].forEach((e=>{Object.keys(null!=e?e:{}).forEach((t=>{var s;e&&h&&Object.keys(null!==(s=e[t])&&void 0!==s?s:{}).length>0&&(h=!1)}))})),h?"Missing values for either Resources or Patterns":void 0}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t.data.token}))}get path(){return`/v3/pam/${this.parameters.keySet.subscribeKey}/grant`}get body(){const{ttl:e,meta:t}=this.parameters,s=Object.assign({},e||0===e?{ttl:e}:{}),n=this.isVspPermissions(this.parameters)?this.parameters.authorizedUserId:this.parameters.authorized_uuid,r={},i={},o={},a=(e,t,s,n)=>{n[s]||(n[s]={}),n[s][e]=t},{resources:c,patterns:u}=this.parameters;return[c,u].forEach(((e,t)=>{var s,n,r,c,u;const l=0===t?i:o;let h={},d={},p={};l.channels||(l.channels={}),l.groups||(l.groups={}),l.uuids||(l.uuids={}),l.users||(l.users={}),l.spaces||(l.spaces={}),e&&("spaces"in e||"users"in e?(h=null!==(s=e.spaces)&&void 0!==s?s:{},p=null!==(n=e.users)&&void 0!==n?n:{}):("channels"in e||"uuids"in e||"groups"in e)&&(h=null!==(r=e.channels)&&void 0!==r?r:{},d=null!==(c=e.groups)&&void 0!==c?c:{},p=null!==(u=e.uuids)&&void 0!==u?u:{})),Object.keys(h).forEach((e=>a(e,this.extractPermissions(h[e]),"channels",l))),Object.keys(d).forEach((e=>a(e,this.extractPermissions(d[e]),"groups",l))),Object.keys(p).forEach((e=>a(e,this.extractPermissions(p[e]),"uuids",l)))})),n&&(r.uuid=`${n}`),r.resources=i,r.patterns=o,r.meta=null!=t?t:{},s.permissions=r,JSON.stringify(s)}extractPermissions(e){let t=0;return"join"in e&&e.join&&(t|=128),"update"in e&&e.update&&(t|=64),"get"in e&&e.get&&(t|=32),"delete"in e&&e.delete&&(t|=8),"manage"in e&&e.manage&&(t|=4),"write"in e&&e.write&&(t|=2),"read"in e&&e.read&&(t|=1),t}isVspPermissions(e){var t,s,n,r;return"authorizedUserId"in e||"spaces"in(null!==(t=e.resources)&&void 0!==t?t:{})||"users"in(null!==(s=e.resources)&&void 0!==s?s:{})||"spaces"in(null!==(n=e.patterns)&&void 0!==n?n:{})||"users"in(null!==(r=e.patterns)&&void 0!==r?r:{})}}class Jt extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f,m,b,v,w;super(),this.parameters=e,null!==(t=(h=this.parameters).channels)&&void 0!==t||(h.channels=[]),null!==(s=(d=this.parameters).channelGroups)&&void 0!==s||(d.channelGroups=[]),null!==(n=(p=this.parameters).uuids)&&void 0!==n||(p.uuids=[]),null!==(r=(g=this.parameters).read)&&void 0!==r||(g.read=false),null!==(i=(y=this.parameters).write)&&void 0!==i||(y.write=false),null!==(o=(f=this.parameters).delete)&&void 0!==o||(f.delete=false),null!==(a=(m=this.parameters).get)&&void 0!==a||(m.get=false),null!==(c=(b=this.parameters).update)&&void 0!==c||(b.update=false),null!==(u=(v=this.parameters).manage)&&void 0!==u||(v.manage=false),null!==(l=(w=this.parameters).join)&&void 0!==l||(w.join=false)}operation(){return re.PNAccessManagerGrant}validate(){const{keySet:{subscribeKey:e,publishKey:t,secretKey:s},uuids:n=[],channels:r=[],channelGroups:i=[],authKeys:o=[]}=this.parameters;return e?t?s?0!==n.length&&0===o.length?"authKeys are required for grant request on uuids":!n.length||0===r.length&&0===i.length?void 0:"Both channel/channel group and uuid cannot be used in the same request":"Missing Secret Key":"Missing Publish Key":"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t.payload}))}get path(){return`/v2/auth/grant/sub-key/${this.parameters.keySet.subscribeKey}`}get queryParameters(){const{channels:e,channelGroups:t,authKeys:s,uuids:n,read:r,write:i,manage:o,delete:a,get:c,join:u,update:l,ttl:h}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},e&&(null==e?void 0:e.length)>0?{channel:e.join(",")}:{}),t&&(null==t?void 0:t.length)>0?{"channel-group":t.join(",")}:{}),s&&(null==s?void 0:s.length)>0?{auth:s.join(",")}:{}),n&&(null==n?void 0:n.length)>0?{"target-uuid":n.join(",")}:{}),{r:r?"1":"0",w:i?"1":"0",m:o?"1":"0",d:a?"1":"0",g:c?"1":"0",j:u?"1":"0",u:l?"1":"0"}),h||0===h?{ttl:h}:{})}}const Qt=[];class Yt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).authKeys)&&void 0!==t||(s.authKeys=Qt)}operation(){return re.PNAccessManagerAudit}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t.payload}))}get path(){return`/v2/auth/audit/sub-key/${this.parameters.keySet.subscribeKey}`}get queryParameters(){const{channel:e,channelGroup:t,authKeys:s}=this.parameters;return Object.assign(Object.assign(Object.assign({},e?{channel:e}:{}),t?{"channel-group":t}:{}),s&&s.length?{auth:s.join(",")}:{})}}class Xt{subscribe(){var e,t;this.pubnub.subscribe(Object.assign({channels:this.channelNames,channelGroups:this.groupNames},(null===(t=null===(e=this.options)||void 0===e?void 0:e.cursor)||void 0===t?void 0:t.timetoken)&&{timetoken:this.options.cursor.timetoken}))}unsubscribe(){this.pubnub.unsubscribe({channels:this.channelNames.filter((e=>!e.endsWith("-pnpres"))),channelGroups:this.groupNames.filter((e=>!e.endsWith("-pnpres")))})}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.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}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 Zt extends Xt{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.filter((e=>!e.endsWith("-pnpres"))).forEach((e=>{const t=this.pubnub.channel(e).subscription(this.options);this.channelNames=[...this.channelNames,...t.channels],this.subscriptionList.push(t)})),t.filter((e=>!e.endsWith("-pnpres"))).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.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}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 es extends Xt{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.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}addSubscription(e){return new Zt({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 ts{constructor(e,t,s){this.id=e,this.eventEmitter=t,this.pubnub=s}subscription(e){return new es({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class ss{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){return new es({channels:[],channelGroups:(null==e?void 0:e.receivePresenceEvents)?[this.name,`${this.name}-pnpres`]:[this.name],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class ns{constructor(e,t,s){this.id=e,this.eventEmitter=t,this.pubnub=s}subscription(e){return new es({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class rs{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){return new es({channels:(null==e?void 0:e.receivePresenceEvents)?[this.name,`${this.name}-pnpres`]:[this.name],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class is extends se{constructor(e){super(),this.parameters=e}operation(){return re.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 h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${R(t)}`}get queryParameters(){return{remove:this.parameters.channels.join(",")}}}class os extends se{constructor(e){super(),this.parameters=e}operation(){return re.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 h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${R(t)}`}get queryParameters(){return{add:this.parameters.channels.join(",")}}}class as extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNChannelsForGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.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/${R(t)}`}}class cs extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNRemoveGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${R(t)}/remove`}}class us extends se{constructor(e){super(),this.parameters=e}operation(){return re.PNChannelGroupsOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return{groups:t.payload.groups}}))}get path(){return`/v1/channel-registration/sub-key/${this.parameters.keySet.subscribeKey}/channel-group`}}class ls{constructor(e,t){this.keySet=e,this.sendRequest=t}listChannels(e,t){return h(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)}))}listGroups(e){return h(this,void 0,void 0,(function*(){const t=new us({keySet:this.keySet});return e?this.sendRequest(t,e):this.sendRequest(t)}))}addChannels(e,t){return h(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)}))}removeChannels(e,t){return h(this,void 0,void 0,(function*(){const s=new is(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteGroup(e,t){return h(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)}))}}class hs extends se{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 h(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 ds extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove"}))}operation(){return re.PNRemovePushNotificationEnabledChannelsOperation}parse(e){return h(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new o("Service response error, check status for details",a("Unable to deserialize service response"));return{}}))}}class ps extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"list"}))}operation(){return re.PNPushNotificationEnabledChannelsOperation}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));return{channels:t}}))}}class gs extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"add"}))}operation(){return re.PNAddPushNotificationEnabledChannelsOperation}parse(e){return h(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new o("Service response error, check status for details",a("Unable to deserialize service response"));return{}}))}}class ys extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove-device"}))}operation(){return re.PNRemoveAllPushNotificationsOperation}parse(e){return h(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new o("Service response error, check status for details",a("Unable to deserialize service response"));return{}}))}}class fs{constructor(e,t){this.keySet=e,this.sendRequest=t}listChannels(e,t){return h(this,void 0,void 0,(function*(){const s=new ps(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}addChannels(e,t){return h(this,void 0,void 0,(function*(){const s=new gs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannels(e,t){return h(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)}))}deleteDevice(e,t){return h(this,void 0,void 0,(function*(){const s=new ys(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class ms extends se{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 re.PNGetAllChannelMetadataOperation}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.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,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));return 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 bs extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNRemoveChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${R(t)}`}}class vs extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(l=e.include).customFields)&&void 0!==s||(l.customFields=false),null!==(n=(h=e.include).totalCount)&&void 0!==n||(h.totalCount=false),null!==(r=(d=e.include).statusField)&&void 0!==r||(d.statusField=false),null!==(i=(p=e.include).channelFields)&&void 0!==i||(p.channelFields=false),null!==(o=(g=e.include).customChannelFields)&&void 0!==o||(g.customChannelFields=false),null!==(a=(y=e.include).channelStatusField)&&void 0!==a||(y.channelStatusField=false),null!==(c=(f=e.include).channelTypeField)&&void 0!==c||(f.channelTypeField=false),null!==(u=e.limit)&&void 0!==u||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNGetMembershipsOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${R(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=[];return e.statusField&&o.push("status"),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 ws extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(a=e.include).customFields)&&void 0!==s||(a.customFields=false),null!==(n=(c=e.include).totalCount)&&void 0!==n||(c.totalCount=false),null!==(r=(u=e.include).channelFields)&&void 0!==r||(u.channelFields=false),null!==(i=(l=e.include).customChannelFields)&&void 0!==i||(l.customChannelFields=false),null!==(o=e.limit)&&void 0!==o||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.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 h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${R(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=["channel.status","channel.type","status"];return e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),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,custom:e.custom}))})}}class Ss extends se{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 re.PNGetAllUUIDMetadataOperation}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.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,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));return 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 ks extends se{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 re.PNGetChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${R(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}}class Es extends se{constructor(e){var t,s,n;super({method:H.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 re.PNSetChannelMetadataOperation}validate(){return this.parameters.channel?this.parameters.data?void 0:"Data cannot be empty":"Channel cannot be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${R(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Os extends se{constructor(e){super({method:H.DELETE}),this.parameters=e,this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.PNRemoveUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${R(t)}`}}class Cs extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(l=e.include).customFields)&&void 0!==s||(l.customFields=false),null!==(n=(h=e.include).totalCount)&&void 0!==n||(h.totalCount=false),null!==(r=(d=e.include).statusField)&&void 0!==r||(d.statusField=false),null!==(i=(p=e.include).UUIDFields)&&void 0!==i||(p.UUIDFields=false),null!==(o=(g=e.include).customUUIDFields)&&void 0!==o||(g.customUUIDFields=false),null!==(a=(y=e.include).UUIDStatusField)&&void 0!==a||(y.UUIDStatusField=false),null!==(c=(f=e.include).UUIDTypeField)&&void 0!==c||(f.UUIDTypeField=false),null!==(u=e.limit)&&void 0!==u||(e.limit=100)}operation(){return re.PNSetMembersOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${R(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=[];return e.statusField&&o.push("status"),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 Ns extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(a=e.include).customFields)&&void 0!==s||(a.customFields=false),null!==(n=(c=e.include).totalCount)&&void 0!==n||(c.totalCount=false),null!==(r=(u=e.include).UUIDFields)&&void 0!==r||(u.UUIDFields=false),null!==(i=(l=e.include).customUUIDFields)&&void 0!==i||(l.customUUIDFields=false),null!==(o=e.limit)&&void 0!==o||(e.limit=100)}operation(){return re.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 h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${R(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=["uuid.status","uuid.type","type"];return e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),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,custom:e.custom}))})}}class Ps extends se{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 re.PNGetUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${R(t)}`}get queryParameters(){const{include:e}=this.parameters;return{include:["status","type",...e.customFields?["custom"]:[]].join(",")}}}class Ms extends se{constructor(e){var t,s,n;super({method:H.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 re.PNSetUUIDMetadataOperation}validate(){return this.parameters.uuid?this.parameters.data?void 0:"Data cannot be empty":"'uuid' cannot be empty"}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));if(t.status>=400)throw c.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${R(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class js{constructor(e,t){this.configuration=e,this.sendRequest=t,this.keySet=e.keySet}getAllUUIDMetadata(e,t){return h(this,void 0,void 0,(function*(){return this._getAllUUIDMetadata(e,t)}))}_getAllUUIDMetadata(e,t){return h(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 Ss(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getUUIDMetadata(e,t){return h(this,void 0,void 0,(function*(){return this._getUUIDMetadata(e,t)}))}_getUUIDMetadata(e,t){return h(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)}))}setUUIDMetadata(e,t){return h(this,void 0,void 0,(function*(){return this._setUUIDMetadata(e,t)}))}_setUUIDMetadata(e,t){return h(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 Ms(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeUUIDMetadata(e,t){return h(this,void 0,void 0,(function*(){return this._removeUUIDMetadata(e,t)}))}_removeUUIDMetadata(e,t){return h(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 Os(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}getAllChannelMetadata(e,t){return h(this,void 0,void 0,(function*(){return this._getAllChannelMetadata(e,t)}))}_getAllChannelMetadata(e,t){return h(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 ms(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getChannelMetadata(e,t){return h(this,void 0,void 0,(function*(){return this._getChannelMetadata(e,t)}))}_getChannelMetadata(e,t){return h(this,void 0,void 0,(function*(){const s=new ks(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setChannelMetadata(e,t){return h(this,void 0,void 0,(function*(){return this._setChannelMetadata(e,t)}))}_setChannelMetadata(e,t){return h(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)}))}removeChannelMetadata(e,t){return h(this,void 0,void 0,(function*(){return this._removeChannelMetadata(e,t)}))}_removeChannelMetadata(e,t){return h(this,void 0,void 0,(function*(){const s=new bs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getChannelMembers(e,t){return h(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)}))}setChannelMembers(e,t){return h(this,void 0,void 0,(function*(){const s=new Ns(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannelMembers(e,t){return h(this,void 0,void 0,(function*(){const s=new Ns(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getMemberships(e,t){return h(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 vs(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setMemberships(e,t){return h(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 ws(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeMemberships(e,t){return h(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 ws(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}fetchMemberships(e,t){return h(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 h(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:(e.userId,{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 _s extends se{constructor(){super()}operation(){return re.PNTimeOperation}parse(e){return h(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new o("Service response error, check status for details",a("Unable to deserialize service response"));return{timetoken:t[0]}}))}get path(){return"/time/0"}}class As extends se{constructor(e){super(),this.parameters=e}operation(){return re.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 h(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/${R(t)}/files/${s}/${n}`}}class Rs{static notificationPayload(e,t){return new te(e,t)}static generateUUID(){return G.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 js(this._configuration,this.sendRequest.bind(this)),this._channelGroups=new ls(this._configuration.keySet,this.sendRequest.bind(this)),this._push=new fs(this._configuration.keySet,this.sendRequest.bind(this)),this.listenerManager=new W,this.eventEmitter=new ce(this.listenerManager),this._configuration.enableEventEngine){let e=this._configuration.getHeartbeatInterval();this.presenceState={},e&&(this.presenceEventEngine=new $e({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 o("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 St({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:i.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 rs(e,this.eventEmitter,this)}channelGroup(e){return new ss(e,this.eventEmitter,this)}channelMetadata(e){return new ts(e,this.eventEmitter,this)}userMetadata(e){return new ns(e,this.eventEmitter,this)}subscriptionSet(e){return new Zt(Object.assign(Object.assign({},e),{eventEmitter:this.eventEmitter,pubnub:this}))}sendRequest(e,t){return h(this,void 0,void 0,(function*(){const s=e.validate();if(s){if(t)return t(a(s),null);throw new o("Validation failed, check status for details",a(s))}const n=e.request();n.formData&&n.formData.length>0?n.timeout=300:e.operation()===re.PNSubscribeOperation?n.timeout=this._configuration.getSubscribeTimeout():n.timeout=this._configuration.getTransactionTimeout();const r={error:!1,operation:e.operation(),category:i.PNAcknowledgmentCategory,statusCode:0},[u,l]=this.transport.makeSendable(n);return e.cancellationController=l||null,u.then((t=>{if(r.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(Rs.decoder.decode(t.body));"object"==typeof e&&"error"in e&&e.error&&"object"==typeof e.error&&(r.errorData=e.error)}}return e.parse(t)})).then((e=>t?t(r,e):e)).catch((s=>{const n=s instanceof c?s:c.create(s);if(t)return t(n.toStatus(e.operation()),null);throw n.toPubNubError(e.operation(),"REST API request processing error, check status for details")}))}))}destroy(e){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 h(this,void 0,void 0,(function*(){const s=new kt(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 h(this,void 0,void 0,(function*(){const s=new Et(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}fire(e,t){return h(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():[]}subscribe(e){this.subscriptionManager?this.subscriptionManager.subscribe(e):this.eventEngine&&this.eventEngine.subscribe(e)}makeSubscribe(e,t){const s=new ae(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 jt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),t)}unsubscribeAll(){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 h(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)})),s=e.abortSignal.subscribe((e=>{t.abort()}));return this.sendRequest(t).then((e=>(s(),e.cursor)))}))}subscribeReceiveMessages(e){return h(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)))}))}getMessageActions(e,t){return h(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)}))}addMessageAction(e,t){return h(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)}))}removeMessageAction(e,t){return h(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)}))}fetchMessages(e,t){return h(this,void 0,void 0,(function*(){const s=new Ft(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 h(this,void 0,void 0,(function*(){const s=new Rt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}messageCounts(e,t){return h(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 h(this,void 0,void 0,(function*(){const s=new Ut(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 h(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 h(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 h(this,void 0,void 0,(function*(){var s;const n=new Nt(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 h(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 Mt(Object.assign(Object.assign({},e),{keySet:r,heartbeat:o})):new Pt(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 h(this,void 0,void 0,(function*(){const s=new Mt(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 h(this,void 0,void 0,(function*(){const s=new Wt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}revokeToken(e,t){return h(this,void 0,void 0,(function*(){const s=new Vt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}get token(){return this.tokenManager.getToken()}getToken(){return this.token}set token(e){this.tokenManager.setToken(e)}setToken(e){this.token=e}parseToken(e){return this.tokenManager.parseToken(e)}grant(e,t){return h(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)}))}audit(e,t){return h(this,void 0,void 0,(function*(){const s=new Yt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}get objects(){return this._objects}fetchUsers(e,t){return h(this,void 0,void 0,(function*(){return this.objects._getAllUUIDMetadata(e,t)}))}fetchUser(e,t){return h(this,void 0,void 0,(function*(){return this.objects._getUUIDMetadata(e,t)}))}createUser(e,t){return h(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}updateUser(e,t){return h(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}removeUser(e,t){return h(this,void 0,void 0,(function*(){return this.objects._removeUUIDMetadata(e,t)}))}fetchSpaces(e,t){return h(this,void 0,void 0,(function*(){return this.objects._getAllChannelMetadata(e,t)}))}fetchSpace(e,t){return h(this,void 0,void 0,(function*(){return this.objects._getChannelMetadata(e,t)}))}createSpace(e,t){return h(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}updateSpace(e,t){return h(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}removeSpace(e,t){return h(this,void 0,void 0,(function*(){return this.objects._removeChannelMetadata(e,t)}))}fetchMemberships(e,t){return h(this,void 0,void 0,(function*(){return this.objects.fetchMemberships(e,t)}))}addMemberships(e,t){return h(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}updateMemberships(e,t){return h(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}removeMemberships(e,t){return h(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 h(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 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})),n={error:!1,operation:re.PNPublishFileOperation,category:i.PNAcknowledgmentCategory,statusCode:0};return s.process().then((e=>(n.statusCode=e.status,t?t(n,e):e))).catch((e=>{let s;throw e instanceof o?s=e.status:e instanceof c&&(s=e.toStatus(n.operation)),t&&s&&t(s,null),new o("REST API request processing error, check status for details",s)}))}))}publishFile(e,t){return h(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 h(this,void 0,void 0,(function*(){const s=new Lt(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}=${R(t)}`)).join("&"):`${e}=${R(t)}`})).join("&");return`${s.origin}${s.path}?${r}`}downloadFile(e,t){return h(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 As(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 h(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)}))}time(e){return h(this,void 0,void 0,(function*(){const t=new _s;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:y(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 h(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 h(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)}))}}Rs.decoder=new TextDecoder,Rs.OPERATIONS=re,Rs.CATEGORIES=i,Rs.ExponentialRetryPolicy=Le.ExponentialRetryPolicy,Rs.LinearRetryPolicy=Le.LinearRetryPolicy;class Is{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 Us extends Rs{constructor(e){var t;const s=D(e),n=Object.assign(Object.assign({},s),{sdkFamily:"Web",PubNubFile:p}),i=$(n,(e=>{if(e.cipherKey)return new j({default:new M(Object.assign({},e)),cryptors:[new E({cipherKey:e.cipherKey})]})})),o=new B(new Is((e=>x(r.decode(e))),g));let a;(i.getCipherKey()||i.secretKey)&&(a=new C({secretKey:i.secretKey,cipherKey:i.getCipherKey(),useRandomIVs:i.getUseRandomIVs(),customEncrypt:i.getCustomEncrypt(),customDecrypt:i.getCustomDecrypt()}));let c=new F(i.keepAlive,i.logVerbosity);s.serviceWorkerUrl&&(c=new u({clientIdentifier:i._instanceId,subscriptionKey:i.subscribeKey,serviceWorkerUrl:s.serviceWorkerUrl,sdkVersion:i.getVersion(),logVerbosity:i.logVerbosity,transport:c}));super({configuration:i,transport:new V({clientConfiguration:i,tokenManager:o,transport:c}),cryptography:new P,tokenManager:o,crypto:a}),(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 Us.CryptoModule=j,Us})); +!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},void 0!==t?{statusCode:t}:{}),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,t){var s={},n=s.lib={},r=function(){},i=n.Base={extend:function(e){r.prototype=this;var t=new r;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)}},o=n.WordArray=i.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||c).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=i.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 o.init(s,t/2)}},u=a.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 o.init(s,t)}},l=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},h=n.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new o.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=l.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var s=this._data,n=s.words,r=s.sigBytes,i=this.blockSize,a=r/(4*i);if(t=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*i,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]}},t.BlockCipher=a.extend({cfg:a.cfg.extend({mode:c,padding:l}),reset:function(){a.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var 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 h=t.CipherParams=s.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),d=(c=(p.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?n.create([1398893684,1701076831]).concat(e).concat(t):t).toString(i)},parse:function(e){var t=(e=i.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var s=n.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return h.create({ciphertext:e,salt:s})}},t.SerializableCipher=s.extend({cfg:s.extend({format:c}),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,h.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}})),p=(p.kdf={}).OpenSSL={execute:function(e,t,s,r){return r||(r=n.random(8)),e=o.create({keySize:t+s}).compute(e,r),s=n.create(e.words.slice(t),4*s),e.sigBytes=4*t,h.create({key:e,iv:s,salt:r})}},g=t.PasswordBasedCipher=d.extend({cfg:d.cfg.extend({kdf:p}),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=d.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,d.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=C.encoder.encode(s.slice(0,32)).buffer;return crypto.subtle.importKey("raw",n,"AES-CBC",!0,["encrypt","decrypt"])}))}}C.IV_LENGTH=16,C.encoder=new TextEncoder,C.decoder=new TextDecoder;class N{constructor(e){this.config=e,this.cryptor=new E(Object.assign({},e)),this.fileCryptor=new C}encrypt(e){const t="string"==typeof e?e:N.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""}}N.encoder=new TextEncoder,N.decoder=new TextDecoder;class P extends o{static legacyCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new P({default:new N(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 P({default:new S({cipherKey:e.cipherKey}),cryptors:[new N(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===P.LEGACY_IDENTIFIER?this.defaultCryptor.encrypt(P.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===M.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=M.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=M.tryParse(s),r=this.getCryptor(n);if((null==r?void 0:r.identifier)===M.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 j)return this.getCryptorFromId(e.identifier)}getHeaderData(e){if(!e.metadata)return;const t=M.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")}))}}P.LEGACY_IDENTIFIER="";class M{static from(e,t){if(e!==M.LEGACY_IDENTIFIER)return new j(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)!==M.SENTINEL))return P.LEGACY_IDENTIFIER;if(!(t.byteLength>=5))throw new Error("Decryption error: invalid header version");if(r=t[4],r>M.MAX_VERSION)throw new Error("Decryption error: Unknown cryptor error");let i=5+M.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 j(this.decoder.decode(n),o)}}M.SENTINEL="PNED",M.LEGACY_IDENTIFIER="",M.IDENTIFIER_LENGTH=4,M.VERSION=1,M.MAX_VERSION=1,M.decoder=new TextDecoder;class j{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 M.VERSION}get length(){return M.SENTINEL.length+1+M.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(M.SENTINEL)),e+=M.SENTINEL.length,t[e]=this.version,e++,this.identifier&&t.set(s.encode(this.identifier),e);const n=this.metadataLength;return e+=M.IDENTIFIER_LENGTH,n<255?t[e]=n:t.set([255,n>>8,255&n],e),t}}j.IDENTIFIER_LENGTH=4,j.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.indexOf("timeout"))t=h.PNTimeoutCategory,s="Request timeout";else if(-1!==s.indexOf("network"))t=h.PNNetworkIssuesCategory,s="Network issues";else if("TypeError"===n)t=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("/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,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);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("-----"))}}const I=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),R=(e,t)=>{const s=e.map((e=>I(e)));return s.length?s.join(","):null!=t?t:""},U=(e,t)=>{const s=Object.fromEntries(t.map((e=>[e,!1])));return e.filter((e=>!(t.includes(e)&&!s[e])||(s[e]=!0,!1)))},T=(e,t)=>[...e].filter((s=>t.includes(s)&&e.indexOf(s)===e.lastIndexOf(s)&&t.indexOf(s)===t.lastIndexOf(s)));class F{constructor(e=!1,t){this.keepAlive=e,this.logVerbosity=t}makeSendable(e){let t,s;return e.cancellable&&(s=new AbortController,t={abortController:s,abort:()=>null==s?void 0:s.abort()}),[this.requestFromTransportRequest(e).then((t=>{const n=(new Date).getTime();this.logRequestProcessProgress(t);const r=new Promise(((t,s)=>{const n=setTimeout((()=>{clearTimeout(n),s(new Error("Request timeout"))}),1e3*e.timeout)}));return Promise.race([fetch(t,{signal:null==s?void 0:s.signal}),r]).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,(new Date).getTime()-n,s),a})).catch((e=>{throw _.create(e)}))})),t]}request(e){return e}requestFromTransportRequest(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}=${I(t)}`)).join("&"):`${e}=${I(t)}`})).join("&")}`),new Request(`${e.origin}${s}`,{method:e.method,headers:e.headers,redirect:"follow",body:t})}))}logRequestProcessProgress(e,t,s){if(!this.logVerbosity)return;const{protocol:n,host:r,pathname:i,search:o}=new URL(e.url),a=(new Date).toISOString();if(t){const e=s?F.decoder.decode(s):void 0;console.log(">>>>>>"),console.log(`[${a} / ${t}]`,`\n${n}//${r}${i}`,`\n${o}`,`\n${e}`),console.log("-----")}else console.log("<<<<<"),console.log(`[${a}]`,`\n${n}//${r}${i}`,`\n${o}`),console.log("-----")}}function x(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)?x(a):a})),n}F.decoder=new TextDecoder;const D=e=>{var t,s,n;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.restore)&&void 0!==i||(m.restore=!1),null!==(o=m.useInstanceId)&&void 0!==o||(m.useInstanceId=!1),null!==(a=m.suppressLeaveEvents)&&void 0!==a||(m.suppressLeaveEvents=!1),null!==(c=m.requestMessageCountThreshold)&&void 0!==c||(m.requestMessageCountThreshold=100),null!==(u=m.autoNetworkDetection)&&void 0!==u||(m.autoNetworkDetection=!1),null!==(l=m.enableEventEngine)&&void 0!==l||(m.enableEventEngine=!1),null!==(h=m.maintainPresenceState)&&void 0!==h||(m.maintainPresenceState=!0),null!==(p=m.keepAlive)&&void 0!==p||(m.keepAlive=!1),m.userId&&m.uuid)throw new d("PubNub client configuration error: use only 'userId'");if(null!==(g=m.userId)&&void 0!==g||(m.userId=m.uuid),!m.userId)throw new d("PubNub client configuration error: 'userId' not set");if(0===(null===(y=m.userId)||void 0===y?void 0:y.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)),null!==(f=m.presenceTimeout)&&void 0!==f||(m.presenceTimeout=300);let v=!1,w=!0,S=5,k=!1,E=!0;return void 0!==m.dedupeOnSubscribe&&"boolean"==typeof m.dedupeOnSubscribe&&(k=m.dedupeOnSubscribe),void 0!==m.useRequestId&&"boolean"==typeof m.useRequestId&&(E=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:100,useRequestId:E,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,keepAlive:null===(n=e.keepAlive)||void 0===n||n})};var K={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)}(K,K.exports);var q=t(K.exports),G={createUUID:()=>q.uuid?q.uuid():q()};const $=(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=L(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-${G.createUUID()}`,_cryptoModule:void 0,_cipherKey:void 0,_setupCryptoModule:t,get instanceId(){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},get PubNubFile(){return e.PubNubFile},get version(){return"8.0.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},L=(e,t)=>{const s=e?"https://":"http://";return"string"==typeof t?`${s}${t}`:`${s}${t[Math.floor(Math.random()*t.length)]}`};class B{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 H;!function(e){e.GET="GET",e.POST="POST",e.PATCH="PATCH",e.DELETE="DELETE",e.LOCAL="LOCAL"}(H||(H={}));class z{constructor(e,t,s){this.publishKey=e,this.secretKey=t,this.hasher=s}signature(e){const t=e.path.startsWith("/publish")?H.GET:e.method;let s=`${t}\n${this.publishKey}\n${e.path}\n${this.queryParameters(e.queryParameters)}\n`;if(t===H.POST||t===H.PATCH){const t=e.body;let n;t&&t instanceof ArrayBuffer?n=z.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}=${I(e)}`)).join("&"):`${t}=${I(s)}`})).join("&")}}z.textDecoder=new TextDecoder("utf-8");class V{constructor(e){this.configuration=e;const{clientConfiguration:{keySet:t},shaHMAC:s}=e;t.secretKey&&s&&(this.signatureGenerator=new z(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.instanceId),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.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 W{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 J{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{_config;hashHistory;constructor({config:e}){this.hashHistory=[],this._config=e}getKey(e){const t=(e=>{let t=0;if(0===e.length)return t;for(let s=0;s=this._config.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}clearHistory(){this.hashHistory=[]}}class Y{constructor(e,t,s,n,r,i,o){this.configuration=e,this.listenerManager=t,this.eventEmitter=s,this.subscribeCall=n,this.heartbeatCall=r,this.leaveCall=i,this.reconnectionManager=new J(o),this.dedupingManager=new Q({config:this.configuration}),this.heartbeatChannelGroups={},this.heartbeatChannels={},this.presenceChannelGroups={},this.presenceChannels={},this.heartbeatTimer=null,this.presenceState={},this.pendingChannelGroupSubscriptions=new Set,this.pendingChannelSubscriptions=new Set,this.channelGroups={},this.channels={},this.currentTimetoken="0",this.lastTimetoken="0",this.storedTimetoken=null,this.subscriptionStatusAnnounced=!1,this.isOnline=!0}get subscribedChannels(){return Object.keys(this.channels)}get subscribedChannelGroups(){return Object.keys(this.channelGroups)}get abort(){return this._subscribeAbort}set abort(e){this._subscribeAbort=e}disconnect(){this.stopSubscribeLoop(),this.stopHeartbeatTimer(),this.reconnectionManager.stopPolling()}reconnect(){this.startSubscribeLoop(),this.startHeartbeatTimer()}subscribe(e){const{channels:t,channelGroups:s,timetoken:n,withPresence:r=!1,withHeartbeats:i=!1}=e;n&&(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=n),"0"!==this.currentTimetoken&&0!==this.currentTimetoken&&(this.storedTimetoken=this.currentTimetoken,this.currentTimetoken=0),null==t||t.forEach((e=>{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())}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){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 X{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 Z extends X{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 ee extends X{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 te{constructor(e,t){this._payload={apns:{},fcm:{}},this._title=e,this._body=t,this.apns=new Z(this._payload.apns,e,t),this.fcm=new ee(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 se{constructor(e){this.params=e,this.requestIdentifier=G.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:H.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:1e4,identifier:this.requestIdentifier},i=this.headers;if(i&&(r.headers=i),r.method===H.POST||r.method===H.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=se.decoder.decode(e.body);try{return JSON.parse(s)}catch(e){return void console.error("Error parsing JSON response:",e)}}}var ne;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"}(ne||(ne={}));var re=ne;var ie;!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"}(ie||(ie={}));class oe extends se{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 re.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=se.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.map((e=>{let{e:t}=e;return null!=t||(t=e.c.endsWith("-pnpres")?ie.Presence:ie.Message),"string"==typeof e.d?t==ie.Message?{type:ie.Message,data:this.messageFromEnvelope(e)}:{type:ie.Files,data:this.fileFromEnvelope(e)}:t==ie.Message?{type:ie.Message,data:this.messageFromEnvelope(e)}:t===ie.Presence?{type:ie.Presence,data:this.presenceEventFromEnvelope(e)}:t==ie.Signal?{type:ie.Signal,data:this.signalFromEnvelope(e)}:t===ie.AppContext?{type:ie.AppContext,data:this.appContextFromEnvelope(e)}:t===ie.MessageAction?{type:ie.MessageAction,data:this.messageActionFromEnvelope(e)}:{type:ie.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){const{d:t}=e,[s,n]=this.subscriptionChannelFromEnvelope(e),r=s.replace("-pnpres",""),i=null!==n?r:null,o=null!==n?n:r;return"string"!=typeof t&&"data"in t&&(t.state=t.data,delete t.data),Object.assign({channel:r,subscription:n,actualChannel:i,subscribedChannel:o,timetoken:e.p.t},t)}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),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),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."),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(ae.decoder.decode(s)):s}catch(e){t=null,s=`Error while decrypting message content: ${e.message}`}return[null!=t?t:e,s]}}class ae extends oe{get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/subscribe/${t}/${R(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 ce{constructor(e){this.listenerManager=e,this.channelListenerMap=new Map,this.groupListenerMap=new Map}emitEvent(e){if(e.type===ie.Message)this.listenerManager.announceMessage(e.data),this.announce("message",e.data,e.data.channel,e.data.subscription);else if(e.type===ie.Signal)this.listenerManager.announceSignal(e.data),this.announce("signal",e.data,e.data.channel,e.data.subscription);else if(e.type===ie.Presence)this.listenerManager.announcePresence(e.data),this.announce("presence",e.data,e.data.channel,e.data.subscription);else if(e.type===ie.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===ie.MessageAction?(this.listenerManager.announceMessageAction(e.data),this.announce("messageAction",e.data,e.data.channel,e.data.subscription)):e.type===ie.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 ue{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 le{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 he extends ue{describe(e){return new le(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 de{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 pe(e,t){const s=function(...s){return{type:e,payload:null==t?void 0:t(...s)}};return s.type=e,s}function ge(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!1});return s.type=e,s}function ye(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 fe extends Error{constructor(){super("The operation was aborted."),this.name="AbortError",Object.setPrototypeOf(this,new.target.prototype)}}class me extends ue{constructor(){super(...arguments),this._aborted=!1}get aborted(){return this._aborted}throwIfAborted(){if(this._aborted)throw new fe}abort(){this._aborted=!0,this.notify(new fe)}}class be{constructor(e,t){this.payload=e,this.dependencies=t}}class ve extends be{constructor(e,t,s){super(e,t),this.asyncFunction=s,this.abortSignal=new me}start(){this.asyncFunction(this.payload,this.abortSignal,this.dependencies).catch((e=>{}))}cancel(){this.abortSignal.abort()}}const we=e=>(t,s)=>new ve(t,s,e),Se=pe("RECONNECT",(()=>({}))),ke=pe("DISCONNECT",(()=>({}))),Ee=pe("JOINED",((e,t)=>({channels:e,groups:t}))),Oe=pe("LEFT",((e,t)=>({channels:e,groups:t}))),Ce=pe("LEFT_ALL",(()=>({}))),Ne=pe("HEARTBEAT_SUCCESS",(e=>({statusCode:e}))),Pe=pe("HEARTBEAT_FAILURE",(e=>e)),Me=pe("HEARTBEAT_GIVEUP",(()=>({}))),je=pe("TIMES_UP",(()=>({}))),_e=ge("HEARTBEAT",((e,t)=>({channels:e,groups:t}))),Ae=ge("LEAVE",((e,t)=>({channels:e,groups:t}))),Ie=ge("EMIT_STATUS",(e=>e)),Re=ye("WAIT",(()=>({}))),Ue=ye("DELAYED_HEARTBEAT",(e=>e));class Te extends de{constructor(e,t){super(t),this.on(_e.type,we(((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(Ne(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Pe(t))}}}))))),this.on(Ae.type,we(((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(Re.type,we(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeatDelay:n}){return s.throwIfAborted(),yield n(),s.throwIfAborted(),e.transition(je())}))))),this.on(Ue.type,we(((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(Me());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(Ne(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Pe(t))}}}))))),this.on(Ie.type,we(((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:re.PNHeartbeatOperation,error:!1}))})))))}}const Fe=new le("HEARTBEAT_STOPPED");Fe.on(Ee.type,((e,t)=>Fe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Fe.on(Oe.type,((e,t)=>Fe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))}))),Fe.on(Se.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),Fe.on(Ce.type,((e,t)=>Ge.with(void 0)));const xe=new le("HEARTBEAT_COOLDOWN");xe.onEnter((()=>Re())),xe.onExit((()=>Re.cancel)),xe.on(je.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),xe.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),xe.on(Oe.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(ke.type,(e=>Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),xe.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const De=new le("HEARTBEAT_FAILED");De.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),De.on(Oe.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)=>qe.with({channels:e.channels,groups:e.groups}))),De.on(ke.type,((e,t)=>Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),De.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const Ke=new le("HEARBEAT_RECONNECTING");Ke.onEnter((e=>Ue(e))),Ke.onExit((()=>Ue.cancel)),Ke.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Ke.on(Oe.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)]))),Ke.on(ke.type,((e,t)=>{Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)])})),Ke.on(Ne.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups}))),Ke.on(Pe.type,((e,t)=>Ke.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),Ke.on(Me.type,((e,t)=>De.with({channels:e.channels,groups:e.groups}))),Ke.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const qe=new le("HEARTBEATING");qe.onEnter((e=>_e(e.channels,e.groups))),qe.on(Ne.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups}))),qe.on(Ee.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),qe.on(Oe.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(Pe.type,((e,t)=>Ke.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),qe.on(ke.type,(e=>Fe.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),qe.on(Ce.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const Ge=new le("HEARTBEAT_INACTIVE");Ge.on(Ee.type,((e,t)=>qe.with({channels:t.payload.channels,groups:t.payload.groups})));class $e{get _engine(){return this.engine}constructor(e){this.dependencies=e,this.engine=new he,this.channels=[],this.groups=[],this.dispatcher=new Te(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(Ee(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(Oe(null!=e?e:[],null!=t?t:[]))}leaveAll(){this.engine.transition(Ce())}dispose(){this._unsubscribeEngine(),this.dispatcher.dispose()}}class Le{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 Be=ye("HANDSHAKE",((e,t)=>({channels:e,groups:t}))),He=ye("RECEIVE_MESSAGES",((e,t,s)=>({channels:e,groups:t,cursor:s}))),ze=ge("EMIT_MESSAGES",(e=>e)),Ve=ge("EMIT_STATUS",(e=>e)),We=ye("RECEIVE_RECONNECT",(e=>e)),Je=ye("HANDSHAKE_RECONNECT",(e=>e)),Qe=pe("SUBSCRIPTION_CHANGED",((e,t)=>({channels:e,groups:t}))),Ye=pe("SUBSCRIPTION_RESTORED",((e,t,s,n)=>({channels:e,groups:t,cursor:{timetoken:s,region:null!=n?n:0}}))),Xe=pe("HANDSHAKE_SUCCESS",(e=>e)),Ze=pe("HANDSHAKE_FAILURE",(e=>e)),et=pe("HANDSHAKE_RECONNECT_SUCCESS",(e=>({cursor:e}))),tt=pe("HANDSHAKE_RECONNECT_FAILURE",(e=>e)),st=pe("HANDSHAKE_RECONNECT_GIVEUP",(e=>e)),nt=pe("RECEIVE_SUCCESS",((e,t)=>({cursor:e,events:t}))),rt=pe("RECEIVE_FAILURE",(e=>e)),it=pe("RECEIVE_RECONNECT_SUCCESS",((e,t)=>({cursor:e,events:t}))),ot=pe("RECEIVE_RECONNECT_FAILURE",(e=>e)),at=pe("RECEIVING_RECONNECT_GIVEUP",(e=>e)),ct=pe("DISCONNECT",(()=>({}))),ut=pe("RECONNECT",((e,t)=>({cursor:{timetoken:null!=e?e:"",region:null!=t?t:0}}))),lt=pe("UNSUBSCRIBE_ALL",(()=>({})));class ht extends de{constructor(e,t){super(t),this.on(Be.type,we(((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(Xe(o))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Ze(t))}}}))))),this.on(He.type,we(((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(nt(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(rt(t))}}}))))),this.on(ze.type,we(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitMessages:s}){e.length>0&&s(e)}))))),this.on(Ve.type,we(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s}){s(e)}))))),this.on(We.type,we(((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(at(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(it(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(Je.type,we(((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(st(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(et(r))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(tt(t))}}})))))}}const dt=new le("HANDSHAKE_FAILED");dt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),dt.on(ut.type,((e,t)=>vt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor||e.cursor}))),dt.on(Ye.type,((e,t)=>{var s,n;return vt.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}})})),dt.on(lt.type,(e=>wt.with()));const pt=new le("HANDSHAKE_STOPPED");pt.on(Qe.type,((e,t)=>pt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),pt.on(ut.type,((e,t)=>vt.with(Object.assign(Object.assign({},e),{cursor:t.payload.cursor||e.cursor})))),pt.on(Ye.type,((e,t)=>{var s;return pt.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}})})),pt.on(lt.type,(e=>wt.with()));const gt=new le("RECEIVE_FAILED");gt.on(ut.type,((e,t)=>{var s;return vt.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(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),gt.on(Ye.type,((e,t)=>vt.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(lt.type,(e=>wt.with(void 0)));const yt=new le("RECEIVE_STOPPED");yt.on(Qe.type,((e,t)=>yt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),yt.on(Ye.type,((e,t)=>yt.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(ut.type,((e,t)=>{var s;return vt.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}})})),yt.on(lt.type,(()=>wt.with(void 0)));const ft=new le("RECEIVE_RECONNECTING");ft.onEnter((e=>We(e))),ft.onExit((()=>We.cancel)),ft.on(it.type,((e,t)=>mt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),ft.on(ot.type,((e,t)=>ft.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),ft.on(at.type,((e,t)=>{var s;return gt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[Ve({category:h.PNDisconnectedUnexpectedlyCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),ft.on(ct.type,(e=>yt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[Ve({category:h.PNDisconnectedCategory})]))),ft.on(Ye.type,((e,t)=>mt.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(Qe.type,((e,t)=>mt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),ft.on(lt.type,(e=>wt.with(void 0,[Ve({category:h.PNDisconnectedCategory})])));const mt=new le("RECEIVING");mt.onEnter((e=>He(e.channels,e.groups,e.cursor))),mt.onExit((()=>He.cancel)),mt.on(nt.type,((e,t)=>mt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),mt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?wt.with(void 0):mt.with({cursor:e.cursor,channels:t.payload.channels,groups:t.payload.groups}))),mt.on(Ye.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?wt.with(void 0):mt.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(rt.type,((e,t)=>ft.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),mt.on(ct.type,(e=>yt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[Ve({category:h.PNDisconnectedCategory})]))),mt.on(lt.type,(e=>wt.with(void 0,[Ve({category:h.PNDisconnectedCategory})])));const bt=new le("HANDSHAKE_RECONNECTING");bt.onEnter((e=>Je(e))),bt.onExit((()=>Je.cancel)),bt.on(et.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 mt.with({channels:e.channels,groups:e.groups,cursor:r},[Ve({category:h.PNConnectedCategory})])})),bt.on(tt.type,((e,t)=>bt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),bt.on(st.type,((e,t)=>{var s;return dt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[Ve({category:h.PNConnectionErrorCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),bt.on(ct.type,(e=>pt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),bt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),bt.on(Ye.type,((e,t)=>{var s,n;return vt.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}})})),bt.on(lt.type,(e=>wt.with(void 0)));const vt=new le("HANDSHAKING");vt.onEnter((e=>Be(e.channels,e.groups))),vt.onExit((()=>Be.cancel)),vt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?wt.with(void 0):vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),vt.on(Xe.type,((e,t)=>{var s,n;return mt.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}},[Ve({category:h.PNConnectedCategory})])})),vt.on(Ze.type,((e,t)=>bt.with({channels:e.channels,groups:e.groups,cursor:e.cursor,attempts:0,reason:t.payload}))),vt.on(ct.type,(e=>pt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),vt.on(Ye.type,((e,t)=>{var s;return vt.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}})})),vt.on(lt.type,(e=>wt.with()));const wt=new le("UNSUBSCRIBED");wt.on(Qe.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups}))),wt.on(Ye.type,((e,t)=>vt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:t.payload.cursor})));class St{get _engine(){return this.engine}constructor(e){this.engine=new he,this.channels=[],this.groups=[],this.dependencies=e,this.dispatcher=new ht(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(wt,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(Ye(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])),s)):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 s=U(this.channels,[...e,...e.map((e=>`${e}-pnpres`))]),n=U(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=T(this.channels,e),i=T(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(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(ut(e,t))}disconnect(){this.engine.transition(ct()),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 kt extends se{constructor(e){var t,s;super({method:e.sendByPost?H.POST:H.GET}),this.parameters=e,null!==(t=(s=this.parameters).sendByPost)&&void 0!==t||(s.sendByPost=false)}operation(){return re.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/${I(t)}/0${this.parameters.sendByPost?"":`/${I(n)}`}`}get queryParameters(){const{meta:e,replicate:t,storeInHistory:s,ttl:n}=this.parameters,r={};return void 0!==s&&(r.store=s?"1":"0"),void 0!==n&&(r.ttl=n),void 0===t||t||(r.norep="true"),e&&"object"==typeof e&&(r.meta=JSON.stringify(e)),r}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 Et extends se{constructor(e){super(),this.parameters=e}operation(){return re.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/${I(s)}/0/${I(r)}`}}class Ot extends oe{operation(){return re.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}/${R(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 Ct extends oe{operation(){return re.PNHandshakeOperation}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${R(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 Nt extends se{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 re.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/${R(null!=s?s:[],",")}/uuid/${t}`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.join(",")}:{}}}class Pt extends se{constructor(e){super(),this.parameters=e}operation(){return re.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/${R(null!=s?s:[],",")}/uuid/${I(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 Mt extends se{constructor(e){super(),this.parameters=e}operation(){return re.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/${R(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 jt 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 re.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/${R(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 se{constructor(e){super(),this.parameters=e}operation(){return re.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/${I(t)}`}}class At extends se{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?re.PNGlobalHereNowOperation:re.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_channels,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/${R(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 It extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.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/${I(t)}`}get queryParameters(){const{start:e,end:t}=this.parameters;return Object.assign(Object.assign({},e?{start:e}:{}),t?{end:t}:{})}}class Rt extends se{constructor(e){super(),this.parameters=e}operation(){return re.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/${R(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 Ut extends se{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 re.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/${I(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(Ut.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 Tt;!function(e){e[e.Message=-1]="Message",e[e.Files=4]="Files"}(Tt||(Tt={}));class Ft extends se{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 re.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=Tt.Message);const s=this.processPayload(e,t),n={channel:e,timetoken:t.timetoken,message:s.payload,messageType:t.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/${R(t)}`}get queryParameters(){const{start:e,end:t,count:s,includeMessageType:n,includeMeta:r,includeUUID:i,stringifiedTimeToken:o}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({max:s},e?{start:e}:{}),t?{end:t}:{}),o?{string_message_token:"true"}:{}),void 0!==r&&r?{include_meta:"true"}:{}),i?{include_uuid:"true"}:{}),n?{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(Ft.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==Tt.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 xt extends se{constructor(e){super(),this.parameters=e}operation(){return re.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/${I(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 Dt extends se{constructor(e){super({method:H.POST}),this.parameters=e}operation(){return re.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 headers(){return{"Content-Type":"application/json"}}get path(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s}=this.parameters;return`/v1/message-actions/${e}/channel/${I(t)}/message/${s}`}get body(){return JSON.stringify(this.parameters.action)}}class Kt extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.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/${I(t)}/message/${n}/action/${s}`}}class qt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).storeInHistory)&&void 0!==t||(s.storeInHistory=true)}operation(){return re.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/${I(t)}/0/${I(this.prepareMessagePayload(o))}`}get queryParameters(){const{storeInHistory:e,ttl:t,meta:s}=this.parameters;return Object.assign(Object.assign({store:e?"1":"0"},t?{ttl:t}:{}),s&&"object"==typeof s?{meta:JSON.stringify(s)}:{})}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 se{constructor(e){super({method:H.LOCAL}),this.parameters=e}operation(){return re.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/${I(e)}/files/${t}/${s}`}}class $t extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.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/${I(s)}/files/${t}/${n}`}}class Lt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).limit)&&void 0!==t||(s.limit=100)}operation(){return re.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/${I(t)}/files`}get queryParameters(){const{limit:e,next:t}=this.parameters;return Object.assign({limit:e},t?{next:t}:{})}}class Bt extends se{constructor(e){super({method:H.POST}),this.parameters=e}operation(){return re.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/${I(t)}/generate-upload-url`}get body(){return JSON.stringify({name:this.parameters.name})}}class Ht extends se{constructor(e){super({method:H.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 re.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?Ht.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((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:re.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(re.PNPublishFileOperation))}))}))}generateFileUploadUrl(){return i(this,void 0,void 0,(function*(){const e=new Bt(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 Ht({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 Vt extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.PNAccessManagerRevokeToken}validate(){return this.parameters.keySet.secretKey?this.parameters.token?void 0:"token can't be empty":"Missing Secret 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},token:t}=this.parameters;return`/v3/pam/${e}/grant/${I(t)}`}}class Wt extends se{constructor(e){var t,s,n,r;super({method:H.POST}),this.parameters=e,null!==(t=(n=this.parameters).resources)&&void 0!==t||(n.resources={}),null!==(s=(r=this.parameters).patterns)&&void 0!==s||(r.patterns={})}operation(){return re.PNAccessManagerGrantToken}validate(){var e,t,s,n,r,i;const{keySet:{subscribeKey:o,publishKey:a,secretKey:c},resources:u,patterns:l}=this.parameters;if(!o)return"Missing Subscribe Key";if(!a)return"Missing Publish Key";if(!c)return"Missing Secret Key";if(!u&&!l)return"Missing either Resources or Patterns";if(this.isVspPermissions(this.parameters)&&("channels"in(null!==(e=this.parameters.resources)&&void 0!==e?e:{})||"uuids"in(null!==(t=this.parameters.resources)&&void 0!==t?t:{})||"groups"in(null!==(s=this.parameters.resources)&&void 0!==s?s:{})||"channels"in(null!==(n=this.parameters.patterns)&&void 0!==n?n:{})||"uuids"in(null!==(r=this.parameters.patterns)&&void 0!==r?r:{})||"groups"in(null!==(i=this.parameters.patterns)&&void 0!==i?i:{})))return"Cannot mix `users`, `spaces` and `authorizedUserId` with `uuids`, `channels`, `groups` and `authorized_uuid`";let h=!0;return[this.parameters.resources,this.parameters.patterns].forEach((e=>{Object.keys(null!=e?e:{}).forEach((t=>{var s;e&&h&&Object.keys(null!==(s=e[t])&&void 0!==s?s:{}).length>0&&(h=!1)}))})),h?"Missing values for either Resources or Patterns":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.data.token}))}get path(){return`/v3/pam/${this.parameters.keySet.subscribeKey}/grant`}get body(){const{ttl:e,meta:t}=this.parameters,s=Object.assign({},e||0===e?{ttl:e}:{}),n=this.isVspPermissions(this.parameters)?this.parameters.authorizedUserId:this.parameters.authorized_uuid,r={},i={},o={},a=(e,t,s,n)=>{n[s]||(n[s]={}),n[s][e]=t},{resources:c,patterns:u}=this.parameters;return[c,u].forEach(((e,t)=>{var s,n,r,c,u;const l=0===t?i:o;let h={},d={},p={};l.channels||(l.channels={}),l.groups||(l.groups={}),l.uuids||(l.uuids={}),l.users||(l.users={}),l.spaces||(l.spaces={}),e&&("spaces"in e||"users"in e?(h=null!==(s=e.spaces)&&void 0!==s?s:{},p=null!==(n=e.users)&&void 0!==n?n:{}):("channels"in e||"uuids"in e||"groups"in e)&&(h=null!==(r=e.channels)&&void 0!==r?r:{},d=null!==(c=e.groups)&&void 0!==c?c:{},p=null!==(u=e.uuids)&&void 0!==u?u:{})),Object.keys(h).forEach((e=>a(e,this.extractPermissions(h[e]),"channels",l))),Object.keys(d).forEach((e=>a(e,this.extractPermissions(d[e]),"groups",l))),Object.keys(p).forEach((e=>a(e,this.extractPermissions(p[e]),"uuids",l)))})),n&&(r.uuid=`${n}`),r.resources=i,r.patterns=o,r.meta=null!=t?t:{},s.permissions=r,JSON.stringify(s)}extractPermissions(e){let t=0;return"join"in e&&e.join&&(t|=128),"update"in e&&e.update&&(t|=64),"get"in e&&e.get&&(t|=32),"delete"in e&&e.delete&&(t|=8),"manage"in e&&e.manage&&(t|=4),"write"in e&&e.write&&(t|=2),"read"in e&&e.read&&(t|=1),t}isVspPermissions(e){var t,s,n,r;return"authorizedUserId"in e||"spaces"in(null!==(t=e.resources)&&void 0!==t?t:{})||"users"in(null!==(s=e.resources)&&void 0!==s?s:{})||"spaces"in(null!==(n=e.patterns)&&void 0!==n?n:{})||"users"in(null!==(r=e.patterns)&&void 0!==r?r:{})}}class Jt extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f,m,b,v,w;super(),this.parameters=e,null!==(t=(h=this.parameters).channels)&&void 0!==t||(h.channels=[]),null!==(s=(d=this.parameters).channelGroups)&&void 0!==s||(d.channelGroups=[]),null!==(n=(p=this.parameters).uuids)&&void 0!==n||(p.uuids=[]),null!==(r=(g=this.parameters).read)&&void 0!==r||(g.read=false),null!==(i=(y=this.parameters).write)&&void 0!==i||(y.write=false),null!==(o=(f=this.parameters).delete)&&void 0!==o||(f.delete=false),null!==(a=(m=this.parameters).get)&&void 0!==a||(m.get=false),null!==(c=(b=this.parameters).update)&&void 0!==c||(b.update=false),null!==(u=(v=this.parameters).manage)&&void 0!==u||(v.manage=false),null!==(l=(w=this.parameters).join)&&void 0!==l||(w.join=false)}operation(){return re.PNAccessManagerGrant}validate(){const{keySet:{subscribeKey:e,publishKey:t,secretKey:s},uuids:n=[],channels:r=[],channelGroups:i=[],authKeys:o=[]}=this.parameters;return e?t?s?0!==n.length&&0===o.length?"authKeys are required for grant request on uuids":!n.length||0===r.length&&0===i.length?void 0:"Both channel/channel group and uuid cannot be used in the same request":"Missing Secret Key":"Missing Publish Key":"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}))}get path(){return`/v2/auth/grant/sub-key/${this.parameters.keySet.subscribeKey}`}get queryParameters(){const{channels:e,channelGroups:t,authKeys:s,uuids:n,read:r,write:i,manage:o,delete:a,get:c,join:u,update:l,ttl:h}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},e&&(null==e?void 0:e.length)>0?{channel:e.join(",")}:{}),t&&(null==t?void 0:t.length)>0?{"channel-group":t.join(",")}:{}),s&&(null==s?void 0:s.length)>0?{auth:s.join(",")}:{}),n&&(null==n?void 0:n.length)>0?{"target-uuid":n.join(",")}:{}),{r:r?"1":"0",w:i?"1":"0",m:o?"1":"0",d:a?"1":"0",g:c?"1":"0",j:u?"1":"0",u:l?"1":"0"}),h||0===h?{ttl:h}:{})}}const Qt=[];class Yt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).authKeys)&&void 0!==t||(s.authKeys=Qt)}operation(){return re.PNAccessManagerAudit}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}))}get path(){return`/v2/auth/audit/sub-key/${this.parameters.keySet.subscribeKey}`}get queryParameters(){const{channel:e,channelGroup:t,authKeys:s}=this.parameters;return Object.assign(Object.assign(Object.assign({},e?{channel:e}:{}),t?{"channel-group":t}:{}),s&&s.length?{auth:s.join(",")}:{})}}class Xt{subscribe(){var e,t;this.pubnub.subscribe(Object.assign({channels:this.channelNames,channelGroups:this.groupNames},(null===(t=null===(e=this.options)||void 0===e?void 0:e.cursor)||void 0===t?void 0:t.timetoken)&&{timetoken:this.options.cursor.timetoken}))}unsubscribe(){this.pubnub.unsubscribe({channels:this.channelNames.filter((e=>!e.endsWith("-pnpres"))),channelGroups:this.groupNames.filter((e=>!e.endsWith("-pnpres")))})}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.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}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 Zt extends Xt{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.filter((e=>!e.endsWith("-pnpres"))).forEach((e=>{const t=this.pubnub.channel(e).subscription(this.options);this.channelNames=[...this.channelNames,...t.channels],this.subscriptionList.push(t)})),t.filter((e=>!e.endsWith("-pnpres"))).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.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}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 es extends Xt{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.filter((e=>!e.endsWith("-pnpres"))),this.groupNames.filter((e=>!e.endsWith("-pnpres"))))}addSubscription(e){return new Zt({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 ts{constructor(e,t,s){this.id=e,this.eventEmitter=t,this.pubnub=s}subscription(e){return new es({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class ss{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){return new es({channels:[],channelGroups:(null==e?void 0:e.receivePresenceEvents)?[this.name,`${this.name}-pnpres`]:[this.name],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class ns{constructor(e,t,s){this.id=e,this.eventEmitter=t,this.pubnub=s}subscription(e){return new es({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class rs{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){return new es({channels:(null==e?void 0:e.receivePresenceEvents)?[this.name,`${this.name}-pnpres`]:[this.name],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class is extends se{constructor(e){super(),this.parameters=e}operation(){return re.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/${I(t)}`}get queryParameters(){return{remove:this.parameters.channels.join(",")}}}class os extends se{constructor(e){super(),this.parameters=e}operation(){return re.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/${I(t)}`}get queryParameters(){return{add:this.parameters.channels.join(",")}}}class as extends se{constructor(e){super(),this.parameters=e}operation(){return re.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/${I(t)}`}}class cs extends se{constructor(e){super(),this.parameters=e}operation(){return re.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/${I(t)}/remove`}}class us extends se{constructor(e){super(),this.parameters=e}operation(){return re.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 ls{constructor(e,t){this.keySet=e,this.sendRequest=t}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)}))}listGroups(e){return i(this,void 0,void 0,(function*(){const t=new us({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 os(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 is(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 cs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class hs extends se{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 ds extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove"}))}operation(){return re.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 ps extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"list"}))}operation(){return re.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 gs extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"add"}))}operation(){return re.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 ys extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove-device"}))}operation(){return re.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 fs{constructor(e,t){this.keySet=e,this.sendRequest=t}listChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new ps(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 gs(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 ds(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 ys(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class ms extends se{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 re.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,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));return 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 bs extends se{constructor(e){super({method:H.DELETE}),this.parameters=e}operation(){return re.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/${I(t)}`}}class vs extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(l=e.include).customFields)&&void 0!==s||(l.customFields=false),null!==(n=(h=e.include).totalCount)&&void 0!==n||(h.totalCount=false),null!==(r=(d=e.include).statusField)&&void 0!==r||(d.statusField=false),null!==(i=(p=e.include).channelFields)&&void 0!==i||(p.channelFields=false),null!==(o=(g=e.include).customChannelFields)&&void 0!==o||(g.customChannelFields=false),null!==(a=(y=e.include).channelStatusField)&&void 0!==a||(y.channelStatusField=false),null!==(c=(f=e.include).channelTypeField)&&void 0!==c||(f.channelTypeField=false),null!==(u=e.limit)&&void 0!==u||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.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/${I(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=[];return e.statusField&&o.push("status"),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 ws extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(a=e.include).customFields)&&void 0!==s||(a.customFields=false),null!==(n=(c=e.include).totalCount)&&void 0!==n||(c.totalCount=false),null!==(r=(u=e.include).channelFields)&&void 0!==r||(u.channelFields=false),null!==(i=(l=e.include).customChannelFields)&&void 0!==i||(l.customChannelFields=false),null!==(o=e.limit)&&void 0!==o||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.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/${I(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=["channel.status","channel.type","status"];return e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),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,custom:e.custom}))})}}class Ss extends se{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 re.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,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));return 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 ks extends se{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 re.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/${I(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}}class Es extends se{constructor(e){var t,s,n;super({method:H.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 re.PNSetChannelMetadataOperation}validate(){return this.parameters.channel?this.parameters.data?void 0:"Data 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/${I(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Os extends se{constructor(e){super({method:H.DELETE}),this.parameters=e,this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return re.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/${I(t)}`}}class Cs extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(l=e.include).customFields)&&void 0!==s||(l.customFields=false),null!==(n=(h=e.include).totalCount)&&void 0!==n||(h.totalCount=false),null!==(r=(d=e.include).statusField)&&void 0!==r||(d.statusField=false),null!==(i=(p=e.include).UUIDFields)&&void 0!==i||(p.UUIDFields=false),null!==(o=(g=e.include).customUUIDFields)&&void 0!==o||(g.customUUIDFields=false),null!==(a=(y=e.include).UUIDStatusField)&&void 0!==a||(y.UUIDStatusField=false),null!==(c=(f=e.include).UUIDTypeField)&&void 0!==c||(f.UUIDTypeField=false),null!==(u=e.limit)&&void 0!==u||(e.limit=100)}operation(){return re.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/${I(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=[];return e.statusField&&o.push("status"),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 Ns extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l;super({method:H.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(a=e.include).customFields)&&void 0!==s||(a.customFields=false),null!==(n=(c=e.include).totalCount)&&void 0!==n||(c.totalCount=false),null!==(r=(u=e.include).UUIDFields)&&void 0!==r||(u.UUIDFields=false),null!==(i=(l=e.include).customUUIDFields)&&void 0!==i||(l.customUUIDFields=false),null!==(o=e.limit)&&void 0!==o||(e.limit=100)}operation(){return re.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/${I(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters,i=Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),o=["uuid.status","uuid.type","type"];return e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),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,custom:e.custom}))})}}class Ps extends se{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 re.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/${I(t)}`}get queryParameters(){const{include:e}=this.parameters;return{include:["status","type",...e.customFields?["custom"]:[]].join(",")}}}class Ms extends se{constructor(e){var t,s,n;super({method:H.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 re.PNSetUUIDMetadataOperation}validate(){return this.parameters.uuid?this.parameters.data?void 0:"Data 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/${I(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class js{constructor(e,t){this.configuration=e,this.sendRequest=t,this.keySet=e.keySet}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 Ss(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 Ps(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 Ms(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 Os(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 ms(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 ks(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 Es(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 bs(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 Cs(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 Ns(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 Ns(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 vs(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 ws(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 ws(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:(e.userId,{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 _s extends se{constructor(){super()}operation(){return re.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 As extends se{constructor(e){super(),this.parameters=e}operation(){return re.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/${I(t)}/files/${s}/${n}`}}class Is{static notificationPayload(e,t){return new te(e,t)}static generateUUID(){return G.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 js(this._configuration,this.sendRequest.bind(this)),this._channelGroups=new ls(this._configuration.keySet,this.sendRequest.bind(this)),this._push=new fs(this._configuration.keySet,this.sendRequest.bind(this)),this.listenerManager=new W,this.eventEmitter=new ce(this.listenerManager),this._configuration.enableEventEngine){let e=this._configuration.getHeartbeatInterval();this.presenceState={},e&&(this.presenceEventEngine=new $e({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 St({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 rs(e,this.eventEmitter,this)}channelGroup(e){return new ss(e,this.eventEmitter,this)}channelMetadata(e){return new ts(e,this.eventEmitter,this)}userMetadata(e){return new ns(e,this.eventEmitter,this)}subscriptionSet(e){return new Zt(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();n.formData&&n.formData.length>0?n.timeout=300:e.operation()===re.PNSubscribeOperation?n.timeout=this._configuration.getSubscribeTimeout():n.timeout=this._configuration.getTransactionTimeout();const r={error:!1,operation:e.operation(),category:h.PNAcknowledgmentCategory,statusCode:0},[i,o]=this.transport.makeSendable(n);return e.cancellationController=o||null,i.then((t=>{if(r.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(Is.decoder.decode(t.body));"object"==typeof e&&"error"in e&&e.error&&"object"==typeof e.error&&(r.errorData=e.error)}}return e.parse(t)})).then((e=>t?t(r,e):e)).catch((s=>{const n=s instanceof _?s:_.create(s);if(t)return t(n.toStatus(e.operation()),null);throw n.toPubNubError(e.operation(),"REST API request processing error, check status for details")}))}))}destroy(e){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 kt(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 Et(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():[]}subscribe(e){this.subscriptionManager?this.subscriptionManager.subscribe(e):this.eventEngine&&this.eventEngine.subscribe(e)}makeSubscribe(e,t){const s=new ae(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 jt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),t)}unsubscribeAll(){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 Ct(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 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)))}))}getMessageActions(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)}))}addMessageAction(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)}))}removeMessageAction(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)}))}fetchMessages(e,t){return i(this,void 0,void 0,(function*(){const s=new Ft(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 It(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 Rt(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 Ut(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 Nt(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 Mt(Object.assign(Object.assign({},e),{keySet:r,heartbeat:o})):new Pt(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 Mt(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*(){const s=new Wt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}revokeToken(e,t){return i(this,void 0,void 0,(function*(){const s=new Vt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}get token(){return this.tokenManager.getToken()}getToken(){return this.token}set token(e){this.tokenManager.setToken(e)}setToken(e){this.token=e}parseToken(e){return this.tokenManager.parseToken(e)}grant(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)}))}audit(e,t){return i(this,void 0,void 0,(function*(){const s=new Yt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}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 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})),n={error:!1,operation:re.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 Lt(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}=${I(t)}`)).join("&"):`${e}=${I(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 As(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 $t(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 _s;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)}))}}Is.decoder=new TextDecoder,Is.OPERATIONS=re,Is.CATEGORIES=h,Is.ExponentialRetryPolicy=Le.ExponentialRetryPolicy,Is.LinearRetryPolicy=Le.LinearRetryPolicy;class Rs{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 Us extends Is{constructor(e){var t;const s=D(e),r=Object.assign(Object.assign({},s),{sdkFamily:"Web",PubNubFile:a}),i=$(r,(e=>{if(e.cipherKey)return new P({default:new N(Object.assign({},e)),cryptors:[new S({cipherKey:e.cipherKey})]})})),o=new B(new Rs((e=>x(n.decode(e))),c));let u;(i.getCipherKey()||i.secretKey)&&(u=new E({secretKey:i.secretKey,cipherKey:i.getCipherKey(),useRandomIVs:i.getUseRandomIVs(),customEncrypt:i.getCustomEncrypt(),customDecrypt:i.getCustomDecrypt()}));let l=new F(i.keepAlive,i.logVerbosity);s.subscriptionWorkerUrl&&(l=new A({clientIdentifier:i._instanceId,subscriptionKey:i.subscribeKey,userId:i.getUserId(),workerUrl:s.subscriptionWorkerUrl,sdkVersion:i.getVersion(),logVerbosity:i.logVerbosity,workerLogVerbosity:r.subscriptionWorkerLogVerbosity,transport:l}));super({configuration:i,transport:new V({clientConfiguration:i,tokenManager:o,transport:l}),cryptography:new C,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 Us.CryptoModule=P,Us})); diff --git a/dist/web/pubnub.worker.js b/dist/web/pubnub.worker.js index 31a3ef3ac..b033cf48e 100644 --- a/dist/web/pubnub.worker.js +++ b/dist/web/pubnub.worker.js @@ -106,11 +106,27 @@ * Service worker provides support for PubNub subscription feature to give better user experience across * multiple opened pages. */ + /** + * How often PING request should be sent to the PubNub clients. + */ + const clientPingRequestInterval = 5000; // region State /** * Service `ArrayBuffer` response decoder. */ const decoder = new TextDecoder(); + /** + * Whether `Subscription` worker should print debug information to the console or not. + */ + let logVerbosity = false; + /** + * PubNub clients active ping interval. + */ + let pingInterval; + /** + * Unique shared worker instance identifier. + */ + const sharedWorkerIdentifier = uuidGenerator.createUUID(); /** * Map of identifiers, scheduled by the Service Worker, to their abort controllers. * @@ -132,11 +148,11 @@ */ const presenceState = {}; /** - * Per-subscription key map of client identifiers to the Service Worker {@link Client} identifier. + * Per-subscription key map of client identifiers to the Shared Worker {@link MessagePort}. * - * Service Worker {@link Client} represent pages at which PubNub clients registered Service Workers. + * Shared Worker {@link MessagePort} represent specific PubNub client which connected to the Shared Worker. */ - const serviceWorkerClients = {}; + const sharedWorkerClients = {}; /** * List of ongoing subscription requests. * @@ -149,33 +165,45 @@ // -------------------------------------------------------- // region Event Handlers /** - * Listen for Service Worker activation. - */ - self.addEventListener('activate', (event) => { - event.waitUntil(self.clients.claim()); - }); - /** - * Listen for events from the client. + * Handle new PubNub client 'connection'. + * + * Echo listeners to let `SharedWorker` users that it is ready. + * + * @param event - Remote `SharedWorker` client connection event. */ - self.addEventListener('message', (event) => { - // Ignoring requests sent from other service workers. - if (!validateEventPayload(event)) - return; - const data = event.data; - if (data.type === 'send-request') { - if (data.request.path.startsWith('/v2/subscribe')) { - registerClientIfRequired(event); - handleSendSubscribeRequestEvent(data); - } - else { - if (!pubNubClients[data.clientIdentifier]) - registerClientIfRequired(event); - handleSendLeaveRequestEvent(event); - } - } - else if (data.type === 'cancel-request') - handleCancelRequestEvent(data); - }); + self.onconnect = (event) => { + consoleLog('New PubNub Client connected to the Subscription Shared Worker.'); + event.ports.forEach((receiver) => { + receiver.start(); + receiver.onmessage = (event) => { + // Ignoring unknown event payloads. + if (!validateEventPayload(event)) + return; + const data = event.data; + if (data.type === 'client-register') { + if (!logVerbosity && data.workerLogVerbosity) + logVerbosity = true; + // Appending information about messaging port for responses. + data.port = receiver; + registerClientIfRequired(data); + consoleLog(`Client '${data.clientIdentifier}' registered with '${sharedWorkerIdentifier}' shared worker`); + } + else if (data.type === 'client-pong') + handleClientPong(data); + else if (data.type === 'send-request') { + if (data.request.path.startsWith('/v2/subscribe')) { + updateClientStateIfRequired(data); + handleSendSubscribeRequestEvent(data); + } + else + handleSendLeaveRequestEvent(data); + } + else if (data.type === 'cancel-request') + handleCancelRequestEvent(data); + }; + receiver.postMessage({ type: 'shared-worker-connected' }); + }); + }; /** * Handle client request to send subscription request. * @@ -187,7 +215,7 @@ if (client) notifyRequestProcessing('start', [client], new Date().toISOString()); if (typeof requestOrId === 'string') { - if (client) { + if (client && client.subscription) { // Updating client timetoken information. client.subscription.previousTimetoken = client.subscription.timetoken; client.subscription.timetoken = serviceRequests[requestOrId].timetoken; @@ -208,14 +236,14 @@ // Clean up scheduled request and client references to it. markRequestCompleted(clients, requestOrId.identifier); }); + consoleLog(`'${Object.keys(serviceRequests).length}' subscription request currently active.`); }; /** * Handle client request to leave request. * - * @param event - Leave event details. + * @param data - Leave event details. */ - const handleSendLeaveRequestEvent = (event) => { - const data = event.data; + const handleSendLeaveRequestEvent = (data) => { const request = leaveTransportRequestFromEvent(data); const client = pubNubClients[data.clientIdentifier]; if (!client) @@ -228,10 +256,7 @@ result.url = `${data.request.origin}${data.request.path}`; result.clientIdentifier = data.clientIdentifier; result.identifier = data.request.identifier; - publishClientEvent(event.source.id, result).then((sent) => { - if (sent) - invalidateClient(client.subscriptionKey, client.clientIdentifier, client.userId); - }); + publishClientEvent(client, result); return; } sendRequest(request, () => [client], (clients, response) => { @@ -241,6 +266,7 @@ // Notify each PubNub client which awaited for response. notifyRequestProcessingResult(clients, null, data.request, requestProcessingError(error)); }); + consoleLog(`Started leave request.`, client); }; /** * Handle cancel request event. @@ -251,7 +277,9 @@ */ const handleCancelRequestEvent = (event) => { const client = pubNubClients[event.clientIdentifier]; - const serviceRequestId = client ? client.subscription.serviceRequestId : undefined; + if (!client || !client.subscription) + return; + const serviceRequestId = client.subscription.serviceRequestId; if (!client || !serviceRequestId) return; // Unset awaited requests. @@ -335,7 +363,7 @@ * @returns List of PubNub client state objects for Service Worker. */ const clientsForRequest = (identifier) => { - return Object.values(pubNubClients).filter((client) => client !== undefined && client.subscription.serviceRequestId === identifier); + return Object.values(pubNubClients).filter((client) => client !== undefined && client.subscription !== undefined && client.subscription.serviceRequestId === identifier); }; /** * Clean up PubNub client states from ongoing request. @@ -348,8 +376,10 @@ const markRequestCompleted = (clients, requestId) => { delete serviceRequests[requestId]; clients.forEach((client) => { - delete client.subscription.request; - delete client.subscription.serviceRequestId; + if (client.subscription) { + delete client.subscription.request; + delete client.subscription.serviceRequestId; + } }); }; /** @@ -390,7 +420,8 @@ const subscribeTransportRequestFromEvent = (event) => { var _a, _b, _c, _d; const client = pubNubClients[event.clientIdentifier]; - const clients = clientsForSendSubscribeRequestEvent(client.subscription.previousTimetoken, event); + const subscription = client.subscription; + const clients = clientsForSendSubscribeRequestEvent(subscription.previousTimetoken, event); const serviceRequestId = uuidGenerator.createUUID(); const request = Object.assign({}, event.request); if (clients.length > 1) { @@ -400,10 +431,10 @@ return activeRequestId; const state = ((_a = presenceState[client.subscriptionKey]) !== null && _a !== void 0 ? _a : {})[client.userId]; const aggregatedState = {}; - const channelGroups = new Set(client.subscription.channelGroups); - const channels = new Set(client.subscription.channels); - if (state && client.subscription.objectsWithState.length) { - client.subscription.objectsWithState.forEach((name) => { + const channelGroups = new Set(subscription.channelGroups); + const channels = new Set(subscription.channels); + if (state && subscription.objectsWithState.length) { + subscription.objectsWithState.forEach((name) => { const objectState = state[name]; if (objectState) aggregatedState[name] = objectState; @@ -412,7 +443,7 @@ for (const client of clients) { const { subscription } = client; // Skip clients which already have active subscription request. - if (subscription.serviceRequestId) + if (!subscription || !subscription.serviceRequestId) continue; subscription.channelGroups.forEach(channelGroups.add, channelGroups); subscription.channels.forEach(channels.add, channels); @@ -452,12 +483,21 @@ serviceRequests[serviceRequestId] = { requestId: serviceRequestId, timetoken: (_d = request.queryParameters.tt) !== null && _d !== void 0 ? _d : '0', - channelGroups: client.subscription.channelGroups, - channels: client.subscription.channels, + channelGroups: subscription.channelGroups, + channels: subscription.channels, }; } - client.subscription.serviceRequestId = serviceRequestId; + subscription.serviceRequestId = serviceRequestId; request.identifier = serviceRequestId; + if (logVerbosity) { + const clientIds = clients + .reduce((identifiers, { clientIdentifier }) => { + identifiers.push(clientIdentifier); + return identifiers; + }, []) + .join(','); + consoleDir(serviceRequests[serviceRequestId], `Started aggregated request for clients: ${clientIds}`); + } return request; }; /** @@ -476,7 +516,7 @@ let channelGroups = channelGroupsFromRequest(event.request); let channels = channelsFromRequest(event.request); const request = Object.assign({}, event.request); - if (client) { + if (client && client.subscription) { const { subscription } = client; if (channels.length) subscription.channels = subscription.channels.filter((channel) => !channels.includes(channel)); @@ -486,15 +526,28 @@ } // Filter out channels and groups which is still in use by the other PubNub client instances. for (const client of clients) { + const subscription = client.subscription; + if (subscription === undefined) + continue; if (client.clientIdentifier === event.clientIdentifier) continue; if (channels.length) - channels = channels.filter((channel) => !client.subscription.channels.includes(channel)); + channels = channels.filter((channel) => !subscription.channels.includes(channel)); if (channelGroups.length) - channelGroups = channelGroups.filter((group) => !client.subscription.channelGroups.includes(group)); + channelGroups = channelGroups.filter((group) => !subscription.channelGroups.includes(group)); } - if (channels.length === 0 && channelGroups.length === 0) + if (channels.length === 0 && channelGroups.length === 0) { + if (logVerbosity && client) { + const clientIds = clients + .reduce((identifiers, { clientIdentifier }) => { + identifiers.push(clientIdentifier); + return identifiers; + }, []) + .join(','); + consoleLog(`Specified channels and groups still in use by other clients: ${clientIds}. Ignoring leave request.`, client); + } return undefined; + } // Update request channels list (if required). if (channels.length) { const pathComponents = request.path.split('/'); @@ -507,18 +560,22 @@ return request; }; /** - * Send event to all service worker clients. + * Send event to the specific PubNub client. * - * @param identifier - Service Worker receiving {@link Client} identifier. - * @param event - Service worker event object. + * @param client - State for the client which should receive {@link event}. + * @param event - Subscription worker event object. */ - const publishClientEvent = (identifier, event) => { - return self.clients.get(identifier).then((client) => { - if (!client) - return false; - client.postMessage(event); + const publishClientEvent = (client, event) => { + var _a; + const receiver = ((_a = sharedWorkerClients[client.subscriptionKey]) !== null && _a !== void 0 ? _a : {})[client.clientIdentifier]; + if (!receiver) + return false; + try { + receiver.postMessage(event); return true; - }); + } + catch (error) { } + return false; }; /** * Send request processing update. @@ -535,7 +592,7 @@ var _a; if (clients.length === 0) return; - const clientIds = (_a = serviceWorkerClients[clients[0].subscriptionKey]) !== null && _a !== void 0 ? _a : {}; + const clientIds = (_a = sharedWorkerClients[clients[0].subscriptionKey]) !== null && _a !== void 0 ? _a : {}; let event; if (type === 'start') { event = { @@ -564,17 +621,17 @@ duration: duration, }; } - clients.forEach((client) => { + for (const client of clients) { + if (client.subscription === undefined) + continue; const serviceWorkerClientId = clientIds[client.clientIdentifier]; const { request: clientRequest } = client.subscription; const decidedRequest = clientRequest !== null && clientRequest !== void 0 ? clientRequest : request; if (client.logVerbosity && serviceWorkerClientId && decidedRequest) { - publishClientEvent(serviceWorkerClientId, Object.assign(Object.assign({}, event), { clientIdentifier: client.clientIdentifier, url: `${decidedRequest.origin}${decidedRequest.path}`, query: decidedRequest.queryParameters })).then((sent) => { - if (sent) - invalidateClient(client.subscriptionKey, client.clientIdentifier, client.userId); - }); + const payload = Object.assign(Object.assign({}, event), { clientIdentifier: client.clientIdentifier, url: `${decidedRequest.origin}${decidedRequest.path}`, query: decidedRequest.queryParameters }); + publishClientEvent(client, payload); } - }); + } }; /** * Send request processing result event. @@ -590,7 +647,7 @@ return; if (!result && !response) return; - const clientIds = (_a = serviceWorkerClients[clients[0].subscriptionKey]) !== null && _a !== void 0 ? _a : {}; + const clientIds = (_a = sharedWorkerClients[clients[0].subscriptionKey]) !== null && _a !== void 0 ? _a : {}; if (!result && response) { result = response[0].status >= 400 @@ -598,17 +655,17 @@ requestProcessingError(undefined, response) : requestProcessingSuccess(response); } - clients.forEach((client) => { + for (const client of clients) { + if (client.subscription === undefined) + continue; const serviceWorkerClientId = clientIds[client.clientIdentifier]; const { request: clientRequest } = client.subscription; const decidedRequest = clientRequest !== null && clientRequest !== void 0 ? clientRequest : request; if (serviceWorkerClientId && decidedRequest) { - publishClientEvent(serviceWorkerClientId, Object.assign(Object.assign({}, result), { clientIdentifier: client.clientIdentifier, identifier: decidedRequest.identifier, url: `${decidedRequest.origin}${decidedRequest.path}` })).then((sent) => { - if (sent) - invalidateClient(client.subscriptionKey, client.clientIdentifier, client.userId); - }); + const payload = Object.assign(Object.assign({}, result), { clientIdentifier: client.clientIdentifier, identifier: decidedRequest.identifier, url: `${decidedRequest.origin}${decidedRequest.path}` }); + publishClientEvent(client, payload); } - }); + } }; /** * Create processing success event from service response. @@ -696,82 +753,111 @@ * @param event - Base information about PubNub client instance and Service Worker {@link Client}. */ const registerClientIfRequired = (event) => { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u; - var _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5; - const information = event.data; - const { clientIdentifier } = information; - const query = information.request.queryParameters; - let client = pubNubClients[clientIdentifier]; - if (!client) { - const isPresenceLeave = !information.request.path.startsWith('/v2/subscribe'); - const channelGroupQuery = !isPresenceLeave ? ((_a = query['channel-group']) !== null && _a !== void 0 ? _a : '') : ''; - const state = !isPresenceLeave ? ((_b = query.state) !== null && _b !== void 0 ? _b : '') : ''; - client = pubNubClients[clientIdentifier] = { - clientIdentifier, - subscriptionKey: information.subscriptionKey, - userId: query.uuid, - authKey: ((_c = query.auth) !== null && _c !== void 0 ? _c : ''), - logVerbosity: information.logVerbosity, - subscription: { - path: !isPresenceLeave ? information.request.path : '', - channelGroupQuery: !isPresenceLeave ? channelGroupQuery : '', - channels: !isPresenceLeave ? channelsFromRequest(information.request) : [], - channelGroups: !isPresenceLeave ? channelGroupsFromRequest(information.request) : [], - previousTimetoken: !isPresenceLeave ? ((_d = query.tt) !== null && _d !== void 0 ? _d : '0') : '0', - timetoken: !isPresenceLeave ? ((_e = query.tt) !== null && _e !== void 0 ? _e : '0') : '0', - request: !isPresenceLeave ? information.request : undefined, - objectsWithState: [], - filterExpression: !isPresenceLeave ? ((_f = query['filter-expr']) !== null && _f !== void 0 ? _f : '') : undefined, - }, + var _a, _b; + var _c, _d; + const { clientIdentifier } = event; + if (pubNubClients[clientIdentifier]) + return; + const client = (pubNubClients[clientIdentifier] = { + clientIdentifier, + subscriptionKey: event.subscriptionKey, + userId: event.userId, + logVerbosity: event.logVerbosity, + }); + // Map registered PubNub client to its subscription key. + const clientsBySubscriptionKey = ((_a = pubNubClientsBySubscriptionKey[_c = event.subscriptionKey]) !== null && _a !== void 0 ? _a : (pubNubClientsBySubscriptionKey[_c] = [])); + if (clientsBySubscriptionKey.every((entry) => entry.clientIdentifier !== clientIdentifier)) + clientsBySubscriptionKey.push(client); + // Binding PubNub client to the MessagePort (receiver). + ((_b = sharedWorkerClients[_d = event.subscriptionKey]) !== null && _b !== void 0 ? _b : (sharedWorkerClients[_d] = {}))[clientIdentifier] = event.port; + consoleLog(`Registered PubNub client with '${clientIdentifier}' identifier. ` + + `'${Object.keys(pubNubClients).length}' clients currently active.`); + if (!pingInterval && Object.keys(pubNubClients).length > 0) { + consoleLog(`Setup PubNub client ping event ${clientPingRequestInterval / 1000} seconds`); + pingInterval = setInterval(() => pingClients(), clientPingRequestInterval); + } + }; + /** + * Update information about previously registered client. + * + * Use information from request to populate list of channels and other useful information. + * + * @param event - Send request. + */ + const updateClientStateIfRequired = (event) => { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; + var _m, _o, _p, _q, _r, _s, _t, _u, _v; + const query = event.request.queryParameters; + const { clientIdentifier } = event; + const client = pubNubClients[clientIdentifier]; + // This should never happen. + if (!client) + return; + const channelGroupQuery = ((_a = query['channel-group']) !== null && _a !== void 0 ? _a : ''); + const state = ((_b = query.state) !== null && _b !== void 0 ? _b : ''); + let subscription = client.subscription; + if (!subscription) { + subscription = { + path: '', + channelGroupQuery: '', + channels: [], + channelGroups: [], + previousTimetoken: '0', + timetoken: '0', + objectsWithState: [], }; - if (!isPresenceLeave && state.length > 0) { + if (state.length > 0) { const parsedState = JSON.parse(state); - const userState = ((_h = (_w = ((_g = presenceState[_v = client.subscriptionKey]) !== null && _g !== void 0 ? _g : (presenceState[_v] = {})))[_x = client.userId]) !== null && _h !== void 0 ? _h : (_w[_x] = {})); + const userState = ((_d = (_o = ((_c = presenceState[_m = client.subscriptionKey]) !== null && _c !== void 0 ? _c : (presenceState[_m] = {})))[_p = client.userId]) !== null && _d !== void 0 ? _d : (_o[_p] = {})); Object.entries(parsedState).forEach(([objectName, value]) => (userState[objectName] = value)); - client.subscription.objectsWithState = Object.keys(parsedState); + subscription.objectsWithState = Object.keys(parsedState); } - // Map registered PubNub client to its subscription key. - const clientsBySubscriptionKey = ((_j = pubNubClientsBySubscriptionKey[_y = information.subscriptionKey]) !== null && _j !== void 0 ? _j : (pubNubClientsBySubscriptionKey[_y] = [])); - if (clientsBySubscriptionKey.every((entry) => entry.clientIdentifier !== clientIdentifier)) - clientsBySubscriptionKey.push(client); - // Binding PubNub client to the page (Service Worker Client). - ((_k = serviceWorkerClients[_z = information.subscriptionKey]) !== null && _k !== void 0 ? _k : (serviceWorkerClients[_z] = {}))[clientIdentifier] = event.source.id; + client.subscription = subscription; } else { - const channelGroupQuery = ((_l = query['channel-group']) !== null && _l !== void 0 ? _l : ''); - const state = ((_m = query.state) !== null && _m !== void 0 ? _m : ''); - client.subscription.filterExpression = ((_o = query['filter-expr']) !== null && _o !== void 0 ? _o : ''); - client.subscription.previousTimetoken = client.subscription.timetoken; - client.subscription.timetoken = ((_p = query.tt) !== null && _p !== void 0 ? _p : '0'); - client.subscription.request = information.request; - client.authKey = ((_q = query.auth) !== null && _q !== void 0 ? _q : ''); - client.userId = query.uuid; - if (client.subscription.path !== information.request.path) { - client.subscription.path = information.request.path; - client.subscription.channels = channelsFromRequest(information.request); - } - if (client.subscription.channelGroupQuery !== channelGroupQuery) { - client.subscription.channelGroupQuery = channelGroupQuery; - client.subscription.channelGroups = channelGroupsFromRequest(information.request); - } + subscription.previousTimetoken = subscription.timetoken; if (state.length > 0) { const parsedState = JSON.parse(state); - const userState = ((_s = (_1 = ((_r = presenceState[_0 = client.subscriptionKey]) !== null && _r !== void 0 ? _r : (presenceState[_0] = {})))[_2 = client.userId]) !== null && _s !== void 0 ? _s : (_1[_2] = {})); + const userState = ((_f = (_r = ((_e = presenceState[_q = client.subscriptionKey]) !== null && _e !== void 0 ? _e : (presenceState[_q] = {})))[_s = client.userId]) !== null && _f !== void 0 ? _f : (_r[_s] = {})); Object.entries(parsedState).forEach(([objectName, value]) => (userState[objectName] = value)); // Clean up state for objects where presence state has been reset. - for (const objectName of client.subscription.objectsWithState) + for (const objectName of subscription.objectsWithState) if (!parsedState[objectName]) delete userState[objectName]; - client.subscription.objectsWithState = Object.keys(parsedState); + subscription.objectsWithState = Object.keys(parsedState); } // Handle potential presence state reset. - else if (client.subscription.objectsWithState.length) { - const userState = ((_u = (_4 = ((_t = presenceState[_3 = client.subscriptionKey]) !== null && _t !== void 0 ? _t : (presenceState[_3] = {})))[_5 = client.userId]) !== null && _u !== void 0 ? _u : (_4[_5] = {})); - for (const objectName of client.subscription.objectsWithState) + else if (subscription.objectsWithState.length) { + const userState = ((_h = (_u = ((_g = presenceState[_t = client.subscriptionKey]) !== null && _g !== void 0 ? _g : (presenceState[_t] = {})))[_v = client.userId]) !== null && _h !== void 0 ? _h : (_u[_v] = {})); + for (const objectName of subscription.objectsWithState) delete userState[objectName]; - client.subscription.objectsWithState = []; + subscription.objectsWithState = []; } } + if (subscription.path !== event.request.path) { + subscription.path = event.request.path; + subscription.channels = channelsFromRequest(event.request); + } + if (subscription.channelGroupQuery !== channelGroupQuery) { + subscription.channelGroupQuery = channelGroupQuery; + subscription.channelGroups = channelGroupsFromRequest(event.request); + } + subscription.request = event.request; + subscription.filterExpression = ((_j = query['filter-expr']) !== null && _j !== void 0 ? _j : ''); + subscription.timetoken = ((_k = query.tt) !== null && _k !== void 0 ? _k : '0'); + client.authKey = ((_l = query.auth) !== null && _l !== void 0 ? _l : ''); + client.userId = query.uuid; + }; + /** + * Handle PubNub client response on PING request. + * + * @param event - Information about client which responded on PING request. + */ + const handleClientPong = (event) => { + const client = pubNubClients[event.clientIdentifier]; + if (!client) + return; + client.lastPongEvent = new Date().getTime() / 1000; }; /** * Clean up resources used by registered PubNub client instance. @@ -779,9 +865,8 @@ * @param subscriptionKey - Subscription key which has been used by the * invalidated instance. * @param clientId - Unique PubNub client identifier. - * @param userId - Unique identifier of the user used by PubNub client instance. */ - const invalidateClient = (subscriptionKey, clientId, userId) => { + const invalidateClient = (subscriptionKey, clientId) => { delete pubNubClients[clientId]; let clients = pubNubClientsBySubscriptionKey[subscriptionKey]; if (clients) { @@ -796,25 +881,23 @@ delete presenceState[subscriptionKey]; // Clean up service workers client linkage to PubNub clients. if (clients.length > 0) { - const workerClients = serviceWorkerClients[subscriptionKey]; + const workerClients = sharedWorkerClients[subscriptionKey]; if (workerClients) { delete workerClients[clientId]; if (Object.keys(workerClients).length === 0) - delete serviceWorkerClients[subscriptionKey]; + delete sharedWorkerClients[subscriptionKey]; } } else - delete serviceWorkerClients[subscriptionKey]; + delete sharedWorkerClients[subscriptionKey]; } + consoleLog(`Invalidate '${clientId}' client. '${Object.keys(pubNubClients).length}' clients currently active.`); }; /** * Validate received event payload. */ const validateEventPayload = (event) => { - if (!event.source || !(event.source instanceof Client)) - return false; - const data = event.data; - const { clientIdentifier, subscriptionKey, logVerbosity } = data; + const { clientIdentifier, subscriptionKey, logVerbosity } = event.data; if (logVerbosity === undefined || typeof logVerbosity !== 'boolean') return false; if (!clientIdentifier || typeof clientIdentifier !== 'string') @@ -822,7 +905,7 @@ return !(!subscriptionKey || typeof subscriptionKey !== 'string'); }; /** - * Search for active subscription for one of the passed {@link serviceWorkerClients}. + * Search for active subscription for one of the passed {@link sharedWorkerClients}. * * @param activeClients - List of suitable registered PubNub clients. * @param event - Send Subscriber Request event data. @@ -840,9 +923,13 @@ for (const client of activeClients) { const { subscription } = client; // Skip PubNub clients which doesn't await for subscription response. - if (!subscription.serviceRequestId) + if (!subscription || !subscription.serviceRequestId) continue; + const sourceClient = pubNubClients[event.clientIdentifier]; + const requestId = subscription.serviceRequestId; if (subscription.path === requestPath && subscription.channelGroupQuery === channelGroupQuery) { + consoleLog(`Found identical request started by '${client.clientIdentifier}' client. +Waiting for existing '${requestId}' request completion.`, sourceClient); return subscription.serviceRequestId; } else { @@ -856,6 +943,8 @@ continue; if (channelGroups.length && !includesStrings(scheduledRequest.channelGroups, channelGroups)) continue; + consoleDir(scheduledRequest, `'${event.request.identifier}' request channels and groups are subset of ongoing '${requestId}' request +which has started by '${client.clientIdentifier}' client. Waiting for existing '${requestId}' request completion.`, sourceClient); return subscription.serviceRequestId; } } @@ -885,6 +974,7 @@ const userId = query.uuid; return ((_c = pubNubClientsBySubscriptionKey[event.subscriptionKey]) !== null && _c !== void 0 ? _c : []).filter((client) => client.userId === userId && client.authKey === authKey && + client.subscription && client.subscription.filterExpression === filterExpression && (timetoken === '0' || client.subscription.previousTimetoken === '0' || @@ -944,6 +1034,74 @@ const set = new Set(main); return sub.every(set.has, set); }; + /** + * Send PubNub client PING request to identify disconnected instances. + */ + const pingClients = () => { + consoleLog(`Pinging clients...`); + const payload = { type: 'shared-worker-ping' }; + Object.values(pubNubClients).forEach((client) => { + let clientInvalidated = false; + if (client && client.lastPingRequest) { + consoleLog(`Checking whether ${client.clientIdentifier} ping has been sent too long ago...`); + // Check whether client never respond or last response was too long time ago. + if (!client.lastPongEvent || + Math.abs(client.lastPongEvent - client.lastPingRequest) > (clientPingRequestInterval / 1000) * 0.5) { + clientInvalidated = true; + consoleLog(`'${client.clientIdentifier}' client is inactive. Invalidating.`); + invalidateClient(client.subscriptionKey, client.clientIdentifier); + } + } + if (client && !clientInvalidated) { + consoleLog(`Sending ping to ${client.clientIdentifier}...`); + client.lastPingRequest = new Date().getTime() / 1000; + publishClientEvent(client, payload); + } + }); + // Cancel interval if there is no active clients. + if (Object.keys(pubNubClients).length === 0 && pingInterval) + clearInterval(pingInterval); + }; + /** + * Print message on the worker's clients console. + * + * @param message - Message which should be printed. + * @param [client] - Target client to which log message should be sent. + */ + const consoleLog = (message, client) => { + if (!logVerbosity) + return; + const clients = client ? [client] : Object.values(pubNubClients); + const payload = { + type: 'shared-worker-console-log', + message, + }; + clients.forEach((client) => { + if (client) + publishClientEvent(client, payload); + }); + }; + /** + * Print message on the worker's clients console. + * + * @param data - Data which should be printed into the console. + * @param [message] - Message which should be printed before {@link data}. + * @param [client] - Target client to which log message should be sent. + */ + const consoleDir = (data, message, client) => { + if (!logVerbosity) + return; + const clients = client ? [client] : Object.values(pubNubClients); + const payload = { + type: 'shared-worker-console-dir', + message, + data, + }; + clients.forEach((client) => { + if (client) + publishClientEvent(client, payload); + }); + }; /** * Stringify request query key / value pairs. * diff --git a/dist/web/pubnub.worker.min.js b/dist/web/pubnub.worker.min.js index 864385802..17cca5554 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,i){return new(n||(n=Promise))((function(s,r){function o(e){try{c(i.next(e))}catch(e){r(e)}}function u(e){try{c(i.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,u)}c((i=i.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,i,s={exports:{}}; -/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */n=s,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 i(){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 s(e,t){var i=n[t||"all"];return i&&i.test(e)||!1}i.isUUID=s,i.VERSION=t,e.uuid=i,e.isUUID=s}(i=s.exports),null!==n&&(n.exports=i.uuid);var r=t(s.exports),o={createUUID:()=>r.uuid?r.uuid():r()};const u=new TextDecoder,c=new Map,l={},a={},d={},p={},f={};self.addEventListener("activate",(e=>{e.waitUntil(self.clients.claim())})),self.addEventListener("message",(e=>{if(!K(e))return;const t=e.data;"send-request"===t.type?t.request.path.startsWith("/v2/subscribe")?(k(e),h(t)):(l[t.clientIdentifier]||k(e),b(e)):"cancel-request"===t.type&&v(t)}));const h=e=>{const t=j(e),n=l[e.clientIdentifier];n&&w("start",[n],(new Date).toISOString()),"string"!=typeof t?(e.request.cancellable&&c.set(t.identifier,new AbortController),g(t,(()=>q(t.identifier)),((e,n)=>{E(e,n),I(e,t.identifier)}),((e,n)=>{E(e,null,t,T(n)),I(e,t.identifier)}))):n&&(n.subscription.previousTimetoken=n.subscription.timetoken,n.subscription.timetoken=f[t].timetoken,n.subscription.serviceRequestId=t)},b=e=>{const t=e.data,n=O(t),i=l[t.clientIdentifier];if(i){if(!n){const n=(new TextEncoder).encode('{"status": 200, "action": "leave", "message": "OK", "service":"Presence"}'),s=new Headers({"Content-Type":'text/javascript; charset="UTF-8"',"Content-Length":"74"}),r=new Response(n,{status:200,headers:s}),o=S([r,n]);return o.url=`${t.request.origin}${t.request.path}`,o.clientIdentifier=t.clientIdentifier,o.identifier=t.request.identifier,void A(e.source.id,o).then((e=>{e&&x(i.subscriptionKey,i.clientIdentifier,i.userId)}))}g(n,(()=>[i]),((e,n)=>{E(e,n,t.request)}),((e,n)=>{E(e,null,t.request,T(n))}))}},v=e=>{const t=l[e.clientIdentifier],n=t?t.subscription.serviceRequestId:void 0;if(t&&n&&(delete t.subscription.serviceRequestId,delete t.subscription.request,0===q(n).length)){const e=c.get(n);c.delete(n),delete f[n],e&&e.abort()}},g=(t,n,i,s)=>{e(void 0,void 0,void 0,(function*(){var e;const r=(new Date).getTime();Promise.race([fetch(m(t),{signal:null===(e=c.get(t.identifier))||void 0===e?void 0:e.signal,keepalive:!0}),y(t.identifier,t.timeout)]).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>{const s=e[1].byteLength>0?e[1]:void 0,o=n();0!==o.length&&(w("end",o,(new Date).toISOString(),t,s,e[0].headers.get("Content-Type"),(new Date).getTime()-r),i(o,e))})).catch((e=>{const t=n();0!==t.length&&s(t,e)}))}))},y=(e,t)=>new Promise(((n,i)=>{const s=setTimeout((()=>{c.delete(e),clearTimeout(s),i(new Error("Request timeout"))}),1e3*t)})),q=e=>Object.values(l).filter((t=>void 0!==t&&t.subscription.serviceRequestId===e)),I=(e,t)=>{delete f[t],e.forEach((e=>{delete e.subscription.request,delete e.subscription.serviceRequestId}))},m=e=>{let t;const n=e.queryParameters;let i=e.path;if(e.headers){t={};for(const[n,i]of Object.entries(e.headers))t[n]=i}return n&&0!==Object.keys(n).length&&(i=`${i}?${W(n)}`),new Request(`${e.origin}${i}`,{method:e.method,headers:t,redirect:"follow"})},j=e=>{var t,n,i,s;const r=l[e.clientIdentifier],u=R(r.subscription.previousTimetoken,e),c=o.createUUID(),a=Object.assign({},e.request);if(u.length>1){const s=F(u,e);if(s)return s;const o=(null!==(t=d[r.subscriptionKey])&&void 0!==t?t:{})[r.userId],l={},p=new Set(r.subscription.channelGroups),h=new Set(r.subscription.channels);o&&r.subscription.objectsWithState.length&&r.subscription.objectsWithState.forEach((e=>{const t=o[e];t&&(l[e]=t)}));for(const e of u){const{subscription:t}=e;t.serviceRequestId||(t.channelGroups.forEach(p.add,p),t.channels.forEach(h.add,h),t.serviceRequestId=c,o&&t.objectsWithState.forEach((e=>{const t=o[e];t&&!l[e]&&(l[e]=t)})))}const b=null!==(n=f[c])&&void 0!==n?n:f[c]={requestId:c,timetoken:null!==(i=a.queryParameters.tt)&&void 0!==i?i:"0",channelGroups:[],channels:[]};if(h.size){b.channels=Array.from(h).sort();const e=a.path.split("/");e[4]=b.channels.join(","),a.path=e.join("/")}p.size&&(b.channelGroups=Array.from(p).sort(),a.queryParameters["channel-group"]=b.channelGroups.join(",")),Object.keys(l).length&&(a.queryParameters.state=JSON.stringify(l))}else f[c]={requestId:c,timetoken:null!==(s=a.queryParameters.tt)&&void 0!==s?s:"0",channelGroups:r.subscription.channelGroups,channels:r.subscription.channels};return r.subscription.serviceRequestId=c,a.identifier=c,a},O=e=>{const t=l[e.clientIdentifier],n=$(e);let i=P(e.request),s=G(e.request);const r=Object.assign({},e.request);if(t){const{subscription:e}=t;s.length&&(e.channels=e.channels.filter((e=>!s.includes(e)))),i.length&&(e.channelGroups=e.channelGroups.filter((e=>!i.includes(e))))}for(const t of n)t.clientIdentifier!==e.clientIdentifier&&(s.length&&(s=s.filter((e=>!t.subscription.channels.includes(e)))),i.length&&(i=i.filter((e=>!t.subscription.channelGroups.includes(e)))));if(0!==s.length||0!==i.length){if(s.length){const e=r.path.split("/");e[4]=s.join(","),r.path=e.join("/")}return i.length&&(r.queryParameters["channel-group"]=i.join(",")),r}},A=(e,t)=>self.clients.get(e).then((e=>!!e&&(e.postMessage(t),!0))),w=(e,t,n,i,s,r,o)=>{var c;if(0===t.length)return;const l=null!==(c=p[t[0].subscriptionKey])&&void 0!==c?c:{};let a;if("start"===e)a={type:"request-progress-start",clientIdentifier:"",url:"",timestamp:n};else{let e;s&&r&&(-1!==r.indexOf("text/javascript")||-1!==r.indexOf("application/json")||-1!==r.indexOf("text/plain")||-1!==r.indexOf("text/html"))&&(e=u.decode(s)),a={type:"request-progress-end",clientIdentifier:"",url:"",response:e,timestamp:n,duration:o}}t.forEach((e=>{const t=l[e.clientIdentifier],{request:n}=e.subscription,s=null!=n?n:i;e.logVerbosity&&t&&s&&A(t,Object.assign(Object.assign({},a),{clientIdentifier:e.clientIdentifier,url:`${s.origin}${s.path}`,query:s.queryParameters})).then((t=>{t&&x(e.subscriptionKey,e.clientIdentifier,e.userId)}))}))},E=(e,t,n,i)=>{var s;if(0===e.length)return;if(!i&&!t)return;const r=null!==(s=p[e[0].subscriptionKey])&&void 0!==s?s:{};!i&&t&&(i=t[0].status>=400?T(void 0,t):S(t)),e.forEach((e=>{const t=r[e.clientIdentifier],{request:s}=e.subscription,o=null!=s?s:n;t&&o&&A(t,Object.assign(Object.assign({},i),{clientIdentifier:e.clientIdentifier,identifier:o.identifier,url:`${o.origin}${o.path}`})).then((t=>{t&&x(e.subscriptionKey,e.clientIdentifier,e.userId)}))}))},S=e=>{var t;const[n,i]=e,s=i.byteLength>0?i:void 0,r=parseInt(null!==(t=n.headers.get("Content-Length"))&&void 0!==t?t:"0",10),o=n.headers.get("Content-Type"),u={};return n.headers.forEach(((e,t)=>u[t]=e.toLowerCase())),{type:"request-process-success",clientIdentifier:"",identifier:"",url:"",response:{contentLength:r,contentType:o,headers:u,status:n.status,body:s}}},T=(e,t)=>{if(t)return Object.assign(Object.assign({},S(t)),{type:"request-process-error"});let n="NETWORK_ISSUE",i="Unknown error",s="Error";return e&&e instanceof Error&&(i=e.message,s=e.name),"AbortError"===s?(i="Request aborted",n="ABORTED"):"Request timeout"===i&&(n="TIMEOUT"),{type:"request-process-error",clientIdentifier:"",identifier:"",url:"",error:{name:s,type:n,message:i}}},k=e=>{var t,n,i,s,r,o,u,c,f,h,b,v,g,y,q,I,m,j,O,A,w,E,S,T,k,x,K,F,R,$;const U=e.data,{clientIdentifier:W}=U,C=U.request.queryParameters;let D=l[W];if(D){const e=null!==(b=C["channel-group"])&&void 0!==b?b:"",t=null!==(v=C.state)&&void 0!==v?v:"";if(D.subscription.filterExpression=null!==(g=C["filter-expr"])&&void 0!==g?g:"",D.subscription.previousTimetoken=D.subscription.timetoken,D.subscription.timetoken=null!==(y=C.tt)&&void 0!==y?y:"0",D.subscription.request=U.request,D.authKey=null!==(q=C.auth)&&void 0!==q?q:"",D.userId=C.uuid,D.subscription.path!==U.request.path&&(D.subscription.path=U.request.path,D.subscription.channels=G(U.request)),D.subscription.channelGroupQuery!==e&&(D.subscription.channelGroupQuery=e,D.subscription.channelGroups=P(U.request)),t.length>0){const e=JSON.parse(t),n=null!==(m=(x=null!==(I=d[k=D.subscriptionKey])&&void 0!==I?I:d[k]={})[K=D.userId])&&void 0!==m?m:x[K]={};Object.entries(e).forEach((([e,t])=>n[e]=t));for(const t of D.subscription.objectsWithState)e[t]||delete n[t];D.subscription.objectsWithState=Object.keys(e)}else if(D.subscription.objectsWithState.length){const e=null!==(O=(R=null!==(j=d[F=D.subscriptionKey])&&void 0!==j?j:d[F]={})[$=D.userId])&&void 0!==O?O:R[$]={};for(const t of D.subscription.objectsWithState)delete e[t];D.subscription.objectsWithState=[]}}else{const b=!U.request.path.startsWith("/v2/subscribe"),v=b?"":null!==(t=C["channel-group"])&&void 0!==t?t:"",g=b?"":null!==(n=C.state)&&void 0!==n?n:"";if(D=l[W]={clientIdentifier:W,subscriptionKey:U.subscriptionKey,userId:C.uuid,authKey:null!==(i=C.auth)&&void 0!==i?i:"",logVerbosity:U.logVerbosity,subscription:{path:b?"":U.request.path,channelGroupQuery:b?"":v,channels:b?[]:G(U.request),channelGroups:b?[]:P(U.request),previousTimetoken:b?"0":null!==(s=C.tt)&&void 0!==s?s:"0",timetoken:b?"0":null!==(r=C.tt)&&void 0!==r?r:"0",request:b?void 0:U.request,objectsWithState:[],filterExpression:b?void 0:null!==(o=C["filter-expr"])&&void 0!==o?o:""}},!b&&g.length>0){const e=JSON.parse(g),t=null!==(c=(w=null!==(u=d[A=D.subscriptionKey])&&void 0!==u?u:d[A]={})[E=D.userId])&&void 0!==c?c:w[E]={};Object.entries(e).forEach((([e,n])=>t[e]=n)),D.subscription.objectsWithState=Object.keys(e)}const y=null!==(f=a[S=U.subscriptionKey])&&void 0!==f?f:a[S]=[];y.every((e=>e.clientIdentifier!==W))&&y.push(D),(null!==(h=p[T=U.subscriptionKey])&&void 0!==h?h:p[T]={})[W]=e.source.id}},x=(e,t,n)=>{delete l[t];let i=a[e];if(i)if(i=i.filter((e=>e.clientIdentifier!==t)),i.length>0?a[e]=i:delete a[e],0===i.length&&delete d[e],i.length>0){const n=p[e];n&&(delete n[t],0===Object.keys(n).length&&delete p[e])}else delete p[e]},K=e=>{if(!(e.source&&e.source instanceof Client))return!1;const t=e.data,{clientIdentifier:n,subscriptionKey:i,logVerbosity:s}=t;return void 0!==s&&"boolean"==typeof s&&(!(!n||"string"!=typeof n)&&!(!i||"string"!=typeof i))},F=(e,t)=>{var n;const i=null!==(n=t.request.queryParameters["channel-group"])&&void 0!==n?n:"",s=t.request.path;let r,o;for(const n of e){const{subscription:e}=n;if(e.serviceRequestId){if(e.path===s&&e.channelGroupQuery===i)return e.serviceRequestId;{const n=f[e.serviceRequestId];if(r||(r=P(t.request)),o||(o=G(t.request)),o.length&&!U(n.channels,o))continue;if(r.length&&!U(n.channelGroups,r))continue;return e.serviceRequestId}}}},R=(e,t)=>{var n,i,s;const r=t.request.queryParameters,o=null!==(n=r["filter-expr"])&&void 0!==n?n:"",u=null!==(i=r.auth)&&void 0!==i?i:"",c=r.uuid;return(null!==(s=a[t.subscriptionKey])&&void 0!==s?s:[]).filter((t=>t.userId===c&&t.authKey===u&&t.subscription.filterExpression===o&&("0"===e||"0"===t.subscription.previousTimetoken||t.subscription.previousTimetoken===e)))},$=e=>{var t,n;const i=e.request.queryParameters,s=null!==(t=i.auth)&&void 0!==t?t:"",r=i.uuid;return(null!==(n=a[e.subscriptionKey])&&void 0!==n?n:[]).filter((e=>e.userId===r&&e.authKey===s))},G=e=>{const t=e.path.split("/")[e.path.startsWith("/v2/subscribe/")?4:6];return","===t?[]:t.split(",").filter((e=>e.length>0))},P=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))},U=(e,t)=>{const n=new Set(e);return t.every(n.has,n)},W=e=>Object.keys(e).map((t=>{const n=e[t];return Array.isArray(n)?n.map((e=>`${t}=${C(e)}`)).join("&"):`${t}=${C(n)}`})).join("&"),C=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,i){return new(n||(n=Promise))((function(r,s){function o(e){try{u(i.next(e))}catch(e){s(e)}}function c(e){try{u(i.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,c)}u((i=i.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,i,r={exports:{}}; +/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */n=r,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 i(){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 i=n[t||"all"];return i&&i.test(e)||!1}i.isUUID=r,i.VERSION=t,e.uuid=i,e.isUUID=r}(i=r.exports),null!==n&&(n.exports=i.uuid);var s=t(r.exports),o={createUUID:()=>s.uuid?s.uuid():s()};const c=5e3,u=new TextDecoder;let l,a=!1;const d=o.createUUID(),f=new Map,p={},h={},g={},b={},v={};self.onconnect=e=>{V("New PubNub Client connected to the Subscription Shared Worker."),e.ports.forEach((e=>{e.start(),e.onmessage=t=>{if(!G(t))return;const n=t.data;"client-register"===n.type?(!a&&n.workerLogVerbosity&&(a=!0),n.port=e,x(n),V(`Client '${n.clientIdentifier}' registered with '${d}' shared worker`)):"client-pong"===n.type?K(n):"send-request"===n.type?n.request.path.startsWith("/v2/subscribe")?(F(n),y(n)):q(n):"cancel-request"===n.type&&I(n)},e.postMessage({type:"shared-worker-connected"})}))};const y=e=>{const t=k(e),n=p[e.clientIdentifier];n&&E("start",[n],(new Date).toISOString()),"string"!=typeof t?(e.request.cancellable&&f.set(t.identifier,new AbortController),m(t,(()=>O(t.identifier)),((e,n)=>{P(e,n),w(e,t.identifier)}),((e,n)=>{P(e,null,t,T(n)),w(e,t.identifier)})),V(`'${Object.keys(v).length}' subscription request currently active.`)):n&&n.subscription&&(n.subscription.previousTimetoken=n.subscription.timetoken,n.subscription.timetoken=v[t].timetoken,n.subscription.serviceRequestId=t)},q=e=>{const t=S(e),n=p[e.clientIdentifier];if(n){if(!t){const t=(new TextEncoder).encode('{"status": 200, "action": "leave", "message": "OK", "service":"Presence"}'),i=new Headers({"Content-Type":'text/javascript; charset="UTF-8"',"Content-Length":"74"}),r=new Response(t,{status:200,headers:i}),s=R([r,t]);return s.url=`${e.request.origin}${e.request.path}`,s.clientIdentifier=e.clientIdentifier,s.identifier=e.request.identifier,void A(n,s)}m(t,(()=>[n]),((t,n)=>{P(t,n,e.request)}),((t,n)=>{P(t,null,e.request,T(n))})),V("Started leave request.",n)}},I=e=>{const t=p[e.clientIdentifier];if(!t||!t.subscription)return;const n=t.subscription.serviceRequestId;if(t&&n&&(delete t.subscription.serviceRequestId,delete t.subscription.request,0===O(n).length)){const e=f.get(n);f.delete(n),delete v[n],e&&e.abort()}},m=(t,n,i,r)=>{e(void 0,void 0,void 0,(function*(){var e;const s=(new Date).getTime();Promise.race([fetch($(t),{signal:null===(e=f.get(t.identifier))||void 0===e?void 0:e.signal,keepalive:!0}),j(t.identifier,t.timeout)]).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>{const r=e[1].byteLength>0?e[1]:void 0,o=n();0!==o.length&&(E("end",o,(new Date).toISOString(),t,r,e[0].headers.get("Content-Type"),(new Date).getTime()-s),i(o,e))})).catch((e=>{const t=n();0!==t.length&&r(t,e)}))}))},j=(e,t)=>new Promise(((n,i)=>{const r=setTimeout((()=>{f.delete(e),clearTimeout(r),i(new Error("Request timeout"))}),1e3*t)})),O=e=>Object.values(p).filter((t=>void 0!==t&&void 0!==t.subscription&&t.subscription.serviceRequestId===e)),w=(e,t)=>{delete v[t],e.forEach((e=>{e.subscription&&(delete e.subscription.request,delete e.subscription.serviceRequestId)}))},$=e=>{let t;const n=e.queryParameters;let i=e.path;if(e.headers){t={};for(const[n,i]of Object.entries(e.headers))t[n]=i}return n&&0!==Object.keys(n).length&&(i=`${i}?${Q(n)}`),new Request(`${e.origin}${i}`,{method:e.method,headers:t,redirect:"follow"})},k=e=>{var t,n,i,r;const s=p[e.clientIdentifier],c=s.subscription,u=W(c.previousTimetoken,e),l=o.createUUID(),d=Object.assign({},e.request);if(u.length>1){const r=U(u,e);if(r)return r;const o=(null!==(t=g[s.subscriptionKey])&&void 0!==t?t:{})[s.userId],a={},f=new Set(c.channelGroups),p=new Set(c.channels);o&&c.objectsWithState.length&&c.objectsWithState.forEach((e=>{const t=o[e];t&&(a[e]=t)}));for(const e of u){const{subscription:t}=e;t&&t.serviceRequestId&&(t.channelGroups.forEach(f.add,f),t.channels.forEach(p.add,p),t.serviceRequestId=l,o&&t.objectsWithState.forEach((e=>{const t=o[e];t&&!a[e]&&(a[e]=t)})))}const h=null!==(n=v[l])&&void 0!==n?n:v[l]={requestId:l,timetoken:null!==(i=d.queryParameters.tt)&&void 0!==i?i:"0",channelGroups:[],channels:[]};if(p.size){h.channels=Array.from(p).sort();const e=d.path.split("/");e[4]=h.channels.join(","),d.path=e.join("/")}f.size&&(h.channelGroups=Array.from(f).sort(),d.queryParameters["channel-group"]=h.channelGroups.join(",")),Object.keys(a).length&&(d.queryParameters.state=JSON.stringify(a))}else v[l]={requestId:l,timetoken:null!==(r=d.queryParameters.tt)&&void 0!==r?r:"0",channelGroups:c.channelGroups,channels:c.channels};if(c.serviceRequestId=l,d.identifier=l,a){const e=u.reduce(((e,{clientIdentifier:t})=>(e.push(t),e)),[]).join(",");B(v[l],`Started aggregated request for clients: ${e}`)}return d},S=e=>{const t=p[e.clientIdentifier],n=C(e);let i=N(e.request),r=D(e.request);const s=Object.assign({},e.request);if(t&&t.subscription){const{subscription:e}=t;r.length&&(e.channels=e.channels.filter((e=>!r.includes(e)))),i.length&&(e.channelGroups=e.channelGroups.filter((e=>!i.includes(e))))}for(const t of n){const n=t.subscription;void 0!==n&&(t.clientIdentifier!==e.clientIdentifier&&(r.length&&(r=r.filter((e=>!n.channels.includes(e)))),i.length&&(i=i.filter((e=>!n.channelGroups.includes(e))))))}if(0!==r.length||0!==i.length){if(r.length){const e=s.path.split("/");e[4]=r.join(","),s.path=e.join("/")}return i.length&&(s.queryParameters["channel-group"]=i.join(",")),s}if(a&&t){const e=n.reduce(((e,{clientIdentifier:t})=>(e.push(t),e)),[]).join(",");V(`Specified channels and groups still in use by other clients: ${e}. Ignoring leave request.`,t)}},A=(e,t)=>{var n;const i=(null!==(n=b[e.subscriptionKey])&&void 0!==n?n:{})[e.clientIdentifier];if(!i)return!1;try{return i.postMessage(t),!0}catch(e){}return!1},E=(e,t,n,i,r,s,o)=>{var c;if(0===t.length)return;const l=null!==(c=b[t[0].subscriptionKey])&&void 0!==c?c:{};let a;if("start"===e)a={type:"request-progress-start",clientIdentifier:"",url:"",timestamp:n};else{let e;r&&s&&(-1!==s.indexOf("text/javascript")||-1!==s.indexOf("application/json")||-1!==s.indexOf("text/plain")||-1!==s.indexOf("text/html"))&&(e=u.decode(r)),a={type:"request-progress-end",clientIdentifier:"",url:"",response:e,timestamp:n,duration:o}}for(const e of t){if(void 0===e.subscription)continue;const t=l[e.clientIdentifier],{request:n}=e.subscription,r=null!=n?n:i;if(e.logVerbosity&&t&&r){const t=Object.assign(Object.assign({},a),{clientIdentifier:e.clientIdentifier,url:`${r.origin}${r.path}`,query:r.queryParameters});A(e,t)}}},P=(e,t,n,i)=>{var r;if(0===e.length)return;if(!i&&!t)return;const s=null!==(r=b[e[0].subscriptionKey])&&void 0!==r?r:{};!i&&t&&(i=t[0].status>=400?T(void 0,t):R(t));for(const t of e){if(void 0===t.subscription)continue;const e=s[t.clientIdentifier],{request:r}=t.subscription,o=null!=r?r:n;if(e&&o){const e=Object.assign(Object.assign({},i),{clientIdentifier:t.clientIdentifier,identifier:o.identifier,url:`${o.origin}${o.path}`});A(t,e)}}},R=e=>{var t;const[n,i]=e,r=i.byteLength>0?i: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:r}}},T=(e,t)=>{if(t)return Object.assign(Object.assign({},R(t)),{type:"request-process-error"});let n="NETWORK_ISSUE",i="Unknown error",r="Error";return e&&e instanceof Error&&(i=e.message,r=e.name),"AbortError"===r?(i="Request aborted",n="ABORTED"):"Request timeout"===i&&(n="TIMEOUT"),{type:"request-process-error",clientIdentifier:"",identifier:"",url:"",error:{name:r,type:n,message:i}}},x=e=>{var t,n,i,r;const{clientIdentifier:s}=e;if(p[s])return;const o=p[s]={clientIdentifier:s,subscriptionKey:e.subscriptionKey,userId:e.userId,logVerbosity:e.logVerbosity},u=null!==(t=h[i=e.subscriptionKey])&&void 0!==t?t:h[i]=[];u.every((e=>e.clientIdentifier!==s))&&u.push(o),(null!==(n=b[r=e.subscriptionKey])&&void 0!==n?n:b[r]={})[s]=e.port,V(`Registered PubNub client with '${s}' identifier. '${Object.keys(p).length}' clients currently active.`),!l&&Object.keys(p).length>0&&(V("Setup PubNub client ping event 5 seconds"),l=setInterval((()=>M()),c))},F=e=>{var t,n,i,r,s,o,c,u,l,a,d,f,h,b,v,y,q,I,m,j;const O=e.request.queryParameters,{clientIdentifier:w}=e,$=p[w];if(!$)return;const k=null!==(t=O["channel-group"])&&void 0!==t?t:"",S=null!==(n=O.state)&&void 0!==n?n:"";let A=$.subscription;if(A){if(A.previousTimetoken=A.timetoken,S.length>0){const e=JSON.parse(S),t=null!==(o=(y=null!==(s=g[v=$.subscriptionKey])&&void 0!==s?s:g[v]={})[q=$.userId])&&void 0!==o?o:y[q]={};Object.entries(e).forEach((([e,n])=>t[e]=n));for(const n of A.objectsWithState)e[n]||delete t[n];A.objectsWithState=Object.keys(e)}else if(A.objectsWithState.length){const e=null!==(u=(m=null!==(c=g[I=$.subscriptionKey])&&void 0!==c?c:g[I]={})[j=$.userId])&&void 0!==u?u:m[j]={};for(const t of A.objectsWithState)delete e[t];A.objectsWithState=[]}}else{if(A={path:"",channelGroupQuery:"",channels:[],channelGroups:[],previousTimetoken:"0",timetoken:"0",objectsWithState:[]},S.length>0){const e=JSON.parse(S),t=null!==(r=(h=null!==(i=g[f=$.subscriptionKey])&&void 0!==i?i:g[f]={})[b=$.userId])&&void 0!==r?r:h[b]={};Object.entries(e).forEach((([e,n])=>t[e]=n)),A.objectsWithState=Object.keys(e)}$.subscription=A}A.path!==e.request.path&&(A.path=e.request.path,A.channels=D(e.request)),A.channelGroupQuery!==k&&(A.channelGroupQuery=k,A.channelGroups=N(e.request)),A.request=e.request,A.filterExpression=null!==(l=O["filter-expr"])&&void 0!==l?l:"",A.timetoken=null!==(a=O.tt)&&void 0!==a?a:"0",$.authKey=null!==(d=O.auth)&&void 0!==d?d:"",$.userId=O.uuid},K=e=>{const t=p[e.clientIdentifier];t&&(t.lastPongEvent=(new Date).getTime()/1e3)},G=e=>{const{clientIdentifier:t,subscriptionKey:n,logVerbosity:i}=e.data;return void 0!==i&&"boolean"==typeof i&&(!(!t||"string"!=typeof t)&&!(!n||"string"!=typeof n))},U=(e,t)=>{var n;const i=null!==(n=t.request.queryParameters["channel-group"])&&void 0!==n?n:"",r=t.request.path;let s,o;for(const n of e){const{subscription:e}=n;if(!e||!e.serviceRequestId)continue;const c=p[t.clientIdentifier],u=e.serviceRequestId;if(e.path===r&&e.channelGroupQuery===i)return V(`Found identical request started by '${n.clientIdentifier}' client. \nWaiting for existing '${u}' request completion.`,c),e.serviceRequestId;{const i=v[e.serviceRequestId];if(s||(s=N(t.request)),o||(o=D(t.request)),o.length&&!L(i.channels,o))continue;if(s.length&&!L(i.channelGroups,s))continue;return B(i,`'${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}}},W=(e,t)=>{var n,i,r;const s=t.request.queryParameters,o=null!==(n=s["filter-expr"])&&void 0!==n?n:"",c=null!==(i=s.auth)&&void 0!==i?i:"",u=s.uuid;return(null!==(r=h[t.subscriptionKey])&&void 0!==r?r:[]).filter((t=>t.userId===u&&t.authKey===c&&t.subscription&&t.subscription.filterExpression===o&&("0"===e||"0"===t.subscription.previousTimetoken||t.subscription.previousTimetoken===e)))},C=e=>{var t,n;const i=e.request.queryParameters,r=null!==(t=i.auth)&&void 0!==t?t:"",s=i.uuid;return(null!==(n=h[e.subscriptionKey])&&void 0!==n?n:[]).filter((e=>e.userId===s&&e.authKey===r))},D=e=>{const t=e.path.split("/")[e.path.startsWith("/v2/subscribe/")?4:6];return","===t?[]:t.split(",").filter((e=>e.length>0))},N=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))},L=(e,t)=>{const n=new Set(e);return t.every(n.has,n)},M=()=>{V("Pinging clients...");const e={type:"shared-worker-ping"};Object.values(p).forEach((t=>{let n=!1;t&&t.lastPingRequest&&(V(`Checking whether ${t.clientIdentifier} ping has been sent too long ago...`),(!t.lastPongEvent||Math.abs(t.lastPongEvent-t.lastPingRequest)>2.5)&&(n=!0,V(`'${t.clientIdentifier}' client is inactive. Invalidating.`),((e,t)=>{delete p[t];let n=h[e];if(n)if(n=n.filter((e=>e.clientIdentifier!==t)),n.length>0?h[e]=n:delete h[e],0===n.length&&delete g[e],n.length>0){const n=b[e];n&&(delete n[t],0===Object.keys(n).length&&delete b[e])}else delete b[e];V(`Invalidate '${t}' client. '${Object.keys(p).length}' clients currently active.`)})(t.subscriptionKey,t.clientIdentifier))),t&&!n&&(V(`Sending ping to ${t.clientIdentifier}...`),t.lastPingRequest=(new Date).getTime()/1e3,A(t,e))})),0===Object.keys(p).length&&l&&clearInterval(l)},V=(e,t)=>{if(!a)return;const n=t?[t]:Object.values(p),i={type:"shared-worker-console-log",message:e};n.forEach((e=>{e&&A(e,i)}))},B=(e,t,n)=>{if(!a)return;const i=n?[n]:Object.values(p),r={type:"shared-worker-console-dir",message:t,data:e};i.forEach((e=>{e&&A(e,r)}))},Q=e=>Object.keys(e).map((t=>{const n=e[t];return Array.isArray(n)?n.map((e=>`${t}=${J(e)}`)).join("&"):`${t}=${J(n)}`})).join("&"),J=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`))})); diff --git a/lib/core/utils.js b/lib/core/utils.js index 2bd14eee4..512d80040 100644 --- a/lib/core/utils.js +++ b/lib/core/utils.js @@ -1,6 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.queryStringFromObject = exports.findUniqueCommonElements = exports.removeSingleOccurance = exports.encodeNames = exports.encodeString = void 0; +exports.queryStringFromObject = exports.findUniqueCommonElements = exports.removeSingleOccurrence = exports.encodeNames = exports.encodeString = void 0; const encodeString = (input) => { return encodeURIComponent(input).replace(/[!~*'()]/g, (x) => `%${x.charCodeAt(0).toString(16).toUpperCase()}`); }; @@ -10,7 +10,7 @@ const encodeNames = (names, defaultString) => { return encodedNames.length ? encodedNames.join(',') : defaultString !== null && defaultString !== void 0 ? defaultString : ''; }; exports.encodeNames = encodeNames; -const removeSingleOccurance = (source, elementsToRemove) => { +const removeSingleOccurrence = (source, elementsToRemove) => { const removed = Object.fromEntries(elementsToRemove.map((prop) => [prop, false])); return source.filter((e) => { if (elementsToRemove.includes(e) && !removed[e]) { @@ -20,7 +20,7 @@ const removeSingleOccurance = (source, elementsToRemove) => { return true; }); }; -exports.removeSingleOccurance = removeSingleOccurance; +exports.removeSingleOccurrence = removeSingleOccurrence; const findUniqueCommonElements = (a, b) => { return [...a].filter((value) => b.includes(value) && a.indexOf(value) === a.lastIndexOf(value) && b.indexOf(value) === b.lastIndexOf(value)); }; diff --git a/lib/event-engine/index.js b/lib/event-engine/index.js index fd48c7427..697416481 100644 --- a/lib/event-engine/index.js +++ b/lib/event-engine/index.js @@ -67,11 +67,11 @@ class EventEngine { } } unsubscribe({ channels = [], channelGroups = [] }) { - const filteredChannels = utils.removeSingleOccurance(this.channels, [ + const filteredChannels = utils.removeSingleOccurrence(this.channels, [ ...channels, ...channels.map((c) => `${c}-pnpres`), ]); - const filteredGroups = utils.removeSingleOccurance(this.groups, [ + const filteredGroups = utils.removeSingleOccurrence(this.groups, [ ...channelGroups, ...channelGroups.map((c) => `${c}-pnpres`), ]); diff --git a/lib/node/index.js b/lib/node/index.js index 5fd5e321e..45fb6690c 100644 --- a/lib/node/index.js +++ b/lib/node/index.js @@ -2,7 +2,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; -var _a; const cbor_sync_1 = __importDefault(require("cbor-sync")); const buffer_1 = require("buffer"); const nodeCryptoModule_1 = require("../crypto/modules/NodeCryptoModule/nodeCryptoModule"); @@ -18,50 +17,50 @@ const cryptography_1 = __importDefault(require("../core/components/cryptography" const pubnub_error_1 = require("../errors/pubnub-error"); const pubnub_common_1 = require("../core/pubnub-common"); const common_1 = __importDefault(require("../cbor/common")); -module.exports = (_a = class PubNub extends pubnub_common_1.PubNubCore { - constructor(configuration) { - const configurationCopy = (0, configuration_2.setDefaults)(configuration); - const platformConfiguration = Object.assign(Object.assign({}, configurationCopy), { sdkFamily: 'Nodejs', PubNubFile: node_1.default }); - const clientConfiguration = (0, configuration_1.makeConfiguration)(platformConfiguration, (cryptoConfiguration) => { - if (!cryptoConfiguration.cipherKey) - return undefined; - return new nodeCryptoModule_1.CryptoModule({ - default: new nodeCryptoModule_1.LegacyCryptor(Object.assign({}, cryptoConfiguration)), - cryptors: [new nodeCryptoModule_1.AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })], - }); +class PubNub extends pubnub_common_1.PubNubCore { + constructor(configuration) { + const configurationCopy = (0, configuration_2.setDefaults)(configuration); + const platformConfiguration = Object.assign(Object.assign({}, configurationCopy), { sdkFamily: 'Nodejs', PubNubFile: node_1.default }); + const clientConfiguration = (0, configuration_1.makeConfiguration)(platformConfiguration, (cryptoConfiguration) => { + if (!cryptoConfiguration.cipherKey) + return undefined; + return new nodeCryptoModule_1.CryptoModule({ + default: new nodeCryptoModule_1.LegacyCryptor(Object.assign({}, cryptoConfiguration)), + cryptors: [new nodeCryptoModule_1.AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })], }); - const tokenManager = new token_manager_1.TokenManager(new common_1.default((buffer) => cbor_sync_1.default.decode(buffer_1.Buffer.from(buffer)), base64_codec_1.decode)); - const crypto = new cryptography_1.default({ - secretKey: clientConfiguration.secretKey, - cipherKey: clientConfiguration.getCipherKey(), - useRandomIVs: clientConfiguration.getUseRandomIVs(), - customEncrypt: clientConfiguration.getCustomEncrypt(), - customDecrypt: clientConfiguration.getCustomDecrypt(), - }); - const transport = new node_transport_1.NodeTransport(configuration.keepAlive, configuration.keepAliveSettings); - const transportMiddleware = new middleware_1.PubNubMiddleware({ - clientConfiguration, - tokenManager, - transport, - shaHMAC: crypto === null || crypto === void 0 ? void 0 : crypto.HMACSHA256.bind(crypto), - }); - super({ - configuration: clientConfiguration, - transport: transportMiddleware, - cryptography: new node_2.default(), - tokenManager, - crypto, - }); - this.File = node_1.default; - this.nodeTransport = transport; - } - setProxy(configuration) { - var _b; - if (configuration && ((_b = this._configuration.keepAlive) !== null && _b !== void 0 ? _b : false)) - throw new pubnub_error_1.PubNubError("Can't set 'proxy' because already configured for 'keepAlive'"); - this.nodeTransport.setProxy(configuration); - this.reconnect(); - } - }, - _a.CryptoModule = nodeCryptoModule_1.CryptoModule, - _a); + }); + const tokenManager = new token_manager_1.TokenManager(new common_1.default((buffer) => cbor_sync_1.default.decode(buffer_1.Buffer.from(buffer)), base64_codec_1.decode)); + const crypto = new cryptography_1.default({ + secretKey: clientConfiguration.secretKey, + cipherKey: clientConfiguration.getCipherKey(), + useRandomIVs: clientConfiguration.getUseRandomIVs(), + customEncrypt: clientConfiguration.getCustomEncrypt(), + customDecrypt: clientConfiguration.getCustomDecrypt(), + }); + const transport = new node_transport_1.NodeTransport(configuration.keepAlive, configuration.keepAliveSettings); + const transportMiddleware = new middleware_1.PubNubMiddleware({ + clientConfiguration, + tokenManager, + transport, + shaHMAC: crypto === null || crypto === void 0 ? void 0 : crypto.HMACSHA256.bind(crypto), + }); + super({ + configuration: clientConfiguration, + transport: transportMiddleware, + cryptography: new node_2.default(), + tokenManager, + crypto, + }); + this.File = node_1.default; + this.nodeTransport = transport; + } + setProxy(configuration) { + var _a; + if (configuration && ((_a = this._configuration.keepAlive) !== null && _a !== void 0 ? _a : false)) + throw new pubnub_error_1.PubNubError("Can't set 'proxy' because already configured for 'keepAlive'"); + this.nodeTransport.setProxy(configuration); + this.reconnect(); + } +} +PubNub.CryptoModule = nodeCryptoModule_1.CryptoModule; +module.exports = PubNub; diff --git a/lib/types/cbor/common.d.ts b/lib/types/cbor/common.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/cbor/common.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/components/abort_signal.d.ts b/lib/types/core/components/abort_signal.d.ts new file mode 100644 index 000000000..926a042d3 --- /dev/null +++ b/lib/types/core/components/abort_signal.d.ts @@ -0,0 +1,4 @@ +export declare class AbortError extends Error { + name: string; + constructor(); +} diff --git a/lib/types/core/components/base64_codec.d.ts b/lib/types/core/components/base64_codec.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/components/base64_codec.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/components/configuration.d.ts b/lib/types/core/components/configuration.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/components/configuration.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/components/cryptography/hmac-sha256.d.ts b/lib/types/core/components/cryptography/hmac-sha256.d.ts new file mode 100644 index 000000000..112f25199 --- /dev/null +++ b/lib/types/core/components/cryptography/hmac-sha256.d.ts @@ -0,0 +1,3 @@ +export namespace mode { + let ECB: any; +} diff --git a/lib/types/core/components/cryptography/index.d.ts b/lib/types/core/components/cryptography/index.d.ts new file mode 100644 index 000000000..ff88b48b7 --- /dev/null +++ b/lib/types/core/components/cryptography/index.d.ts @@ -0,0 +1,30 @@ +import { CryptorConfiguration } from '../../interfaces/crypto-module'; +import { Payload } from '../../types/api'; +type CryptoConfiguration = { + encryptKey?: boolean; + keyEncoding?: 'hex' | 'utf8' | 'base64' | 'binary'; + keyLength?: 128 | 256; + mode?: 'ecb' | 'cbc'; +}; +export default class { + private readonly configuration; + private iv; + private allowedKeyEncodings; + private allowedKeyLengths; + private allowedModes; + private readonly defaultOptions; + constructor(configuration: CryptorConfiguration); + HMACSHA256(data: string): string; + SHA256(data: string): string; + encrypt(data: string | Payload, customCipherKey?: string, options?: CryptoConfiguration): string; + decrypt(data: string, customCipherKey?: string, options?: CryptoConfiguration): Payload | null; + private pnEncrypt; + private pnDecrypt; + private parseOptions; + private decodeKey; + private getPaddedKey; + private getMode; + private getIV; + private getRandomIV; +} +export {}; diff --git a/lib/types/core/components/deduping_manager.d.ts b/lib/types/core/components/deduping_manager.d.ts new file mode 100644 index 000000000..121ef9cf6 --- /dev/null +++ b/lib/types/core/components/deduping_manager.d.ts @@ -0,0 +1,11 @@ +export default class _default { + constructor({ config }: { + config: any; + }); + _config: any; + hashHistory: any[]; + getKey(message: any): string; + isDuplicate(message: any): boolean; + addEntry(message: any): void; + clearHistory(): void; +} diff --git a/lib/types/core/components/eventEmitter.d.ts b/lib/types/core/components/eventEmitter.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/components/eventEmitter.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/components/listener_manager.d.ts b/lib/types/core/components/listener_manager.d.ts new file mode 100644 index 000000000..fec05ebba --- /dev/null +++ b/lib/types/core/components/listener_manager.d.ts @@ -0,0 +1,14 @@ +import * as Subscription from '../types/api/subscription'; +import { Status, StatusEvent } from '../types/api'; +export type Listener = { + message?: (message: Subscription.Message) => void; + signal?: (signal: Subscription.Signal) => void; + presence?: (presence: Subscription.Presence) => void; + objects?: (object: Subscription.AppContextObject) => void; + messageAction?: (action: Subscription.MessageAction) => void; + file?: (file: Subscription.File) => void; + status?: (status: Status | StatusEvent) => void; + user?: (user: Subscription.UserAppContextObject) => void; + space?: (space: Subscription.SpaceAppContextObject) => void; + membership?: (membership: Subscription.VSPMembershipAppContextObject) => void; +}; diff --git a/lib/types/core/components/push_payload.d.ts b/lib/types/core/components/push_payload.d.ts new file mode 100644 index 000000000..30be0cc7c --- /dev/null +++ b/lib/types/core/components/push_payload.d.ts @@ -0,0 +1,156 @@ +type APNSPayload = { + aps: { + alert?: { + title?: string; + subtitle?: string; + body?: string; + }; + badge?: number | null; + sound?: string; + 'content-available'?: 1; + }; + pn_push: PubNubAPNS2Configuration[]; +}; +type APNS2Configuration = { + collapseId?: string; + expirationDate?: Date; + targets: APNS2Target[]; +}; +type PubNubAPNS2Configuration = { + auth_method: 'token'; + targets: PubNubAPNS2Target[]; + collapse_id?: string; + expiration?: string; + version: 'v2'; +}; +type APNS2Target = { + topic: string; + environment?: 'development' | 'production'; + excludedDevices?: string[]; +}; +type PubNubAPNS2Target = Omit & { + excluded_devices?: string[]; +}; +type FCMPayload = { + notification?: { + title?: string; + body?: string; + icon?: string; + sound?: string; + tag?: string; + }; + data?: { + notification?: FCMPayload['notification']; + }; +}; +declare class BaseNotificationPayload { + protected _title?: string; + protected _subtitle?: string; + protected _sound?: string; + protected _badge?: number | null; + protected _body?: string; + protected _payload: unknown; + constructor(payload: unknown, title?: string, body?: string); + get payload(): unknown; + set title(value: string | undefined); + set subtitle(value: string | undefined); + set body(value: string | undefined); + set badge(value: number | null | undefined); + set sound(value: string | undefined); + protected setDefaultPayloadStructure(): void; + toObject(): unknown; +} +export declare class APNSNotificationPayload extends BaseNotificationPayload { + private _configurations?; + private _apnsPushType; + private _isSilent; + get payload(): APNSPayload; + set configurations(value: APNS2Configuration[]); + get notification(): { + alert?: { + title?: string | undefined; + subtitle?: string | undefined; + body?: string | undefined; + } | undefined; + badge?: number | null | undefined; + sound?: string | undefined; + 'content-available'?: 1 | undefined; + }; + get title(): string | undefined; + set title(value: string | undefined); + get subtitle(): string | undefined; + set subtitle(value: string | undefined); + get body(): string | undefined; + set body(value: string | undefined); + get badge(): number | null | undefined; + set badge(value: number | null | undefined); + get sound(): string | undefined; + set sound(value: string | undefined); + set silent(value: boolean); + protected setDefaultPayloadStructure(): void; + toObject(): APNSPayload | null; + private objectFromAPNS2Configuration; + private objectFromAPNSTarget; +} +export declare class FCMNotificationPayload extends BaseNotificationPayload { + private _isSilent?; + private _icon?; + private _tag?; + get payload(): FCMPayload; + get notification(): { + title?: string | undefined; + body?: string | undefined; + icon?: string | undefined; + sound?: string | undefined; + tag?: string | undefined; + } | undefined; + get data(): { + notification?: { + title?: string | undefined; + body?: string | undefined; + icon?: string | undefined; + sound?: string | undefined; + tag?: string | undefined; + } | undefined; + } | undefined; + get title(): string | undefined; + set title(value: string | undefined); + get body(): string | undefined; + set body(value: string | undefined); + get sound(): string | undefined; + set sound(value: string | undefined); + get icon(): string | undefined; + set icon(value: string | undefined); + get tag(): string | undefined; + set tag(value: string | undefined); + set silent(value: boolean); + protected setDefaultPayloadStructure(): void; + toObject(): FCMPayload | null; +} +declare class NotificationsPayload { + private readonly _payload; + private _debugging?; + private readonly _title; + private _subtitle?; + private readonly _body; + private _badge?; + private _sound?; + apns: APNSNotificationPayload; + fcm: FCMNotificationPayload; + constructor(title: string, body: string); + set debugging(value: boolean); + get title(): string; + get subtitle(): string | undefined; + set subtitle(value: string | undefined); + get body(): string; + get badge(): number | undefined; + set badge(value: number | undefined); + get sound(): string | undefined; + set sound(value: string | undefined); + buildPayload(platforms: string[]): { + pn_apns?: APNSPayload | undefined; + pn_gcm?: FCMPayload | undefined; + pn_debug?: boolean | undefined; + }; +} +export default NotificationsPayload; diff --git a/lib/types/core/components/reconnection_manager.d.ts b/lib/types/core/components/reconnection_manager.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/components/reconnection_manager.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/components/request.d.ts b/lib/types/core/components/request.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/components/request.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/components/stringify_buffer_keys.d.ts b/lib/types/core/components/stringify_buffer_keys.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/components/stringify_buffer_keys.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/components/subject.d.ts b/lib/types/core/components/subject.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/components/subject.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/components/subscription-manager.d.ts b/lib/types/core/components/subscription-manager.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/components/subscription-manager.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/components/token_manager.d.ts b/lib/types/core/components/token_manager.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/components/token_manager.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/components/uuid.d.ts b/lib/types/core/components/uuid.d.ts new file mode 100644 index 000000000..0131316e7 --- /dev/null +++ b/lib/types/core/components/uuid.d.ts @@ -0,0 +1,4 @@ +declare const _default: { + createUUID(): any; +}; +export default _default; diff --git a/lib/types/core/constants/categories.d.ts b/lib/types/core/constants/categories.d.ts new file mode 100644 index 000000000..a56853dae --- /dev/null +++ b/lib/types/core/constants/categories.d.ts @@ -0,0 +1,19 @@ +declare enum StatusCategory { + PNNetworkIssuesCategory = "PNNetworkIssuesCategory", + PNTimeoutCategory = "PNTimeoutCategory", + PNCancelledCategory = "PNCancelledCategory", + PNBadRequestCategory = "PNBadRequestCategory", + PNAccessDeniedCategory = "PNAccessDeniedCategory", + PNValidationErrorCategory = "PNValidationErrorCategory", + PNAcknowledgmentCategory = "PNAcknowledgmentCategory", + PNUnknownCategory = "PNUnknownCategory", + PNNetworkUpCategory = "PNNetworkUpCategory", + PNNetworkDownCategory = "PNNetworkDownCategory", + PNReconnectedCategory = "PNReconnectedCategory", + PNConnectedCategory = "PNConnectedCategory", + PNRequestMessageCountExceededCategory = "PNRequestMessageCountExceededCategory", + PNDisconnectedCategory = "PNDisconnectedCategory", + PNConnectionErrorCategory = "PNConnectionErrorCategory", + PNDisconnectedUnexpectedlyCategory = "PNDisconnectedUnexpectedlyCategory" +} +export default StatusCategory; diff --git a/lib/types/core/constants/operations.d.ts b/lib/types/core/constants/operations.d.ts new file mode 100644 index 000000000..c7b7ec87b --- /dev/null +++ b/lib/types/core/constants/operations.d.ts @@ -0,0 +1,55 @@ +declare enum RequestOperation { + PNPublishOperation = "PNPublishOperation", + PNSignalOperation = "PNSignalOperation", + PNSubscribeOperation = "PNSubscribeOperation", + PNUnsubscribeOperation = "PNUnsubscribeOperation", + PNWhereNowOperation = "PNWhereNowOperation", + PNHereNowOperation = "PNHereNowOperation", + PNGlobalHereNowOperation = "PNGlobalHereNowOperation", + PNSetStateOperation = "PNSetStateOperation", + PNGetStateOperation = "PNGetStateOperation", + PNHeartbeatOperation = "PNHeartbeatOperation", + PNAddMessageActionOperation = "PNAddActionOperation", + PNRemoveMessageActionOperation = "PNRemoveMessageActionOperation", + PNGetMessageActionsOperation = "PNGetMessageActionsOperation", + PNTimeOperation = "PNTimeOperation", + PNHistoryOperation = "PNHistoryOperation", + PNDeleteMessagesOperation = "PNDeleteMessagesOperation", + PNFetchMessagesOperation = "PNFetchMessagesOperation", + PNMessageCounts = "PNMessageCountsOperation", + PNGetAllUUIDMetadataOperation = "PNGetAllUUIDMetadataOperation", + PNGetUUIDMetadataOperation = "PNGetUUIDMetadataOperation", + PNSetUUIDMetadataOperation = "PNSetUUIDMetadataOperation", + PNRemoveUUIDMetadataOperation = "PNRemoveUUIDMetadataOperation", + PNGetAllChannelMetadataOperation = "PNGetAllChannelMetadataOperation", + PNGetChannelMetadataOperation = "PNGetChannelMetadataOperation", + PNSetChannelMetadataOperation = "PNSetChannelMetadataOperation", + PNRemoveChannelMetadataOperation = "PNRemoveChannelMetadataOperation", + PNGetMembersOperation = "PNGetMembersOperation", + PNSetMembersOperation = "PNSetMembersOperation", + PNGetMembershipsOperation = "PNGetMembershipsOperation", + PNSetMembershipsOperation = "PNSetMembershipsOperation", + PNListFilesOperation = "PNListFilesOperation", + PNGenerateUploadUrlOperation = "PNGenerateUploadUrlOperation", + PNPublishFileOperation = "PNPublishFileOperation", + PNPublishFileMessageOperation = "PNPublishFileMessageOperation", + PNGetFileUrlOperation = "PNGetFileUrlOperation", + PNDownloadFileOperation = "PNDownloadFileOperation", + PNDeleteFileOperation = "PNDeleteFileOperation", + PNAddPushNotificationEnabledChannelsOperation = "PNAddPushNotificationEnabledChannelsOperation", + PNRemovePushNotificationEnabledChannelsOperation = "PNRemovePushNotificationEnabledChannelsOperation", + PNPushNotificationEnabledChannelsOperation = "PNPushNotificationEnabledChannelsOperation", + PNRemoveAllPushNotificationsOperation = "PNRemoveAllPushNotificationsOperation", + PNChannelGroupsOperation = "PNChannelGroupsOperation", + PNRemoveGroupOperation = "PNRemoveGroupOperation", + PNChannelsForGroupOperation = "PNChannelsForGroupOperation", + PNAddChannelsToGroupOperation = "PNAddChannelsToGroupOperation", + PNRemoveChannelsFromGroupOperation = "PNRemoveChannelsFromGroupOperation", + PNAccessManagerGrant = "PNAccessManagerGrant", + PNAccessManagerGrantToken = "PNAccessManagerGrantToken", + PNAccessManagerAudit = "PNAccessManagerAudit", + PNAccessManagerRevokeToken = "PNAccessManagerRevokeToken", + PNHandshakeOperation = "PNHandshakeOperation", + PNReceiveMessagesOperation = "PNReceiveMessagesOperation" +} +export default RequestOperation; diff --git a/lib/types/core/endpoints/access_manager/audit.d.ts b/lib/types/core/endpoints/access_manager/audit.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/access_manager/audit.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/access_manager/grant.d.ts b/lib/types/core/endpoints/access_manager/grant.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/access_manager/grant.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/access_manager/grant_token.d.ts b/lib/types/core/endpoints/access_manager/grant_token.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/access_manager/grant_token.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/access_manager/revoke_token.d.ts b/lib/types/core/endpoints/access_manager/revoke_token.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/access_manager/revoke_token.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/actions/add_message_action.d.ts b/lib/types/core/endpoints/actions/add_message_action.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/actions/add_message_action.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/actions/get_message_actions.d.ts b/lib/types/core/endpoints/actions/get_message_actions.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/actions/get_message_actions.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/actions/remove_message_action.d.ts b/lib/types/core/endpoints/actions/remove_message_action.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/actions/remove_message_action.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/channel_groups/add_channels.d.ts b/lib/types/core/endpoints/channel_groups/add_channels.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/channel_groups/add_channels.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/channel_groups/delete_group.d.ts b/lib/types/core/endpoints/channel_groups/delete_group.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/channel_groups/delete_group.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/channel_groups/list_channels.d.ts b/lib/types/core/endpoints/channel_groups/list_channels.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/channel_groups/list_channels.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/channel_groups/list_groups.d.ts b/lib/types/core/endpoints/channel_groups/list_groups.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/channel_groups/list_groups.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/channel_groups/remove_channels.d.ts b/lib/types/core/endpoints/channel_groups/remove_channels.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/channel_groups/remove_channels.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/fetch_messages.d.ts b/lib/types/core/endpoints/fetch_messages.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/fetch_messages.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/file_upload/delete_file.d.ts b/lib/types/core/endpoints/file_upload/delete_file.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/file_upload/delete_file.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/file_upload/download_file.d.ts b/lib/types/core/endpoints/file_upload/download_file.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/file_upload/download_file.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/file_upload/generate_upload_url.d.ts b/lib/types/core/endpoints/file_upload/generate_upload_url.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/file_upload/generate_upload_url.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/file_upload/get_file_url.d.ts b/lib/types/core/endpoints/file_upload/get_file_url.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/file_upload/get_file_url.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/file_upload/list_files.d.ts b/lib/types/core/endpoints/file_upload/list_files.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/file_upload/list_files.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/file_upload/publish_file.d.ts b/lib/types/core/endpoints/file_upload/publish_file.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/file_upload/publish_file.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/file_upload/send_file.d.ts b/lib/types/core/endpoints/file_upload/send_file.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/file_upload/send_file.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/file_upload/upload-file.d.ts b/lib/types/core/endpoints/file_upload/upload-file.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/file_upload/upload-file.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/history/delete_messages.d.ts b/lib/types/core/endpoints/history/delete_messages.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/history/delete_messages.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/history/get_history.d.ts b/lib/types/core/endpoints/history/get_history.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/history/get_history.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/history/message_counts.d.ts b/lib/types/core/endpoints/history/message_counts.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/history/message_counts.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/channel/get.d.ts b/lib/types/core/endpoints/objects/channel/get.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/channel/get.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/channel/get_all.d.ts b/lib/types/core/endpoints/objects/channel/get_all.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/channel/get_all.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/channel/remove.d.ts b/lib/types/core/endpoints/objects/channel/remove.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/channel/remove.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/channel/set.d.ts b/lib/types/core/endpoints/objects/channel/set.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/channel/set.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/member/get.d.ts b/lib/types/core/endpoints/objects/member/get.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/member/get.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/member/set.d.ts b/lib/types/core/endpoints/objects/member/set.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/member/set.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/membership/get.d.ts b/lib/types/core/endpoints/objects/membership/get.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/membership/get.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/membership/set.d.ts b/lib/types/core/endpoints/objects/membership/set.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/membership/set.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/uuid/get.d.ts b/lib/types/core/endpoints/objects/uuid/get.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/uuid/get.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/uuid/get_all.d.ts b/lib/types/core/endpoints/objects/uuid/get_all.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/uuid/get_all.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/uuid/remove.d.ts b/lib/types/core/endpoints/objects/uuid/remove.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/uuid/remove.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/objects/uuid/set.d.ts b/lib/types/core/endpoints/objects/uuid/set.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/objects/uuid/set.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/presence/get_state.d.ts b/lib/types/core/endpoints/presence/get_state.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/presence/get_state.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/presence/heartbeat.d.ts b/lib/types/core/endpoints/presence/heartbeat.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/presence/heartbeat.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/presence/here_now.d.ts b/lib/types/core/endpoints/presence/here_now.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/presence/here_now.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/presence/leave.d.ts b/lib/types/core/endpoints/presence/leave.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/presence/leave.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/presence/set_state.d.ts b/lib/types/core/endpoints/presence/set_state.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/presence/set_state.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/presence/where_now.d.ts b/lib/types/core/endpoints/presence/where_now.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/presence/where_now.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/publish.d.ts b/lib/types/core/endpoints/publish.d.ts new file mode 100644 index 000000000..7b4e99310 --- /dev/null +++ b/lib/types/core/endpoints/publish.d.ts @@ -0,0 +1,15 @@ +import { CryptoModule } from '../interfaces/crypto-module'; +import { Payload } from '../types/api'; +export type PublishParameters = { + channel: string; + message: Payload; + storeInHistory?: boolean; + sendByPost?: boolean; + meta?: Payload; + ttl?: number; + replicate?: boolean; + [key: string]: string | number | boolean | undefined | Payload | CryptoModule; +}; +export type PublishResponse = { + timetoken: string; +}; diff --git a/lib/types/core/endpoints/push/add_push_channels.d.ts b/lib/types/core/endpoints/push/add_push_channels.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/push/add_push_channels.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/push/list_push_channels.d.ts b/lib/types/core/endpoints/push/list_push_channels.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/push/list_push_channels.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/push/push.d.ts b/lib/types/core/endpoints/push/push.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/push/push.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/push/remove_device.d.ts b/lib/types/core/endpoints/push/remove_device.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/push/remove_device.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/push/remove_push_channels.d.ts b/lib/types/core/endpoints/push/remove_push_channels.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/push/remove_push_channels.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/signal.d.ts b/lib/types/core/endpoints/signal.d.ts new file mode 100644 index 000000000..6b739aac8 --- /dev/null +++ b/lib/types/core/endpoints/signal.d.ts @@ -0,0 +1,8 @@ +import { Payload } from '../types/api'; +export type SignalParameters = { + channel: string; + message: Payload; +}; +export type SignalResponse = { + timetoken: string; +}; diff --git a/lib/types/core/endpoints/subscribe.d.ts b/lib/types/core/endpoints/subscribe.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/subscribe.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/subscriptionUtils/handshake.d.ts b/lib/types/core/endpoints/subscriptionUtils/handshake.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/subscriptionUtils/handshake.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/subscriptionUtils/receiveMessages.d.ts b/lib/types/core/endpoints/subscriptionUtils/receiveMessages.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/endpoints/subscriptionUtils/receiveMessages.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/endpoints/time.d.ts b/lib/types/core/endpoints/time.d.ts new file mode 100644 index 000000000..e02a488b9 --- /dev/null +++ b/lib/types/core/endpoints/time.d.ts @@ -0,0 +1,3 @@ +export type TimeResponse = { + timetoken: string; +}; diff --git a/lib/types/core/interfaces/configuration.d.ts b/lib/types/core/interfaces/configuration.d.ts new file mode 100644 index 000000000..b6debb50c --- /dev/null +++ b/lib/types/core/interfaces/configuration.d.ts @@ -0,0 +1,74 @@ +import { PubNubFileConstructor, PubNubFileInterface } from '../types/file'; +import { RequestRetryPolicy } from '../../event-engine/core/retryPolicy'; +import { CryptoModule } from './crypto-module'; +import { Payload } from '../types/api'; +export type UserConfiguration = { + subscribeKey: string; + subscribe_key?: string; + publishKey?: string; + publish_key?: string; + secretKey?: string; + secret_key?: string; + userId?: string; + authKey?: string | null; + logVerbosity?: boolean; + ssl?: boolean; + origin?: string | string[]; + presenceTimeout?: number; + heartbeatInterval?: number; + transactionalRequestTimeout?: number; + subscribeRequestTimeout?: number; + restore?: boolean; + useInstanceId?: boolean; + suppressLeaveEvents?: boolean; + requestMessageCountThreshold?: number; + autoNetworkDetection?: boolean; + enableEventEngine?: boolean; + retryConfiguration?: RequestRetryPolicy; + maintainPresenceState?: boolean; + uuid?: string; + keepAlive?: boolean; + sdkName?: string; + partnerId?: string; +}; +export type PlatformConfiguration = { + sdkFamily: string; + cryptoModule?: CryptoModule; + PubNubFile?: PubNubFileConstructor; + cipherKey?: string; + useRandomIVs?: boolean; + customEncrypt?: (data: string | Payload) => string; + customDecrypt?: (data: string) => string; +}; +export interface ClientConfiguration { + getUserId(): string; + setUserId(value: string): void; + setAuthKey(authKey: string | null): void; + getFilterExpression(): string | undefined | null; + setFilterExpression(expression: string | null | undefined): void; + setCipherKey(key: string | undefined): void; + get version(): string; + getVersion(): string; + _addPnsdkSuffix(name: string, suffix: string | number): void; + getUUID(): string; + setUUID(value: string): void; +} +export interface PrivateClientConfiguration extends ClientConfiguration, Omit { + getAuthKey(): string | undefined | null; + getCryptoModule(): CryptoModule | undefined; + getPresenceTimeout(): number; + setPresenceTimeout(timeout: number): void; + getHeartbeatInterval(): number | undefined; + setHeartbeatInterval(interval: number): void; + getTransactionTimeout(): number; + getSubscribeTimeout(): number; + get PubNubFile(): PubNubFileConstructor | undefined; + get instanceId(): string | undefined; + get sdkFamily(): string; + _getPnsdkSuffix(separator: string): string; + getCipherKey(): string | undefined; + getUseRandomIVs(): boolean | undefined; + getCustomEncrypt(): ((data: string | Payload) => string) | undefined; + getCustomDecrypt(): ((data: string) => string) | undefined; +} +export declare const setDefaults: (configuration: UserConfiguration) => ExtendedConfiguration; diff --git a/lib/types/core/interfaces/crypto-module.d.ts b/lib/types/core/interfaces/crypto-module.d.ts new file mode 100644 index 000000000..8629730da --- /dev/null +++ b/lib/types/core/interfaces/crypto-module.d.ts @@ -0,0 +1,33 @@ +import { PubNubFileConstructor, PubNubFileInterface } from '../types/file'; +import { Payload } from '../types/api'; +export type CryptoModuleConfiguration = { + default: C; + cryptors?: C[]; +}; +export type CryptorConfiguration = { + cipherKey?: string; + secretKey?: string; + useRandomIVs?: boolean; + customEncrypt?: (data: string | Payload) => string; + customDecrypt?: (data: string) => string; +}; +export interface CryptoModule { + encrypt(data: ArrayBuffer | string): ArrayBuffer | string; + encryptFile(file: PubNubFileInterface, File: PubNubFileConstructor): Promise; + decrypt(data: ArrayBuffer | string): ArrayBuffer | Payload | null; + decryptFile(file: PubNubFileInterface, File: PubNubFileConstructor): Promise; +} +export declare abstract class AbstractCryptoModule implements CryptoModule { + protected static encoder: TextEncoder; + protected static decoder: TextDecoder; + defaultCryptor: C; + cryptors: C[]; + static legacyCryptoModule(config: CryptorConfiguration): CryptoModule; + static aesCbcCryptoModule(config: CryptorConfiguration): CryptoModule; + constructor(configuration: CryptoModuleConfiguration); + abstract encrypt(data: ArrayBuffer | string): ArrayBuffer | string; + abstract encryptFile(file: PubNubFileInterface, File: PubNubFileConstructor): Promise; + abstract decrypt(data: ArrayBuffer | string): ArrayBuffer | Payload | null; + abstract decryptFile(file: PubNubFileInterface, File: PubNubFileConstructor): Promise; + protected getAllCryptors(): C[]; +} diff --git a/lib/types/core/interfaces/cryptography.d.ts b/lib/types/core/interfaces/cryptography.d.ts new file mode 100644 index 000000000..cfdfb1a2c --- /dev/null +++ b/lib/types/core/interfaces/cryptography.d.ts @@ -0,0 +1,7 @@ +import { PubNubFileConstructor, PubNubFileInterface } from '../types/file'; +export interface Cryptography { + encrypt(key: string, input: Types): Promise; + decrypt(key: string, input: Types): Promise; + encryptFile(key: string, file: PubNubFileInterface, File: PubNubFileConstructor): Promise; + decryptFile(key: string, file: PubNubFileInterface, File: PubNubFileConstructor): Promise; +} diff --git a/lib/types/core/interfaces/request.d.ts b/lib/types/core/interfaces/request.d.ts new file mode 100644 index 000000000..cb0ff5c3b --- /dev/null +++ b/lib/types/core/interfaces/request.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/lib/types/core/interfaces/transport.d.ts b/lib/types/core/interfaces/transport.d.ts new file mode 100644 index 000000000..1b081f700 --- /dev/null +++ b/lib/types/core/interfaces/transport.d.ts @@ -0,0 +1,12 @@ +import { CancellationController, TransportRequest } from '../types/transport-request'; +import { TransportResponse } from '../types/transport-response'; +export type TransportKeepAlive = { + keepAliveMsecs?: number; + maxSockets?: number; + maxFreeSockets?: number; + timeout?: number; +}; +export interface Transport { + makeSendable(req: TransportRequest): [Promise, CancellationController | undefined]; + request(req: TransportRequest): TransportRequest; +} diff --git a/lib/types/core/pubnub-channel-groups.d.ts b/lib/types/core/pubnub-channel-groups.d.ts new file mode 100644 index 000000000..efcecac4d --- /dev/null +++ b/lib/types/core/pubnub-channel-groups.d.ts @@ -0,0 +1,17 @@ +import { KeySet, ResultCallback, SendRequestFunction, StatusCallback } from './types/api'; +import * as ChannelGroups from './types/api/channel-groups'; +export default class PubnubChannelGroups { + private readonly keySet; + private readonly sendRequest; + constructor(keySet: KeySet, sendRequest: SendRequestFunction); + listChannels(parameters: ChannelGroups.ListChannelGroupChannelsParameters, callback: ResultCallback): void; + listChannels(parameters: ChannelGroups.ListChannelGroupChannelsParameters): Promise; + listGroups(callback: ResultCallback): void; + listGroups(): Promise; + addChannels(parameters: ChannelGroups.ManageChannelGroupChannelsParameters, callback: StatusCallback): void; + addChannels(parameters: ChannelGroups.ManageChannelGroupChannelsParameters): Promise>; + removeChannels(parameters: ChannelGroups.ManageChannelGroupChannelsParameters, callback: StatusCallback): void; + removeChannels(parameters: ChannelGroups.ManageChannelGroupChannelsParameters): Promise>; + deleteGroup(parameters: ChannelGroups.DeleteChannelGroupParameters, callback: StatusCallback): void; + deleteGroup(parameters: ChannelGroups.DeleteChannelGroupParameters): Promise>; +} diff --git a/lib/types/core/pubnub-common.d.ts b/lib/types/core/pubnub-common.d.ts new file mode 100644 index 000000000..02fea41d4 --- /dev/null +++ b/lib/types/core/pubnub-common.d.ts @@ -0,0 +1,230 @@ +import { Listener } from './components/listener_manager'; +import NotificationsPayload from './components/push_payload'; +import { TokenManager } from './components/token_manager'; +import Crypto from './components/cryptography/index'; +import { Payload, ResultCallback } from './types/api'; +import { ClientConfiguration, PrivateClientConfiguration } from './interfaces/configuration'; +import { Cryptography } from './interfaces/cryptography'; +import { Transport } from './interfaces/transport'; +import RequestOperation from './constants/operations'; +import StatusCategory from './constants/categories'; +import { RetryPolicy } from '../event-engine/core/retryPolicy'; +import * as Publish from './endpoints/publish'; +import * as Signal from './endpoints/signal'; +import * as Subscription from './types/api/subscription'; +import * as Presence from './types/api/presence'; +import * as History from './types/api/history'; +import * as MessageAction from './types/api/message-action'; +import * as FileSharing from './types/api/file-sharing'; +import { PubNubFileInterface } from './types/file'; +import * as PAM from './types/api/access-panager'; +import { SubscriptionOptions } from '../entities/commonTypes'; +import { ChannelMetadata } from '../entities/ChannelMetadata'; +import { SubscriptionSet } from '../entities/SubscriptionSet'; +import { ChannelGroup } from '../entities/ChannelGroup'; +import { UserMetadata } from '../entities/UserMetadata'; +import { Channel } from '../entities/Channel'; +import PubNubChannelGroups from './pubnub-channel-groups'; +import PubNubPushNotifications from './pubnub-push'; +import * as AppContext from './types/api/app-context'; +import PubNubObjects from './pubnub-objects'; +import * as Time from './endpoints/time'; +type ClientInstanceConfiguration = { + configuration: PrivateClientConfiguration; + transport: Transport; + tokenManager: TokenManager; + cryptography?: Cryptography; + crypto?: Crypto; +}; +export declare class PubNubCore = Record> { + static OPERATIONS: typeof RequestOperation; + static CATEGORIES: typeof StatusCategory; + static ExponentialRetryPolicy: typeof RetryPolicy.ExponentialRetryPolicy; + static LinearRetryPolicy: typeof RetryPolicy.LinearRetryPolicy; + static notificationPayload(title: string, body: string): NotificationsPayload; + static generateUUID(): any; + constructor(configuration: ClientInstanceConfiguration); + get configuration(): ClientConfiguration; + get _config(): ClientConfiguration; + get authKey(): string | undefined; + getAuthKey(): string | undefined; + setAuthKey(authKey: string): void; + get userId(): string; + set userId(value: string); + getUserId(): string; + setUserId(value: string): void; + get filterExpression(): string | undefined; + getFilterExpression(): string | undefined; + set filterExpression(expression: string | null | undefined); + setFilterExpression(expression: string | null): void; + get cipherKey(): string | undefined; + set cipherKey(key: string | undefined); + setCipherKey(key: string): void; + set heartbeatInterval(interval: number); + setHeartbeatInterval(interval: number): void; + getVersion(): string; + _addPnsdkSuffix(name: string, suffix: string | number): void; + getUUID(): string; + setUUID(value: string): void; + get customEncrypt(): ((data: string) => string) | undefined; + get customDecrypt(): ((data: string) => string) | undefined; + channel(name: string): Channel; + channelGroup(name: string): ChannelGroup; + channelMetadata(id: string): ChannelMetadata; + userMetadata(id: string): UserMetadata; + subscriptionSet(parameters: { + channels?: string[]; + channelGroups?: string[]; + subscriptionOptions?: SubscriptionOptions; + }): SubscriptionSet; + private sendRequest; + destroy(isOffline?: boolean): void; + stop(): void; + addListener(listener: Listener): void; + removeListener(listener: Listener): void; + removeAllListeners(): void; + publish(parameters: Publish.PublishParameters, callback: ResultCallback): void; + publish(parameters: Publish.PublishParameters): Promise; + signal(parameters: Signal.SignalParameters, callback: ResultCallback): void; + signal(parameters: Signal.SignalParameters): Promise; + fire(parameters: Publish.PublishParameters, callback: ResultCallback): void; + fire(parameters: Publish.PublishParameters): Promise; + getSubscribedChannels(): string[]; + getSubscribedChannelGroups(): string[]; + subscribe(parameters: Subscription.SubscribeParameters): void; + private makeSubscribe; + unsubscribe(parameters: Presence.PresenceLeaveParameters): void; + private makeUnsubscribe; + unsubscribeAll(): void; + disconnect(): void; + reconnect(parameters?: { + timetoken?: string; + region?: number; + }): void; + private subscribeHandshake; + private subscribeReceiveMessages; + getMessageActions(parameters: MessageAction.GetMessageActionsParameters, callback: ResultCallback): void; + getMessageActions(parameters: MessageAction.GetMessageActionsParameters): Promise; + addMessageAction(parameters: MessageAction.AddMessageActionParameters, callback: ResultCallback): void; + addMessageAction(parameters: MessageAction.AddMessageActionParameters): Promise; + removeMessageAction(parameters: MessageAction.RemoveMessageActionParameters, callback: ResultCallback): void; + removeMessageAction(parameters: MessageAction.RemoveMessageActionParameters): Promise; + fetchMessages(parameters: History.FetchMessagesParameters, callback: ResultCallback): void; + fetchMessages(parameters: History.FetchMessagesParameters): Promise; + deleteMessages(parameters: History.DeleteMessagesParameters, callback: ResultCallback): void; + deleteMessages(parameters: History.DeleteMessagesParameters): Promise; + messageCounts(parameters: History.MessageCountParameters, callback: ResultCallback): void; + messageCounts(parameters: History.MessageCountParameters): Promise; + history(parameters: History.GetHistoryParameters, callback: ResultCallback): void; + history(parameters: History.GetHistoryParameters): Promise; + hereNow(parameters: Presence.HereNowParameters, callback: ResultCallback): void; + hereNow(parameters: Presence.HereNowParameters): Promise; + whereNow(parameters: Presence.WhereNowParameters, callback: ResultCallback): void; + whereNow(parameters: Presence.WhereNowParameters): Promise; + getState(parameters: Presence.GetPresenceStateParameters, callback: ResultCallback): void; + getState(parameters: Presence.GetPresenceStateParameters): Promise; + setState(parameters: Presence.SetPresenceStateParameters | Presence.SetPresenceStateWithHeartbeatParameters, callback: ResultCallback): void; + setState(parameters: Presence.SetPresenceStateParameters | Presence.SetPresenceStateWithHeartbeatParameters): Promise; + presence(parameters: { + connected: boolean; + channels?: string[]; + channelGroups?: string[]; + }): void; + private heartbeat; + private join; + private leave; + private leaveAll; + grantToken(parameters: PAM.GrantTokenParameters, callback: ResultCallback): void; + grantToken(parameters: PAM.GrantTokenParameters): Promise; + revokeToken(parameters: PAM.RevokeParameters, callback: ResultCallback): void; + revokeToken(parameters: PAM.RevokeParameters): Promise; + get token(): string | undefined; + getToken(): string | undefined; + set token(token: string | undefined); + setToken(token: string | undefined): void; + parseToken(token: string): { + version: number; + timestamp: number; + ttl: number; + resources?: Partial>> | undefined; + patterns?: Partial>> | undefined; + authorized_uuid?: string | undefined; + signature: ArrayBuffer; + meta?: Payload | undefined; + } | undefined; + grant(parameters: PAM.GrantParameters, callback: ResultCallback): void; + grant(parameters: PAM.GrantParameters): Promise; + audit(parameters: PAM.AuditParameters, callback: ResultCallback): void; + audit(parameters: PAM.AuditParameters): Promise; + get objects(): PubNubObjects; + fetchUsers(callback: ResultCallback>): void; + fetchUsers(parameters: AppContext.GetAllMetadataParameters>, callback: ResultCallback>): void; + fetchUsers(parameters?: AppContext.GetAllMetadataParameters>): Promise>; + fetchUser(callback: ResultCallback>): void; + fetchUser(parameters: AppContext.GetUUIDMetadataParameters, callback: ResultCallback>): void; + fetchUser(parameters?: AppContext.GetUUIDMetadataParameters): Promise>; + createUser(parameters: AppContext.SetUUIDMetadataParameters, callback: ResultCallback>): void; + createUser(parameters: AppContext.SetUUIDMetadataParameters): Promise>; + updateUser(parameters: AppContext.SetUUIDMetadataParameters, callback: ResultCallback>): void; + updateUser(parameters: AppContext.SetUUIDMetadataParameters): Promise>; + removeUser(callback: ResultCallback): void; + removeUser(parameters: AppContext.RemoveUUIDMetadataParameters, callback: ResultCallback): void; + removeUser(parameters?: AppContext.RemoveUUIDMetadataParameters): Promise; + fetchSpaces(callback: ResultCallback>): void; + fetchSpaces(parameters: AppContext.GetAllMetadataParameters>, callback: ResultCallback>): void; + fetchSpaces(parameters?: AppContext.GetAllMetadataParameters>): Promise>; + fetchSpace(parameters: AppContext.GetChannelMetadataParameters, callback: ResultCallback>): void; + fetchSpace(parameters: AppContext.GetChannelMetadataParameters): Promise>; + createSpace(parameters: AppContext.SetChannelMetadataParameters, callback: ResultCallback>): void; + createSpace(parameters: AppContext.SetChannelMetadataParameters): Promise>; + updateSpace(parameters: AppContext.SetChannelMetadataParameters, callback: ResultCallback>): void; + updateSpace(parameters: AppContext.SetChannelMetadataParameters): Promise>; + removeSpace(parameters: AppContext.RemoveChannelMetadataParameters, callback: ResultCallback): void; + removeSpace(parameters: AppContext.RemoveChannelMetadataParameters): Promise; + fetchMemberships(parameters: AppContext.GetMembershipsParameters | AppContext.GetMembersParameters, callback: ResultCallback | AppContext.UserMembersResponse>): void; + fetchMemberships(parameters: AppContext.GetMembershipsParameters | AppContext.GetMembersParameters): Promise | AppContext.UserMembersResponse>; + addMemberships(parameters: AppContext.SetMembershipsParameters | AppContext.SetChannelMembersParameters, callback: ResultCallback | AppContext.SetMembersResponse>): void; + addMemberships(parameters: AppContext.SetMembershipsParameters | AppContext.SetChannelMembersParameters): Promise | AppContext.SetMembersResponse>; + updateMemberships(parameters: AppContext.SetMembershipsParameters | AppContext.SetChannelMembersParameters, callback: ResultCallback | AppContext.SetMembersResponse>): void; + updateMemberships(parameters: AppContext.SetMembershipsParameters | AppContext.SetChannelMembersParameters): Promise | AppContext.SetMembersResponse>; + removeMemberships(parameters: AppContext.RemoveMembersParameters | AppContext.RemoveMembershipsParameters, callback: ResultCallback | AppContext.RemoveMembershipsResponse>): void; + removeMemberships(parameters: AppContext.RemoveMembersParameters | AppContext.RemoveMembershipsParameters): Promise>; + get channelGroups(): PubNubChannelGroups; + get push(): PubNubPushNotifications; + sendFile(parameters: FileSharing.SendFileParameters, callback: ResultCallback): void; + sendFile(parameters: FileSharing.SendFileParameters): Promise; + publishFile(parameters: FileSharing.PublishFileMessageParameters, callback: ResultCallback): void; + publishFile(parameters: FileSharing.PublishFileMessageParameters): Promise; + listFiles(parameters: FileSharing.ListFilesParameters, callback: ResultCallback): void; + listFiles(parameters: FileSharing.ListFilesParameters): Promise; + getFileUrl(parameters: FileSharing.FileUrlParameters): FileSharing.FileUrlResponse; + downloadFile(parameters: FileSharing.DownloadFileParameters, callback: ResultCallback): void; + downloadFile(parameters: FileSharing.DownloadFileParameters): Promise; + deleteFile(parameters: FileSharing.DeleteFileParameters, callback: ResultCallback): void; + deleteFile(parameters: FileSharing.DeleteFileParameters): Promise; + time(callback: ResultCallback): void; + time(): Promise; + encrypt(data: string | Payload, customCipherKey?: string): string; + decrypt(data: string, customCipherKey?: string): Payload | null; + encryptFile(file: PubNubFileInterface): Promise; + encryptFile(key: string, file: PubNubFileInterface): Promise; + decryptFile(file: PubNubFileInterface): Promise; + decryptFile(key: string | PubNubFileInterface, file?: PubNubFileInterface): Promise; +} +export {}; diff --git a/lib/types/core/pubnub-objects.d.ts b/lib/types/core/pubnub-objects.d.ts new file mode 100644 index 000000000..5dc0b3e44 --- /dev/null +++ b/lib/types/core/pubnub-objects.d.ts @@ -0,0 +1,52 @@ +import { ResultCallback, SendRequestFunction } from './types/api'; +import { PrivateClientConfiguration } from './interfaces/configuration'; +import * as AppContext from './types/api/app-context'; +export default class PubNubObjects { + private readonly configuration; + private readonly sendRequest; + private readonly keySet; + constructor(configuration: PrivateClientConfiguration, sendRequest: SendRequestFunction); + getAllUUIDMetadata(callback: ResultCallback>): void; + getAllUUIDMetadata(parameters: AppContext.GetAllMetadataParameters>, callback: ResultCallback>): void; + getAllUUIDMetadata(parameters?: AppContext.GetAllMetadataParameters>): Promise>; + _getAllUUIDMetadata(parametersOrCallback?: AppContext.GetAllMetadataParameters> | ResultCallback>, callback?: ResultCallback>): Promise | void>; + getUUIDMetadata(callback: ResultCallback>): void; + getUUIDMetadata(parameters: AppContext.GetUUIDMetadataParameters, callback: ResultCallback>): void; + getUUIDMetadata(parameters?: AppContext.GetUUIDMetadataParameters): Promise>; + _getUUIDMetadata(parametersOrCallback?: AppContext.GetUUIDMetadataParameters | ResultCallback>, callback?: ResultCallback>): Promise | void>; + setUUIDMetadata(parameters: AppContext.SetUUIDMetadataParameters, callback: ResultCallback>): void; + setUUIDMetadata(parameters: AppContext.SetUUIDMetadataParameters): Promise>; + _setUUIDMetadata(parameters: AppContext.SetUUIDMetadataParameters, callback?: ResultCallback>): Promise | void>; + removeUUIDMetadata(callback: ResultCallback): void; + removeUUIDMetadata(parameters: AppContext.RemoveUUIDMetadataParameters, callback: ResultCallback): void; + removeUUIDMetadata(parameters?: AppContext.RemoveUUIDMetadataParameters): Promise; + _removeUUIDMetadata(parametersOrCallback?: AppContext.RemoveUUIDMetadataParameters | ResultCallback, callback?: ResultCallback): Promise; + getAllChannelMetadata(callback: ResultCallback>): void; + getAllChannelMetadata(parameters: AppContext.GetAllMetadataParameters>, callback: ResultCallback>): void; + getAllChannelMetadata(parameters?: AppContext.GetAllMetadataParameters>): Promise>; + _getAllChannelMetadata(parametersOrCallback?: AppContext.GetAllMetadataParameters> | ResultCallback>, callback?: ResultCallback>): Promise | void>; + getChannelMetadata(parameters: AppContext.GetChannelMetadataParameters, callback: ResultCallback>): void; + getChannelMetadata(parameters: AppContext.GetChannelMetadataParameters): Promise>; + _getChannelMetadata(parameters: AppContext.GetChannelMetadataParameters, callback?: ResultCallback>): Promise | void>; + setChannelMetadata(parameters: AppContext.SetChannelMetadataParameters, callback: ResultCallback>): void; + setChannelMetadata(parameters: AppContext.SetChannelMetadataParameters): Promise>; + _setChannelMetadata(parameters: AppContext.SetChannelMetadataParameters, callback?: ResultCallback>): Promise | void>; + removeChannelMetadata(parameters: AppContext.RemoveChannelMetadataParameters, callback: ResultCallback): void; + removeChannelMetadata(parameters: AppContext.RemoveChannelMetadataParameters): Promise; + _removeChannelMetadata(parameters: AppContext.RemoveChannelMetadataParameters, callback?: ResultCallback): Promise; + getChannelMembers(parameters: AppContext.GetMembersParameters, callback: ResultCallback>): void; + getChannelMembers(parameters: AppContext.GetMembersParameters): Promise>; + setChannelMembers(parameters: AppContext.SetChannelMembersParameters, callback: ResultCallback>): void; + setChannelMembers(parameters: AppContext.SetChannelMembersParameters): Promise>; + removeChannelMembers(parameters: AppContext.RemoveMembersParameters, callback: ResultCallback>): void; + removeChannelMembers(parameters: AppContext.RemoveMembersParameters): Promise>; + getMemberships(callback: ResultCallback>): void; + getMemberships(parameters: AppContext.GetMembershipsParameters, callback: ResultCallback>): void; + getMemberships(parameters?: AppContext.GetMembershipsParameters): Promise>; + setMemberships(parameters: AppContext.SetMembershipsParameters, callback: ResultCallback>): void; + setMemberships(parameters: AppContext.SetMembershipsParameters): Promise>; + removeMemberships(parameters: AppContext.RemoveMembershipsParameters, callback: ResultCallback>): void; + removeMemberships(parameters: AppContext.RemoveMembershipsParameters): Promise>; + fetchMemberships(parameters: AppContext.GetMembershipsParameters | AppContext.GetMembersParameters, callback?: ResultCallback | AppContext.UserMembersResponse>): Promise | AppContext.UserMembersResponse | void>; + addMemberships(parameters: AppContext.SetMembershipsParameters | AppContext.SetChannelMembersParameters, callback?: ResultCallback | AppContext.SetMembersResponse>): Promise | AppContext.SetMembersResponse | void>; +} diff --git a/lib/types/core/pubnub-push.d.ts b/lib/types/core/pubnub-push.d.ts new file mode 100644 index 000000000..32bd72558 --- /dev/null +++ b/lib/types/core/pubnub-push.d.ts @@ -0,0 +1,15 @@ +import { KeySet, ResultCallback, SendRequestFunction, StatusCallback } from './types/api'; +import * as Push from './types/api/push'; +export default class PubNubPushNotifications { + private readonly keySet; + private readonly sendRequest; + constructor(keySet: KeySet, sendRequest: SendRequestFunction); + listChannels(parameters: Push.ListDeviceChannelsParameters, callback: ResultCallback): void; + listChannels(parameters: Push.ListDeviceChannelsParameters): Promise; + addChannels(parameters: Push.ManageDeviceChannelsParameters, callback: StatusCallback): void; + addChannels(parameters: Push.ManageDeviceChannelsParameters): Promise; + removeChannels(parameters: Push.ManageDeviceChannelsParameters, callback: StatusCallback): void; + removeChannels(parameters: Push.ManageDeviceChannelsParameters): Promise; + deleteDevice(parameters: Push.RemoveDeviceParameters, callback: StatusCallback): void; + deleteDevice(parameters: Push.RemoveDeviceParameters): Promise; +} diff --git a/lib/types/core/types/api/access-panager.d.ts b/lib/types/core/types/api/access-panager.d.ts new file mode 100644 index 000000000..70ad4f31e --- /dev/null +++ b/lib/types/core/types/api/access-panager.d.ts @@ -0,0 +1,124 @@ +export type Metadata = Record; +export type ChannelTokenPermissions = { + read?: boolean; + write?: boolean; + get?: boolean; + manage?: boolean; + update?: boolean; + join?: boolean; + delete?: boolean; +}; +type SpaceTokenPermissions = ChannelTokenPermissions; +export type ChannelGroupTokenPermissions = { + read?: boolean; + manage?: boolean; +}; +export type UuidTokenPermissions = { + get?: boolean; + update?: boolean; + delete?: boolean; +}; +type UserTokenPermissions = UuidTokenPermissions; +export type ObjectsGrantTokenParameters = { + ttl: number; + resources?: { + spaces?: Record; + users?: Record; + }; + patterns?: { + spaces?: Record; + users?: Record; + }; + meta?: Metadata; + authorizedUserId?: string; +}; +export type GrantTokenParameters = { + ttl: number; + resources?: { + uuids?: Record; + channels?: Record; + groups?: Record; + }; + patterns?: { + uuids?: Record; + channels?: Record; + groups?: Record; + }; + meta?: Metadata; + authorized_uuid?: string; +}; +export type GrantTokenResponse = string; +export type RevokeParameters = { + token: string; +}; +export type RevokeTokenResponse = Record; +type ChannelPermissions = { + r?: 0 | 1; + w?: 0 | 1; + d?: 0 | 1; + g?: 0 | 1; + u?: 0 | 1; + m?: 0 | 1; + j?: 0 | 1; + ttl?: number; +}; +type ChannelGroupPermissions = { + r?: 0 | 1; + m?: 0 | 1; + ttl?: number; +}; +type UserPermissions = { + g?: 0 | 1; + u?: 0 | 1; + d?: 0 | 1; + ttl?: number; +}; +type BaseAuditResponse = { + level: Level; + subscribe_key: string; + ttl?: number; +}; +type AuthKeysPermissions = { + auths: Record; +}; +type ChannelPermissionsResponse = BaseAuditResponse<'channel+auth'> & { + channel: string; +} & AuthKeysPermissions; +type ChannelsPermissionsResponse = BaseAuditResponse<'channel'> & { + channels: Record>; +}; +type ChannelGroupPermissionsResponse = BaseAuditResponse<'channel-group+auth'> & { + 'channel-group': string; +} & AuthKeysPermissions; +type ChannelGroupsPermissionsResponse = BaseAuditResponse<'channel'> & { + 'channel-groups': Record>; +}; +type UserPermissionsResponse = BaseAuditResponse<'user'> & { + channel: string; +} & AuthKeysPermissions; +type SubKeyPermissionsResponse = BaseAuditResponse<'subkey'> & { + channels: Record>; + 'channel-groups': Record>; + objects: Record>; +}; +export type PermissionsResponse = ChannelPermissionsResponse | ChannelsPermissionsResponse | ChannelGroupPermissionsResponse | ChannelGroupsPermissionsResponse | UserPermissionsResponse | SubKeyPermissionsResponse; +export type AuditParameters = { + channel?: string; + channelGroup?: string; + authKeys?: string[]; +}; +export type GrantParameters = { + channels?: string[]; + channelGroups?: string[]; + uuids?: string[]; + authKeys?: string[]; + read?: boolean; + write?: boolean; + delete?: boolean; + get?: boolean; + update?: boolean; + manage?: boolean; + join?: boolean; + ttl?: number; +}; +export {}; diff --git a/lib/types/core/types/api/app-context.d.ts b/lib/types/core/types/api/app-context.d.ts new file mode 100644 index 000000000..eea32fe4e --- /dev/null +++ b/lib/types/core/types/api/app-context.d.ts @@ -0,0 +1,207 @@ +type PartialNullable = { + [P in keyof T]?: T[P] | null; +}; +export type CustomData = { + [key: string]: string | number | boolean | null; +}; +type ObjectParameters = { + custom?: Custom; +}; +export type ObjectData = { + id: string; + updated: string; + eTag: string; + custom?: Custom | null; +}; +type ObjectsRelation = { + id: string; + status?: string; + custom?: Custom; +}; +type Page = { + next?: string; + prev?: string; +}; +type IncludeOptions = { + totalCount?: boolean; + customFields?: boolean; +}; +type MembershipsIncludeOptions = IncludeOptions & { + channelFields?: boolean; + customChannelFields?: boolean; + statusField?: boolean; + channelStatusField?: boolean; + channelTypeField?: boolean; +}; +type MembersIncludeOptions = IncludeOptions & { + UUIDFields?: boolean; + customUUIDFields?: boolean; + statusField?: boolean; + UUIDStatusField?: boolean; + UUIDTypeField?: boolean; +}; +type PagedRequestParameters = { + include?: Include; + filter?: string; + sort?: Sort; + limit?: number; + page?: Page; +}; +type ObjectResponse = { + status: number; + data: ObjectType; +}; +type PagedResponse = ObjectResponse & { + totalCount?: number; + next?: string; + prev?: string; +}; +type MetadataSortingOptions = keyof Omit | ({ + [K in keyof Omit]?: 'asc' | 'desc' | null; +} & { + [key: `custom.${string}`]: 'asc' | 'desc' | null; +}); +type MembershipsSortingOptions = 'channel.id' | 'channel.name' | 'channel.description' | 'channel.updated' | 'space.id' | 'space.name' | 'space.description' | 'space.updated' | 'updated' | { + 'channel.id'?: 'asc' | 'desc' | null; + 'channel.name'?: 'asc' | 'desc' | null; + 'channel.description'?: 'asc' | 'desc' | null; + 'channel.updated'?: 'asc' | 'desc' | null; + 'space.id'?: 'asc' | 'desc' | null; + 'space.name'?: 'asc' | 'desc' | null; + 'space.description'?: 'asc' | 'desc' | null; + 'space.updated'?: 'asc' | 'desc' | null; + updated?: 'asc' | 'desc' | null; +}; +type MembersSortingOptions = 'uuid.id' | 'uuid.name' | 'uuid.updated' | 'user.id' | 'user.name' | 'user.updated' | 'updated' | { + 'uuid.id'?: 'asc' | 'desc' | null; + 'uuid.name'?: 'asc' | 'desc' | null; + 'uuid.updated'?: 'asc' | 'desc' | null; + 'user.id'?: 'asc' | 'desc' | null; + 'user.name'?: 'asc' | 'desc' | null; + 'user.updated'?: 'asc' | 'desc' | null; + updated?: 'asc' | 'desc' | null; +}; +export type GetAllMetadataParameters = PagedRequestParameters>; +type UUIDMetadataFields = { + name?: string; + email?: string; + externalId?: string; + profileUrl?: string; + type?: string; + status?: string; +}; +type UUIDMetadata = ObjectParameters & Partial; +export type UUIDMetadataObject = ObjectData & PartialNullable; +export type GetAllUUIDMetadataResponse = PagedResponse>; +export type GetUUIDMetadataParameters = { + uuid?: string; + userId?: string; + include?: Omit; +}; +export type GetUUIDMetadataResponse = ObjectResponse>; +export type SetUUIDMetadataParameters = { + uuid?: string; + userId?: string; + data: UUIDMetadata; + include?: Omit; +}; +export type SetUUIDMetadataResponse = ObjectResponse>; +export type RemoveUUIDMetadataParameters = { + uuid?: string; + userId?: string; +}; +export type RemoveUUIDMetadataResponse = ObjectResponse>; +type ChannelMetadataFields = { + name?: string; + description?: string; + type?: string; + status?: string; +}; +type ChannelMetadata = ObjectParameters & Partial; +export type ChannelMetadataObject = ObjectData & PartialNullable; +export type GetAllChannelMetadataResponse = PagedResponse>; +export type GetChannelMetadataParameters = { + channel: string; + spaceId?: string; + include?: Omit; +}; +export type GetChannelMetadataResponse = ObjectResponse>; +export type SetChannelMetadataParameters = { + channel: string; + spaceId?: string; + data: ChannelMetadata; + include?: Omit; +}; +export type SetChannelMetadataResponse = ObjectResponse>; +export type RemoveChannelMetadataParameters = { + channel: string; + spaceId?: string; +}; +export type RemoveChannelMetadataResponse = ObjectResponse>; +type MembershipsObject = Omit, 'id'> & { + channel: ChannelMetadataObject | { + id: string; + }; +}; +type MembershipsResponse = PagedResponse>; +export type GetMembershipsParameters = PagedRequestParameters & { + uuid?: string; + userId?: string; +}; +export type GetMembershipsResponse = MembershipsResponse; +export type SetMembershipsParameters = PagedRequestParameters, MembershipsSortingOptions> & { + uuid?: string; + userId?: string; + channels: Array>; + spaces?: Array, 'id'> & { + spaceId: string; + })>; +}; +export type SetMembershipsResponse = MembershipsResponse; +export type RemoveMembershipsParameters = PagedRequestParameters & { + uuid?: string; + userId?: string; + channels: string[]; + spaceIds?: string[]; +}; +export type RemoveMembershipsResponse = MembershipsResponse; +type MembersObject = Omit, 'id'> & { + uuid: UUIDMetadataObject | { + id: string; + }; +}; +type MembersResponse = PagedResponse>; +export type GetMembersParameters = PagedRequestParameters & { + channel: string; + spaceId?: string; +}; +export type GetMembersResponse = MembersResponse; +export type SetChannelMembersParameters = PagedRequestParameters, MembersSortingOptions> & { + channel: string; + spaceId?: string; + uuids: Array>; + users?: Array, 'id'> & { + userId: string; + })>; +}; +export type SetMembersResponse = MembersResponse; +export type RemoveMembersParameters = PagedRequestParameters & { + channel: string; + spaceId?: string; + uuids: string[]; + userIds?: string[]; +}; +export type RemoveMembersResponse = MembersResponse; +type UserMembersObject = Omit, 'id'> & { + user: UUIDMetadataObject | { + id: string; + }; +}; +export type UserMembersResponse = PagedResponse>; +type SpaceMembershipObject = Omit, 'id'> & { + space: ChannelMetadataObject | { + id: string; + }; +}; +export type SpaceMembershipsResponse = PagedResponse>; +export {}; diff --git a/lib/types/core/types/api/channel-groups.d.ts b/lib/types/core/types/api/channel-groups.d.ts new file mode 100644 index 000000000..c2408d009 --- /dev/null +++ b/lib/types/core/types/api/channel-groups.d.ts @@ -0,0 +1,18 @@ +export type ManageChannelGroupChannelsParameters = { + channelGroup: string; + channels: string[]; +}; +export type ManageChannelGroupChannelsResponse = Record; +export type ListAllChannelGroupsResponse = { + groups: string[]; +}; +export type ListChannelGroupChannelsParameters = { + channelGroup: string; +}; +export type ListChannelGroupChannelsResponse = { + channels: string[]; +}; +export type DeleteChannelGroupParameters = { + channelGroup: string; +}; +export type DeleteChannelGroupResponse = Record; diff --git a/lib/types/core/types/api/file-sharing.d.ts b/lib/types/core/types/api/file-sharing.d.ts new file mode 100644 index 000000000..dbc5552a4 --- /dev/null +++ b/lib/types/core/types/api/file-sharing.d.ts @@ -0,0 +1,85 @@ +import { PubNubFileInterface } from '../file'; +import { Payload } from './index'; +export type SharedFile = { + name: string; + id: string; + size: number; + created: string; +}; +export type ListFilesParameters = { + channel: string; + limit?: number; + next?: string; +}; +export type ListFilesResponse = { + status: number; + data: SharedFile[]; + next: string; + count: number; +}; +export type SendFileParameters = Omit & { + channel: string; + file: FileParameters; +}; +export type SendFileResponse = PublishFileMessageResponse & { + status: number; + name: string; + id: string; +}; +export type UploadFileParameters = { + fileId: string; + fileName: string; + file: PubNubFileInterface; + uploadUrl: string; + formFields: { + name: string; + value: string; + }[]; +}; +export type UploadFileResponse = { + status: number; + message: Payload; +}; +export type GenerateFileUploadUrlParameters = { + channel: string; + name: string; +}; +export type GenerateFileUploadUrlResponse = { + id: string; + name: string; + url: string; + formFields: { + name: string; + value: string; + }[]; +}; +export type PublishFileMessageParameters = { + channel: string; + message?: Payload; + cipherKey?: string; + fileId: string; + fileName: string; + storeInHistory?: boolean; + ttl?: number; + meta?: Payload; +}; +export type PublishFileMessageResponse = { + timetoken: string; +}; +export type DownloadFileParameters = FileUrlParameters & { + cipherKey?: string; +}; +export type FileUrlParameters = { + channel: string; + id: string; + name: string; +}; +export type FileUrlResponse = string; +export type DeleteFileParameters = { + channel: string; + id: string; + name: string; +}; +export type DeleteFileResponse = { + status: number; +}; diff --git a/lib/types/core/types/api/history.d.ts b/lib/types/core/types/api/history.d.ts new file mode 100644 index 000000000..cdb748fc2 --- /dev/null +++ b/lib/types/core/types/api/history.d.ts @@ -0,0 +1,105 @@ +import { Payload } from './index'; +export type GetHistoryParameters = { + channel: string; + count?: number; + includeMeta?: boolean; + start?: string; + end?: string; + reverse?: boolean; + stringifiedTimeToken?: boolean; +}; +export type GetHistoryResponse = { + messages: { + entry: Payload; + timetoken: string | number; + meta?: Payload; + error?: string; + }[]; + startTimeToken: string | number; + endTimeToken: string | number; +}; +export declare enum PubNubMessageType { + Message = -1, + Files = 4 +} +export type Actions = { + [t: string]: { + [v: string]: { + uuid: string; + actionTimetoken: string; + }; + }; +}; +export type MoreActions = { + url: string; + start: string; + max: number; +}; +type BaseFetchedMessage = { + channel: string; + timetoken: string | number; + uuid?: string; + meta?: Payload; + error?: string; +}; +export type RegularMessage = BaseFetchedMessage & { + message: Payload; + messageType?: PubNubMessageType.Message; +}; +export type FileMessage = BaseFetchedMessage & { + message: { + message?: Payload; + file: { + id: string; + name: string; + 'mime-type': string; + size: number; + url: string; + }; + }; + messageType?: PubNubMessageType.Files; +}; +export type FetchedMessage = RegularMessage | FileMessage; +export type FetchedMessageWithActions = FetchedMessage & { + actions?: Actions; + data?: Actions; +}; +export type FetchMessagesParameters = { + channels: string[]; + count?: number; + includeMessageType?: boolean; + includeUUID?: boolean; + includeUuid?: boolean; + includeMeta?: boolean; + includeMessageActions?: boolean; + start?: string; + end?: string; + stringifiedTimeToken?: boolean; +}; +export type FetchMessagesForChannelsResponse = { + channels: { + [p: string]: FetchedMessage[]; + }; +}; +export type FetchMessagesWithActionsResponse = { + channels: { + [p: string]: FetchedMessageWithActions[]; + }; + more: MoreActions; +}; +export type FetchMessagesResponse = FetchMessagesForChannelsResponse | FetchMessagesWithActionsResponse; +export type MessageCountParameters = { + channels: string[]; + channelTimetokens?: string[]; + timetoken?: string; +}; +export type MessageCountResponse = { + channels: Record; +}; +export type DeleteMessagesParameters = { + channel: string; + start?: string; + end?: string; +}; +export type DeleteMessagesResponse = Record; +export {}; diff --git a/lib/types/core/types/api/index.d.ts b/lib/types/core/types/api/index.d.ts new file mode 100644 index 000000000..a76d7e94e --- /dev/null +++ b/lib/types/core/types/api/index.d.ts @@ -0,0 +1,33 @@ +import { AbstractRequest } from '../../components/request'; +import RequestOperation from '../../constants/operations'; +import StatusCategory from '../../constants/categories'; +export type KeySet = { + subscribeKey: string; + publishKey?: string; + secretKey?: string; +}; +export type SendRequestFunction = (request: AbstractRequest, callback?: ResultCallback) => Promise; +export type ResultCallback = (status: Status, response: ResponseType | null) => void; +export type StatusCallback = (status: Status) => void; +export type Status = { + error: boolean; + category: StatusCategory; + operation?: RequestOperation; + statusCode: number; + errorData?: Error | Payload; + [p: string]: Payload | Error | undefined; +}; +export type StatusEvent = { + category: StatusCategory; + operation?: RequestOperation; + error?: string | boolean; + affectedChannels?: string[]; + subscribedChannels?: string[]; + affectedChannelGroups?: string[]; + lastTimetoken?: number | string; + currentTimetoken?: number | string; +}; +export type Query = Record; +export type Payload = string | number | boolean | { + [key: string]: Payload | null; +} | Payload[]; diff --git a/lib/types/core/types/api/message-action.d.ts b/lib/types/core/types/api/message-action.d.ts new file mode 100644 index 000000000..aee3c2454 --- /dev/null +++ b/lib/types/core/types/api/message-action.d.ts @@ -0,0 +1,44 @@ +export type MessageAction = { + type: string; + value: string; + uuid: string; + actionTimetoken: string; + messageTimetoken: string; +}; +export type MoreMessageActions = { + url: string; + start: string; + end: string; + limit: number; +}; +export type AddMessageActionParameters = { + channel: string; + messageTimetoken: string; + action: { + type: string; + value: string; + }; +}; +export type AddMessageActionResponse = { + data: MessageAction; +}; +export type GetMessageActionsParameters = { + channel: string; + start?: string; + end?: string; + limit?: number; +}; +export type GetMessageActionsResponse = { + data: MessageAction[]; + start: string | null; + end: string | null; + more?: MoreMessageActions; +}; +export type RemoveMessageActionParameters = { + channel: string; + messageTimetoken: string; + actionTimetoken: string; +}; +export type RemoveMessageActionResponse = { + data: Record; +}; diff --git a/lib/types/core/types/api/presence.d.ts b/lib/types/core/types/api/presence.d.ts new file mode 100644 index 000000000..ef1fb4b1f --- /dev/null +++ b/lib/types/core/types/api/presence.d.ts @@ -0,0 +1,61 @@ +import { Payload } from './index'; +export type GetPresenceStateParameters = { + uuid?: string; + channels?: string[]; + channelGroups?: string[]; +}; +export type GetPresenceStateResponse = { + channels: Record; +}; +export type SetPresenceStateParameters = { + channels?: string[]; + channelGroups?: string[]; + state: Payload; +}; +export type SetPresenceStateWithHeartbeatParameters = { + channels?: string[]; + state: Payload; + withHeartbeat: boolean; +}; +export type SetPresenceStateResponse = { + state: Payload; +}; +export type PresenceHeartbeatParameters = { + heartbeat: number; + channels?: string[]; + channelGroups?: string[]; + state?: Payload; +}; +export type PresenceHeartbeatResponse = Record; +export type PresenceLeaveParameters = { + channels?: string[]; + channelGroups?: string[]; +}; +export type PresenceLeaveResponse = Record; +export type HereNowParameters = { + channels?: string[]; + channelGroups?: string[]; + includeUUIDs?: boolean; + includeState?: boolean; + queryParameters?: Record; +}; +export type HereNowResponse = { + totalChannels: number; + totalOccupancy: number; + channels: { + [p: string]: { + occupants: { + uuid: string; + state?: Payload | null; + }[]; + name: string; + occupancy: number; + }; + }; +}; +export type WhereNowParameters = { + uuid?: string; +}; +export type WhereNowResponse = { + channels: string[]; +}; diff --git a/lib/types/core/types/api/push-notifications.d.ts b/lib/types/core/types/api/push-notifications.d.ts new file mode 100644 index 000000000..8a71a4dee --- /dev/null +++ b/lib/types/core/types/api/push-notifications.d.ts @@ -0,0 +1,14 @@ +type PushGateway = 'apns2' | 'gcm'; +type DevicePush = { + device: string; + pushGateway: PushGateway; +}; +export type ManageDeviceChannelsParameters = { + channels: string[]; +} & DevicePush; +export type ListDeviceChannelsParameters = DevicePush; +export type ListDeviceChannelsResponse = { + channels: string[]; +}; +export type DeleteDeviceParameters = DevicePush; +export {}; diff --git a/lib/types/core/types/api/push.d.ts b/lib/types/core/types/api/push.d.ts new file mode 100644 index 000000000..1b8cf0763 --- /dev/null +++ b/lib/types/core/types/api/push.d.ts @@ -0,0 +1,32 @@ +type ManagedDeviceChannels = { + channels: string[]; + device: string; + start?: string; + count?: number; +}; +type ListFCMDeviceChannelsParameters = Omit; +type ListAPNSDeviceChannelsParameters = Omit; +type ListAPNS2DeviceChannelsParameters = Omit; +export type ListDeviceChannelsParameters = ListFCMDeviceChannelsParameters | ListAPNSDeviceChannelsParameters | ListAPNS2DeviceChannelsParameters; +export type ListDeviceChannelsResponse = { + channels: string[]; +}; +type ManageFCMDeviceChannelsParameters = ManagedDeviceChannels & { + pushGateway: 'gcm'; +}; +type ManageAPNSDeviceChannelsParameters = ManagedDeviceChannels & { + pushGateway: 'apns'; +}; +type ManageAPNS2DeviceChannelsParameters = ManagedDeviceChannels & { + pushGateway: 'apns2'; + environment?: 'development' | 'production'; + topic: string; +}; +export type ManageDeviceChannelsParameters = ManageFCMDeviceChannelsParameters | ManageAPNSDeviceChannelsParameters | ManageAPNS2DeviceChannelsParameters; +export type ManageDeviceChannelsResponse = Record; +type RemoveFCMDeviceParameters = Omit; +type RemoveAPNSDeviceParameters = Omit; +type RemoveAPNS2DeviceParameters = Omit; +export type RemoveDeviceParameters = RemoveFCMDeviceParameters | RemoveAPNSDeviceParameters | RemoveAPNS2DeviceParameters; +export type RemoveDeviceResponse = Record; +export {}; diff --git a/lib/types/core/types/api/subscription.d.ts b/lib/types/core/types/api/subscription.d.ts new file mode 100644 index 000000000..24b2396ed --- /dev/null +++ b/lib/types/core/types/api/subscription.d.ts @@ -0,0 +1,96 @@ +import { RequestParameters as SubscribeRequestParameters, VSPMembershipObjectData, AppContextObjectData, MessageActionData, PubNubEventType, SpaceObjectData, UserObjectData, PresenceData, FileData } from '../../endpoints/subscribe'; +import { AbortSignal } from '../../components/abort_signal'; +import { Payload } from './index'; +export type SubscriptionCursor = { + timetoken: string | number; + region?: number; +}; +type Event = { + channel: string; + subscription: string | null; + timetoken: string; +}; +type LegacyEvent = Event & { + actualChannel?: string | null; + subscribedChannel?: string; +}; +export type Presence = LegacyEvent & PresenceData; +type PresenceEvent = { + type: PubNubEventType.Presence; + data: Presence; +}; +type PublishedData = { + publisher?: string; + userMetadata?: { + [p: string]: Payload; + }; + message: Payload; +}; +export type Message = LegacyEvent & PublishedData & { + error?: string; +}; +type MessageEvent = { + type: PubNubEventType.Message; + data: Message; +}; +export type Signal = Event & PublishedData; +type SignalEvent = { + type: PubNubEventType.Signal; + data: Signal; +}; +export type MessageAction = Event & Omit & { + publisher?: string; + data: MessageActionData['data'] & { + uuid: string; + }; +}; +type MessageActionEvent = { + type: PubNubEventType.MessageAction; + data: MessageAction; +}; +export type AppContextObject = Event & { + message: AppContextObjectData; +}; +export type UserAppContextObject = Omit & { + spaceId: string; + message: UserObjectData; +}; +export type SpaceAppContextObject = Omit & { + spaceId: string; + message: SpaceObjectData; +}; +export type VSPMembershipAppContextObject = Omit & { + spaceId: string; + message: VSPMembershipObjectData; +}; +type AppContextEvent = { + type: PubNubEventType.AppContext; + data: AppContextObject; +}; +export type File = Event & Omit & Omit & { + message?: Payload; + file?: FileData['file'] & { + url: string; + }; + error?: string; +}; +type FileEvent = { + type: PubNubEventType.Files; + data: File; +}; +export type CancelableSubscribeParameters = Omit & { + abortSignal: AbortSignal; +}; +export type SubscribeParameters = { + channels?: string[]; + channelGroups?: string[]; + timetoken?: string | number; + withPresence?: boolean; + state?: Record; + withHeartbeats?: boolean; +}; +export type SubscriptionResponse = { + cursor: SubscriptionCursor; + messages: (PresenceEvent | MessageEvent | SignalEvent | MessageActionEvent | AppContextEvent | FileEvent)[]; +}; +export {}; diff --git a/lib/types/core/types/file.d.ts b/lib/types/core/types/file.d.ts new file mode 100644 index 000000000..fc6d3d7f4 --- /dev/null +++ b/lib/types/core/types/file.d.ts @@ -0,0 +1,24 @@ +export type PubNubBasicFileParameters = { + data: string | ArrayBuffer; + name: string; + mimeType?: string; +}; +export interface PubNubFileInterface { + name: string; + mimeType?: string; + contentLength?: number; + toArrayBuffer(): Promise; + toFileUri(): Promise>; +} +export interface PubNubFileConstructor { + supportsBlob: boolean; + supportsFile: boolean; + supportsBuffer: boolean; + supportsStream: boolean; + supportsString: boolean; + supportsArrayBuffer: boolean; + supportsEncryptFile: boolean; + supportsFileUri: boolean; + create(file: ConstructorParameters): File; + new (file: ConstructorParameters): File; +} diff --git a/lib/types/core/types/transport-request.d.ts b/lib/types/core/types/transport-request.d.ts new file mode 100644 index 000000000..db7da1684 --- /dev/null +++ b/lib/types/core/types/transport-request.d.ts @@ -0,0 +1,24 @@ +import { PubNubFileInterface } from './file'; +import { Query } from './api'; +export declare enum TransportMethod { + GET = "GET", + POST = "POST", + PATCH = "PATCH", + DELETE = "DELETE", + LOCAL = "LOCAL" +} +export type CancellationController = { + abort: () => void; +}; +export type TransportRequest = { + origin?: string; + path: string; + queryParameters?: Query; + method: TransportMethod; + headers?: Record; + formData?: Record[]; + body?: ArrayBuffer | PubNubFileInterface | string; + timeout: number; + cancellable: boolean; + identifier: string; +}; diff --git a/lib/types/core/types/transport-response.d.ts b/lib/types/core/types/transport-response.d.ts new file mode 100644 index 000000000..6c059d060 --- /dev/null +++ b/lib/types/core/types/transport-response.d.ts @@ -0,0 +1,6 @@ +export type TransportResponse = { + url: string; + status: number; + headers: Record; + body?: ArrayBuffer; +}; diff --git a/lib/types/core/utils.d.ts b/lib/types/core/utils.d.ts new file mode 100644 index 000000000..148db9a49 --- /dev/null +++ b/lib/types/core/utils.d.ts @@ -0,0 +1,6 @@ +import { Query } from './types/api'; +export declare const encodeString: (input: string | number) => string; +export declare const encodeNames: (names: string[], defaultString?: string) => string; +export declare const removeSingleOccurrence: (source: string[], elementsToRemove: string[]) => string[]; +export declare const findUniqueCommonElements: (a: string[], b: string[]) => string[]; +export declare const queryStringFromObject: (query: Query) => string; diff --git a/lib/types/crypto/index.d.ts b/lib/types/crypto/index.d.ts new file mode 100644 index 000000000..e69de29bb diff --git a/lib/types/crypto/modules/NodeCryptoModule/ICryptor.d.ts b/lib/types/crypto/modules/NodeCryptoModule/ICryptor.d.ts new file mode 100644 index 000000000..934139069 --- /dev/null +++ b/lib/types/crypto/modules/NodeCryptoModule/ICryptor.d.ts @@ -0,0 +1,18 @@ +/// +/// +export type EncryptedDataType = { + data: Buffer | string; + metadata: Buffer | null; +}; +export type EncryptedStream = { + stream: NodeJS.ReadableStream; + metadataLength: number; + metadata?: Buffer | undefined; +}; +export interface ICryptor { + get identifier(): string; + encrypt(data: BufferSource | string): EncryptedDataType; + encryptStream(stream: NodeJS.ReadableStream): Promise; + decrypt(data: EncryptedDataType): ArrayBuffer; + decryptStream(stream: EncryptedStream): Promise; +} diff --git a/lib/types/crypto/modules/NodeCryptoModule/ILegacyCryptor.d.ts b/lib/types/crypto/modules/NodeCryptoModule/ILegacyCryptor.d.ts new file mode 100644 index 000000000..b41a01098 --- /dev/null +++ b/lib/types/crypto/modules/NodeCryptoModule/ILegacyCryptor.d.ts @@ -0,0 +1,11 @@ +import PubNubFile, { PubNubFileParameters } from '../../../file/modules/node'; +import { PubNubFileConstructor } from '../../../core/types/file'; +import { Payload } from '../../../core/types/api'; +import { EncryptedDataType } from './ICryptor'; +export interface ILegacyCryptor { + get identifier(): string; + encrypt(data: string): EncryptedDataType; + encryptFile(file: PubNubFile, File: PubNubFileConstructor): Promise; + decrypt(data: EncryptedDataType): Payload | null; + decryptFile(file: PubNubFile, File: PubNubFileConstructor): Promise; +} diff --git a/lib/types/crypto/modules/NodeCryptoModule/aesCbcCryptor.d.ts b/lib/types/crypto/modules/NodeCryptoModule/aesCbcCryptor.d.ts new file mode 100644 index 000000000..ac56f1db9 --- /dev/null +++ b/lib/types/crypto/modules/NodeCryptoModule/aesCbcCryptor.d.ts @@ -0,0 +1,25 @@ +/// +/// +/// +import { PassThrough } from 'stream'; +import { ICryptor, EncryptedDataType, EncryptedStream } from './ICryptor'; +export default class AesCbcCryptor implements ICryptor { + static BLOCK_SIZE: number; + static encoder: TextEncoder; + cipherKey: string; + constructor({ cipherKey }: { + cipherKey: string; + }); + encrypt(data: ArrayBuffer | string): EncryptedDataType; + encryptStream(stream: NodeJS.ReadableStream): Promise<{ + stream: PassThrough; + metadata: Buffer; + metadataLength: number; + }>; + decrypt(input: EncryptedDataType): ArrayBuffer; + decryptStream(stream: EncryptedStream): Promise; + get identifier(): string; + private get algo(); + private getIv; + private getKey; +} diff --git a/lib/types/crypto/modules/NodeCryptoModule/legacyCryptor.d.ts b/lib/types/crypto/modules/NodeCryptoModule/legacyCryptor.d.ts new file mode 100644 index 000000000..39bb14f3d --- /dev/null +++ b/lib/types/crypto/modules/NodeCryptoModule/legacyCryptor.d.ts @@ -0,0 +1,18 @@ +import PubNubFile, { PubNubFileParameters } from '../../../file/modules/node'; +import { CryptorConfiguration } from '../../../core/interfaces/crypto-module'; +import Crypto from '../../../core/components/cryptography/index'; +import { PubNubFileConstructor } from '../../../core/types/file'; +import { ILegacyCryptor } from './ILegacyCryptor'; +import { EncryptedDataType } from './ICryptor'; +import FileCryptor from '../node'; +export default class LegacyCryptor implements ILegacyCryptor { + config: CryptorConfiguration; + fileCryptor: FileCryptor; + cryptor: Crypto; + constructor(config: CryptorConfiguration); + encrypt(data: string): EncryptedDataType; + encryptFile(file: PubNubFile, File: PubNubFileConstructor): Promise; + decrypt(encryptedData: EncryptedDataType): import("../../../core/types/api").Payload | null; + decryptFile(file: PubNubFile, File: PubNubFileConstructor): Promise; + get identifier(): string; +} diff --git a/lib/types/crypto/modules/NodeCryptoModule/nodeCryptoModule.d.ts b/lib/types/crypto/modules/NodeCryptoModule/nodeCryptoModule.d.ts new file mode 100644 index 000000000..a55a0ce33 --- /dev/null +++ b/lib/types/crypto/modules/NodeCryptoModule/nodeCryptoModule.d.ts @@ -0,0 +1,26 @@ +import { AbstractCryptoModule, CryptorConfiguration } from '../../../core/interfaces/crypto-module'; +import PubNubFile, { PubNubFileParameters } from '../../../file/modules/node'; +import { PubNubFileConstructor } from '../../../core/types/file'; +import { ICryptor } from './ICryptor'; +import { ILegacyCryptor } from './ILegacyCryptor'; +import AesCbcCryptor from './aesCbcCryptor'; +import LegacyCryptor from './legacyCryptor'; +export { LegacyCryptor, AesCbcCryptor }; +type CryptorType = ICryptor | ILegacyCryptor; +export declare class CryptoModule extends AbstractCryptoModule { + static LEGACY_IDENTIFIER: string; + static legacyCryptoModule(config: CryptorConfiguration): CryptoModule; + static aesCbcCryptoModule(config: CryptorConfiguration): CryptoModule; + static withDefaultCryptor(defaultCryptor: CryptorType): CryptoModule; + encrypt(data: ArrayBuffer | string): string | ArrayBuffer; + encryptFile(file: PubNubFile, File: PubNubFileConstructor): Promise; + decrypt(data: ArrayBuffer | string): ArrayBuffer | import("../../../core/types/api").Payload | null; + decryptFile(file: PubNubFile, File: PubNubFileConstructor): Promise; + private getLegacyCryptor; + private getCryptorFromId; + private getCryptor; + private getHeaderData; + private concatArrayBuffer; + private onStreamReadable; + private decryptLegacyFileStream; +} diff --git a/lib/types/crypto/modules/node.d.ts b/lib/types/crypto/modules/node.d.ts new file mode 100644 index 000000000..0a35ba46b --- /dev/null +++ b/lib/types/crypto/modules/node.d.ts @@ -0,0 +1,23 @@ +/// +/// +import { Readable, PassThrough, Transform } from 'stream'; +import { Buffer } from 'buffer'; +import PubNubFile, { PubNubFileParameters } from '../../file/modules/node'; +import { Cryptography } from '../../core/interfaces/cryptography'; +import { PubNubFileConstructor } from '../../core/types/file'; +export default class NodeCryptography implements Cryptography { + static IV_LENGTH: number; + encrypt(key: string, input: string | ArrayBuffer | Buffer | Readable): Promise; + private encryptBuffer; + private encryptStream; + private encryptString; + encryptFile(key: string, file: PubNubFile, File: PubNubFileConstructor): Promise; + decrypt(key: string, input: string | ArrayBuffer | Buffer | Readable): Promise; + private decryptBuffer; + private decryptStream; + private decryptString; + decryptFile(key: string, file: PubNubFile, File: PubNubFileConstructor): Promise; + private get algo(); + private getKey; + private getIv; +} diff --git a/lib/types/entities/Channel.d.ts b/lib/types/entities/Channel.d.ts new file mode 100644 index 000000000..fdeb23a76 --- /dev/null +++ b/lib/types/entities/Channel.d.ts @@ -0,0 +1,11 @@ +import type { PubNubCore as PubNub } from '../core/pubnub-common'; +import EventEmitter from '../core/components/eventEmitter'; +import { SubscriptionOptions } from './commonTypes'; +import { Subscription } from './Subscription'; +export declare class Channel { + private readonly eventEmitter; + private readonly pubnub; + private readonly name; + constructor(channelName: string, eventEmitter: EventEmitter, pubnub: PubNub); + subscription(subscriptionOptions?: SubscriptionOptions): Subscription; +} diff --git a/lib/types/entities/ChannelGroup.d.ts b/lib/types/entities/ChannelGroup.d.ts new file mode 100644 index 000000000..a1c383d59 --- /dev/null +++ b/lib/types/entities/ChannelGroup.d.ts @@ -0,0 +1,11 @@ +import type { PubNubCore as PubNub } from '../core/pubnub-common'; +import EventEmitter from '../core/components/eventEmitter'; +import { SubscriptionOptions } from './commonTypes'; +import { Subscription } from './Subscription'; +export declare class ChannelGroup { + private readonly eventEmitter; + private readonly pubnub; + private readonly name; + constructor(channelGroup: string, eventEmitter: EventEmitter, pubnub: PubNub); + subscription(subscriptionOptions?: SubscriptionOptions): Subscription; +} diff --git a/lib/types/entities/ChannelMetadata.d.ts b/lib/types/entities/ChannelMetadata.d.ts new file mode 100644 index 000000000..101562ad0 --- /dev/null +++ b/lib/types/entities/ChannelMetadata.d.ts @@ -0,0 +1,11 @@ +import type { PubNubCore as PubNub } from '../core/pubnub-common'; +import EventEmitter from '../core/components/eventEmitter'; +import { SubscriptionOptions } from './commonTypes'; +import { Subscription } from './Subscription'; +export declare class ChannelMetadata { + private readonly id; + private readonly eventEmitter; + private readonly pubnub; + constructor(id: string, eventEmitter: EventEmitter, pubnub: PubNub); + subscription(subscriptionOptions?: SubscriptionOptions): Subscription; +} diff --git a/lib/types/entities/SubscribeCapable.d.ts b/lib/types/entities/SubscribeCapable.d.ts new file mode 100644 index 000000000..b4ca7001d --- /dev/null +++ b/lib/types/entities/SubscribeCapable.d.ts @@ -0,0 +1,25 @@ +import type { PubNubCore as PubNub } from '../core/pubnub-common'; +import { Listener } from '../core/components/listener_manager'; +import * as Subscription from '../core/types/api/subscription'; +import EventEmitter from '../core/components/eventEmitter'; +import { SubscriptionOptions } from './commonTypes'; +export declare abstract class SubscribeCapable { + protected abstract channelNames: string[]; + protected abstract groupNames: string[]; + protected abstract listener: Listener; + protected abstract eventEmitter: EventEmitter; + protected abstract pubnub: PubNub; + protected abstract options?: SubscriptionOptions; + subscribe(): void; + unsubscribe(): void; + set onMessage(onMessageListener: (messageEvent: Subscription.Message) => void); + set onPresence(onPresenceListener: (presenceEvent: Subscription.Presence) => void); + set onSignal(onSignalListener: (signalEvent: Subscription.Signal) => void); + set onObjects(onObjectsListener: (objectsEvent: Subscription.AppContextObject) => void); + set onMessageAction(messageActionEventListener: (messageActionEvent: Subscription.MessageAction) => void); + set onFile(fileEventListener: (fileEvent: Subscription.File) => void); + addListener(listener: Listener): void; + removeListener(listener: Listener): void; + get channels(): string[]; + get channelGroups(): string[]; +} diff --git a/lib/types/entities/Subscription.d.ts b/lib/types/entities/Subscription.d.ts new file mode 100644 index 000000000..ca7002a27 --- /dev/null +++ b/lib/types/entities/Subscription.d.ts @@ -0,0 +1,22 @@ +import type { PubNubCore as PubNub } from '../core/pubnub-common'; +import { Listener } from '../core/components/listener_manager'; +import EventEmitter from '../core/components/eventEmitter'; +import { SubscribeCapable } from './SubscribeCapable'; +import { SubscriptionOptions } from './commonTypes'; +import { SubscriptionSet } from './SubscriptionSet'; +export declare class Subscription extends SubscribeCapable { + protected channelNames: string[]; + protected groupNames: string[]; + protected options?: SubscriptionOptions; + protected pubnub: PubNub; + protected eventEmitter: EventEmitter; + protected listener: Listener; + constructor({ channels, channelGroups, subscriptionOptions, eventEmitter, pubnub, }: { + channels: string[]; + channelGroups: string[]; + subscriptionOptions?: SubscriptionOptions; + eventEmitter: EventEmitter; + pubnub: PubNub; + }); + addSubscription(subscription: Subscription): SubscriptionSet; +} diff --git a/lib/types/entities/SubscriptionSet.d.ts b/lib/types/entities/SubscriptionSet.d.ts new file mode 100644 index 000000000..a7e0c2465 --- /dev/null +++ b/lib/types/entities/SubscriptionSet.d.ts @@ -0,0 +1,27 @@ +import type { PubNubCore as PubNub } from '../core/pubnub-common'; +import { Listener } from '../core/components/listener_manager'; +import EventEmitter from '../core/components/eventEmitter'; +import { SubscribeCapable } from './SubscribeCapable'; +import { SubscriptionOptions } from './commonTypes'; +import { Subscription } from './Subscription'; +export declare class SubscriptionSet extends SubscribeCapable { + protected channelNames: string[]; + protected groupNames: string[]; + protected options?: SubscriptionOptions; + protected pubnub: PubNub; + protected eventEmitter: EventEmitter; + protected subscriptionList: Subscription[]; + protected listener: Listener; + constructor({ channels, channelGroups, subscriptionOptions, eventEmitter, pubnub, }: { + channels?: string[]; + channelGroups?: string[]; + subscriptionOptions?: SubscriptionOptions; + eventEmitter: EventEmitter; + pubnub: PubNub; + }); + addSubscription(subscription: Subscription): void; + removeSubscription(subscription: Subscription): void; + addSubscriptionSet(subscriptionSet: SubscriptionSet): void; + removeSubscriptionSet(subscriptionSet: SubscriptionSet): void; + get subscriptions(): Subscription[]; +} diff --git a/lib/types/entities/UserMetadata.d.ts b/lib/types/entities/UserMetadata.d.ts new file mode 100644 index 000000000..354ef437d --- /dev/null +++ b/lib/types/entities/UserMetadata.d.ts @@ -0,0 +1,11 @@ +import type { PubNubCore as PubNub } from '../core/pubnub-common'; +import EventEmitter from '../core/components/eventEmitter'; +import { SubscriptionOptions } from './commonTypes'; +import { Subscription } from './Subscription'; +export declare class UserMetadata { + private readonly id; + private readonly eventEmitter; + private readonly pubnub; + constructor(id: string, eventEmitter: EventEmitter, pubnub: PubNub); + subscription(subscriptionOptions?: SubscriptionOptions): Subscription; +} diff --git a/lib/types/entities/commonTypes.d.ts b/lib/types/entities/commonTypes.d.ts new file mode 100644 index 000000000..170abf0d4 --- /dev/null +++ b/lib/types/entities/commonTypes.d.ts @@ -0,0 +1,7 @@ +export type SubscriptionOptions = { + cursor?: { + timetoken?: string; + region?: number; + }; + receivePresenceEvents?: boolean; +}; diff --git a/lib/types/errors/pubnub-api-error.d.ts b/lib/types/errors/pubnub-api-error.d.ts new file mode 100644 index 000000000..037db6967 --- /dev/null +++ b/lib/types/errors/pubnub-api-error.d.ts @@ -0,0 +1,16 @@ +import { TransportResponse } from '../core/types/transport-response'; +import RequestOperation from '../core/constants/operations'; +import StatusCategory from '../core/constants/categories'; +import { Payload, Status } from '../core/types/api'; +import { PubNubError } from './pubnub-error'; +export declare class PubNubAPIError extends Error { + readonly category: StatusCategory; + readonly statusCode: number; + readonly errorData?: Error | Payload | undefined; + static create(errorOrResponse: Error | TransportResponse, data?: ArrayBuffer): PubNubAPIError; + private static createFromError; + private static createFromServiceResponse; + constructor(message: string, category: StatusCategory, statusCode: number, errorData?: Error | Payload | undefined); + toStatus(operation: RequestOperation): Status; + toPubNubError(operation: RequestOperation, message?: string): PubNubError; +} diff --git a/lib/types/errors/pubnub-error.d.ts b/lib/types/errors/pubnub-error.d.ts new file mode 100644 index 000000000..549b195f9 --- /dev/null +++ b/lib/types/errors/pubnub-error.d.ts @@ -0,0 +1,6 @@ +import { Status } from '../core/types/api'; +export declare class PubNubError extends Error { + status?: Status | undefined; + constructor(message: string, status?: Status | undefined); +} +export declare function createValidationError(message: string, statusCode?: number): Status; diff --git a/lib/types/event-engine/core/change.d.ts b/lib/types/event-engine/core/change.d.ts new file mode 100644 index 000000000..7aaf7a029 --- /dev/null +++ b/lib/types/event-engine/core/change.d.ts @@ -0,0 +1,24 @@ +import { State } from './state'; +import { EventTypeFromMap, GenericMap, InvocationTypeFromMap } from './types'; +export type EngineStarted = { + type: 'engineStarted'; + state: State; + context: any; +}; +export type EventReceived = { + type: 'eventReceived'; + event: EventTypeFromMap; +}; +export type TransitionDone = { + type: 'transitionDone'; + event: EventTypeFromMap; + fromState: State; + toState: State; + fromContext: any; + toContext: any; +}; +export type InvocationDispatched = { + type: 'invocationDispatched'; + invocation: InvocationTypeFromMap; +}; +export type Change = TransitionDone | InvocationDispatched | EngineStarted | EventReceived; diff --git a/lib/types/event-engine/core/dispatcher.d.ts b/lib/types/event-engine/core/dispatcher.d.ts new file mode 100644 index 000000000..d70bc9359 --- /dev/null +++ b/lib/types/event-engine/core/dispatcher.d.ts @@ -0,0 +1,13 @@ +import { Handler } from './handler'; +import { GenericInvocation, GenericMap, InvocationTypeFromMap } from './types'; +type HandlerCreator = (payload: Payload, dependencies: Dependencies) => Handler; +export declare class Dispatcher> { + private readonly dependencies; + constructor(dependencies: Dependencies); + private instances; + private handlers; + on(type: K, handlerCreator: HandlerCreator): void; + dispatch(invocation: Invocation): void; + dispose(): void; +} +export {}; diff --git a/lib/types/event-engine/core/engine.d.ts b/lib/types/event-engine/core/engine.d.ts new file mode 100644 index 000000000..ba108d423 --- /dev/null +++ b/lib/types/event-engine/core/engine.d.ts @@ -0,0 +1,11 @@ +import { Subject } from '../../core/components/subject'; +import { Change } from './change'; +import { State } from './state'; +import { GenericMap, Event } from './types'; +export declare class Engine extends Subject> { + describe(label: string): State; + private currentState?; + private currentContext?; + start(initialState: State, initialContext: Context): void; + transition(event: Event): void; +} diff --git a/lib/types/event-engine/core/handler.d.ts b/lib/types/event-engine/core/handler.d.ts new file mode 100644 index 000000000..c8a53c875 --- /dev/null +++ b/lib/types/event-engine/core/handler.d.ts @@ -0,0 +1,18 @@ +import { AbortSignal } from '../../core/components/abort_signal'; +export declare abstract class Handler { + protected payload: Payload; + protected readonly dependencies: Dependencies; + constructor(payload: Payload, dependencies: Dependencies); + abstract start(): void; + abstract cancel(): void; +} +type AsyncHandlerFunction = (payload: Payload, abortSignal: AbortSignal, dependencies: Dependencies) => Promise; +declare class AsyncHandler extends Handler { + private asyncFunction; + abortSignal: AbortSignal; + constructor(payload: Payload, dependencies: Dependencies, asyncFunction: AsyncHandlerFunction); + start(): void; + cancel(): void; +} +export declare const asyncHandler: (handlerFunction: AsyncHandlerFunction) => (payload: Payload, dependencies: Dependencies) => AsyncHandler; +export {}; diff --git a/lib/types/event-engine/core/index.d.ts b/lib/types/event-engine/core/index.d.ts new file mode 100644 index 000000000..b8eab6782 --- /dev/null +++ b/lib/types/event-engine/core/index.d.ts @@ -0,0 +1,4 @@ +export { Engine } from './engine'; +export { Dispatcher } from './dispatcher'; +export { MapOf, createEvent, createEffect, createManagedEffect } from './types'; +export { asyncHandler } from './handler'; diff --git a/lib/types/event-engine/core/retryPolicy.d.ts b/lib/types/event-engine/core/retryPolicy.d.ts new file mode 100644 index 000000000..628c73d13 --- /dev/null +++ b/lib/types/event-engine/core/retryPolicy.d.ts @@ -0,0 +1,26 @@ +import { PubNubError } from '../../errors/pubnub-error'; +export declare class RetryPolicy { + static LinearRetryPolicy(configuration: LinearRetryPolicyConfiguration): RequestRetryPolicy & LinearRetryPolicyConfiguration; + static ExponentialRetryPolicy(configuration: ExponentialRetryPolicyConfiguration): RequestRetryPolicy & ExponentialRetryPolicyConfiguration; +} +export type RequestRetryPolicy = { + shouldRetry(reason: PubNubError & { + retryAfter?: number; + }, attempt: number): boolean; + getDelay(attempt: number, reason: PubNubError & { + retryAfter?: number; + }): number; + getGiveupReason(reason: PubNubError & { + retryAfter?: number; + }, attempt: number): string; + validate(): void; +}; +export type LinearRetryPolicyConfiguration = { + delay: number; + maximumRetry: number; +}; +export type ExponentialRetryPolicyConfiguration = { + minimumDelay: number; + maximumDelay: number; + maximumRetry: number; +}; diff --git a/lib/types/event-engine/core/state.d.ts b/lib/types/event-engine/core/state.d.ts new file mode 100644 index 000000000..59b3bb534 --- /dev/null +++ b/lib/types/event-engine/core/state.d.ts @@ -0,0 +1,21 @@ +import { Event, EventOfType, GenericInvocation, GenericMap, InvocationTypeFromMap } from './types'; +export type TransitionFunction> = { + (context: Context, event: EventType): Transition | void; +}; +export type Transition = [ + State, + Context, + InvocationTypeFromMap[] +]; +export declare class State { + label: string; + private transitionMap; + transition(context: Context, event: EventOfType): void | Transition; + constructor(label: string); + on(eventType: K, transition: TransitionFunction>): this; + with(context: Context, effects?: InvocationTypeFromMap[]): Transition; + enterEffects: ((context: Context) => InvocationTypeFromMap)[]; + exitEffects: ((context: Context) => InvocationTypeFromMap)[]; + onEnter(effect: (context: Context) => GenericInvocation): this; + onExit(effect: (context: Context) => GenericInvocation): this; +} diff --git a/lib/types/event-engine/core/types.d.ts b/lib/types/event-engine/core/types.d.ts new file mode 100644 index 000000000..14524f0ec --- /dev/null +++ b/lib/types/event-engine/core/types.d.ts @@ -0,0 +1,45 @@ +export type Event = { + type: T; + payload: P; +}; +export type Invocation = { + type: T; + payload: P; + managed: boolean; +}; +export type GenericEvent = Event; +export type GenericInvocation = Invocation; +export type GenericMap = Record; +export type EventTypeFromMap = { + [T in keyof Map & string]: Event; +}[keyof Map & string]; +export type InvocationTypeFromMap = { + [T in keyof Map & string]: Invocation; +}[keyof Map & string]; +export type EventOfType = Event; +export type InvocationOfType = Invocation; +type EventCreator = { + (...args: S): Event; + type: K; +}; +export declare function createEvent(type: K, fn: (...args: S) => P): EventCreator; +export type MapOf { + type: string | number | symbol; + payload: any; +}> = { + [K in ReturnType['type']]: (ReturnType & { + type: K; + })['payload']; +}; +type EffectCreator = { + (...args: S): Invocation; + type: K; +}; +type ManagedEffectCreator = { + (...args: S): Invocation; + type: K; + cancel: Invocation<'CANCEL', K>; +}; +export declare function createEffect(type: K, fn: (...args: S) => P): EffectCreator; +export declare function createManagedEffect(type: K, fn: (...args: S) => P): ManagedEffectCreator; +export {}; diff --git a/lib/types/event-engine/dispatcher.d.ts b/lib/types/event-engine/dispatcher.d.ts new file mode 100644 index 000000000..b2afbeb72 --- /dev/null +++ b/lib/types/event-engine/dispatcher.d.ts @@ -0,0 +1,27 @@ +import { PrivateClientConfiguration } from '../core/interfaces/configuration'; +import * as Subscription from '../core/types/api/subscription'; +import { Dispatcher, Engine } from './core'; +import * as effects from './effects'; +import * as events from './events'; +import { Payload, StatusEvent } from '../core/types/api'; +export type Dependencies = { + handshake: (parameters: Subscription.CancelableSubscribeParameters) => Promise; + receiveMessages: (parameters: Subscription.CancelableSubscribeParameters) => Promise; + join?: (parameters: { + channels?: string[]; + groups?: string[]; + }) => void; + leave?: (parameters: { + channels?: string[]; + groups?: string[]; + }) => void; + leaveAll?: () => void; + presenceState: Record; + config: PrivateClientConfiguration; + delay: (milliseconds: number) => Promise; + emitMessages: (events: Subscription.SubscriptionResponse['messages']) => void; + emitStatus: (status: StatusEvent) => void; +}; +export declare class EventEngineDispatcher extends Dispatcher { + constructor(engine: Engine, dependencies: Dependencies); +} diff --git a/lib/types/event-engine/effects.d.ts b/lib/types/event-engine/effects.d.ts new file mode 100644 index 000000000..803ce383b --- /dev/null +++ b/lib/types/event-engine/effects.d.ts @@ -0,0 +1,77 @@ +import { MapOf } from './core'; +import { HandshakeReconnectingStateContext } from './states/handshake_reconnecting'; +import { ReceiveReconnectingStateContext } from './states/receive_reconnecting'; +import * as Subscription from '../core/types/api/subscription'; +import { StatusEvent } from '../core/types/api'; +export declare const handshake: { + (channels: string[], groups: string[]): import("./core/types").Invocation<"HANDSHAKE", { + channels: string[]; + groups: string[]; + }>; + type: "HANDSHAKE"; + cancel: import("./core/types").Invocation<"CANCEL", "HANDSHAKE">; +}; +export declare const receiveMessages: { + (channels: string[], groups: string[], cursor: Subscription.SubscriptionCursor): import("./core/types").Invocation<"RECEIVE_MESSAGES", { + channels: string[]; + groups: string[]; + cursor: Subscription.SubscriptionCursor; + }>; + type: "RECEIVE_MESSAGES"; + cancel: import("./core/types").Invocation<"CANCEL", "RECEIVE_MESSAGES">; +}; +export declare const emitMessages: { + (events: ({ + type: import("../core/endpoints/subscribe").PubNubEventType.Presence; + data: Subscription.Presence; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Message; + data: Subscription.Message; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Signal; + data: Subscription.Signal; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.MessageAction; + data: Subscription.MessageAction; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.AppContext; + data: Subscription.AppContextObject; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Files; + data: Subscription.File; + })[]): import("./core/types").Invocation<"EMIT_MESSAGES", ({ + type: import("../core/endpoints/subscribe").PubNubEventType.Presence; + data: Subscription.Presence; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Message; + data: Subscription.Message; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Signal; + data: Subscription.Signal; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.MessageAction; + data: Subscription.MessageAction; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.AppContext; + data: Subscription.AppContextObject; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Files; + data: Subscription.File; + })[]>; + type: "EMIT_MESSAGES"; +}; +export declare const emitStatus: { + (status: StatusEvent): import("./core/types").Invocation<"EMIT_STATUS", StatusEvent>; + type: "EMIT_STATUS"; +}; +export declare const receiveReconnect: { + (context: ReceiveReconnectingStateContext): import("./core/types").Invocation<"RECEIVE_RECONNECT", ReceiveReconnectingStateContext>; + type: "RECEIVE_RECONNECT"; + cancel: import("./core/types").Invocation<"CANCEL", "RECEIVE_RECONNECT">; +}; +export declare const handshakeReconnect: { + (context: HandshakeReconnectingStateContext): import("./core/types").Invocation<"HANDSHAKE_RECONNECT", HandshakeReconnectingStateContext>; + type: "HANDSHAKE_RECONNECT"; + cancel: import("./core/types").Invocation<"CANCEL", "HANDSHAKE_RECONNECT">; +}; +export type Effects = MapOf; diff --git a/lib/types/event-engine/events.d.ts b/lib/types/event-engine/events.d.ts new file mode 100644 index 000000000..98418cab9 --- /dev/null +++ b/lib/types/event-engine/events.d.ts @@ -0,0 +1,159 @@ +import * as Subscription from '../core/types/api/subscription'; +import { PubNubError } from '../errors/pubnub-error'; +import { MapOf } from './core'; +export declare const subscriptionChange: { + (channels: string[], groups: string[]): import("./core/types").Event<"SUBSCRIPTION_CHANGED", { + channels: string[]; + groups: string[]; + }>; + type: "SUBSCRIPTION_CHANGED"; +}; +export declare const restore: { + (channels: string[], groups: string[], timetoken: string | number, region?: number | undefined): import("./core/types").Event<"SUBSCRIPTION_RESTORED", { + channels: string[]; + groups: string[]; + cursor: { + timetoken: string | number; + region: number; + }; + }>; + type: "SUBSCRIPTION_RESTORED"; +}; +export declare const handshakeSuccess: { + (cursor: Subscription.SubscriptionCursor): import("./core/types").Event<"HANDSHAKE_SUCCESS", Subscription.SubscriptionCursor>; + type: "HANDSHAKE_SUCCESS"; +}; +export declare const handshakeFailure: { + (error: PubNubError): import("./core/types").Event<"HANDSHAKE_FAILURE", PubNubError>; + type: "HANDSHAKE_FAILURE"; +}; +export declare const handshakeReconnectSuccess: { + (cursor: Subscription.SubscriptionCursor): import("./core/types").Event<"HANDSHAKE_RECONNECT_SUCCESS", { + cursor: Subscription.SubscriptionCursor; + }>; + type: "HANDSHAKE_RECONNECT_SUCCESS"; +}; +export declare const handshakeReconnectFailure: { + (error: PubNubError): import("./core/types").Event<"HANDSHAKE_RECONNECT_FAILURE", PubNubError>; + type: "HANDSHAKE_RECONNECT_FAILURE"; +}; +export declare const handshakeReconnectGiveup: { + (error: PubNubError): import("./core/types").Event<"HANDSHAKE_RECONNECT_GIVEUP", PubNubError>; + type: "HANDSHAKE_RECONNECT_GIVEUP"; +}; +export declare const receiveSuccess: { + (cursor: Subscription.SubscriptionCursor, events: ({ + type: import("../core/endpoints/subscribe").PubNubEventType.Presence; + data: Subscription.Presence; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Message; + data: Subscription.Message; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Signal; + data: Subscription.Signal; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.MessageAction; + data: Subscription.MessageAction; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.AppContext; + data: Subscription.AppContextObject; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Files; + data: Subscription.File; + })[]): import("./core/types").Event<"RECEIVE_SUCCESS", { + cursor: Subscription.SubscriptionCursor; + events: ({ + type: import("../core/endpoints/subscribe").PubNubEventType.Presence; + data: Subscription.Presence; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Message; + data: Subscription.Message; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Signal; + data: Subscription.Signal; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.MessageAction; + data: Subscription.MessageAction; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.AppContext; + data: Subscription.AppContextObject; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Files; + data: Subscription.File; + })[]; + }>; + type: "RECEIVE_SUCCESS"; +}; +export declare const receiveFailure: { + (error: PubNubError): import("./core/types").Event<"RECEIVE_FAILURE", PubNubError>; + type: "RECEIVE_FAILURE"; +}; +export declare const receiveReconnectSuccess: { + (cursor: Subscription.SubscriptionCursor, events: ({ + type: import("../core/endpoints/subscribe").PubNubEventType.Presence; + data: Subscription.Presence; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Message; + data: Subscription.Message; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Signal; + data: Subscription.Signal; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.MessageAction; + data: Subscription.MessageAction; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.AppContext; + data: Subscription.AppContextObject; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Files; + data: Subscription.File; + })[]): import("./core/types").Event<"RECEIVE_RECONNECT_SUCCESS", { + cursor: Subscription.SubscriptionCursor; + events: ({ + type: import("../core/endpoints/subscribe").PubNubEventType.Presence; + data: Subscription.Presence; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Message; + data: Subscription.Message; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Signal; + data: Subscription.Signal; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.MessageAction; + data: Subscription.MessageAction; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.AppContext; + data: Subscription.AppContextObject; + } | { + type: import("../core/endpoints/subscribe").PubNubEventType.Files; + data: Subscription.File; + })[]; + }>; + type: "RECEIVE_RECONNECT_SUCCESS"; +}; +export declare const receiveReconnectFailure: { + (error: PubNubError): import("./core/types").Event<"RECEIVE_RECONNECT_FAILURE", PubNubError>; + type: "RECEIVE_RECONNECT_FAILURE"; +}; +export declare const receiveReconnectGiveup: { + (error: PubNubError): import("./core/types").Event<"RECEIVING_RECONNECT_GIVEUP", PubNubError>; + type: "RECEIVING_RECONNECT_GIVEUP"; +}; +export declare const disconnect: { + (): import("./core/types").Event<"DISCONNECT", {}>; + type: "DISCONNECT"; +}; +export declare const reconnect: { + (timetoken?: string | undefined, region?: number | undefined): import("./core/types").Event<"RECONNECT", { + cursor: { + timetoken: string; + region: number; + }; + }>; + type: "RECONNECT"; +}; +export declare const unsubscribeAll: { + (): import("./core/types").Event<"UNSUBSCRIBE_ALL", {}>; + type: "UNSUBSCRIBE_ALL"; +}; +export type Events = MapOf; diff --git a/lib/types/event-engine/index.d.ts b/lib/types/event-engine/index.d.ts new file mode 100644 index 000000000..2542bfa3b --- /dev/null +++ b/lib/types/event-engine/index.d.ts @@ -0,0 +1,33 @@ +import { Engine } from './core'; +import { Dependencies } from './dispatcher'; +import * as effects from './effects'; +import * as events from './events'; +export declare class EventEngine { + private engine; + private dispatcher; + private dependencies; + get _engine(): Engine; + private readonly _unsubscribeEngine; + constructor(dependencies: Dependencies); + channels: string[]; + groups: string[]; + subscribe({ channels, channelGroups, timetoken, withPresence, }: { + channels?: string[]; + channelGroups?: string[]; + timetoken?: string | number; + withPresence?: boolean; + }): void; + unsubscribe({ channels, channelGroups }: { + channels?: string[]; + channelGroups?: string[]; + }): void; + unsubscribeAll(): void; + reconnect({ timetoken, region }: { + timetoken?: string; + region?: number; + }): void; + disconnect(): void; + getSubscribedChannels(): string[]; + getSubscribedChannelGroups(): string[]; + dispose(): void; +} diff --git a/lib/types/event-engine/presence/dispatcher.d.ts b/lib/types/event-engine/presence/dispatcher.d.ts new file mode 100644 index 000000000..9fdf3de45 --- /dev/null +++ b/lib/types/event-engine/presence/dispatcher.d.ts @@ -0,0 +1,18 @@ +import { PrivateClientConfiguration } from '../../core/interfaces/configuration'; +import { Dispatcher, Engine } from '../core'; +import * as Presence from '../../core/types/api/presence'; +import { Payload, ResultCallback } from '../../core/types/api'; +import * as effects from './effects'; +import * as events from './events'; +export type Dependencies = { + heartbeat: (parameters: Presence.PresenceHeartbeatParameters, callback?: ResultCallback) => Promise; + leave: (parameters: Presence.PresenceLeaveParameters) => void; + heartbeatDelay: () => Promise; + retryDelay: (milliseconds: number) => Promise; + config: PrivateClientConfiguration; + presenceState: Record; + emitStatus: (status: any) => void; +}; +export declare class PresenceEventEngineDispatcher extends Dispatcher { + constructor(engine: Engine, dependencies: Dependencies); +} diff --git a/lib/types/event-engine/presence/effects.d.ts b/lib/types/event-engine/presence/effects.d.ts new file mode 100644 index 000000000..a905c6835 --- /dev/null +++ b/lib/types/event-engine/presence/effects.d.ts @@ -0,0 +1,31 @@ +import { MapOf } from '../core'; +import { HeartbeatReconnectingStateContext } from './states/heartbeat_reconnecting'; +export declare const heartbeat: { + (channels: string[], groups: string[]): import("../core/types").Invocation<"HEARTBEAT", { + channels: string[]; + groups: string[]; + }>; + type: "HEARTBEAT"; +}; +export declare const leave: { + (channels: string[], groups: string[]): import("../core/types").Invocation<"LEAVE", { + channels: string[]; + groups: string[]; + }>; + type: "LEAVE"; +}; +export declare const emitStatus: { + (status: any): import("../core/types").Invocation<"EMIT_STATUS", any>; + type: "EMIT_STATUS"; +}; +export declare const wait: { + (): import("../core/types").Invocation<"WAIT", {}>; + type: "WAIT"; + cancel: import("../core/types").Invocation<"CANCEL", "WAIT">; +}; +export declare const delayedHeartbeat: { + (context: HeartbeatReconnectingStateContext): import("../core/types").Invocation<"DELAYED_HEARTBEAT", HeartbeatReconnectingStateContext>; + type: "DELAYED_HEARTBEAT"; + cancel: import("../core/types").Invocation<"CANCEL", "DELAYED_HEARTBEAT">; +}; +export type Effects = MapOf; diff --git a/lib/types/event-engine/presence/events.d.ts b/lib/types/event-engine/presence/events.d.ts new file mode 100644 index 000000000..cfceec153 --- /dev/null +++ b/lib/types/event-engine/presence/events.d.ts @@ -0,0 +1,47 @@ +import { PubNubError } from '../../errors/pubnub-error'; +import { MapOf } from '../core'; +export declare const reconnect: { + (): import("../core/types").Event<"RECONNECT", {}>; + type: "RECONNECT"; +}; +export declare const disconnect: { + (): import("../core/types").Event<"DISCONNECT", {}>; + type: "DISCONNECT"; +}; +export declare const joined: { + (channels: string[], groups: string[]): import("../core/types").Event<"JOINED", { + channels: string[]; + groups: string[]; + }>; + type: "JOINED"; +}; +export declare const left: { + (channels: string[], groups: string[]): import("../core/types").Event<"LEFT", { + channels: string[]; + groups: string[]; + }>; + type: "LEFT"; +}; +export declare const leftAll: { + (): import("../core/types").Event<"LEFT_ALL", {}>; + type: "LEFT_ALL"; +}; +export declare const heartbeatSuccess: { + (statusCode: number): import("../core/types").Event<"HEARTBEAT_SUCCESS", { + statusCode: number; + }>; + type: "HEARTBEAT_SUCCESS"; +}; +export declare const heartbeatFailure: { + (error: PubNubError): import("../core/types").Event<"HEARTBEAT_FAILURE", PubNubError>; + type: "HEARTBEAT_FAILURE"; +}; +export declare const heartbeatGiveup: { + (): import("../core/types").Event<"HEARTBEAT_GIVEUP", {}>; + type: "HEARTBEAT_GIVEUP"; +}; +export declare const timesUp: { + (): import("../core/types").Event<"TIMES_UP", {}>; + type: "TIMES_UP"; +}; +export type Events = MapOf; diff --git a/lib/types/event-engine/presence/presence.d.ts b/lib/types/event-engine/presence/presence.d.ts new file mode 100644 index 000000000..42f82e750 --- /dev/null +++ b/lib/types/event-engine/presence/presence.d.ts @@ -0,0 +1,24 @@ +import { Engine } from '../core'; +import * as events from './events'; +import * as effects from './effects'; +import { Dependencies } from './dispatcher'; +export declare class PresenceEventEngine { + private dependencies; + private engine; + private dispatcher; + get _engine(): Engine; + private _unsubscribeEngine; + constructor(dependencies: Dependencies); + channels: string[]; + groups: string[]; + join({ channels, groups }: { + channels?: string[]; + groups?: string[]; + }): void; + leave({ channels, groups }: { + channels?: string[]; + groups?: string[]; + }): void; + leaveAll(): void; + dispose(): void; +} diff --git a/lib/types/event-engine/presence/states/heartbeat_cooldown.d.ts b/lib/types/event-engine/presence/states/heartbeat_cooldown.d.ts new file mode 100644 index 000000000..6b2273d2b --- /dev/null +++ b/lib/types/event-engine/presence/states/heartbeat_cooldown.d.ts @@ -0,0 +1,8 @@ +import { State } from '../../core/state'; +import { Events } from '../events'; +import { Effects } from '../effects'; +export type HeartbeatCooldownStateContext = { + channels: string[]; + groups: string[]; +}; +export declare const HeartbeatCooldownState: State; diff --git a/lib/types/event-engine/presence/states/heartbeat_failed.d.ts b/lib/types/event-engine/presence/states/heartbeat_failed.d.ts new file mode 100644 index 000000000..dce365993 --- /dev/null +++ b/lib/types/event-engine/presence/states/heartbeat_failed.d.ts @@ -0,0 +1,8 @@ +import { State } from '../../core/state'; +import { Events } from '../events'; +import { Effects } from '../effects'; +export type HeartbeatFailedStateContext = { + channels: string[]; + groups: string[]; +}; +export declare const HeartbeatFailedState: State; diff --git a/lib/types/event-engine/presence/states/heartbeat_inactive.d.ts b/lib/types/event-engine/presence/states/heartbeat_inactive.d.ts new file mode 100644 index 000000000..d39ebfb4f --- /dev/null +++ b/lib/types/event-engine/presence/states/heartbeat_inactive.d.ts @@ -0,0 +1,4 @@ +import { State } from '../../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +export declare const HeartbeatInactiveState: State; diff --git a/lib/types/event-engine/presence/states/heartbeat_reconnecting.d.ts b/lib/types/event-engine/presence/states/heartbeat_reconnecting.d.ts new file mode 100644 index 000000000..3a3044a0b --- /dev/null +++ b/lib/types/event-engine/presence/states/heartbeat_reconnecting.d.ts @@ -0,0 +1,11 @@ +import { PubNubError } from '../../../errors/pubnub-error'; +import { State } from '../../core/state'; +import { Events } from '../events'; +import { Effects } from '../effects'; +export type HeartbeatReconnectingStateContext = { + channels: string[]; + groups: string[]; + attempts: number; + reason: PubNubError; +}; +export declare const HearbeatReconnectingState: State; diff --git a/lib/types/event-engine/presence/states/heartbeat_stopped.d.ts b/lib/types/event-engine/presence/states/heartbeat_stopped.d.ts new file mode 100644 index 000000000..9df101a87 --- /dev/null +++ b/lib/types/event-engine/presence/states/heartbeat_stopped.d.ts @@ -0,0 +1,8 @@ +import { State } from '../../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +export type HeartbeatStoppedStateContext = { + channels: string[]; + groups: string[]; +}; +export declare const HeartbeatStoppedState: State; diff --git a/lib/types/event-engine/presence/states/heartbeating.d.ts b/lib/types/event-engine/presence/states/heartbeating.d.ts new file mode 100644 index 000000000..57bc59f8f --- /dev/null +++ b/lib/types/event-engine/presence/states/heartbeating.d.ts @@ -0,0 +1,8 @@ +import { State } from '../../core/state'; +import { Events } from '../events'; +import { Effects } from '../effects'; +export type HeartbeatingStateContext = { + channels: string[]; + groups: string[]; +}; +export declare const HeartbeatingState: State; diff --git a/lib/types/event-engine/states/handshake_failed.d.ts b/lib/types/event-engine/states/handshake_failed.d.ts new file mode 100644 index 000000000..be8769ab6 --- /dev/null +++ b/lib/types/event-engine/states/handshake_failed.d.ts @@ -0,0 +1,12 @@ +import { State } from '../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +import { PubNubError } from '../../errors/pubnub-error'; +import * as Subscription from '../../core/types/api/subscription'; +export type HandshakeFailedStateContext = { + channels: string[]; + groups: string[]; + cursor?: Subscription.SubscriptionCursor; + reason: PubNubError; +}; +export declare const HandshakeFailedState: State; diff --git a/lib/types/event-engine/states/handshake_reconnecting.d.ts b/lib/types/event-engine/states/handshake_reconnecting.d.ts new file mode 100644 index 000000000..ed2817320 --- /dev/null +++ b/lib/types/event-engine/states/handshake_reconnecting.d.ts @@ -0,0 +1,13 @@ +import { PubNubError } from '../../errors/pubnub-error'; +import { State } from '../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +import * as Subscription from '../../core/types/api/subscription'; +export type HandshakeReconnectingStateContext = { + channels: string[]; + groups: string[]; + cursor?: Subscription.SubscriptionCursor; + attempts: number; + reason: PubNubError; +}; +export declare const HandshakeReconnectingState: State; diff --git a/lib/types/event-engine/states/handshake_stopped.d.ts b/lib/types/event-engine/states/handshake_stopped.d.ts new file mode 100644 index 000000000..40ffa7c4c --- /dev/null +++ b/lib/types/event-engine/states/handshake_stopped.d.ts @@ -0,0 +1,11 @@ +import { State } from '../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +import * as Subscription from '../../core/types/api/subscription'; +type HandshakeStoppedStateContext = { + channels: string[]; + groups: string[]; + cursor?: Subscription.SubscriptionCursor; +}; +export declare const HandshakeStoppedState: State; +export {}; diff --git a/lib/types/event-engine/states/handshaking.d.ts b/lib/types/event-engine/states/handshaking.d.ts new file mode 100644 index 000000000..cff30ca43 --- /dev/null +++ b/lib/types/event-engine/states/handshaking.d.ts @@ -0,0 +1,10 @@ +import { State } from '../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +import * as Subscription from '../../core/types/api/subscription'; +export type HandshakingStateContext = { + channels: string[]; + groups: string[]; + cursor?: Subscription.SubscriptionCursor; +}; +export declare const HandshakingState: State; diff --git a/lib/types/event-engine/states/receive_failed.d.ts b/lib/types/event-engine/states/receive_failed.d.ts new file mode 100644 index 000000000..925a8f857 --- /dev/null +++ b/lib/types/event-engine/states/receive_failed.d.ts @@ -0,0 +1,12 @@ +import { State } from '../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +import { PubNubError } from '../../errors/pubnub-error'; +import * as Subscription from '../../core/types/api/subscription'; +export type ReceiveFailedStateContext = { + channels: string[]; + groups: string[]; + cursor: Subscription.SubscriptionCursor; + reason: PubNubError; +}; +export declare const ReceiveFailedState: State; diff --git a/lib/types/event-engine/states/receive_reconnecting.d.ts b/lib/types/event-engine/states/receive_reconnecting.d.ts new file mode 100644 index 000000000..399e76ada --- /dev/null +++ b/lib/types/event-engine/states/receive_reconnecting.d.ts @@ -0,0 +1,13 @@ +import { PubNubError } from '../../errors/pubnub-error'; +import { State } from '../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +import * as Subscription from '../../core/types/api/subscription'; +export type ReceiveReconnectingStateContext = { + channels: string[]; + groups: string[]; + cursor: Subscription.SubscriptionCursor; + attempts: number; + reason: PubNubError; +}; +export declare const ReceiveReconnectingState: State; diff --git a/lib/types/event-engine/states/receive_stopped.d.ts b/lib/types/event-engine/states/receive_stopped.d.ts new file mode 100644 index 000000000..85a3986be --- /dev/null +++ b/lib/types/event-engine/states/receive_stopped.d.ts @@ -0,0 +1,11 @@ +import { State } from '../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +import * as Subscription from '../../core/types/api/subscription'; +type ReceiveStoppedStateContext = { + channels: string[]; + groups: string[]; + cursor: Subscription.SubscriptionCursor; +}; +export declare const ReceiveStoppedState: State; +export {}; diff --git a/lib/types/event-engine/states/receiving.d.ts b/lib/types/event-engine/states/receiving.d.ts new file mode 100644 index 000000000..221353f4f --- /dev/null +++ b/lib/types/event-engine/states/receiving.d.ts @@ -0,0 +1,10 @@ +import { State } from '../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +import * as Subscription from '../../core/types/api/subscription'; +export type ReceivingStateContext = { + channels: string[]; + groups: string[]; + cursor: Subscription.SubscriptionCursor; +}; +export declare const ReceivingState: State; diff --git a/lib/types/event-engine/states/unsubscribed.d.ts b/lib/types/event-engine/states/unsubscribed.d.ts new file mode 100644 index 000000000..ad8a2f25a --- /dev/null +++ b/lib/types/event-engine/states/unsubscribed.d.ts @@ -0,0 +1,4 @@ +import { State } from '../core/state'; +import { Effects } from '../effects'; +import { Events } from '../events'; +export declare const UnsubscribedState: State; diff --git a/lib/types/file/modules/node.d.ts b/lib/types/file/modules/node.d.ts new file mode 100644 index 000000000..63ad822b1 --- /dev/null +++ b/lib/types/file/modules/node.d.ts @@ -0,0 +1,35 @@ +/// +/// +import { Readable, PassThrough } from 'stream'; +import { Buffer } from 'buffer'; +import { PubNubFileInterface } from '../../core/types/file'; +export type PubNubFileParameters = { + stream?: Readable; + data?: Buffer | ArrayBuffer | string; + encoding?: StringEncoding; + name: string; + mimeType?: string; +}; +export default class PubNubFile implements PubNubFileInterface { + static supportsBlob: boolean; + static supportsFile: boolean; + static supportsBuffer: boolean; + static supportsStream: boolean; + static supportsString: boolean; + static supportsArrayBuffer: boolean; + static supportsEncryptFile: boolean; + static supportsFileUri: boolean; + readonly data: Readable | Buffer; + contentLength?: number; + mimeType: string; + name: string; + static create(file: PubNubFileParameters): PubNubFile; + constructor(file: PubNubFileParameters); + toBuffer(): Promise; + toArrayBuffer(): Promise; + toString(encoding?: BufferEncoding): Promise; + toStream(): Promise; + toFile(): Promise; + toFileUri(): Promise>; + toBlob(): Promise; +} diff --git a/lib/types/file/modules/react-native.d.ts b/lib/types/file/modules/react-native.d.ts new file mode 100644 index 000000000..ff707b6bd --- /dev/null +++ b/lib/types/file/modules/react-native.d.ts @@ -0,0 +1,40 @@ +import { PubNubFileInterface } from '../../core/types/file'; +type FileUri = { + uri: string; + name: string; + mimeType?: string; +}; +type ReadableFile = { + arrayBuffer: () => Promise; + blob: () => Promise; + text: () => Promise; +}; +export type PubNubFileParameters = File | FileUri | ReadableFile | { + data: string | Blob | ArrayBuffer | ArrayBufferView; + name: string; + mimeType?: string; +}; +export declare class PubNubFile implements PubNubFileInterface { + static supportsBlob: boolean; + static supportsFile: boolean; + static supportsBuffer: boolean; + static supportsStream: boolean; + static supportsString: boolean; + static supportsArrayBuffer: boolean; + static supportsEncryptFile: boolean; + static supportsFileUri: boolean; + readonly data: File | FileUri | ReadableFile; + contentLength?: number; + mimeType: string; + name: string; + static create(file: PubNubFileParameters): PubNubFile; + constructor(file: PubNubFileParameters); + toBuffer(): Promise; + toArrayBuffer(): Promise; + toString(): Promise; + toStream(): Promise; + toFile(): Promise; + toFileUri(): Promise; + toBlob(): Promise; +} +export default PubNubFile; diff --git a/lib/types/models/Cursor.d.ts b/lib/types/models/Cursor.d.ts new file mode 100644 index 000000000..8ba000353 --- /dev/null +++ b/lib/types/models/Cursor.d.ts @@ -0,0 +1,4 @@ +export type Cursor = { + readonly timetoken: string; + readonly region: number; +}; diff --git a/lib/types/node/configuration.d.ts b/lib/types/node/configuration.d.ts new file mode 100644 index 000000000..042052553 --- /dev/null +++ b/lib/types/node/configuration.d.ts @@ -0,0 +1,13 @@ +import { UserConfiguration, ExtendedConfiguration } from '../core/interfaces/configuration'; +import { TransportKeepAlive } from '../core/interfaces/transport'; +import { Payload } from '../core/types/api'; +import { CryptoModule } from '../core/interfaces/crypto-module'; +export type PubNubConfiguration = UserConfiguration & { + keepAliveSettings?: TransportKeepAlive; + cryptoModule?: CryptoModule; + cipherKey?: string; + useRandomIVs?: boolean; + customEncrypt?: (data: string | Payload) => string; + customDecrypt?: (data: string) => string; +}; +export declare const setDefaults: (configuration: PubNubConfiguration) => PubNubConfiguration & ExtendedConfiguration; diff --git a/lib/types/node/index.d.ts b/lib/types/node/index.d.ts new file mode 100644 index 000000000..f1005d985 --- /dev/null +++ b/lib/types/node/index.d.ts @@ -0,0 +1,18 @@ +/// +/// +import { ProxyAgentOptions } from 'proxy-agent'; +import { Readable } from 'stream'; +import { Buffer } from 'buffer'; +import { CryptoModule } from '../crypto/modules/NodeCryptoModule/nodeCryptoModule'; +import PubNubFile, { PubNubFileParameters } from '../file/modules/node'; +import { PubNubConfiguration } from './configuration'; +import { PubNubFileConstructor } from '../core/types/file'; +import { PubNubCore } from '../core/pubnub-common'; +declare class PubNub extends PubNubCore { + static CryptoModule: typeof CryptoModule; + File: PubNubFileConstructor; + private nodeTransport; + constructor(configuration: PubNubConfiguration); + setProxy(configuration?: ProxyAgentOptions): void; +} +export = PubNub; diff --git a/lib/types/react_native/configuration.d.ts b/lib/types/react_native/configuration.d.ts new file mode 100644 index 000000000..f2f28948b --- /dev/null +++ b/lib/types/react_native/configuration.d.ts @@ -0,0 +1,3 @@ +import { ExtendedConfiguration, UserConfiguration } from '../core/interfaces/configuration'; +export type PubNubConfiguration = UserConfiguration; +export declare const setDefaults: (configuration: PubNubConfiguration) => PubNubConfiguration & ExtendedConfiguration; diff --git a/lib/types/react_native/index.d.ts b/lib/types/react_native/index.d.ts new file mode 100644 index 000000000..aff2a70fa --- /dev/null +++ b/lib/types/react_native/index.d.ts @@ -0,0 +1,7 @@ +import 'react-native-url-polyfill/auto'; +import { PubNubFileParameters } from '../file/modules/react-native'; +import { PubNubConfiguration } from './configuration'; +import { PubNubCore } from '../core/pubnub-common'; +export default class PubNub extends PubNubCore { + constructor(configuration: PubNubConfiguration); +} diff --git a/lib/types/transport/middleware.d.ts b/lib/types/transport/middleware.d.ts new file mode 100644 index 000000000..6d88feba4 --- /dev/null +++ b/lib/types/transport/middleware.d.ts @@ -0,0 +1,30 @@ +import { TransportRequest } from '../core/types/transport-request'; +import { PrivateClientConfiguration } from '../core/interfaces/configuration'; +import { TokenManager } from '../core/components/token_manager'; +import { Transport } from '../core/interfaces/transport'; +type PubNubMiddlewareConfiguration = { + clientConfiguration: PrivateClientConfiguration; + tokenManager: TokenManager; + shaHMAC?: (data: string) => string; + transport: Transport; +}; +export declare class RequestSignature { + private publishKey; + private secretKey; + private hasher; + private static textDecoder; + constructor(publishKey: string, secretKey: string, hasher: (input: string, secret: string) => string); + signature(req: TransportRequest): string; + private queryParameters; +} +export declare class PubNubMiddleware implements Transport { + private configuration; + signatureGenerator?: RequestSignature; + constructor(configuration: PubNubMiddlewareConfiguration); + makeSendable(req: TransportRequest): [Promise, import("../core/types/transport-request").CancellationController | undefined]; + request(req: TransportRequest): TransportRequest; + private authenticateRequest; + private signRequest; + private generatePNSDK; +} +export {}; diff --git a/lib/types/transport/node-transport.d.ts b/lib/types/transport/node-transport.d.ts new file mode 100644 index 000000000..b7af775eb --- /dev/null +++ b/lib/types/transport/node-transport.d.ts @@ -0,0 +1,22 @@ +import { Request } from 'node-fetch'; +import { ProxyAgentOptions } from 'proxy-agent'; +import { CancellationController, TransportRequest } from '../core/types/transport-request'; +import { Transport, TransportKeepAlive } from '../core/interfaces/transport'; +import { TransportResponse } from '../core/types/transport-response'; +export declare class NodeTransport implements Transport { + private readonly keepAlive; + private readonly keepAliveSettings; + private readonly logVerbosity; + protected static decoder: TextDecoder; + private proxyConfiguration?; + private proxyAgent?; + private httpsAgent?; + private httpAgent?; + constructor(keepAlive?: boolean, keepAliveSettings?: TransportKeepAlive, logVerbosity?: boolean); + setProxy(configuration?: ProxyAgentOptions): void; + makeSendable(req: TransportRequest): [Promise, CancellationController | undefined]; + request(req: TransportRequest): TransportRequest; + private requestFromTransportRequest; + private agentForTransportRequest; + protected logRequestProcessProgress(request: Request, elapsed?: number, body?: ArrayBuffer): void; +} diff --git a/lib/types/transport/web-react-native-transport.d.ts b/lib/types/transport/web-react-native-transport.d.ts new file mode 100644 index 000000000..2a5f650dd --- /dev/null +++ b/lib/types/transport/web-react-native-transport.d.ts @@ -0,0 +1,13 @@ +import { CancellationController, TransportRequest } from '../core/types/transport-request'; +import { TransportResponse } from '../core/types/transport-response'; +import { Transport } from '../core/interfaces/transport'; +export declare class WebReactNativeTransport implements Transport { + private keepAlive; + private readonly logVerbosity; + protected static decoder: TextDecoder; + constructor(keepAlive: boolean, logVerbosity: boolean); + makeSendable(req: TransportRequest): [Promise, CancellationController | undefined]; + request(req: TransportRequest): TransportRequest; + private requestFromTransportRequest; + protected logRequestProcessProgress(request: Request, elapsed?: number, body?: ArrayBuffer): void; +} diff --git a/package-lock.json b/package-lock.json index a075d7e07..22d3060ef 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "pubnub", - "version": "8.0.0", + "version": "8.0.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "pubnub", - "version": "8.0.0", + "version": "8.0.1", "license": "SEE LICENSE IN LICENSE", "dependencies": { "agentkeepalive": "^3.5.2", diff --git a/package.json b/package.json index 6eeacb20e..5c26ca43c 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,7 @@ "type": "git", "url": "git://github.com/pubnub/javascript.git" }, + "keywords": [ "cloud", "publish", diff --git a/rollup.config.js b/rollup.config.js index 9eeb322f3..cc481e66e 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -54,7 +54,7 @@ export default [ ], }, { - input: 'src/transport/service-worker/subscription-service-worker.ts', + input: 'src/transport/subscription-worker/subscription-worker.ts', output: { file: join(dirname(browser), basename(browser, '.min.js') + '.worker.min.js'), format: 'umd', @@ -69,7 +69,7 @@ export default [ ], }, { - input: 'src/transport/service-worker/subscription-service-worker.ts', + input: 'src/transport/subscription-worker/subscription-worker.ts', output: { file: join(dirname(browser), basename(browser, '.min.js') + '.worker.js'), format: 'umd', @@ -158,7 +158,7 @@ export default [ ], }, { - input: 'src/transport/service-worker/subscription-service-worker.ts', + input: 'src/transport/subscription-worker/subscription-worker.ts', output: { file: `upload/gzip/pubnub.worker.${version}.min.js`, format: 'umd', @@ -174,7 +174,7 @@ export default [ ], }, { - input: 'src/transport/service-worker/subscription-service-worker.ts', + input: 'src/transport/subscription-worker/subscription-worker.ts', output: { file: `upload/gzip/pubnub.worker.${version}.js`, format: 'umd', @@ -189,7 +189,7 @@ export default [ ], }, { - input: 'src/transport/service-worker/subscription-service-worker.ts', + input: 'src/transport/subscription-worker/subscription-worker.ts', output: { file: `upload/normal/pubnub.worker.${version}.min.js`, format: 'umd', @@ -204,7 +204,7 @@ export default [ ], }, { - input: 'src/transport/service-worker/subscription-service-worker.ts', + input: 'src/transport/subscription-worker/subscription-worker.ts', output: { file: `upload/normal/pubnub.worker.${version}.js`, format: 'umd', diff --git a/src/cbor/common.ts b/src/cbor/common.ts index a4149ca82..26c0ba1dd 100644 --- a/src/cbor/common.ts +++ b/src/cbor/common.ts @@ -4,6 +4,8 @@ /** * CBOR data decoder. + * + * @internal */ export default class Cbor { constructor( diff --git a/src/core/components/abort_signal.ts b/src/core/components/abort_signal.ts index ac990b782..caffb93c3 100644 --- a/src/core/components/abort_signal.ts +++ b/src/core/components/abort_signal.ts @@ -10,6 +10,11 @@ export class AbortError extends Error { } } +/** + * Event Engine stored effect processing cancellation signal. + * + * @internal + */ export class AbortSignal extends Subject { private _aborted = false; diff --git a/src/core/components/base64_codec.ts b/src/core/components/base64_codec.ts index 7908d5c75..c447673b7 100644 --- a/src/core/components/base64_codec.ts +++ b/src/core/components/base64_codec.ts @@ -5,6 +5,8 @@ const BASE64_CHARMAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123 * * @param paddedInput Base64 string with padding * @returns ArrayBuffer with decoded data + * + * @internal */ export function decode(paddedInput: string): ArrayBuffer { // Remove up to last two equal signs. @@ -54,6 +56,14 @@ export function decode(paddedInput: string): ArrayBuffer { return data; } +/** + * Encode `ArrayBuffer` as a Base64 encoded string. + * + * @param input ArrayBuffer with source data. + * @returns Base64 string with padding. + * + * @internal + */ export function encode(input: ArrayBuffer): string { let base64 = ''; const encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; diff --git a/src/core/components/configuration.ts b/src/core/components/configuration.ts index d46d2c5f1..316a122c6 100644 --- a/src/core/components/configuration.ts +++ b/src/core/components/configuration.ts @@ -15,6 +15,8 @@ import { Payload } from '../types/api'; /** * Whether encryption (if set) should use random initialization vector or not. + * + * @internal */ const USE_RANDOM_INITIALIZATION_VECTOR = true; // endregion @@ -23,6 +25,8 @@ const USE_RANDOM_INITIALIZATION_VECTOR = true; * Crypto Module instance configuration function. * * Function will be used each time when `cipherKey` will be changed. + * + * @internal */ type SetupCryptoModule = (configuration: CryptorConfiguration) => CryptoModule | undefined; @@ -69,6 +73,8 @@ type PrivateConfigurationFields = { * @param setupCryptoModule - Platform-provided {@link CryptoModule} configuration block. * * @returns `PubNub` client private configuration. + * + * @internal */ export const makeConfiguration = ( base: ExtendedConfiguration & PlatformConfiguration, diff --git a/src/core/components/deduping_manager.js b/src/core/components/deduping_manager.js index ab8aa9607..7d1503ce8 100644 --- a/src/core/components/deduping_manager.js +++ b/src/core/components/deduping_manager.js @@ -11,6 +11,11 @@ const hashCode = (payload) => { return hash; }; +/** + * Real-time events deduplication manager. + * + * @internal + */ export default class { _config; diff --git a/src/core/components/eventEmitter.ts b/src/core/components/eventEmitter.ts index 7f10d3112..bedc98ac8 100644 --- a/src/core/components/eventEmitter.ts +++ b/src/core/components/eventEmitter.ts @@ -2,6 +2,14 @@ import { Listener, ListenerManager } from './listener_manager'; import * as Subscription from '../types/api/subscription'; import { PubNubEventType } from '../endpoints/subscribe'; +/** + * Real-time events' emitter. + * + * Emitter responsible for forwarding received real-time events to the closures which has been + * registered for specific events handling. + * + * @internal + */ export default class EventEmitter { /** * Map of channels to listener callbacks for them. diff --git a/src/core/components/listener_manager.ts b/src/core/components/listener_manager.ts index 49e4c47d5..dd8d56040 100644 --- a/src/core/components/listener_manager.ts +++ b/src/core/components/listener_manager.ts @@ -95,6 +95,8 @@ export type Listener = { /** * Real-time listeners' manager. + * + * @internal */ export class ListenerManager { /** diff --git a/src/core/components/reconnection_manager.ts b/src/core/components/reconnection_manager.ts index eac22539b..2b3c18ba3 100644 --- a/src/core/components/reconnection_manager.ts +++ b/src/core/components/reconnection_manager.ts @@ -6,6 +6,13 @@ import { PubNubCore } from '../pubnub-common'; +/** + * Network "discovery" manager. + * + * Manager perform periodic `time` API calls to identify network availability. + * + * @internal + */ export class ReconnectionManager { /** * Successful availability check callback. diff --git a/src/core/components/request.ts b/src/core/components/request.ts index c0f328c73..f39499610 100644 --- a/src/core/components/request.ts +++ b/src/core/components/request.ts @@ -8,6 +8,8 @@ import uuidGenerator from './uuid'; /** * Base REST API request class. + * + * @internal */ export abstract class AbstractRequest implements Request { /** diff --git a/src/core/components/stringify_buffer_keys.ts b/src/core/components/stringify_buffer_keys.ts index 2b9247ff1..eff039140 100644 --- a/src/core/components/stringify_buffer_keys.ts +++ b/src/core/components/stringify_buffer_keys.ts @@ -1,3 +1,12 @@ +/** + * Re-map CBOR object keys from potentially C buffer strings to actual strings. + * + * @param obj CBOR which should be remapped to stringified keys. + * + * @returns Dictionary with stringified keys. + * + * @internal + */ export function stringifyBufferKeys(obj: unknown): Record { const isObject = (value: unknown): value is Record => typeof value === 'object' && value !== null && value.constructor === Object; diff --git a/src/core/components/subject.ts b/src/core/components/subject.ts index cad6fdffd..67d53a77a 100644 --- a/src/core/components/subject.ts +++ b/src/core/components/subject.ts @@ -1,5 +1,8 @@ type Listener = (event: T) => void; +/** + * @internal + */ export class Subject { protected listeners: Set> = new Set(); diff --git a/src/core/components/subscription-manager.ts b/src/core/components/subscription-manager.ts index 3f295c200..19b74ffdc 100644 --- a/src/core/components/subscription-manager.ts +++ b/src/core/components/subscription-manager.ts @@ -18,6 +18,8 @@ import EventEmitter from './eventEmitter'; /** * Subscription loop manager. + * + * @internal */ export class SubscriptionManager { /** diff --git a/src/core/components/token_manager.ts b/src/core/components/token_manager.ts index 97c5944d3..e60cf2a3f 100644 --- a/src/core/components/token_manager.ts +++ b/src/core/components/token_manager.ts @@ -192,6 +192,8 @@ type RawToken = { * REST API access token manager. * * Manager maintains active access token and let parse it to get information about permissions. + * + * @internal */ export class TokenManager { /** diff --git a/src/core/endpoints/access_manager/audit.ts b/src/core/endpoints/access_manager/audit.ts index e9aa8b8fd..bfcea42d3 100644 --- a/src/core/endpoints/access_manager/audit.ts +++ b/src/core/endpoints/access_manager/audit.ts @@ -64,6 +64,8 @@ type ServiceResponse = { /** * Permissions audit request. + * + * @internal */ export class AuditRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/access_manager/grant.ts b/src/core/endpoints/access_manager/grant.ts index 43b98208d..bf83c69b1 100644 --- a/src/core/endpoints/access_manager/grant.ts +++ b/src/core/endpoints/access_manager/grant.ts @@ -94,6 +94,8 @@ type ServiceResponse = { /** * Grant permissions request. + * + * @internal */ export class GrantRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/access_manager/grant_token.ts b/src/core/endpoints/access_manager/grant_token.ts index cd9b898dd..5c6d5de6a 100644 --- a/src/core/endpoints/access_manager/grant_token.ts +++ b/src/core/endpoints/access_manager/grant_token.ts @@ -88,6 +88,8 @@ type ServiceResponse = { /** * Grant token permissions request. + * + * @internal */ export class GrantTokenRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/access_manager/revoke_token.ts b/src/core/endpoints/access_manager/revoke_token.ts index da4d95578..0063dab80 100644 --- a/src/core/endpoints/access_manager/revoke_token.ts +++ b/src/core/endpoints/access_manager/revoke_token.ts @@ -52,6 +52,8 @@ type ServiceResponse = { * Access token revoke request. * * Invalidate token and permissions which has been granted for it. + * + * @internal */ export class RevokeTokenRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/actions/add_message_action.ts b/src/core/endpoints/actions/add_message_action.ts index e14a4142a..6f1192b58 100644 --- a/src/core/endpoints/actions/add_message_action.ts +++ b/src/core/endpoints/actions/add_message_action.ts @@ -45,6 +45,8 @@ type ServiceResponse = { /** * Add Message Reaction request. + * + * @internal */ export class AddMessageActionRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/actions/get_message_actions.ts b/src/core/endpoints/actions/get_message_actions.ts index 60a729830..1bd8bb02b 100644 --- a/src/core/endpoints/actions/get_message_actions.ts +++ b/src/core/endpoints/actions/get_message_actions.ts @@ -49,6 +49,8 @@ type ServiceResponse = { /** * Fetch channel message actions request. + * + * @internal */ export class GetMessageActionsRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/actions/remove_message_action.ts b/src/core/endpoints/actions/remove_message_action.ts index a7b397d7c..8c2eed84e 100644 --- a/src/core/endpoints/actions/remove_message_action.ts +++ b/src/core/endpoints/actions/remove_message_action.ts @@ -45,6 +45,8 @@ type ServiceResponse = { /** * Remove specific message action request. + * + * @internal */ export class RemoveMessageAction extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/channel_groups/add_channels.ts b/src/core/endpoints/channel_groups/add_channels.ts index 326e742c9..ad5e5473d 100644 --- a/src/core/endpoints/channel_groups/add_channels.ts +++ b/src/core/endpoints/channel_groups/add_channels.ts @@ -54,6 +54,8 @@ type ServiceResponse = { /** * Add channel group channels request. + * + * @internal */ export class AddChannelGroupChannelsRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/channel_groups/delete_group.ts b/src/core/endpoints/channel_groups/delete_group.ts index e06a68c28..526e91098 100644 --- a/src/core/endpoints/channel_groups/delete_group.ts +++ b/src/core/endpoints/channel_groups/delete_group.ts @@ -54,6 +54,8 @@ type ServiceResponse = { /** * Channel group delete request. + * + * @internal */ export class DeleteChannelGroupRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/channel_groups/list_channels.ts b/src/core/endpoints/channel_groups/list_channels.ts index d5bf3b8fa..a7d66308e 100644 --- a/src/core/endpoints/channel_groups/list_channels.ts +++ b/src/core/endpoints/channel_groups/list_channels.ts @@ -69,6 +69,8 @@ type ServiceResponse = { /** * List Channel Group Channels request. + * + * @internal */ export class ListChannelGroupChannels extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/channel_groups/list_groups.ts b/src/core/endpoints/channel_groups/list_groups.ts index 2d4ef4a02..531da6f4f 100644 --- a/src/core/endpoints/channel_groups/list_groups.ts +++ b/src/core/endpoints/channel_groups/list_groups.ts @@ -68,6 +68,8 @@ type ServiceResponse = { /** * List all channel groups request. + * + * @internal */ export class ListChannelGroupsRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/channel_groups/remove_channels.ts b/src/core/endpoints/channel_groups/remove_channels.ts index 0301d36e5..d8f78d1c9 100644 --- a/src/core/endpoints/channel_groups/remove_channels.ts +++ b/src/core/endpoints/channel_groups/remove_channels.ts @@ -54,6 +54,8 @@ type ServiceResponse = { /** * Remove channel group channels request. + * + * @internal */ // prettier-ignore export class RemoveChannelGroupChannelsRequest extends AbstractRequest< diff --git a/src/core/endpoints/fetch_messages.ts b/src/core/endpoints/fetch_messages.ts index cb5927495..a8b0298b0 100644 --- a/src/core/endpoints/fetch_messages.ts +++ b/src/core/endpoints/fetch_messages.ts @@ -162,6 +162,8 @@ type ServiceResponse = { /** * Fetch messages from channels request. + * + * @internal */ export class FetchMessagesRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/file_upload/delete_file.ts b/src/core/endpoints/file_upload/delete_file.ts index 7ccacb914..fc5dcc976 100644 --- a/src/core/endpoints/file_upload/delete_file.ts +++ b/src/core/endpoints/file_upload/delete_file.ts @@ -40,6 +40,8 @@ type ServiceResponse = { /** * Delete File request. + * + * @internal */ export class DeleteFileRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/file_upload/download_file.ts b/src/core/endpoints/file_upload/download_file.ts index 6f91ec76a..9d1c9bade 100644 --- a/src/core/endpoints/file_upload/download_file.ts +++ b/src/core/endpoints/file_upload/download_file.ts @@ -45,6 +45,8 @@ type RequestParameters = FileSharing.DownloadFileParameters & { /** * Download File request. + * + * @internal */ export class DownloadFileRequest< PlatformFile extends Partial = Record, diff --git a/src/core/endpoints/file_upload/generate_upload_url.ts b/src/core/endpoints/file_upload/generate_upload_url.ts index 8f1b43b1c..264d57365 100644 --- a/src/core/endpoints/file_upload/generate_upload_url.ts +++ b/src/core/endpoints/file_upload/generate_upload_url.ts @@ -100,6 +100,8 @@ type ServiceResponse = { /** * Generate File Upload Url request. + * + * @internal */ export class GenerateFileUploadUrlRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/file_upload/get_file_url.ts b/src/core/endpoints/file_upload/get_file_url.ts index 300ed96d6..449284416 100644 --- a/src/core/endpoints/file_upload/get_file_url.ts +++ b/src/core/endpoints/file_upload/get_file_url.ts @@ -30,6 +30,8 @@ type RequestParameters = FileSharing.FileUrlParameters & { * File download Url generation request. * * Local request which generates Url to download shared file from the specific channel. + * + * @internal */ export class GetFileDownloadUrlRequest extends AbstractRequest { /** diff --git a/src/core/endpoints/file_upload/list_files.ts b/src/core/endpoints/file_upload/list_files.ts index 0d1f95304..7f899f7ea 100644 --- a/src/core/endpoints/file_upload/list_files.ts +++ b/src/core/endpoints/file_upload/list_files.ts @@ -65,6 +65,8 @@ type ServiceResponse = { /** * Files List request. + * + * @internal */ export class FilesListRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/file_upload/publish_file.ts b/src/core/endpoints/file_upload/publish_file.ts index a88fd5682..0c9af86e6 100644 --- a/src/core/endpoints/file_upload/publish_file.ts +++ b/src/core/endpoints/file_upload/publish_file.ts @@ -49,6 +49,11 @@ type RequestParameters = FileSharing.PublishFileMessageParameters & { type ServiceResponse = [0 | 1, string, string]; // endregion +/** + * Publish shared file information request. + * + * @internal + */ export class PublishFileMessageRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); diff --git a/src/core/endpoints/file_upload/send_file.ts b/src/core/endpoints/file_upload/send_file.ts index 0c50dfae6..97fad2f1c 100644 --- a/src/core/endpoints/file_upload/send_file.ts +++ b/src/core/endpoints/file_upload/send_file.ts @@ -72,6 +72,8 @@ type RequestParameters = FileSharing.SendFileParameters { /** diff --git a/src/core/endpoints/file_upload/upload-file.ts b/src/core/endpoints/file_upload/upload-file.ts index 7147e819c..e63e8c6b4 100644 --- a/src/core/endpoints/file_upload/upload-file.ts +++ b/src/core/endpoints/file_upload/upload-file.ts @@ -11,6 +11,8 @@ import { PubNubFileInterface } from '../../types/file'; /** * File Upload request. + * + * @internal */ export class UploadFileRequest extends AbstractRequest { constructor(private readonly parameters: FileSharing.UploadFileParameters) { diff --git a/src/core/endpoints/history/delete_messages.ts b/src/core/endpoints/history/delete_messages.ts index f2a4f8269..4a12022eb 100644 --- a/src/core/endpoints/history/delete_messages.ts +++ b/src/core/endpoints/history/delete_messages.ts @@ -50,6 +50,8 @@ type ServiceResponse = { /** * Delete messages from channel history. + * + * @internal */ export class DeleteMessageRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/history/get_history.ts b/src/core/endpoints/history/get_history.ts index 206a05b57..b340aba49 100644 --- a/src/core/endpoints/history/get_history.ts +++ b/src/core/endpoints/history/get_history.ts @@ -103,6 +103,8 @@ type ServiceResponse = [ /** * Get single channel messages request. + * + * @internal */ export class GetHistoryRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/history/message_counts.ts b/src/core/endpoints/history/message_counts.ts index 6672fe8e4..8413b6b3b 100644 --- a/src/core/endpoints/history/message_counts.ts +++ b/src/core/endpoints/history/message_counts.ts @@ -68,6 +68,11 @@ type ServiceResponse = { }; // endregion +/** + * Count messages request. + * + * @internal + */ export class MessageCountRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); diff --git a/src/core/endpoints/objects/channel/get.ts b/src/core/endpoints/objects/channel/get.ts index 3c1534218..6136f62c9 100644 --- a/src/core/endpoints/objects/channel/get.ts +++ b/src/core/endpoints/objects/channel/get.ts @@ -40,6 +40,8 @@ type RequestParameters = AppContext.GetChannelMetadataParameters & { /** * Get Channel Metadata request. + * + * @internal */ export class GetChannelMetadataRequest< Response extends AppContext.GetChannelMetadataResponse, diff --git a/src/core/endpoints/objects/channel/get_all.ts b/src/core/endpoints/objects/channel/get_all.ts index cd442c42f..b4f97889b 100644 --- a/src/core/endpoints/objects/channel/get_all.ts +++ b/src/core/endpoints/objects/channel/get_all.ts @@ -50,6 +50,8 @@ type RequestParameters, diff --git a/src/core/endpoints/objects/channel/remove.ts b/src/core/endpoints/objects/channel/remove.ts index 50918491d..05148fdc4 100644 --- a/src/core/endpoints/objects/channel/remove.ts +++ b/src/core/endpoints/objects/channel/remove.ts @@ -30,6 +30,8 @@ type RequestParameters = AppContext.RemoveChannelMetadataParameters & { /** * Remove Channel Metadata request. + * + * @internal */ export class RemoveChannelMetadataRequest< Response extends AppContext.RemoveChannelMetadataResponse, diff --git a/src/core/endpoints/objects/channel/set.ts b/src/core/endpoints/objects/channel/set.ts index 555604d2c..57482a05e 100644 --- a/src/core/endpoints/objects/channel/set.ts +++ b/src/core/endpoints/objects/channel/set.ts @@ -41,6 +41,8 @@ type RequestParameters = AppContext.SetChannelMetadataParameters, diff --git a/src/core/endpoints/objects/member/get.ts b/src/core/endpoints/objects/member/get.ts index 1b80c78b8..2425c258e 100644 --- a/src/core/endpoints/objects/member/get.ts +++ b/src/core/endpoints/objects/member/get.ts @@ -75,6 +75,8 @@ type RequestParameters = AppContext.GetMembersParameters & { /** * Get Channel Members request. + * + * @internal */ export class GetChannelMembersRequest< Response extends AppContext.GetMembersResponse, diff --git a/src/core/endpoints/objects/member/set.ts b/src/core/endpoints/objects/member/set.ts index c5bb2500d..f0d5b3ed7 100644 --- a/src/core/endpoints/objects/member/set.ts +++ b/src/core/endpoints/objects/member/set.ts @@ -66,6 +66,8 @@ type RequestParameters = AppContext.SetChannelMembersParameters, diff --git a/src/core/endpoints/objects/membership/get.ts b/src/core/endpoints/objects/membership/get.ts index 34e2b6dab..30048e526 100644 --- a/src/core/endpoints/objects/membership/get.ts +++ b/src/core/endpoints/objects/membership/get.ts @@ -75,6 +75,8 @@ type RequestParameters = AppContext.GetMembershipsParameters & { /** * Get UUID Memberships request. + * + * @internal */ export class GetUUIDMembershipsRequest< Response extends AppContext.GetMembershipsResponse, diff --git a/src/core/endpoints/objects/membership/set.ts b/src/core/endpoints/objects/membership/set.ts index 1633dcce1..5b1edc29e 100644 --- a/src/core/endpoints/objects/membership/set.ts +++ b/src/core/endpoints/objects/membership/set.ts @@ -66,6 +66,8 @@ type RequestParameters = AppContext.SetMembershipsParameters, diff --git a/src/core/endpoints/objects/uuid/get.ts b/src/core/endpoints/objects/uuid/get.ts index 7a93648aa..b58342797 100644 --- a/src/core/endpoints/objects/uuid/get.ts +++ b/src/core/endpoints/objects/uuid/get.ts @@ -40,6 +40,8 @@ type RequestParameters = AppContext.GetUUIDMetadataParameters & { /** * Get UUID Metadata request. + * + * @internal */ export class GetUUIDMetadataRequest< Response extends AppContext.GetUUIDMetadataResponse, diff --git a/src/core/endpoints/objects/uuid/get_all.ts b/src/core/endpoints/objects/uuid/get_all.ts index c7b5efca8..744a4d6e8 100644 --- a/src/core/endpoints/objects/uuid/get_all.ts +++ b/src/core/endpoints/objects/uuid/get_all.ts @@ -43,6 +43,11 @@ type RequestParameters, Custom extends AppContext.CustomData = AppContext.CustomData, diff --git a/src/core/endpoints/objects/uuid/remove.ts b/src/core/endpoints/objects/uuid/remove.ts index 2bc521d6f..b84707fde 100644 --- a/src/core/endpoints/objects/uuid/remove.ts +++ b/src/core/endpoints/objects/uuid/remove.ts @@ -30,6 +30,8 @@ type RequestParameters = AppContext.RemoveUUIDMetadataParameters & { /** * Remove UUID Metadata request. + * + * @internal */ export class RemoveUUIDMetadataRequest< Response extends AppContext.RemoveUUIDMetadataResponse, diff --git a/src/core/endpoints/objects/uuid/set.ts b/src/core/endpoints/objects/uuid/set.ts index 9ba8736c7..403ebd1aa 100644 --- a/src/core/endpoints/objects/uuid/set.ts +++ b/src/core/endpoints/objects/uuid/set.ts @@ -41,6 +41,8 @@ type RequestParameters = AppContext.SetUUIDMetadataParameters, diff --git a/src/core/endpoints/presence/get_state.ts b/src/core/endpoints/presence/get_state.ts index ede87639e..3a00f1893 100644 --- a/src/core/endpoints/presence/get_state.ts +++ b/src/core/endpoints/presence/get_state.ts @@ -59,6 +59,8 @@ type ServiceResponse = { /** * Get `uuid` presence state request. + * + * @internal */ export class GetPresenceStateRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/presence/heartbeat.ts b/src/core/endpoints/presence/heartbeat.ts index 80c26f1d3..71eeece41 100644 --- a/src/core/endpoints/presence/heartbeat.ts +++ b/src/core/endpoints/presence/heartbeat.ts @@ -47,6 +47,11 @@ type ServiceResponse = { }; // endregion +/** + * Announce `uuid` presence request. + * + * @internal + */ export class HeartbeatRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); diff --git a/src/core/endpoints/presence/here_now.ts b/src/core/endpoints/presence/here_now.ts index 79eaa7af3..db494f9ad 100644 --- a/src/core/endpoints/presence/here_now.ts +++ b/src/core/endpoints/presence/here_now.ts @@ -124,6 +124,11 @@ type MultipleChannelServiceResponse = BasicServiceResponse & { type ServiceResponse = SingleChannelServiceResponse | MultipleChannelServiceResponse; // endregion +/** + * Channel presence request. + * + * @internal + */ export class HereNowRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); diff --git a/src/core/endpoints/presence/leave.ts b/src/core/endpoints/presence/leave.ts index 4dfb32194..36ff29c1f 100644 --- a/src/core/endpoints/presence/leave.ts +++ b/src/core/endpoints/presence/leave.ts @@ -52,6 +52,11 @@ type ServiceResponse = { }; // endregion +/** + * Announce user leave request. + * + * @internal + */ export class PresenceLeaveRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); diff --git a/src/core/endpoints/presence/set_state.ts b/src/core/endpoints/presence/set_state.ts index 583ff2343..9e0776bef 100644 --- a/src/core/endpoints/presence/set_state.ts +++ b/src/core/endpoints/presence/set_state.ts @@ -59,6 +59,8 @@ type ServiceResponse = { /** * Set `uuid` presence state request. + * + * @internal */ export class SetPresenceStateRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/presence/where_now.ts b/src/core/endpoints/presence/where_now.ts index 379b578a3..533a3f73b 100644 --- a/src/core/endpoints/presence/where_now.ts +++ b/src/core/endpoints/presence/where_now.ts @@ -57,6 +57,11 @@ type ServiceResponse = { }; // endregion +/** + * Get `uuid` presence request. + * + * @internal + */ export class WhereNowRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); diff --git a/src/core/endpoints/publish.ts b/src/core/endpoints/publish.ts index 93f369c8b..47c9110e2 100644 --- a/src/core/endpoints/publish.ts +++ b/src/core/endpoints/publish.ts @@ -127,6 +127,8 @@ type ServiceResponse = [0 | 1, string, string]; * * Request will normalize and encrypt (if required) provided data and push it to the specified * channel. + * + * @internal */ export class PublishRequest extends AbstractRequest { /** diff --git a/src/core/endpoints/push/add_push_channels.ts b/src/core/endpoints/push/add_push_channels.ts index 8692f4b50..5265071d9 100644 --- a/src/core/endpoints/push/add_push_channels.ts +++ b/src/core/endpoints/push/add_push_channels.ts @@ -32,6 +32,8 @@ type ServiceResponse = [0 | 1, string]; /** * Register channels with device push request. + * + * @internal */ // prettier-ignore export class AddDevicePushNotificationChannelsRequest extends BasePushNotificationChannelsRequest< diff --git a/src/core/endpoints/push/list_push_channels.ts b/src/core/endpoints/push/list_push_channels.ts index 725bbbefc..1892463a3 100644 --- a/src/core/endpoints/push/list_push_channels.ts +++ b/src/core/endpoints/push/list_push_channels.ts @@ -32,6 +32,8 @@ type ServiceResponse = string[]; /** * List device push enabled channels request. + * + * @internal */ // prettier-ignore export class ListDevicePushNotificationChannelsRequest extends BasePushNotificationChannelsRequest< diff --git a/src/core/endpoints/push/push.ts b/src/core/endpoints/push/push.ts index 20e231d62..660435f30 100644 --- a/src/core/endpoints/push/push.ts +++ b/src/core/endpoints/push/push.ts @@ -47,6 +47,8 @@ type RequestParameters = (Push.ManageDeviceChannelsParameters | Push.RemoveDevic /** * Base push notification request. + * + * @internal */ export class BasePushNotificationChannelsRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { diff --git a/src/core/endpoints/push/remove_device.ts b/src/core/endpoints/push/remove_device.ts index 5fd4235f3..e0108d5fe 100644 --- a/src/core/endpoints/push/remove_device.ts +++ b/src/core/endpoints/push/remove_device.ts @@ -32,6 +32,8 @@ type ServiceResponse = [0 | 1, string]; /** * Unregister device push notifications request. + * + * @internal */ // prettier-ignore export class RemoveDevicePushNotificationRequest extends BasePushNotificationChannelsRequest< diff --git a/src/core/endpoints/push/remove_push_channels.ts b/src/core/endpoints/push/remove_push_channels.ts index 69a939045..ce4fac47e 100644 --- a/src/core/endpoints/push/remove_push_channels.ts +++ b/src/core/endpoints/push/remove_push_channels.ts @@ -32,6 +32,8 @@ type ServiceResponse = [0 | 1, string]; /** * Unregister channels from device push request. + * + * @internal */ // prettier-ignore export class RemoveDevicePushNotificationChannelsRequest extends BasePushNotificationChannelsRequest< diff --git a/src/core/endpoints/signal.ts b/src/core/endpoints/signal.ts index b17379d89..5d1c84d05 100644 --- a/src/core/endpoints/signal.ts +++ b/src/core/endpoints/signal.ts @@ -57,6 +57,11 @@ type RequestParameters = SignalParameters & { type ServiceResponse = [0 | 1, string, string]; // endregion +/** + * Signal data (size-limited) publish request. + * + * @internal + */ export class SignalRequest extends AbstractRequest { constructor(private readonly parameters: RequestParameters) { super(); diff --git a/src/core/endpoints/subscribe.ts b/src/core/endpoints/subscribe.ts index d31302ce5..ee179ab24 100644 --- a/src/core/endpoints/subscribe.ts +++ b/src/core/endpoints/subscribe.ts @@ -32,6 +32,8 @@ const WITH_PRESENCE = false; /** * PubNub-defined event types by payload. + * + * @internal */ export enum PubNubEventType { /** @@ -191,6 +193,8 @@ type PresenceStateChangeData = { /** * Channel presence service response. + * + * @internal */ export type PresenceData = PresenceIntervalData | PresenceChangeData | PresenceStateChangeData; // endregion @@ -198,6 +202,8 @@ export type PresenceData = PresenceIntervalData | PresenceChangeData | PresenceS // region Message Actions service response /** * Message reaction change service response. + * + * @internal */ export type MessageActionData = { /** @@ -303,6 +309,8 @@ type ChannelObjectData = ObjectData< /** * `Space` object change real-time service response. + * + * @internal */ export type SpaceObjectData = ObjectData< AppContextVSPEvents, @@ -317,6 +325,8 @@ type UuidObjectData = ObjectData { constructor(protected readonly parameters: RequestParameters) { @@ -840,6 +860,8 @@ export class BaseSubscribeRequest extends AbstractRequest { constructor() { super(); diff --git a/src/core/interfaces/configuration.ts b/src/core/interfaces/configuration.ts index 4003f427b..dc8409957 100644 --- a/src/core/interfaces/configuration.ts +++ b/src/core/interfaces/configuration.ts @@ -325,6 +325,8 @@ export type UserConfiguration = { * Extended client configuration. * * Extended configuration contains unannounced configuration options. + * + * @internal */ export type ExtendedConfiguration = UserConfiguration & { /** diff --git a/src/core/interfaces/request.ts b/src/core/interfaces/request.ts index 77168006f..df1e443b7 100644 --- a/src/core/interfaces/request.ts +++ b/src/core/interfaces/request.ts @@ -4,6 +4,8 @@ import RequestOperation from '../constants/operations'; /** * General REST API call request interface. + * + * @internal */ export interface Request { /** diff --git a/src/core/pubnub-common.ts b/src/core/pubnub-common.ts index bfac679c0..fbde5b550 100644 --- a/src/core/pubnub-common.ts +++ b/src/core/pubnub-common.ts @@ -150,6 +150,8 @@ export class PubNubCore< > { /** * PubNub client configuration. + * + * @internal */ protected readonly _configuration: PrivateClientConfiguration; @@ -157,71 +159,98 @@ export class PubNubCore< * Subscription loop manager. * * **Note:** Manager created when EventEngine is off. + * + * @internal */ private readonly subscriptionManager?: SubscriptionManager; /** * Transport for network requests processing. + * + * @internal */ protected readonly transport: Transport; /** * REST API endpoints access tokens manager. + * + * @internal */ private readonly tokenManager: TokenManager; /** * Legacy crypto module implementation. + * + * @internal */ private readonly cryptography?: Cryptography; /** * Legacy crypto (legacy data encryption / decryption and request signature support). + * + * @internal */ private readonly crypto?: Crypto; /** * Real-time event listeners manager. + * + * @internal */ protected readonly listenerManager: ListenerManager; /** * User's presence event engine. + * + * @internal */ private presenceEventEngine?: PresenceEventEngine; /** * Subscription event engine. + * + * @internal */ private readonly eventEngine?: EventEngine; /** * Client-managed presence information. + * + * @internal */ private readonly presenceState?: Record; /** * Real-time events emitter. + * + * @internal */ private readonly eventEmitter: EventEmitter; /** * PubNub App Context REST API entry point. + * + * @internal */ private readonly _objects: PubNubObjects; /** * PubNub Channel Group REST API entry point. */ + // @internal @ts-ignore private readonly _channelGroups: PubNubChannelGroups; /** * PubNub Push Notification REST API entry point. + * + * @internal */ private readonly _push: PubNubPushNotifications; /** - * {@link ArrayBuffer} to {@link string} decoder. + * {@link ArrayBuffer} to {@link string} decoder. + * + * @internal */ private static decoder = new TextDecoder(); diff --git a/src/core/utils.ts b/src/core/utils.ts index dc65d95b4..5cee8bf45 100644 --- a/src/core/utils.ts +++ b/src/core/utils.ts @@ -27,7 +27,7 @@ export const encodeNames = (names: string[], defaultString?: string) => { return encodedNames.length ? encodedNames.join(',') : defaultString ?? ''; }; -export const removeSingleOccurance = (source: string[], elementsToRemove: string[]) => { +export const removeSingleOccurrence = (source: string[], elementsToRemove: string[]) => { const removed = Object.fromEntries(elementsToRemove.map((prop) => [prop, false])); return source.filter((e) => { diff --git a/src/event-engine/index.ts b/src/event-engine/index.ts index 871d78c7e..983a659c5 100644 --- a/src/event-engine/index.ts +++ b/src/event-engine/index.ts @@ -76,12 +76,12 @@ export class EventEngine { } unsubscribe({ channels = [], channelGroups = [] }: { channels?: string[]; channelGroups?: string[] }): void { - const filteredChannels = utils.removeSingleOccurance(this.channels, [ + const filteredChannels = utils.removeSingleOccurrence(this.channels, [ ...channels, ...channels.map((c) => `${c}-pnpres`), ]); - const filteredGroups = utils.removeSingleOccurance(this.groups, [ + const filteredGroups = utils.removeSingleOccurrence(this.groups, [ ...channelGroups, ...channelGroups.map((c) => `${c}-pnpres`), ]); diff --git a/src/node/configuration.ts b/src/node/configuration.ts index a3c5d2b99..e23d744d8 100644 --- a/src/node/configuration.ts +++ b/src/node/configuration.ts @@ -7,9 +7,9 @@ import { ExtendedConfiguration, setDefaults as setBaseDefaults, } from '../core/interfaces/configuration'; -import { CryptoModule } from '../crypto/modules/NodeCryptoModule/nodeCryptoModule'; import { TransportKeepAlive } from '../core/interfaces/transport'; import { Payload } from '../core/types/api'; +import { CryptoModule } from '../core/interfaces/crypto-module'; // -------------------------------------------------------- // ----------------------- Defaults ----------------------- diff --git a/src/node/index.ts b/src/node/index.ts index a3ac1273b..63f3b1d4f 100755 --- a/src/node/index.ts +++ b/src/node/index.ts @@ -22,7 +22,7 @@ import Cbor from '../cbor/common'; /** * PubNub client for Node.js platform. */ -export = class PubNub extends PubNubCore { +class PubNub extends PubNubCore { /** * Data encryption / decryption module constructor. */ @@ -104,4 +104,6 @@ export = class PubNub extends PubNubCore void; reject: (value: Error) => void }>; /** - * Subscription service worker. + * Subscription shared worker. * - * **Note:** Web PubNub SDK Transport provider adjustment for explicit subscription feature support. + * **Note:** Browser PubNub SDK Transport provider adjustment for explicit subscription / leave features support. */ - serviceWorkerRegistration?: ServiceWorkerRegistration; + subscriptionWorker?: SharedWorker; /** * Queue of events for service worker. * * Keep list of events which should be sent to the worker after its activation. */ - serviceWorkerEventsQueue: PubNubSubscriptionServiceWorker.ClientEvent[]; + workerEventsQueue: PubNubSubscriptionWorker.ClientEvent[]; + + /** + * Whether subscription worker has been initialized and ready to handle events. + */ + subscriptionWorkerReady: boolean = false; constructor(private readonly configuration: PubNubMiddlewareConfiguration) { - this.serviceWorkerEventsQueue = []; + this.workerEventsQueue = []; this.callbacks = new Map(); - this.setupServiceWorker(); + this.setupSubscriptionWorker(); } makeSendable(req: TransportRequest): [Promise, CancellationController | undefined] { @@ -87,7 +102,7 @@ export class SubscriptionServiceWorkerMiddleware implements Transport { return this.configuration.transport.makeSendable(req); let controller: CancellationController | undefined; - const sendRequestEvent: PubNubSubscriptionServiceWorker.SendRequestEvent = { + const sendRequestEvent: PubNubSubscriptionWorker.SendRequestEvent = { type: 'send-request', clientIdentifier: this.configuration.clientIdentifier, subscriptionKey: this.configuration.subscriptionKey, @@ -98,7 +113,7 @@ export class SubscriptionServiceWorkerMiddleware implements Transport { if (req.cancellable) { controller = { abort: () => { - const cancelRequest: PubNubSubscriptionServiceWorker.CancelRequestEvent = { + const cancelRequest: PubNubSubscriptionWorker.CancelRequestEvent = { type: 'cancel-request', clientIdentifier: this.configuration.clientIdentifier, subscriptionKey: this.configuration.subscriptionKey, @@ -130,42 +145,42 @@ export class SubscriptionServiceWorkerMiddleware implements Transport { } /** - * Schedule {@link event} publish to the service worker. + * Schedule {@link event} publish to the subscription worker. * - * Service worker may not be ready for events processing and this method build queue for the time when worker will be - * ready. + * Subscription worker may not be ready for events processing and this method build queue for the time when worker + * will be ready. * - * @param event - Event payload for service worker. + * @param event - Event payload for the subscription worker. * @param outOfOrder - Whether event should be processed first then enqueued queue. */ - private scheduleEventPost(event: PubNubSubscriptionServiceWorker.ClientEvent, outOfOrder: boolean = false) { - // Trigger request processing by Web Worker. - const serviceWorker = this.serviceWorker; - if (serviceWorker) serviceWorker.postMessage(event); + private scheduleEventPost(event: PubNubSubscriptionWorker.ClientEvent, outOfOrder: boolean = false) { + // Trigger request processing by subscription worker. + const subscriptionWorker = this.sharedSubscriptionWorker; + if (subscriptionWorker) subscriptionWorker.port.postMessage(event); else { - if (outOfOrder) this.serviceWorkerEventsQueue.splice(0, 0, event); - else this.serviceWorkerEventsQueue.push(event); + if (outOfOrder) this.workerEventsQueue.splice(0, 0, event); + else this.workerEventsQueue.push(event); } } /** - * Dequeue and post events from the queue to the service worker. + * Dequeue and post events from the queue to the subscription worker. */ private flushScheduledEvents(): void { - // Trigger request processing by Web Worker. - const serviceWorker = this.serviceWorker; - if (!serviceWorker || this.serviceWorkerEventsQueue.length === 0) return; + // Trigger request processing by subscription worker. + const subscriptionWorker = this.sharedSubscriptionWorker; + if (!subscriptionWorker || this.workerEventsQueue.length === 0) return; // Clean up from cancelled events. - const outdatedEvents: PubNubSubscriptionServiceWorker.ClientEvent[] = []; - for (let i = 0; i < this.serviceWorkerEventsQueue.length; i++) { - const event = this.serviceWorkerEventsQueue[i]; + const outdatedEvents: PubNubSubscriptionWorker.ClientEvent[] = []; + for (let i = 0; i < this.workerEventsQueue.length; i++) { + const event = this.workerEventsQueue[i]; // Check whether found request cancel event to search for request send event it cancels. if (event.type !== 'cancel-request' || i === 0) continue; for (let j = 0; j < i; j++) { - const otherEvent = this.serviceWorkerEventsQueue[j]; + const otherEvent = this.workerEventsQueue[j]; if (otherEvent.type !== 'send-request') continue; // Collect outdated events if identifiers match. @@ -177,73 +192,77 @@ export class SubscriptionServiceWorkerMiddleware implements Transport { } // Actualizing events queue. - this.serviceWorkerEventsQueue = this.serviceWorkerEventsQueue.filter((event) => !outdatedEvents.includes(event)); - this.serviceWorkerEventsQueue.forEach((event) => serviceWorker.postMessage(event)); - this.serviceWorkerEventsQueue = []; + this.workerEventsQueue = this.workerEventsQueue.filter((event) => !outdatedEvents.includes(event)); + this.workerEventsQueue.forEach((event) => subscriptionWorker.port.postMessage(event)); + this.workerEventsQueue = []; } /** - * Subscription service worker. + * Subscription worker. * - * @returns Service worker which has been registered by the PubNub SDK. + * @returns Worker which has been registered by the PubNub SDK. */ - private get serviceWorker() { - return this.serviceWorkerRegistration ? this.serviceWorkerRegistration.active : null; + private get sharedSubscriptionWorker() { + return this.subscriptionWorkerReady ? this.subscriptionWorker : null; } - private setupServiceWorker(): void { - if (!('serviceWorker' in navigator)) return; - const serviceWorkerContainer = navigator.serviceWorker as ServiceWorkerContainer; - serviceWorkerContainer - .register(this.configuration.serviceWorkerUrl, { - scope: `/pubnub-${this.configuration.sdkVersion}`, - }) - .then((registration) => { - this.serviceWorkerRegistration = registration; - - // Flush any pending service worker events. - if (registration.active) this.flushScheduledEvents(); - - /** - * Listening for service worker code update. - * - * It is possible that one of the tabs will open with newer SDK version and Subscription Service Worker - * will be re-installed - in this case we need to "rehydrate" it. - * - * After re-installation of new service worker it will lose all accumulated state and client need to - * re-introduce itself and its state. - */ - this.serviceWorkerRegistration.addEventListener('updatefound', () => { - if (!this.serviceWorkerRegistration) return; - - // New service installing right now. - const serviceWorker = this.serviceWorkerRegistration.installing!; - - const stateChangeListener = () => { - // Flush any pending service worker events. - if (serviceWorker.state === 'activated') { - // Flush any pending service worker events. - this.flushScheduledEvents(); - } else if (serviceWorker.state === 'redundant') { - // Clean up listener from deprecated service worker version. - serviceWorker.removeEventListener('statechange', stateChangeListener); - } - }; - - serviceWorker.addEventListener('statechange', stateChangeListener); - }); - }); - - serviceWorkerContainer.addEventListener('message', (event) => this.handleServiceWorkerEvent(event)); + private setupSubscriptionWorker(): void { + if (typeof SharedWorker === 'undefined') return; + + this.subscriptionWorker = new SharedWorker( + this.configuration.workerUrl, + `/pubnub-${this.configuration.sdkVersion}`, + ); + + this.subscriptionWorker.port.start(); + + // Register PubNub client within subscription worker. + this.scheduleEventPost( + { + type: 'client-register', + clientIdentifier: this.configuration.clientIdentifier, + subscriptionKey: this.configuration.subscriptionKey, + userId: this.configuration.userId, + logVerbosity: this.configuration.logVerbosity, + workerLogVerbosity: this.configuration.workerLogVerbosity, + }, + true, + ); + + this.subscriptionWorker.port.onmessage = (event) => this.handleWorkerEvent(event); } - private handleServiceWorkerEvent(event: MessageEvent) { + private handleWorkerEvent(event: MessageEvent) { const { data } = event; // Ignoring updates not related to this instance. - if (data.clientIdentifier !== this.configuration.clientIdentifier) return; - - if (data.type === 'request-progress-start' || data.type === 'request-progress-end') { + if ( + data.type !== 'shared-worker-ping' && + data.type !== 'shared-worker-connected' && + data.type !== 'shared-worker-console-log' && + data.type !== 'shared-worker-console-dir' && + data.clientIdentifier !== this.configuration.clientIdentifier + ) + return; + + if (data.type === 'shared-worker-connected') { + this.subscriptionWorkerReady = true; + this.flushScheduledEvents(); + } else if (data.type === 'shared-worker-console-log') { + console.log(`[SharedWorker] ${data.message}`); + } else if (data.type === 'shared-worker-console-dir') { + if (data.message) console.log(`[SharedWorker] ${data.message}`); + console.dir(data.data); + } else if (data.type === 'shared-worker-ping') { + const { logVerbosity, subscriptionKey, clientIdentifier } = this.configuration; + + this.scheduleEventPost({ + type: 'client-pong', + subscriptionKey, + clientIdentifier, + logVerbosity, + }); + } else if (data.type === 'request-progress-start' || data.type === 'request-progress-end') { this.logRequestProgress(data); } else if (data.type === 'request-process-success' || data.type === 'request-process-error') { const { resolve, reject } = this.callbacks!.get(data.identifier)!; @@ -289,9 +308,9 @@ export class SubscriptionServiceWorkerMiddleware implements Transport { /** * Print request progress information. * - * @param information - Request progress information from Web Worker. + * @param information - Request progress information from worker. */ - private logRequestProgress(information: PubNubSubscriptionServiceWorker.RequestSendingProgress) { + private logRequestProgress(information: PubNubSubscriptionWorker.RequestSendingProgress) { if (information.type === 'request-progress-start') { console.log('<<<<<'); console.log(`[${information.timestamp}] ${information.url}\n${JSON.stringify(information.query ?? {})}`); diff --git a/src/transport/service-worker/subscription-service-worker.ts b/src/transport/subscription-worker/subscription-worker.ts similarity index 71% rename from src/transport/service-worker/subscription-service-worker.ts rename to src/transport/subscription-worker/subscription-worker.ts index 970ded65a..84fb67c60 100644 --- a/src/transport/service-worker/subscription-service-worker.ts +++ b/src/transport/subscription-worker/subscription-worker.ts @@ -34,6 +34,28 @@ type BasicEvent = { * Whether verbose logging enabled or not. */ logVerbosity: boolean; + + /** + * Whether verbose logging should be enabled for `Subscription` worker should print debug messages or not. + */ + workerLogVerbosity?: boolean; +}; + +/** + * PubNub client registration event. + */ +export type RegisterEvent = BasicEvent & { + type: 'client-register'; + + /** + * Unique identifier of the user for which PubNub SDK client has been created. + */ + userId: string; + + /** + * Specific PubNub client instance communication port. + */ + port?: MessagePort; }; /** @@ -62,13 +84,29 @@ export type CancelRequestEvent = BasicEvent & { identifier: string; }; +/** + * Client response on PING request. + */ +export type PongEvent = BasicEvent & { + type: 'client-pong'; +}; + /** * List of known events from the PubNub Core. */ -export type ClientEvent = SendRequestEvent | CancelRequestEvent; +export type ClientEvent = RegisterEvent | PongEvent | SendRequestEvent | CancelRequestEvent; // endregion -// region Service Worker +// region Subscription Worker +/** + * Shared subscription worker connected event. + * + * Event signal shared worker client that worker can be used. + */ +export type SharedWorkerConnected = { + type: 'shared-worker-connected'; +}; + /** * {@link Request} processing start event. * @@ -249,10 +287,57 @@ export type RequestSendingSuccess = { */ export type RequestSendingResult = RequestSendingError | RequestSendingSuccess; +/** + * Send message to debug console. + */ +export type SharedWorkerConsoleLog = { + type: 'shared-worker-console-log'; + + /** + * Message which should be printed into the console. + */ + message: string; +}; +/** + * Send message to debug console. + */ +export type SharedWorkerConsoleDir = { + type: 'shared-worker-console-dir'; + + /** + * Message which should be printed into the console before {@link data}. + */ + message?: string; + + /** + * Data which should be printed into the console. + */ + data: Payload; +}; + +/** + * Shared worker console output request. + */ +export type SharedWorkerConsole = SharedWorkerConsoleLog | SharedWorkerConsoleDir; + +/** + * Shared worker client ping request. + * + * Ping used to discover disconnected PubNub instances. + */ +export type SharedWorkerPing = { + type: 'shared-worker-ping'; +}; + /** * List of known events from the PubNub Subscription Service Worker. */ -export type ServiceWorkerEvent = RequestSendingProgress | RequestSendingResult; +export type SubscriptionWorkerEvent = + | SharedWorkerConnected + | SharedWorkerConsole + | SharedWorkerPing + | RequestSendingProgress + | RequestSendingResult; /** * PubNub client state representation in Service Worker. @@ -284,13 +369,23 @@ type PubNubClientState = { */ logVerbosity: boolean; + /** + * Last time when PING request has been sent. + */ + lastPingRequest?: number; + + /** + * Last time when PubNub client respond with PONG event. + */ + lastPongEvent?: number; + /** * Current subscription session information. * * **Note:** Information updated each time when PubNub client instance schedule `subscribe` or * `unsubscribe` requests. */ - subscription: { + subscription?: { /** * Subscription REST API uri path. * @@ -361,7 +456,12 @@ type PubNubClientState = { // -------------------------------------------------------- // region Service Worker -declare const self: ServiceWorkerGlobalScope; +declare const self: SharedWorkerGlobalScope; + +/** + * How often PING request should be sent to the PubNub clients. + */ +const clientPingRequestInterval = 5000; // region State /** @@ -369,6 +469,21 @@ declare const self: ServiceWorkerGlobalScope; */ const decoder = new TextDecoder(); +/** + * Whether `Subscription` worker should print debug information to the console or not. + */ +let logVerbosity: boolean = false; + +/** + * PubNub clients active ping interval. + */ +let pingInterval: number | undefined; + +/** + * Unique shared worker instance identifier. + */ +const sharedWorkerIdentifier = uuidGenerator.createUUID(); + /** * Map of identifiers, scheduled by the Service Worker, to their abort controllers. * @@ -400,12 +515,12 @@ const presenceState: { } = {}; /** - * Per-subscription key map of client identifiers to the Service Worker {@link Client} identifier. + * Per-subscription key map of client identifiers to the Shared Worker {@link MessagePort}. * - * Service Worker {@link Client} represent pages at which PubNub clients registered Service Workers. + * Shared Worker {@link MessagePort} represent specific PubNub client which connected to the Shared Worker. */ -const serviceWorkerClients: { - [subscriptionKey: string]: { [clientId: string]: string | undefined } | undefined; +const sharedWorkerClients: { + [subscriptionKey: string]: { [clientId: string]: MessagePort | undefined } | undefined; } = {}; /** @@ -444,31 +559,44 @@ const serviceRequests: { // region Event Handlers /** - * Listen for Service Worker activation. + * Handle new PubNub client 'connection'. + * + * Echo listeners to let `SharedWorker` users that it is ready. + * + * @param event - Remote `SharedWorker` client connection event. */ -self.addEventListener('activate', (event) => { - event.waitUntil(self.clients.claim()); -}); +self.onconnect = (event) => { + consoleLog('New PubNub Client connected to the Subscription Shared Worker.'); -/** - * Listen for events from the client. - */ -self.addEventListener('message', (event) => { - // Ignoring requests sent from other service workers. - if (!validateEventPayload(event)) return; + event.ports.forEach((receiver) => { + receiver.start(); - const data = event.data as ClientEvent; + receiver.onmessage = (event: MessageEvent) => { + // Ignoring unknown event payloads. + if (!validateEventPayload(event)) return; - if (data.type === 'send-request') { - if (data.request.path.startsWith('/v2/subscribe')) { - registerClientIfRequired(event); - handleSendSubscribeRequestEvent(data); - } else { - if (!pubNubClients[data.clientIdentifier]) registerClientIfRequired(event); - handleSendLeaveRequestEvent(event); - } - } else if (data.type === 'cancel-request') handleCancelRequestEvent(data); -}); + const data = event.data as ClientEvent; + + if (data.type === 'client-register') { + if (!logVerbosity && data.workerLogVerbosity) logVerbosity = true; + + // Appending information about messaging port for responses. + data.port = receiver; + registerClientIfRequired(data); + + consoleLog(`Client '${data.clientIdentifier}' registered with '${sharedWorkerIdentifier}' shared worker`); + } else if (data.type === 'client-pong') handleClientPong(data); + else if (data.type === 'send-request') { + if (data.request.path.startsWith('/v2/subscribe')) { + updateClientStateIfRequired(data); + handleSendSubscribeRequestEvent(data); + } else handleSendLeaveRequestEvent(data); + } else if (data.type === 'cancel-request') handleCancelRequestEvent(data); + }; + + receiver.postMessage({ type: 'shared-worker-connected' }); + }); +}; /** * Handle client request to send subscription request. @@ -482,7 +610,7 @@ const handleSendSubscribeRequestEvent = (event: SendRequestEvent) => { if (client) notifyRequestProcessing('start', [client], new Date().toISOString()); if (typeof requestOrId === 'string') { - if (client) { + if (client && client.subscription) { // Updating client timetoken information. client.subscription.previousTimetoken = client.subscription.timetoken; client.subscription.timetoken = serviceRequests[requestOrId].timetoken; @@ -511,15 +639,16 @@ const handleSendSubscribeRequestEvent = (event: SendRequestEvent) => { markRequestCompleted(clients, requestOrId.identifier); }, ); + + consoleLog(`'${Object.keys(serviceRequests).length}' subscription request currently active.`); }; /** * Handle client request to leave request. * - * @param event - Leave event details. + * @param data - Leave event details. */ -const handleSendLeaveRequestEvent = (event: ExtendableMessageEvent) => { - const data = event.data as SendRequestEvent; +const handleSendLeaveRequestEvent = (data: SendRequestEvent) => { const request = leaveTransportRequestFromEvent(data); const client = pubNubClients[data.clientIdentifier]; @@ -533,9 +662,7 @@ const handleSendLeaveRequestEvent = (event: ExtendableMessageEvent) => { result.clientIdentifier = data.clientIdentifier; result.identifier = data.request.identifier; - publishClientEvent((event.source! as Client).id, result).then((sent) => { - if (sent) invalidateClient(client.subscriptionKey, client.clientIdentifier, client.userId); - }); + publishClientEvent(client, result); return; } @@ -551,6 +678,8 @@ const handleSendLeaveRequestEvent = (event: ExtendableMessageEvent) => { notifyRequestProcessingResult(clients, null, data.request, requestProcessingError(error)); }, ); + + consoleLog(`Started leave request.`, client); }; /** @@ -562,7 +691,9 @@ const handleSendLeaveRequestEvent = (event: ExtendableMessageEvent) => { */ const handleCancelRequestEvent = (event: CancelRequestEvent) => { const client = pubNubClients[event.clientIdentifier]; - const serviceRequestId = client ? client.subscription.serviceRequestId : undefined; + if (!client || !client.subscription) return; + + const serviceRequestId = client.subscription.serviceRequestId; if (!client || !serviceRequestId) return; // Unset awaited requests. @@ -673,7 +804,7 @@ const requestTimeoutTimer = (requestId: string, requestTimeout: number) => const clientsForRequest = (identifier: string) => { return Object.values(pubNubClients).filter( (client): client is PubNubClientState => - client !== undefined && client.subscription.serviceRequestId === identifier, + client !== undefined && client.subscription !== undefined && client.subscription.serviceRequestId === identifier, ); }; @@ -689,8 +820,10 @@ const markRequestCompleted = (clients: PubNubClientState[], requestId: string) = delete serviceRequests[requestId]; clients.forEach((client) => { - delete client.subscription.request; - delete client.subscription.serviceRequestId; + if (client.subscription) { + delete client.subscription.request; + delete client.subscription.serviceRequestId; + } }); }; @@ -734,7 +867,8 @@ const requestFromTransportRequest = (req: TransportRequest): Request => { */ const subscribeTransportRequestFromEvent = (event: SendRequestEvent): TransportRequest | string => { const client = pubNubClients[event.clientIdentifier]!; - const clients = clientsForSendSubscribeRequestEvent(client.subscription.previousTimetoken, event); + const subscription = client.subscription!; + const clients = clientsForSendSubscribeRequestEvent(subscription.previousTimetoken, event); const serviceRequestId = uuidGenerator.createUUID(); const request = { ...event.request }; @@ -746,11 +880,11 @@ const subscribeTransportRequestFromEvent = (event: SendRequestEvent): TransportR const state = (presenceState[client.subscriptionKey] ?? {})[client.userId]; const aggregatedState: Record = {}; - const channelGroups = new Set(client.subscription.channelGroups); - const channels = new Set(client.subscription.channels); + const channelGroups = new Set(subscription.channelGroups); + const channels = new Set(subscription.channels); - if (state && client.subscription.objectsWithState.length) { - client.subscription.objectsWithState.forEach((name) => { + if (state && subscription.objectsWithState.length) { + subscription.objectsWithState.forEach((name) => { const objectState = state[name]; if (objectState) aggregatedState[name] = objectState; }); @@ -759,7 +893,7 @@ const subscribeTransportRequestFromEvent = (event: SendRequestEvent): TransportR for (const client of clients) { const { subscription } = client!; // Skip clients which already have active subscription request. - if (subscription.serviceRequestId) continue; + if (!subscription || !subscription.serviceRequestId) continue; subscription.channelGroups.forEach(channelGroups.add, channelGroups); subscription.channels.forEach(channels.add, channels); @@ -803,14 +937,25 @@ const subscribeTransportRequestFromEvent = (event: SendRequestEvent): TransportR serviceRequests[serviceRequestId] = { requestId: serviceRequestId, timetoken: (request.queryParameters!.tt as string) ?? '0', - channelGroups: client.subscription.channelGroups, - channels: client.subscription.channels, + channelGroups: subscription.channelGroups, + channels: subscription.channels, }; } - client.subscription.serviceRequestId = serviceRequestId; + subscription.serviceRequestId = serviceRequestId; request.identifier = serviceRequestId; + if (logVerbosity) { + const clientIds = clients + .reduce((identifiers: string[], { clientIdentifier }) => { + identifiers.push(clientIdentifier); + return identifiers; + }, []) + .join(','); + + consoleDir(serviceRequests[serviceRequestId], `Started aggregated request for clients: ${clientIds}`); + } + return request; }; @@ -831,7 +976,7 @@ const leaveTransportRequestFromEvent = (event: SendRequestEvent): TransportReque let channels = channelsFromRequest(event.request); const request = { ...event.request }; - if (client) { + if (client && client.subscription) { const { subscription } = client; if (channels.length) subscription.channels = subscription.channels.filter((channel) => !channels.includes(channel)); if (channelGroups.length) { @@ -841,13 +986,31 @@ const leaveTransportRequestFromEvent = (event: SendRequestEvent): TransportReque // Filter out channels and groups which is still in use by the other PubNub client instances. for (const client of clients) { + const subscription = client.subscription; + if (subscription === undefined) continue; if (client.clientIdentifier === event.clientIdentifier) continue; - if (channels.length) channels = channels.filter((channel) => !client.subscription.channels.includes(channel)); + if (channels.length) channels = channels.filter((channel) => !subscription.channels.includes(channel)); if (channelGroups.length) - channelGroups = channelGroups.filter((group) => !client.subscription.channelGroups.includes(group)); + channelGroups = channelGroups.filter((group) => !subscription.channelGroups.includes(group)); } - if (channels.length === 0 && channelGroups.length === 0) return undefined; + if (channels.length === 0 && channelGroups.length === 0) { + if (logVerbosity && client) { + const clientIds = clients + .reduce((identifiers: string[], { clientIdentifier }) => { + identifiers.push(clientIdentifier); + return identifiers; + }, []) + .join(','); + + consoleLog( + `Specified channels and groups still in use by other clients: ${clientIds}. Ignoring leave request.`, + client, + ); + } + + return undefined; + } // Update request channels list (if required). if (channels.length) { @@ -863,18 +1026,21 @@ const leaveTransportRequestFromEvent = (event: SendRequestEvent): TransportReque }; /** - * Send event to all service worker clients. + * Send event to the specific PubNub client. * - * @param identifier - Service Worker receiving {@link Client} identifier. - * @param event - Service worker event object. + * @param client - State for the client which should receive {@link event}. + * @param event - Subscription worker event object. */ -const publishClientEvent = (identifier: string, event: ServiceWorkerEvent) => { - return self.clients.get(identifier).then((client) => { - if (!client) return false; +const publishClientEvent = (client: PubNubClientState, event: SubscriptionWorkerEvent) => { + const receiver = (sharedWorkerClients[client.subscriptionKey] ?? {})[client.clientIdentifier]; + if (!receiver) return false; - client.postMessage(event); + try { + receiver.postMessage(event); return true; - }); + } catch (error) {} + + return false; }; /** @@ -899,7 +1065,7 @@ const notifyRequestProcessing = ( ) => { if (clients.length === 0) return; - const clientIds = serviceWorkerClients[clients[0].subscriptionKey] ?? {}; + const clientIds = sharedWorkerClients[clients[0].subscriptionKey] ?? {}; let event: RequestSendingProgress; if (type === 'start') { @@ -932,22 +1098,24 @@ const notifyRequestProcessing = ( }; } - clients.forEach((client) => { + for (const client of clients) { + if (client.subscription === undefined) continue; + const serviceWorkerClientId = clientIds[client.clientIdentifier]; const { request: clientRequest } = client.subscription; const decidedRequest = clientRequest ?? request; if (client.logVerbosity && serviceWorkerClientId && decidedRequest) { - publishClientEvent(serviceWorkerClientId, { + const payload = { ...event, clientIdentifier: client.clientIdentifier, url: `${decidedRequest.origin}${decidedRequest.path}`, query: decidedRequest.queryParameters, - }).then((sent) => { - if (sent) invalidateClient(client.subscriptionKey, client.clientIdentifier, client.userId); - }); + }; + + publishClientEvent(client, payload); } - }); + } }; /** @@ -967,7 +1135,7 @@ const notifyRequestProcessingResult = ( if (clients.length === 0) return; if (!result && !response) return; - const clientIds = serviceWorkerClients[clients[0].subscriptionKey] ?? {}; + const clientIds = sharedWorkerClients[clients[0].subscriptionKey] ?? {}; if (!result && response) { result = @@ -977,22 +1145,24 @@ const notifyRequestProcessingResult = ( : requestProcessingSuccess(response); } - clients.forEach((client) => { + for (const client of clients) { + if (client.subscription === undefined) continue; + const serviceWorkerClientId = clientIds[client.clientIdentifier]; const { request: clientRequest } = client.subscription; const decidedRequest = clientRequest ?? request; if (serviceWorkerClientId && decidedRequest) { - publishClientEvent(serviceWorkerClientId, { + const payload = { ...result!, clientIdentifier: client.clientIdentifier, identifier: decidedRequest.identifier, url: `${decidedRequest.origin}${decidedRequest.path}`, - }).then((sent) => { - if (sent) invalidateClient(client.subscriptionKey, client.clientIdentifier, client.userId); - }); + }; + + publishClientEvent(client, payload); } - }); + } }; /** @@ -1089,71 +1259,79 @@ const requestProcessingError = (error?: unknown, res?: [Response, ArrayBuffer]): * * @param event - Base information about PubNub client instance and Service Worker {@link Client}. */ -const registerClientIfRequired = (event: ExtendableMessageEvent) => { - const information = event.data as SendRequestEvent; - const { clientIdentifier } = information; - const query = information.request.queryParameters!; - - let client = pubNubClients[clientIdentifier]; - - if (!client) { - const isPresenceLeave = !information.request.path.startsWith('/v2/subscribe'); - const channelGroupQuery = !isPresenceLeave ? ((query!['channel-group'] ?? '') as string) : ''; - const state = !isPresenceLeave ? ((query.state ?? '') as string) : ''; - - client = pubNubClients[clientIdentifier] = { - clientIdentifier, - subscriptionKey: information.subscriptionKey, - userId: query.uuid as string, - authKey: (query.auth ?? '') as string, - logVerbosity: information.logVerbosity, - subscription: { - path: !isPresenceLeave ? information.request.path : '', - channelGroupQuery: !isPresenceLeave ? channelGroupQuery : '', - channels: !isPresenceLeave ? channelsFromRequest(information.request) : [], - channelGroups: !isPresenceLeave ? channelGroupsFromRequest(information.request) : [], - previousTimetoken: !isPresenceLeave ? ((query.tt ?? '0') as string) : '0', - timetoken: !isPresenceLeave ? ((query.tt ?? '0') as string) : '0', - request: !isPresenceLeave ? information.request : undefined, - objectsWithState: [], - filterExpression: !isPresenceLeave ? ((query['filter-expr'] ?? '') as string) : undefined, - }, +const registerClientIfRequired = (event: RegisterEvent) => { + const { clientIdentifier } = event; + + if (pubNubClients[clientIdentifier]) return; + + const client = (pubNubClients[clientIdentifier] = { + clientIdentifier, + subscriptionKey: event.subscriptionKey, + userId: event.userId, + logVerbosity: event.logVerbosity, + }); + + // Map registered PubNub client to its subscription key. + const clientsBySubscriptionKey = (pubNubClientsBySubscriptionKey[event.subscriptionKey] ??= []); + if (clientsBySubscriptionKey.every((entry) => entry.clientIdentifier !== clientIdentifier)) + clientsBySubscriptionKey.push(client); + + // Binding PubNub client to the MessagePort (receiver). + (sharedWorkerClients[event.subscriptionKey] ??= {})[clientIdentifier] = event.port; + + consoleLog( + `Registered PubNub client with '${clientIdentifier}' identifier. ` + + `'${Object.keys(pubNubClients).length}' clients currently active.`, + ); + + if (!pingInterval && Object.keys(pubNubClients).length > 0) { + consoleLog(`Setup PubNub client ping event ${clientPingRequestInterval / 1000} seconds`); + pingInterval = setInterval(() => pingClients(), clientPingRequestInterval) as unknown as number; + } +}; + +/** + * Update information about previously registered client. + * + * Use information from request to populate list of channels and other useful information. + * + * @param event - Send request. + */ +const updateClientStateIfRequired = (event: SendRequestEvent) => { + const query = event.request.queryParameters!; + const { clientIdentifier } = event; + + const client = pubNubClients[clientIdentifier]; + + // This should never happen. + if (!client) return; + + const channelGroupQuery = (query!['channel-group'] ?? '') as string; + const state = (query.state ?? '') as string; + + let subscription = client.subscription; + if (!subscription) { + subscription = { + path: '', + channelGroupQuery: '', + channels: [], + channelGroups: [], + previousTimetoken: '0', + timetoken: '0', + objectsWithState: [], }; - if (!isPresenceLeave && state.length > 0) { + if (state.length > 0) { const parsedState = JSON.parse(state) as Record; const userState = ((presenceState[client.subscriptionKey] ??= {})[client.userId] ??= {}); Object.entries(parsedState).forEach(([objectName, value]) => (userState[objectName] = value)); - client.subscription.objectsWithState = Object.keys(parsedState); + subscription.objectsWithState = Object.keys(parsedState); } - // Map registered PubNub client to its subscription key. - const clientsBySubscriptionKey = (pubNubClientsBySubscriptionKey[information.subscriptionKey] ??= []); - if (clientsBySubscriptionKey.every((entry) => entry.clientIdentifier !== clientIdentifier)) - clientsBySubscriptionKey.push(client); - - // Binding PubNub client to the page (Service Worker Client). - (serviceWorkerClients[information.subscriptionKey] ??= {})[clientIdentifier] = (event.source! as Client).id; + client.subscription = subscription; } else { - const channelGroupQuery = (query!['channel-group'] ?? '') as string; - const state = (query.state ?? '') as string; - client.subscription.filterExpression = (query['filter-expr'] ?? '') as string; - client.subscription.previousTimetoken = client.subscription.timetoken; - client.subscription.timetoken = (query.tt ?? '0') as string; - client.subscription.request = information.request; - client.authKey = (query.auth ?? '') as string; - client.userId = query.uuid as string; - - if (client.subscription.path !== information.request.path) { - client.subscription.path = information.request.path; - client.subscription.channels = channelsFromRequest(information.request); - } - - if (client.subscription.channelGroupQuery !== channelGroupQuery) { - client.subscription.channelGroupQuery = channelGroupQuery; - client.subscription.channelGroups = channelGroupsFromRequest(information.request); - } + subscription.previousTimetoken = subscription.timetoken; if (state.length > 0) { const parsedState = JSON.parse(state) as Record; @@ -1161,18 +1339,48 @@ const registerClientIfRequired = (event: ExtendableMessageEvent) => { Object.entries(parsedState).forEach(([objectName, value]) => (userState[objectName] = value)); // Clean up state for objects where presence state has been reset. - for (const objectName of client.subscription.objectsWithState) + for (const objectName of subscription.objectsWithState) if (!parsedState[objectName]) delete userState[objectName]; - client.subscription.objectsWithState = Object.keys(parsedState); + + subscription.objectsWithState = Object.keys(parsedState); } // Handle potential presence state reset. - else if (client.subscription.objectsWithState.length) { + else if (subscription.objectsWithState.length) { const userState = ((presenceState[client.subscriptionKey] ??= {})[client.userId] ??= {}); - for (const objectName of client.subscription.objectsWithState) delete userState[objectName]; - client.subscription.objectsWithState = []; + for (const objectName of subscription.objectsWithState) delete userState[objectName]; + subscription.objectsWithState = []; } } + + if (subscription.path !== event.request.path) { + subscription.path = event.request.path; + subscription.channels = channelsFromRequest(event.request); + } + + if (subscription.channelGroupQuery !== channelGroupQuery) { + subscription.channelGroupQuery = channelGroupQuery; + subscription.channelGroups = channelGroupsFromRequest(event.request); + } + + subscription.request = event.request; + subscription.filterExpression = (query['filter-expr'] ?? '') as string; + subscription.timetoken = (query.tt ?? '0') as string; + client.authKey = (query.auth ?? '') as string; + client.userId = query.uuid as string; +}; + +/** + * Handle PubNub client response on PING request. + * + * @param event - Information about client which responded on PING request. + */ +const handleClientPong = (event: PongEvent) => { + const client = pubNubClients[event.clientIdentifier]; + + if (!client) return; + + client.lastPongEvent = new Date().getTime() / 1000; }; /** @@ -1181,9 +1389,8 @@ const registerClientIfRequired = (event: ExtendableMessageEvent) => { * @param subscriptionKey - Subscription key which has been used by the * invalidated instance. * @param clientId - Unique PubNub client identifier. - * @param userId - Unique identifier of the user used by PubNub client instance. */ -const invalidateClient = (subscriptionKey: string, clientId: string, userId: string) => { +const invalidateClient = (subscriptionKey: string, clientId: string) => { delete pubNubClients[clientId]; let clients = pubNubClientsBySubscriptionKey[subscriptionKey]; @@ -1198,24 +1405,23 @@ const invalidateClient = (subscriptionKey: string, clientId: string, userId: str // Clean up service workers client linkage to PubNub clients. if (clients.length > 0) { - const workerClients = serviceWorkerClients[subscriptionKey]; + const workerClients = sharedWorkerClients[subscriptionKey]; if (workerClients) { delete workerClients[clientId]; - if (Object.keys(workerClients).length === 0) delete serviceWorkerClients[subscriptionKey]; + if (Object.keys(workerClients).length === 0) delete sharedWorkerClients[subscriptionKey]; } - } else delete serviceWorkerClients[subscriptionKey]; + } else delete sharedWorkerClients[subscriptionKey]; } + + consoleLog(`Invalidate '${clientId}' client. '${Object.keys(pubNubClients).length}' clients currently active.`); }; /** * Validate received event payload. */ -const validateEventPayload = (event: ExtendableMessageEvent): boolean => { - if (!event.source || !(event.source instanceof Client)) return false; - const data = event.data as ClientEvent; - - const { clientIdentifier, subscriptionKey, logVerbosity } = data as ClientEvent; +const validateEventPayload = (event: MessageEvent): boolean => { + const { clientIdentifier, subscriptionKey, logVerbosity } = event.data as ClientEvent; if (logVerbosity === undefined || typeof logVerbosity !== 'boolean') return false; if (!clientIdentifier || typeof clientIdentifier !== 'string') return false; @@ -1223,7 +1429,7 @@ const validateEventPayload = (event: ExtendableMessageEvent): boolean => { }; /** - * Search for active subscription for one of the passed {@link serviceWorkerClients}. + * Search for active subscription for one of the passed {@link sharedWorkerClients}. * * @param activeClients - List of suitable registered PubNub clients. * @param event - Send Subscriber Request event data. @@ -1244,9 +1450,17 @@ const activeSubscriptionForEvent = ( for (const client of activeClients) { const { subscription } = client; // Skip PubNub clients which doesn't await for subscription response. - if (!subscription.serviceRequestId) continue; + if (!subscription || !subscription.serviceRequestId) continue; + const sourceClient = pubNubClients[event.clientIdentifier]; + const requestId = subscription.serviceRequestId; if (subscription.path === requestPath && subscription.channelGroupQuery === channelGroupQuery) { + consoleLog( + `Found identical request started by '${client.clientIdentifier}' client. +Waiting for existing '${requestId}' request completion.`, + sourceClient, + ); + return subscription.serviceRequestId; } else { const scheduledRequest = serviceRequests[subscription.serviceRequestId]; @@ -1257,6 +1471,13 @@ const activeSubscriptionForEvent = ( if (channels.length && !includesStrings(scheduledRequest.channels, channels)) continue; if (channelGroups.length && !includesStrings(scheduledRequest.channelGroups, channelGroups)) continue; + consoleDir( + scheduledRequest, + `'${event.request.identifier}' request channels and groups are subset of ongoing '${requestId}' request +which has started by '${client.clientIdentifier}' client. Waiting for existing '${requestId}' request completion.`, + sourceClient, + ); + return subscription.serviceRequestId; } } @@ -1290,6 +1511,7 @@ const clientsForSendSubscribeRequestEvent = (timetoken: string, event: SendReque (client) => client.userId === userId && client.authKey === authKey && + client.subscription && client.subscription.filterExpression === filterExpression && (timetoken === '0' || client.subscription.previousTimetoken === '0' || @@ -1356,6 +1578,83 @@ const includesStrings = (main: string[], sub: string[]) => { return sub.every(set.has, set); }; +/** + * Send PubNub client PING request to identify disconnected instances. + */ +const pingClients = () => { + consoleLog(`Pinging clients...`); + const payload: SharedWorkerPing = { type: 'shared-worker-ping' }; + + Object.values(pubNubClients).forEach((client) => { + let clientInvalidated = false; + + if (client && client.lastPingRequest) { + consoleLog(`Checking whether ${client.clientIdentifier} ping has been sent too long ago...`); + // Check whether client never respond or last response was too long time ago. + if ( + !client.lastPongEvent || + Math.abs(client.lastPongEvent - client.lastPingRequest) > (clientPingRequestInterval / 1000) * 0.5 + ) { + clientInvalidated = true; + + consoleLog(`'${client.clientIdentifier}' client is inactive. Invalidating.`); + invalidateClient(client.subscriptionKey, client.clientIdentifier); + } + } + + if (client && !clientInvalidated) { + consoleLog(`Sending ping to ${client.clientIdentifier}...`); + client.lastPingRequest = new Date().getTime() / 1000; + publishClientEvent(client, payload); + } + }); + + // Cancel interval if there is no active clients. + if (Object.keys(pubNubClients).length === 0 && pingInterval) clearInterval(pingInterval); +}; + +/** + * Print message on the worker's clients console. + * + * @param message - Message which should be printed. + * @param [client] - Target client to which log message should be sent. + */ +const consoleLog = (message: string, client?: PubNubClientState): void => { + if (!logVerbosity) return; + + const clients = client ? [client] : Object.values(pubNubClients); + const payload: SharedWorkerConsoleLog = { + type: 'shared-worker-console-log', + message, + }; + + clients.forEach((client) => { + if (client) publishClientEvent(client, payload); + }); +}; + +/** + * Print message on the worker's clients console. + * + * @param data - Data which should be printed into the console. + * @param [message] - Message which should be printed before {@link data}. + * @param [client] - Target client to which log message should be sent. + */ +const consoleDir = (data: Payload, message?: string, client?: PubNubClientState): void => { + if (!logVerbosity) return; + + const clients = client ? [client] : Object.values(pubNubClients); + const payload: SharedWorkerConsoleDir = { + type: 'shared-worker-console-dir', + message, + data, + }; + + clients.forEach((client) => { + if (client) publishClientEvent(client, payload); + }); +}; + /** * Stringify request query key / value pairs. * diff --git a/src/web/components/configuration.ts b/src/web/components/configuration.ts index 651cd1530..06e65c335 100644 --- a/src/web/components/configuration.ts +++ b/src/web/components/configuration.ts @@ -3,6 +3,7 @@ import { ExtendedConfiguration, setDefaults as setBaseDefaults, } from '../../core/interfaces/configuration'; +import { CryptoModule } from '../../core/interfaces/crypto-module'; // -------------------------------------------------------- // ----------------------- Defaults ----------------------- @@ -17,6 +18,11 @@ import { */ const LISTEN_TO_BROWSER_NETWORK_EVENTS = true; +/** + * Whether verbose logging should be enabled for `Subscription` worker to print debug messages or not. + */ +const SUBSCRIPTION_WORKER_LOG_VERBOSITY = false; + /** * Whether PubNub client should try to utilize existing TCP connection for new requests or not. */ @@ -45,7 +51,14 @@ export type PubNubConfiguration = UserConfiguration & { * statics provided from `subdomain.main.com` and page loaded from `account.main.com` - then server should be * configured to serve worker file from `account.main.com`. */ - serviceWorkerUrl?: string | null; + subscriptionWorkerUrl?: string | null; + + /** + * Whether verbose logging should be enabled for `Subscription` worker should print debug messages or not. + * + * @default `false` + */ + subscriptionWorkerLogVerbosity?: boolean; /** * If set to `true`, SDK will use the same TCP connection for each HTTP request, instead of @@ -54,23 +67,57 @@ export type PubNubConfiguration = UserConfiguration & { * @default `true` */ keepAlive?: boolean; + + /** + * The cryptography module used for encryption and decryption of messages and files. Takes the + * {@link cipherKey} and {@link useRandomIVs} parameters as arguments. + * + * For more information, refer to the + * {@link /docs/sdks/javascript/api-reference/configuration#cryptomodule|cryptoModule} section. + * + * @default `not set` + */ + cryptoModule?: CryptoModule; + + // region Deprecated parameters + /** + * If passed, will encrypt the payloads. + * + * @deprecated Pass it to {@link cryptoModule} instead. + */ + cipherKey?: string; + + /** + * When `true` the initialization vector (IV) is random for all requests (not just for file + * upload). + * When `false` the IV is hard-coded for all requests except for file upload. + * + * @default `true` + * + * @deprecated Pass it to {@link cryptoModule} instead. + */ + useRandomIVs?: boolean; }; /** * Apply configuration default values. * * @param configuration - User-provided configuration. + * + * @internal */ export const setDefaults = (configuration: PubNubConfiguration): PubNubConfiguration & ExtendedConfiguration => { // Force disable service workers if environment doesn't support them. - if (configuration.serviceWorkerUrl && !('serviceWorker' in navigator)) configuration.serviceWorkerUrl = null; + if (configuration.subscriptionWorkerUrl && typeof SharedWorker === 'undefined') + configuration.subscriptionWorkerUrl = null; return { // Set base configuration defaults. ...setBaseDefaults(configuration), // Set platform-specific options. listenToBrowserNetworkEvents: configuration.listenToBrowserNetworkEvents ?? LISTEN_TO_BROWSER_NETWORK_EVENTS, - serviceWorkerUrl: configuration.serviceWorkerUrl, + subscriptionWorkerUrl: configuration.subscriptionWorkerUrl, + subscriptionWorkerLogVerbosity: configuration.subscriptionWorkerLogVerbosity ?? SUBSCRIPTION_WORKER_LOG_VERBOSITY, keepAlive: configuration.keepAlive ?? KEEP_ALIVE, }; }; diff --git a/src/web/index.ts b/src/web/index.ts index 5fc10654b..7cf367027 100644 --- a/src/web/index.ts +++ b/src/web/index.ts @@ -4,8 +4,8 @@ import CborReader from 'cbor-js'; // eslint-disable-next-line max-len -import { SubscriptionServiceWorkerMiddleware } from '../transport/service-worker/subscription-service-worker-middleware'; import { AesCbcCryptor, LegacyCryptor, WebCryptoModule } from '../crypto/modules/WebCryptoModule/webCryptoModule'; +import { SubscriptionWorkerMiddleware } from '../transport/subscription-worker/subscription-worker-middleware'; import { WebReactNativeTransport } from '../transport/web-react-native-transport'; import { stringifyBufferKeys } from '../core/components/stringify_buffer_keys'; import { PubNubConfiguration, setDefaults } from './components/configuration'; @@ -69,14 +69,17 @@ export default class PubNub extends PubNubCore