diff --git a/.DS_Store b/.DS_Store index fd15415..83bd49c 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/composer-bot-extensions/composer-bot-extensions/background.js b/composer-bot-extensions/composer-bot-extensions/background.js index e8d056a..b86eb19 100644 --- a/composer-bot-extensions/composer-bot-extensions/background.js +++ b/composer-bot-extensions/composer-bot-extensions/background.js @@ -1 +1 @@ -const y=Object.create(null);y.open="0";y.close="1";y.ping="2";y.pong="3";y.message="4";y.upgrade="5";y.noop="6";const S=Object.create(null);Object.keys(y).forEach(n=>{S[y[n]]=n});const I={type:"error",data:"parser error"},ee=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",te=typeof ArrayBuffer=="function",se=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,$=({type:n,data:e},t,s)=>ee&&e instanceof Blob?t?s(e):J(e,s):te&&(e instanceof ArrayBuffer||se(e))?t?s(e):J(new Blob([e]),s):s(y[n]+(e||"")),J=(n,e)=>{const t=new FileReader;return t.onload=function(){const s=t.result.split(",")[1];e("b"+(s||""))},t.readAsDataURL(n)};function X(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let P;function pe(n,e){if(ee&&n.data instanceof Blob)return n.data.arrayBuffer().then(X).then(e);if(te&&(n.data instanceof ArrayBuffer||se(n.data)))return e(X(n.data));$(n,!1,t=>{P||(P=new TextEncoder),e(P.encode(t))})}const G="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",k=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n{let e=n.length*.75,t=n.length,s,i=0,r,o,c,h;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);const m=new ArrayBuffer(e),f=new Uint8Array(m);for(s=0;s>4,f[i++]=(o&15)<<4|c>>2,f[i++]=(c&3)<<6|h&63;return m},ye=typeof ArrayBuffer=="function",K=(n,e)=>{if(typeof n!="string")return{type:"message",data:ne(n,e)};const t=n.charAt(0);return t==="b"?{type:"message",data:me(n.substring(1),e)}:S[t]?n.length>1?{type:S[t],data:n.substring(1)}:{type:S[t]}:I},me=(n,e)=>{if(ye){const t=de(n);return ne(t,e)}else return{base64:!0,data:n}},ne=(n,e)=>{switch(e){case"blob":return n instanceof Blob?n:new Blob([n]);case"arraybuffer":default:return n instanceof ArrayBuffer?n:n.buffer}},ie="",ge=(n,e)=>{const t=n.length,s=new Array(t);let i=0;n.forEach((r,o)=>{$(r,!1,c=>{s[o]=c,++i===t&&e(s.join(ie))})})},_e=(n,e)=>{const t=n.split(ie),s=[];for(let i=0;i{const s=t.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const r=new DataView(i.buffer);r.setUint8(0,126),r.setUint16(1,s)}else{i=new Uint8Array(9);const r=new DataView(i.buffer);r.setUint8(0,127),r.setBigUint64(1,BigInt(s))}n.data&&typeof n.data!="string"&&(i[0]|=128),e.enqueue(i),e.enqueue(t)})}})}let q;function T(n){return n.reduce((e,t)=>e+t.length,0)}function A(n,e){if(n[0].length===e)return n.shift();const t=new Uint8Array(e);let s=0;for(let i=0;iMath.pow(2,21)-1){c.enqueue(I);break}i=f*Math.pow(2,32)+m.getUint32(4),s=3}else{if(T(t)n){c.enqueue(I);break}}}})}const re=4;function u(n){if(n)return Ee(n)}function Ee(n){for(var e in u.prototype)n[e]=u.prototype[e];return n}u.prototype.on=u.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};u.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};u.prototype.off=u.prototype.removeListener=u.prototype.removeAllListeners=u.prototype.removeEventListener=function(n,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+n];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;for(var s,i=0;iPromise.resolve().then(e):(e,t)=>t(e,0),l=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),ve="arraybuffer";function oe(n,...e){return e.reduce((t,s)=>(n.hasOwnProperty(s)&&(t[s]=n[s]),t),{})}const ke=l.setTimeout,Te=l.clearTimeout;function L(n,e){e.useNativeTimers?(n.setTimeoutFn=ke.bind(l),n.clearTimeoutFn=Te.bind(l)):(n.setTimeoutFn=l.setTimeout.bind(l),n.clearTimeoutFn=l.clearTimeout.bind(l))}const Ae=1.33;function Re(n){return typeof n=="string"?Se(n):Math.ceil((n.byteLength||n.size)*Ae)}function Se(n){let e=0,t=0;for(let s=0,i=n.length;s=57344?t+=3:(s++,t+=4);return t}function ae(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Oe(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function Ce(n){let e={},t=n.split("&");for(let s=0,i=t.length;s{this.readyState="paused",e()};if(this._polling||!this.writable){let s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||t()})),this.writable||(s++,this.once("drain",function(){--s||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const t=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};_e(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,ge(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=ae()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let ce=!1;try{ce=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const xe=ce;function Le(){}class Pe extends Ne{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let s=location.port;s||(s=t?"443":"80"),this.xd=typeof location<"u"&&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",(i,r)=>{this.onError("xhr post error",i,r)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,s)=>{this.onError("xhr poll error",t,s)}),this.pollXhr=e}}class d extends u{constructor(e,t,s){super(),this.createRequest=e,L(this,s),this._opts=s,this._method=s.method||"GET",this._uri=t,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var e;const t=oe(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 i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&s.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var i;s.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=d.requestsCount++,d.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Le,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete d.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}d.requestsCount=0;d.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Q);else if(typeof addEventListener=="function"){const n="onpagehide"in l?"pagehide":"unload";addEventListener(n,Q,!1)}}function Q(){for(let n in d.requests)d.requests.hasOwnProperty(n)&&d.requests[n].abort()}const qe=function(){const n=he({xdomain:!1});return n&&n.responseType!==null}();class De extends Pe{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=qe&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new d(he,this.uri(),e)}}function he(n){const e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||xe))return new XMLHttpRequest}catch{}if(!e)try{return new l[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const ue=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Ie extends W{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=ue?{}:oe(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(i){return this.emitReserved("error",i)}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{try{this.doWrite(s,r)}catch{}i&&x(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(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]=ae()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const D=l.WebSocket||l.MozWebSocket;class Ue extends Ie{createSocket(e,t,s){return ue?new D(e,t,s):t?new D(e,t):new D(e)}doWrite(e,t){this.ws.send(t)}}class Ve extends W{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=we(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),i=be();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const r=()=>{s.read().then(({done:c,value:h})=>{c||(this.onPacket(h),r())}).catch(c=>{})};r();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{i&&x(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const Fe={websocket:Ue,webtransport:Ve,polling:De},Me=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,He=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function U(n){if(n.length>8e3)throw"URI too long";const e=n,t=n.indexOf("["),s=n.indexOf("]");t!=-1&&s!=-1&&(n=n.substring(0,t)+n.substring(t,s).replace(/:/g,";")+n.substring(s,n.length));let i=Me.exec(n||""),r={},o=14;for(;o--;)r[He[o]]=i[o]||"";return t!=-1&&s!=-1&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=$e(r,r.path),r.queryKey=Ke(r,r.query),r}function $e(n,e){const t=/\/{2,9}/g,s=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&s.splice(0,1),e.slice(-1)=="/"&&s.splice(s.length-1,1),s}function Ke(n,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,i,r){i&&(t[i]=r)}),t}const V=typeof addEventListener=="function"&&typeof removeEventListener=="function",O=[];V&&addEventListener("offline",()=>{O.forEach(n=>n())},!1);class _ extends u{constructor(e,t){if(super(),this.binaryType=ve,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){const s=U(e);t.hostname=s.host,t.secure=s.protocol==="https"||s.protocol==="wss",t.port=s.port,s.query&&(t.query=s.query)}else t.host&&(t.hostname=U(t.host).host);L(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(s=>{const i=s.prototype.name;this.transports.push(i),this._transportsByName[i]=s}),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?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Ce(this.opts.query)),V&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},O.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=re,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(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&_.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"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",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",_.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")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);break}}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(),this.readyState!=="closed"&&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,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&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&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let s=0;s0&&t>this._maxPayload)return this.writeBuffer.slice(0,s);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,x(()=>{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,i){if(typeof t=="function"&&(i=t,t=void 0),typeof s=="function"&&(i=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const r={type:e,data:t,options:s};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),i&&this.once("flush",i),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(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():e()}):this.upgrading?s():e()),this}_onError(e){if(_.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),V&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=O.indexOf(this._offlineEventListener);s!==-1&&O.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}_.protocol=re;class We extends _{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e{s||(t.send([{type:"ping",data:"probe"}]),t.once("packet",g=>{if(!s)if(g.type==="pong"&&g.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;_.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(f(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const w=new Error("probe error");w.transport=t.name,this.emitReserved("upgradeError",w)}}))};function r(){s||(s=!0,f(),t.close(),t=null)}const o=g=>{const w=new Error("probe error: "+g);w.transport=t.name,r(),this.emitReserved("upgradeError",w)};function c(){o("transport closed")}function h(){o("socket closed")}function m(g){t&&g.name!==t.name&&r()}const f=()=>{t.removeListener("open",i),t.removeListener("error",o),t.removeListener("close",c),this.off("close",h),this.off("upgrading",m)};t.once("open",i),t.once("error",o),t.once("close",c),this.once("close",h),this.once("upgrading",m),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?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;sFe[i]).filter(i=>!!i)),super(e,s)}};function ze(n,e="",t){let s=n;t=t||typeof location<"u"&&location,n==null&&(n=t.protocol+"//"+t.host),typeof n=="string"&&(n.charAt(0)==="/"&&(n.charAt(1)==="/"?n=t.protocol+n:n=t.host+n),/^(https?|wss?):\/\//.test(n)||(typeof t<"u"?n=t.protocol+"//"+n:n="https://"+n),s=U(n)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const r=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+r+":"+s.port+e,s.href=s.protocol+"://"+r+(t&&t.port===s.port?"":":"+s.port),s}const Je=typeof ArrayBuffer=="function",Xe=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,fe=Object.prototype.toString,Ge=typeof Blob=="function"||typeof Blob<"u"&&fe.call(Blob)==="[object BlobConstructor]",Qe=typeof File=="function"||typeof File<"u"&&fe.call(File)==="[object FileConstructor]";function Y(n){return Je&&(n instanceof ArrayBuffer||Xe(n))||Ge&&n instanceof Blob||Qe&&n instanceof File}function C(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,s=n.length;t=0&&n.num{delete this.acks[e];for(let c=0;c{this.io.clearTimeoutFn(r),t.apply(this,c)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((s,i)=>{const r=(o,c)=>o?i(o):s(c);r.withError=!0,t.push(r),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...r)=>s!==this._queue[0]?void 0:(i!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(i)):(this._queue.shift(),t&&t(null,...r)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)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(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:a.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(s=>String(s.id)===e)){const s=this.acks[e];delete this.acks[e],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case a.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 a.EVENT:case a.BINARY_EVENT:this.onevent(e);break;case a.ACK:case a.BINARY_ACK:this.onack(e);break;case a.DISCONNECT:this.ondisconnect();break;case a.CONNECT_ERROR:this.destroy();const s=new Error(e.data.message);s.data=e.data.data,this.emitReserved("connect_error",s);break}}onevent(e){const t=e.data||[];e.id!=null&&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&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let s=!1;return function(...i){s||(s=!0,t.packet({type:a.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];typeof t=="function"&&(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:a.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;s0&&n.jitter<=1?n.jitter:0,this.attempts=0}b.prototype.duration=function(){var n=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*n);n=(Math.floor(e*10)&1)==0?n-t:n+t}return Math.min(n,this.max)|0};b.prototype.reset=function(){this.attempts=0};b.prototype.setMin=function(n){this.ms=n};b.prototype.setMax=function(n){this.max=n};b.prototype.setJitter=function(n){this.jitter=n};class H extends u{constructor(e,t){var s;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,L(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((s=t.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new b({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||it;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Ye(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const i=p(t,"open",function(){s.onopen(),e&&e()}),r=c=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},o=p(t,"error",r);if(this._timeout!==!1){const c=this._timeout,h=this.setTimeoutFn(()=>{i(),r(new Error("timeout")),t.close()},c);this.opts.autoUnref&&h.unref(),this.subs.push(()=>{this.clearTimeoutFn(h)})}return this.subs.push(i),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(p(e,"ping",this.onping.bind(this)),p(e,"data",this.ondata.bind(this)),p(e,"error",this.onerror.bind(this)),p(e,"close",this.onclose.bind(this)),p(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){x(()=>{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 le(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;se()),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(),(s=this.engine)===null||s===void 0||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(i=>{i?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):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 E={};function B(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};const t=ze(n,e.path||"/socket.io"),s=t.source,i=t.id,r=t.path,o=E[i]&&r in E[i].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let h;return c?h=new H(s,e):(E[i]||(E[i]=new H(s,e)),h=E[i]),t.query&&!e.query&&(e.query=t.queryKey),h.socket(t.path,e)}Object.assign(B,{Manager:H,Socket:le,io:B,connect:B});const R={GET_CONVERSATIONS:"messages.get-conversations",GET_CONVERSATION:"messages.get-conversation",SEND_MESSAGE:"messages.send-messsage",REPLY_MESSAGE:"messages.reply-messsage"};let v=null,N=[];function ot(){v||(v=B("ws://localhost:4001",{transports:["websocket"]}),chrome.runtime.onConnect.addListener(e=>{e.name==="message"&&(N.push(e),e.postMessage({type:"status",msg:"Connected to background"}),e.onDisconnect.addListener(()=>{N=N.filter(t=>t!==e)})),e.onMessage.addListener(t=>{console.log(`[${t.event}] Received from content:`,t),t.type==="socket-response"&&v?.emit(t.event,t?.data)})}),v.on("connect",()=>{console.log("✅ Socket.IO connected"),Z({type:"socket",event:"connect",msg:"Socket.IO connected"})}),[R.GET_CONVERSATIONS,R.GET_CONVERSATION,R.SEND_MESSAGE,R.REPLY_MESSAGE].forEach(e=>{v?.on(e,t=>{Z({type:"socket",event:e,data:t})})}))}function Z(n){N.forEach(e=>{try{e.postMessage(n)}catch(t){console.warn("❌ Failed to send message:",t)}})}function at(){const n="reloadEvery4Hours";chrome.alarms.clear(n,()=>{chrome.alarms.create(n,{delayInMinutes:1,periodInMinutes:4*60}),console.log(`⏰ Reload alarm "${n}" set to repeat every 4 hours`)})}chrome.alarms.onAlarm.addListener(n=>{n.name==="reloadEvery4Hours"&&(console.log("🔄 Reloading all tabs (every 4 hours)",new Date().toLocaleString()),chrome.tabs.query({},e=>{e.forEach(t=>{t.id&&chrome.tabs.reload(t.id)})}))});ot();at(); +const y=Object.create(null);y.open="0";y.close="1";y.ping="2";y.pong="3";y.message="4";y.upgrade="5";y.noop="6";const S=Object.create(null);Object.keys(y).forEach(n=>{S[y[n]]=n});const I={type:"error",data:"parser error"},ee=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",te=typeof ArrayBuffer=="function",se=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,$=({type:n,data:e},t,s)=>ee&&e instanceof Blob?t?s(e):J(e,s):te&&(e instanceof ArrayBuffer||se(e))?t?s(e):J(new Blob([e]),s):s(y[n]+(e||"")),J=(n,e)=>{const t=new FileReader;return t.onload=function(){const s=t.result.split(",")[1];e("b"+(s||""))},t.readAsDataURL(n)};function X(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let P;function pe(n,e){if(ee&&n.data instanceof Blob)return n.data.arrayBuffer().then(X).then(e);if(te&&(n.data instanceof ArrayBuffer||se(n.data)))return e(X(n.data));$(n,!1,t=>{P||(P=new TextEncoder),e(P.encode(t))})}const G="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",k=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n{let e=n.length*.75,t=n.length,s,i=0,r,o,c,h;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);const m=new ArrayBuffer(e),f=new Uint8Array(m);for(s=0;s>4,f[i++]=(o&15)<<4|c>>2,f[i++]=(c&3)<<6|h&63;return m},ye=typeof ArrayBuffer=="function",K=(n,e)=>{if(typeof n!="string")return{type:"message",data:ne(n,e)};const t=n.charAt(0);return t==="b"?{type:"message",data:me(n.substring(1),e)}:S[t]?n.length>1?{type:S[t],data:n.substring(1)}:{type:S[t]}:I},me=(n,e)=>{if(ye){const t=de(n);return ne(t,e)}else return{base64:!0,data:n}},ne=(n,e)=>{switch(e){case"blob":return n instanceof Blob?n:new Blob([n]);case"arraybuffer":default:return n instanceof ArrayBuffer?n:n.buffer}},ie="",ge=(n,e)=>{const t=n.length,s=new Array(t);let i=0;n.forEach((r,o)=>{$(r,!1,c=>{s[o]=c,++i===t&&e(s.join(ie))})})},_e=(n,e)=>{const t=n.split(ie),s=[];for(let i=0;i{const s=t.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const r=new DataView(i.buffer);r.setUint8(0,126),r.setUint16(1,s)}else{i=new Uint8Array(9);const r=new DataView(i.buffer);r.setUint8(0,127),r.setBigUint64(1,BigInt(s))}n.data&&typeof n.data!="string"&&(i[0]|=128),e.enqueue(i),e.enqueue(t)})}})}let q;function T(n){return n.reduce((e,t)=>e+t.length,0)}function A(n,e){if(n[0].length===e)return n.shift();const t=new Uint8Array(e);let s=0;for(let i=0;iMath.pow(2,21)-1){c.enqueue(I);break}i=f*Math.pow(2,32)+m.getUint32(4),s=3}else{if(T(t)n){c.enqueue(I);break}}}})}const re=4;function u(n){if(n)return Ee(n)}function Ee(n){for(var e in u.prototype)n[e]=u.prototype[e];return n}u.prototype.on=u.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};u.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};u.prototype.off=u.prototype.removeListener=u.prototype.removeAllListeners=u.prototype.removeEventListener=function(n,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+n];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;for(var s,i=0;iPromise.resolve().then(e):(e,t)=>t(e,0),l=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),ve="arraybuffer";function oe(n,...e){return e.reduce((t,s)=>(n.hasOwnProperty(s)&&(t[s]=n[s]),t),{})}const ke=l.setTimeout,Te=l.clearTimeout;function L(n,e){e.useNativeTimers?(n.setTimeoutFn=ke.bind(l),n.clearTimeoutFn=Te.bind(l)):(n.setTimeoutFn=l.setTimeout.bind(l),n.clearTimeoutFn=l.clearTimeout.bind(l))}const Ae=1.33;function Re(n){return typeof n=="string"?Se(n):Math.ceil((n.byteLength||n.size)*Ae)}function Se(n){let e=0,t=0;for(let s=0,i=n.length;s=57344?t+=3:(s++,t+=4);return t}function ae(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Oe(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function Ce(n){let e={},t=n.split("&");for(let s=0,i=t.length;s{this.readyState="paused",e()};if(this._polling||!this.writable){let s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||t()})),this.writable||(s++,this.once("drain",function(){--s||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const t=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};_e(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,ge(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=ae()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let ce=!1;try{ce=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const xe=ce;function Le(){}class Pe extends Ne{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let s=location.port;s||(s=t?"443":"80"),this.xd=typeof location<"u"&&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",(i,r)=>{this.onError("xhr post error",i,r)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,s)=>{this.onError("xhr poll error",t,s)}),this.pollXhr=e}}class d extends u{constructor(e,t,s){super(),this.createRequest=e,L(this,s),this._opts=s,this._method=s.method||"GET",this._uri=t,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var e;const t=oe(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 i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&s.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var i;s.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=d.requestsCount++,d.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Le,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete d.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}d.requestsCount=0;d.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Q);else if(typeof addEventListener=="function"){const n="onpagehide"in l?"pagehide":"unload";addEventListener(n,Q,!1)}}function Q(){for(let n in d.requests)d.requests.hasOwnProperty(n)&&d.requests[n].abort()}const qe=function(){const n=he({xdomain:!1});return n&&n.responseType!==null}();class De extends Pe{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=qe&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new d(he,this.uri(),e)}}function he(n){const e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||xe))return new XMLHttpRequest}catch{}if(!e)try{return new l[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const ue=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Ie extends W{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=ue?{}:oe(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(i){return this.emitReserved("error",i)}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{try{this.doWrite(s,r)}catch{}i&&x(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(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]=ae()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const D=l.WebSocket||l.MozWebSocket;class Ue extends Ie{createSocket(e,t,s){return ue?new D(e,t,s):t?new D(e,t):new D(e)}doWrite(e,t){this.ws.send(t)}}class Ve extends W{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=we(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),i=be();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const r=()=>{s.read().then(({done:c,value:h})=>{c||(this.onPacket(h),r())}).catch(c=>{})};r();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{i&&x(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const Fe={websocket:Ue,webtransport:Ve,polling:De},Me=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,He=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function U(n){if(n.length>8e3)throw"URI too long";const e=n,t=n.indexOf("["),s=n.indexOf("]");t!=-1&&s!=-1&&(n=n.substring(0,t)+n.substring(t,s).replace(/:/g,";")+n.substring(s,n.length));let i=Me.exec(n||""),r={},o=14;for(;o--;)r[He[o]]=i[o]||"";return t!=-1&&s!=-1&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=$e(r,r.path),r.queryKey=Ke(r,r.query),r}function $e(n,e){const t=/\/{2,9}/g,s=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&s.splice(0,1),e.slice(-1)=="/"&&s.splice(s.length-1,1),s}function Ke(n,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,i,r){i&&(t[i]=r)}),t}const V=typeof addEventListener=="function"&&typeof removeEventListener=="function",O=[];V&&addEventListener("offline",()=>{O.forEach(n=>n())},!1);class _ extends u{constructor(e,t){if(super(),this.binaryType=ve,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){const s=U(e);t.hostname=s.host,t.secure=s.protocol==="https"||s.protocol==="wss",t.port=s.port,s.query&&(t.query=s.query)}else t.host&&(t.hostname=U(t.host).host);L(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(s=>{const i=s.prototype.name;this.transports.push(i),this._transportsByName[i]=s}),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?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Ce(this.opts.query)),V&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},O.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=re,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(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&_.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"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",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",_.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")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);break}}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(),this.readyState!=="closed"&&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,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&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&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let s=0;s0&&t>this._maxPayload)return this.writeBuffer.slice(0,s);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,x(()=>{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,i){if(typeof t=="function"&&(i=t,t=void 0),typeof s=="function"&&(i=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const r={type:e,data:t,options:s};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),i&&this.once("flush",i),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(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():e()}):this.upgrading?s():e()),this}_onError(e){if(_.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),V&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=O.indexOf(this._offlineEventListener);s!==-1&&O.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}_.protocol=re;class We extends _{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e{s||(t.send([{type:"ping",data:"probe"}]),t.once("packet",g=>{if(!s)if(g.type==="pong"&&g.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;_.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(f(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const w=new Error("probe error");w.transport=t.name,this.emitReserved("upgradeError",w)}}))};function r(){s||(s=!0,f(),t.close(),t=null)}const o=g=>{const w=new Error("probe error: "+g);w.transport=t.name,r(),this.emitReserved("upgradeError",w)};function c(){o("transport closed")}function h(){o("socket closed")}function m(g){t&&g.name!==t.name&&r()}const f=()=>{t.removeListener("open",i),t.removeListener("error",o),t.removeListener("close",c),this.off("close",h),this.off("upgrading",m)};t.once("open",i),t.once("error",o),t.once("close",c),this.once("close",h),this.once("upgrading",m),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?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;sFe[i]).filter(i=>!!i)),super(e,s)}};function ze(n,e="",t){let s=n;t=t||typeof location<"u"&&location,n==null&&(n=t.protocol+"//"+t.host),typeof n=="string"&&(n.charAt(0)==="/"&&(n.charAt(1)==="/"?n=t.protocol+n:n=t.host+n),/^(https?|wss?):\/\//.test(n)||(typeof t<"u"?n=t.protocol+"//"+n:n="https://"+n),s=U(n)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const r=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+r+":"+s.port+e,s.href=s.protocol+"://"+r+(t&&t.port===s.port?"":":"+s.port),s}const Je=typeof ArrayBuffer=="function",Xe=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,fe=Object.prototype.toString,Ge=typeof Blob=="function"||typeof Blob<"u"&&fe.call(Blob)==="[object BlobConstructor]",Qe=typeof File=="function"||typeof File<"u"&&fe.call(File)==="[object FileConstructor]";function Y(n){return Je&&(n instanceof ArrayBuffer||Xe(n))||Ge&&n instanceof Blob||Qe&&n instanceof File}function C(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,s=n.length;t=0&&n.num{delete this.acks[e];for(let c=0;c{this.io.clearTimeoutFn(r),t.apply(this,c)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((s,i)=>{const r=(o,c)=>o?i(o):s(c);r.withError=!0,t.push(r),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...r)=>s!==this._queue[0]?void 0:(i!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(i)):(this._queue.shift(),t&&t(null,...r)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)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(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:a.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(s=>String(s.id)===e)){const s=this.acks[e];delete this.acks[e],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case a.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 a.EVENT:case a.BINARY_EVENT:this.onevent(e);break;case a.ACK:case a.BINARY_ACK:this.onack(e);break;case a.DISCONNECT:this.ondisconnect();break;case a.CONNECT_ERROR:this.destroy();const s=new Error(e.data.message);s.data=e.data.data,this.emitReserved("connect_error",s);break}}onevent(e){const t=e.data||[];e.id!=null&&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&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let s=!1;return function(...i){s||(s=!0,t.packet({type:a.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];typeof t=="function"&&(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:a.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;s0&&n.jitter<=1?n.jitter:0,this.attempts=0}b.prototype.duration=function(){var n=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*n);n=(Math.floor(e*10)&1)==0?n-t:n+t}return Math.min(n,this.max)|0};b.prototype.reset=function(){this.attempts=0};b.prototype.setMin=function(n){this.ms=n};b.prototype.setMax=function(n){this.max=n};b.prototype.setJitter=function(n){this.jitter=n};class H extends u{constructor(e,t){var s;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,L(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((s=t.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new b({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||it;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Ye(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const i=p(t,"open",function(){s.onopen(),e&&e()}),r=c=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},o=p(t,"error",r);if(this._timeout!==!1){const c=this._timeout,h=this.setTimeoutFn(()=>{i(),r(new Error("timeout")),t.close()},c);this.opts.autoUnref&&h.unref(),this.subs.push(()=>{this.clearTimeoutFn(h)})}return this.subs.push(i),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(p(e,"ping",this.onping.bind(this)),p(e,"data",this.ondata.bind(this)),p(e,"error",this.onerror.bind(this)),p(e,"close",this.onclose.bind(this)),p(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){x(()=>{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 le(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;se()),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(),(s=this.engine)===null||s===void 0||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(i=>{i?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):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 E={};function B(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};const t=ze(n,e.path||"/socket.io"),s=t.source,i=t.id,r=t.path,o=E[i]&&r in E[i].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let h;return c?h=new H(s,e):(E[i]||(E[i]=new H(s,e)),h=E[i]),t.query&&!e.query&&(e.query=t.queryKey),h.socket(t.path,e)}Object.assign(B,{Manager:H,Socket:le,io:B,connect:B});const R={GET_CONVERSATIONS:"messages.get-conversations",GET_CONVERSATION:"messages.get-conversation",SEND_MESSAGE:"messages.send-messsage",REPLY_MESSAGE:"messages.reply-messsage"};let v=null,N=[];function ot(){v||(v=B("ws://localhost:4000",{transports:["websocket"]}),chrome.runtime.onConnect.addListener(e=>{e.name==="message"&&(N.push(e),e.postMessage({type:"status",msg:"Connected to background"}),e.onDisconnect.addListener(()=>{N=N.filter(t=>t!==e)})),e.onMessage.addListener(t=>{console.log(`[${t.event}] Received from content:`,t),t.type==="socket-response"&&v?.emit(t.event,t?.data)})}),v.on("connect",()=>{console.log("✅ Socket.IO connectedd"),Z({type:"socket",event:"connect",msg:"Socket.IO connected"})}),[R.GET_CONVERSATIONS,R.GET_CONVERSATION,R.SEND_MESSAGE,R.REPLY_MESSAGE].forEach(e=>{v?.on(e,t=>{console.log({event:e}),Z({type:"socket",event:e,data:t})})}))}function Z(n){N.forEach(e=>{try{e.postMessage(n)}catch(t){console.warn("❌ Failed to send message:",t)}})}function at(){const n="reloadEvery4Hours";chrome.alarms.clear(n,()=>{chrome.alarms.create(n,{delayInMinutes:1,periodInMinutes:4*60}),console.log(`⏰ Reload alarm "${n}" set to repeat every 4 hours`)})}chrome.alarms.onAlarm.addListener(n=>{n.name==="reloadEvery4Hours"&&(console.log("🔄 Reloading all tabs (every 4 hours)",new Date().toLocaleString()),chrome.tabs.query({},e=>{e.forEach(t=>{t.id&&chrome.tabs.reload(t.id)})}))});ot();at(); diff --git a/composer-bot-extensions/composer-bot-extensions/content.js b/composer-bot-extensions/composer-bot-extensions/content.js index ced70cc..0abfaaf 100644 --- a/composer-bot-extensions/composer-bot-extensions/content.js +++ b/composer-bot-extensions/composer-bot-extensions/content.js @@ -1,6 +1,6 @@ -const D={GET_CONVERSATIONS:"messages.get-conversations",GET_CONVERSATION:"messages.get-conversation",RECEIVE_CONVERSATIONS:"messages.receive-conversations",RECEIVE_CONVERSATION:"messages.receive-conversation",SEND_MESSAGE:"messages.send-messsage",REPLY_MESSAGE:"messages.reply-messsage"};function ht(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ae={exports:{}},Se;function pt(){return Se||(Se=1,function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function s(f,a,u){this.fn=f,this.context=a,this.once=u||!1}function o(f,a,u,d,m){if(typeof u!="function")throw new TypeError("The listener must be a function");var g=new s(u,d||f,m),p=n?n+a:a;return f._events[p]?f._events[p].fn?f._events[p]=[f._events[p],g]:f._events[p].push(g):(f._events[p]=g,f._eventsCount++),f}function i(f,a){--f._eventsCount===0?f._events=new r:delete f._events[a]}function c(){this._events=new r,this._eventsCount=0}c.prototype.eventNames=function(){var a=[],u,d;if(this._eventsCount===0)return a;for(d in u=this._events)e.call(u,d)&&a.push(n?d.slice(1):d);return Object.getOwnPropertySymbols?a.concat(Object.getOwnPropertySymbols(u)):a},c.prototype.listeners=function(a){var u=n?n+a:a,d=this._events[u];if(!d)return[];if(d.fn)return[d.fn];for(var m=0,g=d.length,p=new Array(g);mglobalThis.DOMException===void 0?new gt(t):new DOMException(t),Re=t=>{const e=t.reason===void 0?Te("This operation was aborted."):t.reason;return e instanceof Error?e:Te(e)};function wt(t,e){const{milliseconds:n,fallback:r,message:s,customTimers:o={setTimeout,clearTimeout}}=e;let i,c;const a=new Promise((u,d)=>{if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(e.signal){const{signal:g}=e;g.aborted&&d(Re(g)),c=()=>{d(Re(g))},g.addEventListener("abort",c,{once:!0})}if(n===Number.POSITIVE_INFINITY){t.then(u,d);return}const m=new Ue;i=o.setTimeout.call(void 0,()=>{if(r){try{u(r())}catch(g){d(g)}return}typeof t.cancel=="function"&&t.cancel(),s===!1?u():s instanceof Error?d(s):(m.message=s??`Promise timed out after ${n} milliseconds`,d(m))},n),(async()=>{try{u(await t)}catch(g){d(g)}})()}).finally(()=>{a.clear(),c&&e.signal&&e.signal.removeEventListener("abort",c)});return a.clear=()=>{o.clearTimeout.call(void 0,i),i=void 0},a}function bt(t,e,n){let r=0,s=t.length;for(;s>0;){const o=Math.trunc(s/2);let i=r+o;n(t[i],e)<=0?(r=++i,s-=o+1):s=o}return r}class Et{#e=[];enqueue(e,n){n={priority:0,...n};const r={priority:n.priority,id:n.id,run:e};if(this.size===0||this.#e[this.size-1].priority>=n.priority){this.#e.push(r);return}const s=bt(this.#e,r,(o,i)=>i.priority-o.priority);this.#e.splice(s,0,r)}setPriority(e,n){const r=this.#e.findIndex(o=>o.id===e);if(r===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);const[s]=this.#e.splice(r,1);this.enqueue(s.run,{priority:n,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(n=>n.priority===e.priority).map(n=>n.run)}get size(){return this.#e.length}}class St extends yt{#e;#i;#o=0;#h;#a;#p=0;#n;#c;#t;#m;#r=0;#l;#s;#y;#b=1n;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Et,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#i=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#h=e.intervalCap,this.#a=e.interval,this.#t=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#y=e.throwOnTimeout===!0,this.#s=e.autoStart===!1}get#E(){return this.#i||this.#o{this.#R()},n)),!0}return!1}#u(){if(this.#t.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#r===0&&this.emit("idle"),!1;if(!this.#s){const e=!this.#v;if(this.#E&&this.#S){const n=this.#t.dequeue();return n?(this.emit("active"),n(),e&&this.#g(),!0):!1}}return!1}#g(){this.#i||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#a),this.#p=Date.now()+this.#a)}#w(){this.#o===0&&this.#r===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#o=this.#e?this.#r:0,this.#f()}#f(){for(;this.#u(););}get concurrency(){return this.#l}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#l=e,this.#f()}async#_(e){return new Promise((n,r)=>{e.addEventListener("abort",()=>{r(e.reason)},{once:!0})})}setPriority(e,n){this.#t.setPriority(e,n)}async add(e,n={}){return n.id??=(this.#b++).toString(),n={timeout:this.timeout,throwOnTimeout:this.#y,...n},new Promise((r,s)=>{this.#t.enqueue(async()=>{this.#r++,this.#o++;try{n.signal?.throwIfAborted();let o=e({signal:n.signal});n.timeout&&(o=wt(Promise.resolve(o),{milliseconds:n.timeout})),n.signal&&(o=Promise.race([o,this.#_(n.signal)]));const i=await o;r(i),this.emit("completed",i)}catch(o){if(o instanceof Ue&&!n.throwOnTimeout){r();return}s(o),this.emit("error",o)}finally{this.#T()}},n),this.emit("add"),this.#u()})}async addAll(e,n){return Promise.all(e.map(async r=>this.add(r,n)))}start(){return this.#s?(this.#s=!1,this.#f(),this):this}pause(){this.#s=!0}clear(){this.#t=new this.#m}async onEmpty(){this.#t.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#t.sizethis.#t.size{const s=()=>{n&&!n()||(this.off(e,s),r())};this.on(e,s)})}get size(){return this.#t.size}sizeBy(e){return this.#t.filter(e).length}get pending(){return this.#r}get isPaused(){return this.#s}}const B=new St({concurrency:1});function P(t){return new Promise(e=>setTimeout(e,t))}async function ve(t){const n=await(await fetch(t)).blob();return new Promise((r,s)=>{const o=new FileReader;o.onloadend=()=>{typeof o.result=="string"?r(o.result.split(",")[1]):s("Không thể đọc dữ liệu ảnh")},o.onerror=s,o.readAsDataURL(n)})}function _e(t){return t.startsWith("blob:")}function je(t,e){return function(){return t.apply(e,arguments)}}const{toString:Tt}=Object.prototype,{getPrototypeOf:ge}=Object,{iterator:te,toStringTag:He}=Symbol,ne=(t=>e=>{const n=Tt.call(e);return t[n]||(t[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),C=t=>(t=t.toLowerCase(),e=>ne(e)===t),re=t=>e=>typeof e===t,{isArray:j}=Array,V=re("undefined");function z(t){return t!==null&&!V(t)&&t.constructor!==null&&!V(t.constructor)&&_(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const $e=C("ArrayBuffer");function Rt(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&$e(t.buffer),e}const vt=re("string"),_=re("function"),Ve=re("number"),J=t=>t!==null&&typeof t=="object",_t=t=>t===!0||t===!1,X=t=>{if(ne(t)!=="object")return!1;const e=ge(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(He in t)&&!(te in t)},At=t=>{if(!J(t)||z(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},Ot=C("Date"),Ct=C("File"),xt=C("Blob"),Nt=C("FileList"),Pt=t=>J(t)&&_(t.pipe),It=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||_(t.append)&&((e=ne(t))==="formdata"||e==="object"&&_(t.toString)&&t.toString()==="[object FormData]"))},Mt=C("URLSearchParams"),[kt,Lt,Ft,Bt]=["ReadableStream","Request","Response","Headers"].map(C),Dt=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function K(t,e,{allOwnKeys:n=!1}={}){if(t===null||typeof t>"u")return;let r,s;if(typeof t!="object"&&(t=[t]),j(t))for(r=0,s=t.length;r0;)if(s=n[r],e===s.toLowerCase())return s;return null}const k=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Je=t=>!V(t)&&t!==k;function fe(){const{caseless:t}=Je(this)&&this||{},e={},n=(r,s)=>{const o=t&&ze(e,s)||s;X(e[o])&&X(r)?e[o]=fe(e[o],r):X(r)?e[o]=fe({},r):j(r)?e[o]=r.slice():e[o]=r};for(let r=0,s=arguments.length;r(K(e,(s,o)=>{n&&_(s)?t[o]=je(s,n):t[o]=s},{allOwnKeys:r}),t),Ut=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),jt=(t,e,n,r)=>{t.prototype=Object.create(e.prototype,r),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},Ht=(t,e,n,r)=>{let s,o,i;const c={};if(e=e||{},t==null)return e;do{for(s=Object.getOwnPropertyNames(t),o=s.length;o-- >0;)i=s[o],(!r||r(i,t,e))&&!c[i]&&(e[i]=t[i],c[i]=!0);t=n!==!1&&ge(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},$t=(t,e,n)=>{t=String(t),(n===void 0||n>t.length)&&(n=t.length),n-=e.length;const r=t.indexOf(e,n);return r!==-1&&r===n},Vt=t=>{if(!t)return null;if(j(t))return t;let e=t.length;if(!Ve(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},zt=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&ge(Uint8Array)),Jt=(t,e)=>{const r=(t&&t[te]).call(t);let s;for(;(s=r.next())&&!s.done;){const o=s.value;e.call(t,o[0],o[1])}},Kt=(t,e)=>{let n;const r=[];for(;(n=t.exec(e))!==null;)r.push(n);return r},Wt=C("HTMLFormElement"),Gt=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,s){return r.toUpperCase()+s}),Ae=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),Xt=C("RegExp"),Ke=(t,e)=>{const n=Object.getOwnPropertyDescriptors(t),r={};K(n,(s,o)=>{let i;(i=e(s,o,t))!==!1&&(r[o]=i||s)}),Object.defineProperties(t,r)},Qt=t=>{Ke(t,(e,n)=>{if(_(t)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=t[n];if(_(r)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},Yt=(t,e)=>{const n={},r=s=>{s.forEach(o=>{n[o]=!0})};return j(t)?r(t):r(String(t).split(e)),n},Zt=()=>{},en=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function tn(t){return!!(t&&_(t.append)&&t[He]==="FormData"&&t[te])}const nn=t=>{const e=new Array(10),n=(r,s)=>{if(J(r)){if(e.indexOf(r)>=0)return;if(z(r))return r;if(!("toJSON"in r)){e[s]=r;const o=j(r)?[]:{};return K(r,(i,c)=>{const f=n(i,s+1);!V(f)&&(o[c]=f)}),e[s]=void 0,o}}return r};return n(t,0)},rn=C("AsyncFunction"),sn=t=>t&&(J(t)||_(t))&&_(t.then)&&_(t.catch),We=((t,e)=>t?setImmediate:e?((n,r)=>(k.addEventListener("message",({source:s,data:o})=>{s===k&&o===n&&r.length&&r.shift()()},!1),s=>{r.push(s),k.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",_(k.postMessage)),on=typeof queueMicrotask<"u"?queueMicrotask.bind(k):typeof process<"u"&&process.nextTick||We,an=t=>t!=null&&_(t[te]),l={isArray:j,isArrayBuffer:$e,isBuffer:z,isFormData:It,isArrayBufferView:Rt,isString:vt,isNumber:Ve,isBoolean:_t,isObject:J,isPlainObject:X,isEmptyObject:At,isReadableStream:kt,isRequest:Lt,isResponse:Ft,isHeaders:Bt,isUndefined:V,isDate:Ot,isFile:Ct,isBlob:xt,isRegExp:Xt,isFunction:_,isStream:Pt,isURLSearchParams:Mt,isTypedArray:zt,isFileList:Nt,forEach:K,merge:fe,extend:qt,trim:Dt,stripBOM:Ut,inherits:jt,toFlatObject:Ht,kindOf:ne,kindOfTest:C,endsWith:$t,toArray:Vt,forEachEntry:Jt,matchAll:Kt,isHTMLForm:Wt,hasOwnProperty:Ae,hasOwnProp:Ae,reduceDescriptors:Ke,freezeMethods:Qt,toObjectSet:Yt,toCamelCase:Gt,noop:Zt,toFiniteNumber:en,findKey:ze,global:k,isContextDefined:Je,isSpecCompliantForm:tn,toJSONObject:nn,isAsyncFn:rn,isThenable:sn,setImmediate:We,asap:on,isIterable:an};function w(t,e,n,r,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),n&&(this.config=n),r&&(this.request=r),s&&(this.response=s,this.status=s.status?s.status:null)}l.inherits(w,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:l.toJSONObject(this.config),code:this.code,status:this.status}}});const Ge=w.prototype,Xe={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(t=>{Xe[t]={value:t}});Object.defineProperties(w,Xe);Object.defineProperty(Ge,"isAxiosError",{value:!0});w.from=(t,e,n,r,s,o)=>{const i=Object.create(Ge);return l.toFlatObject(t,i,function(f){return f!==Error.prototype},c=>c!=="isAxiosError"),w.call(i,t.message,e,n,r,s),i.cause=t,i.name=t.name,o&&Object.assign(i,o),i};const cn=null;function de(t){return l.isPlainObject(t)||l.isArray(t)}function Qe(t){return l.endsWith(t,"[]")?t.slice(0,-2):t}function Oe(t,e,n){return t?t.concat(e).map(function(s,o){return s=Qe(s),!n&&o?"["+s+"]":s}).join(n?".":""):e}function ln(t){return l.isArray(t)&&!t.some(de)}const un=l.toFlatObject(l,{},null,function(e){return/^is[A-Z]/.test(e)});function se(t,e,n){if(!l.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,n=l.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,h){return!l.isUndefined(h[y])});const r=n.metaTokens,s=n.visitor||u,o=n.dots,i=n.indexes,f=(n.Blob||typeof Blob<"u"&&Blob)&&l.isSpecCompliantForm(e);if(!l.isFunction(s))throw new TypeError("visitor must be a function");function a(p){if(p===null)return"";if(l.isDate(p))return p.toISOString();if(l.isBoolean(p))return p.toString();if(!f&&l.isBlob(p))throw new w("Blob is not supported. Use a Buffer instead.");return l.isArrayBuffer(p)||l.isTypedArray(p)?f&&typeof Blob=="function"?new Blob([p]):Buffer.from(p):p}function u(p,y,h){let E=p;if(p&&!h&&typeof p=="object"){if(l.endsWith(y,"{}"))y=r?y:y.slice(0,-2),p=JSON.stringify(p);else if(l.isArray(p)&&ln(p)||(l.isFileList(p)||l.endsWith(y,"[]"))&&(E=l.toArray(p)))return y=Qe(y),E.forEach(function(b,O){!(l.isUndefined(b)||b===null)&&e.append(i===!0?Oe([y],O,o):i===null?y:y+"[]",a(b))}),!1}return de(p)?!0:(e.append(Oe(h,y,o),a(p)),!1)}const d=[],m=Object.assign(un,{defaultVisitor:u,convertValue:a,isVisitable:de});function g(p,y){if(!l.isUndefined(p)){if(d.indexOf(p)!==-1)throw Error("Circular reference detected in "+y.join("."));d.push(p),l.forEach(p,function(E,S){(!(l.isUndefined(E)||E===null)&&s.call(e,E,l.isString(S)?S.trim():S,y,m))===!0&&g(E,y?y.concat(S):[S])}),d.pop()}}if(!l.isObject(t))throw new TypeError("data must be an object");return g(t),e}function Ce(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(r){return e[r]})}function we(t,e){this._pairs=[],t&&se(t,this,e)}const Ye=we.prototype;Ye.append=function(e,n){this._pairs.push([e,n])};Ye.toString=function(e){const n=e?function(r){return e.call(this,r,Ce)}:Ce;return this._pairs.map(function(s){return n(s[0])+"="+n(s[1])},"").join("&")};function fn(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Ze(t,e,n){if(!e)return t;const r=n&&n.encode||fn;l.isFunction(n)&&(n={serialize:n});const s=n&&n.serialize;let o;if(s?o=s(e,n):o=l.isURLSearchParams(e)?e.toString():new we(e,n).toString(r),o){const i=t.indexOf("#");i!==-1&&(t=t.slice(0,i)),t+=(t.indexOf("?")===-1?"?":"&")+o}return t}class xe{constructor(){this.handlers=[]}use(e,n,r){return this.handlers.push({fulfilled:e,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){l.forEach(this.handlers,function(r){r!==null&&e(r)})}}const et={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},dn=typeof URLSearchParams<"u"?URLSearchParams:we,hn=typeof FormData<"u"?FormData:null,pn=typeof Blob<"u"?Blob:null,mn={isBrowser:!0,classes:{URLSearchParams:dn,FormData:hn,Blob:pn},protocols:["http","https","file","blob","url","data"]},be=typeof window<"u"&&typeof document<"u",he=typeof navigator=="object"&&navigator||void 0,yn=be&&(!he||["ReactNative","NativeScript","NS"].indexOf(he.product)<0),gn=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",wn=be&&window.location.href||"http://localhost",bn=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:be,hasStandardBrowserEnv:yn,hasStandardBrowserWebWorkerEnv:gn,navigator:he,origin:wn},Symbol.toStringTag,{value:"Module"})),v={...bn,...mn};function En(t,e){return se(t,new v.classes.URLSearchParams,{visitor:function(n,r,s,o){return v.isNode&&l.isBuffer(n)?(this.append(r,n.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...e})}function Sn(t){return l.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function Tn(t){const e={},n=Object.keys(t);let r;const s=n.length;let o;for(r=0;r=n.length;return i=!i&&l.isArray(s)?s.length:i,f?(l.hasOwnProp(s,i)?s[i]=[s[i],r]:s[i]=r,!c):((!s[i]||!l.isObject(s[i]))&&(s[i]=[]),e(n,r,s[i],o)&&l.isArray(s[i])&&(s[i]=Tn(s[i])),!c)}if(l.isFormData(t)&&l.isFunction(t.entries)){const n={};return l.forEachEntry(t,(r,s)=>{e(Sn(r),s,n,0)}),n}return null}function Rn(t,e,n){if(l.isString(t))try{return(e||JSON.parse)(t),l.trim(t)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(t)}const W={transitional:et,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const r=n.getContentType()||"",s=r.indexOf("application/json")>-1,o=l.isObject(e);if(o&&l.isHTMLForm(e)&&(e=new FormData(e)),l.isFormData(e))return s?JSON.stringify(tt(e)):e;if(l.isArrayBuffer(e)||l.isBuffer(e)||l.isStream(e)||l.isFile(e)||l.isBlob(e)||l.isReadableStream(e))return e;if(l.isArrayBufferView(e))return e.buffer;if(l.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let c;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return En(e,this.formSerializer).toString();if((c=l.isFileList(e))||r.indexOf("multipart/form-data")>-1){const f=this.env&&this.env.FormData;return se(c?{"files[]":e}:e,f&&new f,this.formSerializer)}}return o||s?(n.setContentType("application/json",!1),Rn(e)):e}],transformResponse:[function(e){const n=this.transitional||W.transitional,r=n&&n.forcedJSONParsing,s=this.responseType==="json";if(l.isResponse(e)||l.isReadableStream(e))return e;if(e&&l.isString(e)&&(r&&!this.responseType||s)){const i=!(n&&n.silentJSONParsing)&&s;try{return JSON.parse(e)}catch(c){if(i)throw c.name==="SyntaxError"?w.from(c,w.ERR_BAD_RESPONSE,this,null,this.response):c}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:v.classes.FormData,Blob:v.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};l.forEach(["delete","get","head","post","put","patch"],t=>{W.headers[t]={}});const vn=l.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),_n=t=>{const e={};let n,r,s;return t&&t.split(` -`).forEach(function(i){s=i.indexOf(":"),n=i.substring(0,s).trim().toLowerCase(),r=i.substring(s+1).trim(),!(!n||e[n]&&vn[n])&&(n==="set-cookie"?e[n]?e[n].push(r):e[n]=[r]:e[n]=e[n]?e[n]+", "+r:r)}),e},Ne=Symbol("internals");function $(t){return t&&String(t).trim().toLowerCase()}function Q(t){return t===!1||t==null?t:l.isArray(t)?t.map(Q):String(t)}function An(t){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(t);)e[r[1]]=r[2];return e}const On=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function ce(t,e,n,r,s){if(l.isFunction(r))return r.call(this,e,n);if(s&&(e=n),!!l.isString(e)){if(l.isString(r))return e.indexOf(r)!==-1;if(l.isRegExp(r))return r.test(e)}}function Cn(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,r)=>n.toUpperCase()+r)}function xn(t,e){const n=l.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(t,r+n,{value:function(s,o,i){return this[r].call(this,e,s,o,i)},configurable:!0})})}let A=class{constructor(e){e&&this.set(e)}set(e,n,r){const s=this;function o(c,f,a){const u=$(f);if(!u)throw new Error("header name must be a non-empty string");const d=l.findKey(s,u);(!d||s[d]===void 0||a===!0||a===void 0&&s[d]!==!1)&&(s[d||f]=Q(c))}const i=(c,f)=>l.forEach(c,(a,u)=>o(a,u,f));if(l.isPlainObject(e)||e instanceof this.constructor)i(e,n);else if(l.isString(e)&&(e=e.trim())&&!On(e))i(_n(e),n);else if(l.isObject(e)&&l.isIterable(e)){let c={},f,a;for(const u of e){if(!l.isArray(u))throw TypeError("Object iterator must return a key-value pair");c[a=u[0]]=(f=c[a])?l.isArray(f)?[...f,u[1]]:[f,u[1]]:u[1]}i(c,n)}else e!=null&&o(n,e,r);return this}get(e,n){if(e=$(e),e){const r=l.findKey(this,e);if(r){const s=this[r];if(!n)return s;if(n===!0)return An(s);if(l.isFunction(n))return n.call(this,s,r);if(l.isRegExp(n))return n.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=$(e),e){const r=l.findKey(this,e);return!!(r&&this[r]!==void 0&&(!n||ce(this,this[r],r,n)))}return!1}delete(e,n){const r=this;let s=!1;function o(i){if(i=$(i),i){const c=l.findKey(r,i);c&&(!n||ce(r,r[c],c,n))&&(delete r[c],s=!0)}}return l.isArray(e)?e.forEach(o):o(e),s}clear(e){const n=Object.keys(this);let r=n.length,s=!1;for(;r--;){const o=n[r];(!e||ce(this,this[o],o,e,!0))&&(delete this[o],s=!0)}return s}normalize(e){const n=this,r={};return l.forEach(this,(s,o)=>{const i=l.findKey(r,o);if(i){n[i]=Q(s),delete n[o];return}const c=e?Cn(o):String(o).trim();c!==o&&delete n[o],n[c]=Q(s),r[c]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return l.forEach(this,(r,s)=>{r!=null&&r!==!1&&(n[s]=e&&l.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(` -`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const r=new this(e);return n.forEach(s=>r.set(s)),r}static accessor(e){const r=(this[Ne]=this[Ne]={accessors:{}}).accessors,s=this.prototype;function o(i){const c=$(i);r[c]||(xn(s,i),r[c]=!0)}return l.isArray(e)?e.forEach(o):o(e),this}};A.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);l.reduceDescriptors(A.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(r){this[n]=r}}});l.freezeMethods(A);function le(t,e){const n=this||W,r=e||n,s=A.from(r.headers);let o=r.data;return l.forEach(t,function(c){o=c.call(n,o,s.normalize(),e?e.status:void 0)}),s.normalize(),o}function nt(t){return!!(t&&t.__CANCEL__)}function H(t,e,n){w.call(this,t??"canceled",w.ERR_CANCELED,e,n),this.name="CanceledError"}l.inherits(H,w,{__CANCEL__:!0});function rt(t,e,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?t(n):e(new w("Request failed with status code "+n.status,[w.ERR_BAD_REQUEST,w.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function Nn(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function Pn(t,e){t=t||10;const n=new Array(t),r=new Array(t);let s=0,o=0,i;return e=e!==void 0?e:1e3,function(f){const a=Date.now(),u=r[o];i||(i=a),n[s]=f,r[s]=a;let d=o,m=0;for(;d!==s;)m+=n[d++],d=d%t;if(s=(s+1)%t,s===o&&(o=(o+1)%t),a-i{n=u,s=null,o&&(clearTimeout(o),o=null),t(...a)};return[(...a)=>{const u=Date.now(),d=u-n;d>=r?i(a,u):(s=a,o||(o=setTimeout(()=>{o=null,i(s)},r-d)))},()=>s&&i(s)]}const Z=(t,e,n=3)=>{let r=0;const s=Pn(50,250);return In(o=>{const i=o.loaded,c=o.lengthComputable?o.total:void 0,f=i-r,a=s(f),u=i<=c;r=i;const d={loaded:i,total:c,progress:c?i/c:void 0,bytes:f,rate:a||void 0,estimated:a&&c&&u?(c-i)/a:void 0,event:o,lengthComputable:c!=null,[e?"download":"upload"]:!0};t(d)},n)},Pe=(t,e)=>{const n=t!=null;return[r=>e[0]({lengthComputable:n,total:t,loaded:r}),e[1]]},Ie=t=>(...e)=>l.asap(()=>t(...e)),Mn=v.hasStandardBrowserEnv?((t,e)=>n=>(n=new URL(n,v.origin),t.protocol===n.protocol&&t.host===n.host&&(e||t.port===n.port)))(new URL(v.origin),v.navigator&&/(msie|trident)/i.test(v.navigator.userAgent)):()=>!0,kn=v.hasStandardBrowserEnv?{write(t,e,n,r,s,o){const i=[t+"="+encodeURIComponent(e)];l.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),l.isString(r)&&i.push("path="+r),l.isString(s)&&i.push("domain="+s),o===!0&&i.push("secure"),document.cookie=i.join("; ")},read(t){const e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Ln(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Fn(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function st(t,e,n){let r=!Ln(e);return t&&(r||n==!1)?Fn(t,e):e}const Me=t=>t instanceof A?{...t}:t;function F(t,e){e=e||{};const n={};function r(a,u,d,m){return l.isPlainObject(a)&&l.isPlainObject(u)?l.merge.call({caseless:m},a,u):l.isPlainObject(u)?l.merge({},u):l.isArray(u)?u.slice():u}function s(a,u,d,m){if(l.isUndefined(u)){if(!l.isUndefined(a))return r(void 0,a,d,m)}else return r(a,u,d,m)}function o(a,u){if(!l.isUndefined(u))return r(void 0,u)}function i(a,u){if(l.isUndefined(u)){if(!l.isUndefined(a))return r(void 0,a)}else return r(void 0,u)}function c(a,u,d){if(d in e)return r(a,u);if(d in t)return r(void 0,a)}const f={url:o,method:o,data:o,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:c,headers:(a,u,d)=>s(Me(a),Me(u),d,!0)};return l.forEach(Object.keys({...t,...e}),function(u){const d=f[u]||s,m=d(t[u],e[u],u);l.isUndefined(m)&&d!==c||(n[u]=m)}),n}const ot=t=>{const e=F({},t);let{data:n,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:o,headers:i,auth:c}=e;e.headers=i=A.from(i),e.url=Ze(st(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),c&&i.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):"")));let f;if(l.isFormData(n)){if(v.hasStandardBrowserEnv||v.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if((f=i.getContentType())!==!1){const[a,...u]=f?f.split(";").map(d=>d.trim()).filter(Boolean):[];i.setContentType([a||"multipart/form-data",...u].join("; "))}}if(v.hasStandardBrowserEnv&&(r&&l.isFunction(r)&&(r=r(e)),r||r!==!1&&Mn(e.url))){const a=s&&o&&kn.read(o);a&&i.set(s,a)}return e},Bn=typeof XMLHttpRequest<"u",Dn=Bn&&function(t){return new Promise(function(n,r){const s=ot(t);let o=s.data;const i=A.from(s.headers).normalize();let{responseType:c,onUploadProgress:f,onDownloadProgress:a}=s,u,d,m,g,p;function y(){g&&g(),p&&p(),s.cancelToken&&s.cancelToken.unsubscribe(u),s.signal&&s.signal.removeEventListener("abort",u)}let h=new XMLHttpRequest;h.open(s.method.toUpperCase(),s.url,!0),h.timeout=s.timeout;function E(){if(!h)return;const b=A.from("getAllResponseHeaders"in h&&h.getAllResponseHeaders()),R={data:!c||c==="text"||c==="json"?h.responseText:h.response,status:h.status,statusText:h.statusText,headers:b,config:t,request:h};rt(function(I){n(I),y()},function(I){r(I),y()},R),h=null}"onloadend"in h?h.onloadend=E:h.onreadystatechange=function(){!h||h.readyState!==4||h.status===0&&!(h.responseURL&&h.responseURL.indexOf("file:")===0)||setTimeout(E)},h.onabort=function(){h&&(r(new w("Request aborted",w.ECONNABORTED,t,h)),h=null)},h.onerror=function(){r(new w("Network Error",w.ERR_NETWORK,t,h)),h=null},h.ontimeout=function(){let O=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const R=s.transitional||et;s.timeoutErrorMessage&&(O=s.timeoutErrorMessage),r(new w(O,R.clarifyTimeoutError?w.ETIMEDOUT:w.ECONNABORTED,t,h)),h=null},o===void 0&&i.setContentType(null),"setRequestHeader"in h&&l.forEach(i.toJSON(),function(O,R){h.setRequestHeader(R,O)}),l.isUndefined(s.withCredentials)||(h.withCredentials=!!s.withCredentials),c&&c!=="json"&&(h.responseType=s.responseType),a&&([m,p]=Z(a,!0),h.addEventListener("progress",m)),f&&h.upload&&([d,g]=Z(f),h.upload.addEventListener("progress",d),h.upload.addEventListener("loadend",g)),(s.cancelToken||s.signal)&&(u=b=>{h&&(r(!b||b.type?new H(null,t,h):b),h.abort(),h=null)},s.cancelToken&&s.cancelToken.subscribe(u),s.signal&&(s.signal.aborted?u():s.signal.addEventListener("abort",u)));const S=Nn(s.url);if(S&&v.protocols.indexOf(S)===-1){r(new w("Unsupported protocol "+S+":",w.ERR_BAD_REQUEST,t));return}h.send(o||null)})},qn=(t,e)=>{const{length:n}=t=t?t.filter(Boolean):[];if(e||n){let r=new AbortController,s;const o=function(a){if(!s){s=!0,c();const u=a instanceof Error?a:this.reason;r.abort(u instanceof w?u:new H(u instanceof Error?u.message:u))}};let i=e&&setTimeout(()=>{i=null,o(new w(`timeout ${e} of ms exceeded`,w.ETIMEDOUT))},e);const c=()=>{t&&(i&&clearTimeout(i),i=null,t.forEach(a=>{a.unsubscribe?a.unsubscribe(o):a.removeEventListener("abort",o)}),t=null)};t.forEach(a=>a.addEventListener("abort",o));const{signal:f}=r;return f.unsubscribe=()=>l.asap(c),f}},Un=function*(t,e){let n=t.byteLength;if(n{const s=jn(t,e);let o=0,i,c=f=>{i||(i=!0,r&&r(f))};return new ReadableStream({async pull(f){try{const{done:a,value:u}=await s.next();if(a){c(),f.close();return}let d=u.byteLength;if(n){let m=o+=d;n(m)}f.enqueue(new Uint8Array(u))}catch(a){throw c(a),a}},cancel(f){return c(f),s.return()}},{highWaterMark:2})},oe=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",it=oe&&typeof ReadableStream=="function",$n=oe&&(typeof TextEncoder=="function"?(t=>e=>t.encode(e))(new TextEncoder):async t=>new Uint8Array(await new Response(t).arrayBuffer())),at=(t,...e)=>{try{return!!t(...e)}catch{return!1}},Vn=it&&at(()=>{let t=!1;const e=new Request(v.origin,{body:new ReadableStream,method:"POST",get duplex(){return t=!0,"half"}}).headers.has("Content-Type");return t&&!e}),Le=64*1024,pe=it&&at(()=>l.isReadableStream(new Response("").body)),ee={stream:pe&&(t=>t.body)};oe&&(t=>{["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!ee[e]&&(ee[e]=l.isFunction(t[e])?n=>n[e]():(n,r)=>{throw new w(`Response type '${e}' is not supported`,w.ERR_NOT_SUPPORT,r)})})})(new Response);const zn=async t=>{if(t==null)return 0;if(l.isBlob(t))return t.size;if(l.isSpecCompliantForm(t))return(await new Request(v.origin,{method:"POST",body:t}).arrayBuffer()).byteLength;if(l.isArrayBufferView(t)||l.isArrayBuffer(t))return t.byteLength;if(l.isURLSearchParams(t)&&(t=t+""),l.isString(t))return(await $n(t)).byteLength},Jn=async(t,e)=>{const n=l.toFiniteNumber(t.getContentLength());return n??zn(e)},Kn=oe&&(async t=>{let{url:e,method:n,data:r,signal:s,cancelToken:o,timeout:i,onDownloadProgress:c,onUploadProgress:f,responseType:a,headers:u,withCredentials:d="same-origin",fetchOptions:m}=ot(t);a=a?(a+"").toLowerCase():"text";let g=qn([s,o&&o.toAbortSignal()],i),p;const y=g&&g.unsubscribe&&(()=>{g.unsubscribe()});let h;try{if(f&&Vn&&n!=="get"&&n!=="head"&&(h=await Jn(u,r))!==0){let R=new Request(e,{method:"POST",body:r,duplex:"half"}),N;if(l.isFormData(r)&&(N=R.headers.get("content-type"))&&u.setContentType(N),R.body){const[I,G]=Pe(h,Z(Ie(f)));r=ke(R.body,Le,I,G)}}l.isString(d)||(d=d?"include":"omit");const E="credentials"in Request.prototype;p=new Request(e,{...m,signal:g,method:n.toUpperCase(),headers:u.normalize().toJSON(),body:r,duplex:"half",credentials:E?d:void 0});let S=await fetch(p,m);const b=pe&&(a==="stream"||a==="response");if(pe&&(c||b&&y)){const R={};["status","statusText","headers"].forEach(Ee=>{R[Ee]=S[Ee]});const N=l.toFiniteNumber(S.headers.get("content-length")),[I,G]=c&&Pe(N,Z(Ie(c),!0))||[];S=new Response(ke(S.body,Le,I,()=>{G&&G(),y&&y()}),R)}a=a||"text";let O=await ee[l.findKey(ee,a)||"text"](S,t);return!b&&y&&y(),await new Promise((R,N)=>{rt(R,N,{data:O,headers:A.from(S.headers),status:S.status,statusText:S.statusText,config:t,request:p})})}catch(E){throw y&&y(),E&&E.name==="TypeError"&&/Load failed|fetch/i.test(E.message)?Object.assign(new w("Network Error",w.ERR_NETWORK,t,p),{cause:E.cause||E}):w.from(E,E&&E.code,t,p)}}),me={http:cn,xhr:Dn,fetch:Kn};l.forEach(me,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const Fe=t=>`- ${t}`,Wn=t=>l.isFunction(t)||t===null||t===!1,ct={getAdapter:t=>{t=l.isArray(t)?t:[t];const{length:e}=t;let n,r;const s={};for(let o=0;o`adapter ${c} `+(f===!1?"is not supported by the environment":"is not available in the build"));let i=e?o.length>1?`since : +const D={GET_CONVERSATIONS:"messages.get-conversations",GET_CONVERSATION:"messages.get-conversation",RECEIVE_CONVERSATIONS:"messages.receive-conversations",RECEIVE_CONVERSATION:"messages.receive-conversation",SEND_MESSAGE:"messages.send-messsage",REPLY_MESSAGE:"messages.reply-messsage"};function ht(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ae={exports:{}},Se;function pt(){return Se||(Se=1,function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function s(f,c,u){this.fn=f,this.context=c,this.once=u||!1}function o(f,c,u,d,m){if(typeof u!="function")throw new TypeError("The listener must be a function");var g=new s(u,d||f,m),p=n?n+c:c;return f._events[p]?f._events[p].fn?f._events[p]=[f._events[p],g]:f._events[p].push(g):(f._events[p]=g,f._eventsCount++),f}function i(f,c){--f._eventsCount===0?f._events=new r:delete f._events[c]}function a(){this._events=new r,this._eventsCount=0}a.prototype.eventNames=function(){var c=[],u,d;if(this._eventsCount===0)return c;for(d in u=this._events)e.call(u,d)&&c.push(n?d.slice(1):d);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},a.prototype.listeners=function(c){var u=n?n+c:c,d=this._events[u];if(!d)return[];if(d.fn)return[d.fn];for(var m=0,g=d.length,p=new Array(g);mglobalThis.DOMException===void 0?new gt(t):new DOMException(t),Re=t=>{const e=t.reason===void 0?Te("This operation was aborted."):t.reason;return e instanceof Error?e:Te(e)};function wt(t,e){const{milliseconds:n,fallback:r,message:s,customTimers:o={setTimeout,clearTimeout}}=e;let i,a;const c=new Promise((u,d)=>{if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(e.signal){const{signal:g}=e;g.aborted&&d(Re(g)),a=()=>{d(Re(g))},g.addEventListener("abort",a,{once:!0})}if(n===Number.POSITIVE_INFINITY){t.then(u,d);return}const m=new Ue;i=o.setTimeout.call(void 0,()=>{if(r){try{u(r())}catch(g){d(g)}return}typeof t.cancel=="function"&&t.cancel(),s===!1?u():s instanceof Error?d(s):(m.message=s??`Promise timed out after ${n} milliseconds`,d(m))},n),(async()=>{try{u(await t)}catch(g){d(g)}})()}).finally(()=>{c.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return c.clear=()=>{o.clearTimeout.call(void 0,i),i=void 0},c}function bt(t,e,n){let r=0,s=t.length;for(;s>0;){const o=Math.trunc(s/2);let i=r+o;n(t[i],e)<=0?(r=++i,s-=o+1):s=o}return r}class Et{#e=[];enqueue(e,n){n={priority:0,...n};const r={priority:n.priority,id:n.id,run:e};if(this.size===0||this.#e[this.size-1].priority>=n.priority){this.#e.push(r);return}const s=bt(this.#e,r,(o,i)=>i.priority-o.priority);this.#e.splice(s,0,r)}setPriority(e,n){const r=this.#e.findIndex(o=>o.id===e);if(r===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);const[s]=this.#e.splice(r,1);this.enqueue(s.run,{priority:n,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(n=>n.priority===e.priority).map(n=>n.run)}get size(){return this.#e.length}}class St extends yt{#e;#i;#o=0;#h;#a;#p=0;#n;#c;#t;#m;#r=0;#l;#s;#y;#b=1n;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Et,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#i=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#h=e.intervalCap,this.#a=e.interval,this.#t=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#y=e.throwOnTimeout===!0,this.#s=e.autoStart===!1}get#E(){return this.#i||this.#o{this.#R()},n)),!0}return!1}#u(){if(this.#t.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#r===0&&this.emit("idle"),!1;if(!this.#s){const e=!this.#_;if(this.#E&&this.#S){const n=this.#t.dequeue();return n?(this.emit("active"),n(),e&&this.#g(),!0):!1}}return!1}#g(){this.#i||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#a),this.#p=Date.now()+this.#a)}#w(){this.#o===0&&this.#r===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#o=this.#e?this.#r:0,this.#f()}#f(){for(;this.#u(););}get concurrency(){return this.#l}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#l=e,this.#f()}async#A(e){return new Promise((n,r)=>{e.addEventListener("abort",()=>{r(e.reason)},{once:!0})})}setPriority(e,n){this.#t.setPriority(e,n)}async add(e,n={}){return n.id??=(this.#b++).toString(),n={timeout:this.timeout,throwOnTimeout:this.#y,...n},new Promise((r,s)=>{this.#t.enqueue(async()=>{this.#r++,this.#o++;try{n.signal?.throwIfAborted();let o=e({signal:n.signal});n.timeout&&(o=wt(Promise.resolve(o),{milliseconds:n.timeout})),n.signal&&(o=Promise.race([o,this.#A(n.signal)]));const i=await o;r(i),this.emit("completed",i)}catch(o){if(o instanceof Ue&&!n.throwOnTimeout){r();return}s(o),this.emit("error",o)}finally{this.#T()}},n),this.emit("add"),this.#u()})}async addAll(e,n){return Promise.all(e.map(async r=>this.add(r,n)))}start(){return this.#s?(this.#s=!1,this.#f(),this):this}pause(){this.#s=!0}clear(){this.#t=new this.#m}async onEmpty(){this.#t.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#t.sizethis.#t.size{const s=()=>{n&&!n()||(this.off(e,s),r())};this.on(e,s)})}get size(){return this.#t.size}sizeBy(e){return this.#t.filter(e).length}get pending(){return this.#r}get isPaused(){return this.#s}}const B=new St({concurrency:1});function P(t){return new Promise(e=>setTimeout(e,t))}async function _e(t){const n=await(await fetch(t)).blob();return new Promise((r,s)=>{const o=new FileReader;o.onloadend=()=>{typeof o.result=="string"?r(o.result.split(",")[1]):s("Không thể đọc dữ liệu ảnh")},o.onerror=s,o.readAsDataURL(n)})}function Ae(t){return t.startsWith("blob:")}function je(t,e){return function(){return t.apply(e,arguments)}}const{toString:Tt}=Object.prototype,{getPrototypeOf:ge}=Object,{iterator:te,toStringTag:He}=Symbol,ne=(t=>e=>{const n=Tt.call(e);return t[n]||(t[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),C=t=>(t=t.toLowerCase(),e=>ne(e)===t),re=t=>e=>typeof e===t,{isArray:j}=Array,V=re("undefined");function z(t){return t!==null&&!V(t)&&t.constructor!==null&&!V(t.constructor)&&A(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const $e=C("ArrayBuffer");function Rt(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&$e(t.buffer),e}const _t=re("string"),A=re("function"),Ve=re("number"),J=t=>t!==null&&typeof t=="object",At=t=>t===!0||t===!1,G=t=>{if(ne(t)!=="object")return!1;const e=ge(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(He in t)&&!(te in t)},vt=t=>{if(!J(t)||z(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},Ot=C("Date"),Ct=C("File"),xt=C("Blob"),Nt=C("FileList"),Pt=t=>J(t)&&A(t.pipe),It=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||A(t.append)&&((e=ne(t))==="formdata"||e==="object"&&A(t.toString)&&t.toString()==="[object FormData]"))},Mt=C("URLSearchParams"),[kt,Lt,Ft,Bt]=["ReadableStream","Request","Response","Headers"].map(C),Dt=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function K(t,e,{allOwnKeys:n=!1}={}){if(t===null||typeof t>"u")return;let r,s;if(typeof t!="object"&&(t=[t]),j(t))for(r=0,s=t.length;r0;)if(s=n[r],e===s.toLowerCase())return s;return null}const k=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Je=t=>!V(t)&&t!==k;function fe(){const{caseless:t}=Je(this)&&this||{},e={},n=(r,s)=>{const o=t&&ze(e,s)||s;G(e[o])&&G(r)?e[o]=fe(e[o],r):G(r)?e[o]=fe({},r):j(r)?e[o]=r.slice():e[o]=r};for(let r=0,s=arguments.length;r(K(e,(s,o)=>{n&&A(s)?t[o]=je(s,n):t[o]=s},{allOwnKeys:r}),t),Ut=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),jt=(t,e,n,r)=>{t.prototype=Object.create(e.prototype,r),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},Ht=(t,e,n,r)=>{let s,o,i;const a={};if(e=e||{},t==null)return e;do{for(s=Object.getOwnPropertyNames(t),o=s.length;o-- >0;)i=s[o],(!r||r(i,t,e))&&!a[i]&&(e[i]=t[i],a[i]=!0);t=n!==!1&&ge(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},$t=(t,e,n)=>{t=String(t),(n===void 0||n>t.length)&&(n=t.length),n-=e.length;const r=t.indexOf(e,n);return r!==-1&&r===n},Vt=t=>{if(!t)return null;if(j(t))return t;let e=t.length;if(!Ve(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},zt=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&ge(Uint8Array)),Jt=(t,e)=>{const r=(t&&t[te]).call(t);let s;for(;(s=r.next())&&!s.done;){const o=s.value;e.call(t,o[0],o[1])}},Kt=(t,e)=>{let n;const r=[];for(;(n=t.exec(e))!==null;)r.push(n);return r},Wt=C("HTMLFormElement"),Xt=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,s){return r.toUpperCase()+s}),ve=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),Gt=C("RegExp"),Ke=(t,e)=>{const n=Object.getOwnPropertyDescriptors(t),r={};K(n,(s,o)=>{let i;(i=e(s,o,t))!==!1&&(r[o]=i||s)}),Object.defineProperties(t,r)},Qt=t=>{Ke(t,(e,n)=>{if(A(t)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=t[n];if(A(r)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},Yt=(t,e)=>{const n={},r=s=>{s.forEach(o=>{n[o]=!0})};return j(t)?r(t):r(String(t).split(e)),n},Zt=()=>{},en=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function tn(t){return!!(t&&A(t.append)&&t[He]==="FormData"&&t[te])}const nn=t=>{const e=new Array(10),n=(r,s)=>{if(J(r)){if(e.indexOf(r)>=0)return;if(z(r))return r;if(!("toJSON"in r)){e[s]=r;const o=j(r)?[]:{};return K(r,(i,a)=>{const f=n(i,s+1);!V(f)&&(o[a]=f)}),e[s]=void 0,o}}return r};return n(t,0)},rn=C("AsyncFunction"),sn=t=>t&&(J(t)||A(t))&&A(t.then)&&A(t.catch),We=((t,e)=>t?setImmediate:e?((n,r)=>(k.addEventListener("message",({source:s,data:o})=>{s===k&&o===n&&r.length&&r.shift()()},!1),s=>{r.push(s),k.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",A(k.postMessage)),on=typeof queueMicrotask<"u"?queueMicrotask.bind(k):typeof process<"u"&&process.nextTick||We,an=t=>t!=null&&A(t[te]),l={isArray:j,isArrayBuffer:$e,isBuffer:z,isFormData:It,isArrayBufferView:Rt,isString:_t,isNumber:Ve,isBoolean:At,isObject:J,isPlainObject:G,isEmptyObject:vt,isReadableStream:kt,isRequest:Lt,isResponse:Ft,isHeaders:Bt,isUndefined:V,isDate:Ot,isFile:Ct,isBlob:xt,isRegExp:Gt,isFunction:A,isStream:Pt,isURLSearchParams:Mt,isTypedArray:zt,isFileList:Nt,forEach:K,merge:fe,extend:qt,trim:Dt,stripBOM:Ut,inherits:jt,toFlatObject:Ht,kindOf:ne,kindOfTest:C,endsWith:$t,toArray:Vt,forEachEntry:Jt,matchAll:Kt,isHTMLForm:Wt,hasOwnProperty:ve,hasOwnProp:ve,reduceDescriptors:Ke,freezeMethods:Qt,toObjectSet:Yt,toCamelCase:Xt,noop:Zt,toFiniteNumber:en,findKey:ze,global:k,isContextDefined:Je,isSpecCompliantForm:tn,toJSONObject:nn,isAsyncFn:rn,isThenable:sn,setImmediate:We,asap:on,isIterable:an};function w(t,e,n,r,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),n&&(this.config=n),r&&(this.request=r),s&&(this.response=s,this.status=s.status?s.status:null)}l.inherits(w,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:l.toJSONObject(this.config),code:this.code,status:this.status}}});const Xe=w.prototype,Ge={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(t=>{Ge[t]={value:t}});Object.defineProperties(w,Ge);Object.defineProperty(Xe,"isAxiosError",{value:!0});w.from=(t,e,n,r,s,o)=>{const i=Object.create(Xe);return l.toFlatObject(t,i,function(f){return f!==Error.prototype},a=>a!=="isAxiosError"),w.call(i,t.message,e,n,r,s),i.cause=t,i.name=t.name,o&&Object.assign(i,o),i};const cn=null;function de(t){return l.isPlainObject(t)||l.isArray(t)}function Qe(t){return l.endsWith(t,"[]")?t.slice(0,-2):t}function Oe(t,e,n){return t?t.concat(e).map(function(s,o){return s=Qe(s),!n&&o?"["+s+"]":s}).join(n?".":""):e}function ln(t){return l.isArray(t)&&!t.some(de)}const un=l.toFlatObject(l,{},null,function(e){return/^is[A-Z]/.test(e)});function se(t,e,n){if(!l.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,n=l.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,h){return!l.isUndefined(h[y])});const r=n.metaTokens,s=n.visitor||u,o=n.dots,i=n.indexes,f=(n.Blob||typeof Blob<"u"&&Blob)&&l.isSpecCompliantForm(e);if(!l.isFunction(s))throw new TypeError("visitor must be a function");function c(p){if(p===null)return"";if(l.isDate(p))return p.toISOString();if(l.isBoolean(p))return p.toString();if(!f&&l.isBlob(p))throw new w("Blob is not supported. Use a Buffer instead.");return l.isArrayBuffer(p)||l.isTypedArray(p)?f&&typeof Blob=="function"?new Blob([p]):Buffer.from(p):p}function u(p,y,h){let E=p;if(p&&!h&&typeof p=="object"){if(l.endsWith(y,"{}"))y=r?y:y.slice(0,-2),p=JSON.stringify(p);else if(l.isArray(p)&&ln(p)||(l.isFileList(p)||l.endsWith(y,"[]"))&&(E=l.toArray(p)))return y=Qe(y),E.forEach(function(b,O){!(l.isUndefined(b)||b===null)&&e.append(i===!0?Oe([y],O,o):i===null?y:y+"[]",c(b))}),!1}return de(p)?!0:(e.append(Oe(h,y,o),c(p)),!1)}const d=[],m=Object.assign(un,{defaultVisitor:u,convertValue:c,isVisitable:de});function g(p,y){if(!l.isUndefined(p)){if(d.indexOf(p)!==-1)throw Error("Circular reference detected in "+y.join("."));d.push(p),l.forEach(p,function(E,S){(!(l.isUndefined(E)||E===null)&&s.call(e,E,l.isString(S)?S.trim():S,y,m))===!0&&g(E,y?y.concat(S):[S])}),d.pop()}}if(!l.isObject(t))throw new TypeError("data must be an object");return g(t),e}function Ce(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(r){return e[r]})}function we(t,e){this._pairs=[],t&&se(t,this,e)}const Ye=we.prototype;Ye.append=function(e,n){this._pairs.push([e,n])};Ye.toString=function(e){const n=e?function(r){return e.call(this,r,Ce)}:Ce;return this._pairs.map(function(s){return n(s[0])+"="+n(s[1])},"").join("&")};function fn(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Ze(t,e,n){if(!e)return t;const r=n&&n.encode||fn;l.isFunction(n)&&(n={serialize:n});const s=n&&n.serialize;let o;if(s?o=s(e,n):o=l.isURLSearchParams(e)?e.toString():new we(e,n).toString(r),o){const i=t.indexOf("#");i!==-1&&(t=t.slice(0,i)),t+=(t.indexOf("?")===-1?"?":"&")+o}return t}class xe{constructor(){this.handlers=[]}use(e,n,r){return this.handlers.push({fulfilled:e,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){l.forEach(this.handlers,function(r){r!==null&&e(r)})}}const et={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},dn=typeof URLSearchParams<"u"?URLSearchParams:we,hn=typeof FormData<"u"?FormData:null,pn=typeof Blob<"u"?Blob:null,mn={isBrowser:!0,classes:{URLSearchParams:dn,FormData:hn,Blob:pn},protocols:["http","https","file","blob","url","data"]},be=typeof window<"u"&&typeof document<"u",he=typeof navigator=="object"&&navigator||void 0,yn=be&&(!he||["ReactNative","NativeScript","NS"].indexOf(he.product)<0),gn=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",wn=be&&window.location.href||"http://localhost",bn=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:be,hasStandardBrowserEnv:yn,hasStandardBrowserWebWorkerEnv:gn,navigator:he,origin:wn},Symbol.toStringTag,{value:"Module"})),_={...bn,...mn};function En(t,e){return se(t,new _.classes.URLSearchParams,{visitor:function(n,r,s,o){return _.isNode&&l.isBuffer(n)?(this.append(r,n.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...e})}function Sn(t){return l.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function Tn(t){const e={},n=Object.keys(t);let r;const s=n.length;let o;for(r=0;r=n.length;return i=!i&&l.isArray(s)?s.length:i,f?(l.hasOwnProp(s,i)?s[i]=[s[i],r]:s[i]=r,!a):((!s[i]||!l.isObject(s[i]))&&(s[i]=[]),e(n,r,s[i],o)&&l.isArray(s[i])&&(s[i]=Tn(s[i])),!a)}if(l.isFormData(t)&&l.isFunction(t.entries)){const n={};return l.forEachEntry(t,(r,s)=>{e(Sn(r),s,n,0)}),n}return null}function Rn(t,e,n){if(l.isString(t))try{return(e||JSON.parse)(t),l.trim(t)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(t)}const W={transitional:et,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const r=n.getContentType()||"",s=r.indexOf("application/json")>-1,o=l.isObject(e);if(o&&l.isHTMLForm(e)&&(e=new FormData(e)),l.isFormData(e))return s?JSON.stringify(tt(e)):e;if(l.isArrayBuffer(e)||l.isBuffer(e)||l.isStream(e)||l.isFile(e)||l.isBlob(e)||l.isReadableStream(e))return e;if(l.isArrayBufferView(e))return e.buffer;if(l.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return En(e,this.formSerializer).toString();if((a=l.isFileList(e))||r.indexOf("multipart/form-data")>-1){const f=this.env&&this.env.FormData;return se(a?{"files[]":e}:e,f&&new f,this.formSerializer)}}return o||s?(n.setContentType("application/json",!1),Rn(e)):e}],transformResponse:[function(e){const n=this.transitional||W.transitional,r=n&&n.forcedJSONParsing,s=this.responseType==="json";if(l.isResponse(e)||l.isReadableStream(e))return e;if(e&&l.isString(e)&&(r&&!this.responseType||s)){const i=!(n&&n.silentJSONParsing)&&s;try{return JSON.parse(e)}catch(a){if(i)throw a.name==="SyntaxError"?w.from(a,w.ERR_BAD_RESPONSE,this,null,this.response):a}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:_.classes.FormData,Blob:_.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};l.forEach(["delete","get","head","post","put","patch"],t=>{W.headers[t]={}});const _n=l.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),An=t=>{const e={};let n,r,s;return t&&t.split(` +`).forEach(function(i){s=i.indexOf(":"),n=i.substring(0,s).trim().toLowerCase(),r=i.substring(s+1).trim(),!(!n||e[n]&&_n[n])&&(n==="set-cookie"?e[n]?e[n].push(r):e[n]=[r]:e[n]=e[n]?e[n]+", "+r:r)}),e},Ne=Symbol("internals");function $(t){return t&&String(t).trim().toLowerCase()}function Q(t){return t===!1||t==null?t:l.isArray(t)?t.map(Q):String(t)}function vn(t){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(t);)e[r[1]]=r[2];return e}const On=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function ce(t,e,n,r,s){if(l.isFunction(r))return r.call(this,e,n);if(s&&(e=n),!!l.isString(e)){if(l.isString(r))return e.indexOf(r)!==-1;if(l.isRegExp(r))return r.test(e)}}function Cn(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,r)=>n.toUpperCase()+r)}function xn(t,e){const n=l.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(t,r+n,{value:function(s,o,i){return this[r].call(this,e,s,o,i)},configurable:!0})})}let v=class{constructor(e){e&&this.set(e)}set(e,n,r){const s=this;function o(a,f,c){const u=$(f);if(!u)throw new Error("header name must be a non-empty string");const d=l.findKey(s,u);(!d||s[d]===void 0||c===!0||c===void 0&&s[d]!==!1)&&(s[d||f]=Q(a))}const i=(a,f)=>l.forEach(a,(c,u)=>o(c,u,f));if(l.isPlainObject(e)||e instanceof this.constructor)i(e,n);else if(l.isString(e)&&(e=e.trim())&&!On(e))i(An(e),n);else if(l.isObject(e)&&l.isIterable(e)){let a={},f,c;for(const u of e){if(!l.isArray(u))throw TypeError("Object iterator must return a key-value pair");a[c=u[0]]=(f=a[c])?l.isArray(f)?[...f,u[1]]:[f,u[1]]:u[1]}i(a,n)}else e!=null&&o(n,e,r);return this}get(e,n){if(e=$(e),e){const r=l.findKey(this,e);if(r){const s=this[r];if(!n)return s;if(n===!0)return vn(s);if(l.isFunction(n))return n.call(this,s,r);if(l.isRegExp(n))return n.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=$(e),e){const r=l.findKey(this,e);return!!(r&&this[r]!==void 0&&(!n||ce(this,this[r],r,n)))}return!1}delete(e,n){const r=this;let s=!1;function o(i){if(i=$(i),i){const a=l.findKey(r,i);a&&(!n||ce(r,r[a],a,n))&&(delete r[a],s=!0)}}return l.isArray(e)?e.forEach(o):o(e),s}clear(e){const n=Object.keys(this);let r=n.length,s=!1;for(;r--;){const o=n[r];(!e||ce(this,this[o],o,e,!0))&&(delete this[o],s=!0)}return s}normalize(e){const n=this,r={};return l.forEach(this,(s,o)=>{const i=l.findKey(r,o);if(i){n[i]=Q(s),delete n[o];return}const a=e?Cn(o):String(o).trim();a!==o&&delete n[o],n[a]=Q(s),r[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return l.forEach(this,(r,s)=>{r!=null&&r!==!1&&(n[s]=e&&l.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(` +`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const r=new this(e);return n.forEach(s=>r.set(s)),r}static accessor(e){const r=(this[Ne]=this[Ne]={accessors:{}}).accessors,s=this.prototype;function o(i){const a=$(i);r[a]||(xn(s,i),r[a]=!0)}return l.isArray(e)?e.forEach(o):o(e),this}};v.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);l.reduceDescriptors(v.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(r){this[n]=r}}});l.freezeMethods(v);function le(t,e){const n=this||W,r=e||n,s=v.from(r.headers);let o=r.data;return l.forEach(t,function(a){o=a.call(n,o,s.normalize(),e?e.status:void 0)}),s.normalize(),o}function nt(t){return!!(t&&t.__CANCEL__)}function H(t,e,n){w.call(this,t??"canceled",w.ERR_CANCELED,e,n),this.name="CanceledError"}l.inherits(H,w,{__CANCEL__:!0});function rt(t,e,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?t(n):e(new w("Request failed with status code "+n.status,[w.ERR_BAD_REQUEST,w.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function Nn(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function Pn(t,e){t=t||10;const n=new Array(t),r=new Array(t);let s=0,o=0,i;return e=e!==void 0?e:1e3,function(f){const c=Date.now(),u=r[o];i||(i=c),n[s]=f,r[s]=c;let d=o,m=0;for(;d!==s;)m+=n[d++],d=d%t;if(s=(s+1)%t,s===o&&(o=(o+1)%t),c-i{n=u,s=null,o&&(clearTimeout(o),o=null),t(...c)};return[(...c)=>{const u=Date.now(),d=u-n;d>=r?i(c,u):(s=c,o||(o=setTimeout(()=>{o=null,i(s)},r-d)))},()=>s&&i(s)]}const Z=(t,e,n=3)=>{let r=0;const s=Pn(50,250);return In(o=>{const i=o.loaded,a=o.lengthComputable?o.total:void 0,f=i-r,c=s(f),u=i<=a;r=i;const d={loaded:i,total:a,progress:a?i/a:void 0,bytes:f,rate:c||void 0,estimated:c&&a&&u?(a-i)/c:void 0,event:o,lengthComputable:a!=null,[e?"download":"upload"]:!0};t(d)},n)},Pe=(t,e)=>{const n=t!=null;return[r=>e[0]({lengthComputable:n,total:t,loaded:r}),e[1]]},Ie=t=>(...e)=>l.asap(()=>t(...e)),Mn=_.hasStandardBrowserEnv?((t,e)=>n=>(n=new URL(n,_.origin),t.protocol===n.protocol&&t.host===n.host&&(e||t.port===n.port)))(new URL(_.origin),_.navigator&&/(msie|trident)/i.test(_.navigator.userAgent)):()=>!0,kn=_.hasStandardBrowserEnv?{write(t,e,n,r,s,o){const i=[t+"="+encodeURIComponent(e)];l.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),l.isString(r)&&i.push("path="+r),l.isString(s)&&i.push("domain="+s),o===!0&&i.push("secure"),document.cookie=i.join("; ")},read(t){const e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Ln(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Fn(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function st(t,e,n){let r=!Ln(e);return t&&(r||n==!1)?Fn(t,e):e}const Me=t=>t instanceof v?{...t}:t;function F(t,e){e=e||{};const n={};function r(c,u,d,m){return l.isPlainObject(c)&&l.isPlainObject(u)?l.merge.call({caseless:m},c,u):l.isPlainObject(u)?l.merge({},u):l.isArray(u)?u.slice():u}function s(c,u,d,m){if(l.isUndefined(u)){if(!l.isUndefined(c))return r(void 0,c,d,m)}else return r(c,u,d,m)}function o(c,u){if(!l.isUndefined(u))return r(void 0,u)}function i(c,u){if(l.isUndefined(u)){if(!l.isUndefined(c))return r(void 0,c)}else return r(void 0,u)}function a(c,u,d){if(d in e)return r(c,u);if(d in t)return r(void 0,c)}const f={url:o,method:o,data:o,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:a,headers:(c,u,d)=>s(Me(c),Me(u),d,!0)};return l.forEach(Object.keys({...t,...e}),function(u){const d=f[u]||s,m=d(t[u],e[u],u);l.isUndefined(m)&&d!==a||(n[u]=m)}),n}const ot=t=>{const e=F({},t);let{data:n,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:o,headers:i,auth:a}=e;e.headers=i=v.from(i),e.url=Ze(st(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):"")));let f;if(l.isFormData(n)){if(_.hasStandardBrowserEnv||_.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if((f=i.getContentType())!==!1){const[c,...u]=f?f.split(";").map(d=>d.trim()).filter(Boolean):[];i.setContentType([c||"multipart/form-data",...u].join("; "))}}if(_.hasStandardBrowserEnv&&(r&&l.isFunction(r)&&(r=r(e)),r||r!==!1&&Mn(e.url))){const c=s&&o&&kn.read(o);c&&i.set(s,c)}return e},Bn=typeof XMLHttpRequest<"u",Dn=Bn&&function(t){return new Promise(function(n,r){const s=ot(t);let o=s.data;const i=v.from(s.headers).normalize();let{responseType:a,onUploadProgress:f,onDownloadProgress:c}=s,u,d,m,g,p;function y(){g&&g(),p&&p(),s.cancelToken&&s.cancelToken.unsubscribe(u),s.signal&&s.signal.removeEventListener("abort",u)}let h=new XMLHttpRequest;h.open(s.method.toUpperCase(),s.url,!0),h.timeout=s.timeout;function E(){if(!h)return;const b=v.from("getAllResponseHeaders"in h&&h.getAllResponseHeaders()),R={data:!a||a==="text"||a==="json"?h.responseText:h.response,status:h.status,statusText:h.statusText,headers:b,config:t,request:h};rt(function(I){n(I),y()},function(I){r(I),y()},R),h=null}"onloadend"in h?h.onloadend=E:h.onreadystatechange=function(){!h||h.readyState!==4||h.status===0&&!(h.responseURL&&h.responseURL.indexOf("file:")===0)||setTimeout(E)},h.onabort=function(){h&&(r(new w("Request aborted",w.ECONNABORTED,t,h)),h=null)},h.onerror=function(){r(new w("Network Error",w.ERR_NETWORK,t,h)),h=null},h.ontimeout=function(){let O=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const R=s.transitional||et;s.timeoutErrorMessage&&(O=s.timeoutErrorMessage),r(new w(O,R.clarifyTimeoutError?w.ETIMEDOUT:w.ECONNABORTED,t,h)),h=null},o===void 0&&i.setContentType(null),"setRequestHeader"in h&&l.forEach(i.toJSON(),function(O,R){h.setRequestHeader(R,O)}),l.isUndefined(s.withCredentials)||(h.withCredentials=!!s.withCredentials),a&&a!=="json"&&(h.responseType=s.responseType),c&&([m,p]=Z(c,!0),h.addEventListener("progress",m)),f&&h.upload&&([d,g]=Z(f),h.upload.addEventListener("progress",d),h.upload.addEventListener("loadend",g)),(s.cancelToken||s.signal)&&(u=b=>{h&&(r(!b||b.type?new H(null,t,h):b),h.abort(),h=null)},s.cancelToken&&s.cancelToken.subscribe(u),s.signal&&(s.signal.aborted?u():s.signal.addEventListener("abort",u)));const S=Nn(s.url);if(S&&_.protocols.indexOf(S)===-1){r(new w("Unsupported protocol "+S+":",w.ERR_BAD_REQUEST,t));return}h.send(o||null)})},qn=(t,e)=>{const{length:n}=t=t?t.filter(Boolean):[];if(e||n){let r=new AbortController,s;const o=function(c){if(!s){s=!0,a();const u=c instanceof Error?c:this.reason;r.abort(u instanceof w?u:new H(u instanceof Error?u.message:u))}};let i=e&&setTimeout(()=>{i=null,o(new w(`timeout ${e} of ms exceeded`,w.ETIMEDOUT))},e);const a=()=>{t&&(i&&clearTimeout(i),i=null,t.forEach(c=>{c.unsubscribe?c.unsubscribe(o):c.removeEventListener("abort",o)}),t=null)};t.forEach(c=>c.addEventListener("abort",o));const{signal:f}=r;return f.unsubscribe=()=>l.asap(a),f}},Un=function*(t,e){let n=t.byteLength;if(n{const s=jn(t,e);let o=0,i,a=f=>{i||(i=!0,r&&r(f))};return new ReadableStream({async pull(f){try{const{done:c,value:u}=await s.next();if(c){a(),f.close();return}let d=u.byteLength;if(n){let m=o+=d;n(m)}f.enqueue(new Uint8Array(u))}catch(c){throw a(c),c}},cancel(f){return a(f),s.return()}},{highWaterMark:2})},oe=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",it=oe&&typeof ReadableStream=="function",$n=oe&&(typeof TextEncoder=="function"?(t=>e=>t.encode(e))(new TextEncoder):async t=>new Uint8Array(await new Response(t).arrayBuffer())),at=(t,...e)=>{try{return!!t(...e)}catch{return!1}},Vn=it&&at(()=>{let t=!1;const e=new Request(_.origin,{body:new ReadableStream,method:"POST",get duplex(){return t=!0,"half"}}).headers.has("Content-Type");return t&&!e}),Le=64*1024,pe=it&&at(()=>l.isReadableStream(new Response("").body)),ee={stream:pe&&(t=>t.body)};oe&&(t=>{["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!ee[e]&&(ee[e]=l.isFunction(t[e])?n=>n[e]():(n,r)=>{throw new w(`Response type '${e}' is not supported`,w.ERR_NOT_SUPPORT,r)})})})(new Response);const zn=async t=>{if(t==null)return 0;if(l.isBlob(t))return t.size;if(l.isSpecCompliantForm(t))return(await new Request(_.origin,{method:"POST",body:t}).arrayBuffer()).byteLength;if(l.isArrayBufferView(t)||l.isArrayBuffer(t))return t.byteLength;if(l.isURLSearchParams(t)&&(t=t+""),l.isString(t))return(await $n(t)).byteLength},Jn=async(t,e)=>{const n=l.toFiniteNumber(t.getContentLength());return n??zn(e)},Kn=oe&&(async t=>{let{url:e,method:n,data:r,signal:s,cancelToken:o,timeout:i,onDownloadProgress:a,onUploadProgress:f,responseType:c,headers:u,withCredentials:d="same-origin",fetchOptions:m}=ot(t);c=c?(c+"").toLowerCase():"text";let g=qn([s,o&&o.toAbortSignal()],i),p;const y=g&&g.unsubscribe&&(()=>{g.unsubscribe()});let h;try{if(f&&Vn&&n!=="get"&&n!=="head"&&(h=await Jn(u,r))!==0){let R=new Request(e,{method:"POST",body:r,duplex:"half"}),N;if(l.isFormData(r)&&(N=R.headers.get("content-type"))&&u.setContentType(N),R.body){const[I,X]=Pe(h,Z(Ie(f)));r=ke(R.body,Le,I,X)}}l.isString(d)||(d=d?"include":"omit");const E="credentials"in Request.prototype;p=new Request(e,{...m,signal:g,method:n.toUpperCase(),headers:u.normalize().toJSON(),body:r,duplex:"half",credentials:E?d:void 0});let S=await fetch(p,m);const b=pe&&(c==="stream"||c==="response");if(pe&&(a||b&&y)){const R={};["status","statusText","headers"].forEach(Ee=>{R[Ee]=S[Ee]});const N=l.toFiniteNumber(S.headers.get("content-length")),[I,X]=a&&Pe(N,Z(Ie(a),!0))||[];S=new Response(ke(S.body,Le,I,()=>{X&&X(),y&&y()}),R)}c=c||"text";let O=await ee[l.findKey(ee,c)||"text"](S,t);return!b&&y&&y(),await new Promise((R,N)=>{rt(R,N,{data:O,headers:v.from(S.headers),status:S.status,statusText:S.statusText,config:t,request:p})})}catch(E){throw y&&y(),E&&E.name==="TypeError"&&/Load failed|fetch/i.test(E.message)?Object.assign(new w("Network Error",w.ERR_NETWORK,t,p),{cause:E.cause||E}):w.from(E,E&&E.code,t,p)}}),me={http:cn,xhr:Dn,fetch:Kn};l.forEach(me,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const Fe=t=>`- ${t}`,Wn=t=>l.isFunction(t)||t===null||t===!1,ct={getAdapter:t=>{t=l.isArray(t)?t:[t];const{length:e}=t;let n,r;const s={};for(let o=0;o`adapter ${a} `+(f===!1?"is not supported by the environment":"is not available in the build"));let i=e?o.length>1?`since : `+o.map(Fe).join(` -`):" "+Fe(o[0]):"as no adapter specified";throw new w("There is no suitable adapter to dispatch the request "+i,"ERR_NOT_SUPPORT")}return r},adapters:me};function ue(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new H(null,t)}function Be(t){return ue(t),t.headers=A.from(t.headers),t.data=le.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),ct.getAdapter(t.adapter||W.adapter)(t).then(function(r){return ue(t),r.data=le.call(t,t.transformResponse,r),r.headers=A.from(r.headers),r},function(r){return nt(r)||(ue(t),r&&r.response&&(r.response.data=le.call(t,t.transformResponse,r.response),r.response.headers=A.from(r.response.headers))),Promise.reject(r)})}const lt="1.11.0",ie={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{ie[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});const De={};ie.transitional=function(e,n,r){function s(o,i){return"[Axios v"+lt+"] Transitional option '"+o+"'"+i+(r?". "+r:"")}return(o,i,c)=>{if(e===!1)throw new w(s(i," has been removed"+(n?" in "+n:"")),w.ERR_DEPRECATED);return n&&!De[i]&&(De[i]=!0,console.warn(s(i," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(o,i,c):!0}};ie.spelling=function(e){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};function Gn(t,e,n){if(typeof t!="object")throw new w("options must be an object",w.ERR_BAD_OPTION_VALUE);const r=Object.keys(t);let s=r.length;for(;s-- >0;){const o=r[s],i=e[o];if(i){const c=t[o],f=c===void 0||i(c,o,t);if(f!==!0)throw new w("option "+o+" must be "+f,w.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new w("Unknown option "+o,w.ERR_BAD_OPTION)}}const Y={assertOptions:Gn,validators:ie},x=Y.validators;let L=class{constructor(e){this.defaults=e||{},this.interceptors={request:new xe,response:new xe}}async request(e,n){try{return await this._request(e,n)}catch(r){if(r instanceof Error){let s={};Error.captureStackTrace?Error.captureStackTrace(s):s=new Error;const o=s.stack?s.stack.replace(/^.+\n/,""):"";try{r.stack?o&&!String(r.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(r.stack+=` -`+o):r.stack=o}catch{}}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=F(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&Y.assertOptions(r,{silentJSONParsing:x.transitional(x.boolean),forcedJSONParsing:x.transitional(x.boolean),clarifyTimeoutError:x.transitional(x.boolean)},!1),s!=null&&(l.isFunction(s)?n.paramsSerializer={serialize:s}:Y.assertOptions(s,{encode:x.function,serialize:x.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Y.assertOptions(n,{baseUrl:x.spelling("baseURL"),withXsrfToken:x.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=o&&l.merge(o.common,o[n.method]);o&&l.forEach(["delete","get","head","post","put","patch","common"],p=>{delete o[p]}),n.headers=A.concat(i,o);const c=[];let f=!0;this.interceptors.request.forEach(function(y){typeof y.runWhen=="function"&&y.runWhen(n)===!1||(f=f&&y.synchronous,c.unshift(y.fulfilled,y.rejected))});const a=[];this.interceptors.response.forEach(function(y){a.push(y.fulfilled,y.rejected)});let u,d=0,m;if(!f){const p=[Be.bind(this),void 0];for(p.unshift(...c),p.push(...a),m=p.length,u=Promise.resolve(n);d{if(!r._listeners)return;let o=r._listeners.length;for(;o-- >0;)r._listeners[o](s);r._listeners=null}),this.promise.then=s=>{let o;const i=new Promise(c=>{r.subscribe(c),o=c}).then(s);return i.cancel=function(){r.unsubscribe(o)},i},e(function(o,i,c){r.reason||(r.reason=new H(o,i,c),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=r=>{e.abort(r)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new ut(function(s){e=s}),cancel:e}}};function Qn(t){return function(n){return t.apply(null,n)}}function Yn(t){return l.isObject(t)&&t.isAxiosError===!0}const ye={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(ye).forEach(([t,e])=>{ye[e]=t});function ft(t){const e=new L(t),n=je(L.prototype.request,e);return l.extend(n,L.prototype,e,{allOwnKeys:!0}),l.extend(n,e,null,{allOwnKeys:!0}),n.create=function(s){return ft(F(t,s))},n}const T=ft(W);T.Axios=L;T.CanceledError=H;T.CancelToken=Xn;T.isCancel=nt;T.VERSION=lt;T.toFormData=se;T.AxiosError=w;T.Cancel=T.CanceledError;T.all=function(e){return Promise.all(e)};T.spread=Qn;T.isAxiosError=Yn;T.mergeConfig=F;T.AxiosHeaders=A;T.formToJSON=t=>tt(l.isHTMLForm(t)?new FormData(t):t);T.getAdapter=ct.getAdapter;T.HttpStatusCode=ye;T.default=T;const{Axios:ar,AxiosError:cr,CanceledError:lr,isCancel:ur,CancelToken:fr,VERSION:dr,all:hr,Cancel:pr,isAxiosError:mr,spread:yr,toFormData:gr,AxiosHeaders:wr,HttpStatusCode:br,formToJSON:Er,getAdapter:Sr,mergeConfig:Tr}=T,q=T.create({baseURL:"https://localhost:4000/api/v1/",headers:{"Content-Type":"application/json"}});class Zn{async sendSingleMessage(e){try{const{data:n}=await q.post("/messages",e);return console.log("[NestJS] Response (single):",n),n}catch(n){throw console.error("[NestJS] Error (single):",n),n}}async sendBulkMessages(e){try{const{data:n}=await q.post("/messages/bulk",{data:e});return console.log("[NestJS] Response (bulk):",n),n}catch(n){throw console.error("[NestJS] Error (bulk):",n),n}}async createAndSendToZulip(e){try{const n=await Promise.all(e.map(async s=>{if(Array.isArray(s.message)){const o=await Promise.all(s.message.map(async i=>_e(i)?await ve(i):i));return{...s,message:o}}if(_e(s.message||"")){console.log("Found blob URL, converting to Base64:",s.message);const o=await ve(s.message||"");return{...s,message:o}}return s})),{data:r}=await q.post("/messages/create-and-send",{data:n});return console.log("[NestJS] Response (create and send):",r),r}catch(n){throw console.error("[NestJS] Error (create and send):",n),n}}async sendLog(e){try{const{data:n}=await q.post("/messages/logs",e);return console.log("[NestJS] Response (logs):",n),n}catch(n){throw console.error("[NestJS] Error (logs):",n),n}}}const M=new Zn;class er{MY_NAME="Apactech com";lastMessage;initialHistories=[];elTags={container_scroll:"/html/body/div[1]/div/div/div/div[5]/div[1]/div[1]/div[2]/div[1]/div[1]/div",conatainer_conversations:"/html/body/div[1]/div/div/div/div[5]/div[1]/div[1]/div[2]/div[1]/div[1]/div/div[1]",container_chat:'[data-testid="message-wrapper"]',root_id:'[aria-selected="true"] [id^="chat-list-item"]',room_name:'[data-tid="chat-title"]',close_reply_btn:'[data-track-action-scenario="messageQuotedReplyDismissed"]',reply_btn:'[aria-label="Reply"]',chat_input:'[placeholder="Type a message"]'};_getImageFormEl(e){let n=Array.from(e.querySelectorAll("img[data-gallery-src]"));return n.length===0&&e.parentElement&&(n=Array.from(e.parentElement.querySelectorAll("img[data-gallery-src]"))),n}getCurrentRoomInfo(){const e=document.querySelector(this.elTags.root_id)?.id?.replace("chat-list-item_",""),n=document.querySelector(this.elTags.room_name)?.innerText;return{room_id:e,room_name:n}}_getFileLinks(e){const n=`attachments-${e?.date_time}`,r=document.getElementById(n);return r?Array.from(r.children).flatMap(i=>{const c=this.getAssetToken(),f=i.getAttribute("title");if(!f)return[];const a=f.split(/\r?\n/).map(m=>m.trim()).filter(Boolean),u=a[0]||null,d=a.find(m=>/^https?:\/\//.test(m));return d?[{name:u,url:d,token:c}]:[]}):[]}_getMessageByEl(e){if(!e)return[];const n=[],r=e.innerText?.trim()||"",o=(this._getImageFormEl(e)||[]).map(a=>a.getAttribute("src")).filter(Boolean);if(o.length>0){const a=document.getElementById(`message-body-${e?.date_time}`)?.querySelector('[data-tid="overlay-count-text"]');a&&a.innerText===r?n.push(...o):(n.push(...o),r&&n.push(r))}else r&&n.push(r);const i=this._getFileLinks(e)||[];i.length&&i.forEach(a=>{n.push(JSON.stringify({...a,type:"file"}))});const f=Array.from(e.querySelectorAll("img[itemtype]")).map(a=>a.getAttribute("alt")||"").filter(Boolean);return f.length>0&&n.push(f.join("")),n}parseMessageElement(e,n=!1){const r=e.querySelector(n?".fui-ChatMyMessage__timestamp":".fui-ChatMessage__timestamp"),s=e.querySelector(n?".fui-ChatMyMessage__author":".fui-ChatMessage__author");if(!r)return null;const o=r.getAttribute("datetime");if(!o)return null;const i=Number.isNaN(r.id.replace("timestamp-",""))?new Date(o).getTime():Number(r.id.replace("timestamp-","")),c=document.querySelector(`#content-${i}`);c.date_time=i;const{room_id:f,room_name:a}=this.getCurrentRoomInfo();return{name:s?.innerText,message:this._getMessageByEl(c),time:i,room_id:f,room_name:a,date_time:new Date(o).getTime()}}getAssetToken(){const e=Object.keys(localStorage).find(r=>{const s=localStorage[r];return s.includes('"credentialType":"AccessToken"')&&s.includes('"target":"https://graph.microsoft.com/.default')});return e?JSON.parse(localStorage[e]).secret:null}extractAllMessages(){const e=Array.from(document.querySelectorAll(".fui-ChatMyMessage")).map(r=>this.parseMessageElement(r,!0)).filter(r=>r!==null),n=Array.from(document.querySelectorAll(".fui-ChatMessage")).map(r=>this.parseMessageElement(r,!1)).filter(r=>r!==null);return console.log({myMessages:e,otherMessages:n}),[...e,...n].sort((r,s)=>r.time-s.time)}async detectNewMessages(){const e=this.extractAllMessages(),n=e.findIndex(o=>o.time===this.lastMessage?.time),r=e.slice(n+1);if(r.length===0){console.log("[Monitor] No new messages...");return}const s=r[0];return this.lastMessage=e.pop(),s}async start(e=1e4){console.log("[Monitor] Starting..."),this.initialHistories=this.extractAllMessages(),this.lastMessage=this.initialHistories.pop(),setInterval(async()=>await this.detectNewMessages(),e)}async _getConversationsInfo(e=this.elTags.conatainer_conversations){const n=document.evaluate(e,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;return n?Array.from(n.children).filter(o=>o.getAttribute("role")==="none").map(o=>{const i=o.id||null,c=`title-chat-list-item_${i}`,a=document.getElementById(c)?.innerText||null;let u=null;return i?.includes("@thread.skype")?u="group":i?.includes("@oneToOne.skype")?u="personal":u="group",{id:i,name:a,type:u}}):(console.log("Không tìm thấy phần tử theo XPath."),M.sendLog({type:"error",message:`Not found selector: ${e}`}),[])}async _scrollToBottomByXPath(e=this.elTags.container_scroll,n){const{maxStableRounds:r=5,delay:s=300,maxScrolls:o=100}=n||{},i=document.evaluate(e,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;if(!i){console.warn("❌ Không tìm thấy phần tử với XPath:",e),M.sendLog({type:"error",message:`Not found selector: ${e}`});return}return new Promise(c=>{let f=-1,a=0,u=0;const d=setInterval(()=>{const m=i.scrollHeight;i.scrollTop=m,m===f?a++:(a=0,f=m),u++,(a>=r||u>=o)&&(clearInterval(d),c())},s)})}async handleGetConversations(){return await this._scrollToBottomByXPath(),this._getConversationsInfo()}}class tr{axios=null;constructor(){this.axios=T.create({baseURL:"MyCoolApp",headers:{"Content-Type":"application/json"}})}async send(e){if(!this.axios)return null;const{data:n}=await this.axios({method:"POST",url:"type",data:{message:e}});return n}}const qe=new tr;class nr{async index(e){try{const{data:n}=await q({url:"conversations",params:e});return console.log("[NestJS] Response (conversation-index):",n),n}catch(n){throw console.error("[NestJS] Error (conversation-index):",n),n}}async getConversationByPrefix(){try{const{data:e}=await q({url:"conversations/prefix",method:"POST"});return console.log("[NestJS] Response (conversation-prefix):",e),e}catch(e){throw console.error("[NestJS] Error (conversation-prefix):",e),e}}}const rr=new nr;class sr{service;port;constructor(e){this.service=new er,this.port=e}_forceHeightObserver;getElementByXPath(e){return document.evaluate(e,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}forceHeight(e,n="100px"){if(!e)return;e.style.setProperty("height",n,"important"),e.style.setProperty("resize","none","important");const r=()=>{e.style.setProperty("height",n,"important")};e.addEventListener("focus",r),e.addEventListener("input",r),e.addEventListener("blur",r);const s=new MutationObserver(()=>{e.style.setProperty("height",n,"important")});s.observe(e,{attributes:!0,attributeFilter:["style"]}),this._forceHeightObserver=s}_clickToConversation(e){const n=document.getElementById(`chat-list-item_${e}`);return n&&(n.scrollIntoView({behavior:"smooth",block:"center"}),setTimeout(()=>n.click(),200)),n?.click()}async _waitForMessagesToAppear(e=1e4){return new Promise((n,r)=>{const s=document.getElementById("chat-pane-list");let o=null;if(!s)return r(new Error("#chat-pane-list not found"));const i=()=>Array.from(s.children),c=()=>{const a=i();a.length>0&&(f.disconnect(),o&&clearTimeout(o),n(a))},f=new MutationObserver(()=>{c()});f.observe(s,{childList:!0,subtree:!0}),c(),o=setTimeout(()=>{f.disconnect(),r(new Error("Timeout waiting for chat messages to appear"))},e)})}async _waitForNewMessages(e,n=1e4){return new Promise((r,s)=>{const o=document.getElementById("chat-pane-list");if(!o)return s(new Error("#chat-pane-list not found"));const i=()=>Array.from(o.children),c=new Set(e);let f=null;const a=new MutationObserver(()=>{const d=i().filter(m=>!c.has(m));d.length>0&&(a.disconnect(),f&&clearTimeout(f),r(d))});a.observe(o,{childList:!0,subtree:!0}),f=setTimeout(()=>{a.disconnect(),s(new Error("Timeout waiting for new messages"))},n)})}async _waitToloadMessages(e=300){return new Promise(n=>{const r=document.getElementById("chat-pane-list");if(!r)throw new Error("#chat-pane-list not found");let s=null,o=[];const i=new MutationObserver(()=>{s&&clearTimeout(s),o=Array.from(r.children),s=setTimeout(()=>{i.disconnect(),n(o)},e)});i.observe(r,{childList:!0,subtree:!0,attributes:!0,characterData:!0})})}_getTypeGeo(){const e=document.querySelector(".ck-placeholder");if(e){const n=e.getBoundingClientRect();return{top:n.top,left:n.left,right:n.right,bottom:n.bottom,width:n.width,height:n.height}}return null}async _rightClickMessage(e){const n=this.service.elTags.container_chat,r=`content-${e}`,s=30,o=200;let i=0,c=document.querySelector(n);if(!c){console.error("Wrapper not found:",n),await M.sendLog({type:"error",message:`Not found selector: ${n}`});return}let f=document.querySelector(`#${r}`);for(;!f&&i{const r=document.querySelector(e);r?(r.scrollIntoView({behavior:"auto",block:"center"}),setTimeout(()=>{r?.click(),n(!0)},100)):(console.warn("Không tìm thấy phần tử:",e),n(!1))})}async getConversations(e){B.add(async()=>{console.log("[Queue] Handling GET_CONVERSATIONS");const n=await this.service.handleGetConversations();this.port.postMessage({type:"socket-response",event:D.RECEIVE_CONVERSATIONS,data:n})})}async getConversation(e){B.add(async()=>{if(console.log("[Queue] Handling GET_CONVERSATION"),!e.data?.id)return;const{room_id:n}=this.service.getCurrentRoomInfo();n!=e.data.id&&(this._clickToConversation(e.data.id),await this._waitForMessagesToAppear(),await this._waitToloadMessages());const r=this.service.extractAllMessages();this.port.postMessage({type:"socket-response",event:D.RECEIVE_CONVERSATION,data:r})})}async sendMessage({data:{conversation_id:e,message:n}}){B.add(async()=>{console.log("[Queue] Handling SEND_MESSAGE");const{room_id:r}=this.service.getCurrentRoomInfo();r!=e&&this._clickToConversation(e),await P(200),await qe.send(n)})}async replyMessage({data:{conversation_id:e,message:n,time:r}}){B.add(async()=>{console.log("[Queue] Handling REPLY_MESSAGE");const{room_id:s}=this.service.getCurrentRoomInfo();s!=e&&(this._clickToConversation(e),await this._waitForMessagesToAppear(),await this._waitToloadMessages()),await this._clickIfExists(this.service.elTags.close_reply_btn),await this._rightClickMessage(r);const o=document.querySelector(this.service.elTags.reply_btn);o&&o.click(),await P(200),console.log({message:n}),await qe.send(n)})}fixedHeightChatInput(e=20,n=2e3){(()=>{const s=document.querySelector(this.service.elTags.chat_input);s?(this.forceHeight(s,"100px"),console.log("✔ Fixed height applied to chat input")):e>0?setTimeout(()=>this.fixedHeightChatInput(e-1,n),n):(console.warn("✘ Element not found with provided XPath after retries"),M.sendLog({type:"error",message:`Not found selector: ${this.service.elTags.chat_input}`}))})()}async detectNewMessage(e=2e3){console.log("[Monitor] Starting..."),this.service.initialHistories=this.service.extractAllMessages(),this.service.lastMessage=this.service.initialHistories.pop(),setInterval(()=>{B.add(async()=>{try{const n=this.service.getCurrentRoomInfo(),r=document.querySelector('[aria-labelledby^="cn-normal-notification-main-content-"]')?.getAttribute("aria-labelledby");if(!r){const c=await this.service.detectNewMessages();if(!c){console.log("[Monitor] No new message...");return}if(n.room_id!==c?.room_id){console.log("[Monitor] Message from another room → skip");return}console.log("[Monitor] Found new message:",c),await this._sendLastMessage(c);return}const s=r.split(" ")[0].replace("cn-normal-notification-main-content-","");if(!s){console.warn("[Monitor] Could not extract room_id from aria-labelledby");return}console.log("[Monitor] Notification detected:",{roomId:s,ariaValue:r}),this._clickToConversation(s),await P(2e3);const i=this.service.extractAllMessages().at(-1);if(!i){console.log("[Queue] No last message found after sync");return}console.log("[Queue] Sending last message:",i),await this._sendLastMessage(i)}catch(n){console.error("[Monitor] Error detecting new message:",n)}})},e)}async _sendLastMessage(e){try{await M.sendSingleMessage(e),console.log("[API] Sent message successfully:",e)}catch(n){console.error("[API] Failed to send message:",n)}}filesMessages(){return this.service.extractAllMessages().filter(r=>Array.isArray(r.message)?r.message.some(s=>{try{return(typeof s=="string"?JSON.parse(s):s)?.type==="file"}catch{return!1}}):!1)}async clickToRefreshToken(e){const n=e.at(-1);document.getElementById(`attachments-${n?.date_time}`)?.querySelector('[aria-label="More attachment options"]')?.click(),await P(500)}startSyncConversations(){window._chatIntervals=window?._chatIntervals||{},window._chatIntervals.syncConversations?console.log("ℹ️ startSyncConversations already running"):(window._chatIntervals.syncConversations=window.setInterval(()=>{this.getConversations()},12e4),console.log("✅ startSyncConversations running"))}autoSyncConversationPrefixMessages(){window._chatIntervals=window?._chatIntervals||{},window._chatIntervals.syncPrefixMessages?console.log("ℹ️ autoSyncConversationPrefixMessages already running"):(window._chatIntervals.syncPrefixMessages=window.setInterval(()=>{B.add(async()=>{try{const{data:e}=await rr.getConversationByPrefix();if(!e)return;for(const n of e){this._clickToConversation(n.id),await P(5e3);const r=this.service.getCurrentRoomInfo();if(!r||r.room_id!==n.id)return;const s=this.filesMessages();s.length&&await this.clickToRefreshToken(s);const o=this.service.extractAllMessages();await M.createAndSendToZulip(o),await P(5e3)}}catch(e){console.error("❌ autoSyncConversationPrefixMessages error:",e?.message),M.sendLog({type:"error",message:`auto_to_sync_conersations: ${e?.message}`})}})},4e4),console.log("✅ autoSyncConversationPrefixMessages running with PQueue"))}}const dt=chrome.runtime.connect({name:"message"}),U=new sr(dt);dt.onMessage.addListener(t=>{if(console.log({msg:t}),t.type==="socket")switch(t.event){case D.GET_CONVERSATIONS:{U.getConversations(t);break}case D.GET_CONVERSATION:{U.getConversation(t);break}case D.SEND_MESSAGE:{U.sendMessage(t);break}case D.REPLY_MESSAGE:{U.replyMessage(t);break}}});U.startSyncConversations();U.autoSyncConversationPrefixMessages(); +`):" "+Fe(o[0]):"as no adapter specified";throw new w("There is no suitable adapter to dispatch the request "+i,"ERR_NOT_SUPPORT")}return r},adapters:me};function ue(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new H(null,t)}function Be(t){return ue(t),t.headers=v.from(t.headers),t.data=le.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),ct.getAdapter(t.adapter||W.adapter)(t).then(function(r){return ue(t),r.data=le.call(t,t.transformResponse,r),r.headers=v.from(r.headers),r},function(r){return nt(r)||(ue(t),r&&r.response&&(r.response.data=le.call(t,t.transformResponse,r.response),r.response.headers=v.from(r.response.headers))),Promise.reject(r)})}const lt="1.11.0",ie={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{ie[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});const De={};ie.transitional=function(e,n,r){function s(o,i){return"[Axios v"+lt+"] Transitional option '"+o+"'"+i+(r?". "+r:"")}return(o,i,a)=>{if(e===!1)throw new w(s(i," has been removed"+(n?" in "+n:"")),w.ERR_DEPRECATED);return n&&!De[i]&&(De[i]=!0,console.warn(s(i," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(o,i,a):!0}};ie.spelling=function(e){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};function Xn(t,e,n){if(typeof t!="object")throw new w("options must be an object",w.ERR_BAD_OPTION_VALUE);const r=Object.keys(t);let s=r.length;for(;s-- >0;){const o=r[s],i=e[o];if(i){const a=t[o],f=a===void 0||i(a,o,t);if(f!==!0)throw new w("option "+o+" must be "+f,w.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new w("Unknown option "+o,w.ERR_BAD_OPTION)}}const Y={assertOptions:Xn,validators:ie},x=Y.validators;let L=class{constructor(e){this.defaults=e||{},this.interceptors={request:new xe,response:new xe}}async request(e,n){try{return await this._request(e,n)}catch(r){if(r instanceof Error){let s={};Error.captureStackTrace?Error.captureStackTrace(s):s=new Error;const o=s.stack?s.stack.replace(/^.+\n/,""):"";try{r.stack?o&&!String(r.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(r.stack+=` +`+o):r.stack=o}catch{}}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=F(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&Y.assertOptions(r,{silentJSONParsing:x.transitional(x.boolean),forcedJSONParsing:x.transitional(x.boolean),clarifyTimeoutError:x.transitional(x.boolean)},!1),s!=null&&(l.isFunction(s)?n.paramsSerializer={serialize:s}:Y.assertOptions(s,{encode:x.function,serialize:x.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Y.assertOptions(n,{baseUrl:x.spelling("baseURL"),withXsrfToken:x.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=o&&l.merge(o.common,o[n.method]);o&&l.forEach(["delete","get","head","post","put","patch","common"],p=>{delete o[p]}),n.headers=v.concat(i,o);const a=[];let f=!0;this.interceptors.request.forEach(function(y){typeof y.runWhen=="function"&&y.runWhen(n)===!1||(f=f&&y.synchronous,a.unshift(y.fulfilled,y.rejected))});const c=[];this.interceptors.response.forEach(function(y){c.push(y.fulfilled,y.rejected)});let u,d=0,m;if(!f){const p=[Be.bind(this),void 0];for(p.unshift(...a),p.push(...c),m=p.length,u=Promise.resolve(n);d{if(!r._listeners)return;let o=r._listeners.length;for(;o-- >0;)r._listeners[o](s);r._listeners=null}),this.promise.then=s=>{let o;const i=new Promise(a=>{r.subscribe(a),o=a}).then(s);return i.cancel=function(){r.unsubscribe(o)},i},e(function(o,i,a){r.reason||(r.reason=new H(o,i,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=r=>{e.abort(r)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new ut(function(s){e=s}),cancel:e}}};function Qn(t){return function(n){return t.apply(null,n)}}function Yn(t){return l.isObject(t)&&t.isAxiosError===!0}const ye={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(ye).forEach(([t,e])=>{ye[e]=t});function ft(t){const e=new L(t),n=je(L.prototype.request,e);return l.extend(n,L.prototype,e,{allOwnKeys:!0}),l.extend(n,e,null,{allOwnKeys:!0}),n.create=function(s){return ft(F(t,s))},n}const T=ft(W);T.Axios=L;T.CanceledError=H;T.CancelToken=Gn;T.isCancel=nt;T.VERSION=lt;T.toFormData=se;T.AxiosError=w;T.Cancel=T.CanceledError;T.all=function(e){return Promise.all(e)};T.spread=Qn;T.isAxiosError=Yn;T.mergeConfig=F;T.AxiosHeaders=v;T.formToJSON=t=>tt(l.isHTMLForm(t)?new FormData(t):t);T.getAdapter=ct.getAdapter;T.HttpStatusCode=ye;T.default=T;const{Axios:ar,AxiosError:cr,CanceledError:lr,isCancel:ur,CancelToken:fr,VERSION:dr,all:hr,Cancel:pr,isAxiosError:mr,spread:yr,toFormData:gr,AxiosHeaders:wr,HttpStatusCode:br,formToJSON:Er,getAdapter:Sr,mergeConfig:Tr}=T,q=T.create({baseURL:"https://localhost:4000/api/v1/",headers:{"Content-Type":"application/json"}});class Zn{async sendSingleMessage(e){try{const{data:n}=await q.post("/messages",e);return console.log("[NestJS] Response (single):",n),n}catch(n){throw console.error("[NestJS] Error (single):",n),n}}async sendBulkMessages(e){try{const{data:n}=await q.post("/messages/bulk",{data:e});return console.log("[NestJS] Response (bulk):",n),n}catch(n){throw console.error("[NestJS] Error (bulk):",n),n}}async createAndSendToZulip(e){try{const n=await Promise.all(e.map(async s=>{if(Array.isArray(s.message)){const o=await Promise.all(s.message.map(async i=>Ae(i)?await _e(i):i));return{...s,message:o}}if(Ae(s.message||"")){console.log("Found blob URL, converting to Base64:",s.message);const o=await _e(s.message||"");return{...s,message:o}}return s})),{data:r}=await q.post("/messages/create-and-send",{data:n});return console.log("[NestJS] Response (create and send):",r),r}catch(n){throw console.error("[NestJS] Error (create and send):",n),n}}async sendLog(e){try{const{data:n}=await q.post("/messages/logs",e);return console.log("[NestJS] Response (logs):",n),n}catch(n){throw console.error("[NestJS] Error (logs):",n),n}}}const M=new Zn;class er{lastMessage;initialHistories=[];elTags={container_scroll:'//*[@data-testid="simple-collab-rail"]',conatainer_conversations:'//*[@data-testid="simple-collab-dnd-rail"]',container_chat:'[data-testid="message-wrapper"]',root_id:'[aria-selected="true"] [id^="chat-list-item"]',room_name:'[data-tid="chat-title"]',close_reply_btn:'[data-track-action-scenario="messageQuotedReplyDismissed"]',reply_btn:'[aria-label="Reply"]',chat_input:'[placeholder="Type a message"]'};_getImageFormEl(e){let n=Array.from(e.querySelectorAll("img[data-gallery-src]"));return n.length===0&&e.parentElement&&(n=Array.from(e.parentElement.querySelectorAll("img[data-gallery-src]"))),n}getCurrentRoomInfo(){const e=document.querySelector(this.elTags.root_id)?.id?.replace("chat-list-item_",""),n=document.querySelector(this.elTags.room_name)?.innerText;return{room_id:e,room_name:n}}_getFileLinks(e){const n=`attachments-${e?.date_time}`,r=document.getElementById(n);return r?Array.from(r.children).flatMap(i=>{const a=this.getAssetToken(),f=i.getAttribute("title");if(!f)return[];const c=f.split(/\r?\n/).map(m=>m.trim()).filter(Boolean),u=c[0]||null,d=c.find(m=>/^https?:\/\//.test(m));return d?[{name:u,url:d,token:a}]:[]}):[]}_getMessageByEl(e){if(!e)return[];const n=[],r=e.innerText?.trim()||"",o=(this._getImageFormEl(e)||[]).map(c=>c.getAttribute("src")).filter(Boolean);if(o.length>0){const c=document.getElementById(`message-body-${e?.date_time}`)?.querySelector('[data-tid="overlay-count-text"]');c&&c.innerText===r?n.push(...o):(n.push(...o),r&&n.push(r))}else r&&n.push(r);const i=this._getFileLinks(e)||[];i.length&&i.forEach(c=>{n.push(JSON.stringify({...c,type:"file"}))});const f=Array.from(e.querySelectorAll("img[itemtype]")).map(c=>c.getAttribute("alt")||"").filter(Boolean);return f.length>0&&n.push(f.join("")),n}parseMessageElement(e,n=!1){const r=e.querySelector(n?".fui-ChatMyMessage__timestamp":".fui-ChatMessage__timestamp"),s=e.querySelector(n?".fui-ChatMyMessage__author":".fui-ChatMessage__author");if(!r)return null;const o=r.getAttribute("datetime");if(!o)return null;const i=Number.isNaN(r.id.replace("timestamp-",""))?new Date(o).getTime():Number(r.id.replace("timestamp-","")),a=document.querySelector(`#content-${i}`);a.date_time=i;const{room_id:f,room_name:c}=this.getCurrentRoomInfo();return{name:s?.innerText,message:this._getMessageByEl(a),time:i,room_id:f,room_name:c,date_time:new Date(o).getTime()}}getAssetToken(){const e=Object.keys(localStorage).find(r=>{const s=localStorage[r];return s.includes('"credentialType":"AccessToken"')&&s.includes('"target":"https://graph.microsoft.com/.default')});return e?JSON.parse(localStorage[e]).secret:null}extractAllMessages(){const e=Array.from(document.querySelectorAll(".fui-ChatMyMessage")).map(r=>this.parseMessageElement(r,!0)).filter(r=>r!==null),n=Array.from(document.querySelectorAll(".fui-ChatMessage")).map(r=>this.parseMessageElement(r,!1)).filter(r=>r!==null);return console.log({myMessages:e,otherMessages:n}),[...e,...n].sort((r,s)=>r.time-s.time)}async detectNewMessages(){const e=this.extractAllMessages(),n=e.findIndex(o=>o.time===this.lastMessage?.time),r=e.slice(n+1);if(r.length===0){console.log("[Monitor] No new messages...");return}const s=r[0];return this.lastMessage=e.pop(),s}async start(e=1e4){console.log("[Monitor] Starting..."),this.initialHistories=this.extractAllMessages(),this.lastMessage=this.initialHistories.pop(),setInterval(async()=>await this.detectNewMessages(),e)}async _getConversationsInfo(e=this.elTags.conatainer_conversations){const n=document.evaluate(e,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;return n?Array.from(n.querySelectorAll('[data-item-type="chat"]')).map(o=>{const a=(o.getAttribute("data-fui-tree-item-value")||"").split("/").pop()||"",f=a.includes("|")?a.split("|")[1]:null,c=`title-chat-list-item_${f}`,d=document.getElementById(c)?.innerText||null;let m=null;return f?.includes("@thread.skype")?m="group":f?.includes("@oneToOne.skype")?m="personal":m="group",{id:f,name:d,type:m}}):(console.log("Không tìm thấy phần tử theo XPath."),M.sendLog({type:"error",message:`Not found selector: ${e}`}),[])}async _scrollToBottomByXPath(e=this.elTags.container_scroll,n){const{maxStableRounds:r=5,delay:s=300,maxScrolls:o=100}=n||{},i=document.evaluate(e,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;if(!i){console.warn("❌ Không tìm thấy phần tử với XPath:",e),M.sendLog({type:"error",message:`Not found selector: ${e}`});return}return new Promise(a=>{let f=-1,c=0,u=0;const d=setInterval(()=>{const m=i.scrollHeight;i.scrollTop=m,m===f?c++:(c=0,f=m),u++,(c>=r||u>=o)&&(clearInterval(d),a())},s)})}async handleGetConversations(){return await this._scrollToBottomByXPath(),this._getConversationsInfo()}}class tr{axios=null;constructor(){this.axios=T.create({baseURL:"MyCoolApp",headers:{"Content-Type":"application/json"}})}async send(e){if(!this.axios)return null;const{data:n}=await this.axios({method:"POST",url:"type",data:{message:e}});return n}}const qe=new tr;class nr{async index(e){try{const{data:n}=await q({url:"conversations",params:e});return console.log("[NestJS] Response (conversation-index):",n),n}catch(n){throw console.error("[NestJS] Error (conversation-index):",n),n}}async getConversationByPrefix(){try{const{data:e}=await q({url:"conversations/prefix",method:"POST"});return console.log("[NestJS] Response (conversation-prefix):",e),e}catch(e){throw console.error("[NestJS] Error (conversation-prefix):",e),e}}}const rr=new nr;class sr{service;port;constructor(e){this.service=new er,this.port=e}_forceHeightObserver;getElementByXPath(e){return document.evaluate(e,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}forceHeight(e,n="100px"){if(!e)return;e.style.setProperty("height",n,"important"),e.style.setProperty("resize","none","important");const r=()=>{e.style.setProperty("height",n,"important")};e.addEventListener("focus",r),e.addEventListener("input",r),e.addEventListener("blur",r);const s=new MutationObserver(()=>{e.style.setProperty("height",n,"important")});s.observe(e,{attributes:!0,attributeFilter:["style"]}),this._forceHeightObserver=s}_clickToConversation(e){const n=document.getElementById(`chat-list-item_${e}`);return n&&(n.scrollIntoView({behavior:"smooth",block:"center"}),setTimeout(()=>n.click(),200)),n?.click()}async _waitForMessagesToAppear(e=1e4){return new Promise((n,r)=>{const s=document.getElementById("chat-pane-list");let o=null;if(!s)return r(new Error("#chat-pane-list not found"));const i=()=>Array.from(s.children),a=()=>{const c=i();c.length>0&&(f.disconnect(),o&&clearTimeout(o),n(c))},f=new MutationObserver(()=>{a()});f.observe(s,{childList:!0,subtree:!0}),a(),o=setTimeout(()=>{f.disconnect(),r(new Error("Timeout waiting for chat messages to appear"))},e)})}async _waitToloadMessages(e=300){return new Promise(n=>{const r=document.getElementById("chat-pane-list");if(!r)throw new Error("#chat-pane-list not found");let s=null,o=[];const i=new MutationObserver(()=>{s&&clearTimeout(s),o=Array.from(r.children),s=setTimeout(()=>{i.disconnect(),n(o)},e)});i.observe(r,{childList:!0,subtree:!0,attributes:!0,characterData:!0})})}async _rightClickMessage(e){const n=this.service.elTags.container_chat,r=`content-${e}`,s=30,o=200;let i=0,a=document.querySelector(n);if(!a){console.error("Wrapper not found:",n),await M.sendLog({type:"error",message:`Not found selector: ${n}`});return}let f=document.querySelector(`#${r}`);for(;!f&&i{const r=document.querySelector(e);r?(r.scrollIntoView({behavior:"auto",block:"center"}),setTimeout(()=>{r?.click(),n(!0)},100)):(console.warn("Không tìm thấy phần tử:",e),n(!1))})}async getConversations(e){B.add(async()=>{console.log("[Queue] Handling GET_CONVERSATIONS");const n=await this.service.handleGetConversations();this.port.postMessage({type:"socket-response",event:D.RECEIVE_CONVERSATIONS,data:n})})}async getConversation(e){B.add(async()=>{if(console.log("[Queue] Handling GET_CONVERSATION"),!e.data?.id)return;const{room_id:n}=this.service.getCurrentRoomInfo();n!=e.data.id&&(this._clickToConversation(e.data.id),await this._waitForMessagesToAppear(),await this._waitToloadMessages());const r=this.service.extractAllMessages();this.port.postMessage({type:"socket-response",event:D.RECEIVE_CONVERSATION,data:r})})}async sendMessage({data:{conversation_id:e,message:n}}){B.add(async()=>{console.log("[Queue] Handling SEND_MESSAGE");const{room_id:r}=this.service.getCurrentRoomInfo();r!=e&&this._clickToConversation(e),await P(200),await qe.send(n)})}async replyMessage({data:{conversation_id:e,message:n,time:r}}){B.add(async()=>{console.log("[Queue] Handling REPLY_MESSAGE");let s=null;const{room_id:o}=this.service.getCurrentRoomInfo();o!=e&&(this._clickToConversation(e),s=await this._waitForMessagesToAppear(),await this._waitToloadMessages(),console.log({initialMessages:s})),await this._clickIfExists(this.service.elTags.close_reply_btn),await this._rightClickMessage(r);const i=document.querySelector(this.service.elTags.reply_btn);i&&i.click(),await P(200),console.log({message:n}),await qe.send(n)})}fixedHeightChatInput(e=20,n=2e3){(()=>{const s=document.querySelector(this.service.elTags.chat_input);s?(this.forceHeight(s,"100px"),console.log("✔ Fixed height applied to chat input")):e>0?setTimeout(()=>this.fixedHeightChatInput(e-1,n),n):(console.warn("✘ Element not found with provided XPath after retries"),M.sendLog({type:"error",message:`Not found selector: ${this.service.elTags.chat_input}`}))})()}async detectNewMessage(e=2e3){console.log("[Monitor] Starting..."),this.service.initialHistories=this.service.extractAllMessages(),this.service.lastMessage=this.service.initialHistories.pop(),setInterval(()=>{B.add(async()=>{try{const n=this.service.getCurrentRoomInfo(),r=document.querySelector('[aria-labelledby^="cn-normal-notification-main-content-"]')?.getAttribute("aria-labelledby");if(!r){const a=await this.service.detectNewMessages();if(!a){console.log("[Monitor] No new message...");return}if(n.room_id!==a?.room_id){console.log("[Monitor] Message from another room → skip");return}console.log("[Monitor] Found new message:",a),await this._sendLastMessage(a);return}const s=r.split(" ")[0].replace("cn-normal-notification-main-content-","");if(!s){console.warn("[Monitor] Could not extract room_id from aria-labelledby");return}console.log("[Monitor] Notification detected:",{roomId:s,ariaValue:r}),this._clickToConversation(s),await P(2e3);const i=this.service.extractAllMessages().at(-1);if(!i){console.log("[Queue] No last message found after sync");return}console.log("[Queue] Sending last message:",i),await this._sendLastMessage(i)}catch(n){console.error("[Monitor] Error detecting new message:",n)}})},e)}async _sendLastMessage(e){try{await M.sendSingleMessage(e),console.log("[API] Sent message successfully:",e)}catch(n){console.error("[API] Failed to send message:",n)}}filesMessages(){return this.service.extractAllMessages().filter(r=>Array.isArray(r.message)?r.message.some(s=>{try{return(typeof s=="string"?JSON.parse(s):s)?.type==="file"}catch{return!1}}):!1)}async clickToRefreshToken(e){const n=e.at(-1);document.getElementById(`attachments-${n?.date_time}`)?.querySelector('[aria-label="More attachment options"]')?.click(),await P(500)}startSyncConversations(){window._chatIntervals=window?._chatIntervals||{},window._chatIntervals.syncConversations?console.log("ℹ️ startSyncConversations already running"):(window._chatIntervals.syncConversations=window.setInterval(()=>{this.getConversations()},12e4),console.log("✅ startSyncConversations running"))}autoSyncConversationPrefixMessages(){if(window._chatIntervals=window._chatIntervals||{},window._chatIntervals.syncPrefixMessages){console.log("autoSyncConversationPrefixMessages already running");return}let e=!1;window._chatIntervals.syncPrefixMessages=window.setInterval(()=>{if(e){console.log("syncPrefixMessages skipped (still running)");return}e=!0,B.add(async()=>{try{const{data:n}=await rr.getConversationByPrefix();if(!n?.length)return;for(const r of n){this._clickToConversation(r.id),await P(5e3);const s=this.service.getCurrentRoomInfo();if(!s||s.room_id!==r.id){console.warn("room mismatch, skip:",r.id);continue}const o=this.filesMessages();o.length&&await this.clickToRefreshToken(o);const i=this.service.extractAllMessages();await M.createAndSendToZulip(i),await P(5e3)}}catch(n){console.error("autoSyncConversationPrefixMessages error:",n?.message),M.sendLog({type:"error",message:`auto_to_sync_conersations: ${n?.message}`})}finally{e=!1}})},6e4),console.log("autoSyncConversationPrefixMessages running safely")}}const dt=chrome.runtime.connect({name:"message"}),U=new sr(dt);dt.onMessage.addListener(t=>{if(console.log({msg:t}),t.type==="socket")switch(t.event){case D.GET_CONVERSATIONS:{U.getConversations(t);break}case D.GET_CONVERSATION:{U.getConversation(t);break}case D.SEND_MESSAGE:{U.sendMessage(t);break}case D.REPLY_MESSAGE:{U.replyMessage(t);break}}});U.startSyncConversations();U.autoSyncConversationPrefixMessages(); diff --git a/composer-bot-extensions/eslint.config.js b/composer-bot-extensions/eslint.config.js index d94e7de..3187548 100644 --- a/composer-bot-extensions/eslint.config.js +++ b/composer-bot-extensions/eslint.config.js @@ -1,23 +1,26 @@ -import js from '@eslint/js' -import globals from 'globals' -import reactHooks from 'eslint-plugin-react-hooks' -import reactRefresh from 'eslint-plugin-react-refresh' -import tseslint from 'typescript-eslint' -import { globalIgnores } from 'eslint/config' +import js from "@eslint/js"; +import globals from "globals"; +import reactHooks from "eslint-plugin-react-hooks"; +import reactRefresh from "eslint-plugin-react-refresh"; +import tseslint from "typescript-eslint"; +import { globalIgnores } from "eslint/config"; export default tseslint.config([ - globalIgnores(['dist']), + globalIgnores(["dist"]), { - files: ['**/*.{ts,tsx}'], + files: ["**/*.{ts,tsx}"], extends: [ js.configs.recommended, tseslint.configs.recommended, - reactHooks.configs['recommended-latest'], + reactHooks.configs["recommended-latest"], reactRefresh.configs.vite, ], languageOptions: { ecmaVersion: 2020, globals: globals.browser, }, + rules: { + "@typescript-eslint/no-unused-vars": ["off"], + }, }, -]) +]); diff --git a/composer-bot-extensions/src/background.ts b/composer-bot-extensions/src/background.ts index 4d9053f..61ebfa1 100644 --- a/composer-bot-extensions/src/background.ts +++ b/composer-bot-extensions/src/background.ts @@ -42,7 +42,7 @@ function initSocket() { // Socket.IO events socket.on("connect", () => { - console.log("✅ Socket.IO connected"); + console.log("✅ Socket.IO connectedd"); broadcastToPorts({ type: "socket", event: "connect", @@ -60,6 +60,7 @@ function initSocket() { eventsToListen.forEach((event) => { socket?.on(event, (data: any) => { + console.log({ event }); broadcastToPorts({ type: "socket", event, @@ -143,7 +144,7 @@ chrome.alarms.onAlarm.addListener((alarm) => { if (alarm.name === "reloadEvery4Hours") { console.log( "🔄 Reloading all tabs (every 4 hours)", - new Date().toLocaleString() + new Date().toLocaleString(), ); // Reload tất cả các tab đang mở diff --git a/composer-bot-extensions/src/content.ts b/composer-bot-extensions/src/content.ts index b45ee00..bb42c45 100644 --- a/composer-bot-extensions/src/content.ts +++ b/composer-bot-extensions/src/content.ts @@ -44,11 +44,3 @@ contentService.startSyncConversations(); // AUTO SYNC MESAGE PREFIX (INTERNAL) contentService.autoSyncConversationPrefixMessages(); - -// setTimeout(async () => { -// const a = new TeamsChatService(); - -// const conversations = await a.handleGetConversations(); - -// console.log({ conversations }); -// }, 10000); diff --git a/composer-bot-extensions/src/services/content.service.ts b/composer-bot-extensions/src/services/content.service.ts index b62cc4d..2709879 100644 --- a/composer-bot-extensions/src/services/content.service.ts +++ b/composer-bot-extensions/src/services/content.service.ts @@ -23,7 +23,7 @@ export class ContentService { document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, - null + null, ).singleNodeValue; } @@ -74,7 +74,7 @@ export class ContentService { } private async _waitForMessagesToAppear( - timeoutMs = 10000 + timeoutMs = 10000, ): Promise { return new Promise((resolve, reject) => { const chatPaneList = document.getElementById("chat-pane-list"); @@ -114,46 +114,46 @@ export class ContentService { }); } - private async _waitForNewMessages( - existingItems: HTMLElement[], - timeoutMs = 10000 - ): Promise { - return new Promise((resolve, reject) => { - const chatPaneList = document.getElementById("chat-pane-list"); + // private async _waitForNewMessages( + // existingItems: HTMLElement[], + // timeoutMs = 10000 + // ): Promise { + // return new Promise((resolve, reject) => { + // const chatPaneList = document.getElementById("chat-pane-list"); - if (!chatPaneList) { - return reject(new Error("#chat-pane-list not found")); - } + // if (!chatPaneList) { + // return reject(new Error("#chat-pane-list not found")); + // } - const getChildren = () => - Array.from(chatPaneList.children) as HTMLElement[]; + // const getChildren = () => + // Array.from(chatPaneList.children) as HTMLElement[]; - const existingSet = new Set(existingItems); + // const existingSet = new Set(existingItems); - let timeoutHandle: any = null; + // let timeoutHandle: any = null; - const observer = new MutationObserver(() => { - const currentChildren = getChildren(); - const newItems = currentChildren.filter((el) => !existingSet.has(el)); + // const observer = new MutationObserver(() => { + // const currentChildren = getChildren(); + // const newItems = currentChildren.filter((el) => !existingSet.has(el)); - if (newItems.length > 0) { - observer.disconnect(); - if (timeoutHandle) clearTimeout(timeoutHandle); - resolve(newItems); - } - }); + // if (newItems.length > 0) { + // observer.disconnect(); + // if (timeoutHandle) clearTimeout(timeoutHandle); + // resolve(newItems); + // } + // }); - observer.observe(chatPaneList, { - childList: true, - subtree: true, - }); + // observer.observe(chatPaneList, { + // childList: true, + // subtree: true, + // }); - timeoutHandle = setTimeout(() => { - observer.disconnect(); - reject(new Error("Timeout waiting for new messages")); - }, timeoutMs); - }); - } + // timeoutHandle = setTimeout(() => { + // observer.disconnect(); + // reject(new Error("Timeout waiting for new messages")); + // }, timeoutMs); + // }); + // } private async _waitToloadMessages(stableTime = 300): Promise { return new Promise((resolve) => { @@ -189,24 +189,24 @@ export class ContentService { }); } - private _getTypeGeo() { - const el = document.querySelector(".ck-placeholder"); + // private _getTypeGeo() { + // const el = document.querySelector(".ck-placeholder"); - if (el) { - const rect = el.getBoundingClientRect(); + // if (el) { + // const rect = el.getBoundingClientRect(); - return { - top: rect.top, - left: rect.left, - right: rect.right, - bottom: rect.bottom, - width: rect.width, - height: rect.height, - }; - } + // return { + // top: rect.top, + // left: rect.left, + // right: rect.right, + // bottom: rect.bottom, + // width: rect.width, + // height: rect.height, + // }; + // } - return null; - } + // return null; + // } private async _rightClickMessage(date_time: number) { const selector = this.service.elTags.container_chat; @@ -234,7 +234,7 @@ export class ContentService { scrollContainer.scrollTop = Math.max( 0, - scrollContainer.scrollTop - scrollStep + scrollContainer.scrollTop - scrollStep, ); await delay(200); // Đợi scroll và DOM render lại @@ -385,6 +385,8 @@ export class ContentService { initialMessages = await this._waitForMessagesToAppear(); // Đợi có item đầu tiên await this._waitToloadMessages(); + + console.log({ initialMessages }); } await this._clickIfExists(this.service.elTags.close_reply_btn); @@ -392,7 +394,7 @@ export class ContentService { await this._rightClickMessage(time); const replyBtn: any = document.querySelector( - this.service.elTags.reply_btn + this.service.elTags.reply_btn, ); if (replyBtn) { @@ -410,7 +412,7 @@ export class ContentService { fixedHeightChatInput(retry = 20, interval = 2000) { const tryFind = () => { const el = document.querySelector( - this.service.elTags.chat_input + this.service.elTags.chat_input, ) as HTMLElement; if (el) { @@ -419,7 +421,7 @@ export class ContentService { } else if (retry > 0) { setTimeout( () => this.fixedHeightChatInput(retry - 1, interval), - interval + interval, ); } else { console.warn("✘ Element not found with provided XPath after retries"); @@ -448,7 +450,7 @@ export class ContentService { // Lấy attribute aria-labelledby const ariaValue = document .querySelector( - '[aria-labelledby^="cn-normal-notification-main-content-"]' + '[aria-labelledby^="cn-normal-notification-main-content-"]', ) ?.getAttribute("aria-labelledby"); @@ -478,7 +480,7 @@ export class ContentService { if (!roomId) { console.warn( - "[Monitor] Could not extract room_id from aria-labelledby" + "[Monitor] Could not extract room_id from aria-labelledby", ); return; } @@ -563,7 +565,7 @@ export class ContentService { () => { this.getConversations(); }, - 120000 + 120000, ); console.log("✅ startSyncConversations running"); } else { @@ -572,13 +574,73 @@ export class ContentService { } // Interval chạy, chỉ add task vào queue - autoSyncConversationPrefixMessages() { - (window as any)._chatIntervals = (window as any)?._chatIntervals || {}; + // autoSyncConversationPrefixMessages() { + // (window as any)._chatIntervals = (window as any)?._chatIntervals || {}; + + // if (!(window as any)._chatIntervals.syncPrefixMessages) { + // (window as any)._chatIntervals.syncPrefixMessages = ( + // window as any + // ).setInterval(() => { + // (window as any)["is_sync_conversation_prefix"] = true; + + // queue.add(async () => { + // try { + // const { data } = + // (await conversationApi.getConversationByPrefix()) as { + // data: ChatItem[]; + // }; + // if (!data) return; + // for (const chat of data) { + // this._clickToConversation(chat.id as string); + // await delay(5000); + // const currentRoom = this.service.getCurrentRoomInfo(); + // if (!currentRoom || currentRoom.room_id !== chat.id) return; + // const filesMessages = this.filesMessages(); + // if (filesMessages.length) { + // await this.clickToRefreshToken(filesMessages); + // } + // const messages = this.service.extractAllMessages(); + // await messageApi.createAndSendToZulip(messages); + // await delay(5000); + // } + // } catch (err) { + // console.error( + // "❌ autoSyncConversationPrefixMessages error:", + // (err as any)?.message, + // ); + // messageApi.sendLog({ + // type: "error", + // message: `auto_to_sync_conersations: ${(err as any)?.message}`, + // }); + // } + // }); + // }, 60000); + + // console.log("✅ autoSyncConversationPrefixMessages running with PQueue"); + // } else { + // console.log("ℹ️ autoSyncConversationPrefixMessages already running"); + // } + // } + + autoSyncConversationPrefixMessages() { + (window as any)._chatIntervals = (window as any)._chatIntervals || {}; + + if ((window as any)._chatIntervals.syncPrefixMessages) { + console.log("autoSyncConversationPrefixMessages already running"); + return; + } + + let isRunning = false; + + (window as any)._chatIntervals.syncPrefixMessages = window.setInterval( + () => { + if (isRunning) { + console.log("syncPrefixMessages skipped (still running)"); + return; + } + + isRunning = true; - if (!(window as any)._chatIntervals.syncPrefixMessages) { - (window as any)._chatIntervals.syncPrefixMessages = ( - window as any - ).setInterval(() => { queue.add(async () => { try { const { data } = @@ -586,7 +648,7 @@ export class ContentService { data: ChatItem[]; }; - if (!data) return; + if (!data?.length) return; for (const chat of data) { this._clickToConversation(chat.id as string); @@ -594,37 +656,39 @@ export class ContentService { await delay(5000); const currentRoom = this.service.getCurrentRoomInfo(); - - if (!currentRoom || currentRoom.room_id !== chat.id) return; + if (!currentRoom || currentRoom.room_id !== chat.id) { + console.warn("room mismatch, skip:", chat.id); + continue; + } const filesMessages = this.filesMessages(); - if (filesMessages.length) { await this.clickToRefreshToken(filesMessages); } const messages = this.service.extractAllMessages(); - await messageApi.createAndSendToZulip(messages); await delay(5000); } } catch (err) { console.error( - "❌ autoSyncConversationPrefixMessages error:", - (err as any)?.message + "autoSyncConversationPrefixMessages error:", + (err as any)?.message, ); + messageApi.sendLog({ type: "error", message: `auto_to_sync_conersations: ${(err as any)?.message}`, }); + } finally { + isRunning = false; // 🔑 cực kỳ quan trọng } }); - }, 40000); + }, + 60000, + ); - console.log("✅ autoSyncConversationPrefixMessages running with PQueue"); - } else { - console.log("ℹ️ autoSyncConversationPrefixMessages already running"); - } + console.log("autoSyncConversationPrefixMessages running safely"); } } diff --git a/server/src/main.ts b/server/src/main.ts index 67e96c5..bf31a04 100644 --- a/server/src/main.ts +++ b/server/src/main.ts @@ -11,12 +11,13 @@ import * as fs from 'fs'; import { SocketIoAdapter } from './socket-adapter'; async function bootstrap() { - const httpsOptions = { - key: fs.readFileSync('ssl/localhost+1-key.pem'), - cert: fs.readFileSync('ssl/localhost+1.pem'), - }; + // const httpsOptions = { + // key: fs.readFileSync('ssl/localhost+1-key.pem'), + // cert: fs.readFileSync('ssl/localhost+1.pem'), + // }; - const app = await NestFactory.create(AppModule, { httpsOptions }); + const app = await NestFactory.create(AppModule); + // const app = await NestFactory.create(AppModule, { httpsOptions }); const prefix_version = process.env.PREFIX_VERSION; @@ -54,12 +55,14 @@ async function bootstrap() { useContainer(app.select(AppModule), { fallbackOnErrors: true }); + app.useWebSocketAdapter(new SocketIoAdapter(app)); + await app.listen(Number(process.env.APP_API_PORT)); - // ===== App cho WebSocket (WS hoặc WSS) ===== - const wsApp = await NestFactory.create(AppModule); - wsApp.useWebSocketAdapter(new SocketIoAdapter(wsApp)); - await wsApp.listen(Number(process.env.APP_SOCKET_PORT)); + // // ===== App cho WebSocket (WS hoặc WSS) ===== + // const wsApp = await NestFactory.create(AppModule); + // wsApp.useWebSocketAdapter(new SocketIoAdapter(wsApp)); + // await wsApp.listen(Number(process.env.APP_SOCKET_PORT)); } bootstrap(); diff --git a/server/src/modules/messages/messages.gateway.ts b/server/src/modules/messages/messages.gateway.ts index 7a1601a..fd3d7e5 100644 --- a/server/src/modules/messages/messages.gateway.ts +++ b/server/src/modules/messages/messages.gateway.ts @@ -30,6 +30,7 @@ export class MessagesGateway implements OnGatewayConnection { for (const event of eventsToForward) { this.event.on(event, (data) => { + console.log({ event, data }); this.server.emit(event, data); }); }