1var at={exports:{}},wr=at.exports,gs;function Cr(){return gs||(gs=1,(function(bs,Pr){var Mt={};(function(Rt,De){bs.exports=De()})(wr,(function(){var Rt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof Mt<"u"?Mt:typeof self<"u"?self:{};function De(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var Dt={exports:{}};(function(a){(function(e,t){var s=Math.pow(2,-24),n=Math.pow(2,32),r=Math.pow(2,53),i={encode:function(o){var c,u=new ArrayBuffer(256),d=new DataView(u),l=0;function h(R){for(var C=u.byteLength,T=l+R;C<T;)C*=2;if(C!==u.byteLength){var f=d;u=new ArrayBuffer(C),d=new DataView(u);for(var S=l+3>>2,O=0;O<S;++O)d.setUint32(4*O,f.getUint32(4*O))}return c=R,d}function y(){l+=c}function p(R){y(h(1).setUint8(l,R))}function b(R){for(var C=h(R.length),T=0;T<R.length;++T)C.setUint8(l+T,R[T]);y()}function m(R,C){C<24?p(R<<5|C):C<256?(p(R<<5|24),p(C)):C<65536?(p(R<<5|25),(function(T){y(h(2).setUint16(l,T))})(C)):C<4294967296?(p(R<<5|26),(function(T){y(h(4).setUint32(l,T))})(C)):(p(R<<5|27),(function(T){var f=T%n,S=(T-f)/n,O=h(8);O.setUint32(l,S),O.setUint32(l+4,f),y()})(C))}if((function R(C){var T;if(C===!1)return p(244);if(C===!0)return p(245);if(C===null)return p(246);if(C===t)return p(247);switch(typeof C){case"number":if(Math.floor(C)===C){if(0<=C&&C<=r)return m(0,C);if(-r<=C&&C<0)return m(1,-(C+1))}return p(251),(function($){y(h(8).setFloat64(l,$))})(C);case"string":var f=[];for(T=0;T<C.length;++T){var S=C.charCodeAt(T);S<128?f.push(S):S<2048?(f.push(192|S>>6),f.push(128|63&S)):S<55296?(f.push(224|S>>12),f.push(128|S>>6&63),f.push(128|63&S)):(S=(1023&S)<<10,S|=1023&C.charCodeAt(++T),S+=65536,f.push(240|S>>18),f.push(128|S>>12&63),f.push(128|S>>6&63),f.push(128|63&S))}return m(3,f.length),b(f);default:var O;if(Array.isArray(C))for(m(4,O=C.length),T=0;T<O;++T)R(C[T]);else if(C instanceof Uint8Array)m(2,C.length),b(C);else{var F=Object.keys(C);for(m(5,O=F.length),T=0;T<O;++T){var A=F[T];R(A),R(C[A])}}}})(o),"slice"in u)return u.slice(0,l);for(var v=new ArrayBuffer(l),_=new DataView(v),D=0;D<l;++D)_.setUint8(D,d.getUint8(D));return v},decode:function(o,c,u){var d=new DataView(o),l=0;function h(T,f){return l+=f,T}function y(T){return h(new Uint8Array(o,l,T),T)}function p(){return h(d.getUint8(l),1)}function b(){return h(d.getUint16(l),2)}function m(){return h(d.getUint32(l),4)}function v(){return d.getUint8(l)===255&&(l+=1,!0)}function _(T){if(T<24)return T;if(T===24)return p();if(T===25)return b();if(T===26)return m();if(T===27)return m()*n+m();if(T===31)return-1;throw"Invalid length encoding"}function D(T){var f=p();if(f===255)return-1;var S=_(31&f);if(S<0||f>>5!==T)throw"Invalid indefinite length element";return S}function R(T,f){for(var S=0;S<f;++S){var O=p();128&O&&(O<224?(O=(31&O)<<6|63&p(),f-=1):O<240?(O=(15&O)<<12|(63&p())<<6|63&p(),f-=2):(O=(15&O)<<18|(63&p())<<12|(63&p())<<6|63&p(),f-=3)),O<65536?T.push(O):(O-=65536,T.push(55296|O>>10),T.push(56320|1023&O))}}typeof c!="function"&&(c=function(T){return T}),typeof u!="function"&&(u=function(){return t});var C=(function T(){var f,S,O=p(),F=O>>5,A=31&O;if(F===7)switch(A){case 25:return(function(){var se=new ArrayBuffer(4),ue=new DataView(se),Re=b(),Ve=32768&Re,be=31744&Re,Pe=1023ℜif(be===31744)be=261120;else if(be!==0)be+=114688;else if(Pe!==0)return Pe*s;return ue.setUint32(0,Ve<<16|be<<13|Pe<<13),ue.getFloat32(0)})();case 26:return h(d.getFloat32(l),4);case 27:return h(d.getFloat64(l),8)}if((S=_(A))<0&&(F<2||6<F))throw"Invalid length";switch(F){case 0:return S;case 1:return-1-S;case 2:if(S<0){for(var $=[],X=0;(S=D(F))>=0;)X+=S,$.push(y(S));var k=new Uint8Array(X),N=0;for(f=0;f<$.length;++f)k.set($[f],N),N+=$[f].length;return k}return y(S);case 3:var w=[];if(S<0)for(;(S=D(F))>=0;)R(w,S);else R(w,S);return String.fromCharCode.apply(null,w);case 4:var P;if(S<0)for(P=[];!v();)P.push(T());else for(P=new Array(S),f=0;f<S;++f)P[f]=T();return P;case 5:var ie={};for(f=0;f<S||S<0&&!v();++f)ie[T()]=T();return ie;case 6:return c(T(),S);case 7:switch(S){case 20:return!1;case 21:return!0;case 22:return null;case 23:return t;default:return u(S)}}})();if(l!==o.byteLength)throw"Remaining bytes";return C}};a.exports?a.exports=i:e.CBOR||(e.CBOR=i)})(Rt)})(Dt);var ys=De(Dt.exports);function Z(a,e){var t={};for(var s in a)Object.prototype.hasOwnProperty.call(a,s)&&e.indexOf(s)<0&&(t[s]=a[s]);if(a!=null&&typeof Object.getOwnPropertySymbols=="function"){var n=0;for(s=Object.getOwnPropertySymbols(a);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(a,s[n])&&(t[s[n]]=a[s[n]])}return t}function g(a,e,t,s){return new(t||(t=Promise))((function(n,r){function i(u){try{c(s.next(u))}catch(d){r(d)}}function o(u){try{c(s.throw(u))}catch(d){r(d)}}function c(u){var d;u.done?n(u.value):(d=u.value,d instanceof t?d:new t((function(l){l(d)}))).then(i,o)}c((s=s.apply(a,e||[])).next())}))}typeof SuppressedError=="function"&&SuppressedError;class ot{static legacyCryptoModule(e){throw new Error("Should be implemented by concrete crypto module implementation.")}static aesCbcCryptoModule(e){throw new Error("Should be implemented by concrete crypto module implementation.")}constructor(e){var t;this.defaultCryptor=e.default,this.cryptors=(t=e.cryptors)!==null&&t!==void 0?t:[]}set logger(e){throw new Error("Method not implemented.")}getAllCryptors(){return[this.defaultCryptor,...this.cryptors]}toString(){return`AbstractCryptoModule { default: ${this.defaultCryptor.toString()}, cryptors: [${this.cryptors.map((e=>e.toString())).join(", ")}]}`}}ot.encoder=new TextEncoder,ot.decoder=new TextDecoder;class ee{static create(e){return new ee(e)}constructor(e){let t,s,n,r;if(e instanceof File)r=e,n=e.name,s=e.type,t=e.size;else if("data"in e){const i=e.data;s=e.mimeType,n=e.name,r=new File([i],n,{type:s}),t=r.size}if(r===void 0)throw new Error("Couldn't construct a file out of supplied options.");if(n===void 0)throw new Error("Couldn't guess filename out of the options. Please provide one.");t&&(this.contentLength=t),this.mimeType=s,this.data=r,this.name=n}toBuffer(){return g(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in Node.js environments.")}))}toArrayBuffer(){return g(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const s=new FileReader;s.addEventListener("load",(()=>{if(s.result instanceof ArrayBuffer)return e(s.result)})),s.addEventListener("error",(()=>t(s.error))),s.readAsArrayBuffer(this.data)}))}))}toString(){return g(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const s=new FileReader;s.addEventListener("load",(()=>{if(typeof s.result=="string")return e(s.result)})),s.addEventListener("error",(()=>{t(s.error)})),s.readAsBinaryString(this.data)}))}))}toStream(){return g(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in Node.js environments.")}))}toFile(){return g(this,void 0,void 0,(function*(){return this.data}))}toFileUri(){return g(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in React Native environments.")}))}toBlob(){return g(this,void 0,void 0,(function*(){return this.data}))}}
1ee.supportsBlob=typeof Blob<"u",ee.supportsFile=typeof File<"u",ee.supportsBuffer=!1,ee.supportsStream=!1,ee.supportsString=!0,ee.supportsArrayBuffer=!0,ee.supportsEncryptFile=!0,ee.supportsFileUri=!1;function ze(a){const e=a.replace(/==?$/,""),t=Math.floor(e.length/4*3),s=new ArrayBuffer(t),n=new Uint8Array(s);let r=0;function i(){const o=e.charAt(r++),c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o);if(c===-1)throw new Error(`Illegal character at ${r}: ${e.charAt(r-1)}`);return c}for(let o=0;o<t;o+=3){const c=i(),u=i(),d=i(),l=i(),h=(63&c)<<2|u>>4,y=(15&u)<<4|d>>2,p=(3&d)<<6|l;n[o]=h,d!=64&&(n[o+1]=y),l!=64&&(n[o+2]=p)}return s}function Je(a){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=new Uint8Array(a),n=s.byteLength,r=n%3,i=n-r;let o,c,u,d,l;for(let h=0;h<i;h+=3)l=s[h]<<16|s[h+1]<<8|s[h+2],o=(16515072&l)>>18,c=(258048&l)>>12,u=(4032&l)>>6,d=63&l,e+=t[o]+t[c]+t[u]+t[d];return r==1?(l=s[i],o=(252&l)>>2,c=(3&l)<<4,e+=t[o]+t[c]+"=="):r==2&&(l=s[i]<<8|s[i+1],o=(64512&l)>>10,c=(1008&l)>>4,u=(15&l)<<2,e+=t[o]+t[c]+t[u]+"="),e}var ct;(function(a){a.PNNetworkIssuesCategory="PNNetworkIssuesCategory",a.PNTimeoutCategory="PNTimeoutCategory",a.PNCancelledCategory="PNCancelledCategory",a.PNBadRequestCategory="PNBadRequestCategory",a.PNAccessDeniedCategory="PNAccessDeniedCategory",a.PNValidationErrorCategory="PNValidationErrorCategory",a.PNAcknowledgmentCategory="PNAcknowledgmentCategory",a.PNMalformedResponseCategory="PNMalformedResponseCategory",a.PNServerErrorCategory="PNServerErrorCategory",a.PNUnknownCategory="PNUnknownCategory",a.PNNetworkUpCategory="PNNetworkUpCategory",a.PNNetworkDownCategory="PNNetworkDownCategory",a.PNReconnectedCategory="PNReconnectedCategory",a.PNConnectedCategory="PNConnectedCategory",a.PNSubscriptionChangedCategory="PNSubscriptionChangedCategory",a.PNRequestMessageCountExceededCategory="PNRequestMessageCountExceededCategory",a.PNDisconnectedCategory="PNDisconnectedCategory",a.PNConnectionErrorCategory="PNConnectionErrorCategory",a.PNDisconnectedUnexpectedlyCategory="PNDisconnectedUnexpectedlyCategory",a.PNSharedWorkerUpdatedCategory="PNSharedWorkerUpdatedCategory"})(ct||(ct={}));var M=ct;class G extends Error{constructor(e,t){super(e),this.status=t,this.name="PubNubError",this.message=e,Object.setPrototypeOf(this,new.target.prototype)}}function Ut(a,e){var t;return(t=a.statusCode)!==null&&t!==void 0||(a.statusCode=0),Object.assign(Object.assign({},a),{statusCode:a.statusCode,category:e,error:!0})}function ut(a,e){return Ut(Object.assign(Object.assign({message:"Unable to deserialize service response"},a!==void 0?{responseText:a}:{}),e!==void 0?{statusCode:e}:{}),M.PNMalformedResponseCategory)}var lt,At,$t,xt,Ue,ne=ne||(function(a){var e={},t=e.lib={},s=function(){},n=t.Base={extend:function(h){s.prototype=this;var y=new s;return h&&y.mixIn(h),y.hasOwnProperty("init")||(y.init=function(){y.$super.init.apply(this,arguments)}),y.init.prototype=y,y.$super=this,y},create:function(){var h=this.extend();return h.init.apply(h,arguments),h},init:function(){},mixIn:function(h){for(var y in h)h.hasOwnProperty(y)&&(this[y]=h[y]);h.hasOwnProperty("toString")&&(this.toString=h.toString)},clone:function(){return this.init.prototype.extend(this)}},r=t.WordArray=n.extend({init:function(h,y){h=this.words=h||[],this.sigBytes=y??4*h.length},toString:function(h){return(h||o).stringify(this)},concat:function(h){var y=this.words,p=h.words,b=this.sigBytes;if(h=h.sigBytes,this.clamp(),b%4)for(var m=0;m<h;m++)y[b+m>>>2]|=(p[m>>>2]>>>24-m%4*8&255)<<24-(b+m)%4*8;else if(65535<p.length)for(m=0;m<h;m+=4)y[b+m>>>2]=p[m>>>2];else y.push.apply(y,p);return this.sigBytes+=h,this},clamp:function(){var h=this.words,y=this.sigBytes;h[y>>>2]&=4294967295<<32-y%4*8,h.length=a.ceil(y/4)},clone:function(){var h=n.clone.call(this);return h.words=this.words.slice(0),h},random:function(h){for(var y=[],p=0;p<h;p+=4)y.push(4294967296*a.random()|0);return new r.init(y,h)}}),i=e.enc={},o=i.Hex={stringify:function(h){var y=h.words;h=h.sigBytes;for(var p=[],b=0;b<h;b++){var m=y[b>>>2]>>>24-b%4*8&255;p.push((m>>>4).toString(16)),p.push((15&m).toString(16))}return p.join("")},parse:function(h){for(var y=h.length,p=[],b=0;b<y;b+=2)p[b>>>3]|=parseInt(h.substr(b,2),16)<<24-b%8*4;return new r.init(p,y/2)}},c=i.Latin1={stringify:function(h){var y=h.words;h=h.sigBytes;for(var p=[],b=0;b<h;b++)p.push(String.fromCharCode(y[b>>>2]>>>24-b%4*8&255));return p.join("")},parse:function(h){for(var y=h.length,p=[],b=0;b<y;b++)p[b>>>2]|=(255&h.charCodeAt(b))<<24-b%4*8;return new r.init(p,y)}},u=i.Utf8={stringify:function(h){try{return decodeURIComponent(escape(c.stringify(h)))}catch{throw Error("Malformed UTF-8 data")}},parse:function(h){return c.parse(unescape(encodeURIComponent(h)))}},d=t.BufferedBlockAlgorithm=n.extend({reset:function(){this._data=new r.init,this._nDataBytes=0},_append:function(h){typeof h=="string"&&(h=u.parse(h)),this._data.concat(h),this._nDataBytes+=h.sigBytes},_process:function(h){var y=this._data,p=y.words,b=y.sigBytes,m=this.blockSize,v=b/(4*m);if(h=(v=h?a.ceil(v):a.max((0|v)-this._minBufferSize,0))*m,b=a.min(4*h,b),h){for(var _=0;_<h;_+=m)this._doProcessBlock(p,_);_=p.splice(0,h),y.sigBytes-=b}return new r.init(_,b)},clone:function(){var h=n.clone.call(this);return h._data=this._data.clone(),h},_minBufferSize:0});t.Hasher=d.extend({cfg:n.extend(),init:function(h){this.cfg=this.cfg.extend(h),this.reset()},reset:function(){d.reset.call(this),this._doReset()},update:function(h){return this._append(h),this._process(),this},finalize:function(h){return h&&this._append(h),this._doFinalize()},blockSize:16,_createHelper:function(h){return function(y,p){return new h.init(p).finalize(y)}},_createHmacHelper:function(h){return function(y,p){return new l.HMAC.init(h,p).finalize(y)}}});var l=e.algo={};return e})(Math);(function(a){for(var e=ne,t=(n=e.lib).WordArray,s=n.Hasher,n=e.algo,r=[],i=[],o=function(p){return 4294967296*(p-(0|p))|0},c=2,u=0;64>u;){var d;e:{d=c;for(var l=a.sqrt(d),h=2;h<=l;h++)if(!(d%h)){d=!1;break e}d=!0}d&&(8>u&&(r[u]=o(a.pow(c,.5))),i[u]=o(a.pow(c,1/3)),u++),c++}var y=[];n=n.SHA256=s.extend({_doReset:function(){this._hash=new t.init(r.slice(0))},_doProcessBlock:function(p,b){for(var m=this._hash.words,v=m[0],_=m[1],D=m[2],R=m[3],C=m[4],T=m[5],f=m[6],S=m[7],O=0;64>O;O++){if(16>O)y[O]=0|p[b+O];else{var F=y[O-15],A=y[O-2];y[O]=((F<<25|F>>>7)^(F<<14|F>>>18)^F>>>3)+y[O-7]+((A<<15|A>>>17)^(A<<13|A>>>19)^A>>>10)+y[O-16]}F=S+((C<<26|C>>>6)^(C<<21|C>>>11)^(C<<7|C>>>25))+(C&T^~C&f)+i[O]+y[O],A=((v<<30|v>>>2)^(v<<19|v>>>13)^(v<<10|v>>>22))+(v&_^v&D^_&D),S=f,f=T,T=C,C=R+F|0,R=D,D=_,_=v,v=F+A|0}m[0]=m[0]+v|0,m[1]=m[1]+_|0,m[2]=m[2]+D|0,m[3]=m[3]+R|0,m[4]=m[4]+C|0,m[5]=m[5]+T|0,m[6]=m[6]+f|0,m[7]=m[7]+S|0},_doFinalize:function(){var p=this._data,b=p.words,m=8*this._nDataBytes,v=8*p.sigBytes;return b[v>>>5]|=128<<24-v%32,b[14+(v+64>>>9<<4)]=a.floor(m/4294967296),b[15+(v+64>>>9<<4)]=m,p.sigBytes=4*b.length,this._process(),this._hash},clone:function(){var p=s.clone.call(this);return p._hash=this._hash.clone(),p}}),e.SHA256=s._createHelper(n),e.HmacSHA256=s._createHmacHelper(n)})(Math),At=(lt=ne).enc.Utf8,lt.algo.HMAC=lt.lib.Base.extend({init:function(a,e){a=this._hasher=new a.init,typeof e=="string"&&(e=At.parse(e));var t=a.blockSize,s=4*t;e.sigBytes>s&&(e=a.finalize(e)),e.clamp();for(var n=this._oKey=e.clone(),r=this._iKey=e.clone(),i=n.words,o=r.words,c=0;c<t;c++)i[c]^=1549556828,o[c]^=909522486;n.sigBytes=r.sigBytes=s,this.reset()},reset:function(){var a=this._hasher;a.reset(),a.update(this._iKey)},update:function(a){return this._hasher.update(a),this},finalize:function(a){var e=this._hasher;return a=e.finalize(a),e.reset(),e.finalize(this._oKey.clone().concat(a))}}),xt=($t=ne).lib.WordArray,$t.enc.Base64={stringify:function(a){var e=a.words,t=a.sigBytes,s=this._map;a.clamp(),a=[];for(var n=0;n<t;n+=3)for(var r=(e[n>>>2]>>>24-n%4*8&255)<<16|(e[n+1>>>2]>>>24-(n+1)%4*8&255)<<8|e[n+2>>>2]>>>24-(n+2)%4*8&255,i=0;4>i&&n+.75*i<t;i++)a.push(s.charAt(r>>>6*(3-i)&63));if(e=s.charAt(64))for(;a.length%4;)a.push(e);return a.join("")},parse:function(a){var e=a.length,t=this._map;(s=t.charAt(64))&&(s=a.indexOf(s))!=-1&&(e=s);for(var s=[],n=0,r=0;r<e;r++)if(r%4){var i=t.indexOf(a.charAt(r-1))<<r%4*2,o=t.indexOf(a.charAt(r))>>>6-r%4*2;s[n>>>2]|=(i|o)<<24-n%4*8,n++}return xt.create(s,n)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
1+/="},(function(a){function e(l,h,y,p,b,m,v){return((l=l+(h&y|~h&p)+b+v)<<m|l>>>32-m)+h}function t(l,h,y,p,b,m,v){return((l=l+(h&p|y&~p)+b+v)<<m|l>>>32-m)+h}function s(l,h,y,p,b,m,v){return((l=l+(h^y^p)+b+v)<<m|l>>>32-m)+h}function n(l,h,y,p,b,m,v){return((l=l+(y^(h|~p))+b+v)<<m|l>>>32-m)+h}for(var r=ne,i=(c=r.lib).WordArray,o=c.Hasher,c=r.algo,u=[],d=0;64>d;d++)u[d]=4294967296*a.abs(a.sin(d+1))|0;c=c.MD5=o.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(l,h){for(var y=0;16>y;y++){var p=l[b=h+y];l[b]=16711935&(p<<8|p>>>24)|4278255360&(p<<24|p>>>8)}y=this._hash.words;var b=l[h+0],m=(p=l[h+1],l[h+2]),v=l[h+3],_=l[h+4],D=l[h+5],R=l[h+6],C=l[h+7],T=l[h+8],f=l[h+9],S=l[h+10],O=l[h+11],F=l[h+12],A=l[h+13],$=l[h+14],X=l[h+15],k=e(k=y[0],P=y[1],w=y[2],N=y[3],b,7,u[0]),N=e(N,k,P,w,p,12,u[1]),w=e(w,N,k,P,m,17,u[2]),P=e(P,w,N,k,v,22,u[3]);k=e(k,P,w,N,_,7,u[4]),N=e(N,k,P,w,D,12,u[5]),w=e(w,N,k,P,R,17,u[6]),P=e(P,w,N,k,C,22,u[7]),k=e(k,P,w,N,T,7,u[8]),N=e(N,k,P,w,f,12,u[9]),w=e(w,N,k,P,S,17,u[10]),P=e(P,w,N,k,O,22,u[11]),k=e(k,P,w,N,F,7,u[12]),N=e(N,k,P,w,A,12,u[13]),w=e(w,N,k,P,$,17,u[14]),k=t(k,P=e(P,w,N,k,X,22,u[15]),w,N,p,5,u[16]),N=t(N,k,P,w,R,9,u[17]),w=t(w,N,k,P,O,14,u[18]),P=t(P,w,N,k,b,20,u[19]),k=t(k,P,w,N,D,5,u[20]),N=t(N,k,P,w,S,9,u[21]),w=t(w,N,k,P,X,14,u[22]),P=t(P,w,N,k,_,20,u[23]),k=t(k,P,w,N,f,5,u[24]),N=t(N,k,P,w,$,9,u[25]),w=t(w,N,k,P,v,14,u[26]),P=t(P,w,N,k,T,20,u[27]),k=t(k,P,w,N,A,5,u[28]),N=t(N,k,P,w,m,9,u[29]),w=t(w,N,k,P,C,14,u[30]),k=s(k,P=t(P,w,N,k,F,20,u[31]),w,N,D,4,u[32]),N=s(N,k,P,w,T,11,u[33]),w=s(w,N,k,P,O,16,u[34]),P=s(P,w,N,k,$,23,u[35]),k=s(k,P,w,N,p,4,u[36]),N=s(N,k,P,w,_,11,u[37]),w=s(w,N,k,P,C,16,u[38]),P=s(P,w,N,k,S,23,u[39]),k=s(k,P,w,N,A,4,u[40]),N=s(N,k,P,w,b,11,u[41]),w=s(w,N,k,P,v,16,u[42]),P=s(P,w,N,k,R,23,u[43]),k=s(k,P,w,N,f,4,u[44]),N=s(N,k,P,w,F,11,u[45]),w=s(w,N,k,P,X,16,u[46]),k=n(k,P=s(P,w,N,k,m,23,u[47]),w,N,b,6,u[48]),N=n(N,k,P,w,C,10,u[49]),w=n(w,N,k,P,$,15,u[50]),P=n(P,w,N,k,D,21,u[51]),k=n(k,P,w,N,F,6,u[52]),N=n(N,k,P,w,v,10,u[53]),w=n(w,N,k,P,S,15,u[54]),P=n(P,w,N,k,p,21,u[55]),k=n(k,P,w,N,T,6,u[56]),N=n(N,k,P,w,X,10,u[57]),w=n(w,N,k,P,R,15,u[58]),P=n(P,w,N,k,A,21,u[59]),k=n(k,P,w,N,_,6,u[60]),N=n(N,k,P,w,O,10,u[61]),w=n(w,N,k,P,m,15,u[62]),P=n(P,w,N,k,f,21,u[63]),y[0]=y[0]+k|0,y[1]=y[1]+P|0,y[2]=y[2]+w|0,y[3]=y[3]+N|0},_doFinalize:function(){var l=this._data,h=l.words,y=8*this._nDataBytes,p=8*l.sigBytes;h[p>>>5]|=128<<24-p%32;var b=a.floor(y/4294967296);for(h[15+(p+64>>>9<<4)]=16711935&(b<<8|b>>>24)|4278255360&(b<<24|b>>>8),h[14+(p+64>>>9<<4)]=16711935&(y<<8|y>>>24)|4278255360&(y<<24|y>>>8),l.sigBytes=4*(h.length+1),this._process(),h=(l=this._hash).words,y=0;4>y;y++)p=h[y],h[y]=16711935&(p<<8|p>>>24)|4278255360&(p<<24|p>>>8);return l},clone:function(){var l=o.clone.call(this);return l._hash=this._hash.clone(),l}}),r.MD5=o._createHelper(c),r.HmacMD5=o._createHmacHelper(c)})(Math),(function(){var a,e=ne,t=(a=e.lib).Base,s=a.WordArray,n=(a=e.algo).EvpKDF=t.extend({cfg:t.extend({keySize:4,hasher:a.MD5,iterations:1}),init:function(r){this.cfg=this.cfg.extend(r)},compute:function(r,i){for(var o=(l=this.cfg).hasher.create(),c=s.create(),u=c.words,d=l.keySize,l=l.iterations;u.length<d;){h&&o.update(h);var h=o.update(r).finalize(i);o.reset();for(var y=1;y<l;y++)h=o.finalize(h),o.reset();c.concat(h)}return c.sigBytes=4*d,c}});e.EvpKDF=function(r,i,o){return n.create(o).compute(r,i)}})(),ne.lib.Cipher||(function(){var a=(h=ne).lib,e=a.Base,t=a.WordArray,s=a.BufferedBlockAlgorithm,n=h.enc.Base64,r=h.algo.EvpKDF,i=a.Cipher=s.extend({cfg:e.extend(),createEncryptor:function(p,b){return this.create(this._ENC_XFORM_MODE,p,b)},createDecryptor:function(p,b){return this.create(this._DEC_XFORM_MODE,p,b)},init:function(p,b,m){this.cfg=this.cfg.extend(m),this._xformMode=p,this._key=b,this.reset()},reset:function(){s.reset.call(this),this._doReset()},process:function(p){return this._append(p),this._process()},finalize:function(p){return p&&this._append(p),this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(p){return{encrypt:function(b,m,v){return(typeof m=="string"?y:l).encrypt
vendor: 4,218 bytes, line 1
1(p,b,m,v)},decrypt:function(b,m,v){return(typeof m=="string"?y:l).decrypt(p,b,m,v)}}}});a.StreamCipher=i.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var o=h.mode={},c=function(p,b,m){var v=this._iv;v?this._iv=void 0:v=this._prevBlock;for(var _=0;_<m;_++)p[b+_]^=v[_]},u=(a.BlockCipherMode=e.extend({createEncryptor:function(p,b){return this.Encryptor.create(p,b)},createDecryptor:function(p,b){return this.Decryptor.create(p,b)},init:function(p,b){this._cipher=p,this._iv=b}})).extend();u.Encryptor=u.extend({processBlock:function(p,b){var m=this._cipher,v=m.blockSize;c.call(this,p,b,v),m.encryptBlock(p,b),this._prevBlock=p.slice(b,b+v)}}),u.Decryptor=u.extend({processBlock:function(p,b){var m=this._cipher,v=m.blockSize,_=p.slice(b,b+v);m.decryptBlock(p,b),c.call(this,p,b,v),this._prevBlock=_}}),o=o.CBC=u,u=(h.pad={}).Pkcs7={pad:function(p,b){for(var m,v=(m=(m=4*b)-p.sigBytes%m)<<24|m<<16|m<<8|m,_=[],D=0;D<m;D+=4)_.push(v);m=t.create(_,m),p.concat(m)},unpad:function(p){p.sigBytes-=255&p.words[p.sigBytes-1>>>2]}},a.BlockCipher=i.extend({cfg:i.cfg.extend({mode:o,padding:u}),reset:function(){i.reset.call(this);var p=(b=this.cfg).iv,b=b.mode;if(this._xformMode==this._ENC_XFORM_MODE)var m=b.createEncryptor;else m=b.createDecryptor,this._minBufferSize=1;this._mode=m.call(b,this,p&&p.words)},_doProcessBlock:function(p,b){this._mode.processBlock(p,b)},_doFinalize:function(){var p=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){p.pad(this._data,this.blockSize);var b=this._process(!0)}else b=this._process(!0),p.unpad(b);return b},blockSize:4});var d=a.CipherParams=e.extend({init:function(p){this.mixIn(p)},toString:function(p){return(p||this.formatter).stringify(this)}}),l=(o=(h.format={}).OpenSSL={stringify:function(p){var b=p.ciphertext;return((p=p.salt)?t.create([1398893684,1701076831]).concat(p).concat(b):b).toString(n)},parse:function(p){var b=(p=n.parse(p)).words;if(b[0]==1398893684&&b[1]==1701076831){var m=t.create(b.slice(2,4));b.splice(0,4),p.sigBytes-=16}return d.create({ciphertext:p,salt:m})}},a.SerializableCipher=e.extend({cfg:e.extend({format:o}),encrypt:function(p,b,m,v){v=this.cfg.extend(v);var _=p.createEncryptor(m,v);return b=_.finalize(b),_=_.cfg,d.create({ciphertext:b,key:m,iv:_.iv,algorithm:p,mode:_.mode,padding:_.padding,blockSize:p.blockSize,formatter:v.format})},decrypt:function(p,b,m,v){return v=this.cfg.extend(v),b=this._parse(b,v.format),p.createDecryptor(m,v).finalize(b.ciphertext)},_parse:function(p,b){return typeof p=="string"?b.parse(p,this):p}})),h=(h.kdf={}).OpenSSL={execute:function(p,b,m,v){return v||(v=t.random(8)),p=r.create({keySize:b+m}).compute(p,v),m=t.create(p.words.slice(b),4*m),p.sigBytes=4*b,d.create({key:p,iv:m,salt:v})}},y=a.PasswordBasedCipher=l.extend({cfg:l.cfg.extend({kdf:h}),encrypt:function(p,b,m,v){return m=(v=this.cfg.extend(v)).kdf.execute(m,p.keySize,p.ivSize),v.iv=m.iv,(p=l.encrypt.call(this,p,b,m.key,v)).mixIn(m),p},decrypt:function(p,b,m,v){return v=this.cfg.extend(v),b=this._parse(b,v.format),m=v.kdf.execute(m,p.keySize,p.ivSize,b.salt),v.iv=m.iv,l.decrypt.call(this,p,b,m.key,v)}})})(),(function(){for(var a=ne,e=a.lib.BlockCipher,t=a.algo,s=[],n=[],r=[],i=[],o=[],c=[],u=[],d=[],l=[],h=[],y=[],p=0;256>p;p++)y[p]=128>p?p<<1:p<<1^283;var b=0,m=0;for(p=0;256>p;p++){var v=(v=m^m<<1^m<<2^m<<3^m<<4)>>>8^255&v^99;s[b]=v,n[v]=b;var _=y[b],D=y[_],R=y[D],C=257*y[v]^16843008*v;r[b]=C<<24|C>>>8,i[b]=C<<16|C>>>16,o[b]=C<<8|C>>>24,c[b]=C,C=16843009*R^65537*D^257*_^16843008*b,u[v]=C<<24|C>>>8,d[v]=C<<16|C>>>16,l[v]=C<<8|C>>>24,h[v]=C,b?(b=_^y[y[y[R^_]]],m^=y[y[m]]):b=m=1}var T=[0,1,2,4,8,16,32,64,128,27,54];t=t.AES=e.extend({_doReset:function(){for(var f=(O=this._key).words,S=O.sigBytes/4,O=4*((this._nRounds=S+6)+1),F=this._keySchedule=[],A=0;A<O;A++)if(A<S)F[A]=f[A];else{var $=F[A-1];A%S?6<S&&A%S==4&&($=s[$>>>24]<<24|s[$>>>16&255]<<16|s[$>>>8&255]<<8|s[255&$]):($=s[($=$<<8|$>>>24)>>>24]<<24|s[$>>>16&255]<<16|s[$>>>8&255]<<8|s[255&$],$^=T[A/S|0]<<24),F[A]=F[A-S]^$}for(f=this._invKeySchedule=[],S=0;S<O;S++)A=O-S,$=S%4?F[A]:F[A-4],f[S]=4>S||4>=A?$:u[s[$>>>24]]^d[s[$>>>16&255]]^l[s[$>>>8&255]]^h[s[255&$]]},encryptBlock:function(f,S){this._doCryptBlock(f,S,this._keySchedule,r,i,o,
1c,s)},decryptBlock:function(f,S){var O=f[S+1];f[S+1]=f[S+3],f[S+3]=O,this._doCryptBlock(f,S,this._invKeySchedule,u,d,l,h,n),O=f[S+1],f[S+1]=f[S+3],f[S+3]=O},_doCryptBlock:function(f,S,O,F,A,$,X,k){for(var N=this._nRounds,w=f[S]^O[0],P=f[S+1]^O[1],ie=f[S+2]^O[2],se=f[S+3]^O[3],ue=4,Re=1;Re<N;Re++){var Ve=F[w>>>24]^A[P>>>16&255]^$[ie>>>8&255]^X[255&se]^O[ue++],be=F[P>>>24]^A[ie>>>16&255]^$[se>>>8&255]^X[255&w]^O[ue++],Pe=F[ie>>>24]^A[se>>>16&255]^$[w>>>8&255]^X[255&P]^O[ue++];se=F[se>>>24]^A[w>>>16&255]^$[P>>>8&255]^X[255&ie]^O[ue++],w=Ve,P=be,ie=Pe}Ve=(k[w>>>24]<<24|k[P>>>16&255]<<16|k[ie>>>8&255]<<8|k[255&se])^O[ue++],be=(k[P>>>24]<<24|k[ie>>>16&255]<<16|k[se>>>8&255]<<8|k[255&w])^O[ue++],Pe=(k[ie>>>24]<<24|k[se>>>16&255]<<16|k[w>>>8&255]<<8|k[255&P])^O[ue++],se=(k[se>>>24]<<24|k[w>>>16&255]<<16|k[P>>>8&255]<<8|k[255&ie])^O[ue++],f[S]=Ve,f[S+1]=be,f[S+2]=Pe,f[S+3]=se},keySize:8}),a.AES=e._createHelper(t)})(),ne.mode.ECB=((Ue=ne.lib.BlockCipherMode.extend()).Encryptor=Ue.extend({processBlock:function(a,e){this._cipher.encryptBlock(a,e)}}),Ue.Decryptor=Ue.extend({processBlock:function(a,e){this._cipher.decryptBlock(a,e)}}),Ue);var L=De(ne);class ae{constructor({cipherKey:e}){this.cipherKey=e,this.CryptoJS=L,this.encryptedKey=this.CryptoJS.SHA256(e)}encrypt(e){if((typeof e=="string"?e:ae.decoder.decode(e)).length===0)throw new Error("encryption error. empty content");const t=this.getIv();return{metadata:t,data:ze(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 g(this,void 0,void 0,(function*(){const t=yield this.getKey(),s=this.getIv();return{data:yield crypto.subtle.encrypt({name:this.algo,iv:s},t,e),metadata:s}}))}decrypt(e){if(typeof e.data=="string")throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=this.bufferToWordArray(new Uint8ClampedArray(e.metadata)),s=this.bufferToWordArray(new Uint8ClampedArray(e.data));return ae.encoder.encode(this.CryptoJS.AES.decrypt({ciphertext:s},this.encryptedKey,{iv:t,mode:this.CryptoJS.mode.CBC}).toString(this.CryptoJS.enc.Utf8)).buffer}decryptFileData(e){return g(this,void 0,void 0,(function*(){if(typeof e.data=="string")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(ae.BLOCK_SIZE))}getKey(){return g(this,void 0,void 0,(function*(){const e=ae.encoder.encode(this.cipherKey),t=yield crypto.subtle.digest("SHA-256",e.buffer);return crypto.subtle.importKey("raw",t,this.algo,!0,["encrypt","decrypt"])}))}bufferToWordArray(e){const t=[];let s;for(s=0;s<e.length;s+=1)t[s/4|0]|=e[s]<<24-8*s;return this.CryptoJS.lib.WordArray.create(t,e.length)}toString(){return"AesCbcCryptor {}"}}ae.BLOCK_SIZE=16,ae.encoder=new TextEncoder,ae.decoder=new TextDecoder;const ms=new Set(["authKey","authKeys","secretKey","cipherKey","token","auth"]),ye=a=>ms.has(a),I=a=>encodeURIComponent(a).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),le=(a,e)=>{const t=a.map((s=>I(s)));return t.length?t.join(","):e??""},Ft=(a,e)=>{const t=Object.fromEntries(e.map((s=>[s,!1])));return a.filter((s=>!(e.includes(s)&&!t[s])||(t[s]=!0,!1)))},qt=(a,e)=>[...a].filter((t=>e.includes(t)&&a.indexOf(t)===a.lastIndexOf(t)&&e.indexOf(t)===e.lastIndexOf(t))),Gt=a=>Object.keys(a).map((e=>{const t=a[e];return Array.isArray(t)?t.map((s=>`${e}=${I(s)}`)).join("&"):`${e}=${I(t)}`})).join("&"),Kt=(a,e)=>{if(e==="0"||a==="0")return;const t=Qe(`${Date.now()}0000`,e,!1);return Qe(a,t,!0)},Xe=(a,e,t)=>{if(a&&a.length!==0){if(e&&e.length>0&&e!=="0"){const s=Qe(a,e,!1);return Qe(t??`${Date.now()}0000`,s.replace("-",""),Number(s)<0)}return t&&t.length>0&&t!=="0"?t:`${Date.now()}0000`}},Qe=(a,e,t)=>{e.startsWith("-")&&(e=e.replace("-",""),t=!1),e=e.padStart(17,"0");const s=a.slice(0,10),n=a.slice(10,17),r=e.slice(0,10),i=e.slice(10,17);let o=Number(s),c=Number(n);return o+=Number(r)*(t?1:-1),c+=Number(i)*(t?1:-1),c>=1e7?(o+=Math.floor(c/1e7),c%=1e7):c<0?o>
10?(o-=1,c+=1e7):o<0&&(c*=-1):o<0&&c>0&&(o+=1,c=1e7-c),o!==0?`${o}${`${c}`.padStart(7,"0")}`:`${c}`},ht=a=>{const e=typeof a!="string"?JSON.stringify(a):a,t=new Uint32Array(1);let s=0,n=e.length;for(;n-- >0;)t[0]=(t[0]<<5)-t[0]+e.charCodeAt(s++);return t[0].toString(16).padStart(8,"0")};function Lt(a){const e=[];let t;for(t=0;t<a.length;t+=1)e[t/4|0]|=a[t]<<24-8*t;return L.lib.WordArray.create(e,a.length)}class Ht{constructor(e){this.configuration=e,this.iv="0123456789012345",this.allowedKeyEncodings=["hex","utf8","base64","binary"],this.allowedKeyLengths=[128,256],this.allowedModes=["ecb","cbc"],this.logger=e.logger,this.defaultOptions={encryptKey:!0,keyEncoding:"utf8",keyLength:256,mode:"cbc"}}set logger(e){this._logger=e,this.logger&&this.logger.debug("Crypto",(()=>({messageType:"object",message:this.configuration,details:"Create with configuration:",ignoredKeys:(t,s)=>typeof s[t]=="function"||t==="logger"||ye(t)})))}get logger(){return this._logger}HMACSHA256(e){return L.HmacSHA256(e,this.configuration.secretKey).toString(L.enc.Base64)}SHA256(e){return L.SHA256(e).toString(L.enc.Hex)}encrypt(e,t,s){return this.configuration.customEncrypt?(this.logger&&this.logger.warn("Crypto","'customEncrypt' is deprecated. Consult docs for better alternative."),this.configuration.customEncrypt(e)):this.pnEncrypt(e,t,s)}decrypt(e,t,s){return this.configuration.customDecrypt?(this.logger&&this.logger.warn("Crypto","'customDecrypt' is deprecated. Consult docs for better alternative."),this.configuration.customDecrypt(e)):this.pnDecrypt(e,t,s)}pnEncrypt(e,t,s){const n=t??this.configuration.cipherKey;if(!n)return e;this.logger&&this.logger.debug("Crypto",(()=>({messageType:"object",message:Object.assign({data:e},s??{}),details:"Encrypt with parameters:",ignoredKeys:ye}))),s=this.parseOptions(s);const r=this.getMode(s),i=this.getPaddedKey(n,s);if(this.configuration.useRandomIVs){const c=this.getRandomIV(),u=L.AES.encrypt(e,i,{iv:c,mode:r}).ciphertext;return c.clone().concat(u.clone()).toString(L.enc.Base64)}const o=this.getIV(s);return L.AES.encrypt(e,i,{iv:o,mode:r}).ciphertext.toString(L.enc.Base64)||e}pnDecrypt(e,t,s){const n=t??this.configuration.cipherKey;if(!n)return e;this.logger&&this.logger.debug("Crypto",(()=>({messageType:"object",message:Object.assign({data:e},s??{}),details:"Decrypt with parameters:",ignoredKeys:ye}))),s=this.parseOptions(s);const r=this.getMode(s),i=this.getPaddedKey(n,s);if(this.configuration.useRandomIVs){const o=new Uint8ClampedArray(ze(e)),c=Lt(o.slice(0,16)),u=Lt(o.slice(16));try{const d=L.AES.decrypt({ciphertext:u},i,{iv:c,mode:r}).toString(L.enc.Utf8);return JSON.parse(d)}catch(d){return this.logger&&this.logger.error("Crypto",(()=>({messageType:"error",message:d}))),null}}else{const o=this.getIV(s);try{const c=L.enc.Base64.parse(e),u=L.AES.decrypt({ciphertext:c},i,{iv:o,mode:r}).toString(L.enc.Utf8);return JSON.parse(u)}catch(c){return this.logger&&this.logger.error("Crypto",(()=>({messageType:"error",message:c}))),null}}}parseOptions(e){var t,s,n,r;if(!e)return this.defaultOptions;const i={encryptKey:(t=e.encryptKey)!==null&&t!==void 0?t:this.defaultOptions.encryptKey,keyEncoding:(s=e.keyEncoding)!==null&&s!==void 0?s:this.defaultOptions.keyEncoding,keyLength:(n=e.keyLength)!==null&&n!==void 0?n:this.defaultOptions.keyLength,mode:(r=e.mode)!==null&&r!==void 0?r:this.defaultOptions.mode};return this.allowedKeyEncodings.indexOf(i.keyEncoding.toLowerCase())===-1&&(i.keyEncoding=this.defaultOptions.keyEncoding),this.allowedKeyLengths.indexOf(i.keyLength)===-1&&(i.keyLength=this.defaultOptions.keyLength),this.allowedModes.indexOf(i.mode.toLowerCase())===-1&&(i.mode=this.defaultOptions.mode),i}decodeKey(e,t){return t.keyEncoding==="base64"?L.enc.Base64.parse(e):t.keyEncoding==="hex"?L.enc.Hex.parse(e):e}getPaddedKey(e,t){return e=this.decodeKey(e,t),t.encryptKey?L.enc.Utf8.parse(this.SHA256(e).slice(0,32)):e}getMode(e){return e.mode==="ecb"?L.mode.ECB:L.mode.CBC}getIV(e){return e.mode==="cbc"?L.enc.Utf8.parse(this.iv):null}getRandomIV(){return L.lib.WordArray.random(16)}}class Q{encrypt(e,t){return g(this,void 0,void 0,(function*(){if(!(t instanceof ArrayBuffer)&&typeof t!="string")throw new Error("Cannot encrypt this file. In browsers file encryption supports only string or ArrayBuffer");const s=yield this.getKey(e);return t instanceof ArrayBuffer?this.encryptArrayBuffer(s,t):this.encryptString(s,t)}))}encryptArrayBuffer(e,t){return g(this,void 0,void 0,(function*(){const s=crypto.getRandomValues(new Uint8Array(16));return this.concatArrayBuffer(s.buffer,yield crypto.subtle.encrypt({name:"AES-CBC",iv:s},e,t))}))}encryptString(e,t){return g(this,void 0,void 0,(function*(){const s=crypto.getRandomValues(new Uint8Array(16)),n=Q.encoder.encode(t).buffer,r=yield crypto.subtle.encrypt({name:"AES-CBC",iv:s},e,n),i=this.concatArrayBuffer(s.buffer,r);return Q.decoder.decode(i)}))}encryptFile(e,t,s){return g(this,void 0,void 0,(function*(){var n,r;if(((n=t.contentLength)!==null&&n!==void 0?n:0)<=0)throw new Error("encryption error. empty content");const i=yield this.getKey(e),o=yield t.toArrayBuffer(),c=yield this.encryptArrayBuffer(i,o);return s.create({name:t.name,mimeType:(r=t.mimeType)!==null&&r!==void 0?r:"application/octet-stream",data:c})}
1))}decrypt(e,t){return g(this,void 0,void 0,(function*(){if(!(t instanceof ArrayBuffer)&&typeof t!="string")throw new Error("Cannot decrypt this file. In browsers file decryption supports only string or ArrayBuffer");const s=yield this.getKey(e);return t instanceof ArrayBuffer?this.decryptArrayBuffer(s,t):this.decryptString(s,t)}))}decryptArrayBuffer(e,t){return g(this,void 0,void 0,(function*(){const s=t.slice(0,16);if(t.slice(Q.IV_LENGTH).byteLength<=0)throw new Error("decryption error: empty content");return yield crypto.subtle.decrypt({name:"AES-CBC",iv:s},e,t.slice(Q.IV_LENGTH))}))}decryptString(e,t){return g(this,void 0,void 0,(function*(){const s=Q.encoder.encode(t).buffer,n=s.slice(0,16),r=s.slice(16),i=yield crypto.subtle.decrypt({name:"AES-CBC",iv:n},e,r);return Q.decoder.decode(i)}))}decryptFile(e,t,s){return g(this,void 0,void 0,(function*(){const n=yield this.getKey(e),r=yield t.toArrayBuffer(),i=yield this.decryptArrayBuffer(n,r);return s.create({name:t.name,mimeType:t.mimeType,data:i})}))}getKey(e){return g(this,void 0,void 0,(function*(){const t=yield crypto.subtle.digest("SHA-256",Q.encoder.encode(e)),s=Array.from(new Uint8Array(t)).map((r=>r.toString(16).padStart(2,"0"))).join(""),n=Q.encoder.encode(s.slice(0,32)).buffer;return crypto.subtle.importKey("raw",n,"AES-CBC",!0,["encrypt","decrypt"])}))}concatArrayBuffer(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(new Uint8Array(e),0),s.set(new Uint8Array(t),e.byteLength),s.buffer}}Q.IV_LENGTH=16,Q.encoder=new TextEncoder,Q.decoder=new TextDecoder;class Se{constructor(e){this.config=e,this.cryptor=new Ht(Object.assign({},e)),this.fileCryptor=new Q}set logger(e){this.cryptor.logger=e,this.config.useRandomIVs===!1&&e.warn("LegacyCryptor",`Setting 'useRandomIVs' to false is insecure and should only be used to support legacy clients. 2 Do not disable random IVs in new applications.`)}encrypt(e){const t=typeof e=="string"?e:Se.decoder.decode(e);return{data:this.cryptor.encrypt(t),metadata:null}}encryptFile(e,t){return g(this,void 0,void 0,(function*(){var s;if(!this.config.cipherKey)throw new G("File encryption error: cipher key not set.");return this.fileCryptor.encryptFile((s=this.config)===null||s===void 0?void 0:s.cipherKey,e,t)}))}decrypt(e){const t=typeof e.data=="string"?e.data:Je(e.data);return this.cryptor.decrypt(t)}decryptFile(e,t){return g(this,void 0,void 0,(function*(){if(!this.config.cipherKey)throw new G("File encryption error: cipher key not set.");return this.fileCryptor.decryptFile(this.config.cipherKey,e,t)}))}get identifier(){return""}toString(){return`LegacyCryptor { ${Object.entries(this.config).reduce(((e,[t,s])=>(t==="logger"||ye(t)||e.push(`${t}: ${typeof s=="function"?"<function>":s}`),e)),[]).join(", ")} }`}}Se.encoder=new TextEncoder,Se.decoder=new TextDecoder;class oe extends ot{set logger(e){if(this.defaultCryptor.identifier===oe.LEGACY_IDENTIFIER)e.warn("CryptoModule","'legacyCryptoModule' is deprecated. Use 'aesCbcCryptoModule' instead for new applications."),this.defaultCryptor.logger=e;else{const t=this.cryptors.find((s=>s.identifier===oe.LEGACY_IDENTIFIER));t&&(t.logger=e)}}static legacyCryptoModule(e){var t;if(!e.cipherKey)throw new G("Crypto module error: cipher key not set.");return e.logger&&(e.logger.warn("CryptoModule","'legacyCryptoModule' is deprecated. Use 'aesCbcCryptoModule' instead for new applications."),e.useRandomIVs===!1&&e.logger.warn("CryptoModule",`Setting 'useRandomIVs' to false is insecure and should only be used to support legacy clients. 3 Do not disable random IVs in new applications.`)),new oe({default:new Se(Object.assign(Object.assign({},e),{useRandomIVs:(t=e.useRandomIVs)===null||t===void 0||t})),cryptors:[new ae({cipherKey:e.cipherKey})]})}static aesCbcCryptoModule(e){var t;if(!e.cipherKey)throw new G("Crypto module error: cipher key not set.");return new oe({default:new ae({cipherKey:e.cipherKey}),cryptors:[new Se(Object.assign(Object.assign({},e),{useRandomIVs:(t=e.useRandomIVs)===null||t===void 0||t}))]})}static withDefaultCryptor(e){return new this({default:e})}encrypt(e){const t=e instanceof ArrayBuffer&&this.defaultCryptor.identifier===oe.LEGACY_IDENTIFIER?this.defaultCryptor.encrypt(oe.decoder.decode(e)):this.defaultCryptor.encrypt(e);
3if(!t.metadata)return t.data;if(typeof t.data=="string")throw new Error("Encryption error: encrypted data should be ArrayBuffed.");const s=this.getHeaderData(t);return this.concatArrayBuffer(s,t.data)}encryptFile(e,t){return g(this,void 0,void 0,(function*(){if(this.defaultCryptor.identifier===H.LEGACY_IDENTIFIER)return this.defaultCryptor.encryptFile(e,t);const s=yield this.getFileData(e),n=yield this.defaultCryptor.encryptFileData(s);if(typeof n.data=="string")throw new Error("Encryption error: encrypted data should be ArrayBuffed.");return t.create({name:e.name,mimeType:"application/octet-stream",data:this.concatArrayBuffer(this.getHeaderData(n),n.data)})}))}decrypt(e){const t=typeof e=="string"?ze(e):e,s=H.tryParse(t),n=this.getCryptor(s),r=s.length>0?t.slice(s.length-s.metadataLength,s.length):null;if(t.slice(s.length).byteLength<=0)throw new Error("Decryption error: empty content");return n.decrypt({data:t.slice(s.length),metadata:r})}decryptFile(e,t){return g(this,void 0,void 0,(function*(){const s=yield e.data.arrayBuffer(),n=H.tryParse(s),r=this.getCryptor(n);if(r?.identifier===H.LEGACY_IDENTIFIER)return r.decryptFile(e,t);const i=(yield this.getFileData(s)).slice(n.length-n.metadataLength,n.length);return t.create({name:e.name,data:yield this.defaultCryptor.decryptFileData({data:s.slice(n.length),metadata:i})})}))}getCryptorFromId(e){const t=this.getAllCryptors().find((s=>e===s.identifier));if(t)return t;throw Error("Unknown cryptor error")}getCryptor(e){if(typeof e=="string"){const t=this.getAllCryptors().find((s=>s.identifier===e));if(t)return t;throw new Error("Unknown cryptor error")}if(e instanceof Ae)return this.getCryptorFromId(e.identifier)}getHeaderData(e){if(!e.metadata)return;const t=H.from(this.defaultCryptor.identifier,e.metadata),s=new Uint8Array(t.length);let n=0;return s.set(t.data,n),n+=t.length-e.metadata.byteLength,s.set(new Uint8Array(e.metadata),n),s.buffer}concatArrayBuffer(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(new Uint8Array(e),0),s.set(new Uint8Array(t),e.byteLength),s.buffer}getFileData(e){return g(this,void 0,void 0,(function*(){if(e instanceof ArrayBuffer)return e;if(e instanceof ee)return e.toArrayBuffer();throw new Error("Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob")}))}}oe.LEGACY_IDENTIFIER="";class H{static from(e,t){if(e!==H.LEGACY_IDENTIFIER)return new Ae(e,t.byteLength)}static tryParse(e){const t=new Uint8Array(e);let s,n,r=null;if(t.byteLength>=4&&(s=t.slice(0,4),this.decoder.decode(s)!==H.SENTINEL))return oe.LEGACY_IDENTIFIER;if(!(t.byteLength>=5))throw new Error("Decryption error: invalid header version");if(r=t[4],r>H.MAX_VERSION)throw new Error("Decryption error: Unknown cryptor error");let i=5+H.IDENTIFIER_LENGTH;if(!(t.byteLength>=i))throw new Error("Decryption error: invalid crypto identifier");n=t.slice(5,i);let o=null;if(!(t.byteLength>=i+1))throw new Error("Decryption error: invalid metadata length");return o=t[i],i+=1,o===255&&t.byteLength>=i+2&&(o=new Uint16Array(t.slice(i,i+2)).reduce(((c,u)=>(c<<8)+u),0)),new Ae(this.decoder.decode(n),o)}}H.SENTINEL="PNED",H.LEGACY_IDENTIFIER="",H.IDENTIFIER_LENGTH=4,H.VERSION=1,H.MAX_VERSION=1,H.decoder=new TextDecoder;class Ae{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 H.VERSION}get length(){return H.SENTINEL.length+1+H.IDENTIFIER_LENGTH+(this.metadataLength<255?1:3)+this.metadataLength}get data(){let e=0;const t=new Uint8Array(this.length),s=new TextEncoder;t.set(s.encode(H.SENTINEL)),e+=H.SENTINEL.length,t[e]=this.version,e++,this.identifier&&t.set(s.encode(this.identifier),e);const n=this.metadataLength;return e+=H.IDENTIFIER_LENGTH,n<255?t[e]=n:t.set([255,n>>8,255&n],e),t}}Ae.IDENTIFIER_LENGTH=4,Ae.SENTINEL="PNED";class q extends Error{static create(e,t){return q.isErrorObject(e)?q.createFromError(e):q.createFromServiceResponse(e,t)}static createFromError(e){let t=M.PNUnknownCategory,s="Unknown error",n="Error";if(!e)return new q(s,t,0);if(e instanceof q)return e;if(q.isErrorObject(e)&&(s=e.message,n=e.name),n==="AbortError"||s.indexOf("Aborted")!==-1)t=M.P
3NCancelledCategory,s="Request cancelled";else if(s.toLowerCase().indexOf("timeout")!==-1)t=M.PNTimeoutCategory,s="Request timeout";else if(s.toLowerCase().indexOf("network")!==-1)t=M.PNNetworkIssuesCategory,s="Network issues";else if(n==="TypeError")t=s.indexOf("Load failed")!==-1||s.indexOf("Failed to fetch")!=-1?M.PNNetworkIssuesCategory:M.PNBadRequestCategory;else if(n==="FetchError"){const r=e.code;["ECONNREFUSED","ENETUNREACH","ENOTFOUND","ECONNRESET","EAI_AGAIN"].includes(r)&&(t=M.PNNetworkIssuesCategory),r==="ECONNREFUSED"?s="Connection refused":r==="ENETUNREACH"?s="Network not reachable":r==="ENOTFOUND"?s="Server not found":r==="ECONNRESET"?s="Connection reset by peer":r==="EAI_AGAIN"?s="Name resolution error":r==="ETIMEDOUT"?(t=M.PNTimeoutCategory,s="Request timeout"):s=`Unknown system error: ${e}`}else s==="Request timeout"&&(t=M.PNTimeoutCategory);return new q(s,t,0,e)}static createFromServiceResponse(e,t){let s,n=M.PNUnknownCategory,r="Unknown error",{status:i}=e;if(t!=null||(t=e.body),i===402?r="Not available for used key set. Contact [email protected]":i===404?r="Resource not found":i===400?(n=M.PNBadRequestCategory,r="Bad request"):i===403?(n=M.PNAccessDeniedCategory,r="Access denied"):i>=500&&(n=M.PNServerErrorCategory,r="Internal server error"),typeof e=="object"&&Object.keys(e).length===0&&(n=M.PNMalformedResponseCategory,r="Malformed response (network issues)",i=400),t&&t.byteLength>0){const o=new TextDecoder().decode(t);if(e.headers["content-type"].indexOf("text/javascript")!==-1||e.headers["content-type"].indexOf("application/json")!==-1)try{const c=JSON.parse(o);typeof c=="object"&&(Array.isArray(c)?typeof c[0]=="number"&&c[0]===0&&c.length>1&&typeof c[1]=="string"&&(s=c[1]):("error"in c&&(c.error===1||c.error===!0)&&"status"in c&&typeof c.status=="number"&&"message"in c&&"service"in c?(s=c,i=c.status):s=c,"error"in c&&c.error instanceof Error&&(s=c.error)))}catch{s=o}else if(e.headers["content-type"].indexOf("xml")!==-1){const c=/<Message>(.*)<\/Message>/gi.exec(o);r=c?`Upload to bucket failed: ${c[1]}`:"Upload to bucket failed."}else s=o}return new q(r,n,i,s)}constructor(e,t,s,n){super(e),this.category=t,this.statusCode=s,this.errorData=n,this.name="PubNubAPIError"}toStatus(e){return{error:!0,category:this.category,operation:e,statusCode:this.statusCode,errorData:this.errorData,toJSON:function(){let t;const s=this.errorData;if(s)try{if(typeof s=="object"){const r=Object.assign(Object.assign(Object.assign(Object.assign({},"name"in s?{name:s.name}:{}),"message"in s?{message:s.message}:{}),"stack"in s?{stack:s.stack}:{}),s);t=JSON.parse(JSON.stringify(r,q.circularReplacer()))}else t=s}catch{t={error:"Could not serialize the error object"}}const n=Z(this,["toJSON"]);return JSON.stringify(Object.assign(Object.assign({},n),{errorData:t}))}}}toPubNubError(e,t){return new G(t??this.message,this.toStatus(e))}static circularReplacer(){const e=new WeakSet;return function(t,s){if(typeof s=="object"&&s!==null){if(e.has(s))return"[Circular]";e.add(s)}return s}}static isErrorObject(e){return!(!e||typeof e!="object")&&(e instanceof Error||"name"in e&&"message"in e&&typeof e.name=="string"&&typeof e.message=="string"||Object.prototype.toString.call(e)==="[object Error]")}}var dt;(function(a){a.PNPublishOperation="PNPublishOperation",a.PNSignalOperation="PNSignalOperation",a.PNSubscribeOperation="PNSubscribeOperation",a.PNUnsubscribeOperation="PNUnsubscribeOperation",a.PNWhereNowOperation="PNWhereNowOperation",a.PNHereNowOperation="PNHereNowOperation",a.PNGlobalHereNowOperation="PNGlobalHereNowOperation",a.PNSetStateOperation="PNSetStateOperation",a.PNGetStateOperation="PNGetStateOperation",a.PNHeartbeatOperation="PNHeartbeatOperation",a.PNAddMessageActionOperation="PNAddActionOperation",a.PNRemoveMessageActionOperation="PNRemoveMessageActionOperation",a.PNGetMessageActionsOperation="PNGetMessageActionsOperation",a.PNTimeOperation="PNTimeOperation",a.PNHistoryOperation="PNHistoryOperation",a.PNDeleteMessagesOperation="PNDeleteMessagesOperation",a.PNFetchMessagesOperation="PNFetchMessagesOperation",a.PNMessageCounts="PNMessageCountsOperation",a.PNGetAllUUIDMetadataOperation="PNGetAllUUIDMetadataOperation",a.PNGetUUIDMetadataOperation="PNGetUUIDMetadataOperation",a.PNSetUUIDMetadataOperation="PNSetUUIDMetadataOperation",a.PNRemoveUUIDMetadataOperation="PNRemoveUUIDMetadataOperation",a.PNGetAllChannelMetadataOperation="PNGetAllChannelMetadataOperation",a.PNGetChannelMetadataOperation="PNGetChannelMetadataOperation",a.PNSetChannelMetadataOperation="PNSetChannelMetadataOperation",a.PNRemoveChannelMetadataOperation="PNRemoveChannelMetadataOperation",a.PNGetMembersOperation="PNGetMembersOperation",a.PNSetMembersOperation="PNSetMembersOperation",a.PNGetMembershipsOperation="PNGetMembershipsOperation",a.PNSetMembershipsOperation="PNSetMembershipsOperation",a.PNCreateDataSyncEntityOperation="PNCreateDataSyncEntityOperation",a.PNGetDataSyncEntityOperation="PNGetDataSyncEntityOperation",a.PNGetDataSyncEntitiesOperation="PNGetDataSyncEntitiesOperation",a.PNSetDataSyncEntityOperation="PNSetDataSyncEntityOperation",a.PNUpdateDataSyncEntityOperation="PNUpdateDataSyncEntityOperation",a.PNRemoveDataSyncEntityOperation="PNRemoveDataSyncEntityOperation",a.PNCreateDataSyncRelationshipOperation="PNCreateDataSyncRelationshipOperation",a.PNGetDataSyncRelationshipOperation="PNGetDataSyncRelationshipOperation",a.PNGetDataSyncRelationshipsOperation="PNGetDataSyncRelationshipsOperation",a.PNSetDataSyncRelationshipOperation="PNSetDataSyncRelationshipOperation",a.PNUpdateDataSyncRelationshipOperation="PNUpdateDataSyncRelationshipOperation",a.PNRemoveDataSyncRelationshipOperation="PNRemoveDataSyncRelationshipOperation",a.PNCreateDataSyncUserOperation="PNCreateDataSyncUserOperation",a.PNGetDataSyncUserOperation="PNGetDataSyncUserOperation",a.PNGetDataSyncUsersOperation="PNGetDataSyncUsersOperation",a.PNSetDataSyncUserOperation="PNSetDataSyncUserOperation",a.PNUpdateDataSyncUserOperation="PNUpdateDataSyncUserOperation",a.PNRemoveDataSyncUserOperation="PNRemoveDataSyncUserOperation",a.PNCreateDataSyncChannelOperation="PNCreateDataSyncChannelOperation",a.PNGetDataSyncChannelOperation="PNGetDataSyncChannelOperation",a.PNGetDataSyncChannelsOperation="PNGetDataSyncChannelsOperation",a.PNSetDataSyncChannelOperation="PNSetDataSyncChannelOperation",a.PNUpdateDataSyncChannelOperation="PNUpdateDataSyncChannelOperation",a.PNRemoveDataSyncChannelOperation="PNRemoveDataSyncChannelOperation",a.PNCreateDataSyncMembershipOperation="PNCreateDataSyncMembershipOperation",a.PNGetDataSyncMembershipOperation="PNGetDataSyncMembershipOperation",a.PNGetDataSyncMembershipsOperation="PNGetDataSyncMembershipsOperation",a.PNSetDataSyncMembershipOperation="PNSetDataSyncMembershipOperation",a.PNUpdateDataSyncMembershipOperation="PNUpdateDataSyncMembershipOperation",a.PNRemoveDataSyncMembershipOperation="PNRemoveDataSyncMembershipOperation",a.PNListFilesOperation="PNListFilesOperation",a.PNGenerateUploadUrlOperation="PNGenerateUploadUrlOperation",a.PNPublishFileOperation="PNPublishFileOperation",a.PNPublishFileMessageOperation="PNPublishFileMessageOperation",a.PNGetFileUrlOperation="PNGetFileUrlOperation",a.PNDownloadFileOperation="PNDownloadFileOperation",a.PNDeleteFileOperation="PNDeleteFileOperation",a.PNAddPushNotificationEnabledChannelsOperation="PNAddPushNotificationEnabledChannelsOperation",a.PNRemovePushNotificationEnabledChannelsOperation="PNRemovePushNotificationEnabledChannelsOperation",a.PNPushNotificationEnabledChannelsOperation="PNPushNotificationEnabledChannelsOperation",a.PNRemoveAllPushNotificationsOperation="PNRemoveAllPushNotificationsOperation",a.PNChannelGroupsOperation="PNChannelGroupsOperation",a.PNRemoveGroupOperation="PNRemoveGroupOperation",a.PNChannelsForGroupOperation="PNChannelsForGroupOperation",a.PNAddChannelsToGroupOperation="PNAddChannelsToGroupOperation",a.PNRemoveChannelsFromGroupOperation="PNRemoveChannelsFromGroupOperation",a.PNAccessManagerGrant="PNAccessManagerGrant",a.PNAccessManagerGrantToken="PNAccessManagerGrantToken",a.PNAccessManagerAudit="PNAccessManagerAudit",a.PNAccessManagerRevokeToken="PNAccessManagerRevokeToken",a.PNHandshakeOperation="PNHandshakeOperation",a.PNReceiveMessagesOperation="PNReceiveMessagesOperation"})(dt||(dt={}));var j=dt;class Bt{constructor(e){this.configuration=e,this.subscriptionWorkerReady=!1,this.accessTokensMap={},this.workerEventsQueue=[],this.callbacks=new Map,this.setupSubscriptionWorker()}set emitStatus(e){this._emitStatus=e}onUserIdChange(e){this.configuration.userId=e,this.scheduleEventPost({type:"client-update",heartbeatInterval:this.configuration.heartbeatInterval,clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,workerLogLevel:this.configuration.workerLogLevel})}onPresenceStateChange(e){this.scheduleEventPost({type:"client-presence-state-update",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,workerLogLevel:this.configuration.workerLogLevel,state:e})}onHeartbeatIntervalChange(e){this.configuration.heartbeatInterval=e,this.scheduleEventPost({type:"client-update",heartbeatInterval:this.configuration.heartbeatInterval,clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,workerLogLevel:this.configuration.workerLogLevel})}onTokenChange(e){const t={type:"client-update",heartbeatInterval:this.configuration.heartbeatInterval,clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,workerLogLevel:this.configuration.workerLogLevel};this.parsedAccessToken(e).then((s=>{t.preProcessedToken=s,t.accessToken=e})).then((()=>this.scheduleEventPost(t)))}disconnect(){this.scheduleEventPost({type:"client-disconnect",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,workerLogLevel:this.configuration.workerLogLevel})}terminate(){this.scheduleEventPost({type:"client-unregister",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,workerLogLevel:this.configuration.workerLogLevel})}makeSendable(e){if(!e.path.startsWith("/v2/subscribe")&&!e.path.endsWith("/heartbeat")&&!e.path.endsWith("/leave"))return this.configuration.transport.makeSendable(e);let t;this.configuration.logger.debug("SubscriptionWorkerMiddleware","Process request with SharedWorker transport.");const s={type:"send-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,request:e,workerLogLevel:this.configuration.workerLogLevel};return e.cancellable&&(t={abort:()=>{const n={type:"cancel-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,identifier:e.identifier,workerLogLevel:this.configuration.workerLogLevel};this.scheduleEventPost(n)}}),[new Promise(((n,r)=>{this.callbacks.set(e.identifier,{resolve:n,reject:r}),this.parsedAccessTokenForRequest(e).then((i=>s.preProcessedToken=i)).then((()=>this.scheduleEventPost(s)))})),t]}request(e){return e}scheduleEventPost(e,t=!1){const s=this.sharedSubscriptionWorker;s?s.port.postMessage(e):t?this.workerEventsQueue.splice(0,0,e):this.workerEventsQueue.push(e)}flushScheduledEvents(){const e=this.sharedSubscriptionWorker;if(!e||this.workerEventsQueue.length===0)return;const t=[];for(let s=0;s<this.workerEventsQueue.length;s++){const n=this.workerEventsQueue[s];if(n.type==="cancel-request"&&s!==0)for(let r=0;r<s;r++){const i=this.workerEventsQueue[r];
3if(i.type==="send-request"&&i.request.identifier===n.identifier){t.push(n,i);break}}}this.workerEventsQueue=this.workerEventsQueue.filter((s=>!t.includes(s))),this.workerEventsQueue.forEach((s=>e.port.postMessage(s))),this.workerEventsQueue=[]}get sharedSubscriptionWorker(){return this.subscriptionWorkerReady?this.subscriptionWorker:null}setupSubscriptionWorker(){if(typeof SharedWorker<"u"){try{this.subscriptionWorker=new SharedWorker(this.configuration.workerUrl,`/pubnub-${this.configuration.sdkVersion}`)}catch(e){throw this.configuration.logger.error("SubscriptionWorkerMiddleware",(()=>({messageType:"error",message:e}))),e}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,workerOfflineClientsCheckInterval:this.configuration.workerOfflineClientsCheckInterval,workerUnsubscribeOfflineClients:this.configuration.workerUnsubscribeOfflineClients,workerLogLevel:this.configuration.workerLogLevel},!0),this.subscriptionWorker.port.onmessage=e=>this.handleWorkerEvent(e),this.shouldAnnounceNewerSharedWorkerVersionAvailability()&&localStorage.setItem("PNSubscriptionSharedWorkerVersion",this.configuration.sdkVersion),window.addEventListener("storage",(e=>{e.key==="PNSubscriptionSharedWorkerVersion"&&e.newValue&&this._emitStatus&&this.isNewerSharedWorkerVersion(e.newValue)&&this._emitStatus({error:!1,category:M.PNSharedWorkerUpdatedCategory})}))}}handleWorkerEvent(e){const{data:t}=e;if(t.type==="shared-worker-ping"||t.type==="shared-worker-connected"||t.type==="shared-worker-console-log"||t.type==="shared-worker-console-dir"||t.clientIdentifier===this.configuration.clientIdentifier){if(t.type==="shared-worker-connected")this.configuration.logger.trace("SharedWorker","Ready for events processing."),this.subscriptionWorkerReady=!0,this.flushScheduledEvents();else if(t.type==="shared-worker-console-log")this.configuration.logger.debug("SharedWorker",(()=>typeof t.message=="string"||typeof t.message=="number"||typeof t.message=="boolean"?{messageType:"text",message:t.message}:t.message));else if(t.type==="shared-worker-console-dir")this.configuration.logger.debug("SharedWorker",(()=>({messageType:"object",message:t.data,details:t.message?t.message:void 0})));else if(t.type==="shared-worker-ping"){const{subscriptionKey:s,clientIdentifier:n}=this.configuration;this.scheduleEventPost({type:"client-pong",subscriptionKey:s,clientIdentifier:n,workerLogLevel:this.configuration.workerLogLevel})}else if(t.type==="request-process-success"||t.type==="request-process-error")if(this.callbacks.has(t.identifier)){const{resolve:s,reject:n}=this.callbacks.get(t.identifier);this.callbacks.delete(t.identifier),t.type==="request-process-success"?s({status:t.response.status,url:t.url,headers:t.response.headers,body:t.response.body}):n(this.errorFromRequestSendingError(t))}else this._emitStatus&&t.url.indexOf("/v2/presence")>=0&&t.url.indexOf("/heartbeat")>=0&&(t.type==="request-process-success"&&this.configuration.announceSuccessfulHeartbeats?this._emitStatus({statusCode:t.response.status,error:!1,operation:j.PNHeartbeatOperation,category:M.PNAcknowledgmentCategory}):t.type==="request-process-error"&&this.configuration.announceFailedHeartbeats&&this._emitStatus(this.errorFromRequestSendingError(t).toStatus(j.PNHeartbeatOperation)))}}parsedAccessTokenForRequest(e){return g(this,void 0,void 0,(function*(){var t;return this.parsedAccessToken(e.queryParameters?(t=e.queryParameters.auth)!==null&&t!==void 0?t:"":void 0)}))}parsedAccessToken(e){return g(this,void 0,void 0,(function*(){if(e)return this.accessTokensMap[e]?this.accessTokensMap[e]:this.stringifyAccessToken(e).then((([t,s])=>{if(t&&s)return(this.accessTokensMap={[e]:{token:s,expiration:t.timestamp+60*t.ttl}})[e]}))}))}stringifyAccessToken(e){return g(this,void 0,void 0,(function*(){if(!this.configuration.tokenManager)return[void 0,void 0];const t=this.configuration.tokenManager.parseToken(e);if(!t)return[void 0,void 0];const s=r=>r?Object.entries(r).sort((([i],[o])=>
3i.localeCompare(o))).map((([i,o])=>Object.entries(o||{}).sort((([c],[u])=>c.localeCompare(u))).map((([c,u])=>{return`${i}:${c}=${u?(d=u,Object.entries(d).filter((([l,h])=>h)).map((([l])=>l[0])).sort().join("")):""}`;var d})).join(","))).join(";"):"";let n=[s(t.resources),s(t.patterns),t.authorized_uuid].filter(Boolean).join("|");if(typeof crypto<"u"&&crypto.subtle){const r=yield crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));n=String.fromCharCode(...Array.from(new Uint8Array(r)))}return[t,typeof btoa<"u"?btoa(n):n]}))}errorFromRequestSendingError(e){let t=M.PNUnknownCategory,s="Unknown error";if(e.error)e.error.type==="NETWORK_ISSUE"?t=M.PNNetworkIssuesCategory:e.error.type==="TIMEOUT"?t=M.PNTimeoutCategory:e.error.type==="ABORTED"&&(t=M.PNCancelledCategory),s=`${e.error.message} (${e.identifier})`;else if(e.response){const{url:n,response:r}=e;return q.create({url:n,headers:r.headers,body:r.body,status:r.status},r.body)}return new q(s,t,0,new Error(s))}shouldAnnounceNewerSharedWorkerVersionAvailability(){const e=localStorage.getItem("PNSubscriptionSharedWorkerVersion");return!e||!this.isNewerSharedWorkerVersion(e)}isNewerSharedWorkerVersion(e){const[t,s,n]=this.configuration.sdkVersion.split(".").map(Number),[r,i,o]=e.split(".").map(Number);return r>t||i>s||o>n}}function Wt(a,e=0){const t=r=>typeof r=="object"&&r!==null&&r.constructor===Object,s=r=>typeof r=="number"&&isFinite(r);if(!t(a))return a;const n={};return Object.keys(a).forEach((r=>{const i=(u=>typeof u=="string"||u instanceof String)(r);let o=r;const c=a[r];e<2&&(i&&r.indexOf(",")>=0?o=r.split(",").map(Number).reduce(((u,d)=>u+String.fromCharCode(d)),""):(s(r)||i&&!isNaN(Number(r)))&&(o=String.fromCharCode(s(r)?r:parseInt(r,10)))),n[o]=t(c)?Wt(c,e+1):c})),n}const fs=a=>{var e,t,s,n,r,i;return a.subscriptionWorkerUrl&&typeof SharedWorker>"u"&&(a.subscriptionWorkerUrl=null),Object.assign(Object.assign({},(o=>{var c,u,d,l,h,y,p,b,m,v,_,D,R,C,T;const f=Object.assign({},o);if((c=f.ssl)!==null&&c!==void 0||(f.ssl=!0),(u=f.transactionalRequestTimeout)!==null&&u!==void 0||(f.transactionalRequestTimeout=15),(d=f.subscribeRequestTimeout)!==null&&d!==void 0||(f.subscribeRequestTimeout=310),(l=f.fileRequestTimeout)!==null&&l!==void 0||(f.fileRequestTimeout=300),(h=f.restore)!==null&&h!==void 0||(f.restore=!0),(y=f.useInstanceId)!==null&&y!==void 0||(f.useInstanceId=!1),(p=f.suppressLeaveEvents)!==null&&p!==void 0||(f.suppressLeaveEvents=!1),(b=f.requestMessageCountThreshold)!==null&&b!==void 0||(f.requestMessageCountThreshold=100),(m=f.autoNetworkDetection)!==null&&m!==void 0||(f.autoNetworkDetection=!1),(v=f.enableEventEngine)!==null&&v!==void 0||(f.enableEventEngine=!0),(_=f.maintainPresenceState)!==null&&_!==void 0||(f.maintainPresenceState=!0),(D=f.useSmartHeartbeat)!==null&&D!==void 0||(f.useSmartHeartbeat=!1),(R=f.keepAlive)!==null&&R!==void 0||(f.keepAlive=!1),f.userId&&f.uuid)throw new G("PubNub client configuration error: use only 'userId'");if((C=f.userId)!==null&&C!==void 0||(f.userId=f.uuid),!f.userId)throw new G("PubNub client configuration error: 'userId' not set");if(((T=f.userId)===null||T===void 0?void 0:T.trim().length)===0)throw new G("PubNub client configuration error: 'userId' is empty");f.origin||(f.origin=Array.from({length:20},((N,w)=>`ps${w+1}.pndsn.com`)));const S={subscribeKey:f.subscribeKey,publishKey:f.publishKey,secretKey:f.secretKey};f.presenceTimeout!==void 0&&(f.presenceTimeout>320?(f.presenceTimeout=320,console.warn("WARNING: Presence timeout is larger than the maximum. Using maximum value: ",320)):f.presenceTimeout<=0&&(console.warn("WARNING: Presence timeout should be larger than zero."),delete f.presenceTimeout)),f.presenceTimeout!==void 0?f.heartbeatInterval=f.presenceTimeout/2-1:f.presenceTimeout=300;let O=!1,F=!0,A=5,$=!1,X=100,k=!0;return f.dedupeOnSubscribe!==void 0&&typeof f.dedupeOnSubscribe=="boolean"&&($=f.dedupeOnSubscribe),f.maximumCacheSize!==void 0&&typeof f.maximumCacheSize=="number"&&(X=f.maximumCacheSize),f.useRequestId!==void 0&&typeof f.useRequestId=="boolean"&&(k=f.useRequestId),f.announceSuccessfulHeartbeats!==void 0&&typeof f.announceSuccessfulHeartbeats=="boolean"&&(O=f.announceSuccessfulHeartbeats),f.announceFailedHeartbeats!==void 0&&typeof f.announceFailedHeartbeats=="boolean"&&(F=f.announceFailedHeartbeats),f.fileUploadPublishRetryLimit!==void 0&&typeof f.fileUploadPublishRetryLimit=="number"&&(A=f.fileUploadPublishRetryLimit),Object.assign(Object.assign({},f),{keySet:S,dedupeOnSubscribe:$,maximumCacheSize:X,useRequestId:k,announceSuccessfulHeartbeats:O,announceFailedHeartbeats:F,fileUploadPublishRetryLimit:A})})(a)),{listenToBrowserNetworkEvents:(e=a.listenToBrowserNetworkEvents)===null||e===void 0||e,subscriptionWorkerUrl:a.subscriptionWorkerUrl,subscriptionWorkerOfflineClientsCheckInterval:(t=a.subscriptionWorkerOfflineClientsCheckInterval)!==null&&t!==void 0?t:10,subscriptionWorkerUnsubscribeOfflineClients:(s=a.subscriptionWorkerUnsubscribeOfflineClients)!==null&&s!==void 0&&s,subscriptionWorkerLogVerbosity:(n=a.subscriptionWorkerLogVerbosity)!==null&&n!==void 0&&n,transport:(r=a.transport)!==null&&r!==void 0?r:"fetch",keepAlive:(i=a.keepAlive)===null||i===void 0||i})};var J;(function(a){a[a.Trace=0]="Trace",a[a.Debug=1]="Debug",a[a.Info=2]="Info",a[a.Warn=3]="Warn",a[a.Error=4]="Error",a[a.None=5]="None"})(J||(J={}));class $e{debug(e){this.log(e)}error(e){this.log(e)}info(e){this.log(e)}trace(e){this.log(e)}warn(e){this.log(e)}toString(){return"ConsoleLogger {}"}log(e){const t=J[e.level],s=t.toLowerCase();console[s==="trace"?"debug":s](`${e.timestamp.toISOString()} PubNub-${e.pubNubId} ${t.padEnd(5," ")}${e.location?` ${e.location}`:""} ${this.logMessage(e)}`)}logMessage(e){if(e.messageType==="text")return e.message;if(e.messageType==="object")return`${e.details?`${e.details} 4`:""}${this.formattedObject(e)}`;if(e.messageType==="network-request"){const t=!!e.canceled||!!e.failed,s=e.minimumLevel!==J.Trace||t?void 0:this.formattedHeaders(e),n=e.message,r=n.queryParameters&&Object.keys(n.queryParameters).length>0?Gt(n.queryParameters):void 0,i=`${n.origin}${n.path}${r?`?${r}`:""}`,o=t?void 0:this.formattedBody(e);let c="Sending";t&&(c=`${e.canceled?"Canceled":"Failed"}${e.details?` (${e.details})`:""}`);const u=(o?.formData?"FormData":"Method").length;return`${c} HTTP request: 5 ${this.paddedString("Method",u)}: ${n.method} 6 ${this.paddedString("URL",u)}: ${i}${s?` 7 ${this.paddedString("Headers",u)}: 8${s}`:""}${o?.formData?` 9 ${this.paddedString("FormData",u)}: 10${o.formData}`:""}${o?.body?` 11 ${this.paddedString("Body",u)}: 12${o.body}`:""}`}if(e.messageType==="network-response"){const t=e.minimumLevel===J.Trace?this.formattedHeaders(e):void 0,s=this.formattedBody(e),n=(s?.formData?"Headers":"Status").length,r=e.message;return`Received HTTP response: 13 ${this.paddedString("URL",n)}: ${r.url} 14 ${this.paddedString("Status",n)}: ${r.status}${e.details?` 15 ${this.paddedString("Details",n)}: ${e.details}`:""}${t?` 16 ${this.paddedString("Headers",n)}: 17${t}`:""}${s?.body?`
18 ${this.paddedString("Body",n)}: 19${s.body}`:""}`}if(e.messageType==="error"){const t=this.formattedErrorStatus(e),s=e.message;return`${s.name}: ${s.message}${t?` 20${t}`:""}`}return"<unknown log message data>"}formattedObject(e){const t=(s,n=1,r=!1)=>{const i=n===10,o=" ".repeat(2*n),c=[],u=(d,l)=>!!e.ignoredKeys&&(typeof e.ignoredKeys=="function"?e.ignoredKeys(d,l):e.ignoredKeys.includes(d));if(typeof s=="string")c.push(`${o}- ${s}`);else if(typeof s=="number")c.push(`${o}- ${s}`);else if(typeof s=="boolean")c.push(`${o}- ${s}`);else if(s===null)c.push(`${o}- null`);else if(s===void 0)c.push(`${o}- undefined`);else if(typeof s=="function")c.push(`${o}- <function>`);else if(typeof s=="object")if(Array.isArray(s)||typeof s.toString!="function"||s.toString().indexOf("[object")===0)if(Array.isArray(s))for(const d of s){const l=r?"":o;if(d===null)c.push(`${l}- null`);else if(d===void 0)c.push(`${l}- undefined`);else if(typeof d=="function")c.push(`${l}- <function>`);else if(typeof d=="object"){const h=Array.isArray(d),y=i?"...":t(d,n+1,!h);c.push(`${l}-${h&&!i?` 21`:" "}${y}`)}else c.push(`${l}- ${d}`);r=!1}else{const d=s,l=Object.keys(d),h=l.reduce(((y,p)=>Math.max(y,u(p,d)?y:p.length)),0);for(const y of l){if(u(y,d))continue;const p=r?"":o,b=d[y],m=y.padEnd(h," ");if(b===null)c.push(`${p}${m}: null`);else if(b===void 0)c.push(`${p}${m}: undefined`);else if(typeof b=="function")c.push(`${p}${m}: <function>`);else if(typeof b=="object"){const v=Array.isArray(b),_=v&&b.length===0,D=!(v||b instanceof String||Object.keys(b).length!==0),R=!v&&typeof b.toString=="function"&&b.toString().indexOf("[object")!==0,C=i?"...":_?"[]":D?"{}":t(b,n+1,R);c.push(`${p}${m}:${i||R||_||D?" ":` 22`}${C}`)}else c.push(`${p}${m}: ${b}`);r=!1}}else c.push(`${r?"":o}${s.toString()}`),r=!1;return c.join(` 23`)};return t(e.message)}formattedHeaders(e){if(!e.message.headers)return;const t=e.message.headers,s=Object.keys(t).reduce(((n,r)=>Math.max(n,r.length)),0);return Object.keys(t).map((n=>` - ${n.toLowerCase().padEnd(s," ")}: ${t[n]}`)).join(` 24`)}formattedBody(e){var t;if(!e.message.headers)return;let s,n;const r=e.message.headers,i=(t=r["content-type"])!==null&&t!==void 0?t:r["Content-Type"],o="formData"in e.message?e.message.formData:void 0,c=e.message.body;if(o){const u=o.reduce(((d,{key:l})=>Math.max(d,l.length)),0);s=o.map((({key:d,value:l})=>` - ${d.padEnd(u," ")}: ${l}`)).join(` 25`)}return c?(n=typeof c=="string"?` ${c}`:c instanceof ArrayBuffer||Object.prototype.toString.call(c)==="[object ArrayBuffer]"?!i||i.indexOf("javascript")===-1&&i.indexOf("json")===-1?` ArrayBuffer { byteLength: ${c.byteLength} }`:` ${$e.decoder.decode(c)}`:` File { name: ${c.name}${c.contentLength?`, contentLength: ${c.contentLength}`:""}${c.mimeType?`, mimeType: ${c.mimeType}`:""} }`,{body:n,formData:s}):{formData:s}}formattedErrorStatus(e){if(!e.message.status)return;const t=e.message.status,s=t.errorData;let n;if($e.isError(s))n=` ${s.name}: ${s.message}`,s.stack&&(n+=` 26${s.stack.split(` 27`).map((r=>` ${r}`)).join(` 28`)}`);else if(s)try{n=` ${JSON.stringify(s)}`}catch{n=` ${s}`}return` Category : ${t.category} 29 Operation : ${t.operation} 30 Status : ${t.statusCode}${n?` 31 Error data: 32${n}`:""}`}paddedString(e,t){return e.padEnd(t-e.length," ")}static isError(e){return!!e&&(e instanceof Error||Object.prototype.toString.call(e)==="[object Error]")}}$e.decoder=new TextDecoder;const vs=[404,409];var B;(function(a){a.Unknown="UnknownEndpoint",a.MessageSend="MessageSendEndpoint",a.Subscribe="SubscribeEndpoint",a.Presence="PresenceEndpoint",a.Files="FilesEndpoint",a.MessageStorage="MessageStorageEndpoint",a.ChannelGroups="ChannelGroupsEndpoint",a.DevicePushNotifications="DevicePushNotificationsEndpoint",a.AppContext="AppContextEndpoint",a.MessageReactions="MessageReactionsEndpoint"})(B||(B={}));class Ye{static None(){return{shouldRetry:(e,t,s,n,r)=>!1,getDelay:(e,t)=>-1,validate:()=>!0}}static LinearRetryPolicy(e){var t;return{delay:e.delay,maximumRetry:e.maximumRetry,excluded:(t=e.excluded)!==null&&t!==void 0?t:[],shouldRetry(s,n,r,i,o){return Vt(s,n,r,i??0,this.maximumRetry,this.excluded,o)},getDelay(s,n){let r=-1;return n&&n.headers["retry-after"]!==void 0&&(r=parseInt(n.headers["retry-after"],10)),r===-1&&(r=this.delay),1e3*(r+Math.random())},validate(){if(this.delay<2)throw new Error("Delay can not be set less than 2 seconds for retry")}}}static ExponentialRetryPolicy(e){var t;return{minimumDelay:e.minimumDelay,maximumDelay:e.maximumDelay,maximumRetry:e.maximumRetry,excluded:(t=e.excluded)!==null&&t!==void 0?t:[],shouldRetry(s,n,r,i,o){return Vt(s,n,r,i??0,this.maximumRetry,this.excluded,o)},getDelay(s,n){let r=-1;return n&&n.headers["retry-after"]!==void 0&&(r=parseInt(n.headers["retry-after"],10)),r===-1&&(r=Math.min(this.minimumDelay*Math.pow(2,s),this.maximumDelay)),1e3*(r+Math.random())},validate(){if(this.minimumDelay<2)throw new Error("Minimum delay can not be set less than 2 seconds for retry")}}}}const Vt=(a,e,t,s,n,r,i)=>{var o;if(t&&(t===M.PNCancelledCategory||t===M.PNBadRequestCategory||t===M.PNAccessDeniedCategory)||Os(a,r)||s>n)return!1;const c=(o=e?.status)!==null&&o!==void 0?o:i;return(c===void 0||!vs.includes(c))&&(!e||e.status===429||e.status>=500)},Os=(a,e)=>!!(e&&e.length>0)&&e.includes(Ss(a)),Ss=a=>{let e=B.Unknown;return a.path.startsWith("/v2/subscribe")?e=B.Subscribe:a.path.startsWith("/publish/")||a.path.startsWith("/signal/")?e=B.MessageSend:a.path.startsWith("/v2/presence")?e=B.Presence:a.path.startsWith("/v2/history")||a.path.startsWith("/v3/history")?e=B.MessageStorage:a.path.startsWith("/v1/message-actions/")?e=B.MessageReactions:a.path.startsWith("/v1/channel-registration/")||a.path.startsWith("/v2/objects/")?e=B.ChannelGroups:a.path.startsWith("/v1/push/")||a.path.startsWith("/v2/push/")?e=B.DevicePushNotifications:a.path.startsWith("/v1/files/")&&(e=B.Files),e};class js{constructor(e,t,s){this.previousEntryTimestamp=0,this.pubNubId=e,this.minLogLevel=t,this.loggers=s}get logLevel(){return this.minLogLevel}trace(e,t){this.log(J.Trace,e,t)}debug(e,t){this.log(J.Debug,e,t)}info(e,t){this.log(J.Info,e,t)}warn(e,t){this.log(J.Warn,e,t)}error(e,t){this.log(J.Error,e,t)}
32log(e,t,s){if(e<this.minLogLevel||this.loggers.length===0)return;const n=new Date;n.getTime()<=this.previousEntryTimestamp?(this.previousEntryTimestamp++,n.setTime(this.previousEntryTimestamp)):this.previousEntryTimestamp=n.getTime();const r=J[e].toLowerCase(),i=Object.assign({timestamp:n,pubNubId:this.pubNubId,level:e,minimumLevel:this.minLogLevel,location:t},typeof s=="function"?s():{messageType:"text",message:s});this.loggers.forEach((o=>o[r](i)))}}var pt={exports:{}};(function(a,e){(function(t){var s="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 o,c,u="";for(o=0;o<32;o++)c=16*Math.random()|0,o!==8&&o!==12&&o!==16&&o!==20||(u+="-"),u+=(o===12?4:o===16?3&c|8:c).toString(16);return u}function i(o,c){var u=n[c||"all"];return u&&u.test(o)||!1}r.isUUID=i,r.VERSION=s,t.uuid=r,t.isUUID=i})(e),a!==null&&(a.exports=e.uuid)})(pt,pt.exports);var gt=De(pt.exports),xe={createUUID:()=>gt.uuid?gt.uuid():gt()};const ks=(a,e)=>{var t,s,n,r;!a.retryConfiguration&&a.enableEventEngine&&(a.retryConfiguration=Ye.ExponentialRetryPolicy({minimumDelay:2,maximumDelay:150,maximumRetry:6,excluded:[B.MessageSend,B.Presence,B.Files,B.MessageStorage,B.ChannelGroups,B.DevicePushNotifications,B.AppContext,B.MessageReactions]}));const i=`pn-${xe.createUUID()}`;a.logVerbosity?a.logLevel=J.Debug:a.logLevel===void 0&&(a.logLevel=J.None);const o=new js(Ps(i),a.logLevel,[...(t=a.loggers)!==null&&t!==void 0?t:[],new $e]);a.logVerbosity!==void 0&&o.warn("Configuration","'logVerbosity' is deprecated. Use 'logLevel' instead."),(s=a.retryConfiguration)===null||s===void 0||s.validate();const c=a.useRandomIVs;(n=a.useRandomIVs)!==null&&n!==void 0||(a.useRandomIVs=!0),c!==void 0&&(o.warn("Configuration","'useRandomIVs' is deprecated. Pass it to 'cryptoModule' instead."),c===!1&&o.warn("Configuration",`Setting 'useRandomIVs' to false is insecure and should only be used to support legacy clients. 33 Do not disable random IVs in new applications.`)),a.origin=ws((r=a.ssl)!==null&&r!==void 0&&r,a.origin);const u=a.cryptoModule;u&&delete a.cryptoModule;const d=Object.assign(Object.assign({},a),{_pnsdkSuffix:{},_loggerManager:o,_instanceId:i,_cryptoModule:void 0,_cipherKey:void 0,_setupCryptoModule:e,get instanceId(){if(a.useInstanceId)return this._instanceId},getInstanceId(){if(a.useInstanceId)return this._instanceId},getUserId(){return this.userId},setUserId(l){if(!l||typeof l!="string"||l.trim().length===0)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this.userId=l},logger(){return this._loggerManager},getAuthKey(){return this.authKey},setAuthKey(l){this.authKey=l},getFilterExpression(){return this.filterExpression},setFilterExpression(l){this.filterExpression=l},getCipherKey(){return this._cipherKey},setCipherKey(l){this._cipherKey=l,l||!this._cryptoModule?l&&this._setupCryptoModule&&(this._cryptoModule=this._setupCryptoModule({cipherKey:l,useRandomIVs:a.useRandomIVs,customEncrypt:this.getCustomEncrypt(),customDecrypt:this.getCustomDecrypt(),logger:this.logger()})):this._cryptoModule=void 0},getCryptoModule(){return this._cryptoModule},getUseRandomIVs:()=>a.useRandomIVs,isSharedWorkerEnabled:()=>a.sdkFamily==="Web"&&a.subscriptionWorkerUrl,getKeepPresenceChannelsInPresenceRequests:()=>a.sdkFamily==="Web"&&a.subscriptionWorkerUrl,setPresenceTimeout(l){this.heartbeatInterval=l/2-1,this.presenceTimeout=l},getPresenceTimeout(){return this.presenceTimeout},getHeartbeatInterval(){return this.heartbeatInterval},setHeartbeatInterval(l){this.heartbeatInterval=l},getTransactionTimeout(){return this.transactionalRequestTimeout},getSubscribeTimeout(){return this.subscribeRequestTimeout},getFileTimeout(){return this.fileRequestTimeout},get PubNubFile(){return a.PubNubFile},get version(){return"13.0.1"},getVersion(){return this.version},_addPnsdkSuffix(l,h){this._pnsdkSuffix[l]=`${h}`},_getPnsdkSuffix(l){const h=Object.values(this._pnsdkSuffix).join(l);return h.length>0?l+h:""},getUUID(){return this.getUserId()},setUUID(l){this.setUserId(l)},getCustomEncrypt:()=>a.customEncrypt,getCustomDecrypt:()=>a.customDecrypt});return a.cipherKey?(o.warn("Configuration","'cipherKey' is deprecated. Use 'cryptoModule' instead."),d.setCipherKey(a.cipherKey)):u&&(d._cryptoModule=u),d},ws=(a,e)=>{const t=a?"https://":"http://";return typeof e=="string"?`${t}${e}
33`:`${t}${e[Math.floor(Math.random()*e.length)]}`},Ps=a=>{let e=2166136261;for(let t=0;t<a.length;t++)e^=a.charCodeAt(t),e=e+((e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24))>>>0;return e.toString(16).padStart(8,"0")};class Cs{constructor(e){this.cbor=e}setToken(e){e&&e.length>0?this.token=e:this.token=void 0}getToken(){return this.token}parseToken(e){var t,s;const n=this.cbor.decodeToken(e);if(n!==void 0){const r=n.res.uuid?Object.keys(n.res.uuid):[],i=n.res.usr?Object.keys(n.res.usr):[],o=Object.keys(n.res.chan),c=Object.keys(n.res.grp),u=n.pat.uuid?Object.keys(n.pat.uuid):[],d=n.pat.usr?Object.keys(n.pat.usr):[],l=Object.keys(n.pat.chan),h=Object.keys(n.pat.grp),y={version:n.v,timestamp:n.t,ttl:n.ttl,authorized_uuid:n.uuid,signature:n.sig},p=r.length>0,b=i.length>0,m=o.length>0,v=c.length>0;if(p||b||m||v){if(y.resources={},p){const S=y.resources.uuids={};r.forEach((O=>S[O]=this.extractPermissions(n.res.uuid[O])))}if(b){const S=y.resources.users={};i.forEach((O=>S[O]=this.extractCrudPermissions(n.res.usr[O])))}if(m){const S=y.resources.channels={};o.forEach((O=>S[O]=this.extractPermissions(n.res.chan[O])))}if(v){const S=y.resources.groups={};c.forEach((O=>S[O]=this.extractPermissions(n.res.grp[O])))}}const _=this.extractDataSyncScopes(n.res);_&&(((t=y.resources)!==null&&t!==void 0?t:y.resources={}).dataSync=_);const D=u.length>0,R=d.length>0,C=l.length>0,T=h.length>0;if(D||R||C||T){if(y.patterns={},D){const S=y.patterns.uuids={};u.forEach((O=>S[O]=this.extractPermissions(n.pat.uuid[O])))}if(R){const S=y.patterns.users={};d.forEach((O=>S[O]=this.extractCrudPermissions(n.pat.usr[O])))}if(C){const S=y.patterns.channels={};l.forEach((O=>S[O]=this.extractPermissions(n.pat.chan[O])))}if(T){const S=y.patterns.groups={};h.forEach((O=>S[O]=this.extractPermissions(n.pat.grp[O])))}}const f=this.extractDataSyncScopes(n.pat);return f&&(((s=y.patterns)!==null&&s!==void 0?s:y.patterns={}).dataSync=f),n.meta&&Object.keys(n.meta).length>0&&(y.meta=n.meta),y}}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}extractDataSyncScopes(e){let t;return[["entities","datasync:entities"],["relationships","datasync:relationships"],["memberships","datasync:memberships"]].forEach((([s,n])=>{const r=e[n];if(!r)return;const i=Object.keys(r);if(i.length===0)return;const o=(t??(t={}))[s]={};i.forEach((c=>o[c]=this.extractCrudPermissions(r[c])))})),t}extractCrudPermissions(e){return{create:!(16&~e),get:!(32&~e),update:!(64&~e),delete:!(8&~e)}}}var U;(function(a){a.GET="GET",a.POST="POST",a.PATCH="PATCH",a.PUT="PUT",a.DELETE="DELETE",a.LOCAL="LOCAL"})(U||(U={}));class Ze{constructor(e,t,s,n){this.publishKey=e,this.secretKey=t,this.hasher=s,this.logger=n}signature(e){const t=e.path.startsWith("/publish")?U.GET:e.method;let s=`${t} 34${this.publishKey} 35${e.path} 36${this.queryParameters(e.queryParameters)} 37`;if(t===U.POST||t===U.PATCH||t===U.PUT){const n=e.body;let r;n&&n instanceof ArrayBuffer?r=Ze.textDecoder.decode(n):n&&typeof n!="object"&&(r=n),r&&(s+=r)}return this.logger.trace("RequestSignature",(()=>({messageType:"text",message:`Request signature input: 38${s}`}))),`v2.${this.hasher(s,this.secretKey)}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}queryParameters(e){return Object.keys(e).sort().map((t=>{const s=e[t];return Array.isArray(s)?s.sort().map((n=>`${t}=${I(n)}`)).join("&"):`${t}=${I(s)}`})).join("&")}}Ze.textDecoder=new TextDecoder("utf-8");class Ns{constructor(e){this.configuration=e;const{clientConfiguration:{keySet:t},shaHMAC:s}=e;t.secretKey&&s&&(this.signatureGenerator=new Ze(t.publishKey,t.secretKey,s,this.logger))}get logger(){return this.configuration.clientConfiguration.logger()}makeSendable(e){const t=this.configuration.clientConfiguration.retryConfiguration,s=this.configuration.transport;if(t!==void 0){let n,r,i=!1,o=0;const c={abort:u=>{i=!0,n&&clearTimeout(n),r&&r.abort(u)}};return[new Promise(((u,d)=>{const l=()=>{if(i)return;const[h,y]=s.makeSendable(this.request(e));r=y;const p=(b,m)=>{let v=-1;t.shouldRetry(e,b,m?.category,o+1,m?.statusCode)&&(v=t.getDelay(o,b)),v>0?(o++,this.logger.warn("PubNubMiddleware",`HTTP request retry #${o} in ${v}ms.`),n=setTimeout((()=>l()),v)):b?u(b):m&&d(m)};h.then((b=>p(b))).catch((b=>p(void 0,b)))};l()}
38)),r?c:void 0]}return s.makeSendable(this.request(e))}request(e){var t;const{clientConfiguration:s}=this.configuration;return(e=this.configuration.transport.request(e)).queryParameters||(e.queryParameters={}),s.useInstanceId&&(e.queryParameters.instanceid=s.getInstanceId()),e.queryParameters.uuid||(e.queryParameters.uuid=s.userId),s.useRequestId&&(e.queryParameters.requestid=e.identifier),e.queryParameters.pnsdk=this.generatePNSDK(),(t=e.origin)!==null&&t!==void 0||(e.origin=s.origin),this.authenticateRequest(e),this.signRequest(e),e}authenticateRequest(e){var t;if(e.path.startsWith("/v2/auth/")||e.path.startsWith("/v3/pam/")||e.path.startsWith("/time"))return;const{clientConfiguration:s,tokenManager:n}=this.configuration,r=(t=n&&n.getToken())!==null&&t!==void 0?t:s.authKey;r&&(e.queryParameters.auth=r)}signRequest(e){this.signatureGenerator&&!e.path.startsWith("/time")&&(e.queryParameters.timestamp=String(Math.floor(new Date().getTime()/1e3)),e.queryParameters.signature=this.signatureGenerator.signature(e))}generatePNSDK(){const{clientConfiguration:e}=this.configuration;if(e.sdkName)return e.sdkName;let t=`PubNub-JS-${e.sdkFamily}`;e.partnerId&&(t+=`-${e.partnerId}`),t+=`/${e.getVersion()}`;const s=e._getPnsdkSuffix(" ");return s.length>0&&(t+=s),t}}class me{constructor(e,t="fetch"){this.logger=e,this.transport=t,e.debug("WebTransport",`Create with configuration: 39 - transport: ${t}`),t==="fetch"&&typeof fetch>"u"&&(e.warn("WebTransport",`'${t}' not supported in this browser. Fallback to the 'xhr' transport.`),this.transport="xhr"),this.transport==="fetch"&&(me.originalFetch=me.getOriginalFetch(),this.isFetchMonkeyPatched()&&e.warn("WebTransport","Native Web Fetch API 'fetch' function monkey patched."))}makeSendable(e){const t=new AbortController,s={abortController:t,abort:n=>{t.signal.aborted||(this.logger.trace("WebTransport",`On-demand request aborting: ${n}`),t.abort(n))}};return[this.webTransportRequestFromTransportRequest(e).then((n=>(this.logger.debug("WebTransport",(()=>({messageType:"network-request",message:e}))),this.sendRequest(n,s).then((r=>r.arrayBuffer().then((i=>[r,i])))).then((r=>{const i=r[1].byteLength>0?r[1]:void 0,{status:o,headers:c}=r[0],u={};
39c.forEach(((l,h)=>u[h]=l.toLowerCase()));const d={status:o,url:n.url,headers:u,body:i};if(this.logger.debug("WebTransport",(()=>({messageType:"network-response",message:d}))),o>=400)throw q.create(d);return d})).catch((r=>{const i=(typeof r=="string"?r:r.message).toLowerCase();let o=typeof r=="string"?new Error(r):r;throw i.includes("timeout")?this.logger.warn("WebTransport",(()=>({messageType:"network-request",message:e,details:"Timeout",canceled:!0}))):i.includes("cancel")||i.includes("abort")?(this.logger.debug("WebTransport",(()=>({messageType:"network-request",message:e,details:"Aborted",canceled:!0}))),o=new Error("Aborted"),o.name="AbortError"):i.includes("network")?this.logger.warn("WebTransport",(()=>({messageType:"network-request",message:e,details:"Network error",failed:!0}))):this.logger.warn("WebTransport",(()=>({messageType:"network-request",message:e,details:q.create(o).message,failed:!0}))),q.create(o)}))))),s]}request(e){return e}sendRequest(e,t){return g(this,void 0,void 0,(function*(){return this.transport==="fetch"?this.sendFetchRequest(e,t):this.sendXHRRequest(e,t)}))}sendFetchRequest(e,t){return g(this,void 0,void 0,(function*(){let s;const n=new Promise(((i,o)=>{s=setTimeout((()=>{clearTimeout(s),o(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([me.originalFetch(r,{signal:t.abortController.signal,credentials:"omit",cache:"no-cache"}).then((i=>(s&&clearTimeout(s),i))),n])}))}sendXHRRequest(e,t){return g(this,void 0,void 0,(function*(){return new Promise(((s,n)=>{var r;const i=new XMLHttpRequest;i.open(e.method,e.url,!0);let o=!1;i.responseType="arraybuffer",i.timeout=1e3*e.timeout,t.abortController.signal.onabort=()=>{i.readyState!=XMLHttpRequest.DONE&&i.readyState!=XMLHttpRequest.UNSENT&&(o=!0,i.abort())},Object.entries((r=e.headers)!==null&&r!==void 0?r:{}).forEach((([c,u])=>i.setRequestHeader(c,u))),i.onabort=()=>{n(new Error("Aborted"))},i.ontimeout=()=>{n(new Error("Request timeout"))},i.onerror=()=>{if(!o){const c=this.transportResponseFromXHR(e.url,i);n(new Error(q.create(c).message))}},i.onload=()=>{const c=new Headers;i.getAllResponseHeaders().split(`\r 40`).forEach((u=>{const[d,l]=u.split(": ");d.length>1&&l.length>1&&c.append(d,l)})),s(new Response(i.response,{status:i.status,headers:c,statusText:i.statusText}))},i.send(e.body)}))}))}webTransportRequestFromTransportRequest(e){return g(this,void 0,void 0,(function*(){let t,s=e.path;if(e.formData&&e.formData.length>0){e.queryParameters={};const n=e.body,r=new FormData;for(const{key:i,value:o}of e.formData)r.append(i,o);try{const i=yield n.toArrayBuffer();r.append("file",new Blob([i],{type:"application/octet-stream"}),n.name)}catch(i){this.logger.warn("WebTransport",(()=>({messageType:"error",message:i})));try{const o=yield n.toFileUri();r.append("file",o,n.name)}catch(o){this.logger.error("WebTransport",(()=>({messageType:"error",message:o})))}}t=r}else if(e.body&&(typeof e.body=="string"||e.body instanceof ArrayBuffer))if(e.compressible&&typeof CompressionStream<"u"){const n=typeof e.body=="string"?me.encoder.encode(e.body):e.body,r=n.byteLength,i=new ReadableStream({start(o){o.enqueue(n),o.close()}});t=yield new Response(i.pipeThrough(new CompressionStream("deflate"))).arrayBuffer(),this.logger.trace("WebTransport",(()=>{const o=t.byteLength,c=(o/r).toFixed(2);return{messageType:"text",message:`Body of ${r} bytes, compressed by ${c}x to ${o} bytes.`}}))}else t=e.body;return e.queryParameters&&Object.keys(e.queryParameters).length!==0&&(s=`${s}?${Gt(e.queryParameters)}`),{url:`${e.origin}${s}`,method:e.method,headers:e.headers,timeout:e.timeout,body:t}}))}isFetchMonkeyPatched(e){return!(e??fetch).toString().includes("[native code]")&&fetch.name!=="fetch"}transportResponseFromXHR(e,t){const s=t.getAllResponseHeaders().split(` 41`),n={};for(const r of s){const[i,o]=r.trim().split(":");i&&o&&(n[i.toLowerCase()]=o.trim())}return{status:t.status,url:e,headers:n,body:t.response}}static getOriginalFetch(){if(typeof document>"u"||!document.body)return fetch.bind(globalThis);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.bind(globalThis)}}me.encoder=new TextEncoder,me.decoder=new TextDecoder;class E{constructor(e){this.params=e,this.requestIdentifier=xe.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 g(this,void 0,void 0,(function*(){return this.deserializeResponse(e)}))}request(){var e,t,s,n,r,i;const o={method:(t=(e=this.params)===null||e===void 0?void 0:e.method)!==null&&t!==void 0?t:U.GET,path:this.path,queryParameters:this.queryParameters,cancellable:(n=(s=this.params)===null||s===void 0?void 0:s.cancellable)!==null&&n!==void 0&&n,compressible:(i=(r=this.params)===null||r===void 0?void 0:r.compressible)!==null&&i!==void 0&&i,timeout:10,identifier:this.requestIdentifier},c=this.headers;if(c&&(o.headers=c),o.method===U.POST||o.method===U.PATCH||o.method===U.PUT){const[u,d]=[this.body,this.formData];d&&(o.formData=d),u&&(o.body=u)}return o}get headers(){var e,t;return Object.assign({"Accept-Encoding":"gzip, deflate"},(t=(e=this.params)===null||e===void 0?void 0:e.compressible)!==null&&t!==void 0&&t?{"Content-Encoding":"deflate"}:{})}get path(){throw Error("`path` getter should be implemented by subclass.")}get queryParameters(){return{}}get formData(){}get body(){}deserializeResponse(e){const t=E.decoder.decode(e.body),s=e.headers["content-type"];let n;if(!s||s.indexOf("javascript")===-1&&s.indexOf("json")===-1)throw new G("Service response error, check status for details",ut(t,e.
41status));try{n=JSON.parse(t)}catch(r){throw console.error("Error parsing JSON response:",r),new G("Service response error, check status for details",ut(t,e.status))}if("status"in n&&typeof n.status=="number"&&n.status>=400)throw q.create(e);return n}}E.decoder=new TextDecoder;var x;(function(a){a[a.Presence=-2]="Presence",a[a.Message=-1]="Message",a[a.Signal=1]="Signal",a[a.AppContext=2]="AppContext",a[a.MessageAction=3]="MessageAction",a[a.Files=4]="Files",a[a.DataSync=5]="DataSync"})(x||(x={}));const Es=new Set([x.Presence,x.Message,x.Signal,x.AppContext,x.MessageAction,x.Files,x.DataSync]),Ts={user:"user",channel:"channel",membership:"membership"};class bt extends E{constructor(e){var t,s,n,r,i,o;super({cancellable:!0}),this.parameters=e,(t=(r=this.parameters).withPresence)!==null&&t!==void 0||(r.withPresence=!1),(s=(i=this.parameters).channelGroups)!==null&&s!==void 0||(i.channelGroups=[]),(n=(o=this.parameters).channels)!==null&&n!==void 0||(o.channels=[])}operation(){return j.PNSubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;return e?t||s?void 0:"`channels` and `channelGroups` both should not be empty":"Missing Subscribe Key"}parse(e){return g(this,void 0,void 0,(function*(){let t,s;try{s=E.decoder.decode(e.body),t=JSON.parse(s)}catch(r){console.error("Error parsing JSON response:",r)}if(!t)throw new G("Service response error, check status for details",ut(s,e.status));const n=t.m.filter((r=>{const i=r.b===void 0?r.c:r.b;return this.parameters.channels&&this.parameters.channels.includes(i)||this.parameters.channelGroups&&this.parameters.channelGroups.includes(i)})).map((r=>{let{e:i}=r;if(r.c.endsWith("-pnpres")?i=x.Presence:i!=null||(i=x.Message),!Es.has(i))return;const o=ht(r.d);if(i!=x.Presence&&i!=x.Signal&&typeof r.d=="string")return i==x.Message?{type:x.Message,data:this.messageFromEnvelope(r),pn_mfp:o}:{type:x.Files,data:this.fileFromEnvelope(r),pn_mfp:o};if(i==x.Message)return{type:x.Message,data:this.messageFromEnvelope(r),pn_mfp:o};if(i===x.Presence)return{type:x.Presence,data:this.presenceEventFromEnvelope(r),pn_mfp:o};if(i==x.Signal)return{type:x.Signal,data:this.signalFromEnvelope(r),pn_mfp:o};if(i===x.AppContext)return{type:x.AppContext,data:this.appContextFromEnvelope(r),pn_mfp:o};if(i===x.MessageAction)return{type:x.MessageAction,data:this.messageActionFromEnvelope(r),pn_mfp:o};if(i===x.DataSync){const c=this.dataSyncFromEnvelope(r);return c?{type:x.DataSync,data:c,pn_mfp:o}:{type:x.Message,data:this.messageFromEnvelope(r),pn_mfp:o}}return{type:x.Files,data:this.fileFromEnvelope(r),pn_mfp:o}})).filter((r=>r!==void 0));return{cursor:{timetoken:t.t.t,region:t.t.r},messages:n}}))}get headers(){var e;return Object.assign(Object.assign({},(e=super.headers)!==null&&e!==void 0?e:{}),{accept:"text/javascript"})}presenceEventFromEnvelope(e){var t;const{d:s}=e,[n,r]=this.subscriptionChannelFromEnvelope(e),i=n.replace("-pnpres",""),o=r!==null?i:null,c=r!==null?r:i;let u;if(typeof s=="string")try{const d=JSON.parse(s);d===null||typeof d!="object"||Array.isArray(d)||(u=d)}catch{}else u=s;return u&&("data"in u?(u.state=u.data,delete u.data):"action"in u&&u.action==="interval"&&(u.hereNowRefresh=(t=u.here_now_refresh)!==null&&t!==void 0&&t,delete u.here_now_refresh)),Object.assign({channel:i,subscription:r,actualChannel:o,subscribedChannel:c,timetoken:e.p.t},u??{})}messageFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d),i={channel:t,subscription:s,actualChannel:s!==null?t:null,subscribedChannel:s!==null?s:t,timetoken:e.p.t,publisher:e.i,message:n};return e.u&&(i.userMetadata=e.u),e.cmt&&(i.customMessageType=e.cmt),r&&(i.error=r),i}signalFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,message:e.d};return e.u&&(n.userMetadata=e.u),e.cmt&&(n.customMessageType=e.cmt),n}messageActionFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,event:n.event,data:Object.assign(Object.assign({},n.data),{uuid:e.i})}}appContextFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,message:n}}dataSyncFromEnvelope(e){var t;const[s,n]=this.subscriptionChannelFromEnvelope(e),r=e.d,i=r?.metadata;if(!i||i.source!=="data-sync"||!i.event||!i.type)return;const o=i.className?i.className.split(":"):[],c=o.filter((_=>_.length>0)),u=c.length>0?c[c.length-1]:void 0,d=i.classLevel,l=d===void 0?o[0]:d==="Global"?u:void 0,h=(i.type==="entity"||i.type==="relationship")&&l&&Ts[l.toLowerCase()]||i.type,y=i.classVersion!==void 0?Number.parseInt(`${i.classVersion}`,10):NaN,p=Number.isNaN(y)?void 0:y,b=(t=r.data)!==null&&t!==void 0?t:{}
41,m={version:r.version,source:i.source,type:i.type,className:u,classLevel:d,classVersion:p};let v;return v=i.event==="delete"?Object.assign(Object.assign({},m),{event:i.event,objectType:h,data:{id:b.id,deletedAt:b.deletedAt}}):Object.assign(Object.assign({},m),{event:i.event,objectType:h,data:Object.assign({},b)}),{channel:s,subscription:n,timetoken:e.p.t,message:v}}fileFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d);let i=r;const o={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i};return e.u&&(o.userMetadata=e.u),n?typeof n=="string"?i!=null||(i="Unexpected file information payload data type."):(o.message=n.message,n.file&&(o.file={id:n.file.id,name:n.file.name,url:this.parameters.getFileUrl({id:n.file.id,name:n.file.name,channel:t})})):i!=null||(i="File information payload is missing."),e.cmt&&(o.customMessageType=e.cmt),i&&(o.error=i),o}subscriptionChannelFromEnvelope(e){return[e.c,e.b===void 0?e.c:e.b]}decryptedData(e){if(!this.parameters.crypto||typeof e!="string")return[e,void 0];let t,s;try{const n=this.parameters.crypto.decrypt(e);t=n instanceof ArrayBuffer?JSON.parse(zt.decoder.decode(n)):n}catch(n){t=null,s=`Error while decrypting message content: ${n.message}`}return[t??e,s]}}class zt extends bt{get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/subscribe/${t}/${le((e=s?.sort())!==null&&e!==void 0?e:[],",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,heartbeat:s,state:n,timetoken:r,region:i,onDemand:o}=this.parameters,c={};return o&&(c["on-demand"]=1),e&&e.length>0&&(c["channel-group"]=e.sort().join(",")),t&&t.length>0&&(c["filter-expr"]=t),s&&(c.heartbeat=s),n&&Object.keys(n).length>0&&(c.state=JSON.stringify(n)),r!==void 0&&typeof r=="string"?r.length>0&&r!=="0"&&(c.tt=r):r!==void 0&&r>0&&(c.tt=r),i&&(c.tr=i),c}}class Jt{constructor(){this.hasListeners=!1,this.listeners=[{count:-1,listener:{}}]}set onStatus(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"status"})}set onMessage(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"message"})}set onPresence(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"presence"})}set onSignal(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"signal"})}set onObjects(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"objects"})}set onMessageAction(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"messageAction"})}set onFile(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"file"})}set onDataSync(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"dataSync"})}handleEvent(e){if(this.hasListeners)if(e.type===x.Message)this.announce("message",e.data);else if(e.type===x.Signal)this.announce("signal",e.data);else if(e.type===x.Presence)this.announce("presence",e.data);else if(e.type===x.AppContext){const{data:t}=e,{message:s}=t;if(this.announce("objects",t),s.type==="uuid"){const{message:n,channel:r}=t,i=Z(t,["message","channel"]),{event:o,type:c}=s,u=Z(s,["event","type"]),d=Object.assign(Object.assign({},i),{spaceId:r,message:Object.assign(Object.assign({},u),{event:o==="set"?"updated":"removed",type:"user"})});this.announce("user",d)}else if(s.type==="channel"){const{message:n,channel:r}=t,i=Z(t,["message","channel"]),{event:o,type:c}=s,u=Z(s,["event","type"]),d=Object.assign(Object.assign({},i),{spaceId:r,message:Object.assign(Object.assign({},u),{event:o==="set"?"updated":"removed",type:"space"})});this.announce("space",d)}else if(s.type==="membership"){const{message:n,channel:r}=t,i=Z(t,["message","channel"]),{event:o,data:c}=s,u=Z(s,["event","data"]),{uuid:d,channel:l}=c,h=Z(c,["uuid","channel"]),y=Object.assign(Object.assign({},i),{spaceId:r,message:Object.assign(Object.assign({},u),{event:o==="set"?"updated":"removed",data:Object.assign(Object.assign({},h),{user:d,space:l})})});this.announce("membership",y)}}else e.type===x.MessageAction?this.announce("messageAction",e.data):e.type===x.Files?this.announce("file",e.data):e.type===x.DataSync&&this.announce("dataSync",e.data)}handleStatus(e){this.hasListeners&&this.announce("status",e)}addListener(e){this.updateTypeOrObjectListener({add:!0,listener:e})}removeListener(e){this.updateTypeOrObjectListener({add:!1,listener:e})}removeAllListeners(){this.listeners=[{count:-1,listener:{}}],this.hasListeners=!1}updateTypeOrObjectListener(e){if(e.type)typeof e.listener=="function"?this.listeners[0].listener[e.type]=e.listener:delete this.listeners[0].listener[e.type];else if(e.listener&&typeof e.listener!="function"){let t,s=!1;for(t of this.listeners)if(t.listener===e.listener){e.add?(t.count++,s=!0):(t.count--,t.count===0&&this.listeners.splice(this.listeners.indexOf(t),1));break}e.add&&!s&&this.listeners.push({count:1,listener:e.listener})}this.hasListeners=this.listeners.length>1||Object.keys(this.listeners[0]).length>0}
41announce(e,t){this.listeners.forEach((({listener:s})=>{const n=s[e];n&&n(t)}))}}class _s{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 Is{constructor(e){this.config=e,e.logger().debug("DedupingManager",(()=>({messageType:"object",message:{maximumCacheSize:e.maximumCacheSize},details:"Create with configuration:"}))),this.maximumCacheSize=e.maximumCacheSize,this.hashHistory=[]}getKey(e){var t;return`${e.timetoken}-${this.hashCode(JSON.stringify((t=e.message)!==null&&t!==void 0?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(e.length===0)return t;for(let s=0;s<e.length;s+=1)t=(t<<5)-t+e.charCodeAt(s),t|=0;return t}}class Ms{constructor(e,t,s,n,r,i,o){this.configuration=e,this.emitEvent=t,this.emitStatus=s,this.subscribeCall=n,this.heartbeatCall=r,this.leaveCall=i,this.disconnectedWhileHandledEvent=!1,e.logger().trace("SubscriptionManager","Create manager."),this.reconnectionManager=new _s(o),this.dedupingManager=new Is(this.configuration),this.heartbeatChannelGroups={},this.heartbeatChannels={},this.presenceChannelGroups={},this.presenceChannels={},this.heartbeatTimer=null,this.presenceState={},this.pendingChannelGroupSubscriptions=new Set,this.pendingChannelSubscriptions=new Set,this.channelGroups={},this.channels={},this.currentTimetoken="0",this.lastTimetoken="0",this.storedTimetoken=null,this.referenceTimetoken=null,this.subscriptionStatusAnnounced=!1,this.isOnline=!0}get subscriptionTimetoken(){var e;return Kt(this.currentTimetoken,(e=this.referenceTimetoken)!==null&&e!==void 0?e:"0")}get subscribedChannels(){return Object.keys(this.channels)}get subscribedChannelGroups(){return Object.keys(this.channelGroups)}get abort(){return this._subscribeAbort}set abort(e){this._subscribeAbort=e}disconnect(){this.disconnectedWhileHandledEvent=!0,this.stopSubscribeLoop(),this.stopHeartbeatTimer(),this.reconnectionManager.stopPolling()}reconnect(e=!1){this.startSubscribeLoop(e),e||this.configuration.useSmartHeartbeat||this.startHeartbeatTimer()}subscribe(e){const{channels:t,channelGroups:s,timetoken:n,withPresence:r=!1,withHeartbeats:i=!1}=e;n&&(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=`${n}`),this.currentTimetoken!=="0"&&(this.storedTimetoken=this.currentTimetoken,this.currentTimetoken="0"),t?.forEach((o=>{this.pendingChannelSubscriptions.add(o),this.channels[o]={},r&&(this.presenceChannels[o]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannels[o]={})})),s?.forEach((o=>{this.pendingChannelGroupSubscriptions.add(o),this.channelGroups[o]={},r&&(this.presenceChannelGroups[o]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannelGroups[o]={})})),this.subscriptionStatusAnnounced=!1,this.reconnect()}unsubscribe(e,t=!1){let{channels:s,channelGroups:n}=e;const r=new Set,i=new Set;if(s?.forEach((u=>{u in this.channels&&(delete this.channels[u],i.add(u),u in this.heartbeatChannels&&delete this.heartbeatChannels[u]),u in this.presenceState&&delete this.presenceState[u],u in this.presenceChannels&&(delete this.presenceChannels[u],i.add(u))})),n?.forEach((u=>{u in this.channelGroups&&(delete this.channelGroups[u],r.add(u),u in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[u]),u in this.presenceState&&delete this.presenceState[u],u in this.presenceChannelGroups&&(delete this.presenceChannelGroups[u],r.add(u))})),i.size===0&&r.size===0)return;const o=this.lastTimetoken,c=this.currentTimetoken;Object.keys(this.channels).length===0&&Object.keys(this.presenceChannels).length===0&&Object.keys(this.channelGroups).length===0&&Object.keys(this.presenceChannelGroups).length===0&&(this.lastTimetoken="0",this.currentTimetoken="0",this.referenceTimetoken=null,this.storedTimetoken=null,this.region=null,this.reconnectionManager.stopPolling()),this.reconnect(!0),this.configuration.suppressLeaveEvents!==!1||t||(n=Array.from(r),s=Array.from(i),this.leaveCall({channels:s,channelGroups:n},(u=>{const{error:d}=u,l=Z(u,["error"]);let h;d&&(u.errorData&&typeof u.errorData=="object"&&"message"in u.errorData&&typeof u.errorData.message=="string"?h=u.errorData.message:"message"in u&&typeof u.message=="string"&&(h=u.message)),this.emitStatus(Object.assign(Object.assign({},l),{error:h!=null&&h,affectedChannels:s,affectedChannelGroups:n,currentTimetoken:c,lastTimetoken:o}))})))}unsubscribeAll(e=!1){this.disconnectedWhileHandledEvent=!0,this.unsubscribe({channels:this.subscribedChannels,channelGroups:this.subscribedChannelGroups},e)}startSubscribeLoop(e=!1){this.disconnectedWhileHandledEvent=!1,this.stopSubscribeLoop();const t=[...Object.keys(this.channelGroups)],s=[...Object.keys(this.channels)];
41Object.keys(this.presenceChannelGroups).forEach((n=>t.push(`${n}-pnpres`))),Object.keys(this.presenceChannels).forEach((n=>s.push(`${n}-pnpres`))),s.length===0&&t.length===0||(this.subscribeCall(Object.assign(Object.assign(Object.assign({channels:s,channelGroups:t,state:this.presenceState,heartbeat:this.configuration.getPresenceTimeout(),timetoken:this.currentTimetoken},this.region!==null?{region:this.region}:{}),this.configuration.filterExpression?{filterExpression:this.configuration.filterExpression}:{}),{onDemand:!this.subscriptionStatusAnnounced||e}),((n,r)=>{this.processSubscribeResponse(n,r)})),!e&&this.configuration.useSmartHeartbeat&&this.startHeartbeatTimer())}stopSubscribeLoop(){this._subscribeAbort&&(this._subscribeAbort(),this._subscribeAbort=null)}processSubscribeResponse(e,t){if(e.error)return typeof e.errorData=="object"&&"name"in e.errorData&&e.errorData.name==="AbortError"||e.category===M.PNCancelledCategory?void 0:void(e.category===M.PNTimeoutCategory?this.startSubscribeLoop():e.category===M.PNNetworkIssuesCategory||e.category===M.PNMalformedResponseCategory?(this.disconnect(),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.emitStatus({category:M.PNNetworkDownCategory})),this.reconnectionManager.onReconnect((()=>{this.configuration.autoNetworkDetection&&!this.isOnline&&(this.isOnline=!0,this.emitStatus({category:M.PNNetworkUpCategory})),this.reconnect(),this.subscriptionStatusAnnounced=!0;const i={category:M.PNReconnectedCategory,operation:e.operation,lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.emitStatus(i)})),this.reconnectionManager.startPolling(),this.emitStatus(Object.assign(Object.assign({},e),{category:M.PNNetworkIssuesCategory}))):e.category===M.PNBadRequestCategory?(this.stopHeartbeatTimer(),this.emitStatus(e)):this.emitStatus(e));if(this.referenceTimetoken=Xe(t.cursor.timetoken,this.storedTimetoken),this.storedTimetoken?(this.currentTimetoken=this.storedTimetoken,this.storedTimetoken=null):(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=t.cursor.timetoken),!this.subscriptionStatusAnnounced){const i={category:M.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.emitStatus(i),this.pendingChannelGroupSubscriptions.clear(),this.pendingChannelSubscriptions.clear()}const{messages:s}=t,{requestMessageCountThreshold:n,dedupeOnSubscribe:r}=this.configuration;n&&s.length>=n&&this.emitStatus({category:M.PNRequestMessageCountExceededCategory,operation:e.operation});try{const i={timetoken:this.currentTimetoken,region:this.region?this.region:void 0};this.configuration.logger().debug("SubscriptionManager",(()=>({messageType:"object",message:s.map((o=>({type:o.type,data:Object.assign(Object.assign({},o.data),{pn_mfp:o.pn_mfp})}))),details:"Received events:"}))),s.forEach((o=>{if(r&&"message"in o.data&&"timetoken"in o.data){if(this.dedupingManager.isDuplicate(o.data))return void this.configuration.logger().warn("SubscriptionManager",(()=>({messageType:"object",message:o.data,details:"Duplicate message detected (skipped):"})));this.dedupingManager.addEntry(o.data)}this.emitEvent(i,o)}))}catch(i){const o={error:!0,category:M.PNUnknownCategory,errorData:i,statusCode:0};this.emitStatus(o)}this.region=t.cursor.region,this.disconnectedWhileHandledEvent?this.disconnectedWhileHandledEvent=!1:this.startSubscribeLoop()}setState(e){const{state:t,channels:s,channelGroups:n}=e;s?.forEach((r=>r in this.channels&&(this.presenceState[r]=t))),n?.forEach((r=>r in this.channelGroups&&(this.presenceState[r]=t)))}changePresence(e){const{connected:t,channels:s,channelGroups:n}=e;t?(s?.forEach((r=>this.heartbeatChannels[r]={})),n?.forEach((r=>this.heartbeatChannelGroups[r]={}))):(s?.forEach((r=>{r in this.heartbeatChannels&&delete this.heartbeatChannels[r]})),n?.forEach((r=>{r in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[r]})),this.configuration.suppressLeaveEvents===!1&&this.leaveCall({channels:s,channelGroups:n},(r=>this.emitStatus(r)))),this.reconnect()}startHeartbeatTimer(){this.stopHeartbeatTimer();const e=this.configuration.getHeartbeatInterval();e&&e!==0&&(this.configuration.useSmartHeartbeat||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);t.length===0&&e.length===0||this.heartbeatCall({channels:t,channelGroups:e,heartbeat:this.configuration.getPresenceTimeout(),state:this.presenceState},(s=>{s.error&&this.configuration.announceFailedHeartbeats&&this.emitStatus(s),s.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.disconnect(),this.emitStatus({category:M.PNNetworkDownCategory}),this.reconnect()),!s.error&&this.configuration.announceSuccessfulHeartbeats&&this.emitStatus(s)}))}}class Xt{constructor(e,t,s){this._payload=e,this.setDefaultPayloadStructure(),this.title=t,this.body=s}get payload(){return this._payload}set title(e){this._title=e}set subtitle(e){this._subtitle=e}set body(e){this._body=e}set badge(e){this._badge=e}set sound(e){this._sound=e}setDefaultPayloadStructure(){}toObject(){return{}}}class Rs extends Xt{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}
41set 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){e!=null&&(this.payload.aps.badge=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.aps.sound=e,this._sound=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.aps={alert:{}}}toObject(){const e=Object.assign({},this.payload),{aps:t}=e;let{alert:s}=t;if(this._isSilent&&(t["content-available"]=1),this._apnsPushType==="apns2"){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");const n=[];this._configurations.forEach((r=>{n.push(this.objectFromAPNS2Configuration(r))})),n.length&&(e.pn_push=n)}return s&&Object.keys(s).length||delete t.alert,this._isSilent&&(delete t.alert,delete t.badge,delete t.sound,s={}),this._isSilent||s&&Object.keys(s).length?e:null}objectFromAPNS2Configuration(e){if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");const{collapseId:t,expirationDate:s}=e,n={auth_method:"token",targets:e.targets.map((r=>this.objectFromAPNSTarget(r))),version:"v2"};return t&&t.length&&(n.collapse_id=t),s&&(n.expiration=s.toISOString()),n}objectFromAPNSTarget(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");const{topic:t,environment:s="development",excludedDevices:n=[]}=e,r={topic:t,environment:s};return n.length&&(r.excluded_devices=n),r}}class Ds extends Xt{get payload(){return this._payload}get notification(){return this.payload.notification}get data(){return this.payload.data}get androidNotification(){var e;return(e=this.payload.android)===null||e===void 0?void 0:e.notification}get title(){return this._title}set title(e){e&&e.length&&(this.payload.notification.title=e,this.androidNotification.title=e,this._title=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.notification.body=e,this.androidNotification.body=e,this._body=e)}get badge(){return this._badge}set badge(e){e!=null&&(this.androidNotification.notification_count=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.androidNotification.sound=e,this._sound=e)}get icon(){return this._icon}set icon(e){e&&e.length&&(this.androidNotification.icon=e,this._icon=e)}get tag(){return this._tag}set tag(e){e&&e.length&&(this.androidNotification.tag=e,this._tag=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.notification={},this.payload.data={},this.payload.android={notification:{}}}toObject(){var e,t;const s={},n=Object.assign({},this.payload.notification),r=Object.assign({},this.payload.android),i=Z(Object.assign({},(e=r.notification)!==null&&e!==void 0?e:{}),["title","body"]);if(this._isSilent){const c={};this._title&&(c.title=this._title),this._body&&(c.body=this._body);for(const[u,d]of Object.entries(i))d!=null&&(c[u]=String(d));this.payload.data&&Object.assign(c,this.payload.data),Object.keys(c).length&&(s.data=c),delete r.notification,Object.keys(r).length&&(s.android=r)}else if(Object.keys(n).length&&(s.notification=n),this.payload.data&&Object.keys(this.payload.data).length&&(s.data=Object.assign({},this.payload.data)),Object.keys(i).length){const c=Z(r,["notification"]);s.android=Object.assign(Object.assign({},c),{notification:i})}else{const c=Z(r,["notification"]);Object.keys(c).length&&(s.android=c)}const o=Z(this.payload,["notification","android","data","pn_exceptions"]);return Object.assign(s,o),!((t=this.payload.pn_exceptions)===null||t===void 0)&&t.length&&(s.pn_exceptions=this.payload.pn_exceptions),Object.keys(s).length?s:null}}class Us{constructor(e,t){this._payload={apns:{},fcm:{}},this._title=e,this._body=t,this.apns=new Rs(this._payload.apns,e,t),this.fcm=new Ds(this._payload.fcm,e,t)}set debugging(e){this._debugging=e}get title(){return this._title}get subtitle(){return this._subtitle}set subtitle(e){this._subtitle=e,this.apns.subtitle=e,this.fcm.subtitle=e}get body(){return this._body}get badge(){return this._badge}set badge(e){this._badge=e,this.apns.badge=e,this.fcm.badge=e}get sound(){return this._sound}set sound(e){this._sound=e,this.apns.sound=e,this.fcm.sound=e}buildPayload(e){const t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";const s=this.apns.toObject();s&&Object.keys(s).length&&(t.pn_apns=s)}if(e.includes("fcm")){const s=this.fcm.toObject();s&&Object.keys(s).length&&(t.pn_fcm=s)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t}}class Qt{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=()=>
41{this.listeners.forEach((s=>{s(e)}))};this.sync?t():setTimeout(t,0)}}class te{transition(e,t){var s;if(this.transitionMap.has(t.type))return(s=this.transitionMap.get(t.type))===null||s===void 0?void 0:s(e,t)}constructor(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}on(e,t){return this.transitionMap.set(e,t),this}with(e,t){return[this,e,t??[]]}onEnter(e){return this.enterEffects.push(e),this}onExit(e){return this.exitEffects.push(e),this}}class Yt extends Qt{constructor(e){super(!0),this.logger=e,this._pendingEvents=[],this._inTransition=!1}get currentState(){return this._currentState}get currentContext(){return this._currentContext}describe(e){return new te(e)}start(e,t){this._currentState=e,this._currentContext=t,this.notify({type:"engineStarted",state:e,context:t})}transition(e){if(!this._currentState)throw this.logger.error("Engine","Finite state machine is not started"),new Error("Start the engine first");if(this._inTransition)return this.logger.trace("Engine",(()=>({messageType:"object",message:e,details:"Event engine in transition. Enqueue received event:"}))),void this._pendingEvents.push(e);this._inTransition=!0,this.logger.trace("Engine",(()=>({messageType:"object",message:e,details:"Event engine received event:"}))),this.notify({type:"eventReceived",event:e});const t=this._currentState.transition(this._currentContext,e);if(t){const[s,n,r]=t;this.logger.trace("Engine",`Exiting state: ${this._currentState.label}`);for(const c of this._currentState.exitEffects)this.notify({type:"invocationDispatched",invocation:c(this._currentContext)});this.logger.trace("Engine",(()=>({messageType:"object",details:`Entering '${s.label}' state with context:`,message:n})));const i=this._currentState;this._currentState=s;const o=this._currentContext;this._currentContext=n,this.notify({type:"transitionDone",fromState:i,fromContext:o,toState:s,toContext:n,event:e});for(const c of r)this.notify({type:"invocationDispatched",invocation:c});for(const c of this._currentState.enterEffects)this.notify({type:"invocationDispatched",invocation:c(this._currentContext)})}else this.logger.warn("Engine",`No transition from '${this._currentState.label}' found for event: ${e.type}`);if(this._inTransition=!1,this._pendingEvents.length>0){const s=this._pendingEvents.shift();s&&(this.logger.trace("Engine",(()=>({messageType:"object",message:s,details:"De-queueing pending event:"}))),this.transition(s))}}}class Zt{constructor(e,t){this.dependencies=e,this.logger=t,this.instances=new Map,this.handlers=new Map}on(e,t){this.handlers.set(e,t)}dispatch(e){if(this.logger.trace("Dispatcher",`Process invocation: ${e.type}`),e.type==="CANCEL"){if(this.instances.has(e.payload)){const n=this.instances.get(e.payload);n?.cancel(),this.instances.delete(e.payload)}return}const t=this.handlers.get(e.type);if(!t)throw this.logger.error("Dispatcher",`Unhandled invocation '${e.type}'`),new Error(`Unhandled invocation '${e.type}'`);const s=t(e.payload,this.dependencies);this.logger.trace("Dispatcher",(()=>({messageType:"object",details:"Call invocation handler with parameters:",message:e.payload,ignoredKeys:["abortSignal"]}))),e.managed&&this.instances.set(e.type,s),s.start()}dispose(){for(const[e,t]of this.instances.entries())t.cancel(),this.instances.delete(e)}}function z(a,e){const t=function(...s){return{type:a,payload:e?.(...s)}};return t.type=a,t}function et(a,e){const t=(...s)=>({type:a,payload:e(...s),managed:!1});return t.type=a,t}function tt(a,e){const t=(...s)=>({type:a,payload:e(...s),managed:!0});return t.type=a,t.cancel={type:"CANCEL",payload:a,managed:!1},t}class es extends Error{constructor(){super("The operation was aborted."),this.name="AbortError",Object.setPrototypeOf(this,new.target.prototype)}}class As extends Qt{constructor(){super(...arguments),this._aborted=!1}get aborted(){return this._aborted}throwIfAborted(){if(this._aborted)throw new es}abort(){this._aborted=!0,this.notify(new es)}}class $s{constructor(e,t){this.payload=e,this.dependencies=t}}class xs extends $s{constructor(e,t,s){super(e,t),this.asyncFunction=s,this.abort
41Signal=new As}start(){this.asyncFunction(this.payload,this.abortSignal,this.dependencies).catch((e=>{}))}cancel(){this.abortSignal.abort()}}const fe=a=>(e,t)=>new xs(e,t,a),yt=tt("HEARTBEAT",((a,e)=>({channels:a,groups:e}))),he=et("LEAVE",((a,e)=>({channels:a,groups:e}))),mt=et("EMIT_STATUS",(a=>a)),ft=tt("WAIT",(()=>({}))),vt=z("RECONNECT",(()=>({}))),st=z("DISCONNECT",((a=!1)=>({isOffline:a}))),Ce=z("JOINED",((a,e)=>({channels:a,groups:e}))),Fe=z("LEFT",((a,e)=>({channels:a,groups:e}))),qe=z("LEFT_ALL",((a=!1)=>({isOffline:a}))),ts=z("HEARTBEAT_SUCCESS",(a=>({statusCode:a}))),ss=z("HEARTBEAT_FAILURE",(a=>a)),ns=z("TIMES_UP",(()=>({})));class Fs extends Zt{constructor(e,t){super(t,t.config.logger()),this.on(yt.type,fe(((s,n,r)=>g(this,[s,n,r],void 0,(function*(i,o,{heartbeat:c,presenceState:u,config:d}){o.throwIfAborted();try{yield c(Object.assign(Object.assign({abortSignal:o,channels:i.channels,channelGroups:i.groups},d.maintainPresenceState&&{state:u}),{heartbeat:d.presenceTimeout})),e.transition(ts(200))}catch(l){if(l instanceof G){if(l.status&&l.status.category==M.PNCancelledCategory)return;e.transition(ss(l))}}}))))),this.on(he.type,fe(((s,n,r)=>g(this,[s,n,r],void 0,(function*(i,o,{leave:c,config:u}){if(!u.suppressLeaveEvents)try{c({channels:i.channels,channelGroups:i.groups})}catch{}}))))),this.on(ft.type,fe(((s,n,r)=>g(this,[s,n,r],void 0,(function*(i,o,{heartbeatDelay:c}){return o.throwIfAborted(),yield c(),o.throwIfAborted(),e.transition(ns())}))))),this.on(mt.type,fe(((s,n,r)=>g(this,[s,n,r],void 0,(function*(i,o,{emitStatus:c,config:u}){u.announceFailedHeartbeats&&i?.error===!0?c(Object.assign(Object.assign({},i),{operation:j.PNHeartbeatOperation})):u.announceSuccessfulHeartbeats&&i.statusCode===200&&c(Object.assign(Object.assign({},i),{error:!1,operation:j.PNHeartbeatOperation,category:M.PNAcknowledgmentCategory}))})))))}}const pe=new te("HEARTBEAT_STOPPED");pe.on(Ce.type,((a,e)=>pe.with({channels:[...a.channels,...e.payload.channels.filter((t=>!a.channels.includes(t)))],groups:[...a.groups,...e.payload.groups.filter((t=>!a.groups.includes(t)))]}))),pe.on(Fe.type,((a,e)=>pe.with({channels:a.channels.filter((t=>!e.payload.channels.includes(t))),groups:a.groups.filter((t=>!e.payload.groups.includes(t)))}))),pe.on(vt.type,((a,e)=>V.with({channels:a.channels,groups:a.groups}))),pe.on(qe.type,((a,e)=>Ee.with(void 0)));const ve=new te("HEARTBEAT_COOLDOWN");ve.onEnter((()=>ft())),ve.onExit((()=>ft.cancel)),ve.on(ns.type,((a,e)=>V.with({channels:a.channels,groups:a.groups}))),ve.on(Ce.type,((a,e)=>V.with({channels:[...a.channels,...e.payload.channels.filter((t=>!a.channels.includes(t)))],groups:[...a.groups,...e.payload.groups.filter((t=>!a.groups.includes(t)))]}))),ve.on(Fe.type,((a,e)=>V.with({channels:a.channels.filter((t=>!e.payload.channels.includes(t))),groups:a.groups.filter((t=>!e.payload.groups.includes(t)))},[he(e.payload.channels,e.payload.groups)]))),ve.on(st.type,((a,e)=>pe.with({channels:a.channels,groups:a.groups},[...e.payload.isOffline?[]:[he(a.channels,a.groups)]]))),ve.on(qe.type,((a,e)=>Ee.with(void 0,[...e.payload.isOffline?[]:[he(a.channels,a.groups)]])));const Ne=new te("HEARTBEAT_FAILED");Ne.on(Ce.type,((a,e)=>V.with({channels:[...a.channels,...e.payload.channels.filter((t=>!a.channels.includes(t)))],groups:[...a.groups,...e.payload.groups.filter((t=>!a.groups.includes(t)))]}))),Ne.on(Fe.type,((a,e)=>V.with({channels:a.channels.filter((t=>!e.payload.channels.includes(t))),groups:a.groups.filter((t=>!e.payload.groups.includes(t)))},[he(e.payload.channels,e.payload.groups)]))),Ne.on(vt.type,((a,e)=>V.with({channels:a.channels,groups:a.groups}))),Ne.on(st.type,((a,e)=>pe.with({channels:a.channels,groups:a.groups},[...e.payload.isOffline?[]:[he(a.channels,a.groups)]]))),Ne.on(qe.type,((a,e)=>Ee.with(void 0,[...e.payload.isOffline?[]:[he(a.channels,a.groups)]])));const V=new te("HEARTBEATING");V.onEnter((a=>yt(a.channels,a.groups))),V.onExit((()=>yt.cancel)),V.on(ts.type,((a,e)=>ve.with({channels:a.channels,groups:a.groups},[mt(Object.assign({},e.payload))]))),V.on(Ce.type,((a,e)=>V.with({channels:[...a.channels,...e.payload.channels.filter((t=>!a.channels.includes(t)))],groups:[...a.groups,...e.payload.groups.filter((t=>!a.groups.includes(t)))]}))),V.on(Fe.type,((a,e)=>V.with({channels:a.channels.filter((t=>!e.payload.channels.includes(t))),groups:a.groups.filter((t=>!e.payload.groups.includes(t)))},[he(e.payload.channels,e.payload.groups)]))),V.on(ss.type,((a,e)=>Ne.with(Object.assign({},a),[...e.payload.status?[mt(Object.assign({},e.payload.status))]:[]]))),V.on(st.type,((a,e)=>pe.with({channels:a.channels,groups:a.groups},[...e.payload.isOffline?[]:[he(a.channels,a.groups)]]))),V.on(qe.type,((a,e)=>Ee.with(void 0,[...e.payload.isOffline?[]:[he(a.channels,a.groups)]])));const Ee=new te("HEARTBEAT_INACTIVE");Ee.on(Ce.type,((a,e)=>V.with({channels:e.payload.channels,groups:e.payload.groups})));class qs{get _engine(){return this.engine}constructor(e){this.dependencies=e,this.channels=[],this.groups=[],this.engine=new Yt(e.config.logger()),this.dispatcher=new Fs(this.engine,e),e.config.logger().debug("PresenceEventEngine","Create presence event engine."),this._unsubscribeEngine=this.engine.subscribe((t=>{t.type==="invocationDispatched"&&this.dispatcher.dispatch(t.invocation)})),this.engine.start(Ee,void 0)}join({channels:e,groups:t}){this.channels=[...this.channels,...(e??[]).filter((s=>!this.channels.includes(s)))],this.groups=[...this.groups,...(t??[]).filter((s=>!this.groups.includes(s)))],this.channels.length===0&&this.groups.length===0||this.engine.transition(Ce(this.channels.slice(0),this.groups.slice(0)))}leave({channels:e,groups:t}){e&&(this.channels=this.channels.filter((s=>!e.includes(s)))),t&&(this.groups=this.groups.filter((s=>!t.includes(s)))),this.dependencies.presenceState&&(e?.forEach((s=>delete this.dependencies.presenceState[s])),t?.forEach((s=>delete this.dependencies.presenceState[s]))),this.engine.transition(Fe(e??[],t??[]))}leaveAll(e=!1){this.dependencies.presenceState&&(this.channels.forEac
41h((t=>delete this.dependencies.presenceState[t])),this.groups.forEach((t=>delete this.dependencies.presenceState[t]))),this.channels=[],this.groups=[],this.engine.transition(qe(e))}reconnect(){this.engine.transition(vt())}disconnect(e=!1){this.engine.transition(st(e))}dispose(){this.disconnect(!0),this._unsubscribeEngine(),this.dispatcher.dispose()}}const Ot=tt("HANDSHAKE",((a,e,t)=>({channels:a,groups:e,onDemand:t}))),St=tt("RECEIVE_MESSAGES",((a,e,t,s)=>({channels:a,groups:e,cursor:t,onDemand:s}))),rs=et("EMIT_MESSAGES",((a,e)=>({cursor:a,events:e}))),re=et("EMIT_STATUS",(a=>a)),de=z("SUBSCRIPTION_CHANGED",((a,e,t=!1)=>({channels:a,groups:e,isOffline:t}))),Oe=z("SUBSCRIPTION_RESTORED",((a,e,t,s)=>({channels:a,groups:e,cursor:{timetoken:t,region:s??0}}))),is=z("HANDSHAKE_SUCCESS",(a=>a)),as=z("HANDSHAKE_FAILURE",(a=>a)),os=z("RECEIVE_SUCCESS",((a,e)=>({cursor:a,events:e}))),cs=z("RECEIVE_FAILURE",(a=>a)),jt=z("DISCONNECT",((a=!1)=>({isOffline:a}))),Ge=z("RECONNECT",((a,e)=>({cursor:{timetoken:a??"",region:e??0}}))),Te=z("UNSUBSCRIBE_ALL",(()=>({}))),K=new te("UNSUBSCRIBED");K.on(de.type,((a,{payload:e})=>e.channels.length===0&&e.groups.length===0?K.with(void 0):W.with({channels:e.channels,groups:e.groups,onDemand:!0}))),K.on(Oe.type,((a,{payload:e})=>e.channels.length===0&&e.groups.length===0?K.with(void 0):W.with({channels:e.channels,groups:e.groups,cursor:{timetoken:`${e.cursor.timetoken}`,region:e.cursor.region},onDemand:!0})));const je=new te("HANDSHAKE_STOPPED");je.on(de.type,((a,{payload:e})=>e.channels.length===0&&e.groups.length===0?K.with(void 0):je.with({channels:e.channels,groups:e.groups,cursor:a.cursor}))),je.on(Ge.type,((a,{payload:e})=>W.with(Object.assign(Object.assign({},a),{cursor:e.cursor||a.cursor,onDemand:!0})))),je.on(Oe.type,((a,{payload:e})=>{var t;return e.channels.length===0&&e.groups.length===0?K.with(void 0):je.with({channels:e.channels,groups:e.groups,cursor:{timetoken:`${e.cursor.timetoken}`,region:e.cursor.region||((t=a.cursor)===null||t===void 0?void 0:t.region)||0}})})),je.on(Te.type,(a=>K.with()));const _e=new te("HANDSHAKE_FAILED");_e.on(de.type,((a,{payload:e})=>e.channels.length===0&&e.groups.length===0?K.with(void 0):W.with({channels:e.channels,groups:e.groups,cursor:a.cursor,onDemand:!0}))),_e.on(Ge.type,((a,{payload:e})=>W.with(Object.assign(Object.assign({},a),{cursor:e.cursor||a.cursor,onDemand:!0})))),_e.on(Oe.type,((a,{payload:e})=>{var t,s;return e.channels.length===0&&e.groups.length===0?K.with(void 0):W.with({channels:e.channels,groups:e.groups,cursor:{timetoken:`${e.cursor.timetoken}`,region:e.cursor.region?e.cursor.region:(s=(t=a?.cursor)===null||t===void 0?void 0:t.region)!==null&&s!==void 0?s:0},onDemand:!0})})),_e.on(Te.type,(a=>K.with()));const W=new te("HANDSHAKING");W.onEnter((a=>{var e;return Ot(a.channels,a.groups,(e=a.onDemand)!==null&&e!==void 0&&e)})),W.onExit((()=>Ot.cancel)),W.on(de.type,((a,{payload:e})=>e.channels.length===0&&e.groups.length===0?K.with(void 0):W.with({channels:e.channels,groups:e.groups,cursor:a.cursor,onDemand:!0}))),W.on(is.type,((a,{payload:e})=>{var t,s,n,r,i;return Y.with({channels:a.channels,groups:a.groups,cursor:{timetoken:!((t=a.cursor)===null||t===void 0)&&t.timetoken?(s=a.cursor)===null||s===void 0?void 0:s.timetoken:e.timetoken,region:e.region},referenceTimetoken:Xe(e.timetoken,(n=a.cursor)===null||n===void 0?void 0:n.timetoken)},[re({category:M.PNConnectedCategory,affectedChannels:a.channels.slice(0),affectedChannelGroups:a.groups.slice(0),operation:j.PNSubscribeOperation,currentTimetoken:!((r=a.cursor)===null||r===void 0)&&r.timetoken?(i=a.cursor)===null||i===void 0?void 0:i.timetoken:e.timetoken})])})),W.on(as.type,((a,e)=>{var t;return _e.with(Object.assign(Object.assign({},a),{reason:e.payload}),[re({category:M.PNConnectionErrorCategory,error:(t=e.payload.status)===null||t===void 0?void 0:t.category})])})),W.on(jt.type,((a,e)=>{var t;if(e.payload.isOffline){const s=q.create(new Error("Network connection error")).toPubNubError(j.PNSubscribeOperation);return _e.with(Object.assign(Object.assign({},a),{reason:s}),[re({category:M.PNConnectionErrorCategory,error:(t=s.status)===null||t===void 0?void 0:t.category})])}return je.with(Object.assign({},a))})),W.on(Oe.type,((a,{payload:e})=>{var t;return e.channels.length===0&&e.groups.length===0?K.with(void 0):W.with({channels:e.channels,groups:e.groups,cursor:{timetoken:`${e.cursor.timetoken}
41`,region:e.cursor.region||((t=a?.cursor)===null||t===void 0?void 0:t.region)||0},onDemand:!0})})),W.on(Te.type,(a=>K.with()));const ke=new te("RECEIVE_STOPPED");ke.on(de.type,((a,{payload:e})=>e.channels.length===0&&e.groups.length===0?K.with(void 0):ke.with({channels:e.channels,groups:e.groups,cursor:a.cursor}))),ke.on(Oe.type,((a,{payload:e})=>e.channels.length===0&&e.groups.length===0?K.with(void 0):ke.with({channels:e.channels,groups:e.groups,cursor:{timetoken:`${e.cursor.timetoken}`,region:e.cursor.region||a.cursor.region}}))),ke.on(Ge.type,((a,{payload:e})=>{var t;return W.with({channels:a.channels,groups:a.groups,cursor:{timetoken:e.cursor.timetoken?(t=e.cursor)===null||t===void 0?void 0:t.timetoken:a.cursor.timetoken,region:e.cursor.region||a.cursor.region},onDemand:!0})})),ke.on(Te.type,(()=>K.with(void 0)));const Ie=new te("RECEIVE_FAILED");Ie.on(Ge.type,((a,{payload:e})=>{var t;return W.with({channels:a.channels,groups:a.groups,cursor:{timetoken:e.cursor.timetoken?(t=e.cursor)===null||t===void 0?void 0:t.timetoken:a.cursor.timetoken,region:e.cursor.region||a.cursor.region},onDemand:!0})})),Ie.on(de.type,((a,{payload:e})=>e.channels.length===0&&e.groups.length===0?K.with(void 0):W.with({channels:e.channels,groups:e.groups,cursor:a.cursor,onDemand:!0}))),Ie.on(Oe.type,((a,{payload:e})=>e.channels.length===0&&e.groups.length===0?K.with(void 0):W.with({channels:e.channels,groups:e.groups,cursor:{timetoken:`${e.cursor.timetoken}`,region:e.cursor.region||a.cursor.region},onDemand:!0}))),Ie.on(Te.type,(a=>K.with(void 0)));const Y=new te("RECEIVING");Y.onEnter((a=>{var e;return St(a.channels,a.groups,a.cursor,(e=a.onDemand)!==null&&e!==void 0&&e)})),Y.onExit((()=>St.cancel)),Y.on(os.type,((a,{payload:e})=>Y.with({channels:a.channels,groups:a.groups,cursor:e.cursor,referenceTimetoken:Xe(e.cursor.timetoken)},[rs(a.cursor,e.events)]))),Y.on(de.type,((a,{payload:e})=>{var t;if(e.channels.length===0&&e.groups.length===0){let s;return e.isOffline&&(s=(t=q.create(new Error("Network connection error")).toPubNubError(j.PNSubscribeOperation).status)===null||t===void 0?void 0:t.category),K.with(void 0,[re(Object.assign({category:e.isOffline?M.PNDisconnectedUnexpectedlyCategory:M.PNDisconnectedCategory,operation:j.PNUnsubscribeOperation},s?{error:s}:{}))])}return Y.with({channels:e.channels,groups:e.groups,cursor:a.cursor,referenceTimetoken:a.referenceTimetoken,onDemand:!0},[re({category:M.PNSubscriptionChangedCategory,affectedChannels:e.channels.slice(0),affectedChannelGroups:e.groups.slice(0),currentTimetoken:a.cursor.timetoken})])})),Y.on(Oe.type,((a,{payload:e})=>e.channels.length===0&&e.groups.length===0?K.with(void 0,[re({category:M.PNDisconnectedCategory})]):Y.with({channels:e.channels,groups:e.groups,cursor:{timetoken:`${e.cursor.timetoken}`,region:e.cursor.region||a.cursor.region},referenceTimetoken:Xe(a.cursor.timetoken,`${e.cursor.timetoken}`,a.referenceTimetoken),onDemand:!0},[re({category:M.PNSubscriptionChangedCategory,affectedChannels:e.channels.slice(0),affectedChannelGroups:e.groups.slice(0),currentTimetoken:e.cursor.timetoken})]))),Y.on(cs.type,((a,{payload:e})=>{var t;return Ie.with(Object.assign(Object.assign({},a),{reason:e}),[re({category:M.PNDisconnectedUnexpectedlyCategory,error:(t=e.status)===null||t===void 0?void 0:t.category})])})),Y.on(jt.type,((a,e)=>{var t;if(e.payload.isOffline){const s=q.create(new Error("Network connection error")).toPubNubError(j.PNSubscribeOperation);return Ie.with(Object.assign(Object.assign({},a),{reason:s}),[re({category:M.PNDisconnectedUnexpectedlyCategory,operation:j.PNSubscribeOperation,error:(t=s.status)===null||t===void 0?void 0:t.category})])}return ke.with(Object.assign({},a),[re({category:M.PNDisconnectedCategory,operation:j.PNSubscribeOperation})])})),Y.on(Te.type,(a=>K.with(void 0,[re({category:M.PNDisconnectedCategory,operation:j.PNUnsubscribeOperation})])));class Gs extends Zt{constructor(e,t){super(t,t.config.logger()),this.on(Ot.type,fe(((s,n,r)=>g(this,[s,n,r],void 0,(function*(i,o,{handshake:c,presenceState:u,config:d}){o.throwIfAborted();try{const l=yield c(Object.assign(Object.assign({abortSignal:o,channels:i.channels,channelGroups:i.groups,filterExpression:d.filterExpression},d.maintainPresenceState&&{state:u}),{onDemand:i.onDemand}));return e.transition(is(l))}catch(l){if(l instanceof G)return l.status&&l.status.category==M.PNCancelledCategory?void 0:e.transition(as(l))}}))))),this.on(St.type,fe(((s,n,r)=>
41g(this,[s,n,r],void 0,(function*(i,o,{receiveMessages:c,config:u}){o.throwIfAborted();try{const d=yield c({abortSignal:o,channels:i.channels,channelGroups:i.groups,timetoken:i.cursor.timetoken,region:i.cursor.region,filterExpression:u.filterExpression,onDemand:i.onDemand});e.transition(os(d.cursor,d.messages))}catch(d){if(d instanceof G){if(d.status&&d.status.category==M.PNCancelledCategory)return;if(!o.aborted)return e.transition(cs(d))}}}))))),this.on(rs.type,fe(((s,n,r)=>g(this,[s,n,r],void 0,(function*({cursor:i,events:o},c,{emitMessages:u}){o.length>0&&u(i,o)}))))),this.on(re.type,fe(((s,n,r)=>g(this,[s,n,r],void 0,(function*(i,o,{emitStatus:c}){return c(i)})))))}}class Ks{get _engine(){return this.engine}constructor(e){this.channels=[],this.groups=[],this.dependencies=e,this.engine=new Yt(e.config.logger()),this.dispatcher=new Gs(this.engine,e),e.config.logger().debug("EventEngine","Create subscribe event engine."),this._unsubscribeEngine=this.engine.subscribe((t=>{t.type==="invocationDispatched"&&this.dispatcher.dispatch(t.invocation)})),this.engine.start(K,void 0)}get subscriptionTimetoken(){const e=this.engine.currentState;if(!e)return;let t,s="0";if(e.label===Y.label){const n=this.engine.currentContext;s=n.cursor.timetoken,t=n.referenceTimetoken}return Kt(s,t??"0")}subscribe({channels:e,channelGroups:t,timetoken:s,withPresence:n}){var r;const i=e?.some((u=>!this.channels.includes(u))),o=t?.some((u=>!this.groups.includes(u))),c=i||o;if(this.channels=[...this.channels,...e??[]],this.groups=[...this.groups,...t??[]],n&&(this.channels.map((u=>this.channels.push(`${u}-pnpres`))),this.groups.map((u=>this.groups.push(`${u}-pnpres`)))),s)this.engine.transition(Oe(Array.from(new Set([...this.channels,...e??[]])),Array.from(new Set([...this.groups,...t??[]])),s));else if(c)this.engine.transition(de(Array.from(new Set([...this.channels,...e??[]])),Array.from(new Set([...this.groups,...t??[]]))));else{this.dependencies.config.logger().debug("EventEngine","Skipping state transition - all channels/groups already subscribed. Emitting SubscriptionChanged event.");const u=this.engine.currentState,d=this.engine.currentContext;let l="0";u?.label===Y.label&&d&&(l=(r=d.cursor)===null||r===void 0?void 0:r.timetoken),this.dependencies.emitStatus({category:M.PNSubscriptionChangedCategory,affectedChannels:Array.from(new Set(this.channels)),affectedChannelGroups:Array.from(new Set(this.groups)),currentTimetoken:l})}this.dependencies.join&&this.dependencies.join({channels:Array.from(new Set(this.channels.filter((u=>!u.endsWith("-pnpres"))))),groups:Array.from(new Set(this.groups.filter((u=>!u.endsWith("-pnpres")))))})}unsubscribe({channels:e=[],channelGroups:t=[]}){const s=Ft(this.channels,[...e,...e.map((r=>`${r}-pnpres`))]),n=Ft(this.groups,[...t,...t.map((r=>`${r}-pnpres`))]);if(new Set(this.channels).size!==new Set(s).size||new Set(this.groups).size!==new Set(n).size){const r=qt(this.channels,e),i=qt(this.groups,t);this.dependencies.presenceState&&(r?.forEach((o=>delete this.dependencies.presenceState[o])),i?.forEach((o=>delete this.dependencies.presenceState[o]))),this.channels=s,this.groups=n,this.engine.transition(de(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(e=!1){const t=this.getSubscribedChannelGroups(),s=this.getSubscribedChannels();this.channels=[],this.groups=[],this.dependencies.presenceState&&Object.keys(this.dependencies.presenceState).forEach((n=>{delete this.dependencies.presenceState[n]})),this.engine.transition(de(this.channels.slice(0),this.groups.slice(0),e)),this.dependencies.leaveAll&&this.dependencies.leaveAll({channels:s,groups:t,isOffline:e})}reconnect({timetoken:e,region:t}){const s=this.getSubscribedChannels(),n=this.getSubscribedChannels();this.engine.transition(Ge(e,t)),this.dependencies.presenceReconnect&&this.dependencies.presenceReconnect({channels:n,groups:s})}disconnect(e=!1){const t=this.getSubscribedChannels(),s=this.getSubscribedChannels();this.engine.transition(jt(e)),this.dependencies.presenceDisconnect&&this.dependencies.presenceDisconnect({channels:s,groups:t,isOffline:e})}getSubscribedChannels(){return Array.from(new Set(this.channels.slice(0)))}getSubscribedChannelGroups(){return Array.from(new Set(this.groups.slice(0)))}dispose(){this.disconnect(!0),this._unsubscribeEngine(),this.dispatcher.dispose()}}
41class Ls extends E{constructor(e){var t;const s=(t=e.sendByPost)!==null&&t!==void 0&&t;super({method:s?U.POST:U.GET,compressible:s}),this.parameters=e,this.parameters.sendByPost=s}operation(){return j.PNPublishOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return g(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{message:e,channel:t,keySet:s}=this.parameters,n=this.prepareMessagePayload(e);return`/publish/${s.publishKey}/${s.subscribeKey}/0/${I(t)}/0${this.parameters.sendByPost?"":`/${I(n)}`}`}get queryParameters(){const{customMessageType:e,meta:t,replicate:s,storeInHistory:n,ttl:r}=this.parameters,i={};return e&&(i.custom_message_type=e),n!==void 0&&(i.store=n?"1":"0"),r!==void 0&&(i.ttl=r),s===void 0||s||(i.norep="true"),t&&typeof t=="object"&&(i.meta=JSON.stringify(t)),i}get headers(){var e;return this.parameters.sendByPost?Object.assign(Object.assign({},(e=super.headers)!==null&&e!==void 0?e:{}),{"Content-Type":"application/json"}):super.headers}get body(){return this.prepareMessagePayload(this.parameters.message)}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify(typeof s=="string"?s:Je(s))}}class Hs extends E{constructor(e){super(),this.parameters=e}operation(){return j.PNSignalOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return g(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{keySet:{publishKey:e,subscribeKey:t},channel:s,message:n}=this.parameters,r=JSON.stringify(n);return`/signal/${e}/${t}/0/${I(s)}/0/${I(r)}`}get queryParameters(){const{customMessageType:e}=this.parameters,t={};return e&&(t.custom_message_type=e),t}}class Bs extends bt{operation(){return j.PNReceiveMessagesOperation}validate(){return super.validate()||(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}/${le(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,timetoken:s,region:n,onDemand:r}=this.parameters,i={ee:""};return r&&(i["on-demand"]=1),e&&e.length>0&&(i["channel-group"]=e.sort().join(",")),t&&t.length>0&&(i["filter-expr"]=t),typeof s=="string"?s&&s!=="0"&&s.length>0&&(i.tt=s):s&&s>0&&(i.tt=s),n&&(i.tr=n),i}}class Ws extends bt{operation(){return j.PNHandshakeOperation}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${le(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,state:s,onDemand:n}=this.parameters,r={ee:""};return n&&(r["on-demand"]=1),e&&e.length>0&&(r["channel-group"]=e.sort().join(",")),t&&t.length>0&&(r["filter-expr"]=t),s&&Object.keys(s).length>0&&(r.state=JSON.stringify(s)),r}}var Me;(function(a){a[a.Channel=0]="Channel",a[a.ChannelGroup=1]="ChannelGroup"})(Me||(Me={}));class ge{constructor({channels:e,channelGroups:t}){this.isEmpty=!0,this._channelGroups=new Set((t??[]).filter((s=>s.length>0))),this._channels=new Set((e??[]).filter((s=>s.length>0))),this.isEmpty=this._channels.size===0&&this._channelGroups.size===0}get length(){return this.isEmpty?0:this._channels.size+this._channelGroups.size}get channels(){return this.isEmpty?[]:Array.from(this._channels)}get channelGroups(){return this.isEmpty?[]:Array.from(this._channelGroups)}contains(e){return!this.isEmpty&&(this._channels.has(e)||this._channelGroups.has(e))}with(e){return new ge({channels:[...this._channels,...e._channels],channelGroups:[...this._channelGroups,...e._channelGroups]})}without(e){return new ge({channels:[...this._channels].filter((t=>!e._channels.has(t))),channelGroups:[...this._channelGroups].filter((t=>!e._channelGroups.has(t)))})}add(e){return e._channelGroups.size>0&&(this._channelGroups=new Set([...this._channelGroups,...e._channelGroups])),e._channels.size>0&&(this._channels=new Set([...this._channels,...e._channels])),this.isEmpty=this._channels.size===0&&this._channelGroups.size===0,this}remove(e){return e._channelGroups.size>0&&(this._channelGroups=new Set([...this._channelGroups].filter((t=>!e._channelGroups.has(t))))),e._channels.size>0&&(this._channels=new Set([...this._channels].filter((t=>!e._channels.has(t))))),this}removeAll(){return this._channels.clear(),this._channelGroups.clear(),this.isEmpty=!0,this}toString(){return`SubscriptionInput { channels: [${this.channels.join(", ")}], channelGroups: [${this.channelGroups.join(", ")}], is empty: ${this.isEmpty?"true":"false"}} }`}}class us{constructor(e,t,s,n){this._isSubscribed=!1,this.clones={},this.parents=[],this._id=xe.createUUID(),this.referenceTimetoken=n,this.subscriptionInput=t,this.options=s,this.client=e}get id(){return this._id}get isLastClone(){return Object.keys(this.clones).length===1}get isSubscribed(){return!!this._isSubscribed||this.parents.length>0&&this.parents.some((e=>e.isSubscribed))}set isSubscribed(e){this.isSubscribed!==e&&(this._isSubscribed=e)}addParentState(e){this.parents.includes(e)||this.parents.push(e)}removeParentState(e){const t=this.parents.indexOf(e);t!==-1&&this.parents.splice(t,1)}
41storeClone(e,t){this.clones[e]||(this.clones[e]=t)}}class ls{constructor(e,t="Subscription"){this.subscriptionType=t,this.id=xe.createUUID(),this.eventDispatcher=new Jt,this._state=e}get state(){return this._state}get channels(){return this.state.subscriptionInput.channels.slice(0)}get channelGroups(){return this.state.subscriptionInput.channelGroups.slice(0)}set onMessage(e){this.eventDispatcher.onMessage=e}set onPresence(e){this.eventDispatcher.onPresence=e}set onSignal(e){this.eventDispatcher.onSignal=e}set onObjects(e){this.eventDispatcher.onObjects=e}set onMessageAction(e){this.eventDispatcher.onMessageAction=e}set onFile(e){this.eventDispatcher.onFile=e}set onDataSync(e){this.eventDispatcher.onDataSync=e}addListener(e){this.eventDispatcher.addListener(e)}removeListener(e){this.eventDispatcher.removeListener(e)}removeAllListeners(){this.eventDispatcher.removeAllListeners()}handleEvent(e,t){var s;if((!this.state.cursor||e>this.state.cursor)&&(this.state.cursor=e),this.state.referenceTimetoken&&t.data.timetoken<this.state.referenceTimetoken)return void this.state.client.logger.trace(this.subscriptionType,(()=>({messageType:"text",message:`Event timetoken (${t.data.timetoken}) is older than reference timetoken (${this.state.referenceTimetoken}) for ${this.id} subscription object. Ignoring event.`})));if(!((s=this.state.options)===null||s===void 0)&&s.filter&&!this.state.options.filter(t))return void this.state.client.logger.trace(this.subscriptionType,`Event filtered out by filter function for ${this.id} subscription object. Ignoring event.`);const n=Object.values(this.state.clones);n.length>0&&this.state.client.logger.trace(this.subscriptionType,`Notify ${this.id} subscription object clones (count: ${n.length}) about received event.`),n.forEach((r=>r.eventDispatcher.handleEvent(t)))}dispose(){const e=Object.keys(this.state.clones);e.length>1?(this.state.client.logger.debug(this.subscriptionType,`Remove subscription object clone on dispose: ${this.id}`),delete this.state.clones[this.id]):e.length===1&&this.state.clones[this.id]&&(this.state.client.logger.debug(this.subscriptionType,`Unsubscribe subscription object on dispose: ${this.id}`),this.unsubscribe())}invalidate(e=!1){this.state._isSubscribed=!1,e&&(delete this.state.clones[this.id],Object.keys(this.state.clones).length===0&&(this.state.client.logger.trace(this.subscriptionType,"Last clone removed. Reset shared subscription state."),this.state.subscriptionInput.removeAll(),this.state.parents=[]))}subscribe(e){this.state.isSubscribed?this.state.client.logger.trace(this.subscriptionType,"Already subscribed. Ignoring subscribe request."):(this.state.client.logger.debug(this.subscriptionType,(()=>e?{messageType:"object",message:e,details:"Subscribe with parameters:"}:{messageType:"text",message:"Subscribe"})),this.state.isSubscribed=!0,this.updateSubscription({subscribing:!0,timetoken:e?.timetoken}
41))}unsubscribe(){if(!this.state._isSubscribed||this.state.isSubscribed){if(!this.state._isSubscribed&&this.state.parents.length>0&&this.state.isSubscribed)return void this.state.client.logger.warn(this.subscriptionType,(()=>({messageType:"object",details:"Subscription is subscribed as part of a subscription set. Remove from active sets to unsubscribe:",message:this.state.parents.filter((e=>e.isSubscribed))})));if(!this.state._isSubscribed)return void this.state.client.logger.trace(this.subscriptionType,"Not subscribed. Ignoring unsubscribe request.")}this.state.client.logger.debug(this.subscriptionType,"Unsubscribe"),this.state.isSubscribed=!1,delete this.state.cursor,this.updateSubscription({subscribing:!1})}updateSubscription(e){var t,s;e?.timetoken&&(!((t=this.state.cursor)===null||t===void 0)&&t.timetoken&&((s=this.state.cursor)===null||s===void 0?void 0:s.timetoken)!=="0"?e.timetoken!=="0"&&e.timetoken>this.state.cursor.timetoken&&(this.state.cursor.timetoken=e.timetoken):this.state.cursor={timetoken:e.timetoken});const n=e.subscriptions&&e.subscriptions.length>0?e.subscriptions:void 0;e.subscribing?this.register(Object.assign(Object.assign({},e.timetoken?{cursor:this.state.cursor}:{}),n?{subscriptions:n}:{})):this.unregister(n)}}class Vs extends us{constructor(e){const t=new ge({});e.subscriptions.forEach((s=>t.add(s.state.subscriptionInput))),super(e.client,t,e.options,e.client.subscriptionTimetoken),this.subscriptions=e.subscriptions}addSubscription(e){this.subscriptions.includes(e)||(e.state.addParentState(this),this.subscriptions.push(e),this.subscriptionInput.add(e.state.subscriptionInput))}removeSubscription(e,t){const s=this.subscriptions.indexOf(e);s!==-1&&(this.subscriptions.splice(s,1),t||e.state.removeParentState(this),this.subscriptionInput.remove(e.state.subscriptionInput))}removeAllSubscriptions(){this.subscriptions.forEach((e=>e.state.removeParentState(this))),this.subscriptions.splice(0,this.subscriptions.length),this.subscriptionInput.removeAll()}}class we extends ls{constructor(e){let t;if("client"in e){let s=[];!e.subscriptions&&e.entities?e.entities.forEach((n=>s.push(n.subscription(e.options)))):e.subscriptions&&(s=e.subscriptions),t=new Vs({client:e.client,subscriptions:s,options:e.options}),s.forEach((n=>n.state.addParentState(t))),t.client.logger.debug("SubscriptionSet",(()=>({messageType:"object",details:"Create subscription set with parameters:",message:Object.assign({subscriptions:t.subscriptions},e.options?e.options:{})})))}else t=e.state,t.client.logger.debug("SubscriptionSet","Create subscription set clone");super(t,"SubscriptionSet"),this.state.storeClone(this.id,this),t.subscriptions.forEach((s=>s.addParentSet(this)))}get state(){return super.state}get subscriptions(){return this.state.subscriptions.slice(0)}handleEvent(e,t){var s;this.state.subscriptionInput.contains((s=t.data.subscription)!==null&&s!==void 0?s:t.data.channel)&&(this.state._isSubscribed?(super.handleEvent(e,t),this.state.subscriptions.length>0&&this.state.client.logger.trace(this.subscriptionType,`Notify ${this.id} subscription set subscriptions (count: ${this.state.subscriptions.length}) about received event.`),this.state.subscriptions.forEach((n=>n.handleEvent(e,t)))):this.state.client.logger.trace(this.subscriptionType,`Subscription set ${this.id} is not subscribed. Ignoring event.`))}subscriptionInput(e=!1){let t=this.state.subscriptionInput;return this.state.subscriptions.forEach((s=>{e&&s.state.entity.subscriptionsCount>0&&(t=t.without(s.state.subscriptionInput))})),t}cloneEmpty(){return new we({state:this.state})}dispose(){const e=this.state.isLastClone;this.state.subscriptions.forEach((t=>{t.removeParentSet(this),e&&t.state.removeParentState(this.state)})),super.dispose()}invalidate(e=!1){(e?this.state.subscriptions.slice(0):this.state.subscriptions).forEach((t=>{e&&(t.state.entity.decreaseSubscriptionCount(this.state.id),t.removeParentSet(this)),t.invalidate(e)})),e&&this.state.removeAllSubscriptions(),super.invalidate()}addSubscription(e){this.addSubscriptions([e])}addSubscriptions(e){const t=[],s=[];this.state.client.logger.debug(this.subscriptionType,(()=>{const n=[],r=[];return e.forEach((i=>{this.state.subscriptions.includes(i)?n.push(i):r.push(i)})),{messageType:"object",details:`Add subscriptions to ${this.id} (subscriptions count: ${this.state.subscriptions.length+r.length}):`,message:{addedSubscriptions:r,ignoredSubscriptions:n}}})),e.filter((n=>
41!this.state.subscriptions.includes(n))).forEach((n=>{n.state.isSubscribed?s.push(n):t.push(n),n.addParentSet(this),this.state.addSubscription(n)})),s.length===0&&t.length===0||!this.state.isSubscribed||(s.forEach((({state:n})=>n.entity.increaseSubscriptionCount(this.state.id))),t.length>0&&this.updateSubscription({subscribing:!0,subscriptions:t}))}removeSubscription(e){this.removeSubscriptions([e])}removeSubscriptions(e){const t=[];this.state.client.logger.debug(this.subscriptionType,(()=>{const s=[],n=[];return e.forEach((r=>{this.state.subscriptions.includes(r)?n.push(r):s.push(r)})),{messageType:"object",details:`Remove subscriptions from ${this.id} (subscriptions count: ${this.state.subscriptions.length}):`,message:{removedSubscriptions:n,ignoredSubscriptions:s}}})),e.filter((s=>this.state.subscriptions.includes(s))).forEach((s=>{s.state.isSubscribed&&t.push(s),s.removeParentSet(this),this.state.removeSubscription(s,s.parentSetsCount>1)})),t.length!==0&&this.state.isSubscribed&&this.updateSubscription({subscribing:!1,subscriptions:t})}addSubscriptionSet(e){this.addSubscriptions(e.subscriptions)}removeSubscriptionSet(e){this.removeSubscriptions(e.subscriptions)}register(e){var t;const s=(t=e.subscriptions)!==null&&t!==void 0?t:this.state.subscriptions;s.forEach((({state:n})=>n.entity.increaseSubscriptionCount(this.state.id))),this.state.client.logger.trace(this.subscriptionType,(()=>({messageType:"text",message:`Register subscription for real-time events: ${this}`}))),this.state.client.registerEventHandleCapable(this,e.cursor,s)}unregister(e){const t=e??this.state.subscriptions;t.forEach((({state:s})=>s.entity.decreaseSubscriptionCount(this.state.id))),this.state.client.logger.trace(this.subscriptionType,(()=>e?{messageType:"object",message:{subscription:this,subscriptions:e},details:"Unregister subscriptions of subscription set from real-time events:"}:{messageType:"text",message:`Unregister subscription from real-time events: ${this}`})),this.state.client.unregisterEventHandleCapable(this,t)}toString(){const e=this.state;return`${this.subscriptionType} { id: ${this.id}, stateId: ${e.id}, clonesCount: ${Object.keys(this.state.clones).length}, isSubscribed: ${e.isSubscribed}, subscriptions: [${e.subscriptions.map((t=>t.toString())).join(", ")}] }`}}class zs extends us{constructor(e){var t,s;const n=e.entity.subscriptionNames((s=(t=e.options)===null||t===void 0?void 0:t.receivePresenceEvents)!==null&&s!==void 0&&s),r=new ge({[e.entity.subscriptionType==Me.Channel?"channels":"channelGroups"]:n});super(e.client,r,e.options,e.client.subscriptionTimetoken),this.entity=e.entity}}class nt extends ls{constructor(e){"client"in e?e.client.logger.debug("Subscription",(()=>({messageType:"object",details:"Create subscription with parameters:",message:Object.assign({entity:e.entity},e.options?e.options:{})}))):e.state.client.logger.debug("Subscription","Create subscription clone"),super("state"in e?e.state:new zs(e)),this.parents=[],this.handledUpdates=[],this.state.storeClone(this.id,this)}get state(){return super.state}get parentSetsCount(){return this.parents.length}handleEvent(e,t){var s,n;if(this.state.isSubscribed&&this.state.subscriptionInput.contains((s=t.data.subscription)!==null&&s!==void 0?s:t.data.channel)){if(this.parentSetsCount>0){const r=ht(t.data);if(this.handledUpdates.includes(r))return void this.state.client.logger.trace(this.subscriptionType,`Event (${r}) already handled by ${this.id}. Ignoring.`);this.handledUpdates.push(r),this.handledUpdates.length>10&&this.handledUpdates.shift()}this.state.subscriptionInput.contains((n=t.data.subscription)!==null&&n!==void 0?n:t.data.channel)&&super.handleEvent(e,t)}}subscriptionInput(e=!1){return e&&this.state.entity.subscriptionsCount>0?new ge({}):this.state.subscriptionInput}cloneEmpty(){return new nt({state:this.state})}dispose(){this.parentSetsCount>0?this.state.client.logger.debug(this.subscriptionType,(()=>({messageType:"text",message:`'${this.state.entity.subscriptionNames()}' subscription still in use. Ignore dispose request.`}))):(this.handledUpdates.splice(0,this.handledUpdates.length),super.dispose())}invalidate(e=!1){e&&this.state.entity.decreaseSubscriptionCount(this.state.id),this.handledUpdates.splice(0,this.handledUpdates.length),super.invalidate(e)}addParentSet(e){this.parents.includes(e)||(this.parents.push(e),this.state.client.logger.trace(this.subscriptionType,`Add parent subscription set for ${this.id}: ${e.id}. Parent subscription set count: ${this.parentSetsCount}`))}removeParentSet(e){const t=this.parents.indexOf(e);t!==-1&&(this.parents.splice(t,1),this.state.client.logger.trace(this.subscriptionType,`Remove parent subscription set from ${this.id}: ${e.id}. Parent subscription set count: ${this.parentSetsCount}`)),this.parentSetsCount===0&&this.handledUpdates.splice(0,this.handledUpdates.length)}addSubscription(e){this.state.client.logger.debug(this.subscriptionType,(()=>({messageType:"text",message:`Create set with subscription: ${e}`})));const t=new we({client:this.state.client,subscriptions:[this,e],options:this.state.options});return(this.state.isSubscribed||e.state.isSubscribed)&&(this.state.client.logger.trace(this.subscriptionType,"Subscribe resulting set because the receiver is already subscribed."),t.subscribe()),t}register(e){this.state.entity.increaseSubscriptionCount(this.state.id),this.state.client.logger.trace(this.subscriptionType,(()=>({messageType:"text",message:`Register subscription for real-time events: ${this}`}))),this.state.client.registerEventHandleCapable(this,e.cursor)}unregister(e){this.state.entity.decreaseSubscriptionCount(this.state.id),this.state.client.logger.trace(this.subscriptionType,(()=>({messageType:"text",message:`Unregister subscription from real-time events: ${this}`}))),this.handledUpdates.splice(0,this.handledUpdates.length),this.state.client.unregisterEventHandleCapable(this)}toString(){const e=this.state;return`${this.subscriptionType} { id: ${this.id}, stateId: ${e.id}, entity: ${e.entity.subscriptionNames(!1).pop()}, clonesCount: ${Object.keys(e.clones).length}, isSubscribed: ${e.isSubscribed}, parentSetsCount: ${this.parentSetsCount}, cursor: ${e.cursor?e.cursor.timetoken:"not set"}, referenceTimetoken: ${e.referenceTimetoken?e.referenceTimetoken:"not set"} }`}}
41class Js extends E{constructor(e){var t,s,n,r;super(),this.parameters=e,(t=(n=this.parameters).channels)!==null&&t!==void 0||(n.channels=[]),(s=(r=this.parameters).channelGroups)!==null&&s!==void 0||(r.channelGroups=[])}operation(){return j.PNGetStateOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;if(!e)return"Missing Subscribe Key"}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e),{channels:s=[],channelGroups:n=[]}=this.parameters,r={channels:{}};return s.length===1&&n.length===0?r.channels[s[0]]=t.payload:r.channels=t.payload,r}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${le(s??[],",")}/uuid/${I(t??"")}`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&e.length!==0?{"channel-group":e.join(",")}:{}}}class Xs extends E{constructor(e){super(),this.parameters=e}operation(){return j.PNSetStateOperation}validate(){const{keySet:{subscribeKey:e},state:t,channels:s=[],channelGroups:n=[]}=this.parameters;return e?t===void 0?"Missing State":s?.length===0&&n?.length===0?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key"}parse(e){return g(this,void 0,void 0,(function*(){return{state:this.deserializeResponse(e).payload}}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${le(s??[],",")}/uuid/${I(t)}/data`}get queryParameters(){const{channelGroups:e,state:t}=this.parameters,s={state:JSON.stringify(t)};return e&&e.length!==0&&(s["channel-group"]=e.join(",")),s}}class kt extends E{constructor(e){super({cancellable:!0}),this.parameters=e}operation(){return j.PNHeartbeatOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?t.length===0&&s.length===0?"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 g(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((s=>({})))}))}get path(){const{keySet:{subscribeKey:e},channels:t}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${le(t??[],",")}/heartbeat`}get queryParameters(){const{channelGroups:e,state:t,heartbeat:s}=this.parameters,n={heartbeat:`${s}`};return e&&e.length!==0&&(n["channel-group"]=e.join(",")),t!==void 0&&(n.state=JSON.stringify(t)),n}}class Qs extends E{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 j.PNUnsubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?t.length===0&&s.length===0?"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 g(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((s=>({})))}))}get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/presence/sub-key/${t}/channel/${le((e=s?.sort())!==null&&e!==void 0?e:[],",")}/leave`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&e.length!==0?{"channel-group":e.sort().join(",")}:{}}}class Ys extends E{constructor(e){super(),this.parameters=e}operation(){return j.PNWhereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return g(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/${I(t)}`}}class Zs extends E{constructor(e){var t,s,n,r,i,o,c,u;super(),this.parameters=e,(t=(i=this.parameters).queryParameters)!==null&&t!==void 0||(i.queryParameters={}),(s=(o=this.parameters).includeUUIDs)!==null&&s!==void 0||(o.includeUUIDs=!0),(n=(c=this.parameters).includeState)!==null&&n!==void 0||(c.includeState=!1),(r=(u=this.parameters).limit)!==null&&r!==void 0||(u.limit=1e3)}operation(){const{channels:e=[],channelGroups:t=[]}=this.parameters;return e.length===0&&t.length===0?j.PNGlobalHereNowOperation:j.PNHereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return g(this,void 0,void 0,(function*(){var t,s;const n=this.deserializeResponse(e),r="occupancy"in n?1:n.payload.total_channels,i="occupancy"in n?n.occupancy:n.payload.total_occupancy,o={};let c={};const u=this.parameters.limit;let d=!1;if("occupancy"in n){const l=this.parameters.channels[0];c[l]={uuids:(t=n.uuids)!==null&&t!==void 0?t:[],occupancy:i}}else c=(s=n.payload.channels)!==null&&s!==void 0?s:{};
41return Object.keys(c).forEach((l=>{const h=c[l];o[l]={occupants:this.parameters.includeUUIDs?h.uuids.map((y=>typeof y=="string"?{uuid:y,state:null}:y)):[],name:l,occupancy:h.occupancy},d||h.occupancy!==u||(d=!0)})),{totalChannels:r,totalOccupancy:i,channels:o}}))}get path(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;let n=`/v2/presence/sub-key/${e}`;return(t&&t.length>0||s&&s.length>0)&&(n+=`/channel/${le(t??[],",")}`),n}get queryParameters(){const{channelGroups:e,includeUUIDs:t,includeState:s,limit:n,offset:r,queryParameters:i}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.operation()===j.PNHereNowOperation?{limit:n}:{}),this.operation()===j.PNHereNowOperation&&r!=null&&r?{offset:r}:{}),t?{}:{disable_uuids:"1"}),s!=null&&s?{state:"1"}:{}),e&&e.length>0?{"channel-group":e.join(",")}:{}),i)}}class en extends E{constructor(e){super({method:U.DELETE}),this.parameters=e}operation(){return j.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 g(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((s=>({})))}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v3/history/sub-key/${e}/channel/${I(t)}`}get queryParameters(){const{start:e,end:t}=this.parameters;return Object.assign(Object.assign({},e?{start:e}:{}),t?{end:t}:{})}}class tn extends E{constructor(e){super(),this.parameters=e}operation(){return j.PNMessageCounts}validate(){const{keySet:{subscribeKey:e},channels:t,timetoken:s,channelTimetokens:n}=this.parameters;return e?t?s&&n?"`timetoken` and `channelTimetokens` are incompatible together":s||n?n&&n.length>1&&n.length!==t.length?"Length of `channelTimetokens` and `channels` do not match":void 0:"`timetoken` or `channelTimetokens` need to be set":"Missing channels":"Missing Subscribe Key"}parse(e){return g(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/${le(this.parameters.channels)}`}get queryParameters(){let{channelTimetokens:e}=this.parameters;return this.parameters.timetoken&&(e=[this.parameters.timetoken]),Object.assign(Object.assign({},e.length===1?{timetoken:e[0]}:{}),e.length>1?{channelsTimetoken:e.join(",")}:{})}}class wt extends E{constructor(e){var t,s,n;super(),this.parameters=e,e.count?e.count=Math.min(e.count,100):e.count=100,(t=e.stringifiedTimeToken)!==null&&t!==void 0||(e.stringifiedTimeToken=!1),(s=e.includeMeta)!==null&&s!==void 0||(e.includeMeta=!1),(n=e.logVerbosity)!==null&&n!==void 0||(e.logVerbosity=!1)}operation(){return j.PNHistoryOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e),s=t[0],n=t[1],r=t[2];return Array.isArray(s)?{messages:s.map((i=>{const o=this.processPayload(i.message),c={entry:o.payload,timetoken:i.timetoken};return o.error&&(c.error=o.error),i.meta&&(c.meta=i.meta),c})),startTimeToken:n,endTimeToken:r}:{messages:[],startTimeToken:n,endTimeToken:r}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/history/sub-key/${e}/channel/${I(t)}`}get queryParameters(){const{start:e,end:t,reverse:s,count:n,stringifiedTimeToken:r,includeMeta:i}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:n,include_token:"true"},e?{start:e}:{}),t?{end:t}:{}),r?{string_message_token:"true"}:{}),s!=null?{reverse:s.toString()}:{}),i?{include_meta:"true"}:{})}processPayload(e){const{crypto:t,logVerbosity:s}=this.parameters;if(!t||typeof e!="string")return{payload:e};let n,r;try{const i=t.decrypt(e);n=i instanceof ArrayBuffer?JSON.parse(wt.decoder.decode(i)):i}catch(i){s&&console.log("decryption error",i.message),n=e,r=`Error while decrypting message content: ${i.message}`}return{payload:n,error:r}}}var rt;(function(a){a[a.Message=-1]="Message",a[a.Files=4]="Files"})(rt||(rt={}));
41class Pt extends E{constructor(e){var t,s,n,r,i;super(),this.parameters=e;const o=(t=e.includeMessageActions)!==null&&t!==void 0&&t,c=e.channels.length>1||o?25:100;e.count?e.count=Math.min(e.count,c):e.count=c,e.includeUuid?e.includeUUID=e.includeUuid:(s=e.includeUUID)!==null&&s!==void 0||(e.includeUUID=!0),(n=e.stringifiedTimeToken)!==null&&n!==void 0||(e.stringifiedTimeToken=!1),(r=e.includeMessageType)!==null&&r!==void 0||(e.includeMessageType=!0),(i=e.logVerbosity)!==null&&i!==void 0||(e.logVerbosity=!1)}operation(){return j.PNFetchMessagesOperation}validate(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return e?t?s!==void 0&&s&&t.length>1?"History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.":void 0:"Missing channels":"Missing Subscribe Key"}parse(e){return g(this,void 0,void 0,(function*(){var t;const s=this.deserializeResponse(e),n=(t=s.channels)!==null&&t!==void 0?t:{},r={};return Object.keys(n).forEach((i=>{r[i]=n[i].map((o=>{o.message_type===null&&(o.message_type=rt.Message);const c=this.processPayload(i,o),u=Object.assign(Object.assign({channel:i,timetoken:o.timetoken,message:c.payload,messageType:o.message_type},o.custom_message_type?{customMessageType:o.custom_message_type}:{}),{uuid:o.uuid});if(o.actions){const d=u;d.actions=o.actions,d.data=o.actions}return o.meta&&(u.meta=o.meta),c.error&&(u.error=c.error),u}))})),s.more?{channels:r,more:s.more}:{channels:r}}))}get path(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return`/v3/${s?"history-with-actions":"history"}/sub-key/${e}/channel/${le(t)}`}get queryParameters(){const{start:e,end:t,count:s,includeCustomMessageType:n,includeMessageType:r,includeMeta:i,includeUUID:o,stringifiedTimeToken:c}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({max:s},e?{start:e}:{}),t?{end:t}:{}),c?{string_message_token:"true"}:{}),i!==void 0&&i?{include_meta:"true"}:{}),o?{include_uuid:"true"}:{}),n!=null?{include_custom_message_type:n?"true":"false"}:{}),r?{include_message_type:"true"}:{})}processPayload(e,t){const{crypto:s,logVerbosity:n}=this.parameters;if(!s||typeof t.message!="string")return{payload:t.message};let r,i;try{const o=s.decrypt(t.message);r=o instanceof ArrayBuffer?JSON.parse(Pt.decoder.decode(o)):o}catch(o){n&&console.log("decryption error",o.message),r=t.message,i=`Error while decrypting message content: ${o.message}`}if(!i&&r&&t.message_type==rt.Files&&typeof r=="object"&&this.isFileMessage(r)){const o=r;return{payload:{message:o.message,file:Object.assign(Object.assign({},o.file),{url:this.parameters.getFileUrl({channel:e,id:o.file.id,name:o.file.name})})},error:i}}return{payload:r,error:i}}isFileMessage(e){return e.file!==void 0}}
41class sn extends E{constructor(e){super(),this.parameters=e}operation(){return j.PNGetMessageActionsOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing message channel":"Missing Subscribe Key"}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);let s=null,n=null;return t.data.length>0&&(s=t.data[0].actionTimetoken,n=t.data[t.data.length-1].actionTimetoken),{data:t.data,more:t.more,start:s,end:n}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/message-actions/${e}/channel/${I(t)}`}get queryParameters(){const{limit:e,start:t,end:s}=this.parameters;return Object.assign(Object.assign(Object.assign({},t?{start:t}:{}),s?{end:s}:{}),e?{limit:e}:{})}}class nn extends E{constructor(e){super({method:U.POST}),this.parameters=e}operation(){return j.PNAddMessageActionOperation}validate(){const{keySet:{subscribeKey:e},action:t,channel:s,messageTimetoken:n}=this.parameters;return e?s?n?t?t.value?t.type?t.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message timetoken":"Missing message channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return g(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((({data:s})=>({data:s})))}))}get path(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s}=this.parameters;return`/v1/message-actions/${e}/channel/${I(t)}/message/${s}`}get headers(){var e;return Object.assign(Object.assign({},(e=super.headers)!==null&&e!==void 0?e:{}),{"Content-Type":"application/json"})}get body(){return JSON.stringify(this.parameters.action)}}class rn extends E{constructor(e){super({method:U.DELETE}),this.parameters=e}operation(){return j.PNRemoveMessageActionOperation}validate(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s,actionTimetoken:n}=this.parameters;return e?t?s?n?void 0:"Missing action timetoken":"Missing message timetoken":"Missing message action channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return g(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((({data:s})=>({data:s})))}))}get path(){const{keySet:{subscribeKey:e},channel:t,actionTimetoken:s,messageTimetoken:n}=this.parameters;return`/v1/message-actions/${e}/channel/${I(t)}/message/${n}/action/${s}`}}class an extends E{constructor(e){var t,s;super(),this.parameters=e,(t=(s=this.parameters).storeInHistory)!==null&&t!==void 0||(s.storeInHistory=!0)}operation(){return j.PNPublishFileMessageOperation}validate(){const{channel:e,fileId:t,fileName:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return g(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{message:e,channel:t,keySet:{publishKey:s,subscribeKey:n},fileId:r,fileName:i}=this.parameters,o=Object.assign({file:{name:i,id:r}},e?{message:e}:{});return`/v1/files/publish-file/${s}/${n}/0/${I(t)}/0/${I(this.prepareMessagePayload(o))}`}get queryParameters(){const{customMessageType:e,storeInHistory:t,ttl:s,meta:n}=this.parameters;return Object.assign(Object.assign(Object.assign({store:t?"1":"0"},e?{custom_message_type:e}:{}),s?{ttl:s}:{}),n&&typeof n=="object"?{meta:JSON.stringify(n)}:{})}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify(typeof s=="string"?s:Je(s))}}class on extends E{constructor(e){super({method:U.LOCAL}),this.parameters=e}operation(){return j.PNGetFileUrlOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return g(this,void 0,void 0,(function*(){return e.url}))}get path(){const{channel:e,id:t,name:s,keySet:{subscribeKey:n}}=this.parameters;return`/v1/files/${n}/channels/${I(e)}/files/${I(t)}/${I(s)}`}}
41class cn extends E{constructor(e){super({method:U.DELETE}),this.parameters=e}operation(){return j.PNDeleteFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}get path(){const{keySet:{subscribeKey:e},id:t,channel:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${I(s)}/files/${I(t)}/${I(n)}`}}class un extends E{constructor(e){var t,s;super(),this.parameters=e,(t=(s=this.parameters).limit)!==null&&t!==void 0||(s.limit=100)}operation(){return j.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/${I(t)}/files`}get queryParameters(){const{limit:e,next:t}=this.parameters;return Object.assign({limit:e},t?{next:t}:{})}}class ln extends E{constructor(e){super({method:U.POST}),this.parameters=e}operation(){return j.PNGenerateUploadUrlOperation}validate(){return this.parameters.channel?this.parameters.name?void 0:"'name' can't be empty":"channel can't be empty"}parse(e){return g(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/${I(t)}/generate-upload-url`}get headers(){var e;return Object.assign(Object.assign({},(e=super.headers)!==null&&e!==void 0?e:{}),{"Content-Type":"application/json"})}get body(){return JSON.stringify({name:this.parameters.name})}}class Ct extends E{constructor(e){super({method:U.POST}),this.parameters=e;const t=e.file.mimeType;t&&(e.formFields=e.formFields.map((s=>s.name==="Content-Type"?{name:s.name,value:t}:s)))}operation(){return j.PNPublishFileOperation}validate(){const{fileId:e,fileName:t,file:s,uploadUrl:n}=this.parameters;return e?t?s?n?void 0:"Validation failed: file upload 'url' can't be empty":"Validation failed: 'file' can't be empty":"Validation failed: file 'name' can't be empty":"Validation failed: file 'id' can't be empty"}parse(e){return g(this,void 0,void 0,(function*(){return{status:e.status,message:e.body?Ct.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 hn{constructor(e){var t;if(this.parameters=e,this.file=(t=this.parameters.PubNubFile)===null||t===void 0?void 0:t.create(e.file),!this.file)throw new Error("File upload error: unable to create File object.")}process(){return g(this,void 0,void 0,(function*(){let e,t;return this.generateFileUploadUrl().then((s=>(e=s.name,t=s.id,this.uploadFile(s)))).then((s=>{if(s.status!==204)throw new G("Upload to bucket was unsuccessful",{error:!0,statusCode:s.status,category:M.PNUnknownCategory,operation:j.PNPublishFileOperation,errorData:{message:s.message}})})).then((()=>this.publishFileMessage(t,e))).catch((s=>{if(s instanceof G)throw s;const n=s instanceof q?s:q.create(s);throw new G("File upload error.",n.toStatus(j.PNPublishFileOperation))}))}))}generateFileUploadUrl(){return g(this,void 0,void 0,(function*(){const e=new ln(Object.assign(Object.assign({},this.parameters),{name:this.file.name,keySet:this.parameters.keySet}));return this.parameters.sendRequest(e)}))}uploadFile(e){return g(this,void 0,void 0,(function*(){const{cipherKey:t,PubNubFile:s,crypto:n,cryptography:r}=this.parameters,{id:i,name:o,url:c,formFields:u}=e;return this.parameters.PubNubFile.supportsEncryptFile&&(!t&&n?this.file=yield n.encryptFile(this.file,s):t&&r&&(this.file=yield r.encryptFile(t,this.file,s))),this.parameters.sendRequest(new Ct({fileId:i,fileName:o,file:this.file,uploadUrl:c,formFields:u}))}))}publishFileMessage(e,t){return g(this,void 0,void 0,(function*(){var s,n,r,i;let o,c={timetoken:"0"},u=this.parameters.fileUploadPublishRetryLimit,d=!1;do try{c=yield this.parameters.publishFile(Object.assign(Object.assign({},this.parameters),{fileId:e,fileName:t})),d=!0}catch(l){l instanceof G&&(o=l),u-=1}while(!d&&u>0);if(d)return{status:200,timetoken:c.timetoken,id:e,name:t};throw new G("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{error:!0,category:(n=(s=o.status)===null||s===void 0?void 0:s.category)!==null&&n!==void 0?n:M.PNUnknownCategory,statusCode:(i=(r=o.status)===null||r===void 0?void 0:r.statusCode)!==null&&i!==void 0?i:0,channel:this.parameters.channel,id:e,name:t})}))}}
41class dn extends E{constructor(e){super({method:U.DELETE}),this.parameters=e}operation(){return j.PNAccessManagerRevokeToken}validate(){return this.parameters.keySet.secretKey?this.parameters.token?void 0:"token can't be empty":"Missing Secret Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return g(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((s=>({})))}))}get path(){const{keySet:{subscribeKey:e},token:t}=this.parameters;return`/v3/pam/${e}/grant/${I(t)}`}}class pn extends E{constructor(e){var t,s,n,r;super({method:U.POST}),this.parameters=e,(t=(n=this.parameters).resources)!==null&&t!==void 0||(n.resources={}),(s=(r=this.parameters).patterns)!==null&&s!==void 0||(r.patterns={})}operation(){return j.PNAccessManagerGrantToken}validate(){const{keySet:{subscribeKey:e,publishKey:t,secretKey:s},resources:n,patterns:r}=this.parameters,i=this.buildProjections()!==void 0;if(!e)return"Missing Subscribe Key";if(!t)return"Missing Publish Key";if(!s)return"Missing Secret Key";if(!n&&!r&&!i)return"Missing either Resources or Patterns";const o=u=>{var d,l;return u in((d=this.parameters.resources)!==null&&d!==void 0?d:{})||u in((l=this.parameters.patterns)!==null&&l!==void 0?l:{})};if(o("users")&&o("uuids"))return"Cannot mix `users` with `uuids` — `uuids` is deprecated App Context terminology; use `users`";if(o("spaces")&&o("channels"))return"Cannot mix `spaces` with `channels` — `spaces` is deprecated terminology; use `channels`";if(o("spaces")&&o("uuids"))return"Cannot mix `spaces` with `uuids` — mixed deprecated terminology; use `channels` with `users`";if("authorizedUserId"in this.parameters&&"authorized_uuid"in this.parameters)return"Cannot mix `authorizedUserId` with `authorized_uuid` — use `authorizedUserId`";let c=!0;return[this.parameters.resources,this.parameters.patterns].forEach((u=>{Object.keys(u??{}).forEach((d=>{var l;u&&c&&Object.keys((l=u[d])!==null&&l!==void 0?l:{}).length>0&&(c=!1)}))})),c&&!i?"Missing values for either Resources or Patterns":void 0}parse(e){return g(this,void 0,void 0,(function*(){return this.deserializeResponse(e).data.token}))}get path(){return`/v3/pam/${this.parameters.keySet.subscribeKey}/grant`}get headers(){var e;return Object.assign(Object.assign({},(e=super.headers)!==null&&e!==void 0?e:{}),{"Content-Type":"application/json"})}get body(){var e;const{ttl:t,meta:s}=this.parameters,n=Object.assign({},t||t===0?{ttl:t}:{}),r=(e="authorizedUserId"in this.parameters?this.parameters.authorizedUserId:void 0)!==null&&e!==void 0?e:"authorized_uuid"in this.parameters?this.parameters.authorized_uuid:void 0,i={},o={},c={},u=(y,p,b,m)=>{m[b]||(m[b]={}),m[b][y]=p},{resources:d,patterns:l}=this.parameters;[d,l].forEach(((y,p)=>{var b,m,v,_,D;const R=p===0?o:c;let C={},T={},f={},S={};if(R.channels||(R.channels={}),R.groups||(R.groups={}),R.uuids||(R.uuids={}),R.users||(R.users={}),R.spaces||(R.spaces={}),y){const O=y;C="channels"in O?(b=O.channels)!==null&&b!==void 0?b:{}:"spaces"in O&&(m=O.spaces)!==null&&m!==void 0?m:{},T="groups"in O&&(v=O.groups)!==null&&v!==void 0?v:{},f="uuids"in O&&(_=O.uuids)!==null&&_!==void 0?_:{},S="users"in O&&(D=O.users)!==null&&D!==void 0?D:{}}Object.keys(C).forEach((O=>u(O,this.extractPermissions(C[O]),"channels",R))),Object.keys(T).forEach((O=>u(O,this.extractPermissions(T[O]),"groups",R))),Object.keys(f).forEach((O=>u(O,this.extractPermissions(f[O]),"uuids",R))),Object.keys(S).forEach((O=>u(O,this.extractPermissions(S[O]),"users",R))),y&&"dataSync"in y&&this.mapDataSyncPermissions(y.dataSync,R,u)})),r&&(i.uuid=`${r}`),i.resources=o,i.patterns=c;const h=this.buildProjections();return i.meta=Object.assign(Object.assign({},s??{}),h?{"pn-projections":h}:{}),n.permissions=i,JSON.stringify(n)}mapDataSyncPermissions(e,t,s){e&&[["entities","datasync:entities"],["relationships","datasync:relationships"],["memberships","datasync:memberships"]].forEach((([n,r])=>{const i=e[n];
41i&&Object.keys(i).forEach((o=>s(o,this.extractPermissions(i[o]),r,t)))}))}buildProjections(){const e="dataSyncProjections"in this.parameters?this.parameters.dataSyncProjections:void 0;if(!e)return;const t=i=>{const o={};return i&&["entities","relationships","users","channels","memberships"].forEach((c=>{const u=i[c];u&&Object.keys(u).forEach((d=>o[`datasync:${c}:${d}`]=u[d]))})),o},s={},n=t(e.resources),r=t(e.patterns);return Object.keys(n).length>0&&(s.res=n),Object.keys(r).length>0&&(s.pat=r),Object.keys(s).length>0?s:void 0}extractPermissions(e){let t=0;return"join"in e&&e.join&&(t|=128),"update"in e&&e.update&&(t|=64),"get"in e&&e.get&&(t|=32),"create"in e&&e.create&&(t|=16),"delete"in e&&e.delete&&(t|=8),"manage"in e&&e.manage&&(t|=4),"write"in e&&e.write&&(t|=2),"read"in e&&e.read&&(t|=1),t}}class gn extends E{constructor(e){var t,s,n,r,i,o,c,u,d,l,h,y,p,b,m,v,_,D,R,C;super(),this.parameters=e,(t=(h=this.parameters).channels)!==null&&t!==void 0||(h.channels=[]),(s=(y=this.parameters).channelGroups)!==null&&s!==void 0||(y.channelGroups=[]),(n=(p=this.parameters).uuids)!==null&&n!==void 0||(p.uuids=[]),(r=(b=this.parameters).read)!==null&&r!==void 0||(b.read=!1),(i=(m=this.parameters).write)!==null&&i!==void 0||(m.write=!1),(o=(v=this.parameters).delete)!==null&&o!==void 0||(v.delete=!1),(c=(_=this.parameters).get)!==null&&c!==void 0||(_.get=!1),(u=(D=this.parameters).update)!==null&&u!==void 0||(D.update=!1),(d=(R=this.parameters).manage)!==null&&d!==void 0||(R.manage=!1),(l=(C=this.parameters).join)!==null&&l!==void 0||(C.join=!1)}operation(){return j.PNAccessManagerGrant}validate(){const{keySet:{subscribeKey:e,publishKey:t,secretKey:s},uuids:n=[],channels:r=[],channelGroups:i=[],authKeys:o=[]}=this.parameters;return e?t?s?n.length!==0&&o.length===0?"authKeys are required for grant request on uuids":!n.length||r.length===0&&i.length===0?void 0:"Both channel/channel group and uuid cannot be used in the same request":"Missing Secret Key":"Missing Publish Key":"Missing Subscribe Key"}parse(e){return g(this,void 0,void 0,(function*(){return this.deserializeResponse(e).payload}))}get path(){return`/v2/auth/grant/sub-key/${this.parameters.keySet.subscribeKey}`}get queryParameters(){const{channels:e,channelGroups:t,authKeys:s,uuids:n,read:r,write:i,manage:o,delete:c,get:u,join:d,update:l,ttl:h}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},e&&e?.length>0?{channel:e.join(",")}:{}),t&&t?.length>0?{"channel-group":t.join(",")}:{}),s&&s?.length>0?{auth:s.join(",")}:{}),n&&n?.length>0?{"target-uuid":n.join(",")}:{}),{r:r?"1":"0",w:i?"1":"0",m:o?"1":"0",d:c?"1":"0",g:u?"1":"0",j:d?"1":"0",u:l?"1":"0"}),h||h===0?{ttl:h}:{})}}const bn=[];
41class yn extends E{constructor(e){var t,s;super(),this.parameters=e,(t=(s=this.parameters).authKeys)!==null&&t!==void 0||(s.authKeys=bn)}operation(){return j.PNAccessManagerAudit}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return g(this,void 0,void 0,(function*(){return this.deserializeResponse(e).payload}))}get path(){return`/v2/auth/audit/sub-key/${this.parameters.keySet.subscribeKey}`}get queryParameters(){const{channel:e,channelGroup:t,authKeys:s}=this.parameters;return Object.assign(Object.assign(Object.assign({},e?{channel:e}:{}),t?{"channel-group":t}:{}),s&&s.length?{auth:s.join(",")}:{})}}class Ke{constructor(e,t){this.subscriptionStateIds=[],this.client=t,this._nameOrId=e}get entityType(){return"Channel"}get subscriptionType(){return Me.Channel}subscriptionNames(e){return[this._nameOrId,...e&&!this._nameOrId.endsWith("-pnpres")?[`${this._nameOrId}-pnpres`]:[]]}subscription(e){return new nt({client:this.client,entity:this,options:e})}get subscriptionsCount(){return this.subscriptionStateIds.length}increaseSubscriptionCount(e){this.subscriptionStateIds.includes(e)||this.subscriptionStateIds.push(e)}decreaseSubscriptionCount(e){{const t=this.subscriptionStateIds.indexOf(e);t>=0&&this.subscriptionStateIds.splice(t,1)}}toString(){return`${this.entityType} { nameOrId: ${this._nameOrId}, subscriptionsCount: ${this.subscriptionsCount} }`}}const mn=["default","__default__"],hs=a=>{if(!a)return;const e=a.trim();return e.length===0||mn.includes(e.toLowerCase())?void 0:e};class Le extends Ke{constructor(e,t,s){super(e,t),this._projection=hs(s)}get id(){return this._nameOrId}get projection(){return this._projection}get subscriptionChannel(){return this._projection?`__${this._projection}__${this._nameOrId}`:this._nameOrId}subscriptionNames(e){return[this.subscriptionChannel]}subscription(e){{const t=this.entityForProjection(hs(e?.projection));return t!==this?t.subscription(e):super.subscription(e)}}entityForProjection(e){var t,s,n,r;if(e===this._projection)return this;const i=(t=this.variants)!==null&&t!==void 0?t:this.variants={};(n=i[r=(s=this._projection)!==null&&s!==void 0?s:""])!==null&&n!==void 0||(i[r]=this);const o=e??"";let c=i[o];return c||(c=i[o]=this.withProjection(e),c.variants=i),c}toString(){var e;return`${this.entityType} { id: ${this._nameOrId}, projection: ${(e=this._projection)!==null&&e!==void 0?e:"none"}, channel: ${this.subscriptionChannel}, subscriptionsCount: ${this.subscriptionsCount} }`}}class Nt extends Le{get entityType(){return"DataSyncRelationship"}withProjection(e){return new Nt(this._nameOrId,this.client,e)}}class Et extends Le{get entityType(){return"DataSyncMembership"}withProjection(e){return new Et(this._nameOrId,this.client,e)}}class Tt extends Le{get entityType(){return"DataSyncChannel"}withProjection(e){return new Tt(this._nameOrId,this.client,e)}}class _t extends Le{get entityType(){return"DataSyncEntity"}withProjection(e){return new _t(this._nameOrId,this.client,e)}}class fn extends Ke{get entityType(){return"ChannelMetadata"}get id(){return this._nameOrId}subscriptionNames(e){return[this.id]}}class It extends Le{get entityType(){return"DataSyncUser"}withProjection(e){return new It(this._nameOrId,this.client,e)}}class vn extends Ke{get entityType(){return"ChannelGroups"}get name(){return this._nameOrId}get subscriptionType(){return Me.ChannelGroup}}class On extends Ke{get entityType(){return"UserMetadata"}get id(){return this._nameOrId}subscriptionNames(e){return[this.id]}}class Sn extends Ke{get entityType(){return"Channel"}get name(){return this._nameOrId}}
41class jn extends E{constructor(e){super(),this.parameters=e}operation(){return j.PNRemoveChannelsFromGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return g(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((s=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${I(t)}`}get queryParameters(){return{remove:this.parameters.channels.join(",")}}}class kn extends E{constructor(e){super(),this.parameters=e}operation(){return j.PNAddChannelsToGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return g(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((s=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${I(t)}`}get queryParameters(){return{add:this.parameters.channels.join(",")}}}
41class wn extends E{constructor(e){super(),this.parameters=e}operation(){return j.PNChannelsForGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return g(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/${I(t)}`}}class Pn extends E{constructor(e){super(),this.parameters=e}operation(){return j.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 g(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((s=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${I(t)}/remove`}}class Cn extends E{constructor(e){super(),this.parameters=e}operation(){return j.PNChannelGroupsOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return g(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 Nn{constructor(e,t,s){this.sendRequest=s,this.logger=e,this.keySet=t}listChannels(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"List channel group channels with parameters:"})));const s=new wn(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=r=>{r&&this.logger.debug("PubNub",`List channel group channels success. Received ${r.channels.length} channels.`)};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)})):this.sendRequest(s).then((r=>(n(r),r)))}))}listGroups(e){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub","List all channel groups.");const t=new Cn({keySet:this.keySet}),s=n=>{n&&this.logger.debug("PubNub",`List all channel groups success. Received ${n.groups.length} groups.`)};return e?this.sendRequest(t,((n,r)=>{s(r),e(n,r)})):this.sendRequest(t).then((n=>(s(n),n)))}))}addChannels(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Add channels to the channel group with parameters:"})));const s=new kn(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub","Add channels to the channel group success.")};return t?this.sendRequest(s,(r=>{r.error||n(),t(r)})):this.sendRequest(s).then((r=>(n(),r)))}))}removeChannels(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove channels from the channel group with parameters:"})));const s=new jn(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub","Remove channels from the channel group success.")};return t?this.sendRequest(s,(r=>{r.error||n(),t(r)})):this.sendRequest(s).then((r=>(n(),r)))}))}deleteGroup(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove a channel group with parameters:"})));const s=new Pn(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub",`Remove a channel group success. Removed '${e.channelGroup}' channel group.'`)};return t?this.sendRequest(s,(r=>{r.error||n(),t(r)})):this.sendRequest(s).then((r=>(n(),r)))}))}}class it extends E{constructor(e){var t,s;super(),this.parameters=e,this.parameters.pushGateway==="apns2"&&((t=(s=this.parameters).environment)!==null&&t!==void 0||(s.environment="development")),this.parameters.count&&this.parameters.count>1e3&&(this.parameters.count=1e3)}operation(){throw Error("Should be implemented in subclass.")}validate(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;return e?s?t!=="add"&&t!=="remove"||"channels"in this.parameters&&this.parameters.channels.length!==0?n?this.parameters.pushGateway!=="apns2"||this.parameters.topic?void 0:"Missing APNS2 topic":"Missing GW Type (pushGateway: fcm or apns2)":"Missing Channels":"Missing Device ID (device)":"Missing Subscribe Key"}get path(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;let r=n==="apns2"?`/v2/push/sub-key/${e}/devices-apns2/${s}`:`/v1/push/sub-key/${e}/devices/${s}`;return t==="remove-device"&&(r=`${r}/remove`),r}get queryParameters(){const{start:e,count:t}=this.parameters;let s=Object.assign(Object.assign({type:this.parameters.pushGateway},e?{start:e}:{}),t&&t>0?{count:t}:{});if("channels"in this.parameters&&(s[this.parameters.action]=this.parameters.channels.join(",")),this.parameters.pushGateway==="apns2"){const{environment:n,topic:r}=this.parameters;s=Object.assign(Object.assign({},s),{environment:n,topic:r})}return s}}class En extends it{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove"}))}operation(){return j.PNRemovePushNotificationEnabledChannelsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return g(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((s=>({})))}))}}class Tn extends it{constructor(e){super(Object.assign(Object.assign({},e),{action:"list"}))}operation(){return j.PNPushNotificationEnabledChannelsOperation}parse(e){return g(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e)}}))}}class _n extends it{constructor(e){super(Object.assign(Object.assign({},e),{action:"add"}))}operation(){return j.PNAddPushNotificationEnabledChannelsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return g(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((s=>({})))}))}}class In extends it{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove-device"}))}operation(){return j.PNRemoveAllPushNotificationsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return g(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((s=>({})))}))}}class Mn{constructor(e,t,s){this.sendRequest=s,this.logger=e,this.keySet=t}listChannels(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"List push-enabled channels with parameters:"})));const s=new Tn(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=r=>{r&&this.logger.debug("PubNub",`List push-enabled channels success. Received ${r.channels.length} channels.`)};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)}
41)):this.sendRequest(s).then((r=>(n(r),r)))}))}addChannels(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Add push-enabled channels with parameters:"})));const s=new _n(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub","Add push-enabled channels success.")};return t?this.sendRequest(s,(r=>{r.error||n(),t(r)})):this.sendRequest(s).then((r=>(n(),r)))}))}removeChannels(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove push-enabled channels with parameters:"})));const s=new En(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub","Remove push-enabled channels success.")};return t?this.sendRequest(s,(r=>{r.error||n(),t(r)})):this.sendRequest(s).then((r=>(n(),r)))}))}deleteDevice(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove push notifications for device with parameters:"})));const s=new In(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub","Remove push notifications for device success.")};return t?this.sendRequest(s,(r=>{r.error||n(),t(r)})):this.sendRequest(s).then((r=>(n(),r)))}))}}class Rn extends E{constructor(e){var t,s,n,r,i,o;super(),this.parameters=e,(t=e.include)!==null&&t!==void 0||(e.include={}),(s=(i=e.include).customFields)!==null&&s!==void 0||(i.customFields=!1),(n=(o=e.include).totalCount)!==null&&n!==void 0||(o.totalCount=!1),(r=e.limit)!==null&&r!==void 0||(e.limit=100)}operation(){return j.PNGetAllChannelMetadataOperation}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";return i=typeof n=="string"?n:Object.entries(n??{}).map((([o,c])=>c!==null?`${o}:${c}`:o)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(","),count:`${e.totalCount}`},s?{filter:s}:{}),t?.next?{start:t.next}:{}),t?.prev?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class Dn extends E{constructor(e){super({method:U.DELETE}),this.parameters=e}operation(){return j.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/${I(t)}`}}
41class Un extends E{constructor(e){var t,s,n,r,i,o,c,u,d,l,h,y,p,b,m,v,_,D;super(),this.parameters=e,(t=e.include)!==null&&t!==void 0||(e.include={}),(s=(h=e.include).customFields)!==null&&s!==void 0||(h.customFields=!1),(n=(y=e.include).totalCount)!==null&&n!==void 0||(y.totalCount=!1),(r=(p=e.include).statusField)!==null&&r!==void 0||(p.statusField=!1),(i=(b=e.include).typeField)!==null&&i!==void 0||(b.typeField=!1),(o=(m=e.include).channelFields)!==null&&o!==void 0||(m.channelFields=!1),(c=(v=e.include).customChannelFields)!==null&&c!==void 0||(v.customChannelFields=!1),(u=(_=e.include).channelStatusField)!==null&&u!==void 0||(_.channelStatusField=!1),(d=(D=e.include).channelTypeField)!==null&&d!==void 0||(D.channelTypeField=!1),(l=e.limit)!==null&&l!==void 0||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return j.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/${I(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i=typeof n=="string"?n:Object.entries(n??{}).map((([c,u])=>u!==null?`${c}:${u}`:c));const o=[];return e.statusField&&o.push("status"),e.typeField&&o.push("type"),e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),e.channelStatusField&&o.push("channel.status"),e.channelTypeField&&o.push("channel.type"),e.customChannelFields&&o.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),t?.next?{start:t.next}:{}),t?.prev?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class ds extends E{constructor(e){var t,s,n,r,i,o,c,u,d,l,h,y,p,b,m,v,_,D;super({method:U.PATCH}),this.parameters=e,(t=e.include)!==null&&t!==void 0||(e.include={}),(s=(h=e.include).customFields)!==null&&s!==void 0||(h.customFields=!1),(n=(y=e.include).totalCount)!==null&&n!==void 0||(y.totalCount=!1),(r=(p=e.include).statusField)!==null&&r!==void 0||(p.statusField=!1),(i=(b=e.include).typeField)!==null&&i!==void 0||(b.typeField=!1),(o=(m=e.include).channelFields)!==null&&o!==void 0||(m.channelFields=!1),(c=(v=e.include).customChannelFields)!==null&&c!==void 0||(v.customChannelFields=!1),(u=(_=e.include).channelStatusField)!==null&&u!==void 0||(_.channelStatusField=!1),(d=(D=e.include).channelTypeField)!==null&&d!==void 0||(D.channelTypeField=!1),(l=e.limit)!==null&&l!==void 0||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return j.PNSetMembershipsOperation}validate(){const{uuid:e,channels:t}=this.parameters;return e?t&&t.length!==0?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/${I(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i=typeof n=="string"?n:Object.entries(n??{}).map((([c,u])=>u!==null?`${c}:${u}`:c));const o=["channel.status","channel.type","status"];return e.statusField&&o.push("status"),e.typeField&&o.push("type"),e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),e.channelStatusField&&o.push("channel.status"),e.channelTypeField&&o.push("channel.type"),e.customChannelFields&&o.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),t?.next?{start:t.next}:{}),t?.prev?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get headers(){var e;return Object.assign(Object.assign({},(e=super.headers)!==null&&e!==void 0?e:{}),{"Content-Type":"application/json"})}get body(){const{channels:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((s=>typeof s=="string"?{channel:{id:s}}:{channel:{id:s.id},status:s.status,type:s.type,custom:s.custom}))})}}class An extends E{constructor(e){var t,s,n,r;super(),this.parameters=e,(t=e.include)!==null&&t!==void 0||(e.include={}),(s=(r=e.include).customFields)!==null&&s!==void 0||(r.customFields=!1),(n=e.limit)!==null&&n!==void 0||(e.limit=100)}operation(){return j.PNGetAllUUIDMetadataOperation}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";return i=typeof n=="string"?n:Object.entries(n??{}).map((([o,c])=>c!==null?`${o}:${c}`:o)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(",")},e.totalCount!==void 0?{count:`${e.totalCount}`}:{}),s?{filter:s}:{}),t?.next?{start:t.next}:{}),t?.prev?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}
41class $n extends E{constructor(e){var t,s,n;super(),this.parameters=e,(t=e.include)!==null&&t!==void 0||(e.include={}),(s=(n=e.include).customFields)!==null&&s!==void 0||(n.customFields=!0)}operation(){return j.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/${I(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}}class xn extends E{constructor(e){var t,s,n;super({method:U.PATCH}),this.parameters=e,(t=e.include)!==null&&t!==void 0||(e.include={}),(s=(n=e.include).customFields)!==null&&s!==void 0||(n.customFields=!0)}operation(){return j.PNSetChannelMetadataOperation}validate(){return this.parameters.channel?this.parameters.data?void 0:"Data cannot be empty":"Channel cannot be empty"}get headers(){var e;let t=(e=super.headers)!==null&&e!==void 0?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json"})}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${I(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Fn extends E{constructor(e){super({method:U.DELETE}),this.parameters=e,this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return j.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/${I(t)}`}}class qn extends E{constructor(e){var t,s,n,r,i,o,c,u,d,l,h,y,p,b,m,v,_,D;super(),this.parameters=e,(t=e.include)!==null&&t!==void 0||(e.include={}),(s=(h=e.include).customFields)!==null&&s!==void 0||(h.customFields=!1),(n=(y=e.include).totalCount)!==null&&n!==void 0||(y.totalCount=!1),(r=(p=e.include).statusField)!==null&&r!==void 0||(p.statusField=!1),(i=(b=e.include).typeField)!==null&&i!==void 0||(b.typeField=!1),(o=(m=e.include).UUIDFields)!==null&&o!==void 0||(m.UUIDFields=!1),(c=(v=e.include).customUUIDFields)!==null&&c!==void 0||(v.customUUIDFields=!1),(u=(_=e.include).UUIDStatusField)!==null&&u!==void 0||(_.UUIDStatusField=!1),(d=(D=e.include).UUIDTypeField)!==null&&d!==void 0||(D.UUIDTypeField=!1),(l=e.limit)!==null&&l!==void 0||(e.limit=100)}operation(){return j.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/${I(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i=typeof n=="string"?n:Object.entries(n??{}).map((([c,u])=>u!==null?`${c}:${u}`:c));const o=[];return e.statusField&&o.push("status"),e.typeField&&o.push("type"),e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),e.UUIDStatusField&&o.push("uuid.status"),e.UUIDTypeField&&o.push("uuid.type"),e.customUUIDFields&&o.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),t?.next?{start:t.next}:{}),t?.prev?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class ps extends E{constructor(e){var t,s,n,r,i,o,c,u,d,l,h,y,p,b,m,v,_,D;super({method:U.PATCH}),this.parameters=e,(t=e.include)!==null&&t!==void 0||(e.include={}),(s=(h=e.include).customFields)!==null&&s!==void 0||(h.customFields=!1),(n=(y=e.include).totalCount)!==null&&n!==void 0||(y.totalCount=!1),(r=(p=e.include).statusField)!==null&&r!==void 0||(p.statusField=!1),(i=(b=e.include).typeField)!==null&&i!==void 0||(b.typeField=!1),(o=(m=e.include).UUIDFields)!==null&&o!==void 0||(m.UUIDFields=!1),(c=(v=e.include).customUUIDFields)!==null&&c!==void 0||(v.customUUIDFields=!1),(u=(_=e.include).UUIDStatusField)!==null&&u!==void 0||(_.UUIDStatusField=!1),(d=(D=e.include).UUIDTypeField)!==null&&d!==void 0||(D.UUIDTypeField=!1),(l=e.limit)!==null&&l!==void 0||(e.limit=100)}operation(){return j.PNSetMembersOperation}validate(){const{channel:e,uuids:t}=this.parameters;return e?t&&t.length!==0?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/${I(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i=typeof n=="string"?n:Object.entries(n??{}).map((([c,u])=>u!==null?`${c}:${u}`:c));const o=["uuid.status","uuid.type","type"];return e.statusField&&o.push("status"),e.typeField&&o.push("type"),e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),e.UUIDStatusField&&o.push("uuid.status"),e.UUIDTypeField&&o.push("uuid.type"),e.customUUIDFields&&o.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),t?.next?{start:t.next}:{}),t?.prev?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get headers(){var e;return Object.assign(Object.assign({},(e=super.headers)!==null&&e!==void 0?e:{}),{"Content-Type":"application/json"})}get body(){const{uuids:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((s=>typeof s=="string"?{uuid:{id:s}}:{uuid:{id:s.id},status:s.status,type:s.type,custom:s.custom}))})}}
41class Gn extends E{constructor(e){var t,s,n;super(),this.parameters=e,(t=e.include)!==null&&t!==void 0||(e.include={}),(s=(n=e.include).customFields)!==null&&s!==void 0||(n.customFields=!0),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return j.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/${I(t)}`}get queryParameters(){const{include:e}=this.parameters;return{include:["status","type",...e.customFields?["custom"]:[]].join(",")}}}class Kn extends E{constructor(e){var t,s,n;super({method:U.PATCH}),this.parameters=e,(t=e.include)!==null&&t!==void 0||(e.include={}),(s=(n=e.include).customFields)!==null&&s!==void 0||(n.customFields=!0),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return j.PNSetUUIDMetadataOperation}validate(){return this.parameters.uuid?this.parameters.data?void 0:"Data cannot be empty":"'uuid' cannot be empty"}get headers(){var e;let t=(e=super.headers)!==null&&e!==void 0?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json"})}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${I(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Ln{constructor(e,t){this.keySet=e.keySet,this.configuration=e,this.sendRequest=t}get logger(){return this.configuration.logger()}getAllUUIDMetadata(e,t){return g(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&typeof e!="function"?e:{},details:"Get all UUID metadata objects with parameters:"}))),this._getAllUUIDMetadata(e,t)}))}_getAllUUIDMetadata(e,t){return g(this,void 0,void 0,(function*(){const s=e&&typeof e!="function"?e:{};t!=null||(t=typeof e=="function"?e:void 0);const n=new An(Object.assign(Object.assign({},s),{keySet:this.keySet})),r=i=>{i&&this.logger.debug("PubNub",`Get all UUID metadata success. Received ${i.totalCount} UUID metadata objects.`)};return t?this.sendRequest(n,((i,o)=>{r(o),t(i,o)})):this.sendRequest(n).then((i=>(r(i),i)))}))}getUUIDMetadata(e,t){return g(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&typeof e!="function"?e:{uuid:this.configuration.userId},details:`Get ${e&&typeof e!="function"?"":" current"} UUID metadata object with parameters:`}))),this._getUUIDMetadata(e,t)}))}_getUUIDMetadata(e,t){return g(this,void 0,void 0,(function*(){var s;const n=e&&typeof e!="function"?e:{};t!=null||(t=typeof e=="function"?e:void 0),n.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),n.uuid=n.userId),(s=n.uuid)!==null&&s!==void 0||(n.uuid=this.configuration.userId);const r=new Gn(Object.assign(Object.assign({},n),{keySet:this.keySet})),i=o=>{o&&this.logger.debug("PubNub",`Get UUID metadata object success. Received '${n.uuid}' UUID metadata object.`)};return t?this.sendRequest(r,((o,c)=>{i(c),t(o,c)})):this.sendRequest(r).then((o=>(i(o),o)))}))}setUUIDMetadata(e,t){return g(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set UUID metadata object with parameters:"}))),this._setUUIDMetadata(e,t)}))}_setUUIDMetadata(e,t){return g(this,void 0,void 0,(function*(){var s;e.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),e.uuid=e.userId),(s=e.uuid)!==null&&s!==void 0||(e.uuid=this.configuration.userId);const n=new Kn(Object.assign(Object.assign({},e),{keySet:this.keySet})),r=i=>{i&&this.logger.debug("PubNub",`Set UUID metadata object success. Updated '${e.uuid}' UUID metadata object.`)};return t?this.sendRequest(n,((i,o)=>{r(o),t(i,o)})):this.sendRequest(n).then((i=>(r(i),i)))}))}removeUUIDMetadata(e,t){return g(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&typeof e!="function"?e:{uuid:this.configuration.userId},details:`Remove${e&&typeof e!="function"?"":" current"} UUID metadata object with parameters:`}))),this._removeUUIDMetadata(e,t)}))}_removeUUIDMetadata(e,t){return g(this,void 0,void 0,(function*(){var s;const n=e&&typeof e!="function"?e:{};t!=null||(t=typeof e=="function"?e:void 0),n.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),n.uuid=n.userId),(s=n.uuid)!==null&&s!==void 0||(n.uuid=this.configuration.userId);const r=new Fn(Object.assign(Object.assign({},n),{keySet:this.keySet})),i=o=>{o&&this.logger.debug("PubNub",`Remove UUID metadata object success. Removed '${n.uuid}' UUID metadata object.`)};return t?this.sendRequest(r,((o,c)=>{i(c),t(o,c)})):this.sendRequest(r).then((o=>(i(o),o)))}))}getAllChannelMetadata(e,t){return g(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&typeof e!="function"?e:{},details:"Get all Channel metadata objects with parameters:"}))),this._getAllChannelMetadata(e,t)}))}_getAllChannelMetadata(e,t){return g(this,void 0,void 0,(function*(){const s=e&&typeof e!="function"?e:{};t!=null||(t=typeof e=="function"?e:void 0);const n=new Rn(Object.assign(Object.assign({},s),{keySet:this.keySet})),r=i=>{i&&this.logger.debug("PubNub",`Get all Channel metadata objects success. Received ${i.totalCount} Channel metadata objects.`)};return t?this.sendRequest(n,((i,o)=>{r(o),t(i,o)})):this.sendRequest(n).then((i=>(r(i),i)))}))}getChannelMetadata(e,t){return g(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Channel metadata object with parameters:"}))),this._getChannelMetadata(e,t)}))}_getChannelMetadata(e,t){return g(this,void 0,void 0,(function*(){const s=new $n(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=r=>{r&&this.logger.debug("PubNub",`Get Channel metadata object success. Received '${e.channel}' Channel metadata object.`)};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)}
41)):this.sendRequest(s).then((r=>(n(r),r)))}))}setChannelMetadata(e,t){return g(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set Channel metadata object with parameters:"}))),this._setChannelMetadata(e,t)}))}_setChannelMetadata(e,t){return g(this,void 0,void 0,(function*(){const s=new xn(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=r=>{r&&this.logger.debug("PubNub",`Set Channel metadata object success. Updated '${e.channel}' Channel metadata object.`)};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)})):this.sendRequest(s).then((r=>(n(r),r)))}))}removeChannelMetadata(e,t){return g(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Channel metadata object with parameters:"}))),this._removeChannelMetadata(e,t)}))}_removeChannelMetadata(e,t){return g(this,void 0,void 0,(function*(){const s=new Dn(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=r=>{r&&this.logger.debug("PubNub",`Remove Channel metadata object success. Removed '${e.channel}' Channel metadata object.`)};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)})):this.sendRequest(s).then((r=>(n(r),r)))}))}getChannelMembers(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get channel members with parameters:"})));const s=new qn(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=r=>{r&&this.logger.debug("PubNub",`Get channel members success. Received ${r.totalCount} channel members.`)};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)})):this.sendRequest(s).then((r=>(n(r),r)))}))}setChannelMembers(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set channel members with parameters:"})));const s=new ps(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet})),n=r=>{r&&this.logger.debug("PubNub",`Set channel members success. There are ${r.totalCount} channel members now.`)};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)})):this.sendRequest(s).then((r=>(n(r),r)))}))}removeChannelMembers(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove channel members with parameters:"})));const s=new ps(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet})),n=r=>{r&&this.logger.debug("PubNub",`Remove channel members success. There are ${r.totalCount} channel members now.`)};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)})):this.sendRequest(s).then((r=>(n(r),r)))}))}getMemberships(e,t){return g(this,void 0,void 0,(function*(){var s;const n=e&&typeof e!="function"?e:{};t!=null||(t=typeof e=="function"?e:void 0),n.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),n.uuid=n.userId),(s=n.uuid)!==null&&s!==void 0||(n.uuid=this.configuration.userId),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},n),details:"Get memberships with parameters:"})));const r=new Un(Object.assign(Object.assign({},n),{keySet:this.keySet})),i=o=>{o&&this.logger.debug("PubNub",`Get memberships success. Received ${o.totalCount} memberships.`)};return t?this.sendRequest(r,((o,c)=>{i(c),t(o,c)})):this.sendRequest(r).then((o=>(i(o),o)))}))}setMemberships(e,t){return g(this,void 0,void 0,(function*(){var s;e.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),e.uuid=e.userId),(s=e.uuid)!==null&&s!==void 0||(e.uuid=this.configuration.userId),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set memberships with parameters:"})));const n=new ds(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet})),r=i=>{i&&this.logger.debug("PubNub",`Set memberships success. There are ${i.totalCount} memberships now.`)};return t?this.sendRequest(n,((i,o)=>{r(o),t(i,o)})):this.sendRequest(n).then((i=>(r(i),i)))}))}removeMemberships(e,t){return g(this,void 0,void 0,(function*(){var s;e.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),e.uuid=e.userId),(s=e.uuid)!==null&&s!==void 0||(e.uuid=this.configuration.userId),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove memberships with parameters:"})));const n=new ds(Object.assign(Object.assign({}
41,e),{type:"delete",keySet:this.keySet})),r=i=>{i&&this.logger.debug("PubNub",`Remove memberships success. There are ${i.totalCount} memberships now.`)};return t?this.sendRequest(n,((i,o)=>{r(o),t(i,o)})):this.sendRequest(n).then((i=>(r(i),i)))}))}fetchMemberships(e,t){return g(this,void 0,void 0,(function*(){var s,n;if(this.logger.warn("PubNub","'fetchMemberships' is deprecated. Use 'pubnub.objects.getChannelMembers' or 'pubnub.objects.getMemberships' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fetch memberships with parameters:"}))),"spaceId"in e){const c=e,u={channel:(s=c.spaceId)!==null&&s!==void 0?s:c.channel,filter:c.filter,limit:c.limit,page:c.page,include:Object.assign({},c.include),sort:c.sort?Object.fromEntries(Object.entries(c.sort).map((([l,h])=>[l.replace("user","uuid"),h]))):void 0},d=l=>({status:l.status,data:l.data.map((h=>({user:h.uuid,custom:h.custom,updated:h.updated,eTag:h.eTag}))),totalCount:l.totalCount,next:l.next,prev:l.prev});return t?this.getChannelMembers(u,((l,h)=>{t(l,h&&d(h))})):this.getChannelMembers(u).then(d)}const r=e,i={uuid:(n=r.userId)!==null&&n!==void 0?n:r.uuid,filter:r.filter,limit:r.limit,page:r.page,include:Object.assign({},r.include),sort:r.sort?Object.fromEntries(Object.entries(r.sort).map((([c,u])=>[c.replace("space","channel"),u]))):void 0},o=c=>({status:c.status,data:c.data.map((u=>({space:u.channel,custom:u.custom,updated:u.updated,eTag:u.eTag}))),totalCount:c.totalCount,next:c.next,prev:c.prev});return t?this.getMemberships(i,((c,u)=>{t(c,u&&o(u))})):this.getMemberships(i).then(o)}))}addMemberships(e,t){return g(this,void 0,void 0,(function*(){var s,n,r,i,o,c;if(this.logger.warn("PubNub","'addMemberships' is deprecated. Use 'pubnub.objects.setChannelMembers' or 'pubnub.objects.setMemberships' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Add memberships with parameters:"}))),"spaceId"in e){const l=e,h={channel:(s=l.spaceId)!==null&&s!==void 0?s:l.channel,uuids:(r=(n=l.users)===null||n===void 0?void 0:n.map((y=>typeof y=="string"?y:{id:y.userId,custom:y.custom})))!==null&&r!==void 0?r:l.uuids,limit:0};return t?this.setChannelMembers(h,t):this.setChannelMembers(h)}const u=e,d={uuid:(i=u.userId)!==null&&i!==void 0?i:u.uuid,channels:(c=(o=u.spaces)===null||o===void 0?void 0:o.map((l=>typeof l=="string"?l:{id:l.spaceId,custom:l.custom})))!==null&&c!==void 0?c:u.channels,limit:0};return t?this.setMemberships(d,t):this.setMemberships(d)}))}}class Hn extends E{constructor(e){super({method:U.POST}),this.parameters=e}operation(){return j.PNCreateDataSyncUserOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.data?this.parameters.data.classVersion===void 0||this.parameters.data.classVersion===null?"Entity class version cannot be empty":void 0:"User data cannot be empty"}get headers(){var e;const t=(e=super.headers)!==null&&e!==void 0?e:{};return Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.user+json;version=1"})}get path(){const{keySet:{subscribeKey:e}}=this.parameters;return`/v1/datasync/subkeys/${e}/users`}get body(){const{id:e,class:t,classLevel:s,data:n}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},e!==void 0?{id:e}:{}),t!==void 0?{entityClass:t}:{}),{entityClassVersion:n.classVersion}),s!==void 0?{entityClassLevel:s}:{}),n.status!==void 0?{status:n.status}:{}),n.payload!==void 0?{payload:n.payload}:{})})}}function He(a){return typeof a=="string"?a:Object.entries(a??{}).map((([e,t])=>t!==null?`${e}:${t}`:e))}function Be(a){const{add:e,replace:t,remove:s,move:n,copy:r,test:i}=a,o=[];if(e)for(const[c,u]of Object.entries(e))o.push({op:"add",path:c,value:u});if(t)for(const[c,u]of Object.entries(t))o.push({op:"replace",path:c,value:u});if(s)for(const c of s)o.push({op:"remove",path:c});if(n)for(const{from:c,path:u}of n)o.push({op:"move",from:c,path:u});if(r)for(const{from:c,path:u}
41of r)o.push({op:"copy",from:c,path:u});if(i)for(const[c,u]of Object.entries(i))o.push({op:"test",path:c,value:u});return o}class Bn extends E{constructor(e){var t;super(),this.parameters=e,(t=e.limit)!==null&&t!==void 0||(e.limit=20)}operation(){return j.PNGetDataSyncUsersOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}get path(){return`/v1/datasync/subkeys/${this.parameters.keySet.subscribeKey}/users`}get queryParameters(){const{class:e,classVersion:t,classLevel:s,cursor:n,limit:r,filter:i,filterFast:o,sort:c}=this.parameters,u=He(c);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},e?{entity_class:e}:{}),t!==void 0?{entity_class_version:`${t}`}:{}),s?{entity_class_level:s}:{}),n?{cursor:n}:{}),r?{limit:`${r}`}:{}),i?{filter:i}:{}),o?{filter_fast:o}:{}),u.length?{sort:u}:{})}}class Wn extends E{constructor(e){super({method:U.PUT}),this.parameters=e}operation(){return j.PNSetDataSyncUserOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.id?this.parameters.data?this.parameters.data.classVersion===void 0||this.parameters.data.classVersion===null?"Entity class version cannot be empty":void 0:"User data cannot be empty":"User id cannot be empty"}get headers(){var e;let t=(e=super.headers)!==null&&e!==void 0?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.user+json;version=1"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/users/${I(t)}`}get body(){const{data:e}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign({entityClassVersion:e.classVersion},e.status!==void 0?{status:e.status}:{}),e.payload!==void 0?{payload:e.payload}:{})})}}class Vn extends E{constructor(e){super({method:U.DELETE}),this.parameters=e}operation(){return j.PNRemoveDataSyncUserOperation}validate(){if(!this.parameters.id)return"User id cannot be empty"}get headers(){var e;let t=(e=super.headers)!==null&&e!==void 0?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.keys(t).length>0?t:void 0}parse(e){return g(this,void 0,void 0,(function*(){return{status:e.status}}))}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/users/${I(t)}`}}class zn extends E{constructor(e){super({method:U.PATCH}),this.parameters=e}operation(){return j.PNUpdateDataSyncUserOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"User id cannot be empty";const{add:e,replace:t,remove:s,move:n,copy:r,test:i}=this.parameters,o=e&&Object.keys(e).length>0,c=t&&Object.keys(t).length>0,u=s&&s.length>0,d=n&&n.length>0,l=r&&r.length>0,h=i&&Object.keys(i).length>0;return o||c||u||d||l||h?void 0:"At least one of add, replace, remove, move, copy, or test must be provided"}get headers(){var e;let t=(e=super.headers)!==null&&e!==void 0?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json-patch+json"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/users/${I(t)}`}get body(){const{add:e,replace:t,remove:s,move:n,copy:r,test:i}=this.parameters,o=Be({add:e,replace:t,remove:s,move:n,copy:r,test:i});return JSON.stringify(o)}}class Jn extends E{constructor(e){super(),this.parameters=e}operation(){return j.PNGetDataSyncUserOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"User id cannot be empty"}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/users/${I(t)}`}}
41class Xn extends E{constructor(e){super({method:U.POST}),this.parameters=e}operation(){return j.PNCreateDataSyncChannelOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.data?this.parameters.data.classVersion===void 0||this.parameters.data.classVersion===null?"Entity class version cannot be empty":void 0:"Channel data cannot be empty"}get headers(){var e;const t=(e=super.headers)!==null&&e!==void 0?e:{};return Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.channel+json;version=1"})}get path(){const{keySet:{subscribeKey:e}}=this.parameters;return`/v1/datasync/subkeys/${e}/channels`}get body(){const{id:e,class:t,classLevel:s,data:n}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},e!==void 0?{id:e}:{}),t!==void 0?{entityClass:t}:{}),{entityClassVersion:n.classVersion}),s!==void 0?{entityClassLevel:s}:{}),n.status!==void 0?{status:n.status}:{}),n.payload!==void 0?{payload:n.payload}:{})})}}class Qn extends E{constructor(e){var t;super(),this.parameters=e,(t=e.limit)!==null&&t!==void 0||(e.limit=20)}operation(){return j.PNGetDataSyncChannelsOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}get path(){return`/v1/datasync/subkeys/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{class:e,classVersion:t,classLevel:s,cursor:n,limit:r,filter:i,filterFast:o,sort:c}=this.parameters,u=He(c);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},e?{entity_class:e}:{}),t!==void 0?{entity_class_version:`${t}`}:{}),s?{entity_class_level:s}:{}),n?{cursor:n}:{}),r?{limit:`${r}`}:{}),i?{filter:i}:{}),o?{filter_fast:o}:{}),u.length?{sort:u}:{})}}class Yn extends E{constructor(e){super({method:U.PUT}),this.parameters=e}operation(){return j.PNSetDataSyncChannelOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.id?this.parameters.data?this.parameters.data.classVersion===void 0||this.parameters.data.classVersion===null?"Entity class version cannot be empty":void 0:"Channel data cannot be empty":"Channel id cannot be empty"}get headers(){var e;let t=(e=super.headers)!==null&&e!==void 0?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.channel+json;version=1"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/channels/${I(t)}`}get body(){const{data:e}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign({entityClassVersion:e.classVersion},e.status!==void 0?{status:e.status}:{}),e.payload!==void 0?{payload:e.payload}:{})})}}class Zn extends E{constructor(e){super({method:U.DELETE}),this.parameters=e}operation(){return j.PNRemoveDataSyncChannelOperation}validate(){if(!this.parameters.id)return"Channel id cannot be empty"}get headers(){var e;let t=(e=super.headers)!==null&&e!==void 0?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.keys(t).length>0?t:void 0}parse(e){return g(this,void 0,void 0,(function*(){return{status:e.status}}))}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/channels/${I(t)}`}}class er extends E{constructor(e){super({method:U.PATCH}),this.parameters=e}operation(){return j.PNUpdateDataSyncChannelOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Channel id cannot be empty";const{add:e,replace:t,remove:s,move:n,copy:r,test:i}=this.parameters,o=e&&Object.keys(e).length>0,c=t&&Object.keys(t).length>0,u=s&&s.length>0,d=n&&n.length>0,l=r&&r.length>0,h=i&&Object.keys(i).length>0;return o||c||u||d||l||h?void 0:"At least one of add, replace, remove, move, copy, or test must be provided"}get headers(){var e;let t=(e=super.headers)!==null&&e!==void 0?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json-patch+json"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/channels/${I(t)}`}get body(){const{add:e,replace:t,remove:s,move:n,copy:r,test:i}=this.parameters,o=Be({add:e,replace:t,remove:s,move:n,copy:r,test:i});return JSON.stringify(o)}}
41class tr extends E{constructor(e){super(),this.parameters=e}operation(){return j.PNGetDataSyncChannelOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Channel id cannot be empty"}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/channels/${I(t)}`}}class sr extends E{constructor(e){super({method:U.POST}),this.parameters=e}operation(){return j.PNCreateDataSyncMembershipOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.userId?this.parameters.channelId?this.parameters.data?this.parameters.data.classVersion?void 0:"Membership class version cannot be empty":"Membership data cannot be empty":"Channel id cannot be empty":"User id cannot be empty"}get headers(){var e;const t=(e=super.headers)!==null&&e!==void 0?e:{};return Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.membership+json;version=1"})}get path(){const{keySet:{subscribeKey:e}}=this.parameters;return`/v1/datasync/subkeys/${e}/memberships`}get body(){const{id:e,userId:t,channelId:s,data:n}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign(Object.assign(Object.assign({},e!==void 0?{id:e}:{}),{userId:t,channelId:s,relationshipClassVersion:n.classVersion}),n.status!==void 0?{status:n.status}:{}),n.payload!==void 0?{payload:n.payload}:{})})}}class nr extends E{constructor(e){var t;super(),this.parameters=e,(t=e.limit)!==null&&t!==void 0||(e.limit=20)}operation(){return j.PNGetDataSyncMembershipsOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}get path(){return`/v1/datasync/subkeys/${this.parameters.keySet.subscribeKey}/memberships`}get queryParameters(){const{userId:e,channelId:t,classVersion:s,cursor:n,limit:r,filter:i,filterFast:o,sort:c}=this.parameters,u=He(c);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},e?{user_id:e}:{}),t?{channel_id:t}:{}),s!==void 0?{relationship_class_version:`${s}`}:{}),n?{cursor:n}:{}),r?{limit:`${r}`}:{}),i?{filter:i}:{}),o?{filter_fast:o}:{}),u.length?{sort:u}:{})}}class rr extends E{constructor(e){super({method:U.PUT}),this.parameters=e}operation(){return j.PNSetDataSyncMembershipOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.id?this.parameters.userId?this.parameters.channelId?this.parameters.data?this.parameters.data.classVersion?void 0:"Membership class version cannot be empty":"Membership data cannot be empty":"Channel id cannot be empty":"User id cannot be empty":"Membership id cannot be empty"}get headers(){var e;let t=(e=super.headers)!==null&&e!==void 0?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.membership+json;version=1"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/memberships/${I(t)}`}get body(){const{userId:e,channelId:t,data:s}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign({userId:e,channelId:t,relationshipClassVersion:s.classVersion},s.status!==void 0?{status:s.status}:{}),s.payload!==void 0?{payload:s.payload}:{})})}}class ir extends E{constructor(e){super({method:U.DELETE}),this.parameters=e}operation(){return j.PNRemoveDataSyncMembershipOperation}validate(){if(!this.parameters.id)return"Membership id cannot be empty"}get headers(){var e;let t=(e=super.headers)!==null&&e!==void 0?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.keys(t).length>0?t:void 0}parse(e){return g(this,void 0,void 0,(function*(){return{status:e.status}}))}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/memberships/${I(t)}`}}
41class ar extends E{constructor(e){super({method:U.PATCH}),this.parameters=e}operation(){return j.PNUpdateDataSyncMembershipOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Membership id cannot be empty";const{add:e,replace:t,remove:s,move:n,copy:r,test:i}=this.parameters,o=e&&Object.keys(e).length>0,c=t&&Object.keys(t).length>0,u=s&&s.length>0,d=n&&n.length>0,l=r&&r.length>0,h=i&&Object.keys(i).length>0;return o||c||u||d||l||h?void 0:"At least one of add, replace, remove, move, copy, or test must be provided"}get headers(){var e;let t=(e=super.headers)!==null&&e!==void 0?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json-patch+json"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/memberships/${I(t)}`}get body(){const{add:e,replace:t,remove:s,move:n,copy:r,test:i}=this.parameters,o=Be({add:e,replace:t,remove:s,move:n,copy:r,test:i});return JSON.stringify(o)}}class or extends E{constructor(e){super(),this.parameters=e}operation(){return j.PNGetDataSyncMembershipOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Membership id cannot be empty"}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/memberships/${I(t)}`}}class cr extends E{constructor(e){super({method:U.POST}),this.parameters=e}operation(){return j.PNCreateDataSyncRelationshipOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.entityAId?this.parameters.entityBId?this.parameters.class?this.parameters.data?this.parameters.data.classVersion?void 0:"Relationship class version cannot be empty":"Relationship data cannot be empty":"Relationship class cannot be empty":"Entity B id cannot be empty":"Entity A id cannot be empty"}get headers(){var e;const t=(e=super.headers)!==null&&e!==void 0?e:{};return Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.relationship+json;version=1"})}get path(){const{keySet:{subscribeKey:e}}=this.parameters;return`/v1/datasync/subkeys/${e}/relationships`}get body(){const{id:e,class:t,entityAId:s,entityBId:n,data:r}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign(Object.assign(Object.assign({},e!==void 0?{id:e}:{}),{entityAId:s,entityBId:n,relationshipClass:t,relationshipClassVersion:r.classVersion}),r.status!==void 0?{status:r.status}:{}),r.payload!==void 0?{payload:r.payload}:{})})}}class ur extends E{constructor(e){var t;super(),this.parameters=e,(t=e.limit)!==null&&t!==void 0||(e.limit=20)}operation(){return j.PNGetDataSyncRelationshipsOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.class)return"Relationship class cannot be empty"}get path(){return`/v1/datasync/subkeys/${this.parameters.keySet.subscribeKey}/relationships`}get queryParameters(){const{class:e,classVersion:t,entityAId:s,entityBId:n,cursor:r,limit:i,filter:o,filterFast:c,sort:u}=this.parameters,d=He(u);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({relationship_class:e},t!==void 0?{relationship_class_version:`${t}`}:{}),s?{entity_a_id:s}:{}),n?{entity_b_id:n}:{}),r?{cursor:r}:{}),i?{limit:`${i}`}:{}),o?{filter:o}:{}),c?{filter_fast:c}:{}),d.length?{sort:d}:{})}}class lr extends E{constructor(e){super({method:U.PUT}),this.parameters=e}operation(){return j.PNSetDataSyncRelationshipOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.id?this.parameters.entityAId?this.parameters.entityBId?this.parameters.data?this.parameters.data.classVersion?void 0:"Relationship class version cannot be empty":"Relationship data cannot be empty":"Entity B id cannot be empty":"Entity A id cannot be empty":"Relationship id cannot be empty"}get headers(){var e;let t=(e=super.headers)!==null&&e!==void 0?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.relationship+json;
41version=1"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/relationships/${I(t)}`}get body(){const{entityAId:e,entityBId:t,data:s}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign({entityAId:e,entityBId:t,relationshipClassVersion:s.classVersion},s.status!==void 0?{status:s.status}:{}),s.payload!==void 0?{payload:s.payload}:{})})}}class hr extends E{constructor(e){super({method:U.DELETE}),this.parameters=e}operation(){return j.PNRemoveDataSyncRelationshipOperation}validate(){if(!this.parameters.id)return"Relationship id cannot be empty"}get headers(){var e;let t=(e=super.headers)!==null&&e!==void 0?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.keys(t).length>0?t:void 0}parse(e){return g(this,void 0,void 0,(function*(){return{status:e.status}}))}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/relationships/${I(t)}`}}class dr extends E{constructor(e){super({method:U.PATCH}),this.parameters=e}operation(){return j.PNUpdateDataSyncRelationshipOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Relationship id cannot be empty";const{add:e,replace:t,remove:s,move:n,copy:r,test:i}=this.parameters,o=e&&Object.keys(e).length>0,c=t&&Object.keys(t).length>0,u=s&&s.length>0,d=n&&n.length>0,l=r&&r.length>0,h=i&&Object.keys(i).length>0;return o||c||u||d||l||h?void 0:"At least one of add, replace, remove, move, copy, or test must be provided"}get headers(){var e;let t=(e=super.headers)!==null&&e!==void 0?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json-patch+json"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/relationships/${I(t)}`}get body(){const{add:e,replace:t,remove:s,move:n,copy:r,test:i}=this.parameters,o=Be({add:e,replace:t,remove:s,move:n,copy:r,test:i});return JSON.stringify(o)}}class pr extends E{constructor(e){super(),this.parameters=e}operation(){return j.PNGetDataSyncRelationshipOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Relationship id cannot be empty"}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/relationships/${I(t)}`}}class gr extends E{constructor(e){super({method:U.POST}),this.parameters=e}operation(){return j.PNCreateDataSyncEntityOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.class?this.parameters.data?this.parameters.data.classVersion===void 0||this.parameters.data.classVersion===null?"Entity class version cannot be empty":void 0:"Entity data cannot be empty":"Entity class cannot be empty"}get headers(){var e;const t=(e=super.headers)!==null&&e!==void 0?e:{};return Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.entity+json;version=1"})}get path(){const{keySet:{subscribeKey:e}}=this.parameters;return`/v1/datasync/subkeys/${e}/entities`}get body(){const{id:e,class:t,classLevel:s,data:n}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},e!==void 0?{id:e}:{}),{entityClass:t,entityClassVersion:n.classVersion}),s!==void 0?{entityClassLevel:s}:{}),n.status!==void 0?{status:n.status}:{}),n.payload!==void 0?{payload:n.payload}:{})})}}class br extends E{constructor(e){var t;super(),this.parameters=e,(t=e.limit)!==null&&t!==void 0||(e.limit=20)}operation(){return j.PNGetDataSyncEntitiesOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.class)return"Entity class cannot be empty"}get path(){return`/v1/datasync/subkeys/${this.parameters.keySet.subscribeKey}/entities`}get queryParameters(){const{class:e,classVersion:t,classLevel:s,cursor:n,limit:r,filter:i,filterFast:o,sort:c}=this.parameters,u=He(c);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({entity_class:e},t!==void 0?{entity_class_version:`${t}`}:{}),s?{entity_class_level:s}:{}),n?{cursor:n}:{}),r?{limit:`${r}`}:{}),i?{filter:i}:{}),o?{filter_fast:o}:{}),u.length?{sort:u}:{})}}
41class yr extends E{constructor(e){super({method:U.PUT}),this.parameters=e}operation(){return j.PNSetDataSyncEntityOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.id?this.parameters.data?this.parameters.data.classVersion===void 0||this.parameters.data.classVersion===null?"Entity class version cannot be empty":void 0:"Entity data cannot be empty":"Entity id cannot be empty"}get headers(){var e;let t=(e=super.headers)!==null&&e!==void 0?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.entity+json;version=1"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/entities/${I(t)}`}get body(){const{data:e}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign({entityClassVersion:e.classVersion},e.status!==void 0?{status:e.status}:{}),e.payload!==void 0?{payload:e.payload}:{})})}}class mr extends E{constructor(e){super({method:U.DELETE}),this.parameters=e}operation(){return j.PNRemoveDataSyncEntityOperation}validate(){if(!this.parameters.id)return"Entity id cannot be empty"}get headers(){var e;let t=(e=super.headers)!==null&&e!==void 0?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.keys(t).length>0?t:void 0}parse(e){return g(this,void 0,void 0,(function*(){return{status:e.status}}))}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/entities/${I(t)}`}}class fr extends E{constructor(e){super({method:U.PATCH}),this.parameters=e}operation(){return j.PNUpdateDataSyncEntityOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Entity id cannot be empty";const{add:e,replace:t,remove:s,move:n,copy:r,test:i}=this.parameters,o=e&&Object.keys(e).length>0,c=t&&Object.keys(t).length>0,u=s&&s.length>0,d=n&&n.length>0,l=r&&r.length>0,h=i&&Object.keys(i).length>0;return o||c||u||d||l||h?void 0:"At least one of add, replace, remove, move, copy, or test must be provided"}get headers(){var e;let t=(e=super.headers)!==null&&e!==void 0?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json-patch+json"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/entities/${I(t)}`}get body(){const{add:e,replace:t,remove:s,move:n,copy:r,test:i}=this.parameters,o=Be({add:e,replace:t,remove:s,move:n,copy:r,test:i});return JSON.stringify(o)}}class vr extends E{constructor(e){super(),this.parameters=e}operation(){return j.PNGetDataSyncEntityOperation}parse(e){return g(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Entity id cannot be empty"}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/entities/${I(t)}`}}class Or{constructor(e,t){this.keySet=e.keySet,this.configuration=e,this.sendRequest=t}get logger(){return this.configuration.logger()}createEntity(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create Entity with parameters:"})));const s=new gr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getEntity(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Entity with parameters:"})));const s=new vr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getEntities(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Entities with parameters:"})));const s=new br(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setEntity(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set Entity with parameters:"})));const s=new yr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}updateEntity(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update Entity with parameters:"})));const s=new fr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeEntity(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Entity with parameters:"})));const s=new mr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}createRelationship(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create Relationship with parameters:"})));const s=new cr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getRelationship(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Relationship with parameters:"})));const s=new pr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getRelationships(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Relationships with parameters:"})));const s=new ur(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setRelationship(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set Relationship with parameters:"})));const s=new lr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}updateRelationship(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update Relationship with parameters:"})));const s=new dr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeRelationship(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Relationship with parameters:"})));const s=new hr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}createUser(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create User with parameters:"})));const s=new Hn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getUser(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get User with parameters:"})));const s=new Jn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getUsers(e,t){return g(this,void 0,void 0,(function*(){const s=e&&typeof e!="function"?e:{};t!=null||(t=typeof e=="function"?e:void 0),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},s),details:"Get Users with parameters:"})));const n=new Bn(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setUser(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set User with parameters:"})));const s=new Wn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}updateUser(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update User with parameters:"})));const s=new zn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeUser(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove User with parameters:"})));const s=new Vn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}createChannel(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create Channel with parameters:"})));const s=new Xn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getChannel(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Channel with parameters:"})));const s=new tr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getChannels(e,t){return g(this,void 0,void 0,(function*(){const s=e&&typeof e!="function"?e:{};t!=null||(t=typeof e=="function"?e:void 0),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},s),details:"Get Channels with parameters:"})));const n=new Qn(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setChannel(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set Channel with parameters:"})));const s=new Yn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}updateChannel(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update Channel with parameters:"})));const s=new er(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannel(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Channel with parameters:"})));const s=new Zn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}createMembership(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create Membership with parameters:"})));const s=new sr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getMembership(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Membership with parameters:"})));const s=new or(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getMemberships(e,t){return g(this,void 0,void 0,(function*(){const s=e&&typeof e!="function"?e:{};t!=null||(t=typeof e=="function"?e:void 0),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},s),details:"Get Memberships with parameters:"})));const n=new nr(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setMembership(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set Membership with parameters:"})));const s=new rr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}updateMembership(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update Membership with parameters:"})));const s=new ar(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeMembership(e,t){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Membership with parameters:"})));const s=new ir(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}
41class Sr extends E{constructor(){super()}operation(){return j.PNTimeOperation}parse(e){return g(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[0]}}))}get path(){return"/time/0"}}class jr extends E{constructor(e){super(),this.parameters=e}operation(){return j.PNDownloadFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return g(this,void 0,void 0,(function*(){const{cipherKey:t,crypto:s,cryptography:n,name:r,PubNubFile:i}=this.parameters,o=e.headers["content-type"];let c,u=e.body;return i.supportsEncryptFile&&(t||s)&&(t&&n?u=yield n.decrypt(t,u):!t&&s&&(c=yield s.decryptFile(i.create({data:u,name:r,mimeType:o}),i))),c||i.create({data:u,name:r,mimeType:o})}))}get path(){const{keySet:{subscribeKey:e},channel:t,id:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${I(t)}/files/${I(s)}/${I(n)}`}}class ce{static notificationPayload(e,t){return new Us(e,t)}static generateUUID(){return xe.createUUID()}constructor(e){if(this.eventHandleCapable={},this.entities={},this._configuration=e.configuration,this.cryptography=e.cryptography,this.tokenManager=e.tokenManager,this.transport=e.transport,this.crypto=e.crypto,this.logger.debug("PubNub",(()=>({messageType:"object",message:e.configuration,details:"Create with configuration:",ignoredKeys:(t,s)=>typeof s[t]=="function"||t.startsWith("_")||t==="keySet"||ye(t)}))),this._objects=new Ln(this._configuration,this.sendRequest.bind(this)),this._dataSync=new Or(this._configuration,this.sendRequest.bind(this)),this._channelGroups=new Nn(this._configuration.logger(),this._configuration.keySet,this.sendRequest.bind(this)),this._push=new Mn(this._configuration.logger(),this._configuration.keySet,this.sendRequest.bind(this)),this.eventDispatcher=new Jt,this._configuration.enableEventEngine){this.logger.debug("PubNub","Using new subscription loop management.");let t=this._configuration.getHeartbeatInterval();this.presenceState={},t&&(this.presenceEventEngine=new qs({heartbeat:(s,n)=>(this.logger.trace("PresenceEventEngine",(()=>({messageType:"object",message:Object.assign({},s),details:"Heartbeat with parameters:"}))),this.heartbeat(s,n)),leave:s=>{this.logger.trace("PresenceEventEngine",(()=>({messageType:"object",message:Object.assign({},s),details:"Leave with parameters:"}))),this.makeUnsubscribe(s,(()=>{}))},heartbeatDelay:()=>new Promise(((s,n)=>{t=this._configuration.getHeartbeatInterval(),t?setTimeout(s,1e3*t):n(new G("Heartbeat interval has been reset."))})),emitStatus:s=>this.emitStatus(s),config:this._configuration,presenceState:this.presenceState})),this.eventEngine=new Ks({handshake:s=>(this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},s),details:"Handshake with parameters:",ignoredKeys:["abortSignal","crypto","timeout","keySet","getFileUrl"]}))),this.subscribeHandshake(s)),receiveMessages:s=>(this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},s),details:"Receive messages with parameters:",ignoredKeys:["abortSignal","crypto","timeout","keySet","getFileUrl"]}))),this.subscribeReceiveMessages(s)),delay:s=>new Promise((n=>setTimeout(n,s))),join:s=>{var n,r;this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},s),details:"Join with parameters:"}))),s&&((n=s.channels)!==null&&n!==void 0?n:[]).length===0&&((r=s.groups)!==null&&r!==void 0?r:[]).length===0?this.logger.trace("EventEngine","Ignoring 'join' announcement request."):this.join(s)},leave:s=>{var n,r;this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},s),details:"Leave with parameters:"}))),s&&((n=s.channels)!==null&&n!==void 0?n:[]).length===0&&((r=s.groups)!==null&&r!==void 0?r:[]).length===0?this.logger.trace("EventEngine","Ignoring 'leave' announcement request."):this.leave(s)},leaveAll:s=>{this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},s),details:"Leave all with parameters:"}))),this.leaveAll(s)},presenceReconnect:s=>{this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},s),details:"Reconnect with parameters:"}))),this.presenceReconnect(s)},presenceDisconnect:s=>{this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},s),details:"Disconnect with parameters:"}))),this.presenceDisconnect(s)},presenceState:this.presenceState,config:this._configuration,emitMessages:(s,n)=>{try{this.logger.debug("EventEngine",(()=>({messageType:"object",message:n.map((r=>{const i=r.type===x.Message||r.type===x.Signal?ht(r.data.message):void 0;return i?{type:r.type,data:Object.assign(Object.assign({},r.data),{pn_mfp:i})}:r})),details:"Received events:"}
41))),n.forEach((r=>this.emitEvent(s,r)))}catch(r){const i={error:!0,category:M.PNUnknownCategory,errorData:r,statusCode:0};this.emitStatus(i)}},emitStatus:s=>this.emitStatus(s)})}else this.logger.debug("PubNub","Using legacy subscription loop management."),this.subscriptionManager=new Ms(this._configuration,((t,s)=>{try{this.emitEvent(t,s)}catch(n){const r={error:!0,category:M.PNUnknownCategory,errorData:n,statusCode:0};this.emitStatus(r)}}),this.emitStatus.bind(this),((t,s)=>{this.logger.trace("SubscriptionManager",(()=>({messageType:"object",message:Object.assign({},t),details:"Subscribe with parameters:",ignoredKeys:["crypto","timeout","keySet","getFileUrl"]}))),this.makeSubscribe(t,s)}),((t,s)=>(this.logger.trace("SubscriptionManager",(()=>({messageType:"object",message:Object.assign({},t),details:"Heartbeat with parameters:",ignoredKeys:["crypto","timeout","keySet","getFileUrl"]}))),this.heartbeat(t,s))),((t,s)=>{this.logger.trace("SubscriptionManager",(()=>({messageType:"object",message:Object.assign({},t),details:"Leave with parameters:"}))),this.makeUnsubscribe(t,s)}),this.time.bind(this))}get configuration(){return this._configuration}get _config(){return this.configuration}get authKey(){var e;return(e=this._configuration.authKey)!==null&&e!==void 0?e:void 0}getAuthKey(){return this.authKey}setAuthKey(e){this.logger.debug("PubNub","Auth key updated."),this._configuration.setAuthKey(e),this.onAuthenticationChange&&this.onAuthenticationChange(e)}get userId(){return this._configuration.userId}set userId(e){if(!e||typeof e!="string"||e.trim().length===0){const t=new Error("Missing or invalid userId parameter. Provide a valid string userId");throw this.logger.error("PubNub",(()=>({messageType:"error",message:t}))),t}this.logger.debug("PubNub",`Set user ID: ${e}`),this._configuration.userId=e,this.onUserIdChange&&this.onUserIdChange(this._configuration.userId)}getUserId(){return this._configuration.userId}setUserId(e){this.userId=e}get filterExpression(){var e;return(e=this._configuration.getFilterExpression())!==null&&e!==void 0?e:void 0}getFilterExpression(){return this.filterExpression}set filterExpression(e){this.logger.debug("PubNub",`Set filter expression: ${e}`),this._configuration.setFilterExpression(e)}setFilterExpression(e){this.logger.debug("PubNub",`Set filter expression: ${e}`),this.filterExpression=e}get cipherKey(){return this._configuration.getCipherKey()}set cipherKey(e){this._configuration.setCipherKey(e)}setCipherKey(e){this.logger.debug("PubNub","Cipher key updated."),this.cipherKey=e}set heartbeatInterval(e){var t;this.logger.debug("PubNub",`Set heartbeat interval: ${e}`),this._configuration.setHeartbeatInterval(e),this.onHeartbeatIntervalChange&&this.onHeartbeatIntervalChange((t=this._configuration.getHeartbeatInterval())!==null&&t!==void 0?t:0)}setHeartbeatInterval(e){this.heartbeatInterval=e}get logger(){return this._configuration.logger()}getVersion(){return this._configuration.getVersion()}_addPnsdkSuffix(e,t){this.logger.debug("PubNub",`Add '${e}' 'pnsdk' suffix: ${t}`),this._configuration._addPnsdkSuffix(e,t)}getUUID(){return this.userId}setUUID(e){this.logger.warn("PubNub","'setUserId` is deprecated, please use 'setUserId' or 'userId' setter instead."),this.logger.debug("PubNub",`Set UUID: ${e}`),this.userId=e}get customEncrypt(){return this._configuration.getCustomEncrypt()}get customDecrypt(){return this._configuration.getCustomDecrypt()}channel(e){let t=this.entities[`${e}_ch`];return t||(t=this.entities[`${e}_ch`]=new Sn(e,this)),t}channelGroup(e){let t=this.entities[`${e}_chg`];return t||(t=this.entities[`${e}_chg`]=new vn(e,this)),t}channelMetadata(e){let t=this.entities[`${e}_chm`];return t||(t=this.entities[`${e}_chm`]=new fn(e,this)),t}userMetadata(e){let t=this.entities[`${e}_um`];return t||(t=this.entities[`${e}_um`]=new On(e,this)),t}dataSyncUser(e){let t=this.entities[`${e}_dsu`];return t||(t=this.entities[`${e}_dsu`]=new It(e,this)),t}
41dataSyncChannel(e){let t=this.entities[`${e}_dsc`];return t||(t=this.entities[`${e}_dsc`]=new Tt(e,this)),t}dataSyncMembership(e){let t=this.entities[`${e}_dsm`];return t||(t=this.entities[`${e}_dsm`]=new Et(e,this)),t}dataSyncEntity(e){let t=this.entities[`${e}_dse`];return t||(t=this.entities[`${e}_dse`]=new _t(e,this)),t}dataSyncRelationship(e){let t=this.entities[`${e}_dsr`];return t||(t=this.entities[`${e}_dsr`]=new Nt(e,this)),t}subscriptionSet(e){var t,s;{const n=[];return(t=e.channels)===null||t===void 0||t.forEach((r=>n.push(this.channel(r)))),(s=e.channelGroups)===null||s===void 0||s.forEach((r=>n.push(this.channelGroup(r)))),new we({client:this,entities:n,options:e.subscriptionOptions})}}sendRequest(e,t){return g(this,void 0,void 0,(function*(){const s=e.validate();if(s){const d=(n=s,Ut(Object.assign({message:n},{}),M.PNValidationErrorCategory));if(this.logger.error("PubNub",(()=>({messageType:"error",message:d}))),t)return t(d,null);throw new G("Validation failed, check status for details",d)}var n;const r=e.request(),i=e.operation();r.formData&&r.formData.length>0||i===j.PNDownloadFileOperation?r.timeout=this._configuration.getFileTimeout():i===j.PNSubscribeOperation||i===j.PNReceiveMessagesOperation?r.timeout=this._configuration.getSubscribeTimeout():r.timeout=this._configuration.getTransactionTimeout();const o={error:!1,operation:i,category:M.PNAcknowledgmentCategory,statusCode:0},[c,u]=this.transport.makeSendable(r);return e.cancellationController=u||null,c.then((d=>{if(o.statusCode=d.status,d.status!==200&&d.status!==204){const l=ce.decoder.decode(d.body),h=d.headers["content-type"];if(h||h.indexOf("javascript")!==-1||h.indexOf("json")!==-1){const y=JSON.parse(l);typeof y=="object"&&"error"in y&&y.error&&typeof y.error=="object"&&(o.errorData=y.error)}else o.responseText=l}return e.parse(d)})).then((d=>t?t(o,d):d)).catch((d=>{const l=d instanceof q?d:q.create(d);if(t)return l.category!==M.PNCancelledCategory&&this.logger.error("PubNub",(()=>({messageType:"error",message:l.toPubNubError(i,"REST API request processing error, check status for details")}))),t(l.toStatus(i),null);const h=l.toPubNubError(i,"REST API request processing error, check status for details");throw l.category!==M.PNCancelledCategory&&this.logger.error("PubNub",(()=>({messageType:"error",message:h}))),h}))}))}destroy(e=!1){this.logger.info("PubNub","Destroying PubNub client."),this._globalSubscriptionSet&&(this._globalSubscriptionSet.invalidate(!0),this._globalSubscriptionSet=void 0),Object.values(this.eventHandleCapable).forEach((t=>t.invalidate(!0))),this.eventHandleCapable={},this.subscriptionManager?(this.subscriptionManager.unsubscribeAll(e),this.subscriptionManager.disconnect()):this.eventEngine&&this.eventEngine.unsubscribeAll(e),this.presenceEventEngine&&this.presenceEventEngine.leaveAll(e)}stop(){this.logger.warn("PubNub","'stop' is deprecated, please use 'destroy' instead."),this.destroy()}publish(e,t){return g(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Publish with parameters:"})));const s=e.replicate===!1&&e.storeInHistory===!1,n=new Ls(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()})),r=i=>{i&&this.logger.debug("PubNub",`${s?"Fire":"Publish"} success with timetoken: ${i.timetoken}`)};return t?this.sendRequest(n,((i,o)=>{r(o),t(i,o)})):this.sendRequest(n).then((i=>(r(i),i)))}}))}signal(e,t){return g(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Signal with parameters:"})));const s=new Hs(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=r=>{r&&this.logger.debug("PubNub",`Publish success with timetoken: ${r.timetoken}`)};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)})):this.sendRequest(s).then((r=>(n(r),r)))}}))}fire(e,t){return g(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fire with parameters:"}))),t!=null||(t=()=>{}),this.publish(Object.assign(Object.assign({}
41,e),{replicate:!1,storeInHistory:!1}),t)}))}get globalSubscriptionSet(){return this._globalSubscriptionSet||(this._globalSubscriptionSet=this.subscriptionSet({})),this._globalSubscriptionSet}get subscriptionTimetoken(){return this.subscriptionManager?this.subscriptionManager.subscriptionTimetoken:this.eventEngine?this.eventEngine.subscriptionTimetoken:void 0}getSubscribedChannels(){return this.subscriptionManager?this.subscriptionManager.subscribedChannels:this.eventEngine?this.eventEngine.getSubscribedChannels():[]}getSubscribedChannelGroups(){return this.subscriptionManager?this.subscriptionManager.subscribedChannelGroups:this.eventEngine?this.eventEngine.getSubscribedChannelGroups():[]}registerEventHandleCapable(e,t,s){{let n;this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign(Object.assign({subscription:e},t?{cursor:t}:[]),s?{subscriptions:s}:{}),details:"Register event handle capable:"}))),this.eventHandleCapable[e.state.id]||(this.eventHandleCapable[e.state.id]=e),s&&s.length!==0?(n=new ge({}),s.forEach((i=>n.add(i.subscriptionInput(!1))))):n=e.subscriptionInput(!1);const r={};r.channels=n.channels,r.channelGroups=n.channelGroups,t&&(r.timetoken=t.timetoken),this.subscriptionManager?this.subscriptionManager.subscribe(r):this.eventEngine&&this.eventEngine.subscribe(r)}}unregisterEventHandleCapable(e,t){{if(!this.eventHandleCapable[e.state.id])return;const s=[];this.logger.trace("PubNub",(()=>({messageType:"object",message:{subscription:e,subscriptions:t},details:"Unregister event handle capable:"})));let n,r=!t||t.length===0;if(!r&&e instanceof we&&e.subscriptions.length===t?.length&&(r=e.subscriptions.every((o=>t.includes(o)))),r&&delete this.eventHandleCapable[e.state.id],t&&t.length!==0?(n=new ge({}),t.forEach((o=>{const c=o.subscriptionInput(!0);c.isEmpty?s.push(o):n.add(c)}))):(n=e.subscriptionInput(!0),n.isEmpty&&s.push(e)),s.length>0&&this.logger.trace("PubNub",(()=>{const o=[];return s[0]instanceof we?s[0].subscriptions.forEach((c=>o.push(c.state.entity))):s.forEach((c=>o.push(c.state.entity))),{messageType:"object",message:{entities:o},details:"Can't unregister event handle capable because entities still in use:"}})),n.isEmpty)return;{const o=[],c=[];if(Object.values(this.eventHandleCapable).forEach((u=>{const d=u.subscriptionInput(!1),l=d.channelGroups,h=d.channels;o.push(...n.channelGroups.filter((y=>l.includes(y)))),c.push(...n.channels.filter((y=>h.includes(y))))})),(c.length>0||o.length>0)&&(this.logger.trace("PubNub",(()=>{const u=[],d=h=>{const y=h.subscriptionNames(!0),p=h.subscriptionType===Me.Channel?c:o;y.some((b=>p.includes(b)))&&u.push(h)};Object.values(this.eventHandleCapable).forEach((h=>{h instanceof we?h.subscriptions.forEach((y=>{d(y.state.entity)})):h instanceof nt&&d(h.state.entity)}));let l="Some entities still in use:";return c.length+o.length===n.length&&(l="Can't unregister event handle capable because entities still in use:"),{messageType:"object",message:{entities:u},details:l}})),n.remove(new ge({channels:c,channelGroups:o})),n.isEmpty))return}const i={};i.channels=n.channels,i.channelGroups=n.channelGroups,this.subscriptionManager?this.subscriptionManager.unsubscribe(i):this.eventEngine&&this.eventEngine.unsubscribe(i)}}subscribe(e){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Subscribe with parameters:"})));const t=this.subscriptionSet(Object.assign(Object.assign({},e),{subscriptionOptions:{receivePresenceEvents:e.withPresence}}));this.globalSubscriptionSet.addSubscriptionSet(t),t.dispose();const s=typeof e.timetoken=="number"?`${e.timetoken}`:e.timetoken;this.globalSubscriptionSet.subscribe({timetoken:s})}}makeSubscribe(e,t){{this._configuration.isSharedWorkerEnabled()||(e.onDemand=!1);const s=new zt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));if(this.sendRequest(s,((n,r)=>{var i;this.subscriptionManager&&((i=this.subscriptionManager.abort)===null||i===void 0?void 0:i.identifier)===s.requestIdentifier&&(this.subscriptionManager.abort=null),t(n,r)})),this.subscriptionManager){const n=()=>s.abort("Cancel long-poll subscribe request");n.identifier=s.requestIdentifier,this.subscriptionManager.abort=n}}}unsubscribe(e){{if(this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Unsubscribe with parameters:"}))),!this._globalSubscriptionSet)return void this.logger.debug("PubNub","There are no active subscriptions. Ignore.");const t=this.globalSubscriptionSet.subscriptions.filter((s=>{var n,r;const i=s.subscriptionInput(!1);if(i.isEmpty)return!1;for(const o of(n=e.channels)!==null&&n!==void 0?n:[])if(i.contains(o))return!0;for(const o of(r=e.channelGroups)!==null&&r!==void 0?r:[])if(i.contains(o))return!0}));t.length>0&&this.globalSubscriptionSet.removeSubscriptions(t)}}makeUnsubscribe(e,t){{let{channels:s,channelGroups:n}=e;if(this._configuration.getKeepPresenceChannelsInPresenceRequests()||(n&&(n=n.filter((r=>!r.endsWith("-pnpres")))),s&&(s=s.filter((r=>!r.endsWith("-pnpres"))))),(n??[]).length===0&&(s??[]).length===0)return t({error:!1,operation:j.PNUnsubscribeOperation,category:M.PNAcknowledgmentCategory,statusCode:200});this.sendRequest(new Qs({channels:s,channelGroups:n,keySet:this._configuration.keySet}),t)}}unsubscribeAll(){this.logger.debug("PubNub","Unsubscribe all channels and groups"),this._globalSubscriptionSet&&this._globalSubscriptionSet.invalidate(!1),Object.values(this.eventHandleCapable).forEach((e=>e.invalidate(!1))),this.eventHandleCapable={},this.subscriptionManager?this.subscriptionManager.unsubscribeAll():this.eventEngine&&this.eventEngine.unsubscribeAll()}disconnect(e=!1){this.logger.debug("PubNub",`Disconnect (while offline? ${e?"yes":"no"})`),this.subscriptionManager?this.subscriptionManager.disconnect():this.eventEngine&&this.eventEngine.disconnect(e)}reconnect(e){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Reconnect with parameters:"}))),this.subscriptionManager?this.subscriptionManager.reconnect():this.eventEngine&&this.eventEngine.reconnect(e??{})}subscribeHandshake(e){return g(this,void 0,void 0,(function*(){{this._configuration.isSharedWorkerEnabled()||(e.onDemand=!1);const t=new Ws(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((n=>{t.abort("Cancel subscribe handshake request")}));return this.sendRequest(t).then((n=>(s(),n.cursor)))}}))}subscribeReceiveMessages(e){return g(this,void 0,void 0,(function*(){{this._configuration.isSharedWorkerEnabled()||(e.onDemand=!1);const t=new Bs(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((n=>{t.abort("Cancel long-poll subscribe request")}));return this.sendRequest(t).then((n=>(s(),n)))}}))}getMessageActions(e,t){return g(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get message actions with parameters:"})));const s=new sn(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=r=>{r&&this.logger.debug("PubNub",`Get message actions success. Received ${r.data.length} message actions.`)};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)}
41)):this.sendRequest(s).then((r=>(n(r),r)))}}))}addMessageAction(e,t){return g(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Add message action with parameters:"})));const s=new nn(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=r=>{r&&this.logger.debug("PubNub",`Message action add success. Message action added with timetoken: ${r.data.actionTimetoken}`)};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)})):this.sendRequest(s).then((r=>(n(r),r)))}}))}removeMessageAction(e,t){return g(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove message action with parameters:"})));const s=new rn(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=r=>{r&&this.logger.debug("PubNub",`Message action remove success. Removed message action with ${e.actionTimetoken} timetoken.`)};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)})):this.sendRequest(s).then((r=>(n(r),r)))}}))}fetchMessages(e,t){return g(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fetch messages with parameters:"})));const s=new Pt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),n=r=>{if(!r)return;const i=Object.values(r.channels).reduce(((o,c)=>o+c.length),0);this.logger.debug("PubNub",`Fetch messages success. Received ${i} messages.`)};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)})):this.sendRequest(s).then((r=>(n(r),r)))}}))}deleteMessages(e,t){return g(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Delete messages with parameters:"})));const s=new en(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=r=>{r&&this.logger.debug("PubNub","Delete messages success.")};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)})):this.sendRequest(s).then((r=>(n(r),r)))}}))}messageCounts(e,t){return g(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get messages count with parameters:"})));const s=new tn(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=r=>{if(!r)return;const i=Object.values(r.channels).reduce(((o,c)=>o+c),0);this.logger.debug("PubNub",`Get messages count success. There are ${i} messages since provided reference timetoken${e.channelTimetokens?e.channelTimetokens.join(","):""}.`)};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)})):this.sendRequest(s).then((r=>(n(r),r)))}}))}history(e,t){return g(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fetch history with parameters:"})));const s=new wt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()})),n=r=>{r&&this.logger.debug("PubNub",`Fetch history success. Received ${r.messages.length} messages.`)};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)})):this.sendRequest(s).then((r=>(n(r),r)))}}))}hereNow(e,t){return g(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Here now with parameters:"})));const s=new Zs(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=r=>{r&&this.logger.debug("PubNub",`Here now success. There are ${r.totalOccupancy} participants in ${r.totalChannels} channels.`)};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)})):this.sendRequest(s).then((r=>(n(r),r)))}}))}whereNow(e,t){return g(this,void 0,void 0,(function*(){var s;{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Where now with parameters:"})));const n=new Ys({uuid:(s=e.uuid)!==null&&s!==void 0?s:this._configuration.userId,keySet:this._configuration.keySet}),r=i=>{i&&this.logger.debug("PubNub",`Where now success. Currently present in ${i.channels.length} channels.`)};return t?this.sendRequest(n,((i,o)=>{r(o),t(i,o)})):this.sendRequest(n).then((i=>(r(i),i)))}}))}getState(e,t){return g(this,void 0,void 0,(function*(){var s;{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get presence state with parameters:"})));const n=new Js(Object.assign(Object.assign({},e),{uuid:(s=e.uuid)!==null&&s!==void 0?s:this._configuration.userId,keySet:this._configuration.keySet})),r=i=>{i&&this.logger.debug("PubNub",`Get presence state success. Received presence state for ${Object.keys(i.channels).length} channels.`)};return t?this.sendRequest(n,((i,o)=>{r(o),t(i,o)})):this.sendRequest(n).then((i=>(r(i),i)))}}))}setState(e,t){return g(this,void 0,void 0,(function*(){var s,n;{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set presence state with parameters:"})));const{keySet:r,userId:i}=this._configuration,o=this._configuration.getPresenceTimeout();let c;if(this._configuration.enableEventEngine&&this.presenceState){const d=this.presenceState;
41(s=e.channels)===null||s===void 0||s.forEach((l=>d[l]=e.state)),"channelGroups"in e&&((n=e.channelGroups)===null||n===void 0||n.forEach((l=>d[l]=e.state))),this.onPresenceStateChange&&this.onPresenceStateChange(this.presenceState)}c="withHeartbeat"in e&&e.withHeartbeat?new kt(Object.assign(Object.assign({},e),{keySet:r,heartbeat:o})):new Xs(Object.assign(Object.assign({},e),{keySet:r,uuid:i}));const u=d=>{d&&this.logger.debug("PubNub","Set presence state success."+(c instanceof kt?" Presence state has been set using heartbeat endpoint.":""))};return this.subscriptionManager&&(this.subscriptionManager.setState(e),this.onPresenceStateChange&&this.onPresenceStateChange(this.subscriptionManager.presenceState)),t?this.sendRequest(c,((d,l)=>{u(l),t(d,l)})):this.sendRequest(c).then((d=>(u(d),d)))}}))}presence(e){var t;this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Change presence with parameters:"}))),(t=this.subscriptionManager)===null||t===void 0||t.changePresence(e)}heartbeat(e,t){return g(this,void 0,void 0,(function*(){var s;{this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Heartbeat with parameters:"})));let{channels:n,channelGroups:r}=e;if(r&&(r=r.filter((u=>!u.endsWith("-pnpres")))),n&&(n=n.filter((u=>!u.endsWith("-pnpres")))),(r??[]).length===0&&(n??[]).length===0){const u={error:!1,operation:j.PNHeartbeatOperation,category:M.PNAcknowledgmentCategory,statusCode:200};return this.logger.trace("PubNub","There are no active subscriptions. Ignore."),t?t(u,{}):Promise.resolve(u)}const i=new kt(Object.assign(Object.assign({},e),{channels:[...new Set(n)],channelGroups:[...new Set(r)],keySet:this._configuration.keySet})),o=u=>{u&&this.logger.trace("PubNub","Heartbeat success.")},c=(s=e.abortSignal)===null||s===void 0?void 0:s.subscribe((u=>{i.abort("Cancel long-poll subscribe request")}));return t?this.sendRequest(i,((u,d)=>{o(d),c&&c(),t(u,d)})):this.sendRequest(i).then((u=>(o(u),c&&c(),u)))}}))}join(e){var t,s;this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Join with parameters:"}))),e&&((t=e.channels)!==null&&t!==void 0?t:[]).length===0&&((s=e.groups)!==null&&s!==void 0?s:[]).length===0?this.logger.trace("PubNub","Ignoring 'join' announcement request."):this.presenceEventEngine?this.presenceEventEngine.join(e):this.heartbeat(Object.assign(Object.assign({channels:e.channels,channelGroups:e.groups},this._configuration.maintainPresenceState&&this.presenceState&&Object.keys(this.presenceState).length>0&&{state:this.presenceState}),{heartbeat:this._configuration.getPresenceTimeout()}),(()=>{}))}presenceReconnect(e){this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Presence reconnect with parameters:"}))),this.presenceEventEngine?this.presenceEventEngine.reconnect():this.heartbeat(Object.assign(Object.assign({channels:e.channels,channelGroups:e.groups},this._configuration.maintainPresenceState&&{state:this.presenceState}),{heartbeat:this._configuration.getPresenceTimeout()}),(()=>{}))}leave(e){var t,s,n;this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave with parameters:"}))),e&&((t=e.channels)!==null&&t!==void 0?t:[]).length===0&&((s=e.groups)!==null&&s!==void 0?s:[]).length===0?this.logger.trace("PubNub","Ignoring 'leave' announcement request."):this.presenceEventEngine?(n=this.presenceEventEngine)===null||n===void 0||n.leave(e):this.makeUnsubscribe({channels:e.channels,channelGroups:e.groups},(()=>{}))}leaveAll(e={}){this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave all with parameters:"}))),this.presenceEventEngine?this.presenceEventEngine.leaveAll(!!e.isOffline):e.isOffline||this.makeUnsubscribe({channels:e.channels,channelGroups:e.groups},(()=>{}))}presenceDisconnect(e){this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Presence disconnect parameters:"}))),this.presenceEventEngine?this.presenceEventEngine.disconnect(!!e.isOffline):e.isOffline||this.makeUnsubscribe({channels:e.channels,channelGroups:e.groups},(()=>{}))}grantToken(e,t){return g(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Grant token permissions with parameters:",ignoredKeys:ye})));const s=new pn(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=r=>{r&&this.logger.debug("PubNub","Grant token permissions success.")};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)}
41)):this.sendRequest(s).then((r=>(n(r),r)))}}))}revokeToken(e,t){return g(this,void 0,void 0,(function*(){{this.logger.debug("PubNub","Revoke token permissions.");const s=new dn({token:e,keySet:this._configuration.keySet}),n=r=>{r&&this.logger.debug("PubNub","Revoke token permissions success.")};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)})):this.sendRequest(s).then((r=>(n(r),r)))}}))}get token(){return this.tokenManager&&this.tokenManager.getToken()}getToken(){return this.token}set token(e){this.tokenManager&&this.tokenManager.setToken(e),this.onAuthenticationChange&&this.onAuthenticationChange(e)}setToken(e){this.logger.debug("PubNub","Access token updated."),this.token=e}parseToken(e){return this.logger.debug("PubNub","Parse access token."),this.tokenManager&&this.tokenManager.parseToken(e)}grant(e,t){return g(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Grant auth key(s) permissions with parameters:",ignoredKeys:ye})));const s=new gn(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=r=>{r&&this.logger.debug("PubNub","Grant auth key(s) permissions success.")};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)})):this.sendRequest(s).then((r=>(n(r),r)))}}))}audit(e,t){return g(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Audit auth key(s) permissions with parameters:",ignoredKeys:ye})));const s=new yn(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=r=>{r&&this.logger.debug("PubNub","Audit auth key(s) permissions success.")};return t?this.sendRequest(s,((r,i)=>(n(i),t(r,i)))):this.sendRequest(s).then((r=>(n(r),r)))}}))}get objects(){return this._objects}get dataSync(){return this._dataSync}fetchUsers(e,t){return g(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'fetchUsers' is deprecated. Use 'pubnub.objects.getAllUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&typeof e!="function"?e:{},details:"Fetch all User objects with parameters:"}))),this.objects._getAllUUIDMetadata(e,t)}))}fetchUser(e,t){return g(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'fetchUser' is deprecated. Use 'pubnub.objects.getUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&typeof e!="function"?e:{uuid:this.userId},details:`Fetch${e&&typeof e!="function"?"":" current"} User object with parameters:`}))),this.objects._getUUIDMetadata(e,t)}))}createUser(e,t){return g(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'createUser' is deprecated. Use 'pubnub.objects.setUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create User object with parameters:"}))),this.objects._setUUIDMetadata(e,t)}))}updateUser(e,t){return g(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'updateUser' is deprecated. Use 'pubnub.objects.setUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update User object with parameters:"}))),this.objects._setUUIDMetadata(e,t)}))}removeUser(e,t){return g(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'removeUser' is deprecated. Use 'pubnub.objects.removeUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&typeof e!="function"?e:{uuid:this.userId},details:`Remove${e&&typeof e!="function"?"":" current"} User object with parameters:`}))),this.objects._removeUUIDMetadata(e,t)}))}fetchSpaces(e,t){return g(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'fetchSpaces' is deprecated. Use 'pubnub.objects.getAllChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&typeof e!="function"?e:{},details:"Fetch all Space objects with parameters:"}))),this.objects._getAllChannelMetadata(e,t)}))}fetchSpace(e,t){return g(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'fetchSpace' is deprecated. Use 'pubnub.objects.getChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fetch Space object with parameters:"}))),this.objects._getChannelMetadata(e,t)}))}createSpace(e,t){return g(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'createSpace' is deprecated. Use 'pubnub.objects.setChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create Space object with parameters:"}))),this.objects._setChannelMetadata(e,t)}))}updateSpace(e,t){return g(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'updateSpace' is deprecated. Use 'pubnub.objects.setChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update Space object with parameters:"}))),this.objects._setChannelMetadata(e,t)}))}removeSpace(e,t){return g(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'removeSpace' is deprecated. Use 'pubnub.objects.removeChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Space object with parameters:"}))),this.objects._removeChannelMetadata(e,t)}))}fetchMemberships(e,t){return g(this,void 0,void 0,(function*(){return this.objects.fetchMemberships(e,t)}))}addMemberships(e,t){return g(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}updateMemberships(e,t){return g(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'addMemberships' is deprecated. Use 'pubnub.objects.setChannelMembers' or 'pubnub.objects.setMemberships' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update memberships with parameters:"}))),this.objects.addMemberships(e,t)}))}removeMemberships(e,t){return g(this,void 0,void 0,(function*(){var s,n,r;{if(this.logger.warn("PubNub","'removeMemberships' is deprecated. Use 'pubnub.objects.removeMemberships' or 'pubnub.objects.removeChannelMembers' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove memberships with parameters:"}))),"spaceId"in e){const c=e,u={channel:(s=c.spaceId)!==null&&s!==void 0?s:c.channel,uuids:(n=c.userIds)!==null&&n!==void 0?n:c.uuids,limit:0};return t?this.objects.removeChannelMembers(u,t):this.objects.removeChannelMembers(u)}const i=e,o={uuid:i.userId,channels:(r=i.spaceIds)!==null&&r!==void 0?r:i.channels,limit:0};return t?this.objects.removeMemberships(o,t):this.objects.removeMemberships(o)}}))}get channelGroups(){return this._channelGroups}get push(){return this._push}sendFile(e,t){return g(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.");this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Send file with parameters:"})));const s=new hn(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,fileUploadPublishRetryLimit:this._configuration.fileUploadPublishRetryLimit,file:e.file,sendRequest:this.sendRequest.bind(this),publishFile:this.publishFile.bind(this),crypto:this._configuration.getCryptoModule(),cryptography:this.cryptography?this.cryptography:void 0})),n={error:!1,operation:j.PNPublishFileOperation,category:M.PNAcknowledgmentCategory,statusCode:0},r=i=>{i&&this.logger.debug("PubNub",`Send file success. File shared with ${i.id} ID.`)};return s.process().then((i=>(n.statusCode=i.status,r(i),t?t(n,i):i))).catch((i=>{let o;throw i instanceof G?o=i.status:i instanceof q&&(o=i.toStatus(n.operation)),this.logger.error("PubNub",(()=>({messageType:"error",message:new G("File sending error. Check status for details",o)}))),t&&o&&t(o,null),new G("REST API request processing error. Check status for details",o)}))}}))}publishFile(e,t){return g(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.");this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Publish file message with parameters:"})));const s=new an(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()})),n=r=>{r&&this.logger.debug("PubNub",`Publish file message success. File message published with timetoken: ${r.timetoken}`)};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)}
41)):this.sendRequest(s).then((r=>(n(r),r)))}}))}listFiles(e,t){return g(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"List files with parameters:"})));const s=new un(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=r=>{r&&this.logger.debug("PubNub",`List files success. There are ${r.count} uploaded files.`)};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)})):this.sendRequest(s).then((r=>(n(r),r)))}}))}getFileUrl(e){var t;{const s=this.transport.request(new on(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})).request()),n=(t=s.queryParameters)!==null&&t!==void 0?t:{},r=Object.keys(n).map((i=>{const o=n[i];return Array.isArray(o)?o.map((c=>`${i}=${I(c)}`)).join("&"):`${i}=${I(o)}`})).join("&");return`${s.origin}${s.path}?${r}`}}downloadFile(e,t){return g(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.");this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Download file with parameters:"})));const s=new jr(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,cryptography:this.cryptography?this.cryptography:void 0,crypto:this._configuration.getCryptoModule()})),n=r=>{r&&this.logger.debug("PubNub","Download file success.")};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)})):yield this.sendRequest(s).then((r=>(n(r),r)))}}))}deleteFile(e,t){return g(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Delete file with parameters:"})));const s=new cn(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=r=>{r&&this.logger.debug("PubNub",`Delete file success. Deleted file with ${e.id} ID.`)};return t?this.sendRequest(s,((r,i)=>{n(i),t(r,i)})):this.sendRequest(s).then((r=>(n(r),r)))}}))}time(e){return g(this,void 0,void 0,(function*(){this.logger.debug("PubNub","Get service time.");const t=new Sr,s=n=>{n&&this.logger.debug("PubNub",`Get service time success. Current timetoken: ${n.timetoken}`)};return e?this.sendRequest(t,((n,r)=>{s(r),e(n,r)})):this.sendRequest(t).then((n=>(s(n),n)))}))}emitStatus(e){var t;(t=this.eventDispatcher)===null||t===void 0||t.handleStatus(e)}emitEvent(e,t){var s;this._globalSubscriptionSet&&this._globalSubscriptionSet.handleEvent(e,t),(s=this.eventDispatcher)===null||s===void 0||s.handleEvent(t),Object.values(this.eventHandleCapable).forEach((n=>{n!==this._globalSubscriptionSet&&n.handleEvent(e,t)}))}set onStatus(e){this.eventDispatcher&&(this.eventDispatcher.onStatus=e)}set onMessage(e){this.eventDispatcher&&(this.eventDispatcher.onMessage=e)}set onPresence(e){this.eventDispatcher&&(this.eventDispatcher.onPresence=e)}set onSignal(e){this.eventDispatcher&&(this.eventDispatcher.onSignal=e)}set onObjects(e){this.eventDispatcher&&(this.eventDispatcher.onObjects=e)}set onMessageAction(e){this.eventDispatcher&&(this.eventDispatcher.onMessageAction=e)}set onFile(e){this.eventDispatcher&&(this.eventDispatcher.onFile=e)}set onDataSync(e){this.eventDispatcher&&(this.eventDispatcher.onDataSync=e)}addListener(e){this.eventDispatcher&&this.eventDispatcher.addListener(e)}removeListener(e){this.eventDispatcher&&this.eventDispatcher.removeListener(e)}removeAllListeners(){this.eventDispatcher&&this.eventDispatcher.removeAllListeners()}encrypt(e,t){this.logger.warn("PubNub","'encrypt' is deprecated. Use cryptoModule instead.");const s=this._configuration.getCryptoModule();if(!t&&s&&typeof e=="string"){const n=s.encrypt(e);return typeof n=="string"?n:Je(n)}if(!this.crypto)throw new Error("Encryption error: cypher key not set");return this.crypto.encrypt(e,t)}decrypt(e,t){this.logger.warn("PubNub","'decrypt' is deprecated. Use cryptoModule instead.");const s=this._configuration.getCryptoModule();if(!t&&s){const n=s.decrypt(e);return n instanceof ArrayBuffer?JSON.parse(new TextDecoder().decode(n)):n}if(!this.crypto)throw new Error("Decryption error: cypher key not set");return this.crypto.decrypt(e,t)}encryptFile(e,t){return g(this,void 0,void 0,(function*(){var s;if(typeof e!="string"&&(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.");
41if(typeof e!="string"&&!this._configuration.getCryptoModule())throw new Error("File encryption error. Crypto module not configured.");if(typeof e=="string"){if(!this.cryptography)throw new Error("File encryption error. File encryption not available");return this.cryptography.encryptFile(e,t,this._configuration.PubNubFile)}return(s=this._configuration.getCryptoModule())===null||s===void 0?void 0:s.encryptFile(t,this._configuration.PubNubFile)}))}decryptFile(e,t){return g(this,void 0,void 0,(function*(){var s;if(typeof e!="string"&&(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(typeof e=="string"&&!this._configuration.getCryptoModule())throw new Error("File decryption error. Crypto module not configured.");if(typeof e=="string"){if(!this.cryptography)throw new Error("File decryption error. File decryption not available");return this.cryptography.decryptFile(e,t,this._configuration.PubNubFile)}return(s=this._configuration.getCryptoModule())===null||s===void 0?void 0:s.decryptFile(t,this._configuration.PubNubFile)}))}}ce.decoder=new TextDecoder,ce.OPERATIONS=j,ce.CATEGORIES=M,ce.Endpoint=B,ce.ExponentialRetryPolicy=Ye.ExponentialRetryPolicy,ce.LinearRetryPolicy=Ye.LinearRetryPolicy,ce.NoneRetryPolicy=Ye.None,ce.LogLevel=J;class kr{constructor(e,t){this.decode=e,this.base64ToBinary=t}decodeToken(e){let t="";e.length%4==3?t="=":e.length%4==2&&(t="==");const s=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,n=this.decode(this.base64ToBinary(s));return typeof n=="object"?n:void 0}}class We extends ce{constructor(e){var t;const s=e.subscriptionWorkerUrl!==void 0,n=fs(e),r=Object.assign(Object.assign({},n),{sdkFamily:"Web"});r.PubNubFile=ee;const i=ks(r,(m=>{if(m.cipherKey)return new oe({default:new Se(Object.assign(Object.assign({},m),m.logger?{}:{logger:i.logger()})),cryptors:[new ae({cipherKey:m.cipherKey})]})}));let o,c;e.subscriptionWorkerLogVerbosity?e.subscriptionWorkerLogLevel=J.Debug:e.subscriptionWorkerLogLevel===void 0&&(e.subscriptionWorkerLogLevel=J.None),e.subscriptionWorkerLogVerbosity!==void 0&&i.logger().warn("Configuration","'subscriptionWorkerLogVerbosity' is deprecated. Use 'subscriptionWorkerLogLevel' instead."),i.getCryptoModule()&&(i.getCryptoModule().logger=i.logger()),o=new Cs(new kr((m=>Wt(ys.decode(m))),ze)),(i.getCipherKey()||i.secretKey)&&(c=new Ht({secretKey:i.secretKey,cipherKey:i.getCipherKey(),useRandomIVs:i.getUseRandomIVs(),customEncrypt:i.getCustomEncrypt(),customDecrypt:i.getCustomDecrypt(),logger:i.logger()}));let u,d=()=>{},l=()=>{},h=()=>{},y=()=>{};u=new Q;let p=new me(i.logger(),r.transport);if(n.subscriptionWorkerUrl)try{const m=new Bt({clientIdentifier:i._instanceId,subscriptionKey:i.subscribeKey,userId:i.getUserId(),workerUrl:n.subscriptionWorkerUrl,sdkVersion:i.getVersion(),heartbeatInterval:i.getHeartbeatInterval(),announceSuccessfulHeartbeats:i.announceSuccessfulHeartbeats,announceFailedHeartbeats:i.announceFailedHeartbeats,workerOfflineClientsCheckInterval:r.subscriptionWorkerOfflineClientsCheckInterval,workerUnsubscribeOfflineClients:r.subscriptionWorkerUnsubscribeOfflineClients,workerLogLevel:r.subscriptionWorkerLogLevel,tokenManager:o,transport:p,logger:i.logger()});l=v=>m.onPresenceStateChange(v),d=v=>m.onHeartbeatIntervalChange(v),h=v=>m.onTokenChange(v),y=v=>m.onUserIdChange(v),p=m,n.subscriptionWorkerUnsubscribeOfflineClients&&typeof window<"u"&&window.addEventListener&&window.addEventListener("pagehide",(v=>{v.persisted||m.terminate()}),{once:!0})}catch(m){i.logger().error("PubNub",(()=>({messageType:"error",message:m})))}else s&&i.logger().warn("PubNub","SharedWorker not supported in this browser. Fallback to the original transport.");const b=new Ns({clientConfiguration:i,tokenManager:o,transport:p,shaHMAC:c?.HMACSHA256.bind(c)});if(super({configuration:i,transport:b,cryptography:u,tokenManager:o,crypto:c}),this.File=ee,this.onHeartbeatIntervalChange=d,this.onAuthenticationChange=h,this.onPresenceStateChange=l,this.onUserIdChange=y,p instanceof Bt){p.emitStatus=this.emitStatus.bind(this);const m=this.disconnect.bind(this);this.disconnect=v=>{p.disconnect(),m()}}
41((t=e.listenToBrowserNetworkEvents)===null||t===void 0||t)&&typeof window<"u"&&window.addEventListener&&(window.addEventListener("offline",(()=>{this.networkDownDetected()})),window.addEventListener("online",(()=>{this.networkUpDetected()})))}networkDownDetected(){this.logger.debug("PubNub","Network down detected"),this.emitStatus({category:We.CATEGORIES.PNNetworkDownCategory}),this._configuration.restore?this.disconnect(!0):this.destroy(!0)}networkUpDetected(){this.logger.debug("PubNub","Network up detected"),this.emitStatus({category:We.CATEGORIES.PNNetworkUpCategory}),this.reconnect()}}return We.CryptoModule=oe,We}))})(at)),at.exports}export{Cr as r};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.