gameglue 1.2.2 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +79 -16
- package/dist/gg.cjs.js +1 -1
- package/dist/gg.cjs.js.map +1 -1
- package/dist/gg.esm.js +1 -1
- package/dist/gg.esm.js.map +1 -1
- package/dist/gg.umd.js +1 -1
- package/dist/gg.umd.js.map +1 -1
- package/examples/flight-dashboard.html +69 -39
- package/package.json +1 -1
- package/src/auth.js +187 -86
- package/src/auth.spec.js +167 -77
- package/src/index.js +82 -44
- package/src/listener.js +16 -2
- package/src/listener.spec.js +139 -0
- package/src/test/setup.js +2 -1
- package/src/utils.js +3 -0
- package/src/utils.spec.js +14 -0
- package/dist/gg.sdk.js +0 -1
- /package/{babel.config.js → babel.config.cjs} +0 -0
- /package/{jest.config.js → jest.config.cjs} +0 -0
package/dist/gg.umd.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).GameGlue={})}(this,function(e){"use strict";var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function s(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function r(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var s=function e(){var s=!1;try{s=this instanceof e}catch{}return s?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};s.prototype=t.prototype}else s={};return Object.defineProperty(s,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(s,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})}),s}var i,n={exports:{}},o=r(Object.freeze({__proto__:null,default:{}}));function a(){return i||(i=1,function(e){e.exports=function(){var e=e||function(e,s){var r;if("undefined"!=typeof window&&window.crypto&&(r=window.crypto),"undefined"!=typeof self&&self.crypto&&(r=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(r=globalThis.crypto),!r&&"undefined"!=typeof window&&window.msCrypto&&(r=window.msCrypto),!r&&void 0!==t&&t.crypto&&(r=t.crypto),!r)try{r=o}catch(e){}var i=function(){if(r){if("function"==typeof r.getRandomValues)try{return r.getRandomValues(new Uint32Array(1))[0]}catch(e){}if("function"==typeof r.randomBytes)try{return r.randomBytes(4).readInt32LE()}catch(e){}}throw new Error("Native crypto module could not be used to get secure random number.")},n=Object.create||function(){function e(){}return function(t){var s;return e.prototype=t,s=new e,e.prototype=null,s}}(),a={},c=a.lib={},h=c.Base={extend:function(e){var t=n(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},u=c.WordArray=h.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=t!=s?t:4*e.length},toString:function(e){return(e||l).stringify(this)},concat:function(e){var t=this.words,s=e.words,r=this.sigBytes,i=e.sigBytes;if(this.clamp(),r%4)for(var n=0;n<i;n++){var o=s[n>>>2]>>>24-n%4*8&255;t[r+n>>>2]|=o<<24-(r+n)%4*8}else for(var a=0;a<i;a+=4)t[r+a>>>2]=s[a>>>2];return this.sigBytes+=i,this},clamp:function(){var t=this.words,s=this.sigBytes;t[s>>>2]&=4294967295<<32-s%4*8,t.length=e.ceil(s/4)},clone:function(){var e=h.clone.call(this);return e.words=this.words.slice(0),e},random:function(e){for(var t=[],s=0;s<e;s+=4)t.push(i());return new u.init(t,e)}}),d=a.enc={},l=d.Hex={stringify:function(e){for(var t=e.words,s=e.sigBytes,r=[],i=0;i<s;i++){var n=t[i>>>2]>>>24-i%4*8&255;r.push((n>>>4).toString(16)),r.push((15&n).toString(16))}return r.join("")},parse:function(e){for(var t=e.length,s=[],r=0;r<t;r+=2)s[r>>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new u.init(s,t/2)}},p=d.Latin1={stringify:function(e){for(var t=e.words,s=e.sigBytes,r=[],i=0;i<s;i++){var n=t[i>>>2]>>>24-i%4*8&255;r.push(String.fromCharCode(n))}return r.join("")},parse:function(e){for(var t=e.length,s=[],r=0;r<t;r++)s[r>>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new u.init(s,t)}},f=d.Utf8={stringify:function(e){try{return decodeURIComponent(escape(p.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return p.parse(unescape(encodeURIComponent(e)))}},g=c.BufferedBlockAlgorithm=h.extend({reset:function(){this._data=new u.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=f.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var s,r=this._data,i=r.words,n=r.sigBytes,o=this.blockSize,a=n/(4*o),c=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*o,h=e.min(4*c,n);if(c){for(var d=0;d<c;d+=o)this._doProcessBlock(i,d);s=i.splice(0,c),r.sigBytes-=h}return new u.init(s,h)},clone:function(){var e=h.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0});c.Hasher=g.extend({cfg:h.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){g.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){return e&&this._append(e),this._doFinalize()},blockSize:16,_createHelper:function(e){return function(t,s){return new e.init(s).finalize(t)}},_createHmacHelper:function(e){return function(t,s){return new _.HMAC.init(e,s).finalize(t)}}});var _=a.algo={};return a}(Math);return e}()}(n)),n.exports}var c,h=s(a()),u={exports:{}};var d,l=(c||(c=1,function(e){e.exports=function(e){return function(t){var s=e,r=s.lib,i=r.WordArray,n=r.Hasher,o=s.algo,a=[],c=[];!function(){function e(e){for(var s=t.sqrt(e),r=2;r<=s;r++)if(!(e%r))return!1;return!0}function s(e){return 4294967296*(e-(0|e))|0}for(var r=2,i=0;i<64;)e(r)&&(i<8&&(a[i]=s(t.pow(r,.5))),c[i]=s(t.pow(r,1/3)),i++),r++}();var h=[],u=o.SHA256=n.extend({_doReset:function(){this._hash=new i.init(a.slice(0))},_doProcessBlock:function(e,t){for(var s=this._hash.words,r=s[0],i=s[1],n=s[2],o=s[3],a=s[4],u=s[5],d=s[6],l=s[7],p=0;p<64;p++){if(p<16)h[p]=0|e[t+p];else{var f=h[p-15],g=(f<<25|f>>>7)^(f<<14|f>>>18)^f>>>3,_=h[p-2],m=(_<<15|_>>>17)^(_<<13|_>>>19)^_>>>10;h[p]=g+h[p-7]+m+h[p-16]}var y=r&i^r&n^i&n,w=(r<<30|r>>>2)^(r<<19|r>>>13)^(r<<10|r>>>22),b=l+((a<<26|a>>>6)^(a<<21|a>>>11)^(a<<7|a>>>25))+(a&u^~a&d)+c[p]+h[p];l=d,d=u,u=a,a=o+b|0,o=n,n=i,i=r,r=b+(w+y)|0}s[0]=s[0]+r|0,s[1]=s[1]+i|0,s[2]=s[2]+n|0,s[3]=s[3]+o|0,s[4]=s[4]+a|0,s[5]=s[5]+u|0,s[6]=s[6]+d|0,s[7]=s[7]+l|0},_doFinalize:function(){var e=this._data,s=e.words,r=8*this._nDataBytes,i=8*e.sigBytes;return s[i>>>5]|=128<<24-i%32,s[14+(i+64>>>9<<4)]=t.floor(r/4294967296),s[15+(i+64>>>9<<4)]=r,e.sigBytes=4*s.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}});s.SHA256=n._createHelper(u),s.HmacSHA256=n._createHmacHelper(u)}(Math),e.SHA256}(a())}(u)),u.exports),p=s(l),f={exports:{}};var g,_=(d||(d=1,function(e){e.exports=function(e){return function(){var t=e,s=t.lib.WordArray;function r(e,t,r){for(var i=[],n=0,o=0;o<t;o++)if(o%4){var a=r[e.charCodeAt(o-1)]<<o%4*2|r[e.charCodeAt(o)]>>>6-o%4*2;i[n>>>2]|=a<<24-n%4*8,n++}return s.create(i,n)}t.enc.Base64={stringify:function(e){var t=e.words,s=e.sigBytes,r=this._map;e.clamp();for(var i=[],n=0;n<s;n+=3)for(var o=(t[n>>>2]>>>24-n%4*8&255)<<16|(t[n+1>>>2]>>>24-(n+1)%4*8&255)<<8|t[n+2>>>2]>>>24-(n+2)%4*8&255,a=0;a<4&&n+.75*a<s;a++)i.push(r.charAt(o>>>6*(3-a)&63));var c=r.charAt(64);if(c)for(;i.length%4;)i.push(c);return i.join("")},parse:function(e){var t=e.length,s=this._map,i=this._reverseMap;if(!i){i=this._reverseMap=[];for(var n=0;n<s.length;n++)i[s.charCodeAt(n)]=n}var o=s.charAt(64);if(o){var a=e.indexOf(o);-1!==a&&(t=a)}return r(e,t,i)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),e.enc.Base64}(a())}(f)),f.exports),m=s(_),y={exports:{}};var w=(g||(g=1,function(e){e.exports=function(e){return e.enc.Utf8}(a())}(y)),y.exports),b=s(w);function v(e){this.message=e}v.prototype=new Error,v.prototype.name="InvalidCharacterError";var k="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new v("'atob' failed: The string to be decoded is not correctly encoded.");for(var s,r,i=0,n=0,o="";r=t.charAt(n++);~r&&(s=i%4?64*s+r:r,i++%4)?o+=String.fromCharCode(255&s>>(-2*i&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return o};function S(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(k(e).replace(/(.)/g,function(e,t){var s=t.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(t)}catch(e){return k(t)}}function E(e){this.message=e}function T(e,t){if("string"!=typeof e)throw new E("Invalid token specified");var s=!0===(t=t||{}).header?0:1;try{return JSON.parse(S(e.split(".")[s]))}catch(e){throw new E("Invalid token specified: "+e.message)}}E.prototype=new Error,E.prototype.name="InvalidTokenError";var R,A,C,x={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},O=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(O||{});(C=O||(O={})).reset=function(){R=3,A=x},C.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");R=e},C.setLogger=function(e){A=e};var I=class{constructor(e){this._name=e}debug(...e){R>=4&&A.debug(I._format(this._name,this._method),...e)}info(...e){R>=3&&A.info(I._format(this._name,this._method),...e)}warn(...e){R>=2&&A.warn(I._format(this._name,this._method),...e)}error(...e){R>=1&&A.error(I._format(this._name,this._method),...e)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(e,t){const s=new I(`${e}.${t}`);return s.debug("begin"),s}static _format(e,t){const s=`[${e}]`;return t?`${s} ${t}:`:s}static debug(e,...t){R>=4&&A.debug(I._format(e),...t)}static info(e,...t){R>=3&&A.info(I._format(e),...t)}static warn(e,...t){R>=2&&A.warn(I._format(e),...t)}static error(e,...t){R>=1&&A.error(I._format(e),...t)}};O.reset();var P=class{static _randomWord(){return h.lib.WordArray.random(1).words[0]}static generateUUIDv4(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^P._randomWord()&15>>+e/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return P.generateUUIDv4()+P.generateUUIDv4()+P.generateUUIDv4()}static generateCodeChallenge(e){try{const t=p(e);return m.stringify(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(e){throw I.error("CryptoUtils.generateCodeChallenge",e),e}}static generateBasicAuth(e,t){const s=b.parse([e,t].join(":"));return m.stringify(s)}},N=class{constructor(e){this._name=e,this._logger=new I(`Event('${this._name}')`),this._callbacks=[]}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)t(...e)}},B=class{static decode(e){try{return T(e)}catch(e){throw I.error("JwtUtils.decode",e),e}}},q=class extends N{constructor(){super(...arguments),this._logger=new I(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const e=this._expiration-q.getEpochTime();this._logger.debug("timer completes in",e),this._expiration<=q.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(e){const t=this._logger.create("init");e=Math.max(Math.floor(e),1);const s=q.getEpochTime()+e;if(this.expiration===s&&this._timerHandle)return void t.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),t.debug("using duration",e),this._expiration=s;const r=Math.min(e,5);this._timerHandle=setInterval(this._callback,1e3*r)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},U=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const s=new URL(e,window.location.origin)["fragment"===t?"hash":"search"];return new URLSearchParams(s.slice(1))}},j=class extends Error{constructor(e,t){var s,r,i;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw I.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(s=e.error_description)?s:null,this.error_uri=null!=(r=e.error_uri)?r:null,this.state=e.userState,this.session_state=null!=(i=e.session_state)?i:null}},L=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},D=class{constructor(){this._logger=new I("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},M=class{constructor(e=[],t=null){this._jwtHandler=t,this._logger=new I("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:s,...r}=t;if(!s)return await fetch(e,r);const i=new AbortController,n=setTimeout(()=>i.abort(),1e3*s);try{return await fetch(e,{...t,signal:i.signal})}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw new L("Network timed out");throw e}finally{clearTimeout(n)}}async getJson(e,{token:t,credentials:s}={}){const r=this._logger.create("getJson"),i={Accept:this._contentTypes.join(", ")};let n;t&&(r.debug("token passed, setting Authorization header"),i.Authorization="Bearer "+t);try{r.debug("url:",e),n=await this.fetchWithTimeout(e,{method:"GET",headers:i,credentials:s})}catch(e){throw r.error("Network Error"),e}r.debug("HTTP response received, status",n.status);const o=n.headers.get("Content-Type");if(o&&!this._contentTypes.find(e=>o.startsWith(e))&&r.throw(new Error(`Invalid response Content-Type: ${null!=o?o:"undefined"}, from URL: ${e}`)),n.ok&&this._jwtHandler&&(null==o?void 0:o.startsWith("application/jwt")))return await this._jwtHandler(await n.text());let a;try{a=await n.json()}catch(e){if(r.error("Error parsing JSON response",e),n.ok)throw e;throw new Error(`${n.statusText} (${n.status})`)}if(!n.ok){if(r.error("Error from server:",a),a.error)throw new j(a);throw new Error(`${n.statusText} (${n.status}): ${JSON.stringify(a)}`)}return a}async postForm(e,{body:t,basicAuth:s,timeoutInSeconds:r,initCredentials:i}){const n=this._logger.create("postForm"),o={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded"};let a;void 0!==s&&(o.Authorization="Basic "+s);try{n.debug("url:",e),a=await this.fetchWithTimeout(e,{method:"POST",headers:o,body:t,timeoutInSeconds:r,credentials:i})}catch(e){throw n.error("Network error"),e}n.debug("HTTP response received, status",a.status);const c=a.headers.get("Content-Type");if(c&&!this._contentTypes.find(e=>c.startsWith(e)))throw new Error(`Invalid response Content-Type: ${null!=c?c:"undefined"}, from URL: ${e}`);const h=await a.text();let u={};if(h)try{u=JSON.parse(h)}catch(e){if(n.error("Error parsing JSON response",e),a.ok)throw e;throw new Error(`${a.statusText} (${a.status})`)}if(!a.ok){if(n.error("Error from server:",u),u.error)throw new j(u,t);throw new Error(`${a.statusText} (${a.status}): ${JSON.stringify(u)}`)}return u}},F=class{constructor(e){this._settings=e,this._logger=new I("MetadataService"),this._jsonService=new M(["application/jwk-set+json"]),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},this._settings.metadataSeed,t),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const s=this._logger.create(`_getMetadataProperty('${e}')`),r=await this.getMetadata();if(s.debug("resolved"),void 0===r[e]){if(!0===t)return void s.warn("Metadata does not contain optional property");s.throw(new Error("Metadata does not contain property "+e))}return r[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const s=await this._jsonService.getJson(t);if(e.debug("got key set",s),!Array.isArray(s.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=s.keys,this._signingKeys}},H=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new I("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){this._logger.create(`get('${e}')`),e=this._prefix+e;return await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let s=0;s<e;s++){const e=await this._store.key(s);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},$=class{constructor({authority:e,metadataUrl:t,metadata:s,signingKeys:r,metadataSeed:i,client_id:n,client_secret:o,response_type:a="code",scope:c="openid",redirect_uri:h,post_logout_redirect_uri:u,client_authentication:d="client_secret_post",prompt:l,display:p,max_age:f,ui_locales:g,acr_values:_,resource:m,response_mode:y="query",filterProtocolClaims:w=!0,loadUserInfo:b=!1,staleStateAgeInSeconds:v=900,clockSkewInSeconds:k=300,userInfoJwtIssuer:S="OP",mergeClaims:E=!1,stateStore:T,refreshTokenCredentials:R,revokeTokenAdditionalContentTypes:A,fetchRequestCredentials:C,refreshTokenAllowedScope:x,extraQueryParams:O={},extraTokenParams:I={}}){if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=s,this.metadataSeed=i,this.signingKeys=r,this.client_id=n,this.client_secret=o,this.response_type=a,this.scope=c,this.redirect_uri=h,this.post_logout_redirect_uri=u,this.client_authentication=d,this.prompt=l,this.display=p,this.max_age=f,this.ui_locales=g,this.acr_values=_,this.resource=m,this.response_mode=y,this.filterProtocolClaims=null==w||w,this.loadUserInfo=!!b,this.staleStateAgeInSeconds=v,this.clockSkewInSeconds=k,this.userInfoJwtIssuer=S,this.mergeClaims=!!E,this.revokeTokenAdditionalContentTypes=A,C&&R&&console.warn("Both fetchRequestCredentials and refreshTokenCredentials is set. Only fetchRequestCredentials will be used."),this.fetchRequestCredentials=C||(R||"same-origin"),T)this.stateStore=T;else{const e="undefined"!=typeof window?window.localStorage:new D;this.stateStore=new H({store:e})}this.refreshTokenAllowedScope=x,this.extraQueryParams=O,this.extraTokenParams=I}},z=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new I("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const s=B.decode(e);return t.debug("JWT decoding successful"),s}catch(e){throw t.error("Error parsing JWT response"),e}},this._jsonService=new M(void 0,this._getClaimsFromJwt)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const s=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",s);const r=await this._jsonService.getJson(s,{token:e,credentials:this._settings.fetchRequestCredentials});return t.debug("got claims",r),r}},K=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new I("TokenClient"),this._jsonService=new M(this._settings.revokeTokenAdditionalContentTypes)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:s=this._settings.client_id,client_secret:r=this._settings.client_secret,...i}){const n=this._logger.create("exchangeCode");s||n.throw(new Error("A client_id is required")),t||n.throw(new Error("A redirect_uri is required")),i.code||n.throw(new Error("A code is required")),i.code_verifier||n.throw(new Error("A code_verifier is required"));const o=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[e,t]of Object.entries(i))null!=t&&o.set(e,t);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!r)throw n.throw(new Error("A client_secret is required")),null;a=P.generateBasicAuth(s,r);break;case"client_secret_post":o.append("client_id",s),r&&o.append("client_secret",r)}const c=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");const h=await this._jsonService.postForm(c,{body:o,basicAuth:a,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),h}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:s=this._settings.client_secret,scope:r=this._settings.scope,...i}){const n=this._logger.create("exchangeCredentials");t||n.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:e,scope:r});for(const[e,t]of Object.entries(i))null!=t&&o.set(e,t);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!s)throw n.throw(new Error("A client_secret is required")),null;a=P.generateBasicAuth(t,s);break;case"client_secret_post":o.append("client_id",t),s&&o.append("client_secret",s)}const c=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");const h=await this._jsonService.postForm(c,{body:o,basicAuth:a,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),h}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:s=this._settings.client_secret,timeoutInSeconds:r,...i}){const n=this._logger.create("exchangeRefreshToken");t||n.throw(new Error("A client_id is required")),i.refresh_token||n.throw(new Error("A refresh_token is required"));const o=new URLSearchParams({grant_type:e});for(const[e,t]of Object.entries(i))null!=t&&o.set(e,t);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!s)throw n.throw(new Error("A client_secret is required")),null;a=P.generateBasicAuth(t,s);break;case"client_secret_post":o.append("client_id",t),s&&o.append("client_secret",s)}const c=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");const h=await this._jsonService.postForm(c,{body:o,basicAuth:a,timeoutInSeconds:r,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),h}async revoke(e){var t;const s=this._logger.create("revoke");e.token||s.throw(new Error("A token is required"));const r=await this._metadataService.getRevocationEndpoint(!1);s.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const i=new URLSearchParams;for(const[t,s]of Object.entries(e))null!=s&&i.set(t,s);i.set("client_id",this._settings.client_id),this._settings.client_secret&&i.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(r,{body:i}),s.debug("got response")}},J=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],W=["sub","iss","aud","exp","iat"],V=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new I("ResponseValidator"),this._userInfoService=new z(this._settings,this._metadataService),this._tokenClient=new K(this._settings,this._metadataService)}async validateSigninResponse(e,t){const s=this._logger.create("validateSigninResponse");this._processSigninState(e,t),s.debug("state processed"),await this._processCode(e,t),s.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),s.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),s.debug("claims processed")}async validateCredentialsResponse(e,t){const s=this._logger.create("validateCredentialsResponse");e.isOpenId&&this._validateIdTokenAttributes(e),s.debug("tokens validated"),await this._processClaims(e,t,e.isOpenId),s.debug("claims processed")}async validateRefreshResponse(e,t){const s=this._logger.create("validateRefreshResponse");e.userState=t.data,null!=e.session_state||(e.session_state=t.session_state),null!=e.scope||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),s.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const r=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,r),s.debug("claims processed")}validateSignoutResponse(e,t){const s=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&s.throw(new Error("State does not match")),s.debug("state validated"),e.userState=t.data,e.error)throw s.warn("Response was error",e.error),new j(e)}_processSigninState(e,t){const s=this._logger.create("_processSigninState");if(t.id!==e.state&&s.throw(new Error("State does not match")),t.client_id||s.throw(new Error("No client_id on state")),t.authority||s.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&s.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&s.throw(new Error("client_id mismatch on settings vs. signin state")),s.debug("state validated"),e.userState=t.data,null!=e.scope||(e.scope=t.scope),e.error)throw s.warn("Response was error",e.error),new j(e);t.code_verifier&&!e.code&&s.throw(new Error("Expected code in response")),!t.code_verifier&&e.code&&s.throw(new Error("Unexpected code in response"))}async _processClaims(e,t=!1,s=!0){const r=this._logger.create("_processClaims");if(e.profile=this._filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void r.debug("not loading user info");r.debug("loading user info");const i=await this._userInfoService.getClaims(e.access_token);r.debug("user info claims received from user info endpoint"),s&&i.sub!==e.profile.sub&&r.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._mergeClaims(e.profile,this._filterProtocolClaims(i)),r.debug("user info claims received, updated profile:",e.profile)}_mergeClaims(e,t){const s={...e};for(const[e,r]of Object.entries(t))for(const t of Array.isArray(r)?r:[r]){const r=s[e];r?Array.isArray(r)?r.includes(t)||r.push(t):s[e]!==t&&("object"==typeof t&&this._settings.mergeClaims?s[e]=this._mergeClaims(r,t):s[e]=[r,t]):s[e]=t}return s}_filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:J;for(const s of e)W.includes(s)||delete t[s]}return t}async _processCode(e,t){const s=this._logger.create("_processCode");if(e.code){s.debug("Validating code");const r=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,...t.extraTokenParams});Object.assign(e,r)}else s.debug("No code to process")}_validateIdTokenAttributes(e,t){var s;const r=this._logger.create("_validateIdTokenAttributes");r.debug("decoding ID Token JWT");const i=B.decode(null!=(s=e.id_token)?s:"");if(i.sub||r.throw(new Error("ID Token is missing a subject claim")),t){const e=B.decode(t);e.sub!==i.sub&&r.throw(new Error("sub in id_token does not match current sub")),e.auth_time&&e.auth_time!==i.auth_time&&r.throw(new Error("auth_time in id_token does not match original auth_time")),e.azp&&e.azp!==i.azp&&r.throw(new Error("azp in id_token does not match original azp")),!e.azp&&i.azp&&r.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=i}},Q=class{constructor(e){this.id=e.id||P.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=q.getEpochTime(),this.request_type=e.request_type}toStorageString(){return new I("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type})}static fromStorageString(e){return I.createStatic("State","fromStorageString"),new Q(JSON.parse(e))}static async clearStaleState(e,t){const s=I.createStatic("State","clearStaleState"),r=q.getEpochTime()-t,i=await e.getAllKeys();s.debug("got keys",i);for(let t=0;t<i.length;t++){const n=i[t],o=await e.get(n);let a=!1;if(o)try{const e=Q.fromStorageString(o);s.debug("got item from key:",n,e.created),e.created<=r&&(a=!0)}catch(e){s.error("Error parsing state for key:",n,e),a=!0}else s.debug("no item in storage for key:",n),a=!0;a&&(s.debug("removed item for key:",n),e.remove(n))}}},Y=class extends Q{constructor(e){super(e),!0===e.code_verifier?this.code_verifier=P.generateCodeVerifier():e.code_verifier&&(this.code_verifier=e.code_verifier),this.code_verifier&&(this.code_challenge=P.generateCodeChallenge(this.code_verifier)),this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo}toStorageString(){return new I("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(e){I.createStatic("SigninState","fromStorageString");const t=JSON.parse(e);return new Y(t)}},G=class{constructor({url:e,authority:t,client_id:s,redirect_uri:r,response_type:i,scope:n,state_data:o,response_mode:a,request_type:c,client_secret:h,nonce:u,resource:d,skipUserInfo:l,extraQueryParams:p,extraTokenParams:f,...g}){if(this._logger=new I("SigninRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");if(!s)throw this._logger.error("ctor: No client_id passed"),new Error("client_id");if(!r)throw this._logger.error("ctor: No redirect_uri passed"),new Error("redirect_uri");if(!i)throw this._logger.error("ctor: No response_type passed"),new Error("response_type");if(!n)throw this._logger.error("ctor: No scope passed"),new Error("scope");if(!t)throw this._logger.error("ctor: No authority passed"),new Error("authority");this.state=new Y({data:o,request_type:c,code_verifier:!0,client_id:s,authority:t,redirect_uri:r,response_mode:a,client_secret:h,scope:n,extraTokenParams:f,skipUserInfo:l});const _=new URL(e);if(_.searchParams.append("client_id",s),_.searchParams.append("redirect_uri",r),_.searchParams.append("response_type",i),_.searchParams.append("scope",n),u&&_.searchParams.append("nonce",u),_.searchParams.append("state",this.state.id),this.state.code_challenge&&(_.searchParams.append("code_challenge",this.state.code_challenge),_.searchParams.append("code_challenge_method","S256")),d){(Array.isArray(d)?d:[d]).forEach(e=>_.searchParams.append("resource",e))}for(const[e,t]of Object.entries({response_mode:a,...g,...p}))null!=t&&_.searchParams.append(e,t.toString());this.url=_.href}},X=class{constructor(e){this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-q.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+q.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},Z=class{constructor({url:e,state_data:t,id_token_hint:s,post_logout_redirect_uri:r,extraQueryParams:i,request_type:n}){if(this._logger=new I("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const o=new URL(e);s&&o.searchParams.append("id_token_hint",s),r&&(o.searchParams.append("post_logout_redirect_uri",r),t&&(this.state=new Q({data:t,request_type:n}),o.searchParams.append("state",this.state.id)));for(const[e,t]of Object.entries({...i}))null!=t&&o.searchParams.append(e,t.toString());this.url=o.href}},ee=class{constructor(e){this.state=e.get("state"),this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},te=class{constructor(e){this._logger=new I("OidcClient"),this.settings=new $(e),this.metadataService=new F(this.settings),this._validator=new V(this.settings,this.metadataService),this._tokenClient=new K(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:s,request_type:r,id_token_hint:i,login_hint:n,skipUserInfo:o,nonce:a,response_type:c=this.settings.response_type,scope:h=this.settings.scope,redirect_uri:u=this.settings.redirect_uri,prompt:d=this.settings.prompt,display:l=this.settings.display,max_age:p=this.settings.max_age,ui_locales:f=this.settings.ui_locales,acr_values:g=this.settings.acr_values,resource:_=this.settings.resource,response_mode:m=this.settings.response_mode,extraQueryParams:y=this.settings.extraQueryParams,extraTokenParams:w=this.settings.extraTokenParams}){const b=this._logger.create("createSigninRequest");if("code"!==c)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const v=await this.metadataService.getAuthorizationEndpoint();b.debug("Received authorization endpoint",v);const k=new G({url:v,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:u,response_type:c,scope:h,state_data:e,prompt:d,display:l,max_age:p,ui_locales:f,id_token_hint:i,login_hint:n,acr_values:g,resource:_,request:t,request_uri:s,extraQueryParams:y,extraTokenParams:w,request_type:r,response_mode:m,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a});await this.clearStaleState();const S=k.state;return await this.settings.stateStore.set(S.id,S.toStorageString()),k}async readSigninResponseState(e,t=!1){const s=this._logger.create("readSigninResponseState"),r=new X(U.readParams(e,this.settings.response_mode));if(!r.state)throw s.throw(new Error("No state in response")),null;const i=await this.settings.stateStore[t?"remove":"get"](r.state);if(!i)throw s.throw(new Error("No matching state found in storage")),null;return{state:Y.fromStorageString(i),response:r}}async processSigninResponse(e){const t=this._logger.create("processSigninResponse"),{state:s,response:r}=await this.readSigninResponseState(e,!0);return t.debug("received state from storage; validating response"),await this._validator.validateSigninResponse(r,s),r}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:s=!1,extraTokenParams:r={}}){const i=await this._tokenClient.exchangeCredentials({username:e,password:t,...r}),n=new X(new URLSearchParams);return Object.assign(n,i),await this._validator.validateCredentialsResponse(n,s),n}async useRefreshToken({state:e,timeoutInSeconds:t}){var s;const r=this._logger.create("useRefreshToken");let i;if(void 0===this.settings.refreshTokenAllowedScope)i=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");i=((null==(s=e.scope)?void 0:s.split(" "))||[]).filter(e=>t.includes(e)).join(" ")}const n=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:i,timeoutInSeconds:t}),o=new X(new URLSearchParams);return Object.assign(o,n),r.debug("validating response",o),await this._validator.validateRefreshResponse(o,{...e,scope:i}),o}async createSignoutRequest({state:e,id_token_hint:t,request_type:s,post_logout_redirect_uri:r=this.settings.post_logout_redirect_uri,extraQueryParams:i=this.settings.extraQueryParams}={}){const n=this._logger.create("createSignoutRequest"),o=await this.metadataService.getEndSessionEndpoint();if(!o)throw n.throw(new Error("No end session endpoint")),null;n.debug("Received end session endpoint",o);const a=new Z({url:o,id_token_hint:t,post_logout_redirect_uri:r,state_data:e,extraQueryParams:i,request_type:s});await this.clearStaleState();const c=a.state;return c&&(n.debug("Signout request has state to persist"),await this.settings.stateStore.set(c.id,c.toStorageString())),a}async readSignoutResponseState(e,t=!1){const s=this._logger.create("readSignoutResponseState"),r=new ee(U.readParams(e,this.settings.response_mode));if(!r.state){if(s.debug("No state in response"),r.error)throw s.warn("Response was error:",r.error),new j(r);return{state:void 0,response:r}}const i=await this.settings.stateStore[t?"remove":"get"](r.state);if(!i)throw s.throw(new Error("No matching state found in storage")),null;return{state:Q.fromStorageString(i),response:r}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:s,response:r}=await this.readSignoutResponseState(e,!0);return s?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(r,s)):t.debug("No state from storage; skipping response validation"),r}clearStaleState(){return this._logger.create("clearStaleState"),Q.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}};const se={},re=(e,t)=>ne()?localStorage.setItem(e,t):se[e]=t,ie=e=>ne()?localStorage.getItem(e):se[e],ne=()=>!("object"==typeof process&&"[object process]"===String(process));class oe{constructor(e){this._oidcSettings={authority:"https://auth.gameglue.gg/realms/GameGlue",client_id:e.clientId,redirect_uri:ae(e.redirect_uri||window.location.href),post_logout_redirect_uri:ae(window.location.href),response_type:"code",scope:`openid ${(e.scopes||[]).join(" ")}`,response_mode:"fragment",filterProtocolClaims:!0},this._oidcClient=new te(this._oidcSettings),this._refreshCallback=()=>{},this._refreshTimeout=null}setTokenRefreshTimeout(e){if(!e)return;clearTimeout(this._refreshTimeout);const t=1e3*T(e).exp-Date.now()-5e3;t>0&&(this._refreshTimeout=setTimeout(()=>{this.attemptRefresh()},t))}setAccessToken(e){return this.setTokenRefreshTimeout(e),re("gg-auth-token",e)}getAccessToken(){let e=ie("gg-auth-token");return this.setTokenRefreshTimeout(e),e}getUserId(){return T(this.getAccessToken()).sub}setRefreshToken(e){return re("gg-refresh-token",e)}getRefreshToken(e){return ie("gg-refresh-token")}_shouldHandleRedirectResponse(){return location.hash.includes("state=")&&(location.hash.includes("code=")||location.hash.includes("error="))}async handleRedirectResponse(){let e=await this._oidcClient.processSigninResponse(window.location.href);!e.error&&e.access_token?(window.history.pushState("",document.title,window.location.pathname+window.location.search),this.setAccessToken(e.access_token),this.setRefreshToken(e.refresh_token)):console.error(e.error)}onTokenRefreshed(e){this._refreshCallback=e}async isAuthenticated(e){let t=this.getAccessToken();if(!t)return!1;const s=T(t),r=new Date(1e3*s.exp)<new Date;return r&&!e?(await this.attemptRefresh(),this.isAuthenticated(!0)):!(r&&e)}isTokenExpired(e){const t=T(e);return new Date(1e3*t.exp)<new Date}async attemptRefresh(){const e=`${this._oidcSettings.authority}/protocol/openid-connect/token`,t=this._oidcSettings.client_id,s=this.getRefreshToken();try{const r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:t,grant_type:"refresh_token",refresh_token:s})});if(200===r.status){const e=await r.json();this.setAccessToken(e.access_token),this.setRefreshToken(e.refresh_token),this._refreshCallback(e)}}catch(e){console.log("Error: ",e)}}_triggerAuthRedirect(){this._oidcClient.createSigninRequest({state:{bar:15}}).then(function(e){window.location=e.url}).catch(function(e){console.error(e)})}async authenticate(){this._shouldHandleRedirectResponse()&&await this.handleRedirectResponse(),await this.isAuthenticated()||await this._triggerAuthRedirect()}}function ae(e){return e.endsWith("/")?e.replace(/\/+$/,""):e}const ce=Object.create(null);ce.open="0",ce.close="1",ce.ping="2",ce.pong="3",ce.message="4",ce.upgrade="5",ce.noop="6";const he=Object.create(null);Object.keys(ce).forEach(e=>{he[ce[e]]=e});const ue={type:"error",data:"parser error"},de="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),le="function"==typeof ArrayBuffer,pe=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,fe=({type:e,data:t},s,r)=>de&&t instanceof Blob?s?r(t):ge(t,r):le&&(t instanceof ArrayBuffer||pe(t))?s?r(t):ge(new Blob([t]),r):r(ce[e]+(t||"")),ge=(e,t)=>{const s=new FileReader;return s.onload=function(){const e=s.result.split(",")[1];t("b"+(e||""))},s.readAsDataURL(e)};function _e(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let me;const ye="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",we="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<64;e++)we[ye.charCodeAt(e)]=e;const be="function"==typeof ArrayBuffer,ve=(e,t)=>{if("string"!=typeof e)return{type:"message",data:Se(e,t)};const s=e.charAt(0);if("b"===s)return{type:"message",data:ke(e.substring(1),t)};return he[s]?e.length>1?{type:he[s],data:e.substring(1)}:{type:he[s]}:ue},ke=(e,t)=>{if(be){const s=(e=>{let t,s,r,i,n,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const h=new ArrayBuffer(o),u=new Uint8Array(h);for(t=0;t<a;t+=4)s=we[e.charCodeAt(t)],r=we[e.charCodeAt(t+1)],i=we[e.charCodeAt(t+2)],n=we[e.charCodeAt(t+3)],u[c++]=s<<2|r>>4,u[c++]=(15&r)<<4|i>>2,u[c++]=(3&i)<<6|63&n;return h})(e);return Se(s,t)}return{base64:!0,data:e}},Se=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,Ee=String.fromCharCode(30);function Te(){return new TransformStream({transform(e,t){!function(e,t){de&&e.data instanceof Blob?e.data.arrayBuffer().then(_e).then(t):le&&(e.data instanceof ArrayBuffer||pe(e.data))?t(_e(e.data)):fe(e,!1,e=>{me||(me=new TextEncoder),t(me.encode(e))})}(e,s=>{const r=s.length;let i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);const e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{i=new Uint8Array(9);const e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&"string"!=typeof e.data&&(i[0]|=128),t.enqueue(i),t.enqueue(s)})}})}let Re;function Ae(e){return e.reduce((e,t)=>e+t.length,0)}function Ce(e,t){if(e[0].length===t)return e.shift();const s=new Uint8Array(t);let r=0;for(let i=0;i<t;i++)s[i]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),s}function xe(e){if(e)return function(e){for(var t in xe.prototype)e[t]=xe.prototype[t];return e}(e)}xe.prototype.on=xe.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},xe.prototype.once=function(e,t){function s(){this.off(e,s),t.apply(this,arguments)}return s.fn=t,this.on(e,s),this},xe.prototype.off=xe.prototype.removeListener=xe.prototype.removeAllListeners=xe.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var s,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<r.length;i++)if((s=r[i])===t||s.fn===t){r.splice(i,1);break}return 0===r.length&&delete this._callbacks["$"+e],this},xe.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),s=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(s){r=0;for(var i=(s=s.slice(0)).length;r<i;++r)s[r].apply(this,t)}return this},xe.prototype.emitReserved=xe.prototype.emit,xe.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},xe.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Oe="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Ie="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Pe(e,...t){return t.reduce((t,s)=>(e.hasOwnProperty(s)&&(t[s]=e[s]),t),{})}const Ne=Ie.setTimeout,Be=Ie.clearTimeout;function qe(e,t){t.useNativeTimers?(e.setTimeoutFn=Ne.bind(Ie),e.clearTimeoutFn=Be.bind(Ie)):(e.setTimeoutFn=Ie.setTimeout.bind(Ie),e.clearTimeoutFn=Ie.clearTimeout.bind(Ie))}function Ue(e){return"string"==typeof e?function(e){let t=0,s=0;for(let r=0,i=e.length;r<i;r++)t=e.charCodeAt(r),t<128?s+=1:t<2048?s+=2:t<55296||t>=57344?s+=3:(r++,s+=4);return s}(e):Math.ceil(1.33*(e.byteLength||e.size))}function je(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class Le extends Error{constructor(e,t,s){super(e),this.description=t,this.context=s,this.type="TransportError"}}class De extends xe{constructor(e){super(),this.writable=!1,qe(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,s){return super.emitReserved("error",new Le(e,t,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=ve(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let s in e)e.hasOwnProperty(s)&&(t.length&&(t+="&"),t+=encodeURIComponent(s)+"="+encodeURIComponent(e[s]));return t}(e);return t.length?"?"+t:""}}class Me extends De{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const s=e.split(Ee),r=[];for(let e=0;e<s.length;e++){const i=ve(s[e],t);if(r.push(i),"error"===i.type)break}return r})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const s=e.length,r=new Array(s);let i=0;e.forEach((e,n)=>{fe(e,!1,e=>{r[n]=e,++i===s&&t(r.join(Ee))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=je()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let Fe=!1;try{Fe="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}const He=Fe;function $e(){}class ze extends Me{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let s=location.port;s||(s=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||s!==e.port}}doWrite(e,t){const s=this.request({method:"POST",data:e});s.on("success",t),s.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}class Ke extends xe{constructor(e,t,s){super(),this.createRequest=e,qe(this,s),this._opts=s,this._method=s.method||"GET",this._uri=t,this._data=void 0!==s.data?s.data:null,this._create()}_create(){var e;const t=Pe(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(t);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&s.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(e){}if("POST"===this._method)try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{s.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this._opts.cookieJar)||void 0===e||e.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var e;3===s.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(s.getResponseHeader("set-cookie"))),4===s.readyState&&(200===s.status||1223===s.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof s.status?s.status:0)},0))},s.send(this._data)}catch(e){return void this.setTimeoutFn(()=>{this._onError(e)},0)}"undefined"!=typeof document&&(this._index=Ke.requestsCount++,Ke.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=$e,e)try{this._xhr.abort()}catch(e){}"undefined"!=typeof document&&delete Ke.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(Ke.requestsCount=0,Ke.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",Je);else if("function"==typeof addEventListener){addEventListener("onpagehide"in Ie?"pagehide":"unload",Je,!1)}function Je(){for(let e in Ke.requests)Ke.requests.hasOwnProperty(e)&&Ke.requests[e].abort()}const We=function(){const e=Ve({xdomain:!1});return e&&null!==e.responseType}();function Ve(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||He))return new XMLHttpRequest}catch(e){}if(!t)try{return new(Ie[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}const Qe="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Ye extends De{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=Qe?{}:Pe(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,s)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],r=t===e.length-1;fe(s,this.supportsBinary,e=>{try{this.doWrite(s,e)}catch(e){}r&&Oe(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=je()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const Ge=Ie.WebSocket||Ie.MozWebSocket;const Xe={websocket:class extends Ye{createSocket(e,t,s){return Qe?new Ge(e,t,s):t?new Ge(e,t):new Ge(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends De{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=function(e,t){Re||(Re=new TextDecoder);const s=[];let r=0,i=-1,n=!1;return new TransformStream({transform(o,a){for(s.push(o);;){if(0===r){if(Ae(s)<1)break;const e=Ce(s,1);n=!(128&~e[0]),i=127&e[0],r=i<126?3:126===i?1:2}else if(1===r){if(Ae(s)<2)break;const e=Ce(s,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(2===r){if(Ae(s)<8)break;const e=Ce(s,8),t=new DataView(e.buffer,e.byteOffset,e.length),n=t.getUint32(0);if(n>Math.pow(2,21)-1){a.enqueue(ue);break}i=n*Math.pow(2,32)+t.getUint32(4),r=3}else{if(Ae(s)<i)break;const e=Ce(s,i);a.enqueue(ve(n?e:Re.decode(e),t)),r=0}if(0===i||i>e){a.enqueue(ue);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),r=Te();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();const i=()=>{s.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();const n={type:"open"};this.query.sid&&(n.data=`{"sid":"${this.query.sid}"}`),this._writer.write(n).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],r=t===e.length-1;this._writer.write(s).then(()=>{r&&Oe(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends ze{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=We&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Ke(Ve,this.uri(),e)}}},Ze=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,et=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function tt(e){if(e.length>8e3)throw"URI too long";const t=e,s=e.indexOf("["),r=e.indexOf("]");-1!=s&&-1!=r&&(e=e.substring(0,s)+e.substring(s,r).replace(/:/g,";")+e.substring(r,e.length));let i=Ze.exec(e||""),n={},o=14;for(;o--;)n[et[o]]=i[o]||"";return-1!=s&&-1!=r&&(n.source=t,n.host=n.host.substring(1,n.host.length-1).replace(/;/g,":"),n.authority=n.authority.replace("[","").replace("]","").replace(/;/g,":"),n.ipv6uri=!0),n.pathNames=function(e,t){const s=/\/{2,9}/g,r=t.replace(s,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||r.splice(0,1);"/"==t.slice(-1)&&r.splice(r.length-1,1);return r}(0,n.path),n.queryKey=function(e,t){const s={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(s[t]=r)}),s}(0,n.query),n}const st="function"==typeof addEventListener&&"function"==typeof removeEventListener,rt=[];st&&addEventListener("offline",()=>{rt.forEach(e=>e())},!1);class it extends xe{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const s=tt(e);t.hostname=s.host,t.secure="https"===s.protocol||"wss"===s.protocol,t.port=s.port,s.query&&(t.query=s.query)}else t.host&&(t.hostname=tt(t.host).host);qe(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{const t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},s=e.split("&");for(let e=0,r=s.length;e<r;e++){let r=s[e].split("=");t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}(this.opts.query)),st&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},rt.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const s=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](s)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&it.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",it.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const s=this.writeBuffer[t].data;if(s&&(e+=Ue(s)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,Oe(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,s){return this._sendPacket("message",e,t,s),this}send(e,t,s){return this._sendPacket("message",e,t,s),this}_sendPacket(e,t,s,r){if("function"==typeof t&&(r=t,t=void 0),"function"==typeof s&&(r=s,s=null),"closing"===this.readyState||"closed"===this.readyState)return;(s=s||{}).compress=!1!==s.compress;const i={type:e,data:t,options:s};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},s=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():e()}):this.upgrading?s():e()),this}_onError(e){if(it.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),st&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=rt.indexOf(this._offlineEventListener);-1!==e&&rt.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}it.protocol=4;class nt extends it{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),s=!1;it.priorWebsocketSuccess=!1;const r=()=>{s||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!s)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;it.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{s||"closed"!==this.readyState&&(h(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function i(){s||(s=!0,h(),t.close(),t=null)}const n=e=>{const s=new Error("probe error: "+e);s.transport=t.name,i(),this.emitReserved("upgradeError",s)};function o(){n("transport closed")}function a(){n("socket closed")}function c(e){t&&e.name!==t.name&&i()}const h=()=>{t.removeListener("open",r),t.removeListener("error",n),t.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};t.once("open",r),t.once("error",n),t.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{s||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let s=0;s<e.length;s++)~this.transports.indexOf(e[s])&&t.push(e[s]);return t}}let ot=class extends nt{constructor(e,t={}){const s="object"==typeof e?e:t;(!s.transports||s.transports&&"string"==typeof s.transports[0])&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(e=>Xe[e]).filter(e=>!!e)),super(e,s)}};const at="function"==typeof ArrayBuffer,ct=Object.prototype.toString,ht="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===ct.call(Blob),ut="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===ct.call(File);function dt(e){return at&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||ht&&e instanceof Blob||ut&&e instanceof File}function lt(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,s=e.length;t<s;t++)if(lt(e[t]))return!0;return!1}if(dt(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return lt(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&<(e[t]))return!0;return!1}function pt(e){const t=[],s=e.data,r=e;return r.data=ft(s,t),r.attachments=t.length,{packet:r,buffers:t}}function ft(e,t){if(!e)return e;if(dt(e)){const s={_placeholder:!0,num:t.length};return t.push(e),s}if(Array.isArray(e)){const s=new Array(e.length);for(let r=0;r<e.length;r++)s[r]=ft(e[r],t);return s}if("object"==typeof e&&!(e instanceof Date)){const s={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(s[r]=ft(e[r],t));return s}return e}function gt(e,t){return e.data=_t(e.data,t),delete e.attachments,e}function _t(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let s=0;s<e.length;s++)e[s]=_t(e[s],t);else if("object"==typeof e)for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e[s]=_t(e[s],t));return e}const mt=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var yt;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(yt||(yt={}));class wt extends xe{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const s=t.type===yt.BINARY_EVENT;s||t.type===yt.BINARY_ACK?(t.type=s?yt.EVENT:yt.ACK,this.reconstructor=new bt(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!dt(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const s={type:Number(e.charAt(0))};if(void 0===yt[s.type])throw new Error("unknown packet type "+s.type);if(s.type===yt.BINARY_EVENT||s.type===yt.BINARY_ACK){const r=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const i=e.substring(r,t);if(i!=Number(i)||"-"!==e.charAt(t))throw new Error("Illegal attachments");s.attachments=Number(i)}if("/"===e.charAt(t+1)){const r=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}s.nsp=e.substring(r,t)}else s.nsp="/";const r=e.charAt(t+1);if(""!==r&&Number(r)==r){const r=t+1;for(;++t;){const s=e.charAt(t);if(null==s||Number(s)!=s){--t;break}if(t===e.length)break}s.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(!wt.isPayloadValid(s.type,r))throw new Error("invalid payload");s.data=r}return s}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case yt.CONNECT:return kt(t);case yt.DISCONNECT:return void 0===t;case yt.CONNECT_ERROR:return"string"==typeof t||kt(t);case yt.EVENT:case yt.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===mt.indexOf(t[0]));case yt.ACK:case yt.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class bt{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=gt(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const vt=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function kt(e){return"[object Object]"===Object.prototype.toString.call(e)}var St=Object.freeze({__proto__:null,Decoder:wt,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==yt.EVENT&&e.type!==yt.ACK||!lt(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===yt.EVENT?yt.BINARY_EVENT:yt.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==yt.BINARY_EVENT&&e.type!==yt.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=pt(e),s=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(s),r}},get PacketType(){return yt},isPacketValid:function(e){return"string"==typeof e.nsp&&(void 0===(t=e.id)||vt(t))&&function(e,t){switch(e){case yt.CONNECT:return void 0===t||kt(t);case yt.DISCONNECT:return void 0===t;case yt.EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===mt.indexOf(t[0]));case yt.ACK:return Array.isArray(t);case yt.CONNECT_ERROR:return"string"==typeof t||kt(t);default:return!1}}(e.type,e.data);var t},protocol:5});function Et(e,t,s){return e.on(t,s),function(){e.off(t,s)}}const Tt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Rt extends xe{constructor(e,t,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[Et(e,"open",this.onopen.bind(this)),Et(e,"packet",this.onpacket.bind(this)),Et(e,"error",this.onerror.bind(this)),Et(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var s,r,i;if(Tt.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const n={type:yt.EVENT,data:t,options:{}};if(n.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,s=t.pop();this._registerAckCallback(e,s),n.id=e}const o=null===(r=null===(s=this.io.engine)||void 0===s?void 0:s.transport)||void 0===r?void 0:r.writable,a=this.connected&&!(null===(i=this.io.engine)||void 0===i?void 0:i._hasPingExpired());return this.flags.volatile&&!o||(a?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){var s;const r=null!==(s=this.flags.timeout)&&void 0!==s?s:this._opts.ackTimeout;if(void 0===r)return void(this.acks[e]=t);const i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},r),n=(...e)=>{this.io.clearTimeoutFn(i),t.apply(this,e)};n.withError=!0,this.acks[e]=n}emitWithAck(e,...t){return new Promise((s,r)=>{const i=(e,t)=>e?r(e):s(t);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>{this._queue[0];return null!==e?s.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...r)),s.pending=!1,this._drainQueue()}),this._queue.push(s),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:yt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case yt.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case yt.EVENT:case yt.BINARY_EVENT:this.onevent(e);break;case yt.ACK:case yt.BINARY_ACK:this.onack(e);break;case yt.DISCONNECT:this.ondisconnect();break;case yt.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const s of t)s.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let s=!1;return function(...r){s||(s=!0,t.packet({type:yt.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:yt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let s=0;s<t.length;s++)if(e===t[s])return t.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let s=0;s<t.length;s++)if(e===t[s])return t.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const s of t)s.apply(this,e.data)}}}function At(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}At.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),s=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+s:e-s}return 0|Math.min(e,this.max)},At.prototype.reset=function(){this.attempts=0},At.prototype.setMin=function(e){this.ms=e},At.prototype.setMax=function(e){this.max=e},At.prototype.setJitter=function(e){this.jitter=e};class Ct extends xe{constructor(e,t){var s;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,qe(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(s=t.randomizationFactor)&&void 0!==s?s:.5),this.backoff=new At({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||St;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new ot(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=Et(t,"open",function(){s.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},n=Et(t,"error",i);if(!1!==this._timeout){const e=this._timeout,s=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),t.close()},e);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}return this.subs.push(r),this.subs.push(n),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(Et(e,"ping",this.onping.bind(this)),Et(e,"data",this.ondata.bind(this)),Et(e,"error",this.onerror.bind(this)),Et(e,"close",this.onclose.bind(this)),Et(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){Oe(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let s=this.nsps[e];return s?this._autoConnect&&!s.active&&s.connect():(s=new Rt(this,e,t),this.nsps[e]=s),s}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let s=0;s<t.length;s++)this.engine.write(t[s],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var s;this.cleanup(),null===(s=this.engine)||void 0===s||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const xt={};function Ot(e,t){"object"==typeof e&&(t=e,e=void 0);const s=function(e,t="",s){let r=e;s=s||"undefined"!=typeof location&&location,null==e&&(e=s.protocol+"//"+s.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?s.protocol+e:s.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==s?s.protocol+"//"+e:"https://"+e),r=tt(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const i=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+t,r.href=r.protocol+"://"+i+(s&&s.port===r.port?"":":"+r.port),r}(e,(t=t||{}).path||"/socket.io"),r=s.source,i=s.id,n=s.path,o=xt[i]&&n in xt[i].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new Ct(r,t):(xt[i]||(xt[i]=new Ct(r,t)),a=xt[i]),s.query&&!t.query&&(t.query=s.queryKey),a.socket(s.path,t)}Object.assign(Ot,{Manager:Ct,Socket:Rt,io:Ot,connect:Ot});const It=require("event-emitter");class Pt{constructor(e,t){this._config=t,this._socket=e,this._callbacks=[],this._fields=t.fields?[...t.fields]:null}async establishConnection(){if(!this._socket||!this._config.userId||!this._config.gameId)throw new Error("Missing arguments in establishConnection");return new Promise(e=>{let t;t=this._fields?{userId:this._config.userId,gameId:this._config.gameId,fields:this._fields}:`${this._config.userId}:${this._config.gameId}`,this._socket.timeout(5e3).emit("listen",t,(t,s)=>t?e({status:"failed",reason:"Listen request timed out."}):"success"===s.status?e({status:"success"}):e({status:"failed",reason:s.reason}))})}setupEventListener(){return this._socket.on("update",this.emit.bind(this,"update")),this}async subscribe(e){if(!Array.isArray(e)||0===e.length)throw new Error("fields must be a non-empty array");if(this._fields)for(const t of e)this._fields.includes(t)||this._fields.push(t);else this._fields=[...e];return this._updateSubscription()}async unsubscribe(e){if(!Array.isArray(e)||0===e.length)throw new Error("fields must be a non-empty array");if(!this._fields)throw new Error("Cannot unsubscribe when receiving all fields. Use subscribe() first to set explicit field list.");return this._fields=this._fields.filter(t=>!e.includes(t)),this._updateSubscription()}getFields(){return this._fields?[...this._fields]:null}async sendCommand(e,t){if(!e||"string"!=typeof e)throw new Error("field must be a non-empty string");return new Promise(s=>{const r={userId:this._config.userId,gameId:this._config.gameId,data:{fieldName:e,value:t}};this._socket.timeout(5e3).emit("set",r,(e,t)=>s(e?{status:"failed",reason:"Command request timed out."}:t))})}async _updateSubscription(){return new Promise(e=>{const t={userId:this._config.userId,gameId:this._config.gameId,fields:this._fields};this._socket.timeout(5e3).emit("listen-update",t,(t,s)=>e(t?{status:"failed",reason:"Update request timed out."}:s))})}}It(Pt.prototype);const Nt={msfs:!0};class Bt extends oe{constructor(e){super(e),this._socket=!1}async auth(){return await this.authenticate(),await this.isAuthenticated()&&await this.initialize(),this.getUserId()}async initialize(){return new Promise(e=>{const t=this.getAccessToken();this._socket=Ot("https://socks.gameglue.gg",{transports:["websocket"],auth:{token:t}}),this._socket.on("connect",()=>{e()}),this.onTokenRefreshed(this.updateSocketAuth)})}updateSocketAuth(e){this._socket.auth.token=e}async createListener(e){if(!e)throw new Error("Not a valid listener config");if(!e.gameId||!Nt[e.gameId])throw new Error("Not a valid Game ID");if(!e.userId)throw new Error("User ID not supplied");if(e.fields&&!Array.isArray(e.fields))throw new Error("fields must be an array");this._socket||await this.initialize();const t=new Pt(this._socket,e),s=await t.establishConnection();if(this._socket.io.on("reconnect_attempt",e=>{console.log("Refresh Attempt"),this.updateSocketAuth(this.getAccessToken())}),this._socket.io.on("reconnect",()=>{t.establishConnection()}),"success"!==s.status)throw new Error(`There was a problem setting up the listener. Reason: ${s.reason}`);return t.setupEventListener()}}"undefined"!=typeof window&&(window.GameGlue=Bt),e.GameGlue=Bt,e.default=Bt,Object.defineProperty(e,"__esModule",{value:!0})});
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).GameGlue={})}(this,function(t){"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function s(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function r(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if("function"==typeof e){var s=function t(){var s=!1;try{s=this instanceof t}catch{}return s?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};s.prototype=e.prototype}else s={};return Object.defineProperty(s,"__esModule",{value:!0}),Object.keys(t).forEach(function(e){var r=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(s,e,r.get?r:{enumerable:!0,get:function(){return t[e]}})}),s}var i,n={exports:{}},o=r(Object.freeze({__proto__:null,default:{}}));function a(){return i||(i=1,function(t){t.exports=function(){var t=t||function(t,s){var r;if("undefined"!=typeof window&&window.crypto&&(r=window.crypto),"undefined"!=typeof self&&self.crypto&&(r=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(r=globalThis.crypto),!r&&"undefined"!=typeof window&&window.msCrypto&&(r=window.msCrypto),!r&&void 0!==e&&e.crypto&&(r=e.crypto),!r)try{r=o}catch(t){}var i=function(){if(r){if("function"==typeof r.getRandomValues)try{return r.getRandomValues(new Uint32Array(1))[0]}catch(t){}if("function"==typeof r.randomBytes)try{return r.randomBytes(4).readInt32LE()}catch(t){}}throw new Error("Native crypto module could not be used to get secure random number.")},n=Object.create||function(){function t(){}return function(e){var s;return t.prototype=e,s=new t,t.prototype=null,s}}(),a={},c=a.lib={},h=c.Base={extend:function(t){var e=n(this);return t&&e.mixIn(t),e.hasOwnProperty("init")&&this.init!==e.init||(e.init=function(){e.$super.init.apply(this,arguments)}),e.init.prototype=e,e.$super=this,e},create:function(){var t=this.extend();return t.init.apply(t,arguments),t},init:function(){},mixIn:function(t){for(var e in t)t.hasOwnProperty(e)&&(this[e]=t[e]);t.hasOwnProperty("toString")&&(this.toString=t.toString)},clone:function(){return this.init.prototype.extend(this)}},u=c.WordArray=h.extend({init:function(t,e){t=this.words=t||[],this.sigBytes=e!=s?e:4*t.length},toString:function(t){return(t||d).stringify(this)},concat:function(t){var e=this.words,s=t.words,r=this.sigBytes,i=t.sigBytes;if(this.clamp(),r%4)for(var n=0;n<i;n++){var o=s[n>>>2]>>>24-n%4*8&255;e[r+n>>>2]|=o<<24-(r+n)%4*8}else for(var a=0;a<i;a+=4)e[r+a>>>2]=s[a>>>2];return this.sigBytes+=i,this},clamp:function(){var e=this.words,s=this.sigBytes;e[s>>>2]&=4294967295<<32-s%4*8,e.length=t.ceil(s/4)},clone:function(){var t=h.clone.call(this);return t.words=this.words.slice(0),t},random:function(t){for(var e=[],s=0;s<t;s+=4)e.push(i());return new u.init(e,t)}}),l=a.enc={},d=l.Hex={stringify:function(t){for(var e=t.words,s=t.sigBytes,r=[],i=0;i<s;i++){var n=e[i>>>2]>>>24-i%4*8&255;r.push((n>>>4).toString(16)),r.push((15&n).toString(16))}return r.join("")},parse:function(t){for(var e=t.length,s=[],r=0;r<e;r+=2)s[r>>>3]|=parseInt(t.substr(r,2),16)<<24-r%8*4;return new u.init(s,e/2)}},p=l.Latin1={stringify:function(t){for(var e=t.words,s=t.sigBytes,r=[],i=0;i<s;i++){var n=e[i>>>2]>>>24-i%4*8&255;r.push(String.fromCharCode(n))}return r.join("")},parse:function(t){for(var e=t.length,s=[],r=0;r<e;r++)s[r>>>2]|=(255&t.charCodeAt(r))<<24-r%4*8;return new u.init(s,e)}},f=l.Utf8={stringify:function(t){try{return decodeURIComponent(escape(p.stringify(t)))}catch(t){throw new Error("Malformed UTF-8 data")}},parse:function(t){return p.parse(unescape(encodeURIComponent(t)))}},g=c.BufferedBlockAlgorithm=h.extend({reset:function(){this._data=new u.init,this._nDataBytes=0},_append:function(t){"string"==typeof t&&(t=f.parse(t)),this._data.concat(t),this._nDataBytes+=t.sigBytes},_process:function(e){var s,r=this._data,i=r.words,n=r.sigBytes,o=this.blockSize,a=n/(4*o),c=(a=e?t.ceil(a):t.max((0|a)-this._minBufferSize,0))*o,h=t.min(4*c,n);if(c){for(var l=0;l<c;l+=o)this._doProcessBlock(i,l);s=i.splice(0,c),r.sigBytes-=h}return new u.init(s,h)},clone:function(){var t=h.clone.call(this);return t._data=this._data.clone(),t},_minBufferSize:0});c.Hasher=g.extend({cfg:h.extend(),init:function(t){this.cfg=this.cfg.extend(t),this.reset()},reset:function(){g.reset.call(this),this._doReset()},update:function(t){return this._append(t),this._process(),this},finalize:function(t){return t&&this._append(t),this._doFinalize()},blockSize:16,_createHelper:function(t){return function(e,s){return new t.init(s).finalize(e)}},_createHmacHelper:function(t){return function(e,s){return new _.HMAC.init(t,s).finalize(e)}}});var _=a.algo={};return a}(Math);return t}()}(n)),n.exports}var c,h=s(a()),u={exports:{}};var l,d=(c||(c=1,function(t){t.exports=function(t){return function(e){var s=t,r=s.lib,i=r.WordArray,n=r.Hasher,o=s.algo,a=[],c=[];!function(){function t(t){for(var s=e.sqrt(t),r=2;r<=s;r++)if(!(t%r))return!1;return!0}function s(t){return 4294967296*(t-(0|t))|0}for(var r=2,i=0;i<64;)t(r)&&(i<8&&(a[i]=s(e.pow(r,.5))),c[i]=s(e.pow(r,1/3)),i++),r++}();var h=[],u=o.SHA256=n.extend({_doReset:function(){this._hash=new i.init(a.slice(0))},_doProcessBlock:function(t,e){for(var s=this._hash.words,r=s[0],i=s[1],n=s[2],o=s[3],a=s[4],u=s[5],l=s[6],d=s[7],p=0;p<64;p++){if(p<16)h[p]=0|t[e+p];else{var f=h[p-15],g=(f<<25|f>>>7)^(f<<14|f>>>18)^f>>>3,_=h[p-2],y=(_<<15|_>>>17)^(_<<13|_>>>19)^_>>>10;h[p]=g+h[p-7]+y+h[p-16]}var m=r&i^r&n^i&n,w=(r<<30|r>>>2)^(r<<19|r>>>13)^(r<<10|r>>>22),b=d+((a<<26|a>>>6)^(a<<21|a>>>11)^(a<<7|a>>>25))+(a&u^~a&l)+c[p]+h[p];d=l,l=u,u=a,a=o+b|0,o=n,n=i,i=r,r=b+(w+m)|0}s[0]=s[0]+r|0,s[1]=s[1]+i|0,s[2]=s[2]+n|0,s[3]=s[3]+o|0,s[4]=s[4]+a|0,s[5]=s[5]+u|0,s[6]=s[6]+l|0,s[7]=s[7]+d|0},_doFinalize:function(){var t=this._data,s=t.words,r=8*this._nDataBytes,i=8*t.sigBytes;return s[i>>>5]|=128<<24-i%32,s[14+(i+64>>>9<<4)]=e.floor(r/4294967296),s[15+(i+64>>>9<<4)]=r,t.sigBytes=4*s.length,this._process(),this._hash},clone:function(){var t=n.clone.call(this);return t._hash=this._hash.clone(),t}});s.SHA256=n._createHelper(u),s.HmacSHA256=n._createHmacHelper(u)}(Math),t.SHA256}(a())}(u)),u.exports),p=s(d),f={exports:{}};var g,_=(l||(l=1,function(t){t.exports=function(t){return function(){var e=t,s=e.lib.WordArray;function r(t,e,r){for(var i=[],n=0,o=0;o<e;o++)if(o%4){var a=r[t.charCodeAt(o-1)]<<o%4*2|r[t.charCodeAt(o)]>>>6-o%4*2;i[n>>>2]|=a<<24-n%4*8,n++}return s.create(i,n)}e.enc.Base64={stringify:function(t){var e=t.words,s=t.sigBytes,r=this._map;t.clamp();for(var i=[],n=0;n<s;n+=3)for(var o=(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,a=0;a<4&&n+.75*a<s;a++)i.push(r.charAt(o>>>6*(3-a)&63));var c=r.charAt(64);if(c)for(;i.length%4;)i.push(c);return i.join("")},parse:function(t){var e=t.length,s=this._map,i=this._reverseMap;if(!i){i=this._reverseMap=[];for(var n=0;n<s.length;n++)i[s.charCodeAt(n)]=n}var o=s.charAt(64);if(o){var a=t.indexOf(o);-1!==a&&(e=a)}return r(t,e,i)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),t.enc.Base64}(a())}(f)),f.exports),y=s(_),m={exports:{}};var w=(g||(g=1,function(t){t.exports=function(t){return t.enc.Utf8}(a())}(m)),m.exports),b=s(w);function v(t){this.message=t}v.prototype=new Error,v.prototype.name="InvalidCharacterError";var k="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new v("'atob' failed: The string to be decoded is not correctly encoded.");for(var s,r,i=0,n=0,o="";r=e.charAt(n++);~r&&(s=i%4?64*s+r:r,i++%4)?o+=String.fromCharCode(255&s>>(-2*i&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return o};function S(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(k(t).replace(/(.)/g,function(t,e){var s=e.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(e)}catch(t){return k(e)}}function E(t){this.message=t}function T(t,e){if("string"!=typeof t)throw new E("Invalid token specified");var s=!0===(e=e||{}).header?0:1;try{return JSON.parse(S(t.split(".")[s]))}catch(t){throw new E("Invalid token specified: "+t.message)}}E.prototype=new Error,E.prototype.name="InvalidTokenError";var C,A,R,O={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},x=(t=>(t[t.NONE=0]="NONE",t[t.ERROR=1]="ERROR",t[t.WARN=2]="WARN",t[t.INFO=3]="INFO",t[t.DEBUG=4]="DEBUG",t))(x||{});(R=x||(x={})).reset=function(){C=3,A=O},R.setLevel=function(t){if(!(0<=t&&t<=4))throw new Error("Invalid log level");C=t},R.setLogger=function(t){A=t};var P=class{constructor(t){this._name=t}debug(...t){C>=4&&A.debug(P._format(this._name,this._method),...t)}info(...t){C>=3&&A.info(P._format(this._name,this._method),...t)}warn(...t){C>=2&&A.warn(P._format(this._name,this._method),...t)}error(...t){C>=1&&A.error(P._format(this._name,this._method),...t)}throw(t){throw this.error(t),t}create(t){const e=Object.create(this);return e._method=t,e.debug("begin"),e}static createStatic(t,e){const s=new P(`${t}.${e}`);return s.debug("begin"),s}static _format(t,e){const s=`[${t}]`;return e?`${s} ${e}:`:s}static debug(t,...e){C>=4&&A.debug(P._format(t),...e)}static info(t,...e){C>=3&&A.info(P._format(t),...e)}static warn(t,...e){C>=2&&A.warn(P._format(t),...e)}static error(t,...e){C>=1&&A.error(P._format(t),...e)}};x.reset();var I=class{static _randomWord(){return h.lib.WordArray.random(1).words[0]}static generateUUIDv4(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,t=>(+t^I._randomWord()&15>>+t/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return I.generateUUIDv4()+I.generateUUIDv4()+I.generateUUIDv4()}static generateCodeChallenge(t){try{const e=p(t);return y.stringify(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw P.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(t,e){const s=b.parse([t,e].join(":"));return y.stringify(s)}},N=class{constructor(t){this._name=t,this._logger=new P(`Event('${this._name}')`),this._callbacks=[]}addHandler(t){return this._callbacks.push(t),()=>this.removeHandler(t)}removeHandler(t){const e=this._callbacks.lastIndexOf(t);e>=0&&this._callbacks.splice(e,1)}raise(...t){this._logger.debug("raise:",...t);for(const e of this._callbacks)e(...t)}},B=class{static decode(t){try{return T(t)}catch(t){throw P.error("JwtUtils.decode",t),t}}},j=class extends N{constructor(){super(...arguments),this._logger=new P(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const t=this._expiration-j.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=j.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){const e=this._logger.create("init");t=Math.max(Math.floor(t),1);const s=j.getEpochTime()+t;if(this.expiration===s&&this._timerHandle)return void e.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),e.debug("using duration",t),this._expiration=s;const r=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*r)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},U=class{static readParams(t,e="query"){if(!t)throw new TypeError("Invalid URL");const s=new URL(t,window.location.origin)["fragment"===e?"hash":"search"];return new URLSearchParams(s.slice(1))}},q=class extends Error{constructor(t,e){var s,r,i;if(super(t.error_description||t.error||""),this.form=e,this.name="ErrorResponse",!t.error)throw P.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=t.error,this.error_description=null!=(s=t.error_description)?s:null,this.error_uri=null!=(r=t.error_uri)?r:null,this.state=t.userState,this.session_state=null!=(i=t.session_state)?i:null}},L=class extends Error{constructor(t){super(t),this.name="ErrorTimeout"}},M=class{constructor(){this._logger=new P("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(t){return this._logger.create(`getItem('${t}')`),this._data[t]}setItem(t,e){this._logger.create(`setItem('${t}')`),this._data[t]=e}removeItem(t){this._logger.create(`removeItem('${t}')`),delete this._data[t]}get length(){return Object.getOwnPropertyNames(this._data).length}key(t){return Object.getOwnPropertyNames(this._data)[t]}},D=class{constructor(t=[],e=null){this._jwtHandler=e,this._logger=new P("JsonService"),this._contentTypes=[],this._contentTypes.push(...t,"application/json"),e&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(t,e={}){const{timeoutInSeconds:s,...r}=e;if(!s)return await fetch(t,r);const i=new AbortController,n=setTimeout(()=>i.abort(),1e3*s);try{return await fetch(t,{...e,signal:i.signal})}catch(t){if(t instanceof DOMException&&"AbortError"===t.name)throw new L("Network timed out");throw t}finally{clearTimeout(n)}}async getJson(t,{token:e,credentials:s}={}){const r=this._logger.create("getJson"),i={Accept:this._contentTypes.join(", ")};let n;e&&(r.debug("token passed, setting Authorization header"),i.Authorization="Bearer "+e);try{r.debug("url:",t),n=await this.fetchWithTimeout(t,{method:"GET",headers:i,credentials:s})}catch(t){throw r.error("Network Error"),t}r.debug("HTTP response received, status",n.status);const o=n.headers.get("Content-Type");if(o&&!this._contentTypes.find(t=>o.startsWith(t))&&r.throw(new Error(`Invalid response Content-Type: ${null!=o?o:"undefined"}, from URL: ${t}`)),n.ok&&this._jwtHandler&&(null==o?void 0:o.startsWith("application/jwt")))return await this._jwtHandler(await n.text());let a;try{a=await n.json()}catch(t){if(r.error("Error parsing JSON response",t),n.ok)throw t;throw new Error(`${n.statusText} (${n.status})`)}if(!n.ok){if(r.error("Error from server:",a),a.error)throw new q(a);throw new Error(`${n.statusText} (${n.status}): ${JSON.stringify(a)}`)}return a}async postForm(t,{body:e,basicAuth:s,timeoutInSeconds:r,initCredentials:i}){const n=this._logger.create("postForm"),o={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded"};let a;void 0!==s&&(o.Authorization="Basic "+s);try{n.debug("url:",t),a=await this.fetchWithTimeout(t,{method:"POST",headers:o,body:e,timeoutInSeconds:r,credentials:i})}catch(t){throw n.error("Network error"),t}n.debug("HTTP response received, status",a.status);const c=a.headers.get("Content-Type");if(c&&!this._contentTypes.find(t=>c.startsWith(t)))throw new Error(`Invalid response Content-Type: ${null!=c?c:"undefined"}, from URL: ${t}`);const h=await a.text();let u={};if(h)try{u=JSON.parse(h)}catch(t){if(n.error("Error parsing JSON response",t),a.ok)throw t;throw new Error(`${a.statusText} (${a.status})`)}if(!a.ok){if(n.error("Error from server:",u),u.error)throw new q(u,e);throw new Error(`${a.statusText} (${a.status}): ${JSON.stringify(u)}`)}return u}},F=class{constructor(t){this._settings=t,this._logger=new P("MetadataService"),this._jsonService=new D(["application/jwk-set+json"]),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const t=this._logger.create("getMetadata");if(this._metadata)return t.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw t.throw(new Error("No authority or metadataUrl configured on settings")),null;t.debug("getting metadata from",this._metadataUrl);const e=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials});return t.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},this._settings.metadataSeed,e),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(t=!0){return this._getMetadataProperty("token_endpoint",t)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(t=!0){return this._getMetadataProperty("revocation_endpoint",t)}getKeysEndpoint(t=!0){return this._getMetadataProperty("jwks_uri",t)}async _getMetadataProperty(t,e=!1){const s=this._logger.create(`_getMetadataProperty('${t}')`),r=await this.getMetadata();if(s.debug("resolved"),void 0===r[t]){if(!0===e)return void s.warn("Metadata does not contain optional property");s.throw(new Error("Metadata does not contain property "+t))}return r[t]}async getSigningKeys(){const t=this._logger.create("getSigningKeys");if(this._signingKeys)return t.debug("returning signingKeys from cache"),this._signingKeys;const e=await this.getKeysEndpoint(!1);t.debug("got jwks_uri",e);const s=await this._jsonService.getJson(e);if(t.debug("got key set",s),!Array.isArray(s.keys))throw t.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=s.keys,this._signingKeys}},z=class{constructor({prefix:t="oidc.",store:e=localStorage}={}){this._logger=new P("WebStorageStateStore"),this._store=e,this._prefix=t}async set(t,e){this._logger.create(`set('${t}')`),t=this._prefix+t,await this._store.setItem(t,e)}async get(t){this._logger.create(`get('${t}')`),t=this._prefix+t;return await this._store.getItem(t)}async remove(t){this._logger.create(`remove('${t}')`),t=this._prefix+t;const e=await this._store.getItem(t);return await this._store.removeItem(t),e}async getAllKeys(){this._logger.create("getAllKeys");const t=await this._store.length,e=[];for(let s=0;s<t;s++){const t=await this._store.key(s);t&&0===t.indexOf(this._prefix)&&e.push(t.substr(this._prefix.length))}return e}},$=class{constructor({authority:t,metadataUrl:e,metadata:s,signingKeys:r,metadataSeed:i,client_id:n,client_secret:o,response_type:a="code",scope:c="openid",redirect_uri:h,post_logout_redirect_uri:u,client_authentication:l="client_secret_post",prompt:d,display:p,max_age:f,ui_locales:g,acr_values:_,resource:y,response_mode:m="query",filterProtocolClaims:w=!0,loadUserInfo:b=!1,staleStateAgeInSeconds:v=900,clockSkewInSeconds:k=300,userInfoJwtIssuer:S="OP",mergeClaims:E=!1,stateStore:T,refreshTokenCredentials:C,revokeTokenAdditionalContentTypes:A,fetchRequestCredentials:R,refreshTokenAllowedScope:O,extraQueryParams:x={},extraTokenParams:P={}}){if(this.authority=t,e?this.metadataUrl=e:(this.metadataUrl=t,t&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=s,this.metadataSeed=i,this.signingKeys=r,this.client_id=n,this.client_secret=o,this.response_type=a,this.scope=c,this.redirect_uri=h,this.post_logout_redirect_uri=u,this.client_authentication=l,this.prompt=d,this.display=p,this.max_age=f,this.ui_locales=g,this.acr_values=_,this.resource=y,this.response_mode=m,this.filterProtocolClaims=null==w||w,this.loadUserInfo=!!b,this.staleStateAgeInSeconds=v,this.clockSkewInSeconds=k,this.userInfoJwtIssuer=S,this.mergeClaims=!!E,this.revokeTokenAdditionalContentTypes=A,R&&C&&console.warn("Both fetchRequestCredentials and refreshTokenCredentials is set. Only fetchRequestCredentials will be used."),this.fetchRequestCredentials=R||(C||"same-origin"),T)this.stateStore=T;else{const t="undefined"!=typeof window?window.localStorage:new M;this.stateStore=new z({store:t})}this.refreshTokenAllowedScope=O,this.extraQueryParams=x,this.extraTokenParams=P}},H=class{constructor(t,e){this._settings=t,this._metadataService=e,this._logger=new P("UserInfoService"),this._getClaimsFromJwt=async t=>{const e=this._logger.create("_getClaimsFromJwt");try{const s=B.decode(t);return e.debug("JWT decoding successful"),s}catch(t){throw e.error("Error parsing JWT response"),t}},this._jsonService=new D(void 0,this._getClaimsFromJwt)}async getClaims(t){const e=this._logger.create("getClaims");t||this._logger.throw(new Error("No token passed"));const s=await this._metadataService.getUserInfoEndpoint();e.debug("got userinfo url",s);const r=await this._jsonService.getJson(s,{token:t,credentials:this._settings.fetchRequestCredentials});return e.debug("got claims",r),r}},K=class{constructor(t,e){this._settings=t,this._metadataService=e,this._logger=new P("TokenClient"),this._jsonService=new D(this._settings.revokeTokenAdditionalContentTypes)}async exchangeCode({grant_type:t="authorization_code",redirect_uri:e=this._settings.redirect_uri,client_id:s=this._settings.client_id,client_secret:r=this._settings.client_secret,...i}){const n=this._logger.create("exchangeCode");s||n.throw(new Error("A client_id is required")),e||n.throw(new Error("A redirect_uri is required")),i.code||n.throw(new Error("A code is required")),i.code_verifier||n.throw(new Error("A code_verifier is required"));const o=new URLSearchParams({grant_type:t,redirect_uri:e});for(const[t,e]of Object.entries(i))null!=e&&o.set(t,e);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!r)throw n.throw(new Error("A client_secret is required")),null;a=I.generateBasicAuth(s,r);break;case"client_secret_post":o.append("client_id",s),r&&o.append("client_secret",r)}const c=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");const h=await this._jsonService.postForm(c,{body:o,basicAuth:a,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),h}async exchangeCredentials({grant_type:t="password",client_id:e=this._settings.client_id,client_secret:s=this._settings.client_secret,scope:r=this._settings.scope,...i}){const n=this._logger.create("exchangeCredentials");e||n.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:t,scope:r});for(const[t,e]of Object.entries(i))null!=e&&o.set(t,e);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!s)throw n.throw(new Error("A client_secret is required")),null;a=I.generateBasicAuth(e,s);break;case"client_secret_post":o.append("client_id",e),s&&o.append("client_secret",s)}const c=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");const h=await this._jsonService.postForm(c,{body:o,basicAuth:a,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),h}async exchangeRefreshToken({grant_type:t="refresh_token",client_id:e=this._settings.client_id,client_secret:s=this._settings.client_secret,timeoutInSeconds:r,...i}){const n=this._logger.create("exchangeRefreshToken");e||n.throw(new Error("A client_id is required")),i.refresh_token||n.throw(new Error("A refresh_token is required"));const o=new URLSearchParams({grant_type:t});for(const[t,e]of Object.entries(i))null!=e&&o.set(t,e);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!s)throw n.throw(new Error("A client_secret is required")),null;a=I.generateBasicAuth(e,s);break;case"client_secret_post":o.append("client_id",e),s&&o.append("client_secret",s)}const c=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");const h=await this._jsonService.postForm(c,{body:o,basicAuth:a,timeoutInSeconds:r,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),h}async revoke(t){var e;const s=this._logger.create("revoke");t.token||s.throw(new Error("A token is required"));const r=await this._metadataService.getRevocationEndpoint(!1);s.debug(`got revocation endpoint, revoking ${null!=(e=t.token_type_hint)?e:"default token type"}`);const i=new URLSearchParams;for(const[e,s]of Object.entries(t))null!=s&&i.set(e,s);i.set("client_id",this._settings.client_id),this._settings.client_secret&&i.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(r,{body:i}),s.debug("got response")}},V=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],J=["sub","iss","aud","exp","iat"],W=class{constructor(t,e){this._settings=t,this._metadataService=e,this._logger=new P("ResponseValidator"),this._userInfoService=new H(this._settings,this._metadataService),this._tokenClient=new K(this._settings,this._metadataService)}async validateSigninResponse(t,e){const s=this._logger.create("validateSigninResponse");this._processSigninState(t,e),s.debug("state processed"),await this._processCode(t,e),s.debug("code processed"),t.isOpenId&&this._validateIdTokenAttributes(t),s.debug("tokens validated"),await this._processClaims(t,null==e?void 0:e.skipUserInfo,t.isOpenId),s.debug("claims processed")}async validateCredentialsResponse(t,e){const s=this._logger.create("validateCredentialsResponse");t.isOpenId&&this._validateIdTokenAttributes(t),s.debug("tokens validated"),await this._processClaims(t,e,t.isOpenId),s.debug("claims processed")}async validateRefreshResponse(t,e){const s=this._logger.create("validateRefreshResponse");t.userState=e.data,null!=t.session_state||(t.session_state=e.session_state),null!=t.scope||(t.scope=e.scope),t.isOpenId&&t.id_token&&(this._validateIdTokenAttributes(t,e.id_token),s.debug("ID Token validated")),t.id_token||(t.id_token=e.id_token,t.profile=e.profile);const r=t.isOpenId&&!!t.id_token;await this._processClaims(t,!1,r),s.debug("claims processed")}validateSignoutResponse(t,e){const s=this._logger.create("validateSignoutResponse");if(e.id!==t.state&&s.throw(new Error("State does not match")),s.debug("state validated"),t.userState=e.data,t.error)throw s.warn("Response was error",t.error),new q(t)}_processSigninState(t,e){const s=this._logger.create("_processSigninState");if(e.id!==t.state&&s.throw(new Error("State does not match")),e.client_id||s.throw(new Error("No client_id on state")),e.authority||s.throw(new Error("No authority on state")),this._settings.authority!==e.authority&&s.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==e.client_id&&s.throw(new Error("client_id mismatch on settings vs. signin state")),s.debug("state validated"),t.userState=e.data,null!=t.scope||(t.scope=e.scope),t.error)throw s.warn("Response was error",t.error),new q(t);e.code_verifier&&!t.code&&s.throw(new Error("Expected code in response")),!e.code_verifier&&t.code&&s.throw(new Error("Unexpected code in response"))}async _processClaims(t,e=!1,s=!0){const r=this._logger.create("_processClaims");if(t.profile=this._filterProtocolClaims(t.profile),e||!this._settings.loadUserInfo||!t.access_token)return void r.debug("not loading user info");r.debug("loading user info");const i=await this._userInfoService.getClaims(t.access_token);r.debug("user info claims received from user info endpoint"),s&&i.sub!==t.profile.sub&&r.throw(new Error("subject from UserInfo response does not match subject in ID Token")),t.profile=this._mergeClaims(t.profile,this._filterProtocolClaims(i)),r.debug("user info claims received, updated profile:",t.profile)}_mergeClaims(t,e){const s={...t};for(const[t,r]of Object.entries(e))for(const e of Array.isArray(r)?r:[r]){const r=s[t];r?Array.isArray(r)?r.includes(e)||r.push(e):s[t]!==e&&("object"==typeof e&&this._settings.mergeClaims?s[t]=this._mergeClaims(r,e):s[t]=[r,e]):s[t]=e}return s}_filterProtocolClaims(t){const e={...t};if(this._settings.filterProtocolClaims){let t;t=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:V;for(const s of t)J.includes(s)||delete e[s]}return e}async _processCode(t,e){const s=this._logger.create("_processCode");if(t.code){s.debug("Validating code");const r=await this._tokenClient.exchangeCode({client_id:e.client_id,client_secret:e.client_secret,code:t.code,redirect_uri:e.redirect_uri,code_verifier:e.code_verifier,...e.extraTokenParams});Object.assign(t,r)}else s.debug("No code to process")}_validateIdTokenAttributes(t,e){var s;const r=this._logger.create("_validateIdTokenAttributes");r.debug("decoding ID Token JWT");const i=B.decode(null!=(s=t.id_token)?s:"");if(i.sub||r.throw(new Error("ID Token is missing a subject claim")),e){const t=B.decode(e);t.sub!==i.sub&&r.throw(new Error("sub in id_token does not match current sub")),t.auth_time&&t.auth_time!==i.auth_time&&r.throw(new Error("auth_time in id_token does not match original auth_time")),t.azp&&t.azp!==i.azp&&r.throw(new Error("azp in id_token does not match original azp")),!t.azp&&i.azp&&r.throw(new Error("azp not in id_token, but present in original id_token"))}t.profile=i}},Q=class{constructor(t){this.id=t.id||I.generateUUIDv4(),this.data=t.data,t.created&&t.created>0?this.created=t.created:this.created=j.getEpochTime(),this.request_type=t.request_type}toStorageString(){return new P("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type})}static fromStorageString(t){return P.createStatic("State","fromStorageString"),new Q(JSON.parse(t))}static async clearStaleState(t,e){const s=P.createStatic("State","clearStaleState"),r=j.getEpochTime()-e,i=await t.getAllKeys();s.debug("got keys",i);for(let e=0;e<i.length;e++){const n=i[e],o=await t.get(n);let a=!1;if(o)try{const t=Q.fromStorageString(o);s.debug("got item from key:",n,t.created),t.created<=r&&(a=!0)}catch(t){s.error("Error parsing state for key:",n,t),a=!0}else s.debug("no item in storage for key:",n),a=!0;a&&(s.debug("removed item for key:",n),t.remove(n))}}},Y=class extends Q{constructor(t){super(t),!0===t.code_verifier?this.code_verifier=I.generateCodeVerifier():t.code_verifier&&(this.code_verifier=t.code_verifier),this.code_verifier&&(this.code_challenge=I.generateCodeChallenge(this.code_verifier)),this.authority=t.authority,this.client_id=t.client_id,this.redirect_uri=t.redirect_uri,this.scope=t.scope,this.client_secret=t.client_secret,this.extraTokenParams=t.extraTokenParams,this.response_mode=t.response_mode,this.skipUserInfo=t.skipUserInfo}toStorageString(){return new P("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(t){P.createStatic("SigninState","fromStorageString");const e=JSON.parse(t);return new Y(e)}},G=class{constructor({url:t,authority:e,client_id:s,redirect_uri:r,response_type:i,scope:n,state_data:o,response_mode:a,request_type:c,client_secret:h,nonce:u,resource:l,skipUserInfo:d,extraQueryParams:p,extraTokenParams:f,...g}){if(this._logger=new P("SigninRequest"),!t)throw this._logger.error("ctor: No url passed"),new Error("url");if(!s)throw this._logger.error("ctor: No client_id passed"),new Error("client_id");if(!r)throw this._logger.error("ctor: No redirect_uri passed"),new Error("redirect_uri");if(!i)throw this._logger.error("ctor: No response_type passed"),new Error("response_type");if(!n)throw this._logger.error("ctor: No scope passed"),new Error("scope");if(!e)throw this._logger.error("ctor: No authority passed"),new Error("authority");this.state=new Y({data:o,request_type:c,code_verifier:!0,client_id:s,authority:e,redirect_uri:r,response_mode:a,client_secret:h,scope:n,extraTokenParams:f,skipUserInfo:d});const _=new URL(t);if(_.searchParams.append("client_id",s),_.searchParams.append("redirect_uri",r),_.searchParams.append("response_type",i),_.searchParams.append("scope",n),u&&_.searchParams.append("nonce",u),_.searchParams.append("state",this.state.id),this.state.code_challenge&&(_.searchParams.append("code_challenge",this.state.code_challenge),_.searchParams.append("code_challenge_method","S256")),l){(Array.isArray(l)?l:[l]).forEach(t=>_.searchParams.append("resource",t))}for(const[t,e]of Object.entries({response_mode:a,...g,...p}))null!=e&&_.searchParams.append(t,e.toString());this.url=_.href}},X=class{constructor(t){this.access_token="",this.token_type="",this.profile={},this.state=t.get("state"),this.session_state=t.get("session_state"),this.error=t.get("error"),this.error_description=t.get("error_description"),this.error_uri=t.get("error_uri"),this.code=t.get("code")}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-j.getEpochTime()}set expires_in(t){"string"==typeof t&&(t=Number(t)),void 0!==t&&t>=0&&(this.expires_at=Math.floor(t)+j.getEpochTime())}get isOpenId(){var t;return(null==(t=this.scope)?void 0:t.split(" ").includes("openid"))||!!this.id_token}},Z=class{constructor({url:t,state_data:e,id_token_hint:s,post_logout_redirect_uri:r,extraQueryParams:i,request_type:n}){if(this._logger=new P("SignoutRequest"),!t)throw this._logger.error("ctor: No url passed"),new Error("url");const o=new URL(t);s&&o.searchParams.append("id_token_hint",s),r&&(o.searchParams.append("post_logout_redirect_uri",r),e&&(this.state=new Q({data:e,request_type:n}),o.searchParams.append("state",this.state.id)));for(const[t,e]of Object.entries({...i}))null!=e&&o.searchParams.append(t,e.toString());this.url=o.href}},tt=class{constructor(t){this.state=t.get("state"),this.error=t.get("error"),this.error_description=t.get("error_description"),this.error_uri=t.get("error_uri")}},et=class{constructor(t){this._logger=new P("OidcClient"),this.settings=new $(t),this.metadataService=new F(this.settings),this._validator=new W(this.settings,this.metadataService),this._tokenClient=new K(this.settings,this.metadataService)}async createSigninRequest({state:t,request:e,request_uri:s,request_type:r,id_token_hint:i,login_hint:n,skipUserInfo:o,nonce:a,response_type:c=this.settings.response_type,scope:h=this.settings.scope,redirect_uri:u=this.settings.redirect_uri,prompt:l=this.settings.prompt,display:d=this.settings.display,max_age:p=this.settings.max_age,ui_locales:f=this.settings.ui_locales,acr_values:g=this.settings.acr_values,resource:_=this.settings.resource,response_mode:y=this.settings.response_mode,extraQueryParams:m=this.settings.extraQueryParams,extraTokenParams:w=this.settings.extraTokenParams}){const b=this._logger.create("createSigninRequest");if("code"!==c)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const v=await this.metadataService.getAuthorizationEndpoint();b.debug("Received authorization endpoint",v);const k=new G({url:v,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:u,response_type:c,scope:h,state_data:t,prompt:l,display:d,max_age:p,ui_locales:f,id_token_hint:i,login_hint:n,acr_values:g,resource:_,request:e,request_uri:s,extraQueryParams:m,extraTokenParams:w,request_type:r,response_mode:y,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a});await this.clearStaleState();const S=k.state;return await this.settings.stateStore.set(S.id,S.toStorageString()),k}async readSigninResponseState(t,e=!1){const s=this._logger.create("readSigninResponseState"),r=new X(U.readParams(t,this.settings.response_mode));if(!r.state)throw s.throw(new Error("No state in response")),null;const i=await this.settings.stateStore[e?"remove":"get"](r.state);if(!i)throw s.throw(new Error("No matching state found in storage")),null;return{state:Y.fromStorageString(i),response:r}}async processSigninResponse(t){const e=this._logger.create("processSigninResponse"),{state:s,response:r}=await this.readSigninResponseState(t,!0);return e.debug("received state from storage; validating response"),await this._validator.validateSigninResponse(r,s),r}async processResourceOwnerPasswordCredentials({username:t,password:e,skipUserInfo:s=!1,extraTokenParams:r={}}){const i=await this._tokenClient.exchangeCredentials({username:t,password:e,...r}),n=new X(new URLSearchParams);return Object.assign(n,i),await this._validator.validateCredentialsResponse(n,s),n}async useRefreshToken({state:t,timeoutInSeconds:e}){var s;const r=this._logger.create("useRefreshToken");let i;if(void 0===this.settings.refreshTokenAllowedScope)i=t.scope;else{const e=this.settings.refreshTokenAllowedScope.split(" ");i=((null==(s=t.scope)?void 0:s.split(" "))||[]).filter(t=>e.includes(t)).join(" ")}const n=await this._tokenClient.exchangeRefreshToken({refresh_token:t.refresh_token,scope:i,timeoutInSeconds:e}),o=new X(new URLSearchParams);return Object.assign(o,n),r.debug("validating response",o),await this._validator.validateRefreshResponse(o,{...t,scope:i}),o}async createSignoutRequest({state:t,id_token_hint:e,request_type:s,post_logout_redirect_uri:r=this.settings.post_logout_redirect_uri,extraQueryParams:i=this.settings.extraQueryParams}={}){const n=this._logger.create("createSignoutRequest"),o=await this.metadataService.getEndSessionEndpoint();if(!o)throw n.throw(new Error("No end session endpoint")),null;n.debug("Received end session endpoint",o);const a=new Z({url:o,id_token_hint:e,post_logout_redirect_uri:r,state_data:t,extraQueryParams:i,request_type:s});await this.clearStaleState();const c=a.state;return c&&(n.debug("Signout request has state to persist"),await this.settings.stateStore.set(c.id,c.toStorageString())),a}async readSignoutResponseState(t,e=!1){const s=this._logger.create("readSignoutResponseState"),r=new tt(U.readParams(t,this.settings.response_mode));if(!r.state){if(s.debug("No state in response"),r.error)throw s.warn("Response was error:",r.error),new q(r);return{state:void 0,response:r}}const i=await this.settings.stateStore[e?"remove":"get"](r.state);if(!i)throw s.throw(new Error("No matching state found in storage")),null;return{state:Q.fromStorageString(i),response:r}}async processSignoutResponse(t){const e=this._logger.create("processSignoutResponse"),{state:s,response:r}=await this.readSignoutResponseState(t,!0);return s?(e.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(r,s)):e.debug("No state from storage; skipping response validation"),r}clearStaleState(){return this._logger.create("clearStaleState"),Q.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(t,e){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:t,token_type_hint:e})}};const st={},rt=(t,e)=>ot()?localStorage.setItem(t,e):st[t]=e,it=t=>ot()?localStorage.getItem(t):st[t],nt=t=>ot()?localStorage.removeItem(t):delete st[t],ot=()=>!("object"==typeof process&&"[object process]"===String(process));let at=null;class ct{constructor(t){const e=t.authUrl||"https://auth.gameglue.gg/realms/GameGlue";this._oidcSettings={authority:e,client_id:t.clientId,redirect_uri:ht(t.redirect_uri||window.location.href),post_logout_redirect_uri:ht(window.location.href),response_type:"code",scope:`openid ${(t.scopes||[]).join(" ")}`,response_mode:"fragment",filterProtocolClaims:!0},this._oidcClient=new et(this._oidcSettings),this._refreshCallback=()=>{},this._refreshTimeout=null}async isAuthenticated(){return this._hasCallbackParams()&&await this._processCallback(),this._hasValidTokens()}login(){this._oidcClient.createSigninRequest({state:{bar:15}}).then(t=>{window.location=t.url}).catch(t=>{console.error("Failed to create signin request:",t)})}logout(t={}){if(nt("gg-auth-token"),nt("gg-refresh-token"),clearTimeout(this._refreshTimeout),!1!==t.redirect){const t=`${this._oidcSettings.authority}/protocol/openid-connect/logout?post_logout_redirect_uri=${encodeURIComponent(this._oidcSettings.post_logout_redirect_uri)}`;window.location.href=t}}getUser(){const t=this._getAccessToken();if(!t)throw new Error("Not authenticated");return T(t).sub}getAccessToken(){return this._getAccessToken()}onTokenRefreshed(t){this._refreshCallback=t}_hasCallbackParams(){return location.hash.includes("state=")&&(location.hash.includes("code=")||location.hash.includes("error="))}_clearCallbackUrl(){window.history.replaceState("",document.title,window.location.pathname+window.location.search)}async _processCallback(){if(at)await at;else{at=this._doProcessCallback();try{await at}finally{at=null}}}async _doProcessCallback(){try{const t=await this._oidcClient.processSigninResponse(window.location.href);if(t.error)throw this._clearCallbackUrl(),new Error(t.error);if(!t.access_token)throw this._clearCallbackUrl(),new Error("No access token received");this._setAccessToken(t.access_token),this._setRefreshToken(t.refresh_token),this._clearCallbackUrl()}catch(t){if(this._hasValidTokens())return void this._clearCallbackUrl();throw this._clearCallbackUrl(),t}}_hasValidTokens(){const t=this._getAccessToken();if(!t)return!1;try{const e=T(t);return new Date(1e3*e.exp)>new Date}catch{return!1}}_getAccessToken(){const t=it("gg-auth-token");return t&&this._setTokenRefreshTimeout(t),t}_setAccessToken(t){return this._setTokenRefreshTimeout(t),rt("gg-auth-token",t)}_setRefreshToken(t){return rt("gg-refresh-token",t)}_getRefreshToken(){return it("gg-refresh-token")}_setTokenRefreshTimeout(t){if(t){clearTimeout(this._refreshTimeout);try{const e=1e3*T(t).exp-Date.now()-5e3;e>0&&(this._refreshTimeout=setTimeout(()=>{this._attemptRefresh()},e))}catch{}}}async _attemptRefresh(){const t=`${this._oidcSettings.authority}/protocol/openid-connect/token`,e=this._oidcSettings.client_id,s=this._getRefreshToken();try{const r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e,grant_type:"refresh_token",refresh_token:s})});if(200===r.status){const t=await r.json();this._setAccessToken(t.access_token),this._setRefreshToken(t.refresh_token),this._refreshCallback(t.access_token)}}catch(t){console.error("Token refresh failed:",t)}}}function ht(t){return t.endsWith("/")?t.replace(/\/+$/,""):t}const ut=Object.create(null);ut.open="0",ut.close="1",ut.ping="2",ut.pong="3",ut.message="4",ut.upgrade="5",ut.noop="6";const lt=Object.create(null);Object.keys(ut).forEach(t=>{lt[ut[t]]=t});const dt={type:"error",data:"parser error"},pt="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),ft="function"==typeof ArrayBuffer,gt=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,_t=({type:t,data:e},s,r)=>pt&&e instanceof Blob?s?r(e):yt(e,r):ft&&(e instanceof ArrayBuffer||gt(e))?s?r(e):yt(new Blob([e]),r):r(ut[t]+(e||"")),yt=(t,e)=>{const s=new FileReader;return s.onload=function(){const t=s.result.split(",")[1];e("b"+(t||""))},s.readAsDataURL(t)};function mt(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let wt;const bt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",vt="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)vt[bt.charCodeAt(t)]=t;const kt="function"==typeof ArrayBuffer,St=(t,e)=>{if("string"!=typeof t)return{type:"message",data:Tt(t,e)};const s=t.charAt(0);if("b"===s)return{type:"message",data:Et(t.substring(1),e)};return lt[s]?t.length>1?{type:lt[s],data:t.substring(1)}:{type:lt[s]}:dt},Et=(t,e)=>{if(kt){const s=(t=>{let e,s,r,i,n,o=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(o--,"="===t[t.length-2]&&o--);const h=new ArrayBuffer(o),u=new Uint8Array(h);for(e=0;e<a;e+=4)s=vt[t.charCodeAt(e)],r=vt[t.charCodeAt(e+1)],i=vt[t.charCodeAt(e+2)],n=vt[t.charCodeAt(e+3)],u[c++]=s<<2|r>>4,u[c++]=(15&r)<<4|i>>2,u[c++]=(3&i)<<6|63&n;return h})(t);return Tt(s,e)}return{base64:!0,data:t}},Tt=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,Ct=String.fromCharCode(30);function At(){return new TransformStream({transform(t,e){!function(t,e){pt&&t.data instanceof Blob?t.data.arrayBuffer().then(mt).then(e):ft&&(t.data instanceof ArrayBuffer||gt(t.data))?e(mt(t.data)):_t(t,!1,t=>{wt||(wt=new TextEncoder),e(wt.encode(t))})}(t,s=>{const r=s.length;let i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);const t=new DataView(i.buffer);t.setUint8(0,126),t.setUint16(1,r)}else{i=new Uint8Array(9);const t=new DataView(i.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(r))}t.data&&"string"!=typeof t.data&&(i[0]|=128),e.enqueue(i),e.enqueue(s)})}})}let Rt;function Ot(t){return t.reduce((t,e)=>t+e.length,0)}function xt(t,e){if(t[0].length===e)return t.shift();const s=new Uint8Array(e);let r=0;for(let i=0;i<e;i++)s[i]=t[0][r++],r===t[0].length&&(t.shift(),r=0);return t.length&&r<t[0].length&&(t[0]=t[0].slice(r)),s}function Pt(t){if(t)return function(t){for(var e in Pt.prototype)t[e]=Pt.prototype[e];return t}(t)}Pt.prototype.on=Pt.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},Pt.prototype.once=function(t,e){function s(){this.off(t,s),e.apply(this,arguments)}return s.fn=e,this.on(t,s),this},Pt.prototype.off=Pt.prototype.removeListener=Pt.prototype.removeAllListeners=Pt.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var s,r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var i=0;i<r.length;i++)if((s=r[i])===e||s.fn===e){r.splice(i,1);break}return 0===r.length&&delete this._callbacks["$"+t],this},Pt.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),s=this._callbacks["$"+t],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(s){r=0;for(var i=(s=s.slice(0)).length;r<i;++r)s[r].apply(this,e)}return this},Pt.prototype.emitReserved=Pt.prototype.emit,Pt.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},Pt.prototype.hasListeners=function(t){return!!this.listeners(t).length};const It="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),Nt="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Bt(t,...e){return e.reduce((e,s)=>(t.hasOwnProperty(s)&&(e[s]=t[s]),e),{})}const jt=Nt.setTimeout,Ut=Nt.clearTimeout;function qt(t,e){e.useNativeTimers?(t.setTimeoutFn=jt.bind(Nt),t.clearTimeoutFn=Ut.bind(Nt)):(t.setTimeoutFn=Nt.setTimeout.bind(Nt),t.clearTimeoutFn=Nt.clearTimeout.bind(Nt))}function Lt(t){return"string"==typeof t?function(t){let e=0,s=0;for(let r=0,i=t.length;r<i;r++)e=t.charCodeAt(r),e<128?s+=1:e<2048?s+=2:e<55296||e>=57344?s+=3:(r++,s+=4);return s}(t):Math.ceil(1.33*(t.byteLength||t.size))}function Mt(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class Dt extends Error{constructor(t,e,s){super(t),this.description=e,this.context=s,this.type="TransportError"}}class Ft extends Pt{constructor(t){super(),this.writable=!1,qt(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,s){return super.emitReserved("error",new Dt(t,e,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=St(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(t){const e=function(t){let e="";for(let s in t)t.hasOwnProperty(s)&&(e.length&&(e+="&"),e+=encodeURIComponent(s)+"="+encodeURIComponent(t[s]));return e}(t);return e.length?"?"+e:""}}class zt extends Ft{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let t=0;this._polling&&(t++,this.once("pollComplete",function(){--t||e()})),this.writable||(t++,this.once("drain",function(){--t||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){((t,e)=>{const s=t.split(Ct),r=[];for(let t=0;t<s.length;t++){const i=St(s[t],e);if(r.push(i),"error"===i.type)break}return r})(t,this.socket.binaryType).forEach(t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const s=t.length,r=new Array(s);let i=0;t.forEach((t,n)=>{_t(t,!1,t=>{r[n]=t,++i===s&&e(r.join(Ct))})})})(t,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=Mt()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let $t=!1;try{$t="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const Ht=$t;function Kt(){}class Vt extends zt{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let s=location.port;s||(s=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||s!==t.port}}doWrite(t,e){const s=this.request({method:"POST",data:t});s.on("success",e),s.on("error",(t,e)=>{this.onError("xhr post error",t,e)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t,e)=>{this.onError("xhr poll error",t,e)}),this.pollXhr=t}}class Jt extends Pt{constructor(t,e,s){super(),this.createRequest=t,qt(this,s),this._opts=s,this._method=s.method||"GET",this._uri=e,this._data=void 0!==s.data?s.data:null,this._create()}_create(){var t;const e=Bt(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(e);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let t in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(t)&&s.setRequestHeader(t,this._opts.extraHeaders[t])}}catch(t){}if("POST"===this._method)try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{s.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var t;3===s.readyState&&(null===(t=this._opts.cookieJar)||void 0===t||t.parseCookies(s.getResponseHeader("set-cookie"))),4===s.readyState&&(200===s.status||1223===s.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof s.status?s.status:0)},0))},s.send(this._data)}catch(t){return void this.setTimeoutFn(()=>{this._onError(t)},0)}"undefined"!=typeof document&&(this._index=Jt.requestsCount++,Jt.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=Kt,t)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete Jt.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(Jt.requestsCount=0,Jt.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",Wt);else if("function"==typeof addEventListener){addEventListener("onpagehide"in Nt?"pagehide":"unload",Wt,!1)}function Wt(){for(let t in Jt.requests)Jt.requests.hasOwnProperty(t)&&Jt.requests[t].abort()}const Qt=function(){const t=Yt({xdomain:!1});return t&&null!==t.responseType}();function Yt(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||Ht))return new XMLHttpRequest}catch(t){}if(!e)try{return new(Nt[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const Gt="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Xt extends Ft{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,s=Gt?{}:Bt(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,s)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],r=e===t.length-1;_t(s,this.supportsBinary,t=>{try{this.doWrite(s,t)}catch(t){}r&&It(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=Mt()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const Zt=Nt.WebSocket||Nt.MozWebSocket;const te={websocket:class extends Xt{createSocket(t,e,s){return Gt?new Zt(t,e,s):e?new Zt(t,e):new Zt(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends Ft{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const e=function(t,e){Rt||(Rt=new TextDecoder);const s=[];let r=0,i=-1,n=!1;return new TransformStream({transform(o,a){for(s.push(o);;){if(0===r){if(Ot(s)<1)break;const t=xt(s,1);n=!(128&~t[0]),i=127&t[0],r=i<126?3:126===i?1:2}else if(1===r){if(Ot(s)<2)break;const t=xt(s,2);i=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),r=3}else if(2===r){if(Ot(s)<8)break;const t=xt(s,8),e=new DataView(t.buffer,t.byteOffset,t.length),n=e.getUint32(0);if(n>Math.pow(2,21)-1){a.enqueue(dt);break}i=n*Math.pow(2,32)+e.getUint32(4),r=3}else{if(Ot(s)<i)break;const t=xt(s,i);a.enqueue(St(n?t:Rt.decode(t),e)),r=0}if(0===i||i>t){a.enqueue(dt);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=t.readable.pipeThrough(e).getReader(),r=At();r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const i=()=>{s.read().then(({done:t,value:e})=>{t||(this.onPacket(e),i())}).catch(t=>{})};i();const n={type:"open"};this.query.sid&&(n.data=`{"sid":"${this.query.sid}"}`),this._writer.write(n).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],r=e===t.length-1;this._writer.write(s).then(()=>{r&&It(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this._transport)||void 0===t||t.close()}},polling:class extends Vt{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=Qt&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Jt(Yt,this.uri(),t)}}},ee=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,se=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function re(t){if(t.length>8e3)throw"URI too long";const e=t,s=t.indexOf("["),r=t.indexOf("]");-1!=s&&-1!=r&&(t=t.substring(0,s)+t.substring(s,r).replace(/:/g,";")+t.substring(r,t.length));let i=ee.exec(t||""),n={},o=14;for(;o--;)n[se[o]]=i[o]||"";return-1!=s&&-1!=r&&(n.source=e,n.host=n.host.substring(1,n.host.length-1).replace(/;/g,":"),n.authority=n.authority.replace("[","").replace("]","").replace(/;/g,":"),n.ipv6uri=!0),n.pathNames=function(t,e){const s=/\/{2,9}/g,r=e.replace(s,"/").split("/");"/"!=e.slice(0,1)&&0!==e.length||r.splice(0,1);"/"==e.slice(-1)&&r.splice(r.length-1,1);return r}(0,n.path),n.queryKey=function(t,e){const s={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,r){e&&(s[e]=r)}),s}(0,n.query),n}const ie="function"==typeof addEventListener&&"function"==typeof removeEventListener,ne=[];ie&&addEventListener("offline",()=>{ne.forEach(t=>t())},!1);class oe extends Pt{constructor(t,e){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&"object"==typeof t&&(e=t,t=null),t){const s=re(t);e.hostname=s.host,e.secure="https"===s.protocol||"wss"===s.protocol,e.port=s.port,s.query&&(e.query=s.query)}else e.host&&(e.hostname=re(e.host).host);qt(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(t=>{const e=t.prototype.name;this.transports.push(e),this._transportsByName[e]=t}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(t){let e={},s=t.split("&");for(let t=0,r=s.length;t<r;t++){let r=s[t].split("=");e[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return e}(this.opts.query)),ie&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},ne.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const s=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](s)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&oe.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",oe.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let e=0;e<this.writeBuffer.length;e++){const s=this.writeBuffer[e].data;if(s&&(t+=Lt(s)),e>0&&t>this._maxPayload)return this.writeBuffer.slice(0,e);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,It(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,s){return this._sendPacket("message",t,e,s),this}send(t,e,s){return this._sendPacket("message",t,e,s),this}_sendPacket(t,e,s,r){if("function"==typeof e&&(r=e,e=void 0),"function"==typeof s&&(r=s,s=null),"closing"===this.readyState||"closed"===this.readyState)return;(s=s||{}).compress=!1!==s.compress;const i={type:t,data:e,options:s};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},s=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():t()}):this.upgrading?s():t()),this}_onError(t){if(oe.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),ie&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=ne.indexOf(this._offlineEventListener);-1!==t&&ne.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}oe.protocol=4;class ae extends oe{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),s=!1;oe.priorWebsocketSuccess=!1;const r=()=>{s||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!s)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;oe.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{s||"closed"!==this.readyState&&(h(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}}))};function i(){s||(s=!0,h(),e.close(),e=null)}const n=t=>{const s=new Error("probe error: "+t);s.transport=e.name,i(),this.emitReserved("upgradeError",s)};function o(){n("transport closed")}function a(){n("socket closed")}function c(t){e&&t.name!==e.name&&i()}const h=()=>{e.removeListener("open",r),e.removeListener("error",n),e.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};e.once("open",r),e.once("error",n),e.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{s||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let s=0;s<t.length;s++)~this.transports.indexOf(t[s])&&e.push(t[s]);return e}}let ce=class extends ae{constructor(t,e={}){const s="object"==typeof t?t:e;(!s.transports||s.transports&&"string"==typeof s.transports[0])&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(t=>te[t]).filter(t=>!!t)),super(t,s)}};const he="function"==typeof ArrayBuffer,ue=Object.prototype.toString,le="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===ue.call(Blob),de="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===ue.call(File);function pe(t){return he&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||le&&t instanceof Blob||de&&t instanceof File}function fe(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,s=t.length;e<s;e++)if(fe(t[e]))return!0;return!1}if(pe(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return fe(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&fe(t[e]))return!0;return!1}function ge(t){const e=[],s=t.data,r=t;return r.data=_e(s,e),r.attachments=e.length,{packet:r,buffers:e}}function _e(t,e){if(!t)return t;if(pe(t)){const s={_placeholder:!0,num:e.length};return e.push(t),s}if(Array.isArray(t)){const s=new Array(t.length);for(let r=0;r<t.length;r++)s[r]=_e(t[r],e);return s}if("object"==typeof t&&!(t instanceof Date)){const s={};for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(s[r]=_e(t[r],e));return s}return t}function ye(t,e){return t.data=me(t.data,e),delete t.attachments,t}function me(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let s=0;s<t.length;s++)t[s]=me(t[s],e);else if("object"==typeof t)for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(t[s]=me(t[s],e));return t}const we=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var be;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(be||(be={}));class ve extends Pt{constructor(t){super(),this.reviver=t}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const s=e.type===be.BINARY_EVENT;s||e.type===be.BINARY_ACK?(e.type=s?be.EVENT:be.ACK,this.reconstructor=new ke(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!pe(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const s={type:Number(t.charAt(0))};if(void 0===be[s.type])throw new Error("unknown packet type "+s.type);if(s.type===be.BINARY_EVENT||s.type===be.BINARY_ACK){const r=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const i=t.substring(r,e);if(i!=Number(i)||"-"!==t.charAt(e))throw new Error("Illegal attachments");s.attachments=Number(i)}if("/"===t.charAt(e+1)){const r=e+1;for(;++e;){if(","===t.charAt(e))break;if(e===t.length)break}s.nsp=t.substring(r,e)}else s.nsp="/";const r=t.charAt(e+1);if(""!==r&&Number(r)==r){const r=e+1;for(;++e;){const s=t.charAt(e);if(null==s||Number(s)!=s){--e;break}if(e===t.length)break}s.id=Number(t.substring(r,e+1))}if(t.charAt(++e)){const r=this.tryParse(t.substr(e));if(!ve.isPayloadValid(s.type,r))throw new Error("invalid payload");s.data=r}return s}tryParse(t){try{return JSON.parse(t,this.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case be.CONNECT:return Ee(e);case be.DISCONNECT:return void 0===e;case be.CONNECT_ERROR:return"string"==typeof e||Ee(e);case be.EVENT:case be.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===we.indexOf(e[0]));case be.ACK:case be.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ke{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=ye(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Se=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t};function Ee(t){return"[object Object]"===Object.prototype.toString.call(t)}var Te=Object.freeze({__proto__:null,Decoder:ve,Encoder:class{constructor(t){this.replacer=t}encode(t){return t.type!==be.EVENT&&t.type!==be.ACK||!fe(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===be.EVENT?be.BINARY_EVENT:be.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==be.BINARY_EVENT&&t.type!==be.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=ge(t),s=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(s),r}},get PacketType(){return be},isPacketValid:function(t){return"string"==typeof t.nsp&&(void 0===(e=t.id)||Se(e))&&function(t,e){switch(t){case be.CONNECT:return void 0===e||Ee(e);case be.DISCONNECT:return void 0===e;case be.EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===we.indexOf(e[0]));case be.ACK:return Array.isArray(e);case be.CONNECT_ERROR:return"string"==typeof e||Ee(e);default:return!1}}(t.type,t.data);var e},protocol:5});function Ce(t,e,s){return t.on(e,s),function(){t.off(e,s)}}const Ae=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Re extends Pt{constructor(t,e,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[Ce(t,"open",this.onopen.bind(this)),Ce(t,"packet",this.onpacket.bind(this)),Ce(t,"error",this.onerror.bind(this)),Ce(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var s,r,i;if(Ae.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const n={type:be.EVENT,data:e,options:{}};if(n.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,s=e.pop();this._registerAckCallback(t,s),n.id=t}const o=null===(r=null===(s=this.io.engine)||void 0===s?void 0:s.transport)||void 0===r?void 0:r.writable,a=this.connected&&!(null===(i=this.io.engine)||void 0===i?void 0:i._hasPingExpired());return this.flags.volatile&&!o||(a?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(t,e){var s;const r=null!==(s=this.flags.timeout)&&void 0!==s?s:this._opts.ackTimeout;if(void 0===r)return void(this.acks[t]=e);const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))},r),n=(...t)=>{this.io.clearTimeoutFn(i),e.apply(this,t)};n.withError=!0,this.acks[t]=n}emitWithAck(t,...e){return new Promise((s,r)=>{const i=(t,e)=>t?r(t):s(e);i.withError=!0,e.push(i),this.emit(t,...e)})}_addToQueue(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...r)=>{this._queue[0];return null!==t?s.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(t)):(this._queue.shift(),e&&e(null,...r)),s.pending=!1,this._drainQueue()}),this._queue.push(s),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||0===this._queue.length)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:be.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(e=>String(e.id)===t)){const e=this.acks[t];delete this.acks[t],e.withError&&e.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case be.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case be.EVENT:case be.BINARY_EVENT:this.onevent(t);break;case be.ACK:case be.BINARY_ACK:this.onack(t);break;case be.DISCONNECT:this.ondisconnect();break;case be.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const s of e)s.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&"string"==typeof t[t.length-1]&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let s=!1;return function(...r){s||(s=!0,e.packet({type:be.ACK,id:t,data:r}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:be.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const s of e)s.apply(this,t.data)}}}function Oe(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}Oe.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),s=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+s:t-s}return 0|Math.min(t,this.max)},Oe.prototype.reset=function(){this.attempts=0},Oe.prototype.setMin=function(t){this.ms=t},Oe.prototype.setMax=function(t){this.max=t},Oe.prototype.setJitter=function(t){this.jitter=t};class xe extends Pt{constructor(t,e){var s;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,qt(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(s=e.randomizationFactor)&&void 0!==s?s:.5),this.backoff=new Oe({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const r=e.parser||Te;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=!1!==e.autoConnect,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new ce(this.uri,this.opts);const e=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=Ce(e,"open",function(){s.onopen(),t&&t()}),i=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},n=Ce(e,"error",i);if(!1!==this._timeout){const t=this._timeout,s=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),e.close()},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}return this.subs.push(r),this.subs.push(n),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(Ce(t,"ping",this.onping.bind(this)),Ce(t,"data",this.ondata.bind(this)),Ce(t,"error",this.onerror.bind(this)),Ce(t,"close",this.onclose.bind(this)),Ce(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){It(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let s=this.nsps[t];return s?this._autoConnect&&!s.active&&s.connect():(s=new Re(this,t,e),this.nsps[t]=s),s}_destroy(t){const e=Object.keys(this.nsps);for(const t of e){if(this.nsps[t].active)return}this._close()}_packet(t){const e=this.encoder.encode(t);for(let s=0;s<e.length;s++)this.engine.write(e[s],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var s;this.cleanup(),null===(s=this.engine)||void 0===s||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open(e=>{e?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()}))},e);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Pe={};function Ie(t,e){"object"==typeof t&&(e=t,t=void 0);const s=function(t,e="",s){let r=t;s=s||"undefined"!=typeof location&&location,null==t&&(t=s.protocol+"//"+s.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?s.protocol+t:s.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==s?s.protocol+"//"+t:"https://"+t),r=re(t)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const i=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+e,r.href=r.protocol+"://"+i+(s&&s.port===r.port?"":":"+r.port),r}(t,(e=e||{}).path||"/socket.io"),r=s.source,i=s.id,n=s.path,o=Pe[i]&&n in Pe[i].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||o?a=new xe(r,e):(Pe[i]||(Pe[i]=new xe(r,e)),a=Pe[i]),s.query&&!e.query&&(e.query=s.queryKey),a.socket(s.path,e)}Object.assign(Ie,{Manager:xe,Socket:Re,io:Ie,connect:Ie});var Ne,Be,je,Ue,qe,Le,Me,De,Fe,ze,$e,He,Ke,Ve,Je,We,Qe,Ye,Ge,Xe,Ze,ts,es,ss,rs,is,ns,os,as,cs,hs,us,ls,ds,ps,fs,gs,_s,ys,ms,ws={exports:{}},bs={exports:{}};function vs(){if(Be)return Ne;Be=1;return Ne=function(t){return null!=t},Ne}function ks(){if(Le)return qe;Le=1;var t=function(){if(Ue)return je;Ue=1;var t=vs(),e={object:!0,function:!0,undefined:!0};return je=function(s){return!!t(s)&&hasOwnProperty.call(e,typeof s)},je}();return qe=function(e){if(!t(e))return!1;try{return!!e.constructor&&e.constructor.prototype===e}catch(t){return!1}},qe}function Ss(){if(ze)return Fe;ze=1;var t=function(){if(De)return Me;De=1;var t=ks();return Me=function(e){if("function"!=typeof e)return!1;if(!hasOwnProperty.call(e,"length"))return!1;try{if("number"!=typeof e.length)return!1;if("function"!=typeof e.call)return!1;if("function"!=typeof e.apply)return!1}catch(t){return!1}return!t(e)},Me}(),e=/^\s*class[\s{/}]/,s=Function.prototype.toString;return Fe=function(r){return!!t(r)&&!e.test(s.call(r))},Fe}function Es(){if(Ye)return Qe;Ye=1;var t=(We?Je:(We=1,Je=function(){}))();return Qe=function(e){return e!==t&&null!==e}}function Ts(){return ts||(ts=1,Ze=(Ve?Ke:(Ve=1,Ke=function(){try{return Object.keys("primitive"),!0}catch(t){return!1}}))()?Object.keys:function(){if(Xe)return Ge;Xe=1;var t=Es(),e=Object.keys;return Ge=function(s){return e(t(s)?Object(s):s)}}()),Ze}function Cs(){if(is)return rs;is=1;var t=Ts(),e=function(){if(ss)return es;ss=1;var t=Es();return es=function(e){if(!t(e))throw new TypeError("Cannot use null or undefined");return e},es}(),s=Math.max;return rs=function(r,i){var n,o,a,c=s(arguments.length,2);for(r=Object(e(r)),a=function(t){try{r[t]=i[t]}catch(t){n||(n=t)}},o=1;o<c;++o)t(i=arguments[o]).forEach(a);if(void 0!==n)throw n;return r},rs}function As(){return os?ns:(os=1,ns=(He||(He=1,$e=function(){var t,e=Object.assign;return"function"==typeof e&&(e(t={foo:"raz"},{bar:"dwa"},{trzy:"trzy"}),t.foo+t.bar+t.trzy==="razdwatrzy")}),$e)()?Object.assign:Cs())}function Rs(){return fs||(fs=1,ps=function(){if(us)return hs;us=1;var t="razdwatrzy";return hs=function(){return"function"==typeof t.contains&&!0===t.contains("dwa")&&!1===t.contains("foo")}}()()?String.prototype.contains:function(){if(ds)return ls;ds=1;var t=String.prototype.indexOf;return ls=function(e){return t.call(this,e,arguments[1])>-1},ls}()),ps}function Os(){if(gs)return bs.exports;gs=1;var t=vs(),e=Ss(),s=As(),r=function(){if(cs)return as;cs=1;var t=Es(),e=Array.prototype.forEach,s=Object.create;return as=function(r){var i=s(null);return e.call(arguments,function(e){t(e)&&function(t,e){var s;for(s in t)e[s]=t[s]}(Object(e),i)}),i},as}(),i=Rs(),n=bs.exports=function(e,n){var o,a,c,h,u;return arguments.length<2||"string"!=typeof e?(h=n,n=e,e=null):h=arguments[2],t(e)?(o=i.call(e,"c"),a=i.call(e,"e"),c=i.call(e,"w")):(o=c=!0,a=!1),u={value:n,configurable:o,enumerable:a,writable:c},h?s(r(h),u):u};return n.gs=function(n,o,a){var c,h,u,l;return"string"!=typeof n?(u=a,a=o,o=n,n=null):u=arguments[3],t(o)?e(o)?t(a)?e(a)||(u=a,a=void 0):a=void 0:(u=o,o=a=void 0):o=void 0,t(n)?(c=i.call(n,"c"),h=i.call(n,"e")):(c=!0,h=!1),l={get:o,set:a,configurable:c,enumerable:h},u?s(r(u),l):l},bs.exports}var xs=(ms||(ms=1,function(t,e){var s,r,i,n,o,a,c,h=Os(),u=ys?_s:(ys=1,_s=function(t){if("function"!=typeof t)throw new TypeError(t+" is not a function");return t}),l=Function.prototype.apply,d=Function.prototype.call,p=Object.create,f=Object.defineProperty,g=Object.defineProperties,_=Object.prototype.hasOwnProperty,y={configurable:!0,enumerable:!1,writable:!0};r=function(t,e){var r,n;return u(e),n=this,s.call(this,t,r=function(){i.call(n,t,r),l.call(e,this,arguments)}),r.__eeOnceListener__=e,this},n=function(t){var e,s,r,i,n;if(_.call(this,"__ee__")&&(i=this.__ee__[t]))if("object"==typeof i){for(s=arguments.length,n=new Array(s-1),e=1;e<s;++e)n[e-1]=arguments[e];for(i=i.slice(),e=0;r=i[e];++e)l.call(r,this,n)}else switch(arguments.length){case 1:d.call(i,this);break;case 2:d.call(i,this,arguments[1]);break;case 3:d.call(i,this,arguments[1],arguments[2]);break;default:for(s=arguments.length,n=new Array(s-1),e=1;e<s;++e)n[e-1]=arguments[e];l.call(i,this,n)}},o={on:s=function(t,e){var s;return u(e),_.call(this,"__ee__")?s=this.__ee__:(s=y.value=p(null),f(this,"__ee__",y),y.value=null),s[t]?"object"==typeof s[t]?s[t].push(e):s[t]=[s[t],e]:s[t]=e,this},once:r,off:i=function(t,e){var s,r,i,n;if(u(e),!_.call(this,"__ee__"))return this;if(!(s=this.__ee__)[t])return this;if("object"==typeof(r=s[t]))for(n=0;i=r[n];++n)i!==e&&i.__eeOnceListener__!==e||(2===r.length?s[t]=r[n?0:1]:r.splice(n,1));else r!==e&&r.__eeOnceListener__!==e||delete s[t];return this},emit:n},a={on:h(s),once:h(r),off:h(i),emit:h(n)},c=g({},a),t.exports=e=function(t){return null==t?p(c):g(Object(t),a)},e.methods=o}(ws,ws.exports)),ws.exports),Ps=s(xs);class Is{constructor(t,e){this._config=e,this._socket=t,this._callbacks=[],this._fields=e.fields?[...e.fields]:null}async establishConnection(){if(!this._socket||!this._config.userId||!this._config.gameId)throw new Error("Missing arguments in establishConnection");return new Promise(t=>{let e;e=this._fields?{userId:this._config.userId,gameId:this._config.gameId,fields:this._fields}:`${this._config.userId}:${this._config.gameId}`,this._socket.timeout(5e3).emit("listen",e,(e,s)=>e?t({status:"failed",reason:"Listen request timed out."}):"success"===s.status?t({status:"success"}):t({status:"failed",reason:s.reason}))})}setupEventListener(){return this._socket.on("update",t=>{if(this._fields&&this._fields.length>0&&t?.data){const e={};for(const s of this._fields)s in t.data&&(e[s]=t.data[s]);this.emit("update",{...t,data:e})}else this.emit("update",t)}),this}async subscribe(t){if(!Array.isArray(t)||0===t.length)throw new Error("fields must be a non-empty array");if(this._fields)for(const e of t)this._fields.includes(e)||this._fields.push(e);else this._fields=[...t];return this._updateSubscription()}async unsubscribe(t){if(!Array.isArray(t)||0===t.length)throw new Error("fields must be a non-empty array");if(!this._fields)throw new Error("Cannot unsubscribe when receiving all fields. Use subscribe() first to set explicit field list.");return this._fields=this._fields.filter(e=>!t.includes(e)),this._updateSubscription()}getFields(){return this._fields?[...this._fields]:null}async sendCommand(t,e){if(!t||"string"!=typeof t)throw new Error("field must be a non-empty string");return new Promise(s=>{const r={userId:this._config.userId,gameId:this._config.gameId,data:{fieldName:t,value:e}};this._socket.timeout(5e3).emit("set",r,(t,e)=>s(t?{status:"failed",reason:"Command request timed out."}:e))})}async _updateSubscription(){return new Promise(t=>{const e={userId:this._config.userId,gameId:this._config.gameId,fields:this._fields};this._socket.timeout(5e3).emit("listen-update",e,(e,s)=>t(e?{status:"failed",reason:"Update request timed out."}:s))})}}Ps(Is.prototype);const Ns={msfs:!0};class Bs extends ct{constructor(t){super(t),this._socket=null,this._socketUrl=t.socketUrl||"https://socks.gameglue.gg",this._connectPromise=null}async createListener(t){if(!t)throw new Error("Not a valid listener config");if(!t.gameId||!Ns[t.gameId])throw new Error("Not a valid Game ID");if(!t.userId)throw new Error("User ID not supplied");if(t.fields&&!Array.isArray(t.fields))throw new Error("fields must be an array");await this._ensureConnected();const e=new Is(this._socket,t),s=await e.establishConnection();if(this._socket.io.on("reconnect_attempt",()=>{this._updateSocketAuth(this.getAccessToken())}),this._socket.io.on("reconnect",()=>{e.establishConnection()}),"success"!==s.status)throw new Error(`There was a problem setting up the listener. Reason: ${s.reason}`);return e.setupEventListener()}async _ensureConnected(){if(!this._socket?.connected)if(this._connectPromise)await this._connectPromise;else{this._connectPromise=this._connect();try{await this._connectPromise}finally{this._connectPromise=null}}}_connect(){return new Promise((t,e)=>{const s=this.getAccessToken();s?(this._socket=Ie(this._socketUrl,{transports:["websocket"],auth:{token:s}}),this._socket.on("connect",()=>{t()}),this._socket.on("connect_error",t=>{e(new Error(`Socket connection failed: ${t.message}`))}),this.onTokenRefreshed(t=>{this._updateSocketAuth(t)})):e(new Error("Not authenticated - call isAuthenticated() first"))})}_updateSocketAuth(t){this._socket&&(this._socket.auth.token=t)}}"undefined"!=typeof window&&(window.GameGlue=Bs),t.GameGlue=Bs,t.default=Bs,Object.defineProperty(t,"__esModule",{value:!0})});
|
|
2
2
|
//# sourceMappingURL=gg.umd.js.map
|