xtro-edge-chatbolt 1.0.7 โ†’ 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- const e=Object.create(null);e.open="0",e.close="1",e.ping="2",e.pong="3",e.message="4",e.upgrade="5",e.noop="6";const t=Object.create(null);Object.keys(e).forEach(n=>{t[e[n]]=n});const n={type:"error",data:"parser error"},s="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),i="function"==typeof ArrayBuffer,r=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,o=({type:t,data:n},o,c)=>s&&n instanceof Blob?o?c(n):a(n,c):i&&(n instanceof ArrayBuffer||r(n))?o?c(n):a(new Blob([n]),c):c(e[t]+(n||"")),a=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function c(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let l;const h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<64;e++)p[h.charCodeAt(e)]=e;const d="function"==typeof ArrayBuffer,b=(e,s)=>{if("string"!=typeof e)return{type:"message",data:g(e,s)};const i=e.charAt(0);if("b"===i)return{type:"message",data:u(e.substring(1),s)};return t[i]?e.length>1?{type:t[i],data:e.substring(1)}:{type:t[i]}:n},u=(e,t)=>{if(d){const n=(e=>{let t,n,s,i,r,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const l=new ArrayBuffer(o),h=new Uint8Array(l);for(t=0;t<a;t+=4)n=p[e.charCodeAt(t)],s=p[e.charCodeAt(t+1)],i=p[e.charCodeAt(t+2)],r=p[e.charCodeAt(t+3)],h[c++]=n<<2|s>>4,h[c++]=(15&s)<<4|i>>2,h[c++]=(3&i)<<6|63&r;return l})(e);return g(n,t)}return{base64:!0,data:e}},g=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,f=String.fromCharCode(30);function m(){return new TransformStream({transform(e,t){!function(e,t){s&&e.data instanceof Blob?e.data.arrayBuffer().then(c).then(t):i&&(e.data instanceof ArrayBuffer||r(e.data))?t(c(e.data)):o(e,!1,e=>{l||(l=new TextEncoder),t(l.encode(e))})}(e,n=>{const s=n.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,s)}else{i=new Uint8Array(9);const e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(s))}e.data&&"string"!=typeof e.data&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}})}let x;function y(e){return e.reduce((e,t)=>e+t.length,0)}function k(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let s=0;for(let i=0;i<t;i++)n[i]=e[0][s++],s===e[0].length&&(e.shift(),s=0);return e.length&&s<e[0].length&&(e[0]=e[0].slice(s)),n}function w(e){if(e)return function(e){for(var t in w.prototype)e[t]=w.prototype[t];return e}(e)}w.prototype.on=w.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},w.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},w.prototype.off=w.prototype.removeListener=w.prototype.removeAllListeners=w.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,s=this._callbacks["$"+e];if(!s)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<s.length;i++)if((n=s[i])===t||n.fn===t){s.splice(i,1);break}return 0===s.length&&delete this._callbacks["$"+e],this},w.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],s=1;s<arguments.length;s++)t[s-1]=arguments[s];if(n){s=0;for(var i=(n=n.slice(0)).length;s<i;++s)n[s].apply(this,t)}return this},w.prototype.emitReserved=w.prototype.emit,w.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},w.prototype.hasListeners=function(e){return!!this.listeners(e).length};const v="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),_="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function S(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const E=_.setTimeout,T=_.clearTimeout;function C(e,t){t.useNativeTimers?(e.setTimeoutFn=E.bind(_),e.clearTimeoutFn=T.bind(_)):(e.setTimeoutFn=_.setTimeout.bind(_),e.clearTimeoutFn=_.clearTimeout.bind(_))}function A(e){return"string"==typeof e?function(e){let t=0,n=0;for(let s=0,i=e.length;s<i;s++)t=e.charCodeAt(s),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(s++,n+=4);return n}(e):Math.ceil(1.33*(e.byteLength||e.size))}function $(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class R extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class L extends w{constructor(e){super(),this.writable=!1,C(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new R(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=b(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}(e);return t.length?"?"+t:""}}class B extends L{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const n=e.split(f),s=[];for(let e=0;e<n.length;e++){const i=b(n[e],t);if(s.push(i),"error"===i.type)break}return s})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const n=e.length,s=new Array(n);let i=0;e.forEach((e,r)=>{o(e,!1,e=>{s[r]=e,++i===n&&t(s.join(f))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=$()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let z=!1;try{z="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}const I=z;function O(){}class q extends B{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let n=location.port;n||(n=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}class P extends w{constructor(e,t,n){super(),this.createRequest=e,C(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var e;const t=S(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(e){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{n.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this._opts.cookieJar)||void 0===e||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(e){return void this.setTimeoutFn(()=>{this._onError(e)},0)}"undefined"!=typeof document&&(this._index=P.requestsCount++,P.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=O,e)try{this._xhr.abort()}catch(e){}"undefined"!=typeof document&&delete P.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(P.requestsCount=0,P.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",M);else if("function"==typeof addEventListener){addEventListener("onpagehide"in _?"pagehide":"unload",M,!1)}function M(){for(let e in P.requests)P.requests.hasOwnProperty(e)&&P.requests[e].abort()}const N=function(){const e=j({xdomain:!1});return e&&null!==e.responseType}();function j(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||I))return new XMLHttpRequest}catch(e){}if(!t)try{return new(_[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}const H="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class F extends L{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=H?{}:S(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],s=t===e.length-1;o(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(e){}s&&v(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=$()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const D=_.WebSocket||_.MozWebSocket;const U={websocket:class extends F{createSocket(e,t,n){return H?new D(e,t,n):t?new D(e,t):new D(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends L{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=function(e,t){x||(x=new TextDecoder);const s=[];let i=0,r=-1,o=!1;return new TransformStream({transform(a,c){for(s.push(a);;){if(0===i){if(y(s)<1)break;const e=k(s,1);o=!(128&~e[0]),r=127&e[0],i=r<126?3:126===r?1:2}else if(1===i){if(y(s)<2)break;const e=k(s,2);r=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if(y(s)<8)break;const e=k(s,8),t=new DataView(e.buffer,e.byteOffset,e.length),o=t.getUint32(0);if(o>Math.pow(2,21)-1){c.enqueue(n);break}r=o*Math.pow(2,32)+t.getUint32(4),i=3}else{if(y(s)<r)break;const e=k(s,r);c.enqueue(b(o?e:x.decode(e),t)),i=0}if(0===r||r>e){c.enqueue(n);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),i=m();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const r=()=>{s.read().then(({done:e,value:t})=>{e||(this.onPacket(t),r())}).catch(e=>{})};r();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],s=t===e.length-1;this._writer.write(n).then(()=>{s&&v(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends q{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=N&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new P(j,this.uri(),e)}}},V=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,W=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function K(e){if(e.length>8e3)throw"URI too long";const t=e,n=e.indexOf("["),s=e.indexOf("]");-1!=n&&-1!=s&&(e=e.substring(0,n)+e.substring(n,s).replace(/:/g,";")+e.substring(s,e.length));let i=V.exec(e||""),r={},o=14;for(;o--;)r[W[o]]=i[o]||"";return-1!=n&&-1!=s&&(r.source=t,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=function(e,t){const n=/\/{2,9}/g,s=t.replace(n,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||s.splice(0,1);"/"==t.slice(-1)&&s.splice(s.length-1,1);return s}(0,r.path),r.queryKey=function(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,s){t&&(n[t]=s)}),n}(0,r.query),r}const Y="function"==typeof addEventListener&&"function"==typeof removeEventListener,Q=[];Y&&addEventListener("offline",()=>{Q.forEach(e=>e())},!1);class Z extends w{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const n=K(e);t.hostname=n.host,t.secure="https"===n.protocol||"wss"===n.protocol,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=K(t.host).host);C(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{const t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},n=e.split("&");for(let e=0,s=n.length;e<s;e++){let s=n[e].split("=");t[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return t}(this.opts.query)),Y&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Q.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&Z.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",Z.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const n=this.writeBuffer[t].data;if(n&&(e+=A(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,v(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,s){if("function"==typeof t&&(s=t,t=void 0),"function"==typeof n&&(s=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const i={type:e,data:t,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),s&&this.once("flush",s),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(Z.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Y&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=Q.indexOf(this._offlineEventListener);-1!==e&&Q.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}Z.protocol=4;class X extends Z{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;Z.priorWebsocketSuccess=!1;const s=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!n)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Z.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(l(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function i(){n||(n=!0,l(),t.close(),t=null)}const r=e=>{const n=new Error("probe error: "+e);n.transport=t.name,i(),this.emitReserved("upgradeError",n)};function o(){r("transport closed")}function a(){r("socket closed")}function c(e){t&&e.name!==t.name&&i()}const l=()=>{t.removeListener("open",s),t.removeListener("error",r),t.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};t.once("open",s),t.once("error",r),t.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}let J=class extends X{constructor(e,t={}){const n="object"==typeof e?e:t;(!n.transports||n.transports&&"string"==typeof n.transports[0])&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(e=>U[e]).filter(e=>!!e)),super(e,n)}};const G="function"==typeof ArrayBuffer,ee=Object.prototype.toString,te="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===ee.call(Blob),ne="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===ee.call(File);function se(e){return G&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||te&&e instanceof Blob||ne&&e instanceof File}function ie(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(ie(e[t]))return!0;return!1}if(se(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return ie(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&ie(e[t]))return!0;return!1}function re(e){const t=[],n=e.data,s=e;return s.data=oe(n,t),s.attachments=t.length,{packet:s,buffers:t}}function oe(e,t){if(!e)return e;if(se(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){const n=new Array(e.length);for(let s=0;s<e.length;s++)n[s]=oe(e[s],t);return n}if("object"==typeof e&&!(e instanceof Date)){const n={};for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=oe(e[s],t));return n}return e}function ae(e,t){return e.data=ce(e.data,t),delete e.attachments,e}function ce(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=ce(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=ce(e[n],t));return e}const le=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var he;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(he||(he={}));class pe extends w{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===he.BINARY_EVENT;n||t.type===he.BINARY_ACK?(t.type=n?he.EVENT:he.ACK,this.reconstructor=new de(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!se(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(void 0===he[n.type])throw new Error("unknown packet type "+n.type);if(n.type===he.BINARY_EVENT||n.type===he.BINARY_ACK){const s=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const i=e.substring(s,t);if(i!=Number(i)||"-"!==e.charAt(t))throw new Error("Illegal attachments");n.attachments=Number(i)}if("/"===e.charAt(t+1)){const s=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}n.nsp=e.substring(s,t)}else n.nsp="/";const s=e.charAt(t+1);if(""!==s&&Number(s)==s){const s=t+1;for(;++t;){const n=e.charAt(t);if(null==n||Number(n)!=n){--t;break}if(t===e.length)break}n.id=Number(e.substring(s,t+1))}if(e.charAt(++t)){const s=this.tryParse(e.substr(t));if(!pe.isPayloadValid(n.type,s))throw new Error("invalid payload");n.data=s}return n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case he.CONNECT:return be(t);case he.DISCONNECT:return void 0===t;case he.CONNECT_ERROR:return"string"==typeof t||be(t);case he.EVENT:case he.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===le.indexOf(t[0]));case he.ACK:case he.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class de{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=ae(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function be(e){return"[object Object]"===Object.prototype.toString.call(e)}var ue=Object.freeze({__proto__:null,Decoder:pe,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==he.EVENT&&e.type!==he.ACK||!ie(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===he.EVENT?he.BINARY_EVENT:he.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==he.BINARY_EVENT&&e.type!==he.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=re(e),n=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(n),s}},get PacketType(){return he}});function ge(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const fe=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class me extends w{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[ge(e,"open",this.onopen.bind(this)),ge(e,"packet",this.onpacket.bind(this)),ge(e,"error",this.onerror.bind(this)),ge(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,s,i;if(fe.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const r={type:he.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),r.id=e}const o=null===(s=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===s?void 0:s.writable,a=this.connected&&!(null===(i=this.io.engine)||void 0===i?void 0:i._hasPingExpired());return this.flags.volatile&&!o||(a?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,t){var n;const s=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===s)return void(this.acks[e]=t);const i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},s),r=(...e)=>{this.io.clearTimeoutFn(i),t.apply(this,e)};r.withError=!0,this.acks[e]=r}emitWithAck(e,...t){return new Promise((n,s)=>{const i=(e,t)=>e?s(e):n(t);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...s)=>{this._queue[0];return null!==e?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...s)),n.pending=!1,this._drainQueue()}),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:he.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case he.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case he.EVENT:case he.BINARY_EVENT:this.onevent(e);break;case he.ACK:case he.BINARY_ACK:this.onack(e);break;case he.DISCONNECT:this.ondisconnect();break;case he.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...s){n||(n=!0,t.packet({type:he.ACK,id:e,data:s}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:he.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function xe(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}xe.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+n:e-n}return 0|Math.min(e,this.max)},xe.prototype.reset=function(){this.attempts=0},xe.prototype.setMin=function(e){this.ms=e},xe.prototype.setMax=function(e){this.max=e},xe.prototype.setJitter=function(e){this.jitter=e};class ye extends w{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,C(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=t.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new xe({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const s=t.parser||ue;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new J(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const s=ge(t,"open",function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},r=ge(t,"error",i);if(!1!==this._timeout){const e=this._timeout,n=this.setTimeoutFn(()=>{s(),i(new Error("timeout")),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(s),this.subs.push(r),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(ge(e,"ping",this.onping.bind(this)),ge(e,"data",this.ondata.bind(this)),ge(e,"error",this.onerror.bind(this)),ge(e,"close",this.onclose.bind(this)),ge(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){v(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new me(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),null===(n=this.engine)||void 0===n||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const ke={};function we(e,t){"object"==typeof e&&(t=e,e=void 0);const n=function(e,t="",n){let s=e;n=n||"undefined"!=typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==n?n.protocol+"//"+e:"https://"+e),s=K(e)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const i=-1!==s.host.indexOf(":")?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+i+":"+s.port+t,s.href=s.protocol+"://"+i+(n&&n.port===s.port?"":":"+s.port),s}(e,(t=t||{}).path||"/socket.io"),s=n.source,i=n.id,r=n.path,o=ke[i]&&r in ke[i].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new ye(s,t):(ke[i]||(ke[i]=new ye(s,t)),a=ke[i]),n.query&&!t.query&&(t.query=n.queryKey),a.socket(n.path,t)}function ve(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}Object.assign(we,{Manager:ye,Socket:me,io:we,connect:we});var _e={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};function Se(e){_e=e}var Ee={exec:()=>null};function Te(e,t=""){let n="string"==typeof e?e:e.source,s={replace:(e,t)=>{let i="string"==typeof t?t:t.source;return i=i.replace(Ae.caret,"$1"),n=n.replace(e,i),s},getRegex:()=>new RegExp(n,t)};return s}var Ce=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),Ae={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[\t ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}>`)},$e=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Re=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Le=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Be=Te(Le).replace(/bull/g,Re).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),ze=Te(Le).replace(/bull/g,Re).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Ie=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Oe=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,qe=Te(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Oe).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Pe=Te(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Re).getRegex(),Me="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Ne=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,je=Te("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$))","i").replace("comment",Ne).replace("tag",Me).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),He=Te(Ie).replace("hr",$e).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Me).getRegex(),Fe={blockquote:Te(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",He).getRegex(),code:/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,def:qe,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,hr:$e,html:je,lheading:Be,list:Pe,newline:/^(?:[ \t]*(?:\n|$))+/,paragraph:He,table:Ee,text:/^[^\n]+/},De=Te("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",$e).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3}\t)[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Me).getRegex(),Ue={...Fe,lheading:ze,table:De,paragraph:Te(Ie).replace("hr",$e).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",De).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Me).getRegex()},Ve={...Fe,html:Te("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\s[^'\"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",Ne).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Ee,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Te(Ie).replace("hr",$e).replace("heading"," *#{1,6} *[^\n]").replace("lheading",Be).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},We=/^( {2,}|\\)\n(?!\s*$)/,Ke=/[\p{P}\p{S}]/u,Ye=/[\s\p{P}\p{S}]/u,Qe=/[^\s\p{P}\p{S}]/u,Ze=Te(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Ye).getRegex(),Xe=/(?!~)[\p{P}\p{S}]/u,Je=/(?![*_])[\p{P}\p{S}]/u,Ge=Te(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Ce?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),et=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,tt=Te(et,"u").replace(/punct/g,Ke).getRegex(),nt=Te(et,"u").replace(/punct/g,Xe).getRegex(),st="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",it=Te(st,"gu").replace(/notPunctSpace/g,Qe).replace(/punctSpace/g,Ye).replace(/punct/g,Ke).getRegex(),rt=Te(st,"gu").replace(/notPunctSpace/g,/(?:[^\s\p{P}\p{S}]|~)/u).replace(/punctSpace/g,/(?!~)[\s\p{P}\p{S}]/u).replace(/punct/g,Xe).getRegex(),ot=Te("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Qe).replace(/punctSpace/g,Ye).replace(/punct/g,Ke).getRegex(),at=Te(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Je).getRegex(),ct=Te("^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)","gu").replace(/notPunctSpace/g,/(?:[^\s\p{P}\p{S}]|[*_])/u).replace(/punctSpace/g,/(?![*_])[\s\p{P}\p{S}]/u).replace(/punct/g,Je).getRegex(),lt=Te(/\\(punct)/,"gu").replace(/punct/g,Ke).getRegex(),ht=Te(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),pt=Te(Ne).replace("(?:--\x3e|$)","--\x3e").getRegex(),dt=Te("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",pt).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),bt=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,ut=Te(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",bt).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),gt=Te(/^!?\[(label)\]\[(ref)\]/).replace("label",bt).replace("ref",Oe).getRegex(),ft=Te(/^!?\[(ref)\](?:\[\])?/).replace("ref",Oe).getRegex(),mt=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,xt={_backpedal:Ee,anyPunctuation:lt,autolink:ht,blockSkip:Ge,br:We,code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,del:Ee,delLDelim:Ee,delRDelim:Ee,emStrongLDelim:tt,emStrongRDelimAst:it,emStrongRDelimUnd:ot,escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,link:ut,nolink:ft,punctuation:Ze,reflink:gt,reflinkSearch:Te("reflink|nolink(?!\\()","g").replace("reflink",gt).replace("nolink",ft).getRegex(),tag:dt,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,url:Ee},yt={...xt,link:Te(/^!?\[(label)\]\((.*?)\)/).replace("label",bt).getRegex(),reflink:Te(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",bt).getRegex()},kt={...xt,emStrongRDelimAst:rt,emStrongLDelim:nt,delLDelim:at,delRDelim:ct,url:Te(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",mt).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:Te(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",mt).getRegex()},wt={...kt,br:Te(We).replace("{2,}","*").getRegex(),text:Te(kt.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},vt={normal:Fe,gfm:Ue,pedantic:Ve},_t={normal:xt,gfm:kt,breaks:wt,pedantic:yt},St={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Et=e=>St[e];function Tt(e,t){if(t){if(Ae.escapeTest.test(e))return e.replace(Ae.escapeReplace,Et)}else if(Ae.escapeTestNoEncode.test(e))return e.replace(Ae.escapeReplaceNoEncode,Et);return e}function Ct(e){try{e=encodeURI(e).replace(Ae.percentDecode,"%")}catch{return null}return e}function At(e,t){let n=e.replace(Ae.findPipe,(e,t,n)=>{let s=!1,i=t;for(;--i>=0&&"\\"===n[i];)s=!s;return s?"|":" |"}).split(Ae.splitPipe),s=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;s<n.length;s++)n[s]=n[s].trim().replace(Ae.slashPipe,"|");return n}function $t(e,t,n){let s=e.length;if(0===s)return"";let i=0;for(;i<s;){if(e.charAt(s-i-1)!==t)break;i++}return e.slice(0,s-i)}function Rt(e,t=0){let n=t,s="";for(let t of e)if("\t"===t){let e=4-n%4;s+=" ".repeat(e),n+=e}else s+=t,n++;return s}function Lt(e,t,n,s,i){let r=t.href,o=t.title||null,a=e[1].replace(i.other.outputLinkReplace,"$1");s.state.inLink=!0;let c={type:"!"===e[0].charAt(0)?"image":"link",raw:n,href:r,title:o,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,c}var Bt=class{options;rules;lexer;constructor(e){this.options=e||_e}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let e=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?e:$t(e,"\n")}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let e=t[0],n=function(e,t,n){let s=e.match(n.other.indentCodeCompensation);if(null===s)return t;let i=s[1];return t.split("\n").map(e=>{let t=e.match(n.other.beginningSpace);if(null===t)return e;let[s]=t;return s.length>=i.length?e.slice(i.length):e}).join("\n")}(e,t[3]||"",this.rules);return{type:"code",raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){let t=$t(e,"#");(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:$t(t[0],"\n")}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=$t(t[0],"\n").split("\n"),n="",s="",i=[];for(;e.length>0;){let t,r=!1,o=[];for(t=0;t<e.length;t++)if(this.rules.other.blockquoteStart.test(e[t]))o.push(e[t]),r=!0;else{if(r)break;o.push(e[t])}e=e.slice(t);let a=o.join("\n"),c=a.replace(this.rules.other.blockquoteSetextReplace,"\n $1").replace(this.rules.other.blockquoteSetextReplace2,"");n=n?`${n}\n${a}`:a,s=s?`${s}\n${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(c,i,!0),this.lexer.state.top=l,0===e.length)break;let h=i.at(-1);if("code"===h?.type)break;if("blockquote"===h?.type){let t=h,r=t.raw+"\n"+e.join("\n"),o=this.blockquote(r);i[i.length-1]=o,n=n.substring(0,n.length-t.raw.length)+o.raw,s=s.substring(0,s.length-t.text.length)+o.text;break}if("list"===h?.type){let t=h,r=t.raw+"\n"+e.join("\n"),o=this.list(r);i[i.length-1]=o,n=n.substring(0,n.length-h.raw.length)+o.raw,s=s.substring(0,s.length-t.raw.length)+o.raw,e=r.substring(i.at(-1).raw.length).split("\n");continue}}return{type:"blockquote",raw:n,tokens:i,text:s}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),s=n.length>1,i={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");let r=this.rules.other.listItemRegex(n),o=!1;for(;e;){let n=!1,s="",a="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;s=t[0],e=e.substring(s.length);let c=Rt(t[2].split("\n",1)[0],t[1].length),l=e.split("\n",1)[0],h=!c.trim(),p=0;if(this.options.pedantic?(p=2,a=c.trimStart()):h?p=t[1].length+1:(p=c.search(this.rules.other.nonSpaceChar),p=p>4?1:p,a=c.slice(p),p+=t[1].length),h&&this.rules.other.blankLine.test(l)&&(s+=l+"\n",e=e.substring(l.length+1),n=!0),!n){let t=this.rules.other.nextBulletRegex(p),n=this.rules.other.hrRegex(p),i=this.rules.other.fencesBeginRegex(p),r=this.rules.other.headingBeginRegex(p),o=this.rules.other.htmlBeginRegex(p),d=this.rules.other.blockquoteBeginRegex(p);for(;e;){let b,u=e.split("\n",1)[0];if(l=u,this.options.pedantic?(l=l.replace(this.rules.other.listReplaceNesting," "),b=l):b=l.replace(this.rules.other.tabCharGlobal," "),i.test(l)||r.test(l)||o.test(l)||d.test(l)||t.test(l)||n.test(l))break;if(b.search(this.rules.other.nonSpaceChar)>=p||!l.trim())a+="\n"+b.slice(p);else{if(h||c.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||i.test(c)||r.test(c)||n.test(c))break;a+="\n"+l}h=!l.trim(),s+=u+"\n",e=e.substring(u.length+1),c=b.slice(p)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(s)&&(o=!0)),i.items.push({type:"list_item",raw:s,task:!!this.options.gfm&&this.rules.other.listIsTask.test(a),loose:!1,text:a,tokens:[]}),i.raw+=s}let a=i.items.at(-1);if(!a)return;a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd(),i.raw=i.raw.trimEnd();for(let e of i.items){if(this.lexer.state.top=!1,e.tokens=this.lexer.blockTokens(e.text,[]),e.task){if(e.text=e.text.replace(this.rules.other.listReplaceTask,""),"text"===e.tokens[0]?.type||"paragraph"===e.tokens[0]?.type){e.tokens[0].raw=e.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),e.tokens[0].text=e.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let e=this.lexer.inlineQueue.length-1;e>=0;e--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[e].src)){this.lexer.inlineQueue[e].src=this.lexer.inlineQueue[e].src.replace(this.rules.other.listReplaceTask,"");break}}let t=this.rules.other.listTaskCheckbox.exec(e.raw);if(t){let n={type:"checkbox",raw:t[0]+" ",checked:"[ ]"!==t[0]};e.checked=n.checked,i.loose?e.tokens[0]&&["paragraph","text"].includes(e.tokens[0].type)&&"tokens"in e.tokens[0]&&e.tokens[0].tokens?(e.tokens[0].raw=n.raw+e.tokens[0].raw,e.tokens[0].text=n.raw+e.tokens[0].text,e.tokens[0].tokens.unshift(n)):e.tokens.unshift({type:"paragraph",raw:n.raw,text:n.raw,tokens:[n]}):e.tokens.unshift(n)}}if(!i.loose){let t=e.tokens.filter(e=>"space"===e.type),n=t.length>0&&t.some(e=>this.rules.other.anyLine.test(e.raw));i.loose=n}}if(i.loose)for(let e of i.items){e.loose=!0;for(let t of e.tokens)"text"===t.type&&(t.type="paragraph")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:"html",block:!0,raw:t[0],pre:"pre"===t[1]||"script"===t[1]||"style"===t[1],text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let e=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:e,raw:t[0],href:n,title:s}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=At(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split("\n"):[],r={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===s.length){for(let e of s)this.rules.other.tableAlignRight.test(e)?r.align.push("right"):this.rules.other.tableAlignCenter.test(e)?r.align.push("center"):this.rules.other.tableAlignLeft.test(e)?r.align.push("left"):r.align.push(null);for(let e=0;e<n.length;e++)r.header.push({text:n[e],tokens:this.lexer.inline(n[e]),header:!0,align:r.align[e]});for(let e of i)r.rows.push(At(e,r.header.length).map((e,t)=>({text:e,tokens:this.lexer.inline(e),header:!1,align:r.align[t]})));return r}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:"="===t[2].charAt(0)?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let e="\n"===t[1].charAt(t[1].length-1)?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;let t=$t(e.slice(0,-1),"\\");if((e.length-t.length)%2==0)return}else{let e=function(e,t){if(-1===e.indexOf(t[1]))return-1;let n=0;for(let s=0;s<e.length;s++)if("\\"===e[s])s++;else if(e[s]===t[0])n++;else if(e[s]===t[1]&&(n--,n<0))return s;return n>0?-2:-1}(t[2],"()");if(-2===e)return;if(e>-1){let n=(0===t[0].indexOf("!")?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let n=t[2],s="";if(this.options.pedantic){let e=this.rules.other.pedanticHrefTitle.exec(n);e&&(n=e[1],s=e[3])}else s=t[3]?t[3].slice(1,-1):"";return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(n=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?n.slice(1):n.slice(1,-1)),Lt(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,"$1"),title:s&&s.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let e=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," ").toLowerCase()];if(!e){let e=n[0].charAt(0);return{type:"text",raw:e,text:e}}return Lt(n,e,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||s[3]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!s[1]&&!s[2]||!n||this.rules.inline.punctuation.exec(n))){let n,i,r=[...s[0]].length-1,o=r,a=0,c="*"===s[0][0]?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+r);null!=(s=c.exec(t));){if(n=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!n)continue;if(i=[...n].length,s[3]||s[4]){o+=i;continue}if((s[5]||s[6])&&r%3&&!((r+i)%3)){a+=i;continue}if(o-=i,o>0)continue;i=Math.min(i,i+o+a);let t=[...s[0]][0].length,c=e.slice(0,r+s.index+t+i);if(Math.min(r,i)%2){let e=c.slice(1,-1);return{type:"em",raw:c,text:e,tokens:this.lexer.inlineTokens(e)}}let l=c.slice(2,-2);return{type:"strong",raw:c,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal," "),n=this.rules.other.nonSpaceChar.test(e),s=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&s&&(e=e.substring(1,e.length-1)),{type:"codespan",raw:t[0],text:e}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!n||this.rules.inline.punctuation.exec(n))){let n,i,r=[...s[0]].length-1,o=r,a=this.rules.inline.delRDelim;for(a.lastIndex=0,t=t.slice(-1*e.length+r);null!=(s=a.exec(t));){if(n=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!n||(i=[...n].length,i!==r))continue;if(s[3]||s[4]){o+=i;continue}if(o-=i,o>0)continue;i=Math.min(i,i+o);let t=[...s[0]][0].length,a=e.slice(0,r+s.index+t+i),c=a.slice(r,-r);return{type:"del",raw:a,text:c,tokens:this.lexer.inlineTokens(c)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let e,n;return"@"===t[2]?(e=t[1],n="mailto:"+e):(e=t[1],n=e),{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if("@"===t[2])e=t[0],n="mailto:"+e;else{let s;do{s=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??""}while(s!==t[0]);e=t[0],n="www."===t[1]?"http://"+t[0]:t[0]}return{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let e=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:e}}}},zt=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||_e,this.options.tokenizer=this.options.tokenizer||new Bt,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:Ae,block:vt.normal,inline:_t.normal};this.options.pedantic?(t.block=vt.pedantic,t.inline=_t.pedantic):this.options.gfm&&(t.block=vt.gfm,this.options.breaks?t.inline=_t.breaks:t.inline=_t.gfm),this.tokenizer.rules=t}static get rules(){return{block:vt,inline:_t}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(e){e=e.replace(Ae.carriageReturn,"\n"),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){let t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){for(this.options.pedantic&&(e=e.replace(Ae.tabCharGlobal," ").replace(Ae.spaceLine,""));e;){let s;if(this.options.extensions?.block?.some(n=>!!(s=n.call({lexer:this},e,t))&&(e=e.substring(s.raw.length),t.push(s),!0)))continue;if(s=this.tokenizer.space(e)){e=e.substring(s.raw.length);let n=t.at(-1);1===s.raw.length&&void 0!==n?n.raw+="\n":t.push(s);continue}if(s=this.tokenizer.code(e)){e=e.substring(s.raw.length);let n=t.at(-1);"paragraph"===n?.type||"text"===n?.type?(n.raw+=(n.raw.endsWith("\n")?"":"\n")+s.raw,n.text+="\n"+s.text,this.inlineQueue.at(-1).src=n.text):t.push(s);continue}if(s=this.tokenizer.fences(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.heading(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.hr(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.blockquote(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.list(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.html(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.def(e)){e=e.substring(s.raw.length);let n=t.at(-1);"paragraph"===n?.type||"text"===n?.type?(n.raw+=(n.raw.endsWith("\n")?"":"\n")+s.raw,n.text+="\n"+s.raw,this.inlineQueue.at(-1).src=n.text):this.tokens.links[s.tag]||(this.tokens.links[s.tag]={href:s.href,title:s.title},t.push(s));continue}if(s=this.tokenizer.table(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.lheading(e)){e=e.substring(s.raw.length),t.push(s);continue}let i=e;if(this.options.extensions?.startBlock){let t,n=1/0,s=e.slice(1);this.options.extensions.startBlock.forEach(e=>{t=e.call({lexer:this},s),"number"==typeof t&&t>=0&&(n=Math.min(n,t))}),n<1/0&&n>=0&&(i=e.substring(0,n+1))}if(this.state.top&&(s=this.tokenizer.paragraph(i))){let r=t.at(-1);n&&"paragraph"===r?.type?(r.raw+=(r.raw.endsWith("\n")?"":"\n")+s.raw,r.text+="\n"+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=r.text):t.push(s),n=i.length!==e.length,e=e.substring(s.raw.length);continue}if(s=this.tokenizer.text(e)){e=e.substring(s.raw.length);let n=t.at(-1);"text"===n?.type?(n.raw+=(n.raw.endsWith("\n")?"":"\n")+s.raw,n.text+="\n"+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(s);continue}if(e){let t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n,s=e,i=null;if(this.tokens.links){let e=Object.keys(this.tokens.links);if(e.length>0)for(;null!=(i=this.tokenizer.rules.inline.reflinkSearch.exec(s));)e.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;null!=(i=this.tokenizer.rules.inline.anyPunctuation.exec(s));)s=s.slice(0,i.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;null!=(i=this.tokenizer.rules.inline.blockSkip.exec(s));)n=i[2]?i[2].length:0,s=s.slice(0,i.index+n)+"["+"a".repeat(i[0].length-n-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let r=!1,o="";for(;e;){let n;if(r||(o=""),r=!1,this.options.extensions?.inline?.some(s=>!!(n=s.call({lexer:this},e,t))&&(e=e.substring(n.raw.length),t.push(n),!0)))continue;if(n=this.tokenizer.escape(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.tag(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.link(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(n.raw.length);let s=t.at(-1);"text"===n.type&&"text"===s?.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);continue}if(n=this.tokenizer.emStrong(e,s,o)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.codespan(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.br(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.del(e,s,o)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.autolink(e)){e=e.substring(n.raw.length),t.push(n);continue}if(!this.state.inLink&&(n=this.tokenizer.url(e))){e=e.substring(n.raw.length),t.push(n);continue}let i=e;if(this.options.extensions?.startInline){let t,n=1/0,s=e.slice(1);this.options.extensions.startInline.forEach(e=>{t=e.call({lexer:this},s),"number"==typeof t&&t>=0&&(n=Math.min(n,t))}),n<1/0&&n>=0&&(i=e.substring(0,n+1))}if(n=this.tokenizer.inlineText(i)){e=e.substring(n.raw.length),"_"!==n.raw.slice(-1)&&(o=n.raw.slice(-1)),r=!0;let s=t.at(-1);"text"===s?.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);continue}if(e){let t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}return t}},It=class{options;parser;constructor(e){this.options=e||_e}space(e){return""}code({text:e,lang:t,escaped:n}){let s=(t||"").match(Ae.notSpaceStart)?.[0],i=e.replace(Ae.endingNewline,"")+"\n";return s?'<pre><code class="language-'+Tt(s)+'">'+(n?i:Tt(i,!0))+"</code></pre>\n":"<pre><code>"+(n?i:Tt(i,!0))+"</code></pre>\n"}blockquote({tokens:e}){return`<blockquote>\n${this.parser.parse(e)}</blockquote>\n`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>\n`}hr(e){return"<hr>\n"}list(e){let t=e.ordered,n=e.start,s="";for(let t=0;t<e.items.length;t++){let n=e.items[t];s+=this.listitem(n)}let i=t?"ol":"ul";return"<"+i+(t&&1!==n?' start="'+n+'"':"")+">\n"+s+"</"+i+">\n"}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>\n`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>\n`}table(e){let t="",n="";for(let t=0;t<e.header.length;t++)n+=this.tablecell(e.header[t]);t+=this.tablerow({text:n});let s="";for(let t=0;t<e.rows.length;t++){let i=e.rows[t];n="";for(let e=0;e<i.length;e++)n+=this.tablecell(i[e]);s+=this.tablerow({text:n})}return s&&(s=`<tbody>${s}</tbody>`),"<table>\n<thead>\n"+t+"</thead>\n"+s+"</table>\n"}tablerow({text:e}){return`<tr>\n${e}</tr>\n`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>\n`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${Tt(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let s=this.parser.parseInline(n),i=Ct(e);if(null===i)return s;let r='<a href="'+(e=i)+'"';return t&&(r+=' title="'+Tt(t)+'"'),r+=">"+s+"</a>",r}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let i=Ct(e);if(null===i)return Tt(n);let r=`<img src="${e=i}" alt="${Tt(n)}"`;return t&&(r+=` title="${Tt(t)}"`),r+=">",r}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Tt(e.text)}},Ot=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},qt=class e{options;renderer;textRenderer;constructor(e){this.options=e||_e,this.options.renderer=this.options.renderer||new It,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ot}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){let t="";for(let n=0;n<e.length;n++){let s=e[n];if(this.options.extensions?.renderers?.[s.type]){let e=s,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(!1!==n||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(e.type)){t+=n||"";continue}}let i=s;switch(i.type){case"space":t+=this.renderer.space(i);break;case"hr":t+=this.renderer.hr(i);break;case"heading":t+=this.renderer.heading(i);break;case"code":t+=this.renderer.code(i);break;case"table":t+=this.renderer.table(i);break;case"blockquote":t+=this.renderer.blockquote(i);break;case"list":t+=this.renderer.list(i);break;case"checkbox":t+=this.renderer.checkbox(i);break;case"html":t+=this.renderer.html(i);break;case"def":t+=this.renderer.def(i);break;case"paragraph":t+=this.renderer.paragraph(i);break;case"text":t+=this.renderer.text(i);break;default:{let e='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return t}parseInline(e,t=this.renderer){let n="";for(let s=0;s<e.length;s++){let i=e[s];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(!1!==e||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(i.type)){n+=e||"";continue}}let r=i;switch(r.type){case"escape":case"text":n+=t.text(r);break;case"html":n+=t.html(r);break;case"link":n+=t.link(r);break;case"image":n+=t.image(r);break;case"checkbox":n+=t.checkbox(r);break;case"strong":n+=t.strong(r);break;case"em":n+=t.em(r);break;case"codespan":n+=t.codespan(r);break;case"br":n+=t.br(r);break;case"del":n+=t.del(r);break;default:{let e='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return n}},Pt=class{options;block;constructor(e){this.options=e||_e}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(){return this.block?zt.lex:zt.lexInline}provideParser(){return this.block?qt.parse:qt.parseInline}},Mt=new class{defaults={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=qt;Renderer=It;TextRenderer=Ot;Lexer=zt;Tokenizer=Bt;Hooks=Pt;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let s of e)switch(n=n.concat(t.call(this,s)),s.type){case"table":{let e=s;for(let s of e.header)n=n.concat(this.walkTokens(s.tokens,t));for(let s of e.rows)for(let e of s)n=n.concat(this.walkTokens(e.tokens,t));break}case"list":{let e=s;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=s;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(s=>{let i=e[s].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw new Error("extension name required");if("renderer"in e){let n=t.renderers[e.name];t.renderers[e.name]=n?function(...t){let s=e.renderer.apply(this,t);return!1===s&&(s=n.apply(this,t)),s}:e.renderer}if("tokenizer"in e){if(!e.level||"block"!==e.level&&"inline"!==e.level)throw new Error("extension level must be 'block' or 'inline'");let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&("block"===e.level?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:"inline"===e.level&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}"childTokens"in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new It(this.defaults);for(let n in e.renderer){if(!(n in t))throw new Error(`renderer '${n}' does not exist`);if(["options","parser"].includes(n))continue;let s=n,i=e.renderer[s],r=t[s];t[s]=(...e)=>{let n=i.apply(t,e);return!1===n&&(n=r.apply(t,e)),n||""}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new Bt(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw new Error(`tokenizer '${n}' does not exist`);if(["options","rules","lexer"].includes(n))continue;let s=n,i=e.tokenizer[s],r=t[s];t[s]=(...e)=>{let n=i.apply(t,e);return!1===n&&(n=r.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new Pt;for(let n in e.hooks){if(!(n in t))throw new Error(`hook '${n}' does not exist`);if(["options","block"].includes(n))continue;let s=n,i=e.hooks[s],r=t[s];Pt.passThroughHooks.has(n)?t[s]=e=>{if(this.defaults.async&&Pt.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return r.call(t,n)})();let s=i.call(t,e);return r.call(t,s)}:t[s]=(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return!1===n&&(n=await r.apply(t,e)),n})();let n=i.apply(t,e);return!1===n&&(n=r.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,s=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(s.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return zt.lex(e,t??this.defaults)}parser(e,t){return qt.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let s={...n},i={...this.defaults,...s},r=this.onError(!!i.silent,!!i.async);if(!0===this.defaults.async&&!1===s.async)return r(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||null===t)return r(new Error("marked(): input parameter is undefined or null"));if("string"!=typeof t)return r(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,s=await(i.hooks?await i.hooks.provideLexer():e?zt.lex:zt.lexInline)(n,i),r=i.hooks?await i.hooks.processAllTokens(s):s;i.walkTokens&&await Promise.all(this.walkTokens(r,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser():e?qt.parse:qt.parseInline)(r,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(r);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer():e?zt.lex:zt.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let s=(i.hooks?i.hooks.provideParser():e?qt.parse:qt.parseInline)(n,i);return i.hooks&&(s=i.hooks.postprocess(s)),s}catch(e){return r(e)}}}onError(e,t){return n=>{if(n.message+="\nPlease report this to https://github.com/markedjs/marked.",e){let e="<p>An error occurred:</p><pre>"+Tt(n.message+"",!0)+"</pre>";return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function Nt(e,t){return Mt.parse(e,t)}Nt.options=Nt.setOptions=function(e){return Mt.setOptions(e),Nt.defaults=Mt.defaults,Se(Nt.defaults),Nt},Nt.getDefaults=ve,Nt.defaults=_e,Nt.use=function(...e){return Mt.use(...e),Nt.defaults=Mt.defaults,Se(Nt.defaults),Nt},Nt.walkTokens=function(e,t){return Mt.walkTokens(e,t)},Nt.parseInline=Mt.parseInline,Nt.Parser=qt,Nt.parser=qt.parse,Nt.Renderer=It,Nt.TextRenderer=Ot,Nt.Lexer=zt,Nt.lexer=zt.lex,Nt.Tokenizer=Bt,Nt.Hooks=Pt,Nt.parse=Nt,Nt.options,Nt.setOptions,Nt.use,Nt.walkTokens,Nt.parseInline,qt.parse,zt.lex,Nt.setOptions({breaks:!0,gfm:!0});const jt={chat:'<svg viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>\n </svg>',close:'<svg viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round">\n <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>\n </svg>',send:'<svg viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <line x1="22" y1="2" x2="11" y2="13"/>\n <polygon points="22 2 15 22 11 13 2 9 22 2"/>\n </svg>',bot:'<svg viewBox="0 0 24 24" fill="white">\n <path d="M12 2a2 2 0 0 1 2 2c0 .74-.4 1.39-1 1.73V7h1a7 7 0 0 1 7 7H3a7 7 0 0 1 7-7h1V5.73c-.6-.34-1-.99-1-1.73a2 2 0 0 1 2-2zM7.5 14a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3zm9 0a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3zM3 21v-2h18v2H3z"/>\n </svg>',user:'<svg viewBox="0 0 24 24" fill="white">\n <path d="M12 12c2.7 0 4.8-2.1 4.8-4.8S14.7 2.4 12 2.4 7.2 4.5 7.2 7.2 9.3 12 12 12zm0 2.4c-3.2 0-9.6 1.6-9.6 4.8v2.4h19.2v-2.4c0-3.2-6.4-4.8-9.6-4.8z"/>\n </svg>',shield:'<svg viewBox="0 0 24 24">\n <path d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5l-9-4z"/>\n </svg>',expand:'<svg viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/>\n <line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/>\n </svg>',collapse:'<svg viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <polyline points="4 14 10 14 10 20"/><polyline points="20 10 14 10 14 4"/>\n <line x1="10" y1="14" x2="3" y2="21"/><line x1="21" y1="3" x2="14" y2="10"/>\n </svg>',history:'<svg viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <circle cx="12" cy="12" r="10"/>\n <polyline points="12 6 12 12 16 14"/>\n </svg>',trash:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <polyline points="3 6 5 6 21 6"/>\n <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>\n </svg>',sparkle:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 1l2.4 7.6L22 12l-7.6 2.4L12 22l-2.4-7.6L2 12l7.6-2.4L12 1z"/></svg>',minimize:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><polyline points="4 14 10 14 10 20"/><line x1="21" y1="3" x2="10" y2="14"/></svg>',copy:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>',check:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',thumbUp:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3H14z"/><path d="M7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3"/></svg>',thumbDown:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3H10z"/><path d="M17 2h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17"/></svg>',download:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>'};function Ht(e){return e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}class Ft{constructor(e){this.socket=null,this.messages=[],this.conversationId=null,this.sessionId=null,this.isOpen=!1,this.isTyping=!1,this.isExpanded=!1,this.isHistoryOpen=!1,this.unreadCount=0,this.lastRole=null,this.sessionStorageKey="chatbolt_session_id",this.isWelcomeVisible=!0,this.activeTab="chat",this.conversations=[],this.conversationsKey="chatbolt_conversations",this.activeSessionKey="chatbolt_active_session",this.config=Object.assign({serverUrl:"https://backend-api-chatbolt-backend.hf.space",position:"bottom-right",theme:"auto",accentColor:"#6366f1",placeholder:"Messageโ€ฆ",title:"AI Assistant",subtitle:"Online ยท Powered by XtroEdge",botAvatar:"",triggerIcon:"",triggerText:"",autoOpen:!1,greetingMessage:"Hi there! ๐Ÿ‘‹ How can I help you today?",zIndex:2147483647,conversationId:"",showBranding:!0,gradientEndColor:"",quickReplies:[],welcomeName:"",disclaimerText:""},e),this.config.conversationId&&(this.conversationId=this.config.conversationId),this.buildDOM(),this.applyTheme(),this.connectSocket(),this.restoreMessagesFromHistory(),this.config.autoOpen?setTimeout(()=>this.open(),600):0===this.messages.length&&this.config.greetingMessage&&this.addMessage("assistant",this.config.greetingMessage,!0)}buildDOM(){this.ensureStyles(),this.container=document.createElement("div"),this.container.className=`cb-widget cb-pos-${this.config.position}`;const e=this.config.accentColor.replace("#",""),t=parseInt(e.slice(0,2),16),n=parseInt(e.slice(2,4),16),s=parseInt(e.slice(4,6),16),i=`${t},${n},${s}`;this.container.style.setProperty("--cb-accent",this.config.accentColor),this.container.style.setProperty("--cb-accent-rgb",i);const r=this.config.gradientEndColor?this.config.gradientEndColor.replace("#",""):null,o=r?parseInt(r.slice(0,2),16):t,a=r?parseInt(r.slice(2,4),16):Math.max(0,n-20),c=r?parseInt(r.slice(4,6),16):Math.min(255,s+20);this.container.style.setProperty("--cb-grad",`linear-gradient(135deg, rgba(${i},1) 0%, rgba(${o},${a},${c},1) 100%)`),this.container.style.setProperty("--cb-grad-soft",`linear-gradient(135deg, rgba(${i},0.82) 0%, rgba(${o},${a},${c},0.68) 100%)`),this.container.style.setProperty("--cb-accent-glow",`rgba(${i},0.35)`),this.container.style.setProperty("--cb-accent-ring",`rgba(${i},0.18)`),this.container.style.setProperty("--cb-z",String(this.config.zIndex));const l=this.config.botAvatar?`<img src="${this.config.botAvatar}" alt="bot">`:jt.bot,h=this.config.welcomeName||"there",p=(this.config.quickReplies||[]).map(e=>`<button class="cb-quick-reply-btn">${this.esc(e)}</button>`).join(""),d=this.config.title.match(/^(.+?)\s*AI\b/i),b=d?d[1].toUpperCase():this.config.title.toUpperCase();let u="";this.config.disclaimerText?u=`<div class="cb-disclaimer">${this.esc(this.config.disclaimerText)}</div>`:!1!==this.config.showBranding&&(u='<div class="cb-footer"><span class="cb-footer-dot"></span> Powered by <a href="#" target="_blank" rel="noopener">ChatBolt</a></div>'),this.container.innerHTML=`\n <button class="cb-trigger" aria-label="Open chat">\n <span class="cb-icon-chat">${jt.chat}</span>\n <span class="cb-icon-close">${jt.close}</span>\n <span class="cb-trigger-text">${this.esc(this.config.triggerText||this.config.title||"Chat")}</span>\n <span class="cb-badge" style="display:none">0</span>\n </button>\n\n <div class="cb-window cb-hidden" role="dialog" aria-label="${this.esc(this.config.title)} chat">\n \x3c!-- Tab Bar --\x3e\n <div class="cb-tab-bar">\n <div class="cb-tabs">\n <button class="cb-tab cb-active" data-tab="chat">Chat</button>\n <button class="cb-tab" data-tab="history">History</button>\n </div>\n <div class="cb-tab-actions">\n <button class="cb-tab-action-btn cb-new-chat-btn" aria-label="New Chat">\n <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>\n </button>\n <button class="cb-export-btn" aria-label="Export Chat">\n <span class="cb-tooltip">Export PDF</span>\n ${jt.download}\n </button>\n <button class="cb-tab-action-btn cb-close-btn" aria-label="Close">${jt.close}</button>\n </div>\n </div>\n\n \x3c!-- Welcome / Landing Page --\x3e\n <div class="cb-welcome">\n <div class="cb-welcome-logo">\n <span class="cb-welcome-logo-icon">${jt.sparkle}</span>\n <span class="cb-welcome-logo-text">${this.esc(b)}</span>\n <span class="cb-welcome-logo-badge">AI</span>\n </div>\n <div class="cb-welcome-greeting">Hello ${this.esc(h)} ๐Ÿ‘‹</div>\n <div class="cb-welcome-subtitle">How can I help you today?</div>\n ${p?`<div class="cb-quick-replies">${p}</div>`:""}\n </div>\n\n \x3c!-- Chat Messages (hidden initially) --\x3e\n <div class="cb-messages" role="log" aria-live="polite" style="display:none"></div>\n\n \x3c!-- History Panel (tab-based) --\x3e\n <div class="cb-history-panel">\n <div class="cb-history-panel-header">\n <div class="cb-welcome-logo">\n <span class="cb-welcome-logo-icon">${jt.sparkle}</span>\n <span class="cb-welcome-logo-text">${this.esc(b)}</span>\n <span class="cb-welcome-logo-badge">AI</span>\n </div>\n <div class="cb-history-panel-title">Chat History</div>\n <div class="cb-history-panel-subtitle">Your previous conversations</div>\n </div>\n <div class="cb-history-section-header">\n <span class="cb-history-count">Recent Chats</span>\n <button class="cb-history-clear-btn">${jt.trash} Clear All</button>\n </div>\n <div class="cb-history-list"></div>\n </div>\n\n \x3c!-- Input Area --\x3e\n <div class="cb-input-area">\n <div class="cb-input-wrap">\n <textarea class="cb-input" rows="1"\n placeholder="${this.esc(this.config.placeholder)}"\n aria-label="Message input"></textarea>\n </div>\n <button class="cb-send-btn" aria-label="Send">${jt.send}</button>\n </div>\n\n ${u}\n </div>\n `,document.body.appendChild(this.container),this.trigger=this.container.querySelector(".cb-trigger"),this.window=this.container.querySelector(".cb-window"),this.messagesEl=this.container.querySelector(".cb-messages"),this.inputEl=this.container.querySelector(".cb-input"),this.sendBtn=this.container.querySelector(".cb-send-btn"),this.badgeEl=this.container.querySelector(".cb-badge"),this.expandBtn=this.container.querySelector(".cb-expand-btn"),this.welcomeEl=this.container.querySelector(".cb-welcome"),this.historyPanel=this.container.querySelector(".cb-history-panel"),this.historyList=this.container.querySelector(".cb-history-list"),this.chatTabBtn=this.container.querySelector('.cb-tab[data-tab="chat"]'),this.historyTabBtn=this.container.querySelector('.cb-tab[data-tab="history"]'),this.historyDrawer=this.historyPanel,this.closeHistoryBtn=null,this.clearHistoryBtn=this.container.querySelector(".cb-history-clear-btn"),this.historyBtn=this.historyTabBtn,this.typingEl=document.createElement("div"),this.typingEl.className="cb-typing-wrap",this.typingEl.innerHTML=`\n <div class="cb-msg-avatar">${l}</div>\n <div class="cb-typing"><span></span><span></span><span></span></div>`,this.trigger.addEventListener("click",()=>this.toggle()),this.container.querySelector(".cb-close-btn").addEventListener("click",()=>this.close()),this.container.querySelector(".cb-new-chat-btn").addEventListener("click",()=>this.startNewChat()),this.container.querySelector(".cb-export-btn").addEventListener("click",()=>this.exportChatPDF()),this.expandBtn&&this.expandBtn.addEventListener("click",()=>this.toggleExpand()),this.chatTabBtn.addEventListener("click",()=>this.switchTab("chat")),this.historyTabBtn.addEventListener("click",()=>this.switchTab("history")),this.clearHistoryBtn&&this.clearHistoryBtn.addEventListener("click",()=>this.clearHistory()),this.container.querySelectorAll(".cb-quick-reply-btn").forEach(e=>{e.addEventListener("click",()=>{var t;const n=null===(t=e.textContent)||void 0===t?void 0:t.trim();n&&(this.hideWelcome(),this.send(n))})}),this.sendBtn.addEventListener("click",()=>this.send()),this.inputEl.addEventListener("keydown",e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),this.send())}),this.inputEl.addEventListener("input",()=>this.autoResize()),this.loadHistory()}ensureStyles(){if("undefined"==typeof document)return;if(document.getElementById("cb-widget-style"))return;const e=document.createElement("style");e.id="cb-widget-style",e.textContent="\n/* ChatBolt Widget โ€” Premium Clean Design */\n@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');\n\n.cb-widget {\n --cb-accent: #6366f1;\n --cb-accent-rgb: 99,102,241;\n --cb-accent-glow: rgba(99,102,241,0.32);\n --cb-accent-ring: rgba(99,102,241,0.16);\n --cb-grad: linear-gradient(135deg, rgba(99,102,241,1) 0%, rgba(139,92,246,1) 100%);\n --cb-grad-soft: linear-gradient(135deg, rgba(99,102,241,0.9) 0%, rgba(139,92,246,0.8) 100%);\n\n --cb-window-bg: #ffffff;\n --cb-text: #111827;\n --cb-text-2: #4B5563;\n --cb-text-3: #9CA3AF;\n --cb-msg-bot-bg: #F3F4F6;\n --cb-msg-bot-bd: transparent;\n --cb-input-bg: #ffffff;\n --cb-input-bd: #E5E7EB;\n --cb-divider: #F3F4F6;\n --cb-z: 2147483647;\n\n font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;\n font-size: 14px;\n line-height: 1.5;\n color: var(--cb-text);\n}\n.cb-widget * { box-sizing: border-box; margin: 0; padding: 0; }\n\n.cb-widget.cb-dark {\n --cb-window-bg: #111827;\n --cb-text: #F9FAFB;\n --cb-text-2: #9CA3AF;\n --cb-text-3: #6B7280;\n --cb-msg-bot-bg: #1F2937;\n --cb-msg-bot-bd: transparent;\n --cb-input-bg: #1F2937;\n --cb-input-bd: #374151;\n --cb-divider: #1F2937;\n}\n\n.cb-trigger {\n position: fixed;\n padding: 12px 20px 12px 16px;\n border-radius: 30px;\n background: var(--cb-grad);\n border: none;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 10px;\n z-index: var(--cb-z);\n outline: none;\n transition: transform .3s cubic-bezier(.34,1.56,.64,1), box-shadow .3s ease, border-radius .3s ease, padding .3s ease;\n box-shadow:\n 0 6px 24px var(--cb-accent-glow),\n 0 2px 8px rgba(0,0,0,0.14),\n inset 0 1px 0 rgba(255,255,255,0.28);\n}\n.cb-trigger::after {\n content: '';\n position: absolute;\n inset: 0;\n border-radius: 30px;\n background: linear-gradient(145deg, rgba(255,255,255,0.25) 0%, transparent 55%);\n pointer-events: none;\n}\n.cb-trigger:hover {\n transform: scale(1.04);\n box-shadow:\n 0 8px 28px var(--cb-accent-glow),\n 0 2px 8px rgba(0,0,0,0.12);\n}\n.cb-trigger:active { transform: scale(0.95); }\n.cb-trigger svg {\n width: 22px; height: 22px; fill: none;\n stroke: white; stroke-width: 2;\n stroke-linecap: round; stroke-linejoin: round;\n position: relative; z-index: 1;\n flex-shrink: 0;\n transition: opacity .25s, transform .35s cubic-bezier(.34,1.56,.64,1);\n}\n.cb-trigger-text {\n color: white;\n font-family: 'Inter', sans-serif;\n font-size: 15px;\n font-weight: 600;\n white-space: nowrap;\n position: relative;\n z-index: 1;\n letter-spacing: 0.3px;\n}\n.cb-trigger .cb-icon-chat { opacity: 1; transform: scale(1) rotate(0deg); }\n.cb-trigger .cb-icon-close { opacity: 0; transform: scale(0.4) rotate(-90deg); position: absolute; }\n.cb-trigger.cb-open { opacity: 0; pointer-events: none; transform: scale(0.5); }\n.cb-pos-bottom-right .cb-trigger { bottom: 24px; right: 24px; }\n.cb-pos-bottom-left .cb-trigger { bottom: 24px; left: 24px; }\n.cb-pos-top-right .cb-trigger { top: 24px; right: 24px; }\n.cb-pos-top-left .cb-trigger { top: 24px; left: 24px; }\n\n.cb-badge {\n position: absolute;\n top: -2px; right: -2px;\n background: linear-gradient(135deg, #ef4444, #f97316);\n color: white;\n font-size: 10px; font-weight: 700;\n min-width: 20px; height: 20px;\n border-radius: 10px;\n display: flex; align-items: center; justify-content: center;\n padding: 0 5px;\n border: 2px solid white;\n z-index: 2;\n animation: cb-badge-in .4s cubic-bezier(.34,1.56,.64,1) both;\n}\n@keyframes cb-badge-in { from { transform: scale(0) rotate(-20deg); } to { transform: scale(1) rotate(0); } }\n\n.cb-window {\n position: fixed;\n width: 420px;\n top: 0;\n bottom: 0;\n background: var(--cb-window-bg);\n border-radius: 0;\n border-left: 1px solid rgba(0,0,0,0.08);\n box-shadow:\n -8px 0 32px rgba(0,0,0,0.10),\n -2px 0 8px rgba(0,0,0,0.04);\n display: flex;\n flex-direction: column;\n overflow: hidden;\n z-index: calc(var(--cb-z) - 1);\n transition: opacity .3s cubic-bezier(.4,0,.2,1),\n transform .35s cubic-bezier(.4,0,.2,1),\n width .35s cubic-bezier(.4,0,.2,1);\n}\n.cb-widget.cb-dark .cb-window {\n border-color: rgba(255,255,255,0.08);\n box-shadow:\n -8px 0 32px rgba(0,0,0,0.4),\n -2px 0 8px rgba(0,0,0,0.2);\n}\n.cb-window.cb-hidden {\n opacity: 0;\n pointer-events: none;\n transform: translateX(100%);\n}\n.cb-pos-bottom-right .cb-window { right: 0; }\n.cb-pos-bottom-left .cb-window { left: 0; right: auto; border-left: none; border-right: 1px solid rgba(0,0,0,0.08); box-shadow: 8px 0 32px rgba(0,0,0,0.10); }\n.cb-pos-bottom-left .cb-window.cb-hidden { transform: translateX(-100%); }\n.cb-pos-top-right .cb-window { right: 0; }\n.cb-pos-top-left .cb-window { left: 0; right: auto; border-left: none; border-right: 1px solid rgba(0,0,0,0.08); }\n\n.cb-window.cb-expanded {\n width: min(720px, 50dvw) !important;\n}\n.cb-window.cb-expanded.cb-hidden {\n opacity: 0;\n pointer-events: none;\n transform: translateX(100%) !important;\n}\n\n.cb-header {\n flex-shrink: 0;\n height: 68px;\n padding: 0 16px;\n display: flex;\n align-items: center;\n gap: 12px;\n background: var(--cb-grad);\n position: relative;\n overflow: hidden;\n}\n.cb-header-blob2 {\n display: none;\n}\n.cb-header::after {\n content: '';\n position: absolute; bottom: 0; left: 0; right: 0; height: 1px;\n background: rgba(255,255,255,0.12);\n pointer-events: none;\n}\n.cb-header-avatar {\n width: 40px; height: 40px;\n border-radius: 50%;\n background: rgba(255,255,255,0.2);\n border: 2px solid rgba(255,255,255,0.35);\n display: flex; align-items: center; justify-content: center;\n flex-shrink: 0; overflow: hidden;\n box-shadow: 0 2px 8px rgba(0,0,0,0.15);\n position: relative; z-index: 1;\n}\n.cb-header-avatar img { width: 100%; height: 100%; object-fit: cover; }\n.cb-header-avatar svg { width: 22px; height: 22px; fill: white; }\n.cb-header-info { flex: 1; min-width: 0; position: relative; z-index: 1; }\n.cb-header-title {\n font-size: 15px; font-weight: 600;\n color: white; letter-spacing: -0.01em;\n white-space: nowrap; overflow: hidden; text-overflow: ellipsis;\n}\n.cb-header-status {\n display: flex; align-items: center; gap: 6px; margin-top: 3px;\n}\n.cb-status-dot {\n width: 7px; height: 7px; border-radius: 50%;\n background: #4ade80;\n box-shadow: 0 0 4px rgba(74,222,128,0.6);\n position: relative; flex-shrink: 0;\n}\n.cb-header-subtitle {\n font-size: 11px; color: rgba(255,255,255,0.72); font-weight: 500;\n white-space: nowrap; overflow: hidden; text-overflow: ellipsis;\n}\n.cb-header-actions {\n display: flex; align-items: center; gap: 6px;\n position: relative; z-index: 1; flex-shrink: 0;\n}\n.cb-close-btn,\n.cb-expand-btn {\n width: 32px; height: 32px; border-radius: 50%;\n background: rgba(255,255,255,0.14);\n border: none;\n cursor: pointer; display: flex; align-items: center; justify-content: center;\n transition: background .2s, transform .2s;\n position: relative;\n}\n.cb-close-btn:hover,\n.cb-expand-btn:hover { background: rgba(255,255,255,0.25); transform: scale(1.05); }\n.cb-close-btn svg { width: 14px; height: 14px; stroke: white; stroke-width: 2.5; fill: none; stroke-linecap: round; }\n.cb-expand-btn .cb-icon-expand { display: flex; }\n.cb-expand-btn .cb-icon-collapse { display: none; }\n.cb-expand-btn.cb-expanded .cb-icon-expand { display: none; }\n.cb-expand-btn.cb-expanded .cb-icon-collapse { display: flex; }\n.cb-expand-btn svg { width: 14px; height: 14px; stroke: white; stroke-width: 2; fill: none; stroke-linecap: round; }\n\n.cb-history-btn {\n width: 32px; height: 32px; border-radius: 50%;\n background: rgba(255,255,255,0.14);\n border: none;\n cursor: pointer; display: flex; align-items: center; justify-content: center;\n transition: background .2s, transform .2s;\n position: relative;\n}\n.cb-history-btn:hover { background: rgba(255,255,255,0.25); transform: scale(1.05); }\n.cb-history-btn svg { width: 14px; height: 14px; stroke: white; stroke-width: 2; fill: none; stroke-linecap: round; }\n\n.cb-history-drawer {\n position: absolute;\n top: 0;\n right: 0;\n width: 320px;\n height: 100%;\n background: var(--cb-window-bg);\n border-left: 1.5px solid var(--cb-divider);\n box-shadow: -4px 0 24px rgba(0,0,0,0.12);\n display: flex;\n flex-direction: column;\n transform: translateX(100%);\n transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), width 0.3s cubic-bezier(0.4, 0, 0.2, 1);\n z-index: 10;\n}\n.cb-window.cb-expanded .cb-history-drawer {\n width: 420px;\n}\n.cb-history-drawer.cb-open {\n transform: translateX(0);\n}\n\n.cb-history-header {\n height: 68px;\n padding: 0 16px;\n border-bottom: none;\n display: flex;\n align-items: center;\n justify-content: space-between;\n background: var(--cb-grad);\n position: relative;\n overflow: hidden;\n flex-shrink: 0;\n}\n.cb-history-header::after {\n content: '';\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n height: 1px;\n background: rgba(255,255,255,0.12);\n pointer-events: none;\n}\n.cb-history-title {\n font-size: 16px;\n font-weight: 700;\n color: white;\n letter-spacing: -0.02em;\n position: relative;\n z-index: 1;\n text-shadow: 0 1px 2px rgba(0,0,0,0.1);\n}\n.cb-history-actions {\n display: flex;\n gap: 8px;\n align-items: center;\n position: relative;\n z-index: 1;\n}\n.cb-clear-history-btn {\n width: 32px;\n height: 32px;\n background: rgba(255, 255, 255, 0.14);\n border: none;\n border-radius: 50%;\n color: white;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all .2s;\n}\n.cb-clear-history-btn:hover {\n background: rgba(255, 255, 255, 0.25);\n transform: scale(1.05);\n}\n.cb-clear-history-btn svg {\n width: 16px;\n height: 16px;\n stroke: white;\n}\n.cb-close-history-btn {\n width: 32px;\n height: 32px;\n background: rgba(255, 255, 255, 0.14);\n border: none;\n border-radius: 50%;\n color: white;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all .2s;\n}\n.cb-close-history-btn:hover {\n background: rgba(255, 255, 255, 0.25);\n transform: scale(1.05);\n}\n.cb-close-history-btn svg {\n width: 16px;\n height: 16px;\n stroke: white;\n}\n\n.cb-history-list {\n flex: 1;\n overflow-y: auto;\n padding: 16px;\n display: flex;\n flex-direction: column;\n gap: 10px;\n background: linear-gradient(180deg, var(--cb-window-bg) 0%, rgba(var(--cb-accent-rgb), 0.02) 100%);\n}\n.cb-history-list::-webkit-scrollbar { width: 4px; }\n.cb-history-list::-webkit-scrollbar-track { background: transparent; }\n.cb-history-list::-webkit-scrollbar-thumb {\n background: rgba(var(--cb-accent-rgb), 0.25);\n border-radius: 2px;\n}\n.cb-history-list::-webkit-scrollbar-thumb:hover {\n background: rgba(var(--cb-accent-rgb), 0.4);\n}\n\n.cb-history-item {\n padding: 12px 14px;\n background: var(--cb-window-bg);\n border-radius: 12px;\n cursor: pointer;\n transition: all .25s cubic-bezier(.4,0,.2,1);\n border: 1.5px solid var(--cb-divider);\n box-shadow: 0 1px 3px rgba(0,0,0,0.05);\n}\n.cb-history-item:hover {\n background: var(--cb-msg-bot-bg);\n border-color: rgba(var(--cb-accent-rgb), 0.35);\n transform: translateY(-1px);\n box-shadow: 0 4px 12px rgba(var(--cb-accent-rgb), 0.12);\n}\n.cb-history-item-role {\n font-size: 10px;\n font-weight: 700;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-bottom: 6px;\n display: inline-block;\n padding: 2px 8px;\n border-radius: 4px;\n}\n.cb-history-item[data-role=\"user\"] .cb-history-item-role {\n background: rgba(var(--cb-accent-rgb), 0.12);\n color: var(--cb-accent);\n}\n.cb-history-item[data-role=\"assistant\"] .cb-history-item-role {\n background: rgba(16, 185, 129, 0.12);\n color: #10b981;\n}\n.cb-history-item-content {\n font-size: 13px;\n color: var(--cb-text);\n line-height: 1.6;\n white-space: normal;\n word-wrap: break-word;\n overflow-wrap: break-word;\n max-width: 100%;\n margin-bottom: 6px;\n display: -webkit-box;\n -webkit-line-clamp: 3;\n -webkit-box-orient: vertical;\n overflow: hidden;\n}\n.cb-history-item-time {\n font-size: 10px;\n color: var(--cb-text-3);\n font-weight: 500;\n display: flex;\n align-items: center;\n gap: 4px;\n}\n.cb-history-item-time::before {\n content: '๐Ÿ•’';\n font-size: 9px;\n}\n\n.cb-history-empty {\n flex: 1;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n color: var(--cb-text-3);\n font-size: 13px;\n text-align: center;\n padding: 40px 20px;\n}\n.cb-history-empty::before {\n content: '๐Ÿ“';\n font-size: 48px;\n margin-bottom: 12px;\n opacity: 0.4;\n}\n\n.cb-messages {\n flex: 1;\n overflow-y: auto;\n padding: 16px 14px 10px;\n display: flex; flex-direction: column;\n gap: 2px;\n scroll-behavior: smooth;\n background: var(--cb-window-bg);\n position: relative;\n}\n.cb-messages::-webkit-scrollbar { width: 3px; }\n.cb-messages::-webkit-scrollbar-track { background: transparent; }\n.cb-messages::-webkit-scrollbar-thumb {\n background: rgba(var(--cb-accent-rgb), 0.18);\n border-radius: 2px;\n}\n.cb-msg {\n display: flex; gap: 10px; align-items: flex-end;\n max-width: 85%;\n animation: cb-msg-in .3s cubic-bezier(.34,1.56,.64,1) both;\n}\n@keyframes cb-msg-in {\n from { opacity: 0; transform: translateY(12px) scale(0.96); }\n to { opacity: 1; transform: translateY(0) scale(1); }\n}\n.cb-msg.cb-user { align-self: flex-end; flex-direction: row-reverse; }\n.cb-msg.cb-bot { align-self: flex-start; }\n.cb-msg.cb-first-in-group { margin-top: 14px; }\n.cb-msg-avatar {\n width: 30px; height: 30px; border-radius: 50%;\n display: flex; align-items: center; justify-content: center;\n flex-shrink: 0; overflow: hidden;\n}\n.cb-msg.cb-bot .cb-msg-avatar {\n background: var(--cb-grad);\n box-shadow: 0 2px 8px var(--cb-accent-glow);\n}\n.cb-msg.cb-user .cb-msg-avatar {\n background: var(--cb-grad);\n box-shadow: 0 2px 8px var(--cb-accent-glow);\n}\n.cb-msg.cb-grouped .cb-msg-avatar { visibility: hidden; }\n.cb-msg-avatar img { width: 100%; height: 100%; object-fit: cover; }\n.cb-msg-avatar svg { width: 17px; height: 17px; fill: white; }\n.cb-msg-content { display: flex; flex-direction: column; gap: 4px; min-width: 0; }\n.cb-msg-bubble {\n padding: 10px 14px;\n border-radius: 18px;\n font-size: 13.5px; line-height: 1.55;\n white-space: pre-wrap; word-break: break-word;\n}\n.cb-msg.cb-bot .cb-msg-bubble {\n background: var(--cb-msg-bot-bg);\n border: none;\n color: var(--cb-text);\n border-bottom-left-radius: 4px;\n box-shadow: none;\n}\n.cb-msg.cb-user .cb-msg-bubble {\n background: var(--cb-grad);\n border: none;\n color: white;\n border-bottom-right-radius: 4px;\n box-shadow: 0 2px 10px var(--cb-accent-glow);\n}\n.cb-msg-time {\n font-size: 10px; color: var(--cb-text-3); padding: 0 4px;\n}\n.cb-msg.cb-user .cb-msg-time { text-align: right; }\n.cb-msg.cb-bot .cb-msg-bubble code { background: rgba(var(--cb-accent-rgb),0.10); color: var(--cb-accent); }\n.cb-msg.cb-user .cb-msg-bubble code { background: rgba(255,255,255,0.20); color: white; }\n\n.cb-typing-wrap {\n display: flex; gap: 10px; align-items: flex-end;\n align-self: flex-start; margin-top: 14px;\n animation: cb-msg-in .3s ease both;\n}\n.cb-typing {\n display: flex; gap: 5px; align-items: center;\n padding: 13px 18px;\n background: var(--cb-msg-bot-bg);\n border-radius: 20px; border-bottom-left-radius: 6px;\n}\n.cb-typing span {\n width: 7px; height: 7px; border-radius: 50%;\n background: var(--cb-accent);\n animation: cb-bounce 1.4s ease-in-out infinite;\n flex-shrink: 0;\n opacity: 0.65;\n}\n.cb-typing span:nth-child(1) { animation-delay: 0s; }\n.cb-typing span:nth-child(2) { animation-delay: 0.18s; opacity: 0.82; }\n.cb-typing span:nth-child(3) { animation-delay: 0.36s; opacity: 1; }\n@keyframes cb-bounce {\n 0%, 55%, 100% { transform: translateY(0) scale(1); }\n 28% { transform: translateY(-7px) scale(1.1); }\n}\n\n.cb-input-area {\n flex-shrink: 0;\n padding: 12px 14px 14px;\n border-top: 1px solid var(--cb-divider);\n background: var(--cb-window-bg);\n display: flex; gap: 10px; align-items: flex-end;\n}\n.cb-input-wrap {\n flex: 1;\n display: flex; align-items: flex-end;\n background: var(--cb-input-bg);\n border: 1.5px solid var(--cb-input-bd);\n border-radius: 24px;\n padding: 0 16px;\n min-height: 46px;\n transition: border-color .2s, box-shadow .2s;\n}\n.cb-input-wrap:focus-within {\n border-color: rgba(var(--cb-accent-rgb), 0.45);\n box-shadow: 0 0 0 3px var(--cb-accent-ring);\n}\n.cb-input {\n flex: 1; border: none; background: transparent;\n padding: 13px 0;\n font-size: 13.5px; font-family: inherit;\n resize: none; outline: none;\n max-height: 100px;\n color: var(--cb-text);\n line-height: 1.45;\n overflow-y: auto;\n}\n.cb-input::placeholder { color: var(--cb-text-3); }\n.cb-send-btn {\n width: 44px; height: 44px;\n border-radius: 50%;\n background: var(--cb-grad);\n border: none; cursor: pointer;\n display: flex; align-items: center; justify-content: center;\n flex-shrink: 0;\n transition: transform .25s cubic-bezier(.34,1.56,.64,1), box-shadow .2s, opacity .2s;\n box-shadow: 0 3px 12px var(--cb-accent-glow);\n outline: none;\n}\n.cb-send-btn:hover {\n transform: scale(1.06);\n box-shadow: 0 6px 18px var(--cb-accent-glow);\n}\n.cb-send-btn:active { transform: scale(0.92); }\n.cb-send-btn:disabled {\n opacity: 0.35; cursor: not-allowed;\n transform: none; box-shadow: none;\n}\n.cb-send-btn svg {\n width: 17px; height: 17px;\n fill: none; stroke: white; stroke-width: 2;\n stroke-linecap: round; stroke-linejoin: round;\n position: relative; z-index: 1;\n}\n\n.cb-footer {\n flex-shrink: 0;\n text-align: center;\n padding: 6px 0 10px;\n font-size: 10px;\n color: var(--cb-text-3);\n display: flex; align-items: center; justify-content: center; gap: 5px;\n letter-spacing: 0.01em;\n background: var(--cb-window-bg);\n}\n.cb-footer-dot {\n display: inline-block;\n width: 5px; height: 5px;\n border-radius: 50%;\n background: rgba(var(--cb-accent-rgb), 0.45);\n flex-shrink: 0;\n}\n.cb-footer a {\n color: var(--cb-accent);\n text-decoration: none;\n font-weight: 700;\n letter-spacing: 0.02em;\n background: var(--cb-grad);\n -webkit-background-clip: text;\n -webkit-text-fill-color: transparent;\n background-clip: text;\n}\n.cb-footer a:hover { opacity: .75; }\n\n.cb-bot .cb-msg-bubble p { margin: 0 0 6px; }\n.cb-bot .cb-msg-bubble p:last-child { margin-bottom: 0; }\n.cb-bot .cb-msg-bubble strong,\n.cb-bot .cb-msg-bubble b { font-weight: 700; color: #111827; }\n.cb-bot .cb-msg-bubble em,\n.cb-bot .cb-msg-bubble i { font-style: italic; }\n.cb-bot .cb-msg-bubble h1,\n.cb-bot .cb-msg-bubble h2,\n.cb-bot .cb-msg-bubble h3 { font-weight: 700; margin: 8px 0 4px; color: #111827; line-height: 1.3; }\n.cb-bot .cb-msg-bubble h1 { font-size: 15px; }\n.cb-bot .cb-msg-bubble h2 { font-size: 14px; }\n.cb-bot .cb-msg-bubble h3 { font-size: 13.5px; }\n.cb-bot .cb-msg-bubble ul,\n.cb-bot .cb-msg-bubble ol { margin: 4px 0 6px 16px; padding: 0; }\n.cb-bot .cb-msg-bubble li { margin-bottom: 3px; line-height: 1.55; }\n.cb-bot .cb-msg-bubble code {\n background: #EEF2FF;\n border-radius: 4px;\n padding: 1px 5px;\n font-family: 'Courier New', monospace;\n font-size: 12px;\n color: var(--cb-accent);\n}\n.cb-bot .cb-msg-bubble pre {\n background: #1e293b;\n border-radius: 10px;\n padding: 10px 14px;\n overflow-x: auto;\n margin: 6px 0;\n}\n.cb-bot .cb-msg-bubble pre code {\n background: none; border: none; padding: 0; color: #93c5fd; font-size: 12px;\n}\n.cb-bot .cb-msg-bubble blockquote {\n border-left: 3px solid var(--cb-accent);\n padding: 3px 10px;\n margin: 6px 0;\n color: #64748b;\n background: rgba(var(--cb-accent-rgb), 0.05);\n border-radius: 0 6px 6px 0;\n}\n.cb-bot .cb-msg-bubble a { color: var(--cb-accent); text-decoration: underline; }\n.cb-bot .cb-msg-bubble hr { border: none; border-top: 1px solid #e5e7eb; margin: 8px 0; }\n.cb-bot .cb-msg-bubble table { border-collapse: collapse; width: 100%; margin: 6px 0; font-size: 12px; }\n.cb-bot .cb-msg-bubble th { background: #f3f4f6; font-weight: 600; padding: 5px 8px; border: 1px solid #e5e7eb; }\n.cb-bot .cb-msg-bubble td { padding: 4px 8px; border: 1px solid #e5e7eb; }\n.cb-dark .cb-bot .cb-msg-bubble strong,\n.cb-dark .cb-bot .cb-msg-bubble b { color: #F9FAFB; }\n.cb-dark .cb-bot .cb-msg-bubble h1,\n.cb-dark .cb-bot .cb-msg-bubble h2,\n.cb-dark .cb-bot .cb-msg-bubble h3 { color: #F9FAFB; }\n.cb-dark .cb-bot .cb-msg-bubble code { background: #1e293b; color: #93c5fd; }\n.cb-dark .cb-bot .cb-msg-bubble blockquote { color: #9CA3AF; }\n.cb-dark .cb-bot .cb-msg-bubble th { background: #1F2937; border-color: #374151; }\n.cb-dark .cb-bot .cb-msg-bubble td { border-color: #374151; }\n.cb-dark .cb-bot .cb-msg-bubble hr { border-color: #374151; }\n\n/* โ”€โ”€ Tab Bar โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */\n.cb-tab-bar {\n flex-shrink: 0;\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 12px 14px;\n background: var(--cb-window-bg);\n border-bottom: 1px solid var(--cb-divider);\n}\n.cb-tabs {\n display: flex;\n background: #f3f4f6;\n border-radius: 20px;\n padding: 3px;\n}\n.cb-dark .cb-tabs {\n background: #1F2937;\n}\n.cb-tab {\n padding: 7px 22px;\n border: none;\n border-radius: 18px;\n font-size: 13px;\n font-weight: 600;\n cursor: pointer;\n background: transparent;\n color: var(--cb-text-2);\n font-family: inherit;\n transition: all .2s;\n}\n.cb-tab.cb-active {\n background: #1a1a2e;\n color: white;\n}\n.cb-dark .cb-tab.cb-active {\n background: #f3f4f6;\n color: #111827;\n}\n.cb-tab-actions {\n display: flex;\n gap: 4px;\n align-items: center;\n}\n.cb-tab-action-btn {\n width: 30px;\n height: 30px;\n border-radius: 8px;\n border: none;\n background: transparent;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background .2s;\n}\n.cb-tab-action-btn:hover {\n background: var(--cb-msg-bot-bg);\n}\n.cb-tab-action-btn svg {\n width: 16px;\n height: 16px;\n stroke: var(--cb-text-2);\n fill: none;\n stroke-width: 2;\n stroke-linecap: round;\n stroke-linejoin: round;\n}\n\n/* โ”€โ”€ Welcome / Landing Page โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */\n.cb-welcome {\n flex: 1;\n display: flex;\n flex-direction: column;\n align-items: center;\n padding: 36px 24px 20px;\n overflow-y: auto;\n background: var(--cb-window-bg);\n}\n.cb-welcome.cb-hidden { display: none; }\n.cb-welcome-logo {\n display: flex;\n align-items: center;\n gap: 6px;\n margin-bottom: 22px;\n}\n.cb-welcome-logo-icon {\n width: 22px;\n height: 22px;\n color: var(--cb-accent);\n}\n.cb-welcome-logo-text {\n font-size: 18px;\n font-weight: 800;\n letter-spacing: 1px;\n color: var(--cb-text);\n}\n.cb-welcome-logo-badge {\n background: #1a1a2e;\n color: white;\n font-size: 10px;\n font-weight: 700;\n padding: 2px 7px;\n border-radius: 5px;\n letter-spacing: 0.5px;\n}\n.cb-dark .cb-welcome-logo-badge {\n background: #f3f4f6;\n color: #111827;\n}\n.cb-welcome-greeting {\n font-size: 24px;\n font-weight: 700;\n color: var(--cb-text);\n text-align: center;\n margin-bottom: 6px;\n line-height: 1.3;\n}\n.cb-welcome-subtitle {\n font-size: 14px;\n color: var(--cb-text-2);\n text-align: center;\n margin-bottom: 28px;\n}\n.cb-quick-replies {\n width: 100%;\n display: flex;\n flex-direction: column;\n gap: 10px;\n}\n.cb-quick-reply-btn {\n width: 100%;\n padding: 14px 18px;\n background: var(--cb-window-bg);\n border: 1.5px solid var(--cb-input-bd);\n border-radius: 14px;\n font-size: 13.5px;\n font-family: inherit;\n color: var(--cb-text);\n cursor: pointer;\n text-align: left;\n transition: all .2s;\n}\n.cb-quick-reply-btn:hover {\n border-color: rgba(var(--cb-accent-rgb), 0.4);\n background: rgba(var(--cb-accent-rgb), 0.04);\n transform: translateY(-1px);\n}\n\n/* โ”€โ”€ History Panel (tab-based, replaces drawer) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */\n.cb-history-panel {\n flex: 1;\n overflow-y: auto;\n display: none;\n flex-direction: column;\n background: var(--cb-window-bg);\n}\n.cb-history-panel.cb-active {\n display: flex;\n}\n.cb-history-panel-header {\n display: flex;\n flex-direction: column;\n align-items: center;\n padding: 30px 24px 20px;\n}\n.cb-history-panel-header .cb-welcome-logo {\n margin-bottom: 14px;\n}\n.cb-history-panel-title {\n font-size: 22px;\n font-weight: 700;\n color: var(--cb-text);\n margin-bottom: 4px;\n}\n.cb-history-panel-subtitle {\n font-size: 13px;\n color: var(--cb-text-2);\n}\n.cb-history-section-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 0 20px 10px;\n}\n.cb-history-count {\n font-size: 14px;\n font-weight: 700;\n color: var(--cb-text);\n}\n.cb-history-panel .cb-history-list {\n flex: 1;\n overflow-y: auto;\n padding: 0 20px 16px;\n display: flex;\n flex-direction: column;\n gap: 10px;\n}\n.cb-history-panel .cb-history-empty {\n flex: 1;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n color: var(--cb-text-3);\n font-size: 13px;\n text-align: center;\n padding: 40px 20px;\n}\n.cb-history-clear-btn {\n padding: 0;\n border: none;\n background: none;\n color: #ef4444;\n font-size: 13px;\n font-weight: 600;\n font-family: inherit;\n cursor: pointer;\n display: flex;\n align-items: center;\n gap: 5px;\n transition: opacity .2s;\n}\n.cb-history-clear-btn:hover {\n opacity: 0.7;\n}\n.cb-history-clear-btn svg {\n width: 14px;\n height: 14px;\n stroke: #ef4444;\n}\n\n/* โ”€โ”€ History Chat Items โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */\n.cb-history-chat-item {\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 14px 16px;\n background: var(--cb-window-bg);\n border: 1.5px solid var(--cb-divider);\n border-radius: 14px;\n cursor: pointer;\n transition: all .2s;\n}\n.cb-history-chat-item:hover {\n border-color: rgba(var(--cb-accent-rgb), 0.3);\n box-shadow: 0 2px 8px rgba(0,0,0,0.06);\n}\n.cb-history-chat-item.cb-active {\n border-color: rgba(var(--cb-accent-rgb), 0.4);\n background: rgba(var(--cb-accent-rgb), 0.04);\n}\n.cb-history-chat-item.cb-loading {\n pointer-events: none;\n opacity: 0.7;\n}\n.cb-history-chat-item.cb-loading .cb-history-chat-icon svg {\n display: none;\n}\n.cb-history-chat-item.cb-loading .cb-history-chat-icon::after {\n content: '';\n width: 20px;\n height: 20px;\n border: 2.5px solid rgba(var(--cb-accent-rgb), 0.2);\n border-top-color: var(--cb-accent);\n border-radius: 50%;\n animation: cb-spin 0.7s linear infinite;\n}\n@keyframes cb-spin {\n to { transform: rotate(360deg); }\n}\n.cb-chat-loader {\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: 12px;\n padding: 40px 20px;\n color: var(--cb-text-3);\n font-size: 13px;\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 100%;\n}\n.cb-chat-loader-spinner {\n width: 32px;\n height: 32px;\n border: 3px solid rgba(var(--cb-accent-rgb), 0.15);\n border-top-color: var(--cb-accent);\n border-radius: 50%;\n animation: cb-spin 0.7s linear infinite;\n}\n.cb-history-chat-icon {\n width: 38px;\n height: 38px;\n border-radius: 10px;\n background: rgba(var(--cb-accent-rgb), 0.1);\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n}\n.cb-history-chat-icon svg {\n width: 20px;\n height: 20px;\n}\n.cb-history-chat-info {\n flex: 1;\n min-width: 0;\n}\n.cb-history-chat-title {\n font-size: 14px;\n font-weight: 600;\n color: var(--cb-text);\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n.cb-history-chat-meta {\n font-size: 12px;\n color: var(--cb-text-3);\n margin-top: 2px;\n}\n.cb-history-delete-btn {\n width: 32px;\n height: 32px;\n border-radius: 8px;\n border: none;\n background: transparent;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n transition: all .2s;\n color: var(--cb-text-3);\n}\n.cb-history-delete-btn:hover {\n background: rgba(239,68,68,0.08);\n color: #ef4444;\n}\n.cb-history-delete-btn svg {\n width: 16px;\n height: 16px;\n stroke: #ef4444;\n}\n\n/* โ”€โ”€ Disclaimer footer โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */\n.cb-disclaimer {\n flex-shrink: 0;\n text-align: center;\n padding: 6px 16px 12px;\n font-size: 11px;\n color: #9ca3af;\n font-weight: 500;\n background: var(--cb-window-bg);\n}\n\n/* โ”€โ”€ Message Actions (copy, feedback) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */\n.cb-msg-actions {\n display: flex;\n align-items: center;\n gap: 2px;\n padding: 2px 0 0 4px;\n opacity: 0;\n transition: opacity .2s;\n}\n.cb-msg:hover .cb-msg-actions,\n.cb-msg-actions.cb-visible {\n opacity: 1;\n}\n.cb-msg-action-btn {\n width: 28px;\n height: 28px;\n border-radius: 6px;\n border: none;\n background: transparent;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all .2s;\n color: var(--cb-text-3);\n position: relative;\n}\n.cb-msg-action-btn:hover {\n background: var(--cb-msg-bot-bg);\n color: var(--cb-text-2);\n}\n.cb-msg-action-btn svg {\n width: 14px;\n height: 14px;\n stroke: currentColor;\n fill: none;\n}\n.cb-msg-action-btn.cb-active {\n color: var(--cb-accent);\n}\n.cb-msg-action-btn.cb-active svg {\n stroke: var(--cb-accent);\n}\n.cb-msg-action-btn.cb-copied {\n color: #10b981;\n}\n.cb-msg-action-btn.cb-copied svg {\n stroke: #10b981;\n}\n.cb-msg-action-btn .cb-tooltip {\n position: absolute;\n bottom: 100%;\n left: 50%;\n transform: translateX(-50%) translateY(-4px);\n background: #1a1a2e;\n color: white;\n font-size: 11px;\n font-weight: 500;\n padding: 4px 8px;\n border-radius: 6px;\n white-space: nowrap;\n pointer-events: none;\n opacity: 0;\n transition: opacity .15s;\n}\n.cb-msg-action-btn:hover .cb-tooltip {\n opacity: 1;\n}\n.cb-dark .cb-msg-action-btn .cb-tooltip {\n background: #f3f4f6;\n color: #111827;\n}\n.cb-feedback-divider {\n width: 1px;\n height: 16px;\n background: var(--cb-divider);\n margin: 0 2px;\n}\n\n/* โ”€โ”€ Streaming Text Animation โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */\n.cb-msg-bubble.cb-streaming {\n overflow: hidden;\n}\n.cb-streaming-cursor {\n display: inline-block;\n width: 2px;\n height: 14px;\n background: var(--cb-accent);\n margin-left: 2px;\n vertical-align: text-bottom;\n animation: cb-blink 0.6s step-end infinite;\n}\n@keyframes cb-blink {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0; }\n}\n\n/* โ”€โ”€ Export Button โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */\n.cb-export-btn {\n width: 30px;\n height: 30px;\n border-radius: 8px;\n border: none;\n background: transparent;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background .2s;\n position: relative;\n}\n.cb-export-btn:hover {\n background: var(--cb-msg-bot-bg);\n}\n.cb-export-btn svg {\n width: 16px;\n height: 16px;\n stroke: var(--cb-text-2);\n fill: none;\n stroke-width: 2;\n stroke-linecap: round;\n stroke-linejoin: round;\n}\n.cb-export-btn .cb-tooltip {\n position: absolute;\n bottom: 100%;\n left: 50%;\n transform: translateX(-50%) translateY(-4px);\n background: #1a1a2e;\n color: white;\n font-size: 11px;\n font-weight: 500;\n padding: 4px 8px;\n border-radius: 6px;\n white-space: nowrap;\n pointer-events: none;\n opacity: 0;\n transition: opacity .15s;\n}\n.cb-export-btn:hover .cb-tooltip {\n opacity: 1;\n}\n\n/* โ”€โ”€ Suggested Follow-ups โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */\n.cb-followups {\n display: flex;\n flex-wrap: wrap;\n gap: 6px;\n padding: 4px 0 0 40px;\n animation: cb-msg-in .3s ease both;\n}\n.cb-followup-btn {\n padding: 7px 14px;\n background: var(--cb-window-bg);\n border: 1.5px solid var(--cb-input-bd);\n border-radius: 20px;\n font-size: 12px;\n font-family: inherit;\n font-weight: 500;\n color: var(--cb-text);\n cursor: pointer;\n transition: all .2s;\n white-space: nowrap;\n}\n.cb-followup-btn:hover {\n border-color: rgba(var(--cb-accent-rgb), 0.4);\n background: rgba(var(--cb-accent-rgb), 0.04);\n color: var(--cb-accent);\n}\n\n@media (max-width: 480px) {\n .cb-window {\n width: 100dvw !important;\n left: 0 !important;\n right: 0 !important;\n border-left: none !important;\n border-right: none !important;\n }\n}\n",document.head.appendChild(e)}autoResize(){this.inputEl.style.height="auto",this.inputEl.style.height=Math.min(this.inputEl.scrollHeight,100)+"px"}applyTheme(){const e="dark"===this.config.theme||"auto"===this.config.theme&&window.matchMedia("(prefers-color-scheme: dark)").matches;this.container.classList.toggle("cb-dark",e),"auto"===this.config.theme&&window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",e=>{this.container.classList.toggle("cb-dark",e.matches)})}connectSocket(){this.socket=we(`${this.config.serverUrl}/chat`,{transports:["websocket"],auth:{apiKey:this.config.apiKey},reconnectionAttempts:5,reconnectionDelay:2e3}),this.socket.on("connect",()=>console.log("[ChatBolt] Connected")),this.socket.on("chat:response",e=>{var t;this.conversationId=e.conversationId,this.hideTyping(),this.addMessage("assistant",e.message,!1,null!==(t=e.report)&&void 0!==t?t:void 0),this.isOpen||this.showBadge()}),this.socket.on("chat:error",e=>{this.hideTyping(),this.addMessage("assistant",`Something went wrong: ${e.message}`)}),this.socket.on("disconnect",()=>console.log("[ChatBolt] Disconnected"))}send(e){var t;const n=e||this.inputEl.value.trim();if(!n||this.isTyping)return;this.isWelcomeVisible&&this.hideWelcome(),this.addMessage("user",n),e||(this.inputEl.value="",this.inputEl.style.height="auto"),this.sendBtn.disabled=!0,this.showTyping(),this.sessionId||(this.sessionId=this.getOrCreateSessionId());if(this.conversations.find(e=>e.sessionId===this.sessionId))this.updateConversationMeta(this.sessionId);else{const e=n.length>30?n.substring(0,30)+"...":n;this.addConversation(this.sessionId,e)}null===(t=this.socket)||void 0===t||t.emit("chat:message",{message:n,session_id:this.sessionId,conversationId:this.conversationId||void 0,contextParams:this.config.contextParams||void 0})}addMessage(e,t,n=!1,s){const i={id:Date.now().toString(),role:e,content:t,createdAt:new Date,report:s};this.messages.push(i);const r=this.lastRole===e;this.lastRole=e;const o=document.createElement("div");o.className=`cb-msg ${"user"===e?"cb-user":"cb-bot"}${r?" cb-grouped":" cb-first-in-group"}`;const a="user"===e?`<div class="cb-msg-avatar">${jt.user}</div>`:`<div class="cb-msg-avatar">${this.config.botAvatar?`<img src="${this.config.botAvatar}" alt="bot">`:jt.bot}</div>`,c=s?this.renderReportCard(s):"",l="assistant"!==e||n?"":`\n <div class="cb-msg-actions">\n <button class="cb-msg-action-btn cb-copy-btn" data-content="${this.esc(t)}">\n <span class="cb-tooltip">Copy</span>\n ${jt.copy}\n </button>\n <span class="cb-feedback-divider"></span>\n <button class="cb-msg-action-btn cb-feedback-btn" data-feedback="up" data-msg-id="${i.id}">\n <span class="cb-tooltip">Helpful</span>\n ${jt.thumbUp}\n </button>\n <button class="cb-msg-action-btn cb-feedback-btn" data-feedback="down" data-msg-id="${i.id}">\n <span class="cb-tooltip">Not helpful</span>\n ${jt.thumbDown}\n </button>\n </div>`,h="assistant"===e&&!n&&this.messages.filter(e=>"user"===e.role).length>0;if(o.innerHTML=`\n ${a}\n <div class="cb-msg-content">\n <div class="cb-msg-bubble${h?" cb-streaming":""}">${h?"":this.renderContent(t,e)}${h?"":c}</div>\n ${r?"":`<span class="cb-msg-time">${Ht(i.createdAt)}</span>`}\n </div>`,this.messagesEl.appendChild(o),this.clearFollowups(),h){const e=o.querySelector(".cb-msg-bubble");this.streamText(e,t,c,()=>{const e=o.querySelector(".cb-msg-content"),n=document.createElement("div");n.innerHTML=l;const s=n.firstElementChild;if(s){e.appendChild(s);const n=s.querySelector(".cb-copy-btn");n&&n.addEventListener("click",e=>{e.stopPropagation(),this.copyMessageText(t,n)}),s.querySelectorAll(".cb-feedback-btn").forEach(e=>{e.addEventListener("click",t=>{t.stopPropagation();const n=e.dataset.feedback,s=e.dataset.msgId;this.handleFeedback(s,n,e)})})}this.addFollowups(t),this.scrollBottom()})}else if(l){const e=o.querySelector(".cb-msg-content"),n=document.createElement("div");n.innerHTML=l;const s=n.firstElementChild;if(s){e.appendChild(s);const n=s.querySelector(".cb-copy-btn");n&&n.addEventListener("click",e=>{e.stopPropagation(),this.copyMessageText(t,n)}),s.querySelectorAll(".cb-feedback-btn").forEach(e=>{e.addEventListener("click",t=>{t.stopPropagation();const n=e.dataset.feedback,s=e.dataset.msgId;this.handleFeedback(s,n,e)})})}}this.scrollBottom(),this.isHistoryOpen&&this.renderHistory()}renderReportCard(e){if(!(null==e?void 0:e.report_id))return"";const t=`${this.config.serverUrl||"https://backend-api-chatbolt-backend.hf.space"}/api/v1/export/${e.report_id}`,n=`api_key=${encodeURIComponent(this.config.apiKey)}`,s={excel:"Excel",csv:"CSV",pdf:"PDF",docx:"Word"},i={excel:"๐Ÿ“Š",csv:"๐Ÿ“„",pdf:"๐Ÿ“•",docx:"๐Ÿ“"},r=(e.download_formats||[]).map(e=>`<a href="${t}/${e}?${n}" target="_blank" rel="noopener" class="cb-dl-btn cb-dl-${e}">\n ${i[e]||"โฌ‡"} ${s[e]||e}\n </a>`).join(""),o=(e.columns||[]).slice(0,4),a=(e.preview||[]).slice(0,5),c=o.map(e=>`<th>${this.esc(e.label||e.key)}</th>`).join(""),l=a.map(e=>`<tr>${o.map(t=>{var n;return`<td>${this.esc(String(null!==(n=e[t.key])&&void 0!==n?n:""))}</td>`}).join("")}</tr>`).join("");return`\n <div class="cb-report-card">\n <div class="cb-report-header">\n <span class="cb-report-icon">๐Ÿ“Š</span>\n <div>\n <div class="cb-report-title">${this.esc(e.title)}</div>\n <div class="cb-report-meta">${e.total_rows.toLocaleString()} rows ยท ${new Date(e.generated_at).toLocaleTimeString()}</div>\n </div>\n </div>\n ${l?`<div class="cb-report-table-wrap">\n <table class="cb-report-table">\n <thead><tr>${c}</tr></thead>\n <tbody>${l}</tbody>\n </table>\n ${e.total_rows>5?`<div class="cb-report-more">+${(e.total_rows-5).toLocaleString()} more rows</div>`:""}\n </div>`:""}\n ${r?`<div class="cb-report-downloads">${r}</div>`:""}\n </div>`}renderContent(e,t="assistant"){return"user"===t?this.esc(e).replace(/\n/g,"<br>"):Nt.parse(e)}showTyping(){this.isTyping=!0,this.messagesEl.appendChild(this.typingEl),this.scrollBottom()}hideTyping(){var e;this.isTyping=!1,this.sendBtn.disabled=!1,null===(e=this.typingEl.parentElement)||void 0===e||e.removeChild(this.typingEl)}scrollBottom(){requestAnimationFrame(()=>{this.messagesEl.scrollTop=this.messagesEl.scrollHeight})}showBadge(){this.unreadCount++,this.badgeEl.textContent=this.unreadCount>9?"9+":String(this.unreadCount),this.badgeEl.style.display="flex"}clearBadge(){this.unreadCount=0,this.badgeEl.style.display="none"}open(){this.isOpen=!0,this.window.classList.remove("cb-hidden"),this.trigger.classList.add("cb-open"),this.clearBadge(),setTimeout(()=>this.inputEl.focus(),250),this.scrollBottom()}close(){this.isOpen=!1,this.window.classList.add("cb-hidden"),this.trigger.classList.remove("cb-open")}toggle(){this.isOpen?this.close():this.open()}expand(){this.isExpanded=!0,this.window.classList.add("cb-expanded"),this.expandBtn.classList.add("cb-expanded"),this.scrollBottom()}collapse(){this.isExpanded=!1,this.window.classList.remove("cb-expanded"),this.expandBtn.classList.remove("cb-expanded"),this.scrollBottom()}toggleExpand(){this.isExpanded?this.collapse():this.expand()}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}getOrCreateSessionId(){this.loadConversationsList();const e=localStorage.getItem(this.activeSessionKey);if(e&&this.conversations.some(t=>t.sessionId===e))return e;const t=this.generateSessionId();return this.setActiveSession(t),t}loadConversationsList(){try{const e=localStorage.getItem(this.conversationsKey);this.conversations=e?JSON.parse(e):[]}catch(e){this.conversations=[]}}saveConversationsList(){localStorage.setItem(this.conversationsKey,JSON.stringify(this.conversations))}setActiveSession(e){this.sessionId=e,localStorage.setItem(this.activeSessionKey,e)}addConversation(e,t){const n={sessionId:e,title:t,messageCount:0,createdAt:(new Date).toISOString(),lastMessageAt:(new Date).toISOString()};return this.conversations.unshift(n),this.saveConversationsList(),n}updateConversationMeta(e,t){const n=this.conversations.find(t=>t.sessionId===e);n&&(n.messageCount=this.messages.filter(e=>"user"===e.role).length,n.lastMessageAt=(new Date).toISOString(),!t||"New Chat"!==n.title&&n.title||(n.title=t),this.saveConversationsList())}deleteConversation(e){this.conversations=this.conversations.filter(t=>t.sessionId!==e),this.saveConversationsList()}async loadHistory(){try{this.sessionId=this.getOrCreateSessionId(),this.sessionId&&await this.fetchSessionMessages(this.sessionId),this.renderHistory()}catch(e){console.error("[ChatBolt] Failed to load history:",e),this.sessionId=this.getOrCreateSessionId(),this.renderHistory()}}async fetchSessionMessages(e){try{const t=await fetch(`${this.config.serverUrl}/api/v1/chat/history?session_id=${encodeURIComponent(e)}`,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey}});if(!t.ok)return;const n=await t.json(),s=this.messagesEl.querySelector(".cb-chat-loader");s&&s.remove(),n.messages&&n.messages.length>0&&(this.messages=n.messages.map(e=>({id:e.id,role:e.role,content:e.content,createdAt:new Date(e.createdAt)})),this.restoreMessagesFromHistory())}catch(e){console.error("[ChatBolt] Failed to fetch session messages:",e)}}async loadConversation(e){this.messages=[],this.messagesEl.innerHTML="",this.lastRole=null,this.setActiveSession(e),this.conversationId=null,this.hideWelcome(),this.messagesEl.innerHTML='\n <div class="cb-chat-loader">\n <div class="cb-chat-loader-spinner"></div>\n Loading conversation...\n </div>',this.switchTab("chat");const t=this.container.querySelectorAll(".cb-history-chat-item");t.forEach(e=>e.classList.remove("cb-loading"));const n=Array.from(t).find(e=>e.classList.contains("cb-active"));n&&n.classList.add("cb-loading"),await this.fetchSessionMessages(e),n&&n.classList.remove("cb-loading"),0===this.messages.length&&(this.messagesEl.innerHTML=""),this.messages.some(e=>"user"===e.role)?this.hideWelcome():(this.isWelcomeVisible=!0,this.welcomeEl.classList.remove("cb-hidden"))}restoreMessagesFromHistory(){const e=this.messages.some(e=>"user"===e.role);e&&this.hideWelcome(),this.messages.forEach(e=>{const t=this.lastRole===e.role;this.lastRole=e.role;const n=document.createElement("div");n.className=`cb-msg ${"user"===e.role?"cb-user":"cb-bot"}${t?" cb-grouped":" cb-first-in-group"}`;const s="user"===e.role?`<div class="cb-msg-avatar">${jt.user}</div>`:`<div class="cb-msg-avatar">${this.config.botAvatar?`<img src="${this.config.botAvatar}" alt="bot">`:jt.bot}</div>`,i="assistant"===e.role?`\n <div class="cb-msg-actions">\n <button class="cb-msg-action-btn cb-copy-btn">\n <span class="cb-tooltip">Copy</span>\n ${jt.copy}\n </button>\n <span class="cb-feedback-divider"></span>\n <button class="cb-msg-action-btn cb-feedback-btn" data-feedback="up" data-msg-id="${e.id}">\n <span class="cb-tooltip">Helpful</span>\n ${jt.thumbUp}\n </button>\n <button class="cb-msg-action-btn cb-feedback-btn" data-feedback="down" data-msg-id="${e.id}">\n <span class="cb-tooltip">Not helpful</span>\n ${jt.thumbDown}\n </button>\n </div>`:"";n.innerHTML=`\n ${s}\n <div class="cb-msg-content">\n <div class="cb-msg-bubble">${this.renderContent(e.content,e.role)}</div>\n ${t?"":`<span class="cb-msg-time">${Ht(e.createdAt)}</span>`}\n ${i}\n </div>`;const r=n.querySelector(".cb-copy-btn");r&&r.addEventListener("click",t=>{t.stopPropagation(),this.copyMessageText(e.content,r)}),n.querySelectorAll(".cb-feedback-btn").forEach(e=>{e.addEventListener("click",t=>{t.stopPropagation();const n=e.dataset.feedback,s=e.dataset.msgId;this.handleFeedback(s,n,e)})}),this.messagesEl.appendChild(n)}),this.messages.length>0&&this.scrollBottom()}renderHistory(){this.historyList.innerHTML="",this.loadConversationsList();const e=this.container.querySelector(".cb-history-count");if(0===this.conversations.length)return this.historyList.innerHTML='<div class="cb-history-empty">No conversations yet</div>',void(e&&(e.textContent="Recent Chats (0)"));e&&(e.textContent=`Recent Chats (${this.conversations.length})`),this.conversations.forEach(e=>{const t=document.createElement("div");t.className="cb-history-chat-item",e.sessionId===this.sessionId&&t.classList.add("cb-active");const n=new Date(e.lastMessageAt||e.createdAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});t.innerHTML=`\n <div class="cb-history-chat-icon">\n <svg viewBox="0 0 24 24" fill="none"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" fill="var(--cb-accent)" opacity="0.85"/></svg>\n </div>\n <div class="cb-history-chat-info">\n <div class="cb-history-chat-title">${this.esc(e.title)}</div>\n <div class="cb-history-chat-meta">${e.messageCount} messages ยท ${n}</div>\n </div>\n <button class="cb-history-delete-btn" aria-label="Delete">${jt.trash}</button>\n `,t.addEventListener("click",t=>{t.target.closest(".cb-history-delete-btn")||this.loadConversation(e.sessionId)});const s=t.querySelector(".cb-history-delete-btn");s&&s.addEventListener("click",t=>{t.stopPropagation(),this.deleteConversation(e.sessionId),e.sessionId===this.sessionId&&this.startNewChat(),this.renderHistory()}),this.historyList.appendChild(t)})}switchTab(e){this.activeTab=e,this.chatTabBtn.classList.toggle("cb-active","chat"===e),this.historyTabBtn.classList.toggle("cb-active","history"===e),"chat"===e?(this.historyPanel.classList.remove("cb-active"),this.isWelcomeVisible?(this.welcomeEl.style.display="",this.messagesEl.style.display="none"):(this.welcomeEl.style.display="none",this.messagesEl.style.display=""),this.scrollBottom()):(this.welcomeEl.style.display="none",this.messagesEl.style.display="none",this.historyPanel.classList.add("cb-active"),this.renderHistory())}hideWelcome(){this.isWelcomeVisible=!1,this.welcomeEl.classList.add("cb-hidden"),this.welcomeEl.style.display="none",this.messagesEl.style.display=""}toggleHistory(){this.switchTab("history"===this.activeTab?"chat":"history")}openHistory(){this.isHistoryOpen=!0,this.switchTab("history")}closeHistory(){this.isHistoryOpen=!1,this.switchTab("chat")}clearHistory(){if(confirm("Are you sure you want to clear all chat history?"))try{this.conversations=[],this.saveConversationsList(),localStorage.removeItem(this.activeSessionKey),this.startNewChat(),this.renderHistory()}catch(e){console.error("[ChatBolt] Failed to clear history:",e)}}startNewChat(){const e=this.generateSessionId();this.setActiveSession(e),this.conversationId=null,this.messages=[],this.messagesEl.innerHTML="",this.lastRole=null,this.isWelcomeVisible=!0,this.welcomeEl.classList.remove("cb-hidden"),this.switchTab("chat"),this.config.greetingMessage&&this.addMessage("assistant",this.config.greetingMessage,!0)}streamText(e,t,n,s){const i=t.split(/(\s+)/);let r=0;const o=document.createElement("span");o.className="cb-streaming-cursor",e.appendChild(o);const a=setInterval(()=>{if(r>=i.length)return clearInterval(a),e.classList.remove("cb-streaming"),e.innerHTML=this.renderContent(t,"assistant")+n,void s();let c="";for(let e=0;e<3&&r<i.length;e++,r++)c+=i[r];o.remove();const l=i.slice(0,r).join("");e.textContent=l,e.appendChild(o),this.scrollBottom()},30)}exportChatPDF(){if(0===this.messages.length)return;const e=this.config.accentColor||"#6366f1",t=this.config.title||"Chat",n=new Date,s=n.toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"}),i=n.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"}),r=this.messages.map(n=>{const s="user"===n.role,i=s?e:"#f3f4f6",r=s?"#ffffff":"#111827",o=s?"You":t,a=n.createdAt instanceof Date?n.createdAt.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"}):"";return`\n <div style="margin-bottom:16px;">\n <div style="font-size:11px;font-weight:600;color:${s?e:"#6B7280"};margin-bottom:4px;">${o} <span style="font-weight:400;color:#9CA3AF;margin-left:6px;">${a}</span></div>\n <div style="background:${i};color:${r};padding:10px 14px;border-radius:12px;font-size:13px;line-height:1.6;max-width:85%;${s?"margin-left:auto;":""}">\n ${s?this.esc(n.content).replace(/\n/g,"<br>"):Nt.parse(n.content)}\n </div>\n </div>`}).join(""),o=`<!DOCTYPE html>\n<html><head>\n<meta charset="utf-8">\n<title>${this.esc(t)} - Chat Export</title>\n<style>\n @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');\n * { box-sizing: border-box; margin: 0; padding: 0; }\n body { font-family: 'Inter', sans-serif; background: #fff; padding: 40px; color: #111827; max-width: 700px; margin: 0 auto; }\n .header { text-align: center; margin-bottom: 32px; padding-bottom: 20px; border-bottom: 2px solid ${e}; }\n .header h1 { font-size: 22px; font-weight: 700; color: ${e}; }\n .header p { font-size: 12px; color: #9CA3AF; margin-top: 6px; }\n .messages { margin-bottom: 32px; }\n .footer { text-align: center; font-size: 11px; color: #9CA3AF; padding-top: 16px; border-top: 1px solid #E5E7EB; }\n code { background: #EEF2FF; border-radius: 3px; padding: 1px 4px; font-size: 12px; }\n pre { background: #1e293b; border-radius: 8px; padding: 10px; color: #93c5fd; font-size: 12px; overflow-x: auto; margin: 6px 0; }\n pre code { background: none; color: inherit; padding: 0; }\n table { border-collapse: collapse; width: 100%; margin: 6px 0; font-size: 12px; }\n th { background: #f3f4f6; font-weight: 600; padding: 5px 8px; border: 1px solid #e5e7eb; }\n td { padding: 4px 8px; border: 1px solid #e5e7eb; }\n @media print { body { padding: 20px; } }\n</style>\n</head><body>\n<div class="header">\n <h1>${this.esc(t)}</h1>\n <p>${s} at ${i} &middot; ${this.messages.length} messages</p>\n</div>\n<div class="messages">${r}</div>\n<div class="footer">Exported from ${this.esc(t)}</div>\n</body></html>`,a=window.open("","_blank");a&&(a.document.write(o),a.document.close(),a.onload=()=>{setTimeout(()=>a.print(),300)})}async copyMessageText(e,t){try{await navigator.clipboard.writeText(e),t.classList.add("cb-copied"),t.innerHTML=`<span class="cb-tooltip">Copied!</span>${jt.check}`,setTimeout(()=>{t.classList.remove("cb-copied"),t.innerHTML=`<span class="cb-tooltip">Copy</span>${jt.copy}`},2e3)}catch(n){const s=document.createElement("textarea");s.value=e,s.style.position="fixed",s.style.opacity="0",document.body.appendChild(s),s.select(),document.execCommand("copy"),document.body.removeChild(s),t.classList.add("cb-copied"),t.innerHTML=`<span class="cb-tooltip">Copied!</span>${jt.check}`,setTimeout(()=>{t.classList.remove("cb-copied"),t.innerHTML=`<span class="cb-tooltip">Copy</span>${jt.copy}`},2e3)}}handleFeedback(e,t,n){const s=n.closest(".cb-msg-actions");if(!s)return;const i=n.classList.contains("cb-active");s.querySelectorAll(".cb-feedback-btn").forEach(e=>e.classList.remove("cb-active")),i?s.classList.remove("cb-visible"):(n.classList.add("cb-active"),s.classList.add("cb-visible"),this.sendFeedback(e,t))}sendFeedback(e,t){try{fetch(`${this.config.serverUrl}/api/v1/chat/feedback`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey},body:JSON.stringify({messageId:e,sessionId:this.sessionId,feedback:t})}).catch(()=>{})}catch(e){}}clearFollowups(){this.messagesEl.querySelectorAll(".cb-followups").forEach(e=>e.remove())}addFollowups(e){const t=this.generateFollowups(e);if(0===t.length)return;const n=document.createElement("div");n.className="cb-followups",t.forEach(e=>{const t=document.createElement("button");t.className="cb-followup-btn",t.textContent=e,t.addEventListener("click",()=>{this.clearFollowups(),this.send(e)}),n.appendChild(t)}),this.messagesEl.appendChild(n)}generateFollowups(e){const t=[],n=e.toLowerCase();return n.includes("payment")||n.includes("billing")||n.includes("invoice")?t.push("Show payment details","Download invoice"):n.includes("user")||n.includes("account")||n.includes("member")?t.push("Show user details","Account settings"):n.includes("contest")||n.includes("competition")?t.push("List active contests","Contest statistics"):n.includes("error")||n.includes("issue")||n.includes("problem")?t.push("More details","How to fix this?"):(n.includes("report")||n.includes("data")||n.includes("analytics"))&&t.push("Export report","Show more data"),0===t.length&&t.push("Tell me more","Can you explain?"),t.slice(0,3)}destroy(){var e;null===(e=this.socket)||void 0===e||e.disconnect(),this.container.remove()}esc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}}const Dt={init:e=>(Dt._instance&&Dt._instance.destroy(),Dt._instance=new Ft(e),Dt._instance)};if("undefined"!=typeof window){window.ChatBolt=Dt,window.ChatBoltWidget=Ft;const e=()=>{window.ChatBoltConfig&&Dt.init(window.ChatBoltConfig)};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}export{Ft as ChatBoltWidget,Dt as default};
1
+ const e=Object.create(null);e.open="0",e.close="1",e.ping="2",e.pong="3",e.message="4",e.upgrade="5",e.noop="6";const t=Object.create(null);Object.keys(e).forEach(n=>{t[e[n]]=n});const n={type:"error",data:"parser error"},s="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),i="function"==typeof ArrayBuffer,r=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,o=({type:t,data:n},o,c)=>s&&n instanceof Blob?o?c(n):a(n,c):i&&(n instanceof ArrayBuffer||r(n))?o?c(n):a(new Blob([n]),c):c(e[t]+(n||"")),a=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function c(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let l;const h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<64;e++)p[h.charCodeAt(e)]=e;const d="function"==typeof ArrayBuffer,b=(e,s)=>{if("string"!=typeof e)return{type:"message",data:g(e,s)};const i=e.charAt(0);if("b"===i)return{type:"message",data:u(e.substring(1),s)};return t[i]?e.length>1?{type:t[i],data:e.substring(1)}:{type:t[i]}:n},u=(e,t)=>{if(d){const n=(e=>{let t,n,s,i,r,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const l=new ArrayBuffer(o),h=new Uint8Array(l);for(t=0;t<a;t+=4)n=p[e.charCodeAt(t)],s=p[e.charCodeAt(t+1)],i=p[e.charCodeAt(t+2)],r=p[e.charCodeAt(t+3)],h[c++]=n<<2|s>>4,h[c++]=(15&s)<<4|i>>2,h[c++]=(3&i)<<6|63&r;return l})(e);return g(n,t)}return{base64:!0,data:e}},g=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,f=String.fromCharCode(30);function m(){return new TransformStream({transform(e,t){!function(e,t){s&&e.data instanceof Blob?e.data.arrayBuffer().then(c).then(t):i&&(e.data instanceof ArrayBuffer||r(e.data))?t(c(e.data)):o(e,!1,e=>{l||(l=new TextEncoder),t(l.encode(e))})}(e,n=>{const s=n.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,s)}else{i=new Uint8Array(9);const e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(s))}e.data&&"string"!=typeof e.data&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}})}let x;function y(e){return e.reduce((e,t)=>e+t.length,0)}function k(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let s=0;for(let i=0;i<t;i++)n[i]=e[0][s++],s===e[0].length&&(e.shift(),s=0);return e.length&&s<e[0].length&&(e[0]=e[0].slice(s)),n}function w(e){if(e)return function(e){for(var t in w.prototype)e[t]=w.prototype[t];return e}(e)}w.prototype.on=w.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},w.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},w.prototype.off=w.prototype.removeListener=w.prototype.removeAllListeners=w.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,s=this._callbacks["$"+e];if(!s)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<s.length;i++)if((n=s[i])===t||n.fn===t){s.splice(i,1);break}return 0===s.length&&delete this._callbacks["$"+e],this},w.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],s=1;s<arguments.length;s++)t[s-1]=arguments[s];if(n){s=0;for(var i=(n=n.slice(0)).length;s<i;++s)n[s].apply(this,t)}return this},w.prototype.emitReserved=w.prototype.emit,w.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},w.prototype.hasListeners=function(e){return!!this.listeners(e).length};const v="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),_="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function S(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const E=_.setTimeout,T=_.clearTimeout;function C(e,t){t.useNativeTimers?(e.setTimeoutFn=E.bind(_),e.clearTimeoutFn=T.bind(_)):(e.setTimeoutFn=_.setTimeout.bind(_),e.clearTimeoutFn=_.clearTimeout.bind(_))}function A(e){return"string"==typeof e?function(e){let t=0,n=0;for(let s=0,i=e.length;s<i;s++)t=e.charCodeAt(s),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(s++,n+=4);return n}(e):Math.ceil(1.33*(e.byteLength||e.size))}function $(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class R extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class L extends w{constructor(e){super(),this.writable=!1,C(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new R(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=b(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}(e);return t.length?"?"+t:""}}class B extends L{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const n=e.split(f),s=[];for(let e=0;e<n.length;e++){const i=b(n[e],t);if(s.push(i),"error"===i.type)break}return s})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const n=e.length,s=new Array(n);let i=0;e.forEach((e,r)=>{o(e,!1,e=>{s[r]=e,++i===n&&t(s.join(f))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=$()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let z=!1;try{z="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}const I=z;function O(){}class q extends B{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let n=location.port;n||(n=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}class P extends w{constructor(e,t,n){super(),this.createRequest=e,C(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var e;const t=S(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(e){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{n.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this._opts.cookieJar)||void 0===e||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(e){return void this.setTimeoutFn(()=>{this._onError(e)},0)}"undefined"!=typeof document&&(this._index=P.requestsCount++,P.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=O,e)try{this._xhr.abort()}catch(e){}"undefined"!=typeof document&&delete P.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(P.requestsCount=0,P.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",M);else if("function"==typeof addEventListener){addEventListener("onpagehide"in _?"pagehide":"unload",M,!1)}function M(){for(let e in P.requests)P.requests.hasOwnProperty(e)&&P.requests[e].abort()}const N=function(){const e=j({xdomain:!1});return e&&null!==e.responseType}();function j(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||I))return new XMLHttpRequest}catch(e){}if(!t)try{return new(_[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}const H="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class D extends L{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=H?{}:S(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],s=t===e.length-1;o(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(e){}s&&v(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=$()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const F=_.WebSocket||_.MozWebSocket;const U={websocket:class extends D{createSocket(e,t,n){return H?new F(e,t,n):t?new F(e,t):new F(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends L{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=function(e,t){x||(x=new TextDecoder);const s=[];let i=0,r=-1,o=!1;return new TransformStream({transform(a,c){for(s.push(a);;){if(0===i){if(y(s)<1)break;const e=k(s,1);o=!(128&~e[0]),r=127&e[0],i=r<126?3:126===r?1:2}else if(1===i){if(y(s)<2)break;const e=k(s,2);r=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if(y(s)<8)break;const e=k(s,8),t=new DataView(e.buffer,e.byteOffset,e.length),o=t.getUint32(0);if(o>Math.pow(2,21)-1){c.enqueue(n);break}r=o*Math.pow(2,32)+t.getUint32(4),i=3}else{if(y(s)<r)break;const e=k(s,r);c.enqueue(b(o?e:x.decode(e),t)),i=0}if(0===r||r>e){c.enqueue(n);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),i=m();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const r=()=>{s.read().then(({done:e,value:t})=>{e||(this.onPacket(t),r())}).catch(e=>{})};r();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],s=t===e.length-1;this._writer.write(n).then(()=>{s&&v(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends q{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=N&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new P(j,this.uri(),e)}}},V=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,W=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function K(e){if(e.length>8e3)throw"URI too long";const t=e,n=e.indexOf("["),s=e.indexOf("]");-1!=n&&-1!=s&&(e=e.substring(0,n)+e.substring(n,s).replace(/:/g,";")+e.substring(s,e.length));let i=V.exec(e||""),r={},o=14;for(;o--;)r[W[o]]=i[o]||"";return-1!=n&&-1!=s&&(r.source=t,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=function(e,t){const n=/\/{2,9}/g,s=t.replace(n,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||s.splice(0,1);"/"==t.slice(-1)&&s.splice(s.length-1,1);return s}(0,r.path),r.queryKey=function(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,s){t&&(n[t]=s)}),n}(0,r.query),r}const Y="function"==typeof addEventListener&&"function"==typeof removeEventListener,Q=[];Y&&addEventListener("offline",()=>{Q.forEach(e=>e())},!1);class Z extends w{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const n=K(e);t.hostname=n.host,t.secure="https"===n.protocol||"wss"===n.protocol,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=K(t.host).host);C(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{const t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},n=e.split("&");for(let e=0,s=n.length;e<s;e++){let s=n[e].split("=");t[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return t}(this.opts.query)),Y&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Q.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&Z.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",Z.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const n=this.writeBuffer[t].data;if(n&&(e+=A(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,v(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,s){if("function"==typeof t&&(s=t,t=void 0),"function"==typeof n&&(s=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const i={type:e,data:t,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),s&&this.once("flush",s),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(Z.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Y&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=Q.indexOf(this._offlineEventListener);-1!==e&&Q.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}Z.protocol=4;class X extends Z{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;Z.priorWebsocketSuccess=!1;const s=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!n)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Z.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(l(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function i(){n||(n=!0,l(),t.close(),t=null)}const r=e=>{const n=new Error("probe error: "+e);n.transport=t.name,i(),this.emitReserved("upgradeError",n)};function o(){r("transport closed")}function a(){r("socket closed")}function c(e){t&&e.name!==t.name&&i()}const l=()=>{t.removeListener("open",s),t.removeListener("error",r),t.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};t.once("open",s),t.once("error",r),t.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}let J=class extends X{constructor(e,t={}){const n="object"==typeof e?e:t;(!n.transports||n.transports&&"string"==typeof n.transports[0])&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(e=>U[e]).filter(e=>!!e)),super(e,n)}};const G="function"==typeof ArrayBuffer,ee=Object.prototype.toString,te="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===ee.call(Blob),ne="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===ee.call(File);function se(e){return G&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||te&&e instanceof Blob||ne&&e instanceof File}function ie(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(ie(e[t]))return!0;return!1}if(se(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return ie(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&ie(e[t]))return!0;return!1}function re(e){const t=[],n=e.data,s=e;return s.data=oe(n,t),s.attachments=t.length,{packet:s,buffers:t}}function oe(e,t){if(!e)return e;if(se(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){const n=new Array(e.length);for(let s=0;s<e.length;s++)n[s]=oe(e[s],t);return n}if("object"==typeof e&&!(e instanceof Date)){const n={};for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=oe(e[s],t));return n}return e}function ae(e,t){return e.data=ce(e.data,t),delete e.attachments,e}function ce(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=ce(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=ce(e[n],t));return e}const le=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var he;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(he||(he={}));class pe extends w{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===he.BINARY_EVENT;n||t.type===he.BINARY_ACK?(t.type=n?he.EVENT:he.ACK,this.reconstructor=new de(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!se(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(void 0===he[n.type])throw new Error("unknown packet type "+n.type);if(n.type===he.BINARY_EVENT||n.type===he.BINARY_ACK){const s=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const i=e.substring(s,t);if(i!=Number(i)||"-"!==e.charAt(t))throw new Error("Illegal attachments");n.attachments=Number(i)}if("/"===e.charAt(t+1)){const s=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}n.nsp=e.substring(s,t)}else n.nsp="/";const s=e.charAt(t+1);if(""!==s&&Number(s)==s){const s=t+1;for(;++t;){const n=e.charAt(t);if(null==n||Number(n)!=n){--t;break}if(t===e.length)break}n.id=Number(e.substring(s,t+1))}if(e.charAt(++t)){const s=this.tryParse(e.substr(t));if(!pe.isPayloadValid(n.type,s))throw new Error("invalid payload");n.data=s}return n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case he.CONNECT:return be(t);case he.DISCONNECT:return void 0===t;case he.CONNECT_ERROR:return"string"==typeof t||be(t);case he.EVENT:case he.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===le.indexOf(t[0]));case he.ACK:case he.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class de{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=ae(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function be(e){return"[object Object]"===Object.prototype.toString.call(e)}var ue=Object.freeze({__proto__:null,Decoder:pe,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==he.EVENT&&e.type!==he.ACK||!ie(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===he.EVENT?he.BINARY_EVENT:he.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==he.BINARY_EVENT&&e.type!==he.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=re(e),n=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(n),s}},get PacketType(){return he}});function ge(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const fe=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class me extends w{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[ge(e,"open",this.onopen.bind(this)),ge(e,"packet",this.onpacket.bind(this)),ge(e,"error",this.onerror.bind(this)),ge(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,s,i;if(fe.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const r={type:he.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),r.id=e}const o=null===(s=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===s?void 0:s.writable,a=this.connected&&!(null===(i=this.io.engine)||void 0===i?void 0:i._hasPingExpired());return this.flags.volatile&&!o||(a?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,t){var n;const s=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===s)return void(this.acks[e]=t);const i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},s),r=(...e)=>{this.io.clearTimeoutFn(i),t.apply(this,e)};r.withError=!0,this.acks[e]=r}emitWithAck(e,...t){return new Promise((n,s)=>{const i=(e,t)=>e?s(e):n(t);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...s)=>{this._queue[0];return null!==e?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...s)),n.pending=!1,this._drainQueue()}),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:he.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case he.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case he.EVENT:case he.BINARY_EVENT:this.onevent(e);break;case he.ACK:case he.BINARY_ACK:this.onack(e);break;case he.DISCONNECT:this.ondisconnect();break;case he.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...s){n||(n=!0,t.packet({type:he.ACK,id:e,data:s}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:he.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function xe(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}xe.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+n:e-n}return 0|Math.min(e,this.max)},xe.prototype.reset=function(){this.attempts=0},xe.prototype.setMin=function(e){this.ms=e},xe.prototype.setMax=function(e){this.max=e},xe.prototype.setJitter=function(e){this.jitter=e};class ye extends w{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,C(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=t.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new xe({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const s=t.parser||ue;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new J(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const s=ge(t,"open",function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},r=ge(t,"error",i);if(!1!==this._timeout){const e=this._timeout,n=this.setTimeoutFn(()=>{s(),i(new Error("timeout")),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(s),this.subs.push(r),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(ge(e,"ping",this.onping.bind(this)),ge(e,"data",this.ondata.bind(this)),ge(e,"error",this.onerror.bind(this)),ge(e,"close",this.onclose.bind(this)),ge(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){v(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new me(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),null===(n=this.engine)||void 0===n||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const ke={};function we(e,t){"object"==typeof e&&(t=e,e=void 0);const n=function(e,t="",n){let s=e;n=n||"undefined"!=typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==n?n.protocol+"//"+e:"https://"+e),s=K(e)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const i=-1!==s.host.indexOf(":")?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+i+":"+s.port+t,s.href=s.protocol+"://"+i+(n&&n.port===s.port?"":":"+s.port),s}(e,(t=t||{}).path||"/socket.io"),s=n.source,i=n.id,r=n.path,o=ke[i]&&r in ke[i].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new ye(s,t):(ke[i]||(ke[i]=new ye(s,t)),a=ke[i]),n.query&&!t.query&&(t.query=n.queryKey),a.socket(n.path,t)}function ve(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}Object.assign(we,{Manager:ye,Socket:me,io:we,connect:we});var _e={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};function Se(e){_e=e}var Ee={exec:()=>null};function Te(e,t=""){let n="string"==typeof e?e:e.source,s={replace:(e,t)=>{let i="string"==typeof t?t:t.source;return i=i.replace(Ae.caret,"$1"),n=n.replace(e,i),s},getRegex:()=>new RegExp(n,t)};return s}var Ce=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),Ae={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[\t ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}>`)},$e=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Re=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Le=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Be=Te(Le).replace(/bull/g,Re).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),ze=Te(Le).replace(/bull/g,Re).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Ie=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Oe=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,qe=Te(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Oe).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Pe=Te(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Re).getRegex(),Me="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Ne=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,je=Te("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$))","i").replace("comment",Ne).replace("tag",Me).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),He=Te(Ie).replace("hr",$e).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Me).getRegex(),De={blockquote:Te(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",He).getRegex(),code:/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,def:qe,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,hr:$e,html:je,lheading:Be,list:Pe,newline:/^(?:[ \t]*(?:\n|$))+/,paragraph:He,table:Ee,text:/^[^\n]+/},Fe=Te("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",$e).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3}\t)[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Me).getRegex(),Ue={...De,lheading:ze,table:Fe,paragraph:Te(Ie).replace("hr",$e).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Fe).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Me).getRegex()},Ve={...De,html:Te("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\s[^'\"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",Ne).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Ee,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Te(Ie).replace("hr",$e).replace("heading"," *#{1,6} *[^\n]").replace("lheading",Be).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},We=/^( {2,}|\\)\n(?!\s*$)/,Ke=/[\p{P}\p{S}]/u,Ye=/[\s\p{P}\p{S}]/u,Qe=/[^\s\p{P}\p{S}]/u,Ze=Te(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Ye).getRegex(),Xe=/(?!~)[\p{P}\p{S}]/u,Je=/(?![*_])[\p{P}\p{S}]/u,Ge=Te(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Ce?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),et=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,tt=Te(et,"u").replace(/punct/g,Ke).getRegex(),nt=Te(et,"u").replace(/punct/g,Xe).getRegex(),st="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",it=Te(st,"gu").replace(/notPunctSpace/g,Qe).replace(/punctSpace/g,Ye).replace(/punct/g,Ke).getRegex(),rt=Te(st,"gu").replace(/notPunctSpace/g,/(?:[^\s\p{P}\p{S}]|~)/u).replace(/punctSpace/g,/(?!~)[\s\p{P}\p{S}]/u).replace(/punct/g,Xe).getRegex(),ot=Te("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Qe).replace(/punctSpace/g,Ye).replace(/punct/g,Ke).getRegex(),at=Te(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Je).getRegex(),ct=Te("^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)","gu").replace(/notPunctSpace/g,/(?:[^\s\p{P}\p{S}]|[*_])/u).replace(/punctSpace/g,/(?![*_])[\s\p{P}\p{S}]/u).replace(/punct/g,Je).getRegex(),lt=Te(/\\(punct)/,"gu").replace(/punct/g,Ke).getRegex(),ht=Te(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),pt=Te(Ne).replace("(?:--\x3e|$)","--\x3e").getRegex(),dt=Te("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",pt).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),bt=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,ut=Te(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",bt).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),gt=Te(/^!?\[(label)\]\[(ref)\]/).replace("label",bt).replace("ref",Oe).getRegex(),ft=Te(/^!?\[(ref)\](?:\[\])?/).replace("ref",Oe).getRegex(),mt=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,xt={_backpedal:Ee,anyPunctuation:lt,autolink:ht,blockSkip:Ge,br:We,code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,del:Ee,delLDelim:Ee,delRDelim:Ee,emStrongLDelim:tt,emStrongRDelimAst:it,emStrongRDelimUnd:ot,escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,link:ut,nolink:ft,punctuation:Ze,reflink:gt,reflinkSearch:Te("reflink|nolink(?!\\()","g").replace("reflink",gt).replace("nolink",ft).getRegex(),tag:dt,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,url:Ee},yt={...xt,link:Te(/^!?\[(label)\]\((.*?)\)/).replace("label",bt).getRegex(),reflink:Te(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",bt).getRegex()},kt={...xt,emStrongRDelimAst:rt,emStrongLDelim:nt,delLDelim:at,delRDelim:ct,url:Te(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",mt).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:Te(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",mt).getRegex()},wt={...kt,br:Te(We).replace("{2,}","*").getRegex(),text:Te(kt.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},vt={normal:De,gfm:Ue,pedantic:Ve},_t={normal:xt,gfm:kt,breaks:wt,pedantic:yt},St={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Et=e=>St[e];function Tt(e,t){if(t){if(Ae.escapeTest.test(e))return e.replace(Ae.escapeReplace,Et)}else if(Ae.escapeTestNoEncode.test(e))return e.replace(Ae.escapeReplaceNoEncode,Et);return e}function Ct(e){try{e=encodeURI(e).replace(Ae.percentDecode,"%")}catch{return null}return e}function At(e,t){let n=e.replace(Ae.findPipe,(e,t,n)=>{let s=!1,i=t;for(;--i>=0&&"\\"===n[i];)s=!s;return s?"|":" |"}).split(Ae.splitPipe),s=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;s<n.length;s++)n[s]=n[s].trim().replace(Ae.slashPipe,"|");return n}function $t(e,t,n){let s=e.length;if(0===s)return"";let i=0;for(;i<s;){if(e.charAt(s-i-1)!==t)break;i++}return e.slice(0,s-i)}function Rt(e,t=0){let n=t,s="";for(let t of e)if("\t"===t){let e=4-n%4;s+=" ".repeat(e),n+=e}else s+=t,n++;return s}function Lt(e,t,n,s,i){let r=t.href,o=t.title||null,a=e[1].replace(i.other.outputLinkReplace,"$1");s.state.inLink=!0;let c={type:"!"===e[0].charAt(0)?"image":"link",raw:n,href:r,title:o,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,c}var Bt=class{options;rules;lexer;constructor(e){this.options=e||_e}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let e=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?e:$t(e,"\n")}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let e=t[0],n=function(e,t,n){let s=e.match(n.other.indentCodeCompensation);if(null===s)return t;let i=s[1];return t.split("\n").map(e=>{let t=e.match(n.other.beginningSpace);if(null===t)return e;let[s]=t;return s.length>=i.length?e.slice(i.length):e}).join("\n")}(e,t[3]||"",this.rules);return{type:"code",raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){let t=$t(e,"#");(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:$t(t[0],"\n")}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=$t(t[0],"\n").split("\n"),n="",s="",i=[];for(;e.length>0;){let t,r=!1,o=[];for(t=0;t<e.length;t++)if(this.rules.other.blockquoteStart.test(e[t]))o.push(e[t]),r=!0;else{if(r)break;o.push(e[t])}e=e.slice(t);let a=o.join("\n"),c=a.replace(this.rules.other.blockquoteSetextReplace,"\n $1").replace(this.rules.other.blockquoteSetextReplace2,"");n=n?`${n}\n${a}`:a,s=s?`${s}\n${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(c,i,!0),this.lexer.state.top=l,0===e.length)break;let h=i.at(-1);if("code"===h?.type)break;if("blockquote"===h?.type){let t=h,r=t.raw+"\n"+e.join("\n"),o=this.blockquote(r);i[i.length-1]=o,n=n.substring(0,n.length-t.raw.length)+o.raw,s=s.substring(0,s.length-t.text.length)+o.text;break}if("list"===h?.type){let t=h,r=t.raw+"\n"+e.join("\n"),o=this.list(r);i[i.length-1]=o,n=n.substring(0,n.length-h.raw.length)+o.raw,s=s.substring(0,s.length-t.raw.length)+o.raw,e=r.substring(i.at(-1).raw.length).split("\n");continue}}return{type:"blockquote",raw:n,tokens:i,text:s}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),s=n.length>1,i={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");let r=this.rules.other.listItemRegex(n),o=!1;for(;e;){let n=!1,s="",a="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;s=t[0],e=e.substring(s.length);let c=Rt(t[2].split("\n",1)[0],t[1].length),l=e.split("\n",1)[0],h=!c.trim(),p=0;if(this.options.pedantic?(p=2,a=c.trimStart()):h?p=t[1].length+1:(p=c.search(this.rules.other.nonSpaceChar),p=p>4?1:p,a=c.slice(p),p+=t[1].length),h&&this.rules.other.blankLine.test(l)&&(s+=l+"\n",e=e.substring(l.length+1),n=!0),!n){let t=this.rules.other.nextBulletRegex(p),n=this.rules.other.hrRegex(p),i=this.rules.other.fencesBeginRegex(p),r=this.rules.other.headingBeginRegex(p),o=this.rules.other.htmlBeginRegex(p),d=this.rules.other.blockquoteBeginRegex(p);for(;e;){let b,u=e.split("\n",1)[0];if(l=u,this.options.pedantic?(l=l.replace(this.rules.other.listReplaceNesting," "),b=l):b=l.replace(this.rules.other.tabCharGlobal," "),i.test(l)||r.test(l)||o.test(l)||d.test(l)||t.test(l)||n.test(l))break;if(b.search(this.rules.other.nonSpaceChar)>=p||!l.trim())a+="\n"+b.slice(p);else{if(h||c.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||i.test(c)||r.test(c)||n.test(c))break;a+="\n"+l}h=!l.trim(),s+=u+"\n",e=e.substring(u.length+1),c=b.slice(p)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(s)&&(o=!0)),i.items.push({type:"list_item",raw:s,task:!!this.options.gfm&&this.rules.other.listIsTask.test(a),loose:!1,text:a,tokens:[]}),i.raw+=s}let a=i.items.at(-1);if(!a)return;a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd(),i.raw=i.raw.trimEnd();for(let e of i.items){if(this.lexer.state.top=!1,e.tokens=this.lexer.blockTokens(e.text,[]),e.task){if(e.text=e.text.replace(this.rules.other.listReplaceTask,""),"text"===e.tokens[0]?.type||"paragraph"===e.tokens[0]?.type){e.tokens[0].raw=e.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),e.tokens[0].text=e.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let e=this.lexer.inlineQueue.length-1;e>=0;e--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[e].src)){this.lexer.inlineQueue[e].src=this.lexer.inlineQueue[e].src.replace(this.rules.other.listReplaceTask,"");break}}let t=this.rules.other.listTaskCheckbox.exec(e.raw);if(t){let n={type:"checkbox",raw:t[0]+" ",checked:"[ ]"!==t[0]};e.checked=n.checked,i.loose?e.tokens[0]&&["paragraph","text"].includes(e.tokens[0].type)&&"tokens"in e.tokens[0]&&e.tokens[0].tokens?(e.tokens[0].raw=n.raw+e.tokens[0].raw,e.tokens[0].text=n.raw+e.tokens[0].text,e.tokens[0].tokens.unshift(n)):e.tokens.unshift({type:"paragraph",raw:n.raw,text:n.raw,tokens:[n]}):e.tokens.unshift(n)}}if(!i.loose){let t=e.tokens.filter(e=>"space"===e.type),n=t.length>0&&t.some(e=>this.rules.other.anyLine.test(e.raw));i.loose=n}}if(i.loose)for(let e of i.items){e.loose=!0;for(let t of e.tokens)"text"===t.type&&(t.type="paragraph")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:"html",block:!0,raw:t[0],pre:"pre"===t[1]||"script"===t[1]||"style"===t[1],text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let e=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:e,raw:t[0],href:n,title:s}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=At(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split("\n"):[],r={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===s.length){for(let e of s)this.rules.other.tableAlignRight.test(e)?r.align.push("right"):this.rules.other.tableAlignCenter.test(e)?r.align.push("center"):this.rules.other.tableAlignLeft.test(e)?r.align.push("left"):r.align.push(null);for(let e=0;e<n.length;e++)r.header.push({text:n[e],tokens:this.lexer.inline(n[e]),header:!0,align:r.align[e]});for(let e of i)r.rows.push(At(e,r.header.length).map((e,t)=>({text:e,tokens:this.lexer.inline(e),header:!1,align:r.align[t]})));return r}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:"="===t[2].charAt(0)?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let e="\n"===t[1].charAt(t[1].length-1)?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;let t=$t(e.slice(0,-1),"\\");if((e.length-t.length)%2==0)return}else{let e=function(e,t){if(-1===e.indexOf(t[1]))return-1;let n=0;for(let s=0;s<e.length;s++)if("\\"===e[s])s++;else if(e[s]===t[0])n++;else if(e[s]===t[1]&&(n--,n<0))return s;return n>0?-2:-1}(t[2],"()");if(-2===e)return;if(e>-1){let n=(0===t[0].indexOf("!")?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let n=t[2],s="";if(this.options.pedantic){let e=this.rules.other.pedanticHrefTitle.exec(n);e&&(n=e[1],s=e[3])}else s=t[3]?t[3].slice(1,-1):"";return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(n=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?n.slice(1):n.slice(1,-1)),Lt(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,"$1"),title:s&&s.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let e=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," ").toLowerCase()];if(!e){let e=n[0].charAt(0);return{type:"text",raw:e,text:e}}return Lt(n,e,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||s[3]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!s[1]&&!s[2]||!n||this.rules.inline.punctuation.exec(n))){let n,i,r=[...s[0]].length-1,o=r,a=0,c="*"===s[0][0]?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+r);null!=(s=c.exec(t));){if(n=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!n)continue;if(i=[...n].length,s[3]||s[4]){o+=i;continue}if((s[5]||s[6])&&r%3&&!((r+i)%3)){a+=i;continue}if(o-=i,o>0)continue;i=Math.min(i,i+o+a);let t=[...s[0]][0].length,c=e.slice(0,r+s.index+t+i);if(Math.min(r,i)%2){let e=c.slice(1,-1);return{type:"em",raw:c,text:e,tokens:this.lexer.inlineTokens(e)}}let l=c.slice(2,-2);return{type:"strong",raw:c,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal," "),n=this.rules.other.nonSpaceChar.test(e),s=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&s&&(e=e.substring(1,e.length-1)),{type:"codespan",raw:t[0],text:e}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!n||this.rules.inline.punctuation.exec(n))){let n,i,r=[...s[0]].length-1,o=r,a=this.rules.inline.delRDelim;for(a.lastIndex=0,t=t.slice(-1*e.length+r);null!=(s=a.exec(t));){if(n=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!n||(i=[...n].length,i!==r))continue;if(s[3]||s[4]){o+=i;continue}if(o-=i,o>0)continue;i=Math.min(i,i+o);let t=[...s[0]][0].length,a=e.slice(0,r+s.index+t+i),c=a.slice(r,-r);return{type:"del",raw:a,text:c,tokens:this.lexer.inlineTokens(c)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let e,n;return"@"===t[2]?(e=t[1],n="mailto:"+e):(e=t[1],n=e),{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if("@"===t[2])e=t[0],n="mailto:"+e;else{let s;do{s=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??""}while(s!==t[0]);e=t[0],n="www."===t[1]?"http://"+t[0]:t[0]}return{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let e=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:e}}}},zt=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||_e,this.options.tokenizer=this.options.tokenizer||new Bt,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:Ae,block:vt.normal,inline:_t.normal};this.options.pedantic?(t.block=vt.pedantic,t.inline=_t.pedantic):this.options.gfm&&(t.block=vt.gfm,this.options.breaks?t.inline=_t.breaks:t.inline=_t.gfm),this.tokenizer.rules=t}static get rules(){return{block:vt,inline:_t}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(e){e=e.replace(Ae.carriageReturn,"\n"),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){let t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){for(this.options.pedantic&&(e=e.replace(Ae.tabCharGlobal," ").replace(Ae.spaceLine,""));e;){let s;if(this.options.extensions?.block?.some(n=>!!(s=n.call({lexer:this},e,t))&&(e=e.substring(s.raw.length),t.push(s),!0)))continue;if(s=this.tokenizer.space(e)){e=e.substring(s.raw.length);let n=t.at(-1);1===s.raw.length&&void 0!==n?n.raw+="\n":t.push(s);continue}if(s=this.tokenizer.code(e)){e=e.substring(s.raw.length);let n=t.at(-1);"paragraph"===n?.type||"text"===n?.type?(n.raw+=(n.raw.endsWith("\n")?"":"\n")+s.raw,n.text+="\n"+s.text,this.inlineQueue.at(-1).src=n.text):t.push(s);continue}if(s=this.tokenizer.fences(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.heading(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.hr(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.blockquote(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.list(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.html(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.def(e)){e=e.substring(s.raw.length);let n=t.at(-1);"paragraph"===n?.type||"text"===n?.type?(n.raw+=(n.raw.endsWith("\n")?"":"\n")+s.raw,n.text+="\n"+s.raw,this.inlineQueue.at(-1).src=n.text):this.tokens.links[s.tag]||(this.tokens.links[s.tag]={href:s.href,title:s.title},t.push(s));continue}if(s=this.tokenizer.table(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.lheading(e)){e=e.substring(s.raw.length),t.push(s);continue}let i=e;if(this.options.extensions?.startBlock){let t,n=1/0,s=e.slice(1);this.options.extensions.startBlock.forEach(e=>{t=e.call({lexer:this},s),"number"==typeof t&&t>=0&&(n=Math.min(n,t))}),n<1/0&&n>=0&&(i=e.substring(0,n+1))}if(this.state.top&&(s=this.tokenizer.paragraph(i))){let r=t.at(-1);n&&"paragraph"===r?.type?(r.raw+=(r.raw.endsWith("\n")?"":"\n")+s.raw,r.text+="\n"+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=r.text):t.push(s),n=i.length!==e.length,e=e.substring(s.raw.length);continue}if(s=this.tokenizer.text(e)){e=e.substring(s.raw.length);let n=t.at(-1);"text"===n?.type?(n.raw+=(n.raw.endsWith("\n")?"":"\n")+s.raw,n.text+="\n"+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(s);continue}if(e){let t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n,s=e,i=null;if(this.tokens.links){let e=Object.keys(this.tokens.links);if(e.length>0)for(;null!=(i=this.tokenizer.rules.inline.reflinkSearch.exec(s));)e.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;null!=(i=this.tokenizer.rules.inline.anyPunctuation.exec(s));)s=s.slice(0,i.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;null!=(i=this.tokenizer.rules.inline.blockSkip.exec(s));)n=i[2]?i[2].length:0,s=s.slice(0,i.index+n)+"["+"a".repeat(i[0].length-n-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let r=!1,o="";for(;e;){let n;if(r||(o=""),r=!1,this.options.extensions?.inline?.some(s=>!!(n=s.call({lexer:this},e,t))&&(e=e.substring(n.raw.length),t.push(n),!0)))continue;if(n=this.tokenizer.escape(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.tag(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.link(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(n.raw.length);let s=t.at(-1);"text"===n.type&&"text"===s?.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);continue}if(n=this.tokenizer.emStrong(e,s,o)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.codespan(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.br(e)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.del(e,s,o)){e=e.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.autolink(e)){e=e.substring(n.raw.length),t.push(n);continue}if(!this.state.inLink&&(n=this.tokenizer.url(e))){e=e.substring(n.raw.length),t.push(n);continue}let i=e;if(this.options.extensions?.startInline){let t,n=1/0,s=e.slice(1);this.options.extensions.startInline.forEach(e=>{t=e.call({lexer:this},s),"number"==typeof t&&t>=0&&(n=Math.min(n,t))}),n<1/0&&n>=0&&(i=e.substring(0,n+1))}if(n=this.tokenizer.inlineText(i)){e=e.substring(n.raw.length),"_"!==n.raw.slice(-1)&&(o=n.raw.slice(-1)),r=!0;let s=t.at(-1);"text"===s?.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);continue}if(e){let t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}return t}},It=class{options;parser;constructor(e){this.options=e||_e}space(e){return""}code({text:e,lang:t,escaped:n}){let s=(t||"").match(Ae.notSpaceStart)?.[0],i=e.replace(Ae.endingNewline,"")+"\n";return s?'<pre><code class="language-'+Tt(s)+'">'+(n?i:Tt(i,!0))+"</code></pre>\n":"<pre><code>"+(n?i:Tt(i,!0))+"</code></pre>\n"}blockquote({tokens:e}){return`<blockquote>\n${this.parser.parse(e)}</blockquote>\n`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>\n`}hr(e){return"<hr>\n"}list(e){let t=e.ordered,n=e.start,s="";for(let t=0;t<e.items.length;t++){let n=e.items[t];s+=this.listitem(n)}let i=t?"ol":"ul";return"<"+i+(t&&1!==n?' start="'+n+'"':"")+">\n"+s+"</"+i+">\n"}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>\n`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>\n`}table(e){let t="",n="";for(let t=0;t<e.header.length;t++)n+=this.tablecell(e.header[t]);t+=this.tablerow({text:n});let s="";for(let t=0;t<e.rows.length;t++){let i=e.rows[t];n="";for(let e=0;e<i.length;e++)n+=this.tablecell(i[e]);s+=this.tablerow({text:n})}return s&&(s=`<tbody>${s}</tbody>`),"<table>\n<thead>\n"+t+"</thead>\n"+s+"</table>\n"}tablerow({text:e}){return`<tr>\n${e}</tr>\n`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>\n`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${Tt(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let s=this.parser.parseInline(n),i=Ct(e);if(null===i)return s;let r='<a href="'+(e=i)+'"';return t&&(r+=' title="'+Tt(t)+'"'),r+=">"+s+"</a>",r}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let i=Ct(e);if(null===i)return Tt(n);let r=`<img src="${e=i}" alt="${Tt(n)}"`;return t&&(r+=` title="${Tt(t)}"`),r+=">",r}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Tt(e.text)}},Ot=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},qt=class e{options;renderer;textRenderer;constructor(e){this.options=e||_e,this.options.renderer=this.options.renderer||new It,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ot}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){let t="";for(let n=0;n<e.length;n++){let s=e[n];if(this.options.extensions?.renderers?.[s.type]){let e=s,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(!1!==n||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(e.type)){t+=n||"";continue}}let i=s;switch(i.type){case"space":t+=this.renderer.space(i);break;case"hr":t+=this.renderer.hr(i);break;case"heading":t+=this.renderer.heading(i);break;case"code":t+=this.renderer.code(i);break;case"table":t+=this.renderer.table(i);break;case"blockquote":t+=this.renderer.blockquote(i);break;case"list":t+=this.renderer.list(i);break;case"checkbox":t+=this.renderer.checkbox(i);break;case"html":t+=this.renderer.html(i);break;case"def":t+=this.renderer.def(i);break;case"paragraph":t+=this.renderer.paragraph(i);break;case"text":t+=this.renderer.text(i);break;default:{let e='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return t}parseInline(e,t=this.renderer){let n="";for(let s=0;s<e.length;s++){let i=e[s];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(!1!==e||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(i.type)){n+=e||"";continue}}let r=i;switch(r.type){case"escape":case"text":n+=t.text(r);break;case"html":n+=t.html(r);break;case"link":n+=t.link(r);break;case"image":n+=t.image(r);break;case"checkbox":n+=t.checkbox(r);break;case"strong":n+=t.strong(r);break;case"em":n+=t.em(r);break;case"codespan":n+=t.codespan(r);break;case"br":n+=t.br(r);break;case"del":n+=t.del(r);break;default:{let e='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return n}},Pt=class{options;block;constructor(e){this.options=e||_e}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(){return this.block?zt.lex:zt.lexInline}provideParser(){return this.block?qt.parse:qt.parseInline}},Mt=new class{defaults={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=qt;Renderer=It;TextRenderer=Ot;Lexer=zt;Tokenizer=Bt;Hooks=Pt;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let s of e)switch(n=n.concat(t.call(this,s)),s.type){case"table":{let e=s;for(let s of e.header)n=n.concat(this.walkTokens(s.tokens,t));for(let s of e.rows)for(let e of s)n=n.concat(this.walkTokens(e.tokens,t));break}case"list":{let e=s;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=s;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(s=>{let i=e[s].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw new Error("extension name required");if("renderer"in e){let n=t.renderers[e.name];t.renderers[e.name]=n?function(...t){let s=e.renderer.apply(this,t);return!1===s&&(s=n.apply(this,t)),s}:e.renderer}if("tokenizer"in e){if(!e.level||"block"!==e.level&&"inline"!==e.level)throw new Error("extension level must be 'block' or 'inline'");let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&("block"===e.level?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:"inline"===e.level&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}"childTokens"in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new It(this.defaults);for(let n in e.renderer){if(!(n in t))throw new Error(`renderer '${n}' does not exist`);if(["options","parser"].includes(n))continue;let s=n,i=e.renderer[s],r=t[s];t[s]=(...e)=>{let n=i.apply(t,e);return!1===n&&(n=r.apply(t,e)),n||""}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new Bt(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw new Error(`tokenizer '${n}' does not exist`);if(["options","rules","lexer"].includes(n))continue;let s=n,i=e.tokenizer[s],r=t[s];t[s]=(...e)=>{let n=i.apply(t,e);return!1===n&&(n=r.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new Pt;for(let n in e.hooks){if(!(n in t))throw new Error(`hook '${n}' does not exist`);if(["options","block"].includes(n))continue;let s=n,i=e.hooks[s],r=t[s];Pt.passThroughHooks.has(n)?t[s]=e=>{if(this.defaults.async&&Pt.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return r.call(t,n)})();let s=i.call(t,e);return r.call(t,s)}:t[s]=(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return!1===n&&(n=await r.apply(t,e)),n})();let n=i.apply(t,e);return!1===n&&(n=r.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,s=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(s.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return zt.lex(e,t??this.defaults)}parser(e,t){return qt.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let s={...n},i={...this.defaults,...s},r=this.onError(!!i.silent,!!i.async);if(!0===this.defaults.async&&!1===s.async)return r(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||null===t)return r(new Error("marked(): input parameter is undefined or null"));if("string"!=typeof t)return r(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,s=await(i.hooks?await i.hooks.provideLexer():e?zt.lex:zt.lexInline)(n,i),r=i.hooks?await i.hooks.processAllTokens(s):s;i.walkTokens&&await Promise.all(this.walkTokens(r,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser():e?qt.parse:qt.parseInline)(r,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(r);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer():e?zt.lex:zt.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let s=(i.hooks?i.hooks.provideParser():e?qt.parse:qt.parseInline)(n,i);return i.hooks&&(s=i.hooks.postprocess(s)),s}catch(e){return r(e)}}}onError(e,t){return n=>{if(n.message+="\nPlease report this to https://github.com/markedjs/marked.",e){let e="<p>An error occurred:</p><pre>"+Tt(n.message+"",!0)+"</pre>";return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function Nt(e,t){return Mt.parse(e,t)}Nt.options=Nt.setOptions=function(e){return Mt.setOptions(e),Nt.defaults=Mt.defaults,Se(Nt.defaults),Nt},Nt.getDefaults=ve,Nt.defaults=_e,Nt.use=function(...e){return Mt.use(...e),Nt.defaults=Mt.defaults,Se(Nt.defaults),Nt},Nt.walkTokens=function(e,t){return Mt.walkTokens(e,t)},Nt.parseInline=Mt.parseInline,Nt.Parser=qt,Nt.parser=qt.parse,Nt.Renderer=It,Nt.TextRenderer=Ot,Nt.Lexer=zt,Nt.lexer=zt.lex,Nt.Tokenizer=Bt,Nt.Hooks=Pt,Nt.parse=Nt,Nt.options,Nt.setOptions,Nt.use,Nt.walkTokens,Nt.parseInline,qt.parse,zt.lex,Nt.setOptions({breaks:!0,gfm:!0});const jt={chat:'<svg viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>\n </svg>',close:'<svg viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round">\n <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>\n </svg>',send:'<svg viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <line x1="22" y1="2" x2="11" y2="13"/>\n <polygon points="22 2 15 22 11 13 2 9 22 2"/>\n </svg>',bot:'<svg viewBox="0 0 24 24" fill="white">\n <path d="M12 2a2 2 0 0 1 2 2c0 .74-.4 1.39-1 1.73V7h1a7 7 0 0 1 7 7H3a7 7 0 0 1 7-7h1V5.73c-.6-.34-1-.99-1-1.73a2 2 0 0 1 2-2zM7.5 14a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3zm9 0a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3zM3 21v-2h18v2H3z"/>\n </svg>',user:'<svg viewBox="0 0 24 24" fill="white">\n <path d="M12 12c2.7 0 4.8-2.1 4.8-4.8S14.7 2.4 12 2.4 7.2 4.5 7.2 7.2 9.3 12 12 12zm0 2.4c-3.2 0-9.6 1.6-9.6 4.8v2.4h19.2v-2.4c0-3.2-6.4-4.8-9.6-4.8z"/>\n </svg>',shield:'<svg viewBox="0 0 24 24">\n <path d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5l-9-4z"/>\n </svg>',expand:'<svg viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/>\n <line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/>\n </svg>',collapse:'<svg viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <polyline points="4 14 10 14 10 20"/><polyline points="20 10 14 10 14 4"/>\n <line x1="10" y1="14" x2="3" y2="21"/><line x1="21" y1="3" x2="14" y2="10"/>\n </svg>',history:'<svg viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <circle cx="12" cy="12" r="10"/>\n <polyline points="12 6 12 12 16 14"/>\n </svg>',trash:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <polyline points="3 6 5 6 21 6"/>\n <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>\n </svg>',sparkle:'<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 1l2.4 7.6L22 12l-7.6 2.4L12 22l-2.4-7.6L2 12l7.6-2.4L12 1z"/></svg>',minimize:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><polyline points="4 14 10 14 10 20"/><line x1="21" y1="3" x2="10" y2="14"/></svg>',copy:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>',check:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',thumbUp:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3H14z"/><path d="M7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3"/></svg>',thumbDown:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3H10z"/><path d="M17 2h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17"/></svg>',download:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>'};function Ht(e){return e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}class Dt{constructor(e){this.socket=null,this.messages=[],this.conversationId=null,this.sessionId=null,this.isOpen=!1,this.isTyping=!1,this.isExpanded=!1,this.isHistoryOpen=!1,this.unreadCount=0,this.lastRole=null,this.sessionStorageKey="chatbolt_session_id",this.isWelcomeVisible=!0,this.activeTab="chat",this.conversations=[],this.conversationsKey="chatbolt_conversations",this.activeSessionKey="chatbolt_active_session",this.config=Object.assign({serverUrl:"https://backend-api-chatbolt-backend.hf.space",position:"bottom-right",theme:"auto",accentColor:"#6366f1",placeholder:"Messageโ€ฆ",title:"AI Assistant",subtitle:"Online ยท Powered by XtroEdge",botAvatar:"",triggerIcon:"",triggerText:"",autoOpen:!1,greetingMessage:"Hi there! ๐Ÿ‘‹ How can I help you today?",zIndex:2147483647,conversationId:"",showBranding:!0,gradientEndColor:"",quickReplies:[],welcomeName:"",disclaimerText:""},e),this.config.conversationId&&(this.conversationId=this.config.conversationId),this.buildDOM(),this.applyTheme(),this.connectSocket(),this.restoreMessagesFromHistory(),this.config.autoOpen?setTimeout(()=>this.open(),600):0===this.messages.length&&this.config.greetingMessage&&this.addMessage("assistant",this.config.greetingMessage,!0)}buildDOM(){this.ensureStyles(),this.container=document.createElement("div"),this.container.className=`cb-widget cb-pos-${this.config.position}`;const e=this.config.accentColor.replace("#",""),t=parseInt(e.slice(0,2),16),n=parseInt(e.slice(2,4),16),s=parseInt(e.slice(4,6),16),i=`${t},${n},${s}`;this.container.style.setProperty("--cb-accent",this.config.accentColor),this.container.style.setProperty("--cb-accent-rgb",i);const r=this.config.gradientEndColor?this.config.gradientEndColor.replace("#",""):null,o=r?parseInt(r.slice(0,2),16):t,a=r?parseInt(r.slice(2,4),16):Math.max(0,n-20),c=r?parseInt(r.slice(4,6),16):Math.min(255,s+20);this.container.style.setProperty("--cb-grad",`linear-gradient(135deg, rgba(${i},1) 0%, rgba(${o},${a},${c},1) 100%)`),this.container.style.setProperty("--cb-grad-soft",`linear-gradient(135deg, rgba(${i},0.82) 0%, rgba(${o},${a},${c},0.68) 100%)`),this.container.style.setProperty("--cb-accent-glow",`rgba(${i},0.35)`),this.container.style.setProperty("--cb-accent-ring",`rgba(${i},0.18)`),this.container.style.setProperty("--cb-z",String(this.config.zIndex));const l=this.config.botAvatar?`<img src="${this.config.botAvatar}" alt="bot">`:jt.bot,h=this.config.welcomeName||"there",p=(this.config.quickReplies||[]).map(e=>`<button class="cb-quick-reply-btn">${this.esc(e)}</button>`).join(""),d=this.config.title.match(/^(.+?)\s*AI\b/i),b=d?d[1].toUpperCase():this.config.title.toUpperCase();let u="";this.config.disclaimerText?u=`<div class="cb-disclaimer">${this.esc(this.config.disclaimerText)}</div>`:!1!==this.config.showBranding&&(u='<div class="cb-footer"><span class="cb-footer-dot"></span> Powered by <a href="#" target="_blank" rel="noopener">ChatBolt</a></div>'),this.container.innerHTML=`\n <button class="cb-trigger" aria-label="Open chat">\n <span class="cb-icon-chat">${jt.chat}</span>\n <span class="cb-icon-close">${jt.close}</span>\n <span class="cb-trigger-text">${this.esc(this.config.triggerText||this.config.title||"Chat")}</span>\n <span class="cb-badge" style="display:none">0</span>\n </button>\n\n <div class="cb-window cb-hidden" role="dialog" aria-label="${this.esc(this.config.title)} chat">\n \x3c!-- Tab Bar --\x3e\n <div class="cb-tab-bar">\n <div class="cb-tabs">\n <button class="cb-tab cb-active" data-tab="chat">Chat</button>\n <button class="cb-tab" data-tab="history">History</button>\n </div>\n <div class="cb-tab-actions">\n <button class="cb-tab-action-btn cb-new-chat-btn" aria-label="New Chat">\n <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>\n </button>\n <button class="cb-export-btn" aria-label="Export Chat">\n <span class="cb-tooltip">Export PDF</span>\n ${jt.download}\n </button>\n <button class="cb-tab-action-btn cb-close-btn" aria-label="Close">${jt.close}</button>\n </div>\n </div>\n\n \x3c!-- Welcome / Landing Page --\x3e\n <div class="cb-welcome">\n <div class="cb-welcome-logo">\n <span class="cb-welcome-logo-icon">${jt.sparkle}</span>\n <span class="cb-welcome-logo-text">${this.esc(b)}</span>\n <span class="cb-welcome-logo-badge">AI</span>\n </div>\n <div class="cb-welcome-greeting">Hello ${this.esc(h)} ๐Ÿ‘‹</div>\n <div class="cb-welcome-subtitle">How can I help you today?</div>\n ${p?`<div class="cb-quick-replies">${p}</div>`:""}\n </div>\n\n \x3c!-- Chat Messages (hidden initially) --\x3e\n <div class="cb-messages" role="log" aria-live="polite" style="display:none"></div>\n\n \x3c!-- History Panel (tab-based) --\x3e\n <div class="cb-history-panel">\n <div class="cb-history-panel-header">\n <div class="cb-welcome-logo">\n <span class="cb-welcome-logo-icon">${jt.sparkle}</span>\n <span class="cb-welcome-logo-text">${this.esc(b)}</span>\n <span class="cb-welcome-logo-badge">AI</span>\n </div>\n <div class="cb-history-panel-title">Chat History</div>\n <div class="cb-history-panel-subtitle">Your previous conversations</div>\n </div>\n <div class="cb-history-section-header">\n <span class="cb-history-count">Recent Chats</span>\n <button class="cb-history-clear-btn">${jt.trash} Clear All</button>\n </div>\n <div class="cb-history-list"></div>\n </div>\n\n \x3c!-- Input Area --\x3e\n <div class="cb-input-area">\n <div class="cb-input-wrap">\n <textarea class="cb-input" rows="1"\n placeholder="${this.esc(this.config.placeholder)}"\n aria-label="Message input"></textarea>\n </div>\n <button class="cb-send-btn" aria-label="Send">${jt.send}</button>\n </div>\n\n ${u}\n </div>\n `,document.body.appendChild(this.container),this.trigger=this.container.querySelector(".cb-trigger"),this.window=this.container.querySelector(".cb-window"),this.messagesEl=this.container.querySelector(".cb-messages"),this.inputEl=this.container.querySelector(".cb-input"),this.sendBtn=this.container.querySelector(".cb-send-btn"),this.badgeEl=this.container.querySelector(".cb-badge"),this.expandBtn=this.container.querySelector(".cb-expand-btn"),this.welcomeEl=this.container.querySelector(".cb-welcome"),this.historyPanel=this.container.querySelector(".cb-history-panel"),this.historyList=this.container.querySelector(".cb-history-list"),this.chatTabBtn=this.container.querySelector('.cb-tab[data-tab="chat"]'),this.historyTabBtn=this.container.querySelector('.cb-tab[data-tab="history"]'),this.historyDrawer=this.historyPanel,this.closeHistoryBtn=null,this.clearHistoryBtn=this.container.querySelector(".cb-history-clear-btn"),this.historyBtn=this.historyTabBtn,this.typingEl=document.createElement("div"),this.typingEl.className="cb-typing-wrap",this.typingEl.innerHTML=`\n <div class="cb-msg-avatar">${l}</div>\n <div class="cb-typing"><span></span><span></span><span></span></div>`,this.setupTriggerDrag(),this.container.querySelector(".cb-close-btn").addEventListener("click",()=>this.close()),this.container.querySelector(".cb-new-chat-btn").addEventListener("click",()=>this.startNewChat()),this.container.querySelector(".cb-export-btn").addEventListener("click",()=>this.exportChatPDF()),this.expandBtn&&this.expandBtn.addEventListener("click",()=>this.toggleExpand()),this.chatTabBtn.addEventListener("click",()=>this.switchTab("chat")),this.historyTabBtn.addEventListener("click",()=>this.switchTab("history")),this.clearHistoryBtn&&this.clearHistoryBtn.addEventListener("click",()=>this.clearHistory()),this.container.querySelectorAll(".cb-quick-reply-btn").forEach(e=>{e.addEventListener("click",()=>{var t;const n=null===(t=e.textContent)||void 0===t?void 0:t.trim();n&&(this.hideWelcome(),this.send(n))})}),this.sendBtn.addEventListener("click",()=>this.send()),this.inputEl.addEventListener("keydown",e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),this.send())}),this.inputEl.addEventListener("input",()=>this.autoResize()),this.loadHistory()}ensureStyles(){if("undefined"==typeof document)return;if(document.getElementById("cb-widget-style"))return;const e=document.createElement("style");e.id="cb-widget-style",e.textContent="\n/* ChatBolt Widget โ€” Premium Clean Design */\n@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');\n\n.cb-widget {\n --cb-accent: #6366f1;\n --cb-accent-rgb: 99,102,241;\n --cb-accent-glow: rgba(99,102,241,0.32);\n --cb-accent-ring: rgba(99,102,241,0.16);\n --cb-grad: linear-gradient(135deg, rgba(99,102,241,1) 0%, rgba(139,92,246,1) 100%);\n --cb-grad-soft: linear-gradient(135deg, rgba(99,102,241,0.9) 0%, rgba(139,92,246,0.8) 100%);\n\n --cb-window-bg: #ffffff;\n --cb-text: #111827;\n --cb-text-2: #4B5563;\n --cb-text-3: #9CA3AF;\n --cb-msg-bot-bg: #F3F4F6;\n --cb-msg-bot-bd: transparent;\n --cb-input-bg: #ffffff;\n --cb-input-bd: #E5E7EB;\n --cb-divider: #F3F4F6;\n --cb-z: 2147483647;\n\n font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;\n font-size: 14px;\n line-height: 1.5;\n color: var(--cb-text);\n}\n.cb-widget * { box-sizing: border-box; margin: 0; padding: 0; }\n\n.cb-widget.cb-dark {\n --cb-window-bg: #111827;\n --cb-text: #F9FAFB;\n --cb-text-2: #9CA3AF;\n --cb-text-3: #6B7280;\n --cb-msg-bot-bg: #1F2937;\n --cb-msg-bot-bd: transparent;\n --cb-input-bg: #1F2937;\n --cb-input-bd: #374151;\n --cb-divider: #1F2937;\n}\n\n.cb-trigger {\n position: fixed;\n padding: 12px 20px 12px 16px;\n border-radius: 30px;\n background: var(--cb-grad);\n border: none;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 10px;\n z-index: var(--cb-z);\n outline: none;\n transition: transform .3s cubic-bezier(.34,1.56,.64,1), box-shadow .3s ease, border-radius .3s ease, padding .3s ease;\n box-shadow:\n 0 6px 24px var(--cb-accent-glow),\n 0 2px 8px rgba(0,0,0,0.14),\n inset 0 1px 0 rgba(255,255,255,0.28);\n}\n.cb-trigger::after {\n content: '';\n position: absolute;\n inset: 0;\n border-radius: 30px;\n background: linear-gradient(145deg, rgba(255,255,255,0.25) 0%, transparent 55%);\n pointer-events: none;\n}\n.cb-trigger:hover {\n transform: scale(1.04);\n box-shadow:\n 0 8px 28px var(--cb-accent-glow),\n 0 2px 8px rgba(0,0,0,0.12);\n}\n.cb-trigger:active:not(.cb-dragging) { transform: scale(0.95); }\n.cb-trigger.cb-dragging { cursor: grabbing !important; transition: none !important; box-shadow: 0 10px 40px var(--cb-accent-glow), 0 4px 12px rgba(0,0,0,0.2); transform: scale(1.08); }\n.cb-trigger.cb-dragging:hover { transform: scale(1.08); }\n.cb-trigger svg {\n width: 22px; height: 22px; fill: none;\n stroke: white; stroke-width: 2;\n stroke-linecap: round; stroke-linejoin: round;\n position: relative; z-index: 1;\n flex-shrink: 0;\n transition: opacity .25s, transform .35s cubic-bezier(.34,1.56,.64,1);\n}\n.cb-trigger-text {\n color: white;\n font-family: 'Inter', sans-serif;\n font-size: 15px;\n font-weight: 600;\n white-space: nowrap;\n position: relative;\n z-index: 1;\n letter-spacing: 0.3px;\n}\n.cb-trigger .cb-icon-chat { opacity: 1; transform: scale(1) rotate(0deg); }\n.cb-trigger .cb-icon-close { opacity: 0; transform: scale(0.4) rotate(-90deg); position: absolute; }\n.cb-trigger.cb-open { opacity: 0; pointer-events: none; transform: scale(0.5); }\n.cb-pos-bottom-right .cb-trigger { bottom: 24px; right: 24px; }\n.cb-pos-bottom-left .cb-trigger { bottom: 24px; left: 24px; }\n.cb-pos-top-right .cb-trigger { top: 24px; right: 24px; }\n.cb-pos-top-left .cb-trigger { top: 24px; left: 24px; }\n\n.cb-badge {\n position: absolute;\n top: -2px; right: -2px;\n background: linear-gradient(135deg, #ef4444, #f97316);\n color: white;\n font-size: 10px; font-weight: 700;\n min-width: 20px; height: 20px;\n border-radius: 10px;\n display: flex; align-items: center; justify-content: center;\n padding: 0 5px;\n border: 2px solid white;\n z-index: 2;\n animation: cb-badge-in .4s cubic-bezier(.34,1.56,.64,1) both;\n}\n@keyframes cb-badge-in { from { transform: scale(0) rotate(-20deg); } to { transform: scale(1) rotate(0); } }\n\n.cb-window {\n position: fixed;\n width: 420px;\n top: 0;\n bottom: 0;\n background: var(--cb-window-bg);\n border-radius: 0;\n border-left: 1px solid rgba(0,0,0,0.08);\n box-shadow:\n -8px 0 32px rgba(0,0,0,0.10),\n -2px 0 8px rgba(0,0,0,0.04);\n display: flex;\n flex-direction: column;\n overflow: hidden;\n z-index: calc(var(--cb-z) - 1);\n transition: opacity .3s cubic-bezier(.4,0,.2,1),\n transform .35s cubic-bezier(.4,0,.2,1),\n width .35s cubic-bezier(.4,0,.2,1);\n}\n.cb-widget.cb-dark .cb-window {\n border-color: rgba(255,255,255,0.08);\n box-shadow:\n -8px 0 32px rgba(0,0,0,0.4),\n -2px 0 8px rgba(0,0,0,0.2);\n}\n.cb-window.cb-hidden {\n opacity: 0;\n pointer-events: none;\n transform: translateX(100%);\n}\n.cb-pos-bottom-right .cb-window { right: 0; }\n.cb-pos-bottom-left .cb-window { left: 0; right: auto; border-left: none; border-right: 1px solid rgba(0,0,0,0.08); box-shadow: 8px 0 32px rgba(0,0,0,0.10); }\n.cb-pos-bottom-left .cb-window.cb-hidden { transform: translateX(-100%); }\n.cb-pos-top-right .cb-window { right: 0; }\n.cb-pos-top-left .cb-window { left: 0; right: auto; border-left: none; border-right: 1px solid rgba(0,0,0,0.08); }\n\n.cb-window.cb-expanded {\n width: min(720px, 50dvw) !important;\n}\n.cb-window.cb-expanded.cb-hidden {\n opacity: 0;\n pointer-events: none;\n transform: translateX(100%) !important;\n}\n\n.cb-header {\n flex-shrink: 0;\n height: 68px;\n padding: 0 16px;\n display: flex;\n align-items: center;\n gap: 12px;\n background: var(--cb-grad);\n position: relative;\n overflow: hidden;\n}\n.cb-header-blob2 {\n display: none;\n}\n.cb-header::after {\n content: '';\n position: absolute; bottom: 0; left: 0; right: 0; height: 1px;\n background: rgba(255,255,255,0.12);\n pointer-events: none;\n}\n.cb-header-avatar {\n width: 40px; height: 40px;\n border-radius: 50%;\n background: rgba(255,255,255,0.2);\n border: 2px solid rgba(255,255,255,0.35);\n display: flex; align-items: center; justify-content: center;\n flex-shrink: 0; overflow: hidden;\n box-shadow: 0 2px 8px rgba(0,0,0,0.15);\n position: relative; z-index: 1;\n}\n.cb-header-avatar img { width: 100%; height: 100%; object-fit: cover; }\n.cb-header-avatar svg { width: 22px; height: 22px; fill: white; }\n.cb-header-info { flex: 1; min-width: 0; position: relative; z-index: 1; }\n.cb-header-title {\n font-size: 15px; font-weight: 600;\n color: white; letter-spacing: -0.01em;\n white-space: nowrap; overflow: hidden; text-overflow: ellipsis;\n}\n.cb-header-status {\n display: flex; align-items: center; gap: 6px; margin-top: 3px;\n}\n.cb-status-dot {\n width: 7px; height: 7px; border-radius: 50%;\n background: #4ade80;\n box-shadow: 0 0 4px rgba(74,222,128,0.6);\n position: relative; flex-shrink: 0;\n}\n.cb-header-subtitle {\n font-size: 11px; color: rgba(255,255,255,0.72); font-weight: 500;\n white-space: nowrap; overflow: hidden; text-overflow: ellipsis;\n}\n.cb-header-actions {\n display: flex; align-items: center; gap: 6px;\n position: relative; z-index: 1; flex-shrink: 0;\n}\n.cb-close-btn,\n.cb-expand-btn {\n width: 32px; height: 32px; border-radius: 50%;\n background: rgba(255,255,255,0.14);\n border: none;\n cursor: pointer; display: flex; align-items: center; justify-content: center;\n transition: background .2s, transform .2s;\n position: relative;\n}\n.cb-close-btn:hover,\n.cb-expand-btn:hover { background: rgba(255,255,255,0.25); transform: scale(1.05); }\n.cb-close-btn svg { width: 14px; height: 14px; stroke: white; stroke-width: 2.5; fill: none; stroke-linecap: round; }\n.cb-expand-btn .cb-icon-expand { display: flex; }\n.cb-expand-btn .cb-icon-collapse { display: none; }\n.cb-expand-btn.cb-expanded .cb-icon-expand { display: none; }\n.cb-expand-btn.cb-expanded .cb-icon-collapse { display: flex; }\n.cb-expand-btn svg { width: 14px; height: 14px; stroke: white; stroke-width: 2; fill: none; stroke-linecap: round; }\n\n.cb-history-btn {\n width: 32px; height: 32px; border-radius: 50%;\n background: rgba(255,255,255,0.14);\n border: none;\n cursor: pointer; display: flex; align-items: center; justify-content: center;\n transition: background .2s, transform .2s;\n position: relative;\n}\n.cb-history-btn:hover { background: rgba(255,255,255,0.25); transform: scale(1.05); }\n.cb-history-btn svg { width: 14px; height: 14px; stroke: white; stroke-width: 2; fill: none; stroke-linecap: round; }\n\n.cb-history-drawer {\n position: absolute;\n top: 0;\n right: 0;\n width: 320px;\n height: 100%;\n background: var(--cb-window-bg);\n border-left: 1.5px solid var(--cb-divider);\n box-shadow: -4px 0 24px rgba(0,0,0,0.12);\n display: flex;\n flex-direction: column;\n transform: translateX(100%);\n transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), width 0.3s cubic-bezier(0.4, 0, 0.2, 1);\n z-index: 10;\n}\n.cb-window.cb-expanded .cb-history-drawer {\n width: 420px;\n}\n.cb-history-drawer.cb-open {\n transform: translateX(0);\n}\n\n.cb-history-header {\n height: 68px;\n padding: 0 16px;\n border-bottom: none;\n display: flex;\n align-items: center;\n justify-content: space-between;\n background: var(--cb-grad);\n position: relative;\n overflow: hidden;\n flex-shrink: 0;\n}\n.cb-history-header::after {\n content: '';\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n height: 1px;\n background: rgba(255,255,255,0.12);\n pointer-events: none;\n}\n.cb-history-title {\n font-size: 16px;\n font-weight: 700;\n color: white;\n letter-spacing: -0.02em;\n position: relative;\n z-index: 1;\n text-shadow: 0 1px 2px rgba(0,0,0,0.1);\n}\n.cb-history-actions {\n display: flex;\n gap: 8px;\n align-items: center;\n position: relative;\n z-index: 1;\n}\n.cb-clear-history-btn {\n width: 32px;\n height: 32px;\n background: rgba(255, 255, 255, 0.14);\n border: none;\n border-radius: 50%;\n color: white;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all .2s;\n}\n.cb-clear-history-btn:hover {\n background: rgba(255, 255, 255, 0.25);\n transform: scale(1.05);\n}\n.cb-clear-history-btn svg {\n width: 16px;\n height: 16px;\n stroke: white;\n}\n.cb-close-history-btn {\n width: 32px;\n height: 32px;\n background: rgba(255, 255, 255, 0.14);\n border: none;\n border-radius: 50%;\n color: white;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all .2s;\n}\n.cb-close-history-btn:hover {\n background: rgba(255, 255, 255, 0.25);\n transform: scale(1.05);\n}\n.cb-close-history-btn svg {\n width: 16px;\n height: 16px;\n stroke: white;\n}\n\n.cb-history-list {\n flex: 1;\n overflow-y: auto;\n padding: 16px;\n display: flex;\n flex-direction: column;\n gap: 10px;\n background: linear-gradient(180deg, var(--cb-window-bg) 0%, rgba(var(--cb-accent-rgb), 0.02) 100%);\n}\n.cb-history-list::-webkit-scrollbar { width: 4px; }\n.cb-history-list::-webkit-scrollbar-track { background: transparent; }\n.cb-history-list::-webkit-scrollbar-thumb {\n background: rgba(var(--cb-accent-rgb), 0.25);\n border-radius: 2px;\n}\n.cb-history-list::-webkit-scrollbar-thumb:hover {\n background: rgba(var(--cb-accent-rgb), 0.4);\n}\n\n.cb-history-item {\n padding: 12px 14px;\n background: var(--cb-window-bg);\n border-radius: 12px;\n cursor: pointer;\n transition: all .25s cubic-bezier(.4,0,.2,1);\n border: 1.5px solid var(--cb-divider);\n box-shadow: 0 1px 3px rgba(0,0,0,0.05);\n}\n.cb-history-item:hover {\n background: var(--cb-msg-bot-bg);\n border-color: rgba(var(--cb-accent-rgb), 0.35);\n transform: translateY(-1px);\n box-shadow: 0 4px 12px rgba(var(--cb-accent-rgb), 0.12);\n}\n.cb-history-item-role {\n font-size: 10px;\n font-weight: 700;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-bottom: 6px;\n display: inline-block;\n padding: 2px 8px;\n border-radius: 4px;\n}\n.cb-history-item[data-role=\"user\"] .cb-history-item-role {\n background: rgba(var(--cb-accent-rgb), 0.12);\n color: var(--cb-accent);\n}\n.cb-history-item[data-role=\"assistant\"] .cb-history-item-role {\n background: rgba(16, 185, 129, 0.12);\n color: #10b981;\n}\n.cb-history-item-content {\n font-size: 13px;\n color: var(--cb-text);\n line-height: 1.6;\n white-space: normal;\n word-wrap: break-word;\n overflow-wrap: break-word;\n max-width: 100%;\n margin-bottom: 6px;\n display: -webkit-box;\n -webkit-line-clamp: 3;\n -webkit-box-orient: vertical;\n overflow: hidden;\n}\n.cb-history-item-time {\n font-size: 10px;\n color: var(--cb-text-3);\n font-weight: 500;\n display: flex;\n align-items: center;\n gap: 4px;\n}\n.cb-history-item-time::before {\n content: '๐Ÿ•’';\n font-size: 9px;\n}\n\n.cb-history-empty {\n flex: 1;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n color: var(--cb-text-3);\n font-size: 13px;\n text-align: center;\n padding: 40px 20px;\n}\n.cb-history-empty::before {\n content: '๐Ÿ“';\n font-size: 48px;\n margin-bottom: 12px;\n opacity: 0.4;\n}\n\n.cb-messages {\n flex: 1;\n overflow-y: auto;\n padding: 16px 14px 10px;\n display: flex; flex-direction: column;\n gap: 2px;\n scroll-behavior: smooth;\n background: var(--cb-window-bg);\n position: relative;\n}\n.cb-messages::-webkit-scrollbar { width: 3px; }\n.cb-messages::-webkit-scrollbar-track { background: transparent; }\n.cb-messages::-webkit-scrollbar-thumb {\n background: rgba(var(--cb-accent-rgb), 0.18);\n border-radius: 2px;\n}\n.cb-msg {\n display: flex; gap: 10px; align-items: flex-end;\n max-width: 85%;\n animation: cb-msg-in .3s cubic-bezier(.34,1.56,.64,1) both;\n}\n@keyframes cb-msg-in {\n from { opacity: 0; transform: translateY(12px) scale(0.96); }\n to { opacity: 1; transform: translateY(0) scale(1); }\n}\n.cb-msg.cb-user { align-self: flex-end; flex-direction: row-reverse; }\n.cb-msg.cb-bot { align-self: flex-start; }\n.cb-msg.cb-first-in-group { margin-top: 14px; }\n.cb-msg-avatar {\n width: 30px; height: 30px; border-radius: 50%;\n display: flex; align-items: center; justify-content: center;\n flex-shrink: 0; overflow: hidden;\n}\n.cb-msg.cb-bot .cb-msg-avatar {\n background: var(--cb-grad);\n box-shadow: 0 2px 8px var(--cb-accent-glow);\n}\n.cb-msg.cb-user .cb-msg-avatar {\n background: var(--cb-grad);\n box-shadow: 0 2px 8px var(--cb-accent-glow);\n}\n.cb-msg.cb-grouped .cb-msg-avatar { visibility: hidden; }\n.cb-msg-avatar img { width: 100%; height: 100%; object-fit: cover; }\n.cb-msg-avatar svg { width: 17px; height: 17px; fill: white; }\n.cb-msg-content { display: flex; flex-direction: column; gap: 4px; min-width: 0; }\n.cb-msg-bubble {\n padding: 10px 14px;\n border-radius: 18px;\n font-size: 13.5px; line-height: 1.55;\n white-space: pre-wrap; word-break: break-word;\n}\n.cb-msg.cb-bot .cb-msg-bubble {\n background: var(--cb-msg-bot-bg);\n border: none;\n color: var(--cb-text);\n border-bottom-left-radius: 4px;\n box-shadow: none;\n}\n.cb-msg.cb-user .cb-msg-bubble {\n background: var(--cb-grad);\n border: none;\n color: white;\n border-bottom-right-radius: 4px;\n box-shadow: 0 2px 10px var(--cb-accent-glow);\n}\n.cb-msg-time {\n font-size: 10px; color: var(--cb-text-3); padding: 0 4px;\n}\n.cb-msg.cb-user .cb-msg-time { text-align: right; }\n.cb-msg.cb-bot .cb-msg-bubble code { background: rgba(var(--cb-accent-rgb),0.10); color: var(--cb-accent); }\n.cb-msg.cb-user .cb-msg-bubble code { background: rgba(255,255,255,0.20); color: white; }\n\n.cb-typing-wrap {\n display: flex; gap: 10px; align-items: flex-end;\n align-self: flex-start; margin-top: 14px;\n animation: cb-msg-in .3s ease both;\n}\n.cb-typing {\n display: flex; gap: 5px; align-items: center;\n padding: 13px 18px;\n background: var(--cb-msg-bot-bg);\n border-radius: 20px; border-bottom-left-radius: 6px;\n}\n.cb-typing span {\n width: 7px; height: 7px; border-radius: 50%;\n background: var(--cb-accent);\n animation: cb-bounce 1.4s ease-in-out infinite;\n flex-shrink: 0;\n opacity: 0.65;\n}\n.cb-typing span:nth-child(1) { animation-delay: 0s; }\n.cb-typing span:nth-child(2) { animation-delay: 0.18s; opacity: 0.82; }\n.cb-typing span:nth-child(3) { animation-delay: 0.36s; opacity: 1; }\n@keyframes cb-bounce {\n 0%, 55%, 100% { transform: translateY(0) scale(1); }\n 28% { transform: translateY(-7px) scale(1.1); }\n}\n\n.cb-input-area {\n flex-shrink: 0;\n padding: 12px 14px 14px;\n border-top: 1px solid var(--cb-divider);\n background: var(--cb-window-bg);\n display: flex; gap: 10px; align-items: flex-end;\n}\n.cb-input-wrap {\n flex: 1;\n display: flex; align-items: flex-end;\n background: var(--cb-input-bg);\n border: 1.5px solid var(--cb-input-bd);\n border-radius: 24px;\n padding: 0 16px;\n min-height: 46px;\n transition: border-color .2s, box-shadow .2s;\n}\n.cb-input-wrap:focus-within {\n border-color: rgba(var(--cb-accent-rgb), 0.45);\n box-shadow: 0 0 0 3px var(--cb-accent-ring);\n}\n.cb-input {\n flex: 1; border: none; background: transparent;\n padding: 13px 0;\n font-size: 13.5px; font-family: inherit;\n resize: none; outline: none;\n max-height: 100px;\n color: var(--cb-text);\n line-height: 1.45;\n overflow-y: auto;\n}\n.cb-input::placeholder { color: var(--cb-text-3); }\n.cb-send-btn {\n width: 44px; height: 44px;\n border-radius: 50%;\n background: var(--cb-grad);\n border: none; cursor: pointer;\n display: flex; align-items: center; justify-content: center;\n flex-shrink: 0;\n transition: transform .25s cubic-bezier(.34,1.56,.64,1), box-shadow .2s, opacity .2s;\n box-shadow: 0 3px 12px var(--cb-accent-glow);\n outline: none;\n}\n.cb-send-btn:hover {\n transform: scale(1.06);\n box-shadow: 0 6px 18px var(--cb-accent-glow);\n}\n.cb-send-btn:active { transform: scale(0.92); }\n.cb-send-btn:disabled {\n opacity: 0.35; cursor: not-allowed;\n transform: none; box-shadow: none;\n}\n.cb-send-btn svg {\n width: 17px; height: 17px;\n fill: none; stroke: white; stroke-width: 2;\n stroke-linecap: round; stroke-linejoin: round;\n position: relative; z-index: 1;\n}\n\n.cb-footer {\n flex-shrink: 0;\n text-align: center;\n padding: 6px 0 10px;\n font-size: 10px;\n color: var(--cb-text-3);\n display: flex; align-items: center; justify-content: center; gap: 5px;\n letter-spacing: 0.01em;\n background: var(--cb-window-bg);\n}\n.cb-footer-dot {\n display: inline-block;\n width: 5px; height: 5px;\n border-radius: 50%;\n background: rgba(var(--cb-accent-rgb), 0.45);\n flex-shrink: 0;\n}\n.cb-footer a {\n color: var(--cb-accent);\n text-decoration: none;\n font-weight: 700;\n letter-spacing: 0.02em;\n background: var(--cb-grad);\n -webkit-background-clip: text;\n -webkit-text-fill-color: transparent;\n background-clip: text;\n}\n.cb-footer a:hover { opacity: .75; }\n\n.cb-bot .cb-msg-bubble p { margin: 0 0 6px; }\n.cb-bot .cb-msg-bubble p:last-child { margin-bottom: 0; }\n.cb-bot .cb-msg-bubble strong,\n.cb-bot .cb-msg-bubble b { font-weight: 700; color: #111827; }\n.cb-bot .cb-msg-bubble em,\n.cb-bot .cb-msg-bubble i { font-style: italic; }\n.cb-bot .cb-msg-bubble h1,\n.cb-bot .cb-msg-bubble h2,\n.cb-bot .cb-msg-bubble h3 { font-weight: 700; margin: 8px 0 4px; color: #111827; line-height: 1.3; }\n.cb-bot .cb-msg-bubble h1 { font-size: 15px; }\n.cb-bot .cb-msg-bubble h2 { font-size: 14px; }\n.cb-bot .cb-msg-bubble h3 { font-size: 13.5px; }\n.cb-bot .cb-msg-bubble ul,\n.cb-bot .cb-msg-bubble ol { margin: 4px 0 6px 16px; padding: 0; }\n.cb-bot .cb-msg-bubble li { margin-bottom: 3px; line-height: 1.55; }\n.cb-bot .cb-msg-bubble code {\n background: #EEF2FF;\n border-radius: 4px;\n padding: 1px 5px;\n font-family: 'Courier New', monospace;\n font-size: 12px;\n color: var(--cb-accent);\n}\n.cb-bot .cb-msg-bubble pre {\n background: #1e293b;\n border-radius: 10px;\n padding: 10px 14px;\n overflow-x: auto;\n margin: 6px 0;\n}\n.cb-bot .cb-msg-bubble pre code {\n background: none; border: none; padding: 0; color: #93c5fd; font-size: 12px;\n}\n.cb-bot .cb-msg-bubble blockquote {\n border-left: 3px solid var(--cb-accent);\n padding: 3px 10px;\n margin: 6px 0;\n color: #64748b;\n background: rgba(var(--cb-accent-rgb), 0.05);\n border-radius: 0 6px 6px 0;\n}\n.cb-bot .cb-msg-bubble a { color: var(--cb-accent); text-decoration: underline; }\n.cb-bot .cb-msg-bubble hr { border: none; border-top: 1px solid #e5e7eb; margin: 8px 0; }\n.cb-bot .cb-msg-bubble table { border-collapse: collapse; width: 100%; margin: 6px 0; font-size: 12px; }\n.cb-bot .cb-msg-bubble th { background: #f3f4f6; font-weight: 600; padding: 5px 8px; border: 1px solid #e5e7eb; }\n.cb-bot .cb-msg-bubble td { padding: 4px 8px; border: 1px solid #e5e7eb; }\n.cb-dark .cb-bot .cb-msg-bubble strong,\n.cb-dark .cb-bot .cb-msg-bubble b { color: #F9FAFB; }\n.cb-dark .cb-bot .cb-msg-bubble h1,\n.cb-dark .cb-bot .cb-msg-bubble h2,\n.cb-dark .cb-bot .cb-msg-bubble h3 { color: #F9FAFB; }\n.cb-dark .cb-bot .cb-msg-bubble code { background: #1e293b; color: #93c5fd; }\n.cb-dark .cb-bot .cb-msg-bubble blockquote { color: #9CA3AF; }\n.cb-dark .cb-bot .cb-msg-bubble th { background: #1F2937; border-color: #374151; }\n.cb-dark .cb-bot .cb-msg-bubble td { border-color: #374151; }\n.cb-dark .cb-bot .cb-msg-bubble hr { border-color: #374151; }\n\n/* โ”€โ”€ Tab Bar โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */\n.cb-tab-bar {\n flex-shrink: 0;\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 12px 14px;\n background: var(--cb-window-bg);\n border-bottom: 1px solid var(--cb-divider);\n}\n.cb-tabs {\n display: flex;\n background: #f3f4f6;\n border-radius: 20px;\n padding: 3px;\n}\n.cb-dark .cb-tabs {\n background: #1F2937;\n}\n.cb-tab {\n padding: 7px 22px;\n border: none;\n border-radius: 18px;\n font-size: 13px;\n font-weight: 600;\n cursor: pointer;\n background: transparent;\n color: var(--cb-text-2);\n font-family: inherit;\n transition: all .2s;\n}\n.cb-tab.cb-active {\n background: #1a1a2e;\n color: white;\n}\n.cb-dark .cb-tab.cb-active {\n background: #f3f4f6;\n color: #111827;\n}\n.cb-tab-actions {\n display: flex;\n gap: 4px;\n align-items: center;\n}\n.cb-tab-action-btn {\n width: 30px;\n height: 30px;\n border-radius: 8px;\n border: none;\n background: transparent;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background .2s;\n}\n.cb-tab-action-btn:hover {\n background: var(--cb-msg-bot-bg);\n}\n.cb-tab-action-btn svg {\n width: 16px;\n height: 16px;\n stroke: var(--cb-text-2);\n fill: none;\n stroke-width: 2;\n stroke-linecap: round;\n stroke-linejoin: round;\n}\n\n/* โ”€โ”€ Welcome / Landing Page โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */\n.cb-welcome {\n flex: 1;\n display: flex;\n flex-direction: column;\n align-items: center;\n padding: 36px 24px 20px;\n overflow-y: auto;\n background: var(--cb-window-bg);\n}\n.cb-welcome.cb-hidden { display: none; }\n.cb-welcome-logo {\n display: flex;\n align-items: center;\n gap: 6px;\n margin-bottom: 22px;\n}\n.cb-welcome-logo-icon {\n width: 22px;\n height: 22px;\n color: var(--cb-accent);\n}\n.cb-welcome-logo-text {\n font-size: 18px;\n font-weight: 800;\n letter-spacing: 1px;\n color: var(--cb-text);\n}\n.cb-welcome-logo-badge {\n background: #1a1a2e;\n color: white;\n font-size: 10px;\n font-weight: 700;\n padding: 2px 7px;\n border-radius: 5px;\n letter-spacing: 0.5px;\n}\n.cb-dark .cb-welcome-logo-badge {\n background: #f3f4f6;\n color: #111827;\n}\n.cb-welcome-greeting {\n font-size: 24px;\n font-weight: 700;\n color: var(--cb-text);\n text-align: center;\n margin-bottom: 6px;\n line-height: 1.3;\n}\n.cb-welcome-subtitle {\n font-size: 14px;\n color: var(--cb-text-2);\n text-align: center;\n margin-bottom: 28px;\n}\n.cb-quick-replies {\n width: 100%;\n display: flex;\n flex-direction: column;\n gap: 10px;\n}\n.cb-quick-reply-btn {\n width: 100%;\n padding: 14px 18px;\n background: var(--cb-window-bg);\n border: 1.5px solid var(--cb-input-bd);\n border-radius: 14px;\n font-size: 13.5px;\n font-family: inherit;\n color: var(--cb-text);\n cursor: pointer;\n text-align: left;\n transition: all .2s;\n}\n.cb-quick-reply-btn:hover {\n border-color: rgba(var(--cb-accent-rgb), 0.4);\n background: rgba(var(--cb-accent-rgb), 0.04);\n transform: translateY(-1px);\n}\n\n/* โ”€โ”€ History Panel (tab-based, replaces drawer) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */\n.cb-history-panel {\n flex: 1;\n overflow-y: auto;\n display: none;\n flex-direction: column;\n background: var(--cb-window-bg);\n}\n.cb-history-panel.cb-active {\n display: flex;\n}\n.cb-history-panel-header {\n display: flex;\n flex-direction: column;\n align-items: center;\n padding: 30px 24px 20px;\n}\n.cb-history-panel-header .cb-welcome-logo {\n margin-bottom: 14px;\n}\n.cb-history-panel-title {\n font-size: 22px;\n font-weight: 700;\n color: var(--cb-text);\n margin-bottom: 4px;\n}\n.cb-history-panel-subtitle {\n font-size: 13px;\n color: var(--cb-text-2);\n}\n.cb-history-section-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 0 20px 10px;\n}\n.cb-history-count {\n font-size: 14px;\n font-weight: 700;\n color: var(--cb-text);\n}\n.cb-history-panel .cb-history-list {\n flex: 1;\n overflow-y: auto;\n padding: 0 20px 16px;\n display: flex;\n flex-direction: column;\n gap: 10px;\n}\n.cb-history-panel .cb-history-empty {\n flex: 1;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n color: var(--cb-text-3);\n font-size: 13px;\n text-align: center;\n padding: 40px 20px;\n}\n.cb-history-clear-btn {\n padding: 0;\n border: none;\n background: none;\n color: #ef4444;\n font-size: 13px;\n font-weight: 600;\n font-family: inherit;\n cursor: pointer;\n display: flex;\n align-items: center;\n gap: 5px;\n transition: opacity .2s;\n}\n.cb-history-clear-btn:hover {\n opacity: 0.7;\n}\n.cb-history-clear-btn svg {\n width: 14px;\n height: 14px;\n stroke: #ef4444;\n}\n\n/* โ”€โ”€ History Chat Items โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */\n.cb-history-chat-item {\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 14px 16px;\n background: var(--cb-window-bg);\n border: 1.5px solid var(--cb-divider);\n border-radius: 14px;\n cursor: pointer;\n transition: all .2s;\n}\n.cb-history-chat-item:hover {\n border-color: rgba(var(--cb-accent-rgb), 0.3);\n box-shadow: 0 2px 8px rgba(0,0,0,0.06);\n}\n.cb-history-chat-item.cb-active {\n border-color: rgba(var(--cb-accent-rgb), 0.4);\n background: rgba(var(--cb-accent-rgb), 0.04);\n}\n.cb-history-chat-item.cb-loading {\n pointer-events: none;\n opacity: 0.7;\n}\n.cb-history-chat-item.cb-loading .cb-history-chat-icon svg {\n display: none;\n}\n.cb-history-chat-item.cb-loading .cb-history-chat-icon::after {\n content: '';\n width: 20px;\n height: 20px;\n border: 2.5px solid rgba(var(--cb-accent-rgb), 0.2);\n border-top-color: var(--cb-accent);\n border-radius: 50%;\n animation: cb-spin 0.7s linear infinite;\n}\n@keyframes cb-spin {\n to { transform: rotate(360deg); }\n}\n.cb-chat-loader {\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: 12px;\n padding: 40px 20px;\n color: var(--cb-text-3);\n font-size: 13px;\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 100%;\n}\n.cb-chat-loader-spinner {\n width: 32px;\n height: 32px;\n border: 3px solid rgba(var(--cb-accent-rgb), 0.15);\n border-top-color: var(--cb-accent);\n border-radius: 50%;\n animation: cb-spin 0.7s linear infinite;\n}\n.cb-history-chat-icon {\n width: 38px;\n height: 38px;\n border-radius: 10px;\n background: rgba(var(--cb-accent-rgb), 0.1);\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n}\n.cb-history-chat-icon svg {\n width: 20px;\n height: 20px;\n}\n.cb-history-chat-info {\n flex: 1;\n min-width: 0;\n}\n.cb-history-chat-title {\n font-size: 14px;\n font-weight: 600;\n color: var(--cb-text);\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n.cb-history-chat-meta {\n font-size: 12px;\n color: var(--cb-text-3);\n margin-top: 2px;\n}\n.cb-history-delete-btn {\n width: 32px;\n height: 32px;\n border-radius: 8px;\n border: none;\n background: transparent;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n transition: all .2s;\n color: var(--cb-text-3);\n}\n.cb-history-delete-btn:hover {\n background: rgba(239,68,68,0.08);\n color: #ef4444;\n}\n.cb-history-delete-btn svg {\n width: 16px;\n height: 16px;\n stroke: #ef4444;\n}\n\n/* โ”€โ”€ Disclaimer footer โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */\n.cb-disclaimer {\n flex-shrink: 0;\n text-align: center;\n padding: 6px 16px 12px;\n font-size: 11px;\n color: #9ca3af;\n font-weight: 500;\n background: var(--cb-window-bg);\n}\n\n/* โ”€โ”€ Message Actions (copy, feedback) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */\n.cb-msg-actions {\n display: flex;\n align-items: center;\n gap: 2px;\n padding: 2px 0 0 4px;\n opacity: 0;\n transition: opacity .2s;\n}\n.cb-msg:hover .cb-msg-actions,\n.cb-msg-actions.cb-visible {\n opacity: 1;\n}\n.cb-msg-action-btn {\n width: 28px;\n height: 28px;\n border-radius: 6px;\n border: none;\n background: transparent;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all .2s;\n color: var(--cb-text-3);\n position: relative;\n}\n.cb-msg-action-btn:hover {\n background: var(--cb-msg-bot-bg);\n color: var(--cb-text-2);\n}\n.cb-msg-action-btn svg {\n width: 14px;\n height: 14px;\n stroke: currentColor;\n fill: none;\n}\n.cb-msg-action-btn.cb-active {\n color: var(--cb-accent);\n}\n.cb-msg-action-btn.cb-active svg {\n stroke: var(--cb-accent);\n}\n.cb-msg-action-btn.cb-copied {\n color: #10b981;\n}\n.cb-msg-action-btn.cb-copied svg {\n stroke: #10b981;\n}\n.cb-msg-action-btn .cb-tooltip {\n position: absolute;\n bottom: 100%;\n left: 50%;\n transform: translateX(-50%) translateY(-4px);\n background: #1a1a2e;\n color: white;\n font-size: 11px;\n font-weight: 500;\n padding: 4px 8px;\n border-radius: 6px;\n white-space: nowrap;\n pointer-events: none;\n opacity: 0;\n transition: opacity .15s;\n}\n.cb-msg-action-btn:hover .cb-tooltip {\n opacity: 1;\n}\n.cb-dark .cb-msg-action-btn .cb-tooltip {\n background: #f3f4f6;\n color: #111827;\n}\n.cb-feedback-divider {\n width: 1px;\n height: 16px;\n background: var(--cb-divider);\n margin: 0 2px;\n}\n\n/* โ”€โ”€ Streaming Text Animation โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */\n.cb-msg-bubble.cb-streaming {\n overflow: hidden;\n}\n.cb-streaming-cursor {\n display: inline-block;\n width: 2px;\n height: 14px;\n background: var(--cb-accent);\n margin-left: 2px;\n vertical-align: text-bottom;\n animation: cb-blink 0.6s step-end infinite;\n}\n@keyframes cb-blink {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0; }\n}\n\n/* โ”€โ”€ Export Button โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */\n.cb-export-btn {\n width: 30px;\n height: 30px;\n border-radius: 8px;\n border: none;\n background: transparent;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background .2s;\n position: relative;\n}\n.cb-export-btn:hover {\n background: var(--cb-msg-bot-bg);\n}\n.cb-export-btn svg {\n width: 16px;\n height: 16px;\n stroke: var(--cb-text-2);\n fill: none;\n stroke-width: 2;\n stroke-linecap: round;\n stroke-linejoin: round;\n}\n.cb-export-btn .cb-tooltip {\n position: absolute;\n bottom: 100%;\n left: 50%;\n transform: translateX(-50%) translateY(-4px);\n background: #1a1a2e;\n color: white;\n font-size: 11px;\n font-weight: 500;\n padding: 4px 8px;\n border-radius: 6px;\n white-space: nowrap;\n pointer-events: none;\n opacity: 0;\n transition: opacity .15s;\n}\n.cb-export-btn:hover .cb-tooltip {\n opacity: 1;\n}\n\n/* โ”€โ”€ Suggested Follow-ups โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */\n.cb-followups {\n display: flex;\n flex-wrap: wrap;\n gap: 6px;\n padding: 4px 0 0 40px;\n animation: cb-msg-in .3s ease both;\n}\n.cb-followup-btn {\n padding: 7px 14px;\n background: var(--cb-window-bg);\n border: 1.5px solid var(--cb-input-bd);\n border-radius: 20px;\n font-size: 12px;\n font-family: inherit;\n font-weight: 500;\n color: var(--cb-text);\n cursor: pointer;\n transition: all .2s;\n white-space: nowrap;\n}\n.cb-followup-btn:hover {\n border-color: rgba(var(--cb-accent-rgb), 0.4);\n background: rgba(var(--cb-accent-rgb), 0.04);\n color: var(--cb-accent);\n}\n\n@media (max-width: 480px) {\n .cb-window {\n width: 100dvw !important;\n left: 0 !important;\n right: 0 !important;\n border-left: none !important;\n border-right: none !important;\n }\n}\n",document.head.appendChild(e)}autoResize(){this.inputEl.style.height="auto",this.inputEl.style.height=Math.min(this.inputEl.scrollHeight,100)+"px"}applyTheme(){const e="dark"===this.config.theme||"auto"===this.config.theme&&window.matchMedia("(prefers-color-scheme: dark)").matches;this.container.classList.toggle("cb-dark",e),"auto"===this.config.theme&&window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",e=>{this.container.classList.toggle("cb-dark",e.matches)})}connectSocket(){this.socket=we(`${this.config.serverUrl}/chat`,{transports:["websocket"],auth:{apiKey:this.config.apiKey},reconnectionAttempts:5,reconnectionDelay:2e3}),this.socket.on("connect",()=>console.log("[ChatBolt] Connected")),this.socket.on("chat:response",e=>{var t;this.conversationId=e.conversationId,this.hideTyping(),this.addMessage("assistant",e.message,!1,null!==(t=e.report)&&void 0!==t?t:void 0),this.isOpen||this.showBadge()}),this.socket.on("chat:error",e=>{this.hideTyping(),this.addMessage("assistant",`Something went wrong: ${e.message}`)}),this.socket.on("disconnect",()=>console.log("[ChatBolt] Disconnected"))}send(e){var t;const n=e||this.inputEl.value.trim();if(!n||this.isTyping)return;this.isWelcomeVisible&&this.hideWelcome(),this.addMessage("user",n),e||(this.inputEl.value="",this.inputEl.style.height="auto"),this.sendBtn.disabled=!0,this.showTyping(),this.sessionId||(this.sessionId=this.getOrCreateSessionId());if(this.conversations.find(e=>e.sessionId===this.sessionId))this.updateConversationMeta(this.sessionId);else{const e=n.length>30?n.substring(0,30)+"...":n;this.addConversation(this.sessionId,e)}null===(t=this.socket)||void 0===t||t.emit("chat:message",{message:n,session_id:this.sessionId,conversationId:this.conversationId||void 0,contextParams:this.config.contextParams||void 0})}addMessage(e,t,n=!1,s){const i={id:Date.now().toString(),role:e,content:t,createdAt:new Date,report:s};this.messages.push(i);const r=this.lastRole===e;this.lastRole=e;const o=document.createElement("div");o.className=`cb-msg ${"user"===e?"cb-user":"cb-bot"}${r?" cb-grouped":" cb-first-in-group"}`;const a="user"===e?`<div class="cb-msg-avatar">${jt.user}</div>`:`<div class="cb-msg-avatar">${this.config.botAvatar?`<img src="${this.config.botAvatar}" alt="bot">`:jt.bot}</div>`,c=s?this.renderReportCard(s):"",l="assistant"!==e||n?"":`\n <div class="cb-msg-actions">\n <button class="cb-msg-action-btn cb-copy-btn" data-content="${this.esc(t)}">\n <span class="cb-tooltip">Copy</span>\n ${jt.copy}\n </button>\n <span class="cb-feedback-divider"></span>\n <button class="cb-msg-action-btn cb-feedback-btn" data-feedback="up" data-msg-id="${i.id}">\n <span class="cb-tooltip">Helpful</span>\n ${jt.thumbUp}\n </button>\n <button class="cb-msg-action-btn cb-feedback-btn" data-feedback="down" data-msg-id="${i.id}">\n <span class="cb-tooltip">Not helpful</span>\n ${jt.thumbDown}\n </button>\n </div>`,h="assistant"===e&&!n&&this.messages.filter(e=>"user"===e.role).length>0;if(o.innerHTML=`\n ${a}\n <div class="cb-msg-content">\n <div class="cb-msg-bubble${h?" cb-streaming":""}">${h?"":this.renderContent(t,e)}${h?"":c}</div>\n ${r?"":`<span class="cb-msg-time">${Ht(i.createdAt)}</span>`}\n </div>`,this.messagesEl.appendChild(o),this.clearFollowups(),h){const e=o.querySelector(".cb-msg-bubble");this.streamText(e,t,c,()=>{const e=o.querySelector(".cb-msg-content"),n=document.createElement("div");n.innerHTML=l;const s=n.firstElementChild;if(s){e.appendChild(s);const n=s.querySelector(".cb-copy-btn");n&&n.addEventListener("click",e=>{e.stopPropagation(),this.copyMessageText(t,n)}),s.querySelectorAll(".cb-feedback-btn").forEach(e=>{e.addEventListener("click",t=>{t.stopPropagation();const n=e.dataset.feedback,s=e.dataset.msgId;this.handleFeedback(s,n,e)})})}this.addFollowups(t),this.scrollBottom()})}else if(l){const e=o.querySelector(".cb-msg-content"),n=document.createElement("div");n.innerHTML=l;const s=n.firstElementChild;if(s){e.appendChild(s);const n=s.querySelector(".cb-copy-btn");n&&n.addEventListener("click",e=>{e.stopPropagation(),this.copyMessageText(t,n)}),s.querySelectorAll(".cb-feedback-btn").forEach(e=>{e.addEventListener("click",t=>{t.stopPropagation();const n=e.dataset.feedback,s=e.dataset.msgId;this.handleFeedback(s,n,e)})})}}this.scrollBottom(),this.isHistoryOpen&&this.renderHistory()}renderReportCard(e){if(!(null==e?void 0:e.report_id))return"";const t=`${this.config.serverUrl||"https://backend-api-chatbolt-backend.hf.space"}/api/v1/export/${e.report_id}`,n=`api_key=${encodeURIComponent(this.config.apiKey)}`,s={excel:"Excel",csv:"CSV",pdf:"PDF",docx:"Word"},i={excel:"๐Ÿ“Š",csv:"๐Ÿ“„",pdf:"๐Ÿ“•",docx:"๐Ÿ“"},r=(e.download_formats||[]).map(e=>`<a href="${t}/${e}?${n}" target="_blank" rel="noopener" class="cb-dl-btn cb-dl-${e}">\n ${i[e]||"โฌ‡"} ${s[e]||e}\n </a>`).join(""),o=(e.columns||[]).slice(0,4),a=(e.preview||[]).slice(0,5),c=o.map(e=>`<th>${this.esc(e.label||e.key)}</th>`).join(""),l=a.map(e=>`<tr>${o.map(t=>{var n;return`<td>${this.esc(String(null!==(n=e[t.key])&&void 0!==n?n:""))}</td>`}).join("")}</tr>`).join("");return`\n <div class="cb-report-card">\n <div class="cb-report-header">\n <span class="cb-report-icon">๐Ÿ“Š</span>\n <div>\n <div class="cb-report-title">${this.esc(e.title)}</div>\n <div class="cb-report-meta">${e.total_rows.toLocaleString()} rows ยท ${new Date(e.generated_at).toLocaleTimeString()}</div>\n </div>\n </div>\n ${l?`<div class="cb-report-table-wrap">\n <table class="cb-report-table">\n <thead><tr>${c}</tr></thead>\n <tbody>${l}</tbody>\n </table>\n ${e.total_rows>5?`<div class="cb-report-more">+${(e.total_rows-5).toLocaleString()} more rows</div>`:""}\n </div>`:""}\n ${r?`<div class="cb-report-downloads">${r}</div>`:""}\n </div>`}renderContent(e,t="assistant"){return"user"===t?this.esc(e).replace(/\n/g,"<br>"):Nt.parse(e)}showTyping(){this.isTyping=!0,this.messagesEl.appendChild(this.typingEl),this.scrollBottom()}hideTyping(){var e;this.isTyping=!1,this.sendBtn.disabled=!1,null===(e=this.typingEl.parentElement)||void 0===e||e.removeChild(this.typingEl)}scrollBottom(){requestAnimationFrame(()=>{this.messagesEl.scrollTop=this.messagesEl.scrollHeight})}showBadge(){this.unreadCount++,this.badgeEl.textContent=this.unreadCount>9?"9+":String(this.unreadCount),this.badgeEl.style.display="flex"}clearBadge(){this.unreadCount=0,this.badgeEl.style.display="none"}setupTriggerDrag(){let e=!1,t=!1,n=0,s=0,i=0,r=0;const o=o=>{const a=o.clientX-n,c=o.clientY-s;if(!e&&(Math.abs(a)>5||Math.abs(c)>5)&&(e=!0,t=!0,this.trigger.classList.add("cb-dragging"),this.trigger.style.top="auto",this.trigger.style.bottom="auto",this.trigger.style.left="auto",this.trigger.style.right="auto"),e){let e=i+a,t=r+c;const n=this.trigger.offsetWidth,s=this.trigger.offsetHeight;e=Math.max(0,Math.min(window.innerWidth-n,e)),t=Math.max(0,Math.min(window.innerHeight-s,t)),this.trigger.style.left=e+"px",this.trigger.style.top=t+"px",this.trigger.style.right="auto",this.trigger.style.bottom="auto"}},a=n=>{document.removeEventListener("pointermove",o),document.removeEventListener("pointerup",a),this.trigger.classList.remove("cb-dragging"),e&&(e=!1),t||this.toggle()};this.trigger.addEventListener("pointerdown",c=>{e=!1,t=!1,n=c.clientX,s=c.clientY;const l=this.trigger.getBoundingClientRect();i=l.left,r=l.top,this.trigger.setPointerCapture(c.pointerId),document.addEventListener("pointermove",o),document.addEventListener("pointerup",a)})}open(){this.isOpen=!0,this.window.classList.remove("cb-hidden"),this.trigger.classList.add("cb-open"),this.clearBadge(),setTimeout(()=>this.inputEl.focus(),250),this.scrollBottom()}close(){this.isOpen=!1,this.window.classList.add("cb-hidden"),this.trigger.classList.remove("cb-open")}toggle(){this.isOpen?this.close():this.open()}expand(){this.isExpanded=!0,this.window.classList.add("cb-expanded"),this.expandBtn.classList.add("cb-expanded"),this.scrollBottom()}collapse(){this.isExpanded=!1,this.window.classList.remove("cb-expanded"),this.expandBtn.classList.remove("cb-expanded"),this.scrollBottom()}toggleExpand(){this.isExpanded?this.collapse():this.expand()}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}getOrCreateSessionId(){this.loadConversationsList();const e=localStorage.getItem(this.activeSessionKey);if(e&&this.conversations.some(t=>t.sessionId===e))return e;const t=this.generateSessionId();return this.setActiveSession(t),t}loadConversationsList(){try{const e=localStorage.getItem(this.conversationsKey);this.conversations=e?JSON.parse(e):[]}catch(e){this.conversations=[]}}saveConversationsList(){localStorage.setItem(this.conversationsKey,JSON.stringify(this.conversations))}setActiveSession(e){this.sessionId=e,localStorage.setItem(this.activeSessionKey,e)}addConversation(e,t){const n={sessionId:e,title:t,messageCount:0,createdAt:(new Date).toISOString(),lastMessageAt:(new Date).toISOString()};return this.conversations.unshift(n),this.saveConversationsList(),n}updateConversationMeta(e,t){const n=this.conversations.find(t=>t.sessionId===e);n&&(n.messageCount=this.messages.filter(e=>"user"===e.role).length,n.lastMessageAt=(new Date).toISOString(),!t||"New Chat"!==n.title&&n.title||(n.title=t),this.saveConversationsList())}deleteConversation(e){this.conversations=this.conversations.filter(t=>t.sessionId!==e),this.saveConversationsList()}async loadHistory(){try{this.sessionId=this.getOrCreateSessionId(),this.sessionId&&await this.fetchSessionMessages(this.sessionId),this.renderHistory()}catch(e){console.error("[ChatBolt] Failed to load history:",e),this.sessionId=this.getOrCreateSessionId(),this.renderHistory()}}async fetchSessionMessages(e){try{const t=await fetch(`${this.config.serverUrl}/api/v1/chat/history?session_id=${encodeURIComponent(e)}`,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey}});if(!t.ok)return;const n=await t.json(),s=this.messagesEl.querySelector(".cb-chat-loader");s&&s.remove(),n.messages&&n.messages.length>0&&(this.messages=n.messages.map(e=>({id:e.id,role:e.role,content:e.content,createdAt:new Date(e.createdAt)})),this.restoreMessagesFromHistory())}catch(e){console.error("[ChatBolt] Failed to fetch session messages:",e)}}async loadConversation(e){this.messages=[],this.messagesEl.innerHTML="",this.lastRole=null,this.setActiveSession(e),this.conversationId=null,this.hideWelcome(),this.messagesEl.innerHTML='\n <div class="cb-chat-loader">\n <div class="cb-chat-loader-spinner"></div>\n Loading conversation...\n </div>',this.switchTab("chat");const t=this.container.querySelectorAll(".cb-history-chat-item");t.forEach(e=>e.classList.remove("cb-loading"));const n=Array.from(t).find(e=>e.classList.contains("cb-active"));n&&n.classList.add("cb-loading"),await this.fetchSessionMessages(e),n&&n.classList.remove("cb-loading"),0===this.messages.length&&(this.messagesEl.innerHTML=""),this.messages.some(e=>"user"===e.role)?this.hideWelcome():(this.isWelcomeVisible=!0,this.welcomeEl.classList.remove("cb-hidden"))}restoreMessagesFromHistory(){const e=this.messages.some(e=>"user"===e.role);e&&this.hideWelcome(),this.messages.forEach(e=>{const t=this.lastRole===e.role;this.lastRole=e.role;const n=document.createElement("div");n.className=`cb-msg ${"user"===e.role?"cb-user":"cb-bot"}${t?" cb-grouped":" cb-first-in-group"}`;const s="user"===e.role?`<div class="cb-msg-avatar">${jt.user}</div>`:`<div class="cb-msg-avatar">${this.config.botAvatar?`<img src="${this.config.botAvatar}" alt="bot">`:jt.bot}</div>`,i="assistant"===e.role?`\n <div class="cb-msg-actions">\n <button class="cb-msg-action-btn cb-copy-btn">\n <span class="cb-tooltip">Copy</span>\n ${jt.copy}\n </button>\n <span class="cb-feedback-divider"></span>\n <button class="cb-msg-action-btn cb-feedback-btn" data-feedback="up" data-msg-id="${e.id}">\n <span class="cb-tooltip">Helpful</span>\n ${jt.thumbUp}\n </button>\n <button class="cb-msg-action-btn cb-feedback-btn" data-feedback="down" data-msg-id="${e.id}">\n <span class="cb-tooltip">Not helpful</span>\n ${jt.thumbDown}\n </button>\n </div>`:"";n.innerHTML=`\n ${s}\n <div class="cb-msg-content">\n <div class="cb-msg-bubble">${this.renderContent(e.content,e.role)}</div>\n ${t?"":`<span class="cb-msg-time">${Ht(e.createdAt)}</span>`}\n ${i}\n </div>`;const r=n.querySelector(".cb-copy-btn");r&&r.addEventListener("click",t=>{t.stopPropagation(),this.copyMessageText(e.content,r)}),n.querySelectorAll(".cb-feedback-btn").forEach(e=>{e.addEventListener("click",t=>{t.stopPropagation();const n=e.dataset.feedback,s=e.dataset.msgId;this.handleFeedback(s,n,e)})}),this.messagesEl.appendChild(n)}),this.messages.length>0&&this.scrollBottom()}renderHistory(){this.historyList.innerHTML="",this.loadConversationsList();const e=this.container.querySelector(".cb-history-count");if(0===this.conversations.length)return this.historyList.innerHTML='<div class="cb-history-empty">No conversations yet</div>',void(e&&(e.textContent="Recent Chats (0)"));e&&(e.textContent=`Recent Chats (${this.conversations.length})`),this.conversations.forEach(e=>{const t=document.createElement("div");t.className="cb-history-chat-item",e.sessionId===this.sessionId&&t.classList.add("cb-active");const n=new Date(e.lastMessageAt||e.createdAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});t.innerHTML=`\n <div class="cb-history-chat-icon">\n <svg viewBox="0 0 24 24" fill="none"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" fill="var(--cb-accent)" opacity="0.85"/></svg>\n </div>\n <div class="cb-history-chat-info">\n <div class="cb-history-chat-title">${this.esc(e.title)}</div>\n <div class="cb-history-chat-meta">${e.messageCount} messages ยท ${n}</div>\n </div>\n <button class="cb-history-delete-btn" aria-label="Delete">${jt.trash}</button>\n `,t.addEventListener("click",t=>{t.target.closest(".cb-history-delete-btn")||this.loadConversation(e.sessionId)});const s=t.querySelector(".cb-history-delete-btn");s&&s.addEventListener("click",t=>{t.stopPropagation(),this.deleteConversation(e.sessionId),e.sessionId===this.sessionId&&this.startNewChat(),this.renderHistory()}),this.historyList.appendChild(t)})}switchTab(e){this.activeTab=e,this.chatTabBtn.classList.toggle("cb-active","chat"===e),this.historyTabBtn.classList.toggle("cb-active","history"===e),"chat"===e?(this.historyPanel.classList.remove("cb-active"),this.isWelcomeVisible?(this.welcomeEl.style.display="",this.messagesEl.style.display="none"):(this.welcomeEl.style.display="none",this.messagesEl.style.display=""),this.scrollBottom()):(this.welcomeEl.style.display="none",this.messagesEl.style.display="none",this.historyPanel.classList.add("cb-active"),this.renderHistory())}hideWelcome(){this.isWelcomeVisible=!1,this.welcomeEl.classList.add("cb-hidden"),this.welcomeEl.style.display="none",this.messagesEl.style.display=""}toggleHistory(){this.switchTab("history"===this.activeTab?"chat":"history")}openHistory(){this.isHistoryOpen=!0,this.switchTab("history")}closeHistory(){this.isHistoryOpen=!1,this.switchTab("chat")}clearHistory(){if(confirm("Are you sure you want to clear all chat history?"))try{this.conversations=[],this.saveConversationsList(),localStorage.removeItem(this.activeSessionKey),this.startNewChat(),this.renderHistory()}catch(e){console.error("[ChatBolt] Failed to clear history:",e)}}startNewChat(){const e=this.generateSessionId();this.setActiveSession(e),this.conversationId=null,this.messages=[],this.messagesEl.innerHTML="",this.lastRole=null,this.isWelcomeVisible=!0,this.welcomeEl.classList.remove("cb-hidden"),this.switchTab("chat"),this.config.greetingMessage&&this.addMessage("assistant",this.config.greetingMessage,!0)}streamText(e,t,n,s){const i=t.split(/(\s+)/);let r=0;const o=document.createElement("span");o.className="cb-streaming-cursor",e.appendChild(o);const a=setInterval(()=>{if(r>=i.length)return clearInterval(a),e.classList.remove("cb-streaming"),e.innerHTML=this.renderContent(t,"assistant")+n,void s();let c="";for(let e=0;e<3&&r<i.length;e++,r++)c+=i[r];o.remove();const l=i.slice(0,r).join("");e.textContent=l,e.appendChild(o),this.scrollBottom()},30)}exportChatPDF(){if(0===this.messages.length)return;const e=this.config.accentColor||"#6366f1",t=this.config.title||"Chat",n=new Date,s=n.toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"}),i=n.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"}),r=this.messages.map(n=>{const s="user"===n.role,i=s?e:"#f3f4f6",r=s?"#ffffff":"#111827",o=s?"You":t,a=n.createdAt instanceof Date?n.createdAt.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"}):"";return`\n <div style="margin-bottom:16px;">\n <div style="font-size:11px;font-weight:600;color:${s?e:"#6B7280"};margin-bottom:4px;">${o} <span style="font-weight:400;color:#9CA3AF;margin-left:6px;">${a}</span></div>\n <div style="background:${i};color:${r};padding:10px 14px;border-radius:12px;font-size:13px;line-height:1.6;max-width:85%;${s?"margin-left:auto;":""}">\n ${s?this.esc(n.content).replace(/\n/g,"<br>"):Nt.parse(n.content)}\n </div>\n </div>`}).join(""),o=`<!DOCTYPE html>\n<html><head>\n<meta charset="utf-8">\n<title>${this.esc(t)} - Chat Export</title>\n<style>\n @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');\n * { box-sizing: border-box; margin: 0; padding: 0; }\n body { font-family: 'Inter', sans-serif; background: #fff; padding: 40px; color: #111827; max-width: 700px; margin: 0 auto; }\n .header { text-align: center; margin-bottom: 32px; padding-bottom: 20px; border-bottom: 2px solid ${e}; }\n .header h1 { font-size: 22px; font-weight: 700; color: ${e}; }\n .header p { font-size: 12px; color: #9CA3AF; margin-top: 6px; }\n .messages { margin-bottom: 32px; }\n .footer { text-align: center; font-size: 11px; color: #9CA3AF; padding-top: 16px; border-top: 1px solid #E5E7EB; }\n code { background: #EEF2FF; border-radius: 3px; padding: 1px 4px; font-size: 12px; }\n pre { background: #1e293b; border-radius: 8px; padding: 10px; color: #93c5fd; font-size: 12px; overflow-x: auto; margin: 6px 0; }\n pre code { background: none; color: inherit; padding: 0; }\n table { border-collapse: collapse; width: 100%; margin: 6px 0; font-size: 12px; }\n th { background: #f3f4f6; font-weight: 600; padding: 5px 8px; border: 1px solid #e5e7eb; }\n td { padding: 4px 8px; border: 1px solid #e5e7eb; }\n @media print { body { padding: 20px; } }\n</style>\n</head><body>\n<div class="header">\n <h1>${this.esc(t)}</h1>\n <p>${s} at ${i} &middot; ${this.messages.length} messages</p>\n</div>\n<div class="messages">${r}</div>\n<div class="footer">Exported from ${this.esc(t)}</div>\n</body></html>`,a=window.open("","_blank");a&&(a.document.write(o),a.document.close(),a.onload=()=>{setTimeout(()=>a.print(),300)})}async copyMessageText(e,t){try{await navigator.clipboard.writeText(e),t.classList.add("cb-copied"),t.innerHTML=`<span class="cb-tooltip">Copied!</span>${jt.check}`,setTimeout(()=>{t.classList.remove("cb-copied"),t.innerHTML=`<span class="cb-tooltip">Copy</span>${jt.copy}`},2e3)}catch(n){const s=document.createElement("textarea");s.value=e,s.style.position="fixed",s.style.opacity="0",document.body.appendChild(s),s.select(),document.execCommand("copy"),document.body.removeChild(s),t.classList.add("cb-copied"),t.innerHTML=`<span class="cb-tooltip">Copied!</span>${jt.check}`,setTimeout(()=>{t.classList.remove("cb-copied"),t.innerHTML=`<span class="cb-tooltip">Copy</span>${jt.copy}`},2e3)}}handleFeedback(e,t,n){const s=n.closest(".cb-msg-actions");if(!s)return;const i=n.classList.contains("cb-active");s.querySelectorAll(".cb-feedback-btn").forEach(e=>e.classList.remove("cb-active")),i?s.classList.remove("cb-visible"):(n.classList.add("cb-active"),s.classList.add("cb-visible"),this.sendFeedback(e,t))}sendFeedback(e,t){try{fetch(`${this.config.serverUrl}/api/v1/chat/feedback`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey},body:JSON.stringify({messageId:e,sessionId:this.sessionId,feedback:t})}).catch(()=>{})}catch(e){}}clearFollowups(){this.messagesEl.querySelectorAll(".cb-followups").forEach(e=>e.remove())}addFollowups(e){const t=this.generateFollowups(e);if(0===t.length)return;const n=document.createElement("div");n.className="cb-followups",t.forEach(e=>{const t=document.createElement("button");t.className="cb-followup-btn",t.textContent=e,t.addEventListener("click",()=>{this.clearFollowups(),this.send(e)}),n.appendChild(t)}),this.messagesEl.appendChild(n)}generateFollowups(e){const t=[],n=e.toLowerCase();return n.includes("payment")||n.includes("billing")||n.includes("invoice")?t.push("Show payment details","Download invoice"):n.includes("user")||n.includes("account")||n.includes("member")?t.push("Show user details","Account settings"):n.includes("contest")||n.includes("competition")?t.push("List active contests","Contest statistics"):n.includes("error")||n.includes("issue")||n.includes("problem")?t.push("More details","How to fix this?"):(n.includes("report")||n.includes("data")||n.includes("analytics"))&&t.push("Export report","Show more data"),0===t.length&&t.push("Tell me more","Can you explain?"),t.slice(0,3)}destroy(){var e;null===(e=this.socket)||void 0===e||e.disconnect(),this.container.remove()}esc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}}const Ft={init:e=>(Ft._instance&&Ft._instance.destroy(),Ft._instance=new Dt(e),Ft._instance)};if("undefined"!=typeof window){window.ChatBolt=Ft,window.ChatBoltWidget=Dt;const e=()=>{window.ChatBoltConfig&&Ft.init(window.ChatBoltConfig)};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}export{Dt as ChatBoltWidget,Ft as default};
2
2
  //# sourceMappingURL=chatbolt-widget.esm.js.map