From b36cf023f7985dfe41db68a484c16e247873d17c Mon Sep 17 00:00:00 2001 From: Serhii Mamontov Date: Wed, 26 Feb 2025 10:35:37 +0200 Subject: [PATCH] Fix fetch issue with empty object rejection (#439) fix(fetch): fix fetch issue with empty object rejection Fix issue because of which code doesn't handle edge case when `fetch` reject with empty object and not `Error`. refactor(presence): remove `-pnpres` entries from presence requests Remove `-pnpres` channels and groups from presence `leave` and `heartbeat` requests. --- .pubnub.yml | 13 +- CHANGELOG.md | 9 ++ README.md | 4 +- dist/web/pubnub.js | 113 ++++++++++++--- dist/web/pubnub.min.js | 4 +- dist/web/pubnub.worker.js | 12 +- dist/web/pubnub.worker.min.js | 2 +- lib/core/components/configuration.js | 2 +- lib/core/components/subscription-manager.js | 14 +- lib/core/pubnub-common.js | 38 ++++- lib/errors/pubnub-api-error.js | 63 +++++++- package-lock.json | 4 +- package.json | 2 +- src/core/components/configuration.ts | 2 +- src/core/components/subscription-manager.ts | 17 +-- src/core/pubnub-common.ts | 40 +++++- src/errors/pubnub-api-error.ts | 60 +++++++- .../subscription-worker.ts | 10 +- src/transport/web-transport.ts | 5 +- .../components/subscription_manager.test.ts | 136 ++++++++++++++++++ .../operations/unsubscribe.test.ts | 96 +++++++++++++ 21 files changed, 570 insertions(+), 76 deletions(-) diff --git a/.pubnub.yml b/.pubnub.yml index 4345ec7b6..664fcd54f 100644 --- a/.pubnub.yml +++ b/.pubnub.yml @@ -1,5 +1,12 @@ --- changelog: + - date: 2025-02-26 + version: v8.9.1 + changes: + - type: bug + text: "Fix issue because of which code doesn't handle edge case when `fetch` reject with empty object and not `Error`." + - type: improvement + text: "Remove `-pnpres` channels and groups from presence `leave` and `heartbeat` requests." - date: 2025-02-18 version: v8.9.0 changes: @@ -1144,7 +1151,7 @@ supported-platforms: - 'Ubuntu 14.04 and up' - 'Windows 7 and up' version: 'Pubnub Javascript for Node' -version: '8.9.0' +version: '8.9.1' sdks: - full-name: PubNub Javascript SDK short-name: Javascript @@ -1160,7 +1167,7 @@ sdks: - distribution-type: source distribution-repository: GitHub release package-name: pubnub.js - location: https://github.com/pubnub/javascript/archive/refs/tags/v8.9.0.zip + location: https://github.com/pubnub/javascript/archive/refs/tags/v8.9.1.zip requires: - name: 'agentkeepalive' min-version: '3.5.2' @@ -1831,7 +1838,7 @@ sdks: - distribution-type: library distribution-repository: GitHub release package-name: pubnub.js - location: https://github.com/pubnub/javascript/releases/download/v8.9.0/pubnub.8.9.0.js + location: https://github.com/pubnub/javascript/releases/download/v8.9.1/pubnub.8.9.1.js requires: - name: 'agentkeepalive' min-version: '3.5.2' diff --git a/CHANGELOG.md b/CHANGELOG.md index 57065e5b6..bf0369903 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,12 @@ +## v8.9.1 +February 26 2025 + +#### Fixed +- Fix issue because of which code doesn't handle edge case when `fetch` reject with empty object and not `Error`. + +#### Modified +- Remove `-pnpres` channels and groups from presence `leave` and `heartbeat` requests. + ## v8.9.0 February 18 2025 diff --git a/README.md b/README.md index 5c6f82a1f..4780f799a 100644 --- a/README.md +++ b/README.md @@ -28,8 +28,8 @@ Watch [Getting Started with PubNub JS SDK](https://app.dashcam.io/replay/64ee0d2 npm install pubnub ``` * or download one of our builds from our CDN: - * https://cdn.pubnub.com/sdk/javascript/pubnub.8.9.0.js - * https://cdn.pubnub.com/sdk/javascript/pubnub.8.9.0.min.js + * https://cdn.pubnub.com/sdk/javascript/pubnub.8.9.1.js + * https://cdn.pubnub.com/sdk/javascript/pubnub.8.9.1.min.js 2. Configure your keys: diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index e9957c248..689b8f9b6 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -2890,7 +2890,7 @@ * * @param errorOrResponse - `Error` or service error response object from which error information * should be extracted. - * @param data - Preprocessed service error response. + * @param [data] - Preprocessed service error response. * * @returns `PubNubAPIError` object with known error category and additional information (if * available). @@ -2969,7 +2969,7 @@ * * @param response - Service error response object from which error information should be * extracted. - * @param data - Preprocessed service error response. + * @param [data] - Preprocessed service error response. * * @returns `PubNubAPIError` object with known error category and additional information (if * available). @@ -2990,6 +2990,11 @@ category = StatusCategory$1.PNAccessDeniedCategory; message = 'Access denied'; } + if (typeof response === 'object' && Object.keys(response).length === 0) { + category = StatusCategory$1.PNMalformedResponseCategory; + message = 'Malformed response (network issues)'; + status = 400; + } // Try to get more information about error from service response. if (data && data.byteLength > 0) { const decoded = new TextDecoder().decode(data); @@ -3042,7 +3047,7 @@ * @param message - Short API call error description. * @param category - Error category. * @param statusCode - Response HTTP status code. - * @param errorData - Error information. + * @param [errorData] - Error information. */ constructor(message, category, statusCode, errorData) { super(message); @@ -3065,19 +3070,58 @@ operation, statusCode: this.statusCode, errorData: this.errorData, + // @ts-expect-error Inner helper for JSON.stringify. + toJSON: function () { + let normalizedErrorData; + const errorData = this.errorData; + if (errorData) { + try { + if (typeof errorData === 'object') { + const errorObject = Object.assign(Object.assign(Object.assign(Object.assign({}, ('name' in errorData ? { name: errorData.name } : {})), ('message' in errorData ? { message: errorData.message } : {})), ('stack' in errorData ? { stack: errorData.stack } : {})), errorData); + normalizedErrorData = JSON.parse(JSON.stringify(errorObject, PubNubAPIError.circularReplacer())); + } + else + normalizedErrorData = errorData; + } + catch (_) { + normalizedErrorData = { error: 'Could not serialize the error object' }; + } + } + // Make sure to exclude `toJSON` function from the final object. + const _a = this, status = __rest(_a, ["toJSON"]); + return JSON.stringify(Object.assign(Object.assign({}, status), { errorData: normalizedErrorData })); + }, }; } /** * Convert API error object to PubNub client error object. * * @param operation - Request operation during which error happened. - * @param message - Custom error message. + * @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)); } + /** + * Function which handles circular references in serialized JSON. + * + * @returns Circular reference replacer function. + * + * @internal + */ + static circularReplacer() { + const visited = new WeakSet(); + return function (_, value) { + if (typeof value === 'object' && value !== null) { + if (visited.has(value)) + return '[Circular]'; + visited.add(value); + } + return value; + }; + } } /** @@ -3759,7 +3803,7 @@ return base.PubNubFile; }, get version() { - return '8.9.0'; + return '8.9.1'; }, getVersion() { return this.version; @@ -4273,10 +4317,9 @@ let fetchError = error; if (typeof error === 'string') { const errorMessage = error.toLowerCase(); - if (errorMessage.includes('timeout') || !errorMessage.includes('cancel')) - fetchError = new Error(error); - else if (errorMessage.includes('cancel')) - fetchError = new DOMException('Aborted', 'AbortError'); + fetchError = new Error(error); + if (!errorMessage.includes('timeout') && errorMessage.includes('cancel')) + fetchError.name = 'AbortError'; } throw PubNubAPIError.create(fetchError); }); @@ -5036,7 +5079,8 @@ if (status.category === StatusCategory$1.PNTimeoutCategory) { this.startSubscribeLoop(); } - else if (status.category === StatusCategory$1.PNNetworkIssuesCategory) { + else if (status.category === StatusCategory$1.PNNetworkIssuesCategory || + status.category === StatusCategory$1.PNMalformedResponseCategory) { this.disconnect(); if (status.error && this.configuration.autoNetworkDetection && this.isOnline) { this.isOnline = false; @@ -5058,14 +5102,11 @@ this.listenerManager.announceStatus(reconnectedAnnounce); }); this.reconnectionManager.startPolling(); - this.listenerManager.announceStatus(status); + this.listenerManager.announceStatus(Object.assign(Object.assign({}, status), { category: StatusCategory$1.PNNetworkIssuesCategory })); } - else if (status.category === StatusCategory$1.PNBadRequestCategory || - status.category == StatusCategory$1.PNMalformedResponseCategory) { - const category = this.isOnline ? StatusCategory$1.PNDisconnectedUnexpectedlyCategory : status.category; - this.isOnline = false; - this.disconnect(); - this.listenerManager.announceStatus(Object.assign(Object.assign({}, status), { category })); + else if (status.category === StatusCategory$1.PNBadRequestCategory) { + this.stopHeartbeatTimer(); + this.listenerManager.announceStatus(status); } else this.listenerManager.announceStatus(status); @@ -13319,7 +13360,22 @@ */ makeUnsubscribe(parameters, callback) { { - this.sendRequest(new PresenceLeaveRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet })), callback); + // Filtering out presence channels and groups. + let { channels, channelGroups } = parameters; + if (channelGroups) + channelGroups = channelGroups.filter((channelGroup) => !channelGroup.endsWith('-pnpres')); + if (channels) + channels = channels.filter((channel) => !channel.endsWith('-pnpres')); + // Complete immediately request only for presence channels. + if ((channelGroups !== null && channelGroups !== void 0 ? channelGroups : []).length === 0 && (channels !== null && channels !== void 0 ? channels : []).length === 0) { + return callback({ + error: false, + operation: RequestOperation$1.PNUnsubscribeOperation, + category: StatusCategory$1.PNAcknowledgmentCategory, + statusCode: 200, + }); + } + this.sendRequest(new PresenceLeaveRequest({ channels, channelGroups, keySet: this._configuration.keySet }), callback); } } /** @@ -13670,7 +13726,26 @@ heartbeat(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { { - const request = new HeartbeatRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet })); + // Filtering out presence channels and groups. + let { channels, channelGroups } = parameters; + if (channelGroups) + channelGroups = channelGroups.filter((channelGroup) => !channelGroup.endsWith('-pnpres')); + if (channels) + channels = channels.filter((channel) => !channel.endsWith('-pnpres')); + // Complete immediately request only for presence channels. + if ((channelGroups !== null && channelGroups !== void 0 ? channelGroups : []).length === 0 && (channels !== null && channels !== void 0 ? channels : []).length === 0) { + const responseStatus = { + error: false, + operation: RequestOperation$1.PNHeartbeatOperation, + category: StatusCategory$1.PNAcknowledgmentCategory, + statusCode: 200, + }; + if (callback) + return callback(responseStatus, {}); + return Promise.resolve(responseStatus); + } + const request = new HeartbeatRequest(Object.assign(Object.assign({}, parameters), { channels, + channelGroups, keySet: this._configuration.keySet })); if (callback) return this.sendRequest(request, callback); return this.sendRequest(request); diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index 6ec372c60..7ef391b9e 100644 --- a/dist/web/pubnub.min.js +++ b/dist/web/pubnub.min.js @@ -1,2 +1,2 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).PubNub=t()}(this,(function(){"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n={exports:{}};!function(t){!function(e,n){var s=Math.pow(2,-24),r=Math.pow(2,32),i=Math.pow(2,53);var a={encode:function(e){var t,s=new ArrayBuffer(256),a=new DataView(s),o=0;function c(e){for(var n=s.byteLength,r=o+e;n>2,u=0;u>6),r.push(128|63&a)):a<55296?(r.push(224|a>>12),r.push(128|a>>6&63),r.push(128|63&a)):(a=(1023&a)<<10,a|=1023&t.charCodeAt(++s),a+=65536,r.push(240|a>>18),r.push(128|a>>12&63),r.push(128|a>>6&63),r.push(128|63&a))}return d(3,r.length),h(r);default:var p;if(Array.isArray(t))for(d(4,p=t.length),s=0;s>5!==e)throw"Invalid indefinite length element";return n}function f(e,t){for(var n=0;n>10),e.push(56320|1023&s))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof i&&(i=function(){return n});var m=function e(){var r,d,m=l(),b=m>>5,v=31&m;if(7===b)switch(v){case 25:return function(){var e=new ArrayBuffer(4),t=new DataView(e),n=h(),r=32768&n,i=31744&n,a=1023&n;if(31744===i)i=261120;else if(0!==i)i+=114688;else if(0!==a)return a*s;return t.setUint32(0,r<<16|i<<13|a<<13),t.getFloat32(0)}();case 26:return c(a.getFloat32(o),4);case 27:return c(a.getFloat64(o),8)}if((d=g(v))<0&&(b<2||6=0;)S+=d,w.push(u(d));var E=new Uint8Array(S),O=0;for(r=0;r=0;)f(k,d);else f(k,d);return String.fromCharCode.apply(null,k);case 4:var C;if(d<0)for(C=[];!p();)C.push(e());else for(C=new Array(d),r=0;r{const n=new FileReader;n.addEventListener("load",(()=>{if(n.result instanceof ArrayBuffer)return e(n.result)})),n.addEventListener("error",(()=>t(n.error))),n.readAsArrayBuffer(this.data)}))}))}toString(){return i(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const n=new FileReader;n.addEventListener("load",(()=>{if("string"==typeof n.result)return e(n.result)})),n.addEventListener("error",(()=>{t(n.error)})),n.readAsBinaryString(this.data)}))}))}toStream(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in Node.js environments.")}))}toFile(){return i(this,void 0,void 0,(function*(){return this.data}))}toFileUri(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in React Native environments.")}))}toBlob(){return i(this,void 0,void 0,(function*(){return this.data}))}}o.supportsBlob="undefined"!=typeof Blob,o.supportsFile="undefined"!=typeof File,o.supportsBuffer=!1,o.supportsStream=!1,o.supportsString=!0,o.supportsArrayBuffer=!0,o.supportsEncryptFile=!0,o.supportsFileUri=!1;function c(e){const t=e.replace(/==?$/,""),n=Math.floor(t.length/4*3),s=new ArrayBuffer(n),r=new Uint8Array(s);let i=0;function a(){const e=t.charAt(i++),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e);if(-1===n)throw new Error(`Illegal character at ${i}: ${t.charAt(i-1)}`);return n}for(let e=0;e>4,c=(15&n)<<4|s>>2,u=(3&s)<<6|i;r[e]=o,64!=s&&(r[e+1]=c),64!=i&&(r[e+2]=u)}return s}function u(e){let t="";const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=new Uint8Array(e),r=s.byteLength,i=r%3,a=r-i;let o,c,u,l,h;for(let e=0;e>18,c=(258048&h)>>12,u=(4032&h)>>6,l=63&h,t+=n[o]+n[c]+n[u]+n[l];return 1==i?(h=s[a],o=(252&h)>>2,c=(3&h)<<4,t+=n[o]+n[c]+"=="):2==i&&(h=s[a]<<8|s[a+1],o=(64512&h)>>10,c=(1008&h)>>4,u=(15&h)<<2,t+=n[o]+n[c]+n[u]+"="),t}var l;!function(e){e.PNNetworkIssuesCategory="PNNetworkIssuesCategory",e.PNTimeoutCategory="PNTimeoutCategory",e.PNCancelledCategory="PNCancelledCategory",e.PNBadRequestCategory="PNBadRequestCategory",e.PNAccessDeniedCategory="PNAccessDeniedCategory",e.PNValidationErrorCategory="PNValidationErrorCategory",e.PNAcknowledgmentCategory="PNAcknowledgmentCategory",e.PNMalformedResponseCategory="PNMalformedResponseCategory",e.PNUnknownCategory="PNUnknownCategory",e.PNNetworkUpCategory="PNNetworkUpCategory",e.PNNetworkDownCategory="PNNetworkDownCategory",e.PNReconnectedCategory="PNReconnectedCategory",e.PNConnectedCategory="PNConnectedCategory",e.PNRequestMessageCountExceededCategory="PNRequestMessageCountExceededCategory",e.PNDisconnectedCategory="PNDisconnectedCategory",e.PNConnectionErrorCategory="PNConnectionErrorCategory",e.PNDisconnectedUnexpectedlyCategory="PNDisconnectedUnexpectedlyCategory"}(l||(l={}));var h=l;class d extends Error{constructor(e,t){super(e),this.status=t,this.name="PubNubError",this.message=e,Object.setPrototypeOf(this,new.target.prototype)}}function p(e,t){var n;return null!==(n=e.statusCode)&&void 0!==n||(e.statusCode=0),Object.assign(Object.assign({},e),{statusCode:e.statusCode,category:t,error:!0})}function g(e,t){return p(Object.assign({message:e},{}),h.PNValidationErrorCategory)}function y(e,t){return p(Object.assign(Object.assign({message:"Unable to deserialize service response"},void 0!==e?{responseText:e}:{}),void 0!==t?{statusCode:t}:{}),h.PNMalformedResponseCategory)}var f,m,b,v,w,S=S||function(e){var t={},n=t.lib={},s=function(){},r=n.Base={extend:function(e){s.prototype=this;var t=new s;return e&&t.mixIn(e),t.hasOwnProperty("init")||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},i=n.WordArray=r.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||o).stringify(this)},concat:function(e){var t=this.words,n=e.words,s=this.sigBytes;if(e=e.sigBytes,this.clamp(),s%4)for(var r=0;r>>2]|=(n[r>>>2]>>>24-r%4*8&255)<<24-(s+r)%4*8;else if(65535>>2]=n[r>>>2];else t.push.apply(t,n);return this.sigBytes+=e,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=r.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n=[],s=0;s>>2]>>>24-s%4*8&255;n.push((r>>>4).toString(16)),n.push((15&r).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,n=[],s=0;s>>3]|=parseInt(e.substr(s,2),16)<<24-s%8*4;return new i.init(n,t/2)}},c=a.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],s=0;s>>2]>>>24-s%4*8&255));return n.join("")},parse:function(e){for(var t=e.length,n=[],s=0;s>>2]|=(255&e.charCodeAt(s))<<24-s%4*8;return new i.init(n,t)}},u=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},l=n.BufferedBlockAlgorithm=r.extend({reset:function(){this._data=new i.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=u.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,s=n.words,r=n.sigBytes,a=this.blockSize,o=r/(4*a);if(t=(o=t?e.ceil(o):e.max((0|o)-this._minBufferSize,0))*a,r=e.min(4*t,r),t){for(var c=0;cu;){var l;e:{l=c;for(var h=e.sqrt(l),d=2;d<=h;d++)if(!(l%d)){l=!1;break e}l=!0}l&&(8>u&&(i[u]=o(e.pow(c,.5))),a[u]=o(e.pow(c,1/3)),u++),c++}var p=[];r=r.SHA256=s.extend({_doReset:function(){this._hash=new n.init(i.slice(0))},_doProcessBlock:function(e,t){for(var n=this._hash.words,s=n[0],r=n[1],i=n[2],o=n[3],c=n[4],u=n[5],l=n[6],h=n[7],d=0;64>d;d++){if(16>d)p[d]=0|e[t+d];else{var g=p[d-15],y=p[d-2];p[d]=((g<<25|g>>>7)^(g<<14|g>>>18)^g>>>3)+p[d-7]+((y<<15|y>>>17)^(y<<13|y>>>19)^y>>>10)+p[d-16]}g=h+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&u^~c&l)+a[d]+p[d],y=((s<<30|s>>>2)^(s<<19|s>>>13)^(s<<10|s>>>22))+(s&r^s&i^r&i),h=l,l=u,u=c,c=o+g|0,o=i,i=r,r=s,s=g+y|0}n[0]=n[0]+s|0,n[1]=n[1]+r|0,n[2]=n[2]+i|0,n[3]=n[3]+o|0,n[4]=n[4]+c|0,n[5]=n[5]+u|0,n[6]=n[6]+l|0,n[7]=n[7]+h|0},_doFinalize:function(){var t=this._data,n=t.words,s=8*this._nDataBytes,r=8*t.sigBytes;return n[r>>>5]|=128<<24-r%32,n[14+(r+64>>>9<<4)]=e.floor(s/4294967296),n[15+(r+64>>>9<<4)]=s,t.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var e=s.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=s._createHelper(r),t.HmacSHA256=s._createHmacHelper(r)}(Math),m=(f=S).enc.Utf8,f.algo.HMAC=f.lib.Base.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=m.parse(t));var n=e.blockSize,s=4*n;t.sigBytes>s&&(t=e.finalize(t)),t.clamp();for(var r=this._oKey=t.clone(),i=this._iKey=t.clone(),a=r.words,o=i.words,c=0;c>>2]>>>24-r%4*8&255)<<16|(t[r+1>>>2]>>>24-(r+1)%4*8&255)<<8|t[r+2>>>2]>>>24-(r+2)%4*8&255,a=0;4>a&&r+.75*a>>6*(3-a)&63));if(t=s.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var t=e.length,n=this._map;(s=n.charAt(64))&&-1!=(s=e.indexOf(s))&&(t=s);for(var s=[],r=0,i=0;i>>6-i%4*2;s[r>>>2]|=(a|o)<<24-r%4*8,r++}return v.create(s,r)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},function(e){function t(e,t,n,s,r,i,a){return((e=e+(t&n|~t&s)+r+a)<>>32-i)+t}function n(e,t,n,s,r,i,a){return((e=e+(t&s|n&~s)+r+a)<>>32-i)+t}function s(e,t,n,s,r,i,a){return((e=e+(t^n^s)+r+a)<>>32-i)+t}function r(e,t,n,s,r,i,a){return((e=e+(n^(t|~s))+r+a)<>>32-i)+t}for(var i=S,a=(c=i.lib).WordArray,o=c.Hasher,c=i.algo,u=[],l=0;64>l;l++)u[l]=4294967296*e.abs(e.sin(l+1))|0;c=c.MD5=o.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,i){for(var a=0;16>a;a++){var o=e[c=i+a];e[c]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8)}a=this._hash.words;var c=e[i+0],l=(o=e[i+1],e[i+2]),h=e[i+3],d=e[i+4],p=e[i+5],g=e[i+6],y=e[i+7],f=e[i+8],m=e[i+9],b=e[i+10],v=e[i+11],w=e[i+12],S=e[i+13],E=e[i+14],O=e[i+15],k=t(k=a[0],P=a[1],N=a[2],C=a[3],c,7,u[0]),C=t(C,k,P,N,o,12,u[1]),N=t(N,C,k,P,l,17,u[2]),P=t(P,N,C,k,h,22,u[3]);k=t(k,P,N,C,d,7,u[4]),C=t(C,k,P,N,p,12,u[5]),N=t(N,C,k,P,g,17,u[6]),P=t(P,N,C,k,y,22,u[7]),k=t(k,P,N,C,f,7,u[8]),C=t(C,k,P,N,m,12,u[9]),N=t(N,C,k,P,b,17,u[10]),P=t(P,N,C,k,v,22,u[11]),k=t(k,P,N,C,w,7,u[12]),C=t(C,k,P,N,S,12,u[13]),N=t(N,C,k,P,E,17,u[14]),k=n(k,P=t(P,N,C,k,O,22,u[15]),N,C,o,5,u[16]),C=n(C,k,P,N,g,9,u[17]),N=n(N,C,k,P,v,14,u[18]),P=n(P,N,C,k,c,20,u[19]),k=n(k,P,N,C,p,5,u[20]),C=n(C,k,P,N,b,9,u[21]),N=n(N,C,k,P,O,14,u[22]),P=n(P,N,C,k,d,20,u[23]),k=n(k,P,N,C,m,5,u[24]),C=n(C,k,P,N,E,9,u[25]),N=n(N,C,k,P,h,14,u[26]),P=n(P,N,C,k,f,20,u[27]),k=n(k,P,N,C,S,5,u[28]),C=n(C,k,P,N,l,9,u[29]),N=n(N,C,k,P,y,14,u[30]),k=s(k,P=n(P,N,C,k,w,20,u[31]),N,C,p,4,u[32]),C=s(C,k,P,N,f,11,u[33]),N=s(N,C,k,P,v,16,u[34]),P=s(P,N,C,k,E,23,u[35]),k=s(k,P,N,C,o,4,u[36]),C=s(C,k,P,N,d,11,u[37]),N=s(N,C,k,P,y,16,u[38]),P=s(P,N,C,k,b,23,u[39]),k=s(k,P,N,C,S,4,u[40]),C=s(C,k,P,N,c,11,u[41]),N=s(N,C,k,P,h,16,u[42]),P=s(P,N,C,k,g,23,u[43]),k=s(k,P,N,C,m,4,u[44]),C=s(C,k,P,N,w,11,u[45]),N=s(N,C,k,P,O,16,u[46]),k=r(k,P=s(P,N,C,k,l,23,u[47]),N,C,c,6,u[48]),C=r(C,k,P,N,y,10,u[49]),N=r(N,C,k,P,E,15,u[50]),P=r(P,N,C,k,p,21,u[51]),k=r(k,P,N,C,w,6,u[52]),C=r(C,k,P,N,h,10,u[53]),N=r(N,C,k,P,b,15,u[54]),P=r(P,N,C,k,o,21,u[55]),k=r(k,P,N,C,f,6,u[56]),C=r(C,k,P,N,O,10,u[57]),N=r(N,C,k,P,g,15,u[58]),P=r(P,N,C,k,S,21,u[59]),k=r(k,P,N,C,d,6,u[60]),C=r(C,k,P,N,v,10,u[61]),N=r(N,C,k,P,l,15,u[62]),P=r(P,N,C,k,m,21,u[63]);a[0]=a[0]+k|0,a[1]=a[1]+P|0,a[2]=a[2]+N|0,a[3]=a[3]+C|0},_doFinalize:function(){var t=this._data,n=t.words,s=8*this._nDataBytes,r=8*t.sigBytes;n[r>>>5]|=128<<24-r%32;var i=e.floor(s/4294967296);for(n[15+(r+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),n[14+(r+64>>>9<<4)]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),t.sigBytes=4*(n.length+1),this._process(),n=(t=this._hash).words,s=0;4>s;s++)r=n[s],n[s]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8);return t},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}}),i.MD5=o._createHelper(c),i.HmacMD5=o._createHmacHelper(c)}(Math),function(){var e,t=S,n=(e=t.lib).Base,s=e.WordArray,r=(e=t.algo).EvpKDF=n.extend({cfg:n.extend({keySize:4,hasher:e.MD5,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var n=(o=this.cfg).hasher.create(),r=s.create(),i=r.words,a=o.keySize,o=o.iterations;i.length>>2]}},e.BlockCipher=a.extend({cfg:a.cfg.extend({mode:o,padding:u}),reset:function(){a.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var n=t.createEncryptor;else n=t.createDecryptor,this._minBufferSize=1;this._mode=n.call(t,this,e&&e.words)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else t=this._process(!0),e.unpad(t);return t},blockSize:4});var l=e.CipherParams=t.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),h=(o=(d.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?n.create([1398893684,1701076831]).concat(e).concat(t):t).toString(r)},parse:function(e){var t=(e=r.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var s=n.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return l.create({ciphertext:e,salt:s})}},e.SerializableCipher=t.extend({cfg:t.extend({format:o}),encrypt:function(e,t,n,s){s=this.cfg.extend(s);var r=e.createEncryptor(n,s);return t=r.finalize(t),r=r.cfg,l.create({ciphertext:t,key:n,iv:r.iv,algorithm:e,mode:r.mode,padding:r.padding,blockSize:e.blockSize,formatter:s.format})},decrypt:function(e,t,n,s){return s=this.cfg.extend(s),t=this._parse(t,s.format),e.createDecryptor(n,s).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),d=(d.kdf={}).OpenSSL={execute:function(e,t,s,r){return r||(r=n.random(8)),e=i.create({keySize:t+s}).compute(e,r),s=n.create(e.words.slice(t),4*s),e.sigBytes=4*t,l.create({key:e,iv:s,salt:r})}},p=e.PasswordBasedCipher=h.extend({cfg:h.cfg.extend({kdf:d}),encrypt:function(e,t,n,s){return n=(s=this.cfg.extend(s)).kdf.execute(n,e.keySize,e.ivSize),s.iv=n.iv,(e=h.encrypt.call(this,e,t,n.key,s)).mixIn(n),e},decrypt:function(e,t,n,s){return s=this.cfg.extend(s),t=this._parse(t,s.format),n=s.kdf.execute(n,e.keySize,e.ivSize,t.salt),s.iv=n.iv,h.decrypt.call(this,e,t,n.key,s)}})}(),function(){for(var e=S,t=e.lib.BlockCipher,n=e.algo,s=[],r=[],i=[],a=[],o=[],c=[],u=[],l=[],h=[],d=[],p=[],g=0;256>g;g++)p[g]=128>g?g<<1:g<<1^283;var y=0,f=0;for(g=0;256>g;g++){var m=(m=f^f<<1^f<<2^f<<3^f<<4)>>>8^255&m^99;s[y]=m,r[m]=y;var b=p[y],v=p[b],w=p[v],E=257*p[m]^16843008*m;i[y]=E<<24|E>>>8,a[y]=E<<16|E>>>16,o[y]=E<<8|E>>>24,c[y]=E,E=16843009*w^65537*v^257*b^16843008*y,u[m]=E<<24|E>>>8,l[m]=E<<16|E>>>16,h[m]=E<<8|E>>>24,d[m]=E,y?(y=b^p[p[p[w^b]]],f^=p[p[f]]):y=f=1}var O=[0,1,2,4,8,16,32,64,128,27,54];n=n.AES=t.extend({_doReset:function(){for(var e=(n=this._key).words,t=n.sigBytes/4,n=4*((this._nRounds=t+6)+1),r=this._keySchedule=[],i=0;i>>24]<<24|s[a>>>16&255]<<16|s[a>>>8&255]<<8|s[255&a]):(a=s[(a=a<<8|a>>>24)>>>24]<<24|s[a>>>16&255]<<16|s[a>>>8&255]<<8|s[255&a],a^=O[i/t|0]<<24),r[i]=r[i-t]^a}for(e=this._invKeySchedule=[],t=0;tt||4>=i?a:u[s[a>>>24]]^l[s[a>>>16&255]]^h[s[a>>>8&255]]^d[s[255&a]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,i,a,o,c,s)},decryptBlock:function(e,t){var n=e[t+1];e[t+1]=e[t+3],e[t+3]=n,this._doCryptBlock(e,t,this._invKeySchedule,u,l,h,d,r),n=e[t+1],e[t+1]=e[t+3],e[t+3]=n},_doCryptBlock:function(e,t,n,s,r,i,a,o){for(var c=this._nRounds,u=e[t]^n[0],l=e[t+1]^n[1],h=e[t+2]^n[2],d=e[t+3]^n[3],p=4,g=1;g>>24]^r[l>>>16&255]^i[h>>>8&255]^a[255&d]^n[p++],f=s[l>>>24]^r[h>>>16&255]^i[d>>>8&255]^a[255&u]^n[p++],m=s[h>>>24]^r[d>>>16&255]^i[u>>>8&255]^a[255&l]^n[p++];d=s[d>>>24]^r[u>>>16&255]^i[l>>>8&255]^a[255&h]^n[p++],u=y,l=f,h=m}y=(o[u>>>24]<<24|o[l>>>16&255]<<16|o[h>>>8&255]<<8|o[255&d])^n[p++],f=(o[l>>>24]<<24|o[h>>>16&255]<<16|o[d>>>8&255]<<8|o[255&u])^n[p++],m=(o[h>>>24]<<24|o[d>>>16&255]<<16|o[u>>>8&255]<<8|o[255&l])^n[p++],d=(o[d>>>24]<<24|o[u>>>16&255]<<16|o[l>>>8&255]<<8|o[255&h])^n[p++],e[t]=y,e[t+1]=f,e[t+2]=m,e[t+3]=d},keySize:8});e.AES=t._createHelper(n)}(),S.mode.ECB=((w=S.lib.BlockCipherMode.extend()).Encryptor=w.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),w.Decryptor=w.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),w);var E=t(S);class O{constructor({cipherKey:e}){this.cipherKey=e,this.CryptoJS=E,this.encryptedKey=this.CryptoJS.SHA256(e)}encrypt(e){if(0===("string"==typeof e?e:O.decoder.decode(e)).length)throw new Error("encryption error. empty content");const t=this.getIv();return{metadata:t,data:c(this.CryptoJS.AES.encrypt(e,this.encryptedKey,{iv:this.bufferToWordArray(t),mode:this.CryptoJS.mode.CBC}).ciphertext.toString(this.CryptoJS.enc.Base64))}}encryptFileData(e){return i(this,void 0,void 0,(function*(){const t=yield this.getKey(),n=this.getIv();return{data:yield crypto.subtle.encrypt({name:this.algo,iv:n},t,e),metadata:n}}))}decrypt(e){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=this.bufferToWordArray(new Uint8ClampedArray(e.metadata)),n=this.bufferToWordArray(new Uint8ClampedArray(e.data));return O.encoder.encode(this.CryptoJS.AES.decrypt({ciphertext:n},this.encryptedKey,{iv:t,mode:this.CryptoJS.mode.CBC}).toString(this.CryptoJS.enc.Utf8)).buffer}decryptFileData(e){return i(this,void 0,void 0,(function*(){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=yield this.getKey();return crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)}))}get identifier(){return"ACRH"}get algo(){return"AES-CBC"}getIv(){return crypto.getRandomValues(new Uint8Array(O.BLOCK_SIZE))}getKey(){return i(this,void 0,void 0,(function*(){const e=O.encoder.encode(this.cipherKey),t=yield crypto.subtle.digest("SHA-256",e.buffer);return crypto.subtle.importKey("raw",t,this.algo,!0,["encrypt","decrypt"])}))}bufferToWordArray(e){const t=[];let n;for(n=0;ne.toString(16).padStart(2,"0"))).join(""),s=N.encoder.encode(n.slice(0,32)).buffer;return crypto.subtle.importKey("raw",s,"AES-CBC",!0,["encrypt","decrypt"])}))}concatArrayBuffer(e,t){const n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}}N.IV_LENGTH=16,N.encoder=new TextEncoder,N.decoder=new TextDecoder;class P{constructor(e){this.config=e,this.cryptor=new C(Object.assign({},e)),this.fileCryptor=new N}encrypt(e){const t="string"==typeof e?e:P.decoder.decode(e);return{data:this.cryptor.encrypt(t),metadata:null}}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var n;if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.encryptFile(null===(n=this.config)||void 0===n?void 0:n.cipherKey,e,t)}))}decrypt(e){const t="string"==typeof e.data?e.data:u(e.data);return this.cryptor.decrypt(t)}decryptFile(e,t){return i(this,void 0,void 0,(function*(){if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.decryptFile(this.config.cipherKey,e,t)}))}get identifier(){return""}}P.encoder=new TextEncoder,P.decoder=new TextDecoder;class M extends a{static legacyCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new M({default:new P(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t})),cryptors:[new O({cipherKey:e.cipherKey})]})}static aesCbcCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new M({default:new O({cipherKey:e.cipherKey}),cryptors:[new P(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t}))]})}static withDefaultCryptor(e){return new this({default:e})}encrypt(e){const t=e instanceof ArrayBuffer&&this.defaultCryptor.identifier===M.LEGACY_IDENTIFIER?this.defaultCryptor.encrypt(M.decoder.decode(e)):this.defaultCryptor.encrypt(e);if(!t.metadata)return t.data;if("string"==typeof t.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");const n=this.getHeaderData(t);return this.concatArrayBuffer(n,t.data)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){if(this.defaultCryptor.identifier===_.LEGACY_IDENTIFIER)return this.defaultCryptor.encryptFile(e,t);const n=yield this.getFileData(e),s=yield this.defaultCryptor.encryptFileData(n);if("string"==typeof s.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");return t.create({name:e.name,mimeType:"application/octet-stream",data:this.concatArrayBuffer(this.getHeaderData(s),s.data)})}))}decrypt(e){const t="string"==typeof e?c(e):e,n=_.tryParse(t),s=this.getCryptor(n),r=n.length>0?t.slice(n.length-n.metadataLength,n.length):null;if(t.slice(n.length).byteLength<=0)throw new Error("Decryption error: empty content");return s.decrypt({data:t.slice(n.length),metadata:r})}decryptFile(e,t){return i(this,void 0,void 0,(function*(){const n=yield e.data.arrayBuffer(),s=_.tryParse(n),r=this.getCryptor(s);if((null==r?void 0:r.identifier)===_.LEGACY_IDENTIFIER)return r.decryptFile(e,t);const i=(yield this.getFileData(n)).slice(s.length-s.metadataLength,s.length);return t.create({name:e.name,data:yield this.defaultCryptor.decryptFileData({data:n.slice(s.length),metadata:i})})}))}getCryptorFromId(e){const t=this.getAllCryptors().find((t=>e===t.identifier));if(t)return t;throw Error("Unknown cryptor error")}getCryptor(e){if("string"==typeof e){const t=this.getAllCryptors().find((t=>t.identifier===e));if(t)return t;throw new Error("Unknown cryptor error")}if(e instanceof A)return this.getCryptorFromId(e.identifier)}getHeaderData(e){if(!e.metadata)return;const t=_.from(this.defaultCryptor.identifier,e.metadata),n=new Uint8Array(t.length);let s=0;return n.set(t.data,s),s+=t.length-e.metadata.byteLength,n.set(new Uint8Array(e.metadata),s),n.buffer}concatArrayBuffer(e,t){const n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}getFileData(e){return i(this,void 0,void 0,(function*(){if(e instanceof ArrayBuffer)return e;if(e instanceof o)return e.toArrayBuffer();throw new Error("Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob")}))}}M.LEGACY_IDENTIFIER="";class _{static from(e,t){if(e!==_.LEGACY_IDENTIFIER)return new A(e,t.byteLength)}static tryParse(e){const t=new Uint8Array(e);let n,s,r=null;if(t.byteLength>=4&&(n=t.slice(0,4),this.decoder.decode(n)!==_.SENTINEL))return M.LEGACY_IDENTIFIER;if(!(t.byteLength>=5))throw new Error("Decryption error: invalid header version");if(r=t[4],r>_.MAX_VERSION)throw new Error("Decryption error: Unknown cryptor error");let i=5+_.IDENTIFIER_LENGTH;if(!(t.byteLength>=i))throw new Error("Decryption error: invalid crypto identifier");s=t.slice(5,i);let a=null;if(!(t.byteLength>=i+1))throw new Error("Decryption error: invalid metadata length");return a=t[i],i+=1,255===a&&t.byteLength>=i+2&&(a=new Uint16Array(t.slice(i,i+2)).reduce(((e,t)=>(e<<8)+t),0)),new A(this.decoder.decode(s),a)}}_.SENTINEL="PNED",_.LEGACY_IDENTIFIER="",_.IDENTIFIER_LENGTH=4,_.VERSION=1,_.MAX_VERSION=1,_.decoder=new TextDecoder;class A{constructor(e,t){this._identifier=e,this._metadataLength=t}get identifier(){return this._identifier}set identifier(e){this._identifier=e}get metadataLength(){return this._metadataLength}set metadataLength(e){this._metadataLength=e}get version(){return _.VERSION}get length(){return _.SENTINEL.length+1+_.IDENTIFIER_LENGTH+(this.metadataLength<255?1:3)+this.metadataLength}get data(){let e=0;const t=new Uint8Array(this.length),n=new TextEncoder;t.set(n.encode(_.SENTINEL)),e+=_.SENTINEL.length,t[e]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e);const s=this.metadataLength;return e+=_.IDENTIFIER_LENGTH,s<255?t[e]=s:t.set([255,s>>8,255&s],e),t}}A.IDENTIFIER_LENGTH=4,A.SENTINEL="PNED";class j extends Error{static create(e,t){return e instanceof Error?j.createFromError(e):j.createFromServiceResponse(e,t)}static createFromError(e){let t=h.PNUnknownCategory,n="Unknown error",s="Error";if(!e)return new j(n,t,0);if(e instanceof j)return e;if(e instanceof Error&&(n=e.message,s=e.name),"AbortError"===s||-1!==n.indexOf("Aborted"))t=h.PNCancelledCategory,n="Request cancelled";else if(-1!==n.toLowerCase().indexOf("timeout"))t=h.PNTimeoutCategory,n="Request timeout";else if(-1!==n.toLowerCase().indexOf("network"))t=h.PNNetworkIssuesCategory,n="Network issues";else if("TypeError"===s)t=-1!==n.indexOf("Load failed")||-1!=n.indexOf("Failed to fetch")?h.PNNetworkIssuesCategory:h.PNBadRequestCategory;else if("FetchError"===s){const s=e.code;["ECONNREFUSED","ENETUNREACH","ENOTFOUND","ECONNRESET","EAI_AGAIN"].includes(s)&&(t=h.PNNetworkIssuesCategory),"ECONNREFUSED"===s?n="Connection refused":"ENETUNREACH"===s?n="Network not reachable":"ENOTFOUND"===s?n="Server not found":"ECONNRESET"===s?n="Connection reset by peer":"EAI_AGAIN"===s?n="Name resolution error":"ETIMEDOUT"===s?(t=h.PNTimeoutCategory,n="Request timeout"):n=`Unknown system error: ${e}`}else"Request timeout"===n&&(t=h.PNTimeoutCategory);return new j(n,t,0,e)}static createFromServiceResponse(e,t){let n,s=h.PNUnknownCategory,r="Unknown error",{status:i}=e;if(null!=t||(t=e.body),402===i?r="Not available for used key set. Contact support@pubnub.com":400===i?(s=h.PNBadRequestCategory,r="Bad request"):403===i&&(s=h.PNAccessDeniedCategory,r="Access denied"),t&&t.byteLength>0){const s=(new TextDecoder).decode(t);if(-1!==e.headers["content-type"].indexOf("text/javascript")||-1!==e.headers["content-type"].indexOf("application/json"))try{const e=JSON.parse(s);"object"==typeof e&&(Array.isArray(e)?"number"==typeof e[0]&&0===e[0]&&e.length>1&&"string"==typeof e[1]&&(n=e[1]):("error"in e&&(1===e.error||!0===e.error)&&"status"in e&&"number"==typeof e.status&&"message"in e&&"service"in e?(n=e,i=e.status):n=e,"error"in e&&e.error instanceof Error&&(n=e.error)))}catch(e){n=s}else if(-1!==e.headers["content-type"].indexOf("xml")){const e=/(.*)<\/Message>/gi.exec(s);r=e?`Upload to bucket failed: ${e[1]}`:"Upload to bucket failed."}else n=s}return new j(r,s,i,n)}constructor(e,t,n,s){super(e),this.category=t,this.statusCode=n,this.errorData=s,this.name="PubNubAPIError"}toStatus(e){return{error:!0,category:this.category,operation:e,statusCode:this.statusCode,errorData:this.errorData}}toPubNubError(e,t){return new d(null!=t?t:this.message,this.toStatus(e))}}class I{constructor(e){this.configuration=e,this.subscriptionWorkerReady=!1,this.workerEventsQueue=[],this.callbacks=new Map,this.setupSubscriptionWorker()}makeSendable(e){if(!e.path.startsWith("/v2/subscribe")&&!e.path.endsWith("/heartbeat")&&!e.path.endsWith("/leave"))return this.configuration.transport.makeSendable(e);let t;const n={type:"send-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,request:e};return e.cancellable&&(t={abort:()=>{const t={type:"cancel-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,identifier:e.identifier};this.scheduleEventPost(t)}}),[new Promise(((t,s)=>{this.callbacks.set(e.identifier,{resolve:t,reject:s}),this.scheduleEventPost(n)})),t]}request(e){return e}scheduleEventPost(e,t=!1){const n=this.sharedSubscriptionWorker;n?n.port.postMessage(e):t?this.workerEventsQueue.splice(0,0,e):this.workerEventsQueue.push(e)}flushScheduledEvents(){const e=this.sharedSubscriptionWorker;if(!e||0===this.workerEventsQueue.length)return;const t=[];for(let e=0;e!t.includes(e))),this.workerEventsQueue.forEach((t=>e.port.postMessage(t))),this.workerEventsQueue=[]}get sharedSubscriptionWorker(){return this.subscriptionWorkerReady?this.subscriptionWorker:null}setupSubscriptionWorker(){"undefined"!=typeof SharedWorker&&(this.subscriptionWorker=new SharedWorker(this.configuration.workerUrl,`/pubnub-${this.configuration.sdkVersion}`),this.subscriptionWorker.port.start(),this.scheduleEventPost({type:"client-register",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,heartbeatInterval:this.configuration.heartbeatInterval,logVerbosity:this.configuration.logVerbosity,workerLogVerbosity:this.configuration.workerLogVerbosity},!0),this.subscriptionWorker.port.onmessage=e=>this.handleWorkerEvent(e))}handleWorkerEvent(e){const{data:t}=e;if("shared-worker-ping"===t.type||"shared-worker-connected"===t.type||"shared-worker-console-log"===t.type||"shared-worker-console-dir"===t.type||t.clientIdentifier===this.configuration.clientIdentifier)if("shared-worker-connected"===t.type)this.subscriptionWorkerReady=!0,this.flushScheduledEvents();else if("shared-worker-console-log"===t.type)console.log(`[SharedWorker] ${t.message}`);else if("shared-worker-console-dir"===t.type)t.message&&console.log(`[SharedWorker] ${t.message}`),console.dir(t.data,{depth:10});else if("shared-worker-ping"===t.type){const{logVerbosity:e,subscriptionKey:t,clientIdentifier:n}=this.configuration;this.scheduleEventPost({type:"client-pong",subscriptionKey:t,clientIdentifier:n,logVerbosity:e})}else if("request-progress-start"===t.type||"request-progress-end"===t.type)this.logRequestProgress(t);else if("request-process-success"===t.type||"request-process-error"===t.type){const{resolve:e,reject:n}=this.callbacks.get(t.identifier);if("request-process-success"===t.type)e({status:t.response.status,url:t.url,headers:t.response.headers,body:t.response.body});else{let e=h.PNUnknownCategory,s="Unknown error";if(t.error)"NETWORK_ISSUE"===t.error.type?e=h.PNNetworkIssuesCategory:"TIMEOUT"===t.error.type?e=h.PNTimeoutCategory:"ABORTED"===t.error.type&&(e=h.PNCancelledCategory),s=`${t.error.message} (${t.identifier})`;else if(t.response)return n(j.create({url:t.url,headers:t.response.headers,body:t.response.body,status:t.response.status},t.response.body));n(new j(s,e,0,new Error(s)))}}}logRequestProgress(e){var t,n;"request-progress-start"===e.type?(console.log("<<<<<"),console.log(`[${e.timestamp}] ${e.url}\n${JSON.stringify(null!==(t=e.query)&&void 0!==t?t:{})}`),console.log("-----")):(console.log(">>>>>>"),console.log(`[${e.timestamp} / ${e.duration}] ${e.url}\n${JSON.stringify(null!==(n=e.query)&&void 0!==n?n:{})}\n${e.response}`),console.log("-----"))}}function F(e){const t=e=>"object"==typeof e&&null!==e&&e.constructor===Object,n=e=>"number"==typeof e&&isFinite(e);if(!t(e))return e;const s={};return Object.keys(e).forEach((r=>{const i=(e=>"string"==typeof e||e instanceof String)(r);let a=r;const o=e[r];if(i&&r.indexOf(",")>=0){a=r.split(",").map(Number).reduce(((e,t)=>e+String.fromCharCode(t)),"")}else(n(r)||i&&!isNaN(Number(r)))&&(a=String.fromCharCode(n(r)?r:parseInt(r,10)));s[a]=t(o)?F(o):o})),s}const T=e=>{var t,n,s,r;return e.subscriptionWorkerUrl&&"undefined"==typeof SharedWorker&&(e.subscriptionWorkerUrl=null),Object.assign(Object.assign({},(e=>{var t,n,s,r,i,a,o,c,u,l,h,p,g,y,f;const m=Object.assign({},e);if(null!==(t=m.logVerbosity)&&void 0!==t||(m.logVerbosity=!1),null!==(n=m.ssl)&&void 0!==n||(m.ssl=!0),null!==(s=m.transactionalRequestTimeout)&&void 0!==s||(m.transactionalRequestTimeout=15),null!==(r=m.subscribeRequestTimeout)&&void 0!==r||(m.subscribeRequestTimeout=310),null!==(i=m.fileRequestTimeout)&&void 0!==i||(m.fileRequestTimeout=300),null!==(a=m.restore)&&void 0!==a||(m.restore=!1),null!==(o=m.useInstanceId)&&void 0!==o||(m.useInstanceId=!1),null!==(c=m.suppressLeaveEvents)&&void 0!==c||(m.suppressLeaveEvents=!1),null!==(u=m.requestMessageCountThreshold)&&void 0!==u||(m.requestMessageCountThreshold=100),null!==(l=m.autoNetworkDetection)&&void 0!==l||(m.autoNetworkDetection=!1),null!==(h=m.enableEventEngine)&&void 0!==h||(m.enableEventEngine=!1),null!==(p=m.maintainPresenceState)&&void 0!==p||(m.maintainPresenceState=!0),null!==(g=m.keepAlive)&&void 0!==g||(m.keepAlive=!1),m.userId&&m.uuid)throw new d("PubNub client configuration error: use only 'userId'");if(null!==(y=m.userId)&&void 0!==y||(m.userId=m.uuid),!m.userId)throw new d("PubNub client configuration error: 'userId' not set");if(0===(null===(f=m.userId)||void 0===f?void 0:f.trim().length))throw new d("PubNub client configuration error: 'userId' is empty");m.origin||(m.origin=Array.from({length:20},((e,t)=>`ps${t+1}.pndsn.com`)));const b={subscribeKey:m.subscribeKey,publishKey:m.publishKey,secretKey:m.secretKey};void 0!==m.presenceTimeout&&m.presenceTimeout<20&&(m.presenceTimeout=20,console.log("WARNING: Presence timeout is less than the minimum. Using minimum value: ",20)),void 0!==m.presenceTimeout?m.heartbeatInterval=m.presenceTimeout/2-1:m.presenceTimeout=300;let v=!1,w=!0,S=5,E=!1,O=100,k=!0;return void 0!==m.dedupeOnSubscribe&&"boolean"==typeof m.dedupeOnSubscribe&&(E=m.dedupeOnSubscribe),void 0!==m.maximumCacheSize&&"number"==typeof m.maximumCacheSize&&(O=m.maximumCacheSize),void 0!==m.useRequestId&&"boolean"==typeof m.useRequestId&&(k=m.useRequestId),void 0!==m.announceSuccessfulHeartbeats&&"boolean"==typeof m.announceSuccessfulHeartbeats&&(v=m.announceSuccessfulHeartbeats),void 0!==m.announceFailedHeartbeats&&"boolean"==typeof m.announceFailedHeartbeats&&(w=m.announceFailedHeartbeats),void 0!==m.fileUploadPublishRetryLimit&&"number"==typeof m.fileUploadPublishRetryLimit&&(S=m.fileUploadPublishRetryLimit),Object.assign(Object.assign({},m),{keySet:b,dedupeOnSubscribe:E,maximumCacheSize:O,useRequestId:k,announceSuccessfulHeartbeats:v,announceFailedHeartbeats:w,fileUploadPublishRetryLimit:S})})(e)),{listenToBrowserNetworkEvents:null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t,subscriptionWorkerUrl:e.subscriptionWorkerUrl,subscriptionWorkerLogVerbosity:null!==(n=e.subscriptionWorkerLogVerbosity)&&void 0!==n&&n,transport:null!==(s=e.transport)&&void 0!==s?s:"fetch",keepAlive:null===(r=e.keepAlive)||void 0===r||r})};var R={exports:{}}; -/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */!function(e,t){!function(e){var t="0.1.0",n={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};function s(){var e,t,n="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(n+="-"),n+=(12===e?4:16===e?3&t|8:t).toString(16);return n}function r(e,t){var s=n[t||"all"];return s&&s.test(e)||!1}s.isUUID=r,s.VERSION=t,e.uuid=s,e.isUUID=r}(t),null!==e&&(e.exports=t.uuid)}(R,R.exports);var U=t(R.exports),x={createUUID:()=>U.uuid?U.uuid():U()};const D=(e,t)=>{var n,s,r;null===(n=e.retryConfiguration)||void 0===n||n.validate(),null!==(s=e.useRandomIVs)&&void 0!==s||(e.useRandomIVs=true),e.origin=q(null!==(r=e.ssl)&&void 0!==r&&r,e.origin);const i=e.cryptoModule;i&&delete e.cryptoModule;const a=Object.assign(Object.assign({},e),{_pnsdkSuffix:{},_instanceId:`pn-${x.createUUID()}`,_cryptoModule:void 0,_cipherKey:void 0,_setupCryptoModule:t,get instanceId(){if(this.useInstanceId)return this._instanceId},getInstanceId(){if(this.useInstanceId)return this._instanceId},getUserId(){return this.userId},setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this.userId=e},getAuthKey(){return this.authKey},setAuthKey(e){this.authKey=e},getFilterExpression(){return this.filterExpression},setFilterExpression(e){this.filterExpression=e},getCipherKey(){return this._cipherKey},setCipherKey(t){this._cipherKey=t,t||!this._cryptoModule?t&&this._setupCryptoModule&&(this._cryptoModule=this._setupCryptoModule({cipherKey:t,useRandomIVs:e.useRandomIVs,customEncrypt:this.getCustomEncrypt(),customDecrypt:this.getCustomDecrypt()})):this._cryptoModule=void 0},getCryptoModule(){return this._cryptoModule},getUseRandomIVs:()=>e.useRandomIVs,setPresenceTimeout(e){this.heartbeatInterval=e/2-1,this.presenceTimeout=e},getPresenceTimeout(){return this.presenceTimeout},getHeartbeatInterval(){return this.heartbeatInterval},setHeartbeatInterval(e){this.heartbeatInterval=e},getTransactionTimeout(){return this.transactionalRequestTimeout},getSubscribeTimeout(){return this.subscribeRequestTimeout},getFileTimeout(){return this.fileRequestTimeout},get PubNubFile(){return e.PubNubFile},get version(){return"8.9.0"},getVersion(){return this.version},_addPnsdkSuffix(e,t){this._pnsdkSuffix[e]=`${t}`},_getPnsdkSuffix(e){const t=Object.values(this._pnsdkSuffix).join(e);return t.length>0?e+t:""},getUUID(){return this.getUserId()},setUUID(e){this.setUserId(e)},getCustomEncrypt:()=>e.customEncrypt,getCustomDecrypt:()=>e.customDecrypt});return e.cipherKey?a.setCipherKey(e.cipherKey):i&&(a._cryptoModule=i),a},q=(e,t)=>{const n=e?"https://":"http://";return"string"==typeof t?`${n}${t}`:`${n}${t[Math.floor(Math.random()*t.length)]}`};class G{constructor(e){this.cbor=e}setToken(e){e&&e.length>0?this.token=e:this.token=void 0}getToken(){return this.token}parseToken(e){const t=this.cbor.decodeToken(e);if(void 0!==t){const e=t.res.uuid?Object.keys(t.res.uuid):[],n=Object.keys(t.res.chan),s=Object.keys(t.res.grp),r=t.pat.uuid?Object.keys(t.pat.uuid):[],i=Object.keys(t.pat.chan),a=Object.keys(t.pat.grp),o={version:t.v,timestamp:t.t,ttl:t.ttl,authorized_uuid:t.uuid,signature:t.sig},c=e.length>0,u=n.length>0,l=s.length>0;if(c||u||l){if(o.resources={},c){const n=o.resources.uuids={};e.forEach((e=>n[e]=this.extractPermissions(t.res.uuid[e])))}if(u){const e=o.resources.channels={};n.forEach((n=>e[n]=this.extractPermissions(t.res.chan[n])))}if(l){const e=o.resources.groups={};s.forEach((n=>e[n]=this.extractPermissions(t.res.grp[n])))}}const h=r.length>0,d=i.length>0,p=a.length>0;if(h||d||p){if(o.patterns={},h){const e=o.patterns.uuids={};r.forEach((n=>e[n]=this.extractPermissions(t.pat.uuid[n])))}if(d){const e=o.patterns.channels={};i.forEach((n=>e[n]=this.extractPermissions(t.pat.chan[n])))}if(p){const e=o.patterns.groups={};a.forEach((n=>e[n]=this.extractPermissions(t.pat.grp[n])))}}return t.meta&&Object.keys(t.meta).length>0&&(o.meta=t.meta),o}}extractPermissions(e){const t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128&~e||(t.join=!0),64&~e||(t.update=!0),32&~e||(t.get=!0),8&~e||(t.delete=!0),4&~e||(t.manage=!0),2&~e||(t.write=!0),1&~e||(t.read=!0),t}}var K;!function(e){e.GET="GET",e.POST="POST",e.PATCH="PATCH",e.DELETE="DELETE",e.LOCAL="LOCAL"}(K||(K={}));const $=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),L=(e,t)=>{const n=e.map((e=>$(e)));return n.length?n.join(","):null!=t?t:""},B=(e,t)=>{const n=Object.fromEntries(t.map((e=>[e,!1])));return e.filter((e=>!(t.includes(e)&&!n[e])||(n[e]=!0,!1)))},H=(e,t)=>[...e].filter((n=>t.includes(n)&&e.indexOf(n)===e.lastIndexOf(n)&&t.indexOf(n)===t.lastIndexOf(n)));class V{constructor(e,t,n){this.publishKey=e,this.secretKey=t,this.hasher=n}signature(e){const t=e.path.startsWith("/publish")?K.GET:e.method;let n=`${t}\n${this.publishKey}\n${e.path}\n${this.queryParameters(e.queryParameters)}\n`;if(t===K.POST||t===K.PATCH){const t=e.body;let s;t&&t instanceof ArrayBuffer?s=V.textDecoder.decode(t):t&&"object"!=typeof t&&(s=t),s&&(n+=s)}return`v2.${this.hasher(n,this.secretKey)}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}queryParameters(e){return Object.keys(e).sort().map((t=>{const n=e[t];return Array.isArray(n)?n.sort().map((e=>`${t}=${$(e)}`)).join("&"):`${t}=${$(n)}`})).join("&")}}V.textDecoder=new TextDecoder("utf-8");class z{constructor(e){this.configuration=e;const{clientConfiguration:{keySet:t},shaHMAC:n}=e;t.secretKey&&n&&(this.signatureGenerator=new V(t.publishKey,t.secretKey,n))}makeSendable(e){return this.configuration.transport.makeSendable(this.request(e))}request(e){var t;const{clientConfiguration:n}=this.configuration;return(e=this.configuration.transport.request(e)).queryParameters||(e.queryParameters={}),n.useInstanceId&&(e.queryParameters.instanceid=n.getInstanceId()),e.queryParameters.uuid||(e.queryParameters.uuid=n.userId),n.useRequestId&&(e.queryParameters.requestid=e.identifier),e.queryParameters.pnsdk=this.generatePNSDK(),null!==(t=e.origin)&&void 0!==t||(e.origin=n.origin),this.authenticateRequest(e),this.signRequest(e),e}authenticateRequest(e){var t;if(e.path.startsWith("/v2/auth/")||e.path.startsWith("/v3/pam/")||e.path.startsWith("/time"))return;const{clientConfiguration:n,tokenManager:s}=this.configuration,r=null!==(t=s&&s.getToken())&&void 0!==t?t:n.authKey;r&&(e.queryParameters.auth=r)}signRequest(e){this.signatureGenerator&&!e.path.startsWith("/time")&&(e.queryParameters.timestamp=String(Math.floor((new Date).getTime()/1e3)),e.queryParameters.signature=this.signatureGenerator.signature(e))}generatePNSDK(){const{clientConfiguration:e}=this.configuration;if(e.sdkName)return e.sdkName;let t=`PubNub-JS-${e.sdkFamily}`;e.partnerId&&(t+=`-${e.partnerId}`),t+=`/${e.getVersion()}`;const n=e._getPnsdkSuffix(" ");return n.length>0&&(t+=n),t}}class W{constructor(e="fetch",t=!1,n=!1){if(this.transport=e,this.keepAlive=t,this.logVerbosity=n,"fetch"!==e||window&&window.fetch||(this.transport="xhr"),"fetch"===this.transport&&(W.originalFetch=fetch.bind(window),this.isFetchMonkeyPatched())){if(W.originalFetch=W.getOriginalFetch(),!n)return;console.warn("[PubNub] Native Web Fetch API 'fetch' function monkey patched."),this.isFetchMonkeyPatched(W.originalFetch)?console.warn("[PubNub] Unable receive native Web Fetch API. There can be issues with subscribe long-poll cancellation"):console.info("[PubNub] Use native Web Fetch API 'fetch' implementation from iframe as APM workaround.")}}makeSendable(e){const t=new AbortController,n={abortController:t,abort:e=>!t.signal.aborted&&t.abort(e)};return[this.webTransportRequestFromTransportRequest(e).then((t=>{const s=(new Date).getTime();return this.logRequestProcessProgress(t,e.body),this.sendRequest(t,n).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>{const n=e[1].byteLength>0?e[1]:void 0,{status:r,headers:i}=e[0],a={};i.forEach(((e,t)=>a[t]=e.toLowerCase()));const o={status:r,url:t.url,headers:a,body:n};if(r>=400)throw j.create(o);return this.logRequestProcessProgress(t,void 0,(new Date).getTime()-s,n),o})).catch((e=>{let t=e;if("string"==typeof e){const n=e.toLowerCase();n.includes("timeout")||!n.includes("cancel")?t=new Error(e):n.includes("cancel")&&(t=new DOMException("Aborted","AbortError"))}throw j.create(t)}))})),n]}request(e){return e}sendRequest(e,t){return i(this,void 0,void 0,(function*(){return"fetch"===this.transport?this.sendFetchRequest(e,t):this.sendXHRRequest(e,t)}))}sendFetchRequest(e,t){return i(this,void 0,void 0,(function*(){let n;const s=new Promise(((s,r)=>{n=setTimeout((()=>{clearTimeout(n),r(new Error("Request timeout")),t.abort("Cancel because of timeout")}),1e3*e.timeout)})),r=new Request(e.url,{method:e.method,headers:e.headers,redirect:"follow",body:e.body});return Promise.race([W.originalFetch(r,{signal:t.abortController.signal,credentials:"omit",cache:"no-cache"}).then((e=>(n&&clearTimeout(n),e))),s])}))}sendXHRRequest(e,t){return i(this,void 0,void 0,(function*(){return new Promise(((n,s)=>{var r;const i=new XMLHttpRequest;i.open(e.method,e.url,!0),i.responseType="arraybuffer",i.timeout=1e3*e.timeout,t.abortController.signal.onabort=()=>{i.readyState!=XMLHttpRequest.DONE&&i.readyState!=XMLHttpRequest.UNSENT&&i.abort()},Object.entries(null!==(r=e.headers)&&void 0!==r?r:{}).forEach((([e,t])=>i.setRequestHeader(e,t))),i.onabort=()=>s(new Error("Aborted")),i.ontimeout=()=>s(new Error("Request timeout")),i.onerror=()=>s(new Error("Request timeout")),i.onload=()=>{const e=new Headers;i.getAllResponseHeaders().split("\r\n").forEach((t=>{const[n,s]=t.split(": ");n.length>1&&s.length>1&&e.append(n,s)})),n(new Response(i.response,{status:i.status,headers:e,statusText:i.statusText}))},i.send(e.body)}))}))}webTransportRequestFromTransportRequest(e){return i(this,void 0,void 0,(function*(){let t,n=e.path;if(e.formData&&e.formData.length>0){e.queryParameters={};const n=e.body,s=new FormData;for(const{key:t,value:n}of e.formData)s.append(t,n);try{const e=yield n.toArrayBuffer();s.append("file",new Blob([e],{type:"application/octet-stream"}),n.name)}catch(e){try{const e=yield n.toFileUri();s.append("file",e,n.name)}catch(e){}}t=s}else e.body&&("string"==typeof e.body||e.body instanceof ArrayBuffer)&&(t=e.body);var s;return e.queryParameters&&0!==Object.keys(e.queryParameters).length&&(n=`${n}?${s=e.queryParameters,Object.keys(s).map((e=>{const t=s[e];return Array.isArray(t)?t.map((t=>`${e}=${$(t)}`)).join("&"):`${e}=${$(t)}`})).join("&")}`),{url:`${e.origin}${n}`,method:e.method,headers:e.headers,timeout:e.timeout,body:t}}))}logRequestProcessProgress(e,t,n,s){if(!this.logVerbosity)return;const{protocol:r,host:i,pathname:a,search:o}=new URL(e.url),c=(new Date).toISOString();if(n){let e=`[${c} / ${n}]\n${r}//${i}${a}\n${o}`;s&&(e+=`\n\n${W.decoder.decode(s)}`),console.log(">>>>>>"),console.log(e),console.log("-----")}else{let e=`[${c}]\n${r}//${i}${a}\n${o}`;t&&("string"==typeof t||t instanceof ArrayBuffer)&&(e+="string"==typeof t?`\n\n${t}`:`\n\n${W.decoder.decode(t)}`),console.log("<<<<<"),console.log(e),console.log("-----")}}isFetchMonkeyPatched(e){return!(null!=e?e:fetch).toString().includes("[native code]")&&"fetch"!==fetch.name}static getOriginalFetch(){let e=document.querySelector('iframe[name="pubnub-context-unpatched-fetch"]');return e||(e=document.createElement("iframe"),e.style.display="none",e.name="pubnub-context-unpatched-fetch",e.src="about:blank",document.body.appendChild(e)),e.contentWindow?e.contentWindow.fetch.bind(e.contentWindow):fetch}}W.decoder=new TextDecoder;class J{constructor(){this.listeners=[]}addListener(e){this.listeners.includes(e)||this.listeners.push(e)}removeListener(e){this.listeners=this.listeners.filter((t=>t!==e))}removeAllListeners(){this.listeners=[]}announceStatus(e){this.listeners.forEach((t=>{t.status&&t.status(e)}))}announcePresence(e){this.listeners.forEach((t=>{t.presence&&t.presence(e)}))}announceMessage(e){this.listeners.forEach((t=>{t.message&&t.message(e)}))}announceSignal(e){this.listeners.forEach((t=>{t.signal&&t.signal(e)}))}announceMessageAction(e){this.listeners.forEach((t=>{t.messageAction&&t.messageAction(e)}))}announceFile(e){this.listeners.forEach((t=>{t.file&&t.file(e)}))}announceObjects(e){this.listeners.forEach((t=>{t.objects&&t.objects(e)}))}announceNetworkUp(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkUpCategory})}))}announceNetworkDown(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkDownCategory})}))}announceUser(e){this.listeners.forEach((t=>{t.user&&t.user(e)}))}announceSpace(e){this.listeners.forEach((t=>{t.space&&t.space(e)}))}announceMembership(e){this.listeners.forEach((t=>{t.membership&&t.membership(e)}))}}class X{constructor(e){this.time=e}onReconnect(e){this.callback=e}startPolling(){this.timeTimer=setInterval((()=>this.callTime()),3e3)}stopPolling(){this.timeTimer&&clearInterval(this.timeTimer),this.timeTimer=null}callTime(){this.time((e=>{e.error||(this.stopPolling(),this.callback&&this.callback())}))}}class Q{constructor({maximumCacheSize:e}){this.maximumCacheSize=e,this.hashHistory=[]}getKey(e){var t;return`${e.timetoken}-${this.hashCode(JSON.stringify(null!==(t=e.message)&&void 0!==t?t:"")).toString()}`}isDuplicate(e){return this.hashHistory.includes(this.getKey(e))}addEntry(e){this.hashHistory.length>=this.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}clearHistory(){this.hashHistory=[]}hashCode(e){let t=0;if(0===e.length)return t;for(let n=0;n{this.pendingChannelSubscriptions.add(e),this.channels[e]={},r&&(this.presenceChannels[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannels[e]={})})),null==n||n.forEach((e=>{this.pendingChannelGroupSubscriptions.add(e),this.channelGroups[e]={},r&&(this.presenceChannelGroups[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannelGroups[e]={})})),this.subscriptionStatusAnnounced=!1,this.reconnect()}unsubscribe(e,t){let{channels:n,channelGroups:s}=e;const i=new Set,a=new Set;null==n||n.forEach((e=>{e in this.channels&&(delete this.channels[e],a.add(e),e in this.heartbeatChannels&&delete this.heartbeatChannels[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannels&&(delete this.presenceChannels[e],a.add(e))})),null==s||s.forEach((e=>{e in this.channelGroups&&(delete this.channelGroups[e],i.add(e),e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannelGroups&&(delete this.presenceChannelGroups[e],i.add(e))})),0===a.size&&0===i.size||(!1!==this.configuration.suppressLeaveEvents||t||(s=Array.from(i),n=Array.from(a),this.leaveCall({channels:n,channelGroups:s},(e=>{const{error:t}=e,i=r(e,["error"]);let a;t&&(e.errorData&&"object"==typeof e.errorData&&"message"in e.errorData&&"string"==typeof e.errorData.message?a=e.errorData.message:"message"in e&&"string"==typeof e.message&&(a=e.message)),this.listenerManager.announceStatus(Object.assign(Object.assign({},i),{error:null!=a&&a,affectedChannels:n,affectedChannelGroups:s,currentTimetoken:this.currentTimetoken,lastTimetoken:this.lastTimetoken}))}))),0===Object.keys(this.channels).length&&0===Object.keys(this.presenceChannels).length&&0===Object.keys(this.channelGroups).length&&0===Object.keys(this.presenceChannelGroups).length&&(this.lastTimetoken=0,this.currentTimetoken=0,this.storedTimetoken=null,this.region=null,this.reconnectionManager.stopPolling()),this.reconnect(!0))}unsubscribeAll(e){this.unsubscribe({channels:this.subscribedChannels,channelGroups:this.subscribedChannelGroups},e)}startSubscribeLoop(){this.stopSubscribeLoop();const e=[...Object.keys(this.channelGroups)],t=[...Object.keys(this.channels)];Object.keys(this.presenceChannelGroups).forEach((t=>e.push(`${t}-pnpres`))),Object.keys(this.presenceChannels).forEach((e=>t.push(`${e}-pnpres`))),0===t.length&&0===e.length||this.subscribeCall({channels:t,channelGroups:e,state:this.presenceState,heartbeat:this.configuration.getPresenceTimeout(),timetoken:this.currentTimetoken,region:null!==this.region?this.region:void 0,filterExpression:this.configuration.filterExpression},((e,t)=>{this.processSubscribeResponse(e,t)}))}stopSubscribeLoop(){this._subscribeAbort&&(this._subscribeAbort(),this._subscribeAbort=null)}processSubscribeResponse(e,t){if(e.error){if("object"==typeof e.errorData&&"name"in e.errorData&&"AbortError"===e.errorData.name||e.category===h.PNCancelledCategory)return;if(e.category===h.PNTimeoutCategory)this.startSubscribeLoop();else if(e.category===h.PNNetworkIssuesCategory)this.disconnect(),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.listenerManager.announceNetworkDown()),this.reconnectionManager.onReconnect((()=>{this.configuration.autoNetworkDetection&&!this.isOnline&&(this.isOnline=!0,this.listenerManager.announceNetworkUp()),this.reconnect(),this.subscriptionStatusAnnounced=!0;const t={category:h.PNReconnectedCategory,operation:e.operation,lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.listenerManager.announceStatus(t)})),this.reconnectionManager.startPolling(),this.listenerManager.announceStatus(e);else if(e.category===h.PNBadRequestCategory||e.category==h.PNMalformedResponseCategory){const t=this.isOnline?h.PNDisconnectedUnexpectedlyCategory:e.category;this.isOnline=!1,this.disconnect(),this.listenerManager.announceStatus(Object.assign(Object.assign({},e),{category:t}))}else this.listenerManager.announceStatus(e);return}if(this.storedTimetoken?(this.currentTimetoken=this.storedTimetoken,this.storedTimetoken=null):(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=t.cursor.timetoken),!this.subscriptionStatusAnnounced){const t={category:h.PNConnectedCategory,operation:e.operation,affectedChannels:Array.from(this.pendingChannelSubscriptions),subscribedChannels:this.subscribedChannels,affectedChannelGroups:Array.from(this.pendingChannelGroupSubscriptions),lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.subscriptionStatusAnnounced=!0,this.listenerManager.announceStatus(t),this.pendingChannelGroupSubscriptions.clear(),this.pendingChannelSubscriptions.clear()}const{messages:n}=t,{requestMessageCountThreshold:s,dedupeOnSubscribe:r}=this.configuration;s&&n.length>=s&&this.listenerManager.announceStatus({category:h.PNRequestMessageCountExceededCategory,operation:e.operation});try{n.forEach((e=>{if(r&&"message"in e.data&&"timetoken"in e.data){if(this.dedupingManager.isDuplicate(e.data))return;this.dedupingManager.addEntry(e.data)}this.eventEmitter.emitEvent(e)}))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}this.region=t.cursor.region,this.startSubscribeLoop()}setState(e){const{state:t,channels:n,channelGroups:s}=e;null==n||n.forEach((e=>e in this.channels&&(this.presenceState[e]=t))),null==s||s.forEach((e=>e in this.channelGroups&&(this.presenceState[e]=t)))}changePresence(e){const{connected:t,channels:n,channelGroups:s}=e;t?(null==n||n.forEach((e=>this.heartbeatChannels[e]={})),null==s||s.forEach((e=>this.heartbeatChannelGroups[e]={}))):(null==n||n.forEach((e=>{e in this.heartbeatChannels&&delete this.heartbeatChannels[e]})),null==s||s.forEach((e=>{e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]})),!1===this.configuration.suppressLeaveEvents&&this.leaveCall({channels:n,channelGroups:s},(e=>this.listenerManager.announceStatus(e)))),this.reconnect()}startHeartbeatTimer(){this.stopHeartbeatTimer();const e=this.configuration.getHeartbeatInterval();e&&0!==e&&(this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>this.sendHeartbeat()),1e3*e))}stopHeartbeatTimer(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}sendHeartbeat(){const e=Object.keys(this.heartbeatChannelGroups),t=Object.keys(this.heartbeatChannels);0===t.length&&0===e.length||this.heartbeatCall({channels:t,channelGroups:e,heartbeat:this.configuration.getPresenceTimeout(),state:this.presenceState},(e=>{e.error&&this.configuration.announceFailedHeartbeats&&this.listenerManager.announceStatus(e),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.disconnect(),this.listenerManager.announceNetworkDown(),this.reconnect()),!e.error&&this.configuration.announceSuccessfulHeartbeats&&this.listenerManager.announceStatus(e)}))}}class Z{constructor(e,t,n){this._payload=e,this.setDefaultPayloadStructure(),this.title=t,this.body=n}get payload(){return this._payload}set title(e){this._title=e}set subtitle(e){this._subtitle=e}set body(e){this._body=e}set badge(e){this._badge=e}set sound(e){this._sound=e}setDefaultPayloadStructure(){}toObject(){return{}}}class ee extends Z{constructor(){super(...arguments),this._apnsPushType="apns",this._isSilent=!1}get payload(){return this._payload}set configurations(e){e&&e.length&&(this._configurations=e)}get notification(){return this.payload.aps}get title(){return this._title}set title(e){e&&e.length&&(this.payload.aps.alert.title=e,this._title=e)}get subtitle(){return this._subtitle}set subtitle(e){e&&e.length&&(this.payload.aps.alert.subtitle=e,this._subtitle=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.aps.alert.body=e,this._body=e)}get badge(){return this._badge}set badge(e){null!=e&&(this.payload.aps.badge=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.aps.sound=e,this._sound=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.aps={alert:{}}}toObject(){const e=Object.assign({},this.payload),{aps:t}=e;let{alert:n}=t;if(this._isSilent&&(t["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");const t=[];this._configurations.forEach((e=>{t.push(this.objectFromAPNS2Configuration(e))})),t.length&&(e.pn_push=t)}return n&&Object.keys(n).length||delete t.alert,this._isSilent&&(delete t.alert,delete t.badge,delete t.sound,n={}),this._isSilent||n&&Object.keys(n).length?e:null}objectFromAPNS2Configuration(e){if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");const{collapseId:t,expirationDate:n}=e,s={auth_method:"token",targets:e.targets.map((e=>this.objectFromAPNSTarget(e))),version:"v2"};return t&&t.length&&(s.collapse_id=t),n&&(s.expiration=n.toISOString()),s}objectFromAPNSTarget(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");const{topic:t,environment:n="development",excludedDevices:s=[]}=e,r={topic:t,environment:n};return s.length&&(r.excluded_devices=s),r}}class te extends Z{get payload(){return this._payload}get notification(){return this.payload.notification}get data(){return this.payload.data}get title(){return this._title}set title(e){e&&e.length&&(this.payload.notification.title=e,this._title=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.notification.body=e,this._body=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.notification.sound=e,this._sound=e)}get icon(){return this._icon}set icon(e){e&&e.length&&(this.payload.notification.icon=e,this._icon=e)}get tag(){return this._tag}set tag(e){e&&e.length&&(this.payload.notification.tag=e,this._tag=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.notification={},this.payload.data={}}toObject(){let e=Object.assign({},this.payload.data),t=null;const n={};if(Object.keys(this.payload).length>2){const t=r(this.payload,["notification","data"]);e=Object.assign(Object.assign({},e),t)}return this._isSilent?e.notification=this.payload.notification:t=this.payload.notification,Object.keys(e).length&&(n.data=e),t&&Object.keys(t).length&&(n.notification=t),Object.keys(n).length?n:null}}class ne{constructor(e,t){this._payload={apns:{},fcm:{}},this._title=e,this._body=t,this.apns=new ee(this._payload.apns,e,t),this.fcm=new te(this._payload.fcm,e,t)}set debugging(e){this._debugging=e}get title(){return this._title}get subtitle(){return this._subtitle}set subtitle(e){this._subtitle=e,this.apns.subtitle=e,this.fcm.subtitle=e}get body(){return this._body}get badge(){return this._badge}set badge(e){this._badge=e,this.apns.badge=e,this.fcm.badge=e}get sound(){return this._sound}set sound(e){this._sound=e,this.apns.sound=e,this.fcm.sound=e}buildPayload(e){const t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";const n=this.apns.toObject();n&&Object.keys(n).length&&(t.pn_apns=n)}if(e.includes("fcm")){const e=this.fcm.toObject();e&&Object.keys(e).length&&(t.pn_gcm=e)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t}}class se{constructor(e){this.params=e,this.requestIdentifier=x.createUUID(),this._cancellationController=null}get cancellationController(){return this._cancellationController}set cancellationController(e){this._cancellationController=e}abort(e){this&&this.cancellationController&&this.cancellationController.abort(e)}operation(){throw Error("Should be implemented by subclass.")}validate(){}parse(e){return i(this,void 0,void 0,(function*(){return this.deserializeResponse(e)}))}request(){var e,t,n,s;const r={method:null!==(t=null===(e=this.params)||void 0===e?void 0:e.method)&&void 0!==t?t:K.GET,path:this.path,queryParameters:this.queryParameters,cancellable:null!==(s=null===(n=this.params)||void 0===n?void 0:n.cancellable)&&void 0!==s&&s,timeout:10,identifier:this.requestIdentifier},i=this.headers;if(i&&(r.headers=i),r.method===K.POST||r.method===K.PATCH){const[e,t]=[this.body,this.formData];t&&(r.formData=t),e&&(r.body=e)}return r}get headers(){}get path(){throw Error("`path` getter should be implemented by subclass.")}get queryParameters(){return{}}get formData(){}get body(){}deserializeResponse(e){const t=se.decoder.decode(e.body),n=e.headers["content-type"];let s;if(!n||-1===n.indexOf("javascript")&&-1===n.indexOf("json"))throw new d("Service response error, check status for details",y(t,e.status));try{s=JSON.parse(t)}catch(n){throw console.error("Error parsing JSON response:",n),new d("Service response error, check status for details",y(t,e.status))}if("status"in s&&"number"==typeof s.status&&s.status>=400)throw j.create(e);return s}}var re;se.decoder=new TextDecoder,function(e){e.PNPublishOperation="PNPublishOperation",e.PNSignalOperation="PNSignalOperation",e.PNSubscribeOperation="PNSubscribeOperation",e.PNUnsubscribeOperation="PNUnsubscribeOperation",e.PNWhereNowOperation="PNWhereNowOperation",e.PNHereNowOperation="PNHereNowOperation",e.PNGlobalHereNowOperation="PNGlobalHereNowOperation",e.PNSetStateOperation="PNSetStateOperation",e.PNGetStateOperation="PNGetStateOperation",e.PNHeartbeatOperation="PNHeartbeatOperation",e.PNAddMessageActionOperation="PNAddActionOperation",e.PNRemoveMessageActionOperation="PNRemoveMessageActionOperation",e.PNGetMessageActionsOperation="PNGetMessageActionsOperation",e.PNTimeOperation="PNTimeOperation",e.PNHistoryOperation="PNHistoryOperation",e.PNDeleteMessagesOperation="PNDeleteMessagesOperation",e.PNFetchMessagesOperation="PNFetchMessagesOperation",e.PNMessageCounts="PNMessageCountsOperation",e.PNGetAllUUIDMetadataOperation="PNGetAllUUIDMetadataOperation",e.PNGetUUIDMetadataOperation="PNGetUUIDMetadataOperation",e.PNSetUUIDMetadataOperation="PNSetUUIDMetadataOperation",e.PNRemoveUUIDMetadataOperation="PNRemoveUUIDMetadataOperation",e.PNGetAllChannelMetadataOperation="PNGetAllChannelMetadataOperation",e.PNGetChannelMetadataOperation="PNGetChannelMetadataOperation",e.PNSetChannelMetadataOperation="PNSetChannelMetadataOperation",e.PNRemoveChannelMetadataOperation="PNRemoveChannelMetadataOperation",e.PNGetMembersOperation="PNGetMembersOperation",e.PNSetMembersOperation="PNSetMembersOperation",e.PNGetMembershipsOperation="PNGetMembershipsOperation",e.PNSetMembershipsOperation="PNSetMembershipsOperation",e.PNListFilesOperation="PNListFilesOperation",e.PNGenerateUploadUrlOperation="PNGenerateUploadUrlOperation",e.PNPublishFileOperation="PNPublishFileOperation",e.PNPublishFileMessageOperation="PNPublishFileMessageOperation",e.PNGetFileUrlOperation="PNGetFileUrlOperation",e.PNDownloadFileOperation="PNDownloadFileOperation",e.PNDeleteFileOperation="PNDeleteFileOperation",e.PNAddPushNotificationEnabledChannelsOperation="PNAddPushNotificationEnabledChannelsOperation",e.PNRemovePushNotificationEnabledChannelsOperation="PNRemovePushNotificationEnabledChannelsOperation",e.PNPushNotificationEnabledChannelsOperation="PNPushNotificationEnabledChannelsOperation",e.PNRemoveAllPushNotificationsOperation="PNRemoveAllPushNotificationsOperation",e.PNChannelGroupsOperation="PNChannelGroupsOperation",e.PNRemoveGroupOperation="PNRemoveGroupOperation",e.PNChannelsForGroupOperation="PNChannelsForGroupOperation",e.PNAddChannelsToGroupOperation="PNAddChannelsToGroupOperation",e.PNRemoveChannelsFromGroupOperation="PNRemoveChannelsFromGroupOperation",e.PNAccessManagerGrant="PNAccessManagerGrant",e.PNAccessManagerGrantToken="PNAccessManagerGrantToken",e.PNAccessManagerAudit="PNAccessManagerAudit",e.PNAccessManagerRevokeToken="PNAccessManagerRevokeToken",e.PNHandshakeOperation="PNHandshakeOperation",e.PNReceiveMessagesOperation="PNReceiveMessagesOperation"}(re||(re={}));var ie=re;var ae;!function(e){e[e.Presence=-2]="Presence",e[e.Message=-1]="Message",e[e.Signal=1]="Signal",e[e.AppContext=2]="AppContext",e[e.MessageAction=3]="MessageAction",e[e.Files=4]="Files"}(ae||(ae={}));class oe extends se{constructor(e){var t,n,s,r,i,a;super({cancellable:!0}),this.parameters=e,null!==(t=(r=this.parameters).withPresence)&&void 0!==t||(r.withPresence=false),null!==(n=(i=this.parameters).channelGroups)&&void 0!==n||(i.channelGroups=[]),null!==(s=(a=this.parameters).channels)&&void 0!==s||(a.channels=[])}operation(){return ie.PNSubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:n}=this.parameters;return e?t||n?void 0:"`channels` and `channelGroups` both should not be empty":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){let t,n;try{n=se.decoder.decode(e.body);t=JSON.parse(n)}catch(e){console.error("Error parsing JSON response:",e)}if(!t)throw new d("Service response error, check status for details",y(n,e.status));const s=t.m.filter((e=>{const t=void 0===e.b?e.c:e.b;return this.parameters.channels&&this.parameters.channels.includes(t)||this.parameters.channelGroups&&this.parameters.channelGroups.includes(t)})).map((e=>{let{e:t}=e;return null!=t||(t=e.c.endsWith("-pnpres")?ae.Presence:ae.Message),t!=ae.Signal&&"string"==typeof e.d?t==ae.Message?{type:ae.Message,data:this.messageFromEnvelope(e)}:{type:ae.Files,data:this.fileFromEnvelope(e)}:t==ae.Message?{type:ae.Message,data:this.messageFromEnvelope(e)}:t===ae.Presence?{type:ae.Presence,data:this.presenceEventFromEnvelope(e)}:t==ae.Signal?{type:ae.Signal,data:this.signalFromEnvelope(e)}:t===ae.AppContext?{type:ae.AppContext,data:this.appContextFromEnvelope(e)}:t===ae.MessageAction?{type:ae.MessageAction,data:this.messageActionFromEnvelope(e)}:{type:ae.Files,data:this.fileFromEnvelope(e)}}));return{cursor:{timetoken:t.t.t,region:t.t.r},messages:s}}))}get headers(){return{accept:"text/javascript"}}presenceEventFromEnvelope(e){var t;const{d:n}=e,[s,r]=this.subscriptionChannelFromEnvelope(e),i=s.replace("-pnpres",""),a=null!==r?i:null,o=null!==r?r:i;return"string"!=typeof n&&("data"in n?(n.state=n.data,delete n.data):"action"in n&&"interval"===n.action&&(n.hereNowRefresh=null!==(t=n.here_now_refresh)&&void 0!==t&&t,delete n.here_now_refresh)),Object.assign({channel:i,subscription:r,actualChannel:a,subscribedChannel:o,timetoken:e.p.t},n)}messageFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),[s,r]=this.decryptedData(e.d),i={channel:t,subscription:n,actualChannel:null!==n?t:null,subscribedChannel:null!==n?n:t,timetoken:e.p.t,publisher:e.i,message:s};return e.u&&(i.userMetadata=e.u),e.cmt&&(i.customMessageType=e.cmt),r&&(i.error=r),i}signalFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),s={channel:t,subscription:n,timetoken:e.p.t,publisher:e.i,message:e.d};return e.u&&(s.userMetadata=e.u),e.cmt&&(s.customMessageType=e.cmt),s}messageActionFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),s=e.d;return{channel:t,subscription:n,timetoken:e.p.t,publisher:e.i,event:s.event,data:Object.assign(Object.assign({},s.data),{uuid:e.i})}}appContextFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),s=e.d;return{channel:t,subscription:n,timetoken:e.p.t,message:s}}fileFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),[s,r]=this.decryptedData(e.d);let i=r;const a={channel:t,subscription:n,timetoken:e.p.t,publisher:e.i};return e.u&&(a.userMetadata=e.u),s?"string"==typeof s?null!=i||(i="Unexpected file information payload data type."):(a.message=s.message,s.file&&(a.file={id:s.file.id,name:s.file.name,url:this.parameters.getFileUrl({id:s.file.id,name:s.file.name,channel:t})})):null!=i||(i="File information payload is missing."),e.cmt&&(a.customMessageType=e.cmt),i&&(a.error=i),a}subscriptionChannelFromEnvelope(e){return[e.c,void 0===e.b?e.c:e.b]}decryptedData(e){if(!this.parameters.crypto||"string"!=typeof e)return[e,void 0];let t,n;try{const n=this.parameters.crypto.decrypt(e);t=n instanceof ArrayBuffer?JSON.parse(ce.decoder.decode(n)):n}catch(e){t=null,n=`Error while decrypting message content: ${e.message}`}return[null!=t?t:e,n]}}class ce extends oe{get path(){var e;const{keySet:{subscribeKey:t},channels:n}=this.parameters;return`/v2/subscribe/${t}/${L(null!==(e=null==n?void 0:n.sort())&&void 0!==e?e:[],",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,heartbeat:n,state:s,timetoken:r,region:i}=this.parameters,a={};return e&&e.length>0&&(a["channel-group"]=e.sort().join(",")),t&&t.length>0&&(a["filter-expr"]=t),n&&(a.heartbeat=n),s&&Object.keys(s).length>0&&(a.state=JSON.stringify(s)),void 0!==r&&"string"==typeof r?r.length>0&&"0"!==r&&(a.tt=r):void 0!==r&&r>0&&(a.tt=r),i&&(a.tr=i),a}}class ue{constructor(e){this.listenerManager=e,this.channelListenerMap=new Map,this.groupListenerMap=new Map}emitEvent(e){var t;if(e.type===ae.Message)this.listenerManager.announceMessage(e.data),this.announce("message",e.data,e.data.channel,e.data.subscription);else if(e.type===ae.Signal)this.listenerManager.announceSignal(e.data),this.announce("signal",e.data,e.data.channel,e.data.subscription);else if(e.type===ae.Presence)this.listenerManager.announcePresence(e.data),this.announce("presence",e.data,null!==(t=e.data.subscription)&&void 0!==t?t:e.data.channel,e.data.subscription);else if(e.type===ae.AppContext){const{data:t}=e,{message:n}=t;if(this.listenerManager.announceObjects(t),this.announce("objects",t,t.channel,t.subscription),"uuid"===n.type){const{message:e,channel:s}=t,i=r(t,["message","channel"]),{event:a,type:o}=n,c=r(n,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:s,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",type:"user"})});this.listenerManager.announceUser(u),this.announce("user",u,u.spaceId,u.subscription)}else if("channel"===n.type){const{message:e,channel:s}=t,i=r(t,["message","channel"]),{event:a,type:o}=n,c=r(n,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:s,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",type:"space"})});this.listenerManager.announceSpace(u),this.announce("space",u,u.spaceId,u.subscription)}else if("membership"===n.type){const{message:e,channel:s}=t,i=r(t,["message","channel"]),{event:a,data:o}=n,c=r(n,["event","data"]),{uuid:u,channel:l}=o,h=r(o,["uuid","channel"]),d=Object.assign(Object.assign({},i),{spaceId:s,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",data:Object.assign(Object.assign({},h),{user:u,space:l})})});this.listenerManager.announceMembership(d),this.announce("membership",d,d.spaceId,d.subscription)}}else e.type===ae.MessageAction?(this.listenerManager.announceMessageAction(e.data),this.announce("messageAction",e.data,e.data.channel,e.data.subscription)):e.type===ae.Files&&(this.listenerManager.announceFile(e.data),this.announce("file",e.data,e.data.channel,e.data.subscription))}addListener(e,t,n){t&&n?(null==t||t.forEach((t=>{if(this.channelListenerMap.has(t)){const n=this.channelListenerMap.get(t);n.includes(e)||n.push(e)}else this.channelListenerMap.set(t,[e])})),null==n||n.forEach((t=>{if(this.groupListenerMap.has(t)){const n=this.groupListenerMap.get(t);n.includes(e)||n.push(e)}else this.groupListenerMap.set(t,[e])}))):this.listenerManager.addListener(e)}removeListener(e,t,n){t&&n?(null==t||t.forEach((t=>{this.channelListenerMap.has(t)&&this.channelListenerMap.set(t,this.channelListenerMap.get(t).filter((t=>t!==e)))})),null==n||n.forEach((t=>{this.groupListenerMap.has(t)&&this.groupListenerMap.set(t,this.groupListenerMap.get(t).filter((t=>t!==e)))}))):this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners(),this.channelListenerMap.clear(),this.groupListenerMap.clear()}announce(e,t,n,s){t&&this.channelListenerMap.has(n)&&this.channelListenerMap.get(n).forEach((n=>{const s=n[e];s&&s(t)})),s&&this.groupListenerMap.has(s)&&this.groupListenerMap.get(s).forEach((n=>{const s=n[e];s&&s(t)}))}}class le{constructor(e=!1){this.sync=e,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){const t=()=>{this.listeners.forEach((t=>{t(e)}))};this.sync?t():setTimeout(t,0)}}class he{transition(e,t){var n;if(this.transitionMap.has(t.type))return null===(n=this.transitionMap.get(t.type))||void 0===n?void 0:n(e,t)}constructor(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}on(e,t){return this.transitionMap.set(e,t),this}with(e,t){return[this,e,null!=t?t:[]]}onEnter(e){return this.enterEffects.push(e),this}onExit(e){return this.exitEffects.push(e),this}}class de extends le{describe(e){return new he(e)}start(e,t){this.currentState=e,this.currentContext=t,this.notify({type:"engineStarted",state:e,context:t})}transition(e){if(!this.currentState)throw new Error("Start the engine first");this.notify({type:"eventReceived",event:e});const t=this.currentState.transition(this.currentContext,e);if(t){const[n,s,r]=t;for(const e of this.currentState.exitEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)});const i=this.currentState;this.currentState=n;const a=this.currentContext;this.currentContext=s,this.notify({type:"transitionDone",fromState:i,fromContext:a,toState:n,toContext:s,event:e});for(const e of r)this.notify({type:"invocationDispatched",invocation:e});for(const e of this.currentState.enterEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)})}}}class pe{constructor(e){this.dependencies=e,this.instances=new Map,this.handlers=new Map}on(e,t){this.handlers.set(e,t)}dispatch(e){if("CANCEL"===e.type){if(this.instances.has(e.payload)){const t=this.instances.get(e.payload);null==t||t.cancel(),this.instances.delete(e.payload)}return}const t=this.handlers.get(e.type);if(!t)throw new Error(`Unhandled invocation '${e.type}'`);const n=t(e.payload,this.dependencies);e.managed&&this.instances.set(e.type,n),n.start()}dispose(){for(const[e,t]of this.instances.entries())t.cancel(),this.instances.delete(e)}}function ge(e,t){const n=function(...n){return{type:e,payload:null==t?void 0:t(...n)}};return n.type=e,n}function ye(e,t){const n=(...n)=>({type:e,payload:t(...n),managed:!1});return n.type=e,n}function fe(e,t){const n=(...n)=>({type:e,payload:t(...n),managed:!0});return n.type=e,n.cancel={type:"CANCEL",payload:e,managed:!1},n}class me extends Error{constructor(){super("The operation was aborted."),this.name="AbortError",Object.setPrototypeOf(this,new.target.prototype)}}class be extends le{constructor(){super(...arguments),this._aborted=!1}get aborted(){return this._aborted}throwIfAborted(){if(this._aborted)throw new me}abort(){this._aborted=!0,this.notify(new me)}}class ve{constructor(e,t){this.payload=e,this.dependencies=t}}class we extends ve{constructor(e,t,n){super(e,t),this.asyncFunction=n,this.abortSignal=new be}start(){this.asyncFunction(this.payload,this.abortSignal,this.dependencies).catch((e=>{}))}cancel(){this.abortSignal.abort()}}const Se=e=>(t,n)=>new we(t,n,e),Ee=ge("RECONNECT",(()=>({}))),Oe=ge("DISCONNECT",(()=>({}))),ke=ge("JOINED",((e,t)=>({channels:e,groups:t}))),Ce=ge("LEFT",((e,t)=>({channels:e,groups:t}))),Ne=ge("LEFT_ALL",(()=>({}))),Pe=ge("HEARTBEAT_SUCCESS",(e=>({statusCode:e}))),Me=ge("HEARTBEAT_FAILURE",(e=>e)),_e=ge("HEARTBEAT_GIVEUP",(()=>({}))),Ae=ge("TIMES_UP",(()=>({}))),je=ye("HEARTBEAT",((e,t)=>({channels:e,groups:t}))),Ie=ye("LEAVE",((e,t)=>({channels:e,groups:t}))),Fe=ye("EMIT_STATUS",(e=>e)),Te=fe("WAIT",(()=>({}))),Re=fe("DELAYED_HEARTBEAT",(e=>e));class Ue extends pe{constructor(e,t){super(t),this.on(je.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{heartbeat:s,presenceState:r,config:i}){try{yield s(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},i.maintainPresenceState&&{state:r}),{heartbeat:i.presenceTimeout}));e.transition(Pe(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Me(t))}}}))))),this.on(Ie.type,Se(((e,t,n)=>i(this,[e,t,n],void 0,(function*(e,t,{leave:n,config:s}){if(!s.suppressLeaveEvents)try{n({channels:e.channels,channelGroups:e.groups})}catch(e){}}))))),this.on(Te.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{heartbeatDelay:s}){return n.throwIfAborted(),yield s(),n.throwIfAborted(),e.transition(Ae())}))))),this.on(Re.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{heartbeat:s,retryDelay:r,presenceState:i,config:a}){if(!a.retryConfiguration||!a.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(_e());n.throwIfAborted(),yield r(a.retryConfiguration.getDelay(t.attempts,t.reason)),n.throwIfAborted();try{yield s(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},a.maintainPresenceState&&{state:i}),{heartbeat:a.presenceTimeout}));return e.transition(Pe(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Me(t))}}}))))),this.on(Fe.type,Se(((e,t,n)=>i(this,[e,t,n],void 0,(function*(e,t,{emitStatus:n,config:s}){var r;s.announceFailedHeartbeats&&!0===(null===(r=null==e?void 0:e.status)||void 0===r?void 0:r.error)?n(e.status):s.announceSuccessfulHeartbeats&&200===e.statusCode&&n(Object.assign(Object.assign({},e),{operation:ie.PNHeartbeatOperation,error:!1}))})))))}}const xe=new he("HEARTBEAT_STOPPED");xe.on(ke.type,((e,t)=>xe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),xe.on(Ce.type,((e,t)=>xe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))}))),xe.on(Ee.type,((e,t)=>Ke.with({channels:e.channels,groups:e.groups}))),xe.on(Ne.type,((e,t)=>$e.with(void 0)));const De=new he("HEARTBEAT_COOLDOWN");De.onEnter((()=>Te())),De.onExit((()=>Te.cancel)),De.on(Ae.type,((e,t)=>Ke.with({channels:e.channels,groups:e.groups}))),De.on(ke.type,((e,t)=>Ke.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),De.on(Ce.type,((e,t)=>Ke.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ie(t.payload.channels,t.payload.groups)]))),De.on(Oe.type,(e=>xe.with({channels:e.channels,groups:e.groups},[Ie(e.channels,e.groups)]))),De.on(Ne.type,((e,t)=>$e.with(void 0,[Ie(e.channels,e.groups)])));const qe=new he("HEARTBEAT_FAILED");qe.on(ke.type,((e,t)=>Ke.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),qe.on(Ce.type,((e,t)=>Ke.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ie(t.payload.channels,t.payload.groups)]))),qe.on(Ee.type,((e,t)=>Ke.with({channels:e.channels,groups:e.groups}))),qe.on(Oe.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups},[Ie(e.channels,e.groups)]))),qe.on(Ne.type,((e,t)=>$e.with(void 0,[Ie(e.channels,e.groups)])));const Ge=new he("HEARBEAT_RECONNECTING");Ge.onEnter((e=>Re(e))),Ge.onExit((()=>Re.cancel)),Ge.on(ke.type,((e,t)=>Ke.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Ge.on(Ce.type,((e,t)=>Ke.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ie(t.payload.channels,t.payload.groups)]))),Ge.on(Oe.type,((e,t)=>{xe.with({channels:e.channels,groups:e.groups},[Ie(e.channels,e.groups)])})),Ge.on(Pe.type,((e,t)=>De.with({channels:e.channels,groups:e.groups}))),Ge.on(Me.type,((e,t)=>Ge.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),Ge.on(_e.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),Ge.on(Ne.type,((e,t)=>$e.with(void 0,[Ie(e.channels,e.groups)])));const Ke=new he("HEARTBEATING");Ke.onEnter((e=>je(e.channels,e.groups))),Ke.on(Pe.type,((e,t)=>De.with({channels:e.channels,groups:e.groups}))),Ke.on(ke.type,((e,t)=>Ke.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Ke.on(Ce.type,((e,t)=>Ke.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ie(t.payload.channels,t.payload.groups)]))),Ke.on(Me.type,((e,t)=>Ge.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),Ke.on(Oe.type,(e=>xe.with({channels:e.channels,groups:e.groups},[Ie(e.channels,e.groups)]))),Ke.on(Ne.type,((e,t)=>$e.with(void 0,[Ie(e.channels,e.groups)])));const $e=new he("HEARTBEAT_INACTIVE");$e.on(ke.type,((e,t)=>Ke.with({channels:t.payload.channels,groups:t.payload.groups})));class Le{get _engine(){return this.engine}constructor(e){this.dependencies=e,this.engine=new de,this.channels=[],this.groups=[],this.dispatcher=new Ue(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start($e,void 0)}join({channels:e,groups:t}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],this.engine.transition(ke(this.channels.slice(0),this.groups.slice(0)))}leave({channels:e,groups:t}){this.dependencies.presenceState&&(null==e||e.forEach((e=>delete this.dependencies.presenceState[e])),null==t||t.forEach((e=>delete this.dependencies.presenceState[e]))),this.engine.transition(Ce(null!=e?e:[],null!=t?t:[]))}leaveAll(){this.engine.transition(Ne())}dispose(){this._unsubscribeEngine(),this.dispatcher.dispose()}}class Be{static LinearRetryPolicy(e){return{delay:e.delay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var n;return 403!==(null===(n=null==e?void 0:e.status)||void 0===n?void 0:n.statusCode)&&this.maximumRetry>t},getDelay(e,t){var n;return 1e3*((null!==(n=t.retryAfter)&&void 0!==n?n:this.delay)+Math.random())},getGiveupReason(e,t){var n;return this.maximumRetry<=t?"retry attempts exhaused.":403===(null===(n=null==e?void 0:e.status)||void 0===n?void 0:n.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.maximumRetry>10)throw new Error("Maximum retry for linear retry policy can not be more than 10")}}}static ExponentialRetryPolicy(e){return{minimumDelay:e.minimumDelay,maximumDelay:e.maximumDelay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var n;return 403!==(null===(n=null==e?void 0:e.status)||void 0===n?void 0:n.statusCode)&&this.maximumRetry>t},getDelay(e,t){var n;return 1e3*((null!==(n=t.retryAfter)&&void 0!==n?n:Math.min(Math.pow(2,e),this.maximumDelay))+Math.random())},getGiveupReason(e,t){var n;return this.maximumRetry<=t?"retry attempts exhausted.":403===(null===(n=null==e?void 0:e.status)||void 0===n?void 0:n.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.minimumDelay<2)throw new Error("Minimum delay can not be set less than 2 seconds for retry");if(this.maximumDelay)throw new Error("Maximum delay can not be set more than 150 seconds for retry");if(this.maximumRetry>6)throw new Error("Maximum retry for exponential retry policy can not be more than 6")}}}}const He=fe("HANDSHAKE",((e,t)=>({channels:e,groups:t}))),Ve=fe("RECEIVE_MESSAGES",((e,t,n)=>({channels:e,groups:t,cursor:n}))),ze=ye("EMIT_MESSAGES",(e=>e)),We=ye("EMIT_STATUS",(e=>e)),Je=fe("RECEIVE_RECONNECT",(e=>e)),Xe=fe("HANDSHAKE_RECONNECT",(e=>e)),Qe=ge("SUBSCRIPTION_CHANGED",((e,t)=>({channels:e,groups:t}))),Ye=ge("SUBSCRIPTION_RESTORED",((e,t,n,s)=>({channels:e,groups:t,cursor:{timetoken:n,region:null!=s?s:0}}))),Ze=ge("HANDSHAKE_SUCCESS",(e=>e)),et=ge("HANDSHAKE_FAILURE",(e=>e)),tt=ge("HANDSHAKE_RECONNECT_SUCCESS",(e=>({cursor:e}))),nt=ge("HANDSHAKE_RECONNECT_FAILURE",(e=>e)),st=ge("HANDSHAKE_RECONNECT_GIVEUP",(e=>e)),rt=ge("RECEIVE_SUCCESS",((e,t)=>({cursor:e,events:t}))),it=ge("RECEIVE_FAILURE",(e=>e)),at=ge("RECEIVE_RECONNECT_SUCCESS",((e,t)=>({cursor:e,events:t}))),ot=ge("RECEIVE_RECONNECT_FAILURE",(e=>e)),ct=ge("RECEIVING_RECONNECT_GIVEUP",(e=>e)),ut=ge("DISCONNECT",(()=>({}))),lt=ge("RECONNECT",((e,t)=>({cursor:{timetoken:null!=e?e:"",region:null!=t?t:0}}))),ht=ge("UNSUBSCRIBE_ALL",(()=>({})));class dt extends pe{constructor(e,t){super(t),this.on(He.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{handshake:s,presenceState:r,config:i}){n.throwIfAborted();try{const a=yield s(Object.assign({abortSignal:n,channels:t.channels,channelGroups:t.groups,filterExpression:i.filterExpression},i.maintainPresenceState&&{state:r}));return e.transition(Ze(a))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(et(t))}}}))))),this.on(Ve.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{receiveMessages:s,config:r}){n.throwIfAborted();try{const i=yield s({abortSignal:n,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:r.filterExpression});e.transition(rt(i.cursor,i.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;if(!n.aborted)return e.transition(it(t))}}}))))),this.on(ze.type,Se(((e,t,n)=>i(this,[e,t,n],void 0,(function*(e,t,{emitMessages:n}){e.length>0&&n(e)}))))),this.on(We.type,Se(((e,t,n)=>i(this,[e,t,n],void 0,(function*(e,t,{emitStatus:n}){n(e)}))))),this.on(Je.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{receiveMessages:s,delay:r,config:i}){if(!i.retryConfiguration||!i.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(ct(new d(i.retryConfiguration?i.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe messages receive.")));n.throwIfAborted(),yield r(i.retryConfiguration.getDelay(t.attempts,t.reason)),n.throwIfAborted();try{const r=yield s({abortSignal:n,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:i.filterExpression});return e.transition(at(r.cursor,r.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(ot(t))}}}))))),this.on(Xe.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{handshake:s,delay:r,presenceState:i,config:a}){if(!a.retryConfiguration||!a.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(st(new d(a.retryConfiguration?a.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe handshake")));n.throwIfAborted(),yield r(a.retryConfiguration.getDelay(t.attempts,t.reason)),n.throwIfAborted();try{const r=yield s(Object.assign({abortSignal:n,channels:t.channels,channelGroups:t.groups,filterExpression:a.filterExpression},a.maintainPresenceState&&{state:i}));return e.transition(tt(r))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(nt(t))}}})))))}}const pt=new he("HANDSHAKE_FAILED");pt.on(Qe.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),pt.on(lt.type,((e,t)=>wt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor||e.cursor}))),pt.on(Ye.type,((e,t)=>{var n,s;return wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region?t.payload.cursor.region:null!==(s=null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)&&void 0!==s?s:0}})})),pt.on(ht.type,(e=>St.with()));const gt=new he("HANDSHAKE_STOPPED");gt.on(Qe.type,((e,t)=>gt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),gt.on(lt.type,((e,t)=>wt.with(Object.assign(Object.assign({},e),{cursor:t.payload.cursor||e.cursor})))),gt.on(Ye.type,((e,t)=>{var n;return gt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)||0}})})),gt.on(ht.type,(e=>St.with()));const yt=new he("RECEIVE_FAILED");yt.on(lt.type,((e,t)=>{var n;return wt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(n=t.payload.cursor)||void 0===n?void 0:n.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),yt.on(Qe.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),yt.on(Ye.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),yt.on(ht.type,(e=>St.with(void 0)));const ft=new he("RECEIVE_STOPPED");ft.on(Qe.type,((e,t)=>ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),ft.on(Ye.type,((e,t)=>ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),ft.on(lt.type,((e,t)=>{var n;return wt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(n=t.payload.cursor)||void 0===n?void 0:n.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),ft.on(ht.type,(()=>St.with(void 0)));const mt=new he("RECEIVE_RECONNECTING");mt.onEnter((e=>Je(e))),mt.onExit((()=>Je.cancel)),mt.on(at.type,((e,t)=>bt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),mt.on(ot.type,((e,t)=>mt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),mt.on(ct.type,((e,t)=>{var n;return yt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[We({category:h.PNDisconnectedUnexpectedlyCategory,error:null===(n=t.payload)||void 0===n?void 0:n.message})])})),mt.on(ut.type,(e=>ft.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[We({category:h.PNDisconnectedCategory})]))),mt.on(Ye.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),mt.on(Qe.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),mt.on(ht.type,(e=>St.with(void 0,[We({category:h.PNDisconnectedCategory})])));const bt=new he("RECEIVING");bt.onEnter((e=>Ve(e.channels,e.groups,e.cursor))),bt.onExit((()=>Ve.cancel)),bt.on(rt.type,((e,t)=>bt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),bt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?St.with(void 0):bt.with({cursor:e.cursor,channels:t.payload.channels,groups:t.payload.groups}))),bt.on(Ye.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?St.with(void 0):bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),bt.on(it.type,((e,t)=>mt.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),bt.on(ut.type,(e=>ft.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[We({category:h.PNDisconnectedCategory})]))),bt.on(ht.type,(e=>St.with(void 0,[We({category:h.PNDisconnectedCategory})])));const vt=new he("HANDSHAKE_RECONNECTING");vt.onEnter((e=>Xe(e))),vt.onExit((()=>Xe.cancel)),vt.on(tt.type,((e,t)=>{var n,s;const r={timetoken:(null===(n=e.cursor)||void 0===n?void 0:n.timetoken)?null===(s=e.cursor)||void 0===s?void 0:s.timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region};return bt.with({channels:e.channels,groups:e.groups,cursor:r},[We({category:h.PNConnectedCategory})])})),vt.on(nt.type,((e,t)=>vt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),vt.on(st.type,((e,t)=>{var n;return pt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[We({category:h.PNConnectionErrorCategory,error:null===(n=t.payload)||void 0===n?void 0:n.message})])})),vt.on(ut.type,(e=>gt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),vt.on(Qe.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),vt.on(Ye.type,((e,t)=>{var n,s;return wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:(null===(n=t.payload.cursor)||void 0===n?void 0:n.region)||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),vt.on(ht.type,(e=>St.with(void 0)));const wt=new he("HANDSHAKING");wt.onEnter((e=>He(e.channels,e.groups))),wt.onExit((()=>He.cancel)),wt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?St.with(void 0):wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),wt.on(Ze.type,((e,t)=>{var n,s;return bt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:(null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.timetoken)?null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.timetoken:t.payload.timetoken,region:t.payload.region}},[We({category:h.PNConnectedCategory})])})),wt.on(et.type,((e,t)=>vt.with({channels:e.channels,groups:e.groups,cursor:e.cursor,attempts:0,reason:t.payload}))),wt.on(ut.type,(e=>gt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),wt.on(Ye.type,((e,t)=>{var n;return wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)||0}})})),wt.on(ht.type,(e=>St.with()));const St=new he("UNSUBSCRIBED");St.on(Qe.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups}))),St.on(Ye.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:t.payload.cursor})));class Et{get _engine(){return this.engine}constructor(e){this.engine=new de,this.channels=[],this.groups=[],this.dependencies=e,this.dispatcher=new dt(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(St,void 0)}subscribe({channels:e,channelGroups:t,timetoken:n,withPresence:s}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],s&&(this.channels.map((e=>this.channels.push(`${e}-pnpres`))),this.groups.map((e=>this.groups.push(`${e}-pnpres`)))),n?this.engine.transition(Ye(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])),n)):this.engine.transition(Qe(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])))),this.dependencies.join&&this.dependencies.join({channels:Array.from(new Set(this.channels.filter((e=>!e.endsWith("-pnpres"))))),groups:Array.from(new Set(this.groups.filter((e=>!e.endsWith("-pnpres")))))})}unsubscribe({channels:e=[],channelGroups:t=[]}){const n=B(this.channels,[...e,...e.map((e=>`${e}-pnpres`))]),s=B(this.groups,[...t,...t.map((e=>`${e}-pnpres`))]);if(new Set(this.channels).size!==new Set(n).size||new Set(this.groups).size!==new Set(s).size){const r=H(this.channels,e),i=H(this.groups,t);this.dependencies.presenceState&&(null==r||r.forEach((e=>delete this.dependencies.presenceState[e])),null==i||i.forEach((e=>delete this.dependencies.presenceState[e]))),this.channels=n,this.groups=s,this.engine.transition(Qe(Array.from(new Set(this.channels.slice(0))),Array.from(new Set(this.groups.slice(0))))),this.dependencies.leave&&this.dependencies.leave({channels:r.slice(0),groups:i.slice(0)})}}unsubscribeAll(){this.channels=[],this.groups=[],this.dependencies.presenceState&&Object.keys(this.dependencies.presenceState).forEach((e=>{delete this.dependencies.presenceState[e]})),this.engine.transition(Qe(this.channels.slice(0),this.groups.slice(0))),this.dependencies.leaveAll&&this.dependencies.leaveAll()}reconnect({timetoken:e,region:t}){this.engine.transition(lt(e,t))}disconnect(){this.engine.transition(ut()),this.dependencies.leaveAll&&this.dependencies.leaveAll()}getSubscribedChannels(){return Array.from(new Set(this.channels.slice(0)))}getSubscribedChannelGroups(){return Array.from(new Set(this.groups.slice(0)))}dispose(){this.disconnect(),this._unsubscribeEngine(),this.dispatcher.dispose()}}class Ot extends se{constructor(e){var t,n;super({method:e.sendByPost?K.POST:K.GET}),this.parameters=e,null!==(t=(n=this.parameters).sendByPost)&&void 0!==t||(n.sendByPost=false)}operation(){return ie.PNPublishOperation}validate(){const{message:e,channel:t,keySet:{publishKey:n}}=this.parameters;return t?e?n?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{message:e,channel:t,keySet:n}=this.parameters,s=this.prepareMessagePayload(e);return`/publish/${n.publishKey}/${n.subscribeKey}/0/${$(t)}/0${this.parameters.sendByPost?"":`/${$(s)}`}`}get queryParameters(){const{customMessageType:e,meta:t,replicate:n,storeInHistory:s,ttl:r}=this.parameters,i={};return e&&(i.custom_message_type=e),void 0!==s&&(i.store=s?"1":"0"),void 0!==r&&(i.ttl=r),void 0===n||n||(i.norep="true"),t&&"object"==typeof t&&(i.meta=JSON.stringify(t)),i}get headers(){if(this.parameters.sendByPost)return{"Content-Type":"application/json"}}get body(){return this.prepareMessagePayload(this.parameters.message)}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const n=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof n?n:u(n))}}class kt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNSignalOperation}validate(){const{message:e,channel:t,keySet:{publishKey:n}}=this.parameters;return t?e?n?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{keySet:{publishKey:e,subscribeKey:t},channel:n,message:s}=this.parameters,r=JSON.stringify(s);return`/signal/${e}/${t}/0/${$(n)}/0/${$(r)}`}get queryParameters(){const{customMessageType:e}=this.parameters,t={};return e&&(t.custom_message_type=e),t}}class Ct extends oe{operation(){return ie.PNReceiveMessagesOperation}validate(){const e=super.validate();return e||(this.parameters.timetoken?this.parameters.region?void 0:"region can not be empty":"timetoken can not be empty")}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${L(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,timetoken:n,region:s}=this.parameters,r={ee:""};return e&&e.length>0&&(r["channel-group"]=e.sort().join(",")),t&&t.length>0&&(r["filter-expr"]=t),"string"==typeof n?n&&n.length>0&&(r.tt=n):n&&n>0&&(r.tt=n),s&&(r.tr=s),r}}class Nt extends oe{operation(){return ie.PNHandshakeOperation}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${L(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,state:n}=this.parameters,s={tt:0,ee:""};return e&&e.length>0&&(s["channel-group"]=e.sort().join(",")),t&&t.length>0&&(s["filter-expr"]=t),n&&Object.keys(n).length>0&&(s.state=JSON.stringify(n)),s}}class Pt extends se{constructor(e){var t,n,s,r;super(),this.parameters=e,null!==(t=(s=this.parameters).channels)&&void 0!==t||(s.channels=[]),null!==(n=(r=this.parameters).channelGroups)&&void 0!==n||(r.channelGroups=[])}operation(){return ie.PNGetStateOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:n}=this.parameters;if(!e)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e),{channels:n=[],channelGroups:s=[]}=this.parameters,r={channels:{}};return 1===n.length&&0===s.length?r.channels[n[0]]=t.payload:r.channels=t.payload,r}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:n}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${L(null!=n?n:[],",")}/uuid/${t}`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.join(",")}:{}}}class Mt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNSetStateOperation}validate(){const{keySet:{subscribeKey:e},state:t,channels:n=[],channelGroups:s=[]}=this.parameters;return e?t?0===(null==n?void 0:n.length)&&0===(null==s?void 0:s.length)?"Please provide a list of channels and/or channel-groups":void 0:"Missing State":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{state:this.deserializeResponse(e).payload}}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:n}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${L(null!=n?n:[],",")}/uuid/${$(t)}/data`}get queryParameters(){const{channelGroups:e,state:t}=this.parameters,n={state:JSON.stringify(t)};return e&&0!==e.length&&(n["channel-group"]=e.join(",")),n}}class _t extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNHeartbeatOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:n=[]}=this.parameters;return e?0===t.length&&0===n.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channels:t}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${L(null!=t?t:[],",")}/heartbeat`}get queryParameters(){const{channelGroups:e,state:t,heartbeat:n}=this.parameters,s={heartbeat:`${n}`};return e&&0!==e.length&&(s["channel-group"]=e.join(",")),t&&(s.state=JSON.stringify(t)),s}}class At extends se{constructor(e){super(),this.parameters=e,this.parameters.channelGroups&&(this.parameters.channelGroups=Array.from(new Set(this.parameters.channelGroups))),this.parameters.channels&&(this.parameters.channels=Array.from(new Set(this.parameters.channels)))}operation(){return ie.PNUnsubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:n=[]}=this.parameters;return e?0===t.length&&0===n.length?"At least one `channel` or `channel group` should be provided.":void 0:"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){var e;const{keySet:{subscribeKey:t},channels:n}=this.parameters;return`/v2/presence/sub-key/${t}/channel/${L(null!==(e=null==n?void 0:n.sort())&&void 0!==e?e:[],",")}/leave`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.sort().join(",")}:{}}}class jt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNWhereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return t.payload?{channels:t.payload.channels}:{channels:[]}}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/presence/sub-key/${e}/uuid/${$(t)}`}}class It extends se{constructor(e){var t,n,s,r,i,a;super(),this.parameters=e,null!==(t=(r=this.parameters).queryParameters)&&void 0!==t||(r.queryParameters={}),null!==(n=(i=this.parameters).includeUUIDs)&&void 0!==n||(i.includeUUIDs=true),null!==(s=(a=this.parameters).includeState)&&void 0!==s||(a.includeState=false)}operation(){const{channels:e=[],channelGroups:t=[]}=this.parameters;return 0===e.length&&0===t.length?ie.PNGlobalHereNowOperation:ie.PNHereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t,n;const s=this.deserializeResponse(e),r="occupancy"in s?1:s.payload.total_channels,i="occupancy"in s?s.occupancy:s.payload.total_occupancy,a={};let o={};if("occupancy"in s){const e=this.parameters.channels[0];o[e]={uuids:null!==(t=s.uuids)&&void 0!==t?t:[],occupancy:i}}else o=null!==(n=s.payload.channels)&&void 0!==n?n:{};return Object.keys(o).forEach((e=>{const t=o[e];a[e]={occupants:this.parameters.includeUUIDs?t.uuids.map((e=>"string"==typeof e?{uuid:e,state:null}:e)):[],name:e,occupancy:t.occupancy}})),{totalChannels:r,totalOccupancy:i,channels:a}}))}get path(){const{keySet:{subscribeKey:e},channels:t,channelGroups:n}=this.parameters;let s=`/v2/presence/sub-key/${e}`;return(t&&t.length>0||n&&n.length>0)&&(s+=`/channel/${L(null!=t?t:[],",")}`),s}get queryParameters(){const{channelGroups:e,includeUUIDs:t,includeState:n,queryParameters:s}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign({},t?{}:{disable_uuids:"1"}),null!=n&&n?{state:"1"}:{}),e&&e.length>0?{"channel-group":e.join(",")}:{}),s)}}class Ft extends se{constructor(e){super({method:K.DELETE}),this.parameters=e}operation(){return ie.PNDeleteMessagesOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v3/history/sub-key/${e}/channel/${$(t)}`}get queryParameters(){const{start:e,end:t}=this.parameters;return Object.assign(Object.assign({},e?{start:e}:{}),t?{end:t}:{})}}class Tt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNMessageCounts}validate(){const{keySet:{subscribeKey:e},channels:t,timetoken:n,channelTimetokens:s}=this.parameters;return e?t?n&&s?"`timetoken` and `channelTimetokens` are incompatible together":n||s?s&&s.length>1&&s.length!==t.length?"Length of `channelTimetokens` and `channels` do not match":void 0:"`timetoken` or `channelTimetokens` need to be set":"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e).channels}}))}get path(){return`/v3/history/sub-key/${this.parameters.keySet.subscribeKey}/message-counts/${L(this.parameters.channels)}`}get queryParameters(){let{channelTimetokens:e}=this.parameters;return this.parameters.timetoken&&(e=[this.parameters.timetoken]),Object.assign(Object.assign({},1===e.length?{timetoken:e[0]}:{}),e.length>1?{channelsTimetoken:e.join(",")}:{})}}class Rt extends se{constructor(e){var t,n,s;super(),this.parameters=e,e.count?e.count=Math.min(e.count,100):e.count=100,null!==(t=e.stringifiedTimeToken)&&void 0!==t||(e.stringifiedTimeToken=false),null!==(n=e.includeMeta)&&void 0!==n||(e.includeMeta=false),null!==(s=e.logVerbosity)&&void 0!==s||(e.logVerbosity=false)}operation(){return ie.PNHistoryOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e),n=t[0],s=t[1],r=t[2];return Array.isArray(n)?{messages:n.map((e=>{const t=this.processPayload(e.message),n={entry:t.payload,timetoken:e.timetoken};return t.error&&(n.error=t.error),e.meta&&(n.meta=e.meta),n})),startTimeToken:s,endTimeToken:r}:{messages:[],startTimeToken:s,endTimeToken:r}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/history/sub-key/${e}/channel/${$(t)}`}get queryParameters(){const{start:e,end:t,reverse:n,count:s,stringifiedTimeToken:r,includeMeta:i}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:s,include_token:"true"},e?{start:e}:{}),t?{end:t}:{}),r?{string_message_token:"true"}:{}),null!=n?{reverse:n.toString()}:{}),i?{include_meta:"true"}:{})}processPayload(e){const{crypto:t,logVerbosity:n}=this.parameters;if(!t||"string"!=typeof e)return{payload:e};let s,r;try{const n=t.decrypt(e);s=n instanceof ArrayBuffer?JSON.parse(Rt.decoder.decode(n)):n}catch(t){n&&console.log("decryption error",t.message),s=e,r=`Error while decrypting message content: ${t.message}`}return{payload:s,error:r}}}var Ut;!function(e){e[e.Message=-1]="Message",e[e.Files=4]="Files"}(Ut||(Ut={}));class xt extends se{constructor(e){var t,n,s,r,i;super(),this.parameters=e;const a=null!==(t=e.includeMessageActions)&&void 0!==t&&t,o=e.channels.length>1||a?25:100;e.count?e.count=Math.min(e.count,o):e.count=o,e.includeUuid?e.includeUUID=e.includeUuid:null!==(n=e.includeUUID)&&void 0!==n||(e.includeUUID=true),null!==(s=e.stringifiedTimeToken)&&void 0!==s||(e.stringifiedTimeToken=false),null!==(r=e.includeMessageType)&&void 0!==r||(e.includeMessageType=true),null!==(i=e.logVerbosity)&&void 0!==i||(e.logVerbosity=false)}operation(){return ie.PNFetchMessagesOperation}validate(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:n}=this.parameters;return e?t?void 0!==n&&n&&t.length>1?"History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.":void 0:"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t;const n=this.deserializeResponse(e),s=null!==(t=n.channels)&&void 0!==t?t:{},r={};return Object.keys(s).forEach((e=>{r[e]=s[e].map((t=>{null===t.message_type&&(t.message_type=Ut.Message);const n=this.processPayload(e,t),s=Object.assign(Object.assign({channel:e,timetoken:t.timetoken,message:n.payload,messageType:t.message_type},t.custom_message_type?{customMessageType:t.custom_message_type}:{}),{uuid:t.uuid});if(t.actions){const e=s;e.actions=t.actions,e.data=t.actions}return t.meta&&(s.meta=t.meta),n.error&&(s.error=n.error),s}))})),n.more?{channels:r,more:n.more}:{channels:r}}))}get path(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:n}=this.parameters;return`/v3/${n?"history-with-actions":"history"}/sub-key/${e}/channel/${L(t)}`}get queryParameters(){const{start:e,end:t,count:n,includeCustomMessageType:s,includeMessageType:r,includeMeta:i,includeUUID:a,stringifiedTimeToken:o}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({max:n},e?{start:e}:{}),t?{end:t}:{}),o?{string_message_token:"true"}:{}),void 0!==i&&i?{include_meta:"true"}:{}),a?{include_uuid:"true"}:{}),null!=s?{include_custom_message_type:s?"true":"false"}:{}),r?{include_message_type:"true"}:{})}processPayload(e,t){const{crypto:n,logVerbosity:s}=this.parameters;if(!n||"string"!=typeof t.message)return{payload:t.message};let r,i;try{const e=n.decrypt(t.message);r=e instanceof ArrayBuffer?JSON.parse(xt.decoder.decode(e)):e}catch(e){s&&console.log("decryption error",e.message),r=t.message,i=`Error while decrypting message content: ${e.message}`}if(!i&&r&&t.message_type==Ut.Files&&"object"==typeof r&&this.isFileMessage(r)){const t=r;return{payload:{message:t.message,file:Object.assign(Object.assign({},t.file),{url:this.parameters.getFileUrl({channel:e,id:t.file.id,name:t.file.name})})},error:i}}return{payload:r,error:i}}isFileMessage(e){return void 0!==e.file}}class Dt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNGetMessageActionsOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);let n=null,s=null;return t.data.length>0&&(n=t.data[0].actionTimetoken,s=t.data[t.data.length-1].actionTimetoken),{data:t.data,more:t.more,start:n,end:s}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/message-actions/${e}/channel/${$(t)}`}get queryParameters(){const{limit:e,start:t,end:n}=this.parameters;return Object.assign(Object.assign(Object.assign({},t?{start:t}:{}),n?{end:n}:{}),e?{limit:e}:{})}}class qt extends se{constructor(e){super({method:K.POST}),this.parameters=e}operation(){return ie.PNAddMessageActionOperation}validate(){const{keySet:{subscribeKey:e},action:t,channel:n,messageTimetoken:s}=this.parameters;return e?n?s?t?t.value?t.type?t.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message timetoken":"Missing message channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((({data:e})=>({data:e})))}))}get path(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:n}=this.parameters;return`/v1/message-actions/${e}/channel/${$(t)}/message/${n}`}get headers(){return{"Content-Type":"application/json"}}get body(){return JSON.stringify(this.parameters.action)}}class Gt extends se{constructor(e){super({method:K.DELETE}),this.parameters=e}operation(){return ie.PNRemoveMessageActionOperation}validate(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:n,actionTimetoken:s}=this.parameters;return e?t?n?s?void 0:"Missing action timetoken":"Missing message timetoken":"Missing message action channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((({data:e})=>({data:e})))}))}get path(){const{keySet:{subscribeKey:e},channel:t,actionTimetoken:n,messageTimetoken:s}=this.parameters;return`/v1/message-actions/${e}/channel/${$(t)}/message/${s}/action/${n}`}}class Kt extends se{constructor(e){var t,n;super(),this.parameters=e,null!==(t=(n=this.parameters).storeInHistory)&&void 0!==t||(n.storeInHistory=true)}operation(){return ie.PNPublishFileMessageOperation}validate(){const{channel:e,fileId:t,fileName:n}=this.parameters;return e?t?n?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{message:e,channel:t,keySet:{publishKey:n,subscribeKey:s},fileId:r,fileName:i}=this.parameters,a=Object.assign({file:{name:i,id:r}},e?{message:e}:{});return`/v1/files/publish-file/${n}/${s}/0/${$(t)}/0/${$(this.prepareMessagePayload(a))}`}get queryParameters(){const{customMessageType:e,storeInHistory:t,ttl:n,meta:s}=this.parameters;return Object.assign(Object.assign(Object.assign({store:t?"1":"0"},e?{custom_message_type:e}:{}),n?{ttl:n}:{}),s&&"object"==typeof s?{meta:JSON.stringify(s)}:{})}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const n=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof n?n:u(n))}}class $t extends se{constructor(e){super({method:K.LOCAL}),this.parameters=e}operation(){return ie.PNGetFileUrlOperation}validate(){const{channel:e,id:t,name:n}=this.parameters;return e?t?n?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return e.url}))}get path(){const{channel:e,id:t,name:n,keySet:{subscribeKey:s}}=this.parameters;return`/v1/files/${s}/channels/${$(e)}/files/${t}/${n}`}}class Lt extends se{constructor(e){super({method:K.DELETE}),this.parameters=e}operation(){return ie.PNDeleteFileOperation}validate(){const{channel:e,id:t,name:n}=this.parameters;return e?t?n?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}get path(){const{keySet:{subscribeKey:e},id:t,channel:n,name:s}=this.parameters;return`/v1/files/${e}/channels/${$(n)}/files/${t}/${s}`}}class Bt extends se{constructor(e){var t,n;super(),this.parameters=e,null!==(t=(n=this.parameters).limit)&&void 0!==t||(n.limit=100)}operation(){return ie.PNListFilesOperation}validate(){if(!this.parameters.channel)return"channel can't be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${$(t)}/files`}get queryParameters(){const{limit:e,next:t}=this.parameters;return Object.assign({limit:e},t?{next:t}:{})}}class Ht extends se{constructor(e){super({method:K.POST}),this.parameters=e}operation(){return ie.PNGenerateUploadUrlOperation}validate(){return this.parameters.channel?this.parameters.name?void 0:"'name' can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return{id:t.data.id,name:t.data.name,url:t.file_upload_request.url,formFields:t.file_upload_request.form_fields}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${$(t)}/generate-upload-url`}get headers(){return{"Content-Type":"application/json"}}get body(){return JSON.stringify({name:this.parameters.name})}}class Vt extends se{constructor(e){super({method:K.POST}),this.parameters=e;const t=e.file.mimeType;t&&(e.formFields=e.formFields.map((e=>"Content-Type"===e.name?{name:e.name,value:t}:e)))}operation(){return ie.PNPublishFileOperation}validate(){const{fileId:e,fileName:t,file:n,uploadUrl:s}=this.parameters;return e?t?n?s?void 0:"Validation failed: file upload 'url' can't be empty":"Validation failed: 'file' can't be empty":"Validation failed: file 'name' can't be empty":"Validation failed: file 'id' can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{status:e.status,message:e.body?Vt.decoder.decode(e.body):"OK"}}))}request(){return Object.assign(Object.assign({},super.request()),{origin:new URL(this.parameters.uploadUrl).origin,timeout:300})}get path(){const{pathname:e,search:t}=new URL(this.parameters.uploadUrl);return`${e}${t}`}get body(){return this.parameters.file}get formData(){return this.parameters.formFields}}class zt{constructor(e){var t;if(this.parameters=e,this.file=null===(t=this.parameters.PubNubFile)||void 0===t?void 0:t.create(e.file),!this.file)throw new Error("File upload error: unable to create File object.")}process(){return i(this,void 0,void 0,(function*(){let e,t;return this.generateFileUploadUrl().then((n=>(e=n.name,t=n.id,this.uploadFile(n)))).then((e=>{if(204!==e.status)throw new d("Upload to bucket was unsuccessful",{error:!0,statusCode:e.status,category:h.PNUnknownCategory,operation:ie.PNPublishFileOperation,errorData:{message:e.message}})})).then((()=>this.publishFileMessage(t,e))).catch((e=>{if(e instanceof d)throw e;const t=e instanceof j?e:j.create(e);throw new d("File upload error.",t.toStatus(ie.PNPublishFileOperation))}))}))}generateFileUploadUrl(){return i(this,void 0,void 0,(function*(){const e=new Ht(Object.assign(Object.assign({},this.parameters),{name:this.file.name,keySet:this.parameters.keySet}));return this.parameters.sendRequest(e)}))}uploadFile(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,PubNubFile:n,crypto:s,cryptography:r}=this.parameters,{id:i,name:a,url:o,formFields:c}=e;return this.parameters.PubNubFile.supportsEncryptFile&&(!t&&s?this.file=yield s.encryptFile(this.file,n):t&&r&&(this.file=yield r.encryptFile(t,this.file,n))),this.parameters.sendRequest(new Vt({fileId:i,fileName:a,file:this.file,uploadUrl:o,formFields:c}))}))}publishFileMessage(e,t){return i(this,void 0,void 0,(function*(){var n,s,r,i;let a,o={timetoken:"0"},c=this.parameters.fileUploadPublishRetryLimit,u=!1;do{try{o=yield this.parameters.publishFile(Object.assign(Object.assign({},this.parameters),{fileId:e,fileName:t})),u=!0}catch(e){e instanceof d&&(a=e),c-=1}}while(!u&&c>0);if(u)return{status:200,timetoken:o.timetoken,id:e,name:t};throw new d("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{error:!0,category:null!==(s=null===(n=a.status)||void 0===n?void 0:n.category)&&void 0!==s?s:h.PNUnknownCategory,statusCode:null!==(i=null===(r=a.status)||void 0===r?void 0:r.statusCode)&&void 0!==i?i:0,channel:this.parameters.channel,id:e,name:t})}))}}class Wt{subscribe(e){const t=null==e?void 0:e.timetoken;this.pubnub.registerSubscribeCapable(this),this.pubnub.subscribe(Object.assign({channels:this.channelNames,channelGroups:this.groupNames},null!==t&&""!==t&&{timetoken:t}))}unsubscribe(){this.pubnub.unregisterSubscribeCapable(this);const{channels:e,channelGroups:t}=this.pubnub.getSubscribeCapableEntities(),n=this.groupNames.filter((e=>!t.includes(e))),s=this.channelNames.filter((t=>!e.includes(t)));0===s.length&&0===n.length||this.pubnub.unsubscribe({channels:s,channelGroups:n})}set onMessage(e){this.listener.message=e}set onPresence(e){this.listener.presence=e}set onSignal(e){this.listener.signal=e}set onObjects(e){this.listener.objects=e}set onMessageAction(e){this.listener.messageAction=e}set onFile(e){this.listener.file=e}addListener(e){this.eventEmitter.addListener(e,this.channelNames,this.groupNames)}removeListener(e){this.eventEmitter.removeListener(e,this.channelNames,this.groupNames)}get channels(){return this.channelNames.slice(0)}get channelGroups(){return this.groupNames.slice(0)}}class Jt extends Wt{constructor({channels:e=[],channelGroups:t=[],subscriptionOptions:n,eventEmitter:s,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.subscriptionList=[],this.options=n,this.eventEmitter=s,this.pubnub=r,e.forEach((e=>{const t=this.pubnub.channel(e).subscription(this.options);this.channelNames=[...this.channelNames,...t.channels],this.subscriptionList.push(t)})),t.forEach((e=>{const t=this.pubnub.channelGroup(e).subscription(this.options);this.groupNames=[...this.groupNames,...t.channelGroups],this.subscriptionList.push(t)})),this.listener={},s.addListener(this.listener,this.channelNames,this.groupNames)}addSubscription(e){this.subscriptionList.push(e),this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscription(e){const t=e.channels,n=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!n.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>t!==e)),this.eventEmitter.removeListener(this.listener,t,n)}addSubscriptionSet(e){this.subscriptionList=[...this.subscriptionList,...e.subscriptions],this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscriptionSet(e){const t=e.channels,n=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!n.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>!e.subscriptions.includes(t))),this.eventEmitter.removeListener(this.listener,t,n)}get subscriptions(){return this.subscriptionList.slice(0)}}class Xt extends Wt{constructor({channels:e,channelGroups:t,subscriptionOptions:n,eventEmitter:s,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.channelNames=e,this.groupNames=t,this.options=n,this.pubnub=r,this.eventEmitter=s,this.listener={},s.addListener(this.listener,this.channelNames,this.groupNames)}addSubscription(e){return new Jt({channels:[...this.channelNames,...e.channels],channelGroups:[...this.groupNames,...e.channelGroups],subscriptionOptions:Object.assign(Object.assign({},this.options),null==e?void 0:e.options),eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Qt{constructor(e,t,n){this.eventEmitter=t,this.pubnub=n,this.id=e}subscription(e){return new Xt({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Yt{constructor(e,t,n){this.eventEmitter=t,this.pubnub=n,this.name=e}subscription(e){{const t=[this.name];return(null==e?void 0:e.receivePresenceEvents)&&!this.name.endsWith("-pnpres")&&t.push(`${this.name}-pnpres`),new Xt({channels:[],channelGroups:t,subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}}class Zt{constructor(e,t,n){this.eventEmitter=t,this.pubnub=n,this.id=e}subscription(e){return new Xt({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class en{constructor(e,t,n){this.eventEmitter=t,this.pubnub=n,this.name=e}subscription(e){{const t=[this.name];return(null==e?void 0:e.receivePresenceEvents)&&!this.name.endsWith("-pnpres")&&t.push(`${this.name}-pnpres`),new Xt({channels:t,channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}}class tn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNRemoveChannelsFromGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:n}=this.parameters;return e?n?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${$(t)}`}get queryParameters(){return{remove:this.parameters.channels.join(",")}}}class nn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNAddChannelsToGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:n}=this.parameters;return e?n?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${$(t)}`}get queryParameters(){return{add:this.parameters.channels.join(",")}}}class sn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNChannelsForGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e).payload.channels}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${$(t)}`}}class rn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNRemoveGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${$(t)}/remove`}}class an extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNChannelGroupsOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{groups:this.deserializeResponse(e).payload.groups}}))}get path(){return`/v1/channel-registration/sub-key/${this.parameters.keySet.subscribeKey}/channel-group`}}class on{constructor(e,t){this.sendRequest=t,this.keySet=e}listChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new sn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}listGroups(e){return i(this,void 0,void 0,(function*(){const t=new an({keySet:this.keySet});return e?this.sendRequest(t,e):this.sendRequest(t)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new nn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new tn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}deleteGroup(e,t){return i(this,void 0,void 0,(function*(){const n=new rn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}}class cn extends se{constructor(e){var t,n;super(),this.parameters=e,"apns2"===this.parameters.pushGateway&&(null!==(t=(n=this.parameters).environment)&&void 0!==t||(n.environment="development")),this.parameters.count&&this.parameters.count>1e3&&(this.parameters.count=1e3)}operation(){throw Error("Should be implemented in subclass.")}validate(){const{keySet:{subscribeKey:e},action:t,device:n,pushGateway:s}=this.parameters;return e?n?"add"!==t&&"remove"!==t||"channels"in this.parameters&&0!==this.parameters.channels.length?s?"apns2"!==this.parameters.pushGateway||this.parameters.topic?void 0:"Missing APNS2 topic":"Missing GW Type (pushGateway: gcm or apns2)":"Missing Channels":"Missing Device ID (device)":"Missing Subscribe Key"}get path(){const{keySet:{subscribeKey:e},action:t,device:n,pushGateway:s}=this.parameters;let r="apns2"===s?`/v2/push/sub-key/${e}/devices-apns2/${n}`:`/v1/push/sub-key/${e}/devices/${n}`;return"remove-device"===t&&(r=`${r}/remove`),r}get queryParameters(){const{start:e,count:t}=this.parameters;let n=Object.assign(Object.assign({type:this.parameters.pushGateway},e?{start:e}:{}),t&&t>0?{count:t}:{});if("channels"in this.parameters&&(n[this.parameters.action]=this.parameters.channels.join(",")),"apns2"===this.parameters.pushGateway){const{environment:e,topic:t}=this.parameters;n=Object.assign(Object.assign({},n),{environment:e,topic:t})}return n}}class un extends cn{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove"}))}operation(){return ie.PNRemovePushNotificationEnabledChannelsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class ln extends cn{constructor(e){super(Object.assign(Object.assign({},e),{action:"list"}))}operation(){return ie.PNPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e)}}))}}class hn extends cn{constructor(e){super(Object.assign(Object.assign({},e),{action:"add"}))}operation(){return ie.PNAddPushNotificationEnabledChannelsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class dn extends cn{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove-device"}))}operation(){return ie.PNRemoveAllPushNotificationsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class pn{constructor(e,t){this.sendRequest=t,this.keySet=e}listChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new ln(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new hn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new un(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}deleteDevice(e,t){return i(this,void 0,void 0,(function*(){const n=new dn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}}class gn extends se{constructor(e){var t,n,s,r,i,a;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(i=e.include).customFields)&&void 0!==n||(i.customFields=false),null!==(s=(a=e.include).totalCount)&&void 0!==s||(a.totalCount=false),null!==(r=e.limit)&&void 0!==r||(e.limit=100)}operation(){return ie.PNGetAllChannelMetadataOperation}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";return i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(","),count:`${e.totalCount}`},n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class yn extends se{constructor(e){super({method:K.DELETE}),this.parameters=e}operation(){return ie.PNRemoveChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}`}}class fn extends se{constructor(e){var t,n,s,r,i,a,o,c,u,l,h,d,p,g,y,f,m,b;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(h=e.include).customFields)&&void 0!==n||(h.customFields=false),null!==(s=(d=e.include).totalCount)&&void 0!==s||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(y=e.include).channelFields)&&void 0!==a||(y.channelFields=false),null!==(o=(f=e.include).customChannelFields)&&void 0!==o||(f.customChannelFields=false),null!==(c=(m=e.include).channelStatusField)&&void 0!==c||(m.channelStatusField=false),null!==(u=(b=e.include).channelTypeField)&&void 0!==u||(b.channelTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNGetMembershipsOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=[];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.channelFields&&a.push("channel"),e.channelStatusField&&a.push("channel.status"),e.channelTypeField&&a.push("channel.type"),e.customChannelFields&&a.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class mn extends se{constructor(e){var t,n,s,r,i,a,o,c,u,l,h,d,p,g,y,f,m,b;super({method:K.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(h=e.include).customFields)&&void 0!==n||(h.customFields=false),null!==(s=(d=e.include).totalCount)&&void 0!==s||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(y=e.include).channelFields)&&void 0!==a||(y.channelFields=false),null!==(o=(f=e.include).customChannelFields)&&void 0!==o||(f.customChannelFields=false),null!==(c=(m=e.include).channelStatusField)&&void 0!==c||(m.channelStatusField=false),null!==(u=(b=e.include).channelTypeField)&&void 0!==u||(b.channelTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNSetMembershipsOperation}validate(){const{uuid:e,channels:t}=this.parameters;return e?t&&0!==t.length?void 0:"Channels cannot be empty":"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=["channel.status","channel.type","status"];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.channelFields&&a.push("channel"),e.channelStatusField&&a.push("channel.status"),e.channelTypeField&&a.push("channel.type"),e.customChannelFields&&a.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{channels:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},status:e.status,type:e.type,custom:e.custom}))})}}class bn extends se{constructor(e){var t,n,s,r;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(r=e.include).customFields)&&void 0!==n||(r.customFields=false),null!==(s=e.limit)&&void 0!==s||(e.limit=100)}operation(){return ie.PNGetAllUUIDMetadataOperation}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";return i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(",")},void 0!==e.totalCount?{count:`${e.totalCount}`}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class vn extends se{constructor(e){var t,n,s;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(s=e.include).customFields)&&void 0!==n||(s.customFields=true)}operation(){return ie.PNGetChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}}class wn extends se{constructor(e){var t,n,s;super({method:K.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(s=e.include).customFields)&&void 0!==n||(s.customFields=true)}operation(){return ie.PNSetChannelMetadataOperation}validate(){return this.parameters.channel?this.parameters.data?void 0:"Data cannot be empty":"Channel cannot be empty"}get headers(){return this.parameters.ifMatchesEtag?{"If-Match":this.parameters.ifMatchesEtag}:void 0}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Sn extends se{constructor(e){super({method:K.DELETE}),this.parameters=e,this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNRemoveUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}`}}class En extends se{constructor(e){var t,n,s,r,i,a,o,c,u,l,h,d,p,g,y,f,m,b;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(h=e.include).customFields)&&void 0!==n||(h.customFields=false),null!==(s=(d=e.include).totalCount)&&void 0!==s||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(y=e.include).UUIDFields)&&void 0!==a||(y.UUIDFields=false),null!==(o=(f=e.include).customUUIDFields)&&void 0!==o||(f.customUUIDFields=false),null!==(c=(m=e.include).UUIDStatusField)&&void 0!==c||(m.UUIDStatusField=false),null!==(u=(b=e.include).UUIDTypeField)&&void 0!==u||(b.UUIDTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100)}operation(){return ie.PNSetMembersOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=[];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.UUIDFields&&a.push("uuid"),e.UUIDStatusField&&a.push("uuid.status"),e.UUIDTypeField&&a.push("uuid.type"),e.customUUIDFields&&a.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class On extends se{constructor(e){var t,n,s,r,i,a,o,c,u,l,h,d,p,g,y,f,m,b;super({method:K.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(h=e.include).customFields)&&void 0!==n||(h.customFields=false),null!==(s=(d=e.include).totalCount)&&void 0!==s||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(y=e.include).UUIDFields)&&void 0!==a||(y.UUIDFields=false),null!==(o=(f=e.include).customUUIDFields)&&void 0!==o||(f.customUUIDFields=false),null!==(c=(m=e.include).UUIDStatusField)&&void 0!==c||(m.UUIDStatusField=false),null!==(u=(b=e.include).UUIDTypeField)&&void 0!==u||(b.UUIDTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100)}operation(){return ie.PNSetMembersOperation}validate(){const{channel:e,uuids:t}=this.parameters;return e?t&&0!==t.length?void 0:"UUIDs cannot be empty":"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=["uuid.status","uuid.type","type"];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.UUIDFields&&a.push("uuid"),e.UUIDStatusField&&a.push("uuid.status"),e.UUIDTypeField&&a.push("uuid.type"),e.customUUIDFields&&a.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{uuids:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},status:e.status,type:e.type,custom:e.custom}))})}}class kn extends se{constructor(e){var t,n,s;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(s=e.include).customFields)&&void 0!==n||(s.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNGetUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}`}get queryParameters(){const{include:e}=this.parameters;return{include:["status","type",...e.customFields?["custom"]:[]].join(",")}}}class Cn extends se{constructor(e){var t,n,s;super({method:K.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(s=e.include).customFields)&&void 0!==n||(s.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNSetUUIDMetadataOperation}validate(){return this.parameters.uuid?this.parameters.data?void 0:"Data cannot be empty":"'uuid' cannot be empty"}get headers(){return this.parameters.ifMatchesEtag?{"If-Match":this.parameters.ifMatchesEtag}:void 0}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Nn{constructor(e,t){this.keySet=e.keySet,this.configuration=e,this.sendRequest=t}getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllUUIDMetadata(e,t)}))}_getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const s=new bn(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getUUIDMetadata(e,t)}))}_getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var n;const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),s.userId&&(s.uuid=s.userId),null!==(n=s.uuid)&&void 0!==n||(s.uuid=this.configuration.userId);const r=new kn(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setUUIDMetadata(e,t)}))}_setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var n;e.userId&&(e.uuid=e.userId),null!==(n=e.uuid)&&void 0!==n||(e.uuid=this.configuration.userId);const s=new Cn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeUUIDMetadata(e,t)}))}_removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var n;const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),s.userId&&(s.uuid=s.userId),null!==(n=s.uuid)&&void 0!==n||(s.uuid=this.configuration.userId);const r=new Sn(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllChannelMetadata(e,t)}))}_getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const s=new gn(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getChannelMetadata(e,t)}))}_getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=new vn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setChannelMetadata(e,t)}))}_setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=new wn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeChannelMetadata(e,t)}))}_removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=new yn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const n=new En(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const n=new On(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const n=new On(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getMemberships(e,t){return i(this,void 0,void 0,(function*(){var n;const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),s.userId&&(s.uuid=s.userId),null!==(n=s.uuid)&&void 0!==n||(s.uuid=this.configuration.userId);const r=new fn(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setMemberships(e,t){return i(this,void 0,void 0,(function*(){var n;e.userId&&(e.uuid=e.userId),null!==(n=e.uuid)&&void 0!==n||(e.uuid=this.configuration.userId);const s=new mn(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var n;e.userId&&(e.uuid=e.userId),null!==(n=e.uuid)&&void 0!==n||(e.uuid=this.configuration.userId);const s=new mn(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){var n,s;if("spaceId"in e){const s=e,r={channel:null!==(n=s.spaceId)&&void 0!==n?n:s.channel,filter:s.filter,limit:s.limit,page:s.page,include:Object.assign({},s.include),sort:s.sort?Object.fromEntries(Object.entries(s.sort).map((([e,t])=>[e.replace("user","uuid"),t]))):void 0},i=e=>({status:e.status,data:e.data.map((e=>({user:e.uuid,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getChannelMembers(r,((e,n)=>{t(e,n?i(n):n)})):this.getChannelMembers(r).then(i)}const r=e,i={uuid:null!==(s=r.userId)&&void 0!==s?s:r.uuid,filter:r.filter,limit:r.limit,page:r.page,include:Object.assign({},r.include),sort:r.sort?Object.fromEntries(Object.entries(r.sort).map((([e,t])=>[e.replace("space","channel"),t]))):void 0},a=e=>({status:e.status,data:e.data.map((e=>({space:e.channel,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getMemberships(i,((e,n)=>{t(e,n?a(n):n)})):this.getMemberships(i).then(a)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){var n,s,r,i,a,o;if("spaceId"in e){const i=e,a={channel:null!==(n=i.spaceId)&&void 0!==n?n:i.channel,uuids:null!==(r=null===(s=i.users)||void 0===s?void 0:s.map((e=>"string"==typeof e?e:{id:e.userId,custom:e.custom})))&&void 0!==r?r:i.uuids,limit:0};return t?this.setChannelMembers(a,t):this.setChannelMembers(a)}const c=e,u={uuid:null!==(i=c.userId)&&void 0!==i?i:c.uuid,channels:null!==(o=null===(a=c.spaces)||void 0===a?void 0:a.map((e=>"string"==typeof e?e:{id:e.spaceId,custom:e.custom})))&&void 0!==o?o:c.channels,limit:0};return t?this.setMemberships(u,t):this.setMemberships(u)}))}}class Pn extends se{constructor(){super()}operation(){return ie.PNTimeOperation}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[0]}}))}get path(){return"/time/0"}}class Mn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNDownloadFileOperation}validate(){const{channel:e,id:t,name:n}=this.parameters;return e?t?n?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,crypto:n,cryptography:s,name:r,PubNubFile:i}=this.parameters,a=e.headers["content-type"];let o,c=e.body;return i.supportsEncryptFile&&(t||n)&&(t&&s?c=yield s.decrypt(t,c):!t&&n&&(o=yield n.decryptFile(i.create({data:c,name:r,mimeType:a}),i))),o||i.create({data:c,name:r,mimeType:a})}))}get path(){const{keySet:{subscribeKey:e},channel:t,id:n,name:s}=this.parameters;return`/v1/files/${e}/channels/${$(t)}/files/${n}/${s}`}}class _n{static notificationPayload(e,t){return new ne(e,t)}static generateUUID(){return x.createUUID()}constructor(e){if(this._configuration=e.configuration,this.cryptography=e.cryptography,this.tokenManager=e.tokenManager,this.transport=e.transport,this.crypto=e.crypto,this._objects=new Nn(this._configuration,this.sendRequest.bind(this)),this._channelGroups=new on(this._configuration.keySet,this.sendRequest.bind(this)),this._push=new pn(this._configuration.keySet,this.sendRequest.bind(this)),this.listenerManager=new J,this.eventEmitter=new ue(this.listenerManager),this.subscribeCapable=new Set,this._configuration.enableEventEngine){let e=this._configuration.getHeartbeatInterval();this.presenceState={},e&&(this.presenceEventEngine=new Le({heartbeat:this.heartbeat.bind(this),leave:e=>this.makeUnsubscribe(e,(()=>{})),heartbeatDelay:()=>new Promise(((t,n)=>{e=this._configuration.getHeartbeatInterval(),e?setTimeout(t,1e3*e):n(new d("Heartbeat interval has been reset."))})),retryDelay:e=>new Promise((t=>setTimeout(t,e))),emitStatus:e=>this.listenerManager.announceStatus(e),config:this._configuration,presenceState:this.presenceState})),this.eventEngine=new Et({handshake:this.subscribeHandshake.bind(this),receiveMessages:this.subscribeReceiveMessages.bind(this),delay:e=>new Promise((t=>setTimeout(t,e))),join:this.join.bind(this),leave:this.leave.bind(this),leaveAll:this.leaveAll.bind(this),presenceState:this.presenceState,config:this._configuration,emitMessages:e=>{try{e.forEach((e=>this.eventEmitter.emitEvent(e)))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}},emitStatus:e=>this.listenerManager.announceStatus(e)})}else this.subscriptionManager=new Y(this._configuration,this.listenerManager,this.eventEmitter,this.makeSubscribe.bind(this),this.heartbeat.bind(this),this.makeUnsubscribe.bind(this),this.time.bind(this))}get configuration(){return this._configuration}get _config(){return this.configuration}get authKey(){var e;return null!==(e=this._configuration.authKey)&&void 0!==e?e:void 0}getAuthKey(){return this.authKey}setAuthKey(e){this._configuration.setAuthKey(e)}get userId(){return this._configuration.userId}set userId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}getUserId(){return this._configuration.userId}setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}get filterExpression(){var e;return null!==(e=this._configuration.getFilterExpression())&&void 0!==e?e:void 0}getFilterExpression(){return this.filterExpression}set filterExpression(e){this._configuration.setFilterExpression(e)}setFilterExpression(e){this.filterExpression=e}get cipherKey(){return this._configuration.getCipherKey()}set cipherKey(e){this._configuration.setCipherKey(e)}setCipherKey(e){this.cipherKey=e}set heartbeatInterval(e){this._configuration.setHeartbeatInterval(e)}setHeartbeatInterval(e){this.heartbeatInterval=e}getVersion(){return this._configuration.getVersion()}_addPnsdkSuffix(e,t){this._configuration._addPnsdkSuffix(e,t)}getUUID(){return this.userId}setUUID(e){this.userId=e}get customEncrypt(){return this._configuration.getCustomEncrypt()}get customDecrypt(){return this._configuration.getCustomDecrypt()}channel(e){return new en(e,this.eventEmitter,this)}channelGroup(e){return new Yt(e,this.eventEmitter,this)}channelMetadata(e){return new Qt(e,this.eventEmitter,this)}userMetadata(e){return new Zt(e,this.eventEmitter,this)}subscriptionSet(e){return new Jt(Object.assign(Object.assign({},e),{eventEmitter:this.eventEmitter,pubnub:this}))}sendRequest(e,t){return i(this,void 0,void 0,(function*(){const n=e.validate();if(n){if(t)return t(g(n),null);throw new d("Validation failed, check status for details",g(n))}const s=e.request(),r=e.operation();s.formData&&s.formData.length>0||r===ie.PNDownloadFileOperation?s.timeout=this._configuration.getFileTimeout():r===ie.PNSubscribeOperation||r===ie.PNReceiveMessagesOperation?s.timeout=this._configuration.getSubscribeTimeout():s.timeout=this._configuration.getTransactionTimeout();const i={error:!1,operation:r,category:h.PNAcknowledgmentCategory,statusCode:0},[a,o]=this.transport.makeSendable(s);return e.cancellationController=o||null,a.then((t=>{if(i.statusCode=t.status,200!==t.status&&204!==t.status){const e=_n.decoder.decode(t.body),n=t.headers["content-type"];if(n||-1!==n.indexOf("javascript")||-1!==n.indexOf("json")){const t=JSON.parse(e);"object"==typeof t&&"error"in t&&t.error&&"object"==typeof t.error&&(i.errorData=t.error)}else i.responseText=e}return e.parse(t)})).then((e=>t?t(i,e):e)).catch((e=>{const n=e instanceof j?e:j.create(e);if(t)return t(n.toStatus(r),null);throw n.toPubNubError(r,"REST API request processing error, check status for details")}))}))}destroy(e){var t;null===(t=this.subscribeCapable)||void 0===t||t.clear(),this.subscriptionManager?(this.subscriptionManager.unsubscribeAll(e),this.subscriptionManager.disconnect()):this.eventEngine&&this.eventEngine.dispose()}stop(){this.destroy()}addListener(e){this.listenerManager.addListener(e)}removeListener(e){this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners()}publish(e,t){return i(this,void 0,void 0,(function*(){{const n=new Ot(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}signal(e,t){return i(this,void 0,void 0,(function*(){{const n=new kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}fire(e,t){return i(this,void 0,void 0,(function*(){return null!=t||(t=()=>{}),this.publish(Object.assign(Object.assign({},e),{replicate:!1,storeInHistory:!1}),t)}))}getSubscribedChannels(){return this.subscriptionManager?this.subscriptionManager.subscribedChannels:this.eventEngine?this.eventEngine.getSubscribedChannels():[]}getSubscribedChannelGroups(){return this.subscriptionManager?this.subscriptionManager.subscribedChannelGroups:this.eventEngine?this.eventEngine.getSubscribedChannelGroups():[]}registerSubscribeCapable(e){this.subscribeCapable&&!this.subscribeCapable.has(e)&&this.subscribeCapable.add(e)}unregisterSubscribeCapable(e){this.subscribeCapable&&this.subscribeCapable.has(e)&&this.subscribeCapable.delete(e)}getSubscribeCapableEntities(){{const e={channels:[],channelGroups:[]};if(!this.subscribeCapable)return e;for(const t of this.subscribeCapable)e.channelGroups.push(...t.channelGroups),e.channels.push(...t.channels);return e}}subscribe(e){this.subscriptionManager?this.subscriptionManager.subscribe(e):this.eventEngine&&this.eventEngine.subscribe(e)}makeSubscribe(e,t){{const n=new ce(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));if(this.sendRequest(n,((e,s)=>{var r;this.subscriptionManager&&(null===(r=this.subscriptionManager.abort)||void 0===r?void 0:r.identifier)===n.requestIdentifier&&(this.subscriptionManager.abort=null),t(e,s)})),this.subscriptionManager){const e=()=>n.abort("Cancel long-poll subscribe request");e.identifier=n.requestIdentifier,this.subscriptionManager.abort=e}}}unsubscribe(e){this.subscriptionManager?this.subscriptionManager.unsubscribe(e):this.eventEngine&&this.eventEngine.unsubscribe(e)}makeUnsubscribe(e,t){this.sendRequest(new At(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),t)}unsubscribeAll(){var e;null===(e=this.subscribeCapable)||void 0===e||e.clear(),this.subscriptionManager?this.subscriptionManager.unsubscribeAll():this.eventEngine&&this.eventEngine.unsubscribeAll()}disconnect(){this.subscriptionManager?this.subscriptionManager.disconnect():this.eventEngine&&this.eventEngine.disconnect()}reconnect(e){this.subscriptionManager?this.subscriptionManager.reconnect():this.eventEngine&&this.eventEngine.reconnect(null!=e?e:{})}subscribeHandshake(e){return i(this,void 0,void 0,(function*(){{const t=new Nt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),n=e.abortSignal.subscribe((e=>{t.abort("Cancel subscribe handshake request")}));return this.sendRequest(t).then((e=>(n(),e.cursor)))}}))}subscribeReceiveMessages(e){return i(this,void 0,void 0,(function*(){{const t=new Ct(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),n=e.abortSignal.subscribe((e=>{t.abort("Cancel long-poll subscribe request")}));return this.sendRequest(t).then((e=>(n(),e)))}}))}getMessageActions(e,t){return i(this,void 0,void 0,(function*(){{const n=new Dt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}addMessageAction(e,t){return i(this,void 0,void 0,(function*(){{const n=new qt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}removeMessageAction(e,t){return i(this,void 0,void 0,(function*(){{const n=new Gt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}fetchMessages(e,t){return i(this,void 0,void 0,(function*(){{const n=new xt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}deleteMessages(e,t){return i(this,void 0,void 0,(function*(){{const n=new Ft(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}messageCounts(e,t){return i(this,void 0,void 0,(function*(){{const n=new Tt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}history(e,t){return i(this,void 0,void 0,(function*(){{const n=new Rt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}hereNow(e,t){return i(this,void 0,void 0,(function*(){{const n=new It(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}whereNow(e,t){return i(this,void 0,void 0,(function*(){var n;{const s=new jt({uuid:null!==(n=e.uuid)&&void 0!==n?n:this._configuration.userId,keySet:this._configuration.keySet});return t?this.sendRequest(s,t):this.sendRequest(s)}}))}getState(e,t){return i(this,void 0,void 0,(function*(){var n;{const s=new Pt(Object.assign(Object.assign({},e),{uuid:null!==(n=e.uuid)&&void 0!==n?n:this._configuration.userId,keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}setState(e,t){return i(this,void 0,void 0,(function*(){var n,s;{const{keySet:r,userId:i}=this._configuration,a=this._configuration.getPresenceTimeout();let o;if(this._configuration.enableEventEngine&&this.presenceState){const t=this.presenceState;null===(n=e.channels)||void 0===n||n.forEach((n=>t[n]=e.state)),"channelGroups"in e&&(null===(s=e.channelGroups)||void 0===s||s.forEach((n=>t[n]=e.state)))}return o="withHeartbeat"in e?new _t(Object.assign(Object.assign({},e),{keySet:r,heartbeat:a})):new Mt(Object.assign(Object.assign({},e),{keySet:r,uuid:i})),this.subscriptionManager&&this.subscriptionManager.setState(e),t?this.sendRequest(o,t):this.sendRequest(o)}}))}presence(e){var t;null===(t=this.subscriptionManager)||void 0===t||t.changePresence(e)}heartbeat(e,t){return i(this,void 0,void 0,(function*(){{const n=new _t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}join(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.join(e)}leave(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.leave(e)}leaveAll(){var e;null===(e=this.presenceEventEngine)||void 0===e||e.leaveAll()}grantToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Token error: PAM module disabled")}))}revokeToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Revoke Token error: PAM module disabled")}))}get token(){return this.tokenManager&&this.tokenManager.getToken()}getToken(){return this.token}set token(e){this.tokenManager&&this.tokenManager.setToken(e)}setToken(e){this.token=e}parseToken(e){return this.tokenManager&&this.tokenManager.parseToken(e)}grant(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant error: PAM module disabled")}))}audit(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Permissions error: PAM module disabled")}))}get objects(){return this._objects}fetchUsers(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllUUIDMetadata(e,t)}))}fetchUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getUUIDMetadata(e,t)}))}createUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}updateUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}removeUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeUUIDMetadata(e,t)}))}fetchSpaces(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllChannelMetadata(e,t)}))}fetchSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getChannelMetadata(e,t)}))}createSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}updateSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}removeSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeChannelMetadata(e,t)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.fetchMemberships(e,t)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}updateMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var n,s,r;{if("spaceId"in e){const r=e,i={channel:null!==(n=r.spaceId)&&void 0!==n?n:r.channel,uuids:null!==(s=r.userIds)&&void 0!==s?s:r.uuids,limit:0};return t?this.objects.removeChannelMembers(i,t):this.objects.removeChannelMembers(i)}const i=e,a={uuid:i.userId,channels:null!==(r=i.spaceIds)&&void 0!==r?r:i.channels,limit:0};return t?this.objects.removeMemberships(a,t):this.objects.removeMemberships(a)}}))}get channelGroups(){return this._channelGroups}get push(){return this._push}sendFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const n=new zt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,fileUploadPublishRetryLimit:this._configuration.fileUploadPublishRetryLimit,file:e.file,sendRequest:this.sendRequest.bind(this),publishFile:this.publishFile.bind(this),crypto:this._configuration.getCryptoModule(),cryptography:this.cryptography?this.cryptography:void 0})),s={error:!1,operation:ie.PNPublishFileOperation,category:h.PNAcknowledgmentCategory,statusCode:0};return n.process().then((e=>(s.statusCode=e.status,t?t(s,e):e))).catch((e=>{let n;throw e instanceof d?n=e.status:e instanceof j&&(n=e.toStatus(s.operation)),t&&n&&t(n,null),new d("REST API request processing error, check status for details",n)}))}}))}publishFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const n=new Kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}listFiles(e,t){return i(this,void 0,void 0,(function*(){{const n=new Bt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}getFileUrl(e){var t;{const n=this.transport.request(new $t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})).request()),s=null!==(t=n.queryParameters)&&void 0!==t?t:{},r=Object.keys(s).map((e=>{const t=s[e];return Array.isArray(t)?t.map((t=>`${e}=${$(t)}`)).join("&"):`${e}=${$(t)}`})).join("&");return`${n.origin}${n.path}?${r}`}}downloadFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const n=new Mn(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,cryptography:this.cryptography?this.cryptography:void 0,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(n,t):yield this.sendRequest(n)}}))}deleteFile(e,t){return i(this,void 0,void 0,(function*(){{const n=new Lt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}time(e){return i(this,void 0,void 0,(function*(){const t=new Pn;return e?this.sendRequest(t,e):this.sendRequest(t)}))}encrypt(e,t){const n=this._configuration.getCryptoModule();if(!t&&n&&"string"==typeof e){const t=n.encrypt(e);return"string"==typeof t?t:u(t)}if(!this.crypto)throw new Error("Encryption error: cypher key not set");return this.crypto.encrypt(e,t)}decrypt(e,t){const n=this._configuration.getCryptoModule();if(!t&&n){const t=n.decrypt(e);return t instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(t)):t}if(!this.crypto)throw new Error("Decryption error: cypher key not set");return this.crypto.decrypt(e,t)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var n;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File encryption error. File constructor not configured.");if("string"!=typeof e&&!this._configuration.getCryptoModule())throw new Error("File encryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File encryption error. File encryption not available");return this.cryptography.encryptFile(e,t,this._configuration.PubNubFile)}return null===(n=this._configuration.getCryptoModule())||void 0===n?void 0:n.encryptFile(t,this._configuration.PubNubFile)}))}decryptFile(e,t){return i(this,void 0,void 0,(function*(){var n;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File decryption error. File constructor not configured.");if("string"==typeof e&&!this._configuration.getCryptoModule())throw new Error("File decryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File decryption error. File decryption not available");return this.cryptography.decryptFile(e,t,this._configuration.PubNubFile)}return null===(n=this._configuration.getCryptoModule())||void 0===n?void 0:n.decryptFile(t,this._configuration.PubNubFile)}))}}_n.decoder=new TextDecoder,_n.OPERATIONS=ie,_n.CATEGORIES=h,_n.ExponentialRetryPolicy=Be.ExponentialRetryPolicy,_n.LinearRetryPolicy=Be.LinearRetryPolicy;class An{constructor(e,t){this.decode=e,this.base64ToBinary=t}decodeToken(e){let t="";e.length%4==3?t="=":e.length%4==2&&(t="==");const n=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,s=this.decode(this.base64ToBinary(n));return"object"==typeof s?s:void 0}}class jn extends _n{constructor(e){var t;const n=T(e),r=Object.assign(Object.assign({},n),{sdkFamily:"Web"});r.PubNubFile=o;const i=D(r,(e=>{if(e.cipherKey)return new M({default:new P(Object.assign({},e)),cryptors:[new O({cipherKey:e.cipherKey})]})}));let a,u,l;a=new G(new An((e=>F(s.decode(e))),c)),(i.getCipherKey()||i.secretKey)&&(u=new C({secretKey:i.secretKey,cipherKey:i.getCipherKey(),useRandomIVs:i.getUseRandomIVs(),customEncrypt:i.getCustomEncrypt(),customDecrypt:i.getCustomDecrypt()})),l=new N;let h=new W(r.transport,i.keepAlive,i.logVerbosity);n.subscriptionWorkerUrl&&(h=new I({clientIdentifier:i._instanceId,subscriptionKey:i.subscribeKey,userId:i.getUserId(),workerUrl:n.subscriptionWorkerUrl,sdkVersion:i.getVersion(),heartbeatInterval:i.getHeartbeatInterval(),logVerbosity:i.logVerbosity,workerLogVerbosity:r.subscriptionWorkerLogVerbosity,transport:h}));super({configuration:i,transport:new z({clientConfiguration:i,tokenManager:a,transport:h}),cryptography:l,tokenManager:a,crypto:u}),(null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t)&&(window.addEventListener("offline",(()=>{this.networkDownDetected()})),window.addEventListener("online",(()=>{this.networkUpDetected()})))}networkDownDetected(){this.listenerManager.announceNetworkDown(),this._configuration.restore?this.disconnect():this.destroy(!0)}networkUpDetected(){this.listenerManager.announceNetworkUp(),this.reconnect()}}return jn.CryptoModule=M,jn})); +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).PubNub=t()}(this,(function(){"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n={exports:{}};!function(t){!function(e,n){var s=Math.pow(2,-24),r=Math.pow(2,32),i=Math.pow(2,53);var a={encode:function(e){var t,s=new ArrayBuffer(256),a=new DataView(s),o=0;function c(e){for(var n=s.byteLength,r=o+e;n>2,u=0;u>6),r.push(128|63&a)):a<55296?(r.push(224|a>>12),r.push(128|a>>6&63),r.push(128|63&a)):(a=(1023&a)<<10,a|=1023&t.charCodeAt(++s),a+=65536,r.push(240|a>>18),r.push(128|a>>12&63),r.push(128|a>>6&63),r.push(128|63&a))}return d(3,r.length),h(r);default:var p;if(Array.isArray(t))for(d(4,p=t.length),s=0;s>5!==e)throw"Invalid indefinite length element";return n}function f(e,t){for(var n=0;n>10),e.push(56320|1023&s))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof i&&(i=function(){return n});var m=function e(){var r,d,m=l(),b=m>>5,v=31&m;if(7===b)switch(v){case 25:return function(){var e=new ArrayBuffer(4),t=new DataView(e),n=h(),r=32768&n,i=31744&n,a=1023&n;if(31744===i)i=261120;else if(0!==i)i+=114688;else if(0!==a)return a*s;return t.setUint32(0,r<<16|i<<13|a<<13),t.getFloat32(0)}();case 26:return c(a.getFloat32(o),4);case 27:return c(a.getFloat64(o),8)}if((d=g(v))<0&&(b<2||6=0;)S+=d,w.push(u(d));var E=new Uint8Array(S),O=0;for(r=0;r=0;)f(k,d);else f(k,d);return String.fromCharCode.apply(null,k);case 4:var C;if(d<0)for(C=[];!p();)C.push(e());else for(C=new Array(d),r=0;r{const n=new FileReader;n.addEventListener("load",(()=>{if(n.result instanceof ArrayBuffer)return e(n.result)})),n.addEventListener("error",(()=>t(n.error))),n.readAsArrayBuffer(this.data)}))}))}toString(){return i(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const n=new FileReader;n.addEventListener("load",(()=>{if("string"==typeof n.result)return e(n.result)})),n.addEventListener("error",(()=>{t(n.error)})),n.readAsBinaryString(this.data)}))}))}toStream(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in Node.js environments.")}))}toFile(){return i(this,void 0,void 0,(function*(){return this.data}))}toFileUri(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in React Native environments.")}))}toBlob(){return i(this,void 0,void 0,(function*(){return this.data}))}}o.supportsBlob="undefined"!=typeof Blob,o.supportsFile="undefined"!=typeof File,o.supportsBuffer=!1,o.supportsStream=!1,o.supportsString=!0,o.supportsArrayBuffer=!0,o.supportsEncryptFile=!0,o.supportsFileUri=!1;function c(e){const t=e.replace(/==?$/,""),n=Math.floor(t.length/4*3),s=new ArrayBuffer(n),r=new Uint8Array(s);let i=0;function a(){const e=t.charAt(i++),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e);if(-1===n)throw new Error(`Illegal character at ${i}: ${t.charAt(i-1)}`);return n}for(let e=0;e>4,c=(15&n)<<4|s>>2,u=(3&s)<<6|i;r[e]=o,64!=s&&(r[e+1]=c),64!=i&&(r[e+2]=u)}return s}function u(e){let t="";const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=new Uint8Array(e),r=s.byteLength,i=r%3,a=r-i;let o,c,u,l,h;for(let e=0;e>18,c=(258048&h)>>12,u=(4032&h)>>6,l=63&h,t+=n[o]+n[c]+n[u]+n[l];return 1==i?(h=s[a],o=(252&h)>>2,c=(3&h)<<4,t+=n[o]+n[c]+"=="):2==i&&(h=s[a]<<8|s[a+1],o=(64512&h)>>10,c=(1008&h)>>4,u=(15&h)<<2,t+=n[o]+n[c]+n[u]+"="),t}var l;!function(e){e.PNNetworkIssuesCategory="PNNetworkIssuesCategory",e.PNTimeoutCategory="PNTimeoutCategory",e.PNCancelledCategory="PNCancelledCategory",e.PNBadRequestCategory="PNBadRequestCategory",e.PNAccessDeniedCategory="PNAccessDeniedCategory",e.PNValidationErrorCategory="PNValidationErrorCategory",e.PNAcknowledgmentCategory="PNAcknowledgmentCategory",e.PNMalformedResponseCategory="PNMalformedResponseCategory",e.PNUnknownCategory="PNUnknownCategory",e.PNNetworkUpCategory="PNNetworkUpCategory",e.PNNetworkDownCategory="PNNetworkDownCategory",e.PNReconnectedCategory="PNReconnectedCategory",e.PNConnectedCategory="PNConnectedCategory",e.PNRequestMessageCountExceededCategory="PNRequestMessageCountExceededCategory",e.PNDisconnectedCategory="PNDisconnectedCategory",e.PNConnectionErrorCategory="PNConnectionErrorCategory",e.PNDisconnectedUnexpectedlyCategory="PNDisconnectedUnexpectedlyCategory"}(l||(l={}));var h=l;class d extends Error{constructor(e,t){super(e),this.status=t,this.name="PubNubError",this.message=e,Object.setPrototypeOf(this,new.target.prototype)}}function p(e,t){var n;return null!==(n=e.statusCode)&&void 0!==n||(e.statusCode=0),Object.assign(Object.assign({},e),{statusCode:e.statusCode,category:t,error:!0})}function g(e,t){return p(Object.assign({message:e},{}),h.PNValidationErrorCategory)}function y(e,t){return p(Object.assign(Object.assign({message:"Unable to deserialize service response"},void 0!==e?{responseText:e}:{}),void 0!==t?{statusCode:t}:{}),h.PNMalformedResponseCategory)}var f,m,b,v,w,S=S||function(e){var t={},n=t.lib={},s=function(){},r=n.Base={extend:function(e){s.prototype=this;var t=new s;return e&&t.mixIn(e),t.hasOwnProperty("init")||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},i=n.WordArray=r.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||o).stringify(this)},concat:function(e){var t=this.words,n=e.words,s=this.sigBytes;if(e=e.sigBytes,this.clamp(),s%4)for(var r=0;r>>2]|=(n[r>>>2]>>>24-r%4*8&255)<<24-(s+r)%4*8;else if(65535>>2]=n[r>>>2];else t.push.apply(t,n);return this.sigBytes+=e,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=r.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n=[],s=0;s>>2]>>>24-s%4*8&255;n.push((r>>>4).toString(16)),n.push((15&r).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,n=[],s=0;s>>3]|=parseInt(e.substr(s,2),16)<<24-s%8*4;return new i.init(n,t/2)}},c=a.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],s=0;s>>2]>>>24-s%4*8&255));return n.join("")},parse:function(e){for(var t=e.length,n=[],s=0;s>>2]|=(255&e.charCodeAt(s))<<24-s%4*8;return new i.init(n,t)}},u=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},l=n.BufferedBlockAlgorithm=r.extend({reset:function(){this._data=new i.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=u.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,s=n.words,r=n.sigBytes,a=this.blockSize,o=r/(4*a);if(t=(o=t?e.ceil(o):e.max((0|o)-this._minBufferSize,0))*a,r=e.min(4*t,r),t){for(var c=0;cu;){var l;e:{l=c;for(var h=e.sqrt(l),d=2;d<=h;d++)if(!(l%d)){l=!1;break e}l=!0}l&&(8>u&&(i[u]=o(e.pow(c,.5))),a[u]=o(e.pow(c,1/3)),u++),c++}var p=[];r=r.SHA256=s.extend({_doReset:function(){this._hash=new n.init(i.slice(0))},_doProcessBlock:function(e,t){for(var n=this._hash.words,s=n[0],r=n[1],i=n[2],o=n[3],c=n[4],u=n[5],l=n[6],h=n[7],d=0;64>d;d++){if(16>d)p[d]=0|e[t+d];else{var g=p[d-15],y=p[d-2];p[d]=((g<<25|g>>>7)^(g<<14|g>>>18)^g>>>3)+p[d-7]+((y<<15|y>>>17)^(y<<13|y>>>19)^y>>>10)+p[d-16]}g=h+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&u^~c&l)+a[d]+p[d],y=((s<<30|s>>>2)^(s<<19|s>>>13)^(s<<10|s>>>22))+(s&r^s&i^r&i),h=l,l=u,u=c,c=o+g|0,o=i,i=r,r=s,s=g+y|0}n[0]=n[0]+s|0,n[1]=n[1]+r|0,n[2]=n[2]+i|0,n[3]=n[3]+o|0,n[4]=n[4]+c|0,n[5]=n[5]+u|0,n[6]=n[6]+l|0,n[7]=n[7]+h|0},_doFinalize:function(){var t=this._data,n=t.words,s=8*this._nDataBytes,r=8*t.sigBytes;return n[r>>>5]|=128<<24-r%32,n[14+(r+64>>>9<<4)]=e.floor(s/4294967296),n[15+(r+64>>>9<<4)]=s,t.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var e=s.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=s._createHelper(r),t.HmacSHA256=s._createHmacHelper(r)}(Math),m=(f=S).enc.Utf8,f.algo.HMAC=f.lib.Base.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=m.parse(t));var n=e.blockSize,s=4*n;t.sigBytes>s&&(t=e.finalize(t)),t.clamp();for(var r=this._oKey=t.clone(),i=this._iKey=t.clone(),a=r.words,o=i.words,c=0;c>>2]>>>24-r%4*8&255)<<16|(t[r+1>>>2]>>>24-(r+1)%4*8&255)<<8|t[r+2>>>2]>>>24-(r+2)%4*8&255,a=0;4>a&&r+.75*a>>6*(3-a)&63));if(t=s.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var t=e.length,n=this._map;(s=n.charAt(64))&&-1!=(s=e.indexOf(s))&&(t=s);for(var s=[],r=0,i=0;i>>6-i%4*2;s[r>>>2]|=(a|o)<<24-r%4*8,r++}return v.create(s,r)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},function(e){function t(e,t,n,s,r,i,a){return((e=e+(t&n|~t&s)+r+a)<>>32-i)+t}function n(e,t,n,s,r,i,a){return((e=e+(t&s|n&~s)+r+a)<>>32-i)+t}function s(e,t,n,s,r,i,a){return((e=e+(t^n^s)+r+a)<>>32-i)+t}function r(e,t,n,s,r,i,a){return((e=e+(n^(t|~s))+r+a)<>>32-i)+t}for(var i=S,a=(c=i.lib).WordArray,o=c.Hasher,c=i.algo,u=[],l=0;64>l;l++)u[l]=4294967296*e.abs(e.sin(l+1))|0;c=c.MD5=o.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,i){for(var a=0;16>a;a++){var o=e[c=i+a];e[c]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8)}a=this._hash.words;var c=e[i+0],l=(o=e[i+1],e[i+2]),h=e[i+3],d=e[i+4],p=e[i+5],g=e[i+6],y=e[i+7],f=e[i+8],m=e[i+9],b=e[i+10],v=e[i+11],w=e[i+12],S=e[i+13],E=e[i+14],O=e[i+15],k=t(k=a[0],P=a[1],N=a[2],C=a[3],c,7,u[0]),C=t(C,k,P,N,o,12,u[1]),N=t(N,C,k,P,l,17,u[2]),P=t(P,N,C,k,h,22,u[3]);k=t(k,P,N,C,d,7,u[4]),C=t(C,k,P,N,p,12,u[5]),N=t(N,C,k,P,g,17,u[6]),P=t(P,N,C,k,y,22,u[7]),k=t(k,P,N,C,f,7,u[8]),C=t(C,k,P,N,m,12,u[9]),N=t(N,C,k,P,b,17,u[10]),P=t(P,N,C,k,v,22,u[11]),k=t(k,P,N,C,w,7,u[12]),C=t(C,k,P,N,S,12,u[13]),N=t(N,C,k,P,E,17,u[14]),k=n(k,P=t(P,N,C,k,O,22,u[15]),N,C,o,5,u[16]),C=n(C,k,P,N,g,9,u[17]),N=n(N,C,k,P,v,14,u[18]),P=n(P,N,C,k,c,20,u[19]),k=n(k,P,N,C,p,5,u[20]),C=n(C,k,P,N,b,9,u[21]),N=n(N,C,k,P,O,14,u[22]),P=n(P,N,C,k,d,20,u[23]),k=n(k,P,N,C,m,5,u[24]),C=n(C,k,P,N,E,9,u[25]),N=n(N,C,k,P,h,14,u[26]),P=n(P,N,C,k,f,20,u[27]),k=n(k,P,N,C,S,5,u[28]),C=n(C,k,P,N,l,9,u[29]),N=n(N,C,k,P,y,14,u[30]),k=s(k,P=n(P,N,C,k,w,20,u[31]),N,C,p,4,u[32]),C=s(C,k,P,N,f,11,u[33]),N=s(N,C,k,P,v,16,u[34]),P=s(P,N,C,k,E,23,u[35]),k=s(k,P,N,C,o,4,u[36]),C=s(C,k,P,N,d,11,u[37]),N=s(N,C,k,P,y,16,u[38]),P=s(P,N,C,k,b,23,u[39]),k=s(k,P,N,C,S,4,u[40]),C=s(C,k,P,N,c,11,u[41]),N=s(N,C,k,P,h,16,u[42]),P=s(P,N,C,k,g,23,u[43]),k=s(k,P,N,C,m,4,u[44]),C=s(C,k,P,N,w,11,u[45]),N=s(N,C,k,P,O,16,u[46]),k=r(k,P=s(P,N,C,k,l,23,u[47]),N,C,c,6,u[48]),C=r(C,k,P,N,y,10,u[49]),N=r(N,C,k,P,E,15,u[50]),P=r(P,N,C,k,p,21,u[51]),k=r(k,P,N,C,w,6,u[52]),C=r(C,k,P,N,h,10,u[53]),N=r(N,C,k,P,b,15,u[54]),P=r(P,N,C,k,o,21,u[55]),k=r(k,P,N,C,f,6,u[56]),C=r(C,k,P,N,O,10,u[57]),N=r(N,C,k,P,g,15,u[58]),P=r(P,N,C,k,S,21,u[59]),k=r(k,P,N,C,d,6,u[60]),C=r(C,k,P,N,v,10,u[61]),N=r(N,C,k,P,l,15,u[62]),P=r(P,N,C,k,m,21,u[63]);a[0]=a[0]+k|0,a[1]=a[1]+P|0,a[2]=a[2]+N|0,a[3]=a[3]+C|0},_doFinalize:function(){var t=this._data,n=t.words,s=8*this._nDataBytes,r=8*t.sigBytes;n[r>>>5]|=128<<24-r%32;var i=e.floor(s/4294967296);for(n[15+(r+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),n[14+(r+64>>>9<<4)]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),t.sigBytes=4*(n.length+1),this._process(),n=(t=this._hash).words,s=0;4>s;s++)r=n[s],n[s]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8);return t},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}}),i.MD5=o._createHelper(c),i.HmacMD5=o._createHmacHelper(c)}(Math),function(){var e,t=S,n=(e=t.lib).Base,s=e.WordArray,r=(e=t.algo).EvpKDF=n.extend({cfg:n.extend({keySize:4,hasher:e.MD5,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var n=(o=this.cfg).hasher.create(),r=s.create(),i=r.words,a=o.keySize,o=o.iterations;i.length>>2]}},e.BlockCipher=a.extend({cfg:a.cfg.extend({mode:o,padding:u}),reset:function(){a.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var n=t.createEncryptor;else n=t.createDecryptor,this._minBufferSize=1;this._mode=n.call(t,this,e&&e.words)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else t=this._process(!0),e.unpad(t);return t},blockSize:4});var l=e.CipherParams=t.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),h=(o=(d.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?n.create([1398893684,1701076831]).concat(e).concat(t):t).toString(r)},parse:function(e){var t=(e=r.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var s=n.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return l.create({ciphertext:e,salt:s})}},e.SerializableCipher=t.extend({cfg:t.extend({format:o}),encrypt:function(e,t,n,s){s=this.cfg.extend(s);var r=e.createEncryptor(n,s);return t=r.finalize(t),r=r.cfg,l.create({ciphertext:t,key:n,iv:r.iv,algorithm:e,mode:r.mode,padding:r.padding,blockSize:e.blockSize,formatter:s.format})},decrypt:function(e,t,n,s){return s=this.cfg.extend(s),t=this._parse(t,s.format),e.createDecryptor(n,s).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),d=(d.kdf={}).OpenSSL={execute:function(e,t,s,r){return r||(r=n.random(8)),e=i.create({keySize:t+s}).compute(e,r),s=n.create(e.words.slice(t),4*s),e.sigBytes=4*t,l.create({key:e,iv:s,salt:r})}},p=e.PasswordBasedCipher=h.extend({cfg:h.cfg.extend({kdf:d}),encrypt:function(e,t,n,s){return n=(s=this.cfg.extend(s)).kdf.execute(n,e.keySize,e.ivSize),s.iv=n.iv,(e=h.encrypt.call(this,e,t,n.key,s)).mixIn(n),e},decrypt:function(e,t,n,s){return s=this.cfg.extend(s),t=this._parse(t,s.format),n=s.kdf.execute(n,e.keySize,e.ivSize,t.salt),s.iv=n.iv,h.decrypt.call(this,e,t,n.key,s)}})}(),function(){for(var e=S,t=e.lib.BlockCipher,n=e.algo,s=[],r=[],i=[],a=[],o=[],c=[],u=[],l=[],h=[],d=[],p=[],g=0;256>g;g++)p[g]=128>g?g<<1:g<<1^283;var y=0,f=0;for(g=0;256>g;g++){var m=(m=f^f<<1^f<<2^f<<3^f<<4)>>>8^255&m^99;s[y]=m,r[m]=y;var b=p[y],v=p[b],w=p[v],E=257*p[m]^16843008*m;i[y]=E<<24|E>>>8,a[y]=E<<16|E>>>16,o[y]=E<<8|E>>>24,c[y]=E,E=16843009*w^65537*v^257*b^16843008*y,u[m]=E<<24|E>>>8,l[m]=E<<16|E>>>16,h[m]=E<<8|E>>>24,d[m]=E,y?(y=b^p[p[p[w^b]]],f^=p[p[f]]):y=f=1}var O=[0,1,2,4,8,16,32,64,128,27,54];n=n.AES=t.extend({_doReset:function(){for(var e=(n=this._key).words,t=n.sigBytes/4,n=4*((this._nRounds=t+6)+1),r=this._keySchedule=[],i=0;i>>24]<<24|s[a>>>16&255]<<16|s[a>>>8&255]<<8|s[255&a]):(a=s[(a=a<<8|a>>>24)>>>24]<<24|s[a>>>16&255]<<16|s[a>>>8&255]<<8|s[255&a],a^=O[i/t|0]<<24),r[i]=r[i-t]^a}for(e=this._invKeySchedule=[],t=0;tt||4>=i?a:u[s[a>>>24]]^l[s[a>>>16&255]]^h[s[a>>>8&255]]^d[s[255&a]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,i,a,o,c,s)},decryptBlock:function(e,t){var n=e[t+1];e[t+1]=e[t+3],e[t+3]=n,this._doCryptBlock(e,t,this._invKeySchedule,u,l,h,d,r),n=e[t+1],e[t+1]=e[t+3],e[t+3]=n},_doCryptBlock:function(e,t,n,s,r,i,a,o){for(var c=this._nRounds,u=e[t]^n[0],l=e[t+1]^n[1],h=e[t+2]^n[2],d=e[t+3]^n[3],p=4,g=1;g>>24]^r[l>>>16&255]^i[h>>>8&255]^a[255&d]^n[p++],f=s[l>>>24]^r[h>>>16&255]^i[d>>>8&255]^a[255&u]^n[p++],m=s[h>>>24]^r[d>>>16&255]^i[u>>>8&255]^a[255&l]^n[p++];d=s[d>>>24]^r[u>>>16&255]^i[l>>>8&255]^a[255&h]^n[p++],u=y,l=f,h=m}y=(o[u>>>24]<<24|o[l>>>16&255]<<16|o[h>>>8&255]<<8|o[255&d])^n[p++],f=(o[l>>>24]<<24|o[h>>>16&255]<<16|o[d>>>8&255]<<8|o[255&u])^n[p++],m=(o[h>>>24]<<24|o[d>>>16&255]<<16|o[u>>>8&255]<<8|o[255&l])^n[p++],d=(o[d>>>24]<<24|o[u>>>16&255]<<16|o[l>>>8&255]<<8|o[255&h])^n[p++],e[t]=y,e[t+1]=f,e[t+2]=m,e[t+3]=d},keySize:8});e.AES=t._createHelper(n)}(),S.mode.ECB=((w=S.lib.BlockCipherMode.extend()).Encryptor=w.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),w.Decryptor=w.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),w);var E=t(S);class O{constructor({cipherKey:e}){this.cipherKey=e,this.CryptoJS=E,this.encryptedKey=this.CryptoJS.SHA256(e)}encrypt(e){if(0===("string"==typeof e?e:O.decoder.decode(e)).length)throw new Error("encryption error. empty content");const t=this.getIv();return{metadata:t,data:c(this.CryptoJS.AES.encrypt(e,this.encryptedKey,{iv:this.bufferToWordArray(t),mode:this.CryptoJS.mode.CBC}).ciphertext.toString(this.CryptoJS.enc.Base64))}}encryptFileData(e){return i(this,void 0,void 0,(function*(){const t=yield this.getKey(),n=this.getIv();return{data:yield crypto.subtle.encrypt({name:this.algo,iv:n},t,e),metadata:n}}))}decrypt(e){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=this.bufferToWordArray(new Uint8ClampedArray(e.metadata)),n=this.bufferToWordArray(new Uint8ClampedArray(e.data));return O.encoder.encode(this.CryptoJS.AES.decrypt({ciphertext:n},this.encryptedKey,{iv:t,mode:this.CryptoJS.mode.CBC}).toString(this.CryptoJS.enc.Utf8)).buffer}decryptFileData(e){return i(this,void 0,void 0,(function*(){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=yield this.getKey();return crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)}))}get identifier(){return"ACRH"}get algo(){return"AES-CBC"}getIv(){return crypto.getRandomValues(new Uint8Array(O.BLOCK_SIZE))}getKey(){return i(this,void 0,void 0,(function*(){const e=O.encoder.encode(this.cipherKey),t=yield crypto.subtle.digest("SHA-256",e.buffer);return crypto.subtle.importKey("raw",t,this.algo,!0,["encrypt","decrypt"])}))}bufferToWordArray(e){const t=[];let n;for(n=0;ne.toString(16).padStart(2,"0"))).join(""),s=N.encoder.encode(n.slice(0,32)).buffer;return crypto.subtle.importKey("raw",s,"AES-CBC",!0,["encrypt","decrypt"])}))}concatArrayBuffer(e,t){const n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}}N.IV_LENGTH=16,N.encoder=new TextEncoder,N.decoder=new TextDecoder;class P{constructor(e){this.config=e,this.cryptor=new C(Object.assign({},e)),this.fileCryptor=new N}encrypt(e){const t="string"==typeof e?e:P.decoder.decode(e);return{data:this.cryptor.encrypt(t),metadata:null}}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var n;if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.encryptFile(null===(n=this.config)||void 0===n?void 0:n.cipherKey,e,t)}))}decrypt(e){const t="string"==typeof e.data?e.data:u(e.data);return this.cryptor.decrypt(t)}decryptFile(e,t){return i(this,void 0,void 0,(function*(){if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.decryptFile(this.config.cipherKey,e,t)}))}get identifier(){return""}}P.encoder=new TextEncoder,P.decoder=new TextDecoder;class M extends a{static legacyCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new M({default:new P(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t})),cryptors:[new O({cipherKey:e.cipherKey})]})}static aesCbcCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new M({default:new O({cipherKey:e.cipherKey}),cryptors:[new P(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t}))]})}static withDefaultCryptor(e){return new this({default:e})}encrypt(e){const t=e instanceof ArrayBuffer&&this.defaultCryptor.identifier===M.LEGACY_IDENTIFIER?this.defaultCryptor.encrypt(M.decoder.decode(e)):this.defaultCryptor.encrypt(e);if(!t.metadata)return t.data;if("string"==typeof t.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");const n=this.getHeaderData(t);return this.concatArrayBuffer(n,t.data)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){if(this.defaultCryptor.identifier===_.LEGACY_IDENTIFIER)return this.defaultCryptor.encryptFile(e,t);const n=yield this.getFileData(e),s=yield this.defaultCryptor.encryptFileData(n);if("string"==typeof s.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");return t.create({name:e.name,mimeType:"application/octet-stream",data:this.concatArrayBuffer(this.getHeaderData(s),s.data)})}))}decrypt(e){const t="string"==typeof e?c(e):e,n=_.tryParse(t),s=this.getCryptor(n),r=n.length>0?t.slice(n.length-n.metadataLength,n.length):null;if(t.slice(n.length).byteLength<=0)throw new Error("Decryption error: empty content");return s.decrypt({data:t.slice(n.length),metadata:r})}decryptFile(e,t){return i(this,void 0,void 0,(function*(){const n=yield e.data.arrayBuffer(),s=_.tryParse(n),r=this.getCryptor(s);if((null==r?void 0:r.identifier)===_.LEGACY_IDENTIFIER)return r.decryptFile(e,t);const i=(yield this.getFileData(n)).slice(s.length-s.metadataLength,s.length);return t.create({name:e.name,data:yield this.defaultCryptor.decryptFileData({data:n.slice(s.length),metadata:i})})}))}getCryptorFromId(e){const t=this.getAllCryptors().find((t=>e===t.identifier));if(t)return t;throw Error("Unknown cryptor error")}getCryptor(e){if("string"==typeof e){const t=this.getAllCryptors().find((t=>t.identifier===e));if(t)return t;throw new Error("Unknown cryptor error")}if(e instanceof j)return this.getCryptorFromId(e.identifier)}getHeaderData(e){if(!e.metadata)return;const t=_.from(this.defaultCryptor.identifier,e.metadata),n=new Uint8Array(t.length);let s=0;return n.set(t.data,s),s+=t.length-e.metadata.byteLength,n.set(new Uint8Array(e.metadata),s),n.buffer}concatArrayBuffer(e,t){const n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}getFileData(e){return i(this,void 0,void 0,(function*(){if(e instanceof ArrayBuffer)return e;if(e instanceof o)return e.toArrayBuffer();throw new Error("Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob")}))}}M.LEGACY_IDENTIFIER="";class _{static from(e,t){if(e!==_.LEGACY_IDENTIFIER)return new j(e,t.byteLength)}static tryParse(e){const t=new Uint8Array(e);let n,s,r=null;if(t.byteLength>=4&&(n=t.slice(0,4),this.decoder.decode(n)!==_.SENTINEL))return M.LEGACY_IDENTIFIER;if(!(t.byteLength>=5))throw new Error("Decryption error: invalid header version");if(r=t[4],r>_.MAX_VERSION)throw new Error("Decryption error: Unknown cryptor error");let i=5+_.IDENTIFIER_LENGTH;if(!(t.byteLength>=i))throw new Error("Decryption error: invalid crypto identifier");s=t.slice(5,i);let a=null;if(!(t.byteLength>=i+1))throw new Error("Decryption error: invalid metadata length");return a=t[i],i+=1,255===a&&t.byteLength>=i+2&&(a=new Uint16Array(t.slice(i,i+2)).reduce(((e,t)=>(e<<8)+t),0)),new j(this.decoder.decode(s),a)}}_.SENTINEL="PNED",_.LEGACY_IDENTIFIER="",_.IDENTIFIER_LENGTH=4,_.VERSION=1,_.MAX_VERSION=1,_.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 _.VERSION}get length(){return _.SENTINEL.length+1+_.IDENTIFIER_LENGTH+(this.metadataLength<255?1:3)+this.metadataLength}get data(){let e=0;const t=new Uint8Array(this.length),n=new TextEncoder;t.set(n.encode(_.SENTINEL)),e+=_.SENTINEL.length,t[e]=this.version,e++,this.identifier&&t.set(n.encode(this.identifier),e);const s=this.metadataLength;return e+=_.IDENTIFIER_LENGTH,s<255?t[e]=s:t.set([255,s>>8,255&s],e),t}}j.IDENTIFIER_LENGTH=4,j.SENTINEL="PNED";class A extends Error{static create(e,t){return e instanceof Error?A.createFromError(e):A.createFromServiceResponse(e,t)}static createFromError(e){let t=h.PNUnknownCategory,n="Unknown error",s="Error";if(!e)return new A(n,t,0);if(e instanceof A)return e;if(e instanceof Error&&(n=e.message,s=e.name),"AbortError"===s||-1!==n.indexOf("Aborted"))t=h.PNCancelledCategory,n="Request cancelled";else if(-1!==n.toLowerCase().indexOf("timeout"))t=h.PNTimeoutCategory,n="Request timeout";else if(-1!==n.toLowerCase().indexOf("network"))t=h.PNNetworkIssuesCategory,n="Network issues";else if("TypeError"===s)t=-1!==n.indexOf("Load failed")||-1!=n.indexOf("Failed to fetch")?h.PNNetworkIssuesCategory:h.PNBadRequestCategory;else if("FetchError"===s){const s=e.code;["ECONNREFUSED","ENETUNREACH","ENOTFOUND","ECONNRESET","EAI_AGAIN"].includes(s)&&(t=h.PNNetworkIssuesCategory),"ECONNREFUSED"===s?n="Connection refused":"ENETUNREACH"===s?n="Network not reachable":"ENOTFOUND"===s?n="Server not found":"ECONNRESET"===s?n="Connection reset by peer":"EAI_AGAIN"===s?n="Name resolution error":"ETIMEDOUT"===s?(t=h.PNTimeoutCategory,n="Request timeout"):n=`Unknown system error: ${e}`}else"Request timeout"===n&&(t=h.PNTimeoutCategory);return new A(n,t,0,e)}static createFromServiceResponse(e,t){let n,s=h.PNUnknownCategory,r="Unknown error",{status:i}=e;if(null!=t||(t=e.body),402===i?r="Not available for used key set. Contact support@pubnub.com":400===i?(s=h.PNBadRequestCategory,r="Bad request"):403===i&&(s=h.PNAccessDeniedCategory,r="Access denied"),"object"==typeof e&&0===Object.keys(e).length&&(s=h.PNMalformedResponseCategory,r="Malformed response (network issues)",i=400),t&&t.byteLength>0){const s=(new TextDecoder).decode(t);if(-1!==e.headers["content-type"].indexOf("text/javascript")||-1!==e.headers["content-type"].indexOf("application/json"))try{const e=JSON.parse(s);"object"==typeof e&&(Array.isArray(e)?"number"==typeof e[0]&&0===e[0]&&e.length>1&&"string"==typeof e[1]&&(n=e[1]):("error"in e&&(1===e.error||!0===e.error)&&"status"in e&&"number"==typeof e.status&&"message"in e&&"service"in e?(n=e,i=e.status):n=e,"error"in e&&e.error instanceof Error&&(n=e.error)))}catch(e){n=s}else if(-1!==e.headers["content-type"].indexOf("xml")){const e=/(.*)<\/Message>/gi.exec(s);r=e?`Upload to bucket failed: ${e[1]}`:"Upload to bucket failed."}else n=s}return new A(r,s,i,n)}constructor(e,t,n,s){super(e),this.category=t,this.statusCode=n,this.errorData=s,this.name="PubNubAPIError"}toStatus(e){return{error:!0,category:this.category,operation:e,statusCode:this.statusCode,errorData:this.errorData,toJSON:function(){let e;const t=this.errorData;if(t)try{if("object"==typeof t){const n=Object.assign(Object.assign(Object.assign(Object.assign({},"name"in t?{name:t.name}:{}),"message"in t?{message:t.message}:{}),"stack"in t?{stack:t.stack}:{}),t);e=JSON.parse(JSON.stringify(n,A.circularReplacer()))}else e=t}catch(t){e={error:"Could not serialize the error object"}}const n=r(this,["toJSON"]);return JSON.stringify(Object.assign(Object.assign({},n),{errorData:e}))}}}toPubNubError(e,t){return new d(null!=t?t:this.message,this.toStatus(e))}static circularReplacer(){const e=new WeakSet;return function(t,n){if("object"==typeof n&&null!==n){if(e.has(n))return"[Circular]";e.add(n)}return n}}}class I{constructor(e){this.configuration=e,this.subscriptionWorkerReady=!1,this.workerEventsQueue=[],this.callbacks=new Map,this.setupSubscriptionWorker()}makeSendable(e){if(!e.path.startsWith("/v2/subscribe")&&!e.path.endsWith("/heartbeat")&&!e.path.endsWith("/leave"))return this.configuration.transport.makeSendable(e);let t;const n={type:"send-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,request:e};return e.cancellable&&(t={abort:()=>{const t={type:"cancel-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,identifier:e.identifier};this.scheduleEventPost(t)}}),[new Promise(((t,s)=>{this.callbacks.set(e.identifier,{resolve:t,reject:s}),this.scheduleEventPost(n)})),t]}request(e){return e}scheduleEventPost(e,t=!1){const n=this.sharedSubscriptionWorker;n?n.port.postMessage(e):t?this.workerEventsQueue.splice(0,0,e):this.workerEventsQueue.push(e)}flushScheduledEvents(){const e=this.sharedSubscriptionWorker;if(!e||0===this.workerEventsQueue.length)return;const t=[];for(let e=0;e!t.includes(e))),this.workerEventsQueue.forEach((t=>e.port.postMessage(t))),this.workerEventsQueue=[]}get sharedSubscriptionWorker(){return this.subscriptionWorkerReady?this.subscriptionWorker:null}setupSubscriptionWorker(){"undefined"!=typeof SharedWorker&&(this.subscriptionWorker=new SharedWorker(this.configuration.workerUrl,`/pubnub-${this.configuration.sdkVersion}`),this.subscriptionWorker.port.start(),this.scheduleEventPost({type:"client-register",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,heartbeatInterval:this.configuration.heartbeatInterval,logVerbosity:this.configuration.logVerbosity,workerLogVerbosity:this.configuration.workerLogVerbosity},!0),this.subscriptionWorker.port.onmessage=e=>this.handleWorkerEvent(e))}handleWorkerEvent(e){const{data:t}=e;if("shared-worker-ping"===t.type||"shared-worker-connected"===t.type||"shared-worker-console-log"===t.type||"shared-worker-console-dir"===t.type||t.clientIdentifier===this.configuration.clientIdentifier)if("shared-worker-connected"===t.type)this.subscriptionWorkerReady=!0,this.flushScheduledEvents();else if("shared-worker-console-log"===t.type)console.log(`[SharedWorker] ${t.message}`);else if("shared-worker-console-dir"===t.type)t.message&&console.log(`[SharedWorker] ${t.message}`),console.dir(t.data,{depth:10});else if("shared-worker-ping"===t.type){const{logVerbosity:e,subscriptionKey:t,clientIdentifier:n}=this.configuration;this.scheduleEventPost({type:"client-pong",subscriptionKey:t,clientIdentifier:n,logVerbosity:e})}else if("request-progress-start"===t.type||"request-progress-end"===t.type)this.logRequestProgress(t);else if("request-process-success"===t.type||"request-process-error"===t.type){const{resolve:e,reject:n}=this.callbacks.get(t.identifier);if("request-process-success"===t.type)e({status:t.response.status,url:t.url,headers:t.response.headers,body:t.response.body});else{let e=h.PNUnknownCategory,s="Unknown error";if(t.error)"NETWORK_ISSUE"===t.error.type?e=h.PNNetworkIssuesCategory:"TIMEOUT"===t.error.type?e=h.PNTimeoutCategory:"ABORTED"===t.error.type&&(e=h.PNCancelledCategory),s=`${t.error.message} (${t.identifier})`;else if(t.response)return n(A.create({url:t.url,headers:t.response.headers,body:t.response.body,status:t.response.status},t.response.body));n(new A(s,e,0,new Error(s)))}}}logRequestProgress(e){var t,n;"request-progress-start"===e.type?(console.log("<<<<<"),console.log(`[${e.timestamp}] ${e.url}\n${JSON.stringify(null!==(t=e.query)&&void 0!==t?t:{})}`),console.log("-----")):(console.log(">>>>>>"),console.log(`[${e.timestamp} / ${e.duration}] ${e.url}\n${JSON.stringify(null!==(n=e.query)&&void 0!==n?n:{})}\n${e.response}`),console.log("-----"))}}function F(e){const t=e=>"object"==typeof e&&null!==e&&e.constructor===Object,n=e=>"number"==typeof e&&isFinite(e);if(!t(e))return e;const s={};return Object.keys(e).forEach((r=>{const i=(e=>"string"==typeof e||e instanceof String)(r);let a=r;const o=e[r];if(i&&r.indexOf(",")>=0){a=r.split(",").map(Number).reduce(((e,t)=>e+String.fromCharCode(t)),"")}else(n(r)||i&&!isNaN(Number(r)))&&(a=String.fromCharCode(n(r)?r:parseInt(r,10)));s[a]=t(o)?F(o):o})),s}const T=e=>{var t,n,s,r;return e.subscriptionWorkerUrl&&"undefined"==typeof SharedWorker&&(e.subscriptionWorkerUrl=null),Object.assign(Object.assign({},(e=>{var t,n,s,r,i,a,o,c,u,l,h,p,g,y,f;const m=Object.assign({},e);if(null!==(t=m.logVerbosity)&&void 0!==t||(m.logVerbosity=!1),null!==(n=m.ssl)&&void 0!==n||(m.ssl=!0),null!==(s=m.transactionalRequestTimeout)&&void 0!==s||(m.transactionalRequestTimeout=15),null!==(r=m.subscribeRequestTimeout)&&void 0!==r||(m.subscribeRequestTimeout=310),null!==(i=m.fileRequestTimeout)&&void 0!==i||(m.fileRequestTimeout=300),null!==(a=m.restore)&&void 0!==a||(m.restore=!1),null!==(o=m.useInstanceId)&&void 0!==o||(m.useInstanceId=!1),null!==(c=m.suppressLeaveEvents)&&void 0!==c||(m.suppressLeaveEvents=!1),null!==(u=m.requestMessageCountThreshold)&&void 0!==u||(m.requestMessageCountThreshold=100),null!==(l=m.autoNetworkDetection)&&void 0!==l||(m.autoNetworkDetection=!1),null!==(h=m.enableEventEngine)&&void 0!==h||(m.enableEventEngine=!1),null!==(p=m.maintainPresenceState)&&void 0!==p||(m.maintainPresenceState=!0),null!==(g=m.keepAlive)&&void 0!==g||(m.keepAlive=!1),m.userId&&m.uuid)throw new d("PubNub client configuration error: use only 'userId'");if(null!==(y=m.userId)&&void 0!==y||(m.userId=m.uuid),!m.userId)throw new d("PubNub client configuration error: 'userId' not set");if(0===(null===(f=m.userId)||void 0===f?void 0:f.trim().length))throw new d("PubNub client configuration error: 'userId' is empty");m.origin||(m.origin=Array.from({length:20},((e,t)=>`ps${t+1}.pndsn.com`)));const b={subscribeKey:m.subscribeKey,publishKey:m.publishKey,secretKey:m.secretKey};void 0!==m.presenceTimeout&&m.presenceTimeout<20&&(m.presenceTimeout=20,console.log("WARNING: Presence timeout is less than the minimum. Using minimum value: ",20)),void 0!==m.presenceTimeout?m.heartbeatInterval=m.presenceTimeout/2-1:m.presenceTimeout=300;let v=!1,w=!0,S=5,E=!1,O=100,k=!0;return void 0!==m.dedupeOnSubscribe&&"boolean"==typeof m.dedupeOnSubscribe&&(E=m.dedupeOnSubscribe),void 0!==m.maximumCacheSize&&"number"==typeof m.maximumCacheSize&&(O=m.maximumCacheSize),void 0!==m.useRequestId&&"boolean"==typeof m.useRequestId&&(k=m.useRequestId),void 0!==m.announceSuccessfulHeartbeats&&"boolean"==typeof m.announceSuccessfulHeartbeats&&(v=m.announceSuccessfulHeartbeats),void 0!==m.announceFailedHeartbeats&&"boolean"==typeof m.announceFailedHeartbeats&&(w=m.announceFailedHeartbeats),void 0!==m.fileUploadPublishRetryLimit&&"number"==typeof m.fileUploadPublishRetryLimit&&(S=m.fileUploadPublishRetryLimit),Object.assign(Object.assign({},m),{keySet:b,dedupeOnSubscribe:E,maximumCacheSize:O,useRequestId:k,announceSuccessfulHeartbeats:v,announceFailedHeartbeats:w,fileUploadPublishRetryLimit:S})})(e)),{listenToBrowserNetworkEvents:null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t,subscriptionWorkerUrl:e.subscriptionWorkerUrl,subscriptionWorkerLogVerbosity:null!==(n=e.subscriptionWorkerLogVerbosity)&&void 0!==n&&n,transport:null!==(s=e.transport)&&void 0!==s?s:"fetch",keepAlive:null===(r=e.keepAlive)||void 0===r||r})};var R={exports:{}}; +/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */!function(e,t){!function(e){var t="0.1.0",n={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};function s(){var e,t,n="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(n+="-"),n+=(12===e?4:16===e?3&t|8:t).toString(16);return n}function r(e,t){var s=n[t||"all"];return s&&s.test(e)||!1}s.isUUID=r,s.VERSION=t,e.uuid=s,e.isUUID=r}(t),null!==e&&(e.exports=t.uuid)}(R,R.exports);var U=t(R.exports),x={createUUID:()=>U.uuid?U.uuid():U()};const D=(e,t)=>{var n,s,r;null===(n=e.retryConfiguration)||void 0===n||n.validate(),null!==(s=e.useRandomIVs)&&void 0!==s||(e.useRandomIVs=true),e.origin=q(null!==(r=e.ssl)&&void 0!==r&&r,e.origin);const i=e.cryptoModule;i&&delete e.cryptoModule;const a=Object.assign(Object.assign({},e),{_pnsdkSuffix:{},_instanceId:`pn-${x.createUUID()}`,_cryptoModule:void 0,_cipherKey:void 0,_setupCryptoModule:t,get instanceId(){if(this.useInstanceId)return this._instanceId},getInstanceId(){if(this.useInstanceId)return this._instanceId},getUserId(){return this.userId},setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this.userId=e},getAuthKey(){return this.authKey},setAuthKey(e){this.authKey=e},getFilterExpression(){return this.filterExpression},setFilterExpression(e){this.filterExpression=e},getCipherKey(){return this._cipherKey},setCipherKey(t){this._cipherKey=t,t||!this._cryptoModule?t&&this._setupCryptoModule&&(this._cryptoModule=this._setupCryptoModule({cipherKey:t,useRandomIVs:e.useRandomIVs,customEncrypt:this.getCustomEncrypt(),customDecrypt:this.getCustomDecrypt()})):this._cryptoModule=void 0},getCryptoModule(){return this._cryptoModule},getUseRandomIVs:()=>e.useRandomIVs,setPresenceTimeout(e){this.heartbeatInterval=e/2-1,this.presenceTimeout=e},getPresenceTimeout(){return this.presenceTimeout},getHeartbeatInterval(){return this.heartbeatInterval},setHeartbeatInterval(e){this.heartbeatInterval=e},getTransactionTimeout(){return this.transactionalRequestTimeout},getSubscribeTimeout(){return this.subscribeRequestTimeout},getFileTimeout(){return this.fileRequestTimeout},get PubNubFile(){return e.PubNubFile},get version(){return"8.9.1"},getVersion(){return this.version},_addPnsdkSuffix(e,t){this._pnsdkSuffix[e]=`${t}`},_getPnsdkSuffix(e){const t=Object.values(this._pnsdkSuffix).join(e);return t.length>0?e+t:""},getUUID(){return this.getUserId()},setUUID(e){this.setUserId(e)},getCustomEncrypt:()=>e.customEncrypt,getCustomDecrypt:()=>e.customDecrypt});return e.cipherKey?a.setCipherKey(e.cipherKey):i&&(a._cryptoModule=i),a},q=(e,t)=>{const n=e?"https://":"http://";return"string"==typeof t?`${n}${t}`:`${n}${t[Math.floor(Math.random()*t.length)]}`};class G{constructor(e){this.cbor=e}setToken(e){e&&e.length>0?this.token=e:this.token=void 0}getToken(){return this.token}parseToken(e){const t=this.cbor.decodeToken(e);if(void 0!==t){const e=t.res.uuid?Object.keys(t.res.uuid):[],n=Object.keys(t.res.chan),s=Object.keys(t.res.grp),r=t.pat.uuid?Object.keys(t.pat.uuid):[],i=Object.keys(t.pat.chan),a=Object.keys(t.pat.grp),o={version:t.v,timestamp:t.t,ttl:t.ttl,authorized_uuid:t.uuid,signature:t.sig},c=e.length>0,u=n.length>0,l=s.length>0;if(c||u||l){if(o.resources={},c){const n=o.resources.uuids={};e.forEach((e=>n[e]=this.extractPermissions(t.res.uuid[e])))}if(u){const e=o.resources.channels={};n.forEach((n=>e[n]=this.extractPermissions(t.res.chan[n])))}if(l){const e=o.resources.groups={};s.forEach((n=>e[n]=this.extractPermissions(t.res.grp[n])))}}const h=r.length>0,d=i.length>0,p=a.length>0;if(h||d||p){if(o.patterns={},h){const e=o.patterns.uuids={};r.forEach((n=>e[n]=this.extractPermissions(t.pat.uuid[n])))}if(d){const e=o.patterns.channels={};i.forEach((n=>e[n]=this.extractPermissions(t.pat.chan[n])))}if(p){const e=o.patterns.groups={};a.forEach((n=>e[n]=this.extractPermissions(t.pat.grp[n])))}}return t.meta&&Object.keys(t.meta).length>0&&(o.meta=t.meta),o}}extractPermissions(e){const t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128&~e||(t.join=!0),64&~e||(t.update=!0),32&~e||(t.get=!0),8&~e||(t.delete=!0),4&~e||(t.manage=!0),2&~e||(t.write=!0),1&~e||(t.read=!0),t}}var K;!function(e){e.GET="GET",e.POST="POST",e.PATCH="PATCH",e.DELETE="DELETE",e.LOCAL="LOCAL"}(K||(K={}));const $=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),L=(e,t)=>{const n=e.map((e=>$(e)));return n.length?n.join(","):null!=t?t:""},B=(e,t)=>{const n=Object.fromEntries(t.map((e=>[e,!1])));return e.filter((e=>!(t.includes(e)&&!n[e])||(n[e]=!0,!1)))},H=(e,t)=>[...e].filter((n=>t.includes(n)&&e.indexOf(n)===e.lastIndexOf(n)&&t.indexOf(n)===t.lastIndexOf(n)));class V{constructor(e,t,n){this.publishKey=e,this.secretKey=t,this.hasher=n}signature(e){const t=e.path.startsWith("/publish")?K.GET:e.method;let n=`${t}\n${this.publishKey}\n${e.path}\n${this.queryParameters(e.queryParameters)}\n`;if(t===K.POST||t===K.PATCH){const t=e.body;let s;t&&t instanceof ArrayBuffer?s=V.textDecoder.decode(t):t&&"object"!=typeof t&&(s=t),s&&(n+=s)}return`v2.${this.hasher(n,this.secretKey)}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}queryParameters(e){return Object.keys(e).sort().map((t=>{const n=e[t];return Array.isArray(n)?n.sort().map((e=>`${t}=${$(e)}`)).join("&"):`${t}=${$(n)}`})).join("&")}}V.textDecoder=new TextDecoder("utf-8");class z{constructor(e){this.configuration=e;const{clientConfiguration:{keySet:t},shaHMAC:n}=e;t.secretKey&&n&&(this.signatureGenerator=new V(t.publishKey,t.secretKey,n))}makeSendable(e){return this.configuration.transport.makeSendable(this.request(e))}request(e){var t;const{clientConfiguration:n}=this.configuration;return(e=this.configuration.transport.request(e)).queryParameters||(e.queryParameters={}),n.useInstanceId&&(e.queryParameters.instanceid=n.getInstanceId()),e.queryParameters.uuid||(e.queryParameters.uuid=n.userId),n.useRequestId&&(e.queryParameters.requestid=e.identifier),e.queryParameters.pnsdk=this.generatePNSDK(),null!==(t=e.origin)&&void 0!==t||(e.origin=n.origin),this.authenticateRequest(e),this.signRequest(e),e}authenticateRequest(e){var t;if(e.path.startsWith("/v2/auth/")||e.path.startsWith("/v3/pam/")||e.path.startsWith("/time"))return;const{clientConfiguration:n,tokenManager:s}=this.configuration,r=null!==(t=s&&s.getToken())&&void 0!==t?t:n.authKey;r&&(e.queryParameters.auth=r)}signRequest(e){this.signatureGenerator&&!e.path.startsWith("/time")&&(e.queryParameters.timestamp=String(Math.floor((new Date).getTime()/1e3)),e.queryParameters.signature=this.signatureGenerator.signature(e))}generatePNSDK(){const{clientConfiguration:e}=this.configuration;if(e.sdkName)return e.sdkName;let t=`PubNub-JS-${e.sdkFamily}`;e.partnerId&&(t+=`-${e.partnerId}`),t+=`/${e.getVersion()}`;const n=e._getPnsdkSuffix(" ");return n.length>0&&(t+=n),t}}class W{constructor(e="fetch",t=!1,n=!1){if(this.transport=e,this.keepAlive=t,this.logVerbosity=n,"fetch"!==e||window&&window.fetch||(this.transport="xhr"),"fetch"===this.transport&&(W.originalFetch=fetch.bind(window),this.isFetchMonkeyPatched())){if(W.originalFetch=W.getOriginalFetch(),!n)return;console.warn("[PubNub] Native Web Fetch API 'fetch' function monkey patched."),this.isFetchMonkeyPatched(W.originalFetch)?console.warn("[PubNub] Unable receive native Web Fetch API. There can be issues with subscribe long-poll cancellation"):console.info("[PubNub] Use native Web Fetch API 'fetch' implementation from iframe as APM workaround.")}}makeSendable(e){const t=new AbortController,n={abortController:t,abort:e=>!t.signal.aborted&&t.abort(e)};return[this.webTransportRequestFromTransportRequest(e).then((t=>{const s=(new Date).getTime();return this.logRequestProcessProgress(t,e.body),this.sendRequest(t,n).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>{const n=e[1].byteLength>0?e[1]:void 0,{status:r,headers:i}=e[0],a={};i.forEach(((e,t)=>a[t]=e.toLowerCase()));const o={status:r,url:t.url,headers:a,body:n};if(r>=400)throw A.create(o);return this.logRequestProcessProgress(t,void 0,(new Date).getTime()-s,n),o})).catch((e=>{let t=e;if("string"==typeof e){const n=e.toLowerCase();t=new Error(e),!n.includes("timeout")&&n.includes("cancel")&&(t.name="AbortError")}throw A.create(t)}))})),n]}request(e){return e}sendRequest(e,t){return i(this,void 0,void 0,(function*(){return"fetch"===this.transport?this.sendFetchRequest(e,t):this.sendXHRRequest(e,t)}))}sendFetchRequest(e,t){return i(this,void 0,void 0,(function*(){let n;const s=new Promise(((s,r)=>{n=setTimeout((()=>{clearTimeout(n),r(new Error("Request timeout")),t.abort("Cancel because of timeout")}),1e3*e.timeout)})),r=new Request(e.url,{method:e.method,headers:e.headers,redirect:"follow",body:e.body});return Promise.race([W.originalFetch(r,{signal:t.abortController.signal,credentials:"omit",cache:"no-cache"}).then((e=>(n&&clearTimeout(n),e))),s])}))}sendXHRRequest(e,t){return i(this,void 0,void 0,(function*(){return new Promise(((n,s)=>{var r;const i=new XMLHttpRequest;i.open(e.method,e.url,!0),i.responseType="arraybuffer",i.timeout=1e3*e.timeout,t.abortController.signal.onabort=()=>{i.readyState!=XMLHttpRequest.DONE&&i.readyState!=XMLHttpRequest.UNSENT&&i.abort()},Object.entries(null!==(r=e.headers)&&void 0!==r?r:{}).forEach((([e,t])=>i.setRequestHeader(e,t))),i.onabort=()=>s(new Error("Aborted")),i.ontimeout=()=>s(new Error("Request timeout")),i.onerror=()=>s(new Error("Request timeout")),i.onload=()=>{const e=new Headers;i.getAllResponseHeaders().split("\r\n").forEach((t=>{const[n,s]=t.split(": ");n.length>1&&s.length>1&&e.append(n,s)})),n(new Response(i.response,{status:i.status,headers:e,statusText:i.statusText}))},i.send(e.body)}))}))}webTransportRequestFromTransportRequest(e){return i(this,void 0,void 0,(function*(){let t,n=e.path;if(e.formData&&e.formData.length>0){e.queryParameters={};const n=e.body,s=new FormData;for(const{key:t,value:n}of e.formData)s.append(t,n);try{const e=yield n.toArrayBuffer();s.append("file",new Blob([e],{type:"application/octet-stream"}),n.name)}catch(e){try{const e=yield n.toFileUri();s.append("file",e,n.name)}catch(e){}}t=s}else e.body&&("string"==typeof e.body||e.body instanceof ArrayBuffer)&&(t=e.body);var s;return e.queryParameters&&0!==Object.keys(e.queryParameters).length&&(n=`${n}?${s=e.queryParameters,Object.keys(s).map((e=>{const t=s[e];return Array.isArray(t)?t.map((t=>`${e}=${$(t)}`)).join("&"):`${e}=${$(t)}`})).join("&")}`),{url:`${e.origin}${n}`,method:e.method,headers:e.headers,timeout:e.timeout,body:t}}))}logRequestProcessProgress(e,t,n,s){if(!this.logVerbosity)return;const{protocol:r,host:i,pathname:a,search:o}=new URL(e.url),c=(new Date).toISOString();if(n){let e=`[${c} / ${n}]\n${r}//${i}${a}\n${o}`;s&&(e+=`\n\n${W.decoder.decode(s)}`),console.log(">>>>>>"),console.log(e),console.log("-----")}else{let e=`[${c}]\n${r}//${i}${a}\n${o}`;t&&("string"==typeof t||t instanceof ArrayBuffer)&&(e+="string"==typeof t?`\n\n${t}`:`\n\n${W.decoder.decode(t)}`),console.log("<<<<<"),console.log(e),console.log("-----")}}isFetchMonkeyPatched(e){return!(null!=e?e:fetch).toString().includes("[native code]")&&"fetch"!==fetch.name}static getOriginalFetch(){let e=document.querySelector('iframe[name="pubnub-context-unpatched-fetch"]');return e||(e=document.createElement("iframe"),e.style.display="none",e.name="pubnub-context-unpatched-fetch",e.src="about:blank",document.body.appendChild(e)),e.contentWindow?e.contentWindow.fetch.bind(e.contentWindow):fetch}}W.decoder=new TextDecoder;class J{constructor(){this.listeners=[]}addListener(e){this.listeners.includes(e)||this.listeners.push(e)}removeListener(e){this.listeners=this.listeners.filter((t=>t!==e))}removeAllListeners(){this.listeners=[]}announceStatus(e){this.listeners.forEach((t=>{t.status&&t.status(e)}))}announcePresence(e){this.listeners.forEach((t=>{t.presence&&t.presence(e)}))}announceMessage(e){this.listeners.forEach((t=>{t.message&&t.message(e)}))}announceSignal(e){this.listeners.forEach((t=>{t.signal&&t.signal(e)}))}announceMessageAction(e){this.listeners.forEach((t=>{t.messageAction&&t.messageAction(e)}))}announceFile(e){this.listeners.forEach((t=>{t.file&&t.file(e)}))}announceObjects(e){this.listeners.forEach((t=>{t.objects&&t.objects(e)}))}announceNetworkUp(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkUpCategory})}))}announceNetworkDown(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkDownCategory})}))}announceUser(e){this.listeners.forEach((t=>{t.user&&t.user(e)}))}announceSpace(e){this.listeners.forEach((t=>{t.space&&t.space(e)}))}announceMembership(e){this.listeners.forEach((t=>{t.membership&&t.membership(e)}))}}class X{constructor(e){this.time=e}onReconnect(e){this.callback=e}startPolling(){this.timeTimer=setInterval((()=>this.callTime()),3e3)}stopPolling(){this.timeTimer&&clearInterval(this.timeTimer),this.timeTimer=null}callTime(){this.time((e=>{e.error||(this.stopPolling(),this.callback&&this.callback())}))}}class Q{constructor({maximumCacheSize:e}){this.maximumCacheSize=e,this.hashHistory=[]}getKey(e){var t;return`${e.timetoken}-${this.hashCode(JSON.stringify(null!==(t=e.message)&&void 0!==t?t:"")).toString()}`}isDuplicate(e){return this.hashHistory.includes(this.getKey(e))}addEntry(e){this.hashHistory.length>=this.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}clearHistory(){this.hashHistory=[]}hashCode(e){let t=0;if(0===e.length)return t;for(let n=0;n{this.pendingChannelSubscriptions.add(e),this.channels[e]={},r&&(this.presenceChannels[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannels[e]={})})),null==n||n.forEach((e=>{this.pendingChannelGroupSubscriptions.add(e),this.channelGroups[e]={},r&&(this.presenceChannelGroups[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannelGroups[e]={})})),this.subscriptionStatusAnnounced=!1,this.reconnect()}unsubscribe(e,t){let{channels:n,channelGroups:s}=e;const i=new Set,a=new Set;null==n||n.forEach((e=>{e in this.channels&&(delete this.channels[e],a.add(e),e in this.heartbeatChannels&&delete this.heartbeatChannels[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannels&&(delete this.presenceChannels[e],a.add(e))})),null==s||s.forEach((e=>{e in this.channelGroups&&(delete this.channelGroups[e],i.add(e),e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannelGroups&&(delete this.presenceChannelGroups[e],i.add(e))})),0===a.size&&0===i.size||(!1!==this.configuration.suppressLeaveEvents||t||(s=Array.from(i),n=Array.from(a),this.leaveCall({channels:n,channelGroups:s},(e=>{const{error:t}=e,i=r(e,["error"]);let a;t&&(e.errorData&&"object"==typeof e.errorData&&"message"in e.errorData&&"string"==typeof e.errorData.message?a=e.errorData.message:"message"in e&&"string"==typeof e.message&&(a=e.message)),this.listenerManager.announceStatus(Object.assign(Object.assign({},i),{error:null!=a&&a,affectedChannels:n,affectedChannelGroups:s,currentTimetoken:this.currentTimetoken,lastTimetoken:this.lastTimetoken}))}))),0===Object.keys(this.channels).length&&0===Object.keys(this.presenceChannels).length&&0===Object.keys(this.channelGroups).length&&0===Object.keys(this.presenceChannelGroups).length&&(this.lastTimetoken=0,this.currentTimetoken=0,this.storedTimetoken=null,this.region=null,this.reconnectionManager.stopPolling()),this.reconnect(!0))}unsubscribeAll(e){this.unsubscribe({channels:this.subscribedChannels,channelGroups:this.subscribedChannelGroups},e)}startSubscribeLoop(){this.stopSubscribeLoop();const e=[...Object.keys(this.channelGroups)],t=[...Object.keys(this.channels)];Object.keys(this.presenceChannelGroups).forEach((t=>e.push(`${t}-pnpres`))),Object.keys(this.presenceChannels).forEach((e=>t.push(`${e}-pnpres`))),0===t.length&&0===e.length||this.subscribeCall({channels:t,channelGroups:e,state:this.presenceState,heartbeat:this.configuration.getPresenceTimeout(),timetoken:this.currentTimetoken,region:null!==this.region?this.region:void 0,filterExpression:this.configuration.filterExpression},((e,t)=>{this.processSubscribeResponse(e,t)}))}stopSubscribeLoop(){this._subscribeAbort&&(this._subscribeAbort(),this._subscribeAbort=null)}processSubscribeResponse(e,t){if(e.error){if("object"==typeof e.errorData&&"name"in e.errorData&&"AbortError"===e.errorData.name||e.category===h.PNCancelledCategory)return;return void(e.category===h.PNTimeoutCategory?this.startSubscribeLoop():e.category===h.PNNetworkIssuesCategory||e.category===h.PNMalformedResponseCategory?(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(Object.assign(Object.assign({},e),{category:h.PNNetworkIssuesCategory}))):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:n}=t,{requestMessageCountThreshold:s,dedupeOnSubscribe:r}=this.configuration;s&&n.length>=s&&this.listenerManager.announceStatus({category:h.PNRequestMessageCountExceededCategory,operation:e.operation});try{n.forEach((e=>{if(r&&"message"in e.data&&"timetoken"in e.data){if(this.dedupingManager.isDuplicate(e.data))return;this.dedupingManager.addEntry(e.data)}this.eventEmitter.emitEvent(e)}))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}this.region=t.cursor.region,this.startSubscribeLoop()}setState(e){const{state:t,channels:n,channelGroups:s}=e;null==n||n.forEach((e=>e in this.channels&&(this.presenceState[e]=t))),null==s||s.forEach((e=>e in this.channelGroups&&(this.presenceState[e]=t)))}changePresence(e){const{connected:t,channels:n,channelGroups:s}=e;t?(null==n||n.forEach((e=>this.heartbeatChannels[e]={})),null==s||s.forEach((e=>this.heartbeatChannelGroups[e]={}))):(null==n||n.forEach((e=>{e in this.heartbeatChannels&&delete this.heartbeatChannels[e]})),null==s||s.forEach((e=>{e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]})),!1===this.configuration.suppressLeaveEvents&&this.leaveCall({channels:n,channelGroups:s},(e=>this.listenerManager.announceStatus(e)))),this.reconnect()}startHeartbeatTimer(){this.stopHeartbeatTimer();const e=this.configuration.getHeartbeatInterval();e&&0!==e&&(this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>this.sendHeartbeat()),1e3*e))}stopHeartbeatTimer(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}sendHeartbeat(){const e=Object.keys(this.heartbeatChannelGroups),t=Object.keys(this.heartbeatChannels);0===t.length&&0===e.length||this.heartbeatCall({channels:t,channelGroups:e,heartbeat:this.configuration.getPresenceTimeout(),state:this.presenceState},(e=>{e.error&&this.configuration.announceFailedHeartbeats&&this.listenerManager.announceStatus(e),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.disconnect(),this.listenerManager.announceNetworkDown(),this.reconnect()),!e.error&&this.configuration.announceSuccessfulHeartbeats&&this.listenerManager.announceStatus(e)}))}}class Z{constructor(e,t,n){this._payload=e,this.setDefaultPayloadStructure(),this.title=t,this.body=n}get payload(){return this._payload}set title(e){this._title=e}set subtitle(e){this._subtitle=e}set body(e){this._body=e}set badge(e){this._badge=e}set sound(e){this._sound=e}setDefaultPayloadStructure(){}toObject(){return{}}}class ee extends Z{constructor(){super(...arguments),this._apnsPushType="apns",this._isSilent=!1}get payload(){return this._payload}set configurations(e){e&&e.length&&(this._configurations=e)}get notification(){return this.payload.aps}get title(){return this._title}set title(e){e&&e.length&&(this.payload.aps.alert.title=e,this._title=e)}get subtitle(){return this._subtitle}set subtitle(e){e&&e.length&&(this.payload.aps.alert.subtitle=e,this._subtitle=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.aps.alert.body=e,this._body=e)}get badge(){return this._badge}set badge(e){null!=e&&(this.payload.aps.badge=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.aps.sound=e,this._sound=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.aps={alert:{}}}toObject(){const e=Object.assign({},this.payload),{aps:t}=e;let{alert:n}=t;if(this._isSilent&&(t["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");const t=[];this._configurations.forEach((e=>{t.push(this.objectFromAPNS2Configuration(e))})),t.length&&(e.pn_push=t)}return n&&Object.keys(n).length||delete t.alert,this._isSilent&&(delete t.alert,delete t.badge,delete t.sound,n={}),this._isSilent||n&&Object.keys(n).length?e:null}objectFromAPNS2Configuration(e){if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");const{collapseId:t,expirationDate:n}=e,s={auth_method:"token",targets:e.targets.map((e=>this.objectFromAPNSTarget(e))),version:"v2"};return t&&t.length&&(s.collapse_id=t),n&&(s.expiration=n.toISOString()),s}objectFromAPNSTarget(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");const{topic:t,environment:n="development",excludedDevices:s=[]}=e,r={topic:t,environment:n};return s.length&&(r.excluded_devices=s),r}}class te extends Z{get payload(){return this._payload}get notification(){return this.payload.notification}get data(){return this.payload.data}get title(){return this._title}set title(e){e&&e.length&&(this.payload.notification.title=e,this._title=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.notification.body=e,this._body=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.notification.sound=e,this._sound=e)}get icon(){return this._icon}set icon(e){e&&e.length&&(this.payload.notification.icon=e,this._icon=e)}get tag(){return this._tag}set tag(e){e&&e.length&&(this.payload.notification.tag=e,this._tag=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.notification={},this.payload.data={}}toObject(){let e=Object.assign({},this.payload.data),t=null;const n={};if(Object.keys(this.payload).length>2){const t=r(this.payload,["notification","data"]);e=Object.assign(Object.assign({},e),t)}return this._isSilent?e.notification=this.payload.notification:t=this.payload.notification,Object.keys(e).length&&(n.data=e),t&&Object.keys(t).length&&(n.notification=t),Object.keys(n).length?n:null}}class ne{constructor(e,t){this._payload={apns:{},fcm:{}},this._title=e,this._body=t,this.apns=new ee(this._payload.apns,e,t),this.fcm=new te(this._payload.fcm,e,t)}set debugging(e){this._debugging=e}get title(){return this._title}get subtitle(){return this._subtitle}set subtitle(e){this._subtitle=e,this.apns.subtitle=e,this.fcm.subtitle=e}get body(){return this._body}get badge(){return this._badge}set badge(e){this._badge=e,this.apns.badge=e,this.fcm.badge=e}get sound(){return this._sound}set sound(e){this._sound=e,this.apns.sound=e,this.fcm.sound=e}buildPayload(e){const t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";const n=this.apns.toObject();n&&Object.keys(n).length&&(t.pn_apns=n)}if(e.includes("fcm")){const e=this.fcm.toObject();e&&Object.keys(e).length&&(t.pn_gcm=e)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t}}class se{constructor(e){this.params=e,this.requestIdentifier=x.createUUID(),this._cancellationController=null}get cancellationController(){return this._cancellationController}set cancellationController(e){this._cancellationController=e}abort(e){this&&this.cancellationController&&this.cancellationController.abort(e)}operation(){throw Error("Should be implemented by subclass.")}validate(){}parse(e){return i(this,void 0,void 0,(function*(){return this.deserializeResponse(e)}))}request(){var e,t,n,s;const r={method:null!==(t=null===(e=this.params)||void 0===e?void 0:e.method)&&void 0!==t?t:K.GET,path:this.path,queryParameters:this.queryParameters,cancellable:null!==(s=null===(n=this.params)||void 0===n?void 0:n.cancellable)&&void 0!==s&&s,timeout:10,identifier:this.requestIdentifier},i=this.headers;if(i&&(r.headers=i),r.method===K.POST||r.method===K.PATCH){const[e,t]=[this.body,this.formData];t&&(r.formData=t),e&&(r.body=e)}return r}get headers(){}get path(){throw Error("`path` getter should be implemented by subclass.")}get queryParameters(){return{}}get formData(){}get body(){}deserializeResponse(e){const t=se.decoder.decode(e.body),n=e.headers["content-type"];let s;if(!n||-1===n.indexOf("javascript")&&-1===n.indexOf("json"))throw new d("Service response error, check status for details",y(t,e.status));try{s=JSON.parse(t)}catch(n){throw console.error("Error parsing JSON response:",n),new d("Service response error, check status for details",y(t,e.status))}if("status"in s&&"number"==typeof s.status&&s.status>=400)throw A.create(e);return s}}var re;se.decoder=new TextDecoder,function(e){e.PNPublishOperation="PNPublishOperation",e.PNSignalOperation="PNSignalOperation",e.PNSubscribeOperation="PNSubscribeOperation",e.PNUnsubscribeOperation="PNUnsubscribeOperation",e.PNWhereNowOperation="PNWhereNowOperation",e.PNHereNowOperation="PNHereNowOperation",e.PNGlobalHereNowOperation="PNGlobalHereNowOperation",e.PNSetStateOperation="PNSetStateOperation",e.PNGetStateOperation="PNGetStateOperation",e.PNHeartbeatOperation="PNHeartbeatOperation",e.PNAddMessageActionOperation="PNAddActionOperation",e.PNRemoveMessageActionOperation="PNRemoveMessageActionOperation",e.PNGetMessageActionsOperation="PNGetMessageActionsOperation",e.PNTimeOperation="PNTimeOperation",e.PNHistoryOperation="PNHistoryOperation",e.PNDeleteMessagesOperation="PNDeleteMessagesOperation",e.PNFetchMessagesOperation="PNFetchMessagesOperation",e.PNMessageCounts="PNMessageCountsOperation",e.PNGetAllUUIDMetadataOperation="PNGetAllUUIDMetadataOperation",e.PNGetUUIDMetadataOperation="PNGetUUIDMetadataOperation",e.PNSetUUIDMetadataOperation="PNSetUUIDMetadataOperation",e.PNRemoveUUIDMetadataOperation="PNRemoveUUIDMetadataOperation",e.PNGetAllChannelMetadataOperation="PNGetAllChannelMetadataOperation",e.PNGetChannelMetadataOperation="PNGetChannelMetadataOperation",e.PNSetChannelMetadataOperation="PNSetChannelMetadataOperation",e.PNRemoveChannelMetadataOperation="PNRemoveChannelMetadataOperation",e.PNGetMembersOperation="PNGetMembersOperation",e.PNSetMembersOperation="PNSetMembersOperation",e.PNGetMembershipsOperation="PNGetMembershipsOperation",e.PNSetMembershipsOperation="PNSetMembershipsOperation",e.PNListFilesOperation="PNListFilesOperation",e.PNGenerateUploadUrlOperation="PNGenerateUploadUrlOperation",e.PNPublishFileOperation="PNPublishFileOperation",e.PNPublishFileMessageOperation="PNPublishFileMessageOperation",e.PNGetFileUrlOperation="PNGetFileUrlOperation",e.PNDownloadFileOperation="PNDownloadFileOperation",e.PNDeleteFileOperation="PNDeleteFileOperation",e.PNAddPushNotificationEnabledChannelsOperation="PNAddPushNotificationEnabledChannelsOperation",e.PNRemovePushNotificationEnabledChannelsOperation="PNRemovePushNotificationEnabledChannelsOperation",e.PNPushNotificationEnabledChannelsOperation="PNPushNotificationEnabledChannelsOperation",e.PNRemoveAllPushNotificationsOperation="PNRemoveAllPushNotificationsOperation",e.PNChannelGroupsOperation="PNChannelGroupsOperation",e.PNRemoveGroupOperation="PNRemoveGroupOperation",e.PNChannelsForGroupOperation="PNChannelsForGroupOperation",e.PNAddChannelsToGroupOperation="PNAddChannelsToGroupOperation",e.PNRemoveChannelsFromGroupOperation="PNRemoveChannelsFromGroupOperation",e.PNAccessManagerGrant="PNAccessManagerGrant",e.PNAccessManagerGrantToken="PNAccessManagerGrantToken",e.PNAccessManagerAudit="PNAccessManagerAudit",e.PNAccessManagerRevokeToken="PNAccessManagerRevokeToken",e.PNHandshakeOperation="PNHandshakeOperation",e.PNReceiveMessagesOperation="PNReceiveMessagesOperation"}(re||(re={}));var ie=re;var ae;!function(e){e[e.Presence=-2]="Presence",e[e.Message=-1]="Message",e[e.Signal=1]="Signal",e[e.AppContext=2]="AppContext",e[e.MessageAction=3]="MessageAction",e[e.Files=4]="Files"}(ae||(ae={}));class oe extends se{constructor(e){var t,n,s,r,i,a;super({cancellable:!0}),this.parameters=e,null!==(t=(r=this.parameters).withPresence)&&void 0!==t||(r.withPresence=false),null!==(n=(i=this.parameters).channelGroups)&&void 0!==n||(i.channelGroups=[]),null!==(s=(a=this.parameters).channels)&&void 0!==s||(a.channels=[])}operation(){return ie.PNSubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:n}=this.parameters;return e?t||n?void 0:"`channels` and `channelGroups` both should not be empty":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){let t,n;try{n=se.decoder.decode(e.body);t=JSON.parse(n)}catch(e){console.error("Error parsing JSON response:",e)}if(!t)throw new d("Service response error, check status for details",y(n,e.status));const s=t.m.filter((e=>{const t=void 0===e.b?e.c:e.b;return this.parameters.channels&&this.parameters.channels.includes(t)||this.parameters.channelGroups&&this.parameters.channelGroups.includes(t)})).map((e=>{let{e:t}=e;return null!=t||(t=e.c.endsWith("-pnpres")?ae.Presence:ae.Message),t!=ae.Signal&&"string"==typeof e.d?t==ae.Message?{type:ae.Message,data:this.messageFromEnvelope(e)}:{type:ae.Files,data:this.fileFromEnvelope(e)}:t==ae.Message?{type:ae.Message,data:this.messageFromEnvelope(e)}:t===ae.Presence?{type:ae.Presence,data:this.presenceEventFromEnvelope(e)}:t==ae.Signal?{type:ae.Signal,data:this.signalFromEnvelope(e)}:t===ae.AppContext?{type:ae.AppContext,data:this.appContextFromEnvelope(e)}:t===ae.MessageAction?{type:ae.MessageAction,data:this.messageActionFromEnvelope(e)}:{type:ae.Files,data:this.fileFromEnvelope(e)}}));return{cursor:{timetoken:t.t.t,region:t.t.r},messages:s}}))}get headers(){return{accept:"text/javascript"}}presenceEventFromEnvelope(e){var t;const{d:n}=e,[s,r]=this.subscriptionChannelFromEnvelope(e),i=s.replace("-pnpres",""),a=null!==r?i:null,o=null!==r?r:i;return"string"!=typeof n&&("data"in n?(n.state=n.data,delete n.data):"action"in n&&"interval"===n.action&&(n.hereNowRefresh=null!==(t=n.here_now_refresh)&&void 0!==t&&t,delete n.here_now_refresh)),Object.assign({channel:i,subscription:r,actualChannel:a,subscribedChannel:o,timetoken:e.p.t},n)}messageFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),[s,r]=this.decryptedData(e.d),i={channel:t,subscription:n,actualChannel:null!==n?t:null,subscribedChannel:null!==n?n:t,timetoken:e.p.t,publisher:e.i,message:s};return e.u&&(i.userMetadata=e.u),e.cmt&&(i.customMessageType=e.cmt),r&&(i.error=r),i}signalFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),s={channel:t,subscription:n,timetoken:e.p.t,publisher:e.i,message:e.d};return e.u&&(s.userMetadata=e.u),e.cmt&&(s.customMessageType=e.cmt),s}messageActionFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),s=e.d;return{channel:t,subscription:n,timetoken:e.p.t,publisher:e.i,event:s.event,data:Object.assign(Object.assign({},s.data),{uuid:e.i})}}appContextFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),s=e.d;return{channel:t,subscription:n,timetoken:e.p.t,message:s}}fileFromEnvelope(e){const[t,n]=this.subscriptionChannelFromEnvelope(e),[s,r]=this.decryptedData(e.d);let i=r;const a={channel:t,subscription:n,timetoken:e.p.t,publisher:e.i};return e.u&&(a.userMetadata=e.u),s?"string"==typeof s?null!=i||(i="Unexpected file information payload data type."):(a.message=s.message,s.file&&(a.file={id:s.file.id,name:s.file.name,url:this.parameters.getFileUrl({id:s.file.id,name:s.file.name,channel:t})})):null!=i||(i="File information payload is missing."),e.cmt&&(a.customMessageType=e.cmt),i&&(a.error=i),a}subscriptionChannelFromEnvelope(e){return[e.c,void 0===e.b?e.c:e.b]}decryptedData(e){if(!this.parameters.crypto||"string"!=typeof e)return[e,void 0];let t,n;try{const n=this.parameters.crypto.decrypt(e);t=n instanceof ArrayBuffer?JSON.parse(ce.decoder.decode(n)):n}catch(e){t=null,n=`Error while decrypting message content: ${e.message}`}return[null!=t?t:e,n]}}class ce extends oe{get path(){var e;const{keySet:{subscribeKey:t},channels:n}=this.parameters;return`/v2/subscribe/${t}/${L(null!==(e=null==n?void 0:n.sort())&&void 0!==e?e:[],",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,heartbeat:n,state:s,timetoken:r,region:i}=this.parameters,a={};return e&&e.length>0&&(a["channel-group"]=e.sort().join(",")),t&&t.length>0&&(a["filter-expr"]=t),n&&(a.heartbeat=n),s&&Object.keys(s).length>0&&(a.state=JSON.stringify(s)),void 0!==r&&"string"==typeof r?r.length>0&&"0"!==r&&(a.tt=r):void 0!==r&&r>0&&(a.tt=r),i&&(a.tr=i),a}}class ue{constructor(e){this.listenerManager=e,this.channelListenerMap=new Map,this.groupListenerMap=new Map}emitEvent(e){var t;if(e.type===ae.Message)this.listenerManager.announceMessage(e.data),this.announce("message",e.data,e.data.channel,e.data.subscription);else if(e.type===ae.Signal)this.listenerManager.announceSignal(e.data),this.announce("signal",e.data,e.data.channel,e.data.subscription);else if(e.type===ae.Presence)this.listenerManager.announcePresence(e.data),this.announce("presence",e.data,null!==(t=e.data.subscription)&&void 0!==t?t:e.data.channel,e.data.subscription);else if(e.type===ae.AppContext){const{data:t}=e,{message:n}=t;if(this.listenerManager.announceObjects(t),this.announce("objects",t,t.channel,t.subscription),"uuid"===n.type){const{message:e,channel:s}=t,i=r(t,["message","channel"]),{event:a,type:o}=n,c=r(n,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:s,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",type:"user"})});this.listenerManager.announceUser(u),this.announce("user",u,u.spaceId,u.subscription)}else if("channel"===n.type){const{message:e,channel:s}=t,i=r(t,["message","channel"]),{event:a,type:o}=n,c=r(n,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:s,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",type:"space"})});this.listenerManager.announceSpace(u),this.announce("space",u,u.spaceId,u.subscription)}else if("membership"===n.type){const{message:e,channel:s}=t,i=r(t,["message","channel"]),{event:a,data:o}=n,c=r(n,["event","data"]),{uuid:u,channel:l}=o,h=r(o,["uuid","channel"]),d=Object.assign(Object.assign({},i),{spaceId:s,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",data:Object.assign(Object.assign({},h),{user:u,space:l})})});this.listenerManager.announceMembership(d),this.announce("membership",d,d.spaceId,d.subscription)}}else e.type===ae.MessageAction?(this.listenerManager.announceMessageAction(e.data),this.announce("messageAction",e.data,e.data.channel,e.data.subscription)):e.type===ae.Files&&(this.listenerManager.announceFile(e.data),this.announce("file",e.data,e.data.channel,e.data.subscription))}addListener(e,t,n){t&&n?(null==t||t.forEach((t=>{if(this.channelListenerMap.has(t)){const n=this.channelListenerMap.get(t);n.includes(e)||n.push(e)}else this.channelListenerMap.set(t,[e])})),null==n||n.forEach((t=>{if(this.groupListenerMap.has(t)){const n=this.groupListenerMap.get(t);n.includes(e)||n.push(e)}else this.groupListenerMap.set(t,[e])}))):this.listenerManager.addListener(e)}removeListener(e,t,n){t&&n?(null==t||t.forEach((t=>{this.channelListenerMap.has(t)&&this.channelListenerMap.set(t,this.channelListenerMap.get(t).filter((t=>t!==e)))})),null==n||n.forEach((t=>{this.groupListenerMap.has(t)&&this.groupListenerMap.set(t,this.groupListenerMap.get(t).filter((t=>t!==e)))}))):this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners(),this.channelListenerMap.clear(),this.groupListenerMap.clear()}announce(e,t,n,s){t&&this.channelListenerMap.has(n)&&this.channelListenerMap.get(n).forEach((n=>{const s=n[e];s&&s(t)})),s&&this.groupListenerMap.has(s)&&this.groupListenerMap.get(s).forEach((n=>{const s=n[e];s&&s(t)}))}}class le{constructor(e=!1){this.sync=e,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){const t=()=>{this.listeners.forEach((t=>{t(e)}))};this.sync?t():setTimeout(t,0)}}class he{transition(e,t){var n;if(this.transitionMap.has(t.type))return null===(n=this.transitionMap.get(t.type))||void 0===n?void 0:n(e,t)}constructor(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}on(e,t){return this.transitionMap.set(e,t),this}with(e,t){return[this,e,null!=t?t:[]]}onEnter(e){return this.enterEffects.push(e),this}onExit(e){return this.exitEffects.push(e),this}}class de extends le{describe(e){return new he(e)}start(e,t){this.currentState=e,this.currentContext=t,this.notify({type:"engineStarted",state:e,context:t})}transition(e){if(!this.currentState)throw new Error("Start the engine first");this.notify({type:"eventReceived",event:e});const t=this.currentState.transition(this.currentContext,e);if(t){const[n,s,r]=t;for(const e of this.currentState.exitEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)});const i=this.currentState;this.currentState=n;const a=this.currentContext;this.currentContext=s,this.notify({type:"transitionDone",fromState:i,fromContext:a,toState:n,toContext:s,event:e});for(const e of r)this.notify({type:"invocationDispatched",invocation:e});for(const e of this.currentState.enterEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)})}}}class pe{constructor(e){this.dependencies=e,this.instances=new Map,this.handlers=new Map}on(e,t){this.handlers.set(e,t)}dispatch(e){if("CANCEL"===e.type){if(this.instances.has(e.payload)){const t=this.instances.get(e.payload);null==t||t.cancel(),this.instances.delete(e.payload)}return}const t=this.handlers.get(e.type);if(!t)throw new Error(`Unhandled invocation '${e.type}'`);const n=t(e.payload,this.dependencies);e.managed&&this.instances.set(e.type,n),n.start()}dispose(){for(const[e,t]of this.instances.entries())t.cancel(),this.instances.delete(e)}}function ge(e,t){const n=function(...n){return{type:e,payload:null==t?void 0:t(...n)}};return n.type=e,n}function ye(e,t){const n=(...n)=>({type:e,payload:t(...n),managed:!1});return n.type=e,n}function fe(e,t){const n=(...n)=>({type:e,payload:t(...n),managed:!0});return n.type=e,n.cancel={type:"CANCEL",payload:e,managed:!1},n}class me extends Error{constructor(){super("The operation was aborted."),this.name="AbortError",Object.setPrototypeOf(this,new.target.prototype)}}class be extends le{constructor(){super(...arguments),this._aborted=!1}get aborted(){return this._aborted}throwIfAborted(){if(this._aborted)throw new me}abort(){this._aborted=!0,this.notify(new me)}}class ve{constructor(e,t){this.payload=e,this.dependencies=t}}class we extends ve{constructor(e,t,n){super(e,t),this.asyncFunction=n,this.abortSignal=new be}start(){this.asyncFunction(this.payload,this.abortSignal,this.dependencies).catch((e=>{}))}cancel(){this.abortSignal.abort()}}const Se=e=>(t,n)=>new we(t,n,e),Ee=ge("RECONNECT",(()=>({}))),Oe=ge("DISCONNECT",(()=>({}))),ke=ge("JOINED",((e,t)=>({channels:e,groups:t}))),Ce=ge("LEFT",((e,t)=>({channels:e,groups:t}))),Ne=ge("LEFT_ALL",(()=>({}))),Pe=ge("HEARTBEAT_SUCCESS",(e=>({statusCode:e}))),Me=ge("HEARTBEAT_FAILURE",(e=>e)),_e=ge("HEARTBEAT_GIVEUP",(()=>({}))),je=ge("TIMES_UP",(()=>({}))),Ae=ye("HEARTBEAT",((e,t)=>({channels:e,groups:t}))),Ie=ye("LEAVE",((e,t)=>({channels:e,groups:t}))),Fe=ye("EMIT_STATUS",(e=>e)),Te=fe("WAIT",(()=>({}))),Re=fe("DELAYED_HEARTBEAT",(e=>e));class Ue extends pe{constructor(e,t){super(t),this.on(Ae.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{heartbeat:s,presenceState:r,config:i}){try{yield s(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},i.maintainPresenceState&&{state:r}),{heartbeat:i.presenceTimeout}));e.transition(Pe(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Me(t))}}}))))),this.on(Ie.type,Se(((e,t,n)=>i(this,[e,t,n],void 0,(function*(e,t,{leave:n,config:s}){if(!s.suppressLeaveEvents)try{n({channels:e.channels,channelGroups:e.groups})}catch(e){}}))))),this.on(Te.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{heartbeatDelay:s}){return n.throwIfAborted(),yield s(),n.throwIfAborted(),e.transition(je())}))))),this.on(Re.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{heartbeat:s,retryDelay:r,presenceState:i,config:a}){if(!a.retryConfiguration||!a.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(_e());n.throwIfAborted(),yield r(a.retryConfiguration.getDelay(t.attempts,t.reason)),n.throwIfAborted();try{yield s(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},a.maintainPresenceState&&{state:i}),{heartbeat:a.presenceTimeout}));return e.transition(Pe(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Me(t))}}}))))),this.on(Fe.type,Se(((e,t,n)=>i(this,[e,t,n],void 0,(function*(e,t,{emitStatus:n,config:s}){var r;s.announceFailedHeartbeats&&!0===(null===(r=null==e?void 0:e.status)||void 0===r?void 0:r.error)?n(e.status):s.announceSuccessfulHeartbeats&&200===e.statusCode&&n(Object.assign(Object.assign({},e),{operation:ie.PNHeartbeatOperation,error:!1}))})))))}}const xe=new he("HEARTBEAT_STOPPED");xe.on(ke.type,((e,t)=>xe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),xe.on(Ce.type,((e,t)=>xe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))}))),xe.on(Ee.type,((e,t)=>Ke.with({channels:e.channels,groups:e.groups}))),xe.on(Ne.type,((e,t)=>$e.with(void 0)));const De=new he("HEARTBEAT_COOLDOWN");De.onEnter((()=>Te())),De.onExit((()=>Te.cancel)),De.on(je.type,((e,t)=>Ke.with({channels:e.channels,groups:e.groups}))),De.on(ke.type,((e,t)=>Ke.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),De.on(Ce.type,((e,t)=>Ke.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ie(t.payload.channels,t.payload.groups)]))),De.on(Oe.type,(e=>xe.with({channels:e.channels,groups:e.groups},[Ie(e.channels,e.groups)]))),De.on(Ne.type,((e,t)=>$e.with(void 0,[Ie(e.channels,e.groups)])));const qe=new he("HEARTBEAT_FAILED");qe.on(ke.type,((e,t)=>Ke.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),qe.on(Ce.type,((e,t)=>Ke.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ie(t.payload.channels,t.payload.groups)]))),qe.on(Ee.type,((e,t)=>Ke.with({channels:e.channels,groups:e.groups}))),qe.on(Oe.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups},[Ie(e.channels,e.groups)]))),qe.on(Ne.type,((e,t)=>$e.with(void 0,[Ie(e.channels,e.groups)])));const Ge=new he("HEARBEAT_RECONNECTING");Ge.onEnter((e=>Re(e))),Ge.onExit((()=>Re.cancel)),Ge.on(ke.type,((e,t)=>Ke.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Ge.on(Ce.type,((e,t)=>Ke.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ie(t.payload.channels,t.payload.groups)]))),Ge.on(Oe.type,((e,t)=>{xe.with({channels:e.channels,groups:e.groups},[Ie(e.channels,e.groups)])})),Ge.on(Pe.type,((e,t)=>De.with({channels:e.channels,groups:e.groups}))),Ge.on(Me.type,((e,t)=>Ge.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),Ge.on(_e.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),Ge.on(Ne.type,((e,t)=>$e.with(void 0,[Ie(e.channels,e.groups)])));const Ke=new he("HEARTBEATING");Ke.onEnter((e=>Ae(e.channels,e.groups))),Ke.on(Pe.type,((e,t)=>De.with({channels:e.channels,groups:e.groups}))),Ke.on(ke.type,((e,t)=>Ke.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Ke.on(Ce.type,((e,t)=>Ke.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ie(t.payload.channels,t.payload.groups)]))),Ke.on(Me.type,((e,t)=>Ge.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),Ke.on(Oe.type,(e=>xe.with({channels:e.channels,groups:e.groups},[Ie(e.channels,e.groups)]))),Ke.on(Ne.type,((e,t)=>$e.with(void 0,[Ie(e.channels,e.groups)])));const $e=new he("HEARTBEAT_INACTIVE");$e.on(ke.type,((e,t)=>Ke.with({channels:t.payload.channels,groups:t.payload.groups})));class Le{get _engine(){return this.engine}constructor(e){this.dependencies=e,this.engine=new de,this.channels=[],this.groups=[],this.dispatcher=new Ue(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start($e,void 0)}join({channels:e,groups:t}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],this.engine.transition(ke(this.channels.slice(0),this.groups.slice(0)))}leave({channels:e,groups:t}){this.dependencies.presenceState&&(null==e||e.forEach((e=>delete this.dependencies.presenceState[e])),null==t||t.forEach((e=>delete this.dependencies.presenceState[e]))),this.engine.transition(Ce(null!=e?e:[],null!=t?t:[]))}leaveAll(){this.engine.transition(Ne())}dispose(){this._unsubscribeEngine(),this.dispatcher.dispose()}}class Be{static LinearRetryPolicy(e){return{delay:e.delay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var n;return 403!==(null===(n=null==e?void 0:e.status)||void 0===n?void 0:n.statusCode)&&this.maximumRetry>t},getDelay(e,t){var n;return 1e3*((null!==(n=t.retryAfter)&&void 0!==n?n:this.delay)+Math.random())},getGiveupReason(e,t){var n;return this.maximumRetry<=t?"retry attempts exhaused.":403===(null===(n=null==e?void 0:e.status)||void 0===n?void 0:n.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.maximumRetry>10)throw new Error("Maximum retry for linear retry policy can not be more than 10")}}}static ExponentialRetryPolicy(e){return{minimumDelay:e.minimumDelay,maximumDelay:e.maximumDelay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var n;return 403!==(null===(n=null==e?void 0:e.status)||void 0===n?void 0:n.statusCode)&&this.maximumRetry>t},getDelay(e,t){var n;return 1e3*((null!==(n=t.retryAfter)&&void 0!==n?n:Math.min(Math.pow(2,e),this.maximumDelay))+Math.random())},getGiveupReason(e,t){var n;return this.maximumRetry<=t?"retry attempts exhausted.":403===(null===(n=null==e?void 0:e.status)||void 0===n?void 0:n.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.minimumDelay<2)throw new Error("Minimum delay can not be set less than 2 seconds for retry");if(this.maximumDelay)throw new Error("Maximum delay can not be set more than 150 seconds for retry");if(this.maximumRetry>6)throw new Error("Maximum retry for exponential retry policy can not be more than 6")}}}}const He=fe("HANDSHAKE",((e,t)=>({channels:e,groups:t}))),Ve=fe("RECEIVE_MESSAGES",((e,t,n)=>({channels:e,groups:t,cursor:n}))),ze=ye("EMIT_MESSAGES",(e=>e)),We=ye("EMIT_STATUS",(e=>e)),Je=fe("RECEIVE_RECONNECT",(e=>e)),Xe=fe("HANDSHAKE_RECONNECT",(e=>e)),Qe=ge("SUBSCRIPTION_CHANGED",((e,t)=>({channels:e,groups:t}))),Ye=ge("SUBSCRIPTION_RESTORED",((e,t,n,s)=>({channels:e,groups:t,cursor:{timetoken:n,region:null!=s?s:0}}))),Ze=ge("HANDSHAKE_SUCCESS",(e=>e)),et=ge("HANDSHAKE_FAILURE",(e=>e)),tt=ge("HANDSHAKE_RECONNECT_SUCCESS",(e=>({cursor:e}))),nt=ge("HANDSHAKE_RECONNECT_FAILURE",(e=>e)),st=ge("HANDSHAKE_RECONNECT_GIVEUP",(e=>e)),rt=ge("RECEIVE_SUCCESS",((e,t)=>({cursor:e,events:t}))),it=ge("RECEIVE_FAILURE",(e=>e)),at=ge("RECEIVE_RECONNECT_SUCCESS",((e,t)=>({cursor:e,events:t}))),ot=ge("RECEIVE_RECONNECT_FAILURE",(e=>e)),ct=ge("RECEIVING_RECONNECT_GIVEUP",(e=>e)),ut=ge("DISCONNECT",(()=>({}))),lt=ge("RECONNECT",((e,t)=>({cursor:{timetoken:null!=e?e:"",region:null!=t?t:0}}))),ht=ge("UNSUBSCRIBE_ALL",(()=>({})));class dt extends pe{constructor(e,t){super(t),this.on(He.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{handshake:s,presenceState:r,config:i}){n.throwIfAborted();try{const a=yield s(Object.assign({abortSignal:n,channels:t.channels,channelGroups:t.groups,filterExpression:i.filterExpression},i.maintainPresenceState&&{state:r}));return e.transition(Ze(a))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(et(t))}}}))))),this.on(Ve.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{receiveMessages:s,config:r}){n.throwIfAborted();try{const i=yield s({abortSignal:n,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:r.filterExpression});e.transition(rt(i.cursor,i.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;if(!n.aborted)return e.transition(it(t))}}}))))),this.on(ze.type,Se(((e,t,n)=>i(this,[e,t,n],void 0,(function*(e,t,{emitMessages:n}){e.length>0&&n(e)}))))),this.on(We.type,Se(((e,t,n)=>i(this,[e,t,n],void 0,(function*(e,t,{emitStatus:n}){n(e)}))))),this.on(Je.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{receiveMessages:s,delay:r,config:i}){if(!i.retryConfiguration||!i.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(ct(new d(i.retryConfiguration?i.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe messages receive.")));n.throwIfAborted(),yield r(i.retryConfiguration.getDelay(t.attempts,t.reason)),n.throwIfAborted();try{const r=yield s({abortSignal:n,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:i.filterExpression});return e.transition(at(r.cursor,r.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(ot(t))}}}))))),this.on(Xe.type,Se(((t,n,s)=>i(this,[t,n,s],void 0,(function*(t,n,{handshake:s,delay:r,presenceState:i,config:a}){if(!a.retryConfiguration||!a.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(st(new d(a.retryConfiguration?a.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe handshake")));n.throwIfAborted(),yield r(a.retryConfiguration.getDelay(t.attempts,t.reason)),n.throwIfAborted();try{const r=yield s(Object.assign({abortSignal:n,channels:t.channels,channelGroups:t.groups,filterExpression:a.filterExpression},a.maintainPresenceState&&{state:i}));return e.transition(tt(r))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(nt(t))}}})))))}}const pt=new he("HANDSHAKE_FAILED");pt.on(Qe.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),pt.on(lt.type,((e,t)=>wt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor||e.cursor}))),pt.on(Ye.type,((e,t)=>{var n,s;return wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region?t.payload.cursor.region:null!==(s=null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)&&void 0!==s?s:0}})})),pt.on(ht.type,(e=>St.with()));const gt=new he("HANDSHAKE_STOPPED");gt.on(Qe.type,((e,t)=>gt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),gt.on(lt.type,((e,t)=>wt.with(Object.assign(Object.assign({},e),{cursor:t.payload.cursor||e.cursor})))),gt.on(Ye.type,((e,t)=>{var n;return gt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)||0}})})),gt.on(ht.type,(e=>St.with()));const yt=new he("RECEIVE_FAILED");yt.on(lt.type,((e,t)=>{var n;return wt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(n=t.payload.cursor)||void 0===n?void 0:n.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),yt.on(Qe.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),yt.on(Ye.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),yt.on(ht.type,(e=>St.with(void 0)));const ft=new he("RECEIVE_STOPPED");ft.on(Qe.type,((e,t)=>ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),ft.on(Ye.type,((e,t)=>ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),ft.on(lt.type,((e,t)=>{var n;return wt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(n=t.payload.cursor)||void 0===n?void 0:n.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),ft.on(ht.type,(()=>St.with(void 0)));const mt=new he("RECEIVE_RECONNECTING");mt.onEnter((e=>Je(e))),mt.onExit((()=>Je.cancel)),mt.on(at.type,((e,t)=>bt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),mt.on(ot.type,((e,t)=>mt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),mt.on(ct.type,((e,t)=>{var n;return yt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[We({category:h.PNDisconnectedUnexpectedlyCategory,error:null===(n=t.payload)||void 0===n?void 0:n.message})])})),mt.on(ut.type,(e=>ft.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[We({category:h.PNDisconnectedCategory})]))),mt.on(Ye.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),mt.on(Qe.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),mt.on(ht.type,(e=>St.with(void 0,[We({category:h.PNDisconnectedCategory})])));const bt=new he("RECEIVING");bt.onEnter((e=>Ve(e.channels,e.groups,e.cursor))),bt.onExit((()=>Ve.cancel)),bt.on(rt.type,((e,t)=>bt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[ze(t.payload.events)]))),bt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?St.with(void 0):bt.with({cursor:e.cursor,channels:t.payload.channels,groups:t.payload.groups}))),bt.on(Ye.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?St.with(void 0):bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),bt.on(it.type,((e,t)=>mt.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),bt.on(ut.type,(e=>ft.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[We({category:h.PNDisconnectedCategory})]))),bt.on(ht.type,(e=>St.with(void 0,[We({category:h.PNDisconnectedCategory})])));const vt=new he("HANDSHAKE_RECONNECTING");vt.onEnter((e=>Xe(e))),vt.onExit((()=>Xe.cancel)),vt.on(tt.type,((e,t)=>{var n,s;const r={timetoken:(null===(n=e.cursor)||void 0===n?void 0:n.timetoken)?null===(s=e.cursor)||void 0===s?void 0:s.timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region};return bt.with({channels:e.channels,groups:e.groups,cursor:r},[We({category:h.PNConnectedCategory})])})),vt.on(nt.type,((e,t)=>vt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),vt.on(st.type,((e,t)=>{var n;return pt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[We({category:h.PNConnectionErrorCategory,error:null===(n=t.payload)||void 0===n?void 0:n.message})])})),vt.on(ut.type,(e=>gt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),vt.on(Qe.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),vt.on(Ye.type,((e,t)=>{var n,s;return wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:(null===(n=t.payload.cursor)||void 0===n?void 0:n.region)||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),vt.on(ht.type,(e=>St.with(void 0)));const wt=new he("HANDSHAKING");wt.onEnter((e=>He(e.channels,e.groups))),wt.onExit((()=>He.cancel)),wt.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?St.with(void 0):wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),wt.on(Ze.type,((e,t)=>{var n,s;return bt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:(null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.timetoken)?null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.timetoken:t.payload.timetoken,region:t.payload.region}},[We({category:h.PNConnectedCategory})])})),wt.on(et.type,((e,t)=>vt.with({channels:e.channels,groups:e.groups,cursor:e.cursor,attempts:0,reason:t.payload}))),wt.on(ut.type,(e=>gt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),wt.on(Ye.type,((e,t)=>{var n;return wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)||0}})})),wt.on(ht.type,(e=>St.with()));const St=new he("UNSUBSCRIBED");St.on(Qe.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups}))),St.on(Ye.type,((e,t)=>wt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:t.payload.cursor})));class Et{get _engine(){return this.engine}constructor(e){this.engine=new de,this.channels=[],this.groups=[],this.dependencies=e,this.dispatcher=new dt(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(St,void 0)}subscribe({channels:e,channelGroups:t,timetoken:n,withPresence:s}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],s&&(this.channels.map((e=>this.channels.push(`${e}-pnpres`))),this.groups.map((e=>this.groups.push(`${e}-pnpres`)))),n?this.engine.transition(Ye(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])),n)):this.engine.transition(Qe(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])))),this.dependencies.join&&this.dependencies.join({channels:Array.from(new Set(this.channels.filter((e=>!e.endsWith("-pnpres"))))),groups:Array.from(new Set(this.groups.filter((e=>!e.endsWith("-pnpres")))))})}unsubscribe({channels:e=[],channelGroups:t=[]}){const n=B(this.channels,[...e,...e.map((e=>`${e}-pnpres`))]),s=B(this.groups,[...t,...t.map((e=>`${e}-pnpres`))]);if(new Set(this.channels).size!==new Set(n).size||new Set(this.groups).size!==new Set(s).size){const r=H(this.channels,e),i=H(this.groups,t);this.dependencies.presenceState&&(null==r||r.forEach((e=>delete this.dependencies.presenceState[e])),null==i||i.forEach((e=>delete this.dependencies.presenceState[e]))),this.channels=n,this.groups=s,this.engine.transition(Qe(Array.from(new Set(this.channels.slice(0))),Array.from(new Set(this.groups.slice(0))))),this.dependencies.leave&&this.dependencies.leave({channels:r.slice(0),groups:i.slice(0)})}}unsubscribeAll(){this.channels=[],this.groups=[],this.dependencies.presenceState&&Object.keys(this.dependencies.presenceState).forEach((e=>{delete this.dependencies.presenceState[e]})),this.engine.transition(Qe(this.channels.slice(0),this.groups.slice(0))),this.dependencies.leaveAll&&this.dependencies.leaveAll()}reconnect({timetoken:e,region:t}){this.engine.transition(lt(e,t))}disconnect(){this.engine.transition(ut()),this.dependencies.leaveAll&&this.dependencies.leaveAll()}getSubscribedChannels(){return Array.from(new Set(this.channels.slice(0)))}getSubscribedChannelGroups(){return Array.from(new Set(this.groups.slice(0)))}dispose(){this.disconnect(),this._unsubscribeEngine(),this.dispatcher.dispose()}}class Ot extends se{constructor(e){var t,n;super({method:e.sendByPost?K.POST:K.GET}),this.parameters=e,null!==(t=(n=this.parameters).sendByPost)&&void 0!==t||(n.sendByPost=false)}operation(){return ie.PNPublishOperation}validate(){const{message:e,channel:t,keySet:{publishKey:n}}=this.parameters;return t?e?n?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{message:e,channel:t,keySet:n}=this.parameters,s=this.prepareMessagePayload(e);return`/publish/${n.publishKey}/${n.subscribeKey}/0/${$(t)}/0${this.parameters.sendByPost?"":`/${$(s)}`}`}get queryParameters(){const{customMessageType:e,meta:t,replicate:n,storeInHistory:s,ttl:r}=this.parameters,i={};return e&&(i.custom_message_type=e),void 0!==s&&(i.store=s?"1":"0"),void 0!==r&&(i.ttl=r),void 0===n||n||(i.norep="true"),t&&"object"==typeof t&&(i.meta=JSON.stringify(t)),i}get headers(){if(this.parameters.sendByPost)return{"Content-Type":"application/json"}}get body(){return this.prepareMessagePayload(this.parameters.message)}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const n=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof n?n:u(n))}}class kt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNSignalOperation}validate(){const{message:e,channel:t,keySet:{publishKey:n}}=this.parameters;return t?e?n?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{keySet:{publishKey:e,subscribeKey:t},channel:n,message:s}=this.parameters,r=JSON.stringify(s);return`/signal/${e}/${t}/0/${$(n)}/0/${$(r)}`}get queryParameters(){const{customMessageType:e}=this.parameters,t={};return e&&(t.custom_message_type=e),t}}class Ct extends oe{operation(){return ie.PNReceiveMessagesOperation}validate(){const e=super.validate();return e||(this.parameters.timetoken?this.parameters.region?void 0:"region can not be empty":"timetoken can not be empty")}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${L(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,timetoken:n,region:s}=this.parameters,r={ee:""};return e&&e.length>0&&(r["channel-group"]=e.sort().join(",")),t&&t.length>0&&(r["filter-expr"]=t),"string"==typeof n?n&&n.length>0&&(r.tt=n):n&&n>0&&(r.tt=n),s&&(r.tr=s),r}}class Nt extends oe{operation(){return ie.PNHandshakeOperation}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${L(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,state:n}=this.parameters,s={tt:0,ee:""};return e&&e.length>0&&(s["channel-group"]=e.sort().join(",")),t&&t.length>0&&(s["filter-expr"]=t),n&&Object.keys(n).length>0&&(s.state=JSON.stringify(n)),s}}class Pt extends se{constructor(e){var t,n,s,r;super(),this.parameters=e,null!==(t=(s=this.parameters).channels)&&void 0!==t||(s.channels=[]),null!==(n=(r=this.parameters).channelGroups)&&void 0!==n||(r.channelGroups=[])}operation(){return ie.PNGetStateOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:n}=this.parameters;if(!e)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e),{channels:n=[],channelGroups:s=[]}=this.parameters,r={channels:{}};return 1===n.length&&0===s.length?r.channels[n[0]]=t.payload:r.channels=t.payload,r}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:n}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${L(null!=n?n:[],",")}/uuid/${t}`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.join(",")}:{}}}class Mt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNSetStateOperation}validate(){const{keySet:{subscribeKey:e},state:t,channels:n=[],channelGroups:s=[]}=this.parameters;return e?t?0===(null==n?void 0:n.length)&&0===(null==s?void 0:s.length)?"Please provide a list of channels and/or channel-groups":void 0:"Missing State":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{state:this.deserializeResponse(e).payload}}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:n}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${L(null!=n?n:[],",")}/uuid/${$(t)}/data`}get queryParameters(){const{channelGroups:e,state:t}=this.parameters,n={state:JSON.stringify(t)};return e&&0!==e.length&&(n["channel-group"]=e.join(",")),n}}class _t extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNHeartbeatOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:n=[]}=this.parameters;return e?0===t.length&&0===n.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channels:t}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${L(null!=t?t:[],",")}/heartbeat`}get queryParameters(){const{channelGroups:e,state:t,heartbeat:n}=this.parameters,s={heartbeat:`${n}`};return e&&0!==e.length&&(s["channel-group"]=e.join(",")),t&&(s.state=JSON.stringify(t)),s}}class 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 ie.PNUnsubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:n=[]}=this.parameters;return e?0===t.length&&0===n.length?"At least one `channel` or `channel group` should be provided.":void 0:"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){var e;const{keySet:{subscribeKey:t},channels:n}=this.parameters;return`/v2/presence/sub-key/${t}/channel/${L(null!==(e=null==n?void 0:n.sort())&&void 0!==e?e:[],",")}/leave`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.sort().join(",")}:{}}}class At extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNWhereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return t.payload?{channels:t.payload.channels}:{channels:[]}}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/presence/sub-key/${e}/uuid/${$(t)}`}}class It extends se{constructor(e){var t,n,s,r,i,a;super(),this.parameters=e,null!==(t=(r=this.parameters).queryParameters)&&void 0!==t||(r.queryParameters={}),null!==(n=(i=this.parameters).includeUUIDs)&&void 0!==n||(i.includeUUIDs=true),null!==(s=(a=this.parameters).includeState)&&void 0!==s||(a.includeState=false)}operation(){const{channels:e=[],channelGroups:t=[]}=this.parameters;return 0===e.length&&0===t.length?ie.PNGlobalHereNowOperation:ie.PNHereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t,n;const s=this.deserializeResponse(e),r="occupancy"in s?1:s.payload.total_channels,i="occupancy"in s?s.occupancy:s.payload.total_occupancy,a={};let o={};if("occupancy"in s){const e=this.parameters.channels[0];o[e]={uuids:null!==(t=s.uuids)&&void 0!==t?t:[],occupancy:i}}else o=null!==(n=s.payload.channels)&&void 0!==n?n:{};return Object.keys(o).forEach((e=>{const t=o[e];a[e]={occupants:this.parameters.includeUUIDs?t.uuids.map((e=>"string"==typeof e?{uuid:e,state:null}:e)):[],name:e,occupancy:t.occupancy}})),{totalChannels:r,totalOccupancy:i,channels:a}}))}get path(){const{keySet:{subscribeKey:e},channels:t,channelGroups:n}=this.parameters;let s=`/v2/presence/sub-key/${e}`;return(t&&t.length>0||n&&n.length>0)&&(s+=`/channel/${L(null!=t?t:[],",")}`),s}get queryParameters(){const{channelGroups:e,includeUUIDs:t,includeState:n,queryParameters:s}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign({},t?{}:{disable_uuids:"1"}),null!=n&&n?{state:"1"}:{}),e&&e.length>0?{"channel-group":e.join(",")}:{}),s)}}class Ft extends se{constructor(e){super({method:K.DELETE}),this.parameters=e}operation(){return ie.PNDeleteMessagesOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v3/history/sub-key/${e}/channel/${$(t)}`}get queryParameters(){const{start:e,end:t}=this.parameters;return Object.assign(Object.assign({},e?{start:e}:{}),t?{end:t}:{})}}class Tt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNMessageCounts}validate(){const{keySet:{subscribeKey:e},channels:t,timetoken:n,channelTimetokens:s}=this.parameters;return e?t?n&&s?"`timetoken` and `channelTimetokens` are incompatible together":n||s?s&&s.length>1&&s.length!==t.length?"Length of `channelTimetokens` and `channels` do not match":void 0:"`timetoken` or `channelTimetokens` need to be set":"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e).channels}}))}get path(){return`/v3/history/sub-key/${this.parameters.keySet.subscribeKey}/message-counts/${L(this.parameters.channels)}`}get queryParameters(){let{channelTimetokens:e}=this.parameters;return this.parameters.timetoken&&(e=[this.parameters.timetoken]),Object.assign(Object.assign({},1===e.length?{timetoken:e[0]}:{}),e.length>1?{channelsTimetoken:e.join(",")}:{})}}class Rt extends se{constructor(e){var t,n,s;super(),this.parameters=e,e.count?e.count=Math.min(e.count,100):e.count=100,null!==(t=e.stringifiedTimeToken)&&void 0!==t||(e.stringifiedTimeToken=false),null!==(n=e.includeMeta)&&void 0!==n||(e.includeMeta=false),null!==(s=e.logVerbosity)&&void 0!==s||(e.logVerbosity=false)}operation(){return ie.PNHistoryOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e),n=t[0],s=t[1],r=t[2];return Array.isArray(n)?{messages:n.map((e=>{const t=this.processPayload(e.message),n={entry:t.payload,timetoken:e.timetoken};return t.error&&(n.error=t.error),e.meta&&(n.meta=e.meta),n})),startTimeToken:s,endTimeToken:r}:{messages:[],startTimeToken:s,endTimeToken:r}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/history/sub-key/${e}/channel/${$(t)}`}get queryParameters(){const{start:e,end:t,reverse:n,count:s,stringifiedTimeToken:r,includeMeta:i}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:s,include_token:"true"},e?{start:e}:{}),t?{end:t}:{}),r?{string_message_token:"true"}:{}),null!=n?{reverse:n.toString()}:{}),i?{include_meta:"true"}:{})}processPayload(e){const{crypto:t,logVerbosity:n}=this.parameters;if(!t||"string"!=typeof e)return{payload:e};let s,r;try{const n=t.decrypt(e);s=n instanceof ArrayBuffer?JSON.parse(Rt.decoder.decode(n)):n}catch(t){n&&console.log("decryption error",t.message),s=e,r=`Error while decrypting message content: ${t.message}`}return{payload:s,error:r}}}var Ut;!function(e){e[e.Message=-1]="Message",e[e.Files=4]="Files"}(Ut||(Ut={}));class xt extends se{constructor(e){var t,n,s,r,i;super(),this.parameters=e;const a=null!==(t=e.includeMessageActions)&&void 0!==t&&t,o=e.channels.length>1||a?25:100;e.count?e.count=Math.min(e.count,o):e.count=o,e.includeUuid?e.includeUUID=e.includeUuid:null!==(n=e.includeUUID)&&void 0!==n||(e.includeUUID=true),null!==(s=e.stringifiedTimeToken)&&void 0!==s||(e.stringifiedTimeToken=false),null!==(r=e.includeMessageType)&&void 0!==r||(e.includeMessageType=true),null!==(i=e.logVerbosity)&&void 0!==i||(e.logVerbosity=false)}operation(){return ie.PNFetchMessagesOperation}validate(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:n}=this.parameters;return e?t?void 0!==n&&n&&t.length>1?"History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.":void 0:"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t;const n=this.deserializeResponse(e),s=null!==(t=n.channels)&&void 0!==t?t:{},r={};return Object.keys(s).forEach((e=>{r[e]=s[e].map((t=>{null===t.message_type&&(t.message_type=Ut.Message);const n=this.processPayload(e,t),s=Object.assign(Object.assign({channel:e,timetoken:t.timetoken,message:n.payload,messageType:t.message_type},t.custom_message_type?{customMessageType:t.custom_message_type}:{}),{uuid:t.uuid});if(t.actions){const e=s;e.actions=t.actions,e.data=t.actions}return t.meta&&(s.meta=t.meta),n.error&&(s.error=n.error),s}))})),n.more?{channels:r,more:n.more}:{channels:r}}))}get path(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:n}=this.parameters;return`/v3/${n?"history-with-actions":"history"}/sub-key/${e}/channel/${L(t)}`}get queryParameters(){const{start:e,end:t,count:n,includeCustomMessageType:s,includeMessageType:r,includeMeta:i,includeUUID:a,stringifiedTimeToken:o}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({max:n},e?{start:e}:{}),t?{end:t}:{}),o?{string_message_token:"true"}:{}),void 0!==i&&i?{include_meta:"true"}:{}),a?{include_uuid:"true"}:{}),null!=s?{include_custom_message_type:s?"true":"false"}:{}),r?{include_message_type:"true"}:{})}processPayload(e,t){const{crypto:n,logVerbosity:s}=this.parameters;if(!n||"string"!=typeof t.message)return{payload:t.message};let r,i;try{const e=n.decrypt(t.message);r=e instanceof ArrayBuffer?JSON.parse(xt.decoder.decode(e)):e}catch(e){s&&console.log("decryption error",e.message),r=t.message,i=`Error while decrypting message content: ${e.message}`}if(!i&&r&&t.message_type==Ut.Files&&"object"==typeof r&&this.isFileMessage(r)){const t=r;return{payload:{message:t.message,file:Object.assign(Object.assign({},t.file),{url:this.parameters.getFileUrl({channel:e,id:t.file.id,name:t.file.name})})},error:i}}return{payload:r,error:i}}isFileMessage(e){return void 0!==e.file}}class Dt extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNGetMessageActionsOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);let n=null,s=null;return t.data.length>0&&(n=t.data[0].actionTimetoken,s=t.data[t.data.length-1].actionTimetoken),{data:t.data,more:t.more,start:n,end:s}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/message-actions/${e}/channel/${$(t)}`}get queryParameters(){const{limit:e,start:t,end:n}=this.parameters;return Object.assign(Object.assign(Object.assign({},t?{start:t}:{}),n?{end:n}:{}),e?{limit:e}:{})}}class qt extends se{constructor(e){super({method:K.POST}),this.parameters=e}operation(){return ie.PNAddMessageActionOperation}validate(){const{keySet:{subscribeKey:e},action:t,channel:n,messageTimetoken:s}=this.parameters;return e?n?s?t?t.value?t.type?t.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message timetoken":"Missing message channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((({data:e})=>({data:e})))}))}get path(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:n}=this.parameters;return`/v1/message-actions/${e}/channel/${$(t)}/message/${n}`}get headers(){return{"Content-Type":"application/json"}}get body(){return JSON.stringify(this.parameters.action)}}class Gt extends se{constructor(e){super({method:K.DELETE}),this.parameters=e}operation(){return ie.PNRemoveMessageActionOperation}validate(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:n,actionTimetoken:s}=this.parameters;return e?t?n?s?void 0:"Missing action timetoken":"Missing message timetoken":"Missing message action channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((({data:e})=>({data:e})))}))}get path(){const{keySet:{subscribeKey:e},channel:t,actionTimetoken:n,messageTimetoken:s}=this.parameters;return`/v1/message-actions/${e}/channel/${$(t)}/message/${s}/action/${n}`}}class Kt extends se{constructor(e){var t,n;super(),this.parameters=e,null!==(t=(n=this.parameters).storeInHistory)&&void 0!==t||(n.storeInHistory=true)}operation(){return ie.PNPublishFileMessageOperation}validate(){const{channel:e,fileId:t,fileName:n}=this.parameters;return e?t?n?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{message:e,channel:t,keySet:{publishKey:n,subscribeKey:s},fileId:r,fileName:i}=this.parameters,a=Object.assign({file:{name:i,id:r}},e?{message:e}:{});return`/v1/files/publish-file/${n}/${s}/0/${$(t)}/0/${$(this.prepareMessagePayload(a))}`}get queryParameters(){const{customMessageType:e,storeInHistory:t,ttl:n,meta:s}=this.parameters;return Object.assign(Object.assign(Object.assign({store:t?"1":"0"},e?{custom_message_type:e}:{}),n?{ttl:n}:{}),s&&"object"==typeof s?{meta:JSON.stringify(s)}:{})}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const n=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof n?n:u(n))}}class $t extends se{constructor(e){super({method:K.LOCAL}),this.parameters=e}operation(){return ie.PNGetFileUrlOperation}validate(){const{channel:e,id:t,name:n}=this.parameters;return e?t?n?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return e.url}))}get path(){const{channel:e,id:t,name:n,keySet:{subscribeKey:s}}=this.parameters;return`/v1/files/${s}/channels/${$(e)}/files/${t}/${n}`}}class Lt extends se{constructor(e){super({method:K.DELETE}),this.parameters=e}operation(){return ie.PNDeleteFileOperation}validate(){const{channel:e,id:t,name:n}=this.parameters;return e?t?n?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}get path(){const{keySet:{subscribeKey:e},id:t,channel:n,name:s}=this.parameters;return`/v1/files/${e}/channels/${$(n)}/files/${t}/${s}`}}class Bt extends se{constructor(e){var t,n;super(),this.parameters=e,null!==(t=(n=this.parameters).limit)&&void 0!==t||(n.limit=100)}operation(){return ie.PNListFilesOperation}validate(){if(!this.parameters.channel)return"channel can't be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${$(t)}/files`}get queryParameters(){const{limit:e,next:t}=this.parameters;return Object.assign({limit:e},t?{next:t}:{})}}class Ht extends se{constructor(e){super({method:K.POST}),this.parameters=e}operation(){return ie.PNGenerateUploadUrlOperation}validate(){return this.parameters.channel?this.parameters.name?void 0:"'name' can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return{id:t.data.id,name:t.data.name,url:t.file_upload_request.url,formFields:t.file_upload_request.form_fields}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${$(t)}/generate-upload-url`}get headers(){return{"Content-Type":"application/json"}}get body(){return JSON.stringify({name:this.parameters.name})}}class Vt extends se{constructor(e){super({method:K.POST}),this.parameters=e;const t=e.file.mimeType;t&&(e.formFields=e.formFields.map((e=>"Content-Type"===e.name?{name:e.name,value:t}:e)))}operation(){return ie.PNPublishFileOperation}validate(){const{fileId:e,fileName:t,file:n,uploadUrl:s}=this.parameters;return e?t?n?s?void 0:"Validation failed: file upload 'url' can't be empty":"Validation failed: 'file' can't be empty":"Validation failed: file 'name' can't be empty":"Validation failed: file 'id' can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{status:e.status,message:e.body?Vt.decoder.decode(e.body):"OK"}}))}request(){return Object.assign(Object.assign({},super.request()),{origin:new URL(this.parameters.uploadUrl).origin,timeout:300})}get path(){const{pathname:e,search:t}=new URL(this.parameters.uploadUrl);return`${e}${t}`}get body(){return this.parameters.file}get formData(){return this.parameters.formFields}}class zt{constructor(e){var t;if(this.parameters=e,this.file=null===(t=this.parameters.PubNubFile)||void 0===t?void 0:t.create(e.file),!this.file)throw new Error("File upload error: unable to create File object.")}process(){return i(this,void 0,void 0,(function*(){let e,t;return this.generateFileUploadUrl().then((n=>(e=n.name,t=n.id,this.uploadFile(n)))).then((e=>{if(204!==e.status)throw new d("Upload to bucket was unsuccessful",{error:!0,statusCode:e.status,category:h.PNUnknownCategory,operation:ie.PNPublishFileOperation,errorData:{message:e.message}})})).then((()=>this.publishFileMessage(t,e))).catch((e=>{if(e instanceof d)throw e;const t=e instanceof A?e:A.create(e);throw new d("File upload error.",t.toStatus(ie.PNPublishFileOperation))}))}))}generateFileUploadUrl(){return i(this,void 0,void 0,(function*(){const e=new Ht(Object.assign(Object.assign({},this.parameters),{name:this.file.name,keySet:this.parameters.keySet}));return this.parameters.sendRequest(e)}))}uploadFile(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,PubNubFile:n,crypto:s,cryptography:r}=this.parameters,{id:i,name:a,url:o,formFields:c}=e;return this.parameters.PubNubFile.supportsEncryptFile&&(!t&&s?this.file=yield s.encryptFile(this.file,n):t&&r&&(this.file=yield r.encryptFile(t,this.file,n))),this.parameters.sendRequest(new Vt({fileId:i,fileName:a,file:this.file,uploadUrl:o,formFields:c}))}))}publishFileMessage(e,t){return i(this,void 0,void 0,(function*(){var n,s,r,i;let a,o={timetoken:"0"},c=this.parameters.fileUploadPublishRetryLimit,u=!1;do{try{o=yield this.parameters.publishFile(Object.assign(Object.assign({},this.parameters),{fileId:e,fileName:t})),u=!0}catch(e){e instanceof d&&(a=e),c-=1}}while(!u&&c>0);if(u)return{status:200,timetoken:o.timetoken,id:e,name:t};throw new d("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{error:!0,category:null!==(s=null===(n=a.status)||void 0===n?void 0:n.category)&&void 0!==s?s:h.PNUnknownCategory,statusCode:null!==(i=null===(r=a.status)||void 0===r?void 0:r.statusCode)&&void 0!==i?i:0,channel:this.parameters.channel,id:e,name:t})}))}}class Wt{subscribe(e){const t=null==e?void 0:e.timetoken;this.pubnub.registerSubscribeCapable(this),this.pubnub.subscribe(Object.assign({channels:this.channelNames,channelGroups:this.groupNames},null!==t&&""!==t&&{timetoken:t}))}unsubscribe(){this.pubnub.unregisterSubscribeCapable(this);const{channels:e,channelGroups:t}=this.pubnub.getSubscribeCapableEntities(),n=this.groupNames.filter((e=>!t.includes(e))),s=this.channelNames.filter((t=>!e.includes(t)));0===s.length&&0===n.length||this.pubnub.unsubscribe({channels:s,channelGroups:n})}set onMessage(e){this.listener.message=e}set onPresence(e){this.listener.presence=e}set onSignal(e){this.listener.signal=e}set onObjects(e){this.listener.objects=e}set onMessageAction(e){this.listener.messageAction=e}set onFile(e){this.listener.file=e}addListener(e){this.eventEmitter.addListener(e,this.channelNames,this.groupNames)}removeListener(e){this.eventEmitter.removeListener(e,this.channelNames,this.groupNames)}get channels(){return this.channelNames.slice(0)}get channelGroups(){return this.groupNames.slice(0)}}class Jt extends Wt{constructor({channels:e=[],channelGroups:t=[],subscriptionOptions:n,eventEmitter:s,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.subscriptionList=[],this.options=n,this.eventEmitter=s,this.pubnub=r,e.forEach((e=>{const t=this.pubnub.channel(e).subscription(this.options);this.channelNames=[...this.channelNames,...t.channels],this.subscriptionList.push(t)})),t.forEach((e=>{const t=this.pubnub.channelGroup(e).subscription(this.options);this.groupNames=[...this.groupNames,...t.channelGroups],this.subscriptionList.push(t)})),this.listener={},s.addListener(this.listener,this.channelNames,this.groupNames)}addSubscription(e){this.subscriptionList.push(e),this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscription(e){const t=e.channels,n=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!n.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>t!==e)),this.eventEmitter.removeListener(this.listener,t,n)}addSubscriptionSet(e){this.subscriptionList=[...this.subscriptionList,...e.subscriptions],this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscriptionSet(e){const t=e.channels,n=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!n.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>!e.subscriptions.includes(t))),this.eventEmitter.removeListener(this.listener,t,n)}get subscriptions(){return this.subscriptionList.slice(0)}}class Xt extends Wt{constructor({channels:e,channelGroups:t,subscriptionOptions:n,eventEmitter:s,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.channelNames=e,this.groupNames=t,this.options=n,this.pubnub=r,this.eventEmitter=s,this.listener={},s.addListener(this.listener,this.channelNames,this.groupNames)}addSubscription(e){return new Jt({channels:[...this.channelNames,...e.channels],channelGroups:[...this.groupNames,...e.channelGroups],subscriptionOptions:Object.assign(Object.assign({},this.options),null==e?void 0:e.options),eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Qt{constructor(e,t,n){this.eventEmitter=t,this.pubnub=n,this.id=e}subscription(e){return new Xt({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Yt{constructor(e,t,n){this.eventEmitter=t,this.pubnub=n,this.name=e}subscription(e){{const t=[this.name];return(null==e?void 0:e.receivePresenceEvents)&&!this.name.endsWith("-pnpres")&&t.push(`${this.name}-pnpres`),new Xt({channels:[],channelGroups:t,subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}}class Zt{constructor(e,t,n){this.eventEmitter=t,this.pubnub=n,this.id=e}subscription(e){return new Xt({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class en{constructor(e,t,n){this.eventEmitter=t,this.pubnub=n,this.name=e}subscription(e){{const t=[this.name];return(null==e?void 0:e.receivePresenceEvents)&&!this.name.endsWith("-pnpres")&&t.push(`${this.name}-pnpres`),new Xt({channels:t,channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}}class tn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNRemoveChannelsFromGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:n}=this.parameters;return e?n?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${$(t)}`}get queryParameters(){return{remove:this.parameters.channels.join(",")}}}class nn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNAddChannelsToGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:n}=this.parameters;return e?n?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${$(t)}`}get queryParameters(){return{add:this.parameters.channels.join(",")}}}class sn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNChannelsForGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e).payload.channels}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${$(t)}`}}class rn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNRemoveGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${$(t)}/remove`}}class an extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNChannelGroupsOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{groups:this.deserializeResponse(e).payload.groups}}))}get path(){return`/v1/channel-registration/sub-key/${this.parameters.keySet.subscribeKey}/channel-group`}}class on{constructor(e,t){this.sendRequest=t,this.keySet=e}listChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new sn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}listGroups(e){return i(this,void 0,void 0,(function*(){const t=new an({keySet:this.keySet});return e?this.sendRequest(t,e):this.sendRequest(t)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new nn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new tn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}deleteGroup(e,t){return i(this,void 0,void 0,(function*(){const n=new rn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}}class cn extends se{constructor(e){var t,n;super(),this.parameters=e,"apns2"===this.parameters.pushGateway&&(null!==(t=(n=this.parameters).environment)&&void 0!==t||(n.environment="development")),this.parameters.count&&this.parameters.count>1e3&&(this.parameters.count=1e3)}operation(){throw Error("Should be implemented in subclass.")}validate(){const{keySet:{subscribeKey:e},action:t,device:n,pushGateway:s}=this.parameters;return e?n?"add"!==t&&"remove"!==t||"channels"in this.parameters&&0!==this.parameters.channels.length?s?"apns2"!==this.parameters.pushGateway||this.parameters.topic?void 0:"Missing APNS2 topic":"Missing GW Type (pushGateway: gcm or apns2)":"Missing Channels":"Missing Device ID (device)":"Missing Subscribe Key"}get path(){const{keySet:{subscribeKey:e},action:t,device:n,pushGateway:s}=this.parameters;let r="apns2"===s?`/v2/push/sub-key/${e}/devices-apns2/${n}`:`/v1/push/sub-key/${e}/devices/${n}`;return"remove-device"===t&&(r=`${r}/remove`),r}get queryParameters(){const{start:e,count:t}=this.parameters;let n=Object.assign(Object.assign({type:this.parameters.pushGateway},e?{start:e}:{}),t&&t>0?{count:t}:{});if("channels"in this.parameters&&(n[this.parameters.action]=this.parameters.channels.join(",")),"apns2"===this.parameters.pushGateway){const{environment:e,topic:t}=this.parameters;n=Object.assign(Object.assign({},n),{environment:e,topic:t})}return n}}class un extends cn{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove"}))}operation(){return ie.PNRemovePushNotificationEnabledChannelsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class ln extends cn{constructor(e){super(Object.assign(Object.assign({},e),{action:"list"}))}operation(){return ie.PNPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e)}}))}}class hn extends cn{constructor(e){super(Object.assign(Object.assign({},e),{action:"add"}))}operation(){return ie.PNAddPushNotificationEnabledChannelsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class dn extends cn{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove-device"}))}operation(){return ie.PNRemoveAllPushNotificationsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class pn{constructor(e,t){this.sendRequest=t,this.keySet=e}listChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new ln(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new hn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const n=new un(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}deleteDevice(e,t){return i(this,void 0,void 0,(function*(){const n=new dn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}}class gn extends se{constructor(e){var t,n,s,r,i,a;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(i=e.include).customFields)&&void 0!==n||(i.customFields=false),null!==(s=(a=e.include).totalCount)&&void 0!==s||(a.totalCount=false),null!==(r=e.limit)&&void 0!==r||(e.limit=100)}operation(){return ie.PNGetAllChannelMetadataOperation}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";return i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(","),count:`${e.totalCount}`},n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class yn extends se{constructor(e){super({method:K.DELETE}),this.parameters=e}operation(){return ie.PNRemoveChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}`}}class fn extends se{constructor(e){var t,n,s,r,i,a,o,c,u,l,h,d,p,g,y,f,m,b;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(h=e.include).customFields)&&void 0!==n||(h.customFields=false),null!==(s=(d=e.include).totalCount)&&void 0!==s||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(y=e.include).channelFields)&&void 0!==a||(y.channelFields=false),null!==(o=(f=e.include).customChannelFields)&&void 0!==o||(f.customChannelFields=false),null!==(c=(m=e.include).channelStatusField)&&void 0!==c||(m.channelStatusField=false),null!==(u=(b=e.include).channelTypeField)&&void 0!==u||(b.channelTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNGetMembershipsOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=[];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.channelFields&&a.push("channel"),e.channelStatusField&&a.push("channel.status"),e.channelTypeField&&a.push("channel.type"),e.customChannelFields&&a.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class mn extends se{constructor(e){var t,n,s,r,i,a,o,c,u,l,h,d,p,g,y,f,m,b;super({method:K.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(h=e.include).customFields)&&void 0!==n||(h.customFields=false),null!==(s=(d=e.include).totalCount)&&void 0!==s||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(y=e.include).channelFields)&&void 0!==a||(y.channelFields=false),null!==(o=(f=e.include).customChannelFields)&&void 0!==o||(f.customChannelFields=false),null!==(c=(m=e.include).channelStatusField)&&void 0!==c||(m.channelStatusField=false),null!==(u=(b=e.include).channelTypeField)&&void 0!==u||(b.channelTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNSetMembershipsOperation}validate(){const{uuid:e,channels:t}=this.parameters;return e?t&&0!==t.length?void 0:"Channels cannot be empty":"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=["channel.status","channel.type","status"];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.channelFields&&a.push("channel"),e.channelStatusField&&a.push("channel.status"),e.channelTypeField&&a.push("channel.type"),e.customChannelFields&&a.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{channels:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},status:e.status,type:e.type,custom:e.custom}))})}}class bn extends se{constructor(e){var t,n,s,r;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(r=e.include).customFields)&&void 0!==n||(r.customFields=false),null!==(s=e.limit)&&void 0!==s||(e.limit=100)}operation(){return ie.PNGetAllUUIDMetadataOperation}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";return i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(",")},void 0!==e.totalCount?{count:`${e.totalCount}`}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class vn extends se{constructor(e){var t,n,s;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(s=e.include).customFields)&&void 0!==n||(s.customFields=true)}operation(){return ie.PNGetChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}}class wn extends se{constructor(e){var t,n,s;super({method:K.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(s=e.include).customFields)&&void 0!==n||(s.customFields=true)}operation(){return ie.PNSetChannelMetadataOperation}validate(){return this.parameters.channel?this.parameters.data?void 0:"Data cannot be empty":"Channel cannot be empty"}get headers(){return this.parameters.ifMatchesEtag?{"If-Match":this.parameters.ifMatchesEtag}:void 0}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Sn extends se{constructor(e){super({method:K.DELETE}),this.parameters=e,this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNRemoveUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}`}}class En extends se{constructor(e){var t,n,s,r,i,a,o,c,u,l,h,d,p,g,y,f,m,b;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(h=e.include).customFields)&&void 0!==n||(h.customFields=false),null!==(s=(d=e.include).totalCount)&&void 0!==s||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(y=e.include).UUIDFields)&&void 0!==a||(y.UUIDFields=false),null!==(o=(f=e.include).customUUIDFields)&&void 0!==o||(f.customUUIDFields=false),null!==(c=(m=e.include).UUIDStatusField)&&void 0!==c||(m.UUIDStatusField=false),null!==(u=(b=e.include).UUIDTypeField)&&void 0!==u||(b.UUIDTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100)}operation(){return ie.PNSetMembersOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=[];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.UUIDFields&&a.push("uuid"),e.UUIDStatusField&&a.push("uuid.status"),e.UUIDTypeField&&a.push("uuid.type"),e.customUUIDFields&&a.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class On extends se{constructor(e){var t,n,s,r,i,a,o,c,u,l,h,d,p,g,y,f,m,b;super({method:K.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(h=e.include).customFields)&&void 0!==n||(h.customFields=false),null!==(s=(d=e.include).totalCount)&&void 0!==s||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(y=e.include).UUIDFields)&&void 0!==a||(y.UUIDFields=false),null!==(o=(f=e.include).customUUIDFields)&&void 0!==o||(f.customUUIDFields=false),null!==(c=(m=e.include).UUIDStatusField)&&void 0!==c||(m.UUIDStatusField=false),null!==(u=(b=e.include).UUIDTypeField)&&void 0!==u||(b.UUIDTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100)}operation(){return ie.PNSetMembersOperation}validate(){const{channel:e,uuids:t}=this.parameters;return e?t&&0!==t.length?void 0:"UUIDs cannot be empty":"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${$(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:n,sort:s,limit:r}=this.parameters;let i="";i="string"==typeof s?s:Object.entries(null!=s?s:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=["uuid.status","uuid.type","type"];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.UUIDFields&&a.push("uuid"),e.UUIDStatusField&&a.push("uuid.status"),e.UUIDTypeField&&a.push("uuid.type"),e.customUUIDFields&&a.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),n?{filter:n}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{uuids:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},status:e.status,type:e.type,custom:e.custom}))})}}class kn extends se{constructor(e){var t,n,s;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(s=e.include).customFields)&&void 0!==n||(s.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNGetUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}`}get queryParameters(){const{include:e}=this.parameters;return{include:["status","type",...e.customFields?["custom"]:[]].join(",")}}}class Cn extends se{constructor(e){var t,n,s;super({method:K.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(n=(s=e.include).customFields)&&void 0!==n||(s.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ie.PNSetUUIDMetadataOperation}validate(){return this.parameters.uuid?this.parameters.data?void 0:"Data cannot be empty":"'uuid' cannot be empty"}get headers(){return this.parameters.ifMatchesEtag?{"If-Match":this.parameters.ifMatchesEtag}:void 0}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${$(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Nn{constructor(e,t){this.keySet=e.keySet,this.configuration=e,this.sendRequest=t}getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllUUIDMetadata(e,t)}))}_getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const s=new bn(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getUUIDMetadata(e,t)}))}_getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var n;const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),s.userId&&(s.uuid=s.userId),null!==(n=s.uuid)&&void 0!==n||(s.uuid=this.configuration.userId);const r=new kn(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setUUIDMetadata(e,t)}))}_setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var n;e.userId&&(e.uuid=e.userId),null!==(n=e.uuid)&&void 0!==n||(e.uuid=this.configuration.userId);const s=new Cn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeUUIDMetadata(e,t)}))}_removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var n;const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),s.userId&&(s.uuid=s.userId),null!==(n=s.uuid)&&void 0!==n||(s.uuid=this.configuration.userId);const r=new Sn(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllChannelMetadata(e,t)}))}_getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const s=new gn(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getChannelMetadata(e,t)}))}_getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=new vn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setChannelMetadata(e,t)}))}_setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=new wn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeChannelMetadata(e,t)}))}_removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const n=new yn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const n=new En(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const n=new On(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const n=new On(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getMemberships(e,t){return i(this,void 0,void 0,(function*(){var n;const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),s.userId&&(s.uuid=s.userId),null!==(n=s.uuid)&&void 0!==n||(s.uuid=this.configuration.userId);const r=new fn(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setMemberships(e,t){return i(this,void 0,void 0,(function*(){var n;e.userId&&(e.uuid=e.userId),null!==(n=e.uuid)&&void 0!==n||(e.uuid=this.configuration.userId);const s=new mn(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var n;e.userId&&(e.uuid=e.userId),null!==(n=e.uuid)&&void 0!==n||(e.uuid=this.configuration.userId);const s=new mn(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){var n,s;if("spaceId"in e){const s=e,r={channel:null!==(n=s.spaceId)&&void 0!==n?n:s.channel,filter:s.filter,limit:s.limit,page:s.page,include:Object.assign({},s.include),sort:s.sort?Object.fromEntries(Object.entries(s.sort).map((([e,t])=>[e.replace("user","uuid"),t]))):void 0},i=e=>({status:e.status,data:e.data.map((e=>({user:e.uuid,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getChannelMembers(r,((e,n)=>{t(e,n?i(n):n)})):this.getChannelMembers(r).then(i)}const r=e,i={uuid:null!==(s=r.userId)&&void 0!==s?s:r.uuid,filter:r.filter,limit:r.limit,page:r.page,include:Object.assign({},r.include),sort:r.sort?Object.fromEntries(Object.entries(r.sort).map((([e,t])=>[e.replace("space","channel"),t]))):void 0},a=e=>({status:e.status,data:e.data.map((e=>({space:e.channel,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getMemberships(i,((e,n)=>{t(e,n?a(n):n)})):this.getMemberships(i).then(a)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){var n,s,r,i,a,o;if("spaceId"in e){const i=e,a={channel:null!==(n=i.spaceId)&&void 0!==n?n:i.channel,uuids:null!==(r=null===(s=i.users)||void 0===s?void 0:s.map((e=>"string"==typeof e?e:{id:e.userId,custom:e.custom})))&&void 0!==r?r:i.uuids,limit:0};return t?this.setChannelMembers(a,t):this.setChannelMembers(a)}const c=e,u={uuid:null!==(i=c.userId)&&void 0!==i?i:c.uuid,channels:null!==(o=null===(a=c.spaces)||void 0===a?void 0:a.map((e=>"string"==typeof e?e:{id:e.spaceId,custom:e.custom})))&&void 0!==o?o:c.channels,limit:0};return t?this.setMemberships(u,t):this.setMemberships(u)}))}}class Pn extends se{constructor(){super()}operation(){return ie.PNTimeOperation}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[0]}}))}get path(){return"/time/0"}}class Mn extends se{constructor(e){super(),this.parameters=e}operation(){return ie.PNDownloadFileOperation}validate(){const{channel:e,id:t,name:n}=this.parameters;return e?t?n?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,crypto:n,cryptography:s,name:r,PubNubFile:i}=this.parameters,a=e.headers["content-type"];let o,c=e.body;return i.supportsEncryptFile&&(t||n)&&(t&&s?c=yield s.decrypt(t,c):!t&&n&&(o=yield n.decryptFile(i.create({data:c,name:r,mimeType:a}),i))),o||i.create({data:c,name:r,mimeType:a})}))}get path(){const{keySet:{subscribeKey:e},channel:t,id:n,name:s}=this.parameters;return`/v1/files/${e}/channels/${$(t)}/files/${n}/${s}`}}class _n{static notificationPayload(e,t){return new ne(e,t)}static generateUUID(){return x.createUUID()}constructor(e){if(this._configuration=e.configuration,this.cryptography=e.cryptography,this.tokenManager=e.tokenManager,this.transport=e.transport,this.crypto=e.crypto,this._objects=new Nn(this._configuration,this.sendRequest.bind(this)),this._channelGroups=new on(this._configuration.keySet,this.sendRequest.bind(this)),this._push=new pn(this._configuration.keySet,this.sendRequest.bind(this)),this.listenerManager=new J,this.eventEmitter=new ue(this.listenerManager),this.subscribeCapable=new Set,this._configuration.enableEventEngine){let e=this._configuration.getHeartbeatInterval();this.presenceState={},e&&(this.presenceEventEngine=new Le({heartbeat:this.heartbeat.bind(this),leave:e=>this.makeUnsubscribe(e,(()=>{})),heartbeatDelay:()=>new Promise(((t,n)=>{e=this._configuration.getHeartbeatInterval(),e?setTimeout(t,1e3*e):n(new d("Heartbeat interval has been reset."))})),retryDelay:e=>new Promise((t=>setTimeout(t,e))),emitStatus:e=>this.listenerManager.announceStatus(e),config:this._configuration,presenceState:this.presenceState})),this.eventEngine=new Et({handshake:this.subscribeHandshake.bind(this),receiveMessages:this.subscribeReceiveMessages.bind(this),delay:e=>new Promise((t=>setTimeout(t,e))),join:this.join.bind(this),leave:this.leave.bind(this),leaveAll:this.leaveAll.bind(this),presenceState:this.presenceState,config:this._configuration,emitMessages:e=>{try{e.forEach((e=>this.eventEmitter.emitEvent(e)))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}},emitStatus:e=>this.listenerManager.announceStatus(e)})}else this.subscriptionManager=new Y(this._configuration,this.listenerManager,this.eventEmitter,this.makeSubscribe.bind(this),this.heartbeat.bind(this),this.makeUnsubscribe.bind(this),this.time.bind(this))}get configuration(){return this._configuration}get _config(){return this.configuration}get authKey(){var e;return null!==(e=this._configuration.authKey)&&void 0!==e?e:void 0}getAuthKey(){return this.authKey}setAuthKey(e){this._configuration.setAuthKey(e)}get userId(){return this._configuration.userId}set userId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}getUserId(){return this._configuration.userId}setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}get filterExpression(){var e;return null!==(e=this._configuration.getFilterExpression())&&void 0!==e?e:void 0}getFilterExpression(){return this.filterExpression}set filterExpression(e){this._configuration.setFilterExpression(e)}setFilterExpression(e){this.filterExpression=e}get cipherKey(){return this._configuration.getCipherKey()}set cipherKey(e){this._configuration.setCipherKey(e)}setCipherKey(e){this.cipherKey=e}set heartbeatInterval(e){this._configuration.setHeartbeatInterval(e)}setHeartbeatInterval(e){this.heartbeatInterval=e}getVersion(){return this._configuration.getVersion()}_addPnsdkSuffix(e,t){this._configuration._addPnsdkSuffix(e,t)}getUUID(){return this.userId}setUUID(e){this.userId=e}get customEncrypt(){return this._configuration.getCustomEncrypt()}get customDecrypt(){return this._configuration.getCustomDecrypt()}channel(e){return new en(e,this.eventEmitter,this)}channelGroup(e){return new Yt(e,this.eventEmitter,this)}channelMetadata(e){return new Qt(e,this.eventEmitter,this)}userMetadata(e){return new Zt(e,this.eventEmitter,this)}subscriptionSet(e){return new Jt(Object.assign(Object.assign({},e),{eventEmitter:this.eventEmitter,pubnub:this}))}sendRequest(e,t){return i(this,void 0,void 0,(function*(){const n=e.validate();if(n){if(t)return t(g(n),null);throw new d("Validation failed, check status for details",g(n))}const s=e.request(),r=e.operation();s.formData&&s.formData.length>0||r===ie.PNDownloadFileOperation?s.timeout=this._configuration.getFileTimeout():r===ie.PNSubscribeOperation||r===ie.PNReceiveMessagesOperation?s.timeout=this._configuration.getSubscribeTimeout():s.timeout=this._configuration.getTransactionTimeout();const i={error:!1,operation:r,category:h.PNAcknowledgmentCategory,statusCode:0},[a,o]=this.transport.makeSendable(s);return e.cancellationController=o||null,a.then((t=>{if(i.statusCode=t.status,200!==t.status&&204!==t.status){const e=_n.decoder.decode(t.body),n=t.headers["content-type"];if(n||-1!==n.indexOf("javascript")||-1!==n.indexOf("json")){const t=JSON.parse(e);"object"==typeof t&&"error"in t&&t.error&&"object"==typeof t.error&&(i.errorData=t.error)}else i.responseText=e}return e.parse(t)})).then((e=>t?t(i,e):e)).catch((e=>{const n=e instanceof A?e:A.create(e);if(t)return t(n.toStatus(r),null);throw n.toPubNubError(r,"REST API request processing error, check status for details")}))}))}destroy(e){var t;null===(t=this.subscribeCapable)||void 0===t||t.clear(),this.subscriptionManager?(this.subscriptionManager.unsubscribeAll(e),this.subscriptionManager.disconnect()):this.eventEngine&&this.eventEngine.dispose()}stop(){this.destroy()}addListener(e){this.listenerManager.addListener(e)}removeListener(e){this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners()}publish(e,t){return i(this,void 0,void 0,(function*(){{const n=new Ot(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}signal(e,t){return i(this,void 0,void 0,(function*(){{const n=new kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}fire(e,t){return i(this,void 0,void 0,(function*(){return null!=t||(t=()=>{}),this.publish(Object.assign(Object.assign({},e),{replicate:!1,storeInHistory:!1}),t)}))}getSubscribedChannels(){return this.subscriptionManager?this.subscriptionManager.subscribedChannels:this.eventEngine?this.eventEngine.getSubscribedChannels():[]}getSubscribedChannelGroups(){return this.subscriptionManager?this.subscriptionManager.subscribedChannelGroups:this.eventEngine?this.eventEngine.getSubscribedChannelGroups():[]}registerSubscribeCapable(e){this.subscribeCapable&&!this.subscribeCapable.has(e)&&this.subscribeCapable.add(e)}unregisterSubscribeCapable(e){this.subscribeCapable&&this.subscribeCapable.has(e)&&this.subscribeCapable.delete(e)}getSubscribeCapableEntities(){{const e={channels:[],channelGroups:[]};if(!this.subscribeCapable)return e;for(const t of this.subscribeCapable)e.channelGroups.push(...t.channelGroups),e.channels.push(...t.channels);return e}}subscribe(e){this.subscriptionManager?this.subscriptionManager.subscribe(e):this.eventEngine&&this.eventEngine.subscribe(e)}makeSubscribe(e,t){{const n=new ce(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));if(this.sendRequest(n,((e,s)=>{var r;this.subscriptionManager&&(null===(r=this.subscriptionManager.abort)||void 0===r?void 0:r.identifier)===n.requestIdentifier&&(this.subscriptionManager.abort=null),t(e,s)})),this.subscriptionManager){const e=()=>n.abort("Cancel long-poll subscribe request");e.identifier=n.requestIdentifier,this.subscriptionManager.abort=e}}}unsubscribe(e){this.subscriptionManager?this.subscriptionManager.unsubscribe(e):this.eventEngine&&this.eventEngine.unsubscribe(e)}makeUnsubscribe(e,t){{let{channels:n,channelGroups:s}=e;if(s&&(s=s.filter((e=>!e.endsWith("-pnpres")))),n&&(n=n.filter((e=>!e.endsWith("-pnpres")))),0===(null!=s?s:[]).length&&0===(null!=n?n:[]).length)return t({error:!1,operation:ie.PNUnsubscribeOperation,category:h.PNAcknowledgmentCategory,statusCode:200});this.sendRequest(new jt({channels:n,channelGroups:s,keySet:this._configuration.keySet}),t)}}unsubscribeAll(){var e;null===(e=this.subscribeCapable)||void 0===e||e.clear(),this.subscriptionManager?this.subscriptionManager.unsubscribeAll():this.eventEngine&&this.eventEngine.unsubscribeAll()}disconnect(){this.subscriptionManager?this.subscriptionManager.disconnect():this.eventEngine&&this.eventEngine.disconnect()}reconnect(e){this.subscriptionManager?this.subscriptionManager.reconnect():this.eventEngine&&this.eventEngine.reconnect(null!=e?e:{})}subscribeHandshake(e){return i(this,void 0,void 0,(function*(){{const t=new Nt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),n=e.abortSignal.subscribe((e=>{t.abort("Cancel subscribe handshake request")}));return this.sendRequest(t).then((e=>(n(),e.cursor)))}}))}subscribeReceiveMessages(e){return i(this,void 0,void 0,(function*(){{const t=new Ct(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),n=e.abortSignal.subscribe((e=>{t.abort("Cancel long-poll subscribe request")}));return this.sendRequest(t).then((e=>(n(),e)))}}))}getMessageActions(e,t){return i(this,void 0,void 0,(function*(){{const n=new Dt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}addMessageAction(e,t){return i(this,void 0,void 0,(function*(){{const n=new qt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}removeMessageAction(e,t){return i(this,void 0,void 0,(function*(){{const n=new Gt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}fetchMessages(e,t){return i(this,void 0,void 0,(function*(){{const n=new xt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}deleteMessages(e,t){return i(this,void 0,void 0,(function*(){{const n=new Ft(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}messageCounts(e,t){return i(this,void 0,void 0,(function*(){{const n=new Tt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}history(e,t){return i(this,void 0,void 0,(function*(){{const n=new Rt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}hereNow(e,t){return i(this,void 0,void 0,(function*(){{const n=new It(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}whereNow(e,t){return i(this,void 0,void 0,(function*(){var n;{const s=new At({uuid:null!==(n=e.uuid)&&void 0!==n?n:this._configuration.userId,keySet:this._configuration.keySet});return t?this.sendRequest(s,t):this.sendRequest(s)}}))}getState(e,t){return i(this,void 0,void 0,(function*(){var n;{const s=new Pt(Object.assign(Object.assign({},e),{uuid:null!==(n=e.uuid)&&void 0!==n?n:this._configuration.userId,keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}setState(e,t){return i(this,void 0,void 0,(function*(){var n,s;{const{keySet:r,userId:i}=this._configuration,a=this._configuration.getPresenceTimeout();let o;if(this._configuration.enableEventEngine&&this.presenceState){const t=this.presenceState;null===(n=e.channels)||void 0===n||n.forEach((n=>t[n]=e.state)),"channelGroups"in e&&(null===(s=e.channelGroups)||void 0===s||s.forEach((n=>t[n]=e.state)))}return o="withHeartbeat"in e?new _t(Object.assign(Object.assign({},e),{keySet:r,heartbeat:a})):new Mt(Object.assign(Object.assign({},e),{keySet:r,uuid:i})),this.subscriptionManager&&this.subscriptionManager.setState(e),t?this.sendRequest(o,t):this.sendRequest(o)}}))}presence(e){var t;null===(t=this.subscriptionManager)||void 0===t||t.changePresence(e)}heartbeat(e,t){return i(this,void 0,void 0,(function*(){{let{channels:n,channelGroups:s}=e;if(s&&(s=s.filter((e=>!e.endsWith("-pnpres")))),n&&(n=n.filter((e=>!e.endsWith("-pnpres")))),0===(null!=s?s:[]).length&&0===(null!=n?n:[]).length){const e={error:!1,operation:ie.PNHeartbeatOperation,category:h.PNAcknowledgmentCategory,statusCode:200};return t?t(e,{}):Promise.resolve(e)}const r=new _t(Object.assign(Object.assign({},e),{channels:n,channelGroups:s,keySet:this._configuration.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}}))}join(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.join(e)}leave(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.leave(e)}leaveAll(){var e;null===(e=this.presenceEventEngine)||void 0===e||e.leaveAll()}grantToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Token error: PAM module disabled")}))}revokeToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Revoke Token error: PAM module disabled")}))}get token(){return this.tokenManager&&this.tokenManager.getToken()}getToken(){return this.token}set token(e){this.tokenManager&&this.tokenManager.setToken(e)}setToken(e){this.token=e}parseToken(e){return this.tokenManager&&this.tokenManager.parseToken(e)}grant(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant error: PAM module disabled")}))}audit(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Permissions error: PAM module disabled")}))}get objects(){return this._objects}fetchUsers(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllUUIDMetadata(e,t)}))}fetchUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getUUIDMetadata(e,t)}))}createUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}updateUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}removeUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeUUIDMetadata(e,t)}))}fetchSpaces(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllChannelMetadata(e,t)}))}fetchSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getChannelMetadata(e,t)}))}createSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}updateSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}removeSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeChannelMetadata(e,t)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.fetchMemberships(e,t)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}updateMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var n,s,r;{if("spaceId"in e){const r=e,i={channel:null!==(n=r.spaceId)&&void 0!==n?n:r.channel,uuids:null!==(s=r.userIds)&&void 0!==s?s:r.uuids,limit:0};return t?this.objects.removeChannelMembers(i,t):this.objects.removeChannelMembers(i)}const i=e,a={uuid:i.userId,channels:null!==(r=i.spaceIds)&&void 0!==r?r:i.channels,limit:0};return t?this.objects.removeMemberships(a,t):this.objects.removeMemberships(a)}}))}get channelGroups(){return this._channelGroups}get push(){return this._push}sendFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const n=new zt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,fileUploadPublishRetryLimit:this._configuration.fileUploadPublishRetryLimit,file:e.file,sendRequest:this.sendRequest.bind(this),publishFile:this.publishFile.bind(this),crypto:this._configuration.getCryptoModule(),cryptography:this.cryptography?this.cryptography:void 0})),s={error:!1,operation:ie.PNPublishFileOperation,category:h.PNAcknowledgmentCategory,statusCode:0};return n.process().then((e=>(s.statusCode=e.status,t?t(s,e):e))).catch((e=>{let n;throw e instanceof d?n=e.status:e instanceof A&&(n=e.toStatus(s.operation)),t&&n&&t(n,null),new d("REST API request processing error, check status for details",n)}))}}))}publishFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const n=new Kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}listFiles(e,t){return i(this,void 0,void 0,(function*(){{const n=new Bt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}getFileUrl(e){var t;{const n=this.transport.request(new $t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})).request()),s=null!==(t=n.queryParameters)&&void 0!==t?t:{},r=Object.keys(s).map((e=>{const t=s[e];return Array.isArray(t)?t.map((t=>`${e}=${$(t)}`)).join("&"):`${e}=${$(t)}`})).join("&");return`${n.origin}${n.path}?${r}`}}downloadFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const n=new Mn(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,cryptography:this.cryptography?this.cryptography:void 0,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(n,t):yield this.sendRequest(n)}}))}deleteFile(e,t){return i(this,void 0,void 0,(function*(){{const n=new Lt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}time(e){return i(this,void 0,void 0,(function*(){const t=new Pn;return e?this.sendRequest(t,e):this.sendRequest(t)}))}encrypt(e,t){const n=this._configuration.getCryptoModule();if(!t&&n&&"string"==typeof e){const t=n.encrypt(e);return"string"==typeof t?t:u(t)}if(!this.crypto)throw new Error("Encryption error: cypher key not set");return this.crypto.encrypt(e,t)}decrypt(e,t){const n=this._configuration.getCryptoModule();if(!t&&n){const t=n.decrypt(e);return t instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(t)):t}if(!this.crypto)throw new Error("Decryption error: cypher key not set");return this.crypto.decrypt(e,t)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var n;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File encryption error. File constructor not configured.");if("string"!=typeof e&&!this._configuration.getCryptoModule())throw new Error("File encryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File encryption error. File encryption not available");return this.cryptography.encryptFile(e,t,this._configuration.PubNubFile)}return null===(n=this._configuration.getCryptoModule())||void 0===n?void 0:n.encryptFile(t,this._configuration.PubNubFile)}))}decryptFile(e,t){return i(this,void 0,void 0,(function*(){var n;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File decryption error. File constructor not configured.");if("string"==typeof e&&!this._configuration.getCryptoModule())throw new Error("File decryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File decryption error. File decryption not available");return this.cryptography.decryptFile(e,t,this._configuration.PubNubFile)}return null===(n=this._configuration.getCryptoModule())||void 0===n?void 0:n.decryptFile(t,this._configuration.PubNubFile)}))}}_n.decoder=new TextDecoder,_n.OPERATIONS=ie,_n.CATEGORIES=h,_n.ExponentialRetryPolicy=Be.ExponentialRetryPolicy,_n.LinearRetryPolicy=Be.LinearRetryPolicy;class jn{constructor(e,t){this.decode=e,this.base64ToBinary=t}decodeToken(e){let t="";e.length%4==3?t="=":e.length%4==2&&(t="==");const n=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,s=this.decode(this.base64ToBinary(n));return"object"==typeof s?s:void 0}}class An extends _n{constructor(e){var t;const n=T(e),r=Object.assign(Object.assign({},n),{sdkFamily:"Web"});r.PubNubFile=o;const i=D(r,(e=>{if(e.cipherKey)return new M({default:new P(Object.assign({},e)),cryptors:[new O({cipherKey:e.cipherKey})]})}));let a,u,l;a=new G(new jn((e=>F(s.decode(e))),c)),(i.getCipherKey()||i.secretKey)&&(u=new C({secretKey:i.secretKey,cipherKey:i.getCipherKey(),useRandomIVs:i.getUseRandomIVs(),customEncrypt:i.getCustomEncrypt(),customDecrypt:i.getCustomDecrypt()})),l=new N;let h=new W(r.transport,i.keepAlive,i.logVerbosity);n.subscriptionWorkerUrl&&(h=new I({clientIdentifier:i._instanceId,subscriptionKey:i.subscribeKey,userId:i.getUserId(),workerUrl:n.subscriptionWorkerUrl,sdkVersion:i.getVersion(),heartbeatInterval:i.getHeartbeatInterval(),logVerbosity:i.logVerbosity,workerLogVerbosity:r.subscriptionWorkerLogVerbosity,transport:h}));super({configuration:i,transport:new z({clientConfiguration:i,tokenManager:a,transport:h}),cryptography:l,tokenManager:a,crypto:u}),(null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t)&&(window.addEventListener("offline",(()=>{this.networkDownDetected()})),window.addEventListener("online",(()=>{this.networkUpDetected()})))}networkDownDetected(){this.listenerManager.announceNetworkDown(),this._configuration.restore?this.disconnect():this.destroy(!0)}networkUpDetected(){this.listenerManager.announceNetworkUp(),this.reconnect()}}return An.CryptoModule=M,An})); diff --git a/dist/web/pubnub.worker.js b/dist/web/pubnub.worker.js index 0c5b6a43b..1ab7edd3b 100644 --- a/dist/web/pubnub.worker.js +++ b/dist/web/pubnub.worker.js @@ -550,10 +550,9 @@ let fetchError = error; if (typeof error === 'string') { const errorMessage = error.toLowerCase(); - if (errorMessage.includes('timeout') || !errorMessage.includes('cancel')) - fetchError = new Error(error); - else if (errorMessage.includes('cancel')) - fetchError = new DOMException('Aborted', 'AbortError'); + fetchError = new Error(error); + if (!errorMessage.includes('timeout') && errorMessage.includes('cancel')) + fetchError.name = 'AbortError'; } failure(clients, fetchError); }); @@ -1089,9 +1088,10 @@ message = error.message; name = error.name; } - if (message.toLowerCase().includes('timeout')) + const errorMessage = message.toLowerCase(); + if (errorMessage.includes('timeout')) type = 'TIMEOUT'; - else if (name === 'AbortError' || message.toLowerCase().includes('cancel')) { + else if (name === 'AbortError' || errorMessage.includes('aborted') || errorMessage.includes('cancel')) { message = 'Request aborted'; type = 'ABORTED'; } diff --git a/dist/web/pubnub.worker.min.js b/dist/web/pubnub.worker.min.js index 494438463..2fd538f35 100644 --- a/dist/web/pubnub.worker.min.js +++ b/dist/web/pubnub.worker.min.js @@ -1,2 +1,2 @@ !function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";function e(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{l(r.next(e))}catch(e){s(e)}}function c(e){try{l(r.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,c)}l((r=r.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n,r,i={exports:{}}; -/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */n=i,function(e){var t="0.1.0",n={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};function r(){var e,t,n="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(n+="-"),n+=(12===e?4:16===e?3&t|8:t).toString(16);return n}function i(e,t){var r=n[t||"all"];return r&&r.test(e)||!1}r.isUUID=i,r.VERSION=t,e.uuid=r,e.isUUID=i}(r=i.exports),null!==n&&(n.exports=r.uuid);var s=t(i.exports),o={createUUID:()=>s.uuid?s.uuid():s()};const c=1e4,l=new Map,u=new TextDecoder;let a,d=!1;const h=o.createUUID(),p=new Map,f={},b={},g={},v={},y={},q={};self.onconnect=e=>{ee("New PubNub Client connected to the Subscription Shared Worker."),e.ports.forEach((e=>{e.start(),e.onmessage=t=>{if(!J(t))return;const n=t.data;if("client-register"===n.type)!d&&n.workerLogVerbosity&&(d=!0),n.port=e,U(n),ee(`Client '${n.clientIdentifier}' registered with '${h}' shared worker`);else if("client-pong"===n.type)V(n);else if("send-request"===n.type)if(n.request.path.startsWith("/v2/subscribe")){L(n);const e=f[n.clientIdentifier];if(e){const t=`${e.userId}-${e.subscriptionKey}`;if(!l.has(t)){const e=setTimeout((()=>{I(n),l.delete(t)}),50);l.set(t,e)}}}else n.request.path.endsWith("/heartbeat")?(N(n),w(n)):j(n);else"cancel-request"===n.type&&O(n)},e.postMessage({type:"shared-worker-connected"})}))};const I=e=>{var t;const n=A(e),r=f[e.clientIdentifier];let i=!1;if(r&&(r.subscription&&(i="0"===r.subscription.timetoken),C("start",[r],(new Date).toISOString(),e.request)),"string"==typeof n){const s=q[n];if(r){if(r.subscription&&(r.subscription.timetoken=s.timetoken,r.subscription.region=s.region,r.subscription.serviceRequestId=n),!i)return;const o=(new TextEncoder).encode(`{"t":{"t":"${s.timetoken}","r":${null!==(t=s.region)&&void 0!==t?t:"0"}},"m":[]}`),c=new Headers({"Content-Type":'text/javascript; charset="UTF-8"',"Content-Length":`${o.length}`}),l=new Response(o,{status:200,headers:c}),u=D([l,o]);u.url=`${e.request.origin}${e.request.path}`,u.clientIdentifier=e.clientIdentifier,u.identifier=e.request.identifier,C("end",[r],(new Date).toISOString(),e.request,o,c.get("Content-Type"),0),R(r,u)}return}e.request.cancellable&&p.set(n.identifier,new AbortController);const s=q[n.identifier],{timetokenOverride:o,regionOverride:c}=s;S(n,(()=>E(n.identifier)),((t,r)=>{F(t,r,e.request),G(t,n.identifier)}),((t,r)=>{F(t,null,e.request,W(r)),G(t,n.identifier)}),(e=>{let t=e;return i&&o&&"0"!==o&&(q[n.identifier],t=m(t,o,c)),t})),ee(`'${Object.keys(q).length}' subscription request currently active.`)},m=(e,t,n)=>{if(void 0===t||"0"===t||e[0].status>=400)return e;let r;const i=e[0];let s=i,o=e[1];try{r=JSON.parse((new TextDecoder).decode(o))}catch(t){return ee(`Subscribe response parse error: ${t}`),e}r.t.t=t,n&&(r.t.r=parseInt(n,10));try{if(o=(new TextEncoder).encode(JSON.stringify(r)).buffer,o.byteLength){const e=new Headers(i.headers);e.set("Content-Length",`${o.byteLength}`),s=new Response(o,{status:i.status,statusText:i.statusText,headers:e})}}catch(t){return ee(`Subscribe serialization error: ${t}`),e}return o.byteLength>0?[s,o]:e},w=e=>{var t;const n=f[e.clientIdentifier],r=x(e);if(!n)return;const i=`${n.userId}_${null!==(t=n.authKey)&&void 0!==t?t:""}`,s=g[n.subscriptionKey],o=(null!=s?s:{})[i];if(C("start",[n],(new Date).toISOString(),r),!r){let t,r;if(ee(`Previous heartbeat request has been sent less than ${n.heartbeatInterval} seconds ago. Skipping...`),o&&o.response&&([t,r]=o.response),!t){r=(new TextEncoder).encode('{ "status": 200, "message": "OK", "service": "Presence" }').buffer;const e=new Headers({"Content-Type":'text/javascript; charset="UTF-8"',"Content-Length":`${r.byteLength}`});t=new Response(r,{status:200,headers:e})}const i=D([t,r]);return i.url=`${e.request.origin}${e.request.path}`,i.clientIdentifier=e.clientIdentifier,i.identifier=e.request.identifier,C("end",[n],(new Date).toISOString(),e.request,r,t.headers.get("Content-Type"),0),void R(n,i)}S(r,(()=>[n]),((t,n)=>{o&&(o.response=n),F(t,n,e.request)}),((t,n)=>{F(t,null,e.request,W(n))})),ee("Started heartbeat request.",n)},j=e=>{const t=f[e.clientIdentifier],n=K(e);if(!t)return;const{subscription:r}=t,i=null==r?void 0:r.serviceRequestId;if(r&&0===r.channels.length&&0===r.channelGroups.length&&(r.channelGroupQuery="",r.path="",r.previousTimetoken="0",r.timetoken="0",delete r.region,delete r.serviceRequestId,delete r.request),!n){const n=(new TextEncoder).encode('{"status": 200, "action": "leave", "message": "OK", "service":"Presence"}'),r=new Headers({"Content-Type":'text/javascript; charset="UTF-8"',"Content-Length":`${n.length}`}),i=new Response(n,{status:200,headers:r}),s=D([i,n]);return s.url=`${e.request.origin}${e.request.path}`,s.clientIdentifier=e.clientIdentifier,s.identifier=e.request.identifier,void R(t,s)}if(S(n,(()=>[t]),((t,n)=>{F(t,n,e.request)}),((t,n)=>{F(t,null,e.request,W(n))})),ee("Started leave request.",t),void 0===i)return;const s=E(i);s.forEach((e=>{e&&e.subscription&&delete e.subscription.serviceRequestId})),k(i),$(s)},O=e=>{const t=f[e.clientIdentifier];if(!t||!t.subscription)return;const n=t.subscription.serviceRequestId;t&&n&&(delete t.subscription.serviceRequestId,t.subscription.request&&t.subscription.request.identifier===e.identifier&&delete t.subscription.request,k(n))},$=e=>{let t,n;for(const r of e)if(r.subscription&&r.subscription.request){n=r.subscription.request,t=r;break}n&&t&&I({type:"send-request",clientIdentifier:t.clientIdentifier,subscriptionKey:t.subscriptionKey,logVerbosity:t.logVerbosity,request:n})},S=(t,n,r,i,s)=>{e(void 0,void 0,void 0,(function*(){var e;const o=(new Date).getTime();Promise.race([fetch(T(t),{signal:null===(e=p.get(t.identifier))||void 0===e?void 0:e.signal,keepalive:!0}),P(t.identifier,t.timeout)]).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>s?s(e):e)).then((e=>{const i=e[1].byteLength>0?e[1]:void 0,s=n();0!==s.length&&(C("end",s,(new Date).toISOString(),t,i,e[0].headers.get("Content-Type"),(new Date).getTime()-o),r(s,e))})).catch((e=>{const t=n();if(0===t.length)return;let r=e;if("string"==typeof e){const t=e.toLowerCase();t.includes("timeout")||!t.includes("cancel")?r=new Error(e):t.includes("cancel")&&(r=new DOMException("Aborted","AbortError"))}i(t,r)}))}))},k=e=>{if(0===E(e).length){const t=p.get(e);p.delete(e),delete q[e],t&&t.abort("Cancel request")}},P=(e,t)=>new Promise(((n,r)=>{const i=setTimeout((()=>{p.delete(e),clearTimeout(i),r(new Error("Request timeout"))}),1e3*t)})),E=e=>Object.values(f).filter((t=>void 0!==t&&void 0!==t.subscription&&t.subscription.serviceRequestId===e)),G=(e,t)=>{delete q[t],e.forEach((e=>{e.subscription&&(delete e.subscription.request,delete e.subscription.serviceRequestId)}))},T=e=>{let t;const n=e.queryParameters;let r=e.path;if(e.headers){t={};for(const[n,r]of Object.entries(e.headers))t[n]=r}return n&&0!==Object.keys(n).length&&(r=`${r}?${ne(n)}`),new Request(`${e.origin}${r}`,{method:e.method,headers:t,redirect:"follow"})},A=e=>{var t,n,r,i,s;const c=f[e.clientIdentifier],l=c.subscription,u=Q(l.timetoken,e),a=o.createUUID(),h=Object.assign({},e.request);let p,b;if(u.length>1){const s=_(u,e);if(s){const e=q[s],{channels:n,channelGroups:r}=null!==(t=c.subscription)&&void 0!==t?t:{channels:[],channelGroups:[]};if((!(n.length>0)||Y(e.channels,n))&&(!(r.length>0)||Y(e.channelGroups,r)))return s}const o=(null!==(n=v[c.subscriptionKey])&&void 0!==n?n:{})[c.userId],d={},f=new Set(l.channelGroups),g=new Set(l.channels);o&&l.objectsWithState.length&&l.objectsWithState.forEach((e=>{const t=o[e];t&&(d[e]=t)}));for(const e of u){const{subscription:t}=e;if(!t)continue;1!==u.length&&e.clientIdentifier===c.clientIdentifier||!t.timetoken||(p=t.timetoken,b=t.region),t.channelGroups.forEach(f.add,f),t.channels.forEach(g.add,g);const n=t.serviceRequestId;t.serviceRequestId=a,n&&q[n]&&k(n),o&&t.objectsWithState.forEach((e=>{const t=o[e];t&&!d[e]&&(d[e]=t)}))}const y=null!==(r=q[a])&&void 0!==r?r:q[a]={requestId:a,timetoken:null!==(i=h.queryParameters.tt)&&void 0!==i?i:"0",channelGroups:[],channels:[]};if(g.size){y.channels=Array.from(g).sort();const e=h.path.split("/");e[4]=y.channels.join(","),h.path=e.join("/")}f.size&&(y.channelGroups=Array.from(f).sort(),h.queryParameters["channel-group"]=y.channelGroups.join(",")),Object.keys(d).length&&(h.queryParameters.state=JSON.stringify(d))}else q[a]={requestId:a,timetoken:null!==(s=h.queryParameters.tt)&&void 0!==s?s:"0",channelGroups:l.channelGroups,channels:l.channels};if(q[a]&&(h.queryParameters&&void 0!==h.queryParameters.tt&&void 0!==h.queryParameters.tr&&(q[a].region=h.queryParameters.tr),q[a].timetokenOverride=p,q[a].regionOverride=b),l.serviceRequestId=a,h.identifier=a,d){const e=u.reduce(((e,{clientIdentifier:t})=>(e.push(t),e)),[]).join(",");te(q[a],`Started aggregated request for clients: ${e}`)}return h},x=e=>{var t,n,r,i,s;const o=f[e.clientIdentifier],c=B(e),l=Object.assign({},e.request);if(!o||!o.heartbeat)return;const u=null!==(t=g[s=o.subscriptionKey])&&void 0!==t?t:g[s]={},a=`${o.userId}_${null!==(n=o.authKey)&&void 0!==n?n:""}`,d=o.heartbeat.channelGroups,h=o.heartbeat.channels;let p={},b=!1,v=!0;if(u[a]){const{channels:e,channelGroups:t,response:n}=u[a];p=null!==(i=o.heartbeat.presenceState)&&void 0!==i?i:{},v=Y(e,o.heartbeat.channels)&&Y(t,o.heartbeat.channelGroups),n&&(b=n[0].status>=400)}else u[a]={channels:h,channelGroups:d,timestamp:Date.now()},p=null!==(r=o.heartbeat.presenceState)&&void 0!==r?r:{},v=!1;if(v){const t=u[a].timestamp+1e3*o.heartbeatInterval,n=Date.now();if(!b&&n5e3)return;delete u[a].response;for(const t of c){const{heartbeat:n}=t;void 0!==n&&t.clientIdentifier!==e.clientIdentifier&&(n.presenceState&&(p=Object.assign(Object.assign({},p),n.presenceState)),d.push(...n.channelGroups.filter((e=>!d.includes(e)))),h.push(...n.channels.filter((e=>!h.includes(e)))))}}u[a].channels=h,u[a].channelGroups=d,u[a].timestamp=Date.now();for(const e in Object.keys(p))h.includes(e)||d.includes(e)||delete p[e];if(h.length){const e=l.path.split("/");e[6]=h.join(","),l.path=e.join("/")}return d.length&&(l.queryParameters["channel-group"]=d.join(",")),Object.keys(p).length?l.queryParameters.state=JSON.stringify(p):delete l.queryParameters.state,l},K=e=>{const t=f[e.clientIdentifier],n=H(e);let r=X(e.request),i=z(e.request);const s=Object.assign({},e.request);if(t&&t.subscription){const{subscription:e}=t;i.length&&(e.channels=e.channels.filter((e=>!i.includes(e)))),r.length&&(e.channelGroups=e.channelGroups.filter((e=>!r.includes(e))))}if(t&&t.heartbeat){const{heartbeat:e}=t;i.length&&(e.channels=e.channels.filter((e=>!i.includes(e)))),r.length&&(e.channelGroups=e.channelGroups.filter((e=>!r.includes(e))))}for(const t of n){const n=t.subscription;void 0!==n&&(t.clientIdentifier!==e.clientIdentifier&&(i.length&&(i=i.filter((e=>!n.channels.includes(e)))),r.length&&(r=r.filter((e=>!n.channelGroups.includes(e))))))}if(0!==i.length||0!==r.length){if(i.length){const e=s.path.split("/");e[6]=i.join(","),s.path=e.join("/")}return r.length&&(s.queryParameters["channel-group"]=r.join(",")),s}if(d&&t){const e=n.reduce(((e,{clientIdentifier:t})=>(e.push(t),e)),[]).join(",");ee(`Specified channels and groups still in use by other clients: ${e}. Ignoring leave request.`,t)}},R=(e,t)=>{var n;const r=(null!==(n=y[e.subscriptionKey])&&void 0!==n?n:{})[e.clientIdentifier];if(!r)return!1;try{return r.postMessage(t),!0}catch(e){}return!1},C=(e,t,n,r,i,s,o)=>{var c,l;if(0===t.length)return;const a=null!==(c=y[t[0].subscriptionKey])&&void 0!==c?c:{},d=r&&r.path.startsWith("/v2/subscribe");let h;if("start"===e)h={type:"request-progress-start",clientIdentifier:"",url:"",timestamp:n};else{let e;i&&s&&(-1!==s.indexOf("text/javascript")||-1!==s.indexOf("application/json")||-1!==s.indexOf("text/plain")||-1!==s.indexOf("text/html"))&&(e=u.decode(i)),h={type:"request-progress-end",clientIdentifier:"",url:"",response:e,timestamp:n,duration:o}}for(const e of t){if(d&&!e.subscription)continue;const t=a[e.clientIdentifier],{request:n}=null!==(l=e.subscription)&&void 0!==l?l:{};let i=null!=n?n:r;if(d||(i=r),e.logVerbosity&&t&&i){const t=Object.assign(Object.assign({},h),{clientIdentifier:e.clientIdentifier,url:`${i.origin}${i.path}`,query:i.queryParameters});R(e,t)}}},F=(e,t,n,r)=>{var i,s;if(0===e.length)return;if(!r&&!t)return;const o=null!==(i=y[e[0].subscriptionKey])&&void 0!==i?i:{},c=n&&n.path.startsWith("/v2/subscribe");!r&&t&&(r=t[0].status>=400?W(void 0,t):D(t));for(const t of e){if(c&&!t.subscription)continue;const e=o[t.clientIdentifier],{request:i}=null!==(s=t.subscription)&&void 0!==s?s:{};let l=null!=i?i:n;if(c||(l=n),e&&l){const e=Object.assign(Object.assign({},r),{clientIdentifier:t.clientIdentifier,identifier:l.identifier,url:`${l.origin}${l.path}`});R(t,e)}}},D=e=>{var t;const[n,r]=e,i=r.byteLength>0?r:void 0,s=parseInt(null!==(t=n.headers.get("Content-Length"))&&void 0!==t?t:"0",10),o=n.headers.get("Content-Type"),c={};return n.headers.forEach(((e,t)=>c[t]=e.toLowerCase())),{type:"request-process-success",clientIdentifier:"",identifier:"",url:"",response:{contentLength:s,contentType:o,headers:c,status:n.status,body:i}}},W=(e,t)=>{if(t)return Object.assign(Object.assign({},D(t)),{type:"request-process-error"});let n="NETWORK_ISSUE",r="Unknown error",i="Error";return e&&e instanceof Error&&(r=e.message,i=e.name),r.toLowerCase().includes("timeout")?n="TIMEOUT":("AbortError"===i||r.toLowerCase().includes("cancel"))&&(r="Request aborted",n="ABORTED"),{type:"request-process-error",clientIdentifier:"",identifier:"",url:"",error:{name:i,type:n,message:r}}},U=e=>{var t,n,r,i;const{clientIdentifier:s}=e;if(f[s])return;const o=f[s]={clientIdentifier:s,subscriptionKey:e.subscriptionKey,userId:e.userId,heartbeatInterval:e.heartbeatInterval,logVerbosity:e.logVerbosity},l=null!==(t=b[r=e.subscriptionKey])&&void 0!==t?t:b[r]=[];l.every((e=>e.clientIdentifier!==s))&&l.push(o),(null!==(n=y[i=e.subscriptionKey])&&void 0!==n?n:y[i]={})[s]=e.port,ee(`Registered PubNub client with '${s}' identifier. '${Object.keys(f).length}' clients currently active.`),!a&&Object.keys(f).length>0&&(ee("Setup PubNub client ping event 10 seconds"),a=setInterval((()=>Z()),c))},L=e=>{var t,n,r,i,s,o,c,l,u,a,d,h,p,b,g,y,q,I,m,w;const j=e.request.queryParameters,{clientIdentifier:O}=e,$=f[O];if(!$)return;const S=null!==(t=j["channel-group"])&&void 0!==t?t:"",k=null!==(n=j.state)&&void 0!==n?n:"";let P=$.subscription;if(P){if(k.length>0){const e=JSON.parse(k),t=null!==(o=(y=null!==(s=v[g=$.subscriptionKey])&&void 0!==s?s:v[g]={})[q=$.userId])&&void 0!==o?o:y[q]={};Object.entries(e).forEach((([e,n])=>t[e]=n));for(const n of P.objectsWithState)e[n]||delete t[n];P.objectsWithState=Object.keys(e)}else if(P.objectsWithState.length){const e=null!==(l=(m=null!==(c=v[I=$.subscriptionKey])&&void 0!==c?c:v[I]={})[w=$.userId])&&void 0!==l?l:m[w]={};for(const t of P.objectsWithState)delete e[t];P.objectsWithState=[]}}else{if(P={path:"",channelGroupQuery:"",channels:[],channelGroups:[],previousTimetoken:"0",timetoken:"0",objectsWithState:[]},k.length>0){const e=JSON.parse(k),t=null!==(i=(p=null!==(r=v[h=$.subscriptionKey])&&void 0!==r?r:v[h]={})[b=$.userId])&&void 0!==i?i:p[b]={};Object.entries(e).forEach((([e,n])=>t[e]=n)),P.objectsWithState=Object.keys(e)}$.subscription=P}P.path!==e.request.path&&(P.path=e.request.path,P.channels=z(e.request)),P.channelGroupQuery!==S&&(P.channelGroupQuery=S,P.channelGroups=X(e.request));const{authKey:E,userId:G}=$;P.request=e.request,P.filterExpression=null!==(u=j["filter-expr"])&&void 0!==u?u:"",P.timetoken=null!==(a=j.tt)&&void 0!==a?a:"0",void 0!==j.tr&&(P.region=j.tr),$.authKey=null!==(d=j.auth)&&void 0!==d?d:"",$.userId=j.uuid,M($,G,E)},N=e=>{var t,n;const r=f[e.clientIdentifier],{request:i}=e;if(!r)return;const s=null!==(t=r.heartbeat)&&void 0!==t?t:r.heartbeat={channels:[],channelGroups:[]};s.channelGroups=X(i).filter((e=>!e.endsWith("-pnpres"))),s.channels=z(i).filter((e=>!e.endsWith("-pnpres")));const o=null!==(n=i.queryParameters.state)&&void 0!==n?n:"";if(o.length>0){const e=JSON.parse(o);for(const t of Object.keys(e))s.channels.includes(t)||s.channelGroups.includes(t)||delete e[t];s.presenceState=e}},M=(e,t,n)=>{var r,i;if(!e||t===e.userId&&(null!=n?n:"")===(null!==(r=e.authKey)&&void 0!==r?r:""))return;const s=null!==(i=g[e.subscriptionKey])&&void 0!==i?i:{},o=`${t}_${null!=n?n:""}`;void 0!==s[o]&&delete s[o]},V=e=>{const t=f[e.clientIdentifier];t&&(t.lastPongEvent=(new Date).getTime()/1e3)},J=e=>{const{clientIdentifier:t,subscriptionKey:n,logVerbosity:r}=e.data;return void 0!==r&&"boolean"==typeof r&&(!(!t||"string"!=typeof t)&&!(!n||"string"!=typeof n))},_=(e,t)=>{var n;const r=null!==(n=t.request.queryParameters["channel-group"])&&void 0!==n?n:"",i=t.request.path;let s,o;for(const n of e){const{subscription:e}=n;if(!e||!e.serviceRequestId)continue;const c=f[t.clientIdentifier],l=e.serviceRequestId;if(e.path===i&&e.channelGroupQuery===r)return ee(`Found identical request started by '${n.clientIdentifier}' client. \nWaiting for existing '${l}' request completion.`,c),e.serviceRequestId;{const r=q[e.serviceRequestId];if(s||(s=X(t.request)),o||(o=z(t.request)),o.length&&!Y(r.channels,o))continue;if(s.length&&!Y(r.channelGroups,s))continue;return te(r,`'${t.request.identifier}' request channels and groups are subset of ongoing '${l}' request \nwhich has started by '${n.clientIdentifier}' client. Waiting for existing '${l}' request completion.`,c),e.serviceRequestId}}},Q=(e,t)=>{var n,r,i;const s=t.request.queryParameters,o=null!==(n=s["filter-expr"])&&void 0!==n?n:"",c=null!==(r=s.auth)&&void 0!==r?r:"",l=s.uuid;return(null!==(i=b[t.subscriptionKey])&&void 0!==i?i:[]).filter((t=>t.userId===l&&t.authKey===c&&t.subscription&&(0!==t.subscription.channels.length||0!==t.subscription.channelGroups.length)&&t.subscription.filterExpression===o&&("0"===e||"0"===t.subscription.timetoken||t.subscription.timetoken===e)))},B=e=>H(e),H=e=>{var t,n;const r=e.request.queryParameters,i=null!==(t=r.auth)&&void 0!==t?t:"",s=r.uuid;return(null!==(n=b[e.subscriptionKey])&&void 0!==n?n:[]).filter((e=>e.userId===s&&e.authKey===i))},z=e=>{const t=e.path.split("/")[e.path.startsWith("/v2/subscribe/")?4:6];return","===t?[]:t.split(",").filter((e=>e.length>0))},X=e=>{var t;const n=null!==(t=e.queryParameters["channel-group"])&&void 0!==t?t:"";return 0===n.length?[]:n.split(",").filter((e=>e.length>0))},Y=(e,t)=>{const n=new Set(e);return t.every(n.has,n)},Z=()=>{ee("Pinging clients...");const e={type:"shared-worker-ping"};Object.values(f).forEach((t=>{let n=!1;t&&t.lastPingRequest&&(ee(`Checking whether ${t.clientIdentifier} ping has been sent too long ago...`),(!t.lastPongEvent||Math.abs(t.lastPongEvent-t.lastPingRequest)>5)&&(n=!0,ee(`'${t.clientIdentifier}' client is inactive. Invalidating.`),((e,t)=>{delete f[t];let n=b[e];if(n)if(n=n.filter((e=>e.clientIdentifier!==t)),n.length>0?b[e]=n:(delete b[e],delete g[e]),0===n.length&&delete v[e],n.length>0){const n=y[e];n&&(delete n[t],0===Object.keys(n).length&&delete y[e])}else delete y[e];ee(`Invalidate '${t}' client. '${Object.keys(f).length}' clients currently active.`)})(t.subscriptionKey,t.clientIdentifier))),t&&!n&&(ee(`Sending ping to ${t.clientIdentifier}...`),t.lastPingRequest=(new Date).getTime()/1e3,R(t,e))})),0===Object.keys(f).length&&a&&clearInterval(a)},ee=(e,t)=>{if(!d)return;const n=t?[t]:Object.values(f),r={type:"shared-worker-console-log",message:e};n.forEach((e=>{e&&R(e,r)}))},te=(e,t,n)=>{if(!d)return;const r=n?[n]:Object.values(f),i={type:"shared-worker-console-dir",message:t,data:e};r.forEach((e=>{e&&R(e,i)}))},ne=e=>Object.keys(e).map((t=>{const n=e[t];return Array.isArray(n)?n.map((e=>`${t}=${re(e)}`)).join("&"):`${t}=${re(n)}`})).join("&"),re=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`))})); +/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */n=i,function(e){var t="0.1.0",n={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};function r(){var e,t,n="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(n+="-"),n+=(12===e?4:16===e?3&t|8:t).toString(16);return n}function i(e,t){var r=n[t||"all"];return r&&r.test(e)||!1}r.isUUID=i,r.VERSION=t,e.uuid=r,e.isUUID=i}(r=i.exports),null!==n&&(n.exports=r.uuid);var s=t(i.exports),o={createUUID:()=>s.uuid?s.uuid():s()};const c=1e4,l=new Map,u=new TextDecoder;let a,d=!1;const h=o.createUUID(),p=new Map,f={},b={},g={},v={},y={},q={};self.onconnect=e=>{ee("New PubNub Client connected to the Subscription Shared Worker."),e.ports.forEach((e=>{e.start(),e.onmessage=t=>{if(!J(t))return;const n=t.data;if("client-register"===n.type)!d&&n.workerLogVerbosity&&(d=!0),n.port=e,U(n),ee(`Client '${n.clientIdentifier}' registered with '${h}' shared worker`);else if("client-pong"===n.type)V(n);else if("send-request"===n.type)if(n.request.path.startsWith("/v2/subscribe")){L(n);const e=f[n.clientIdentifier];if(e){const t=`${e.userId}-${e.subscriptionKey}`;if(!l.has(t)){const e=setTimeout((()=>{I(n),l.delete(t)}),50);l.set(t,e)}}}else n.request.path.endsWith("/heartbeat")?(N(n),j(n)):w(n);else"cancel-request"===n.type&&O(n)},e.postMessage({type:"shared-worker-connected"})}))};const I=e=>{var t;const n=A(e),r=f[e.clientIdentifier];let i=!1;if(r&&(r.subscription&&(i="0"===r.subscription.timetoken),F("start",[r],(new Date).toISOString(),e.request)),"string"==typeof n){const s=q[n];if(r){if(r.subscription&&(r.subscription.timetoken=s.timetoken,r.subscription.region=s.region,r.subscription.serviceRequestId=n),!i)return;const o=(new TextEncoder).encode(`{"t":{"t":"${s.timetoken}","r":${null!==(t=s.region)&&void 0!==t?t:"0"}},"m":[]}`),c=new Headers({"Content-Type":'text/javascript; charset="UTF-8"',"Content-Length":`${o.length}`}),l=new Response(o,{status:200,headers:c}),u=W([l,o]);u.url=`${e.request.origin}${e.request.path}`,u.clientIdentifier=e.clientIdentifier,u.identifier=e.request.identifier,F("end",[r],(new Date).toISOString(),e.request,o,c.get("Content-Type"),0),x(r,u)}return}e.request.cancellable&&p.set(n.identifier,new AbortController);const s=q[n.identifier],{timetokenOverride:o,regionOverride:c}=s;S(n,(()=>E(n.identifier)),((t,r)=>{C(t,r,e.request),G(t,n.identifier)}),((t,r)=>{C(t,null,e.request,D(r)),G(t,n.identifier)}),(e=>{let t=e;return i&&o&&"0"!==o&&(q[n.identifier],t=m(t,o,c)),t})),ee(`'${Object.keys(q).length}' subscription request currently active.`)},m=(e,t,n)=>{if(void 0===t||"0"===t||e[0].status>=400)return e;let r;const i=e[0];let s=i,o=e[1];try{r=JSON.parse((new TextDecoder).decode(o))}catch(t){return ee(`Subscribe response parse error: ${t}`),e}r.t.t=t,n&&(r.t.r=parseInt(n,10));try{if(o=(new TextEncoder).encode(JSON.stringify(r)).buffer,o.byteLength){const e=new Headers(i.headers);e.set("Content-Length",`${o.byteLength}`),s=new Response(o,{status:i.status,statusText:i.statusText,headers:e})}}catch(t){return ee(`Subscribe serialization error: ${t}`),e}return o.byteLength>0?[s,o]:e},j=e=>{var t;const n=f[e.clientIdentifier],r=K(e);if(!n)return;const i=`${n.userId}_${null!==(t=n.authKey)&&void 0!==t?t:""}`,s=g[n.subscriptionKey],o=(null!=s?s:{})[i];if(F("start",[n],(new Date).toISOString(),r),!r){let t,r;if(ee(`Previous heartbeat request has been sent less than ${n.heartbeatInterval} seconds ago. Skipping...`),o&&o.response&&([t,r]=o.response),!t){r=(new TextEncoder).encode('{ "status": 200, "message": "OK", "service": "Presence" }').buffer;const e=new Headers({"Content-Type":'text/javascript; charset="UTF-8"',"Content-Length":`${r.byteLength}`});t=new Response(r,{status:200,headers:e})}const i=W([t,r]);return i.url=`${e.request.origin}${e.request.path}`,i.clientIdentifier=e.clientIdentifier,i.identifier=e.request.identifier,F("end",[n],(new Date).toISOString(),e.request,r,t.headers.get("Content-Type"),0),void x(n,i)}S(r,(()=>[n]),((t,n)=>{o&&(o.response=n),C(t,n,e.request)}),((t,n)=>{C(t,null,e.request,D(n))})),ee("Started heartbeat request.",n)},w=e=>{const t=f[e.clientIdentifier],n=R(e);if(!t)return;const{subscription:r}=t,i=null==r?void 0:r.serviceRequestId;if(r&&0===r.channels.length&&0===r.channelGroups.length&&(r.channelGroupQuery="",r.path="",r.previousTimetoken="0",r.timetoken="0",delete r.region,delete r.serviceRequestId,delete r.request),!n){const n=(new TextEncoder).encode('{"status": 200, "action": "leave", "message": "OK", "service":"Presence"}'),r=new Headers({"Content-Type":'text/javascript; charset="UTF-8"',"Content-Length":`${n.length}`}),i=new Response(n,{status:200,headers:r}),s=W([i,n]);return s.url=`${e.request.origin}${e.request.path}`,s.clientIdentifier=e.clientIdentifier,s.identifier=e.request.identifier,void x(t,s)}if(S(n,(()=>[t]),((t,n)=>{C(t,n,e.request)}),((t,n)=>{C(t,null,e.request,D(n))})),ee("Started leave request.",t),void 0===i)return;const s=E(i);s.forEach((e=>{e&&e.subscription&&delete e.subscription.serviceRequestId})),k(i),$(s)},O=e=>{const t=f[e.clientIdentifier];if(!t||!t.subscription)return;const n=t.subscription.serviceRequestId;t&&n&&(delete t.subscription.serviceRequestId,t.subscription.request&&t.subscription.request.identifier===e.identifier&&delete t.subscription.request,k(n))},$=e=>{let t,n;for(const r of e)if(r.subscription&&r.subscription.request){n=r.subscription.request,t=r;break}n&&t&&I({type:"send-request",clientIdentifier:t.clientIdentifier,subscriptionKey:t.subscriptionKey,logVerbosity:t.logVerbosity,request:n})},S=(t,n,r,i,s)=>{e(void 0,void 0,void 0,(function*(){var e;const o=(new Date).getTime();Promise.race([fetch(T(t),{signal:null===(e=p.get(t.identifier))||void 0===e?void 0:e.signal,keepalive:!0}),P(t.identifier,t.timeout)]).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>s?s(e):e)).then((e=>{const i=e[1].byteLength>0?e[1]:void 0,s=n();0!==s.length&&(F("end",s,(new Date).toISOString(),t,i,e[0].headers.get("Content-Type"),(new Date).getTime()-o),r(s,e))})).catch((e=>{const t=n();if(0===t.length)return;let r=e;if("string"==typeof e){const t=e.toLowerCase();r=new Error(e),!t.includes("timeout")&&t.includes("cancel")&&(r.name="AbortError")}i(t,r)}))}))},k=e=>{if(0===E(e).length){const t=p.get(e);p.delete(e),delete q[e],t&&t.abort("Cancel request")}},P=(e,t)=>new Promise(((n,r)=>{const i=setTimeout((()=>{p.delete(e),clearTimeout(i),r(new Error("Request timeout"))}),1e3*t)})),E=e=>Object.values(f).filter((t=>void 0!==t&&void 0!==t.subscription&&t.subscription.serviceRequestId===e)),G=(e,t)=>{delete q[t],e.forEach((e=>{e.subscription&&(delete e.subscription.request,delete e.subscription.serviceRequestId)}))},T=e=>{let t;const n=e.queryParameters;let r=e.path;if(e.headers){t={};for(const[n,r]of Object.entries(e.headers))t[n]=r}return n&&0!==Object.keys(n).length&&(r=`${r}?${ne(n)}`),new Request(`${e.origin}${r}`,{method:e.method,headers:t,redirect:"follow"})},A=e=>{var t,n,r,i,s;const c=f[e.clientIdentifier],l=c.subscription,u=Q(l.timetoken,e),a=o.createUUID(),h=Object.assign({},e.request);let p,b;if(u.length>1){const s=_(u,e);if(s){const e=q[s],{channels:n,channelGroups:r}=null!==(t=c.subscription)&&void 0!==t?t:{channels:[],channelGroups:[]};if((!(n.length>0)||Y(e.channels,n))&&(!(r.length>0)||Y(e.channelGroups,r)))return s}const o=(null!==(n=v[c.subscriptionKey])&&void 0!==n?n:{})[c.userId],d={},f=new Set(l.channelGroups),g=new Set(l.channels);o&&l.objectsWithState.length&&l.objectsWithState.forEach((e=>{const t=o[e];t&&(d[e]=t)}));for(const e of u){const{subscription:t}=e;if(!t)continue;1!==u.length&&e.clientIdentifier===c.clientIdentifier||!t.timetoken||(p=t.timetoken,b=t.region),t.channelGroups.forEach(f.add,f),t.channels.forEach(g.add,g);const n=t.serviceRequestId;t.serviceRequestId=a,n&&q[n]&&k(n),o&&t.objectsWithState.forEach((e=>{const t=o[e];t&&!d[e]&&(d[e]=t)}))}const y=null!==(r=q[a])&&void 0!==r?r:q[a]={requestId:a,timetoken:null!==(i=h.queryParameters.tt)&&void 0!==i?i:"0",channelGroups:[],channels:[]};if(g.size){y.channels=Array.from(g).sort();const e=h.path.split("/");e[4]=y.channels.join(","),h.path=e.join("/")}f.size&&(y.channelGroups=Array.from(f).sort(),h.queryParameters["channel-group"]=y.channelGroups.join(",")),Object.keys(d).length&&(h.queryParameters.state=JSON.stringify(d))}else q[a]={requestId:a,timetoken:null!==(s=h.queryParameters.tt)&&void 0!==s?s:"0",channelGroups:l.channelGroups,channels:l.channels};if(q[a]&&(h.queryParameters&&void 0!==h.queryParameters.tt&&void 0!==h.queryParameters.tr&&(q[a].region=h.queryParameters.tr),q[a].timetokenOverride=p,q[a].regionOverride=b),l.serviceRequestId=a,h.identifier=a,d){const e=u.reduce(((e,{clientIdentifier:t})=>(e.push(t),e)),[]).join(",");te(q[a],`Started aggregated request for clients: ${e}`)}return h},K=e=>{var t,n,r,i,s;const o=f[e.clientIdentifier],c=B(e),l=Object.assign({},e.request);if(!o||!o.heartbeat)return;const u=null!==(t=g[s=o.subscriptionKey])&&void 0!==t?t:g[s]={},a=`${o.userId}_${null!==(n=o.authKey)&&void 0!==n?n:""}`,d=o.heartbeat.channelGroups,h=o.heartbeat.channels;let p={},b=!1,v=!0;if(u[a]){const{channels:e,channelGroups:t,response:n}=u[a];p=null!==(i=o.heartbeat.presenceState)&&void 0!==i?i:{},v=Y(e,o.heartbeat.channels)&&Y(t,o.heartbeat.channelGroups),n&&(b=n[0].status>=400)}else u[a]={channels:h,channelGroups:d,timestamp:Date.now()},p=null!==(r=o.heartbeat.presenceState)&&void 0!==r?r:{},v=!1;if(v){const t=u[a].timestamp+1e3*o.heartbeatInterval,n=Date.now();if(!b&&n5e3)return;delete u[a].response;for(const t of c){const{heartbeat:n}=t;void 0!==n&&t.clientIdentifier!==e.clientIdentifier&&(n.presenceState&&(p=Object.assign(Object.assign({},p),n.presenceState)),d.push(...n.channelGroups.filter((e=>!d.includes(e)))),h.push(...n.channels.filter((e=>!h.includes(e)))))}}u[a].channels=h,u[a].channelGroups=d,u[a].timestamp=Date.now();for(const e in Object.keys(p))h.includes(e)||d.includes(e)||delete p[e];if(h.length){const e=l.path.split("/");e[6]=h.join(","),l.path=e.join("/")}return d.length&&(l.queryParameters["channel-group"]=d.join(",")),Object.keys(p).length?l.queryParameters.state=JSON.stringify(p):delete l.queryParameters.state,l},R=e=>{const t=f[e.clientIdentifier],n=H(e);let r=X(e.request),i=z(e.request);const s=Object.assign({},e.request);if(t&&t.subscription){const{subscription:e}=t;i.length&&(e.channels=e.channels.filter((e=>!i.includes(e)))),r.length&&(e.channelGroups=e.channelGroups.filter((e=>!r.includes(e))))}if(t&&t.heartbeat){const{heartbeat:e}=t;i.length&&(e.channels=e.channels.filter((e=>!i.includes(e)))),r.length&&(e.channelGroups=e.channelGroups.filter((e=>!r.includes(e))))}for(const t of n){const n=t.subscription;void 0!==n&&(t.clientIdentifier!==e.clientIdentifier&&(i.length&&(i=i.filter((e=>!n.channels.includes(e)))),r.length&&(r=r.filter((e=>!n.channelGroups.includes(e))))))}if(0!==i.length||0!==r.length){if(i.length){const e=s.path.split("/");e[6]=i.join(","),s.path=e.join("/")}return r.length&&(s.queryParameters["channel-group"]=r.join(",")),s}if(d&&t){const e=n.reduce(((e,{clientIdentifier:t})=>(e.push(t),e)),[]).join(",");ee(`Specified channels and groups still in use by other clients: ${e}. Ignoring leave request.`,t)}},x=(e,t)=>{var n;const r=(null!==(n=y[e.subscriptionKey])&&void 0!==n?n:{})[e.clientIdentifier];if(!r)return!1;try{return r.postMessage(t),!0}catch(e){}return!1},F=(e,t,n,r,i,s,o)=>{var c,l;if(0===t.length)return;const a=null!==(c=y[t[0].subscriptionKey])&&void 0!==c?c:{},d=r&&r.path.startsWith("/v2/subscribe");let h;if("start"===e)h={type:"request-progress-start",clientIdentifier:"",url:"",timestamp:n};else{let e;i&&s&&(-1!==s.indexOf("text/javascript")||-1!==s.indexOf("application/json")||-1!==s.indexOf("text/plain")||-1!==s.indexOf("text/html"))&&(e=u.decode(i)),h={type:"request-progress-end",clientIdentifier:"",url:"",response:e,timestamp:n,duration:o}}for(const e of t){if(d&&!e.subscription)continue;const t=a[e.clientIdentifier],{request:n}=null!==(l=e.subscription)&&void 0!==l?l:{};let i=null!=n?n:r;if(d||(i=r),e.logVerbosity&&t&&i){const t=Object.assign(Object.assign({},h),{clientIdentifier:e.clientIdentifier,url:`${i.origin}${i.path}`,query:i.queryParameters});x(e,t)}}},C=(e,t,n,r)=>{var i,s;if(0===e.length)return;if(!r&&!t)return;const o=null!==(i=y[e[0].subscriptionKey])&&void 0!==i?i:{},c=n&&n.path.startsWith("/v2/subscribe");!r&&t&&(r=t[0].status>=400?D(void 0,t):W(t));for(const t of e){if(c&&!t.subscription)continue;const e=o[t.clientIdentifier],{request:i}=null!==(s=t.subscription)&&void 0!==s?s:{};let l=null!=i?i:n;if(c||(l=n),e&&l){const e=Object.assign(Object.assign({},r),{clientIdentifier:t.clientIdentifier,identifier:l.identifier,url:`${l.origin}${l.path}`});x(t,e)}}},W=e=>{var t;const[n,r]=e,i=r.byteLength>0?r:void 0,s=parseInt(null!==(t=n.headers.get("Content-Length"))&&void 0!==t?t:"0",10),o=n.headers.get("Content-Type"),c={};return n.headers.forEach(((e,t)=>c[t]=e.toLowerCase())),{type:"request-process-success",clientIdentifier:"",identifier:"",url:"",response:{contentLength:s,contentType:o,headers:c,status:n.status,body:i}}},D=(e,t)=>{if(t)return Object.assign(Object.assign({},W(t)),{type:"request-process-error"});let n="NETWORK_ISSUE",r="Unknown error",i="Error";e&&e instanceof Error&&(r=e.message,i=e.name);const s=r.toLowerCase();return s.includes("timeout")?n="TIMEOUT":("AbortError"===i||s.includes("aborted")||s.includes("cancel"))&&(r="Request aborted",n="ABORTED"),{type:"request-process-error",clientIdentifier:"",identifier:"",url:"",error:{name:i,type:n,message:r}}},U=e=>{var t,n,r,i;const{clientIdentifier:s}=e;if(f[s])return;const o=f[s]={clientIdentifier:s,subscriptionKey:e.subscriptionKey,userId:e.userId,heartbeatInterval:e.heartbeatInterval,logVerbosity:e.logVerbosity},l=null!==(t=b[r=e.subscriptionKey])&&void 0!==t?t:b[r]=[];l.every((e=>e.clientIdentifier!==s))&&l.push(o),(null!==(n=y[i=e.subscriptionKey])&&void 0!==n?n:y[i]={})[s]=e.port,ee(`Registered PubNub client with '${s}' identifier. '${Object.keys(f).length}' clients currently active.`),!a&&Object.keys(f).length>0&&(ee("Setup PubNub client ping event 10 seconds"),a=setInterval((()=>Z()),c))},L=e=>{var t,n,r,i,s,o,c,l,u,a,d,h,p,b,g,y,q,I,m,j;const w=e.request.queryParameters,{clientIdentifier:O}=e,$=f[O];if(!$)return;const S=null!==(t=w["channel-group"])&&void 0!==t?t:"",k=null!==(n=w.state)&&void 0!==n?n:"";let P=$.subscription;if(P){if(k.length>0){const e=JSON.parse(k),t=null!==(o=(y=null!==(s=v[g=$.subscriptionKey])&&void 0!==s?s:v[g]={})[q=$.userId])&&void 0!==o?o:y[q]={};Object.entries(e).forEach((([e,n])=>t[e]=n));for(const n of P.objectsWithState)e[n]||delete t[n];P.objectsWithState=Object.keys(e)}else if(P.objectsWithState.length){const e=null!==(l=(m=null!==(c=v[I=$.subscriptionKey])&&void 0!==c?c:v[I]={})[j=$.userId])&&void 0!==l?l:m[j]={};for(const t of P.objectsWithState)delete e[t];P.objectsWithState=[]}}else{if(P={path:"",channelGroupQuery:"",channels:[],channelGroups:[],previousTimetoken:"0",timetoken:"0",objectsWithState:[]},k.length>0){const e=JSON.parse(k),t=null!==(i=(p=null!==(r=v[h=$.subscriptionKey])&&void 0!==r?r:v[h]={})[b=$.userId])&&void 0!==i?i:p[b]={};Object.entries(e).forEach((([e,n])=>t[e]=n)),P.objectsWithState=Object.keys(e)}$.subscription=P}P.path!==e.request.path&&(P.path=e.request.path,P.channels=z(e.request)),P.channelGroupQuery!==S&&(P.channelGroupQuery=S,P.channelGroups=X(e.request));const{authKey:E,userId:G}=$;P.request=e.request,P.filterExpression=null!==(u=w["filter-expr"])&&void 0!==u?u:"",P.timetoken=null!==(a=w.tt)&&void 0!==a?a:"0",void 0!==w.tr&&(P.region=w.tr),$.authKey=null!==(d=w.auth)&&void 0!==d?d:"",$.userId=w.uuid,M($,G,E)},N=e=>{var t,n;const r=f[e.clientIdentifier],{request:i}=e;if(!r)return;const s=null!==(t=r.heartbeat)&&void 0!==t?t:r.heartbeat={channels:[],channelGroups:[]};s.channelGroups=X(i).filter((e=>!e.endsWith("-pnpres"))),s.channels=z(i).filter((e=>!e.endsWith("-pnpres")));const o=null!==(n=i.queryParameters.state)&&void 0!==n?n:"";if(o.length>0){const e=JSON.parse(o);for(const t of Object.keys(e))s.channels.includes(t)||s.channelGroups.includes(t)||delete e[t];s.presenceState=e}},M=(e,t,n)=>{var r,i;if(!e||t===e.userId&&(null!=n?n:"")===(null!==(r=e.authKey)&&void 0!==r?r:""))return;const s=null!==(i=g[e.subscriptionKey])&&void 0!==i?i:{},o=`${t}_${null!=n?n:""}`;void 0!==s[o]&&delete s[o]},V=e=>{const t=f[e.clientIdentifier];t&&(t.lastPongEvent=(new Date).getTime()/1e3)},J=e=>{const{clientIdentifier:t,subscriptionKey:n,logVerbosity:r}=e.data;return void 0!==r&&"boolean"==typeof r&&(!(!t||"string"!=typeof t)&&!(!n||"string"!=typeof n))},_=(e,t)=>{var n;const r=null!==(n=t.request.queryParameters["channel-group"])&&void 0!==n?n:"",i=t.request.path;let s,o;for(const n of e){const{subscription:e}=n;if(!e||!e.serviceRequestId)continue;const c=f[t.clientIdentifier],l=e.serviceRequestId;if(e.path===i&&e.channelGroupQuery===r)return ee(`Found identical request started by '${n.clientIdentifier}' client. \nWaiting for existing '${l}' request completion.`,c),e.serviceRequestId;{const r=q[e.serviceRequestId];if(s||(s=X(t.request)),o||(o=z(t.request)),o.length&&!Y(r.channels,o))continue;if(s.length&&!Y(r.channelGroups,s))continue;return te(r,`'${t.request.identifier}' request channels and groups are subset of ongoing '${l}' request \nwhich has started by '${n.clientIdentifier}' client. Waiting for existing '${l}' request completion.`,c),e.serviceRequestId}}},Q=(e,t)=>{var n,r,i;const s=t.request.queryParameters,o=null!==(n=s["filter-expr"])&&void 0!==n?n:"",c=null!==(r=s.auth)&&void 0!==r?r:"",l=s.uuid;return(null!==(i=b[t.subscriptionKey])&&void 0!==i?i:[]).filter((t=>t.userId===l&&t.authKey===c&&t.subscription&&(0!==t.subscription.channels.length||0!==t.subscription.channelGroups.length)&&t.subscription.filterExpression===o&&("0"===e||"0"===t.subscription.timetoken||t.subscription.timetoken===e)))},B=e=>H(e),H=e=>{var t,n;const r=e.request.queryParameters,i=null!==(t=r.auth)&&void 0!==t?t:"",s=r.uuid;return(null!==(n=b[e.subscriptionKey])&&void 0!==n?n:[]).filter((e=>e.userId===s&&e.authKey===i))},z=e=>{const t=e.path.split("/")[e.path.startsWith("/v2/subscribe/")?4:6];return","===t?[]:t.split(",").filter((e=>e.length>0))},X=e=>{var t;const n=null!==(t=e.queryParameters["channel-group"])&&void 0!==t?t:"";return 0===n.length?[]:n.split(",").filter((e=>e.length>0))},Y=(e,t)=>{const n=new Set(e);return t.every(n.has,n)},Z=()=>{ee("Pinging clients...");const e={type:"shared-worker-ping"};Object.values(f).forEach((t=>{let n=!1;t&&t.lastPingRequest&&(ee(`Checking whether ${t.clientIdentifier} ping has been sent too long ago...`),(!t.lastPongEvent||Math.abs(t.lastPongEvent-t.lastPingRequest)>5)&&(n=!0,ee(`'${t.clientIdentifier}' client is inactive. Invalidating.`),((e,t)=>{delete f[t];let n=b[e];if(n)if(n=n.filter((e=>e.clientIdentifier!==t)),n.length>0?b[e]=n:(delete b[e],delete g[e]),0===n.length&&delete v[e],n.length>0){const n=y[e];n&&(delete n[t],0===Object.keys(n).length&&delete y[e])}else delete y[e];ee(`Invalidate '${t}' client. '${Object.keys(f).length}' clients currently active.`)})(t.subscriptionKey,t.clientIdentifier))),t&&!n&&(ee(`Sending ping to ${t.clientIdentifier}...`),t.lastPingRequest=(new Date).getTime()/1e3,x(t,e))})),0===Object.keys(f).length&&a&&clearInterval(a)},ee=(e,t)=>{if(!d)return;const n=t?[t]:Object.values(f),r={type:"shared-worker-console-log",message:e};n.forEach((e=>{e&&x(e,r)}))},te=(e,t,n)=>{if(!d)return;const r=n?[n]:Object.values(f),i={type:"shared-worker-console-dir",message:t,data:e};r.forEach((e=>{e&&x(e,i)}))},ne=e=>Object.keys(e).map((t=>{const n=e[t];return Array.isArray(n)?n.map((e=>`${t}=${re(e)}`)).join("&"):`${t}=${re(n)}`})).join("&"),re=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`))})); diff --git a/lib/core/components/configuration.js b/lib/core/components/configuration.js index 3340b856d..cbdcb5eca 100644 --- a/lib/core/components/configuration.js +++ b/lib/core/components/configuration.js @@ -120,7 +120,7 @@ const makeConfiguration = (base, setupCryptoModule) => { return base.PubNubFile; }, get version() { - return '8.9.0'; + return '8.9.1'; }, getVersion() { return this.version; diff --git a/lib/core/components/subscription-manager.js b/lib/core/components/subscription-manager.js index a40977e7f..eba764d5d 100644 --- a/lib/core/components/subscription-manager.js +++ b/lib/core/components/subscription-manager.js @@ -231,7 +231,8 @@ class SubscriptionManager { if (status.category === categories_1.default.PNTimeoutCategory) { this.startSubscribeLoop(); } - else if (status.category === categories_1.default.PNNetworkIssuesCategory) { + else if (status.category === categories_1.default.PNNetworkIssuesCategory || + status.category === categories_1.default.PNMalformedResponseCategory) { this.disconnect(); if (status.error && this.configuration.autoNetworkDetection && this.isOnline) { this.isOnline = false; @@ -253,14 +254,11 @@ class SubscriptionManager { this.listenerManager.announceStatus(reconnectedAnnounce); }); this.reconnectionManager.startPolling(); - this.listenerManager.announceStatus(status); + this.listenerManager.announceStatus(Object.assign(Object.assign({}, status), { category: categories_1.default.PNNetworkIssuesCategory })); } - else if (status.category === categories_1.default.PNBadRequestCategory || - status.category == categories_1.default.PNMalformedResponseCategory) { - const category = this.isOnline ? categories_1.default.PNDisconnectedUnexpectedlyCategory : status.category; - this.isOnline = false; - this.disconnect(); - this.listenerManager.announceStatus(Object.assign(Object.assign({}, status), { category })); + else if (status.category === categories_1.default.PNBadRequestCategory) { + this.stopHeartbeatTimer(); + this.listenerManager.announceStatus(status); } else this.listenerManager.announceStatus(status); diff --git a/lib/core/pubnub-common.js b/lib/core/pubnub-common.js index c90337f70..46e5836dc 100644 --- a/lib/core/pubnub-common.js +++ b/lib/core/pubnub-common.js @@ -895,7 +895,22 @@ class PubNubCore { */ makeUnsubscribe(parameters, callback) { if (process.env.PRESENCE_MODULE !== 'disabled') { - this.sendRequest(new leave_1.PresenceLeaveRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet })), callback); + // Filtering out presence channels and groups. + let { channels, channelGroups } = parameters; + if (channelGroups) + channelGroups = channelGroups.filter((channelGroup) => !channelGroup.endsWith('-pnpres')); + if (channels) + channels = channels.filter((channel) => !channel.endsWith('-pnpres')); + // Complete immediately request only for presence channels. + if ((channelGroups !== null && channelGroups !== void 0 ? channelGroups : []).length === 0 && (channels !== null && channels !== void 0 ? channels : []).length === 0) { + return callback({ + error: false, + operation: operations_1.default.PNUnsubscribeOperation, + category: categories_1.default.PNAcknowledgmentCategory, + statusCode: 200, + }); + } + this.sendRequest(new leave_1.PresenceLeaveRequest({ channels, channelGroups, keySet: this._configuration.keySet }), callback); } else throw new Error('Unsubscription error: presence module disabled'); @@ -1284,7 +1299,26 @@ class PubNubCore { heartbeat(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { if (process.env.PRESENCE_MODULE !== 'disabled') { - const request = new heartbeat_1.HeartbeatRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet })); + // Filtering out presence channels and groups. + let { channels, channelGroups } = parameters; + if (channelGroups) + channelGroups = channelGroups.filter((channelGroup) => !channelGroup.endsWith('-pnpres')); + if (channels) + channels = channels.filter((channel) => !channel.endsWith('-pnpres')); + // Complete immediately request only for presence channels. + if ((channelGroups !== null && channelGroups !== void 0 ? channelGroups : []).length === 0 && (channels !== null && channels !== void 0 ? channels : []).length === 0) { + const responseStatus = { + error: false, + operation: operations_1.default.PNHeartbeatOperation, + category: categories_1.default.PNAcknowledgmentCategory, + statusCode: 200, + }; + if (callback) + return callback(responseStatus, {}); + return Promise.resolve(responseStatus); + } + const request = new heartbeat_1.HeartbeatRequest(Object.assign(Object.assign({}, parameters), { channels, + channelGroups, keySet: this._configuration.keySet })); if (callback) return this.sendRequest(request, callback); return this.sendRequest(request); diff --git a/lib/errors/pubnub-api-error.js b/lib/errors/pubnub-api-error.js index c9ad14517..c3e76c213 100644 --- a/lib/errors/pubnub-api-error.js +++ b/lib/errors/pubnub-api-error.js @@ -4,6 +4,17 @@ * * @internal */ +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -22,7 +33,7 @@ class PubNubAPIError extends Error { * * @param errorOrResponse - `Error` or service error response object from which error information * should be extracted. - * @param data - Preprocessed service error response. + * @param [data] - Preprocessed service error response. * * @returns `PubNubAPIError` object with known error category and additional information (if * available). @@ -101,7 +112,7 @@ class PubNubAPIError extends Error { * * @param response - Service error response object from which error information should be * extracted. - * @param data - Preprocessed service error response. + * @param [data] - Preprocessed service error response. * * @returns `PubNubAPIError` object with known error category and additional information (if * available). @@ -122,6 +133,11 @@ class PubNubAPIError extends Error { category = categories_1.default.PNAccessDeniedCategory; message = 'Access denied'; } + if (typeof response === 'object' && Object.keys(response).length === 0) { + category = categories_1.default.PNMalformedResponseCategory; + message = 'Malformed response (network issues)'; + status = 400; + } // Try to get more information about error from service response. if (data && data.byteLength > 0) { const decoded = new TextDecoder().decode(data); @@ -174,7 +190,7 @@ class PubNubAPIError extends Error { * @param message - Short API call error description. * @param category - Error category. * @param statusCode - Response HTTP status code. - * @param errorData - Error information. + * @param [errorData] - Error information. */ constructor(message, category, statusCode, errorData) { super(message); @@ -197,18 +213,57 @@ class PubNubAPIError extends Error { operation, statusCode: this.statusCode, errorData: this.errorData, + // @ts-expect-error Inner helper for JSON.stringify. + toJSON: function () { + let normalizedErrorData; + const errorData = this.errorData; + if (errorData) { + try { + if (typeof errorData === 'object') { + const errorObject = Object.assign(Object.assign(Object.assign(Object.assign({}, ('name' in errorData ? { name: errorData.name } : {})), ('message' in errorData ? { message: errorData.message } : {})), ('stack' in errorData ? { stack: errorData.stack } : {})), errorData); + normalizedErrorData = JSON.parse(JSON.stringify(errorObject, PubNubAPIError.circularReplacer())); + } + else + normalizedErrorData = errorData; + } + catch (_) { + normalizedErrorData = { error: 'Could not serialize the error object' }; + } + } + // Make sure to exclude `toJSON` function from the final object. + const _a = this, { toJSON } = _a, status = __rest(_a, ["toJSON"]); + return JSON.stringify(Object.assign(Object.assign({}, status), { errorData: normalizedErrorData })); + }, }; } /** * Convert API error object to PubNub client error object. * * @param operation - Request operation during which error happened. - * @param message - Custom error message. + * @param [message] - Custom error message. * * @returns Client-facing pre-formatted endpoint call error. */ toPubNubError(operation, message) { return new pubnub_error_1.PubNubError(message !== null && message !== void 0 ? message : this.message, this.toStatus(operation)); } + /** + * Function which handles circular references in serialized JSON. + * + * @returns Circular reference replacer function. + * + * @internal + */ + static circularReplacer() { + const visited = new WeakSet(); + return function (_, value) { + if (typeof value === 'object' && value !== null) { + if (visited.has(value)) + return '[Circular]'; + visited.add(value); + } + return value; + }; + } } exports.PubNubAPIError = PubNubAPIError; diff --git a/package-lock.json b/package-lock.json index 187770ec6..e1e23a68e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "pubnub", - "version": "8.8.1", + "version": "8.9.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "pubnub", - "version": "8.8.1", + "version": "8.9.0", "license": "SEE LICENSE IN LICENSE", "dependencies": { "agentkeepalive": "^3.5.2", diff --git a/package.json b/package.json index 41fc4a0c1..78f5835b4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "pubnub", - "version": "8.9.0", + "version": "8.9.1", "author": "PubNub ", "description": "Publish & Subscribe Real-time Messaging with PubNub", "scripts": { diff --git a/src/core/components/configuration.ts b/src/core/components/configuration.ts index e66e67c05..e87a19d7e 100644 --- a/src/core/components/configuration.ts +++ b/src/core/components/configuration.ts @@ -178,7 +178,7 @@ export const makeConfiguration = ( return base.PubNubFile; }, get version(): string { - return '8.9.0'; + return '8.9.1'; }, getVersion(): string { return this.version; diff --git a/src/core/components/subscription-manager.ts b/src/core/components/subscription-manager.ts index 3dcca2727..269f08d1f 100644 --- a/src/core/components/subscription-manager.ts +++ b/src/core/components/subscription-manager.ts @@ -383,7 +383,10 @@ export class SubscriptionManager { if (status.category === StatusCategory.PNTimeoutCategory) { this.startSubscribeLoop(); - } else if (status.category === StatusCategory.PNNetworkIssuesCategory) { + } else if ( + status.category === StatusCategory.PNNetworkIssuesCategory || + status.category === StatusCategory.PNMalformedResponseCategory + ) { this.disconnect(); if (status.error && this.configuration.autoNetworkDetection && this.isOnline) { @@ -410,16 +413,10 @@ export class SubscriptionManager { }); this.reconnectionManager.startPolling(); + this.listenerManager.announceStatus({ ...status, category: StatusCategory.PNNetworkIssuesCategory }); + } else if (status.category === StatusCategory.PNBadRequestCategory) { + this.stopHeartbeatTimer(); this.listenerManager.announceStatus(status); - } else if ( - status.category === StatusCategory.PNBadRequestCategory || - status.category == StatusCategory.PNMalformedResponseCategory - ) { - const category = this.isOnline ? StatusCategory.PNDisconnectedUnexpectedlyCategory : status.category; - this.isOnline = false; - this.disconnect(); - - this.listenerManager.announceStatus({ ...status, category }); } else this.listenerManager.announceStatus(status); return; diff --git a/src/core/pubnub-common.ts b/src/core/pubnub-common.ts index 0fc402dc0..0ed8b5883 100644 --- a/src/core/pubnub-common.ts +++ b/src/core/pubnub-common.ts @@ -1238,11 +1238,23 @@ export class PubNubCore< */ private makeUnsubscribe(parameters: Presence.PresenceLeaveParameters, callback: StatusCallback): void { if (process.env.PRESENCE_MODULE !== 'disabled') { + // Filtering out presence channels and groups. + let { channels, channelGroups } = parameters; + if (channelGroups) channelGroups = channelGroups.filter((channelGroup) => !channelGroup.endsWith('-pnpres')); + if (channels) channels = channels.filter((channel) => !channel.endsWith('-pnpres')); + + // Complete immediately request only for presence channels. + if ((channelGroups ?? []).length === 0 && (channels ?? []).length === 0) { + return callback({ + error: false, + operation: RequestOperation.PNUnsubscribeOperation, + category: StatusCategory.PNAcknowledgmentCategory, + statusCode: 200, + }); + } + this.sendRequest( - new PresenceLeaveRequest({ - ...parameters, - keySet: this._configuration.keySet, - }), + new PresenceLeaveRequest({ channels, channelGroups, keySet: this._configuration.keySet }), callback, ); } else throw new Error('Unsubscription error: presence module disabled'); @@ -1917,8 +1929,28 @@ export class PubNubCore< callback?: ResultCallback, ) { if (process.env.PRESENCE_MODULE !== 'disabled') { + // Filtering out presence channels and groups. + let { channels, channelGroups } = parameters; + if (channelGroups) channelGroups = channelGroups.filter((channelGroup) => !channelGroup.endsWith('-pnpres')); + if (channels) channels = channels.filter((channel) => !channel.endsWith('-pnpres')); + + // Complete immediately request only for presence channels. + if ((channelGroups ?? []).length === 0 && (channels ?? []).length === 0) { + const responseStatus = { + error: false, + operation: RequestOperation.PNHeartbeatOperation, + category: StatusCategory.PNAcknowledgmentCategory, + statusCode: 200, + }; + + if (callback) return callback(responseStatus, {}); + return Promise.resolve(responseStatus); + } + const request = new HeartbeatRequest({ ...parameters, + channels, + channelGroups, keySet: this._configuration.keySet, }); diff --git a/src/errors/pubnub-api-error.ts b/src/errors/pubnub-api-error.ts index 2b948be64..e5bd7834f 100644 --- a/src/errors/pubnub-api-error.ts +++ b/src/errors/pubnub-api-error.ts @@ -21,7 +21,7 @@ export class PubNubAPIError extends Error { * * @param errorOrResponse - `Error` or service error response object from which error information * should be extracted. - * @param data - Preprocessed service error response. + * @param [data] - Preprocessed service error response. * * @returns `PubNubAPIError` object with known error category and additional information (if * available). @@ -89,7 +89,7 @@ export class PubNubAPIError extends Error { * * @param response - Service error response object from which error information should be * extracted. - * @param data - Preprocessed service error response. + * @param [data] - Preprocessed service error response. * * @returns `PubNubAPIError` object with known error category and additional information (if * available). @@ -110,6 +110,12 @@ export class PubNubAPIError extends Error { message = 'Access denied'; } + if (typeof response === 'object' && Object.keys(response).length === 0) { + category = StatusCategory.PNMalformedResponseCategory; + message = 'Malformed response (network issues)'; + status = 400; + } + // Try to get more information about error from service response. if (data && data.byteLength > 0) { const decoded = new TextDecoder().decode(data); @@ -163,7 +169,7 @@ export class PubNubAPIError extends Error { * @param message - Short API call error description. * @param category - Error category. * @param statusCode - Response HTTP status code. - * @param errorData - Error information. + * @param [errorData] - Error information. */ constructor( message: string, @@ -190,6 +196,32 @@ export class PubNubAPIError extends Error { operation, statusCode: this.statusCode, errorData: this.errorData, + // @ts-expect-error Inner helper for JSON.stringify. + toJSON: function (this: Status): string { + let normalizedErrorData: Payload | undefined; + const errorData = this.errorData; + + if (errorData) { + try { + if (typeof errorData === 'object') { + const errorObject = { + ...('name' in errorData ? { name: errorData.name } : {}), + ...('message' in errorData ? { message: errorData.message } : {}), + ...('stack' in errorData ? { stack: errorData.stack } : {}), + ...errorData, + }; + + normalizedErrorData = JSON.parse(JSON.stringify(errorObject, PubNubAPIError.circularReplacer())); + } else normalizedErrorData = errorData; + } catch (_) { + normalizedErrorData = { error: 'Could not serialize the error object' }; + } + } + + // Make sure to exclude `toJSON` function from the final object. + const { toJSON, ...status } = this; + return JSON.stringify({ ...status, errorData: normalizedErrorData }); + }, }; } @@ -197,11 +229,31 @@ export class PubNubAPIError extends Error { * Convert API error object to PubNub client error object. * * @param operation - Request operation during which error happened. - * @param message - Custom error message. + * @param [message] - Custom error message. * * @returns Client-facing pre-formatted endpoint call error. */ public toPubNubError(operation: RequestOperation, message?: string): PubNubError { return new PubNubError(message ?? this.message, this.toStatus(operation)); } + + /** + * Function which handles circular references in serialized JSON. + * + * @returns Circular reference replacer function. + * + * @internal + */ + private static circularReplacer() { + const visited = new WeakSet(); + + return function (_: unknown, value: object | null) { + if (typeof value === 'object' && value !== null) { + if (visited.has(value)) return '[Circular]'; + visited.add(value); + } + + return value; + }; + } } diff --git a/src/transport/subscription-worker/subscription-worker.ts b/src/transport/subscription-worker/subscription-worker.ts index 13bf73f1a..e71e4ee19 100644 --- a/src/transport/subscription-worker/subscription-worker.ts +++ b/src/transport/subscription-worker/subscription-worker.ts @@ -1101,8 +1101,9 @@ const sendRequest = ( if (typeof error === 'string') { const errorMessage = error.toLowerCase(); - if (errorMessage.includes('timeout') || !errorMessage.includes('cancel')) fetchError = new Error(error); - else if (errorMessage.includes('cancel')) fetchError = new DOMException('Aborted', 'AbortError'); + fetchError = new Error(error); + + if (!errorMessage.includes('timeout') && errorMessage.includes('cancel')) fetchError.name = 'AbortError'; } failure(clients, fetchError); @@ -1730,8 +1731,9 @@ const requestProcessingError = (error?: unknown, res?: [Response, ArrayBuffer]): name = error.name; } - if (message.toLowerCase().includes('timeout')) type = 'TIMEOUT'; - else if (name === 'AbortError' || message.toLowerCase().includes('cancel')) { + const errorMessage = message.toLowerCase(); + if (errorMessage.includes('timeout')) type = 'TIMEOUT'; + else if (name === 'AbortError' || errorMessage.includes('aborted') || errorMessage.includes('cancel')) { message = 'Request aborted'; type = 'ABORTED'; } diff --git a/src/transport/web-transport.ts b/src/transport/web-transport.ts index c82a3ceab..2facc4bfd 100644 --- a/src/transport/web-transport.ts +++ b/src/transport/web-transport.ts @@ -155,8 +155,9 @@ export class WebTransport implements Transport { if (typeof error === 'string') { const errorMessage = error.toLowerCase(); - if (errorMessage.includes('timeout') || !errorMessage.includes('cancel')) fetchError = new Error(error); - else if (errorMessage.includes('cancel')) fetchError = new DOMException('Aborted', 'AbortError'); + fetchError = new Error(error); + + if (!errorMessage.includes('timeout') && errorMessage.includes('cancel')) fetchError.name = 'AbortError'; } throw PubNubAPIError.create(fetchError); diff --git a/test/integration/components/subscription_manager.test.ts b/test/integration/components/subscription_manager.test.ts index 802690bf6..e040af904 100644 --- a/test/integration/components/subscription_manager.test.ts +++ b/test/integration/components/subscription_manager.test.ts @@ -383,6 +383,8 @@ describe('#components/subscription_manager', () => { pubnub.addListener({ status(statusPayload) { if (statusPayload.operation !== PubNub.OPERATIONS.PNHeartbeatOperation) return; + // @ts-expect-error Remove helper function before compare. + delete statusPayload['toJSON']; const statusWithoutError = _.omit(statusPayload, 'errorData', 'statusCode'); try { @@ -423,6 +425,8 @@ describe('#components/subscription_manager', () => { pubnub.addListener({ status(statusPayload) { if (statusPayload.operation !== PubNub.OPERATIONS.PNHeartbeatOperation) return; + // @ts-expect-error Remove helper function before compare. + delete statusPayload['toJSON']; const statusWithoutError = _.omit(statusPayload, 'errorData'); try { @@ -465,6 +469,8 @@ describe('#components/subscription_manager', () => { pubnubWithPassingHeartbeats.addListener({ status(statusPayload) { if (statusPayload.operation !== PubNub.OPERATIONS.PNHeartbeatOperation) return; + // @ts-expect-error Remove helper function before compare. + delete statusPayload['toJSON']; try { assert.equal(scope.isDone(), true); @@ -491,6 +497,88 @@ describe('#components/subscription_manager', () => { }); }); + it('heartbeat removes presence channels', (done) => { + const scope = utils + .createNock() + .get('/v2/presence/sub-key/mySubKey/channel/ch1/heartbeat') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + heartbeat: 300, + state: '{}', + }) + .reply(200, '{"status": 200, "message": "OK", "service": "Presence"}', { 'content-type': 'text/javascript' }); + + pubnubWithPassingHeartbeats.addListener({ + status(statusPayload) { + if (statusPayload.operation !== PubNub.OPERATIONS.PNHeartbeatOperation) return; + // @ts-expect-error Remove helper function before compare. + delete statusPayload['toJSON']; + + try { + assert.equal(scope.isDone(), true); + assert.deepEqual( + { + error: false, + operation: PubNub.OPERATIONS.PNHeartbeatOperation, + category: PubNub.CATEGORIES.PNAcknowledgmentCategory, + statusCode: 200, + }, + statusPayload, + ); + done(); + } catch (error) { + done(error); + } + }, + }); + + pubnubWithPassingHeartbeats.subscribe({ + channels: ['ch1', 'ch2-pnpres'], + }); + }); + + it("heartbeat doesn't make a call with only presence channels", (done) => { + const scope = utils + .createNock() + .get('/v2/presence/sub-key/mySubKey/channel/ch1-pnpres,ch2-pnpres/heartbeat') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + heartbeat: 300, + state: '{}', + }) + .reply(200, '{"status": 200, "message": "OK", "service": "Presence"}', { 'content-type': 'text/javascript' }); + + pubnubWithPassingHeartbeats.addListener({ + status(statusPayload) { + if (statusPayload.operation !== PubNub.OPERATIONS.PNHeartbeatOperation) return; + // @ts-expect-error Remove helper function before compare. + delete statusPayload['toJSON']; + + try { + assert.equal(scope.isDone(), false); + assert.deepEqual( + { + error: false, + operation: PubNub.OPERATIONS.PNHeartbeatOperation, + category: PubNub.CATEGORIES.PNAcknowledgmentCategory, + statusCode: 200, + }, + statusPayload, + ); + done(); + } catch (error) { + done(error); + } + }, + }); + + pubnubWithPassingHeartbeats.subscribe({ + channels: ['ch1-pnpres', 'ch2-pnpres'], + }); + }); + it('reports when heartbeats pass with heartbeatChannels', (done) => { const scope = utils .createNock() @@ -506,6 +594,8 @@ describe('#components/subscription_manager', () => { pubnubWithPassingHeartbeats.addListener({ status(statusPayload) { if (statusPayload.operation !== PubNub.OPERATIONS.PNHeartbeatOperation) return; + // @ts-expect-error Remove helper function before compare. + delete statusPayload['toJSON']; try { assert.equal(scope.isDone(), true); @@ -531,6 +621,48 @@ describe('#components/subscription_manager', () => { }); }); + it('heartbeat removes presence channel groups', (done) => { + const scope = utils + .createNock() + .get('/v2/presence/sub-key/mySubKey/channel/,/heartbeat') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + heartbeat: 300, + state: '{}', + 'channel-group': 'cg1', + }) + .reply(200, '{"status": 200, "message": "OK", "service": "Presence"}', { 'content-type': 'text/javascript' }); + + pubnubWithPassingHeartbeats.addListener({ + status(statusPayload) { + if (statusPayload.operation !== PubNub.OPERATIONS.PNHeartbeatOperation) return; + // @ts-expect-error Remove helper function before compare. + delete statusPayload['toJSON']; + + try { + assert.equal(scope.isDone(), true); + assert.deepEqual( + { + error: false, + operation: PubNub.OPERATIONS.PNHeartbeatOperation, + category: PubNub.CATEGORIES.PNAcknowledgmentCategory, + statusCode: 200, + }, + statusPayload, + ); + done(); + } catch (error) { + done(error); + } + }, + }); + + pubnubWithPassingHeartbeats.subscribe({ + channelGroups: ['cg1', 'cg2-pnpres'], + }); + }); + it('reports when heartbeats pass with heartbeatChannelGroups', (done) => { const scope = utils .createNock() @@ -547,6 +679,8 @@ describe('#components/subscription_manager', () => { pubnubWithPassingHeartbeats.addListener({ status(statusPayload) { if (statusPayload.operation !== PubNub.OPERATIONS.PNHeartbeatOperation) return; + // @ts-expect-error Remove helper function before compare. + delete statusPayload['toJSON']; try { assert.equal(scope.isDone(), true); @@ -600,6 +734,8 @@ describe('#components/subscription_manager', () => { pubnubWithLimitedQueue.addListener({ status(statusPayload) { if (statusPayload.category !== PubNub.CATEGORIES.PNRequestMessageCountExceededCategory) return; + // @ts-expect-error Remove helper function before compare. + delete statusPayload['toJSON']; try { assert.equal(scope.isDone(), true); diff --git a/test/integration/operations/unsubscribe.test.ts b/test/integration/operations/unsubscribe.test.ts index 919c4e7d3..982ebc093 100644 --- a/test/integration/operations/unsubscribe.test.ts +++ b/test/integration/operations/unsubscribe.test.ts @@ -232,6 +232,70 @@ describe('unsubscribe', () => { pubnub.subscribe({ channels: ['ch1', 'ch2'] }); }); + it('presence leave removes presence channels', (done) => { + const scope = utils + .createNock() + .get('/v2/presence/sub-key/mySubscribeKey/channel/ch1/leave') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + }) + .reply(200, '{ "status": 200, "message": "OK", "service": "Presence"}', { 'content-type': 'text/javascript' }); + + pubnub.addListener({ + status(status) { + if (status.operation !== PubNub.OPERATIONS.PNUnsubscribeOperation) { + pubnub.unsubscribe({ channels: ['ch1', 'ch2-pnpres'] }); + return; + } + + try { + assert.equal(status.error, false); + assert.equal(scope.isDone(), true); + assert.deepEqual(status.affectedChannels, ['ch1', 'ch2-pnpres']); + assert.deepEqual(status.affectedChannelGroups, []); + done(); + } catch (error) { + done(error); + } + }, + }); + + pubnub.subscribe({ channels: ['ch1', 'ch2-pnpres'] }); + }); + + it("presence doesn't make a call with only presence channels", (done) => { + const scope = utils + .createNock() + .get('/v2/presence/sub-key/mySubscribeKey/channel/ch1-pnpres,ch2-pnpres/leave') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + }) + .reply(200, '{ "status": 200, "message": "OK", "service": "Presence"}', { 'content-type': 'text/javascript' }); + + pubnub.addListener({ + status(status) { + if (status.operation !== PubNub.OPERATIONS.PNUnsubscribeOperation) { + pubnub.unsubscribe({ channels: ['ch1-pnpres', 'ch2-pnpres'] }); + return; + } + + try { + assert.equal(status.error, false); + assert.equal(scope.isDone(), false); + assert.deepEqual(status.affectedChannels, ['ch1-pnpres', 'ch2-pnpres']); + assert.deepEqual(status.affectedChannelGroups, []); + done(); + } catch (error) { + done(error); + } + }, + }); + + pubnub.subscribe({ channels: ['ch1-pnpres', 'ch2-pnpres'] }); + }); + it('supports partial leaving for channel groups', (done) => { const scope = utils .createNock() @@ -263,6 +327,38 @@ describe('unsubscribe', () => { pubnub.subscribe({ channelGroups: ['cg1', 'cg2'] }); }); + + it('presence leave removes presence channel groups', (done) => { + const scope = utils + .createNock() + .get('/v2/presence/sub-key/mySubscribeKey/channel/,/leave') + .query({ + pnsdk: `PubNub-JS-Nodejs/${pubnub.getVersion()}`, + uuid: 'myUUID', + 'channel-group': 'cg1', + }) + .reply(200, '{ "status": 200, "message": "OK", "service": "Presence"}', { 'content-type': 'text/javascript' }); + + pubnub.addListener({ + status(status) { + if (status.operation !== PubNub.OPERATIONS.PNUnsubscribeOperation) { + pubnub.unsubscribe({ channelGroups: ['cg1', 'cg2-pnpres'] }); + return; + } + try { + assert.equal(status.error, false); + assert.equal(scope.isDone(), true); + assert.deepEqual(status.affectedChannels, []); + assert.deepEqual(status.affectedChannelGroups, ['cg1', 'cg2-pnpres']); + done(); + } catch (error) { + done(error); + } + }, + }); + + pubnub.subscribe({ channelGroups: ['cg1', 'cg2-pnpres'] }); + }); }); describe('#unsubscribeAll', () => {