gameglue 1.2.2 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +79 -16
- package/dist/gg.cjs.js +1 -1
- package/dist/gg.cjs.js.map +1 -1
- package/dist/gg.esm.js +1 -1
- package/dist/gg.esm.js.map +1 -1
- package/dist/gg.umd.js +1 -1
- package/dist/gg.umd.js.map +1 -1
- package/examples/flight-dashboard.html +69 -39
- package/package.json +1 -1
- package/src/auth.js +187 -86
- package/src/auth.spec.js +167 -77
- package/src/index.js +82 -44
- package/src/listener.js +16 -2
- package/src/listener.spec.js +139 -0
- package/src/test/setup.js +2 -1
- package/src/utils.js +3 -0
- package/src/utils.spec.js +14 -0
- package/dist/gg.sdk.js +0 -1
- /package/{babel.config.js → babel.config.cjs} +0 -0
- /package/{jest.config.js → jest.config.cjs} +0 -0
package/src/listener.spec.js
CHANGED
|
@@ -120,6 +120,145 @@ describe('Listener', () => {
|
|
|
120
120
|
expect(mockSocket.on).toHaveBeenCalledWith('update', expect.any(Function));
|
|
121
121
|
expect(result).toBe(listener);
|
|
122
122
|
});
|
|
123
|
+
|
|
124
|
+
it('should filter update payload to subscribed fields only', () => {
|
|
125
|
+
const emitSpy = jest.fn();
|
|
126
|
+
listener.emit = emitSpy;
|
|
127
|
+
listener.setupEventListener();
|
|
128
|
+
|
|
129
|
+
// Simulate server sending full telemetry payload
|
|
130
|
+
const fullPayload = {
|
|
131
|
+
data: {
|
|
132
|
+
altitude: 35000,
|
|
133
|
+
airspeed: 250,
|
|
134
|
+
heading: 180,
|
|
135
|
+
fuel: 5000,
|
|
136
|
+
temperature: 25
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
// Trigger the update event
|
|
141
|
+
mockSocket._trigger('update', fullPayload);
|
|
142
|
+
|
|
143
|
+
// Should only receive subscribed fields: altitude, airspeed, heading
|
|
144
|
+
expect(emitSpy).toHaveBeenCalledWith('update', {
|
|
145
|
+
data: {
|
|
146
|
+
altitude: 35000,
|
|
147
|
+
airspeed: 250,
|
|
148
|
+
heading: 180
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it('should pass through full payload when no fields specified', () => {
|
|
154
|
+
const configNoFields = { gameId: 'msfs', userId: 'user-123' };
|
|
155
|
+
const listenerNoFields = new Listener(mockSocket, configNoFields);
|
|
156
|
+
const emitSpy = jest.fn();
|
|
157
|
+
listenerNoFields.emit = emitSpy;
|
|
158
|
+
listenerNoFields.setupEventListener();
|
|
159
|
+
|
|
160
|
+
const fullPayload = {
|
|
161
|
+
data: {
|
|
162
|
+
altitude: 35000,
|
|
163
|
+
airspeed: 250,
|
|
164
|
+
fuel: 5000
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
mockSocket._trigger('update', fullPayload);
|
|
169
|
+
|
|
170
|
+
// Should receive all fields
|
|
171
|
+
expect(emitSpy).toHaveBeenCalledWith('update', fullPayload);
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
it('should handle payload with missing subscribed fields', () => {
|
|
175
|
+
const emitSpy = jest.fn();
|
|
176
|
+
listener.emit = emitSpy;
|
|
177
|
+
listener.setupEventListener();
|
|
178
|
+
|
|
179
|
+
// Server sends partial data (missing some subscribed fields)
|
|
180
|
+
const partialPayload = {
|
|
181
|
+
data: {
|
|
182
|
+
altitude: 35000
|
|
183
|
+
// airspeed and heading missing
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
mockSocket._trigger('update', partialPayload);
|
|
188
|
+
|
|
189
|
+
// Should only include fields that exist in payload
|
|
190
|
+
expect(emitSpy).toHaveBeenCalledWith('update', {
|
|
191
|
+
data: {
|
|
192
|
+
altitude: 35000
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
it('should handle empty data payload', () => {
|
|
198
|
+
const emitSpy = jest.fn();
|
|
199
|
+
listener.emit = emitSpy;
|
|
200
|
+
listener.setupEventListener();
|
|
201
|
+
|
|
202
|
+
const emptyPayload = { data: {} };
|
|
203
|
+
mockSocket._trigger('update', emptyPayload);
|
|
204
|
+
|
|
205
|
+
expect(emitSpy).toHaveBeenCalledWith('update', { data: {} });
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
it('should handle null/undefined data gracefully', () => {
|
|
209
|
+
const emitSpy = jest.fn();
|
|
210
|
+
listener.emit = emitSpy;
|
|
211
|
+
listener.setupEventListener();
|
|
212
|
+
|
|
213
|
+
const nullPayload = { data: null };
|
|
214
|
+
mockSocket._trigger('update', nullPayload);
|
|
215
|
+
|
|
216
|
+
// Should pass through when data is null
|
|
217
|
+
expect(emitSpy).toHaveBeenCalledWith('update', nullPayload);
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
it('should preserve other payload properties when filtering', () => {
|
|
221
|
+
const emitSpy = jest.fn();
|
|
222
|
+
listener.emit = emitSpy;
|
|
223
|
+
listener.setupEventListener();
|
|
224
|
+
|
|
225
|
+
const payloadWithMeta = {
|
|
226
|
+
data: { altitude: 35000, fuel: 5000 },
|
|
227
|
+
timestamp: 1234567890,
|
|
228
|
+
sequence: 42
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
mockSocket._trigger('update', payloadWithMeta);
|
|
232
|
+
|
|
233
|
+
expect(emitSpy).toHaveBeenCalledWith('update', {
|
|
234
|
+
data: { altitude: 35000 },
|
|
235
|
+
timestamp: 1234567890,
|
|
236
|
+
sequence: 42
|
|
237
|
+
});
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
it('should reflect field changes after subscribe/unsubscribe', async () => {
|
|
241
|
+
const emitSpy = jest.fn();
|
|
242
|
+
listener.emit = emitSpy;
|
|
243
|
+
listener.setupEventListener();
|
|
244
|
+
|
|
245
|
+
// Add a new field
|
|
246
|
+
await listener.subscribe(['fuel']);
|
|
247
|
+
|
|
248
|
+
const payload = {
|
|
249
|
+
data: { altitude: 35000, fuel: 5000, temperature: 25 }
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
mockSocket._trigger('update', payload);
|
|
253
|
+
|
|
254
|
+
// Should now include fuel
|
|
255
|
+
expect(emitSpy).toHaveBeenCalledWith('update', {
|
|
256
|
+
data: {
|
|
257
|
+
altitude: 35000,
|
|
258
|
+
fuel: 5000
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
});
|
|
123
262
|
});
|
|
124
263
|
|
|
125
264
|
describe('subscribe', () => {
|
package/src/test/setup.js
CHANGED
|
@@ -32,8 +32,9 @@ Object.defineProperty(global, 'localStorage', {
|
|
|
32
32
|
writable: true
|
|
33
33
|
});
|
|
34
34
|
|
|
35
|
-
// Mock window.history.pushState
|
|
35
|
+
// Mock window.history.pushState and replaceState
|
|
36
36
|
window.history.pushState = jest.fn();
|
|
37
|
+
window.history.replaceState = jest.fn();
|
|
37
38
|
|
|
38
39
|
// Reset mocks and store before each test
|
|
39
40
|
beforeEach(() => {
|
package/src/utils.js
CHANGED
|
@@ -5,6 +5,9 @@ export const storage = {
|
|
|
5
5
|
},
|
|
6
6
|
get: (key) => {
|
|
7
7
|
return isBrowser() ? localStorage.getItem(key) : storageMap[key];
|
|
8
|
+
},
|
|
9
|
+
remove: (key) => {
|
|
10
|
+
return isBrowser() ? localStorage.removeItem(key) : delete storageMap[key];
|
|
8
11
|
}
|
|
9
12
|
};
|
|
10
13
|
export const isBrowser = () => {
|
package/src/utils.spec.js
CHANGED
|
@@ -59,6 +59,20 @@ describe('utils', () => {
|
|
|
59
59
|
expect(result).toBeUndefined();
|
|
60
60
|
});
|
|
61
61
|
});
|
|
62
|
+
|
|
63
|
+
describe('remove', () => {
|
|
64
|
+
it('should remove a stored value', () => {
|
|
65
|
+
storage.set('remove-key', 'remove-value');
|
|
66
|
+
expect(storage.get('remove-key')).toBe('remove-value');
|
|
67
|
+
|
|
68
|
+
storage.remove('remove-key');
|
|
69
|
+
expect(storage.get('remove-key')).toBeUndefined();
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it('should not throw when removing non-existent key', () => {
|
|
73
|
+
expect(() => storage.remove('non-existent-key-' + Date.now())).not.toThrow();
|
|
74
|
+
});
|
|
75
|
+
});
|
|
62
76
|
});
|
|
63
77
|
});
|
|
64
78
|
});
|
package/dist/gg.sdk.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.GameGlue=e():t.GameGlue=e()}(this,()=>(()=>{var t={9(t,e,s){var r;t.exports=(r=s(21),function(t){var e=r,s=e.lib,i=s.WordArray,n=s.Hasher,o=e.algo,a=[],c=[];!function(){function e(e){for(var s=t.sqrt(e),r=2;r<=s;r++)if(!(e%r))return!1;return!0}function s(t){return 4294967296*(t-(0|t))|0}for(var r=2,i=0;i<64;)e(r)&&(i<8&&(a[i]=s(t.pow(r,.5))),c[i]=s(t.pow(r,1/3)),i++),r++}();var h=[],u=o.SHA256=n.extend({_doReset:function(){this._hash=new i.init(a.slice(0))},_doProcessBlock:function(t,e){for(var s=this._hash.words,r=s[0],i=s[1],n=s[2],o=s[3],a=s[4],u=s[5],l=s[6],d=s[7],p=0;p<64;p++){if(p<16)h[p]=0|t[e+p];else{var f=h[p-15],g=(f<<25|f>>>7)^(f<<14|f>>>18)^f>>>3,_=h[p-2],y=(_<<15|_>>>17)^(_<<13|_>>>19)^_>>>10;h[p]=g+h[p-7]+y+h[p-16]}var m=r&i^r&n^i&n,w=(r<<30|r>>>2)^(r<<19|r>>>13)^(r<<10|r>>>22),b=d+((a<<26|a>>>6)^(a<<21|a>>>11)^(a<<7|a>>>25))+(a&u^~a&l)+c[p]+h[p];d=l,l=u,u=a,a=o+b|0,o=n,n=i,i=r,r=b+(w+m)|0}s[0]=s[0]+r|0,s[1]=s[1]+i|0,s[2]=s[2]+n|0,s[3]=s[3]+o|0,s[4]=s[4]+a|0,s[5]=s[5]+u|0,s[6]=s[6]+l|0,s[7]=s[7]+d|0},_doFinalize:function(){var e=this._data,s=e.words,r=8*this._nDataBytes,i=8*e.sigBytes;return s[i>>>5]|=128<<24-i%32,s[14+(i+64>>>9<<4)]=t.floor(r/4294967296),s[15+(i+64>>>9<<4)]=r,e.sigBytes=4*s.length,this._process(),this._hash},clone:function(){var t=n.clone.call(this);return t._hash=this._hash.clone(),t}});e.SHA256=n._createHelper(u),e.HmacSHA256=n._createHmacHelper(u)}(Math),r.SHA256)},11(t){"use strict";t.exports=function(){}},21(t,e,s){var r;t.exports=(r=r||function(t){var e;if("undefined"!=typeof window&&window.crypto&&(e=window.crypto),"undefined"!=typeof self&&self.crypto&&(e=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(e=globalThis.crypto),!e&&"undefined"!=typeof window&&window.msCrypto&&(e=window.msCrypto),!e&&void 0!==s.g&&s.g.crypto&&(e=s.g.crypto),!e)try{e=s(477)}catch(t){}var r=function(){if(e){if("function"==typeof e.getRandomValues)try{return e.getRandomValues(new Uint32Array(1))[0]}catch(t){}if("function"==typeof e.randomBytes)try{return e.randomBytes(4).readInt32LE()}catch(t){}}throw new Error("Native crypto module could not be used to get secure random number.")},i=Object.create||function(){function t(){}return function(e){var s;return t.prototype=e,s=new t,t.prototype=null,s}}(),n={},o=n.lib={},a=o.Base={extend:function(t){var e=i(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)}},c=o.WordArray=a.extend({init:function(t,e){t=this.words=t||[],this.sigBytes=null!=e?e:4*t.length},toString:function(t){return(t||u).stringify(this)},concat:function(t){var e=this.words,s=t.words,r=this.sigBytes,i=t.sigBytes;if(this.clamp(),r%4)for(var n=0;n<i;n++){var o=s[n>>>2]>>>24-n%4*8&255;e[r+n>>>2]|=o<<24-(r+n)%4*8}else for(var a=0;a<i;a+=4)e[r+a>>>2]=s[a>>>2];return this.sigBytes+=i,this},clamp:function(){var e=this.words,s=this.sigBytes;e[s>>>2]&=4294967295<<32-s%4*8,e.length=t.ceil(s/4)},clone:function(){var t=a.clone.call(this);return t.words=this.words.slice(0),t},random:function(t){for(var e=[],s=0;s<t;s+=4)e.push(r());return new c.init(e,t)}}),h=n.enc={},u=h.Hex={stringify:function(t){for(var e=t.words,s=t.sigBytes,r=[],i=0;i<s;i++){var n=e[i>>>2]>>>24-i%4*8&255;r.push((n>>>4).toString(16)),r.push((15&n).toString(16))}return r.join("")},parse:function(t){for(var e=t.length,s=[],r=0;r<e;r+=2)s[r>>>3]|=parseInt(t.substr(r,2),16)<<24-r%8*4;return new c.init(s,e/2)}},l=h.Latin1={stringify:function(t){for(var e=t.words,s=t.sigBytes,r=[],i=0;i<s;i++){var n=e[i>>>2]>>>24-i%4*8&255;r.push(String.fromCharCode(n))}return r.join("")},parse:function(t){for(var e=t.length,s=[],r=0;r<e;r++)s[r>>>2]|=(255&t.charCodeAt(r))<<24-r%4*8;return new c.init(s,e)}},d=h.Utf8={stringify:function(t){try{return decodeURIComponent(escape(l.stringify(t)))}catch(t){throw new Error("Malformed UTF-8 data")}},parse:function(t){return l.parse(unescape(encodeURIComponent(t)))}},p=o.BufferedBlockAlgorithm=a.extend({reset:function(){this._data=new c.init,this._nDataBytes=0},_append:function(t){"string"==typeof t&&(t=d.parse(t)),this._data.concat(t),this._nDataBytes+=t.sigBytes},_process:function(e){var s,r=this._data,i=r.words,n=r.sigBytes,o=this.blockSize,a=n/(4*o),h=(a=e?t.ceil(a):t.max((0|a)-this._minBufferSize,0))*o,u=t.min(4*h,n);if(h){for(var l=0;l<h;l+=o)this._doProcessBlock(i,l);s=i.splice(0,h),r.sigBytes-=u}return new c.init(s,u)},clone:function(){var t=a.clone.call(this);return t._data=this._data.clone(),t},_minBufferSize:0}),f=(o.Hasher=p.extend({cfg:a.extend(),init:function(t){this.cfg=this.cfg.extend(t),this.reset()},reset:function(){p.reset.call(this),this._doReset()},update:function(t){return this._append(t),this._process(),this},finalize:function(t){return t&&this._append(t),this._doFinalize()},blockSize:16,_createHelper:function(t){return function(e,s){return new t.init(s).finalize(e)}},_createHmacHelper:function(t){return function(e,s){return new f.HMAC.init(t,s).finalize(e)}}}),n.algo={});return n}(Math),r)},68(t,e,s){"use strict";var r,i,n,o,a,c,h,u=s(263),l=s(499),d=Function.prototype.apply,p=Function.prototype.call,f=Object.create,g=Object.defineProperty,_=Object.defineProperties,y=Object.prototype.hasOwnProperty,m={configurable:!0,enumerable:!1,writable:!0};i=function(t,e){var s,i;return l(e),i=this,r.call(this,t,s=function(){n.call(i,t,s),d.call(e,this,arguments)}),s.__eeOnceListener__=e,this},o=function(t){var e,s,r,i,n;if(y.call(this,"__ee__")&&(i=this.__ee__[t]))if("object"==typeof i){for(s=arguments.length,n=new Array(s-1),e=1;e<s;++e)n[e-1]=arguments[e];for(i=i.slice(),e=0;r=i[e];++e)d.call(r,this,n)}else switch(arguments.length){case 1:p.call(i,this);break;case 2:p.call(i,this,arguments[1]);break;case 3:p.call(i,this,arguments[1],arguments[2]);break;default:for(s=arguments.length,n=new Array(s-1),e=1;e<s;++e)n[e-1]=arguments[e];d.call(i,this,n)}},a={on:r=function(t,e){var s;return l(e),y.call(this,"__ee__")?s=this.__ee__:(s=m.value=f(null),g(this,"__ee__",m),m.value=null),s[t]?"object"==typeof s[t]?s[t].push(e):s[t]=[s[t],e]:s[t]=e,this},once:i,off:n=function(t,e){var s,r,i,n;if(l(e),!y.call(this,"__ee__"))return this;if(!(s=this.__ee__)[t])return this;if("object"==typeof(r=s[t]))for(n=0;i=r[n];++n)i!==e&&i.__eeOnceListener__!==e||(2===r.length?s[t]=r[n?0:1]:r.splice(n,1));else r!==e&&r.__eeOnceListener__!==e||delete s[t];return this},emit:o},c={on:u(r),once:u(i),off:u(n),emit:u(o)},h=_({},c),t.exports=e=function(t){return null==t?f(h):_(Object(t),c)},e.methods=a},80(t,e,s){"use strict";var r=s(202);t.exports=function(t){if("function"!=typeof t)return!1;if(!hasOwnProperty.call(t,"length"))return!1;try{if("number"!=typeof t.length)return!1;if("function"!=typeof t.call)return!1;if("function"!=typeof t.apply)return!1}catch(t){return!1}return!r(t)}},93(t,e,s){"use strict";t.exports=s(380)()?Object.keys:s(232)},134(t,e,s){"use strict";var r=s(762);t.exports=function(t){if(!r(t))throw new TypeError("Cannot use null or undefined");return t}},148(t,e,s){"use strict";var r=s(762),i=Array.prototype.forEach,n=Object.create;t.exports=function(t){var e=n(null);return i.call(arguments,function(t){r(t)&&function(t,e){var s;for(s in t)e[s]=t[s]}(Object(t),e)}),e}},175(t){"use strict";t.exports=function(t){return null!=t}},178(t,e,s){t.exports=s(21).enc.Utf8},181(t,e,s){"use strict";var r=s(175),i={object:!0,function:!0,undefined:!0};t.exports=function(t){return!!r(t)&&hasOwnProperty.call(i,typeof t)}},202(t,e,s){"use strict";var r=s(181);t.exports=function(t){if(!r(t))return!1;try{return!!t.constructor&&t.constructor.prototype===t}catch(t){return!1}}},214(t,e,s){"use strict";t.exports=s(525)()?String.prototype.contains:s(521)},232(t,e,s){"use strict";var r=s(762),i=Object.keys;t.exports=function(t){return i(r(t)?Object(t):t)}},263(t,e,s){"use strict";var r=s(175),i=s(873),n=s(596),o=s(148),a=s(214),c=t.exports=function(t,e){var s,i,c,h,u;return arguments.length<2||"string"!=typeof t?(h=e,e=t,t=null):h=arguments[2],r(t)?(s=a.call(t,"c"),i=a.call(t,"e"),c=a.call(t,"w")):(s=c=!0,i=!1),u={value:e,configurable:s,enumerable:i,writable:c},h?n(o(h),u):u};c.gs=function(t,e,s){var c,h,u,l;return"string"!=typeof t?(u=s,s=e,e=t,t=null):u=arguments[3],r(e)?i(e)?r(s)?i(s)||(u=s,s=void 0):s=void 0:(u=e,e=s=void 0):e=void 0,r(t)?(c=a.call(t,"c"),h=a.call(t,"e")):(c=!0,h=!1),l={get:e,set:s,configurable:c,enumerable:h},u?n(o(u),l):l}},339(t){"use strict";t.exports=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")}},380(t){"use strict";t.exports=function(){try{return Object.keys("primitive"),!0}catch(t){return!1}}},477(){},499(t){"use strict";t.exports=function(t){if("function"!=typeof t)throw new TypeError(t+" is not a function");return t}},521(t){"use strict";var e=String.prototype.indexOf;t.exports=function(t){return e.call(this,t,arguments[1])>-1}},525(t){"use strict";var e="razdwatrzy";t.exports=function(){return"function"==typeof e.contains&&!0===e.contains("dwa")&&!1===e.contains("foo")}},595(t,e,s){"use strict";var r=s(93),i=s(134),n=Math.max;t.exports=function(t,e){var s,o,a,c=n(arguments.length,2);for(t=Object(i(t)),a=function(r){try{t[r]=e[r]}catch(t){s||(s=t)}},o=1;o<c;++o)r(e=arguments[o]).forEach(a);if(void 0!==s)throw s;return t}},596(t,e,s){"use strict";t.exports=s(339)()?Object.assign:s(595)},754(t,e,s){var r,i,n;t.exports=(r=s(21),n=(i=r).lib.WordArray,i.enc.Base64={stringify:function(t){var e=t.words,s=t.sigBytes,r=this._map;t.clamp();for(var i=[],n=0;n<s;n+=3)for(var o=(e[n>>>2]>>>24-n%4*8&255)<<16|(e[n+1>>>2]>>>24-(n+1)%4*8&255)<<8|e[n+2>>>2]>>>24-(n+2)%4*8&255,a=0;a<4&&n+.75*a<s;a++)i.push(r.charAt(o>>>6*(3-a)&63));var c=r.charAt(64);if(c)for(;i.length%4;)i.push(c);return i.join("")},parse:function(t){var e=t.length,s=this._map,r=this._reverseMap;if(!r){r=this._reverseMap=[];for(var i=0;i<s.length;i++)r[s.charCodeAt(i)]=i}var o=s.charAt(64);if(o){var a=t.indexOf(o);-1!==a&&(e=a)}return function(t,e,s){for(var r=[],i=0,o=0;o<e;o++)if(o%4){var a=s[t.charCodeAt(o-1)]<<o%4*2|s[t.charCodeAt(o)]>>>6-o%4*2;r[i>>>2]|=a<<24-i%4*8,i++}return n.create(r,i)}(t,e,r)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},r.enc.Base64)},762(t,e,s){"use strict";var r=s(11)();t.exports=function(t){return t!==r&&null!==t}},873(t,e,s){"use strict";var r=s(80),i=/^\s*class[\s{/}]/,n=Function.prototype.toString;t.exports=function(t){return!!r(t)&&!i.test(n.call(t))}}},e={};function s(r){var i=e[r];if(void 0!==i)return i.exports;var n=e[r]={exports:{}};return t[r].call(n.exports,n,n.exports,s),n.exports}s.d=(t,e)=>{for(var r in e)s.o(e,r)&&!s.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},s.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),s.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),s.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var r={};return(()=>{"use strict";s.d(r,{default:()=>ve});var t={};s.r(t),s.d(t,{Decoder:()=>ne,Encoder:()=>ie,PacketType:()=>re,isPacketValid:()=>he,protocol:()=>se});var e=s(21),i=s(9),n=s(754),o=s(178);function a(t){this.message=t}a.prototype=new Error,a.prototype.name="InvalidCharacterError";var c="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new a("'atob' failed: The string to be decoded is not correctly encoded.");for(var s,r,i=0,n=0,o="";r=e.charAt(n++);~r&&(s=i%4?64*s+r:r,i++%4)?o+=String.fromCharCode(255&s>>(-2*i&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return o};function h(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(c(t).replace(/(.)/g,function(t,e){var s=e.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(e)}catch(t){return c(e)}}function u(t){this.message=t}u.prototype=new Error,u.prototype.name="InvalidTokenError";const l=function(t,e){if("string"!=typeof t)throw new u("Invalid token specified");var s=!0===(e=e||{}).header?0:1;try{return JSON.parse(h(t.split(".")[s]))}catch(t){throw new u("Invalid token specified: "+t.message)}};var d,p,f,g={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},_=(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))(_||{});(f=_||(_={})).reset=function(){d=3,p=g},f.setLevel=function(t){if(!(0<=t&&t<=4))throw new Error("Invalid log level");d=t},f.setLogger=function(t){p=t};var y=class{constructor(t){this._name=t}debug(...t){d>=4&&p.debug(y._format(this._name,this._method),...t)}info(...t){d>=3&&p.info(y._format(this._name,this._method),...t)}warn(...t){d>=2&&p.warn(y._format(this._name,this._method),...t)}error(...t){d>=1&&p.error(y._format(this._name,this._method),...t)}throw(t){throw this.error(t),t}create(t){const e=Object.create(this);return e._method=t,e.debug("begin"),e}static createStatic(t,e){const s=new y(`${t}.${e}`);return s.debug("begin"),s}static _format(t,e){const s=`[${t}]`;return e?`${s} ${e}:`:s}static debug(t,...e){d>=4&&p.debug(y._format(t),...e)}static info(t,...e){d>=3&&p.info(y._format(t),...e)}static warn(t,...e){d>=2&&p.warn(y._format(t),...e)}static error(t,...e){d>=1&&p.error(y._format(t),...e)}};_.reset();var m=class{static _randomWord(){return e.lib.WordArray.random(1).words[0]}static generateUUIDv4(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,t=>(+t^m._randomWord()&15>>+t/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return m.generateUUIDv4()+m.generateUUIDv4()+m.generateUUIDv4()}static generateCodeChallenge(t){try{const e=i(t);return n.stringify(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw y.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(t,e){const s=o.parse([t,e].join(":"));return n.stringify(s)}},w=class{constructor(t){this._name=t,this._logger=new y(`Event('${this._name}')`),this._callbacks=[]}addHandler(t){return this._callbacks.push(t),()=>this.removeHandler(t)}removeHandler(t){const e=this._callbacks.lastIndexOf(t);e>=0&&this._callbacks.splice(e,1)}raise(...t){this._logger.debug("raise:",...t);for(const e of this._callbacks)e(...t)}},b=class{static decode(t){try{return l(t)}catch(t){throw y.error("JwtUtils.decode",t),t}}},v=class extends w{constructor(){super(...arguments),this._logger=new y(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const t=this._expiration-v.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=v.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){const e=this._logger.create("init");t=Math.max(Math.floor(t),1);const s=v.getEpochTime()+t;if(this.expiration===s&&this._timerHandle)return void e.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),e.debug("using duration",t),this._expiration=s;const r=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*r)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},k=class{static readParams(t,e="query"){if(!t)throw new TypeError("Invalid URL");const s=new URL(t,window.location.origin)["fragment"===e?"hash":"search"];return new URLSearchParams(s.slice(1))}},S=class extends Error{constructor(t,e){var s,r,i;if(super(t.error_description||t.error||""),this.form=e,this.name="ErrorResponse",!t.error)throw y.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=t.error,this.error_description=null!=(s=t.error_description)?s:null,this.error_uri=null!=(r=t.error_uri)?r:null,this.state=t.userState,this.session_state=null!=(i=t.session_state)?i:null}},E=class extends Error{constructor(t){super(t),this.name="ErrorTimeout"}},T=class{constructor(){this._logger=new y("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]}},A=class{constructor(t=[],e=null){this._jwtHandler=e,this._logger=new y("JsonService"),this._contentTypes=[],this._contentTypes.push(...t,"application/json"),e&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(t,e={}){const{timeoutInSeconds:s,...r}=e;if(!s)return await fetch(t,r);const i=new AbortController,n=setTimeout(()=>i.abort(),1e3*s);try{return await fetch(t,{...e,signal:i.signal})}catch(t){if(t instanceof DOMException&&"AbortError"===t.name)throw new E("Network timed out");throw t}finally{clearTimeout(n)}}async getJson(t,{token:e,credentials:s}={}){const r=this._logger.create("getJson"),i={Accept:this._contentTypes.join(", ")};let n;e&&(r.debug("token passed, setting Authorization header"),i.Authorization="Bearer "+e);try{r.debug("url:",t),n=await this.fetchWithTimeout(t,{method:"GET",headers:i,credentials:s})}catch(t){throw r.error("Network Error"),t}r.debug("HTTP response received, status",n.status);const o=n.headers.get("Content-Type");if(o&&!this._contentTypes.find(t=>o.startsWith(t))&&r.throw(new Error(`Invalid response Content-Type: ${null!=o?o:"undefined"}, from URL: ${t}`)),n.ok&&this._jwtHandler&&(null==o?void 0:o.startsWith("application/jwt")))return await this._jwtHandler(await n.text());let a;try{a=await n.json()}catch(t){if(r.error("Error parsing JSON response",t),n.ok)throw t;throw new Error(`${n.statusText} (${n.status})`)}if(!n.ok){if(r.error("Error from server:",a),a.error)throw new S(a);throw new Error(`${n.statusText} (${n.status}): ${JSON.stringify(a)}`)}return a}async postForm(t,{body:e,basicAuth:s,timeoutInSeconds:r,initCredentials:i}){const n=this._logger.create("postForm"),o={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded"};let a;void 0!==s&&(o.Authorization="Basic "+s);try{n.debug("url:",t),a=await this.fetchWithTimeout(t,{method:"POST",headers:o,body:e,timeoutInSeconds:r,credentials:i})}catch(t){throw n.error("Network error"),t}n.debug("HTTP response received, status",a.status);const c=a.headers.get("Content-Type");if(c&&!this._contentTypes.find(t=>c.startsWith(t)))throw new Error(`Invalid response Content-Type: ${null!=c?c:"undefined"}, from URL: ${t}`);const h=await a.text();let u={};if(h)try{u=JSON.parse(h)}catch(t){if(n.error("Error parsing JSON response",t),a.ok)throw t;throw new Error(`${a.statusText} (${a.status})`)}if(!a.ok){if(n.error("Error from server:",u),u.error)throw new S(u,e);throw new Error(`${a.statusText} (${a.status}): ${JSON.stringify(u)}`)}return u}},R=class{constructor(t){this._settings=t,this._logger=new y("MetadataService"),this._jsonService=new A(["application/jwk-set+json"]),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const t=this._logger.create("getMetadata");if(this._metadata)return t.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw t.throw(new Error("No authority or metadataUrl configured on settings")),null;t.debug("getting metadata from",this._metadataUrl);const e=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials});return t.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},this._settings.metadataSeed,e),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(t=!0){return this._getMetadataProperty("token_endpoint",t)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(t=!0){return this._getMetadataProperty("revocation_endpoint",t)}getKeysEndpoint(t=!0){return this._getMetadataProperty("jwks_uri",t)}async _getMetadataProperty(t,e=!1){const s=this._logger.create(`_getMetadataProperty('${t}')`),r=await this.getMetadata();if(s.debug("resolved"),void 0===r[t]){if(!0===e)return void s.warn("Metadata does not contain optional property");s.throw(new Error("Metadata does not contain property "+t))}return r[t]}async getSigningKeys(){const t=this._logger.create("getSigningKeys");if(this._signingKeys)return t.debug("returning signingKeys from cache"),this._signingKeys;const e=await this.getKeysEndpoint(!1);t.debug("got jwks_uri",e);const s=await this._jsonService.getJson(e);if(t.debug("got key set",s),!Array.isArray(s.keys))throw t.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=s.keys,this._signingKeys}},C=class{constructor({prefix:t="oidc.",store:e=localStorage}={}){this._logger=new y("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){return this._logger.create(`get('${t}')`),t=this._prefix+t,await this._store.getItem(t)}async remove(t){this._logger.create(`remove('${t}')`),t=this._prefix+t;const e=await this._store.getItem(t);return await this._store.removeItem(t),e}async getAllKeys(){this._logger.create("getAllKeys");const t=await this._store.length,e=[];for(let s=0;s<t;s++){const t=await this._store.key(s);t&&0===t.indexOf(this._prefix)&&e.push(t.substr(this._prefix.length))}return e}},x=class{constructor({authority:t,metadataUrl:e,metadata:s,signingKeys:r,metadataSeed:i,client_id:n,client_secret:o,response_type:a="code",scope:c="openid",redirect_uri:h,post_logout_redirect_uri:u,client_authentication:l="client_secret_post",prompt:d,display:p,max_age:f,ui_locales:g,acr_values:_,resource:y,response_mode:m="query",filterProtocolClaims:w=!0,loadUserInfo:b=!1,staleStateAgeInSeconds:v=900,clockSkewInSeconds:k=300,userInfoJwtIssuer:S="OP",mergeClaims:E=!1,stateStore:A,refreshTokenCredentials:R,revokeTokenAdditionalContentTypes:x,fetchRequestCredentials:O,refreshTokenAllowedScope:I,extraQueryParams:P={},extraTokenParams:N={}}){if(this.authority=t,e?this.metadataUrl=e:(this.metadataUrl=t,t&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=s,this.metadataSeed=i,this.signingKeys=r,this.client_id=n,this.client_secret=o,this.response_type=a,this.scope=c,this.redirect_uri=h,this.post_logout_redirect_uri=u,this.client_authentication=l,this.prompt=d,this.display=p,this.max_age=f,this.ui_locales=g,this.acr_values=_,this.resource=y,this.response_mode=m,this.filterProtocolClaims=null==w||w,this.loadUserInfo=!!b,this.staleStateAgeInSeconds=v,this.clockSkewInSeconds=k,this.userInfoJwtIssuer=S,this.mergeClaims=!!E,this.revokeTokenAdditionalContentTypes=x,O&&R&&console.warn("Both fetchRequestCredentials and refreshTokenCredentials is set. Only fetchRequestCredentials will be used."),this.fetchRequestCredentials=O||R||"same-origin",A)this.stateStore=A;else{const t="undefined"!=typeof window?window.localStorage:new T;this.stateStore=new C({store:t})}this.refreshTokenAllowedScope=I,this.extraQueryParams=P,this.extraTokenParams=N}},O=class{constructor(t,e){this._settings=t,this._metadataService=e,this._logger=new y("UserInfoService"),this._getClaimsFromJwt=async t=>{const e=this._logger.create("_getClaimsFromJwt");try{const s=b.decode(t);return e.debug("JWT decoding successful"),s}catch(t){throw e.error("Error parsing JWT response"),t}},this._jsonService=new A(void 0,this._getClaimsFromJwt)}async getClaims(t){const e=this._logger.create("getClaims");t||this._logger.throw(new Error("No token passed"));const s=await this._metadataService.getUserInfoEndpoint();e.debug("got userinfo url",s);const r=await this._jsonService.getJson(s,{token:t,credentials:this._settings.fetchRequestCredentials});return e.debug("got claims",r),r}},I=class{constructor(t,e){this._settings=t,this._metadataService=e,this._logger=new y("TokenClient"),this._jsonService=new A(this._settings.revokeTokenAdditionalContentTypes)}async exchangeCode({grant_type:t="authorization_code",redirect_uri:e=this._settings.redirect_uri,client_id:s=this._settings.client_id,client_secret:r=this._settings.client_secret,...i}){const n=this._logger.create("exchangeCode");s||n.throw(new Error("A client_id is required")),e||n.throw(new Error("A redirect_uri is required")),i.code||n.throw(new Error("A code is required")),i.code_verifier||n.throw(new Error("A code_verifier is required"));const o=new URLSearchParams({grant_type:t,redirect_uri:e});for(const[t,e]of Object.entries(i))null!=e&&o.set(t,e);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!r)throw n.throw(new Error("A client_secret is required")),null;a=m.generateBasicAuth(s,r);break;case"client_secret_post":o.append("client_id",s),r&&o.append("client_secret",r)}const c=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");const h=await this._jsonService.postForm(c,{body:o,basicAuth:a,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),h}async exchangeCredentials({grant_type:t="password",client_id:e=this._settings.client_id,client_secret:s=this._settings.client_secret,scope:r=this._settings.scope,...i}){const n=this._logger.create("exchangeCredentials");e||n.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:t,scope:r});for(const[t,e]of Object.entries(i))null!=e&&o.set(t,e);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!s)throw n.throw(new Error("A client_secret is required")),null;a=m.generateBasicAuth(e,s);break;case"client_secret_post":o.append("client_id",e),s&&o.append("client_secret",s)}const c=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");const h=await this._jsonService.postForm(c,{body:o,basicAuth:a,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),h}async exchangeRefreshToken({grant_type:t="refresh_token",client_id:e=this._settings.client_id,client_secret:s=this._settings.client_secret,timeoutInSeconds:r,...i}){const n=this._logger.create("exchangeRefreshToken");e||n.throw(new Error("A client_id is required")),i.refresh_token||n.throw(new Error("A refresh_token is required"));const o=new URLSearchParams({grant_type:t});for(const[t,e]of Object.entries(i))null!=e&&o.set(t,e);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!s)throw n.throw(new Error("A client_secret is required")),null;a=m.generateBasicAuth(e,s);break;case"client_secret_post":o.append("client_id",e),s&&o.append("client_secret",s)}const c=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");const h=await this._jsonService.postForm(c,{body:o,basicAuth:a,timeoutInSeconds:r,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),h}async revoke(t){var e;const s=this._logger.create("revoke");t.token||s.throw(new Error("A token is required"));const r=await this._metadataService.getRevocationEndpoint(!1);s.debug(`got revocation endpoint, revoking ${null!=(e=t.token_type_hint)?e:"default token type"}`);const i=new URLSearchParams;for(const[e,s]of Object.entries(t))null!=s&&i.set(e,s);i.set("client_id",this._settings.client_id),this._settings.client_secret&&i.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(r,{body:i}),s.debug("got response")}},P=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],N=["sub","iss","aud","exp","iat"],B=class{constructor(t,e){this._settings=t,this._metadataService=e,this._logger=new y("ResponseValidator"),this._userInfoService=new O(this._settings,this._metadataService),this._tokenClient=new I(this._settings,this._metadataService)}async validateSigninResponse(t,e){const s=this._logger.create("validateSigninResponse");this._processSigninState(t,e),s.debug("state processed"),await this._processCode(t,e),s.debug("code processed"),t.isOpenId&&this._validateIdTokenAttributes(t),s.debug("tokens validated"),await this._processClaims(t,null==e?void 0:e.skipUserInfo,t.isOpenId),s.debug("claims processed")}async validateCredentialsResponse(t,e){const s=this._logger.create("validateCredentialsResponse");t.isOpenId&&this._validateIdTokenAttributes(t),s.debug("tokens validated"),await this._processClaims(t,e,t.isOpenId),s.debug("claims processed")}async validateRefreshResponse(t,e){const s=this._logger.create("validateRefreshResponse");t.userState=e.data,null!=t.session_state||(t.session_state=e.session_state),null!=t.scope||(t.scope=e.scope),t.isOpenId&&t.id_token&&(this._validateIdTokenAttributes(t,e.id_token),s.debug("ID Token validated")),t.id_token||(t.id_token=e.id_token,t.profile=e.profile);const r=t.isOpenId&&!!t.id_token;await this._processClaims(t,!1,r),s.debug("claims processed")}validateSignoutResponse(t,e){const s=this._logger.create("validateSignoutResponse");if(e.id!==t.state&&s.throw(new Error("State does not match")),s.debug("state validated"),t.userState=e.data,t.error)throw s.warn("Response was error",t.error),new S(t)}_processSigninState(t,e){const s=this._logger.create("_processSigninState");if(e.id!==t.state&&s.throw(new Error("State does not match")),e.client_id||s.throw(new Error("No client_id on state")),e.authority||s.throw(new Error("No authority on state")),this._settings.authority!==e.authority&&s.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==e.client_id&&s.throw(new Error("client_id mismatch on settings vs. signin state")),s.debug("state validated"),t.userState=e.data,null!=t.scope||(t.scope=e.scope),t.error)throw s.warn("Response was error",t.error),new S(t);e.code_verifier&&!t.code&&s.throw(new Error("Expected code in response")),!e.code_verifier&&t.code&&s.throw(new Error("Unexpected code in response"))}async _processClaims(t,e=!1,s=!0){const r=this._logger.create("_processClaims");if(t.profile=this._filterProtocolClaims(t.profile),e||!this._settings.loadUserInfo||!t.access_token)return void r.debug("not loading user info");r.debug("loading user info");const i=await this._userInfoService.getClaims(t.access_token);r.debug("user info claims received from user info endpoint"),s&&i.sub!==t.profile.sub&&r.throw(new Error("subject from UserInfo response does not match subject in ID Token")),t.profile=this._mergeClaims(t.profile,this._filterProtocolClaims(i)),r.debug("user info claims received, updated profile:",t.profile)}_mergeClaims(t,e){const s={...t};for(const[t,r]of Object.entries(e))for(const e of Array.isArray(r)?r:[r]){const r=s[t];r?Array.isArray(r)?r.includes(e)||r.push(e):s[t]!==e&&("object"==typeof e&&this._settings.mergeClaims?s[t]=this._mergeClaims(r,e):s[t]=[r,e]):s[t]=e}return s}_filterProtocolClaims(t){const e={...t};if(this._settings.filterProtocolClaims){let t;t=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:P;for(const s of t)N.includes(s)||delete e[s]}return e}async _processCode(t,e){const s=this._logger.create("_processCode");if(t.code){s.debug("Validating code");const r=await this._tokenClient.exchangeCode({client_id:e.client_id,client_secret:e.client_secret,code:t.code,redirect_uri:e.redirect_uri,code_verifier:e.code_verifier,...e.extraTokenParams});Object.assign(t,r)}else s.debug("No code to process")}_validateIdTokenAttributes(t,e){var s;const r=this._logger.create("_validateIdTokenAttributes");r.debug("decoding ID Token JWT");const i=b.decode(null!=(s=t.id_token)?s:"");if(i.sub||r.throw(new Error("ID Token is missing a subject claim")),e){const t=b.decode(e);t.sub!==i.sub&&r.throw(new Error("sub in id_token does not match current sub")),t.auth_time&&t.auth_time!==i.auth_time&&r.throw(new Error("auth_time in id_token does not match original auth_time")),t.azp&&t.azp!==i.azp&&r.throw(new Error("azp in id_token does not match original azp")),!t.azp&&i.azp&&r.throw(new Error("azp not in id_token, but present in original id_token"))}t.profile=i}},j=class{constructor(t){this.id=t.id||m.generateUUIDv4(),this.data=t.data,t.created&&t.created>0?this.created=t.created:this.created=v.getEpochTime(),this.request_type=t.request_type}toStorageString(){return new y("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type})}static fromStorageString(t){return y.createStatic("State","fromStorageString"),new j(JSON.parse(t))}static async clearStaleState(t,e){const s=y.createStatic("State","clearStaleState"),r=v.getEpochTime()-e,i=await t.getAllKeys();s.debug("got keys",i);for(let e=0;e<i.length;e++){const n=i[e],o=await t.get(n);let a=!1;if(o)try{const t=j.fromStorageString(o);s.debug("got item from key:",n,t.created),t.created<=r&&(a=!0)}catch(t){s.error("Error parsing state for key:",n,t),a=!0}else s.debug("no item in storage for key:",n),a=!0;a&&(s.debug("removed item for key:",n),t.remove(n))}}},q=class extends j{constructor(t){super(t),!0===t.code_verifier?this.code_verifier=m.generateCodeVerifier():t.code_verifier&&(this.code_verifier=t.code_verifier),this.code_verifier&&(this.code_challenge=m.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 y("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){y.createStatic("SigninState","fromStorageString");const e=JSON.parse(t);return new q(e)}},U=class{constructor({url:t,authority:e,client_id:s,redirect_uri:r,response_type:i,scope:n,state_data:o,response_mode:a,request_type:c,client_secret:h,nonce:u,resource:l,skipUserInfo:d,extraQueryParams:p,extraTokenParams:f,...g}){if(this._logger=new y("SigninRequest"),!t)throw this._logger.error("ctor: No url passed"),new Error("url");if(!s)throw this._logger.error("ctor: No client_id passed"),new Error("client_id");if(!r)throw this._logger.error("ctor: No redirect_uri passed"),new Error("redirect_uri");if(!i)throw this._logger.error("ctor: No response_type passed"),new Error("response_type");if(!n)throw this._logger.error("ctor: No scope passed"),new Error("scope");if(!e)throw this._logger.error("ctor: No authority passed"),new Error("authority");this.state=new q({data:o,request_type:c,code_verifier:!0,client_id:s,authority:e,redirect_uri:r,response_mode:a,client_secret:h,scope:n,extraTokenParams:f,skipUserInfo:d});const _=new URL(t);_.searchParams.append("client_id",s),_.searchParams.append("redirect_uri",r),_.searchParams.append("response_type",i),_.searchParams.append("scope",n),u&&_.searchParams.append("nonce",u),_.searchParams.append("state",this.state.id),this.state.code_challenge&&(_.searchParams.append("code_challenge",this.state.code_challenge),_.searchParams.append("code_challenge_method","S256")),l&&(Array.isArray(l)?l:[l]).forEach(t=>_.searchParams.append("resource",t));for(const[t,e]of Object.entries({response_mode:a,...g,...p}))null!=e&&_.searchParams.append(t,e.toString());this.url=_.href}},L=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-v.getEpochTime()}set expires_in(t){"string"==typeof t&&(t=Number(t)),void 0!==t&&t>=0&&(this.expires_at=Math.floor(t)+v.getEpochTime())}get isOpenId(){var t;return(null==(t=this.scope)?void 0:t.split(" ").includes("openid"))||!!this.id_token}},D=class{constructor({url:t,state_data:e,id_token_hint:s,post_logout_redirect_uri:r,extraQueryParams:i,request_type:n}){if(this._logger=new y("SignoutRequest"),!t)throw this._logger.error("ctor: No url passed"),new Error("url");const o=new URL(t);s&&o.searchParams.append("id_token_hint",s),r&&(o.searchParams.append("post_logout_redirect_uri",r),e&&(this.state=new j({data:e,request_type:n}),o.searchParams.append("state",this.state.id)));for(const[t,e]of Object.entries({...i}))null!=e&&o.searchParams.append(t,e.toString());this.url=o.href}},M=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")}},F=class{constructor(t){this._logger=new y("OidcClient"),this.settings=new x(t),this.metadataService=new R(this.settings),this._validator=new B(this.settings,this.metadataService),this._tokenClient=new I(this.settings,this.metadataService)}async createSigninRequest({state:t,request:e,request_uri:s,request_type:r,id_token_hint:i,login_hint:n,skipUserInfo:o,nonce:a,response_type:c=this.settings.response_type,scope:h=this.settings.scope,redirect_uri:u=this.settings.redirect_uri,prompt:l=this.settings.prompt,display:d=this.settings.display,max_age:p=this.settings.max_age,ui_locales:f=this.settings.ui_locales,acr_values:g=this.settings.acr_values,resource:_=this.settings.resource,response_mode:y=this.settings.response_mode,extraQueryParams:m=this.settings.extraQueryParams,extraTokenParams:w=this.settings.extraTokenParams}){const b=this._logger.create("createSigninRequest");if("code"!==c)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const v=await this.metadataService.getAuthorizationEndpoint();b.debug("Received authorization endpoint",v);const k=new U({url:v,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:u,response_type:c,scope:h,state_data:t,prompt:l,display:d,max_age:p,ui_locales:f,id_token_hint:i,login_hint:n,acr_values:g,resource:_,request:e,request_uri:s,extraQueryParams:m,extraTokenParams:w,request_type:r,response_mode:y,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a});await this.clearStaleState();const S=k.state;return await this.settings.stateStore.set(S.id,S.toStorageString()),k}async readSigninResponseState(t,e=!1){const s=this._logger.create("readSigninResponseState"),r=new L(k.readParams(t,this.settings.response_mode));if(!r.state)throw s.throw(new Error("No state in response")),null;const i=await this.settings.stateStore[e?"remove":"get"](r.state);if(!i)throw s.throw(new Error("No matching state found in storage")),null;return{state:q.fromStorageString(i),response:r}}async processSigninResponse(t){const e=this._logger.create("processSigninResponse"),{state:s,response:r}=await this.readSigninResponseState(t,!0);return e.debug("received state from storage; validating response"),await this._validator.validateSigninResponse(r,s),r}async processResourceOwnerPasswordCredentials({username:t,password:e,skipUserInfo:s=!1,extraTokenParams:r={}}){const i=await this._tokenClient.exchangeCredentials({username:t,password:e,...r}),n=new L(new URLSearchParams);return Object.assign(n,i),await this._validator.validateCredentialsResponse(n,s),n}async useRefreshToken({state:t,timeoutInSeconds:e}){var s;const r=this._logger.create("useRefreshToken");let i;if(void 0===this.settings.refreshTokenAllowedScope)i=t.scope;else{const e=this.settings.refreshTokenAllowedScope.split(" ");i=((null==(s=t.scope)?void 0:s.split(" "))||[]).filter(t=>e.includes(t)).join(" ")}const n=await this._tokenClient.exchangeRefreshToken({refresh_token:t.refresh_token,scope:i,timeoutInSeconds:e}),o=new L(new URLSearchParams);return Object.assign(o,n),r.debug("validating response",o),await this._validator.validateRefreshResponse(o,{...t,scope:i}),o}async createSignoutRequest({state:t,id_token_hint:e,request_type:s,post_logout_redirect_uri:r=this.settings.post_logout_redirect_uri,extraQueryParams:i=this.settings.extraQueryParams}={}){const n=this._logger.create("createSignoutRequest"),o=await this.metadataService.getEndSessionEndpoint();if(!o)throw n.throw(new Error("No end session endpoint")),null;n.debug("Received end session endpoint",o);const a=new D({url:o,id_token_hint:e,post_logout_redirect_uri:r,state_data:t,extraQueryParams:i,request_type:s});await this.clearStaleState();const c=a.state;return c&&(n.debug("Signout request has state to persist"),await this.settings.stateStore.set(c.id,c.toStorageString())),a}async readSignoutResponseState(t,e=!1){const s=this._logger.create("readSignoutResponseState"),r=new M(k.readParams(t,this.settings.response_mode));if(!r.state){if(s.debug("No state in response"),r.error)throw s.warn("Response was error:",r.error),new S(r);return{state:void 0,response:r}}const i=await this.settings.stateStore[e?"remove":"get"](r.state);if(!i)throw s.throw(new Error("No matching state found in storage")),null;return{state:j.fromStorageString(i),response:r}}async processSignoutResponse(t){const e=this._logger.create("processSignoutResponse"),{state:s,response:r}=await this.readSignoutResponseState(t,!0);return s?(e.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(r,s)):e.debug("No state from storage; skipping response validation"),r}clearStaleState(){return this._logger.create("clearStaleState"),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 z={},H=(t,e)=>K()?localStorage.setItem(t,e):z[t]=e,$=t=>K()?localStorage.getItem(t):z[t],K=()=>!("object"==typeof process&&"[object process]"===String(process));class J{constructor(t){this._oidcSettings={authority:"https://auth.gameglue.gg/realms/GameGlue",client_id:t.clientId,redirect_uri:W(t.redirect_uri||window.location.href),post_logout_redirect_uri:W(window.location.href),response_type:"code",scope:`openid ${(t.scopes||[]).join(" ")}`,response_mode:"fragment",filterProtocolClaims:!0},this._oidcClient=new F(this._oidcSettings),this._refreshCallback=()=>{},this._refreshTimeout=null}setTokenRefreshTimeout(t){if(!t)return;clearTimeout(this._refreshTimeout);const e=1e3*l(t).exp-Date.now()-5e3;e>0&&(this._refreshTimeout=setTimeout(()=>{this.attemptRefresh()},e))}setAccessToken(t){return this.setTokenRefreshTimeout(t),H("gg-auth-token",t)}getAccessToken(){let t=$("gg-auth-token");return this.setTokenRefreshTimeout(t),t}getUserId(){return l(this.getAccessToken()).sub}setRefreshToken(t){return H("gg-refresh-token",t)}getRefreshToken(t){return $("gg-refresh-token")}_shouldHandleRedirectResponse(){return location.hash.includes("state=")&&(location.hash.includes("code=")||location.hash.includes("error="))}async handleRedirectResponse(){let t=await this._oidcClient.processSigninResponse(window.location.href);!t.error&&t.access_token?(window.history.pushState("",document.title,window.location.pathname+window.location.search),this.setAccessToken(t.access_token),this.setRefreshToken(t.refresh_token)):console.error(t.error)}onTokenRefreshed(t){this._refreshCallback=t}async isAuthenticated(t){let e=this.getAccessToken();if(!e)return!1;const s=l(e),r=new Date(1e3*s.exp)<new Date;return r&&!t?(await this.attemptRefresh(),this.isAuthenticated(!0)):!(r&&t)}isTokenExpired(t){const e=l(t);return new Date(1e3*e.exp)<new Date}async attemptRefresh(){const t=`${this._oidcSettings.authority}/protocol/openid-connect/token`,e=this._oidcSettings.client_id,s=this.getRefreshToken();try{const r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e,grant_type:"refresh_token",refresh_token:s})});if(200===r.status){const t=await r.json();this.setAccessToken(t.access_token),this.setRefreshToken(t.refresh_token),this._refreshCallback(t)}}catch(t){console.log("Error: ",t)}}_triggerAuthRedirect(){this._oidcClient.createSigninRequest({state:{bar:15}}).then(function(t){window.location=t.url}).catch(function(t){console.error(t)})}async authenticate(){this._shouldHandleRedirectResponse()&&await this.handleRedirectResponse(),await this.isAuthenticated()||await this._triggerAuthRedirect()}}function W(t){return t.endsWith("/")?t.replace(/\/+$/,""):t}const V=Object.create(null);V.open="0",V.close="1",V.ping="2",V.pong="3",V.message="4",V.upgrade="5",V.noop="6";const Q=Object.create(null);Object.keys(V).forEach(t=>{Q[V[t]]=t});const Y={type:"error",data:"parser error"},G="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),X="function"==typeof ArrayBuffer,Z=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,tt=({type:t,data:e},s,r)=>G&&e instanceof Blob?s?r(e):et(e,r):X&&(e instanceof ArrayBuffer||Z(e))?s?r(e):et(new Blob([e]),r):r(V[t]+(e||"")),et=(t,e)=>{const s=new FileReader;return s.onload=function(){const t=s.result.split(",")[1];e("b"+(t||""))},s.readAsDataURL(t)};function st(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let rt;const it="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)it["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(t)]=t;const nt="function"==typeof ArrayBuffer,ot=(t,e)=>{if("string"!=typeof t)return{type:"message",data:ct(t,e)};const s=t.charAt(0);return"b"===s?{type:"message",data:at(t.substring(1),e)}:Q[s]?t.length>1?{type:Q[s],data:t.substring(1)}:{type:Q[s]}:Y},at=(t,e)=>{if(nt){const s=(t=>{let e,s,r,i,n,o=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(o--,"="===t[t.length-2]&&o--);const h=new ArrayBuffer(o),u=new Uint8Array(h);for(e=0;e<a;e+=4)s=it[t.charCodeAt(e)],r=it[t.charCodeAt(e+1)],i=it[t.charCodeAt(e+2)],n=it[t.charCodeAt(e+3)],u[c++]=s<<2|r>>4,u[c++]=(15&r)<<4|i>>2,u[c++]=(3&i)<<6|63&n;return h})(t);return ct(s,e)}return{base64:!0,data:t}},ct=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,ht=String.fromCharCode(30);let ut;function lt(t){return t.reduce((t,e)=>t+e.length,0)}function dt(t,e){if(t[0].length===e)return t.shift();const s=new Uint8Array(e);let r=0;for(let i=0;i<e;i++)s[i]=t[0][r++],r===t[0].length&&(t.shift(),r=0);return t.length&&r<t[0].length&&(t[0]=t[0].slice(r)),s}function pt(t){if(t)return function(t){for(var e in pt.prototype)t[e]=pt.prototype[e];return t}(t)}pt.prototype.on=pt.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},pt.prototype.once=function(t,e){function s(){this.off(t,s),e.apply(this,arguments)}return s.fn=e,this.on(t,s),this},pt.prototype.off=pt.prototype.removeListener=pt.prototype.removeAllListeners=pt.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var s,r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var i=0;i<r.length;i++)if((s=r[i])===e||s.fn===e){r.splice(i,1);break}return 0===r.length&&delete this._callbacks["$"+t],this},pt.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),s=this._callbacks["$"+t],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(s){r=0;for(var i=(s=s.slice(0)).length;r<i;++r)s[r].apply(this,e)}return this},pt.prototype.emitReserved=pt.prototype.emit,pt.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},pt.prototype.hasListeners=function(t){return!!this.listeners(t).length};const ft="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),gt="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function _t(t,...e){return e.reduce((e,s)=>(t.hasOwnProperty(s)&&(e[s]=t[s]),e),{})}const yt=gt.setTimeout,mt=gt.clearTimeout;function wt(t,e){e.useNativeTimers?(t.setTimeoutFn=yt.bind(gt),t.clearTimeoutFn=mt.bind(gt)):(t.setTimeoutFn=gt.setTimeout.bind(gt),t.clearTimeoutFn=gt.clearTimeout.bind(gt))}function bt(t){return"string"==typeof t?function(t){let e=0,s=0;for(let r=0,i=t.length;r<i;r++)e=t.charCodeAt(r),e<128?s+=1:e<2048?s+=2:e<55296||e>=57344?s+=3:(r++,s+=4);return s}(t):Math.ceil(1.33*(t.byteLength||t.size))}function vt(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class kt extends Error{constructor(t,e,s){super(t),this.description=e,this.context=s,this.type="TransportError"}}class St extends pt{constructor(t){super(),this.writable=!1,wt(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,s){return super.emitReserved("error",new kt(t,e,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=ot(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(t){const e=function(t){let e="";for(let s in t)t.hasOwnProperty(s)&&(e.length&&(e+="&"),e+=encodeURIComponent(s)+"="+encodeURIComponent(t[s]));return e}(t);return e.length?"?"+e:""}}class Et extends St{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let t=0;this._polling&&(t++,this.once("pollComplete",function(){--t||e()})),this.writable||(t++,this.once("drain",function(){--t||e()}))}else e()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){((t,e)=>{const s=t.split(ht),r=[];for(let t=0;t<s.length;t++){const i=ot(s[t],e);if(r.push(i),"error"===i.type)break}return r})(t,this.socket.binaryType).forEach(t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const s=t.length,r=new Array(s);let i=0;t.forEach((t,n)=>{tt(t,!1,t=>{r[n]=t,++i===s&&e(r.join(ht))})})})(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]=vt()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let Tt=!1;try{Tt="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const At=Tt;function Rt(){}class Ct extends Et{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let s=location.port;s||(s=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||s!==t.port}}doWrite(t,e){const s=this.request({method:"POST",data:t});s.on("success",e),s.on("error",(t,e)=>{this.onError("xhr post error",t,e)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t,e)=>{this.onError("xhr poll error",t,e)}),this.pollXhr=t}}class xt extends pt{constructor(t,e,s){super(),this.createRequest=t,wt(this,s),this._opts=s,this._method=s.method||"GET",this._uri=e,this._data=void 0!==s.data?s.data:null,this._create()}_create(){var t;const e=_t(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(e);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let t in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(t)&&s.setRequestHeader(t,this._opts.extraHeaders[t])}}catch(t){}if("POST"===this._method)try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{s.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var t;3===s.readyState&&(null===(t=this._opts.cookieJar)||void 0===t||t.parseCookies(s.getResponseHeader("set-cookie"))),4===s.readyState&&(200===s.status||1223===s.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof s.status?s.status:0)},0))},s.send(this._data)}catch(t){return void this.setTimeoutFn(()=>{this._onError(t)},0)}"undefined"!=typeof document&&(this._index=xt.requestsCount++,xt.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=Rt,t)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete xt.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()}}function Ot(){for(let t in xt.requests)xt.requests.hasOwnProperty(t)&&xt.requests[t].abort()}xt.requestsCount=0,xt.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",Ot):"function"==typeof addEventListener&&addEventListener("onpagehide"in gt?"pagehide":"unload",Ot,!1));const It=function(){const t=Pt({xdomain:!1});return t&&null!==t.responseType}();function Pt(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||At))return new XMLHttpRequest}catch(t){}if(!e)try{return new(gt[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const Nt="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Bt extends St{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,s=Nt?{}:_t(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,s)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],r=e===t.length-1;tt(s,this.supportsBinary,t=>{try{this.doWrite(s,t)}catch(t){}r&&ft(()=>{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]=vt()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const jt=gt.WebSocket||gt.MozWebSocket,qt={websocket:class extends Bt{createSocket(t,e,s){return Nt?new jt(t,e,s):e?new jt(t,e):new jt(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends St{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){ut||(ut=new TextDecoder);const s=[];let r=0,i=-1,n=!1;return new TransformStream({transform(o,a){for(s.push(o);;){if(0===r){if(lt(s)<1)break;const t=dt(s,1);n=!(128&~t[0]),i=127&t[0],r=i<126?3:126===i?1:2}else if(1===r){if(lt(s)<2)break;const t=dt(s,2);i=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),r=3}else if(2===r){if(lt(s)<8)break;const t=dt(s,8),e=new DataView(t.buffer,t.byteOffset,t.length),n=e.getUint32(0);if(n>Math.pow(2,21)-1){a.enqueue(Y);break}i=n*Math.pow(2,32)+e.getUint32(4),r=3}else{if(lt(s)<i)break;const t=dt(s,i);a.enqueue(ot(n?t:ut.decode(t),e)),r=0}if(0===i||i>t){a.enqueue(Y);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=t.readable.pipeThrough(e).getReader(),r=new TransformStream({transform(t,e){!function(t,e){G&&t.data instanceof Blob?t.data.arrayBuffer().then(st).then(e):X&&(t.data instanceof ArrayBuffer||Z(t.data))?e(st(t.data)):tt(t,!1,t=>{rt||(rt=new TextEncoder),e(rt.encode(t))})}(t,s=>{const r=s.length;let i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);const t=new DataView(i.buffer);t.setUint8(0,126),t.setUint16(1,r)}else{i=new Uint8Array(9);const t=new DataView(i.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(r))}t.data&&"string"!=typeof t.data&&(i[0]|=128),e.enqueue(i),e.enqueue(s)})}});r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const i=()=>{s.read().then(({done:t,value:e})=>{t||(this.onPacket(e),i())}).catch(t=>{})};i();const n={type:"open"};this.query.sid&&(n.data=`{"sid":"${this.query.sid}"}`),this._writer.write(n).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],r=e===t.length-1;this._writer.write(s).then(()=>{r&&ft(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this._transport)||void 0===t||t.close()}},polling:class extends Ct{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=It&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new xt(Pt,this.uri(),t)}}},Ut=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Lt=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Dt(t){if(t.length>8e3)throw"URI too long";const e=t,s=t.indexOf("["),r=t.indexOf("]");-1!=s&&-1!=r&&(t=t.substring(0,s)+t.substring(s,r).replace(/:/g,";")+t.substring(r,t.length));let i=Ut.exec(t||""),n={},o=14;for(;o--;)n[Lt[o]]=i[o]||"";return-1!=s&&-1!=r&&(n.source=e,n.host=n.host.substring(1,n.host.length-1).replace(/;/g,":"),n.authority=n.authority.replace("[","").replace("]","").replace(/;/g,":"),n.ipv6uri=!0),n.pathNames=function(t,e){const s=e.replace(/\/{2,9}/g,"/").split("/");return"/"!=e.slice(0,1)&&0!==e.length||s.splice(0,1),"/"==e.slice(-1)&&s.splice(s.length-1,1),s}(0,n.path),n.queryKey=function(t,e){const s={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,r){e&&(s[e]=r)}),s}(0,n.query),n}const Mt="function"==typeof addEventListener&&"function"==typeof removeEventListener,Ft=[];Mt&&addEventListener("offline",()=>{Ft.forEach(t=>t())},!1);class zt extends pt{constructor(t,e){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&"object"==typeof t&&(e=t,t=null),t){const s=Dt(t);e.hostname=s.host,e.secure="https"===s.protocol||"wss"===s.protocol,e.port=s.port,s.query&&(e.query=s.query)}else e.host&&(e.hostname=Dt(e.host).host);wt(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},e.transports.forEach(t=>{const e=t.prototype.name;this.transports.push(e),this._transportsByName[e]=t}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(t){let e={},s=t.split("&");for(let t=0,r=s.length;t<r;t++){let r=s[t].split("=");e[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return e}(this.opts.query)),Mt&&(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"})},Ft.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const s=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](s)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&zt.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",zt.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const e=new Error("server error");e.code=t.data,this._onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let e=0;e<this.writeBuffer.length;e++){const s=this.writeBuffer[e].data;if(s&&(t+=bt(s)),e>0&&t>this._maxPayload)return this.writeBuffer.slice(0,e);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,ft(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,e,s){return this._sendPacket("message",t,e,s),this}send(t,e,s){return this._sendPacket("message",t,e,s),this}_sendPacket(t,e,s,r){if("function"==typeof e&&(r=e,e=void 0),"function"==typeof s&&(r=s,s=null),"closing"===this.readyState||"closed"===this.readyState)return;(s=s||{}).compress=!1!==s.compress;const i={type:t,data:e,options:s};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},s=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():t()}):this.upgrading?s():t()),this}_onError(t){if(zt.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(),Mt&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=Ft.indexOf(this._offlineEventListener);-1!==t&&Ft.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this._prevBufferLen=0}}}zt.protocol=4;class Ht extends zt{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let e=this.createTransport(t),s=!1;zt.priorWebsocketSuccess=!1;const r=()=>{s||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!s)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;zt.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{s||"closed"!==this.readyState&&(h(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}}))};function i(){s||(s=!0,h(),e.close(),e=null)}const n=t=>{const s=new Error("probe error: "+t);s.transport=e.name,i(),this.emitReserved("upgradeError",s)};function o(){n("transport closed")}function a(){n("socket closed")}function c(t){e&&t.name!==e.name&&i()}const h=()=>{e.removeListener("open",r),e.removeListener("error",n),e.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};e.once("open",r),e.once("error",n),e.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{s||e.open()},200):e.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const e=[];for(let s=0;s<t.length;s++)~this.transports.indexOf(t[s])&&e.push(t[s]);return e}}class $t extends Ht{constructor(t,e={}){const s="object"==typeof t?t:e;(!s.transports||s.transports&&"string"==typeof s.transports[0])&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(t=>qt[t]).filter(t=>!!t)),super(t,s)}}const Kt="function"==typeof ArrayBuffer,Jt=Object.prototype.toString,Wt="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Jt.call(Blob),Vt="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Jt.call(File);function Qt(t){return Kt&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||Wt&&t instanceof Blob||Vt&&t instanceof File}function Yt(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,s=t.length;e<s;e++)if(Yt(t[e]))return!0;return!1}if(Qt(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return Yt(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&Yt(t[e]))return!0;return!1}function Gt(t){const e=[],s=t.data,r=t;return r.data=Xt(s,e),r.attachments=e.length,{packet:r,buffers:e}}function Xt(t,e){if(!t)return t;if(Qt(t)){const s={_placeholder:!0,num:e.length};return e.push(t),s}if(Array.isArray(t)){const s=new Array(t.length);for(let r=0;r<t.length;r++)s[r]=Xt(t[r],e);return s}if("object"==typeof t&&!(t instanceof Date)){const s={};for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(s[r]=Xt(t[r],e));return s}return t}function Zt(t,e){return t.data=te(t.data,e),delete t.attachments,t}function te(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let s=0;s<t.length;s++)t[s]=te(t[s],e);else if("object"==typeof t)for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(t[s]=te(t[s],e));return t}const ee=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],se=5;var re;!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"}(re||(re={}));class ie{constructor(t){this.replacer=t}encode(t){return t.type!==re.EVENT&&t.type!==re.ACK||!Yt(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===re.EVENT?re.BINARY_EVENT:re.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==re.BINARY_EVENT&&t.type!==re.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=Gt(t),s=this.encodeAsString(e.packet),r=e.buffers;return r.unshift(s),r}}class ne extends pt{constructor(t){super(),this.reviver=t}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const s=e.type===re.BINARY_EVENT;s||e.type===re.BINARY_ACK?(e.type=s?re.EVENT:re.ACK,this.reconstructor=new oe(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!Qt(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const s={type:Number(t.charAt(0))};if(void 0===re[s.type])throw new Error("unknown packet type "+s.type);if(s.type===re.BINARY_EVENT||s.type===re.BINARY_ACK){const r=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const i=t.substring(r,e);if(i!=Number(i)||"-"!==t.charAt(e))throw new Error("Illegal attachments");s.attachments=Number(i)}if("/"===t.charAt(e+1)){const r=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);s.nsp=t.substring(r,e)}else s.nsp="/";const r=t.charAt(e+1);if(""!==r&&Number(r)==r){const r=e+1;for(;++e;){const s=t.charAt(e);if(null==s||Number(s)!=s){--e;break}if(e===t.length)break}s.id=Number(t.substring(r,e+1))}if(t.charAt(++e)){const r=this.tryParse(t.substr(e));if(!ne.isPayloadValid(s.type,r))throw new Error("invalid payload");s.data=r}return s}tryParse(t){try{return JSON.parse(t,this.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case re.CONNECT:return ce(e);case re.DISCONNECT:return void 0===e;case re.CONNECT_ERROR:return"string"==typeof e||ce(e);case re.EVENT:case re.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===ee.indexOf(e[0]));case re.ACK:case re.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class oe{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=Zt(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const ae=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t};function ce(t){return"[object Object]"===Object.prototype.toString.call(t)}function he(t){return"string"==typeof t.nsp&&(void 0===(e=t.id)||ae(e))&&function(t,e){switch(t){case re.CONNECT:return void 0===e||ce(e);case re.DISCONNECT:return void 0===e;case re.EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===ee.indexOf(e[0]));case re.ACK:return Array.isArray(e);case re.CONNECT_ERROR:return"string"==typeof e||ce(e);default:return!1}}(t.type,t.data);var e}function ue(t,e,s){return t.on(e,s),function(){t.off(e,s)}}const le=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class de extends pt{constructor(t,e,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[ue(t,"open",this.onopen.bind(this)),ue(t,"packet",this.onpacket.bind(this)),ue(t,"error",this.onerror.bind(this)),ue(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var s,r,i;if(le.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const n={type:re.EVENT,data:e,options:{}};if(n.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,s=e.pop();this._registerAckCallback(t,s),n.id=t}const o=null===(r=null===(s=this.io.engine)||void 0===s?void 0:s.transport)||void 0===r?void 0:r.writable,a=this.connected&&!(null===(i=this.io.engine)||void 0===i?void 0:i._hasPingExpired());return this.flags.volatile&&!o||(a?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(t,e){var s;const r=null!==(s=this.flags.timeout)&&void 0!==s?s:this._opts.ackTimeout;if(void 0===r)return void(this.acks[t]=e);const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))},r),n=(...t)=>{this.io.clearTimeoutFn(i),e.apply(this,t)};n.withError=!0,this.acks[t]=n}emitWithAck(t,...e){return new Promise((s,r)=>{const i=(t,e)=>t?r(t):s(e);i.withError=!0,e.push(i),this.emit(t,...e)})}_addToQueue(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...r)=>(this._queue[0],null!==t?s.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(t)):(this._queue.shift(),e&&e(null,...r)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||0===this._queue.length)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:re.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 re.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 re.EVENT:case re.BINARY_EVENT:this.onevent(t);break;case re.ACK:case re.BINARY_ACK:this.onack(t);break;case re.DISCONNECT:this.ondisconnect();break;case re.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const s of e)s.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&"string"==typeof t[t.length-1]&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let s=!1;return function(...r){s||(s=!0,e.packet({type:re.ACK,id:t,data:r}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:re.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const s of e)s.apply(this,t.data)}}}function 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(),s=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+s:t-s}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 fe extends pt{constructor(e,s){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(s=e,e=void 0),(s=s||{}).path=s.path||"/socket.io",this.opts=s,wt(this,s),this.reconnection(!1!==s.reconnection),this.reconnectionAttempts(s.reconnectionAttempts||1/0),this.reconnectionDelay(s.reconnectionDelay||1e3),this.reconnectionDelayMax(s.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=s.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new pe({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==s.timeout?2e4:s.timeout),this._readyState="closed",this.uri=e;const i=s.parser||t;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==s.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 $t(this.uri,this.opts);const e=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=ue(e,"open",function(){s.onopen(),t&&t()}),i=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},n=ue(e,"error",i);if(!1!==this._timeout){const t=this._timeout,s=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),e.close()},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}return this.subs.push(r),this.subs.push(n),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(ue(t,"ping",this.onping.bind(this)),ue(t,"data",this.ondata.bind(this)),ue(t,"error",this.onerror.bind(this)),ue(t,"close",this.onclose.bind(this)),ue(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){ft(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let s=this.nsps[t];return s?this._autoConnect&&!s.active&&s.connect():(s=new de(this,t,e),this.nsps[t]=s),s}_destroy(t){const e=Object.keys(this.nsps);for(const t of e)if(this.nsps[t].active)return;this._close()}_packet(t){const e=this.encoder.encode(t);for(let s=0;s<e.length;s++)this.engine.write(e[s],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,e){var s;this.cleanup(),null===(s=this.engine)||void 0===s||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open(e=>{e?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()}))},e);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const ge={};function _e(t,e){"object"==typeof t&&(e=t,t=void 0);const s=function(t,e="",s){let r=t;s=s||"undefined"!=typeof location&&location,null==t&&(t=s.protocol+"//"+s.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?s.protocol+t:s.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==s?s.protocol+"//"+t:"https://"+t),r=Dt(t)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const i=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+e,r.href=r.protocol+"://"+i+(s&&s.port===r.port?"":":"+r.port),r}(t,(e=e||{}).path||"/socket.io"),r=s.source,i=s.id,n=s.path,o=ge[i]&&n in ge[i].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||o?a=new fe(r,e):(ge[i]||(ge[i]=new fe(r,e)),a=ge[i]),s.query&&!e.query&&(e.query=s.queryKey),a.socket(s.path,e)}Object.assign(_e,{Manager:fe,Socket:de,io:_e,connect:_e});const ye=s(68);class me{constructor(t,e){this._config=e,this._socket=t,this._callbacks=[],this._fields=e.fields?[...e.fields]:null}async establishConnection(){if(!this._socket||!this._config.userId||!this._config.gameId)throw new Error("Missing arguments in establishConnection");return new Promise(t=>{let e;e=this._fields?{userId:this._config.userId,gameId:this._config.gameId,fields:this._fields}:`${this._config.userId}:${this._config.gameId}`,this._socket.timeout(5e3).emit("listen",e,(e,s)=>e?t({status:"failed",reason:"Listen request timed out."}):"success"===s.status?t({status:"success"}):t({status:"failed",reason:s.reason}))})}setupEventListener(){return this._socket.on("update",this.emit.bind(this,"update")),this}async subscribe(t){if(!Array.isArray(t)||0===t.length)throw new Error("fields must be a non-empty array");if(this._fields)for(const e of t)this._fields.includes(e)||this._fields.push(e);else this._fields=[...t];return this._updateSubscription()}async unsubscribe(t){if(!Array.isArray(t)||0===t.length)throw new Error("fields must be a non-empty array");if(!this._fields)throw new Error("Cannot unsubscribe when receiving all fields. Use subscribe() first to set explicit field list.");return this._fields=this._fields.filter(e=>!t.includes(e)),this._updateSubscription()}getFields(){return this._fields?[...this._fields]:null}async sendCommand(t,e){if(!t||"string"!=typeof t)throw new Error("field must be a non-empty string");return new Promise(s=>{const r={userId:this._config.userId,gameId:this._config.gameId,data:{fieldName:t,value:e}};this._socket.timeout(5e3).emit("set",r,(t,e)=>s(t?{status:"failed",reason:"Command request timed out."}:e))})}async _updateSubscription(){return new Promise(t=>{const e={userId:this._config.userId,gameId:this._config.gameId,fields:this._fields};this._socket.timeout(5e3).emit("listen-update",e,(e,s)=>t(e?{status:"failed",reason:"Update request timed out."}:s))})}}ye(me.prototype);const we={msfs:!0};class be extends J{constructor(t){super(t),this._socket=!1}async auth(){return await this.authenticate(),await this.isAuthenticated()&&await this.initialize(),this.getUserId()}async initialize(){return new Promise(t=>{const e=this.getAccessToken();this._socket=_e("https://socks.gameglue.gg",{transports:["websocket"],auth:{token:e}}),this._socket.on("connect",()=>{t()}),this.onTokenRefreshed(this.updateSocketAuth)})}updateSocketAuth(t){this._socket.auth.token=t}async createListener(t){if(!t)throw new Error("Not a valid listener config");if(!t.gameId||!we[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");this._socket||await this.initialize();const e=new me(this._socket,t),s=await e.establishConnection();if(this._socket.io.on("reconnect_attempt",t=>{console.log("Refresh Attempt"),this.updateSocketAuth(this.getAccessToken())}),this._socket.io.on("reconnect",()=>{e.establishConnection()}),"success"!==s.status)throw new Error(`There was a problem setting up the listener. Reason: ${s.reason}`);return e.setupEventListener()}}"undefined"!=typeof window&&(window.GameGlue=be);const ve=be})(),r.default})());
|
|
File without changes
|
|
File without changes
|