From 6befd5f2a74e3fcc3c44ea55bf1fb014b232a2a7 Mon Sep 17 00:00:00 2001 From: Admin Date: Tue, 9 Sep 2025 10:08:11 +0700 Subject: [PATCH] update detech new message and auto sync conversations --- .../composer-bot-extensions/background.js | 2 +- .../composer-bot-extensions/content.js | 2 +- composer-bot-extensions/src/background.ts | 45 +++++++++++++++++++ .../src/services/content.service.ts | 4 +- .../src/modules/messages/messages.service.ts | 39 +++++++++++++--- 5 files changed, 82 insertions(+), 10 deletions(-) diff --git a/composer-bot-extensions/composer-bot-extensions/background.js b/composer-bot-extensions/composer-bot-extensions/background.js index e5c87f3..a46d8d1 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 g=new ArrayBuffer(e),f=new Uint8Array(g);for(s=0;s>4,f[i++]=(o&15)<<4|c>>2,f[i++]=(c&3)<<6|h&63;return g},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:ge(n.substring(1),e)}:S[t]?n.length>1?{type:S[t],data:n.substring(1)}:{type:S[t]}:I},ge=(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="",me=(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)+g.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,me(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",m=>{if(!s)if(m.type==="pong"&&m.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=m=>{const w=new Error("probe error: "+m);w.transport=t.name,r(),this.emitReserved("upgradeError",w)};function c(){o("transport closed")}function h(){o("socket closed")}function g(m){t&&m.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",g)};t.once("open",i),t.once("error",o),t.once("close",c),this.once("close",h),this.once("upgrading",g),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("wss://notable-recently-seagull.ngrok-free.app",{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)}})}ot(); +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 Me={websocket:Ue,webtransport:Ve,polling:De},Fe=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(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=Fe.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;sMe[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("wss://notable-recently-seagull.ngrok-free.app",{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="dailyReload";chrome.alarms.clear(n,()=>{const e=new Date,t=new Date;t.setHours(2,0,0,0),t.getTime()<=e.getTime()&&t.setDate(t.getDate()+1);const s=(t.getTime()-e.getTime())/1e3/60;chrome.alarms.create(n,{delayInMinutes:s,periodInMinutes:24*60}),console.log(`⏰ Daily reload alarm set for ${t}`)}),chrome.alarms.onAlarm.addListener(e=>{e.name==="dailyReload"&&(console.log("🔄 Reloading page (2 AM alarm)"),chrome.tabs.query({},t=>{t.forEach(s=>{s.id&&chrome.tabs.reload(s.id)})}))})}ot();at(); diff --git a/composer-bot-extensions/composer-bot-extensions/content.js b/composer-bot-extensions/composer-bot-extensions/content.js index 9542c1d..58b8dfa 100644 --- a/composer-bot-extensions/composer-bot-extensions/content.js +++ b/composer-bot-extensions/composer-bot-extensions/content.js @@ -3,4 +3,4 @@ const D={GET_CONVERSATIONS:"messages.get-conversations",GET_CONVERSATION:"messag `)}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[Ae]=this[Ae]={accessors:{}}).accessors,s=this.prototype;function o(i){const a=H(i);r[a]||(On(s,i),r[a]=!0)}return l.isArray(e)?e.forEach(o):o(e),this}};C.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);l.reduceDescriptors(C.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(r){this[n]=r}}});l.freezeMethods(C);function ce(t,e){const n=this||K,r=e||n,s=C.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 et(t){return!!(t&&t.__CANCEL__)}function U(t,e,n){w.call(this,t??"canceled",w.ERR_CANCELED,e,n),this.name="CanceledError"}l.inherits(U,w,{__CANCEL__:!0});function tt(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 xn(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function Nn(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 Y=(t,e,n=3)=>{let r=0;const s=Nn(50,250);return Pn(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)},Oe=(t,e)=>{const n=t!=null;return[r=>e[0]({lengthComputable:n,total:t,loaded:r}),e[1]]},xe=t=>(...e)=>l.asap(()=>t(...e)),In=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,Mn=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 kn(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Ln(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function nt(t,e,n){let r=!kn(e);return t&&(r||n==!1)?Ln(t,e):e}const Ne=t=>t instanceof C?{...t}:t;function L(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(Ne(c),Ne(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 rt=t=>{const e=L({},t);let{data:n,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:o,headers:i,auth:a}=e;e.headers=i=C.from(i),e.url=Qe(nt(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(v.hasStandardBrowserEnv||v.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(v.hasStandardBrowserEnv&&(r&&l.isFunction(r)&&(r=r(e)),r||r!==!1&&In(e.url))){const c=s&&o&&Mn.read(o);c&&i.set(s,c)}return e},Fn=typeof XMLHttpRequest<"u",Bn=Fn&&function(t){return new Promise(function(n,r){const s=rt(t);let o=s.data;const i=C.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 b(){if(!h)return;const E=C.from("getAllResponseHeaders"in h&&h.getAllResponseHeaders()),R={data:!a||a==="text"||a==="json"?h.responseText:h.response,status:h.status,statusText:h.statusText,headers:E,config:t,request:h};tt(function(P){n(P),y()},function(P){r(P),y()},R),h=null}"onloadend"in h?h.onloadend=b:h.onreadystatechange=function(){!h||h.readyState!==4||h.status===0&&!(h.responseURL&&h.responseURL.indexOf("file:")===0)||setTimeout(b)},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 A=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const R=s.transitional||Ye;s.timeoutErrorMessage&&(A=s.timeoutErrorMessage),r(new w(A,R.clarifyTimeoutError?w.ETIMEDOUT:w.ECONNABORTED,t,h)),h=null},o===void 0&&i.setContentType(null),"setRequestHeader"in h&&l.forEach(i.toJSON(),function(A,R){h.setRequestHeader(R,A)}),l.isUndefined(s.withCredentials)||(h.withCredentials=!!s.withCredentials),a&&a!=="json"&&(h.responseType=s.responseType),c&&([m,p]=Y(c,!0),h.addEventListener("progress",m)),f&&h.upload&&([d,g]=Y(f),h.upload.addEventListener("progress",d),h.upload.addEventListener("loadend",g)),(s.cancelToken||s.signal)&&(u=E=>{h&&(r(!E||E.type?new U(null,t,h):E),h.abort(),h=null)},s.cancelToken&&s.cancelToken.subscribe(u),s.signal&&(s.signal.aborted?u():s.signal.addEventListener("abort",u)));const S=xn(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)})},Dn=(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 U(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}},qn=function*(t,e){let n=t.byteLength;if(n{const s=Un(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})},se=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",st=se&&typeof ReadableStream=="function",jn=se&&(typeof TextEncoder=="function"?(t=>e=>t.encode(e))(new TextEncoder):async t=>new Uint8Array(await new Response(t).arrayBuffer())),ot=(t,...e)=>{try{return!!t(...e)}catch{return!1}},Vn=st&&ot(()=>{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}),Ie=64*1024,he=st&&ot(()=>l.isReadableStream(new Response("").body)),Z={stream:he&&(t=>t.body)};se&&(t=>{["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!Z[e]&&(Z[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 $n=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 jn(t)).byteLength},zn=async(t,e)=>{const n=l.toFiniteNumber(t.getContentLength());return n??$n(e)},Jn=se&&(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}=rt(t);c=c?(c+"").toLowerCase():"text";let g=Dn([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 zn(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[P,W]=Oe(h,Y(xe(f)));r=Pe(R.body,Ie,P,W)}}l.isString(d)||(d=d?"include":"omit");const b="credentials"in Request.prototype;p=new Request(e,{...m,signal:g,method:n.toUpperCase(),headers:u.normalize().toJSON(),body:r,duplex:"half",credentials:b?d:void 0});let S=await fetch(p,m);const E=he&&(c==="stream"||c==="response");if(he&&(a||E&&y)){const R={};["status","statusText","headers"].forEach(Ee=>{R[Ee]=S[Ee]});const N=l.toFiniteNumber(S.headers.get("content-length")),[P,W]=a&&Oe(N,Y(xe(a),!0))||[];S=new Response(Pe(S.body,Ie,P,()=>{W&&W(),y&&y()}),R)}c=c||"text";let A=await Z[l.findKey(Z,c)||"text"](S,t);return!E&&y&&y(),await new Promise((R,N)=>{tt(R,N,{data:A,headers:C.from(S.headers),status:S.status,statusText:S.statusText,config:t,request:p})})}catch(b){throw y&&y(),b&&b.name==="TypeError"&&/Load failed|fetch/i.test(b.message)?Object.assign(new w("Network Error",w.ERR_NETWORK,t,p),{cause:b.cause||b}):w.from(b,b&&b.code,t,p)}}),pe={http:an,xhr:Bn,fetch:Jn};l.forEach(pe,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const Me=t=>`- ${t}`,Kn=t=>l.isFunction(t)||t===null||t===!1,it={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(Me).join(` `):" "+Me(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:pe};function le(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new U(null,t)}function ke(t){return le(t),t.headers=C.from(t.headers),t.data=ce.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),it.getAdapter(t.adapter||K.adapter)(t).then(function(r){return le(t),r.data=ce.call(t,t.transformResponse,r),r.headers=C.from(r.headers),r},function(r){return et(r)||(le(t),r&&r.response&&(r.response.data=ce.call(t,t.transformResponse,r.response),r.response.headers=C.from(r.response.headers))),Promise.reject(r)})}const at="1.11.0",oe={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{oe[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});const Le={};oe.transitional=function(e,n,r){function s(o,i){return"[Axios v"+at+"] 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&&!Le[i]&&(Le[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}};oe.spelling=function(e){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};function Wn(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 Q={assertOptions:Wn,validators:oe},x=Q.validators;let k=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Ce,response:new Ce}}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=L(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&Q.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}:Q.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),Q.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=C.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=[ke.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 U(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 ct(function(s){e=s}),cancel:e}}};function Xn(t){return function(n){return t.apply(null,n)}}function Qn(t){return l.isObject(t)&&t.isAxiosError===!0}const me={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(me).forEach(([t,e])=>{me[e]=t});function lt(t){const e=new k(t),n=qe(k.prototype.request,e);return l.extend(n,k.prototype,e,{allOwnKeys:!0}),l.extend(n,e,null,{allOwnKeys:!0}),n.create=function(s){return lt(L(t,s))},n}const T=lt(K);T.Axios=k;T.CanceledError=U;T.CancelToken=Gn;T.isCancel=et;T.VERSION=at;T.toFormData=re;T.AxiosError=w;T.Cancel=T.CanceledError;T.all=function(e){return Promise.all(e)};T.spread=Xn;T.isAxiosError=Qn;T.mergeConfig=L;T.AxiosHeaders=C;T.formToJSON=t=>Ze(l.isHTMLForm(t)?new FormData(t):t);T.getAdapter=it.getAdapter;T.HttpStatusCode=me;T.default=T;const{Axios:or,AxiosError:ir,CanceledError:ar,isCancel:cr,CancelToken:lr,VERSION:ur,all:fr,Cancel:dr,isAxiosError:hr,spread:pr,toFormData:mr,AxiosHeaders:yr,HttpStatusCode:gr,formToJSON:wr,getAdapter:Er,mergeConfig:br}=T;class Yn{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 Fe=new Yn;function B(t){return new Promise(e=>setTimeout(e,t))}const j=T.create({baseURL:"https://notable-recently-seagull.ngrok-free.app/api/v1/",headers:{"Content-Type":"application/json"}});class Zn{async sendSingleMessage(e){try{const{data:n}=await j.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 j.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{data:n}=await j.post("/messages/create-and-send",{data:e});return console.log("[NestJS] Response (create and send):",n),n}catch(n){throw console.error("[NestJS] Error (create and send):",n),n}}}const Be=new Zn;class er{async index(e){try{const{data:n}=await j({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 j({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 tr=new er;class nr{service;port;constructor(e){this.service=new bt,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 _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),a=new Set(e);let f=null;const c=new MutationObserver(()=>{const d=i().filter(m=>!a.has(m));d.length>0&&(c.disconnect(),f&&clearTimeout(f),r(d))});c.observe(o,{childList:!0,subtree:!0}),f=setTimeout(()=>{c.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,a=document.querySelector(n);if(!a){console.error("Wrapper not found:",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){F.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){F.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}}){F.add(async()=>{console.log("[Queue] Handling SEND_MESSAGE");const{room_id:r}=this.service.getCurrentRoomInfo();r!=e&&this._clickToConversation(e),await B(200),await Fe.send(n)})}async replyMessage({data:{conversation_id:e,message:n,time:r}}){F.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 B(200),console.log({message:n}),await Fe.send(n)})}fixedHeightChatInput(e=20,n=1e3){(()=>{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")})()}async detectNewMessage(e=2e3){console.log("[Monitor] Starting..."),this.service.initialHistories=this.service.extractAllMessages(),this.service.lastMessage=this.service.initialHistories.pop(),setInterval(()=>{F.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 B(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 Be.sendSingleMessage(e),console.log("[API] Sent message successfully:",e)}catch(n){console.error("[API] Failed to send message:",n)}}startSyncConversations(){window._chatIntervals=window?._chatIntervals||{},window._chatIntervals.syncConversations?console.log("ℹ️ startSyncConversations already running"):(window._chatIntervals.syncConversations=window.setInterval(()=>{this.getConversations()},2e4),console.log("✅ startSyncConversations running"))}autoSyncConversationPrefixMessages(){window._chatIntervals=window?._chatIntervals||{},window._chatIntervals.syncPrefixMessages?console.log("ℹ️ autoSyncConversationPrefixMessages already running"):(window._chatIntervals.syncPrefixMessages=window.setInterval(()=>{F.add(async()=>{try{const{data:e}=await tr.getConversationByPrefix();if(!e)return;for(const n of e){this._clickToConversation(n.id),await B(1e3);const r=this.service.getCurrentRoomInfo();if(!r||r.room_id!==n.id)return;const s=this.service.extractAllMessages();await Be.createAndSendToZulip(s)}}catch(e){console.error("❌ autoSyncConversationPrefixMessages error:",e)}})},1e4),console.log("✅ autoSyncConversationPrefixMessages running with PQueue"))}}const ut=chrome.runtime.connect({name:"message"}),I=new nr(ut);ut.onMessage.addListener(t=>{if(console.log({msg:t}),I.fixedHeightChatInput(),t.type==="socket")switch(t.event){case D.GET_CONVERSATIONS:{I.getConversations(t);break}case D.GET_CONVERSATION:{I.getConversation(t);break}case D.SEND_MESSAGE:{I.sendMessage(t);break}case D.REPLY_MESSAGE:{I.replyMessage(t);break}}});I.startSyncConversations();I.autoSyncConversationPrefixMessages(); +`+o):r.stack=o}catch{}}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=L(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&Q.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}:Q.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),Q.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=C.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=[ke.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 U(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 ct(function(s){e=s}),cancel:e}}};function Xn(t){return function(n){return t.apply(null,n)}}function Qn(t){return l.isObject(t)&&t.isAxiosError===!0}const me={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(me).forEach(([t,e])=>{me[e]=t});function lt(t){const e=new k(t),n=qe(k.prototype.request,e);return l.extend(n,k.prototype,e,{allOwnKeys:!0}),l.extend(n,e,null,{allOwnKeys:!0}),n.create=function(s){return lt(L(t,s))},n}const T=lt(K);T.Axios=k;T.CanceledError=U;T.CancelToken=Gn;T.isCancel=et;T.VERSION=at;T.toFormData=re;T.AxiosError=w;T.Cancel=T.CanceledError;T.all=function(e){return Promise.all(e)};T.spread=Xn;T.isAxiosError=Qn;T.mergeConfig=L;T.AxiosHeaders=C;T.formToJSON=t=>Ze(l.isHTMLForm(t)?new FormData(t):t);T.getAdapter=it.getAdapter;T.HttpStatusCode=me;T.default=T;const{Axios:or,AxiosError:ir,CanceledError:ar,isCancel:cr,CancelToken:lr,VERSION:ur,all:fr,Cancel:dr,isAxiosError:hr,spread:pr,toFormData:mr,AxiosHeaders:yr,HttpStatusCode:gr,formToJSON:wr,getAdapter:Er,mergeConfig:br}=T;class Yn{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 Fe=new Yn;function B(t){return new Promise(e=>setTimeout(e,t))}const j=T.create({baseURL:"https://notable-recently-seagull.ngrok-free.app/api/v1/",headers:{"Content-Type":"application/json"}});class Zn{async sendSingleMessage(e){try{const{data:n}=await j.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 j.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{data:n}=await j.post("/messages/create-and-send",{data:e});return console.log("[NestJS] Response (create and send):",n),n}catch(n){throw console.error("[NestJS] Error (create and send):",n),n}}}const Be=new Zn;class er{async index(e){try{const{data:n}=await j({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 j({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 tr=new er;class nr{service;port;constructor(e){this.service=new bt,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 _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),a=new Set(e);let f=null;const c=new MutationObserver(()=>{const d=i().filter(m=>!a.has(m));d.length>0&&(c.disconnect(),f&&clearTimeout(f),r(d))});c.observe(o,{childList:!0,subtree:!0}),f=setTimeout(()=>{c.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,a=document.querySelector(n);if(!a){console.error("Wrapper not found:",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){F.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){F.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}}){F.add(async()=>{console.log("[Queue] Handling SEND_MESSAGE");const{room_id:r}=this.service.getCurrentRoomInfo();r!=e&&this._clickToConversation(e),await B(200),await Fe.send(n)})}async replyMessage({data:{conversation_id:e,message:n,time:r}}){F.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 B(200),console.log({message:n}),await Fe.send(n)})}fixedHeightChatInput(e=20,n=1e3){(()=>{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")})()}async detectNewMessage(e=2e3){console.log("[Monitor] Starting..."),this.service.initialHistories=this.service.extractAllMessages(),this.service.lastMessage=this.service.initialHistories.pop(),setInterval(()=>{F.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 B(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 Be.sendSingleMessage(e),console.log("[API] Sent message successfully:",e)}catch(n){console.error("[API] Failed to send message:",n)}}startSyncConversations(){window._chatIntervals=window?._chatIntervals||{},window._chatIntervals.syncConversations?console.log("ℹ️ startSyncConversations already running"):(window._chatIntervals.syncConversations=window.setInterval(()=>{this.getConversations()},6e4),console.log("✅ startSyncConversations running"))}autoSyncConversationPrefixMessages(){window._chatIntervals=window?._chatIntervals||{},window._chatIntervals.syncPrefixMessages?console.log("ℹ️ autoSyncConversationPrefixMessages already running"):(window._chatIntervals.syncPrefixMessages=window.setInterval(()=>{F.add(async()=>{try{const{data:e}=await tr.getConversationByPrefix();if(!e)return;for(const n of e){this._clickToConversation(n.id),await B(1e3);const r=this.service.getCurrentRoomInfo();if(!r||r.room_id!==n.id)return;const s=this.service.extractAllMessages();await Be.createAndSendToZulip(s)}}catch(e){console.error("❌ autoSyncConversationPrefixMessages error:",e)}})},2e4),console.log("✅ autoSyncConversationPrefixMessages running with PQueue"))}}const ut=chrome.runtime.connect({name:"message"}),I=new nr(ut);ut.onMessage.addListener(t=>{if(console.log({msg:t}),I.fixedHeightChatInput(),t.type==="socket")switch(t.event){case D.GET_CONVERSATIONS:{I.getConversations(t);break}case D.GET_CONVERSATION:{I.getConversation(t);break}case D.SEND_MESSAGE:{I.sendMessage(t);break}case D.REPLY_MESSAGE:{I.replyMessage(t);break}}});I.startSyncConversations();I.autoSyncConversationPrefixMessages(); diff --git a/composer-bot-extensions/src/background.ts b/composer-bot-extensions/src/background.ts index 262933c..1320811 100644 --- a/composer-bot-extensions/src/background.ts +++ b/composer-bot-extensions/src/background.ts @@ -80,4 +80,49 @@ function broadcastToPorts(message: any) { }); } +function initDailyReloadAlarm() { + // Tên alarm + const alarmName = "dailyReload"; + + // Xóa alarm cũ nếu có + chrome.alarms.clear(alarmName, () => { + // Lấy thời gian hiện tại + const now = new Date(); + + // Thiết lập 2 giờ sáng ngày hôm nay hoặc ngày mai nếu đã quá giờ + const firstTrigger = new Date(); + firstTrigger.setHours(2, 0, 0, 0); // 2:00:00 + + if (firstTrigger.getTime() <= now.getTime()) { + // Nếu đã qua 2h sáng hôm nay, đặt vào ngày mai + firstTrigger.setDate(firstTrigger.getDate() + 1); + } + + const delayInMinutes = (firstTrigger.getTime() - now.getTime()) / 1000 / 60; + + // Tạo alarm + chrome.alarms.create(alarmName, { + delayInMinutes, + periodInMinutes: 24 * 60, // lặp lại mỗi 24h + }); + + console.log(`⏰ Daily reload alarm set for ${firstTrigger}`); + }); + + // Lắng nghe alarm + chrome.alarms.onAlarm.addListener((alarm) => { + if (alarm.name === "dailyReload") { + console.log("🔄 Reloading page (2 AM alarm)"); + // Reload tất cả tab đang mở (hoặc tab cụ thể nếu muốn) + chrome.tabs.query({}, (tabs) => { + tabs.forEach((tab) => { + if (tab.id) chrome.tabs.reload(tab.id); + }); + }); + } + }); +} + initSocket(); + +initDailyReloadAlarm(); diff --git a/composer-bot-extensions/src/services/content.service.ts b/composer-bot-extensions/src/services/content.service.ts index 91e242c..57cabf4 100644 --- a/composer-bot-extensions/src/services/content.service.ts +++ b/composer-bot-extensions/src/services/content.service.ts @@ -542,7 +542,7 @@ export class ContentService { () => { this.getConversations(); }, - 20000 + 60000 ); console.log("✅ startSyncConversations running"); } else { @@ -583,7 +583,7 @@ export class ContentService { console.error("❌ autoSyncConversationPrefixMessages error:", err); } }); - }, 10000); + }, 20000); console.log("✅ autoSyncConversationPrefixMessages running with PQueue"); } else { diff --git a/server/src/modules/messages/messages.service.ts b/server/src/modules/messages/messages.service.ts index a15fcc6..0556932 100644 --- a/server/src/modules/messages/messages.service.ts +++ b/server/src/modules/messages/messages.service.ts @@ -48,7 +48,9 @@ export class MessagesService { return AppResponse.toPagination(result, true, Message); } - async create(dto: CreateMessageDto): Promise { + async create( + dto: CreateMessageDto, + ): Promise<{ data: Message; exit: boolean }> { const time = new Date(dto.time); const existing = await this.repo.findOne({ @@ -56,7 +58,7 @@ export class MessagesService { }); if (existing) { - return existing; + return { data: existing, exit: true }; } const conversation = await this.conversationRepo.findOne({ @@ -87,14 +89,19 @@ export class MessagesService { if (!conversation) return; + const content = `** :rocket: ${result.name} sent:** +\`\`\` +${result.message} +\`\`\``; + await this.zulupService.sendMessageToTopic( process.env.ZULIP_STREAMS_NAME, conversation.name, - result.message, + content, ); } - return result; + return { data: result, exit: false }; } async bulkCreate(dtos: CreateMessageDto[]): Promise { @@ -198,15 +205,35 @@ export class MessagesService { async createAndSendToZulip({ data }: CreateBulkMessageDto) { const results = []; + let iterationCount = 0; // Đếm số lần lặp + + // Đảo ngược array trước khi xử lý + const reversedData = [...data].reverse(); + + for (const mes of reversedData) { + iterationCount++; // Tăng biến đếm mỗi lần lặp - for (const mes of data) { const result = await this.create(mes); if (result) { results.push(result); + + // Nếu result có exit = true thì dừng vòng lặp + if (result.exit === true) { + console.log( + `⛔ Stopped because exit = true after ${iterationCount} iterations`, + result, + ); + break; + } } } - return results; + console.log(`🔁 Total iterations: ${iterationCount}`); + + return { + results, + iterationCount, // Trả về kèm số lần lặp + }; } }