gameglue 4.0.1 → 4.0.2

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.
Files changed (56) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +275 -275
  3. package/babel.config.cjs +5 -5
  4. package/coverage/auth.js.html +525 -525
  5. package/coverage/base.css +224 -224
  6. package/coverage/block-navigation.js +87 -87
  7. package/coverage/favicon.png +0 -0
  8. package/coverage/index.html +175 -175
  9. package/coverage/index.js.html +309 -309
  10. package/coverage/lcov-report/auth.js.html +525 -525
  11. package/coverage/lcov-report/base.css +224 -224
  12. package/coverage/lcov-report/block-navigation.js +87 -87
  13. package/coverage/lcov-report/favicon.png +0 -0
  14. package/coverage/lcov-report/index.html +175 -175
  15. package/coverage/lcov-report/index.js.html +309 -309
  16. package/coverage/lcov-report/listener.js.html +528 -528
  17. package/coverage/lcov-report/prettify.css +1 -1
  18. package/coverage/lcov-report/prettify.js +2 -2
  19. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  20. package/coverage/lcov-report/sorter.js +210 -210
  21. package/coverage/lcov-report/user.js.html +117 -117
  22. package/coverage/lcov-report/utils.js.html +117 -117
  23. package/coverage/lcov.info +391 -391
  24. package/coverage/listener.js.html +528 -528
  25. package/coverage/prettify.css +1 -1
  26. package/coverage/prettify.js +2 -2
  27. package/coverage/sort-arrow-sprite.png +0 -0
  28. package/coverage/sorter.js +210 -210
  29. package/coverage/user.js.html +117 -117
  30. package/coverage/utils.js.html +117 -117
  31. package/dist/gg.cjs.js +1 -1
  32. package/dist/gg.cjs.js.map +1 -1
  33. package/dist/gg.esm.js +1 -1
  34. package/dist/gg.esm.js.map +1 -1
  35. package/dist/gg.umd.js +1 -1
  36. package/dist/gg.umd.js.map +1 -1
  37. package/examples/certs/cert.pem +19 -19
  38. package/examples/certs/key.pem +28 -28
  39. package/examples/flight-dashboard.html +431 -431
  40. package/examples/server.js +99 -99
  41. package/examples/telemetry-validator.html +1410 -1410
  42. package/jest.config.cjs +33 -33
  43. package/package.json +56 -56
  44. package/rollup.config.js +57 -57
  45. package/src/auth.js +255 -255
  46. package/src/auth.spec.js +481 -481
  47. package/src/index.js +168 -168
  48. package/src/listener.js +196 -196
  49. package/src/listener.spec.js +598 -598
  50. package/src/presence_listener.js +112 -112
  51. package/src/test/fixtures.js +106 -106
  52. package/src/test/setup.js +51 -51
  53. package/src/utils.js +63 -63
  54. package/src/utils.spec.js +78 -78
  55. package/types/index.d.ts +338 -338
  56. package/webpack.config.js +15 -15
