UNPKG

@brainfish-ai/web-tracker

Version:

Brainfish Tracker for Web

1 lines 499 kB
var __defProp=Object.defineProperty,__defNormalProp=(e,t,r)=>t in e?__defProp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,__publicField=(e,t,r)=>__defNormalProp(e,"symbol"!=typeof t?t+"":t,r);!function(){"use strict";const e=Object.create(null);e.open="0",e.close="1",e.ping="2",e.pong="3",e.message="4",e.upgrade="5",e.noop="6";const t=Object.create(null);Object.keys(e).forEach(r=>{t[e[r]]=r});const r={type:"error",data:"parser error"},n="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),s="function"==typeof ArrayBuffer,i=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,o=({type:t,data:r},o,l)=>n&&r instanceof Blob?o?l(r):a(r,l):s&&(r instanceof ArrayBuffer||i(r))?o?l(r):a(new Blob([r]),l):l(e[t]+(r||"")),a=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function l(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let c;const h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",u="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let Xk=0;Xk<64;Xk++)u[h.charCodeAt(Xk)]=Xk;const d="function"==typeof ArrayBuffer,p=(e,n)=>{if("string"!=typeof e)return{type:"message",data:f(e,n)};const s=e.charAt(0);if("b"===s)return{type:"message",data:m(e.substring(1),n)};return t[s]?e.length>1?{type:t[s],data:e.substring(1)}:{type:t[s]}:r},m=(e,t)=>{if(d){const r=(e=>{let t,r,n,s,i,o=.75*e.length,a=e.length,l=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const c=new ArrayBuffer(o),h=new Uint8Array(c);for(t=0;t<a;t+=4)r=u[e.charCodeAt(t)],n=u[e.charCodeAt(t+1)],s=u[e.charCodeAt(t+2)],i=u[e.charCodeAt(t+3)],h[l++]=r<<2|n>>4,h[l++]=(15&n)<<4|s>>2,h[l++]=(3&s)<<6|63&i;return c})(e);return f(r,t)}return{base64:!0,data:e}},f=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,g=String.fromCharCode(30);function y(){return new TransformStream({transform(e,t){!function(e,t){n&&e.data instanceof Blob?e.data.arrayBuffer().then(l).then(t):s&&(e.data instanceof ArrayBuffer||i(e.data))?t(l(e.data)):o(e,!1,e=>{c||(c=new TextEncoder),t(c.encode(e))})}(e,r=>{const n=r.length;let s;if(n<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,n);else if(n<65536){s=new Uint8Array(3);const e=new DataView(s.buffer);e.setUint8(0,126),e.setUint16(1,n)}else{s=new Uint8Array(9);const e=new DataView(s.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(n))}e.data&&"string"!=typeof e.data&&(s[0]|=128),t.enqueue(s),t.enqueue(r)})}})}let b;function w(e){return e.reduce((e,t)=>e+t.length,0)}function k(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let n=0;for(let s=0;s<t;s++)r[s]=e[0][n++],n===e[0].length&&(e.shift(),n=0);return e.length&&n<e[0].length&&(e[0]=e[0].slice(n)),r}function v(e){if(e)return function(e){for(var t in v.prototype)e[t]=v.prototype[t];return e}(e)}v.prototype.on=v.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},v.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},v.prototype.off=v.prototype.removeListener=v.prototype.removeAllListeners=v.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var s=0;s<n.length;s++)if((r=n[s])===t||r.fn===t){n.splice(s,1);break}return 0===n.length&&delete this._callbacks["$"+e],this},v.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(r){n=0;for(var s=(r=r.slice(0)).length;n<s;++n)r[n].apply(this,t)}return this},v.prototype.emitReserved=v.prototype.emit,v.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},v.prototype.hasListeners=function(e){return!!this.listeners(e).length};const S="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),C="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function x(e,...t){return t.reduce((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t),{})}const I=C.setTimeout,O=C.clearTimeout;function A(e,t){t.useNativeTimers?(e.setTimeoutFn=I.bind(C),e.clearTimeoutFn=O.bind(C)):(e.setTimeoutFn=C.setTimeout.bind(C),e.clearTimeoutFn=C.clearTimeout.bind(C))}function E(e){return"string"==typeof e?function(e){let t=0,r=0;for(let n=0,s=e.length;n<s;n++)t=e.charCodeAt(n),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(n++,r+=4);return r}(e):Math.ceil(1.33*(e.byteLength||e.size))}function R(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class M extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class j extends v{constructor(e){super(),this.writable=!1,A(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,r){return super.emitReserved("error",new M(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=p(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}(e);return t.length?"?"+t:""}}class z extends j{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const r=e.split(g),n=[];for(let s=0;s<r.length;s++){const e=p(r[s],t);if(n.push(e),"error"===e.type)break}return n})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const r=e.length,n=new Array(r);let s=0;e.forEach((e,i)=>{o(e,!1,e=>{n[i]=e,++s===r&&t(n.join(g))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=R()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let N=!1;try{N="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(Hk){}const _=N;function T(){}class P extends z{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port}}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}class L extends v{constructor(e,t,r){super(),this.createRequest=e,A(this,r),this._opts=r,this._method=r.method||"GET",this._uri=t,this._data=void 0!==r.data?r.data:null,this._create()}_create(){var e;const t=x(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const r=this._xhr=this.createRequest(t);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(n){}if("POST"===this._method)try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(n){}try{r.setRequestHeader("Accept","*/*")}catch(n){}null===(e=this._opts.cookieJar)||void 0===e||e.addCookies(r),"withCredentials"in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var e;3===r.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(r.getResponseHeader("set-cookie"))),4===r.readyState&&(200===r.status||1223===r.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof r.status?r.status:0)},0))},r.send(this._data)}catch(n){return void this.setTimeoutFn(()=>{this._onError(n)},0)}"undefined"!=typeof document&&(this._index=L.requestsCount++,L.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=T,e)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete L.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(L.requestsCount=0,L.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",F);else if("function"==typeof addEventListener){addEventListener("onpagehide"in C?"pagehide":"unload",F,!1)}function F(){for(let e in L.requests)L.requests.hasOwnProperty(e)&&L.requests[e].abort()}const D=function(){const e=B({xdomain:!1});return e&&null!==e.responseType}();function B(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||_))return new XMLHttpRequest}catch(r){}if(!t)try{return new(C[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(r){}}const U="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class V extends j{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,r=U?{}:x(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,r)}catch(Hk){return this.emitReserved("error",Hk)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],n=t===e.length-1;o(r,this.supportsBinary,e=>{try{this.doWrite(r,e)}catch(t){}n&&S(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=R()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const W=C.WebSocket||C.MozWebSocket;const q={websocket:class extends V{createSocket(e,t,r){return U?new W(e,t,r):t?new W(e,t):new W(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends j{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(Hk){return this.emitReserved("error",Hk)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=function(e,t){b||(b=new TextDecoder);const n=[];let s=0,i=-1,o=!1;return new TransformStream({transform(a,l){for(n.push(a);;){if(0===s){if(w(n)<1)break;const e=k(n,1);o=!(128&~e[0]),i=127&e[0],s=i<126?3:126===i?1:2}else if(1===s){if(w(n)<2)break;const e=k(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),s=3}else if(2===s){if(w(n)<8)break;const e=k(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),o=t.getUint32(0);if(o>Math.pow(2,21)-1){l.enqueue(r);break}i=o*Math.pow(2,32)+t.getUint32(4),s=3}else{if(w(n)<i)break;const e=k(n,i);l.enqueue(p(o?e:b.decode(e),t)),s=0}if(0===i||i>e){l.enqueue(r);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),s=y();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();const i=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],n=t===e.length-1;this._writer.write(r).then(()=>{n&&S(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends P{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=D&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new L(B,this.uri(),e)}}},Y=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Z=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function G(e){if(e.length>8e3)throw"URI too long";const t=e,r=e.indexOf("["),n=e.indexOf("]");-1!=r&&-1!=n&&(e=e.substring(0,r)+e.substring(r,n).replace(/:/g,";")+e.substring(n,e.length));let s=Y.exec(e||""),i={},o=14;for(;o--;)i[Z[o]]=s[o]||"";return-1!=r&&-1!=n&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=function(e,t){const r=/\/{2,9}/g,n=t.replace(r,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1);"/"==t.slice(-1)&&n.splice(n.length-1,1);return n}(0,i.path),i.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,n){t&&(r[t]=n)}),r}(0,i.query),i}const J="function"==typeof addEventListener&&"function"==typeof removeEventListener,$=[];J&&addEventListener("offline",()=>{$.forEach(e=>e())},!1);class H extends v{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const r=G(e);t.hostname=r.host,t.secure="https"===r.protocol||"wss"===r.protocol,t.port=r.port,r.query&&(t.query=r.query)}else t.host&&(t.hostname=G(t.host).host);A(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{const t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},r=e.split("&");for(let n=0,s=r.length;n<s;n++){let e=r[n].split("=");t[decodeURIComponent(e[0])]=decodeURIComponent(e[1])}return t}(this.opts.query)),J&&(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"})},$.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](r)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&H.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",H.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const r=this.writeBuffer[t].data;if(r&&(e+=E(r)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,S(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,r){return this._sendPacket("message",e,t,r),this}send(e,t,r){return this._sendPacket("message",e,t,r),this}_sendPacket(e,t,r,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof r&&(n=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const s={type:e,data:t,options:r};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),n&&this.once("flush",n),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():e()}):this.upgrading?r():e()),this}_onError(e){if(H.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),J&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=$.indexOf(this._offlineEventListener);-1!==e&&$.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}H.protocol=4;class X extends H{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),r=!1;H.priorWebsocketSuccess=!1;const n=()=>{r||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!r)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;H.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{r||"closed"!==this.readyState&&(c(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function s(){r||(r=!0,c(),t.close(),t=null)}const i=e=>{const r=new Error("probe error: "+e);r.transport=t.name,s(),this.emitReserved("upgradeError",r)};function o(){i("transport closed")}function a(){i("socket closed")}function l(e){t&&e.name!==t.name&&s()}const c=()=>{t.removeListener("open",n),t.removeListener("error",i),t.removeListener("close",o),this.off("close",a),this.off("upgrading",l)};t.once("open",n),t.once("error",i),t.once("close",o),this.once("close",a),this.once("upgrading",l),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{r||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let r=0;r<e.length;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}}let K=class extends X{constructor(e,t={}){const r="object"==typeof e?e:t;(!r.transports||r.transports&&"string"==typeof r.transports[0])&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(e=>q[e]).filter(e=>!!e)),super(e,r)}};const Q="function"==typeof ArrayBuffer,ee=Object.prototype.toString,te="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===ee.call(Blob),re="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===ee.call(File);function ne(e){return Q&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||te&&e instanceof Blob||re&&e instanceof File}function se(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(se(e[t]))return!0;return!1}if(ne(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return se(e.toJSON(),!0);for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&se(e[r]))return!0;return!1}function ie(e){const t=[],r=e.data,n=e;return n.data=oe(r,t),n.attachments=t.length,{packet:n,buffers:t}}function oe(e,t){if(!e)return e;if(ne(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}if(Array.isArray(e)){const r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=oe(e[n],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=oe(e[n],t));return r}return e}function ae(e,t){return e.data=le(e.data,t),delete e.attachments,e}function le(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=le(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=le(e[r],t));return e}const ce=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var he,ue;(ue=he||(he={}))[ue.CONNECT=0]="CONNECT",ue[ue.DISCONNECT=1]="DISCONNECT",ue[ue.EVENT=2]="EVENT",ue[ue.ACK=3]="ACK",ue[ue.CONNECT_ERROR=4]="CONNECT_ERROR",ue[ue.BINARY_EVENT=5]="BINARY_EVENT",ue[ue.BINARY_ACK=6]="BINARY_ACK";function de(e){return"[object Object]"===Object.prototype.toString.call(e)}class pe extends v{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const r=t.type===he.BINARY_EVENT;r||t.type===he.BINARY_ACK?(t.type=r?he.EVENT:he.ACK,this.reconstructor=new me(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!ne(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const r={type:Number(e.charAt(0))};if(void 0===he[r.type])throw new Error("unknown packet type "+r.type);if(r.type===he.BINARY_EVENT||r.type===he.BINARY_ACK){const n=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const s=e.substring(n,t);if(s!=Number(s)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(s)}if("/"===e.charAt(t+1)){const n=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(n,t)}else r.nsp="/";const n=e.charAt(t+1);if(""!==n&&Number(n)==n){const n=t+1;for(;++t;){const r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){const n=this.tryParse(e.substr(t));if(!pe.isPayloadValid(r.type,n))throw new Error("invalid payload");r.data=n}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(t){return!1}}static isPayloadValid(e,t){switch(e){case he.CONNECT:return de(t);case he.DISCONNECT:return void 0===t;case he.CONNECT_ERROR:return"string"==typeof t||de(t);case he.EVENT:case he.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===ce.indexOf(t[0]));case he.ACK:case he.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class me{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=ae(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const fe=Object.freeze(Object.defineProperty({__proto__:null,Decoder:pe,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==he.EVENT&&e.type!==he.ACK||!se(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===he.EVENT?he.BINARY_EVENT:he.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==he.BINARY_EVENT&&e.type!==he.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=ie(e),r=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(r),n}},get PacketType(){return he},protocol:5},Symbol.toStringTag,{value:"Module"}));function ge(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const ye=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class be extends v{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[ge(e,"open",this.onopen.bind(this)),ge(e,"packet",this.onpacket.bind(this)),ge(e,"error",this.onerror.bind(this)),ge(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var r,n,s;if(ye.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const i={type:he.EVENT,data:t,options:{}};if(i.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,r=t.pop();this._registerAckCallback(e,r),i.id=e}const o=null===(n=null===(r=this.io.engine)||void 0===r?void 0:r.transport)||void 0===n?void 0:n.writable,a=this.connected&&!(null===(s=this.io.engine)||void 0===s?void 0:s._hasPingExpired());return this.flags.volatile&&!o||(a?(this.notifyOutgoingListeners(i),this.packet(i)):this.sendBuffer.push(i)),this.flags={},this}_registerAckCallback(e,t){var r;const n=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===n)return void(this.acks[e]=t);const s=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},n),i=(...e)=>{this.io.clearTimeoutFn(s),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((r,n)=>{const s=(e,t)=>e?n(e):r(t);s.withError=!0,t.push(s),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...n)=>{if(r!==this._queue[0])return;return null!==e?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...n)),r.pending=!1,this._drainQueue()}),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:he.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case he.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case he.EVENT:case he.BINARY_EVENT:this.onevent(e);break;case he.ACK:case he.BINARY_ACK:this.onack(e);break;case he.DISCONNECT:this.ondisconnect();break;case he.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let r=!1;return function(...n){r||(r=!0,t.packet({type:he.ACK,id:e,data:n}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:he.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const r of t)r.apply(this,e.data)}}}function we(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}we.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+r:e-r}return 0|Math.min(e,this.max)},we.prototype.reset=function(){this.attempts=0},we.prototype.setMin=function(e){this.ms=e},we.prototype.setMax=function(e){this.max=e},we.prototype.setJitter=function(e){this.jitter=e};class ke extends v{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,A(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=t.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new we({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const n=t.parser||fe;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new K(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const n=ge(t,"open",function(){r.onopen(),e&&e()}),s=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},i=ge(t,"error",s);if(!1!==this._timeout){const e=this._timeout,r=this.setTimeoutFn(()=>{n(),s(new Error("timeout")),t.close()},e);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}return this.subs.push(n),this.subs.push(i),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(ge(e,"ping",this.onping.bind(this)),ge(e,"data",this.ondata.bind(this)),ge(e,"error",this.onerror.bind(this)),ge(e,"close",this.onclose.bind(this)),ge(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){S(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new be(this,e,t),this.nsps[e]=r),r}_destroy(e){const t=Object.keys(this.nsps);for(const r of t){if(this.nsps[r].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;this.cleanup(),null===(r=this.engine)||void 0===r||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const ve={};function Se(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let n=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==r?r.protocol+"//"+e:"https://"+e),n=G(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const s=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+s+":"+n.port+t,n.href=n.protocol+"://"+s+(r&&r.port===n.port?"":":"+n.port),n}(e,(t=t||{}).path||"/socket.io"),n=r.source,s=r.id,i=r.path,o=ve[s]&&i in ve[s].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new ke(n,t):(ve[s]||(ve[s]=new ke(n,t)),a=ve[s]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}Object.assign(Se,{Manager:ke,Socket:be,io:Se,connect:Se});class Ce{constructor(e){__publicField(this,"socket"),__publicField(this,"encode"),__publicField(this,"decode"),this.socket=Se(e.baseUrl,{transports:["websocket"],path:"/analytics/ws",auth:{token:e.authToken},query:e.query}),this.encode=e.encoder??(e=>function(e){const t=(new TextEncoder).encode(e);if("undefined"!=typeof window&&"function"==typeof window.btoa){const e=Array.from(t,e=>String.fromCharCode(e)).join("");return btoa(e)}if("undefined"!=typeof Buffer)return Buffer.from(t).toString("base64");throw new Error("[utils.base64Encode]: Unsupported environment")}(JSON.stringify(e))),this.decode=e.decoder??(e=>JSON.parse((e=>{if("undefined"!=typeof window&&"function"==typeof window.atob){const t=atob(e),r=t.length,n=new Uint8Array(r);for(let e=0;e<r;e++)n[e]=t.charCodeAt(e);return(new TextDecoder).decode(n)}if("undefined"!=typeof Buffer)return Buffer.from(e,"base64").toString("utf-8");throw new Error("[utils.base64Decode]: Unsupported environment")})(e)))}send(e,t,r){"function"==typeof r?this.socket.emit(e,this.encode(t),r):this.socket.emit(e,this.encode(t))}on(e,t){this.socket.on(e,e=>t(this.decode(e)))}}class xe{constructor(e){if(__publicField(this,"defaultTTL"),__publicField(this,"items"),this.defaultTTL=e,e<=0)throw new Error("Default TTL must be a positive number.");this.items=new Map,this.defaultTTL=e,setInterval(()=>this.cleanup(),e)}add(e,t){const r=void 0!==t?t:this.defaultTTL;if(r<=0)throw new Error("TTL must be a positive number.");const n=Date.now()+r;this.items.set(e,n)}has(e){const t=this.items.get(e);return void 0!==t&&(!(Date.now()>t)||(this.items.delete(e),!1))}delete(e){this.items.delete(e)}get size(){return this.cleanup(),this.items.size}clear(){this.items.clear()}cleanup(){const e=Date.now();for(const[t,r]of this.items.entries())r<=e&&this.items.delete(t)}toArray(){return this.cleanup(),Array.from(this.items.keys())}}var Ie,Oe,Ae,Ee;(Oe=Ie||(Ie={})).OpenUrl="openUrl",Oe.CallPhone="callPhone",Oe.SendEmail="sendEmail",Oe.TriggerEvent="triggerEvent",(Ee=Ae||(Ae={})).Button="button",Ee.Link="link";class Re{constructor(e){__publicField(this,"options"),__publicField(this,"client"),__publicField(this,"userId"),__publicField(this,"global"),__publicField(this,"queue",[]),__publicField(this,"knownEvents",["nudge.show"]),__publicField(this,"eventListeners",{}),__publicField(this,"recentNudgeIds",new xe(1e3)),this.options=e;const t={sdk_name:e.sdk||"node",sdk_version:e.sdkVersion||""};this.client=new Ce({baseUrl:e.apiUrl||"https://analytic.brainfi.sh",authToken:e.accessKey,query:t}),this.setupIncomingPayloadHandler()}init(){}ready(){this.options.waitForUser=!1,this.flush()}setupIncomingPayloadHandler(){this.client.on("e",this.handleIncomingPayload.bind(this))}handleIncomingPayload(e){if("nudge.show"===e.type){const{nudgeId:t}=e.payload;if(this.recentNudgeIds.has(t))return;this.recentNudgeIds.add(t),this.dispatchEventListeners("nudge.show",e.payload)}}dispatchEventListeners(e,t){this.eventListeners[e]?.forEach(e=>e(t))}on(e,t){this.knownEvents.includes(e)&&(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(t))}off(e,t){this.knownEvents.includes(e)&&this.eventListeners[e]&&(this.eventListeners[e]=this.eventListeners[e].filter(e=>e!==t),0===this.eventListeners[e].length&&delete this.eventListeners[e])}async send(e,t){return this.options.disabled||this.options.filter&&!this.options.filter(e)?Promise.resolve():this.options.waitForUser&&!this.userId?(this.queue.push(e),Promise.resolve()):this.client.send("t",e,t)}setGlobalProperties(e){this.global={...this.global,...e}}async track(e,t){return this.send({type:"event.track",payload:{name:e,userId:t?.userId??this.userId,properties:{...this.global??{},...t??{}}}})}async identify(e){e.userId&&(this.userId=e.userId,this.flush());const t=document.querySelector("#bf-iframe-container .trigger-iframe");if(t){const r=()=>{t.contentWindow&&t.contentWindow.postMessage({type:"USER_IDENTIFY",payload:e},"*")};t.contentWindow&&r(),t.addEventListener("load",r)}if(Object.keys(e).length>1)return this.send({type:"user.identify",payload:{...e,properties:{...this.global,...e.properties}}})}async record(e,t){return this.send({type:"event.record",payload:{events:e,userId:this.userId}},t)}async alias(e){return this.send({type:"user.alias",payload:e})}async increment(e){return this.send({type:"user.increment",payload:e})}async decrement(e){return this.send({type:"user.decrement",payload:e})}clear(){this.userId=void 0}flush(){this.queue.forEach(e=>{this.send({...e,payload:{...e.payload,userId:e.payload.userId??this.userId}})}),this.queue=[]}}const Me=(()=>{let e=0;return()=>(e+=1,`u${`0000${(Math.random()*36**4|0).toString(36)}`.slice(-4)}${e}`)})();function je(e){const t=[];for(let r=0,n=e.length;r<n;r++)t.push(e[r]);return t}let ze=null;function Ne(e={}){return ze||(e.includeStyleProperties?(ze=e.includeStyleProperties,ze):(ze=je(window.getComputedStyle(document.documentElement)),ze))}function _e(e,t){const r=(e.ownerDocument.defaultView||window).getComputedStyle(e).getPropertyValue(t);return r?parseFloat(r.replace("px","")):0}function Te(e,t={}){return{width:t.width||function(e){const t=_e(e,"border-left-width"),r=_e(e,"border-right-width");return e.clientWidth+t+r}(e),height:t.height||function(e){const t=_e(e,"border-top-width"),r=_e(e,"border-bottom-width");return e.clientHeight+t+r}(e)}}const Pe=16384;function Le(e){return new Promise((t,r)=>{const n=new Image;n.onload=()=>{n.decode().then(()=>{requestAnimationFrame(()=>t(n))})},n.onerror=r,n.crossOrigin="anonymous",n.decoding="async",n.src=e})}async function Fe(e,t,r){const n="http://www.w3.org/2000/svg",s=document.createElementNS(n,"svg"),i=document.createElementNS(n,"foreignObject");return s.setAttribute("width",`${t}`),s.setAttribute("height",`${r}`),s.setAttribute("viewBox",`0 0 ${t} ${r}`),i.setAttribute("width","100%"),i.setAttribute("height","100%"),i.setAttribute("x","0"),i.setAttribute("y","0"),i.setAttribute("externalResourcesRequired","true"),s.appendChild(i),i.appendChild(e),async function(e){return Promise.resolve().then(()=>(new XMLSerializer).serializeToString(e)).then(encodeURIComponent).then(e=>`data:image/svg+xml;charset=utf-8,${e}`)}(s)}const De=(e,t)=>{if(e instanceof t)return!0;const r=Object.getPrototypeOf(e);return null!==r&&(r.constructor.name===t.name||De(r,t))};function Be(e,t,r,n){const s=`.${e}:${t}`,i=r.cssText?function(e){const t=e.getPropertyValue("content");return`${e.cssText} content: '${t.replace(/'|"/g,"")}';`}(r):function(e,t){return Ne(t).map(t=>`${t}: ${e.getPropertyValue(t)}${e.getPropertyPriority(t)?" !important":""};`).join(" ")}(r,n);return document.createTextNode(`${s}{${i}}`)}function Ue(e,t,r,n){const s=window.getComputedStyle(e,r),i=s.getPropertyValue("content");if(""===i||"none"===i)return;const o=Me();try{t.className=`${t.className} ${o}`}catch(Hk){return}const a=document.createElement("style");a.appendChild(Be(o,r,s,n)),t.appendChild(a)}const Ve="application/font-woff",We="image/jpeg",qe={woff:Ve,woff2:Ve,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:We,jpeg:We,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function Ye(e){const t=function(e){const t=/\.([^./]*?)$/g.exec(e);return t?t[1]:""}(e).toLowerCase();return qe[t]||""}function Ze(e){return-1!==e.search(/^(data:)/)}async function Ge(e,t,r){const n=await fetch(e,t);if(404===n.status)throw new Error(`Resource "${n.url}" not found`);const s=await n.blob();return new Promise((e,t)=>{const i=new FileReader;i.onerror=t,i.onloadend=()=>{try{e(r({res:n,result:i.result}))}catch(s){t(s)}},i.readAsDataURL(s)})}const Je={};async function $e(e,t,r){const n=function(e,t,r){let n=e.replace(/\?.*/,"");return r&&(n=e),/ttf|otf|eot|woff2?/i.test(n)&&(n=n.replace(/.*\//,"")),t?`[${t}]${n}`:n}(e,t,r.includeQueryParams);if(null!=Je[n])return Je[n];let s;r.cacheBust&&(e+=(/\?/.test(e)?"&":"?")+(new Date).getTime());try{const n=await Ge(e,r.fetchRequestInit,({res:e,result:r})=>(t||(t=e.headers.get("Content-Type")||""),function(e){return e.split(/,/)[1]}(r)));s=function(e,t){return`data:${t};base64,${e}`}(n,t)}catch(i){s=r.imagePlaceholder||"";let t=`Failed to fetch resource: ${e}`;i&&(t="string"==typeof i?i:i.message),t&&console.warn(t)}return Je[n]=s,s}async function He(e,t){return De(e,HTMLCanvasElement)?async function(e){const t=e.toDataURL();return"data:,"===t?e.cloneNode(!1):Le(t)}(e):De(e,HTMLVideoElement)?async function(e,t){if(e.currentSrc){const t=document.createEleme