@brainfish-ai/web-tracker
Version:
Brainfish Tracker for Web
1 lines • 375 kB
JavaScript
var __defProp=Object.defineProperty,__defNormalProp=(e,t,s)=>t in e?__defProp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,__publicField=(e,t,s)=>__defNormalProp(e,"symbol"!=typeof t?t+"":t,s);!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(s=>{t[e[s]]=s});const s={type:"error",data:"parser error"},r="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),n="function"==typeof ArrayBuffer,i=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,o=({type:t,data:s},o,l)=>r&&s instanceof Blob?o?l(s):a(s,l):n&&(s instanceof ArrayBuffer||i(s))?o?l(s):a(new Blob([s]),l):l(e[t]+(s||"")),a=(e,t)=>{const s=new FileReader;return s.onload=function(){const e=s.result.split(",")[1];t("b"+(e||""))},s.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 $b=0;$b<64;$b++)u[h.charCodeAt($b)]=$b;const p="function"==typeof ArrayBuffer,d=(e,r)=>{if("string"!=typeof e)return{type:"message",data:m(e,r)};const n=e.charAt(0);if("b"===n)return{type:"message",data:f(e.substring(1),r)};return t[n]?e.length>1?{type:t[n],data:e.substring(1)}:{type:t[n]}:s},f=(e,t)=>{if(p){const s=(e=>{let t,s,r,n,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)s=u[e.charCodeAt(t)],r=u[e.charCodeAt(t+1)],n=u[e.charCodeAt(t+2)],i=u[e.charCodeAt(t+3)],h[l++]=s<<2|r>>4,h[l++]=(15&r)<<4|n>>2,h[l++]=(3&n)<<6|63&i;return c})(e);return m(s,t)}return{base64:!0,data:e}},m=(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){r&&e.data instanceof Blob?e.data.arrayBuffer().then(l).then(t):n&&(e.data instanceof ArrayBuffer||i(e.data))?t(l(e.data)):o(e,!1,e=>{c||(c=new TextEncoder),t(c.encode(e))})}(e,s=>{const r=s.length;let n;if(r<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,r);else if(r<65536){n=new Uint8Array(3);const e=new DataView(n.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{n=new Uint8Array(9);const e=new DataView(n.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&"string"!=typeof e.data&&(n[0]|=128),t.enqueue(n),t.enqueue(s)})}})}let w;function b(e){return e.reduce((e,t)=>e+t.length,0)}function v(e,t){if(e[0].length===t)return e.shift();const s=new Uint8Array(t);let r=0;for(let n=0;n<t;n++)s[n]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),s}function C(e){if(e)return function(e){for(var t in C.prototype)e[t]=C.prototype[t];return e}(e)}C.prototype.on=C.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},C.prototype.once=function(e,t){function s(){this.off(e,s),t.apply(this,arguments)}return s.fn=t,this.on(e,s),this},C.prototype.off=C.prototype.removeListener=C.prototype.removeAllListeners=C.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var s,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var n=0;n<r.length;n++)if((s=r[n])===t||s.fn===t){r.splice(n,1);break}return 0===r.length&&delete this._callbacks["$"+e],this},C.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),s=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(s){r=0;for(var n=(s=s.slice(0)).length;r<n;++r)s[r].apply(this,t)}return this},C.prototype.emitReserved=C.prototype.emit,C.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},C.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),k="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function I(e,...t){return t.reduce((t,s)=>(e.hasOwnProperty(s)&&(t[s]=e[s]),t),{})}const x=k.setTimeout,O=k.clearTimeout;function A(e,t){t.useNativeTimers?(e.setTimeoutFn=x.bind(k),e.clearTimeoutFn=O.bind(k)):(e.setTimeoutFn=k.setTimeout.bind(k),e.clearTimeoutFn=k.clearTimeout.bind(k))}function E(e){return"string"==typeof e?function(e){let t=0,s=0;for(let r=0,n=e.length;r<n;r++)t=e.charCodeAt(r),t<128?s+=1:t<2048?s+=2:t<55296||t>=57344?s+=3:(r++,s+=4);return s}(e):Math.ceil(1.33*(e.byteLength||e.size))}function R(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class M extends Error{constructor(e,t,s){super(e),this.description=t,this.context=s,this.type="TransportError"}}class N extends C{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,s){return super.emitReserved("error",new M(e,t,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=d(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 s in e)e.hasOwnProperty(s)&&(t.length&&(t+="&"),t+=encodeURIComponent(s)+"="+encodeURIComponent(e[s]));return t}(e);return t.length?"?"+t:""}}class _ extends N{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const s=e.split(g),r=[];for(let n=0;n<s.length;n++){const e=d(s[n],t);if(r.push(e),"error"===e.type)break}return r})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const s=e.length,r=new Array(s);let n=0;e.forEach((e,i)=>{o(e,!1,e=>{r[i]=e,++n===s&&t(r.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 T=!1;try{T="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(Kb){}const P=T;function L(){}class F extends _{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let s=location.port;s||(s=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||s!==e.port}}doWrite(e,t){const s=this.request({method:"POST",data:e});s.on("success",t),s.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}class D extends C{constructor(e,t,s){super(),this.createRequest=e,A(this,s),this._opts=s,this._method=s.method||"GET",this._uri=t,this._data=void 0!==s.data?s.data:null,this._create()}_create(){var e;const t=I(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(t);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&s.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(r){}if("POST"===this._method)try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(r){}try{s.setRequestHeader("Accept","*/*")}catch(r){}null===(e=this._opts.cookieJar)||void 0===e||e.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var e;3===s.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(s.getResponseHeader("set-cookie"))),4===s.readyState&&(200===s.status||1223===s.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof s.status?s.status:0)},0))},s.send(this._data)}catch(r){return void this.setTimeoutFn(()=>{this._onError(r)},0)}"undefined"!=typeof document&&(this._index=D.requestsCount++,D.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=L,e)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete D.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(D.requestsCount=0,D.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",B);else if("function"==typeof addEventListener){addEventListener("onpagehide"in k?"pagehide":"unload",B,!1)}function B(){for(let e in D.requests)D.requests.hasOwnProperty(e)&&D.requests[e].abort()}const U=function(){const e=j({xdomain:!1});return e&&null!==e.responseType}();function j(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||P))return new XMLHttpRequest}catch(s){}if(!t)try{return new(k[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(s){}}const z="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class V extends N{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=z?{}:I(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,s)}catch(Kb){return this.emitReserved("error",Kb)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],r=t===e.length-1;o(s,this.supportsBinary,e=>{try{this.doWrite(s,e)}catch(t){}r&&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=k.WebSocket||k.MozWebSocket;const Y={websocket:class extends V{createSocket(e,t,s){return z?new W(e,t,s):t?new W(e,t):new W(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends N{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(Kb){return this.emitReserved("error",Kb)}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){w||(w=new TextDecoder);const r=[];let n=0,i=-1,o=!1;return new TransformStream({transform(a,l){for(r.push(a);;){if(0===n){if(b(r)<1)break;const e=v(r,1);o=!(128&~e[0]),i=127&e[0],n=i<126?3:126===i?1:2}else if(1===n){if(b(r)<2)break;const e=v(r,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),n=3}else if(2===n){if(b(r)<8)break;const e=v(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),o=t.getUint32(0);if(o>Math.pow(2,21)-1){l.enqueue(s);break}i=o*Math.pow(2,32)+t.getUint32(4),n=3}else{if(b(r)<i)break;const e=v(r,i);l.enqueue(d(o?e:w.decode(e),t)),n=0}if(0===i||i>e){l.enqueue(s);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),n=y();n.readable.pipeTo(e.writable),this._writer=n.writable.getWriter();const i=()=>{r.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 s=e[t],r=t===e.length-1;this._writer.write(s).then(()=>{r&&S(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends F{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=U&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new D(j,this.uri(),e)}}},G=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(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 J(e){if(e.length>8e3)throw"URI too long";const t=e,s=e.indexOf("["),r=e.indexOf("]");-1!=s&&-1!=r&&(e=e.substring(0,s)+e.substring(s,r).replace(/:/g,";")+e.substring(r,e.length));let n=G.exec(e||""),i={},o=14;for(;o--;)i[Z[o]]=n[o]||"";return-1!=s&&-1!=r&&(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 s=/\/{2,9}/g,r=t.replace(s,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||r.splice(0,1);"/"==t.slice(-1)&&r.splice(r.length-1,1);return r}(0,i.path),i.queryKey=function(e,t){const s={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(s[t]=r)}),s}(0,i.query),i}const X="function"==typeof addEventListener&&"function"==typeof removeEventListener,H=[];X&&addEventListener("offline",()=>{H.forEach(e=>e())},!1);class K extends C{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const s=J(e);t.hostname=s.host,t.secure="https"===s.protocol||"wss"===s.protocol,t.port=s.port,s.query&&(t.query=s.query)}else t.host&&(t.hostname=J(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={},s=e.split("&");for(let r=0,n=s.length;r<n;r++){let e=s[r].split("=");t[decodeURIComponent(e[0])]=decodeURIComponent(e[1])}return t}(this.opts.query)),X&&(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"})},H.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const s=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](s)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&K.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",K.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const s=this.writeBuffer[t].data;if(s&&(e+=E(s)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,S(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,s){return this._sendPacket("message",e,t,s),this}send(e,t,s){return this._sendPacket("message",e,t,s),this}_sendPacket(e,t,s,r){if("function"==typeof t&&(r=t,t=void 0),"function"==typeof s&&(r=s,s=null),"closing"===this.readyState||"closed"===this.readyState)return;(s=s||{}).compress=!1!==s.compress;const n={type:e,data:t,options:s};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},s=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():e()}):this.upgrading?s():e()),this}_onError(e){if(K.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(),X&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=H.indexOf(this._offlineEventListener);-1!==e&&H.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}K.protocol=4;class $ extends K{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),s=!1;K.priorWebsocketSuccess=!1;const r=()=>{s||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!s)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;K.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{s||"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 n(){s||(s=!0,c(),t.close(),t=null)}const i=e=>{const s=new Error("probe error: "+e);s.transport=t.name,n(),this.emitReserved("upgradeError",s)};function o(){i("transport closed")}function a(){i("socket closed")}function l(e){t&&e.name!==t.name&&n()}const c=()=>{t.removeListener("open",r),t.removeListener("error",i),t.removeListener("close",o),this.off("close",a),this.off("upgrading",l)};t.once("open",r),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(()=>{s||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let s=0;s<e.length;s++)~this.transports.indexOf(e[s])&&t.push(e[s]);return t}}let q=class extends ${constructor(e,t={}){const s="object"==typeof e?e:t;(!s.transports||s.transports&&"string"==typeof s.transports[0])&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(e=>Y[e]).filter(e=>!!e)),super(e,s)}};const Q="function"==typeof ArrayBuffer,ee=Object.prototype.toString,te="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===ee.call(Blob),se="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===ee.call(File);function re(e){return Q&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||te&&e instanceof Blob||se&&e instanceof File}function ne(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,s=e.length;t<s;t++)if(ne(e[t]))return!0;return!1}if(re(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return ne(e.toJSON(),!0);for(const s in e)if(Object.prototype.hasOwnProperty.call(e,s)&&ne(e[s]))return!0;return!1}function ie(e){const t=[],s=e.data,r=e;return r.data=oe(s,t),r.attachments=t.length,{packet:r,buffers:t}}function oe(e,t){if(!e)return e;if(re(e)){const s={_placeholder:!0,num:t.length};return t.push(e),s}if(Array.isArray(e)){const s=new Array(e.length);for(let r=0;r<e.length;r++)s[r]=oe(e[r],t);return s}if("object"==typeof e&&!(e instanceof Date)){const s={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(s[r]=oe(e[r],t));return s}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 s=0;s<e.length;s++)e[s]=le(e[s],t);else if("object"==typeof e)for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(e[s]=le(e[s],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 pe(e){return"[object Object]"===Object.prototype.toString.call(e)}class de extends C{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const s=t.type===he.BINARY_EVENT;s||t.type===he.BINARY_ACK?(t.type=s?he.EVENT:he.ACK,this.reconstructor=new fe(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!re(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const s={type:Number(e.charAt(0))};if(void 0===he[s.type])throw new Error("unknown packet type "+s.type);if(s.type===he.BINARY_EVENT||s.type===he.BINARY_ACK){const r=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const n=e.substring(r,t);if(n!=Number(n)||"-"!==e.charAt(t))throw new Error("Illegal attachments");s.attachments=Number(n)}if("/"===e.charAt(t+1)){const r=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}s.nsp=e.substring(r,t)}else s.nsp="/";const r=e.charAt(t+1);if(""!==r&&Number(r)==r){const r=t+1;for(;++t;){const s=e.charAt(t);if(null==s||Number(s)!=s){--t;break}if(t===e.length)break}s.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(!de.isPayloadValid(s.type,r))throw new Error("invalid payload");s.data=r}return s}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(t){return!1}}static isPayloadValid(e,t){switch(e){case he.CONNECT:return pe(t);case he.DISCONNECT:return void 0===t;case he.CONNECT_ERROR:return"string"==typeof t||pe(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 fe{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 me=Object.freeze(Object.defineProperty({__proto__:null,Decoder:de,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==he.EVENT&&e.type!==he.ACK||!ne(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),s=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(s),r}},get PacketType(){return he},protocol:5},Symbol.toStringTag,{value:"Module"}));function ge(e,t,s){return e.on(t,s),function(){e.off(t,s)}}const ye=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class we extends C{constructor(e,t,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[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 s,r,n;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++,s=t.pop();this._registerAckCallback(e,s),i.id=e}const o=null===(r=null===(s=this.io.engine)||void 0===s?void 0:s.transport)||void 0===r?void 0:r.writable,a=this.connected&&!(null===(n=this.io.engine)||void 0===n?void 0:n._hasPingExpired());return this.flags.volatile&&!o||(a?(this.notifyOutgoingListeners(i),this.packet(i)):this.sendBuffer.push(i)),this.flags={},this}_registerAckCallback(e,t){var s;const r=null!==(s=this.flags.timeout)&&void 0!==s?s:this._opts.ackTimeout;if(void 0===r)return void(this.acks[e]=t);const n=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},r),i=(...e)=>{this.io.clearTimeoutFn(n),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((s,r)=>{const n=(e,t)=>e?r(e):s(t);n.withError=!0,t.push(n),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>{if(s!==this._queue[0])return;return null!==e?s.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...r)),s.pending=!1,this._drainQueue()}),this._queue.push(s),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type: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 s of t)s.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let s=!1;return function(...r){s||(s=!0,t.packet({type:he.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.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 s=0;s<t.length;s++)if(e===t[s])return t.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let s=0;s<t.length;s++)if(e===t[s])return t.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const s of t)s.apply(this,e.data)}}}function be(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}be.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),s=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+s:e-s}return 0|Math.min(e,this.max)},be.prototype.reset=function(){this.attempts=0},be.prototype.setMin=function(e){this.ms=e},be.prototype.setMax=function(e){this.max=e},be.prototype.setJitter=function(e){this.jitter=e};class ve extends C{constructor(e,t){var s;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,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!==(s=t.randomizationFactor)&&void 0!==s?s:.5),this.backoff=new be({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||me;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new q(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=ge(t,"open",function(){s.onopen(),e&&e()}),n=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},i=ge(t,"error",n);if(!1!==this._timeout){const e=this._timeout,s=this.setTimeoutFn(()=>{r(),n(new Error("timeout")),t.close()},e);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}return this.subs.push(r),this.subs.push(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 s=this.nsps[e];return s?this._autoConnect&&!s.active&&s.connect():(s=new we(this,e,t),this.nsps[e]=s),s}_destroy(e){const t=Object.keys(this.nsps);for(const s of t){if(this.nsps[s].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let s=0;s<t.length;s++)this.engine.write(t[s],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var s;this.cleanup(),null===(s=this.engine)||void 0===s||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const Ce={};function Se(e,t){"object"==typeof e&&(t=e,e=void 0);const s=function(e,t="",s){let r=e;s=s||"undefined"!=typeof location&&location,null==e&&(e=s.protocol+"//"+s.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?s.protocol+e:s.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==s?s.protocol+"//"+e:"https://"+e),r=J(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const n=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+n+":"+r.port+t,r.href=r.protocol+"://"+n+(s&&s.port===r.port?"":":"+r.port),r}(e,(t=t||{}).path||"/socket.io"),r=s.source,n=s.id,i=s.path,o=Ce[n]&&i in Ce[n].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new ve(r,t):(Ce[n]||(Ce[n]=new ve(r,t)),a=Ce[n]),s.query&&!t.query&&(t.query=s.queryKey),a.socket(s.path,t)}Object.assign(Se,{Manager:ve,Socket:we,io:Se,connect:Se});class ke{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),s=t.length,r=new Uint8Array(s);for(let e=0;e<s;e++)r[e]=t.charCodeAt(e);return(new TextDecoder).decode(r)}if("undefined"!=typeof Buffer)return Buffer.from(e,"base64").toString("utf-8");throw new Error("[utils.base64Decode]: Unsupported environment")})(e)))}send(e,t,s){"function"==typeof s?this.socket.emit(e,this.encode(t),s):this.socket.emit(e,this.encode(t))}on(e,t){this.socket.on(e,e=>t(this.decode(e)))}}class Ie{constructor(e){__publicField(this,"baseUrl"),__publicField(this,"authToken"),__publicField(this,"sdkMetadata"),this.baseUrl=e.baseUrl,this.authToken=e.authToken,this.sdkMetadata=e.sdkMetadata}async send(e,t){const s=new URL(e,this.baseUrl),r={...t,...this.sdkMetadata&&{sdk:this.sdkMetadata}};try{const e=await fetch(s.toString(),{method:"POST",headers:{"Content-Type":"application/json",...this.authToken&&{Authorization:`Bearer ${this.authToken}`}},body:JSON.stringify(r)});if(!e.ok)return null;let t;try{t=await e.json()}catch{t={}}return t}catch(n){}}}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 s=void 0!==t?t:this.defaultTTL;if(s<=0)throw new Error("TTL must be a positive number.");const r=Date.now()+s;this.items.set(e,r)}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,s]of this.items.entries())s<=e&&this.items.delete(t)}toArray(){return this.cleanup(),Array.from(this.items.keys())}}let Oe=null;var Ae,Ee,Re,Me;"undefined"!=typeof window&&window.addEventListener("message",e=>{if("https://agent.brainfi.sh"===e.origin&&"REQUEST_USER_IDENTITY"===e.data?.type&&Oe&&e.source){const t=document.querySelector("#bf-iframe-container .trigger-iframe");if(!t||e.source!==t.contentWindow)return void console.warn("BrainfishWidgetWarn: Rejected REQUEST_USER_IDENTITY from untrusted iframe source:",e.origin);e.source.postMessage({type:"USER_IDENTIFY",payload:Oe},e.origin)}}),(Ee=Ae||(Ae={})).OpenUrl="openUrl",Ee.CallPhone="callPhone",Ee.SendEmail="sendEmail",Ee.TriggerEvent="triggerEvent",(Me=Re||(Re={})).Button="button",Me.Link="link";const Ne=class e{constructor(t){__publicField(this,"options"),__publicField(this,"client"),__publicField(this,"httpClient"),__publicField(this,"userId"),__publicField(this,"global"),__publicField(this,"queue",[]),__publicField(this,"knownEvents",["nudge.show"]),__publicField(this,"eventListeners",{}),__publicField(this,"recentNudgeIds",new xe(1e3)),__publicField(this,"trackingDisabled",!1),this.options=t;const s={sdk_name:t.sdk||"node",sdk_version:t.sdkVersion||""},r=t.apiUrl||"https://analytic.brainfi.sh",n=t.accessKey;this.client=new ke({baseUrl:r,authToken:n,query:s}),this.httpClient=new Ie({baseUrl:r,authToken:n,sdkMetadata:{name:t.sdk||"node",version:t.sdkVersion||""}}),"undefined"!=typeof window&&"undefined"!=typeof localStorage&&(this.trackingDisabled="true"===localStorage.getItem(e.TRACKING_DISABLED_KEY)),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.trackingDisabled||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,s){return this.send({type:"event.track",payload:{name:e,userId:t?.userId??this.userId,properties:{...this.global??{},...t??{},...s?{_bfOverrides:s}:{}}}})}async identify(e){e.userId?(this.userId=e.userId,this.flush()):console.warn("BrainfishWidgetWarn: `.identify` called without a userId. User identification requires a valid userId to be provided.");const t=new Set(["userId","firstName","lastName","email","phone","avatar","properties"]),s=Object.keys(e).filter(e=>!t.has(e));s.length>0&&console.warn(`BrainfishWidgetWarn: The following fields are not recognized as main identifier fields: ${s.join(", ")}. Please place custom fields under the 'properties' object instead. Note: Using fields incorrectly may cause user identification to not work as expected.`),e.phone&&!/^\+[1-9]\d{1,14}$/.test(e.phone)&&console.warn("BrainfishWidgetWarn: phone should be in E.164 format (e.g., +14155552671). Providing the correct format ensures accurate user identification."),Oe=e;const r=document.querySelector("#bf-iframe-container .trigger-iframe");if(r){const t=()=>{r.contentWindow&&r.contentWindow.postMessage({type:"USER_IDENTIFY",payload:e},"*")};r.contentWindow&&t(),r.addEventListener("load",t)}if(Object.keys(e).length>1)return this.send({type:"user.identify",payload:{...e,properties:{...this.global,...e.properties}}})}async record(e){if(this.options.disabled)return Promise.resolve(null);if(this.trackingDisabled)return Promise.resolve(null);const t={type:"event.record",payload:{events:e,userId:this.userId}};if(this.options.filter&&!this.options.filter(t))return Promise.resolve(null);const s=await this.httpClient.send("/s",{events:e,userId:this.userId});return s?.sessionId||null}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=[]}disableTracking(){this.trackingDisabled=!0,"undefined"!=typeof window&&"undefined"!=typeof localStorage&&localStorage.setItem(e.TRACKING_DISABLED_KEY,"true")}enableTracking(){this.trackingDisabled=!1,"undefined"!=typeof window&&"undefined"!=typeof localStorage&&localStorage.removeItem(e.TRACKING_DISABLED_KEY),console.log("Brainfish tracking re-enabled. Refresh page for full effect.")}isTrackingDisabled(){return this.trackingDisabled}};__publicField(Ne,"TRACKING_DISABLED_KEY","bf_tracking_disabled");let _e=Ne;var Te,Pe=Object.defineProperty,Le=(e,t,s)=>((e,t,s)=>t in e?Pe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s),Fe=Object.defineProperty,De=(e,t,s)=>((e,t,s)=>t in e?Fe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s),Be=(e=>(e[e.Document=0]="Document",e[e.DocumentType=1]="DocumentType",e[e.Element=2]="Element",e[e.Text=3]="Text",e[e.CDATA=4]="CDATA",e[e.Comment=5]="Comment",e))(Be||{});const Ue={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},je={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},ze={};function Ve(e){if(ze[e])return ze[e];const t=globalThis[e],s=t.prototype,r=e in Ue?Ue[e]:void 0,n=Boolean(r&&r.every(e=>{var t,r;return Boolean(null==(r=null==(t=Object.getOwnP