package/dist/gg.umd.js CHANGED
@@ -1,2 +1,2 @@
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 n(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function i(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if("function"==typeof e){var n=function t(){var n=!1;try{n=this instanceof t}catch{}return n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(e){var i=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(n,e,i.get?i:{enumerable:!0,get:function(){return t[e]}})}),n}var o,r={exports:{}},s=i(Object.freeze({__proto__:null,default:{}}));function a(){return o||(o=1,function(t){t.exports=function(){var t=t||function(t,n){var i;if("undefined"!=typeof window&&window.crypto&&(i=window.crypto),"undefined"!=typeof self&&self.crypto&&(i=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(i=globalThis.crypto),!i&&"undefined"!=typeof window&&window.msCrypto&&(i=window.msCrypto),!i&&void 0!==e&&e.crypto&&(i=e.crypto),!i)try{i=s}catch(t){}var o=function(){if(i){if("function"==typeof i.getRandomValues)try{return i.getRandomValues(new Uint32Array(1))[0]}catch(t){}if("function"==typeof i.randomBytes)try{return i.randomBytes(4).readInt32LE()}catch(t){}}throw new Error("Native crypto module could not be used to get secure random number.")},r=Object.create||function(){function t(){}return function(e){var n;return t.prototype=e,n=new t,t.prototype=null,n}}(),a={},c=a.lib={},l=c.Base={extend:function(t){var e=r(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)}},h=c.WordArray=l.extend({init:function(t,e){t=this.words=t||[],this.sigBytes=e!=n?e:4*t.length},toString:function(t){return(t||u).stringify(this)},concat:function(t){var e=this.words,n=t.words,i=this.sigBytes,o=t.sigBytes;if(this.clamp(),i%4)for(var r=0;r<o;r++){var s=n[r>>>2]>>>24-r%4*8&255;e[i+r>>>2]|=s<<24-(i+r)%4*8}else for(var a=0;a<o;a+=4)e[i+a>>>2]=n[a>>>2];return this.sigBytes+=o,this},clamp:function(){var e=this.words,n=this.sigBytes;e[n>>>2]&=4294967295<<32-n%4*8,e.length=t.ceil(n/4)},clone:function(){var t=l.clone.call(this);return t.words=this.words.slice(0),t},random:function(t){for(var e=[],n=0;n<t;n+=4)e.push(o());return new h.init(e,t)}}),p=a.enc={},u=p.Hex={stringify:function(t){for(var e=t.words,n=t.sigBytes,i=[],o=0;o<n;o++){var r=e[o>>>2]>>>24-o%4*8&255;i.push((r>>>4).toString(16)),i.push((15&r).toString(16))}return i.join("")},parse:function(t){for(var e=t.length,n=[],i=0;i<e;i+=2)n[i>>>3]|=parseInt(t.substr(i,2),16)<<24-i%8*4;return new h.init(n,e/2)}},d=p.Latin1={stringify:function(t){for(var e=t.words,n=t.sigBytes,i=[],o=0;o<n;o++){var r=e[o>>>2]>>>24-o%4*8&255;i.push(String.fromCharCode(r))}return i.join("")},parse:function(t){for(var e=t.length,n=[],i=0;i<e;i++)n[i>>>2]|=(255&t.charCodeAt(i))<<24-i%4*8;return new h.init(n,e)}},g=p.Utf8={stringify:function(t){try{return decodeURIComponent(escape(d.stringify(t)))}catch(t){throw new Error("Malformed UTF-8 data")}},parse:function(t){return d.parse(unescape(encodeURIComponent(t)))}},_=c.BufferedBlockAlgorithm=l.extend({reset:function(){this._data=new h.init,this._nDataBytes=0},_append:function(t){"string"==typeof t&&(t=g.parse(t)),this._data.concat(t),this._nDataBytes+=t.sigBytes},_process:function(e){var n,i=this._data,o=i.words,r=i.sigBytes,s=this.blockSize,a=r/(4*s),c=(a=e?t.ceil(a):t.max((0|a)-this._minBufferSize,0))*s,l=t.min(4*c,r);if(c){for(var p=0;p<c;p+=s)this._doProcessBlock(o,p);n=o.splice(0,c),i.sigBytes-=l}return new h.init(n,l)},clone:function(){var t=l.clone.call(this);return t._data=this._data.clone(),t},_minBufferSize:0});c.Hasher=_.extend({cfg:l.extend(),init:function(t){this.cfg=this.cfg.extend(t),this.reset()},reset:function(){_.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,n){return new t.init(n).finalize(e)}},_createHmacHelper:function(t){return function(e,n){return new m.HMAC.init(t,n).finalize(e)}}});var m=a.algo={};return a}(Math);return t}()}(r)),r.exports}var c,l=n(a()),h={exports:{}};var p,u=(c||(c=1,function(t){t.exports=function(t){return function(e){var n=t,i=n.lib,o=i.WordArray,r=i.Hasher,s=n.algo,a=[],c=[];!function(){function t(t){for(var n=e.sqrt(t),i=2;i<=n;i++)if(!(t%i))return!1;return!0}function n(t){return 4294967296*(t-(0|t))|0}for(var i=2,o=0;o<64;)t(i)&&(o<8&&(a[o]=n(e.pow(i,.5))),c[o]=n(e.pow(i,1/3)),o++),i++}();var l=[],h=s.SHA256=r.extend({_doReset:function(){this._hash=new o.init(a.slice(0))},_doProcessBlock:function(t,e){for(var n=this._hash.words,i=n[0],o=n[1],r=n[2],s=n[3],a=n[4],h=n[5],p=n[6],u=n[7],d=0;d<64;d++){if(d<16)l[d]=0|t[e+d];else{var g=l[d-15],_=(g<<25|g>>>7)^(g<<14|g>>>18)^g>>>3,m=l[d-2],f=(m<<15|m>>>17)^(m<<13|m>>>19)^m>>>10;l[d]=_+l[d-7]+f+l[d-16]}var y=i&o^i&r^o&r,w=(i<<30|i>>>2)^(i<<19|i>>>13)^(i<<10|i>>>22),b=u+((a<<26|a>>>6)^(a<<21|a>>>11)^(a<<7|a>>>25))+(a&h^~a&p)+c[d]+l[d];u=p,p=h,h=a,a=s+b|0,s=r,r=o,o=i,i=b+(w+y)|0}n[0]=n[0]+i|0,n[1]=n[1]+o|0,n[2]=n[2]+r|0,n[3]=n[3]+s|0,n[4]=n[4]+a|0,n[5]=n[5]+h|0,n[6]=n[6]+p|0,n[7]=n[7]+u|0},_doFinalize:function(){var t=this._data,n=t.words,i=8*this._nDataBytes,o=8*t.sigBytes;return n[o>>>5]|=128<<24-o%32,n[14+(o+64>>>9<<4)]=e.floor(i/4294967296),n[15+(o+64>>>9<<4)]=i,t.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var t=r.clone.call(this);return t._hash=this._hash.clone(),t}});n.SHA256=r._createHelper(h),n.HmacSHA256=r._createHmacHelper(h)}(Math),t.SHA256}(a())}(h)),h.exports),d=n(u),g={exports:{}};var _,m=(p||(p=1,function(t){t.exports=function(t){return function(){var e=t,n=e.lib.WordArray;function i(t,e,i){for(var o=[],r=0,s=0;s<e;s++)if(s%4){var a=i[t.charCodeAt(s-1)]<<s%4*2|i[t.charCodeAt(s)]>>>6-s%4*2;o[r>>>2]|=a<<24-r%4*8,r++}return n.create(o,r)}e.enc.Base64={stringify:function(t){var e=t.words,n=t.sigBytes,i=this._map;t.clamp();for(var o=[],r=0;r<n;r+=3)for(var s=(e[r>>>2]>>>24-r%4*8&255)<<16|(e[r+1>>>2]>>>24-(r+1)%4*8&255)<<8|e[r+2>>>2]>>>24-(r+2)%4*8&255,a=0;a<4&&r+.75*a<n;a++)o.push(i.charAt(s>>>6*(3-a)&63));var c=i.charAt(64);if(c)for(;o.length%4;)o.push(c);return o.join("")},parse:function(t){var e=t.length,n=this._map,o=this._reverseMap;if(!o){o=this._reverseMap=[];for(var r=0;r<n.length;r++)o[n.charCodeAt(r)]=r}var s=n.charAt(64);if(s){var a=t.indexOf(s);-1!==a&&(e=a)}return i(t,e,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),t.enc.Base64}(a())}(g)),g.exports),f=n(m),y={exports:{}};var w=(_||(_=1,function(t){t.exports=function(t){return t.enc.Utf8}(a())}(y)),y.exports),b=n(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 n,i,o=0,r=0,s="";i=e.charAt(r++);~i&&(n=o%4?64*n+i:i,o++%4)?s+=String.fromCharCode(255&n>>(-2*o&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return s};function C(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 n=e.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n}))}(e)}catch(t){return k(e)}}function S(t){this.message=t}function E(t,e){if("string"!=typeof t)throw new S("Invalid token specified");var n=!0===(e=e||{}).header?0:1;try{return JSON.parse(C(t.split(".")[n]))}catch(t){throw new S("Invalid token specified: "+t.message)}}S.prototype=new Error,S.prototype.name="InvalidTokenError";var T,A,x,O={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},R=(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))(R||{});(x=R||(R={})).reset=function(){T=3,A=O},x.setLevel=function(t){if(!(0<=t&&t<=4))throw new Error("Invalid log level");T=t},x.setLogger=function(t){A=t};var P=class{constructor(t){this._name=t}debug(...t){T>=4&&A.debug(P._format(this._name,this._method),...t)}info(...t){T>=3&&A.info(P._format(this._name,this._method),...t)}warn(...t){T>=2&&A.warn(P._format(this._name,this._method),...t)}error(...t){T>=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 n=new P(`${t}.${e}`);return n.debug("begin"),n}static _format(t,e){const n=`[${t}]`;return e?`${n} ${e}:`:n}static debug(t,...e){T>=4&&A.debug(P._format(t),...e)}static info(t,...e){T>=3&&A.info(P._format(t),...e)}static warn(t,...e){T>=2&&A.warn(P._format(t),...e)}static error(t,...e){T>=1&&A.error(P._format(t),...e)}};R.reset();var I=class{static _randomWord(){return l.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=d(t);return f.stringify(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw P.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(t,e){const n=b.parse([t,e].join(":"));return f.stringify(n)}},L=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)}},N=class{static decode(t){try{return E(t)}catch(t){throw P.error("JwtUtils.decode",t),t}}},B=class extends L{constructor(){super(...arguments),this._logger=new P(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const t=this._expiration-B.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=B.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 n=B.getEpochTime()+t;if(this.expiration===n&&this._timerHandle)return void e.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),e.debug("using duration",t),this._expiration=n;const i=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*i)}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 n=new URL(t,window.location.origin)["fragment"===e?"hash":"search"];return new URLSearchParams(n.slice(1))}},q=class extends Error{constructor(t,e){var n,i,o;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!=(n=t.error_description)?n:null,this.error_uri=null!=(i=t.error_uri)?i:null,this.state=t.userState,this.session_state=null!=(o=t.session_state)?o:null}},j=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]}},F=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:n,...i}=e;if(!n)return await fetch(t,i);const o=new AbortController,r=setTimeout(()=>o.abort(),1e3*n);try{return await fetch(t,{...e,signal:o.signal})}catch(t){if(t instanceof DOMException&&"AbortError"===t.name)throw new j("Network timed out");throw t}finally{clearTimeout(r)}}async getJson(t,{token:e,credentials:n}={}){const i=this._logger.create("getJson"),o={Accept:this._contentTypes.join(", ")};let r;e&&(i.debug("token passed, setting Authorization header"),o.Authorization="Bearer "+e);try{i.debug("url:",t),r=await this.fetchWithTimeout(t,{method:"GET",headers:o,credentials:n})}catch(t){throw i.error("Network Error"),t}i.debug("HTTP response received, status",r.status);const s=r.headers.get("Content-Type");if(s&&!this._contentTypes.find(t=>s.startsWith(t))&&i.throw(new Error(`Invalid response Content-Type: ${null!=s?s:"undefined"}, from URL: ${t}`)),r.ok&&this._jwtHandler&&(null==s?void 0:s.startsWith("application/jwt")))return await this._jwtHandler(await r.text());let a;try{a=await r.json()}catch(t){if(i.error("Error parsing JSON response",t),r.ok)throw t;throw new Error(`${r.statusText} (${r.status})`)}if(!r.ok){if(i.error("Error from server:",a),a.error)throw new q(a);throw new Error(`${r.statusText} (${r.status}): ${JSON.stringify(a)}`)}return a}async postForm(t,{body:e,basicAuth:n,timeoutInSeconds:i,initCredentials:o}){const r=this._logger.create("postForm"),s={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded"};let a;void 0!==n&&(s.Authorization="Basic "+n);try{r.debug("url:",t),a=await this.fetchWithTimeout(t,{method:"POST",headers:s,body:e,timeoutInSeconds:i,credentials:o})}catch(t){throw r.error("Network error"),t}r.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 l=await a.text();let h={};if(l)try{h=JSON.parse(l)}catch(t){if(r.error("Error parsing JSON response",t),a.ok)throw t;throw new Error(`${a.statusText} (${a.status})`)}if(!a.ok){if(r.error("Error from server:",h),h.error)throw new q(h,e);throw new Error(`${a.statusText} (${a.status}): ${JSON.stringify(h)}`)}return h}},D=class{constructor(t){this._settings=t,this._logger=new P("MetadataService"),this._jsonService=new F(["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 n=this._logger.create(`_getMetadataProperty('${t}')`),i=await this.getMetadata();if(n.debug("resolved"),void 0===i[t]){if(!0===e)return void n.warn("Metadata does not contain optional property");n.throw(new Error("Metadata does not contain property "+t))}return i[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 n=await this._jsonService.getJson(e);if(t.debug("got key set",n),!Array.isArray(n.keys))throw t.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=n.keys,this._signingKeys}},H=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 n=0;n<t;n++){const t=await this._store.key(n);t&&0===t.indexOf(this._prefix)&&e.push(t.substr(this._prefix.length))}return e}},G=class{constructor({authority:t,metadataUrl:e,metadata:n,signingKeys:i,metadataSeed:o,client_id:r,client_secret:s,response_type:a="code",scope:c="openid",redirect_uri:l,post_logout_redirect_uri:h,client_authentication:p="client_secret_post",prompt:u,display:d,max_age:g,ui_locales:_,acr_values:m,resource:f,response_mode:y="query",filterProtocolClaims:w=!0,loadUserInfo:b=!1,staleStateAgeInSeconds:v=900,clockSkewInSeconds:k=300,userInfoJwtIssuer:C="OP",mergeClaims:S=!1,stateStore:E,refreshTokenCredentials:T,revokeTokenAdditionalContentTypes:A,fetchRequestCredentials:x,refreshTokenAllowedScope:O,extraQueryParams:R={},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=n,this.metadataSeed=o,this.signingKeys=i,this.client_id=r,this.client_secret=s,this.response_type=a,this.scope=c,this.redirect_uri=l,this.post_logout_redirect_uri=h,this.client_authentication=p,this.prompt=u,this.display=d,this.max_age=g,this.ui_locales=_,this.acr_values=m,this.resource=f,this.response_mode=y,this.filterProtocolClaims=null==w||w,this.loadUserInfo=!!b,this.staleStateAgeInSeconds=v,this.clockSkewInSeconds=k,this.userInfoJwtIssuer=C,this.mergeClaims=!!S,this.revokeTokenAdditionalContentTypes=A,x&&T&&console.warn("Both fetchRequestCredentials and refreshTokenCredentials is set. Only fetchRequestCredentials will be used."),this.fetchRequestCredentials=x||(T||"same-origin"),E)this.stateStore=E;else{const t="undefined"!=typeof window?window.localStorage:new M;this.stateStore=new H({store:t})}this.refreshTokenAllowedScope=O,this.extraQueryParams=R,this.extraTokenParams=P}},V=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 n=N.decode(t);return e.debug("JWT decoding successful"),n}catch(t){throw e.error("Error parsing JWT response"),t}},this._jsonService=new F(void 0,this._getClaimsFromJwt)}async getClaims(t){const e=this._logger.create("getClaims");t||this._logger.throw(new Error("No token passed"));const n=await this._metadataService.getUserInfoEndpoint();e.debug("got userinfo url",n);const i=await this._jsonService.getJson(n,{token:t,credentials:this._settings.fetchRequestCredentials});return e.debug("got claims",i),i}},z=class{constructor(t,e){this._settings=t,this._metadataService=e,this._logger=new P("TokenClient"),this._jsonService=new F(this._settings.revokeTokenAdditionalContentTypes)}async exchangeCode({grant_type:t="authorization_code",redirect_uri:e=this._settings.redirect_uri,client_id:n=this._settings.client_id,client_secret:i=this._settings.client_secret,...o}){const r=this._logger.create("exchangeCode");n||r.throw(new Error("A client_id is required")),e||r.throw(new Error("A redirect_uri is required")),o.code||r.throw(new Error("A code is required")),o.code_verifier||r.throw(new Error("A code_verifier is required"));const s=new URLSearchParams({grant_type:t,redirect_uri:e});for(const[t,e]of Object.entries(o))null!=e&&s.set(t,e);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!i)throw r.throw(new Error("A client_secret is required")),null;a=I.generateBasicAuth(n,i);break;case"client_secret_post":s.append("client_id",n),i&&s.append("client_secret",i)}const c=await this._metadataService.getTokenEndpoint(!1);r.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:s,basicAuth:a,initCredentials:this._settings.fetchRequestCredentials});return r.debug("got response"),l}async exchangeCredentials({grant_type:t="password",client_id:e=this._settings.client_id,client_secret:n=this._settings.client_secret,scope:i=this._settings.scope,...o}){const r=this._logger.create("exchangeCredentials");e||r.throw(new Error("A client_id is required"));const s=new URLSearchParams({grant_type:t,scope:i});for(const[t,e]of Object.entries(o))null!=e&&s.set(t,e);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!n)throw r.throw(new Error("A client_secret is required")),null;a=I.generateBasicAuth(e,n);break;case"client_secret_post":s.append("client_id",e),n&&s.append("client_secret",n)}const c=await this._metadataService.getTokenEndpoint(!1);r.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:s,basicAuth:a,initCredentials:this._settings.fetchRequestCredentials});return r.debug("got response"),l}async exchangeRefreshToken({grant_type:t="refresh_token",client_id:e=this._settings.client_id,client_secret:n=this._settings.client_secret,timeoutInSeconds:i,...o}){const r=this._logger.create("exchangeRefreshToken");e||r.throw(new Error("A client_id is required")),o.refresh_token||r.throw(new Error("A refresh_token is required"));const s=new URLSearchParams({grant_type:t});for(const[t,e]of Object.entries(o))null!=e&&s.set(t,e);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!n)throw r.throw(new Error("A client_secret is required")),null;a=I.generateBasicAuth(e,n);break;case"client_secret_post":s.append("client_id",e),n&&s.append("client_secret",n)}const c=await this._metadataService.getTokenEndpoint(!1);r.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:s,basicAuth:a,timeoutInSeconds:i,initCredentials:this._settings.fetchRequestCredentials});return r.debug("got response"),l}async revoke(t){var e;const n=this._logger.create("revoke");t.token||n.throw(new Error("A token is required"));const i=await this._metadataService.getRevocationEndpoint(!1);n.debug(`got revocation endpoint, revoking ${null!=(e=t.token_type_hint)?e:"default token type"}`);const o=new URLSearchParams;for(const[e,n]of Object.entries(t))null!=n&&o.set(e,n);o.set("client_id",this._settings.client_id),this._settings.client_secret&&o.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(i,{body:o}),n.debug("got response")}},$=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],W=["sub","iss","aud","exp","iat"],K=class{constructor(t,e){this._settings=t,this._metadataService=e,this._logger=new P("ResponseValidator"),this._userInfoService=new V(this._settings,this._metadataService),this._tokenClient=new z(this._settings,this._metadataService)}async validateSigninResponse(t,e){const n=this._logger.create("validateSigninResponse");this._processSigninState(t,e),n.debug("state processed"),await this._processCode(t,e),n.debug("code processed"),t.isOpenId&&this._validateIdTokenAttributes(t),n.debug("tokens validated"),await this._processClaims(t,null==e?void 0:e.skipUserInfo,t.isOpenId),n.debug("claims processed")}async validateCredentialsResponse(t,e){const n=this._logger.create("validateCredentialsResponse");t.isOpenId&&this._validateIdTokenAttributes(t),n.debug("tokens validated"),await this._processClaims(t,e,t.isOpenId),n.debug("claims processed")}async validateRefreshResponse(t,e){const n=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),n.debug("ID Token validated")),t.id_token||(t.id_token=e.id_token,t.profile=e.profile);const i=t.isOpenId&&!!t.id_token;await this._processClaims(t,!1,i),n.debug("claims processed")}validateSignoutResponse(t,e){const n=this._logger.create("validateSignoutResponse");if(e.id!==t.state&&n.throw(new Error("State does not match")),n.debug("state validated"),t.userState=e.data,t.error)throw n.warn("Response was error",t.error),new q(t)}_processSigninState(t,e){const n=this._logger.create("_processSigninState");if(e.id!==t.state&&n.throw(new Error("State does not match")),e.client_id||n.throw(new Error("No client_id on state")),e.authority||n.throw(new Error("No authority on state")),this._settings.authority!==e.authority&&n.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==e.client_id&&n.throw(new Error("client_id mismatch on settings vs. signin state")),n.debug("state validated"),t.userState=e.data,null!=t.scope||(t.scope=e.scope),t.error)throw n.warn("Response was error",t.error),new q(t);e.code_verifier&&!t.code&&n.throw(new Error("Expected code in response")),!e.code_verifier&&t.code&&n.throw(new Error("Unexpected code in response"))}async _processClaims(t,e=!1,n=!0){const i=this._logger.create("_processClaims");if(t.profile=this._filterProtocolClaims(t.profile),e||!this._settings.loadUserInfo||!t.access_token)return void i.debug("not loading user info");i.debug("loading user info");const o=await this._userInfoService.getClaims(t.access_token);i.debug("user info claims received from user info endpoint"),n&&o.sub!==t.profile.sub&&i.throw(new Error("subject from UserInfo response does not match subject in ID Token")),t.profile=this._mergeClaims(t.profile,this._filterProtocolClaims(o)),i.debug("user info claims received, updated profile:",t.profile)}_mergeClaims(t,e){const n={...t};for(const[t,i]of Object.entries(e))for(const e of Array.isArray(i)?i:[i]){const i=n[t];i?Array.isArray(i)?i.includes(e)||i.push(e):n[t]!==e&&("object"==typeof e&&this._settings.mergeClaims?n[t]=this._mergeClaims(i,e):n[t]=[i,e]):n[t]=e}return n}_filterProtocolClaims(t){const e={...t};if(this._settings.filterProtocolClaims){let t;t=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:$;for(const n of t)W.includes(n)||delete e[n]}return e}async _processCode(t,e){const n=this._logger.create("_processCode");if(t.code){n.debug("Validating code");const i=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,i)}else n.debug("No code to process")}_validateIdTokenAttributes(t,e){var n;const i=this._logger.create("_validateIdTokenAttributes");i.debug("decoding ID Token JWT");const o=N.decode(null!=(n=t.id_token)?n:"");if(o.sub||i.throw(new Error("ID Token is missing a subject claim")),e){const t=N.decode(e);t.sub!==o.sub&&i.throw(new Error("sub in id_token does not match current sub")),t.auth_time&&t.auth_time!==o.auth_time&&i.throw(new Error("auth_time in id_token does not match original auth_time")),t.azp&&t.azp!==o.azp&&i.throw(new Error("azp in id_token does not match original azp")),!t.azp&&o.azp&&i.throw(new Error("azp not in id_token, but present in original id_token"))}t.profile=o}},J=class{constructor(t){this.id=t.id||I.generateUUIDv4(),this.data=t.data,t.created&&t.created>0?this.created=t.created:this.created=B.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 J(JSON.parse(t))}static async clearStaleState(t,e){const n=P.createStatic("State","clearStaleState"),i=B.getEpochTime()-e,o=await t.getAllKeys();n.debug("got keys",o);for(let e=0;e<o.length;e++){const r=o[e],s=await t.get(r);let a=!1;if(s)try{const t=J.fromStorageString(s);n.debug("got item from key:",r,t.created),t.created<=i&&(a=!0)}catch(t){n.error("Error parsing state for key:",r,t),a=!0}else n.debug("no item in storage for key:",r),a=!0;a&&(n.debug("removed item for key:",r),t.remove(r))}}},Q=class extends J{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 Q(e)}},Y=class{constructor({url:t,authority:e,client_id:n,redirect_uri:i,response_type:o,scope:r,state_data:s,response_mode:a,request_type:c,client_secret:l,nonce:h,resource:p,skipUserInfo:u,extraQueryParams:d,extraTokenParams:g,..._}){if(this._logger=new P("SigninRequest"),!t)throw this._logger.error("ctor: No url passed"),new Error("url");if(!n)throw this._logger.error("ctor: No client_id passed"),new Error("client_id");if(!i)throw this._logger.error("ctor: No redirect_uri passed"),new Error("redirect_uri");if(!o)throw this._logger.error("ctor: No response_type passed"),new Error("response_type");if(!r)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 Q({data:s,request_type:c,code_verifier:!0,client_id:n,authority:e,redirect_uri:i,response_mode:a,client_secret:l,scope:r,extraTokenParams:g,skipUserInfo:u});const m=new URL(t);if(m.searchParams.append("client_id",n),m.searchParams.append("redirect_uri",i),m.searchParams.append("response_type",o),m.searchParams.append("scope",r),h&&m.searchParams.append("nonce",h),m.searchParams.append("state",this.state.id),this.state.code_challenge&&(m.searchParams.append("code_challenge",this.state.code_challenge),m.searchParams.append("code_challenge_method","S256")),p){(Array.isArray(p)?p:[p]).forEach(t=>m.searchParams.append("resource",t))}for(const[t,e]of Object.entries({response_mode:a,..._,...d}))null!=e&&m.searchParams.append(t,e.toString());this.url=m.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-B.getEpochTime()}set expires_in(t){"string"==typeof t&&(t=Number(t)),void 0!==t&&t>=0&&(this.expires_at=Math.floor(t)+B.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:n,post_logout_redirect_uri:i,extraQueryParams:o,request_type:r}){if(this._logger=new P("SignoutRequest"),!t)throw this._logger.error("ctor: No url passed"),new Error("url");const s=new URL(t);n&&s.searchParams.append("id_token_hint",n),i&&(s.searchParams.append("post_logout_redirect_uri",i),e&&(this.state=new J({data:e,request_type:r}),s.searchParams.append("state",this.state.id)));for(const[t,e]of Object.entries({...o}))null!=e&&s.searchParams.append(t,e.toString());this.url=s.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 G(t),this.metadataService=new D(this.settings),this._validator=new K(this.settings,this.metadataService),this._tokenClient=new z(this.settings,this.metadataService)}async createSigninRequest({state:t,request:e,request_uri:n,request_type:i,id_token_hint:o,login_hint:r,skipUserInfo:s,nonce:a,response_type:c=this.settings.response_type,scope:l=this.settings.scope,redirect_uri:h=this.settings.redirect_uri,prompt:p=this.settings.prompt,display:u=this.settings.display,max_age:d=this.settings.max_age,ui_locales:g=this.settings.ui_locales,acr_values:_=this.settings.acr_values,resource:m=this.settings.resource,response_mode:f=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 Y({url:v,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:h,response_type:c,scope:l,state_data:t,prompt:p,display:u,max_age:d,ui_locales:g,id_token_hint:o,login_hint:r,acr_values:_,resource:m,request:e,request_uri:n,extraQueryParams:y,extraTokenParams:w,request_type:i,response_mode:f,client_secret:this.settings.client_secret,skipUserInfo:s,nonce:a});await this.clearStaleState();const C=k.state;return await this.settings.stateStore.set(C.id,C.toStorageString()),k}async readSigninResponseState(t,e=!1){const n=this._logger.create("readSigninResponseState"),i=new X(U.readParams(t,this.settings.response_mode));if(!i.state)throw n.throw(new Error("No state in response")),null;const o=await this.settings.stateStore[e?"remove":"get"](i.state);if(!o)throw n.throw(new Error("No matching state found in storage")),null;return{state:Q.fromStorageString(o),response:i}}async processSigninResponse(t){const e=this._logger.create("processSigninResponse"),{state:n,response:i}=await this.readSigninResponseState(t,!0);return e.debug("received state from storage; validating response"),await this._validator.validateSigninResponse(i,n),i}async processResourceOwnerPasswordCredentials({username:t,password:e,skipUserInfo:n=!1,extraTokenParams:i={}}){const o=await this._tokenClient.exchangeCredentials({username:t,password:e,...i}),r=new X(new URLSearchParams);return Object.assign(r,o),await this._validator.validateCredentialsResponse(r,n),r}async useRefreshToken({state:t,timeoutInSeconds:e}){var n;const i=this._logger.create("useRefreshToken");let o;if(void 0===this.settings.refreshTokenAllowedScope)o=t.scope;else{const e=this.settings.refreshTokenAllowedScope.split(" ");o=((null==(n=t.scope)?void 0:n.split(" "))||[]).filter(t=>e.includes(t)).join(" ")}const r=await this._tokenClient.exchangeRefreshToken({refresh_token:t.refresh_token,scope:o,timeoutInSeconds:e}),s=new X(new URLSearchParams);return Object.assign(s,r),i.debug("validating response",s),await this._validator.validateRefreshResponse(s,{...t,scope:o}),s}async createSignoutRequest({state:t,id_token_hint:e,request_type:n,post_logout_redirect_uri:i=this.settings.post_logout_redirect_uri,extraQueryParams:o=this.settings.extraQueryParams}={}){const r=this._logger.create("createSignoutRequest"),s=await this.metadataService.getEndSessionEndpoint();if(!s)throw r.throw(new Error("No end session endpoint")),null;r.debug("Received end session endpoint",s);const a=new Z({url:s,id_token_hint:e,post_logout_redirect_uri:i,state_data:t,extraQueryParams:o,request_type:n});await this.clearStaleState();const c=a.state;return c&&(r.debug("Signout request has state to persist"),await this.settings.stateStore.set(c.id,c.toStorageString())),a}async readSignoutResponseState(t,e=!1){const n=this._logger.create("readSignoutResponseState"),i=new tt(U.readParams(t,this.settings.response_mode));if(!i.state){if(n.debug("No state in response"),i.error)throw n.warn("Response was error:",i.error),new q(i);return{state:void 0,response:i}}const o=await this.settings.stateStore[e?"remove":"get"](i.state);if(!o)throw n.throw(new Error("No matching state found in storage")),null;return{state:J.fromStorageString(o),response:i}}async processSignoutResponse(t){const e=this._logger.create("processSignoutResponse"),{state:n,response:i}=await this.readSignoutResponseState(t,!0);return n?(e.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(i,n)):e.debug("No state from storage; skipping response validation"),i}clearStaleState(){return this._logger.create("clearStaleState"),J.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 nt={},it=(t,e)=>st()?localStorage.setItem(t,e):nt[t]=e,ot=t=>st()?localStorage.getItem(t):nt[t],rt=t=>st()?localStorage.removeItem(t):delete nt[t],st=()=>!("object"==typeof process&&"[object process]"===String(process));function at(t){if(!t)return!1;const e=(t.message||t.toString()||"").toLowerCase();return e.includes("cors")||e.includes("cross-origin")||e.includes("network error")||e.includes("failed to fetch")||e.includes("networkerror")||e.includes("load failed")||e.includes("xhr poll error")||e.includes("websocket error")||e.includes("transport")&&e.includes("error")}function ct(t,e){console.error(`\n╔══════════════════════════════════════════════════════════════════════════════╗\n║ GameGlue SDK: Possible CORS Error Detected ║\n╠══════════════════════════════════════════════════════════════════════════════╣\n║ Context: ${t.padEnd(66)}║\n║ URL: ${(e||"unknown").substring(0,70).padEnd(70)}║\n╠══════════════════════════════════════════════════════════════════════════════╣\n║ This error typically means the server rejected the request due to CORS. ║\n║ ║\n║ To fix this, add your origin to your app's allowed Web Origins: ║\n║ ║\n║ 1. Go to the GameGlue Developer Portal (https://developer.gameglue.gg) ║\n║ 2. Select your app ║\n║ 3. Add your origin to "Web Origins" and save ║\n║ ║\n║ IMPORTANT: Protocol and port must match exactly. ║\n║ http://localhost:3000 and https://localhost:3000 are different origins. ║\n║ http://localhost:3000 and http://localhost:5000 are different origins. ║\n╚══════════════════════════════════════════════════════════════════════════════╝\n`)}let lt=null;class ht{constructor(t){const e=t.authUrl||"https://auth.gameglue.gg/realms/GameGlue";this._oidcSettings={authority:e,client_id:t.clientId,redirect_uri:pt(t.redirect_uri||window.location.href),post_logout_redirect_uri:pt(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=>{at(t)&&ct("Login Request",this._oidcSettings.authority),console.error("Failed to create signin request:",t)})}logout(t={}){if(rt("gg-auth-token"),rt("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 E(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(lt)await lt;else{lt=this._doProcessCallback();try{await lt}finally{lt=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=E(t);return new Date(1e3*e.exp)>new Date}catch{return!1}}_getAccessToken(){const t=ot("gg-auth-token");return t&&this._setTokenRefreshTimeout(t),t||void 0}_setAccessToken(t){return this._setTokenRefreshTimeout(t),it("gg-auth-token",t)}_setRefreshToken(t){return it("gg-refresh-token",t)}_getRefreshToken(){return ot("gg-refresh-token")}_setTokenRefreshTimeout(t){if(t){clearTimeout(this._refreshTimeout);try{const e=1e3*E(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,n=this._getRefreshToken();try{const i=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:n})});if(200===i.status){const t=await i.json();this._setAccessToken(t.access_token),this._setRefreshToken(t.refresh_token),this._refreshCallback(t.access_token)}}catch(e){at(e)&&ct("Token Refresh",t),console.error("Token refresh failed:",e)}}}function pt(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 dt=Object.create(null);Object.keys(ut).forEach(t=>{dt[ut[t]]=t});const gt={type:"error",data:"parser error"},_t="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),mt="function"==typeof ArrayBuffer,ft=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,yt=({type:t,data:e},n,i)=>_t&&e instanceof Blob?n?i(e):wt(e,i):mt&&(e instanceof ArrayBuffer||ft(e))?n?i(e):wt(new Blob([e]),i):i(ut[t]+(e||"")),wt=(t,e)=>{const n=new FileReader;return n.onload=function(){const t=n.result.split(",")[1];e("b"+(t||""))},n.readAsDataURL(t)};function bt(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let vt;const kt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ct="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)Ct[kt.charCodeAt(t)]=t;const St="function"==typeof ArrayBuffer,Et=(t,e)=>{if("string"!=typeof t)return{type:"message",data:At(t,e)};const n=t.charAt(0);if("b"===n)return{type:"message",data:Tt(t.substring(1),e)};return dt[n]?t.length>1?{type:dt[n],data:t.substring(1)}:{type:dt[n]}:gt},Tt=(t,e)=>{if(St){const n=(t=>{let e,n,i,o,r,s=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(s--,"="===t[t.length-2]&&s--);const l=new ArrayBuffer(s),h=new Uint8Array(l);for(e=0;e<a;e+=4)n=Ct[t.charCodeAt(e)],i=Ct[t.charCodeAt(e+1)],o=Ct[t.charCodeAt(e+2)],r=Ct[t.charCodeAt(e+3)],h[c++]=n<<2|i>>4,h[c++]=(15&i)<<4|o>>2,h[c++]=(3&o)<<6|63&r;return l})(t);return At(n,e)}return{base64:!0,data:t}},At=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,xt=String.fromCharCode(30);function Ot(){return new TransformStream({transform(t,e){!function(t,e){_t&&t.data instanceof Blob?t.data.arrayBuffer().then(bt).then(e):mt&&(t.data instanceof ArrayBuffer||ft(t.data))?e(bt(t.data)):yt(t,!1,t=>{vt||(vt=new TextEncoder),e(vt.encode(t))})}(t,n=>{const i=n.length;let o;if(i<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,i);else if(i<65536){o=new Uint8Array(3);const t=new DataView(o.buffer);t.setUint8(0,126),t.setUint16(1,i)}else{o=new Uint8Array(9);const t=new DataView(o.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(i))}t.data&&"string"!=typeof t.data&&(o[0]|=128),e.enqueue(o),e.enqueue(n)})}})}let Rt;function Pt(t){return t.reduce((t,e)=>t+e.length,0)}function It(t,e){if(t[0].length===e)return t.shift();const n=new Uint8Array(e);let i=0;for(let o=0;o<e;o++)n[o]=t[0][i++],i===t[0].length&&(t.shift(),i=0);return t.length&&i<t[0].length&&(t[0]=t[0].slice(i)),n}function Lt(t){if(t)return function(t){for(var e in Lt.prototype)t[e]=Lt.prototype[e];return t}(t)}Lt.prototype.on=Lt.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},Lt.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},Lt.prototype.off=Lt.prototype.removeListener=Lt.prototype.removeAllListeners=Lt.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,i=this._callbacks["$"+t];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var o=0;o<i.length;o++)if((n=i[o])===e||n.fn===e){i.splice(o,1);break}return 0===i.length&&delete this._callbacks["$"+t],this},Lt.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],i=1;i<arguments.length;i++)e[i-1]=arguments[i];if(n){i=0;for(var o=(n=n.slice(0)).length;i<o;++i)n[i].apply(this,e)}return this},Lt.prototype.emitReserved=Lt.prototype.emit,Lt.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},Lt.prototype.hasListeners=function(t){return!!this.listeners(t).length};const Nt="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),Bt="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Ut(t,...e){return e.reduce((e,n)=>(t.hasOwnProperty(n)&&(e[n]=t[n]),e),{})}const qt=Bt.setTimeout,jt=Bt.clearTimeout;function Mt(t,e){e.useNativeTimers?(t.setTimeoutFn=qt.bind(Bt),t.clearTimeoutFn=jt.bind(Bt)):(t.setTimeoutFn=Bt.setTimeout.bind(Bt),t.clearTimeoutFn=Bt.clearTimeout.bind(Bt))}function Ft(t){return"string"==typeof t?function(t){let e=0,n=0;for(let i=0,o=t.length;i<o;i++)e=t.charCodeAt(i),e<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(i++,n+=4);return n}(t):Math.ceil(1.33*(t.byteLength||t.size))}function Dt(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class Ht extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class Gt extends Lt{constructor(t){super(),this.writable=!1,Mt(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,n){return super.emitReserved("error",new Ht(t,e,n)),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=Et(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 n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e}(t);return e.length?"?"+e:""}}class Vt extends Gt{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 n=t.split(xt),i=[];for(let t=0;t<n.length;t++){const o=Et(n[t],e);if(i.push(o),"error"===o.type)break}return i})(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 n=t.length,i=new Array(n);let o=0;t.forEach((t,r)=>{yt(t,!1,t=>{i[r]=t,++o===n&&e(i.join(xt))})})})(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]=Dt()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let zt=!1;try{zt="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const $t=zt;function Wt(){}class Kt extends Vt{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let n=location.port;n||(n=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.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 Lt{constructor(t,e,n){super(),this.createRequest=t,Mt(this,n),this._opts=n,this._method=n.method||"GET",this._uri=e,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var t;const e=Ut(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(e);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let t in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(t)&&n.setRequestHeader(t,this._opts.extraHeaders[t])}}catch(t){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{n.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var t;3===n.readyState&&(null===(t=this._opts.cookieJar)||void 0===t||t.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.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=Wt,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",Qt);else if("function"==typeof addEventListener){addEventListener("onpagehide"in Bt?"pagehide":"unload",Qt,!1)}function Qt(){for(let t in Jt.requests)Jt.requests.hasOwnProperty(t)&&Jt.requests[t].abort()}const Yt=function(){const t=Xt({xdomain:!1});return t&&null!==t.responseType}();function Xt(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||$t))return new XMLHttpRequest}catch(t){}if(!e)try{return new(Bt[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const Zt="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class te extends Gt{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=Zt?{}:Ut(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,n)}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 n=t[e],i=e===t.length-1;yt(n,this.supportsBinary,t=>{try{this.doWrite(n,t)}catch(t){}i&&Nt(()=>{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]=Dt()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const ee=Bt.WebSocket||Bt.MozWebSocket;const ne={websocket:class extends te{createSocket(t,e,n){return Zt?new ee(t,e,n):e?new ee(t,e):new ee(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends Gt{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 n=[];let i=0,o=-1,r=!1;return new TransformStream({transform(s,a){for(n.push(s);;){if(0===i){if(Pt(n)<1)break;const t=It(n,1);r=!(128&~t[0]),o=127&t[0],i=o<126?3:126===o?1:2}else if(1===i){if(Pt(n)<2)break;const t=It(n,2);o=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),i=3}else if(2===i){if(Pt(n)<8)break;const t=It(n,8),e=new DataView(t.buffer,t.byteOffset,t.length),r=e.getUint32(0);if(r>Math.pow(2,21)-1){a.enqueue(gt);break}o=r*Math.pow(2,32)+e.getUint32(4),i=3}else{if(Pt(n)<o)break;const t=It(n,o);a.enqueue(Et(r?t:Rt.decode(t),e)),i=0}if(0===o||o>t){a.enqueue(gt);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),i=Ot();i.readable.pipeTo(t.writable),this._writer=i.writable.getWriter();const o=()=>{n.read().then(({done:t,value:e})=>{t||(this.onPacket(e),o())}).catch(t=>{})};o();const r={type:"open"};this.query.sid&&(r.data=`{"sid":"${this.query.sid}"}`),this._writer.write(r).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],i=e===t.length-1;this._writer.write(n).then(()=>{i&&Nt(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this._transport)||void 0===t||t.close()}},polling:class extends Kt{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=Yt&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Jt(Xt,this.uri(),t)}}},ie=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,oe=["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,n=t.indexOf("["),i=t.indexOf("]");-1!=n&&-1!=i&&(t=t.substring(0,n)+t.substring(n,i).replace(/:/g,";")+t.substring(i,t.length));let o=ie.exec(t||""),r={},s=14;for(;s--;)r[oe[s]]=o[s]||"";return-1!=n&&-1!=i&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=function(t,e){const n=/\/{2,9}/g,i=e.replace(n,"/").split("/");"/"!=e.slice(0,1)&&0!==e.length||i.splice(0,1);"/"==e.slice(-1)&&i.splice(i.length-1,1);return i}(0,r.path),r.queryKey=function(t,e){const n={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,i){e&&(n[e]=i)}),n}(0,r.query),r}const se="function"==typeof addEventListener&&"function"==typeof removeEventListener,ae=[];se&&addEventListener("offline",()=>{ae.forEach(t=>t())},!1);class ce extends Lt{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 n=re(t);e.hostname=n.host,e.secure="https"===n.protocol||"wss"===n.protocol,e.port=n.port,n.query&&(e.query=n.query)}else e.host&&(e.hostname=re(e.host).host);Mt(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={},n=t.split("&");for(let t=0,i=n.length;t<i;t++){let i=n[t].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}(this.opts.query)),se&&(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"})},ae.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 n=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](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&ce.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",ce.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 n=this.writeBuffer[e].data;if(n&&(t+=Ft(n)),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,Nt(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,n){return this._sendPacket("message",t,e,n),this}send(t,e,n){return this._sendPacket("message",t,e,n),this}_sendPacket(t,e,n,i){if("function"==typeof e&&(i=e,e=void 0),"function"==typeof n&&(i=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const o={type:t,data:e,options:n};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),i&&this.once("flush",i),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{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?n():t()}):this.upgrading?n():t()),this}_onError(t){if(ce.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(),se&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=ae.indexOf(this._offlineEventListener);-1!==t&&ae.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}ce.protocol=4;class le extends ce{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),n=!1;ce.priorWebsocketSuccess=!1;const i=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!n)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;ce.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(l(),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 o(){n||(n=!0,l(),e.close(),e=null)}const r=t=>{const n=new Error("probe error: "+t);n.transport=e.name,o(),this.emitReserved("upgradeError",n)};function s(){r("transport closed")}function a(){r("socket closed")}function c(t){e&&t.name!==e.name&&o()}const l=()=>{e.removeListener("open",i),e.removeListener("error",r),e.removeListener("close",s),this.off("close",a),this.off("upgrading",c)};e.once("open",i),e.once("error",r),e.once("close",s),this.once("close",a),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{n||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}let he=class extends le{constructor(t,e={}){const n="object"==typeof t?t:e;(!n.transports||n.transports&&"string"==typeof n.transports[0])&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(t=>ne[t]).filter(t=>!!t)),super(t,n)}};const pe="function"==typeof ArrayBuffer,ue=Object.prototype.toString,de="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===ue.call(Blob),ge="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===ue.call(File);function _e(t){return pe&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||de&&t instanceof Blob||ge&&t instanceof File}function me(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,n=t.length;e<n;e++)if(me(t[e]))return!0;return!1}if(_e(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return me(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&me(t[e]))return!0;return!1}function fe(t){const e=[],n=t.data,i=t;return i.data=ye(n,e),i.attachments=e.length,{packet:i,buffers:e}}function ye(t,e){if(!t)return t;if(_e(t)){const n={_placeholder:!0,num:e.length};return e.push(t),n}if(Array.isArray(t)){const n=new Array(t.length);for(let i=0;i<t.length;i++)n[i]=ye(t[i],e);return n}if("object"==typeof t&&!(t instanceof Date)){const n={};for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[i]=ye(t[i],e));return n}return t}function we(t,e){return t.data=be(t.data,e),delete t.attachments,t}function be(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 n=0;n<t.length;n++)t[n]=be(t[n],e);else if("object"==typeof t)for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(t[n]=be(t[n],e));return t}const ve=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var ke;!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"}(ke||(ke={}));class Ce extends Lt{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 n=e.type===ke.BINARY_EVENT;n||e.type===ke.BINARY_ACK?(e.type=n?ke.EVENT:ke.ACK,this.reconstructor=new Se(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!_e(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 n={type:Number(t.charAt(0))};if(void 0===ke[n.type])throw new Error("unknown packet type "+n.type);if(n.type===ke.BINARY_EVENT||n.type===ke.BINARY_ACK){const i=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const o=t.substring(i,e);if(o!=Number(o)||"-"!==t.charAt(e))throw new Error("Illegal attachments");n.attachments=Number(o)}if("/"===t.charAt(e+1)){const i=e+1;for(;++e;){if(","===t.charAt(e))break;if(e===t.length)break}n.nsp=t.substring(i,e)}else n.nsp="/";const i=t.charAt(e+1);if(""!==i&&Number(i)==i){const i=e+1;for(;++e;){const n=t.charAt(e);if(null==n||Number(n)!=n){--e;break}if(e===t.length)break}n.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(!Ce.isPayloadValid(n.type,i))throw new Error("invalid payload");n.data=i}return n}tryParse(t){try{return JSON.parse(t,this.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case ke.CONNECT:return Te(e);case ke.DISCONNECT:return void 0===e;case ke.CONNECT_ERROR:return"string"==typeof e||Te(e);case ke.EVENT:case ke.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===ve.indexOf(e[0]));case ke.ACK:case ke.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Se{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=we(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Ee=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t};function Te(t){return"[object Object]"===Object.prototype.toString.call(t)}var Ae=Object.freeze({__proto__:null,Decoder:Ce,Encoder:class{constructor(t){this.replacer=t}encode(t){return t.type!==ke.EVENT&&t.type!==ke.ACK||!me(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===ke.EVENT?ke.BINARY_EVENT:ke.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==ke.BINARY_EVENT&&t.type!==ke.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=fe(t),n=this.encodeAsString(e.packet),i=e.buffers;return i.unshift(n),i}},get PacketType(){return ke},isPacketValid:function(t){return"string"==typeof t.nsp&&(void 0===(e=t.id)||Ee(e))&&function(t,e){switch(t){case ke.CONNECT:return void 0===e||Te(e);case ke.DISCONNECT:return void 0===e;case ke.EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===ve.indexOf(e[0]));case ke.ACK:return Array.isArray(e);case ke.CONNECT_ERROR:return"string"==typeof e||Te(e);default:return!1}}(t.type,t.data);var e},protocol:5});function xe(t,e,n){return t.on(e,n),function(){t.off(e,n)}}const Oe=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Re extends Lt{constructor(t,e,n){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,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[xe(t,"open",this.onopen.bind(this)),xe(t,"packet",this.onpacket.bind(this)),xe(t,"error",this.onerror.bind(this)),xe(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 n,i,o;if(Oe.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 r={type:ke.EVENT,data:e,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,n=e.pop();this._registerAckCallback(t,n),r.id=t}const s=null===(i=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===i?void 0:i.writable,a=this.connected&&!(null===(o=this.io.engine)||void 0===o?void 0:o._hasPingExpired());return this.flags.volatile&&!s||(a?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(t,e){var n;const i=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===i)return void(this.acks[t]=e);const o=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"))},i),r=(...t)=>{this.io.clearTimeoutFn(o),e.apply(this,t)};r.withError=!0,this.acks[t]=r}emitWithAck(t,...e){return new Promise((n,i)=>{const o=(t,e)=>t?i(t):n(e);o.withError=!0,e.push(o),this.emit(t,...e)})}_addToQueue(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...i)=>{this._queue[0];return null!==t?n.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(t)):(this._queue.shift(),e&&e(null,...i)),n.pending=!1,this._drainQueue()}),this._queue.push(n),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:ke.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 ke.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 ke.EVENT:case ke.BINARY_EVENT:this.onevent(t);break;case ke.ACK:case ke.BINARY_ACK:this.onack(t);break;case ke.DISCONNECT:this.ondisconnect();break;case ke.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 n of e)n.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 n=!1;return function(...i){n||(n=!0,e.packet({type:ke.ACK,id:t,data:i}))}}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:ke.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 n=0;n<e.length;n++)if(t===e[n])return e.splice(n,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 n=0;n<e.length;n++)if(t===e[n])return e.splice(n,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 n of e)n.apply(this,t.data)}}}function Pe(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}Pe.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+n:t-n}return 0|Math.min(t,this.max)},Pe.prototype.reset=function(){this.attempts=0},Pe.prototype.setMin=function(t){this.ms=t},Pe.prototype.setMax=function(t){this.max=t},Pe.prototype.setJitter=function(t){this.jitter=t};class Ie extends Lt{constructor(t,e){var n;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,Mt(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!==(n=e.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new Pe({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const i=e.parser||Ae;this.encoder=new i.Encoder,this.decoder=new i.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 he(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=xe(e,"open",function(){n.onopen(),t&&t()}),o=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},r=xe(e,"error",o);if(!1!==this._timeout){const t=this._timeout,n=this.setTimeoutFn(()=>{i(),o(new Error("timeout")),e.close()},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(i),this.subs.push(r),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(xe(t,"ping",this.onping.bind(this)),xe(t,"data",this.ondata.bind(this)),xe(t,"error",this.onerror.bind(this)),xe(t,"close",this.onclose.bind(this)),xe(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){Nt(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new Re(this,t,e),this.nsps[t]=n),n}_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 n=0;n<e.length;n++)this.engine.write(e[n],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 n;this.cleanup(),null===(n=this.engine)||void 0===n||n.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 n=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&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Le={};function Ne(t,e){"object"==typeof t&&(e=t,t=void 0);const n=function(t,e="",n){let i=t;n=n||"undefined"!=typeof location&&location,null==t&&(t=n.protocol+"//"+n.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?n.protocol+t:n.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==n?n.protocol+"//"+t:"https://"+t),i=re(t)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const o=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+o+":"+i.port+e,i.href=i.protocol+"://"+o+(n&&n.port===i.port?"":":"+i.port),i}(t,(e=e||{}).path||"/socket.io"),i=n.source,o=n.id,r=n.path,s=Le[o]&&r in Le[o].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||s?a=new Ie(i,e):(Le[o]||(Le[o]=new Ie(i,e)),a=Le[o]),n.query&&!e.query&&(e.query=n.queryKey),a.socket(n.path,e)}Object.assign(Ne,{Manager:Ie,Socket:Re,io:Ne,connect:Ne});var Be,Ue,qe,je,Me,Fe,De,He,Ge,Ve,ze,$e,We,Ke,Je,Qe,Ye,Xe,Ze,tn,en,nn,on,rn,sn,an,cn,ln,hn,pn,un,dn,gn,_n,mn,fn,yn,wn,bn,vn,kn={exports:{}},Cn={exports:{}};function Sn(){if(Ue)return Be;Ue=1;return Be=function(t){return null!=t},Be}function En(){if(Fe)return Me;Fe=1;var t=function(){if(je)return qe;je=1;var t=Sn(),e={object:!0,function:!0,undefined:!0};return qe=function(n){return!!t(n)&&hasOwnProperty.call(e,typeof n)},qe}();return Me=function(e){if(!t(e))return!1;try{return!!e.constructor&&e.constructor.prototype===e}catch(t){return!1}},Me}function Tn(){if(Ve)return Ge;Ve=1;var t=function(){if(He)return De;He=1;var t=En();return De=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)},De}(),e=/^\s*class[\s{/}]/,n=Function.prototype.toString;return Ge=function(i){return!!t(i)&&!e.test(n.call(i))},Ge}function An(){if(Xe)return Ye;Xe=1;var t=(Qe?Je:(Qe=1,Je=function(){}))();return Ye=function(e){return e!==t&&null!==e}}function xn(){return nn||(nn=1,en=(Ke?We:(Ke=1,We=function(){try{return Object.keys("primitive"),!0}catch(t){return!1}}))()?Object.keys:function(){if(tn)return Ze;tn=1;var t=An(),e=Object.keys;return Ze=function(n){return e(t(n)?Object(n):n)}}()),en}function On(){if(an)return sn;an=1;var t=xn(),e=function(){if(rn)return on;rn=1;var t=An();return on=function(e){if(!t(e))throw new TypeError("Cannot use null or undefined");return e},on}(),n=Math.max;return sn=function(i,o){var r,s,a,c=n(arguments.length,2);for(i=Object(e(i)),a=function(t){try{i[t]=o[t]}catch(t){r||(r=t)}},s=1;s<c;++s)t(o=arguments[s]).forEach(a);if(void 0!==r)throw r;return i},sn}function Rn(){return ln?cn:(ln=1,cn=($e||($e=1,ze=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")}),ze)()?Object.assign:On())}function Pn(){return fn||(fn=1,mn=function(){if(dn)return un;dn=1;var t="razdwatrzy";return un=function(){return"function"==typeof t.contains&&!0===t.contains("dwa")&&!1===t.contains("foo")}}()()?String.prototype.contains:function(){if(_n)return gn;_n=1;var t=String.prototype.indexOf;return gn=function(e){return t.call(this,e,arguments[1])>-1},gn}()),mn}function In(){if(yn)return Cn.exports;yn=1;var t=Sn(),e=Tn(),n=Rn(),i=function(){if(pn)return hn;pn=1;var t=An(),e=Array.prototype.forEach,n=Object.create;return hn=function(i){var o=n(null);return e.call(arguments,function(e){t(e)&&function(t,e){var n;for(n in t)e[n]=t[n]}(Object(e),o)}),o},hn}(),o=Pn(),r=Cn.exports=function(e,r){var s,a,c,l,h;return arguments.length<2||"string"!=typeof e?(l=r,r=e,e=null):l=arguments[2],t(e)?(s=o.call(e,"c"),a=o.call(e,"e"),c=o.call(e,"w")):(s=c=!0,a=!1),h={value:r,configurable:s,enumerable:a,writable:c},l?n(i(l),h):h};return r.gs=function(r,s,a){var c,l,h,p;return"string"!=typeof r?(h=a,a=s,s=r,r=null):h=arguments[3],t(s)?e(s)?t(a)?e(a)||(h=a,a=void 0):a=void 0:(h=s,s=a=void 0):s=void 0,t(r)?(c=o.call(r,"c"),l=o.call(r,"e")):(c=!0,l=!1),p={get:s,set:a,configurable:c,enumerable:l},h?n(i(h),p):p},Cn.exports}var Ln=(vn||(vn=1,function(t,e){var n,i,o,r,s,a,c,l=In(),h=bn?wn:(bn=1,wn=function(t){if("function"!=typeof t)throw new TypeError(t+" is not a function");return t}),p=Function.prototype.apply,u=Function.prototype.call,d=Object.create,g=Object.defineProperty,_=Object.defineProperties,m=Object.prototype.hasOwnProperty,f={configurable:!0,enumerable:!1,writable:!0};i=function(t,e){var i,r;return h(e),r=this,n.call(this,t,i=function(){o.call(r,t,i),p.call(e,this,arguments)}),i.__eeOnceListener__=e,this},r=function(t){var e,n,i,o,r;if(m.call(this,"__ee__")&&(o=this.__ee__[t]))if("object"==typeof o){for(n=arguments.length,r=new Array(n-1),e=1;e<n;++e)r[e-1]=arguments[e];for(o=o.slice(),e=0;i=o[e];++e)p.call(i,this,r)}else switch(arguments.length){case 1:u.call(o,this);break;case 2:u.call(o,this,arguments[1]);break;case 3:u.call(o,this,arguments[1],arguments[2]);break;default:for(n=arguments.length,r=new Array(n-1),e=1;e<n;++e)r[e-1]=arguments[e];p.call(o,this,r)}},s={on:n=function(t,e){var n;return h(e),m.call(this,"__ee__")?n=this.__ee__:(n=f.value=d(null),g(this,"__ee__",f),f.value=null),n[t]?"object"==typeof n[t]?n[t].push(e):n[t]=[n[t],e]:n[t]=e,this},once:i,off:o=function(t,e){var n,i,o,r;if(h(e),!m.call(this,"__ee__"))return this;if(!(n=this.__ee__)[t])return this;if("object"==typeof(i=n[t]))for(r=0;o=i[r];++r)o!==e&&o.__eeOnceListener__!==e||(2===i.length?n[t]=i[r?0:1]:i.splice(r,1));else i!==e&&i.__eeOnceListener__!==e||delete n[t];return this},emit:r},a={on:l(n),once:l(i),off:l(o),emit:l(r)},c=_({},a),t.exports=e=function(t){return null==t?d(c):_(Object(t),a)},e.methods=s}(kn,kn.exports)),kn.exports),Nn=n(Ln);const Bn={radiansToDegrees:t=>t*(180/Math.PI),degreesToRadians:t=>t*(Math.PI/180),metersToFeet:t=>3.28084*t,feetToMeters:t=>t/3.28084,msToKnots:t=>1.94384*t,knotsToMs:t=>t/1.94384,msToFpm:t=>196.85*t,toBoolean:t=>Boolean(t),divideBy100:t=>t/100},Un={category:"flight_sim",name:"Flight Simulator",description:"Canonical telemetry fields for flight simulation games",recommendedUpdateRateHz:10,requiredFields:["latitude","longitude","altitude","indicated_airspeed","heading","vertical_speed","on_ground"],fields:{latitude:{type:"number",description:"Aircraft latitude",unit:"degrees",min:-90,max:90,group:"Position"},longitude:{type:"number",description:"Aircraft longitude",unit:"degrees",min:-180,max:180,group:"Position"},altitude:{type:"number",description:"Aircraft altitude above sea level",unit:"ft",min:-2e3,max:1e5,group:"Position"},altitude_agl:{type:"number",description:"Aircraft altitude above ground level",unit:"ft",min:0,max:1e5,group:"Position"},on_ground:{type:"boolean",description:"Whether aircraft is on the ground",group:"Position"},indicated_airspeed:{type:"number",description:"Indicated airspeed",unit:"kts",min:0,max:1e3,group:"Velocity"},true_airspeed:{type:"number",description:"True airspeed",unit:"kts",min:0,max:1e3,group:"Velocity"},ground_speed:{type:"number",description:"Ground speed",unit:"kts",min:0,max:1e3,group:"Velocity"},mach:{type:"number",description:"Mach number",min:0,max:5,group:"Velocity"},vertical_speed:{type:"number",description:"Vertical speed",unit:"ft/min",min:-2e4,max:2e4,group:"Velocity"},g_force:{type:"number",description:"Current G-force",unit:"G",min:-10,max:10,group:"Velocity"},heading:{type:"number",description:"Aircraft magnetic heading",unit:"degrees",min:0,max:360,group:"Attitude"},true_heading:{type:"number",description:"Aircraft true heading",unit:"degrees",min:0,max:360,group:"Attitude"},pitch:{type:"number",description:"Aircraft pitch angle",unit:"degrees",min:-90,max:90,group:"Attitude"},roll:{type:"number",description:"Aircraft roll/bank angle",unit:"degrees",min:-180,max:180,group:"Attitude"},yaw:{type:"number",description:"Aircraft yaw angle",unit:"degrees",min:-180,max:180,group:"Attitude"},throttle_0:{type:"number",description:"Engine 0 throttle position",unit:"%",min:0,max:100,group:"Engine"},throttle_1:{type:"number",description:"Engine 1 throttle position",unit:"%",min:0,max:100,group:"Engine"},throttle_2:{type:"number",description:"Engine 2 throttle position",unit:"%",min:0,max:100,group:"Engine"},throttle_3:{type:"number",description:"Engine 3 throttle position",unit:"%",min:0,max:100,group:"Engine"},rpm_0:{type:"number",description:"Engine 0 RPM",unit:"RPM",min:0,max:1e4,group:"Engine"},rpm_1:{type:"number",description:"Engine 1 RPM",unit:"RPM",min:0,max:1e4,group:"Engine"},rpm_2:{type:"number",description:"Engine 2 RPM",unit:"RPM",min:0,max:1e4,group:"Engine"},rpm_3:{type:"number",description:"Engine 3 RPM",unit:"RPM",min:0,max:1e4,group:"Engine"},n1_0:{type:"number",description:"Engine 0 N1 (turbine)",unit:"%",min:0,max:120,group:"Engine"},n1_1:{type:"number",description:"Engine 1 N1 (turbine)",unit:"%",min:0,max:120,group:"Engine"},n1_2:{type:"number",description:"Engine 2 N1 (turbine)",unit:"%",min:0,max:120,group:"Engine"},n1_3:{type:"number",description:"Engine 3 N1 (turbine)",unit:"%",min:0,max:120,group:"Engine"},n2_0:{type:"number",description:"Engine 0 N2 (turbine)",unit:"%",min:0,max:120,group:"Engine"},n2_1:{type:"number",description:"Engine 1 N2 (turbine)",unit:"%",min:0,max:120,group:"Engine"},n2_2:{type:"number",description:"Engine 2 N2 (turbine)",unit:"%",min:0,max:120,group:"Engine"},n2_3:{type:"number",description:"Engine 3 N2 (turbine)",unit:"%",min:0,max:120,group:"Engine"},egt_0:{type:"number",description:"Engine 0 exhaust gas temperature",unit:"°C",min:0,max:1200,group:"Engine"},egt_1:{type:"number",description:"Engine 1 exhaust gas temperature",unit:"°C",min:0,max:1200,group:"Engine"},egt_2:{type:"number",description:"Engine 2 exhaust gas temperature",unit:"°C",min:0,max:1200,group:"Engine"},egt_3:{type:"number",description:"Engine 3 exhaust gas temperature",unit:"°C",min:0,max:1200,group:"Engine"},fuel_quantity:{type:"number",description:"Total fuel quantity",unit:"lbs",min:0,max:6e5,group:"Fuel"},fuel_flow_0:{type:"number",description:"Engine 0 fuel flow",unit:"lbs/hr",min:0,max:3e4,group:"Fuel"},fuel_flow_1:{type:"number",description:"Engine 1 fuel flow",unit:"lbs/hr",min:0,max:3e4,group:"Fuel"},fuel_flow_2:{type:"number",description:"Engine 2 fuel flow",unit:"lbs/hr",min:0,max:3e4,group:"Fuel"},fuel_flow_3:{type:"number",description:"Engine 3 fuel flow",unit:"lbs/hr",min:0,max:3e4,group:"Fuel"},autopilot_master:{type:"boolean",description:"Autopilot master engaged",group:"Autopilot"},autopilot_altitude_hold:{type:"boolean",description:"Altitude hold engaged",group:"Autopilot"},autopilot_heading_hold:{type:"boolean",description:"Heading hold engaged",group:"Autopilot"},autopilot_vs_hold:{type:"boolean",description:"Vertical speed hold engaged",group:"Autopilot"},autopilot_speed_hold:{type:"boolean",description:"Speed hold engaged",group:"Autopilot"},autopilot_approach:{type:"boolean",description:"Approach mode engaged",group:"Autopilot"},autopilot_nav:{type:"boolean",description:"NAV mode engaged",group:"Autopilot"},flight_director:{type:"boolean",description:"Flight director active",group:"Autopilot"},autopilot_flc:{type:"boolean",description:"Flight level change mode engaged",group:"Autopilot"},autopilot_altitude_target:{type:"number",description:"Autopilot target altitude",unit:"ft",min:0,max:6e4,group:"Autopilot"},autopilot_heading_target:{type:"number",description:"Autopilot target heading",unit:"degrees",min:0,max:360,group:"Autopilot"},autopilot_vs_target:{type:"number",description:"Autopilot target vertical speed",unit:"ft/min",min:-1e4,max:1e4,group:"Autopilot"},autopilot_speed_target:{type:"number",description:"Autopilot target airspeed",unit:"kts",min:0,max:600,group:"Autopilot"},flaps:{type:"number",description:"Flaps position",unit:"%",min:0,max:100,group:"Controls"},spoilers:{type:"number",description:"Spoilers position",unit:"%",min:0,max:100,group:"Controls"},gear_down:{type:"boolean",description:"Landing gear extended",group:"Controls"},parking_brake:{type:"boolean",description:"Parking brake engaged",group:"Controls"},brake_left:{type:"number",description:"Left brake position",unit:"%",min:0,max:100,group:"Controls"},brake_right:{type:"number",description:"Right brake position",unit:"%",min:0,max:100,group:"Controls"},light_landing:{type:"boolean",description:"Landing lights on",group:"Lights"},light_taxi:{type:"boolean",description:"Taxi lights on",group:"Lights"},light_beacon:{type:"boolean",description:"Beacon lights on",group:"Lights"},light_nav:{type:"boolean",description:"Navigation lights on",group:"Lights"},light_strobe:{type:"boolean",description:"Strobe lights on",group:"Lights"},outside_air_temp:{type:"number",description:"Outside air temperature",unit:"°C",min:-80,max:60,group:"Environment"},barometric_pressure:{type:"number",description:"Barometric pressure setting",unit:"inHg",min:27,max:32,group:"Environment"},wind_direction:{type:"number",description:"Wind direction",unit:"degrees",min:0,max:360,group:"Environment"},wind_speed:{type:"number",description:"Wind speed",unit:"kts",min:0,max:200,group:"Environment"},stall_warning:{type:"boolean",description:"Stall warning active",group:"Warnings"},overspeed_warning:{type:"boolean",description:"Overspeed warning active",group:"Warnings"},sim_paused:{type:"boolean",description:"Simulation is paused",group:"Simulation"},gps_wp_distance:{type:"number",description:"Distance to next GPS waypoint",unit:"nm",min:0,max:1e4,group:"Navigation"},gps_wp_ete:{type:"number",description:"Estimated time enroute to next GPS waypoint",unit:"seconds",min:0,max:86400,group:"Navigation"}},commands:{autopilot_on:{description:"Engage autopilot master",group:"Autopilot"},autopilot_off:{description:"Disengage autopilot master",group:"Autopilot"},autopilot_toggle:{description:"Toggle autopilot master",group:"Autopilot"},autopilot_altitude_hold_on:{description:"Engage altitude hold",group:"Autopilot"},autopilot_altitude_hold_off:{description:"Disengage altitude hold",group:"Autopilot"},autopilot_heading_hold_on:{description:"Engage heading hold",group:"Autopilot"},autopilot_heading_hold_off:{description:"Disengage heading hold",group:"Autopilot"},autopilot_vs_hold_on:{description:"Engage vertical speed hold",group:"Autopilot"},autopilot_vs_hold_off:{description:"Disengage vertical speed hold",group:"Autopilot"},autopilot_nav_on:{description:"Engage NAV mode",group:"Autopilot"},autopilot_nav_off:{description:"Disengage NAV mode",group:"Autopilot"},autopilot_approach_on:{description:"Engage approach mode",group:"Autopilot"},autopilot_approach_off:{description:"Disengage approach mode",group:"Autopilot"},flight_director_on:{description:"Engage flight director",group:"Autopilot"},flight_director_off:{description:"Disengage flight director",group:"Autopilot"},autopilot_flc_on:{description:"Engage flight level change mode",group:"Autopilot"},autopilot_flc_off:{description:"Disengage flight level change mode",group:"Autopilot"},autopilot_flc_toggle:{description:"Toggle flight level change mode",group:"Autopilot"},set_autopilot_altitude:{description:"Set autopilot target altitude",group:"Autopilot",paramType:"number",paramDescription:"Target altitude in feet",paramMin:0,paramMax:6e4},set_autopilot_heading:{description:"Set autopilot target heading",group:"Autopilot",paramType:"number",paramDescription:"Target heading in degrees",paramMin:0,paramMax:360},set_autopilot_vs:{description:"Set autopilot target vertical speed",group:"Autopilot",paramType:"number",paramDescription:"Target vertical speed in ft/min",paramMin:-1e4,paramMax:1e4},set_autopilot_speed:{description:"Set autopilot target airspeed",group:"Autopilot",paramType:"number",paramDescription:"Target airspeed in knots",paramMin:0,paramMax:600},gear_up:{description:"Retract landing gear",group:"Controls"},gear_down:{description:"Extend landing gear",group:"Controls"},gear_toggle:{description:"Toggle landing gear",group:"Controls"},flaps_up:{description:"Retract flaps one notch",group:"Controls"},flaps_down:{description:"Extend flaps one notch",group:"Controls"},flaps_full:{description:"Extend flaps fully",group:"Controls"},flaps_retract:{description:"Fully retract flaps",group:"Controls"},set_flaps:{description:"Set flaps to specific position",group:"Controls",paramType:"number",paramDescription:"Flaps position (0-100%)",paramMin:0,paramMax:100},spoilers_arm:{description:"Arm spoilers",group:"Controls"},spoilers_deploy:{description:"Deploy spoilers",group:"Controls"},spoilers_retract:{description:"Retract spoilers",group:"Controls"},spoilers_toggle:{description:"Toggle spoilers",group:"Controls"},parking_brake_toggle:{description:"Toggle parking brake",group:"Controls"},parking_brake_on:{description:"Engage parking brake",group:"Controls"},parking_brake_off:{description:"Release parking brake",group:"Controls"},set_throttle:{description:"Set all throttles",group:"Engine",paramType:"number",paramDescription:"Throttle position (0-100%)",paramMin:0,paramMax:100},set_throttle_0:{description:"Set engine 0 throttle",group:"Engine",paramType:"number",paramDescription:"Throttle position (0-100%)",paramMin:0,paramMax:100},set_throttle_1:{description:"Set engine 1 throttle",group:"Engine",paramType:"number",paramDescription:"Throttle position (0-100%)",paramMin:0,paramMax:100},set_throttle_2:{description:"Set engine 2 throttle",group:"Engine",paramType:"number",paramDescription:"Throttle position (0-100%)",paramMin:0,paramMax:100},set_throttle_3:{description:"Set engine 3 throttle",group:"Engine",paramType:"number",paramDescription:"Throttle position (0-100%)",paramMin:0,paramMax:100},throttle_full:{description:"Set throttles to full",group:"Engine"},throttle_idle:{description:"Set throttles to idle",group:"Engine"},throttle_cutoff:{description:"Cut throttles completely",group:"Engine"},landing_lights_on:{description:"Turn on landing lights",group:"Lights"},landing_lights_off:{description:"Turn off landing lights",group:"Lights"},landing_lights_toggle:{description:"Toggle landing lights",group:"Lights"},taxi_lights_on:{description:"Turn on taxi lights",group:"Lights"},taxi_lights_off:{description:"Turn off taxi lights",group:"Lights"},taxi_lights_toggle:{description:"Toggle taxi lights",group:"Lights"},beacon_lights_on:{description:"Turn on beacon lights",group:"Lights"},beacon_lights_off:{description:"Turn off beacon lights",group:"Lights"},beacon_lights_toggle:{description:"Toggle beacon lights",group:"Lights"},nav_lights_on:{description:"Turn on navigation lights",group:"Lights"},nav_lights_off:{description:"Turn off navigation lights",group:"Lights"},nav_lights_toggle:{description:"Toggle navigation lights",group:"Lights"},strobe_lights_on:{description:"Turn on strobe lights",group:"Lights"},strobe_lights_off:{description:"Turn off strobe lights",group:"Lights"},strobe_lights_toggle:{description:"Toggle strobe lights",group:"Lights"},pause:{description:"Pause simulation",group:"Simulation"},unpause:{description:"Unpause simulation",group:"Simulation"},pause_toggle:{description:"Toggle simulation pause",group:"Simulation"}}},qn={flight_sim:Un,racing_sim:Un};function jn(t){return qn[t]}var Mn={gameId:"msfs",name:"Microsoft Flight Simulator",category:"flight_sim",fieldMappings:{latitude:{canonical:"latitude"},longitude:{canonical:"longitude"},indicated_altitude:{canonical:"altitude"},plane_altitude:{canonical:"altitude"},on_ground:{canonical:"on_ground",transform:"toBoolean"},altitude_agl:{canonical:"altitude_agl"},indicated_airspeed:{canonical:"indicated_airspeed"},true_airspeed:{canonical:"true_airspeed"},airspeed_mach:{canonical:"mach"},airspeed_indicated:{canonical:"indicated_airspeed"},ground_speed:{canonical:"ground_speed"},ground_velocity:{canonical:"ground_speed"},vertical_speed:{canonical:"vertical_speed"},gforce:{canonical:"g_force"},heading_gyro:{canonical:"heading"},heading_indicator:{canonical:"heading"},true_heading:{canonical:"true_heading"},attitude_indicator_pitch:{canonical:"pitch"},attitude_indicator_roll:{canonical:"roll"},yaw_rate:{canonical:"yaw"},eng_throttle_1:{canonical:"throttle_0",transform:"divideBy100"},eng_throttle_2:{canonical:"throttle_1",transform:"divideBy100"},eng_throttle_3:{canonical:"throttle_2",transform:"divideBy100"},eng_throttle_4:{canonical:"throttle_3",transform:"divideBy100"},eng_rpm_1:{canonical:"rpm_0"},eng_rpm_2:{canonical:"rpm_1"},eng_rpm_3:{canonical:"rpm_2"},eng_rpm_4:{canonical:"rpm_3"},turb_eng_n1_1:{canonical:"n1_0"},turb_eng_n1_2:{canonical:"n1_1"},turb_eng_n1_3:{canonical:"n1_2"},turb_eng_n1_4:{canonical:"n1_3"},turb_eng_n2_1:{canonical:"n2_0"},turb_eng_n2_2:{canonical:"n2_1"},turb_eng_n2_3:{canonical:"n2_2"},turb_eng_n2_4:{canonical:"n2_3"},turb_eng_itt_1:{canonical:"egt_0"},turb_eng_itt_2:{canonical:"egt_1"},turb_eng_itt_3:{canonical:"egt_2"},turb_eng_itt_4:{canonical:"egt_3"},fuel_quantity_pounds:{canonical:"fuel_quantity"},fuel_flow_pph_1:{canonical:"fuel_flow_0"},fuel_flow_pph_2:{canonical:"fuel_flow_1"},fuel_flow_pph_3:{canonical:"fuel_flow_2"},fuel_flow_pph_4:{canonical:"fuel_flow_3"},autopilot_master:{canonical:"autopilot_master",transform:"toBoolean"},autopilot_altitude_lock:{canonical:"autopilot_altitude_hold",transform:"toBoolean"},autopilot_heading_lock:{canonical:"autopilot_heading_hold",transform:"toBoolean"},autopilot_vertical_hold:{canonical:"autopilot_vs_hold",transform:"toBoolean"},autopilot_airspeed_hold:{canonical:"autopilot_speed_hold",transform:"toBoolean"},autopilot_approach_hold:{canonical:"autopilot_approach",transform:"toBoolean"},autopilot_nav1_lock:{canonical:"autopilot_nav",transform:"toBoolean"},autopilot_flight_director:{canonical:"flight_director",transform:"toBoolean"},autopilot_flc:{canonical:"autopilot_flc",transform:"toBoolean"},autopilot_altitude_set:{canonical:"autopilot_altitude_target"},autopilot_heading_set:{canonical:"autopilot_heading_target"},autopilot_vertical_speed_set:{canonical:"autopilot_vs_target"},autopilot_airspeed_set:{canonical:"autopilot_speed_target"},flaps_handle_percent:{canonical:"flaps"},spoilers_handle_percent:{canonical:"spoilers"},gear_handle_position:{canonical:"gear_down",transform:"toBoolean"},parking_brake:{canonical:"parking_brake",transform:"toBoolean"},brake_left_position:{canonical:"brake_left"},brake_right_position:{canonical:"brake_right"},light_landing:{canonical:"light_landing",transform:"toBoolean"},light_taxi:{canonical:"light_taxi",transform:"toBoolean"},light_beacon:{canonical:"light_beacon",transform:"toBoolean"},light_nav:{canonical:"light_nav",transform:"toBoolean"},light_strobe:{canonical:"light_strobe",transform:"toBoolean"},ambient_temperature:{canonical:"outside_air_temp"},kohlsman_setting_hg:{canonical:"barometric_pressure"},ambient_wind_direction:{canonical:"wind_direction"},ambient_wind_velocity:{canonical:"wind_speed"},stall_warning:{canonical:"stall_warning",transform:"toBoolean"},overspeed_warning:{canonical:"overspeed_warning",transform:"toBoolean"},sim_paused:{canonical:"sim_paused",transform:"toBoolean"},gps_wp_distance:{canonical:"gps_wp_distance"},gps_wp_ete:{canonical:"gps_wp_ete"}},commandMappings:{autopilot_on:{gameCommand:"AP_MASTER_ON",type:"command"},autopilot_off:{gameCommand:"AP_MASTER_OFF",type:"command"},autopilot_toggle:{gameCommand:"AP_MASTER",type:"command"},autopilot_altitude_hold_on:{gameCommand:"AP_ALT_HOLD_ON",type:"command"},autopilot_altitude_hold_off:{gameCommand:"AP_ALT_HOLD_OFF",type:"command"},autopilot_heading_hold_on:{gameCommand:"AP_HDG_HOLD_ON",type:"command"},autopilot_heading_hold_off:{gameCommand:"AP_HDG_HOLD_OFF",type:"command"},autopilot_vs_hold_on:{gameCommand:"AP_VS_HOLD_ON",type:"command"},autopilot_vs_hold_off:{gameCommand:"AP_VS_HOLD_OFF",type:"command"},autopilot_nav_on:{gameCommand:"AP_NAV1_HOLD_ON",type:"command"},autopilot_nav_off:{gameCommand:"AP_NAV1_HOLD_OFF",type:"command"},autopilot_approach_on:{gameCommand:"AP_APR_HOLD_ON",type:"command"},autopilot_approach_off:{gameCommand:"AP_APR_HOLD_OFF",type:"command"},flight_director_on:{gameCommand:"TOGGLE_FLIGHT_DIRECTOR",type:"command"},flight_director_off:{gameCommand:"TOGGLE_FLIGHT_DIRECTOR",type:"command"},autopilot_flc_on:{gameCommand:"FLIGHT_LEVEL_CHANGE_ON",type:"command"},autopilot_flc_off:{gameCommand:"FLIGHT_LEVEL_CHANGE_OFF",type:"command"},autopilot_flc_toggle:{gameCommand:"FLIGHT_LEVEL_CHANGE",type:"command"},set_autopilot_altitude:{gameCommand:"AP_ALT_VAR_SET_ENGLISH",type:"command"},set_autopilot_heading:{gameCommand:"HEADING_BUG_SET",type:"command"},set_autopilot_vs:{gameCommand:"AP_VS_VAR_SET_ENGLISH",type:"command"},set_autopilot_speed:{gameCommand:"AP_SPD_VAR_SET",type:"command"},gear_up:{gameCommand:"GEAR_UP",type:"command"},gear_down:{gameCommand:"GEAR_DOWN",type:"command"},gear_toggle:{gameCommand:"GEAR_TOGGLE",type:"command"},flaps_up:{gameCommand:"FLAPS_DECR",type:"command"},flaps_down:{gameCommand:"FLAPS_INCR",type:"command"},flaps_full:{gameCommand:"FLAPS_DOWN",type:"command"},flaps_retract:{gameCommand:"FLAPS_UP",type:"command"},set_flaps:{gameCommand:"FLAPS_SET",type:"command"},spoilers_arm:{gameCommand:"SPOILERS_ARM_TOGGLE",type:"command"},spoilers_deploy:{gameCommand:"SPOILERS_ON",type:"command"},spoilers_retract:{gameCommand:"SPOILERS_OFF",type:"command"},spoilers_toggle:{gameCommand:"SPOILERS_TOGGLE",type:"command"},parking_brake_toggle:{gameCommand:"PARKING_BRAKES",type:"command"},parking_brake_on:{gameCommand:"PARKING_BRAKE_SET",type:"command"},parking_brake_off:{gameCommand:"PARKING_BRAKE_SET",type:"command"},set_throttle:{gameCommand:"THROTTLE_SET",type:"command"},set_throttle_0:{gameCommand:"THROTTLE1_SET",type:"command"},set_throttle_1:{gameCommand:"THROTTLE2_SET",type:"command"},set_throttle_2:{gameCommand:"THROTTLE3_SET",type:"command"},set_throttle_3:{gameCommand:"THROTTLE4_SET",type:"command"},throttle_full:{gameCommand:"THROTTLE_FULL",type:"command"},throttle_idle:{gameCommand:"THROTTLE_CUT",type:"command"},throttle_cutoff:{gameCommand:"THROTTLE_CUT",type:"command"},landing_lights_on:{gameCommand:"LANDING_LIGHTS_ON",type:"command"},landing_lights_off:{gameCommand:"LANDING_LIGHTS_OFF",type:"command"},landing_lights_toggle:{gameCommand:"LANDING_LIGHTS_TOGGLE",type:"command"},taxi_lights_on:{gameCommand:"TAXI_LIGHTS_ON",type:"command"},taxi_lights_off:{gameCommand:"TAXI_LIGHTS_OFF",type:"command"},taxi_lights_toggle:{gameCommand:"TAXI_LIGHTS_TOGGLE",type:"command"},beacon_lights_on:{gameCommand:"BEACON_LIGHTS_ON",type:"command"},beacon_lights_off:{gameCommand:"BEACON_LIGHTS_OFF",type:"command"},beacon_lights_toggle:{gameCommand:"BEACON_LIGHTS_TOGGLE",type:"command"},nav_lights_on:{gameCommand:"NAV_LIGHTS_ON",type:"command"},nav_lights_off:{gameCommand:"NAV_LIGHTS_OFF",type:"command"},nav_lights_toggle:{gameCommand:"NAV_LIGHTS_TOGGLE",type:"command"},strobe_lights_on:{gameCommand:"STROBES_ON",type:"command"},strobe_lights_off:{gameCommand:"STROBES_OFF",type:"command"},strobe_lights_toggle:{gameCommand:"STROBES_TOGGLE",type:"command"},pause:{gameCommand:"PAUSE_ON",type:"command"},unpause:{gameCommand:"PAUSE_OFF",type:"command"},pause_toggle:{gameCommand:"PAUSE_TOGGLE",type:"command"}}};var Fn={gameId:"xplane",name:"X-Plane 12",category:"flight_sim",fieldMappings:{lat:{canonical:"latitude"},lon:{canonical:"longitude"},alt_msl:{canonical:"altitude"},alt_agl:{canonical:"altitude_agl"},on_ground:{canonical:"on_ground",transform:"toBoolean"},ias:{canonical:"indicated_airspeed"},tas:{canonical:"true_airspeed"},gs:{canonical:"ground_speed"},mach:{canonical:"mach"},vvi:{canonical:"vertical_speed"},g_load:{canonical:"g_force"},hdg_mag:{canonical:"heading"},hdg_true:{canonical:"true_heading"},pitch:{canonical:"pitch"},roll:{canonical:"roll"},yaw:{canonical:"yaw"},throttle_0:{canonical:"throttle_0"},throttle_1:{canonical:"throttle_1"},throttle_2:{canonical:"throttle_2"},throttle_3:{canonical:"throttle_3"},rpm_0:{canonical:"rpm_0"},rpm_1:{canonical:"rpm_1"},rpm_2:{canonical:"rpm_2"},rpm_3:{canonical:"rpm_3"},n1_0:{canonical:"n1_0"},n1_1:{canonical:"n1_1"},n1_2:{canonical:"n1_2"},n1_3:{canonical:"n1_3"},n2_0:{canonical:"n2_0"},n2_1:{canonical:"n2_1"},n2_2:{canonical:"n2_2"},n2_3:{canonical:"n2_3"},egt_0:{canonical:"egt_0"},egt_1:{canonical:"egt_1"},egt_2:{canonical:"egt_2"},egt_3:{canonical:"egt_3"},fuel_total_lbs:{canonical:"fuel_quantity"},ff_0:{canonical:"fuel_flow_0"},ff_1:{canonical:"fuel_flow_1"},ff_2:{canonical:"fuel_flow_2"},ff_3:{canonical:"fuel_flow_3"},ap_master:{canonical:"autopilot_master",transform:"toBoolean"},ap_alt_hold:{canonical:"autopilot_altitude_hold",transform:"toBoolean"},ap_hdg_hold:{canonical:"autopilot_heading_hold",transform:"toBoolean"},ap_vs_hold:{canonical:"autopilot_vs_hold",transform:"toBoolean"},ap_spd_hold:{canonical:"autopilot_speed_hold",transform:"toBoolean"},ap_apr:{canonical:"autopilot_approach",transform:"toBoolean"},ap_nav:{canonical:"autopilot_nav",transform:"toBoolean"},fd_on:{canonical:"flight_director",transform:"toBoolean"},ap_alt_set:{canonical:"autopilot_altitude_target"},ap_hdg_set:{canonical:"autopilot_heading_target"},ap_vs_set:{canonical:"autopilot_vs_target"},ap_spd_set:{canonical:"autopilot_speed_target"},flap_ratio:{canonical:"flaps"},spoiler_ratio:{canonical:"spoilers"},gear_deploy:{canonical:"gear_down",transform:"toBoolean"},park_brake:{canonical:"parking_brake",transform:"toBoolean"},brake_left:{canonical:"brake_left"},brake_right:{canonical:"brake_right"},land_lights:{canonical:"light_landing",transform:"toBoolean"},taxi_lights:{canonical:"light_taxi",transform:"toBoolean"},beacon:{canonical:"light_beacon",transform:"toBoolean"},nav_lights:{canonical:"light_nav",transform:"toBoolean"},strobe:{canonical:"light_strobe",transform:"toBoolean"},oat:{canonical:"outside_air_temp"},baro_set:{canonical:"barometric_pressure"},wind_dir:{canonical:"wind_direction"},wind_spd:{canonical:"wind_speed"},stall:{canonical:"stall_warning",transform:"toBoolean"},overspeed:{canonical:"overspeed_warning",transform:"toBoolean"},paused:{canonical:"sim_paused",transform:"toBoolean"},gps_wp_distance:{canonical:"gps_wp_distance"},gps_wp_ete:{canonical:"gps_wp_ete"}},commandMappings:{autopilot_on:{gameCommand:"sim/autopilot/servos_on",type:"command"},autopilot_off:{gameCommand:"sim/autopilot/servos_off_any",type:"command"},autopilot_toggle:{gameCommand:"sim/autopilot/servos_toggle",type:"command"},autopilot_altitude_hold_on:{gameCommand:"sim/autopilot/altitude_hold",type:"command"},autopilot_altitude_hold_off:{gameCommand:"sim/autopilot/altitude_hold",type:"command"},autopilot_heading_hold_on:{gameCommand:"sim/autopilot/heading",type:"command"},autopilot_heading_hold_off:{gameCommand:"sim/autopilot/heading",type:"command"},autopilot_vs_hold_on:{gameCommand:"sim/autopilot/vertical_speed",type:"command"},autopilot_vs_hold_off:{gameCommand:"sim/autopilot/vertical_speed",type:"command"},autopilot_nav_on:{gameCommand:"sim/autopilot/NAV",type:"command"},autopilot_nav_off:{gameCommand:"sim/autopilot/NAV",type:"command"},autopilot_approach_on:{gameCommand:"sim/autopilot/approach",type:"command"},autopilot_approach_off:{gameCommand:"sim/autopilot/approach",type:"command"},flight_director_on:{gameCommand:"sim/autopilot/fdir_on",type:"command"},flight_director_off:{gameCommand:"sim/autopilot/fdir_toggle",type:"command"},autopilot_flc_on:{gameCommand:"sim/autopilot/level_change",type:"command"},autopilot_flc_off:{gameCommand:"sim/autopilot/level_change",type:"command"},autopilot_flc_toggle:{gameCommand:"sim/autopilot/level_change",type:"command"},set_autopilot_altitude:{gameCommand:"sim/cockpit/autopilot/altitude",type:"dataref"},set_autopilot_heading:{gameCommand:"sim/cockpit/autopilot/heading_mag",type:"dataref"},set_autopilot_vs:{gameCommand:"sim/cockpit/autopilot/vertical_velocity",type:"dataref"},set_autopilot_speed:{gameCommand:"sim/cockpit/autopilot/airspeed",type:"dataref"},gear_up:{gameCommand:"sim/flight_controls/landing_gear_up",type:"command"},gear_down:{gameCommand:"sim/flight_controls/landing_gear_down",type:"command"},gear_toggle:{gameCommand:"sim/flight_controls/landing_gear_toggle",type:"command"},flaps_up:{gameCommand:"sim/flight_controls/flaps_up",type:"command"},flaps_down:{gameCommand:"sim/flight_controls/flaps_down",type:"command"},flaps_full:{gameCommand:"sim/flight_controls/flaps_down",type:"command"},flaps_retract:{gameCommand:"sim/flight_controls/flaps_up",type:"command"},set_flaps:{gameCommand:"sim/cockpit2/controls/flap_ratio",type:"dataref"},spoilers_arm:{gameCommand:"sim/flight_controls/speed_brakes_down_one",type:"command"},spoilers_deploy:{gameCommand:"sim/flight_controls/speed_brakes_down_all",type:"command"},spoilers_retract:{gameCommand:"sim/flight_controls/speed_brakes_up_all",type:"command"},spoilers_toggle:{gameCommand:"sim/flight_controls/speed_brakes_toggle",type:"command"},parking_brake_toggle:{gameCommand:"sim/flight_controls/brakes_toggle_max",type:"command"},parking_brake_on:{gameCommand:"sim/flight_controls/brakes_max",type:"command"},parking_brake_off:{gameCommand:"sim/flight_controls/brakes_regular",type:"command"},set_throttle:{gameCommand:"sim/cockpit2/engine/actuators/throttle_ratio_all",type:"dataref"},set_throttle_0:{gameCommand:"sim/cockpit2/engine/actuators/throttle_ratio[0]",type:"dataref"},set_throttle_1:{gameCommand:"sim/cockpit2/engine/actuators/throttle_ratio[1]",type:"dataref"},set_throttle_2:{gameCommand:"sim/cockpit2/engine/actuators/throttle_ratio[2]",type:"dataref"},set_throttle_3:{gameCommand:"sim/cockpit2/engine/actuators/throttle_ratio[3]",type:"dataref"},throttle_full:{gameCommand:"sim/engines/throttle_up",type:"command"},throttle_idle:{gameCommand:"sim/engines/throttle_down",type:"command"},throttle_cutoff:{gameCommand:"sim/starters/shut_down",type:"command"},landing_lights_on:{gameCommand:"sim/lights/landing_lights_on",type:"command"},landing_lights_off:{gameCommand:"sim/lights/landing_lights_off",type:"command"},landing_lights_toggle:{gameCommand:"sim/lights/landing_lights_toggle",type:"command"},taxi_lights_on:{gameCommand:"sim/lights/taxi_lights_on",type:"command"},taxi_lights_off:{gameCommand:"sim/lights/taxi_lights_off",type:"command"},taxi_lights_toggle:{gameCommand:"sim/lights/taxi_lights_toggle",type:"command"},beacon_lights_on:{gameCommand:"sim/lights/beacon_lights_on",type:"command"},beacon_lights_off:{gameCommand:"sim/lights/beacon_lights_off",type:"command"},beacon_lights_toggle:{gameCommand:"sim/lights/beacon_lights_toggle",type:"command"},nav_lights_on:{gameCommand:"sim/lights/nav_lights_on",type:"command"},nav_lights_off:{gameCommand:"sim/lights/nav_lights_off",type:"command"},nav_lights_toggle:{gameCommand:"sim/lights/nav_lights_toggle",type:"command"},strobe_lights_on:{gameCommand:"sim/lights/strobe_lights_on",type:"command"},strobe_lights_off:{gameCommand:"sim/lights/strobe_lights_off",type:"command"},strobe_lights_toggle:{gameCommand:"sim/lights/strobe_lights_toggle",type:"command"},pause:{gameCommand:"sim/operation/pause_on",type:"command"},unpause:{gameCommand:"sim/operation/pause_off",type:"command"},pause_toggle:{gameCommand:"sim/operation/pause_toggle",type:"command"}}};const Dn={msfs:{gameId:Mn.gameId,name:Mn.name,category:Mn.category,fieldMappings:Mn.fieldMappings,commandMappings:Mn.commandMappings,extraFields:{pitot_heat:{type:"boolean",description:"Pitot heat active",group:"Systems"},fuel_quantity_gallons:{type:"number",description:"Total fuel in gallons",unit:"gal",min:0,max:1e5,group:"Fuel"},fuel_flow_gph_1:{type:"number",description:"Engine 1 fuel flow in GPH",unit:"gal/hr",min:0,max:5e3,group:"Fuel"},fuel_flow_gph_2:{type:"number",description:"Engine 2 fuel flow in GPH",unit:"gal/hr",min:0,max:5e3,group:"Fuel"},fuel_flow_gph_3:{type:"number",description:"Engine 3 fuel flow in GPH",unit:"gal/hr",min:0,max:5e3,group:"Fuel"},fuel_flow_gph_4:{type:"number",description:"Engine 4 fuel flow in GPH",unit:"gal/hr",min:0,max:5e3,group:"Fuel"},flaps_left_percent:{type:"number",description:"Left flaps position",unit:"%",min:0,max:100,group:"Controls"},flaps_right_percent:{type:"number",description:"Right flaps position",unit:"%",min:0,max:100,group:"Controls"},spoilers_left_percent:{type:"number",description:"Left spoilers position",unit:"%",min:0,max:100,group:"Controls"},spoilers_right_percent:{type:"number",description:"Right spoilers position",unit:"%",min:0,max:100,group:"Controls"},gear_left_position:{type:"number",description:"Left gear position",unit:"%",min:0,max:100,group:"Controls"},gear_center_position:{type:"number",description:"Center gear position",unit:"%",min:0,max:100,group:"Controls"},gear_right_position:{type:"number",description:"Right gear position",unit:"%",min:0,max:100,group:"Controls"},ambient_pressure:{type:"number",description:"Ambient pressure",unit:"inHg",min:20,max:35,group:"Environment"},sea_level_pressure:{type:"number",description:"Sea level pressure",unit:"inHg",min:27,max:32,group:"Environment"},aircraft_wind_x:{type:"number",description:"Wind component X-axis",unit:"kts",min:-200,max:200,group:"Environment"},aircraft_wind_y:{type:"number",description:"Wind component Y-axis",unit:"kts",min:-200,max:200,group:"Environment"},aircraft_wind_z:{type:"number",description:"Wind component Z-axis",unit:"kts",min:-200,max:200,group:"Environment"}}},xplane:{gameId:Fn.gameId,name:Fn.name,category:Fn.category,fieldMappings:Fn.fieldMappings,commandMappings:Fn.commandMappings,extraFields:{replay_mode:{type:"boolean",description:"Replay mode active",group:"Simulation"},time_local:{type:"number",description:"Local time in seconds since midnight",unit:"sec",min:0,max:86400,group:"Simulation"},time_zulu:{type:"number",description:"Zulu time in seconds since midnight",unit:"sec",min:0,max:86400,group:"Simulation"}}}};function Hn(t){return Dn[t]}function Gn(t,e){const n={};for(const[i,o]of Object.entries(t)){const t=e.fieldMappings[i];if(t){let e=o;if(t.transform&&t.transform in Bn){e=(0,Bn[t.transform])(o)}n[t.canonical]=e}else e.extraFields?.[i]&&(n[`${e.gameId}:${i}`]=o)}return n}class Vn{constructor(t,e){this._config=e,this._socket=t,this._callbacks=[],this._fields=e.fields?[...e.fields]:null,this._gameSchema=Hn(e.gameId)}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,n)=>e?t({status:"failed",reason:"Listen request timed out."}):"success"===n.status?t({status:"success"}):t({status:"failed",reason:n.reason}))})}setupEventListener(){return this._socket.on("update",t=>{if(t?.gameId&&t.gameId!==this._config.gameId)return;const e=t?.data,n=e&&this._gameSchema?Gn(e,this._gameSchema):e;let i=n;if(this._fields&&this._fields.length>0&&n){i={};for(const t of this._fields)t in n&&(i[t]=n[t])}this.emit("update",{...t,raw:e,data:i})}),this._socket.on("key-events",t=>{const{gameId:e,eventType:n,data:i}=t||{};e===this._config.gameId&&n&&i&&this.emit(n,i)}),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("command must be a non-empty string");return new Promise(n=>{const i={userId:this._config.userId,gameId:this._config.gameId,data:{fieldName:t,value:e}};this._socket.timeout(5e3).emit("set",i,(t,e)=>n(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,n)=>t(e?{status:"failed",reason:"Update request timed out."}:n))})}}Nn(Vn.prototype);class zn{constructor(t,e){this._config=e,this._socket=t,this._gameSchema=Hn(e.gameId),this._broadcasters=[]}async establishConnection(){if(!this._socket||!this._config.clientId||!this._config.gameId)throw new Error("Missing arguments in establishConnection");return new Promise(t=>{const e={clientId:this._config.clientId,gameId:this._config.gameId};this._socket.timeout(5e3).emit("presenceSubscribe",e,(e,n)=>{if(e)return t({status:"failed",reason:"Presence request timed out."});if("success"===n?.status){const e=Array.isArray(n.broadcasters)?n.broadcasters.map(t=>this._normalizeSnapshot(t)):[];return this._broadcasters=e,t({status:"success",broadcasters:e})}return t({status:"failed",reason:n?.reason||"Presence subscription failed."})})})}setupEventListener(){return this._socket.on("presence-update",t=>{const e=this._normalizeSnapshot(t);this._upsertBroadcaster(e),this.emit("update",e)}),this._socket.on("presence-remove",({userId:t})=>{t&&(this._broadcasters=this._broadcasters.filter(e=>e.userId!==t),this.emit("remove",{userId:t}))}),this._socket.on("connect",()=>{this.emit("connect")}),this._socket.on("disconnect",t=>{this.emit("disconnect",t)}),this}getBroadcasters(){return[...this._broadcasters]}disconnect(){this._socket&&this._socket.disconnect()}_normalizeSnapshot(t){if(!t||"object"!=typeof t)return t;const e=t.data,n=e&&this._gameSchema?Gn(e,this._gameSchema):e;return{...t,data:n,raw:e}}_upsertBroadcaster(t){if(!t||!t.userId)return;const e=this._broadcasters.findIndex(e=>e.userId===t.userId);if(e>=0){const n=[...this._broadcasters];return n[e]=t,void(this._broadcasters=n)}this._broadcasters=[...this._broadcasters,t]}}Nn(zn.prototype);const $n={msfs:!0,xplane:!0};class Wn extends ht{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||!$n[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 Vn(this._socket,t),n=await e.establishConnection();if(this._socket.io.on("reconnect_attempt",()=>{this._updateSocketAuth(this.getAccessToken())}),this._socket.io.on("reconnect",()=>{e.establishConnection()}),"success"!==n.status)throw new Error(`There was a problem setting up the listener. Reason: ${n.reason}`);return e.setupEventListener()}async createPresenceListener(t){if(!t)throw new Error("Not a valid presence listener config");if(!t.gameId||!$n[t.gameId])throw new Error("Not a valid Game ID");if(!t.clientId)throw new Error("Client ID not supplied");const e=Ne(this._socketUrl,{transports:["websocket"]});await new Promise((t,n)=>{e.on("connect",t),e.on("connect_error",t=>{at(t)&&ct("WebSocket Connection",this._socketUrl),n(new Error(`Socket connection failed: ${t.message}`))})});const n=new zn(e,t),i=await n.establishConnection();if(e.io.on("reconnect",()=>{n.establishConnection()}),"success"!==i.status)throw new Error(`There was a problem setting up the presence listener. Reason: ${i.reason}`);return n.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 n=this.getAccessToken();n?(this._socket=Ne(this._socketUrl,{transports:["websocket"],auth:{token:n}}),this._socket.on("connect",()=>{t()}),this._socket.on("connect_error",t=>{at(t)&&ct("WebSocket Connection",this._socketUrl),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=Wn,window.GameGlueSchemas={getGameSchema:Hn,getCategorySchema:jn,normalizeTelemetry:Gn}),t.GameGlue=Wn,t.default=Wn,t.getCategorySchema=jn,t.getGameSchema=Hn,t.normalizeTelemetry=Gn,Object.defineProperty(t,"__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 n(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function i(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if("function"==typeof e){var n=function t(){var n=!1;try{n=this instanceof t}catch{}return n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(e){var i=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(n,e,i.get?i:{enumerable:!0,get:function(){return t[e]}})}),n}var o,r={exports:{}},s=i(Object.freeze({__proto__:null,default:{}}));function a(){return o||(o=1,function(t){t.exports=function(){var t=t||function(t,n){var i;if("undefined"!=typeof window&&window.crypto&&(i=window.crypto),"undefined"!=typeof self&&self.crypto&&(i=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(i=globalThis.crypto),!i&&"undefined"!=typeof window&&window.msCrypto&&(i=window.msCrypto),!i&&void 0!==e&&e.crypto&&(i=e.crypto),!i)try{i=s}catch(t){}var o=function(){if(i){if("function"==typeof i.getRandomValues)try{return i.getRandomValues(new Uint32Array(1))[0]}catch(t){}if("function"==typeof i.randomBytes)try{return i.randomBytes(4).readInt32LE()}catch(t){}}throw new Error("Native crypto module could not be used to get secure random number.")},r=Object.create||function(){function t(){}return function(e){var n;return t.prototype=e,n=new t,t.prototype=null,n}}(),a={},c=a.lib={},l=c.Base={extend:function(t){var e=r(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)}},h=c.WordArray=l.extend({init:function(t,e){t=this.words=t||[],this.sigBytes=e!=n?e:4*t.length},toString:function(t){return(t||u).stringify(this)},concat:function(t){var e=this.words,n=t.words,i=this.sigBytes,o=t.sigBytes;if(this.clamp(),i%4)for(var r=0;r<o;r++){var s=n[r>>>2]>>>24-r%4*8&255;e[i+r>>>2]|=s<<24-(i+r)%4*8}else for(var a=0;a<o;a+=4)e[i+a>>>2]=n[a>>>2];return this.sigBytes+=o,this},clamp:function(){var e=this.words,n=this.sigBytes;e[n>>>2]&=4294967295<<32-n%4*8,e.length=t.ceil(n/4)},clone:function(){var t=l.clone.call(this);return t.words=this.words.slice(0),t},random:function(t){for(var e=[],n=0;n<t;n+=4)e.push(o());return new h.init(e,t)}}),p=a.enc={},u=p.Hex={stringify:function(t){for(var e=t.words,n=t.sigBytes,i=[],o=0;o<n;o++){var r=e[o>>>2]>>>24-o%4*8&255;i.push((r>>>4).toString(16)),i.push((15&r).toString(16))}return i.join("")},parse:function(t){for(var e=t.length,n=[],i=0;i<e;i+=2)n[i>>>3]|=parseInt(t.substr(i,2),16)<<24-i%8*4;return new h.init(n,e/2)}},d=p.Latin1={stringify:function(t){for(var e=t.words,n=t.sigBytes,i=[],o=0;o<n;o++){var r=e[o>>>2]>>>24-o%4*8&255;i.push(String.fromCharCode(r))}return i.join("")},parse:function(t){for(var e=t.length,n=[],i=0;i<e;i++)n[i>>>2]|=(255&t.charCodeAt(i))<<24-i%4*8;return new h.init(n,e)}},g=p.Utf8={stringify:function(t){try{return decodeURIComponent(escape(d.stringify(t)))}catch(t){throw new Error("Malformed UTF-8 data")}},parse:function(t){return d.parse(unescape(encodeURIComponent(t)))}},_=c.BufferedBlockAlgorithm=l.extend({reset:function(){this._data=new h.init,this._nDataBytes=0},_append:function(t){"string"==typeof t&&(t=g.parse(t)),this._data.concat(t),this._nDataBytes+=t.sigBytes},_process:function(e){var n,i=this._data,o=i.words,r=i.sigBytes,s=this.blockSize,a=r/(4*s),c=(a=e?t.ceil(a):t.max((0|a)-this._minBufferSize,0))*s,l=t.min(4*c,r);if(c){for(var p=0;p<c;p+=s)this._doProcessBlock(o,p);n=o.splice(0,c),i.sigBytes-=l}return new h.init(n,l)},clone:function(){var t=l.clone.call(this);return t._data=this._data.clone(),t},_minBufferSize:0});c.Hasher=_.extend({cfg:l.extend(),init:function(t){this.cfg=this.cfg.extend(t),this.reset()},reset:function(){_.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,n){return new t.init(n).finalize(e)}},_createHmacHelper:function(t){return function(e,n){return new m.HMAC.init(t,n).finalize(e)}}});var m=a.algo={};return a}(Math);return t}()}(r)),r.exports}var c,l=n(a()),h={exports:{}};var p,u=(c||(c=1,function(t){t.exports=function(t){return function(e){var n=t,i=n.lib,o=i.WordArray,r=i.Hasher,s=n.algo,a=[],c=[];!function(){function t(t){for(var n=e.sqrt(t),i=2;i<=n;i++)if(!(t%i))return!1;return!0}function n(t){return 4294967296*(t-(0|t))|0}for(var i=2,o=0;o<64;)t(i)&&(o<8&&(a[o]=n(e.pow(i,.5))),c[o]=n(e.pow(i,1/3)),o++),i++}();var l=[],h=s.SHA256=r.extend({_doReset:function(){this._hash=new o.init(a.slice(0))},_doProcessBlock:function(t,e){for(var n=this._hash.words,i=n[0],o=n[1],r=n[2],s=n[3],a=n[4],h=n[5],p=n[6],u=n[7],d=0;d<64;d++){if(d<16)l[d]=0|t[e+d];else{var g=l[d-15],_=(g<<25|g>>>7)^(g<<14|g>>>18)^g>>>3,m=l[d-2],f=(m<<15|m>>>17)^(m<<13|m>>>19)^m>>>10;l[d]=_+l[d-7]+f+l[d-16]}var y=i&o^i&r^o&r,w=(i<<30|i>>>2)^(i<<19|i>>>13)^(i<<10|i>>>22),b=u+((a<<26|a>>>6)^(a<<21|a>>>11)^(a<<7|a>>>25))+(a&h^~a&p)+c[d]+l[d];u=p,p=h,h=a,a=s+b|0,s=r,r=o,o=i,i=b+(w+y)|0}n[0]=n[0]+i|0,n[1]=n[1]+o|0,n[2]=n[2]+r|0,n[3]=n[3]+s|0,n[4]=n[4]+a|0,n[5]=n[5]+h|0,n[6]=n[6]+p|0,n[7]=n[7]+u|0},_doFinalize:function(){var t=this._data,n=t.words,i=8*this._nDataBytes,o=8*t.sigBytes;return n[o>>>5]|=128<<24-o%32,n[14+(o+64>>>9<<4)]=e.floor(i/4294967296),n[15+(o+64>>>9<<4)]=i,t.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var t=r.clone.call(this);return t._hash=this._hash.clone(),t}});n.SHA256=r._createHelper(h),n.HmacSHA256=r._createHmacHelper(h)}(Math),t.SHA256}(a())}(h)),h.exports),d=n(u),g={exports:{}};var _,m=(p||(p=1,function(t){t.exports=function(t){return function(){var e=t,n=e.lib.WordArray;function i(t,e,i){for(var o=[],r=0,s=0;s<e;s++)if(s%4){var a=i[t.charCodeAt(s-1)]<<s%4*2|i[t.charCodeAt(s)]>>>6-s%4*2;o[r>>>2]|=a<<24-r%4*8,r++}return n.create(o,r)}e.enc.Base64={stringify:function(t){var e=t.words,n=t.sigBytes,i=this._map;t.clamp();for(var o=[],r=0;r<n;r+=3)for(var s=(e[r>>>2]>>>24-r%4*8&255)<<16|(e[r+1>>>2]>>>24-(r+1)%4*8&255)<<8|e[r+2>>>2]>>>24-(r+2)%4*8&255,a=0;a<4&&r+.75*a<n;a++)o.push(i.charAt(s>>>6*(3-a)&63));var c=i.charAt(64);if(c)for(;o.length%4;)o.push(c);return o.join("")},parse:function(t){var e=t.length,n=this._map,o=this._reverseMap;if(!o){o=this._reverseMap=[];for(var r=0;r<n.length;r++)o[n.charCodeAt(r)]=r}var s=n.charAt(64);if(s){var a=t.indexOf(s);-1!==a&&(e=a)}return i(t,e,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),t.enc.Base64}(a())}(g)),g.exports),f=n(m),y={exports:{}};var w=(_||(_=1,function(t){t.exports=function(t){return t.enc.Utf8}(a())}(y)),y.exports),b=n(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 n,i,o=0,r=0,s="";i=e.charAt(r++);~i&&(n=o%4?64*n+i:i,o++%4)?s+=String.fromCharCode(255&n>>(-2*o&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return s};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 n=e.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n}))}(e)}catch(t){return k(e)}}function C(t){this.message=t}function E(t,e){if("string"!=typeof t)throw new C("Invalid token specified");var n=!0===(e=e||{}).header?0:1;try{return JSON.parse(S(t.split(".")[n]))}catch(t){throw new C("Invalid token specified: "+t.message)}}C.prototype=new Error,C.prototype.name="InvalidTokenError";var T,A,x,R={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},O=(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))(O||{});(x=O||(O={})).reset=function(){T=3,A=R},x.setLevel=function(t){if(!(0<=t&&t<=4))throw new Error("Invalid log level");T=t},x.setLogger=function(t){A=t};var P=class{constructor(t){this._name=t}debug(...t){T>=4&&A.debug(P._format(this._name,this._method),...t)}info(...t){T>=3&&A.info(P._format(this._name,this._method),...t)}warn(...t){T>=2&&A.warn(P._format(this._name,this._method),...t)}error(...t){T>=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 n=new P(`${t}.${e}`);return n.debug("begin"),n}static _format(t,e){const n=`[${t}]`;return e?`${n} ${e}:`:n}static debug(t,...e){T>=4&&A.debug(P._format(t),...e)}static info(t,...e){T>=3&&A.info(P._format(t),...e)}static warn(t,...e){T>=2&&A.warn(P._format(t),...e)}static error(t,...e){T>=1&&A.error(P._format(t),...e)}};O.reset();var I=class{static _randomWord(){return l.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=d(t);return f.stringify(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw P.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(t,e){const n=b.parse([t,e].join(":"));return f.stringify(n)}},L=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)}},N=class{static decode(t){try{return E(t)}catch(t){throw P.error("JwtUtils.decode",t),t}}},B=class extends L{constructor(){super(...arguments),this._logger=new P(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const t=this._expiration-B.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=B.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 n=B.getEpochTime()+t;if(this.expiration===n&&this._timerHandle)return void e.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),e.debug("using duration",t),this._expiration=n;const i=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*i)}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 n=new URL(t,window.location.origin)["fragment"===e?"hash":"search"];return new URLSearchParams(n.slice(1))}},q=class extends Error{constructor(t,e){var n,i,o;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!=(n=t.error_description)?n:null,this.error_uri=null!=(i=t.error_uri)?i:null,this.state=t.userState,this.session_state=null!=(o=t.session_state)?o:null}},j=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]}},F=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:n,...i}=e;if(!n)return await fetch(t,i);const o=new AbortController,r=setTimeout(()=>o.abort(),1e3*n);try{return await fetch(t,{...e,signal:o.signal})}catch(t){if(t instanceof DOMException&&"AbortError"===t.name)throw new j("Network timed out");throw t}finally{clearTimeout(r)}}async getJson(t,{token:e,credentials:n}={}){const i=this._logger.create("getJson"),o={Accept:this._contentTypes.join(", ")};let r;e&&(i.debug("token passed, setting Authorization header"),o.Authorization="Bearer "+e);try{i.debug("url:",t),r=await this.fetchWithTimeout(t,{method:"GET",headers:o,credentials:n})}catch(t){throw i.error("Network Error"),t}i.debug("HTTP response received, status",r.status);const s=r.headers.get("Content-Type");if(s&&!this._contentTypes.find(t=>s.startsWith(t))&&i.throw(new Error(`Invalid response Content-Type: ${null!=s?s:"undefined"}, from URL: ${t}`)),r.ok&&this._jwtHandler&&(null==s?void 0:s.startsWith("application/jwt")))return await this._jwtHandler(await r.text());let a;try{a=await r.json()}catch(t){if(i.error("Error parsing JSON response",t),r.ok)throw t;throw new Error(`${r.statusText} (${r.status})`)}if(!r.ok){if(i.error("Error from server:",a),a.error)throw new q(a);throw new Error(`${r.statusText} (${r.status}): ${JSON.stringify(a)}`)}return a}async postForm(t,{body:e,basicAuth:n,timeoutInSeconds:i,initCredentials:o}){const r=this._logger.create("postForm"),s={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded"};let a;void 0!==n&&(s.Authorization="Basic "+n);try{r.debug("url:",t),a=await this.fetchWithTimeout(t,{method:"POST",headers:s,body:e,timeoutInSeconds:i,credentials:o})}catch(t){throw r.error("Network error"),t}r.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 l=await a.text();let h={};if(l)try{h=JSON.parse(l)}catch(t){if(r.error("Error parsing JSON response",t),a.ok)throw t;throw new Error(`${a.statusText} (${a.status})`)}if(!a.ok){if(r.error("Error from server:",h),h.error)throw new q(h,e);throw new Error(`${a.statusText} (${a.status}): ${JSON.stringify(h)}`)}return h}},D=class{constructor(t){this._settings=t,this._logger=new P("MetadataService"),this._jsonService=new F(["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 n=this._logger.create(`_getMetadataProperty('${t}')`),i=await this.getMetadata();if(n.debug("resolved"),void 0===i[t]){if(!0===e)return void n.warn("Metadata does not contain optional property");n.throw(new Error("Metadata does not contain property "+t))}return i[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 n=await this._jsonService.getJson(e);if(t.debug("got key set",n),!Array.isArray(n.keys))throw t.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=n.keys,this._signingKeys}},H=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 n=0;n<t;n++){const t=await this._store.key(n);t&&0===t.indexOf(this._prefix)&&e.push(t.substr(this._prefix.length))}return e}},G=class{constructor({authority:t,metadataUrl:e,metadata:n,signingKeys:i,metadataSeed:o,client_id:r,client_secret:s,response_type:a="code",scope:c="openid",redirect_uri:l,post_logout_redirect_uri:h,client_authentication:p="client_secret_post",prompt:u,display:d,max_age:g,ui_locales:_,acr_values:m,resource:f,response_mode:y="query",filterProtocolClaims:w=!0,loadUserInfo:b=!1,staleStateAgeInSeconds:v=900,clockSkewInSeconds:k=300,userInfoJwtIssuer:S="OP",mergeClaims:C=!1,stateStore:E,refreshTokenCredentials:T,revokeTokenAdditionalContentTypes:A,fetchRequestCredentials:x,refreshTokenAllowedScope:R,extraQueryParams:O={},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=n,this.metadataSeed=o,this.signingKeys=i,this.client_id=r,this.client_secret=s,this.response_type=a,this.scope=c,this.redirect_uri=l,this.post_logout_redirect_uri=h,this.client_authentication=p,this.prompt=u,this.display=d,this.max_age=g,this.ui_locales=_,this.acr_values=m,this.resource=f,this.response_mode=y,this.filterProtocolClaims=null==w||w,this.loadUserInfo=!!b,this.staleStateAgeInSeconds=v,this.clockSkewInSeconds=k,this.userInfoJwtIssuer=S,this.mergeClaims=!!C,this.revokeTokenAdditionalContentTypes=A,x&&T&&console.warn("Both fetchRequestCredentials and refreshTokenCredentials is set. Only fetchRequestCredentials will be used."),this.fetchRequestCredentials=x||(T||"same-origin"),E)this.stateStore=E;else{const t="undefined"!=typeof window?window.localStorage:new M;this.stateStore=new H({store:t})}this.refreshTokenAllowedScope=R,this.extraQueryParams=O,this.extraTokenParams=P}},V=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 n=N.decode(t);return e.debug("JWT decoding successful"),n}catch(t){throw e.error("Error parsing JWT response"),t}},this._jsonService=new F(void 0,this._getClaimsFromJwt)}async getClaims(t){const e=this._logger.create("getClaims");t||this._logger.throw(new Error("No token passed"));const n=await this._metadataService.getUserInfoEndpoint();e.debug("got userinfo url",n);const i=await this._jsonService.getJson(n,{token:t,credentials:this._settings.fetchRequestCredentials});return e.debug("got claims",i),i}},z=class{constructor(t,e){this._settings=t,this._metadataService=e,this._logger=new P("TokenClient"),this._jsonService=new F(this._settings.revokeTokenAdditionalContentTypes)}async exchangeCode({grant_type:t="authorization_code",redirect_uri:e=this._settings.redirect_uri,client_id:n=this._settings.client_id,client_secret:i=this._settings.client_secret,...o}){const r=this._logger.create("exchangeCode");n||r.throw(new Error("A client_id is required")),e||r.throw(new Error("A redirect_uri is required")),o.code||r.throw(new Error("A code is required")),o.code_verifier||r.throw(new Error("A code_verifier is required"));const s=new URLSearchParams({grant_type:t,redirect_uri:e});for(const[t,e]of Object.entries(o))null!=e&&s.set(t,e);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!i)throw r.throw(new Error("A client_secret is required")),null;a=I.generateBasicAuth(n,i);break;case"client_secret_post":s.append("client_id",n),i&&s.append("client_secret",i)}const c=await this._metadataService.getTokenEndpoint(!1);r.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:s,basicAuth:a,initCredentials:this._settings.fetchRequestCredentials});return r.debug("got response"),l}async exchangeCredentials({grant_type:t="password",client_id:e=this._settings.client_id,client_secret:n=this._settings.client_secret,scope:i=this._settings.scope,...o}){const r=this._logger.create("exchangeCredentials");e||r.throw(new Error("A client_id is required"));const s=new URLSearchParams({grant_type:t,scope:i});for(const[t,e]of Object.entries(o))null!=e&&s.set(t,e);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!n)throw r.throw(new Error("A client_secret is required")),null;a=I.generateBasicAuth(e,n);break;case"client_secret_post":s.append("client_id",e),n&&s.append("client_secret",n)}const c=await this._metadataService.getTokenEndpoint(!1);r.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:s,basicAuth:a,initCredentials:this._settings.fetchRequestCredentials});return r.debug("got response"),l}async exchangeRefreshToken({grant_type:t="refresh_token",client_id:e=this._settings.client_id,client_secret:n=this._settings.client_secret,timeoutInSeconds:i,...o}){const r=this._logger.create("exchangeRefreshToken");e||r.throw(new Error("A client_id is required")),o.refresh_token||r.throw(new Error("A refresh_token is required"));const s=new URLSearchParams({grant_type:t});for(const[t,e]of Object.entries(o))null!=e&&s.set(t,e);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!n)throw r.throw(new Error("A client_secret is required")),null;a=I.generateBasicAuth(e,n);break;case"client_secret_post":s.append("client_id",e),n&&s.append("client_secret",n)}const c=await this._metadataService.getTokenEndpoint(!1);r.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:s,basicAuth:a,timeoutInSeconds:i,initCredentials:this._settings.fetchRequestCredentials});return r.debug("got response"),l}async revoke(t){var e;const n=this._logger.create("revoke");t.token||n.throw(new Error("A token is required"));const i=await this._metadataService.getRevocationEndpoint(!1);n.debug(`got revocation endpoint, revoking ${null!=(e=t.token_type_hint)?e:"default token type"}`);const o=new URLSearchParams;for(const[e,n]of Object.entries(t))null!=n&&o.set(e,n);o.set("client_id",this._settings.client_id),this._settings.client_secret&&o.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(i,{body:o}),n.debug("got response")}},$=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],W=["sub","iss","aud","exp","iat"],K=class{constructor(t,e){this._settings=t,this._metadataService=e,this._logger=new P("ResponseValidator"),this._userInfoService=new V(this._settings,this._metadataService),this._tokenClient=new z(this._settings,this._metadataService)}async validateSigninResponse(t,e){const n=this._logger.create("validateSigninResponse");this._processSigninState(t,e),n.debug("state processed"),await this._processCode(t,e),n.debug("code processed"),t.isOpenId&&this._validateIdTokenAttributes(t),n.debug("tokens validated"),await this._processClaims(t,null==e?void 0:e.skipUserInfo,t.isOpenId),n.debug("claims processed")}async validateCredentialsResponse(t,e){const n=this._logger.create("validateCredentialsResponse");t.isOpenId&&this._validateIdTokenAttributes(t),n.debug("tokens validated"),await this._processClaims(t,e,t.isOpenId),n.debug("claims processed")}async validateRefreshResponse(t,e){const n=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),n.debug("ID Token validated")),t.id_token||(t.id_token=e.id_token,t.profile=e.profile);const i=t.isOpenId&&!!t.id_token;await this._processClaims(t,!1,i),n.debug("claims processed")}validateSignoutResponse(t,e){const n=this._logger.create("validateSignoutResponse");if(e.id!==t.state&&n.throw(new Error("State does not match")),n.debug("state validated"),t.userState=e.data,t.error)throw n.warn("Response was error",t.error),new q(t)}_processSigninState(t,e){const n=this._logger.create("_processSigninState");if(e.id!==t.state&&n.throw(new Error("State does not match")),e.client_id||n.throw(new Error("No client_id on state")),e.authority||n.throw(new Error("No authority on state")),this._settings.authority!==e.authority&&n.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==e.client_id&&n.throw(new Error("client_id mismatch on settings vs. signin state")),n.debug("state validated"),t.userState=e.data,null!=t.scope||(t.scope=e.scope),t.error)throw n.warn("Response was error",t.error),new q(t);e.code_verifier&&!t.code&&n.throw(new Error("Expected code in response")),!e.code_verifier&&t.code&&n.throw(new Error("Unexpected code in response"))}async _processClaims(t,e=!1,n=!0){const i=this._logger.create("_processClaims");if(t.profile=this._filterProtocolClaims(t.profile),e||!this._settings.loadUserInfo||!t.access_token)return void i.debug("not loading user info");i.debug("loading user info");const o=await this._userInfoService.getClaims(t.access_token);i.debug("user info claims received from user info endpoint"),n&&o.sub!==t.profile.sub&&i.throw(new Error("subject from UserInfo response does not match subject in ID Token")),t.profile=this._mergeClaims(t.profile,this._filterProtocolClaims(o)),i.debug("user info claims received, updated profile:",t.profile)}_mergeClaims(t,e){const n={...t};for(const[t,i]of Object.entries(e))for(const e of Array.isArray(i)?i:[i]){const i=n[t];i?Array.isArray(i)?i.includes(e)||i.push(e):n[t]!==e&&("object"==typeof e&&this._settings.mergeClaims?n[t]=this._mergeClaims(i,e):n[t]=[i,e]):n[t]=e}return n}_filterProtocolClaims(t){const e={...t};if(this._settings.filterProtocolClaims){let t;t=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:$;for(const n of t)W.includes(n)||delete e[n]}return e}async _processCode(t,e){const n=this._logger.create("_processCode");if(t.code){n.debug("Validating code");const i=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,i)}else n.debug("No code to process")}_validateIdTokenAttributes(t,e){var n;const i=this._logger.create("_validateIdTokenAttributes");i.debug("decoding ID Token JWT");const o=N.decode(null!=(n=t.id_token)?n:"");if(o.sub||i.throw(new Error("ID Token is missing a subject claim")),e){const t=N.decode(e);t.sub!==o.sub&&i.throw(new Error("sub in id_token does not match current sub")),t.auth_time&&t.auth_time!==o.auth_time&&i.throw(new Error("auth_time in id_token does not match original auth_time")),t.azp&&t.azp!==o.azp&&i.throw(new Error("azp in id_token does not match original azp")),!t.azp&&o.azp&&i.throw(new Error("azp not in id_token, but present in original id_token"))}t.profile=o}},J=class{constructor(t){this.id=t.id||I.generateUUIDv4(),this.data=t.data,t.created&&t.created>0?this.created=t.created:this.created=B.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 J(JSON.parse(t))}static async clearStaleState(t,e){const n=P.createStatic("State","clearStaleState"),i=B.getEpochTime()-e,o=await t.getAllKeys();n.debug("got keys",o);for(let e=0;e<o.length;e++){const r=o[e],s=await t.get(r);let a=!1;if(s)try{const t=J.fromStorageString(s);n.debug("got item from key:",r,t.created),t.created<=i&&(a=!0)}catch(t){n.error("Error parsing state for key:",r,t),a=!0}else n.debug("no item in storage for key:",r),a=!0;a&&(n.debug("removed item for key:",r),t.remove(r))}}},Q=class extends J{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 Q(e)}},Y=class{constructor({url:t,authority:e,client_id:n,redirect_uri:i,response_type:o,scope:r,state_data:s,response_mode:a,request_type:c,client_secret:l,nonce:h,resource:p,skipUserInfo:u,extraQueryParams:d,extraTokenParams:g,..._}){if(this._logger=new P("SigninRequest"),!t)throw this._logger.error("ctor: No url passed"),new Error("url");if(!n)throw this._logger.error("ctor: No client_id passed"),new Error("client_id");if(!i)throw this._logger.error("ctor: No redirect_uri passed"),new Error("redirect_uri");if(!o)throw this._logger.error("ctor: No response_type passed"),new Error("response_type");if(!r)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 Q({data:s,request_type:c,code_verifier:!0,client_id:n,authority:e,redirect_uri:i,response_mode:a,client_secret:l,scope:r,extraTokenParams:g,skipUserInfo:u});const m=new URL(t);if(m.searchParams.append("client_id",n),m.searchParams.append("redirect_uri",i),m.searchParams.append("response_type",o),m.searchParams.append("scope",r),h&&m.searchParams.append("nonce",h),m.searchParams.append("state",this.state.id),this.state.code_challenge&&(m.searchParams.append("code_challenge",this.state.code_challenge),m.searchParams.append("code_challenge_method","S256")),p){(Array.isArray(p)?p:[p]).forEach(t=>m.searchParams.append("resource",t))}for(const[t,e]of Object.entries({response_mode:a,..._,...d}))null!=e&&m.searchParams.append(t,e.toString());this.url=m.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-B.getEpochTime()}set expires_in(t){"string"==typeof t&&(t=Number(t)),void 0!==t&&t>=0&&(this.expires_at=Math.floor(t)+B.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:n,post_logout_redirect_uri:i,extraQueryParams:o,request_type:r}){if(this._logger=new P("SignoutRequest"),!t)throw this._logger.error("ctor: No url passed"),new Error("url");const s=new URL(t);n&&s.searchParams.append("id_token_hint",n),i&&(s.searchParams.append("post_logout_redirect_uri",i),e&&(this.state=new J({data:e,request_type:r}),s.searchParams.append("state",this.state.id)));for(const[t,e]of Object.entries({...o}))null!=e&&s.searchParams.append(t,e.toString());this.url=s.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 G(t),this.metadataService=new D(this.settings),this._validator=new K(this.settings,this.metadataService),this._tokenClient=new z(this.settings,this.metadataService)}async createSigninRequest({state:t,request:e,request_uri:n,request_type:i,id_token_hint:o,login_hint:r,skipUserInfo:s,nonce:a,response_type:c=this.settings.response_type,scope:l=this.settings.scope,redirect_uri:h=this.settings.redirect_uri,prompt:p=this.settings.prompt,display:u=this.settings.display,max_age:d=this.settings.max_age,ui_locales:g=this.settings.ui_locales,acr_values:_=this.settings.acr_values,resource:m=this.settings.resource,response_mode:f=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 Y({url:v,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:h,response_type:c,scope:l,state_data:t,prompt:p,display:u,max_age:d,ui_locales:g,id_token_hint:o,login_hint:r,acr_values:_,resource:m,request:e,request_uri:n,extraQueryParams:y,extraTokenParams:w,request_type:i,response_mode:f,client_secret:this.settings.client_secret,skipUserInfo:s,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 n=this._logger.create("readSigninResponseState"),i=new X(U.readParams(t,this.settings.response_mode));if(!i.state)throw n.throw(new Error("No state in response")),null;const o=await this.settings.stateStore[e?"remove":"get"](i.state);if(!o)throw n.throw(new Error("No matching state found in storage")),null;return{state:Q.fromStorageString(o),response:i}}async processSigninResponse(t){const e=this._logger.create("processSigninResponse"),{state:n,response:i}=await this.readSigninResponseState(t,!0);return e.debug("received state from storage; validating response"),await this._validator.validateSigninResponse(i,n),i}async processResourceOwnerPasswordCredentials({username:t,password:e,skipUserInfo:n=!1,extraTokenParams:i={}}){const o=await this._tokenClient.exchangeCredentials({username:t,password:e,...i}),r=new X(new URLSearchParams);return Object.assign(r,o),await this._validator.validateCredentialsResponse(r,n),r}async useRefreshToken({state:t,timeoutInSeconds:e}){var n;const i=this._logger.create("useRefreshToken");let o;if(void 0===this.settings.refreshTokenAllowedScope)o=t.scope;else{const e=this.settings.refreshTokenAllowedScope.split(" ");o=((null==(n=t.scope)?void 0:n.split(" "))||[]).filter(t=>e.includes(t)).join(" ")}const r=await this._tokenClient.exchangeRefreshToken({refresh_token:t.refresh_token,scope:o,timeoutInSeconds:e}),s=new X(new URLSearchParams);return Object.assign(s,r),i.debug("validating response",s),await this._validator.validateRefreshResponse(s,{...t,scope:o}),s}async createSignoutRequest({state:t,id_token_hint:e,request_type:n,post_logout_redirect_uri:i=this.settings.post_logout_redirect_uri,extraQueryParams:o=this.settings.extraQueryParams}={}){const r=this._logger.create("createSignoutRequest"),s=await this.metadataService.getEndSessionEndpoint();if(!s)throw r.throw(new Error("No end session endpoint")),null;r.debug("Received end session endpoint",s);const a=new Z({url:s,id_token_hint:e,post_logout_redirect_uri:i,state_data:t,extraQueryParams:o,request_type:n});await this.clearStaleState();const c=a.state;return c&&(r.debug("Signout request has state to persist"),await this.settings.stateStore.set(c.id,c.toStorageString())),a}async readSignoutResponseState(t,e=!1){const n=this._logger.create("readSignoutResponseState"),i=new tt(U.readParams(t,this.settings.response_mode));if(!i.state){if(n.debug("No state in response"),i.error)throw n.warn("Response was error:",i.error),new q(i);return{state:void 0,response:i}}const o=await this.settings.stateStore[e?"remove":"get"](i.state);if(!o)throw n.throw(new Error("No matching state found in storage")),null;return{state:J.fromStorageString(o),response:i}}async processSignoutResponse(t){const e=this._logger.create("processSignoutResponse"),{state:n,response:i}=await this.readSignoutResponseState(t,!0);return n?(e.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(i,n)):e.debug("No state from storage; skipping response validation"),i}clearStaleState(){return this._logger.create("clearStaleState"),J.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 nt={},it=(t,e)=>st()?localStorage.setItem(t,e):nt[t]=e,ot=t=>st()?localStorage.getItem(t):nt[t],rt=t=>st()?localStorage.removeItem(t):delete nt[t],st=()=>!("object"==typeof process&&"[object process]"===String(process));function at(t){if(!t)return!1;const e=(t.message||t.toString()||"").toLowerCase();return e.includes("cors")||e.includes("cross-origin")||e.includes("network error")||e.includes("failed to fetch")||e.includes("networkerror")||e.includes("load failed")||e.includes("xhr poll error")||e.includes("websocket error")||e.includes("transport")&&e.includes("error")}function ct(t,e){console.error(`\n╔══════════════════════════════════════════════════════════════════════════════╗\n║ GameGlue SDK: Possible CORS Error Detected ║\n╠══════════════════════════════════════════════════════════════════════════════╣\n║ Context: ${t.padEnd(66)}║\n║ URL: ${(e||"unknown").substring(0,70).padEnd(70)}║\n╠══════════════════════════════════════════════════════════════════════════════╣\n║ This error typically means the server rejected the request due to CORS. ║\n║ ║\n║ To fix this, add your origin to your app's allowed Web Origins: ║\n║ ║\n║ 1. Go to the GameGlue Developer Portal (https://developer.gameglue.gg) ║\n║ 2. Select your app ║\n║ 3. Add your origin to "Web Origins" and save ║\n║ ║\n║ IMPORTANT: Protocol and port must match exactly. ║\n║ http://localhost:3000 and https://localhost:3000 are different origins. ║\n║ http://localhost:3000 and http://localhost:5000 are different origins. ║\n╚══════════════════════════════════════════════════════════════════════════════╝\n`)}let lt=null;class ht{constructor(t){const e=t.authUrl||"https://auth.gameglue.gg/realms/GameGlue";this._oidcSettings={authority:e,client_id:t.clientId,redirect_uri:pt(t.redirect_uri||window.location.href),post_logout_redirect_uri:pt(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=>{at(t)&&ct("Login Request",this._oidcSettings.authority),console.error("Failed to create signin request:",t)})}logout(t={}){if(rt("gg-auth-token"),rt("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 E(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(lt)await lt;else{lt=this._doProcessCallback();try{await lt}finally{lt=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=E(t);return new Date(1e3*e.exp)>new Date}catch{return!1}}_getAccessToken(){const t=ot("gg-auth-token");return t&&this._setTokenRefreshTimeout(t),t||void 0}_setAccessToken(t){return this._setTokenRefreshTimeout(t),it("gg-auth-token",t)}_setRefreshToken(t){return it("gg-refresh-token",t)}_getRefreshToken(){return ot("gg-refresh-token")}_setTokenRefreshTimeout(t){if(t){clearTimeout(this._refreshTimeout);try{const e=1e3*E(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,n=this._getRefreshToken();try{const i=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:n})});if(200===i.status){const t=await i.json();this._setAccessToken(t.access_token),this._setRefreshToken(t.refresh_token),this._refreshCallback(t.access_token)}}catch(e){at(e)&&ct("Token Refresh",t),console.error("Token refresh failed:",e)}}}function pt(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 dt=Object.create(null);Object.keys(ut).forEach(t=>{dt[ut[t]]=t});const gt={type:"error",data:"parser error"},_t="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),mt="function"==typeof ArrayBuffer,ft=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,yt=({type:t,data:e},n,i)=>_t&&e instanceof Blob?n?i(e):wt(e,i):mt&&(e instanceof ArrayBuffer||ft(e))?n?i(e):wt(new Blob([e]),i):i(ut[t]+(e||"")),wt=(t,e)=>{const n=new FileReader;return n.onload=function(){const t=n.result.split(",")[1];e("b"+(t||""))},n.readAsDataURL(t)};function bt(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let vt;const kt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",St="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)St[kt.charCodeAt(t)]=t;const Ct="function"==typeof ArrayBuffer,Et=(t,e)=>{if("string"!=typeof t)return{type:"message",data:At(t,e)};const n=t.charAt(0);if("b"===n)return{type:"message",data:Tt(t.substring(1),e)};return dt[n]?t.length>1?{type:dt[n],data:t.substring(1)}:{type:dt[n]}:gt},Tt=(t,e)=>{if(Ct){const n=(t=>{let e,n,i,o,r,s=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(s--,"="===t[t.length-2]&&s--);const l=new ArrayBuffer(s),h=new Uint8Array(l);for(e=0;e<a;e+=4)n=St[t.charCodeAt(e)],i=St[t.charCodeAt(e+1)],o=St[t.charCodeAt(e+2)],r=St[t.charCodeAt(e+3)],h[c++]=n<<2|i>>4,h[c++]=(15&i)<<4|o>>2,h[c++]=(3&o)<<6|63&r;return l})(t);return At(n,e)}return{base64:!0,data:t}},At=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,xt=String.fromCharCode(30);function Rt(){return new TransformStream({transform(t,e){!function(t,e){_t&&t.data instanceof Blob?t.data.arrayBuffer().then(bt).then(e):mt&&(t.data instanceof ArrayBuffer||ft(t.data))?e(bt(t.data)):yt(t,!1,t=>{vt||(vt=new TextEncoder),e(vt.encode(t))})}(t,n=>{const i=n.length;let o;if(i<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,i);else if(i<65536){o=new Uint8Array(3);const t=new DataView(o.buffer);t.setUint8(0,126),t.setUint16(1,i)}else{o=new Uint8Array(9);const t=new DataView(o.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(i))}t.data&&"string"!=typeof t.data&&(o[0]|=128),e.enqueue(o),e.enqueue(n)})}})}let Ot;function Pt(t){return t.reduce((t,e)=>t+e.length,0)}function It(t,e){if(t[0].length===e)return t.shift();const n=new Uint8Array(e);let i=0;for(let o=0;o<e;o++)n[o]=t[0][i++],i===t[0].length&&(t.shift(),i=0);return t.length&&i<t[0].length&&(t[0]=t[0].slice(i)),n}function Lt(t){if(t)return function(t){for(var e in Lt.prototype)t[e]=Lt.prototype[e];return t}(t)}Lt.prototype.on=Lt.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},Lt.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},Lt.prototype.off=Lt.prototype.removeListener=Lt.prototype.removeAllListeners=Lt.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,i=this._callbacks["$"+t];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var o=0;o<i.length;o++)if((n=i[o])===e||n.fn===e){i.splice(o,1);break}return 0===i.length&&delete this._callbacks["$"+t],this},Lt.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],i=1;i<arguments.length;i++)e[i-1]=arguments[i];if(n){i=0;for(var o=(n=n.slice(0)).length;i<o;++i)n[i].apply(this,e)}return this},Lt.prototype.emitReserved=Lt.prototype.emit,Lt.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},Lt.prototype.hasListeners=function(t){return!!this.listeners(t).length};const Nt="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),Bt="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Ut(t,...e){return e.reduce((e,n)=>(t.hasOwnProperty(n)&&(e[n]=t[n]),e),{})}const qt=Bt.setTimeout,jt=Bt.clearTimeout;function Mt(t,e){e.useNativeTimers?(t.setTimeoutFn=qt.bind(Bt),t.clearTimeoutFn=jt.bind(Bt)):(t.setTimeoutFn=Bt.setTimeout.bind(Bt),t.clearTimeoutFn=Bt.clearTimeout.bind(Bt))}function Ft(t){return"string"==typeof t?function(t){let e=0,n=0;for(let i=0,o=t.length;i<o;i++)e=t.charCodeAt(i),e<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(i++,n+=4);return n}(t):Math.ceil(1.33*(t.byteLength||t.size))}function Dt(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class Ht extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class Gt extends Lt{constructor(t){super(),this.writable=!1,Mt(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,n){return super.emitReserved("error",new Ht(t,e,n)),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=Et(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 n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e}(t);return e.length?"?"+e:""}}class Vt extends Gt{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 n=t.split(xt),i=[];for(let t=0;t<n.length;t++){const o=Et(n[t],e);if(i.push(o),"error"===o.type)break}return i})(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 n=t.length,i=new Array(n);let o=0;t.forEach((t,r)=>{yt(t,!1,t=>{i[r]=t,++o===n&&e(i.join(xt))})})})(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]=Dt()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let zt=!1;try{zt="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const $t=zt;function Wt(){}class Kt extends Vt{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let n=location.port;n||(n=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.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 Lt{constructor(t,e,n){super(),this.createRequest=t,Mt(this,n),this._opts=n,this._method=n.method||"GET",this._uri=e,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var t;const e=Ut(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(e);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let t in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(t)&&n.setRequestHeader(t,this._opts.extraHeaders[t])}}catch(t){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{n.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var t;3===n.readyState&&(null===(t=this._opts.cookieJar)||void 0===t||t.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.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=Wt,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",Qt);else if("function"==typeof addEventListener){addEventListener("onpagehide"in Bt?"pagehide":"unload",Qt,!1)}function Qt(){for(let t in Jt.requests)Jt.requests.hasOwnProperty(t)&&Jt.requests[t].abort()}const Yt=function(){const t=Xt({xdomain:!1});return t&&null!==t.responseType}();function Xt(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||$t))return new XMLHttpRequest}catch(t){}if(!e)try{return new(Bt[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const Zt="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class te extends Gt{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=Zt?{}:Ut(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,n)}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 n=t[e],i=e===t.length-1;yt(n,this.supportsBinary,t=>{try{this.doWrite(n,t)}catch(t){}i&&Nt(()=>{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]=Dt()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const ee=Bt.WebSocket||Bt.MozWebSocket;const ne={websocket:class extends te{createSocket(t,e,n){return Zt?new ee(t,e,n):e?new ee(t,e):new ee(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends Gt{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){Ot||(Ot=new TextDecoder);const n=[];let i=0,o=-1,r=!1;return new TransformStream({transform(s,a){for(n.push(s);;){if(0===i){if(Pt(n)<1)break;const t=It(n,1);r=!(128&~t[0]),o=127&t[0],i=o<126?3:126===o?1:2}else if(1===i){if(Pt(n)<2)break;const t=It(n,2);o=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),i=3}else if(2===i){if(Pt(n)<8)break;const t=It(n,8),e=new DataView(t.buffer,t.byteOffset,t.length),r=e.getUint32(0);if(r>Math.pow(2,21)-1){a.enqueue(gt);break}o=r*Math.pow(2,32)+e.getUint32(4),i=3}else{if(Pt(n)<o)break;const t=It(n,o);a.enqueue(Et(r?t:Ot.decode(t),e)),i=0}if(0===o||o>t){a.enqueue(gt);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),i=Rt();i.readable.pipeTo(t.writable),this._writer=i.writable.getWriter();const o=()=>{n.read().then(({done:t,value:e})=>{t||(this.onPacket(e),o())}).catch(t=>{})};o();const r={type:"open"};this.query.sid&&(r.data=`{"sid":"${this.query.sid}"}`),this._writer.write(r).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],i=e===t.length-1;this._writer.write(n).then(()=>{i&&Nt(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this._transport)||void 0===t||t.close()}},polling:class extends Kt{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=Yt&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Jt(Xt,this.uri(),t)}}},ie=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,oe=["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,n=t.indexOf("["),i=t.indexOf("]");-1!=n&&-1!=i&&(t=t.substring(0,n)+t.substring(n,i).replace(/:/g,";")+t.substring(i,t.length));let o=ie.exec(t||""),r={},s=14;for(;s--;)r[oe[s]]=o[s]||"";return-1!=n&&-1!=i&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=function(t,e){const n=/\/{2,9}/g,i=e.replace(n,"/").split("/");"/"!=e.slice(0,1)&&0!==e.length||i.splice(0,1);"/"==e.slice(-1)&&i.splice(i.length-1,1);return i}(0,r.path),r.queryKey=function(t,e){const n={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,i){e&&(n[e]=i)}),n}(0,r.query),r}const se="function"==typeof addEventListener&&"function"==typeof removeEventListener,ae=[];se&&addEventListener("offline",()=>{ae.forEach(t=>t())},!1);class ce extends Lt{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 n=re(t);e.hostname=n.host,e.secure="https"===n.protocol||"wss"===n.protocol,e.port=n.port,n.query&&(e.query=n.query)}else e.host&&(e.hostname=re(e.host).host);Mt(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={},n=t.split("&");for(let t=0,i=n.length;t<i;t++){let i=n[t].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}(this.opts.query)),se&&(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"})},ae.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 n=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](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&ce.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",ce.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 n=this.writeBuffer[e].data;if(n&&(t+=Ft(n)),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,Nt(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,n){return this._sendPacket("message",t,e,n),this}send(t,e,n){return this._sendPacket("message",t,e,n),this}_sendPacket(t,e,n,i){if("function"==typeof e&&(i=e,e=void 0),"function"==typeof n&&(i=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const o={type:t,data:e,options:n};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),i&&this.once("flush",i),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{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?n():t()}):this.upgrading?n():t()),this}_onError(t){if(ce.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(),se&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=ae.indexOf(this._offlineEventListener);-1!==t&&ae.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}ce.protocol=4;class le extends ce{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),n=!1;ce.priorWebsocketSuccess=!1;const i=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!n)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;ce.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(l(),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 o(){n||(n=!0,l(),e.close(),e=null)}const r=t=>{const n=new Error("probe error: "+t);n.transport=e.name,o(),this.emitReserved("upgradeError",n)};function s(){r("transport closed")}function a(){r("socket closed")}function c(t){e&&t.name!==e.name&&o()}const l=()=>{e.removeListener("open",i),e.removeListener("error",r),e.removeListener("close",s),this.off("close",a),this.off("upgrading",c)};e.once("open",i),e.once("error",r),e.once("close",s),this.once("close",a),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{n||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}let he=class extends le{constructor(t,e={}){const n="object"==typeof t?t:e;(!n.transports||n.transports&&"string"==typeof n.transports[0])&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(t=>ne[t]).filter(t=>!!t)),super(t,n)}};const pe="function"==typeof ArrayBuffer,ue=Object.prototype.toString,de="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===ue.call(Blob),ge="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===ue.call(File);function _e(t){return pe&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||de&&t instanceof Blob||ge&&t instanceof File}function me(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,n=t.length;e<n;e++)if(me(t[e]))return!0;return!1}if(_e(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return me(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&me(t[e]))return!0;return!1}function fe(t){const e=[],n=t.data,i=t;return i.data=ye(n,e),i.attachments=e.length,{packet:i,buffers:e}}function ye(t,e){if(!t)return t;if(_e(t)){const n={_placeholder:!0,num:e.length};return e.push(t),n}if(Array.isArray(t)){const n=new Array(t.length);for(let i=0;i<t.length;i++)n[i]=ye(t[i],e);return n}if("object"==typeof t&&!(t instanceof Date)){const n={};for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[i]=ye(t[i],e));return n}return t}function we(t,e){return t.data=be(t.data,e),delete t.attachments,t}function be(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 n=0;n<t.length;n++)t[n]=be(t[n],e);else if("object"==typeof t)for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(t[n]=be(t[n],e));return t}const ve=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var ke;!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"}(ke||(ke={}));class Se extends Lt{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 n=e.type===ke.BINARY_EVENT;n||e.type===ke.BINARY_ACK?(e.type=n?ke.EVENT:ke.ACK,this.reconstructor=new Ce(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!_e(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 n={type:Number(t.charAt(0))};if(void 0===ke[n.type])throw new Error("unknown packet type "+n.type);if(n.type===ke.BINARY_EVENT||n.type===ke.BINARY_ACK){const i=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const o=t.substring(i,e);if(o!=Number(o)||"-"!==t.charAt(e))throw new Error("Illegal attachments");n.attachments=Number(o)}if("/"===t.charAt(e+1)){const i=e+1;for(;++e;){if(","===t.charAt(e))break;if(e===t.length)break}n.nsp=t.substring(i,e)}else n.nsp="/";const i=t.charAt(e+1);if(""!==i&&Number(i)==i){const i=e+1;for(;++e;){const n=t.charAt(e);if(null==n||Number(n)!=n){--e;break}if(e===t.length)break}n.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(!Se.isPayloadValid(n.type,i))throw new Error("invalid payload");n.data=i}return n}tryParse(t){try{return JSON.parse(t,this.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case ke.CONNECT:return Te(e);case ke.DISCONNECT:return void 0===e;case ke.CONNECT_ERROR:return"string"==typeof e||Te(e);case ke.EVENT:case ke.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===ve.indexOf(e[0]));case ke.ACK:case ke.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Ce{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=we(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Ee=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t};function Te(t){return"[object Object]"===Object.prototype.toString.call(t)}var Ae=Object.freeze({__proto__:null,Decoder:Se,Encoder:class{constructor(t){this.replacer=t}encode(t){return t.type!==ke.EVENT&&t.type!==ke.ACK||!me(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===ke.EVENT?ke.BINARY_EVENT:ke.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==ke.BINARY_EVENT&&t.type!==ke.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=fe(t),n=this.encodeAsString(e.packet),i=e.buffers;return i.unshift(n),i}},get PacketType(){return ke},isPacketValid:function(t){return"string"==typeof t.nsp&&(void 0===(e=t.id)||Ee(e))&&function(t,e){switch(t){case ke.CONNECT:return void 0===e||Te(e);case ke.DISCONNECT:return void 0===e;case ke.EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===ve.indexOf(e[0]));case ke.ACK:return Array.isArray(e);case ke.CONNECT_ERROR:return"string"==typeof e||Te(e);default:return!1}}(t.type,t.data);var e},protocol:5});function xe(t,e,n){return t.on(e,n),function(){t.off(e,n)}}const Re=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Oe extends Lt{constructor(t,e,n){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,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[xe(t,"open",this.onopen.bind(this)),xe(t,"packet",this.onpacket.bind(this)),xe(t,"error",this.onerror.bind(this)),xe(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 n,i,o;if(Re.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 r={type:ke.EVENT,data:e,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,n=e.pop();this._registerAckCallback(t,n),r.id=t}const s=null===(i=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===i?void 0:i.writable,a=this.connected&&!(null===(o=this.io.engine)||void 0===o?void 0:o._hasPingExpired());return this.flags.volatile&&!s||(a?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(t,e){var n;const i=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===i)return void(this.acks[t]=e);const o=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"))},i),r=(...t)=>{this.io.clearTimeoutFn(o),e.apply(this,t)};r.withError=!0,this.acks[t]=r}emitWithAck(t,...e){return new Promise((n,i)=>{const o=(t,e)=>t?i(t):n(e);o.withError=!0,e.push(o),this.emit(t,...e)})}_addToQueue(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...i)=>{this._queue[0];return null!==t?n.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(t)):(this._queue.shift(),e&&e(null,...i)),n.pending=!1,this._drainQueue()}),this._queue.push(n),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:ke.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 ke.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 ke.EVENT:case ke.BINARY_EVENT:this.onevent(t);break;case ke.ACK:case ke.BINARY_ACK:this.onack(t);break;case ke.DISCONNECT:this.ondisconnect();break;case ke.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 n of e)n.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 n=!1;return function(...i){n||(n=!0,e.packet({type:ke.ACK,id:t,data:i}))}}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:ke.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 n=0;n<e.length;n++)if(t===e[n])return e.splice(n,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 n=0;n<e.length;n++)if(t===e[n])return e.splice(n,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 n of e)n.apply(this,t.data)}}}function Pe(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}Pe.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+n:t-n}return 0|Math.min(t,this.max)},Pe.prototype.reset=function(){this.attempts=0},Pe.prototype.setMin=function(t){this.ms=t},Pe.prototype.setMax=function(t){this.max=t},Pe.prototype.setJitter=function(t){this.jitter=t};class Ie extends Lt{constructor(t,e){var n;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,Mt(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!==(n=e.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new Pe({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const i=e.parser||Ae;this.encoder=new i.Encoder,this.decoder=new i.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 he(this.uri,this.opts);const e=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=xe(e,"open",function(){n.onopen(),t&&t()}),o=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},r=xe(e,"error",o);if(!1!==this._timeout){const t=this._timeout,n=this.setTimeoutFn(()=>{i(),o(new Error("timeout")),e.close()},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(i),this.subs.push(r),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(xe(t,"ping",this.onping.bind(this)),xe(t,"data",this.ondata.bind(this)),xe(t,"error",this.onerror.bind(this)),xe(t,"close",this.onclose.bind(this)),xe(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){Nt(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new Oe(this,t,e),this.nsps[t]=n),n}_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 n=0;n<e.length;n++)this.engine.write(e[n],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 n;this.cleanup(),null===(n=this.engine)||void 0===n||n.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 n=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&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Le={};function Ne(t,e){"object"==typeof t&&(e=t,t=void 0);const n=function(t,e="",n){let i=t;n=n||"undefined"!=typeof location&&location,null==t&&(t=n.protocol+"//"+n.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?n.protocol+t:n.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==n?n.protocol+"//"+t:"https://"+t),i=re(t)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const o=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+o+":"+i.port+e,i.href=i.protocol+"://"+o+(n&&n.port===i.port?"":":"+i.port),i}(t,(e=e||{}).path||"/socket.io"),i=n.source,o=n.id,r=n.path,s=Le[o]&&r in Le[o].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||s?a=new Ie(i,e):(Le[o]||(Le[o]=new Ie(i,e)),a=Le[o]),n.query&&!e.query&&(e.query=n.queryKey),a.socket(n.path,e)}Object.assign(Ne,{Manager:Ie,Socket:Oe,io:Ne,connect:Ne});var Be,Ue,qe,je,Me,Fe,De,He,Ge,Ve,ze,$e,We,Ke,Je,Qe,Ye,Xe,Ze,tn,en,nn,on,rn,sn,an,cn,ln,hn,pn,un,dn,gn,_n,mn,fn,yn,wn,bn,vn,kn={exports:{}},Sn={exports:{}};function Cn(){if(Ue)return Be;Ue=1;return Be=function(t){return null!=t},Be}function En(){if(Fe)return Me;Fe=1;var t=function(){if(je)return qe;je=1;var t=Cn(),e={object:!0,function:!0,undefined:!0};return qe=function(n){return!!t(n)&&hasOwnProperty.call(e,typeof n)},qe}();return Me=function(e){if(!t(e))return!1;try{return!!e.constructor&&e.constructor.prototype===e}catch(t){return!1}},Me}function Tn(){if(Ve)return Ge;Ve=1;var t=function(){if(He)return De;He=1;var t=En();return De=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)},De}(),e=/^\s*class[\s{/}]/,n=Function.prototype.toString;return Ge=function(i){return!!t(i)&&!e.test(n.call(i))},Ge}function An(){if(Xe)return Ye;Xe=1;var t=(Qe?Je:(Qe=1,Je=function(){}))();return Ye=function(e){return e!==t&&null!==e}}function xn(){return nn||(nn=1,en=(Ke?We:(Ke=1,We=function(){try{return Object.keys("primitive"),!0}catch(t){return!1}}))()?Object.keys:function(){if(tn)return Ze;tn=1;var t=An(),e=Object.keys;return Ze=function(n){return e(t(n)?Object(n):n)}}()),en}function Rn(){if(an)return sn;an=1;var t=xn(),e=function(){if(rn)return on;rn=1;var t=An();return on=function(e){if(!t(e))throw new TypeError("Cannot use null or undefined");return e},on}(),n=Math.max;return sn=function(i,o){var r,s,a,c=n(arguments.length,2);for(i=Object(e(i)),a=function(t){try{i[t]=o[t]}catch(t){r||(r=t)}},s=1;s<c;++s)t(o=arguments[s]).forEach(a);if(void 0!==r)throw r;return i},sn}function On(){return ln?cn:(ln=1,cn=($e||($e=1,ze=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")}),ze)()?Object.assign:Rn())}function Pn(){return fn||(fn=1,mn=function(){if(dn)return un;dn=1;var t="razdwatrzy";return un=function(){return"function"==typeof t.contains&&!0===t.contains("dwa")&&!1===t.contains("foo")}}()()?String.prototype.contains:function(){if(_n)return gn;_n=1;var t=String.prototype.indexOf;return gn=function(e){return t.call(this,e,arguments[1])>-1},gn}()),mn}function In(){if(yn)return Sn.exports;yn=1;var t=Cn(),e=Tn(),n=On(),i=function(){if(pn)return hn;pn=1;var t=An(),e=Array.prototype.forEach,n=Object.create;return hn=function(i){var o=n(null);return e.call(arguments,function(e){t(e)&&function(t,e){var n;for(n in t)e[n]=t[n]}(Object(e),o)}),o},hn}(),o=Pn(),r=Sn.exports=function(e,r){var s,a,c,l,h;return arguments.length<2||"string"!=typeof e?(l=r,r=e,e=null):l=arguments[2],t(e)?(s=o.call(e,"c"),a=o.call(e,"e"),c=o.call(e,"w")):(s=c=!0,a=!1),h={value:r,configurable:s,enumerable:a,writable:c},l?n(i(l),h):h};return r.gs=function(r,s,a){var c,l,h,p;return"string"!=typeof r?(h=a,a=s,s=r,r=null):h=arguments[3],t(s)?e(s)?t(a)?e(a)||(h=a,a=void 0):a=void 0:(h=s,s=a=void 0):s=void 0,t(r)?(c=o.call(r,"c"),l=o.call(r,"e")):(c=!0,l=!1),p={get:s,set:a,configurable:c,enumerable:l},h?n(i(h),p):p},Sn.exports}var Ln=(vn||(vn=1,function(t,e){var n,i,o,r,s,a,c,l=In(),h=bn?wn:(bn=1,wn=function(t){if("function"!=typeof t)throw new TypeError(t+" is not a function");return t}),p=Function.prototype.apply,u=Function.prototype.call,d=Object.create,g=Object.defineProperty,_=Object.defineProperties,m=Object.prototype.hasOwnProperty,f={configurable:!0,enumerable:!1,writable:!0};i=function(t,e){var i,r;return h(e),r=this,n.call(this,t,i=function(){o.call(r,t,i),p.call(e,this,arguments)}),i.__eeOnceListener__=e,this},r=function(t){var e,n,i,o,r;if(m.call(this,"__ee__")&&(o=this.__ee__[t]))if("object"==typeof o){for(n=arguments.length,r=new Array(n-1),e=1;e<n;++e)r[e-1]=arguments[e];for(o=o.slice(),e=0;i=o[e];++e)p.call(i,this,r)}else switch(arguments.length){case 1:u.call(o,this);break;case 2:u.call(o,this,arguments[1]);break;case 3:u.call(o,this,arguments[1],arguments[2]);break;default:for(n=arguments.length,r=new Array(n-1),e=1;e<n;++e)r[e-1]=arguments[e];p.call(o,this,r)}},s={on:n=function(t,e){var n;return h(e),m.call(this,"__ee__")?n=this.__ee__:(n=f.value=d(null),g(this,"__ee__",f),f.value=null),n[t]?"object"==typeof n[t]?n[t].push(e):n[t]=[n[t],e]:n[t]=e,this},once:i,off:o=function(t,e){var n,i,o,r;if(h(e),!m.call(this,"__ee__"))return this;if(!(n=this.__ee__)[t])return this;if("object"==typeof(i=n[t]))for(r=0;o=i[r];++r)o!==e&&o.__eeOnceListener__!==e||(2===i.length?n[t]=i[r?0:1]:i.splice(r,1));else i!==e&&i.__eeOnceListener__!==e||delete n[t];return this},emit:r},a={on:l(n),once:l(i),off:l(o),emit:l(r)},c=_({},a),t.exports=e=function(t){return null==t?d(c):_(Object(t),a)},e.methods=s}(kn,kn.exports)),kn.exports),Nn=n(Ln);const Bn={radiansToDegrees:t=>t*(180/Math.PI),degreesToRadians:t=>t*(Math.PI/180),metersToFeet:t=>3.28084*t,feetToMeters:t=>t/3.28084,msToKnots:t=>1.94384*t,knotsToMs:t=>t/1.94384,msToFpm:t=>196.85*t,toBoolean:t=>Boolean(t),divideBy100:t=>t/100},Un={category:"flight_sim",name:"Flight Simulator",description:"Canonical telemetry fields for flight simulation games",recommendedUpdateRateHz:10,requiredFields:["latitude","longitude","altitude","indicated_airspeed","heading","vertical_speed","on_ground"],fields:{latitude:{type:"number",description:"Aircraft latitude",unit:"degrees",min:-90,max:90,group:"Position"},longitude:{type:"number",description:"Aircraft longitude",unit:"degrees",min:-180,max:180,group:"Position"},altitude:{type:"number",description:"Aircraft altitude above sea level",unit:"ft",min:-2e3,max:1e5,group:"Position"},altitude_agl:{type:"number",description:"Aircraft altitude above ground level",unit:"ft",min:0,max:1e5,group:"Position"},on_ground:{type:"boolean",description:"Whether aircraft is on the ground",group:"Position"},indicated_airspeed:{type:"number",description:"Indicated airspeed",unit:"kts",min:0,max:1e3,group:"Velocity"},true_airspeed:{type:"number",description:"True airspeed",unit:"kts",min:0,max:1e3,group:"Velocity"},ground_speed:{type:"number",description:"Ground speed",unit:"kts",min:0,max:1e3,group:"Velocity"},mach:{type:"number",description:"Mach number",min:0,max:5,group:"Velocity"},vertical_speed:{type:"number",description:"Vertical speed",unit:"ft/min",min:-2e4,max:2e4,group:"Velocity"},g_force:{type:"number",description:"Current G-force",unit:"G",min:-10,max:10,group:"Velocity"},heading:{type:"number",description:"Aircraft magnetic heading",unit:"degrees",min:0,max:360,group:"Attitude"},true_heading:{type:"number",description:"Aircraft true heading",unit:"degrees",min:0,max:360,group:"Attitude"},pitch:{type:"number",description:"Aircraft pitch angle",unit:"degrees",min:-90,max:90,group:"Attitude"},roll:{type:"number",description:"Aircraft roll/bank angle",unit:"degrees",min:-180,max:180,group:"Attitude"},yaw:{type:"number",description:"Aircraft yaw angle",unit:"degrees",min:-180,max:180,group:"Attitude"},throttle_0:{type:"number",description:"Engine 0 throttle position",unit:"%",min:0,max:100,group:"Engine"},throttle_1:{type:"number",description:"Engine 1 throttle position",unit:"%",min:0,max:100,group:"Engine"},throttle_2:{type:"number",description:"Engine 2 throttle position",unit:"%",min:0,max:100,group:"Engine"},throttle_3:{type:"number",description:"Engine 3 throttle position",unit:"%",min:0,max:100,group:"Engine"},rpm_0:{type:"number",description:"Engine 0 RPM",unit:"RPM",min:0,max:1e4,group:"Engine"},rpm_1:{type:"number",description:"Engine 1 RPM",unit:"RPM",min:0,max:1e4,group:"Engine"},rpm_2:{type:"number",description:"Engine 2 RPM",unit:"RPM",min:0,max:1e4,group:"Engine"},rpm_3:{type:"number",description:"Engine 3 RPM",unit:"RPM",min:0,max:1e4,group:"Engine"},n1_0:{type:"number",description:"Engine 0 N1 (turbine)",unit:"%",min:0,max:120,group:"Engine"},n1_1:{type:"number",description:"Engine 1 N1 (turbine)",unit:"%",min:0,max:120,group:"Engine"},n1_2:{type:"number",description:"Engine 2 N1 (turbine)",unit:"%",min:0,max:120,group:"Engine"},n1_3:{type:"number",description:"Engine 3 N1 (turbine)",unit:"%",min:0,max:120,group:"Engine"},n2_0:{type:"number",description:"Engine 0 N2 (turbine)",unit:"%",min:0,max:120,group:"Engine"},n2_1:{type:"number",description:"Engine 1 N2 (turbine)",unit:"%",min:0,max:120,group:"Engine"},n2_2:{type:"number",description:"Engine 2 N2 (turbine)",unit:"%",min:0,max:120,group:"Engine"},n2_3:{type:"number",description:"Engine 3 N2 (turbine)",unit:"%",min:0,max:120,group:"Engine"},egt_0:{type:"number",description:"Engine 0 exhaust gas temperature",unit:"°C",min:0,max:1200,group:"Engine"},egt_1:{type:"number",description:"Engine 1 exhaust gas temperature",unit:"°C",min:0,max:1200,group:"Engine"},egt_2:{type:"number",description:"Engine 2 exhaust gas temperature",unit:"°C",min:0,max:1200,group:"Engine"},egt_3:{type:"number",description:"Engine 3 exhaust gas temperature",unit:"°C",min:0,max:1200,group:"Engine"},fuel_quantity:{type:"number",description:"Total fuel quantity",unit:"lbs",min:0,max:6e5,group:"Fuel"},fuel_flow_0:{type:"number",description:"Engine 0 fuel flow",unit:"lbs/hr",min:0,max:3e4,group:"Fuel"},fuel_flow_1:{type:"number",description:"Engine 1 fuel flow",unit:"lbs/hr",min:0,max:3e4,group:"Fuel"},fuel_flow_2:{type:"number",description:"Engine 2 fuel flow",unit:"lbs/hr",min:0,max:3e4,group:"Fuel"},fuel_flow_3:{type:"number",description:"Engine 3 fuel flow",unit:"lbs/hr",min:0,max:3e4,group:"Fuel"},autopilot_master:{type:"boolean",description:"Autopilot master engaged",group:"Autopilot"},autopilot_altitude_hold:{type:"boolean",description:"Altitude hold engaged",group:"Autopilot"},autopilot_heading_hold:{type:"boolean",description:"Heading hold engaged",group:"Autopilot"},autopilot_vs_hold:{type:"boolean",description:"Vertical speed hold engaged",group:"Autopilot"},autopilot_speed_hold:{type:"boolean",description:"Speed hold engaged",group:"Autopilot"},autopilot_approach:{type:"boolean",description:"Approach mode engaged",group:"Autopilot"},autopilot_nav:{type:"boolean",description:"NAV mode engaged",group:"Autopilot"},flight_director:{type:"boolean",description:"Flight director active",group:"Autopilot"},autopilot_flc:{type:"boolean",description:"Flight level change mode engaged",group:"Autopilot"},autopilot_altitude_target:{type:"number",description:"Autopilot target altitude",unit:"ft",min:0,max:6e4,group:"Autopilot"},autopilot_heading_target:{type:"number",description:"Autopilot target heading",unit:"degrees",min:0,max:360,group:"Autopilot"},autopilot_vs_target:{type:"number",description:"Autopilot target vertical speed",unit:"ft/min",min:-1e4,max:1e4,group:"Autopilot"},autopilot_speed_target:{type:"number",description:"Autopilot target airspeed",unit:"kts",min:0,max:600,group:"Autopilot"},flaps:{type:"number",description:"Flaps position",unit:"%",min:0,max:100,group:"Controls"},spoilers:{type:"number",description:"Spoilers position",unit:"%",min:0,max:100,group:"Controls"},gear_down:{type:"boolean",description:"Landing gear extended",group:"Controls"},parking_brake:{type:"boolean",description:"Parking brake engaged",group:"Controls"},brake_left:{type:"number",description:"Left brake position",unit:"%",min:0,max:100,group:"Controls"},brake_right:{type:"number",description:"Right brake position",unit:"%",min:0,max:100,group:"Controls"},light_landing:{type:"boolean",description:"Landing lights on",group:"Lights"},light_taxi:{type:"boolean",description:"Taxi lights on",group:"Lights"},light_beacon:{type:"boolean",description:"Beacon lights on",group:"Lights"},light_nav:{type:"boolean",description:"Navigation lights on",group:"Lights"},light_strobe:{type:"boolean",description:"Strobe lights on",group:"Lights"},outside_air_temp:{type:"number",description:"Outside air temperature",unit:"°C",min:-80,max:60,group:"Environment"},barometric_pressure:{type:"number",description:"Barometric pressure setting",unit:"inHg",min:27,max:32,group:"Environment"},wind_direction:{type:"number",description:"Wind direction",unit:"degrees",min:0,max:360,group:"Environment"},wind_speed:{type:"number",description:"Wind speed",unit:"kts",min:0,max:200,group:"Environment"},stall_warning:{type:"boolean",description:"Stall warning active",group:"Warnings"},overspeed_warning:{type:"boolean",description:"Overspeed warning active",group:"Warnings"},sim_paused:{type:"boolean",description:"Simulation is paused",group:"Simulation"},sim_rate:{type:"number",description:"Simulation rate multiplier (1.0 = real time)",group:"Simulation"},gps_wp_distance:{type:"number",description:"Distance to next GPS waypoint",unit:"nm",min:0,max:1e4,group:"Navigation"},gps_wp_ete:{type:"number",description:"Estimated time enroute to next GPS waypoint",unit:"seconds",min:0,max:86400,group:"Navigation"}},commands:{autopilot_on:{description:"Engage autopilot master",group:"Autopilot"},autopilot_off:{description:"Disengage autopilot master",group:"Autopilot"},autopilot_toggle:{description:"Toggle autopilot master",group:"Autopilot"},autopilot_altitude_hold_on:{description:"Engage altitude hold",group:"Autopilot"},autopilot_altitude_hold_off:{description:"Disengage altitude hold",group:"Autopilot"},autopilot_heading_hold_on:{description:"Engage heading hold",group:"Autopilot"},autopilot_heading_hold_off:{description:"Disengage heading hold",group:"Autopilot"},autopilot_vs_hold_on:{description:"Engage vertical speed hold",group:"Autopilot"},autopilot_vs_hold_off:{description:"Disengage vertical speed hold",group:"Autopilot"},autopilot_nav_on:{description:"Engage NAV mode",group:"Autopilot"},autopilot_nav_off:{description:"Disengage NAV mode",group:"Autopilot"},autopilot_approach_on:{description:"Engage approach mode",group:"Autopilot"},autopilot_approach_off:{description:"Disengage approach mode",group:"Autopilot"},flight_director_on:{description:"Engage flight director",group:"Autopilot"},flight_director_off:{description:"Disengage flight director",group:"Autopilot"},autopilot_flc_on:{description:"Engage flight level change mode",group:"Autopilot"},autopilot_flc_off:{description:"Disengage flight level change mode",group:"Autopilot"},autopilot_flc_toggle:{description:"Toggle flight level change mode",group:"Autopilot"},set_autopilot_altitude:{description:"Set autopilot target altitude",group:"Autopilot",paramType:"number",paramDescription:"Target altitude in feet",paramMin:0,paramMax:6e4},set_autopilot_heading:{description:"Set autopilot target heading",group:"Autopilot",paramType:"number",paramDescription:"Target heading in degrees",paramMin:0,paramMax:360},set_autopilot_vs:{description:"Set autopilot target vertical speed",group:"Autopilot",paramType:"number",paramDescription:"Target vertical speed in ft/min",paramMin:-1e4,paramMax:1e4},set_autopilot_speed:{description:"Set autopilot target airspeed",group:"Autopilot",paramType:"number",paramDescription:"Target airspeed in knots",paramMin:0,paramMax:600},gear_up:{description:"Retract landing gear",group:"Controls"},gear_down:{description:"Extend landing gear",group:"Controls"},gear_toggle:{description:"Toggle landing gear",group:"Controls"},flaps_up:{description:"Retract flaps one notch",group:"Controls"},flaps_down:{description:"Extend flaps one notch",group:"Controls"},flaps_full:{description:"Extend flaps fully",group:"Controls"},flaps_retract:{description:"Fully retract flaps",group:"Controls"},set_flaps:{description:"Set flaps to specific position",group:"Controls",paramType:"number",paramDescription:"Flaps position (0-100%)",paramMin:0,paramMax:100},spoilers_arm:{description:"Arm spoilers",group:"Controls"},spoilers_deploy:{description:"Deploy spoilers",group:"Controls"},spoilers_retract:{description:"Retract spoilers",group:"Controls"},spoilers_toggle:{description:"Toggle spoilers",group:"Controls"},parking_brake_toggle:{description:"Toggle parking brake",group:"Controls"},parking_brake_on:{description:"Engage parking brake",group:"Controls"},parking_brake_off:{description:"Release parking brake",group:"Controls"},set_throttle:{description:"Set all throttles",group:"Engine",paramType:"number",paramDescription:"Throttle position (0-100%)",paramMin:0,paramMax:100},set_throttle_0:{description:"Set engine 0 throttle",group:"Engine",paramType:"number",paramDescription:"Throttle position (0-100%)",paramMin:0,paramMax:100},set_throttle_1:{description:"Set engine 1 throttle",group:"Engine",paramType:"number",paramDescription:"Throttle position (0-100%)",paramMin:0,paramMax:100},set_throttle_2:{description:"Set engine 2 throttle",group:"Engine",paramType:"number",paramDescription:"Throttle position (0-100%)",paramMin:0,paramMax:100},set_throttle_3:{description:"Set engine 3 throttle",group:"Engine",paramType:"number",paramDescription:"Throttle position (0-100%)",paramMin:0,paramMax:100},throttle_full:{description:"Set throttles to full",group:"Engine"},throttle_idle:{description:"Set throttles to idle",group:"Engine"},throttle_cutoff:{description:"Cut throttles completely",group:"Engine"},landing_lights_on:{description:"Turn on landing lights",group:"Lights"},landing_lights_off:{description:"Turn off landing lights",group:"Lights"},landing_lights_toggle:{description:"Toggle landing lights",group:"Lights"},taxi_lights_on:{description:"Turn on taxi lights",group:"Lights"},taxi_lights_off:{description:"Turn off taxi lights",group:"Lights"},taxi_lights_toggle:{description:"Toggle taxi lights",group:"Lights"},beacon_lights_on:{description:"Turn on beacon lights",group:"Lights"},beacon_lights_off:{description:"Turn off beacon lights",group:"Lights"},beacon_lights_toggle:{description:"Toggle beacon lights",group:"Lights"},nav_lights_on:{description:"Turn on navigation lights",group:"Lights"},nav_lights_off:{description:"Turn off navigation lights",group:"Lights"},nav_lights_toggle:{description:"Toggle navigation lights",group:"Lights"},strobe_lights_on:{description:"Turn on strobe lights",group:"Lights"},strobe_lights_off:{description:"Turn off strobe lights",group:"Lights"},strobe_lights_toggle:{description:"Toggle strobe lights",group:"Lights"},pause:{description:"Pause simulation",group:"Simulation"},unpause:{description:"Unpause simulation",group:"Simulation"},pause_toggle:{description:"Toggle simulation pause",group:"Simulation"},set_pause:{description:"Set pause state with parameter (1 = pause, 0 = unpause). Preferred over pause/unpause for MSFS where PAUSE_ON/PAUSE_OFF are unreliable.",group:"Simulation"}}},qn={flight_sim:Un,racing_sim:Un};function jn(t){return qn[t]}var Mn={gameId:"msfs",name:"Microsoft Flight Simulator",category:"flight_sim",fieldMappings:{latitude:{canonical:"latitude"},longitude:{canonical:"longitude"},indicated_altitude:{canonical:"altitude"},plane_altitude:{canonical:"altitude"},on_ground:{canonical:"on_ground",transform:"toBoolean"},altitude_agl:{canonical:"altitude_agl"},indicated_airspeed:{canonical:"indicated_airspeed"},true_airspeed:{canonical:"true_airspeed"},airspeed_mach:{canonical:"mach"},airspeed_indicated:{canonical:"indicated_airspeed"},ground_speed:{canonical:"ground_speed"},ground_velocity:{canonical:"ground_speed"},vertical_speed:{canonical:"vertical_speed"},gforce:{canonical:"g_force"},heading_gyro:{canonical:"heading"},heading_indicator:{canonical:"heading"},true_heading:{canonical:"true_heading"},attitude_indicator_pitch:{canonical:"pitch"},attitude_indicator_roll:{canonical:"roll"},yaw_rate:{canonical:"yaw"},eng_throttle_1:{canonical:"throttle_0",transform:"divideBy100"},eng_throttle_2:{canonical:"throttle_1",transform:"divideBy100"},eng_throttle_3:{canonical:"throttle_2",transform:"divideBy100"},eng_throttle_4:{canonical:"throttle_3",transform:"divideBy100"},eng_rpm_1:{canonical:"rpm_0"},eng_rpm_2:{canonical:"rpm_1"},eng_rpm_3:{canonical:"rpm_2"},eng_rpm_4:{canonical:"rpm_3"},turb_eng_n1_1:{canonical:"n1_0"},turb_eng_n1_2:{canonical:"n1_1"},turb_eng_n1_3:{canonical:"n1_2"},turb_eng_n1_4:{canonical:"n1_3"},turb_eng_n2_1:{canonical:"n2_0"},turb_eng_n2_2:{canonical:"n2_1"},turb_eng_n2_3:{canonical:"n2_2"},turb_eng_n2_4:{canonical:"n2_3"},turb_eng_itt_1:{canonical:"egt_0"},turb_eng_itt_2:{canonical:"egt_1"},turb_eng_itt_3:{canonical:"egt_2"},turb_eng_itt_4:{canonical:"egt_3"},fuel_quantity_pounds:{canonical:"fuel_quantity"},fuel_flow_pph_1:{canonical:"fuel_flow_0"},fuel_flow_pph_2:{canonical:"fuel_flow_1"},fuel_flow_pph_3:{canonical:"fuel_flow_2"},fuel_flow_pph_4:{canonical:"fuel_flow_3"},autopilot_master:{canonical:"autopilot_master",transform:"toBoolean"},autopilot_altitude_lock:{canonical:"autopilot_altitude_hold",transform:"toBoolean"},autopilot_heading_lock:{canonical:"autopilot_heading_hold",transform:"toBoolean"},autopilot_vertical_hold:{canonical:"autopilot_vs_hold",transform:"toBoolean"},autopilot_airspeed_hold:{canonical:"autopilot_speed_hold",transform:"toBoolean"},autopilot_approach_hold:{canonical:"autopilot_approach",transform:"toBoolean"},autopilot_nav1_lock:{canonical:"autopilot_nav",transform:"toBoolean"},autopilot_flight_director:{canonical:"flight_director",transform:"toBoolean"},autopilot_flc:{canonical:"autopilot_flc",transform:"toBoolean"},autopilot_altitude_set:{canonical:"autopilot_altitude_target"},autopilot_heading_set:{canonical:"autopilot_heading_target"},autopilot_vertical_speed_set:{canonical:"autopilot_vs_target"},autopilot_airspeed_set:{canonical:"autopilot_speed_target"},flaps_handle_percent:{canonical:"flaps"},spoilers_handle_percent:{canonical:"spoilers"},gear_handle_position:{canonical:"gear_down",transform:"toBoolean"},parking_brake:{canonical:"parking_brake",transform:"toBoolean"},brake_left_position:{canonical:"brake_left"},brake_right_position:{canonical:"brake_right"},light_landing:{canonical:"light_landing",transform:"toBoolean"},light_taxi:{canonical:"light_taxi",transform:"toBoolean"},light_beacon:{canonical:"light_beacon",transform:"toBoolean"},light_nav:{canonical:"light_nav",transform:"toBoolean"},light_strobe:{canonical:"light_strobe",transform:"toBoolean"},ambient_temperature:{canonical:"outside_air_temp"},kohlsman_setting_hg:{canonical:"barometric_pressure"},ambient_wind_direction:{canonical:"wind_direction"},ambient_wind_velocity:{canonical:"wind_speed"},stall_warning:{canonical:"stall_warning",transform:"toBoolean"},overspeed_warning:{canonical:"overspeed_warning",transform:"toBoolean"},sim_paused:{canonical:"sim_paused",transform:"toBoolean"},simulation_rate:{canonical:"sim_rate"},gps_wp_distance:{canonical:"gps_wp_distance"},gps_wp_ete:{canonical:"gps_wp_ete"}},commandMappings:{autopilot_on:{gameCommand:"AP_MASTER_ON",type:"command"},autopilot_off:{gameCommand:"AP_MASTER_OFF",type:"command"},autopilot_toggle:{gameCommand:"AP_MASTER",type:"command"},autopilot_altitude_hold_on:{gameCommand:"AP_ALT_HOLD_ON",type:"command"},autopilot_altitude_hold_off:{gameCommand:"AP_ALT_HOLD_OFF",type:"command"},autopilot_heading_hold_on:{gameCommand:"AP_HDG_HOLD_ON",type:"command"},autopilot_heading_hold_off:{gameCommand:"AP_HDG_HOLD_OFF",type:"command"},autopilot_vs_hold_on:{gameCommand:"AP_VS_ON",type:"command"},autopilot_vs_hold_off:{gameCommand:"AP_VS_OFF",type:"command"},autopilot_nav_on:{gameCommand:"AP_NAV1_HOLD_ON",type:"command"},autopilot_nav_off:{gameCommand:"AP_NAV1_HOLD_OFF",type:"command"},autopilot_approach_on:{gameCommand:"AP_APR_HOLD_ON",type:"command"},autopilot_approach_off:{gameCommand:"AP_APR_HOLD_OFF",type:"command"},flight_director_on:{gameCommand:"TOGGLE_FLIGHT_DIRECTOR",type:"command"},flight_director_off:{gameCommand:"TOGGLE_FLIGHT_DIRECTOR",type:"command"},autopilot_flc_on:{gameCommand:"FLIGHT_LEVEL_CHANGE_ON",type:"command"},autopilot_flc_off:{gameCommand:"FLIGHT_LEVEL_CHANGE_OFF",type:"command"},autopilot_flc_toggle:{gameCommand:"FLIGHT_LEVEL_CHANGE",type:"command"},set_autopilot_altitude:{gameCommand:"AP_ALT_VAR_SET_ENGLISH",type:"command"},set_autopilot_heading:{gameCommand:"HEADING_BUG_SET",type:"command"},set_autopilot_vs:{gameCommand:"AP_VS_VAR_SET_ENGLISH",type:"command"},set_autopilot_speed:{gameCommand:"AP_SPD_VAR_SET",type:"command"},gear_up:{gameCommand:"GEAR_UP",type:"command"},gear_down:{gameCommand:"GEAR_DOWN",type:"command"},gear_toggle:{gameCommand:"GEAR_TOGGLE",type:"command"},flaps_up:{gameCommand:"FLAPS_DECR",type:"command"},flaps_down:{gameCommand:"FLAPS_INCR",type:"command"},flaps_full:{gameCommand:"FLAPS_DOWN",type:"command"},flaps_retract:{gameCommand:"FLAPS_UP",type:"command"},set_flaps:{gameCommand:"FLAPS_SET",type:"command"},spoilers_arm:{gameCommand:"SPOILERS_ARM_TOGGLE",type:"command"},spoilers_deploy:{gameCommand:"SPOILERS_ON",type:"command"},spoilers_retract:{gameCommand:"SPOILERS_OFF",type:"command"},spoilers_toggle:{gameCommand:"SPOILERS_TOGGLE",type:"command"},parking_brake_toggle:{gameCommand:"PARKING_BRAKES",type:"command"},parking_brake_on:{gameCommand:"PARKING_BRAKE_SET",type:"command"},parking_brake_off:{gameCommand:"PARKING_BRAKE_SET",type:"command"},set_throttle:{gameCommand:"THROTTLE_SET",type:"command"},set_throttle_0:{gameCommand:"THROTTLE1_SET",type:"command"},set_throttle_1:{gameCommand:"THROTTLE2_SET",type:"command"},set_throttle_2:{gameCommand:"THROTTLE3_SET",type:"command"},set_throttle_3:{gameCommand:"THROTTLE4_SET",type:"command"},throttle_full:{gameCommand:"THROTTLE_FULL",type:"command"},throttle_idle:{gameCommand:"THROTTLE_CUT",type:"command"},throttle_cutoff:{gameCommand:"THROTTLE_CUT",type:"command"},landing_lights_on:{gameCommand:"LANDING_LIGHTS_ON",type:"command"},landing_lights_off:{gameCommand:"LANDING_LIGHTS_OFF",type:"command"},landing_lights_toggle:{gameCommand:"LANDING_LIGHTS_TOGGLE",type:"command"},taxi_lights_on:{gameCommand:"TAXI_LIGHTS_ON",type:"command"},taxi_lights_off:{gameCommand:"TAXI_LIGHTS_OFF",type:"command"},taxi_lights_toggle:{gameCommand:"TAXI_LIGHTS_TOGGLE",type:"command"},beacon_lights_on:{gameCommand:"BEACON_LIGHTS_ON",type:"command"},beacon_lights_off:{gameCommand:"BEACON_LIGHTS_OFF",type:"command"},beacon_lights_toggle:{gameCommand:"BEACON_LIGHTS_TOGGLE",type:"command"},nav_lights_on:{gameCommand:"NAV_LIGHTS_ON",type:"command"},nav_lights_off:{gameCommand:"NAV_LIGHTS_OFF",type:"command"},nav_lights_toggle:{gameCommand:"NAV_LIGHTS_TOGGLE",type:"command"},strobe_lights_on:{gameCommand:"STROBES_ON",type:"command"},strobe_lights_off:{gameCommand:"STROBES_OFF",type:"command"},strobe_lights_toggle:{gameCommand:"STROBES_TOGGLE",type:"command"},set_pause:{gameCommand:"PAUSE_SET",type:"command"},sim_rate_incr:{gameCommand:"SIM_RATE_INCR",type:"command"},sim_rate_decr:{gameCommand:"SIM_RATE_DECR",type:"command"}}};var Fn={gameId:"xplane",name:"X-Plane 12",category:"flight_sim",fieldMappings:{lat:{canonical:"latitude"},lon:{canonical:"longitude"},alt_msl:{canonical:"altitude"},alt_agl:{canonical:"altitude_agl"},on_ground:{canonical:"on_ground",transform:"toBoolean"},ias:{canonical:"indicated_airspeed"},tas:{canonical:"true_airspeed"},gs:{canonical:"ground_speed"},mach:{canonical:"mach"},vvi:{canonical:"vertical_speed"},g_load:{canonical:"g_force"},hdg_mag:{canonical:"heading"},hdg_true:{canonical:"true_heading"},pitch:{canonical:"pitch"},roll:{canonical:"roll"},yaw:{canonical:"yaw"},throttle_0:{canonical:"throttle_0"},throttle_1:{canonical:"throttle_1"},throttle_2:{canonical:"throttle_2"},throttle_3:{canonical:"throttle_3"},rpm_0:{canonical:"rpm_0"},rpm_1:{canonical:"rpm_1"},rpm_2:{canonical:"rpm_2"},rpm_3:{canonical:"rpm_3"},n1_0:{canonical:"n1_0"},n1_1:{canonical:"n1_1"},n1_2:{canonical:"n1_2"},n1_3:{canonical:"n1_3"},n2_0:{canonical:"n2_0"},n2_1:{canonical:"n2_1"},n2_2:{canonical:"n2_2"},n2_3:{canonical:"n2_3"},egt_0:{canonical:"egt_0"},egt_1:{canonical:"egt_1"},egt_2:{canonical:"egt_2"},egt_3:{canonical:"egt_3"},fuel_total_lbs:{canonical:"fuel_quantity"},ff_0:{canonical:"fuel_flow_0"},ff_1:{canonical:"fuel_flow_1"},ff_2:{canonical:"fuel_flow_2"},ff_3:{canonical:"fuel_flow_3"},ap_master:{canonical:"autopilot_master",transform:"toBoolean"},ap_alt_hold:{canonical:"autopilot_altitude_hold",transform:"toBoolean"},ap_hdg_hold:{canonical:"autopilot_heading_hold",transform:"toBoolean"},ap_vs_hold:{canonical:"autopilot_vs_hold",transform:"toBoolean"},ap_spd_hold:{canonical:"autopilot_speed_hold",transform:"toBoolean"},ap_apr:{canonical:"autopilot_approach",transform:"toBoolean"},ap_nav:{canonical:"autopilot_nav",transform:"toBoolean"},fd_on:{canonical:"flight_director",transform:"toBoolean"},ap_alt_set:{canonical:"autopilot_altitude_target"},ap_hdg_set:{canonical:"autopilot_heading_target"},ap_vs_set:{canonical:"autopilot_vs_target"},ap_spd_set:{canonical:"autopilot_speed_target"},flap_ratio:{canonical:"flaps"},spoiler_ratio:{canonical:"spoilers"},gear_deploy:{canonical:"gear_down",transform:"toBoolean"},park_brake:{canonical:"parking_brake",transform:"toBoolean"},brake_left:{canonical:"brake_left"},brake_right:{canonical:"brake_right"},land_lights:{canonical:"light_landing",transform:"toBoolean"},taxi_lights:{canonical:"light_taxi",transform:"toBoolean"},beacon:{canonical:"light_beacon",transform:"toBoolean"},nav_lights:{canonical:"light_nav",transform:"toBoolean"},strobe:{canonical:"light_strobe",transform:"toBoolean"},oat:{canonical:"outside_air_temp"},baro_set:{canonical:"barometric_pressure"},wind_dir:{canonical:"wind_direction"},wind_spd:{canonical:"wind_speed"},stall:{canonical:"stall_warning",transform:"toBoolean"},overspeed:{canonical:"overspeed_warning",transform:"toBoolean"},paused:{canonical:"sim_paused",transform:"toBoolean"},gps_wp_distance:{canonical:"gps_wp_distance"},gps_wp_ete:{canonical:"gps_wp_ete"}},commandMappings:{autopilot_on:{gameCommand:"sim/autopilot/servos_on",type:"command"},autopilot_off:{gameCommand:"sim/autopilot/servos_off_any",type:"command"},autopilot_toggle:{gameCommand:"sim/autopilot/servos_toggle",type:"command"},autopilot_altitude_hold_on:{gameCommand:"sim/autopilot/altitude_hold",type:"command"},autopilot_altitude_hold_off:{gameCommand:"sim/autopilot/altitude_hold",type:"command"},autopilot_heading_hold_on:{gameCommand:"sim/autopilot/heading",type:"command"},autopilot_heading_hold_off:{gameCommand:"sim/autopilot/heading",type:"command"},autopilot_vs_hold_on:{gameCommand:"sim/autopilot/vertical_speed",type:"command"},autopilot_vs_hold_off:{gameCommand:"sim/autopilot/vertical_speed",type:"command"},autopilot_nav_on:{gameCommand:"sim/autopilot/NAV",type:"command"},autopilot_nav_off:{gameCommand:"sim/autopilot/NAV",type:"command"},autopilot_approach_on:{gameCommand:"sim/autopilot/approach",type:"command"},autopilot_approach_off:{gameCommand:"sim/autopilot/approach",type:"command"},flight_director_on:{gameCommand:"sim/autopilot/fdir_on",type:"command"},flight_director_off:{gameCommand:"sim/autopilot/fdir_toggle",type:"command"},autopilot_flc_on:{gameCommand:"sim/autopilot/level_change",type:"command"},autopilot_flc_off:{gameCommand:"sim/autopilot/level_change",type:"command"},autopilot_flc_toggle:{gameCommand:"sim/autopilot/level_change",type:"command"},set_autopilot_altitude:{gameCommand:"sim/cockpit/autopilot/altitude",type:"dataref"},set_autopilot_heading:{gameCommand:"sim/cockpit/autopilot/heading_mag",type:"dataref"},set_autopilot_vs:{gameCommand:"sim/cockpit/autopilot/vertical_velocity",type:"dataref"},set_autopilot_speed:{gameCommand:"sim/cockpit/autopilot/airspeed",type:"dataref"},gear_up:{gameCommand:"sim/flight_controls/landing_gear_up",type:"command"},gear_down:{gameCommand:"sim/flight_controls/landing_gear_down",type:"command"},gear_toggle:{gameCommand:"sim/flight_controls/landing_gear_toggle",type:"command"},flaps_up:{gameCommand:"sim/flight_controls/flaps_up",type:"command"},flaps_down:{gameCommand:"sim/flight_controls/flaps_down",type:"command"},flaps_full:{gameCommand:"sim/flight_controls/flaps_down",type:"command"},flaps_retract:{gameCommand:"sim/flight_controls/flaps_up",type:"command"},set_flaps:{gameCommand:"sim/cockpit2/controls/flap_ratio",type:"dataref"},spoilers_arm:{gameCommand:"sim/flight_controls/speed_brakes_down_one",type:"command"},spoilers_deploy:{gameCommand:"sim/flight_controls/speed_brakes_down_all",type:"command"},spoilers_retract:{gameCommand:"sim/flight_controls/speed_brakes_up_all",type:"command"},spoilers_toggle:{gameCommand:"sim/flight_controls/speed_brakes_toggle",type:"command"},parking_brake_toggle:{gameCommand:"sim/flight_controls/brakes_toggle_max",type:"command"},parking_brake_on:{gameCommand:"sim/flight_controls/brakes_max",type:"command"},parking_brake_off:{gameCommand:"sim/flight_controls/brakes_regular",type:"command"},set_throttle:{gameCommand:"sim/cockpit2/engine/actuators/throttle_ratio_all",type:"dataref"},set_throttle_0:{gameCommand:"sim/cockpit2/engine/actuators/throttle_ratio[0]",type:"dataref"},set_throttle_1:{gameCommand:"sim/cockpit2/engine/actuators/throttle_ratio[1]",type:"dataref"},set_throttle_2:{gameCommand:"sim/cockpit2/engine/actuators/throttle_ratio[2]",type:"dataref"},set_throttle_3:{gameCommand:"sim/cockpit2/engine/actuators/throttle_ratio[3]",type:"dataref"},throttle_full:{gameCommand:"sim/engines/throttle_up",type:"command"},throttle_idle:{gameCommand:"sim/engines/throttle_down",type:"command"},throttle_cutoff:{gameCommand:"sim/starters/shut_down",type:"command"},landing_lights_on:{gameCommand:"sim/lights/landing_lights_on",type:"command"},landing_lights_off:{gameCommand:"sim/lights/landing_lights_off",type:"command"},landing_lights_toggle:{gameCommand:"sim/lights/landing_lights_toggle",type:"command"},taxi_lights_on:{gameCommand:"sim/lights/taxi_lights_on",type:"command"},taxi_lights_off:{gameCommand:"sim/lights/taxi_lights_off",type:"command"},taxi_lights_toggle:{gameCommand:"sim/lights/taxi_lights_toggle",type:"command"},beacon_lights_on:{gameCommand:"sim/lights/beacon_lights_on",type:"command"},beacon_lights_off:{gameCommand:"sim/lights/beacon_lights_off",type:"command"},beacon_lights_toggle:{gameCommand:"sim/lights/beacon_lights_toggle",type:"command"},nav_lights_on:{gameCommand:"sim/lights/nav_lights_on",type:"command"},nav_lights_off:{gameCommand:"sim/lights/nav_lights_off",type:"command"},nav_lights_toggle:{gameCommand:"sim/lights/nav_lights_toggle",type:"command"},strobe_lights_on:{gameCommand:"sim/lights/strobe_lights_on",type:"command"},strobe_lights_off:{gameCommand:"sim/lights/strobe_lights_off",type:"command"},strobe_lights_toggle:{gameCommand:"sim/lights/strobe_lights_toggle",type:"command"},pause:{gameCommand:"sim/operation/pause_on",type:"command"},unpause:{gameCommand:"sim/operation/pause_off",type:"command"},pause_toggle:{gameCommand:"sim/operation/pause_toggle",type:"command"}}};const Dn={msfs:{gameId:Mn.gameId,name:Mn.name,category:Mn.category,fieldMappings:Mn.fieldMappings,commandMappings:Mn.commandMappings,extraFields:{pitot_heat:{type:"boolean",description:"Pitot heat active",group:"Systems"},fuel_quantity_gallons:{type:"number",description:"Total fuel in gallons",unit:"gal",min:0,max:1e5,group:"Fuel"},fuel_flow_gph_1:{type:"number",description:"Engine 1 fuel flow in GPH",unit:"gal/hr",min:0,max:5e3,group:"Fuel"},fuel_flow_gph_2:{type:"number",description:"Engine 2 fuel flow in GPH",unit:"gal/hr",min:0,max:5e3,group:"Fuel"},fuel_flow_gph_3:{type:"number",description:"Engine 3 fuel flow in GPH",unit:"gal/hr",min:0,max:5e3,group:"Fuel"},fuel_flow_gph_4:{type:"number",description:"Engine 4 fuel flow in GPH",unit:"gal/hr",min:0,max:5e3,group:"Fuel"},flaps_left_percent:{type:"number",description:"Left flaps position",unit:"%",min:0,max:100,group:"Controls"},flaps_right_percent:{type:"number",description:"Right flaps position",unit:"%",min:0,max:100,group:"Controls"},spoilers_left_percent:{type:"number",description:"Left spoilers position",unit:"%",min:0,max:100,group:"Controls"},spoilers_right_percent:{type:"number",description:"Right spoilers position",unit:"%",min:0,max:100,group:"Controls"},gear_left_position:{type:"number",description:"Left gear position",unit:"%",min:0,max:100,group:"Controls"},gear_center_position:{type:"number",description:"Center gear position",unit:"%",min:0,max:100,group:"Controls"},gear_right_position:{type:"number",description:"Right gear position",unit:"%",min:0,max:100,group:"Controls"},ambient_pressure:{type:"number",description:"Ambient pressure",unit:"inHg",min:20,max:35,group:"Environment"},sea_level_pressure:{type:"number",description:"Sea level pressure",unit:"inHg",min:27,max:32,group:"Environment"},aircraft_wind_x:{type:"number",description:"Wind component X-axis",unit:"kts",min:-200,max:200,group:"Environment"},aircraft_wind_y:{type:"number",description:"Wind component Y-axis",unit:"kts",min:-200,max:200,group:"Environment"},aircraft_wind_z:{type:"number",description:"Wind component Z-axis",unit:"kts",min:-200,max:200,group:"Environment"}}},xplane:{gameId:Fn.gameId,name:Fn.name,category:Fn.category,fieldMappings:Fn.fieldMappings,commandMappings:Fn.commandMappings,extraFields:{replay_mode:{type:"boolean",description:"Replay mode active",group:"Simulation"},time_local:{type:"number",description:"Local time in seconds since midnight",unit:"sec",min:0,max:86400,group:"Simulation"},time_zulu:{type:"number",description:"Zulu time in seconds since midnight",unit:"sec",min:0,max:86400,group:"Simulation"}}}};function Hn(t){return Dn[t]}function Gn(t,e){const n={};for(const[i,o]of Object.entries(t)){const t=e.fieldMappings[i];if(t){let e=o;if(t.transform&&t.transform in Bn){e=(0,Bn[t.transform])(o)}n[t.canonical]=e}else e.extraFields?.[i]&&(n[`${e.gameId}:${i}`]=o)}return n}class Vn{constructor(t,e){this._config=e,this._socket=t,this._callbacks=[],this._fields=e.fields?[...e.fields]:null,this._gameSchema=Hn(e.gameId)}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,n)=>e?t({status:"failed",reason:"Listen request timed out."}):"success"===n.status?t({status:"success"}):t({status:"failed",reason:n.reason}))})}setupEventListener(){return this._socket.on("update",t=>{if(t?.gameId&&t.gameId!==this._config.gameId)return;const e=t?.data,n=e&&this._gameSchema?Gn(e,this._gameSchema):e;let i=n;if(this._fields&&this._fields.length>0&&n){i={};for(const t of this._fields)t in n&&(i[t]=n[t])}this.emit("update",{...t,raw:e,data:i})}),this._socket.on("key-events",t=>{const{gameId:e,eventType:n,data:i}=t||{};e===this._config.gameId&&n&&i&&this.emit(n,i)}),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("command must be a non-empty string");return new Promise(n=>{const i={userId:this._config.userId,gameId:this._config.gameId,data:{fieldName:t,value:e}};this._socket.timeout(5e3).emit("set",i,(t,e)=>n(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,n)=>t(e?{status:"failed",reason:"Update request timed out."}:n))})}}Nn(Vn.prototype);class zn{constructor(t,e){this._config=e,this._socket=t,this._gameSchema=Hn(e.gameId),this._broadcasters=[]}async establishConnection(){if(!this._socket||!this._config.clientId||!this._config.gameId)throw new Error("Missing arguments in establishConnection");return new Promise(t=>{const e={clientId:this._config.clientId,gameId:this._config.gameId};this._socket.timeout(5e3).emit("presenceSubscribe",e,(e,n)=>{if(e)return t({status:"failed",reason:"Presence request timed out."});if("success"===n?.status){const e=Array.isArray(n.broadcasters)?n.broadcasters.map(t=>this._normalizeSnapshot(t)):[];return this._broadcasters=e,t({status:"success",broadcasters:e})}return t({status:"failed",reason:n?.reason||"Presence subscription failed."})})})}setupEventListener(){return this._socket.on("presence-update",t=>{const e=this._normalizeSnapshot(t);this._upsertBroadcaster(e),this.emit("update",e)}),this._socket.on("presence-remove",({userId:t})=>{t&&(this._broadcasters=this._broadcasters.filter(e=>e.userId!==t),this.emit("remove",{userId:t}))}),this._socket.on("connect",()=>{this.emit("connect")}),this._socket.on("disconnect",t=>{this.emit("disconnect",t)}),this}getBroadcasters(){return[...this._broadcasters]}disconnect(){this._socket&&this._socket.disconnect()}_normalizeSnapshot(t){if(!t||"object"!=typeof t)return t;const e=t.data,n=e&&this._gameSchema?Gn(e,this._gameSchema):e;return{...t,data:n,raw:e}}_upsertBroadcaster(t){if(!t||!t.userId)return;const e=this._broadcasters.findIndex(e=>e.userId===t.userId);if(e>=0){const n=[...this._broadcasters];return n[e]=t,void(this._broadcasters=n)}this._broadcasters=[...this._broadcasters,t]}}Nn(zn.prototype);const $n={msfs:!0,xplane:!0};class Wn extends ht{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||!$n[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 Vn(this._socket,t),n=await e.establishConnection();if(this._socket.io.on("reconnect_attempt",()=>{this._updateSocketAuth(this.getAccessToken())}),this._socket.io.on("reconnect",()=>{e.establishConnection()}),"success"!==n.status)throw new Error(`There was a problem setting up the listener. Reason: ${n.reason}`);return e.setupEventListener()}async createPresenceListener(t){if(!t)throw new Error("Not a valid presence listener config");if(!t.gameId||!$n[t.gameId])throw new Error("Not a valid Game ID");if(!t.clientId)throw new Error("Client ID not supplied");const e=Ne(this._socketUrl,{transports:["websocket"]});await new Promise((t,n)=>{e.on("connect",t),e.on("connect_error",t=>{at(t)&&ct("WebSocket Connection",this._socketUrl),n(new Error(`Socket connection failed: ${t.message}`))})});const n=new zn(e,t),i=await n.establishConnection();if(e.io.on("reconnect",()=>{n.establishConnection()}),"success"!==i.status)throw new Error(`There was a problem setting up the presence listener. Reason: ${i.reason}`);return n.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 n=this.getAccessToken();n?(this._socket=Ne(this._socketUrl,{transports:["websocket"],auth:{token:n}}),this._socket.on("connect",()=>{t()}),this._socket.on("connect_error",t=>{at(t)&&ct("WebSocket Connection",this._socketUrl),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=Wn,window.GameGlueSchemas={getGameSchema:Hn,getCategorySchema:jn,normalizeTelemetry:Gn}),t.GameGlue=Wn,t.default=Wn,t.getCategorySchema=jn,t.getGameSchema=Hn,t.normalizeTelemetry=Gn,Object.defineProperty(t,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=gg.umd.js.map