diff --git a/composer-bot-extensions/composer-bot-extensions/content.js b/composer-bot-extensions/composer-bot-extensions/content.js index 2d5f0a1..a49b048 100644 --- a/composer-bot-extensions/composer-bot-extensions/content.js +++ b/composer-bot-extensions/composer-bot-extensions/content.js @@ -1,6 +1,6 @@ -const D={GET_CONVERSATIONS:"messages.get-conversations",GET_CONVERSATION:"messages.get-conversation",RECEIVE_CONVERSATIONS:"messages.receive-conversations",RECEIVE_CONVERSATION:"messages.receive-conversation",SEND_MESSAGE:"messages.send-messsage",REPLY_MESSAGE:"messages.reply-messsage"};function ft(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ie={exports:{}},be;function dt(){return be||(be=1,function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function s(f,c,u){this.fn=f,this.context=c,this.once=u||!1}function o(f,c,u,d,m){if(typeof u!="function")throw new TypeError("The listener must be a function");var g=new s(u,d||f,m),p=n?n+c:c;return f._events[p]?f._events[p].fn?f._events[p]=[f._events[p],g]:f._events[p].push(g):(f._events[p]=g,f._eventsCount++),f}function i(f,c){--f._eventsCount===0?f._events=new r:delete f._events[c]}function a(){this._events=new r,this._eventsCount=0}a.prototype.eventNames=function(){var c=[],u,d;if(this._eventsCount===0)return c;for(d in u=this._events)e.call(u,d)&&c.push(n?d.slice(1):d);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},a.prototype.listeners=function(c){var u=n?n+c:c,d=this._events[u];if(!d)return[];if(d.fn)return[d.fn];for(var m=0,g=d.length,p=new Array(g);mglobalThis.DOMException===void 0?new mt(t):new DOMException(t),Te=t=>{const e=t.reason===void 0?Se("This operation was aborted."):t.reason;return e instanceof Error?e:Se(e)};function yt(t,e){const{milliseconds:n,fallback:r,message:s,customTimers:o={setTimeout,clearTimeout}}=e;let i,a;const c=new Promise((u,d)=>{if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(e.signal){const{signal:g}=e;g.aborted&&d(Te(g)),a=()=>{d(Te(g))},g.addEventListener("abort",a,{once:!0})}if(n===Number.POSITIVE_INFINITY){t.then(u,d);return}const m=new De;i=o.setTimeout.call(void 0,()=>{if(r){try{u(r())}catch(g){d(g)}return}typeof t.cancel=="function"&&t.cancel(),s===!1?u():s instanceof Error?d(s):(m.message=s??`Promise timed out after ${n} milliseconds`,d(m))},n),(async()=>{try{u(await t)}catch(g){d(g)}})()}).finally(()=>{c.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return c.clear=()=>{o.clearTimeout.call(void 0,i),i=void 0},c}function gt(t,e,n){let r=0,s=t.length;for(;s>0;){const o=Math.trunc(s/2);let i=r+o;n(t[i],e)<=0?(r=++i,s-=o+1):s=o}return r}class wt{#e=[];enqueue(e,n){n={priority:0,...n};const r={priority:n.priority,id:n.id,run:e};if(this.size===0||this.#e[this.size-1].priority>=n.priority){this.#e.push(r);return}const s=gt(this.#e,r,(o,i)=>i.priority-o.priority);this.#e.splice(s,0,r)}setPriority(e,n){const r=this.#e.findIndex(o=>o.id===e);if(r===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);const[s]=this.#e.splice(r,1);this.enqueue(s.run,{priority:n,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(n=>n.priority===e.priority).map(n=>n.run)}get size(){return this.#e.length}}class Et extends pt{#e;#i;#o=0;#h;#a;#p=0;#n;#c;#t;#m;#r=0;#l;#s;#y;#E=1n;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:wt,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#i=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#h=e.intervalCap,this.#a=e.interval,this.#t=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#y=e.throwOnTimeout===!0,this.#s=e.autoStart===!1}get#b(){return this.#i||this.#o{this.#R()},n)),!0}return!1}#u(){if(this.#t.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#r===0&&this.emit("idle"),!1;if(!this.#s){const e=!this.#v;if(this.#b&&this.#S){const n=this.#t.dequeue();return n?(this.emit("active"),n(),e&&this.#g(),!0):!1}}return!1}#g(){this.#i||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#a),this.#p=Date.now()+this.#a)}#w(){this.#o===0&&this.#r===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#o=this.#e?this.#r:0,this.#f()}#f(){for(;this.#u(););}get concurrency(){return this.#l}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#l=e,this.#f()}async#_(e){return new Promise((n,r)=>{e.addEventListener("abort",()=>{r(e.reason)},{once:!0})})}setPriority(e,n){this.#t.setPriority(e,n)}async add(e,n={}){return n.id??=(this.#E++).toString(),n={timeout:this.timeout,throwOnTimeout:this.#y,...n},new Promise((r,s)=>{this.#t.enqueue(async()=>{this.#r++,this.#o++;try{n.signal?.throwIfAborted();let o=e({signal:n.signal});n.timeout&&(o=yt(Promise.resolve(o),{milliseconds:n.timeout})),n.signal&&(o=Promise.race([o,this.#_(n.signal)]));const i=await o;r(i),this.emit("completed",i)}catch(o){if(o instanceof De&&!n.throwOnTimeout){r();return}s(o),this.emit("error",o)}finally{this.#T()}},n),this.emit("add"),this.#u()})}async addAll(e,n){return Promise.all(e.map(async r=>this.add(r,n)))}start(){return this.#s?(this.#s=!1,this.#f(),this):this}pause(){this.#s=!0}clear(){this.#t=new this.#m}async onEmpty(){this.#t.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#t.sizethis.#t.size{const s=()=>{n&&!n()||(this.off(e,s),r())};this.on(e,s)})}get size(){return this.#t.size}sizeBy(e){return this.#t.filter(e).length}get pending(){return this.#r}get isPaused(){return this.#s}}const B=new Et({concurrency:1});class bt{MY_NAME="Apactech com";lastMessage;initialHistories=[];elTags={container_scroll:"/html/body/div[1]/div/div/div/div[5]/div[1]/div[1]/div[2]/div[1]/div[1]/div",conatainer_conversations:"/html/body/div[1]/div/div/div/div[5]/div[1]/div[1]/div[2]/div[1]/div[1]/div/div[1]",container_chat:'[data-testid="message-wrapper"]',root_id:'[aria-selected="true"] [id^="chat-list-item"]',room_name:'[data-tid="chat-title"]',close_reply_btn:'[data-track-action-scenario="messageQuotedReplyDismissed"]',reply_btn:'[aria-label="Reply"]',chat_input:'[placeholder="Type a message"]'};getCurrentRoomInfo(){const e=document.querySelector(this.elTags.root_id)?.id?.replace("chat-list-item_",""),n=document.querySelector(this.elTags.room_name)?.innerText;return{room_id:e,room_name:n}}_getMessageByEl(e){if(!e)return"";let n=e.innerText||"";const r=e.querySelector("img[data-gallery-src]");if(r)return r.getAttribute("data-gallery-src")||"";const o=Array.from(e.querySelectorAll("img[itemtype]")).map(i=>i.getAttribute("alt")||"").filter(Boolean);return o.length&&(n+=o.join("")),n.trim()}parseMessageElement(e,n=!1){const r=e.querySelector(n?".fui-ChatMyMessage__timestamp":".fui-ChatMessage__timestamp"),s=e.querySelector(n?".fui-ChatMyMessage__author":".fui-ChatMessage__author");if(!r)return null;const o=r.getAttribute("datetime");if(!o)return null;const i=Number.isNaN(r.id.replace("timestamp-",""))?new Date(o).getTime():Number(r.id.replace("timestamp-","")),a=document.querySelector(`#content-${i}`),{room_id:f,room_name:c}=this.getCurrentRoomInfo();return{name:s?.innerText,message:this._getMessageByEl(a),time:i,room_id:f,room_name:c,date_time:new Date(o).getTime()}}extractAllMessages(){const e=Array.from(document.querySelectorAll(".fui-ChatMyMessage")).map(r=>this.parseMessageElement(r,!0)).filter(r=>r!==null),n=Array.from(document.querySelectorAll(".fui-ChatMessage")).map(r=>this.parseMessageElement(r,!1)).filter(r=>r!==null);return console.log({myMessages:e,otherMessages:n}),[...e,...n].sort((r,s)=>r.time-s.time)}handleNewMessage(e){console.log("%c[New incoming message]","color: #007acc;",e)}async detectNewMessages(){const e=this.extractAllMessages(),n=e.findIndex(o=>o.time===this.lastMessage?.time),r=e.slice(n+1);if(r.length===0){console.log("[Monitor] No new messages...");return}const s=r[0];return this.lastMessage=e.pop(),s}async start(e=1e4){console.log("[Monitor] Starting..."),this.initialHistories=this.extractAllMessages(),this.lastMessage=this.initialHistories.pop(),setInterval(async()=>await this.detectNewMessages(),e)}async _getConversationsInfo(e=this.elTags.conatainer_conversations){const n=document.evaluate(e,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;return n?Array.from(n.children).filter(o=>o.getAttribute("role")==="none").map(o=>{const i=o.id||null,a=`title-chat-list-item_${i}`,c=document.getElementById(a)?.innerText||null;let u=null;return i?.includes("@thread.skype")?u="group":i?.includes("@oneToOne.skype")?u="personal":u="group",{id:i,name:c,type:u}}):(console.log("Không tìm thấy phần tử theo XPath."),[])}async _scrollToBottomByXPath(e=this.elTags.container_scroll,n){const{maxStableRounds:r=5,delay:s=300,maxScrolls:o=100}=n||{},i=document.evaluate(e,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;if(!i){console.warn("❌ Không tìm thấy phần tử với XPath:",e);return}return new Promise(a=>{let f=-1,c=0,u=0;const d=setInterval(()=>{const m=i.scrollHeight;i.scrollTop=m,m===f?c++:(c=0,f=m),u++,(c>=r||u>=o)&&(clearInterval(d),a())},s)})}async handleGetConversations(){return await this._scrollToBottomByXPath(),this._getConversationsInfo()}}function qe(t,e){return function(){return t.apply(e,arguments)}}const{toString:St}=Object.prototype,{getPrototypeOf:ye}=Object,{iterator:ee,toStringTag:Ue}=Symbol,te=(t=>e=>{const n=St.call(e);return t[n]||(t[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),O=t=>(t=t.toLowerCase(),e=>te(e)===t),ne=t=>e=>typeof e===t,{isArray:q}=Array,V=ne("undefined");function $(t){return t!==null&&!V(t)&&t.constructor!==null&&!V(t.constructor)&&_(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const He=O("ArrayBuffer");function Tt(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&He(t.buffer),e}const Rt=ne("string"),_=ne("function"),je=ne("number"),z=t=>t!==null&&typeof t=="object",vt=t=>t===!0||t===!1,G=t=>{if(te(t)!=="object")return!1;const e=ye(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Ue in t)&&!(ee in t)},_t=t=>{if(!z(t)||$(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},Ct=O("Date"),At=O("File"),Ot=O("Blob"),xt=O("FileList"),Nt=t=>z(t)&&_(t.pipe),Pt=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||_(t.append)&&((e=te(t))==="formdata"||e==="object"&&_(t.toString)&&t.toString()==="[object FormData]"))},It=O("URLSearchParams"),[Mt,kt,Lt,Ft]=["ReadableStream","Request","Response","Headers"].map(O),Bt=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function J(t,e,{allOwnKeys:n=!1}={}){if(t===null||typeof t>"u")return;let r,s;if(typeof t!="object"&&(t=[t]),q(t))for(r=0,s=t.length;r0;)if(s=n[r],e===s.toLowerCase())return s;return null}const k=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,$e=t=>!V(t)&&t!==k;function ue(){const{caseless:t}=$e(this)&&this||{},e={},n=(r,s)=>{const o=t&&Ve(e,s)||s;G(e[o])&&G(r)?e[o]=ue(e[o],r):G(r)?e[o]=ue({},r):q(r)?e[o]=r.slice():e[o]=r};for(let r=0,s=arguments.length;r(J(e,(s,o)=>{n&&_(s)?t[o]=qe(s,n):t[o]=s},{allOwnKeys:r}),t),qt=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),Ut=(t,e,n,r)=>{t.prototype=Object.create(e.prototype,r),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},Ht=(t,e,n,r)=>{let s,o,i;const a={};if(e=e||{},t==null)return e;do{for(s=Object.getOwnPropertyNames(t),o=s.length;o-- >0;)i=s[o],(!r||r(i,t,e))&&!a[i]&&(e[i]=t[i],a[i]=!0);t=n!==!1&&ye(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},jt=(t,e,n)=>{t=String(t),(n===void 0||n>t.length)&&(n=t.length),n-=e.length;const r=t.indexOf(e,n);return r!==-1&&r===n},Vt=t=>{if(!t)return null;if(q(t))return t;let e=t.length;if(!je(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},$t=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&ye(Uint8Array)),zt=(t,e)=>{const r=(t&&t[ee]).call(t);let s;for(;(s=r.next())&&!s.done;){const o=s.value;e.call(t,o[0],o[1])}},Jt=(t,e)=>{let n;const r=[];for(;(n=t.exec(e))!==null;)r.push(n);return r},Kt=O("HTMLFormElement"),Wt=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,s){return r.toUpperCase()+s}),Re=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),Gt=O("RegExp"),ze=(t,e)=>{const n=Object.getOwnPropertyDescriptors(t),r={};J(n,(s,o)=>{let i;(i=e(s,o,t))!==!1&&(r[o]=i||s)}),Object.defineProperties(t,r)},Xt=t=>{ze(t,(e,n)=>{if(_(t)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=t[n];if(_(r)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},Qt=(t,e)=>{const n={},r=s=>{s.forEach(o=>{n[o]=!0})};return q(t)?r(t):r(String(t).split(e)),n},Yt=()=>{},Zt=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function en(t){return!!(t&&_(t.append)&&t[Ue]==="FormData"&&t[ee])}const tn=t=>{const e=new Array(10),n=(r,s)=>{if(z(r)){if(e.indexOf(r)>=0)return;if($(r))return r;if(!("toJSON"in r)){e[s]=r;const o=q(r)?[]:{};return J(r,(i,a)=>{const f=n(i,s+1);!V(f)&&(o[a]=f)}),e[s]=void 0,o}}return r};return n(t,0)},nn=O("AsyncFunction"),rn=t=>t&&(z(t)||_(t))&&_(t.then)&&_(t.catch),Je=((t,e)=>t?setImmediate:e?((n,r)=>(k.addEventListener("message",({source:s,data:o})=>{s===k&&o===n&&r.length&&r.shift()()},!1),s=>{r.push(s),k.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",_(k.postMessage)),sn=typeof queueMicrotask<"u"?queueMicrotask.bind(k):typeof process<"u"&&process.nextTick||Je,on=t=>t!=null&&_(t[ee]),l={isArray:q,isArrayBuffer:He,isBuffer:$,isFormData:Pt,isArrayBufferView:Tt,isString:Rt,isNumber:je,isBoolean:vt,isObject:z,isPlainObject:G,isEmptyObject:_t,isReadableStream:Mt,isRequest:kt,isResponse:Lt,isHeaders:Ft,isUndefined:V,isDate:Ct,isFile:At,isBlob:Ot,isRegExp:Gt,isFunction:_,isStream:Nt,isURLSearchParams:It,isTypedArray:$t,isFileList:xt,forEach:J,merge:ue,extend:Dt,trim:Bt,stripBOM:qt,inherits:Ut,toFlatObject:Ht,kindOf:te,kindOfTest:O,endsWith:jt,toArray:Vt,forEachEntry:zt,matchAll:Jt,isHTMLForm:Kt,hasOwnProperty:Re,hasOwnProp:Re,reduceDescriptors:ze,freezeMethods:Xt,toObjectSet:Qt,toCamelCase:Wt,noop:Yt,toFiniteNumber:Zt,findKey:Ve,global:k,isContextDefined:$e,isSpecCompliantForm:en,toJSONObject:tn,isAsyncFn:nn,isThenable:rn,setImmediate:Je,asap:sn,isIterable:on};function w(t,e,n,r,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),n&&(this.config=n),r&&(this.request=r),s&&(this.response=s,this.status=s.status?s.status:null)}l.inherits(w,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:l.toJSONObject(this.config),code:this.code,status:this.status}}});const Ke=w.prototype,We={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(t=>{We[t]={value:t}});Object.defineProperties(w,We);Object.defineProperty(Ke,"isAxiosError",{value:!0});w.from=(t,e,n,r,s,o)=>{const i=Object.create(Ke);return l.toFlatObject(t,i,function(f){return f!==Error.prototype},a=>a!=="isAxiosError"),w.call(i,t.message,e,n,r,s),i.cause=t,i.name=t.name,o&&Object.assign(i,o),i};const an=null;function fe(t){return l.isPlainObject(t)||l.isArray(t)}function Ge(t){return l.endsWith(t,"[]")?t.slice(0,-2):t}function ve(t,e,n){return t?t.concat(e).map(function(s,o){return s=Ge(s),!n&&o?"["+s+"]":s}).join(n?".":""):e}function cn(t){return l.isArray(t)&&!t.some(fe)}const ln=l.toFlatObject(l,{},null,function(e){return/^is[A-Z]/.test(e)});function re(t,e,n){if(!l.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,n=l.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,h){return!l.isUndefined(h[y])});const r=n.metaTokens,s=n.visitor||u,o=n.dots,i=n.indexes,f=(n.Blob||typeof Blob<"u"&&Blob)&&l.isSpecCompliantForm(e);if(!l.isFunction(s))throw new TypeError("visitor must be a function");function c(p){if(p===null)return"";if(l.isDate(p))return p.toISOString();if(l.isBoolean(p))return p.toString();if(!f&&l.isBlob(p))throw new w("Blob is not supported. Use a Buffer instead.");return l.isArrayBuffer(p)||l.isTypedArray(p)?f&&typeof Blob=="function"?new Blob([p]):Buffer.from(p):p}function u(p,y,h){let b=p;if(p&&!h&&typeof p=="object"){if(l.endsWith(y,"{}"))y=r?y:y.slice(0,-2),p=JSON.stringify(p);else if(l.isArray(p)&&cn(p)||(l.isFileList(p)||l.endsWith(y,"[]"))&&(b=l.toArray(p)))return y=Ge(y),b.forEach(function(E,A){!(l.isUndefined(E)||E===null)&&e.append(i===!0?ve([y],A,o):i===null?y:y+"[]",c(E))}),!1}return fe(p)?!0:(e.append(ve(h,y,o),c(p)),!1)}const d=[],m=Object.assign(ln,{defaultVisitor:u,convertValue:c,isVisitable:fe});function g(p,y){if(!l.isUndefined(p)){if(d.indexOf(p)!==-1)throw Error("Circular reference detected in "+y.join("."));d.push(p),l.forEach(p,function(b,S){(!(l.isUndefined(b)||b===null)&&s.call(e,b,l.isString(S)?S.trim():S,y,m))===!0&&g(b,y?y.concat(S):[S])}),d.pop()}}if(!l.isObject(t))throw new TypeError("data must be an object");return g(t),e}function _e(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(r){return e[r]})}function ge(t,e){this._pairs=[],t&&re(t,this,e)}const Xe=ge.prototype;Xe.append=function(e,n){this._pairs.push([e,n])};Xe.toString=function(e){const n=e?function(r){return e.call(this,r,_e)}:_e;return this._pairs.map(function(s){return n(s[0])+"="+n(s[1])},"").join("&")};function un(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Qe(t,e,n){if(!e)return t;const r=n&&n.encode||un;l.isFunction(n)&&(n={serialize:n});const s=n&&n.serialize;let o;if(s?o=s(e,n):o=l.isURLSearchParams(e)?e.toString():new ge(e,n).toString(r),o){const i=t.indexOf("#");i!==-1&&(t=t.slice(0,i)),t+=(t.indexOf("?")===-1?"?":"&")+o}return t}class Ce{constructor(){this.handlers=[]}use(e,n,r){return this.handlers.push({fulfilled:e,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){l.forEach(this.handlers,function(r){r!==null&&e(r)})}}const Ye={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},fn=typeof URLSearchParams<"u"?URLSearchParams:ge,dn=typeof FormData<"u"?FormData:null,hn=typeof Blob<"u"?Blob:null,pn={isBrowser:!0,classes:{URLSearchParams:fn,FormData:dn,Blob:hn},protocols:["http","https","file","blob","url","data"]},we=typeof window<"u"&&typeof document<"u",de=typeof navigator=="object"&&navigator||void 0,mn=we&&(!de||["ReactNative","NativeScript","NS"].indexOf(de.product)<0),yn=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",gn=we&&window.location.href||"http://localhost",wn=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:we,hasStandardBrowserEnv:mn,hasStandardBrowserWebWorkerEnv:yn,navigator:de,origin:gn},Symbol.toStringTag,{value:"Module"})),v={...wn,...pn};function En(t,e){return re(t,new v.classes.URLSearchParams,{visitor:function(n,r,s,o){return v.isNode&&l.isBuffer(n)?(this.append(r,n.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...e})}function bn(t){return l.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function Sn(t){const e={},n=Object.keys(t);let r;const s=n.length;let o;for(r=0;r=n.length;return i=!i&&l.isArray(s)?s.length:i,f?(l.hasOwnProp(s,i)?s[i]=[s[i],r]:s[i]=r,!a):((!s[i]||!l.isObject(s[i]))&&(s[i]=[]),e(n,r,s[i],o)&&l.isArray(s[i])&&(s[i]=Sn(s[i])),!a)}if(l.isFormData(t)&&l.isFunction(t.entries)){const n={};return l.forEachEntry(t,(r,s)=>{e(bn(r),s,n,0)}),n}return null}function Tn(t,e,n){if(l.isString(t))try{return(e||JSON.parse)(t),l.trim(t)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(t)}const K={transitional:Ye,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const r=n.getContentType()||"",s=r.indexOf("application/json")>-1,o=l.isObject(e);if(o&&l.isHTMLForm(e)&&(e=new FormData(e)),l.isFormData(e))return s?JSON.stringify(Ze(e)):e;if(l.isArrayBuffer(e)||l.isBuffer(e)||l.isStream(e)||l.isFile(e)||l.isBlob(e)||l.isReadableStream(e))return e;if(l.isArrayBufferView(e))return e.buffer;if(l.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return En(e,this.formSerializer).toString();if((a=l.isFileList(e))||r.indexOf("multipart/form-data")>-1){const f=this.env&&this.env.FormData;return re(a?{"files[]":e}:e,f&&new f,this.formSerializer)}}return o||s?(n.setContentType("application/json",!1),Tn(e)):e}],transformResponse:[function(e){const n=this.transitional||K.transitional,r=n&&n.forcedJSONParsing,s=this.responseType==="json";if(l.isResponse(e)||l.isReadableStream(e))return e;if(e&&l.isString(e)&&(r&&!this.responseType||s)){const i=!(n&&n.silentJSONParsing)&&s;try{return JSON.parse(e)}catch(a){if(i)throw a.name==="SyntaxError"?w.from(a,w.ERR_BAD_RESPONSE,this,null,this.response):a}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:v.classes.FormData,Blob:v.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};l.forEach(["delete","get","head","post","put","patch"],t=>{K.headers[t]={}});const Rn=l.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),vn=t=>{const e={};let n,r,s;return t&&t.split(` -`).forEach(function(i){s=i.indexOf(":"),n=i.substring(0,s).trim().toLowerCase(),r=i.substring(s+1).trim(),!(!n||e[n]&&Rn[n])&&(n==="set-cookie"?e[n]?e[n].push(r):e[n]=[r]:e[n]=e[n]?e[n]+", "+r:r)}),e},Ae=Symbol("internals");function H(t){return t&&String(t).trim().toLowerCase()}function X(t){return t===!1||t==null?t:l.isArray(t)?t.map(X):String(t)}function _n(t){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(t);)e[r[1]]=r[2];return e}const Cn=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function ae(t,e,n,r,s){if(l.isFunction(r))return r.call(this,e,n);if(s&&(e=n),!!l.isString(e)){if(l.isString(r))return e.indexOf(r)!==-1;if(l.isRegExp(r))return r.test(e)}}function An(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,r)=>n.toUpperCase()+r)}function On(t,e){const n=l.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(t,r+n,{value:function(s,o,i){return this[r].call(this,e,s,o,i)},configurable:!0})})}let C=class{constructor(e){e&&this.set(e)}set(e,n,r){const s=this;function o(a,f,c){const u=H(f);if(!u)throw new Error("header name must be a non-empty string");const d=l.findKey(s,u);(!d||s[d]===void 0||c===!0||c===void 0&&s[d]!==!1)&&(s[d||f]=X(a))}const i=(a,f)=>l.forEach(a,(c,u)=>o(c,u,f));if(l.isPlainObject(e)||e instanceof this.constructor)i(e,n);else if(l.isString(e)&&(e=e.trim())&&!Cn(e))i(vn(e),n);else if(l.isObject(e)&&l.isIterable(e)){let a={},f,c;for(const u of e){if(!l.isArray(u))throw TypeError("Object iterator must return a key-value pair");a[c=u[0]]=(f=a[c])?l.isArray(f)?[...f,u[1]]:[f,u[1]]:u[1]}i(a,n)}else e!=null&&o(n,e,r);return this}get(e,n){if(e=H(e),e){const r=l.findKey(this,e);if(r){const s=this[r];if(!n)return s;if(n===!0)return _n(s);if(l.isFunction(n))return n.call(this,s,r);if(l.isRegExp(n))return n.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=H(e),e){const r=l.findKey(this,e);return!!(r&&this[r]!==void 0&&(!n||ae(this,this[r],r,n)))}return!1}delete(e,n){const r=this;let s=!1;function o(i){if(i=H(i),i){const a=l.findKey(r,i);a&&(!n||ae(r,r[a],a,n))&&(delete r[a],s=!0)}}return l.isArray(e)?e.forEach(o):o(e),s}clear(e){const n=Object.keys(this);let r=n.length,s=!1;for(;r--;){const o=n[r];(!e||ae(this,this[o],o,e,!0))&&(delete this[o],s=!0)}return s}normalize(e){const n=this,r={};return l.forEach(this,(s,o)=>{const i=l.findKey(r,o);if(i){n[i]=X(s),delete n[o];return}const a=e?An(o):String(o).trim();a!==o&&delete n[o],n[a]=X(s),r[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return l.forEach(this,(r,s)=>{r!=null&&r!==!1&&(n[s]=e&&l.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(` -`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const r=new this(e);return n.forEach(s=>r.set(s)),r}static accessor(e){const r=(this[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 F(t,e){e=e||{};const n={};function r(c,u,d,m){return l.isPlainObject(c)&&l.isPlainObject(u)?l.merge.call({caseless:m},c,u):l.isPlainObject(u)?l.merge({},u):l.isArray(u)?u.slice():u}function s(c,u,d,m){if(l.isUndefined(u)){if(!l.isUndefined(c))return r(void 0,c,d,m)}else return r(c,u,d,m)}function o(c,u){if(!l.isUndefined(u))return r(void 0,u)}function i(c,u){if(l.isUndefined(u)){if(!l.isUndefined(c))return r(void 0,c)}else return r(void 0,u)}function a(c,u,d){if(d in e)return r(c,u);if(d in t)return r(void 0,c)}const f={url:o,method:o,data:o,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:a,headers:(c,u,d)=>s(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=F({},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 L=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=F(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 L(t),n=qe(L.prototype.request,e);return l.extend(n,L.prototype,e,{allOwnKeys:!0}),l.extend(n,e,null,{allOwnKeys:!0}),n.create=function(s){return lt(F(t,s))},n}const T=lt(K);T.Axios=L;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=F;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 I(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){B.add(async()=>{console.log("[Queue] Handling GET_CONVERSATIONS");const n=await this.service.handleGetConversations();this.port.postMessage({type:"socket-response",event:D.RECEIVE_CONVERSATIONS,data:n})})}async getConversation(e){B.add(async()=>{if(console.log("[Queue] Handling GET_CONVERSATION"),!e.data?.id)return;const{room_id:n}=this.service.getCurrentRoomInfo();n!=e.data.id&&(this._clickToConversation(e.data.id),await this._waitForMessagesToAppear(),await this._waitToloadMessages());const r=this.service.extractAllMessages();this.port.postMessage({type:"socket-response",event:D.RECEIVE_CONVERSATION,data:r})})}async sendMessage({data:{conversation_id:e,message:n}}){B.add(async()=>{console.log("[Queue] Handling SEND_MESSAGE");const{room_id:r}=this.service.getCurrentRoomInfo();r!=e&&this._clickToConversation(e),await I(200),await Fe.send(n)})}async replyMessage({data:{conversation_id:e,message:n,time:r}}){B.add(async()=>{console.log("[Queue] Handling REPLY_MESSAGE");const{room_id:s}=this.service.getCurrentRoomInfo();s!=e&&(this._clickToConversation(e),await this._waitForMessagesToAppear(),await this._waitToloadMessages()),await this._clickIfExists(this.service.elTags.close_reply_btn),await this._rightClickMessage(r);const o=document.querySelector(this.service.elTags.reply_btn);o&&o.click(),await I(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(()=>{B.add(async()=>{try{const n=this.service.getCurrentRoomInfo(),r=document.querySelector('[aria-labelledby^="cn-normal-notification-main-content-"]')?.getAttribute("aria-labelledby");if(!r){const a=await this.service.detectNewMessages();if(!a){console.log("[Monitor] No new message...");return}if(n.room_id!==a?.room_id){console.log("[Monitor] Message from another room → skip");return}console.log("[Monitor] Found new message:",a),await this._sendLastMessage(a);return}const s=r.split(" ")[0].replace("cn-normal-notification-main-content-","");if(!s){console.warn("[Monitor] Could not extract room_id from aria-labelledby");return}console.log("[Monitor] Notification detected:",{roomId:s,ariaValue:r}),this._clickToConversation(s),await I(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(()=>{B.add(async()=>{try{const{data:e}=await tr.getConversationByPrefix();if(!e)return;for(const n of e){this._clickToConversation(n.id),await I(2e3);const r=this.service.getCurrentRoomInfo();if(!r||r.room_id!==n.id)return;const s=this.service.extractAllMessages();await Be.createAndSendToZulip(s),await I(5e3)}}catch(e){console.error("❌ autoSyncConversationPrefixMessages error:",e)}})},3e4),console.log("✅ autoSyncConversationPrefixMessages running with PQueue"))}}const ut=chrome.runtime.connect({name:"message"}),M=new nr(ut);ut.onMessage.addListener(t=>{if(console.log({msg:t}),M.fixedHeightChatInput(),t.type==="socket")switch(t.event){case D.GET_CONVERSATIONS:{M.getConversations(t);break}case D.GET_CONVERSATION:{M.getConversation(t);break}case D.SEND_MESSAGE:{M.sendMessage(t);break}case D.REPLY_MESSAGE:{M.replyMessage(t);break}}});M.startSyncConversations();M.autoSyncConversationPrefixMessages(); +const q={GET_CONVERSATIONS:"messages.get-conversations",GET_CONVERSATION:"messages.get-conversation",RECEIVE_CONVERSATIONS:"messages.receive-conversations",RECEIVE_CONVERSATION:"messages.receive-conversation",SEND_MESSAGE:"messages.send-messsage",REPLY_MESSAGE:"messages.reply-messsage"};function ft(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ae={exports:{}},Se;function dt(){return Se||(Se=1,function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function s(f,c,u){this.fn=f,this.context=c,this.once=u||!1}function o(f,c,u,d,m){if(typeof u!="function")throw new TypeError("The listener must be a function");var g=new s(u,d||f,m),p=n?n+c:c;return f._events[p]?f._events[p].fn?f._events[p]=[f._events[p],g]:f._events[p].push(g):(f._events[p]=g,f._eventsCount++),f}function i(f,c){--f._eventsCount===0?f._events=new r:delete f._events[c]}function a(){this._events=new r,this._eventsCount=0}a.prototype.eventNames=function(){var c=[],u,d;if(this._eventsCount===0)return c;for(d in u=this._events)e.call(u,d)&&c.push(n?d.slice(1):d);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},a.prototype.listeners=function(c){var u=n?n+c:c,d=this._events[u];if(!d)return[];if(d.fn)return[d.fn];for(var m=0,g=d.length,p=new Array(g);mglobalThis.DOMException===void 0?new mt(t):new DOMException(t),Re=t=>{const e=t.reason===void 0?Te("This operation was aborted."):t.reason;return e instanceof Error?e:Te(e)};function yt(t,e){const{milliseconds:n,fallback:r,message:s,customTimers:o={setTimeout,clearTimeout}}=e;let i,a;const c=new Promise((u,d)=>{if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(e.signal){const{signal:g}=e;g.aborted&&d(Re(g)),a=()=>{d(Re(g))},g.addEventListener("abort",a,{once:!0})}if(n===Number.POSITIVE_INFINITY){t.then(u,d);return}const m=new De;i=o.setTimeout.call(void 0,()=>{if(r){try{u(r())}catch(g){d(g)}return}typeof t.cancel=="function"&&t.cancel(),s===!1?u():s instanceof Error?d(s):(m.message=s??`Promise timed out after ${n} milliseconds`,d(m))},n),(async()=>{try{u(await t)}catch(g){d(g)}})()}).finally(()=>{c.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return c.clear=()=>{o.clearTimeout.call(void 0,i),i=void 0},c}function gt(t,e,n){let r=0,s=t.length;for(;s>0;){const o=Math.trunc(s/2);let i=r+o;n(t[i],e)<=0?(r=++i,s-=o+1):s=o}return r}class wt{#e=[];enqueue(e,n){n={priority:0,...n};const r={priority:n.priority,id:n.id,run:e};if(this.size===0||this.#e[this.size-1].priority>=n.priority){this.#e.push(r);return}const s=gt(this.#e,r,(o,i)=>i.priority-o.priority);this.#e.splice(s,0,r)}setPriority(e,n){const r=this.#e.findIndex(o=>o.id===e);if(r===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);const[s]=this.#e.splice(r,1);this.enqueue(s.run,{priority:n,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(n=>n.priority===e.priority).map(n=>n.run)}get size(){return this.#e.length}}class Et extends pt{#e;#i;#o=0;#h;#a;#p=0;#n;#c;#t;#m;#r=0;#l;#s;#y;#E=1n;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:wt,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#i=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#h=e.intervalCap,this.#a=e.interval,this.#t=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#y=e.throwOnTimeout===!0,this.#s=e.autoStart===!1}get#b(){return this.#i||this.#o{this.#R()},n)),!0}return!1}#u(){if(this.#t.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#r===0&&this.emit("idle"),!1;if(!this.#s){const e=!this.#v;if(this.#b&&this.#S){const n=this.#t.dequeue();return n?(this.emit("active"),n(),e&&this.#g(),!0):!1}}return!1}#g(){this.#i||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#a),this.#p=Date.now()+this.#a)}#w(){this.#o===0&&this.#r===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#o=this.#e?this.#r:0,this.#f()}#f(){for(;this.#u(););}get concurrency(){return this.#l}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#l=e,this.#f()}async#_(e){return new Promise((n,r)=>{e.addEventListener("abort",()=>{r(e.reason)},{once:!0})})}setPriority(e,n){this.#t.setPriority(e,n)}async add(e,n={}){return n.id??=(this.#E++).toString(),n={timeout:this.timeout,throwOnTimeout:this.#y,...n},new Promise((r,s)=>{this.#t.enqueue(async()=>{this.#r++,this.#o++;try{n.signal?.throwIfAborted();let o=e({signal:n.signal});n.timeout&&(o=yt(Promise.resolve(o),{milliseconds:n.timeout})),n.signal&&(o=Promise.race([o,this.#_(n.signal)]));const i=await o;r(i),this.emit("completed",i)}catch(o){if(o instanceof De&&!n.throwOnTimeout){r();return}s(o),this.emit("error",o)}finally{this.#T()}},n),this.emit("add"),this.#u()})}async addAll(e,n){return Promise.all(e.map(async r=>this.add(r,n)))}start(){return this.#s?(this.#s=!1,this.#f(),this):this}pause(){this.#s=!0}clear(){this.#t=new this.#m}async onEmpty(){this.#t.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#t.sizethis.#t.size{const s=()=>{n&&!n()||(this.off(e,s),r())};this.on(e,s)})}get size(){return this.#t.size}sizeBy(e){return this.#t.filter(e).length}get pending(){return this.#r}get isPaused(){return this.#s}}const D=new Et({concurrency:1});function qe(t,e){return function(){return t.apply(e,arguments)}}const{toString:bt}=Object.prototype,{getPrototypeOf:ge}=Object,{iterator:te,toStringTag:Ue}=Symbol,ne=(t=>e=>{const n=bt.call(e);return t[n]||(t[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),O=t=>(t=t.toLowerCase(),e=>ne(e)===t),re=t=>e=>typeof e===t,{isArray:H}=Array,V=re("undefined");function z(t){return t!==null&&!V(t)&&t.constructor!==null&&!V(t.constructor)&&_(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const He=O("ArrayBuffer");function St(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&He(t.buffer),e}const Tt=re("string"),_=re("function"),je=re("number"),J=t=>t!==null&&typeof t=="object",Rt=t=>t===!0||t===!1,X=t=>{if(ne(t)!=="object")return!1;const e=ge(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Ue in t)&&!(te in t)},vt=t=>{if(!J(t)||z(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},_t=O("Date"),Ct=O("File"),At=O("Blob"),Ot=O("FileList"),xt=t=>J(t)&&_(t.pipe),Nt=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||_(t.append)&&((e=ne(t))==="formdata"||e==="object"&&_(t.toString)&&t.toString()==="[object FormData]"))},Pt=O("URLSearchParams"),[It,Mt,Lt,kt]=["ReadableStream","Request","Response","Headers"].map(O),Ft=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function K(t,e,{allOwnKeys:n=!1}={}){if(t===null||typeof t>"u")return;let r,s;if(typeof t!="object"&&(t=[t]),H(t))for(r=0,s=t.length;r0;)if(s=n[r],e===s.toLowerCase())return s;return null}const k=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Ve=t=>!V(t)&&t!==k;function fe(){const{caseless:t}=Ve(this)&&this||{},e={},n=(r,s)=>{const o=t&&$e(e,s)||s;X(e[o])&&X(r)?e[o]=fe(e[o],r):X(r)?e[o]=fe({},r):H(r)?e[o]=r.slice():e[o]=r};for(let r=0,s=arguments.length;r(K(e,(s,o)=>{n&&_(s)?t[o]=qe(s,n):t[o]=s},{allOwnKeys:r}),t),Dt=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),qt=(t,e,n,r)=>{t.prototype=Object.create(e.prototype,r),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},Ut=(t,e,n,r)=>{let s,o,i;const a={};if(e=e||{},t==null)return e;do{for(s=Object.getOwnPropertyNames(t),o=s.length;o-- >0;)i=s[o],(!r||r(i,t,e))&&!a[i]&&(e[i]=t[i],a[i]=!0);t=n!==!1&&ge(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},Ht=(t,e,n)=>{t=String(t),(n===void 0||n>t.length)&&(n=t.length),n-=e.length;const r=t.indexOf(e,n);return r!==-1&&r===n},jt=t=>{if(!t)return null;if(H(t))return t;let e=t.length;if(!je(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},$t=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&ge(Uint8Array)),Vt=(t,e)=>{const r=(t&&t[te]).call(t);let s;for(;(s=r.next())&&!s.done;){const o=s.value;e.call(t,o[0],o[1])}},zt=(t,e)=>{let n;const r=[];for(;(n=t.exec(e))!==null;)r.push(n);return r},Jt=O("HTMLFormElement"),Kt=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,s){return r.toUpperCase()+s}),ve=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),Wt=O("RegExp"),ze=(t,e)=>{const n=Object.getOwnPropertyDescriptors(t),r={};K(n,(s,o)=>{let i;(i=e(s,o,t))!==!1&&(r[o]=i||s)}),Object.defineProperties(t,r)},Gt=t=>{ze(t,(e,n)=>{if(_(t)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=t[n];if(_(r)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},Xt=(t,e)=>{const n={},r=s=>{s.forEach(o=>{n[o]=!0})};return H(t)?r(t):r(String(t).split(e)),n},Qt=()=>{},Yt=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function Zt(t){return!!(t&&_(t.append)&&t[Ue]==="FormData"&&t[te])}const en=t=>{const e=new Array(10),n=(r,s)=>{if(J(r)){if(e.indexOf(r)>=0)return;if(z(r))return r;if(!("toJSON"in r)){e[s]=r;const o=H(r)?[]:{};return K(r,(i,a)=>{const f=n(i,s+1);!V(f)&&(o[a]=f)}),e[s]=void 0,o}}return r};return n(t,0)},tn=O("AsyncFunction"),nn=t=>t&&(J(t)||_(t))&&_(t.then)&&_(t.catch),Je=((t,e)=>t?setImmediate:e?((n,r)=>(k.addEventListener("message",({source:s,data:o})=>{s===k&&o===n&&r.length&&r.shift()()},!1),s=>{r.push(s),k.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",_(k.postMessage)),rn=typeof queueMicrotask<"u"?queueMicrotask.bind(k):typeof process<"u"&&process.nextTick||Je,sn=t=>t!=null&&_(t[te]),l={isArray:H,isArrayBuffer:He,isBuffer:z,isFormData:Nt,isArrayBufferView:St,isString:Tt,isNumber:je,isBoolean:Rt,isObject:J,isPlainObject:X,isEmptyObject:vt,isReadableStream:It,isRequest:Mt,isResponse:Lt,isHeaders:kt,isUndefined:V,isDate:_t,isFile:Ct,isBlob:At,isRegExp:Wt,isFunction:_,isStream:xt,isURLSearchParams:Pt,isTypedArray:$t,isFileList:Ot,forEach:K,merge:fe,extend:Bt,trim:Ft,stripBOM:Dt,inherits:qt,toFlatObject:Ut,kindOf:ne,kindOfTest:O,endsWith:Ht,toArray:jt,forEachEntry:Vt,matchAll:zt,isHTMLForm:Jt,hasOwnProperty:ve,hasOwnProp:ve,reduceDescriptors:ze,freezeMethods:Gt,toObjectSet:Xt,toCamelCase:Kt,noop:Qt,toFiniteNumber:Yt,findKey:$e,global:k,isContextDefined:Ve,isSpecCompliantForm:Zt,toJSONObject:en,isAsyncFn:tn,isThenable:nn,setImmediate:Je,asap:rn,isIterable:sn};function w(t,e,n,r,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),n&&(this.config=n),r&&(this.request=r),s&&(this.response=s,this.status=s.status?s.status:null)}l.inherits(w,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:l.toJSONObject(this.config),code:this.code,status:this.status}}});const Ke=w.prototype,We={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(t=>{We[t]={value:t}});Object.defineProperties(w,We);Object.defineProperty(Ke,"isAxiosError",{value:!0});w.from=(t,e,n,r,s,o)=>{const i=Object.create(Ke);return l.toFlatObject(t,i,function(f){return f!==Error.prototype},a=>a!=="isAxiosError"),w.call(i,t.message,e,n,r,s),i.cause=t,i.name=t.name,o&&Object.assign(i,o),i};const on=null;function de(t){return l.isPlainObject(t)||l.isArray(t)}function Ge(t){return l.endsWith(t,"[]")?t.slice(0,-2):t}function _e(t,e,n){return t?t.concat(e).map(function(s,o){return s=Ge(s),!n&&o?"["+s+"]":s}).join(n?".":""):e}function an(t){return l.isArray(t)&&!t.some(de)}const cn=l.toFlatObject(l,{},null,function(e){return/^is[A-Z]/.test(e)});function se(t,e,n){if(!l.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,n=l.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,h){return!l.isUndefined(h[y])});const r=n.metaTokens,s=n.visitor||u,o=n.dots,i=n.indexes,f=(n.Blob||typeof Blob<"u"&&Blob)&&l.isSpecCompliantForm(e);if(!l.isFunction(s))throw new TypeError("visitor must be a function");function c(p){if(p===null)return"";if(l.isDate(p))return p.toISOString();if(l.isBoolean(p))return p.toString();if(!f&&l.isBlob(p))throw new w("Blob is not supported. Use a Buffer instead.");return l.isArrayBuffer(p)||l.isTypedArray(p)?f&&typeof Blob=="function"?new Blob([p]):Buffer.from(p):p}function u(p,y,h){let b=p;if(p&&!h&&typeof p=="object"){if(l.endsWith(y,"{}"))y=r?y:y.slice(0,-2),p=JSON.stringify(p);else if(l.isArray(p)&&an(p)||(l.isFileList(p)||l.endsWith(y,"[]"))&&(b=l.toArray(p)))return y=Ge(y),b.forEach(function(E,A){!(l.isUndefined(E)||E===null)&&e.append(i===!0?_e([y],A,o):i===null?y:y+"[]",c(E))}),!1}return de(p)?!0:(e.append(_e(h,y,o),c(p)),!1)}const d=[],m=Object.assign(cn,{defaultVisitor:u,convertValue:c,isVisitable:de});function g(p,y){if(!l.isUndefined(p)){if(d.indexOf(p)!==-1)throw Error("Circular reference detected in "+y.join("."));d.push(p),l.forEach(p,function(b,S){(!(l.isUndefined(b)||b===null)&&s.call(e,b,l.isString(S)?S.trim():S,y,m))===!0&&g(b,y?y.concat(S):[S])}),d.pop()}}if(!l.isObject(t))throw new TypeError("data must be an object");return g(t),e}function Ce(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(r){return e[r]})}function we(t,e){this._pairs=[],t&&se(t,this,e)}const Xe=we.prototype;Xe.append=function(e,n){this._pairs.push([e,n])};Xe.toString=function(e){const n=e?function(r){return e.call(this,r,Ce)}:Ce;return this._pairs.map(function(s){return n(s[0])+"="+n(s[1])},"").join("&")};function ln(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Qe(t,e,n){if(!e)return t;const r=n&&n.encode||ln;l.isFunction(n)&&(n={serialize:n});const s=n&&n.serialize;let o;if(s?o=s(e,n):o=l.isURLSearchParams(e)?e.toString():new we(e,n).toString(r),o){const i=t.indexOf("#");i!==-1&&(t=t.slice(0,i)),t+=(t.indexOf("?")===-1?"?":"&")+o}return t}class Ae{constructor(){this.handlers=[]}use(e,n,r){return this.handlers.push({fulfilled:e,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){l.forEach(this.handlers,function(r){r!==null&&e(r)})}}const Ye={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},un=typeof URLSearchParams<"u"?URLSearchParams:we,fn=typeof FormData<"u"?FormData:null,dn=typeof Blob<"u"?Blob:null,hn={isBrowser:!0,classes:{URLSearchParams:un,FormData:fn,Blob:dn},protocols:["http","https","file","blob","url","data"]},Ee=typeof window<"u"&&typeof document<"u",he=typeof navigator=="object"&&navigator||void 0,pn=Ee&&(!he||["ReactNative","NativeScript","NS"].indexOf(he.product)<0),mn=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",yn=Ee&&window.location.href||"http://localhost",gn=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ee,hasStandardBrowserEnv:pn,hasStandardBrowserWebWorkerEnv:mn,navigator:he,origin:yn},Symbol.toStringTag,{value:"Module"})),v={...gn,...hn};function wn(t,e){return se(t,new v.classes.URLSearchParams,{visitor:function(n,r,s,o){return v.isNode&&l.isBuffer(n)?(this.append(r,n.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...e})}function En(t){return l.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function bn(t){const e={},n=Object.keys(t);let r;const s=n.length;let o;for(r=0;r=n.length;return i=!i&&l.isArray(s)?s.length:i,f?(l.hasOwnProp(s,i)?s[i]=[s[i],r]:s[i]=r,!a):((!s[i]||!l.isObject(s[i]))&&(s[i]=[]),e(n,r,s[i],o)&&l.isArray(s[i])&&(s[i]=bn(s[i])),!a)}if(l.isFormData(t)&&l.isFunction(t.entries)){const n={};return l.forEachEntry(t,(r,s)=>{e(En(r),s,n,0)}),n}return null}function Sn(t,e,n){if(l.isString(t))try{return(e||JSON.parse)(t),l.trim(t)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(t)}const W={transitional:Ye,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const r=n.getContentType()||"",s=r.indexOf("application/json")>-1,o=l.isObject(e);if(o&&l.isHTMLForm(e)&&(e=new FormData(e)),l.isFormData(e))return s?JSON.stringify(Ze(e)):e;if(l.isArrayBuffer(e)||l.isBuffer(e)||l.isStream(e)||l.isFile(e)||l.isBlob(e)||l.isReadableStream(e))return e;if(l.isArrayBufferView(e))return e.buffer;if(l.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return wn(e,this.formSerializer).toString();if((a=l.isFileList(e))||r.indexOf("multipart/form-data")>-1){const f=this.env&&this.env.FormData;return se(a?{"files[]":e}:e,f&&new f,this.formSerializer)}}return o||s?(n.setContentType("application/json",!1),Sn(e)):e}],transformResponse:[function(e){const n=this.transitional||W.transitional,r=n&&n.forcedJSONParsing,s=this.responseType==="json";if(l.isResponse(e)||l.isReadableStream(e))return e;if(e&&l.isString(e)&&(r&&!this.responseType||s)){const i=!(n&&n.silentJSONParsing)&&s;try{return JSON.parse(e)}catch(a){if(i)throw a.name==="SyntaxError"?w.from(a,w.ERR_BAD_RESPONSE,this,null,this.response):a}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:v.classes.FormData,Blob:v.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};l.forEach(["delete","get","head","post","put","patch"],t=>{W.headers[t]={}});const Tn=l.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Rn=t=>{const e={};let n,r,s;return t&&t.split(` +`).forEach(function(i){s=i.indexOf(":"),n=i.substring(0,s).trim().toLowerCase(),r=i.substring(s+1).trim(),!(!n||e[n]&&Tn[n])&&(n==="set-cookie"?e[n]?e[n].push(r):e[n]=[r]:e[n]=e[n]?e[n]+", "+r:r)}),e},Oe=Symbol("internals");function $(t){return t&&String(t).trim().toLowerCase()}function Q(t){return t===!1||t==null?t:l.isArray(t)?t.map(Q):String(t)}function vn(t){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(t);)e[r[1]]=r[2];return e}const _n=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function ce(t,e,n,r,s){if(l.isFunction(r))return r.call(this,e,n);if(s&&(e=n),!!l.isString(e)){if(l.isString(r))return e.indexOf(r)!==-1;if(l.isRegExp(r))return r.test(e)}}function Cn(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,r)=>n.toUpperCase()+r)}function An(t,e){const n=l.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(t,r+n,{value:function(s,o,i){return this[r].call(this,e,s,o,i)},configurable:!0})})}let C=class{constructor(e){e&&this.set(e)}set(e,n,r){const s=this;function o(a,f,c){const u=$(f);if(!u)throw new Error("header name must be a non-empty string");const d=l.findKey(s,u);(!d||s[d]===void 0||c===!0||c===void 0&&s[d]!==!1)&&(s[d||f]=Q(a))}const i=(a,f)=>l.forEach(a,(c,u)=>o(c,u,f));if(l.isPlainObject(e)||e instanceof this.constructor)i(e,n);else if(l.isString(e)&&(e=e.trim())&&!_n(e))i(Rn(e),n);else if(l.isObject(e)&&l.isIterable(e)){let a={},f,c;for(const u of e){if(!l.isArray(u))throw TypeError("Object iterator must return a key-value pair");a[c=u[0]]=(f=a[c])?l.isArray(f)?[...f,u[1]]:[f,u[1]]:u[1]}i(a,n)}else e!=null&&o(n,e,r);return this}get(e,n){if(e=$(e),e){const r=l.findKey(this,e);if(r){const s=this[r];if(!n)return s;if(n===!0)return vn(s);if(l.isFunction(n))return n.call(this,s,r);if(l.isRegExp(n))return n.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=$(e),e){const r=l.findKey(this,e);return!!(r&&this[r]!==void 0&&(!n||ce(this,this[r],r,n)))}return!1}delete(e,n){const r=this;let s=!1;function o(i){if(i=$(i),i){const a=l.findKey(r,i);a&&(!n||ce(r,r[a],a,n))&&(delete r[a],s=!0)}}return l.isArray(e)?e.forEach(o):o(e),s}clear(e){const n=Object.keys(this);let r=n.length,s=!1;for(;r--;){const o=n[r];(!e||ce(this,this[o],o,e,!0))&&(delete this[o],s=!0)}return s}normalize(e){const n=this,r={};return l.forEach(this,(s,o)=>{const i=l.findKey(r,o);if(i){n[i]=Q(s),delete n[o];return}const a=e?Cn(o):String(o).trim();a!==o&&delete n[o],n[a]=Q(s),r[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return l.forEach(this,(r,s)=>{r!=null&&r!==!1&&(n[s]=e&&l.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(` +`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const r=new this(e);return n.forEach(s=>r.set(s)),r}static accessor(e){const r=(this[Oe]=this[Oe]={accessors:{}}).accessors,s=this.prototype;function o(i){const a=$(i);r[a]||(An(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 le(t,e){const n=this||W,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 j(t,e,n){w.call(this,t??"canceled",w.ERR_CANCELED,e,n),this.name="CanceledError"}l.inherits(j,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 On(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function xn(t,e){t=t||10;const n=new Array(t),r=new Array(t);let s=0,o=0,i;return e=e!==void 0?e:1e3,function(f){const c=Date.now(),u=r[o];i||(i=c),n[s]=f,r[s]=c;let d=o,m=0;for(;d!==s;)m+=n[d++],d=d%t;if(s=(s+1)%t,s===o&&(o=(o+1)%t),c-i{n=u,s=null,o&&(clearTimeout(o),o=null),t(...c)};return[(...c)=>{const u=Date.now(),d=u-n;d>=r?i(c,u):(s=c,o||(o=setTimeout(()=>{o=null,i(s)},r-d)))},()=>s&&i(s)]}const Z=(t,e,n=3)=>{let r=0;const s=xn(50,250);return Nn(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)},xe=(t,e)=>{const n=t!=null;return[r=>e[0]({lengthComputable:n,total:t,loaded:r}),e[1]]},Ne=t=>(...e)=>l.asap(()=>t(...e)),Pn=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,In=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 Mn(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=!Mn(e);return t&&(r||n==!1)?Ln(t,e):e}const Pe=t=>t instanceof C?{...t}:t;function B(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(Pe(c),Pe(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=B({},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&&Pn(e.url))){const c=s&&o&&In.read(o);c&&i.set(s,c)}return e},kn=typeof XMLHttpRequest<"u",Fn=kn&&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]=Z(c,!0),h.addEventListener("progress",m)),f&&h.upload&&([d,g]=Z(f),h.upload.addEventListener("progress",d),h.upload.addEventListener("loadend",g)),(s.cancelToken||s.signal)&&(u=E=>{h&&(r(!E||E.type?new j(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=On(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)})},Bn=(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 j(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}},Dn=function*(t,e){let n=t.byteLength;if(n{const s=qn(t,e);let o=0,i,a=f=>{i||(i=!0,r&&r(f))};return new ReadableStream({async pull(f){try{const{done:c,value:u}=await s.next();if(c){a(),f.close();return}let d=u.byteLength;if(n){let m=o+=d;n(m)}f.enqueue(new Uint8Array(u))}catch(c){throw a(c),c}},cancel(f){return a(f),s.return()}},{highWaterMark:2})},oe=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",st=oe&&typeof ReadableStream=="function",Hn=oe&&(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}},jn=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}),Me=64*1024,pe=st&&ot(()=>l.isReadableStream(new Response("").body)),ee={stream:pe&&(t=>t.body)};oe&&(t=>{["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!ee[e]&&(ee[e]=l.isFunction(t[e])?n=>n[e]():(n,r)=>{throw new w(`Response type '${e}' is not supported`,w.ERR_NOT_SUPPORT,r)})})})(new Response);const $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 Hn(t)).byteLength},Vn=async(t,e)=>{const n=l.toFiniteNumber(t.getContentLength());return n??$n(e)},zn=oe&&(async t=>{let{url:e,method:n,data:r,signal:s,cancelToken:o,timeout:i,onDownloadProgress:a,onUploadProgress:f,responseType:c,headers:u,withCredentials:d="same-origin",fetchOptions:m}=rt(t);c=c?(c+"").toLowerCase():"text";let g=Bn([s,o&&o.toAbortSignal()],i),p;const y=g&&g.unsubscribe&&(()=>{g.unsubscribe()});let h;try{if(f&&jn&&n!=="get"&&n!=="head"&&(h=await Vn(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,G]=xe(h,Z(Ne(f)));r=Ie(R.body,Me,P,G)}}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=pe&&(c==="stream"||c==="response");if(pe&&(a||E&&y)){const R={};["status","statusText","headers"].forEach(be=>{R[be]=S[be]});const N=l.toFiniteNumber(S.headers.get("content-length")),[P,G]=a&&xe(N,Z(Ne(a),!0))||[];S=new Response(Ie(S.body,Me,P,()=>{G&&G(),y&&y()}),R)}c=c||"text";let A=await ee[l.findKey(ee,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)}}),me={http:on,xhr:Fn,fetch:zn};l.forEach(me,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const Le=t=>`- ${t}`,Jn=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(Le).join(` +`):" "+Le(o[0]):"as no adapter specified";throw new w("There is no suitable adapter to dispatch the request "+i,"ERR_NOT_SUPPORT")}return r},adapters:me};function ue(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new j(null,t)}function ke(t){return ue(t),t.headers=C.from(t.headers),t.data=le.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),it.getAdapter(t.adapter||W.adapter)(t).then(function(r){return ue(t),r.data=le.call(t,t.transformResponse,r),r.headers=C.from(r.headers),r},function(r){return et(r)||(ue(t),r&&r.response&&(r.response.data=le.call(t,t.transformResponse,r.response),r.response.headers=C.from(r.response.headers))),Promise.reject(r)})}const at="1.11.0",ie={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{ie[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});const Fe={};ie.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&&!Fe[i]&&(Fe[i]=!0,console.warn(s(i," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(o,i,a):!0}};ie.spelling=function(e){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};function Kn(t,e,n){if(typeof t!="object")throw new w("options must be an object",w.ERR_BAD_OPTION_VALUE);const r=Object.keys(t);let s=r.length;for(;s-- >0;){const o=r[s],i=e[o];if(i){const a=t[o],f=a===void 0||i(a,o,t);if(f!==!0)throw new w("option "+o+" must be "+f,w.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new w("Unknown option "+o,w.ERR_BAD_OPTION)}}const Y={assertOptions:Kn,validators:ie},x=Y.validators;let F=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Ae,response:new Ae}}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=B(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&Y.assertOptions(r,{silentJSONParsing:x.transitional(x.boolean),forcedJSONParsing:x.transitional(x.boolean),clarifyTimeoutError:x.transitional(x.boolean)},!1),s!=null&&(l.isFunction(s)?n.paramsSerializer={serialize:s}:Y.assertOptions(s,{encode:x.function,serialize:x.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Y.assertOptions(n,{baseUrl:x.spelling("baseURL"),withXsrfToken:x.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=o&&l.merge(o.common,o[n.method]);o&&l.forEach(["delete","get","head","post","put","patch","common"],p=>{delete o[p]}),n.headers=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 j(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 Gn(t){return function(n){return t.apply(null,n)}}function Xn(t){return l.isObject(t)&&t.isAxiosError===!0}const ye={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(ye).forEach(([t,e])=>{ye[e]=t});function lt(t){const e=new F(t),n=qe(F.prototype.request,e);return l.extend(n,F.prototype,e,{allOwnKeys:!0}),l.extend(n,e,null,{allOwnKeys:!0}),n.create=function(s){return lt(B(t,s))},n}const T=lt(W);T.Axios=F;T.CanceledError=j;T.CancelToken=Wn;T.isCancel=et;T.VERSION=at;T.toFormData=se;T.AxiosError=w;T.Cancel=T.CanceledError;T.all=function(e){return Promise.all(e)};T.spread=Gn;T.isAxiosError=Xn;T.mergeConfig=B;T.AxiosHeaders=C;T.formToJSON=t=>Ze(l.isHTMLForm(t)?new FormData(t):t);T.getAdapter=it.getAdapter;T.HttpStatusCode=ye;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,U=T.create({baseURL:"https://notable-recently-seagull.ngrok-free.app/api/v1/",headers:{"Content-Type":"application/json"}});class Qn{async sendSingleMessage(e){try{const{data:n}=await U.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 U.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 U.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}}async sendLog(e){try{const{data:n}=await U.post("/messages/logs",e);return console.log("[NestJS] Response (logs):",n),n}catch(n){throw console.error("[NestJS] Error (logs):",n),n}}}const M=new Qn;class Yn{MY_NAME="Apactech com";lastMessage;initialHistories=[];elTags={container_scroll:"/html/body/div[1]/div/div/div/div[5]/div[1]/div[1]/div[2]/div[1]/div[1]/div",conatainer_conversations:"/html/body/div[1]/div/div/div/div[5]/div[1]/div[1]/div[2]/div[1]/div[1]/div/div[1]",container_chat:'[data-testid="message-wrapper"]',root_id:'[aria-selected="true"] [id^="chat-list-item"]',room_name:'[data-tid="chat-title"]',close_reply_btn:'[data-track-action-scenario="messageQuotedReplyDismissed"]',reply_btn:'[aria-label="Reply"]',chat_input:'[placeholder="Type a message"]'};getCurrentRoomInfo(){const e=document.querySelector(this.elTags.root_id)?.id?.replace("chat-list-item_",""),n=document.querySelector(this.elTags.room_name)?.innerText;return{room_id:e,room_name:n}}_getMessageByEl(e){if(!e)return"";let n=e.innerText||"";const r=e.querySelector("img[data-gallery-src]");if(r)return r.getAttribute("data-gallery-src")||"";const o=Array.from(e.querySelectorAll("img[itemtype]")).map(i=>i.getAttribute("alt")||"").filter(Boolean);return o.length&&(n+=o.join("")),n.trim()}parseMessageElement(e,n=!1){const r=e.querySelector(n?".fui-ChatMyMessage__timestamp":".fui-ChatMessage__timestamp"),s=e.querySelector(n?".fui-ChatMyMessage__author":".fui-ChatMessage__author");if(!r)return null;const o=r.getAttribute("datetime");if(!o)return null;const i=Number.isNaN(r.id.replace("timestamp-",""))?new Date(o).getTime():Number(r.id.replace("timestamp-","")),a=document.querySelector(`#content-${i}`),{room_id:f,room_name:c}=this.getCurrentRoomInfo();return{name:s?.innerText,message:this._getMessageByEl(a),time:i,room_id:f,room_name:c,date_time:new Date(o).getTime()}}extractAllMessages(){const e=Array.from(document.querySelectorAll(".fui-ChatMyMessage")).map(r=>this.parseMessageElement(r,!0)).filter(r=>r!==null),n=Array.from(document.querySelectorAll(".fui-ChatMessage")).map(r=>this.parseMessageElement(r,!1)).filter(r=>r!==null);return console.log({myMessages:e,otherMessages:n}),[...e,...n].sort((r,s)=>r.time-s.time)}handleNewMessage(e){console.log("%c[New incoming message]","color: #007acc;",e)}async detectNewMessages(){const e=this.extractAllMessages(),n=e.findIndex(o=>o.time===this.lastMessage?.time),r=e.slice(n+1);if(r.length===0){console.log("[Monitor] No new messages...");return}const s=r[0];return this.lastMessage=e.pop(),s}async start(e=1e4){console.log("[Monitor] Starting..."),this.initialHistories=this.extractAllMessages(),this.lastMessage=this.initialHistories.pop(),setInterval(async()=>await this.detectNewMessages(),e)}async _getConversationsInfo(e=this.elTags.conatainer_conversations){const n=document.evaluate(e,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;return n?Array.from(n.children).filter(o=>o.getAttribute("role")==="none").map(o=>{const i=o.id||null,a=`title-chat-list-item_${i}`,c=document.getElementById(a)?.innerText||null;let u=null;return i?.includes("@thread.skype")?u="group":i?.includes("@oneToOne.skype")?u="personal":u="group",{id:i,name:c,type:u}}):(console.log("Không tìm thấy phần tử theo XPath."),M.sendLog({type:"error",message:`Not found selector: ${e}`}),[])}async _scrollToBottomByXPath(e=this.elTags.container_scroll,n){const{maxStableRounds:r=5,delay:s=300,maxScrolls:o=100}=n||{},i=document.evaluate(e,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;if(!i){console.warn("❌ Không tìm thấy phần tử với XPath:",e),M.sendLog({type:"error",message:`Not found selector: ${e}`});return}return new Promise(a=>{let f=-1,c=0,u=0;const d=setInterval(()=>{const m=i.scrollHeight;i.scrollTop=m,m===f?c++:(c=0,f=m),u++,(c>=r||u>=o)&&(clearInterval(d),a())},s)})}async handleGetConversations(){return await this._scrollToBottomByXPath(),this._getConversationsInfo()}}class Zn{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 Be=new Zn;function I(t){return new Promise(e=>setTimeout(e,t))}class er{async index(e){try{const{data:n}=await U({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 U({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 Yn,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),await M.sendLog({type:"error",message:`Not found selector: ${n}`});return}let f=document.querySelector(`#${r}`);for(;!f&&i{const r=document.querySelector(e);r?(r.scrollIntoView({behavior:"auto",block:"center"}),setTimeout(()=>{r?.click(),n(!0)},100)):(console.warn("Không tìm thấy phần tử:",e),n(!1))})}async getConversations(e){D.add(async()=>{console.log("[Queue] Handling GET_CONVERSATIONS");const n=await this.service.handleGetConversations();this.port.postMessage({type:"socket-response",event:q.RECEIVE_CONVERSATIONS,data:n})})}async getConversation(e){D.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:q.RECEIVE_CONVERSATION,data:r})})}async sendMessage({data:{conversation_id:e,message:n}}){D.add(async()=>{console.log("[Queue] Handling SEND_MESSAGE");const{room_id:r}=this.service.getCurrentRoomInfo();r!=e&&this._clickToConversation(e),await I(200),await Be.send(n)})}async replyMessage({data:{conversation_id:e,message:n,time:r}}){D.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 I(200),console.log({message:n}),await Be.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"),M.sendLog({type:"error",message:`Not found selector: ${this.service.elTags.chat_input}`}))})()}async detectNewMessage(e=2e3){console.log("[Monitor] Starting..."),this.service.initialHistories=this.service.extractAllMessages(),this.service.lastMessage=this.service.initialHistories.pop(),setInterval(()=>{D.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 I(2e3);const i=this.service.extractAllMessages().at(-1);if(!i){console.log("[Queue] No last message found after sync");return}console.log("[Queue] Sending last message:",i),await this._sendLastMessage(i)}catch(n){console.error("[Monitor] Error detecting new message:",n)}})},e)}async _sendLastMessage(e){try{await M.sendSingleMessage(e),console.log("[API] Sent message successfully:",e)}catch(n){console.error("[API] Failed to send message:",n)}}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(()=>{D.add(async()=>{try{const{data:e}=await tr.getConversationByPrefix();if(!e)return;for(const n of e){this._clickToConversation(n.id),await I(2e3);const r=this.service.getCurrentRoomInfo();if(!r||r.room_id!==n.id)return;const s=this.service.extractAllMessages();await M.createAndSendToZulip(s),await I(5e3)}}catch(e){console.error("❌ autoSyncConversationPrefixMessages error:",e?.message),M.sendLog({type:"error",message:`auto_to_sync_conersations: ${e?.message}`})}})},3e4),console.log("✅ autoSyncConversationPrefixMessages running with PQueue"))}}const ut=chrome.runtime.connect({name:"message"}),L=new nr(ut);ut.onMessage.addListener(t=>{if(console.log({msg:t}),L.fixedHeightChatInput(),t.type==="socket")switch(t.event){case q.GET_CONVERSATIONS:{L.getConversations(t);break}case q.GET_CONVERSATION:{L.getConversation(t);break}case q.SEND_MESSAGE:{L.sendMessage(t);break}case q.REPLY_MESSAGE:{L.replyMessage(t);break}}});L.startSyncConversations();L.autoSyncConversationPrefixMessages(); diff --git a/composer-bot-extensions/src/api/message-api.service.ts b/composer-bot-extensions/src/api/message-api.service.ts index 95e15f9..55f10ee 100644 --- a/composer-bot-extensions/src/api/message-api.service.ts +++ b/composer-bot-extensions/src/api/message-api.service.ts @@ -22,6 +22,7 @@ class MessageApiService { throw err; } } + async createAndSendToZulip(messages: IMessage[]) { try { const { data } = await axios.post("/messages/create-and-send", { @@ -34,6 +35,17 @@ class MessageApiService { throw err; } } + + async sendLog(log: ILog) { + try { + const { data } = await axios.post("/messages/logs", log); + console.log("[NestJS] Response (logs):", data); + return data; + } catch (err) { + console.error("[NestJS] Error (logs):", err); + throw err; + } + } } export const messageApi = new MessageApiService(); diff --git a/composer-bot-extensions/src/interfate.d.ts b/composer-bot-extensions/src/interfate.d.ts index 99238eb..b33eb0c 100644 --- a/composer-bot-extensions/src/interfate.d.ts +++ b/composer-bot-extensions/src/interfate.d.ts @@ -9,6 +9,12 @@ interface IMessage { date_time?: number; } +interface ILog { + message: string; + type: "error" | "success"; + id?: number; +} + interface IInputGeo { top: number; left: number; diff --git a/composer-bot-extensions/src/services/content.service.ts b/composer-bot-extensions/src/services/content.service.ts index 255ba69..2263685 100644 --- a/composer-bot-extensions/src/services/content.service.ts +++ b/composer-bot-extensions/src/services/content.service.ts @@ -219,6 +219,10 @@ export class ContentService { let wrapper = document.querySelector(selector); if (!wrapper) { console.error("Wrapper not found:", selector); + await messageApi.sendLog({ + type: "error", + message: `Not found selector: ${selector}`, + }); return; } @@ -400,27 +404,6 @@ export class ContentService { console.log({ message }); await typeingService.send(message); - - // if (!initialMessages) return; - - // // Sroll xuống - // this.service._scrollToBottomByXPath(); - - // // Theo dỗi lấy detech new message - // const newMessages = await this._waitForNewMessages(initialMessages, 3000); - // console.log("New messages appeared:", newMessages); - - // await this._waitToloadMessages(); - - // // Lấy hết message mới nhất - // const data = this.service.extractAllMessages(); - - // // Gửi lên server cập nhật - // this.port.postMessage({ - // type: "socket-response", - // event: EVENTS.RECEIVE_CONVERSATION, - // data, - // } as IMsg); }); } @@ -440,6 +423,10 @@ export class ContentService { ); } else { console.warn("✘ Element not found with provided XPath after retries"); + messageApi.sendLog({ + type: "error", + message: `Not found selector: ${this.service.elTags.chat_input}`, + }); } }; @@ -582,7 +569,14 @@ export class ContentService { await delay(5000); } } catch (err) { - console.error("❌ autoSyncConversationPrefixMessages error:", err); + console.error( + "❌ autoSyncConversationPrefixMessages error:", + (err as any)?.message + ); + messageApi.sendLog({ + type: "error", + message: `auto_to_sync_conersations: ${(err as any)?.message}`, + }); } }); }, 30000); diff --git a/composer-bot-extensions/src/services/teams-chat.service.ts b/composer-bot-extensions/src/services/teams-chat.service.ts index 8774557..20eece5 100644 --- a/composer-bot-extensions/src/services/teams-chat.service.ts +++ b/composer-bot-extensions/src/services/teams-chat.service.ts @@ -1,3 +1,5 @@ +import { messageApi } from "@/api/message-api.service"; + export class TeamsChatService { private readonly MY_NAME = "Apactech com"; public lastMessage?: IMessage; @@ -173,6 +175,10 @@ export class TeamsChatService { if (!result) { console.log("Không tìm thấy phần tử theo XPath."); + messageApi.sendLog({ + type: "error", + message: `Not found selector: ${xpath}`, + }); return []; } @@ -233,6 +239,10 @@ export class TeamsChatService { if (!container) { console.warn("❌ Không tìm thấy phần tử với XPath:", xpath); + messageApi.sendLog({ + type: "error", + message: `Not found selector: ${xpath}`, + }); return; } diff --git a/server/src/entities/log.entity.ts b/server/src/entities/log.entity.ts new file mode 100644 index 0000000..e069f81 --- /dev/null +++ b/server/src/entities/log.entity.ts @@ -0,0 +1,25 @@ +import { + Column, + CreateDateColumn, + Entity, + PrimaryGeneratedColumn, + UpdateDateColumn, +} from 'typeorm'; + +@Entity('logs') +export class Log { + @PrimaryGeneratedColumn('increment') + id: number; + + @Column({ type: 'text', nullable: true }) + message: string; // nội dung + + @Column({ type: 'varchar' }) + type: string; + + @CreateDateColumn() + created_at: Date; + + @UpdateDateColumn() + updated_at: Date; +} diff --git a/server/src/features/conver-message.ts b/server/src/features/conver-message.ts new file mode 100644 index 0000000..325ef57 --- /dev/null +++ b/server/src/features/conver-message.ts @@ -0,0 +1,30 @@ +function isTextInFormat(text: string) { + const lines = text + .split('\n') + .map((l) => l.trim()) + .filter((l) => l !== ''); + if (lines.length < 3) return false; + + const date = lines[1]; + const productCode = lines[2]; + + const dateRegex = /\d{1,2}\/\d{1,2}\/\d{4},?\s+\d{1,2}:\d{2}\s[AP]M/; + const productCodeRegex = /.+/; // ít nhất 1 ký tự + + return dateRegex.test(date) && productCodeRegex.test(productCode); +} + +export function formatTextIfValid(text: string) { + if (!isTextInFormat(text)) return text; // Không đúng format thì trả về nguyên bản + + const lines = text + .split('\n') + .map((l) => l.trim()) + .filter((l) => l !== ''); + const name = lines[0]; + const date = lines[1]; + const productCode = lines[2]; + const rest = lines.slice(3).join('\n'); + + return `${name} -- ${date}\n${productCode}\n\n${rest}`; +} diff --git a/server/src/features/format-time-au.ts b/server/src/features/format-time-au.ts index 3c6c6dd..619c2e2 100644 --- a/server/src/features/format-time-au.ts +++ b/server/src/features/format-time-au.ts @@ -3,5 +3,5 @@ import * as moment from 'moment-timezone'; export function formatTimeAU(timestamp: number) { return moment(timestamp) .tz('Etc/GMT-10') // Luôn cố định UTC+10 - .format('DD/MM/YYYY, h:mm A [AEST]'); + .format('DD/MMM/YY, h:mm A [AEST]'); } diff --git a/server/src/modules/messages/dtos/send-log.dto.ts b/server/src/modules/messages/dtos/send-log.dto.ts new file mode 100644 index 0000000..74153e9 --- /dev/null +++ b/server/src/modules/messages/dtos/send-log.dto.ts @@ -0,0 +1,9 @@ +import { IsString } from 'class-validator'; + +export class SendLogDto { + @IsString() + message: string; + + @IsString() + type: string; +} diff --git a/server/src/modules/messages/logs.service.ts b/server/src/modules/messages/logs.service.ts new file mode 100644 index 0000000..f00b682 --- /dev/null +++ b/server/src/modules/messages/logs.service.ts @@ -0,0 +1,39 @@ +import { Log } from '@/entities/log.entity'; +import { BadRequestException, Injectable } from '@nestjs/common'; +import { InjectRepository } from '@nestjs/typeorm'; +import { Repository } from 'typeorm'; +import { SendLogDto } from './dtos/send-log.dto'; +import { ZulipService } from './zulip.service'; +import AppResponse from '@/system/filters/response/app-response'; +import { SystemLang } from '@/system/lang/system.lang'; +@Injectable() +export class LogsService { + constructor( + @InjectRepository(Log) + readonly repo: Repository, + + private readonly zulipService: ZulipService, + ) {} + + async saveLog(data: SendLogDto) { + const result = await this.repo.save({ + message: data.message, + type: data.type, + }); + + if (!result) + throw new BadRequestException( + AppResponse.toResponse(null, { + message: SystemLang.getText('messages', 'error'), + }), + ); + + await this.zulipService.sendMessageToTopic( + process.env.ZULIP_STREAMS_NAME, + process.env.ZULIP_TOPPIC_LOG_NAME, + `[${result.type.toUpperCase()}] - ${result.message}`, + ); + + return AppResponse.toResponse(result); + } +} diff --git a/server/src/modules/messages/messages.controller.ts b/server/src/modules/messages/messages.controller.ts index 6b00ff7..da81c65 100644 --- a/server/src/modules/messages/messages.controller.ts +++ b/server/src/modules/messages/messages.controller.ts @@ -1,14 +1,19 @@ import { Body, Controller, Get, Post } from '@nestjs/common'; -import { MessagesService } from './messages.service'; -import { CreateMessageDto } from './dtos/create-message.dto'; -import { CreateBulkMessageDto } from './dtos/create-bulk-message.dto'; -import { SendMessageDto } from './dtos/send-message.dto'; -import { ReplyMessageDto } from './dtos/reply-message.dto'; import { Paginate, PaginateQuery } from 'nestjs-paginate'; +import { CreateBulkMessageDto } from './dtos/create-bulk-message.dto'; +import { CreateMessageDto } from './dtos/create-message.dto'; +import { ReplyMessageDto } from './dtos/reply-message.dto'; +import { SendLogDto } from './dtos/send-log.dto'; +import { SendMessageDto } from './dtos/send-message.dto'; +import { LogsService } from './logs.service'; +import { MessagesService } from './messages.service'; @Controller('messages') export class MessagesController { - constructor(private readonly service: MessagesService) {} + constructor( + private readonly service: MessagesService, + private readonly logService: LogsService, + ) {} @Get('') index(@Paginate() query: PaginateQuery) { @@ -34,4 +39,9 @@ export class MessagesController { replyMessage(@Body() data: ReplyMessageDto) { return this.service.replyMessage(data); } + + @Post('logs') + saveLog(@Body() data: SendLogDto) { + return this.logService.saveLog(data); + } } diff --git a/server/src/modules/messages/messages.module.ts b/server/src/modules/messages/messages.module.ts index be3caf5..e2bb40a 100644 --- a/server/src/modules/messages/messages.module.ts +++ b/server/src/modules/messages/messages.module.ts @@ -9,15 +9,18 @@ import { MessagesService } from './messages.service'; import { MessagesListener } from './messages.listener'; import { ZulipService } from './zulip.service'; import { HttpModule } from '@nestjs/axios'; +import { Log } from '@/entities/log.entity'; +import { LogsService } from './logs.service'; @Module({ - imports: [TypeOrmModule.forFeature([Message, Conversation]), HttpModule], + imports: [TypeOrmModule.forFeature([Message, Conversation, Log]), HttpModule], providers: [ MessagesService, MessagesGateway, MessagesEventService, MessagesListener, ZulipService, + LogsService, ], controllers: [MessagesController], exports: [MessagesGateway, MessagesService, MessagesEventService], diff --git a/server/src/modules/messages/messages.service.ts b/server/src/modules/messages/messages.service.ts index c9004b4..7e119c1 100644 --- a/server/src/modules/messages/messages.service.ts +++ b/server/src/modules/messages/messages.service.ts @@ -1,5 +1,7 @@ import { Conversation } from '@/entities/conversation.entity'; import { Message } from '@/entities/message.entity'; +import { formatTextIfValid } from '@/features/conver-message'; +import { formatTimeAU } from '@/features/format-time-au'; import AppResponse from '@/system/filters/response/app-response'; import { SystemLang } from '@/system/lang/system.lang'; import { @@ -11,13 +13,12 @@ import { import { InjectRepository } from '@nestjs/typeorm'; import { paginate, PaginateQuery } from 'nestjs-paginate'; import { Repository } from 'typeorm'; +import { CreateBulkMessageDto } from './dtos/create-bulk-message.dto'; import { CreateMessageDto } from './dtos/create-message.dto'; import { ReplyMessageDto } from './dtos/reply-message.dto'; import { SendMessageDto } from './dtos/send-message.dto'; import { MessagesEventService } from './messages-event.service'; import { ZulipService } from './zulip.service'; -import { CreateBulkMessageDto } from './dtos/create-bulk-message.dto'; -import { formatTimeAU } from '@/features/format-time-au'; @Injectable() export class MessagesService { constructor( @@ -26,7 +27,7 @@ export class MessagesService { @InjectRepository(Conversation) readonly conversationRepo: Repository, private readonly event: MessagesEventService, - private readonly zulupService: ZulipService, + private readonly zulipService: ZulipService, ) {} async index(query: PaginateQuery) { @@ -94,10 +95,10 @@ export class MessagesService { const content = `** :rocket: ${result.name} sent - ${formatTimeAU(result.time_raw)}:** \`\`\` -${result.message} +${formatTextIfValid(result.message)} \`\`\``; - await this.zulupService.sendMessageToTopic( + await this.zulipService.sendMessageToTopic( process.env.ZULIP_STREAMS_NAME, conversation.name, content,