translation-chat-sdk 0.3.8 → 0.3.10

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
- (function(R,c){typeof exports=="object"&&typeof module<"u"?c(exports,require("react/jsx-runtime"),require("react")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react"],c):(R=typeof globalThis<"u"?globalThis:R||self,c(R.TranslationChatSDK={},R.React,R.React))})(this,function(R,c,T){"use strict";const L=Object.create(null);L.open="0",L.close="1",L.ping="2",L.pong="3",L.message="4",L.upgrade="5",L.noop="6";const K=Object.create(null);Object.keys(L).forEach(n=>{K[L[n]]=n});const Z={type:"error",data:"parser error"},pe=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",ge=typeof ArrayBuffer=="function",_e=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,ee=({type:n,data:e},t,s)=>pe&&e instanceof Blob?t?s(e):me(e,s):ge&&(e instanceof ArrayBuffer||_e(e))?t?s(e):me(new Blob([e]),s):s(L[n]+(e||"")),me=(n,e)=>{const t=new FileReader;return t.onload=function(){const s=t.result.split(",")[1];e("b"+(s||""))},t.readAsDataURL(n)};function ye(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let te;function qe(n,e){if(pe&&n.data instanceof Blob)return n.data.arrayBuffer().then(ye).then(e);if(ge&&(n.data instanceof ArrayBuffer||_e(n.data)))return e(ye(n.data));ee(n,!1,t=>{te||(te=new TextEncoder),e(te.encode(t))})}const ke="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",H=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n<ke.length;n++)H[ke.charCodeAt(n)]=n;const Ue=n=>{let e=n.length*.75,t=n.length,s,r=0,i,o,a,d;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);const l=new ArrayBuffer(e),u=new Uint8Array(l);for(s=0;s<t;s+=4)i=H[n.charCodeAt(s)],o=H[n.charCodeAt(s+1)],a=H[n.charCodeAt(s+2)],d=H[n.charCodeAt(s+3)],u[r++]=i<<2|o>>4,u[r++]=(o&15)<<4|a>>2,u[r++]=(a&3)<<6|d&63;return l},Me=typeof ArrayBuffer=="function",se=(n,e)=>{if(typeof n!="string")return{type:"message",data:be(n,e)};const t=n.charAt(0);return t==="b"?{type:"message",data:Fe(n.substring(1),e)}:K[t]?n.length>1?{type:K[t],data:n.substring(1)}:{type:K[t]}:Z},Fe=(n,e)=>{if(Me){const t=Ue(n);return be(t,e)}else return{base64:!0,data:n}},be=(n,e)=>{switch(e){case"blob":return n instanceof Blob?n:new Blob([n]);case"arraybuffer":default:return n instanceof ArrayBuffer?n:n.buffer}},we="",He=(n,e)=>{const t=n.length,s=new Array(t);let r=0;n.forEach((i,o)=>{ee(i,!1,a=>{s[o]=a,++r===t&&e(s.join(we))})})},Ve=(n,e)=>{const t=n.split(we),s=[];for(let r=0;r<t.length;r++){const i=se(t[r],e);if(s.push(i),i.type==="error")break}return s};function Ke(){return new TransformStream({transform(n,e){qe(n,t=>{const s=t.length;let r;if(s<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,s);else if(s<65536){r=new Uint8Array(3);const i=new DataView(r.buffer);i.setUint8(0,126),i.setUint16(1,s)}else{r=new Uint8Array(9);const i=new DataView(r.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(s))}n.data&&typeof n.data!="string"&&(r[0]|=128),e.enqueue(r),e.enqueue(t)})}})}let ne;function z(n){return n.reduce((e,t)=>e+t.length,0)}function $(n,e){if(n[0].length===e)return n.shift();const t=new Uint8Array(e);let s=0;for(let r=0;r<e;r++)t[r]=n[0][s++],s===n[0].length&&(n.shift(),s=0);return n.length&&s<n[0].length&&(n[0]=n[0].slice(s)),t}function ze(n,e){ne||(ne=new TextDecoder);const t=[];let s=0,r=-1,i=!1;return new TransformStream({transform(o,a){for(t.push(o);;){if(s===0){if(z(t)<1)break;const d=$(t,1);i=(d[0]&128)===128,r=d[0]&127,r<126?s=3:r===126?s=1:s=2}else if(s===1){if(z(t)<2)break;const d=$(t,2);r=new DataView(d.buffer,d.byteOffset,d.length).getUint16(0),s=3}else if(s===2){if(z(t)<8)break;const d=$(t,8),l=new DataView(d.buffer,d.byteOffset,d.length),u=l.getUint32(0);if(u>Math.pow(2,21)-1){a.enqueue(Z);break}r=u*Math.pow(2,32)+l.getUint32(4),s=3}else{if(z(t)<r)break;const d=$(t,r);a.enqueue(se(i?d:ne.decode(d),e)),s=0}if(r===0||r>n){a.enqueue(Z);break}}}})}const ve=4;function E(n){if(n)return $e(n)}function $e(n){for(var e in E.prototype)n[e]=E.prototype[e];return n}E.prototype.on=E.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this},E.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this},E.prototype.off=E.prototype.removeListener=E.prototype.removeAllListeners=E.prototype.removeEventListener=function(n,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+n];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;for(var s,r=0;r<t.length;r++)if(s=t[r],s===e||s.fn===e){t.splice(r,1);break}return t.length===0&&delete this._callbacks["$"+n],this},E.prototype.emit=function(n){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+n],s=1;s<arguments.length;s++)e[s-1]=arguments[s];if(t){t=t.slice(0);for(var s=0,r=t.length;s<r;++s)t[s].apply(this,e)}return this},E.prototype.emitReserved=E.prototype.emit,E.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]},E.prototype.hasListeners=function(n){return!!this.listeners(n).length};const W=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),A=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),We="arraybuffer";function Qt(){}function xe(n,...e){return e.reduce((t,s)=>(n.hasOwnProperty(s)&&(t[s]=n[s]),t),{})}const Qe=A.setTimeout,Ye=A.clearTimeout;function Q(n,e){e.useNativeTimers?(n.setTimeoutFn=Qe.bind(A),n.clearTimeoutFn=Ye.bind(A)):(n.setTimeoutFn=A.setTimeout.bind(A),n.clearTimeoutFn=A.clearTimeout.bind(A))}const je=1.33;function Je(n){return typeof n=="string"?Xe(n):Math.ceil((n.byteLength||n.size)*je)}function Xe(n){let e=0,t=0;for(let s=0,r=n.length;s<r;s++)e=n.charCodeAt(s),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(s++,t+=4);return t}function Ee(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Ge(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function Ze(n){let e={},t=n.split("&");for(let s=0,r=t.length;s<r;s++){let i=t[s].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}class et extends Error{constructor(e,t,s){super(e),this.description=t,this.context=s,this.type="TransportError"}}class re extends E{constructor(e){super(),this.writable=!1,Q(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,s){return super.emitReserved("error",new et(e,t,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=se(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 e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const t=Ge(e);return t.length?"?"+t:""}}class tt extends re{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 s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||t()})),this.writable||(s++,this.once("drain",function(){--s||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const t=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};Ve(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,He(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=Ee()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let Te=!1;try{Te=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const st=Te;function nt(){}class rt extends tt{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let s=location.port;s||(s=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||s!==e.port}}doWrite(e,t){const s=this.request({method:"POST",data:e});s.on("success",t),s.on("error",(r,i)=>{this.onError("xhr post error",r,i)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,s)=>{this.onError("xhr poll error",t,s)}),this.pollXhr=e}}class B extends E{constructor(e,t,s){super(),this.createRequest=e,Q(this,s),this._opts=s,this._method=s.method||"GET",this._uri=t,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var e;const t=xe(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(t);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&s.setRequestHeader(r,this._opts.extraHeaders[r])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var r;s.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=B.requestsCount++,B.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=nt,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete B.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(B.requestsCount=0,B.requests={},typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Se);else if(typeof addEventListener=="function"){const n="onpagehide"in A?"pagehide":"unload";addEventListener(n,Se,!1)}}function Se(){for(let n in B.requests)B.requests.hasOwnProperty(n)&&B.requests[n].abort()}const it=function(){const n=Ne({xdomain:!1});return n&&n.responseType!==null}();class ot extends rt{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=it&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new B(Ne,this.uri(),e)}}function Ne(n){const e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||st))return new XMLHttpRequest}catch{}if(!e)try{return new A[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Ce=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class ct extends re{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=Ce?{}:xe(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,s)}catch(r){return this.emitReserved("error",r)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],r=t===e.length-1;ee(s,this.supportsBinary,i=>{try{this.doWrite(s,i)}catch{}r&&W(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=Ee()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const ie=A.WebSocket||A.MozWebSocket;class at extends ct{createSocket(e,t,s){return Ce?new ie(e,t,s):t?new ie(e,t):new ie(e)}doWrite(e,t){this.ws.send(t)}}class ht extends re{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=ze(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),r=Ke();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();const i=()=>{s.read().then(({done:a,value:d})=>{a||(this.onPacket(d),i())}).catch(a=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],r=t===e.length-1;this._writer.write(s).then(()=>{r&&W(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const lt={websocket:at,webtransport:ht,polling:ot},dt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ut=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function oe(n){if(n.length>8e3)throw"URI too long";const e=n,t=n.indexOf("["),s=n.indexOf("]");t!=-1&&s!=-1&&(n=n.substring(0,t)+n.substring(t,s).replace(/:/g,";")+n.substring(s,n.length));let r=dt.exec(n||""),i={},o=14;for(;o--;)i[ut[o]]=r[o]||"";return t!=-1&&s!=-1&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=ft(i,i.path),i.queryKey=pt(i,i.query),i}function ft(n,e){const t=/\/{2,9}/g,s=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&s.splice(0,1),e.slice(-1)=="/"&&s.splice(s.length-1,1),s}function pt(n,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,r,i){r&&(t[r]=i)}),t}const ce=typeof addEventListener=="function"&&typeof removeEventListener=="function",Y=[];ce&&addEventListener("offline",()=>{Y.forEach(n=>n())},!1);class D extends E{constructor(e,t){if(super(),this.binaryType=We,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){const s=oe(e);t.hostname=s.host,t.secure=s.protocol==="https"||s.protocol==="wss",t.port=s.port,s.query&&(t.query=s.query)}else t.host&&(t.hostname=oe(t.host).host);Q(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(s=>{const r=s.prototype.name;this.transports.push(r),this._transportsByName[r]=s}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Ze(this.opts.query)),ce&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Y.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=ve,t.transport=e,this.id&&(t.sid=this.id);const s=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](s)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&D.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",D.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let s=0;s<this.writeBuffer.length;s++){const r=this.writeBuffer[s].data;if(r&&(t+=Je(r)),s>0&&t>this._maxPayload)return this.writeBuffer.slice(0,s);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,W(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,s){return this._sendPacket("message",e,t,s),this}send(e,t,s){return this._sendPacket("message",e,t,s),this}_sendPacket(e,t,s,r){if(typeof t=="function"&&(r=t,t=void 0),typeof s=="function"&&(r=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const i={type:e,data:t,options:s};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},s=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():e()}):this.upgrading?s():e()),this}_onError(e){if(D.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),ce&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=Y.indexOf(this._offlineEventListener);s!==-1&&Y.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}D.protocol=ve;class gt extends D{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),s=!1;D.priorWebsocketSuccess=!1;const r=()=>{s||(t.send([{type:"ping",data:"probe"}]),t.once("packet",f=>{if(!s)if(f.type==="pong"&&f.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;D.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(u(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=t.name,this.emitReserved("upgradeError",g)}}))};function i(){s||(s=!0,u(),t.close(),t=null)}const o=f=>{const g=new Error("probe error: "+f);g.transport=t.name,i(),this.emitReserved("upgradeError",g)};function a(){o("transport closed")}function d(){o("socket closed")}function l(f){t&&f.name!==t.name&&i()}const u=()=>{t.removeListener("open",r),t.removeListener("error",o),t.removeListener("close",a),this.off("close",d),this.off("upgrading",l)};t.once("open",r),t.once("error",o),t.once("close",a),this.once("close",d),this.once("upgrading",l),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{s||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let s=0;s<e.length;s++)~this.transports.indexOf(e[s])&&t.push(e[s]);return t}}let _t=class extends gt{constructor(e,t={}){const s=typeof e=="object"?e:t;(!s.transports||s.transports&&typeof s.transports[0]=="string")&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(r=>lt[r]).filter(r=>!!r)),super(e,s)}};function mt(n,e="",t){let s=n;t=t||typeof location<"u"&&location,n==null&&(n=t.protocol+"//"+t.host),typeof n=="string"&&(n.charAt(0)==="/"&&(n.charAt(1)==="/"?n=t.protocol+n:n=t.host+n),/^(https?|wss?):\/\//.test(n)||(typeof t<"u"?n=t.protocol+"//"+n:n="https://"+n),s=oe(n)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const i=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+i+":"+s.port+e,s.href=s.protocol+"://"+i+(t&&t.port===s.port?"":":"+s.port),s}const yt=typeof ArrayBuffer=="function",kt=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,Ae=Object.prototype.toString,bt=typeof Blob=="function"||typeof Blob<"u"&&Ae.call(Blob)==="[object BlobConstructor]",wt=typeof File=="function"||typeof File<"u"&&Ae.call(File)==="[object FileConstructor]";function ae(n){return yt&&(n instanceof ArrayBuffer||kt(n))||bt&&n instanceof Blob||wt&&n instanceof File}function j(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,s=n.length;t<s;t++)if(j(n[t]))return!0;return!1}if(ae(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return j(n.toJSON(),!0);for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&j(n[t]))return!0;return!1}function vt(n){const e=[],t=n.data,s=n;return s.data=he(t,e),s.attachments=e.length,{packet:s,buffers:e}}function he(n,e){if(!n)return n;if(ae(n)){const t={_placeholder:!0,num:e.length};return e.push(n),t}else if(Array.isArray(n)){const t=new Array(n.length);for(let s=0;s<n.length;s++)t[s]=he(n[s],e);return t}else if(typeof n=="object"&&!(n instanceof Date)){const t={};for(const s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=he(n[s],e));return t}return n}function xt(n,e){return n.data=le(n.data,e),delete n.attachments,n}function le(n,e){if(!n)return n;if(n&&n._placeholder===!0){if(typeof n.num=="number"&&n.num>=0&&n.num<e.length)return e[n.num];throw new Error("illegal attachments")}else if(Array.isArray(n))for(let t=0;t<n.length;t++)n[t]=le(n[t],e);else if(typeof n=="object")for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=le(n[t],e));return n}const Re=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],Et=5;var _;(function(n){n[n.CONNECT=0]="CONNECT",n[n.DISCONNECT=1]="DISCONNECT",n[n.EVENT=2]="EVENT",n[n.ACK=3]="ACK",n[n.CONNECT_ERROR=4]="CONNECT_ERROR",n[n.BINARY_EVENT=5]="BINARY_EVENT",n[n.BINARY_ACK=6]="BINARY_ACK"})(_||(_={}));class Tt{constructor(e){this.replacer=e}encode(e){return(e.type===_.EVENT||e.type===_.ACK)&&j(e)?this.encodeAsBinary({type:e.type===_.EVENT?_.BINARY_EVENT:_.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===_.BINARY_EVENT||e.type===_.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=vt(e),s=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(s),r}}class de extends E{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const s=t.type===_.BINARY_EVENT;s||t.type===_.BINARY_ACK?(t.type=s?_.EVENT:_.ACK,this.reconstructor=new St(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(ae(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0;const s={type:Number(e.charAt(0))};if(_[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===_.BINARY_EVENT||s.type===_.BINARY_ACK){const i=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const o=e.substring(i,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");s.attachments=Number(o)}if(e.charAt(t+1)==="/"){const i=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););s.nsp=e.substring(i,t)}else s.nsp="/";const r=e.charAt(t+1);if(r!==""&&Number(r)==r){const i=t+1;for(;++t;){const o=e.charAt(t);if(o==null||Number(o)!=o){--t;break}if(t===e.length)break}s.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(de.isPayloadValid(s.type,i))s.data=i;else throw new Error("invalid payload")}return s}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case _.CONNECT:return J(t);case _.DISCONNECT:return t===void 0;case _.CONNECT_ERROR:return typeof t=="string"||J(t);case _.EVENT:case _.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Re.indexOf(t[0])===-1);case _.ACK:case _.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class St{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const t=xt(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function Nt(n){return typeof n=="string"}const Ct=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n};function At(n){return n===void 0||Ct(n)}function J(n){return Object.prototype.toString.call(n)==="[object Object]"}function Rt(n,e){switch(n){case _.CONNECT:return e===void 0||J(e);case _.DISCONNECT:return e===void 0;case _.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Re.indexOf(e[0])===-1);case _.ACK:return Array.isArray(e);case _.CONNECT_ERROR:return typeof e=="string"||J(e);default:return!1}}function Ot(n){return Nt(n.nsp)&&At(n.id)&&Rt(n.type,n.data)}const Pt=Object.freeze(Object.defineProperty({__proto__:null,Decoder:de,Encoder:Tt,get PacketType(){return _},isPacketValid:Ot,protocol:Et},Symbol.toStringTag,{value:"Module"}));function O(n,e,t){return n.on(e,t),function(){n.off(e,t)}}const Lt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Oe extends E{constructor(e,t,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[O(e,"open",this.onopen.bind(this)),O(e,"packet",this.onpacket.bind(this)),O(e,"error",this.onerror.bind(this)),O(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var s,r,i;if(Lt.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 o={type:_.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const u=this.ids++,f=t.pop();this._registerAckCallback(u,f),o.id=u}const a=(r=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||r===void 0?void 0:r.writable,d=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!a||(d?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var s;const r=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(r===void 0){this.acks[e]=t;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let a=0;a<this.sendBuffer.length;a++)this.sendBuffer[a].id===e&&this.sendBuffer.splice(a,1);t.call(this,new Error("operation has timed out"))},r),o=(...a)=>{this.io.clearTimeoutFn(i),t.apply(this,a)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((s,r)=>{const i=(o,a)=>o?r(o):s(a);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((r,...i)=>(this._queue[0],r!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(r)):(this._queue.shift(),t&&t(null,...i)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:_.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(s=>String(s.id)===e)){const s=this.acks[e];delete this.acks[e],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case _.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 _.EVENT:case _.BINARY_EVENT:this.onevent(e);break;case _.ACK:case _.BINARY_ACK:this.onack(e);break;case _.DISCONNECT:this.ondisconnect();break;case _.CONNECT_ERROR:this.destroy();const s=new Error(e.data.message);s.data=e.data.data,this.emitReserved("connect_error",s);break}}onevent(e){const t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const s of t)s.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let s=!1;return function(...r){s||(s=!0,t.packet({type:_.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._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:_.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let s=0;s<t.length;s++)if(e===t[s])return t.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let s=0;s<t.length;s++)if(e===t[s])return t.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const s of t)s.apply(this,e.data)}}}function F(n){n=n||{},this.ms=n.min||100,this.max=n.max||1e4,this.factor=n.factor||2,this.jitter=n.jitter>0&&n.jitter<=1?n.jitter:0,this.attempts=0}F.prototype.duration=function(){var n=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*n);n=Math.floor(e*10)&1?n+t:n-t}return Math.min(n,this.max)|0},F.prototype.reset=function(){this.attempts=0},F.prototype.setMin=function(n){this.ms=n},F.prototype.setMax=function(n){this.max=n},F.prototype.setJitter=function(n){this.jitter=n};class ue extends E{constructor(e,t){var s;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,Q(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((s=t.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new F({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||Pt;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new _t(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=O(t,"open",function(){s.onopen(),e&&e()}),i=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=O(t,"error",i);if(this._timeout!==!1){const a=this._timeout,d=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),t.close()},a);this.opts.autoUnref&&d.unref(),this.subs.push(()=>{this.clearTimeoutFn(d)})}return this.subs.push(r),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(O(e,"ping",this.onping.bind(this)),O(e,"data",this.ondata.bind(this)),O(e,"error",this.onerror.bind(this)),O(e,"close",this.onclose.bind(this)),O(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){W(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let s=this.nsps[e];return s?this._autoConnect&&!s.active&&s.connect():(s=new Oe(this,e,t),this.nsps[e]=s),s}_destroy(e){const t=Object.keys(this.nsps);for(const s of t)if(this.nsps[s].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let s=0;s<t.length;s++)this.engine.write(t[s],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var s;this.cleanup(),(s=this.engine)===null||s===void 0||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(r=>{r?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",r)):e.onreconnect()}))},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const V={};function X(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};const t=mt(n,e.path||"/socket.io"),s=t.source,r=t.id,i=t.path,o=V[r]&&i in V[r].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let d;return a?d=new ue(s,e):(V[r]||(V[r]=new ue(s,e)),d=V[r]),t.query&&!e.query&&(e.query=t.queryKey),d.socket(t.path,e)}Object.assign(X,{Manager:ue,Socket:Oe,io:X,connect:X});function C(){return`${Date.now().toString(36)}-${Math.random().toString(16).slice(2,8)}`}class Bt{constructor(e){this.socket=null,this.reconnectAttempts=0,this.listeners=new Map,this.lastContext=null,this.config={reconnectAttempts:5,reconnectDelayMs:1500,logger:console,...e}}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{var s;return(s=this.listeners.get(e))==null?void 0:s.delete(t)}}emit(e,t){var s;(s=this.listeners.get(e))==null||s.forEach(r=>{var i,o;try{r(t)}catch(a){(o=(i=this.config.logger)==null?void 0:i.error)==null||o.call(i,`chat-sdk listener error for ${e}`,a)}})}setConnection(e){var t,s;this.emit("connection",e),(s=(t=this.config).onConnectionChange)==null||s.call(t,e)}async getToken(){var t,s;const{tokenProvider:e}=this.config;if(!e)return null;try{return(typeof e=="function"?await e():e)||null}catch(r){return(s=(t=this.config.logger)==null?void 0:t.warn)==null||s.call(t,"chat-sdk token provider failed",r),null}}async connect(){var i;if((i=this.socket)!=null&&i.connected)return;const e=new URL(this.config.websocketUrl),t=e.pathname==="/"?"/socket.io":e.pathname,s=e.origin,r=await this.getToken();return this.socket=X(s,{path:t,transports:["websocket","polling"],autoConnect:!1,reconnection:!1,auth:r?{token:r}:void 0,withCredentials:!0}),this.registerSocketEvents(),this.setConnection({connected:!1,connecting:!0}),new Promise((o,a)=>{const d=setTimeout(()=>{a(new Error("connection timeout"))},1e4);this.socket.once("connect",()=>{clearTimeout(d),this.reconnectAttempts=0,this.setConnection({connected:!0,connecting:!1}),o()}),this.socket.once("connect_error",l=>{clearTimeout(d),this.setConnection({connected:!1,connecting:!1,error:l.message}),this.handleReconnect(),a(l)}),this.socket.connect()})}disconnect(){var e;(e=this.socket)==null||e.disconnect(),this.socket=null,this.setConnection({connected:!1,connecting:!1})}async submitInstruction(e,t){var i,o;if(!((i=this.socket)!=null&&i.connected))throw new Error("Not connected");this.lastContext=t;const s=await this.getToken(),r={trans_doc_id:t.trans_doc_id,page_num:t.page_num,instruction:e,modification_level:"page",access_token:s||void 0,region_coordinates:t.highlighted_region?{start_offset:t.highlighted_region.start_offset,end_offset:t.highlighted_region.end_offset}:void 0,region_text:(o=t.highlighted_region)==null?void 0:o.text,selection_id:t.selection_id};this.socket.emit("INSTR_SUBMIT",r)}async requestChatHistory(e){var s;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();this.lastContext=e,this.socket.emit("CHAT_HISTORY_REQUEST",{trans_doc_id:e.trans_doc_id,access_token:t||void 0})}async sendPatchDecision(e){var s,r,i,o,a;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();(i=(r=this.config.logger)==null?void 0:r.log)==null||i.call(r,"[chat-sdk] Sending PATCH_DECISION:",{trans_doc_id:e.trans_doc_id,page_num:e.page_num,instruction_id:e.instruction_id,decision:e.decision,remember_this:e.remember_this,has_access_token:!!t}),this.socket.emit("PATCH_DECISION",{...e,access_token:t||void 0}),(a=(o=this.config.logger)==null?void 0:o.log)==null||a.call(o,"[chat-sdk] PATCH_DECISION emitted successfully")}async requestPageTranslation(e){var r,i,o,a,d;if(!((r=this.socket)!=null&&r.connected))throw new Error("Not connected");const t=await this.getToken(),s={...e,access_token:t||void 0};(o=(i=this.config.logger)==null?void 0:i.log)==null||o.call(i,"[chat-sdk] Sending PAGE_TRANSLATION_REQUEST:",{trans_doc_id:e.trans_doc_id,page_num:e.page_num,has_access_token:!!t}),this.socket.emit("PAGE_TRANSLATION_REQUEST",s),(d=(a=this.config.logger)==null?void 0:a.log)==null||d.call(a,"[chat-sdk] PAGE_TRANSLATION_REQUEST emitted successfully")}async requestBulkTranslation(e){var r,i,o,a,d;if(!((r=this.socket)!=null&&r.connected))throw new Error("Not connected");const t=await this.getToken(),s={...e,access_token:t||void 0};(o=(i=this.config.logger)==null?void 0:i.log)==null||o.call(i,"[chat-sdk] Sending BULK_TRANSLATION_REQUEST:",{trans_doc_id:e.trans_doc_id,page_list:e.page_list,has_access_token:!!t}),this.socket.emit("BULK_TRANSLATION_REQUEST",s),(d=(a=this.config.logger)==null?void 0:a.log)==null||d.call(a,"[chat-sdk] BULK_TRANSLATION_REQUEST emitted successfully")}async cancelBulkTranslation(e){var s,r,i,o,a;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();(i=(r=this.config.logger)==null?void 0:r.log)==null||i.call(r,"[chat-sdk] Sending CANCEL_BULK_TRANSLATION_REQUEST:",{trans_doc_id:e,has_access_token:!!t}),this.socket.emit("CANCEL_BULK_TRANSLATION_REQUEST",{trans_doc_id:e,access_token:t||void 0}),(a=(o=this.config.logger)==null?void 0:o.log)==null||a.call(o,"[chat-sdk] CANCEL_BULK_TRANSLATION_REQUEST emitted successfully")}async requestLearnedRules(e){var s,r,i,o,a;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();(i=(r=this.config.logger)==null?void 0:r.log)==null||i.call(r,"[chat-sdk] Sending LEARNED_RULES_REQUEST:",{trans_doc_id:e,has_access_token:!!t}),this.socket.emit("LEARNED_RULES_REQUEST",{trans_doc_id:e,access_token:t||void 0}),(a=(o=this.config.logger)==null?void 0:o.log)==null||a.call(o,"[chat-sdk] LEARNED_RULES_REQUEST emitted successfully")}async updateRules(e,t){var r,i,o,a,d;if(!((r=this.socket)!=null&&r.connected))throw new Error("Not connected");const s=await this.getToken();(o=(i=this.config.logger)==null?void 0:i.log)==null||o.call(i,"[chat-sdk] Sending UPDATE_RULES_REQUEST:",{trans_doc_id:e,rules_text_length:t.length,has_access_token:!!s}),this.socket.emit("UPDATE_RULES_REQUEST",{trans_doc_id:e,rules_text:t,access_token:s||void 0}),(d=(a=this.config.logger)==null?void 0:a.log)==null||d.call(a,"[chat-sdk] UPDATE_RULES_REQUEST emitted successfully")}registerSocketEvents(){this.socket&&(this.socket.on("disconnect",()=>{this.setConnection({connected:!1,connecting:!1}),this.handleReconnect()}),this.socket.on("connect_error",e=>{this.setConnection({connected:!1,connecting:!1,error:e.message}),this.handleReconnect()}),this.socket.on("CHAT_RESPONSE",e=>{this.emit("chat-response",e)}),this.socket.on("PATCH_OFFER",e=>{this.emit("patch-offer",e)}),this.socket.on("CHAT_HISTORY_RESPONSE",e=>{this.emit("chat-history-response",e)}),this.socket.on("INSTRUCTION_ERROR",e=>{this.emit("instruction-error",e)}),this.socket.on("PAGE_TRANSLATION_RESPONSE",e=>{var t,s,r,i,o,a,d,l,u,f,g;(r=(t=this.config.logger)==null?void 0:t.log)==null||r.call(t,"[chat-sdk] Received PAGE_TRANSLATION_RESPONSE from socket:",{trans_doc_id:e.trans_doc_id,page_num:e.page_num,status:e.status,has_content:!!e.trans_page_content,content_length:(s=e.trans_page_content)==null?void 0:s.length,error:e.error,error_type:e.error_type,updated_at:e.updated_at}),this.emit("page-translation-response",e),(o=(i=this.config.logger)==null?void 0:i.log)==null||o.call(i,"[chat-sdk] Emitted page-translation-response internally"),this.config.onPageTranslationResponse?((d=(a=this.config.logger)==null?void 0:a.log)==null||d.call(a,"[chat-sdk] Calling onPageTranslationResponse callback"),this.config.onPageTranslationResponse(e),(u=(l=this.config.logger)==null?void 0:l.log)==null||u.call(l,"[chat-sdk] onPageTranslationResponse callback completed")):(g=(f=this.config.logger)==null?void 0:f.log)==null||g.call(f,"[chat-sdk] No onPageTranslationResponse callback configured")}),this.socket.on("BULK_TRANSLATION_RESPONSE",e=>{var t,s,r,i,o,a,d,l,u,f;(s=(t=this.config.logger)==null?void 0:t.log)==null||s.call(t,"[chat-sdk] Received BULK_TRANSLATION_RESPONSE from socket:",{trans_doc_id:e.trans_doc_id,status:e.status,completed_pages:e.completed_pages,total_pages:e.total_pages,current_page:e.current_page,error:e.error,error_type:e.error_type}),this.emit("bulk-translation-response",e),(i=(r=this.config.logger)==null?void 0:r.log)==null||i.call(r,"[chat-sdk] Emitted bulk-translation-response internally"),this.config.onBulkTranslationResponse?((a=(o=this.config.logger)==null?void 0:o.log)==null||a.call(o,"[chat-sdk] Calling onBulkTranslationResponse callback"),this.config.onBulkTranslationResponse(e),(l=(d=this.config.logger)==null?void 0:d.log)==null||l.call(d,"[chat-sdk] onBulkTranslationResponse callback completed")):(f=(u=this.config.logger)==null?void 0:u.log)==null||f.call(u,"[chat-sdk] No onBulkTranslationResponse callback configured")}),this.socket.on("RULE_LEARNED",e=>{var t,s;(s=(t=this.config.logger)==null?void 0:t.log)==null||s.call(t,"[chat-sdk] Received RULE_LEARNED from socket:",{trans_doc_id:e.trans_doc_id,instruction_id:e.instruction_id,rule_summary:e.rule_summary}),this.emit("rule-learned",e),this.config.onRuleLearned&&this.config.onRuleLearned(e)}),this.socket.on("LEARNED_RULES_RESPONSE",e=>{var t,s;(s=(t=this.config.logger)==null?void 0:t.log)==null||s.call(t,"[chat-sdk] Received LEARNED_RULES_RESPONSE from socket:",{trans_doc_id:e.trans_doc_id,has_rules:e.has_rules,status:e.status,error:e.error}),this.emit("learned-rules-response",e),this.config.onLearnedRulesResponse&&this.config.onLearnedRulesResponse(e)}),this.socket.on("UPDATE_RULES_RESPONSE",e=>{var t,s;(s=(t=this.config.logger)==null?void 0:t.log)==null||s.call(t,"[chat-sdk] Received UPDATE_RULES_RESPONSE from socket:",{trans_doc_id:e.trans_doc_id,status:e.status,error:e.error}),this.emit("update-rules-response",e),this.config.onUpdateRulesResponse&&this.config.onUpdateRulesResponse(e)}),this.socket.on("connected",()=>{this.lastContext&&this.requestChatHistory(this.lastContext).catch(e=>{var t,s;return(s=(t=this.config.logger)==null?void 0:t.warn)==null?void 0:s.call(t,"chat-sdk history on reconnect failed",e)})}))}handleReconnect(){var e,t;if(this.reconnectAttempts>=(this.config.reconnectAttempts??5)){(t=(e=this.config.logger)==null?void 0:e.warn)==null||t.call(e,"chat-sdk max reconnection attempts reached");return}this.reconnectAttempts+=1,setTimeout(()=>{this.connect().catch(s=>{var r,i;return(i=(r=this.config.logger)==null?void 0:r.error)==null?void 0:i.call(r,"chat-sdk reconnect failed",s)})},this.config.reconnectDelayMs)}}function Dt(n){return n.map(e=>{const t={instructionId:e.instruction_id,pageNum:e.page_num??void 0,timestamp:new Date(e.timestamp)};if(e.response_type==="rule_learned")return[{...t,id:C(),type:"rule-learned",content:e.response_content||"Rule learned",ruleSummary:e.rule_summary??void 0}];const s={...t,id:C(),type:"user",content:e.instruction,contextText:e.region_text??void 0},r=[];return e.response_content&&e.response_type==="chat"&&r.push({...t,id:C(),type:"ai-chat",content:e.response_content}),e.response_content&&e.response_type==="patch"&&r.push({...t,id:C(),type:"ai-patch",content:e.response_content,patchData:{originalText:e.region_text??void 0,improvedText:e.response_content,regionText:e.region_text??void 0,isComplete:!0}}),[s,...r]}).flat().sort((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())}const Pe=T.createContext(null),It={connected:!1,connecting:!1};function qt({config:n,children:e}){const t=T.useRef(null),s=T.useRef(new Map),[r,i]=T.useState({messages:[],connection:It,latestPatchOffer:null,isSubmitting:!1}),o=T.useMemo(()=>({reconnectAttempts:5,reconnectDelayMs:1500,...n}),[n]);T.useEffect(()=>{const l=new Bt(o);t.current=l;const u=l.on("connection",h=>{i(p=>({...p,connection:h}))}),f=l.on("chat-response",h=>{i(p=>{const w=p.messages.filter(k=>k.type!=="loading");let v=w.find(k=>k.instructionId===h.instruction_id&&k.type==="ai-chat");v||(v={id:C(),type:"ai-chat",content:"",timestamp:new Date,instructionId:h.instruction_id,pageNum:h.page_num,isStreaming:!0},w.push(v));const S={...v,content:(v.content||"")+(h.chunk_text||""),isStreaming:!h.is_final},m=w.map(k=>k.id===v.id?S:k);return{...p,messages:m,isSubmitting:h.is_final?!1:p.isSubmitting}})}),g=l.on("patch-offer",h=>{var v;const p=`${h.trans_doc_id}-${h.instruction_id}`,w=s.current.get(p)??{trans_doc_id:h.trans_doc_id,page_num:h.page_num,instruction_id:h.instruction_id,original_text:h.region_original_text||"",highlighted_region:h.region_coordinates,new_suggestion:"",is_page_level:!h.region_coordinates,selection_id:h.selection_id};if(w.new_suggestion+=h.region_replacement_text_chunk||"",h.selection_id&&!w.selection_id&&(w.selection_id=h.selection_id),s.current.set(p,w),i(S=>{var Ie;const m=S.messages.filter(M=>M.type!=="loading");let k=m.find(M=>M.instructionId===h.instruction_id&&M.type==="ai-patch");k||(k={id:C(),type:"ai-patch",content:"",timestamp:new Date,instructionId:h.instruction_id,pageNum:h.page_num,isStreaming:!0,patchData:{originalText:h.region_original_text,improvedText:"",regionText:h.region_original_text,isComplete:!1}},m.push(k));const N={...k,content:(k.content||"")+(h.region_replacement_text_chunk||""),isStreaming:!h.is_final,patchData:{...k.patchData,improvedText:(((Ie=k.patchData)==null?void 0:Ie.improvedText)||"")+(h.region_replacement_text_chunk||""),regionText:h.region_original_text,isComplete:h.is_final}},U=m.map(M=>M.id===k.id?N:M);return{...S,messages:U,isSubmitting:h.is_final?!1:S.isSubmitting}}),h.is_final){const S=s.current.get(p);S&&((v=o.onPatchOffer)==null||v.call(o,S),i(m=>({...m,latestPatchOffer:S}))),s.current.delete(p)}}),y=l.on("chat-history-response",h=>{if(h.status==="success"){const p=Dt(h.messages);i(w=>({...w,messages:p}))}else i(p=>({...p,messages:[...p.messages,{id:C(),type:"system",content:h.error||"Failed to load chat history",timestamp:new Date}]}))}),b=l.on("instruction-error",h=>{i(p=>({...p,isSubmitting:!1,messages:[...p.messages,{id:C(),type:"error",content:h.error,timestamp:new Date}]}))}),x=l.on("page-translation-response",h=>{var p,w,v,S,m,k,N,U;(w=(p=o.logger)==null?void 0:p.log)==null||w.call(p,"[chat-sdk][ChatProvider] Received page-translation-response event:",{trans_doc_id:h.trans_doc_id,page_num:h.page_num,status:h.status,has_content:!!h.trans_page_content,error:h.error}),o.onPageTranslationResponse?((S=(v=o.logger)==null?void 0:v.log)==null||S.call(v,"[chat-sdk][ChatProvider] Invoking onPageTranslationResponse callback from config"),o.onPageTranslationResponse(h),(k=(m=o.logger)==null?void 0:m.log)==null||k.call(m,"[chat-sdk][ChatProvider] onPageTranslationResponse callback completed")):(U=(N=o.logger)==null?void 0:N.log)==null||U.call(N,"[chat-sdk][ChatProvider] No onPageTranslationResponse callback in config")}),I=l.on("bulk-translation-response",h=>{var p,w,v,S,m,k,N,U;(w=(p=o.logger)==null?void 0:p.log)==null||w.call(p,"[chat-sdk][ChatProvider] Received bulk-translation-response event:",{trans_doc_id:h.trans_doc_id,status:h.status,completed_pages:h.completed_pages,total_pages:h.total_pages,current_page:h.current_page,error:h.error}),o.onBulkTranslationResponse?((S=(v=o.logger)==null?void 0:v.log)==null||S.call(v,"[chat-sdk][ChatProvider] Invoking onBulkTranslationResponse callback from config"),o.onBulkTranslationResponse(h),(k=(m=o.logger)==null?void 0:m.log)==null||k.call(m,"[chat-sdk][ChatProvider] onBulkTranslationResponse callback completed")):(U=(N=o.logger)==null?void 0:N.log)==null||U.call(N,"[chat-sdk][ChatProvider] No onBulkTranslationResponse callback in config")}),P=l.on("rule-learned",h=>{var p,w;(w=(p=o.logger)==null?void 0:p.log)==null||w.call(p,"[chat-sdk][ChatProvider] Received rule-learned event:",{trans_doc_id:h.trans_doc_id,instruction_id:h.instruction_id,rule_summary:h.rule_summary}),i(v=>({...v,messages:[...v.messages,{id:C(),type:"rule-learned",content:h.message||"Rule learned",timestamp:new Date,instructionId:h.instruction_id,ruleSummary:h.rule_summary}]})),o.onRuleLearned&&o.onRuleLearned(h)}),q=l.on("learned-rules-response",h=>{var p,w;(w=(p=o.logger)==null?void 0:p.log)==null||w.call(p,"[chat-sdk][ChatProvider] Received learned-rules-response event:",{trans_doc_id:h.trans_doc_id,has_rules:h.has_rules,status:h.status}),o.onLearnedRulesResponse&&o.onLearnedRulesResponse(h)});return l.connect().then(()=>{const h=o.contextProvider();if(h)return l.requestChatHistory(h)}).catch(h=>{var p,w;return(w=(p=o.logger)==null?void 0:p.warn)==null?void 0:w.call(p,"chat-sdk connect failed",h)}),()=>{u(),f(),g(),y(),b(),x(),I(),P(),q(),l.disconnect()}},[o]);const a=T.useMemo(()=>({async submitInstruction(l){const u=t.current;if(!u)throw new Error("SDK not ready");const f=o.contextProvider();if(!f)throw new Error("contextProvider returned null");i(g=>{var y;return{...g,isSubmitting:!0,messages:[...g.messages,{id:C(),type:"user",content:l,timestamp:new Date,pageNum:f.page_num,contextText:(y=f.highlighted_region)==null?void 0:y.text},{id:C(),type:"loading",content:"Processing your instruction...",timestamp:new Date,isStreaming:!0}]}}),await u.submitInstruction(l,f)},async submitInstructionWithContext(l,u){const f=t.current;if(!f)throw new Error("SDK not ready");i(g=>{var y;return{...g,isSubmitting:!0,messages:[...g.messages,{id:C(),type:"user",content:l,timestamp:new Date,pageNum:u.page_num,contextText:(y=u.highlighted_region)==null?void 0:y.text},{id:C(),type:"loading",content:"Processing your instruction...",timestamp:new Date,isStreaming:!0}]}}),await f.submitInstruction(l,u)},async requestChatHistory(){const l=t.current;if(!l)throw new Error("SDK not ready");const u=o.contextProvider();if(!u)throw new Error("contextProvider returned null");await l.requestChatHistory(u)},async sendPatchDecision(l,u,f,g,y){var x,I,P,q;const b=t.current;if(!b)throw new Error("SDK not ready");(I=(x=o.logger)==null?void 0:x.log)==null||I.call(x,"[chat-sdk][ChatProvider] sendPatchDecision called:",{trans_doc_id:l,page_num:u,instruction_id:f,decision:g,remember_this:y}),await b.sendPatchDecision({trans_doc_id:l,page_num:u,instruction_id:f,decision:g,remember_this:y}),(q=(P=o.logger)==null?void 0:P.log)==null||q.call(P,"[chat-sdk][ChatProvider] sendPatchDecision completed"),i(h=>({...h,latestPatchOffer:null}))},async requestPageTranslation(l,u){var g,y,b,x;const f=t.current;if(!f)throw new Error("SDK not ready");return(y=(g=o.logger)==null?void 0:g.log)==null||y.call(g,"[chat-sdk][ChatProvider] requestPageTranslation called:",{trans_doc_id:l,page_num:u}),await f.requestPageTranslation({trans_doc_id:l,page_num:u}),(x=(b=o.logger)==null?void 0:b.log)==null||x.call(b,"[chat-sdk][ChatProvider] requestPageTranslation request sent"),!0},async requestBulkTranslation(l,u){var g,y,b,x;const f=t.current;if(!f)throw new Error("SDK not ready");return(y=(g=o.logger)==null?void 0:g.log)==null||y.call(g,"[chat-sdk][ChatProvider] requestBulkTranslation called:",{trans_doc_id:l,page_list:u}),await f.requestBulkTranslation({trans_doc_id:l,page_list:u}),(x=(b=o.logger)==null?void 0:b.log)==null||x.call(b,"[chat-sdk][ChatProvider] requestBulkTranslation request sent"),!0},async cancelBulkTranslation(l){var f,g,y,b;const u=t.current;if(!u)throw new Error("SDK not ready");return(g=(f=o.logger)==null?void 0:f.log)==null||g.call(f,"[chat-sdk][ChatProvider] cancelBulkTranslation called:",{trans_doc_id:l}),await u.cancelBulkTranslation(l),(b=(y=o.logger)==null?void 0:y.log)==null||b.call(y,"[chat-sdk][ChatProvider] cancelBulkTranslation request sent"),!0},async requestLearnedRules(l){var f,g,y,b;const u=t.current;if(!u)throw new Error("SDK not ready");(g=(f=o.logger)==null?void 0:f.log)==null||g.call(f,"[chat-sdk][ChatProvider] requestLearnedRules called:",{trans_doc_id:l}),await u.requestLearnedRules(l),(b=(y=o.logger)==null?void 0:y.log)==null||b.call(y,"[chat-sdk][ChatProvider] requestLearnedRules request sent")},async updateRules(l,u){var g,y,b,x;const f=t.current;if(!f)throw new Error("SDK not ready");(y=(g=o.logger)==null?void 0:g.log)==null||y.call(g,"[chat-sdk][ChatProvider] updateRules called:",{trans_doc_id:l,rules_text_length:u.length}),await f.updateRules(l,u),(x=(b=o.logger)==null?void 0:b.log)==null||x.call(b,"[chat-sdk][ChatProvider] updateRules request sent")},clearMessages(){i(l=>({...l,messages:[]}))},clearSelection(){var l;(l=o.onClearSelection)==null||l.call(o)}}),[o]),d=T.useMemo(()=>({...r,...a}),[r,a]);return c.jsx(Pe.Provider,{value:d,children:e})}function Ut(){const n=T.useContext(Pe);if(!n)throw new Error("useChat must be used within ChatProvider");return n}function Le(){return Ut()}const Be=T.forwardRef(({title:n="AI Assistance",placeholder:e="Ask anything...",height:t="500px",onClose:s},r)=>{const{messages:i,connection:o,submitInstruction:a,submitInstructionWithContext:d,isSubmitting:l,clearSelection:u}=Le(),[f,g]=T.useState(""),[y,b]=T.useState(null),[x,I]=T.useState(null),P=T.useRef(null),q=T.useRef(null),h=!o.connected||l;T.useImperativeHandle(r,()=>({setContext:({text:m,context:k})=>{I(m),b(k),setTimeout(()=>{var N;(N=q.current)==null||N.focus()},100)},focusInput:()=>{var m;(m=q.current)==null||m.focus()}}),[]);const p=T.useMemo(()=>[...i].sort((m,k)=>m.timestamp.getTime()-k.timestamp.getTime()),[i]);T.useEffect(()=>{P.current&&(P.current.scrollTop=P.current.scrollHeight)},[p]);const w=async m=>{m.preventDefault();const k=f.trim();k&&(y?(await d(k,y),b(null),I(null)):await a(k),g(""))},v=m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),w(m))},S=()=>{b(null),I(null),u()};return c.jsxs("div",{className:"chat-sdk",style:{height:t},children:[c.jsxs("div",{className:"chat-sdk__header",children:[c.jsx("div",{className:"chat-sdk__title",children:n}),s&&c.jsx("button",{type:"button",onClick:s,className:"chat-sdk__close-btn",children:c.jsx(Ft,{})})]}),c.jsx("div",{className:"chat-sdk__messages",ref:P,children:p.length===0?c.jsx("div",{className:"chat-sdk__empty",children:"Welcome! Ask anything about the translation."}):p.map(m=>c.jsx(Mt,{message:m},m.id))}),c.jsxs("div",{className:"chat-sdk__composer",children:[c.jsxs("form",{className:"chat-sdk__input-bar",onSubmit:w,children:[x&&c.jsx("div",{className:"chat-sdk__input-context",children:c.jsxs("div",{className:"chat-sdk__context-chip",children:[c.jsx("span",{className:"chat-sdk__context-text",children:x.length>40?`${x.slice(0,40)}…`:x}),c.jsx("button",{type:"button",onClick:S,className:"chat-sdk__context-clear",children:c.jsx($t,{})})]})}),c.jsx("textarea",{ref:q,className:"chat-sdk__input",placeholder:x?"What would you like to change?":e,value:f,onChange:m=>g(m.target.value),onKeyDown:v,disabled:h,rows:1}),c.jsxs("div",{className:"chat-sdk__actions",children:[c.jsx("div",{className:"chat-sdk__actions-left",children:c.jsx("button",{type:"button",className:"chat-sdk__add-btn",disabled:h,children:c.jsx(zt,{})})}),c.jsx("button",{className:"chat-sdk__send",type:"submit",disabled:!f.trim()||h,children:c.jsx(Kt,{})})]})]}),o.error&&c.jsxs("div",{className:"chat-sdk__error",children:["⚠️ ",o.error]})]})]})});Be.displayName="ChatWidget";function Mt({message:n}){var i;const e=n.type==="user",t=n.type==="loading",s=n.type==="ai-patch",r=n.type==="rule-learned";if(e)return c.jsxs("div",{className:"chat-sdk__user-container",children:[n.contextText&&c.jsx("div",{className:"chat-sdk__user-context",children:c.jsx("div",{className:"chat-sdk__context-chip",children:c.jsx("span",{className:"chat-sdk__context-text",children:n.contextText.length>40?`${n.contextText.slice(0,40)}…`:n.contextText})})}),c.jsx("div",{className:"chat-sdk__bubble user",children:c.jsx("div",{className:"chat-sdk__bubble-body",children:n.content})}),c.jsxs("div",{className:"chat-sdk__bubble-meta",children:[n.pageNum!==void 0&&c.jsxs("span",{children:["Page ",n.pageNum]}),n.pageNum!==void 0&&c.jsx("span",{className:"chat-sdk__meta-dot",children:"•"}),c.jsx("span",{children:De(n.timestamp)})]})]});if(r){const o=n.ruleSummary||n.content,a=o.charAt(0).toUpperCase()+o.slice(1);return c.jsxs("div",{className:"chat-sdk__rule-learned-container",children:[c.jsxs("div",{className:"chat-sdk__rule-learned",children:[c.jsx("div",{className:"chat-sdk__rule-learned-icon",children:c.jsx(Ht,{})}),c.jsxs("div",{className:"chat-sdk__rule-learned-body",children:[c.jsx("span",{className:"chat-sdk__rule-learned-title",children:"Memory updated"}),c.jsx("span",{className:"chat-sdk__rule-learned-text",children:a})]})]}),c.jsx("div",{className:"chat-sdk__rule-learned-meta",children:De(n.timestamp)})]})}return c.jsx("div",{className:`chat-sdk__bubble ${s?"ai-patch":"ai"}`,children:c.jsxs("div",{className:`chat-sdk__bubble-body ${n.isStreaming?"streaming":""}`,children:[s&&c.jsx("div",{className:"chat-sdk__suggestion-text",children:c.jsx(Vt,{instructionId:n.instructionId})}),s&&((i=n.patchData)!=null&&i.originalText)?c.jsxs("div",{className:"chat-sdk__patch",children:[c.jsx("div",{className:"chat-sdk__patch-label",children:"Original"}),c.jsx("div",{className:"chat-sdk__patch-block",children:n.patchData.originalText}),c.jsx("div",{className:"chat-sdk__patch-label",children:"Improved"}),c.jsxs("div",{className:"chat-sdk__patch-block",children:[n.patchData.improvedText,n.isStreaming&&c.jsx(fe,{})]})]}):c.jsxs(c.Fragment,{children:[c.jsx("div",{children:n.content}),t&&c.jsx(fe,{}),n.isStreaming&&!t&&c.jsx(fe,{})]})]})})}function Ft(){return c.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("path",{d:"m15 9-6 6"}),c.jsx("path",{d:"m9 9 6 6"})]})}function Ht(){return c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),c.jsx("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"}),c.jsx("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),c.jsx("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),c.jsx("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),c.jsx("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),c.jsx("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),c.jsx("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),c.jsx("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]})}function De(n){const e=new Date,t=new Date(e.getFullYear(),e.getMonth(),e.getDate()),s=new Date(t.getTime()-24*60*60*1e3),r=new Date(n.getFullYear(),n.getMonth(),n.getDate()),i=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1});if(r.getTime()===t.getTime())return i;if(r.getTime()===s.getTime())return`Yesterday, ${i}`;{const o=n.getDate(),d=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][n.getMonth()];return`${o} ${d}, ${i}`}}const G=["I have a suggestion for you","Here is something you might like","How about this?"];function Vt({instructionId:n}){const e=T.useMemo(()=>{if(n){let t=0;for(let s=0;s<n.length;s++)t=(t*31+n.charCodeAt(s))%G.length;return Math.abs(t)%G.length}return Math.floor(Math.random()*G.length)},[n]);return c.jsx(c.Fragment,{children:G[e]})}function Kt(){return c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"5"}),c.jsx("polyline",{points:"5 12 12 5 19 12"})]})}function zt(){return c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),c.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function $t(){return c.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function fe(){return c.jsxs("span",{className:"chat-sdk__stream",children:[c.jsx("span",{}),c.jsx("span",{}),c.jsx("span",{})]})}const Wt=".chat-sdk{--radius-full: 9999px;--radius-large: 20px;--radius-medium: 12px;--spacing-1: 8px;--spacing-2: 16px;--space-20: 20px;--background-primary: #ffffff;--background-secondary: #f5f5f5;--background-tertiary: #f0f0f0;--surface-secondary: #ffffff;--content-primary: #141414;--content-secondary: #666666;--content-tertiary: #999999;--border-secondary: #e6e6e6;--background-brand1-primary: #e8effc;--content-brand1-secondary: #212191;--background-black: #141414;display:flex;flex-direction:column;background:var(--background-primary);border:1px solid var(--border-secondary);border-radius:var(--radius-large);box-shadow:0 8px 30px #0000000f;font-family:Matter,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;overflow:hidden}.chat-sdk__header{padding:14px 20px;display:flex;align-items:center;justify-content:space-between;background:var(--surface-secondary);border-bottom:1px solid var(--border-secondary)}.chat-sdk__title{font-weight:600;font-size:16px;color:var(--content-primary)}.chat-sdk__close-btn{display:flex;align-items:center;justify-content:center;width:20px;height:20px;padding:0;background:transparent;border:none;color:#131313;cursor:pointer;transition:opacity .15s}.chat-sdk__close-btn:hover{opacity:.7}.chat-sdk__messages{flex:1;padding:var(--space-20) 24px;display:flex;flex-direction:column;gap:24px;overflow-y:auto}.chat-sdk__empty{text-align:center;color:var(--content-secondary);font-size:14px;padding:16px}.chat-sdk__user-container{display:flex;flex-direction:column;align-items:flex-end;gap:8px}.chat-sdk__user-context{display:flex;justify-content:flex-end}.chat-sdk__context-chip{background:var(--background-tertiary);padding:8px 12px;border-radius:var(--radius-full);display:inline-flex;align-items:center;gap:8px;max-width:100%}.chat-sdk__context-text{font-size:14px;line-height:1.45;color:var(--content-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:280px}.chat-sdk__bubble.user{background:var(--background-brand1-primary);padding:10px;border-radius:var(--radius-medium);max-width:85%;border:none;color:var(--content-brand1-secondary)}.chat-sdk__bubble-meta{display:flex;align-items:center;justify-content:flex-end;gap:5px;font-size:12px;color:var(--content-tertiary);margin-top:4px}.chat-sdk__meta-dot{font-size:6px}.chat-sdk__bubble.user .chat-sdk__bubble-body{color:var(--content-brand1-secondary);font-size:15px;line-height:1.45;white-space:pre-wrap}.chat-sdk__bubble.ai,.chat-sdk__bubble.ai-patch{align-self:flex-start;max-width:90%;display:flex;flex-direction:column}.chat-sdk__bubble-body{display:flex;flex-direction:column;gap:8px;font-size:15px;color:var(--content-primary);line-height:1.5}.chat-sdk__suggestion-text{font-size:13px;color:var(--content-secondary);margin-bottom:0}.chat-sdk__patch{display:flex;flex-direction:column;gap:8px;margin-top:4px}.chat-sdk__patch-label{font-size:12px;color:var(--content-tertiary);font-weight:600}.chat-sdk__patch-block{background:#f3f4f6;border-radius:10px;padding:12px;border:1px solid #e5e7eb;font-size:14px;line-height:1.5;color:var(--content-secondary)}.chat-sdk__composer{padding:var(--spacing-1);background:var(--background-primary)}.chat-sdk__input-bar{display:flex;flex-direction:column;background:#fff;border:1px solid var(--border-secondary);border-radius:var(--radius-large);padding:8px;overflow:hidden}.chat-sdk__input-context{padding:0 4px 8px}.chat-sdk__input-context .chat-sdk__context-chip{background:var(--background-tertiary);padding:8px 12px;border-radius:var(--radius-full);display:inline-flex;align-items:center;gap:8px}.chat-sdk__input-context .chat-sdk__context-text{font-size:14px;line-height:1.45;color:var(--content-primary)}.chat-sdk__context-clear{display:flex;align-items:center;justify-content:center;width:16px;height:16px;padding:0;background:transparent;border:none;color:var(--content-secondary);cursor:pointer;transition:color .15s}.chat-sdk__context-clear:hover{color:var(--content-primary)}.chat-sdk__input{width:100%;border:none;background:transparent;resize:none;min-height:72px;max-height:120px;font-size:15px;font-family:inherit;color:var(--content-primary);outline:none;line-height:1.45;padding:4px 8px}.chat-sdk__input::placeholder{color:var(--content-tertiary)}.chat-sdk__actions{display:flex;align-items:center;justify-content:space-between}.chat-sdk__actions-left{display:flex;align-items:center}.chat-sdk__add-btn{display:flex;align-items:center;justify-content:center;width:28px;height:28px;padding:0;background:transparent;border:none;border-radius:50%;color:var(--content-secondary);cursor:pointer;transition:background .15s,color .15s}.chat-sdk__add-btn:hover:not(:disabled){background:var(--background-tertiary);color:var(--content-primary)}.chat-sdk__add-btn:disabled{opacity:.4;cursor:not-allowed}.chat-sdk__send{display:flex;align-items:center;justify-content:center;width:28px;height:28px;min-width:28px;min-height:28px;background:var(--background-black);color:#fff;border:none;border-radius:50%;cursor:pointer;transition:opacity .2s}.chat-sdk__send:disabled{opacity:.3;cursor:not-allowed}.chat-sdk__send:not(:disabled):hover{opacity:.8}.chat-sdk__error{font-size:12px;color:#dc2626;padding:4px 8px}.chat-sdk__stream{display:inline-flex;gap:4px;vertical-align:middle}.chat-sdk__stream span{width:4px;height:4px;background:currentColor;border-radius:50%;animation:chat-sdk-pulse 1.4s infinite ease-in-out both}.chat-sdk__stream span:nth-child(1){animation-delay:-.32s}.chat-sdk__stream span:nth-child(2){animation-delay:-.16s}@keyframes chat-sdk-pulse{0%,80%,to{transform:scale(0)}40%{transform:scale(1)}}.chat-sdk__rule-learned-container{display:flex;flex-direction:column;width:100%;animation:chat-sdk-rule-fade-in .5s ease-out}@keyframes chat-sdk-rule-fade-in{0%{opacity:0;transform:translateY(8px) scale(.97)}to{opacity:1;transform:translateY(0) scale(1)}}.chat-sdk__rule-learned{display:flex;align-items:flex-start;gap:6px;padding:8px 12px;background:#9370db2e;border:1px solid rgba(147,112,219,.5);border-radius:var(--radius-medium);width:100%}.chat-sdk__rule-learned-meta{font-size:12px;color:var(--content-tertiary);margin-top:4px;text-align:right}.chat-sdk__rule-learned-icon{flex-shrink:0;color:#9370db;display:flex;align-items:center;height:18px}.chat-sdk__rule-learned-body{display:flex;flex-direction:column;gap:2px;flex:1;min-width:0}.chat-sdk__rule-learned-title{font-size:13px;font-weight:600;color:#7b5cb8;white-space:nowrap;line-height:18px}.chat-sdk__rule-learned-text{font-size:13px;color:var(--content-primary);line-height:1.4;word-wrap:break-word}";R.ChatProvider=qt,R.ChatWidget=Be,R.style=Wt,R.useChat=Le,Object.defineProperty(R,Symbol.toStringTag,{value:"Module"})});
1
+ (function(R,c){typeof exports=="object"&&typeof module<"u"?c(exports,require("react/jsx-runtime"),require("react")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react"],c):(R=typeof globalThis<"u"?globalThis:R||self,c(R.TranslationChatSDK={},R.React,R.React))})(this,function(R,c,T){"use strict";const L=Object.create(null);L.open="0",L.close="1",L.ping="2",L.pong="3",L.message="4",L.upgrade="5",L.noop="6";const K=Object.create(null);Object.keys(L).forEach(n=>{K[L[n]]=n});const Z={type:"error",data:"parser error"},pe=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",ge=typeof ArrayBuffer=="function",_e=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,ee=({type:n,data:e},t,s)=>pe&&e instanceof Blob?t?s(e):me(e,s):ge&&(e instanceof ArrayBuffer||_e(e))?t?s(e):me(new Blob([e]),s):s(L[n]+(e||"")),me=(n,e)=>{const t=new FileReader;return t.onload=function(){const s=t.result.split(",")[1];e("b"+(s||""))},t.readAsDataURL(n)};function ye(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let te;function qe(n,e){if(pe&&n.data instanceof Blob)return n.data.arrayBuffer().then(ye).then(e);if(ge&&(n.data instanceof ArrayBuffer||_e(n.data)))return e(ye(n.data));ee(n,!1,t=>{te||(te=new TextEncoder),e(te.encode(t))})}const ke="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",H=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n<ke.length;n++)H[ke.charCodeAt(n)]=n;const Ue=n=>{let e=n.length*.75,t=n.length,s,r=0,i,o,a,d;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);const l=new ArrayBuffer(e),u=new Uint8Array(l);for(s=0;s<t;s+=4)i=H[n.charCodeAt(s)],o=H[n.charCodeAt(s+1)],a=H[n.charCodeAt(s+2)],d=H[n.charCodeAt(s+3)],u[r++]=i<<2|o>>4,u[r++]=(o&15)<<4|a>>2,u[r++]=(a&3)<<6|d&63;return l},Me=typeof ArrayBuffer=="function",se=(n,e)=>{if(typeof n!="string")return{type:"message",data:be(n,e)};const t=n.charAt(0);return t==="b"?{type:"message",data:Fe(n.substring(1),e)}:K[t]?n.length>1?{type:K[t],data:n.substring(1)}:{type:K[t]}:Z},Fe=(n,e)=>{if(Me){const t=Ue(n);return be(t,e)}else return{base64:!0,data:n}},be=(n,e)=>{switch(e){case"blob":return n instanceof Blob?n:new Blob([n]);case"arraybuffer":default:return n instanceof ArrayBuffer?n:n.buffer}},we="",He=(n,e)=>{const t=n.length,s=new Array(t);let r=0;n.forEach((i,o)=>{ee(i,!1,a=>{s[o]=a,++r===t&&e(s.join(we))})})},Ve=(n,e)=>{const t=n.split(we),s=[];for(let r=0;r<t.length;r++){const i=se(t[r],e);if(s.push(i),i.type==="error")break}return s};function Ke(){return new TransformStream({transform(n,e){qe(n,t=>{const s=t.length;let r;if(s<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,s);else if(s<65536){r=new Uint8Array(3);const i=new DataView(r.buffer);i.setUint8(0,126),i.setUint16(1,s)}else{r=new Uint8Array(9);const i=new DataView(r.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(s))}n.data&&typeof n.data!="string"&&(r[0]|=128),e.enqueue(r),e.enqueue(t)})}})}let ne;function z(n){return n.reduce((e,t)=>e+t.length,0)}function $(n,e){if(n[0].length===e)return n.shift();const t=new Uint8Array(e);let s=0;for(let r=0;r<e;r++)t[r]=n[0][s++],s===n[0].length&&(n.shift(),s=0);return n.length&&s<n[0].length&&(n[0]=n[0].slice(s)),t}function ze(n,e){ne||(ne=new TextDecoder);const t=[];let s=0,r=-1,i=!1;return new TransformStream({transform(o,a){for(t.push(o);;){if(s===0){if(z(t)<1)break;const d=$(t,1);i=(d[0]&128)===128,r=d[0]&127,r<126?s=3:r===126?s=1:s=2}else if(s===1){if(z(t)<2)break;const d=$(t,2);r=new DataView(d.buffer,d.byteOffset,d.length).getUint16(0),s=3}else if(s===2){if(z(t)<8)break;const d=$(t,8),l=new DataView(d.buffer,d.byteOffset,d.length),u=l.getUint32(0);if(u>Math.pow(2,21)-1){a.enqueue(Z);break}r=u*Math.pow(2,32)+l.getUint32(4),s=3}else{if(z(t)<r)break;const d=$(t,r);a.enqueue(se(i?d:ne.decode(d),e)),s=0}if(r===0||r>n){a.enqueue(Z);break}}}})}const ve=4;function E(n){if(n)return $e(n)}function $e(n){for(var e in E.prototype)n[e]=E.prototype[e];return n}E.prototype.on=E.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this},E.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this},E.prototype.off=E.prototype.removeListener=E.prototype.removeAllListeners=E.prototype.removeEventListener=function(n,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+n];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;for(var s,r=0;r<t.length;r++)if(s=t[r],s===e||s.fn===e){t.splice(r,1);break}return t.length===0&&delete this._callbacks["$"+n],this},E.prototype.emit=function(n){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+n],s=1;s<arguments.length;s++)e[s-1]=arguments[s];if(t){t=t.slice(0);for(var s=0,r=t.length;s<r;++s)t[s].apply(this,e)}return this},E.prototype.emitReserved=E.prototype.emit,E.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]},E.prototype.hasListeners=function(n){return!!this.listeners(n).length};const W=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),A=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),We="arraybuffer";function Wt(){}function xe(n,...e){return e.reduce((t,s)=>(n.hasOwnProperty(s)&&(t[s]=n[s]),t),{})}const Qe=A.setTimeout,Ye=A.clearTimeout;function Q(n,e){e.useNativeTimers?(n.setTimeoutFn=Qe.bind(A),n.clearTimeoutFn=Ye.bind(A)):(n.setTimeoutFn=A.setTimeout.bind(A),n.clearTimeoutFn=A.clearTimeout.bind(A))}const Je=1.33;function je(n){return typeof n=="string"?Xe(n):Math.ceil((n.byteLength||n.size)*Je)}function Xe(n){let e=0,t=0;for(let s=0,r=n.length;s<r;s++)e=n.charCodeAt(s),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(s++,t+=4);return t}function Ee(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Ge(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function Ze(n){let e={},t=n.split("&");for(let s=0,r=t.length;s<r;s++){let i=t[s].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}class et extends Error{constructor(e,t,s){super(e),this.description=t,this.context=s,this.type="TransportError"}}class re extends E{constructor(e){super(),this.writable=!1,Q(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,s){return super.emitReserved("error",new et(e,t,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=se(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 e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const t=Ge(e);return t.length?"?"+t:""}}class tt extends re{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 s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||t()})),this.writable||(s++,this.once("drain",function(){--s||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const t=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};Ve(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,He(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=Ee()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let Te=!1;try{Te=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const st=Te;function nt(){}class rt extends tt{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let s=location.port;s||(s=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||s!==e.port}}doWrite(e,t){const s=this.request({method:"POST",data:e});s.on("success",t),s.on("error",(r,i)=>{this.onError("xhr post error",r,i)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,s)=>{this.onError("xhr poll error",t,s)}),this.pollXhr=e}}class B extends E{constructor(e,t,s){super(),this.createRequest=e,Q(this,s),this._opts=s,this._method=s.method||"GET",this._uri=t,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var e;const t=xe(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(t);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&s.setRequestHeader(r,this._opts.extraHeaders[r])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var r;s.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=B.requestsCount++,B.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=nt,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete B.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(B.requestsCount=0,B.requests={},typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Se);else if(typeof addEventListener=="function"){const n="onpagehide"in A?"pagehide":"unload";addEventListener(n,Se,!1)}}function Se(){for(let n in B.requests)B.requests.hasOwnProperty(n)&&B.requests[n].abort()}const it=function(){const n=Ce({xdomain:!1});return n&&n.responseType!==null}();class ot extends rt{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=it&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new B(Ce,this.uri(),e)}}function Ce(n){const e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||st))return new XMLHttpRequest}catch{}if(!e)try{return new A[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Ne=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class ct extends re{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=Ne?{}:xe(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,s)}catch(r){return this.emitReserved("error",r)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],r=t===e.length-1;ee(s,this.supportsBinary,i=>{try{this.doWrite(s,i)}catch{}r&&W(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=Ee()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const ie=A.WebSocket||A.MozWebSocket;class at extends ct{createSocket(e,t,s){return Ne?new ie(e,t,s):t?new ie(e,t):new ie(e)}doWrite(e,t){this.ws.send(t)}}class ht extends re{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=ze(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),r=Ke();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();const i=()=>{s.read().then(({done:a,value:d})=>{a||(this.onPacket(d),i())}).catch(a=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],r=t===e.length-1;this._writer.write(s).then(()=>{r&&W(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const lt={websocket:at,webtransport:ht,polling:ot},dt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ut=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function oe(n){if(n.length>8e3)throw"URI too long";const e=n,t=n.indexOf("["),s=n.indexOf("]");t!=-1&&s!=-1&&(n=n.substring(0,t)+n.substring(t,s).replace(/:/g,";")+n.substring(s,n.length));let r=dt.exec(n||""),i={},o=14;for(;o--;)i[ut[o]]=r[o]||"";return t!=-1&&s!=-1&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=ft(i,i.path),i.queryKey=pt(i,i.query),i}function ft(n,e){const t=/\/{2,9}/g,s=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&s.splice(0,1),e.slice(-1)=="/"&&s.splice(s.length-1,1),s}function pt(n,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,r,i){r&&(t[r]=i)}),t}const ce=typeof addEventListener=="function"&&typeof removeEventListener=="function",Y=[];ce&&addEventListener("offline",()=>{Y.forEach(n=>n())},!1);class D extends E{constructor(e,t){if(super(),this.binaryType=We,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){const s=oe(e);t.hostname=s.host,t.secure=s.protocol==="https"||s.protocol==="wss",t.port=s.port,s.query&&(t.query=s.query)}else t.host&&(t.hostname=oe(t.host).host);Q(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(s=>{const r=s.prototype.name;this.transports.push(r),this._transportsByName[r]=s}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Ze(this.opts.query)),ce&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Y.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=ve,t.transport=e,this.id&&(t.sid=this.id);const s=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](s)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&D.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",D.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let s=0;s<this.writeBuffer.length;s++){const r=this.writeBuffer[s].data;if(r&&(t+=je(r)),s>0&&t>this._maxPayload)return this.writeBuffer.slice(0,s);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,W(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,s){return this._sendPacket("message",e,t,s),this}send(e,t,s){return this._sendPacket("message",e,t,s),this}_sendPacket(e,t,s,r){if(typeof t=="function"&&(r=t,t=void 0),typeof s=="function"&&(r=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const i={type:e,data:t,options:s};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},s=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():e()}):this.upgrading?s():e()),this}_onError(e){if(D.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),ce&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=Y.indexOf(this._offlineEventListener);s!==-1&&Y.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}D.protocol=ve;class gt extends D{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),s=!1;D.priorWebsocketSuccess=!1;const r=()=>{s||(t.send([{type:"ping",data:"probe"}]),t.once("packet",f=>{if(!s)if(f.type==="pong"&&f.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;D.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(u(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=t.name,this.emitReserved("upgradeError",g)}}))};function i(){s||(s=!0,u(),t.close(),t=null)}const o=f=>{const g=new Error("probe error: "+f);g.transport=t.name,i(),this.emitReserved("upgradeError",g)};function a(){o("transport closed")}function d(){o("socket closed")}function l(f){t&&f.name!==t.name&&i()}const u=()=>{t.removeListener("open",r),t.removeListener("error",o),t.removeListener("close",a),this.off("close",d),this.off("upgrading",l)};t.once("open",r),t.once("error",o),t.once("close",a),this.once("close",d),this.once("upgrading",l),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{s||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let s=0;s<e.length;s++)~this.transports.indexOf(e[s])&&t.push(e[s]);return t}}let _t=class extends gt{constructor(e,t={}){const s=typeof e=="object"?e:t;(!s.transports||s.transports&&typeof s.transports[0]=="string")&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(r=>lt[r]).filter(r=>!!r)),super(e,s)}};function mt(n,e="",t){let s=n;t=t||typeof location<"u"&&location,n==null&&(n=t.protocol+"//"+t.host),typeof n=="string"&&(n.charAt(0)==="/"&&(n.charAt(1)==="/"?n=t.protocol+n:n=t.host+n),/^(https?|wss?):\/\//.test(n)||(typeof t<"u"?n=t.protocol+"//"+n:n="https://"+n),s=oe(n)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const i=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+i+":"+s.port+e,s.href=s.protocol+"://"+i+(t&&t.port===s.port?"":":"+s.port),s}const yt=typeof ArrayBuffer=="function",kt=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,Ae=Object.prototype.toString,bt=typeof Blob=="function"||typeof Blob<"u"&&Ae.call(Blob)==="[object BlobConstructor]",wt=typeof File=="function"||typeof File<"u"&&Ae.call(File)==="[object FileConstructor]";function ae(n){return yt&&(n instanceof ArrayBuffer||kt(n))||bt&&n instanceof Blob||wt&&n instanceof File}function J(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,s=n.length;t<s;t++)if(J(n[t]))return!0;return!1}if(ae(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return J(n.toJSON(),!0);for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&J(n[t]))return!0;return!1}function vt(n){const e=[],t=n.data,s=n;return s.data=he(t,e),s.attachments=e.length,{packet:s,buffers:e}}function he(n,e){if(!n)return n;if(ae(n)){const t={_placeholder:!0,num:e.length};return e.push(n),t}else if(Array.isArray(n)){const t=new Array(n.length);for(let s=0;s<n.length;s++)t[s]=he(n[s],e);return t}else if(typeof n=="object"&&!(n instanceof Date)){const t={};for(const s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=he(n[s],e));return t}return n}function xt(n,e){return n.data=le(n.data,e),delete n.attachments,n}function le(n,e){if(!n)return n;if(n&&n._placeholder===!0){if(typeof n.num=="number"&&n.num>=0&&n.num<e.length)return e[n.num];throw new Error("illegal attachments")}else if(Array.isArray(n))for(let t=0;t<n.length;t++)n[t]=le(n[t],e);else if(typeof n=="object")for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=le(n[t],e));return n}const Re=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],Et=5;var _;(function(n){n[n.CONNECT=0]="CONNECT",n[n.DISCONNECT=1]="DISCONNECT",n[n.EVENT=2]="EVENT",n[n.ACK=3]="ACK",n[n.CONNECT_ERROR=4]="CONNECT_ERROR",n[n.BINARY_EVENT=5]="BINARY_EVENT",n[n.BINARY_ACK=6]="BINARY_ACK"})(_||(_={}));class Tt{constructor(e){this.replacer=e}encode(e){return(e.type===_.EVENT||e.type===_.ACK)&&J(e)?this.encodeAsBinary({type:e.type===_.EVENT?_.BINARY_EVENT:_.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===_.BINARY_EVENT||e.type===_.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=vt(e),s=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(s),r}}class de extends E{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const s=t.type===_.BINARY_EVENT;s||t.type===_.BINARY_ACK?(t.type=s?_.EVENT:_.ACK,this.reconstructor=new St(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(ae(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0;const s={type:Number(e.charAt(0))};if(_[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===_.BINARY_EVENT||s.type===_.BINARY_ACK){const i=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const o=e.substring(i,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");s.attachments=Number(o)}if(e.charAt(t+1)==="/"){const i=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););s.nsp=e.substring(i,t)}else s.nsp="/";const r=e.charAt(t+1);if(r!==""&&Number(r)==r){const i=t+1;for(;++t;){const o=e.charAt(t);if(o==null||Number(o)!=o){--t;break}if(t===e.length)break}s.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(de.isPayloadValid(s.type,i))s.data=i;else throw new Error("invalid payload")}return s}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case _.CONNECT:return j(t);case _.DISCONNECT:return t===void 0;case _.CONNECT_ERROR:return typeof t=="string"||j(t);case _.EVENT:case _.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Re.indexOf(t[0])===-1);case _.ACK:case _.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class St{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const t=xt(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function Ct(n){return typeof n=="string"}const Nt=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n};function At(n){return n===void 0||Nt(n)}function j(n){return Object.prototype.toString.call(n)==="[object Object]"}function Rt(n,e){switch(n){case _.CONNECT:return e===void 0||j(e);case _.DISCONNECT:return e===void 0;case _.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Re.indexOf(e[0])===-1);case _.ACK:return Array.isArray(e);case _.CONNECT_ERROR:return typeof e=="string"||j(e);default:return!1}}function Ot(n){return Ct(n.nsp)&&At(n.id)&&Rt(n.type,n.data)}const Pt=Object.freeze(Object.defineProperty({__proto__:null,Decoder:de,Encoder:Tt,get PacketType(){return _},isPacketValid:Ot,protocol:Et},Symbol.toStringTag,{value:"Module"}));function O(n,e,t){return n.on(e,t),function(){n.off(e,t)}}const Lt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Oe extends E{constructor(e,t,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[O(e,"open",this.onopen.bind(this)),O(e,"packet",this.onpacket.bind(this)),O(e,"error",this.onerror.bind(this)),O(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var s,r,i;if(Lt.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 o={type:_.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const u=this.ids++,f=t.pop();this._registerAckCallback(u,f),o.id=u}const a=(r=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||r===void 0?void 0:r.writable,d=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!a||(d?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var s;const r=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(r===void 0){this.acks[e]=t;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let a=0;a<this.sendBuffer.length;a++)this.sendBuffer[a].id===e&&this.sendBuffer.splice(a,1);t.call(this,new Error("operation has timed out"))},r),o=(...a)=>{this.io.clearTimeoutFn(i),t.apply(this,a)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((s,r)=>{const i=(o,a)=>o?r(o):s(a);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((r,...i)=>(this._queue[0],r!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(r)):(this._queue.shift(),t&&t(null,...i)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:_.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(s=>String(s.id)===e)){const s=this.acks[e];delete this.acks[e],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case _.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 _.EVENT:case _.BINARY_EVENT:this.onevent(e);break;case _.ACK:case _.BINARY_ACK:this.onack(e);break;case _.DISCONNECT:this.ondisconnect();break;case _.CONNECT_ERROR:this.destroy();const s=new Error(e.data.message);s.data=e.data.data,this.emitReserved("connect_error",s);break}}onevent(e){const t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const s of t)s.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let s=!1;return function(...r){s||(s=!0,t.packet({type:_.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._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:_.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let s=0;s<t.length;s++)if(e===t[s])return t.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let s=0;s<t.length;s++)if(e===t[s])return t.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const s of t)s.apply(this,e.data)}}}function F(n){n=n||{},this.ms=n.min||100,this.max=n.max||1e4,this.factor=n.factor||2,this.jitter=n.jitter>0&&n.jitter<=1?n.jitter:0,this.attempts=0}F.prototype.duration=function(){var n=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*n);n=Math.floor(e*10)&1?n+t:n-t}return Math.min(n,this.max)|0},F.prototype.reset=function(){this.attempts=0},F.prototype.setMin=function(n){this.ms=n},F.prototype.setMax=function(n){this.max=n},F.prototype.setJitter=function(n){this.jitter=n};class ue extends E{constructor(e,t){var s;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,Q(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((s=t.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new F({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||Pt;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new _t(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=O(t,"open",function(){s.onopen(),e&&e()}),i=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=O(t,"error",i);if(this._timeout!==!1){const a=this._timeout,d=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),t.close()},a);this.opts.autoUnref&&d.unref(),this.subs.push(()=>{this.clearTimeoutFn(d)})}return this.subs.push(r),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(O(e,"ping",this.onping.bind(this)),O(e,"data",this.ondata.bind(this)),O(e,"error",this.onerror.bind(this)),O(e,"close",this.onclose.bind(this)),O(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){W(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let s=this.nsps[e];return s?this._autoConnect&&!s.active&&s.connect():(s=new Oe(this,e,t),this.nsps[e]=s),s}_destroy(e){const t=Object.keys(this.nsps);for(const s of t)if(this.nsps[s].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let s=0;s<t.length;s++)this.engine.write(t[s],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var s;this.cleanup(),(s=this.engine)===null||s===void 0||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(r=>{r?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",r)):e.onreconnect()}))},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const V={};function X(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};const t=mt(n,e.path||"/socket.io"),s=t.source,r=t.id,i=t.path,o=V[r]&&i in V[r].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let d;return a?d=new ue(s,e):(V[r]||(V[r]=new ue(s,e)),d=V[r]),t.query&&!e.query&&(e.query=t.queryKey),d.socket(t.path,e)}Object.assign(X,{Manager:ue,Socket:Oe,io:X,connect:X});function N(){return`${Date.now().toString(36)}-${Math.random().toString(16).slice(2,8)}`}class Bt{constructor(e){this.socket=null,this.reconnectAttempts=0,this.listeners=new Map,this.lastContext=null,this.config={reconnectAttempts:5,reconnectDelayMs:1500,logger:console,...e}}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{var s;return(s=this.listeners.get(e))==null?void 0:s.delete(t)}}emit(e,t){var s;(s=this.listeners.get(e))==null||s.forEach(r=>{var i,o;try{r(t)}catch(a){(o=(i=this.config.logger)==null?void 0:i.error)==null||o.call(i,`chat-sdk listener error for ${e}`,a)}})}setConnection(e){var t,s;this.emit("connection",e),(s=(t=this.config).onConnectionChange)==null||s.call(t,e)}async getToken(){var t,s;const{tokenProvider:e}=this.config;if(!e)return null;try{return(typeof e=="function"?await e():e)||null}catch(r){return(s=(t=this.config.logger)==null?void 0:t.warn)==null||s.call(t,"chat-sdk token provider failed",r),null}}async connect(){var i;if((i=this.socket)!=null&&i.connected)return;const e=new URL(this.config.websocketUrl),t=e.pathname==="/"?"/socket.io":e.pathname,s=e.origin,r=await this.getToken();return this.socket=X(s,{path:t,transports:["websocket","polling"],autoConnect:!1,reconnection:!1,auth:r?{token:r}:void 0,withCredentials:!0}),this.registerSocketEvents(),this.setConnection({connected:!1,connecting:!0}),new Promise((o,a)=>{const d=setTimeout(()=>{a(new Error("connection timeout"))},1e4);this.socket.once("connect",()=>{clearTimeout(d),this.reconnectAttempts=0,this.setConnection({connected:!0,connecting:!1}),o()}),this.socket.once("connect_error",l=>{clearTimeout(d),this.setConnection({connected:!1,connecting:!1,error:l.message}),this.handleReconnect(),a(l)}),this.socket.connect()})}disconnect(){var e;(e=this.socket)==null||e.disconnect(),this.socket=null,this.setConnection({connected:!1,connecting:!1})}async submitInstruction(e,t){var i,o;if(!((i=this.socket)!=null&&i.connected))throw new Error("Not connected");this.lastContext=t;const s=await this.getToken(),r={trans_doc_id:t.trans_doc_id,page_num:t.page_num,instruction:e,modification_level:"page",access_token:s||void 0,region_coordinates:t.highlighted_region?{start_offset:t.highlighted_region.start_offset,end_offset:t.highlighted_region.end_offset}:void 0,region_text:(o=t.highlighted_region)==null?void 0:o.text,selection_id:t.selection_id};this.socket.emit("INSTR_SUBMIT",r)}async requestChatHistory(e){var s;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();this.lastContext=e,this.socket.emit("CHAT_HISTORY_REQUEST",{trans_doc_id:e.trans_doc_id,access_token:t||void 0})}async sendPatchDecision(e){var s,r,i,o,a;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();(i=(r=this.config.logger)==null?void 0:r.log)==null||i.call(r,"[chat-sdk] Sending PATCH_DECISION:",{trans_doc_id:e.trans_doc_id,page_num:e.page_num,instruction_id:e.instruction_id,decision:e.decision,remember_this:e.remember_this,has_access_token:!!t}),this.socket.emit("PATCH_DECISION",{...e,access_token:t||void 0}),(a=(o=this.config.logger)==null?void 0:o.log)==null||a.call(o,"[chat-sdk] PATCH_DECISION emitted successfully")}async requestPageTranslation(e){var r,i,o,a,d;if(!((r=this.socket)!=null&&r.connected))throw new Error("Not connected");const t=await this.getToken(),s={...e,access_token:t||void 0};(o=(i=this.config.logger)==null?void 0:i.log)==null||o.call(i,"[chat-sdk] Sending PAGE_TRANSLATION_REQUEST:",{trans_doc_id:e.trans_doc_id,page_num:e.page_num,has_access_token:!!t}),this.socket.emit("PAGE_TRANSLATION_REQUEST",s),(d=(a=this.config.logger)==null?void 0:a.log)==null||d.call(a,"[chat-sdk] PAGE_TRANSLATION_REQUEST emitted successfully")}async requestBulkTranslation(e){var r,i,o,a,d;if(!((r=this.socket)!=null&&r.connected))throw new Error("Not connected");const t=await this.getToken(),s={...e,access_token:t||void 0};(o=(i=this.config.logger)==null?void 0:i.log)==null||o.call(i,"[chat-sdk] Sending BULK_TRANSLATION_REQUEST:",{trans_doc_id:e.trans_doc_id,page_list:e.page_list,has_access_token:!!t}),this.socket.emit("BULK_TRANSLATION_REQUEST",s),(d=(a=this.config.logger)==null?void 0:a.log)==null||d.call(a,"[chat-sdk] BULK_TRANSLATION_REQUEST emitted successfully")}async cancelBulkTranslation(e){var s,r,i,o,a;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();(i=(r=this.config.logger)==null?void 0:r.log)==null||i.call(r,"[chat-sdk] Sending CANCEL_BULK_TRANSLATION_REQUEST:",{trans_doc_id:e,has_access_token:!!t}),this.socket.emit("CANCEL_BULK_TRANSLATION_REQUEST",{trans_doc_id:e,access_token:t||void 0}),(a=(o=this.config.logger)==null?void 0:o.log)==null||a.call(o,"[chat-sdk] CANCEL_BULK_TRANSLATION_REQUEST emitted successfully")}async requestLearnedRules(e){var s,r,i,o,a;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();(i=(r=this.config.logger)==null?void 0:r.log)==null||i.call(r,"[chat-sdk] Sending LEARNED_RULES_REQUEST:",{trans_doc_id:e,has_access_token:!!t}),this.socket.emit("LEARNED_RULES_REQUEST",{trans_doc_id:e,access_token:t||void 0}),(a=(o=this.config.logger)==null?void 0:o.log)==null||a.call(o,"[chat-sdk] LEARNED_RULES_REQUEST emitted successfully")}async updateRules(e,t){var r,i,o,a,d;if(!((r=this.socket)!=null&&r.connected))throw new Error("Not connected");const s=await this.getToken();(o=(i=this.config.logger)==null?void 0:i.log)==null||o.call(i,"[chat-sdk] Sending UPDATE_RULES_REQUEST:",{trans_doc_id:e,rules_text_length:t.length,has_access_token:!!s}),this.socket.emit("UPDATE_RULES_REQUEST",{trans_doc_id:e,rules_text:t,access_token:s||void 0}),(d=(a=this.config.logger)==null?void 0:a.log)==null||d.call(a,"[chat-sdk] UPDATE_RULES_REQUEST emitted successfully")}registerSocketEvents(){this.socket&&(this.socket.on("disconnect",()=>{this.setConnection({connected:!1,connecting:!1}),this.handleReconnect()}),this.socket.on("connect_error",e=>{this.setConnection({connected:!1,connecting:!1,error:e.message}),this.handleReconnect()}),this.socket.on("CHAT_RESPONSE",e=>{this.emit("chat-response",e)}),this.socket.on("PATCH_OFFER",e=>{this.emit("patch-offer",e)}),this.socket.on("CHAT_HISTORY_RESPONSE",e=>{this.emit("chat-history-response",e)}),this.socket.on("INSTRUCTION_ERROR",e=>{this.emit("instruction-error",e)}),this.socket.on("PAGE_TRANSLATION_RESPONSE",e=>{var t,s,r,i,o,a,d,l,u,f,g;(r=(t=this.config.logger)==null?void 0:t.log)==null||r.call(t,"[chat-sdk] Received PAGE_TRANSLATION_RESPONSE from socket:",{trans_doc_id:e.trans_doc_id,page_num:e.page_num,status:e.status,has_content:!!e.trans_page_content,content_length:(s=e.trans_page_content)==null?void 0:s.length,error:e.error,error_type:e.error_type,updated_at:e.updated_at}),this.emit("page-translation-response",e),(o=(i=this.config.logger)==null?void 0:i.log)==null||o.call(i,"[chat-sdk] Emitted page-translation-response internally"),this.config.onPageTranslationResponse?((d=(a=this.config.logger)==null?void 0:a.log)==null||d.call(a,"[chat-sdk] Calling onPageTranslationResponse callback"),this.config.onPageTranslationResponse(e),(u=(l=this.config.logger)==null?void 0:l.log)==null||u.call(l,"[chat-sdk] onPageTranslationResponse callback completed")):(g=(f=this.config.logger)==null?void 0:f.log)==null||g.call(f,"[chat-sdk] No onPageTranslationResponse callback configured")}),this.socket.on("BULK_TRANSLATION_RESPONSE",e=>{var t,s,r,i,o,a,d,l,u,f;(s=(t=this.config.logger)==null?void 0:t.log)==null||s.call(t,"[chat-sdk] Received BULK_TRANSLATION_RESPONSE from socket:",{trans_doc_id:e.trans_doc_id,status:e.status,completed_pages:e.completed_pages,total_pages:e.total_pages,current_page:e.current_page,error:e.error,error_type:e.error_type}),this.emit("bulk-translation-response",e),(i=(r=this.config.logger)==null?void 0:r.log)==null||i.call(r,"[chat-sdk] Emitted bulk-translation-response internally"),this.config.onBulkTranslationResponse?((a=(o=this.config.logger)==null?void 0:o.log)==null||a.call(o,"[chat-sdk] Calling onBulkTranslationResponse callback"),this.config.onBulkTranslationResponse(e),(l=(d=this.config.logger)==null?void 0:d.log)==null||l.call(d,"[chat-sdk] onBulkTranslationResponse callback completed")):(f=(u=this.config.logger)==null?void 0:u.log)==null||f.call(u,"[chat-sdk] No onBulkTranslationResponse callback configured")}),this.socket.on("RULE_LEARNED",e=>{var t,s;(s=(t=this.config.logger)==null?void 0:t.log)==null||s.call(t,"[chat-sdk] Received RULE_LEARNED from socket:",{trans_doc_id:e.trans_doc_id,instruction_id:e.instruction_id,rule_summary:e.rule_summary}),this.emit("rule-learned",e),this.config.onRuleLearned&&this.config.onRuleLearned(e)}),this.socket.on("LEARNED_RULES_RESPONSE",e=>{var t,s;(s=(t=this.config.logger)==null?void 0:t.log)==null||s.call(t,"[chat-sdk] Received LEARNED_RULES_RESPONSE from socket:",{trans_doc_id:e.trans_doc_id,has_rules:e.has_rules,status:e.status,error:e.error}),this.emit("learned-rules-response",e),this.config.onLearnedRulesResponse&&this.config.onLearnedRulesResponse(e)}),this.socket.on("UPDATE_RULES_RESPONSE",e=>{var t,s;(s=(t=this.config.logger)==null?void 0:t.log)==null||s.call(t,"[chat-sdk] Received UPDATE_RULES_RESPONSE from socket:",{trans_doc_id:e.trans_doc_id,status:e.status,error:e.error}),this.emit("update-rules-response",e),this.config.onUpdateRulesResponse&&this.config.onUpdateRulesResponse(e)}),this.socket.on("connected",()=>{this.lastContext&&this.requestChatHistory(this.lastContext).catch(e=>{var t,s;return(s=(t=this.config.logger)==null?void 0:t.warn)==null?void 0:s.call(t,"chat-sdk history on reconnect failed",e)})}))}handleReconnect(){var e,t;if(this.reconnectAttempts>=(this.config.reconnectAttempts??5)){(t=(e=this.config.logger)==null?void 0:e.warn)==null||t.call(e,"chat-sdk max reconnection attempts reached");return}this.reconnectAttempts+=1,setTimeout(()=>{this.connect().catch(s=>{var r,i;return(i=(r=this.config.logger)==null?void 0:r.error)==null?void 0:i.call(r,"chat-sdk reconnect failed",s)})},this.config.reconnectDelayMs)}}function Dt(n){return n.map(e=>{const t={instructionId:e.instruction_id,pageNum:e.page_num??void 0,timestamp:new Date(e.timestamp)};if(e.response_type==="rule_learned")return[{...t,id:N(),type:"rule-learned",content:e.response_content||"Rule learned",ruleSummary:e.rule_summary??void 0}];const s={...t,id:N(),type:"user",content:e.instruction,contextText:e.region_text??void 0},r=[];return e.response_content&&e.response_type==="chat"&&r.push({...t,id:N(),type:"ai-chat",content:e.response_content}),e.response_content&&e.response_type==="patch"&&r.push({...t,id:N(),type:"ai-patch",content:e.response_content,patchData:{originalText:e.region_text??void 0,improvedText:e.response_content,regionText:e.region_text??void 0,isComplete:!0}}),[s,...r]}).flat().sort((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())}const Pe=T.createContext(null),It={connected:!1,connecting:!1};function qt({config:n,children:e}){const t=T.useRef(null),s=T.useRef(new Map),[r,i]=T.useState({messages:[],connection:It,latestPatchOffer:null,isSubmitting:!1}),o=T.useMemo(()=>({reconnectAttempts:5,reconnectDelayMs:1500,...n}),[n]);T.useEffect(()=>{const l=new Bt(o);t.current=l;const u=l.on("connection",h=>{i(p=>({...p,connection:h}))}),f=l.on("chat-response",h=>{i(p=>{const w=p.messages.filter(k=>k.type!=="loading");let v=w.find(k=>k.instructionId===h.instruction_id&&k.type==="ai-chat");v||(v={id:N(),type:"ai-chat",content:"",timestamp:new Date,instructionId:h.instruction_id,pageNum:h.page_num,isStreaming:!0},w.push(v));const S={...v,content:(v.content||"")+(h.chunk_text||""),isStreaming:!h.is_final},m=w.map(k=>k.id===v.id?S:k);return{...p,messages:m,isSubmitting:h.is_final?!1:p.isSubmitting}})}),g=l.on("patch-offer",h=>{var v;const p=`${h.trans_doc_id}-${h.instruction_id}`,w=s.current.get(p)??{trans_doc_id:h.trans_doc_id,page_num:h.page_num,instruction_id:h.instruction_id,original_text:h.region_original_text||"",highlighted_region:h.region_coordinates,new_suggestion:"",is_page_level:!h.region_coordinates,selection_id:h.selection_id};if(w.new_suggestion+=h.region_replacement_text_chunk||"",h.selection_id&&!w.selection_id&&(w.selection_id=h.selection_id),s.current.set(p,w),i(S=>{var Ie;const m=S.messages.filter(M=>M.type!=="loading");let k=m.find(M=>M.instructionId===h.instruction_id&&M.type==="ai-patch");k||(k={id:N(),type:"ai-patch",content:"",timestamp:new Date,instructionId:h.instruction_id,pageNum:h.page_num,isStreaming:!0,patchData:{originalText:h.region_original_text,improvedText:"",regionText:h.region_original_text,isComplete:!1}},m.push(k));const C={...k,content:(k.content||"")+(h.region_replacement_text_chunk||""),isStreaming:!h.is_final,patchData:{...k.patchData,improvedText:(((Ie=k.patchData)==null?void 0:Ie.improvedText)||"")+(h.region_replacement_text_chunk||""),regionText:h.region_original_text,isComplete:h.is_final}},U=m.map(M=>M.id===k.id?C:M);return{...S,messages:U,isSubmitting:h.is_final?!1:S.isSubmitting}}),h.is_final){const S=s.current.get(p);S&&((v=o.onPatchOffer)==null||v.call(o,S),i(m=>({...m,latestPatchOffer:S}))),s.current.delete(p)}}),y=l.on("chat-history-response",h=>{if(h.status==="success"){const p=Dt(h.messages);i(w=>({...w,messages:p}))}else i(p=>({...p,messages:[...p.messages,{id:N(),type:"system",content:h.error||"Failed to load chat history",timestamp:new Date}]}))}),b=l.on("instruction-error",h=>{i(p=>({...p,isSubmitting:!1,messages:[...p.messages,{id:N(),type:"error",content:h.error,timestamp:new Date}]}))}),x=l.on("page-translation-response",h=>{var p,w,v,S,m,k,C,U;(w=(p=o.logger)==null?void 0:p.log)==null||w.call(p,"[chat-sdk][ChatProvider] Received page-translation-response event:",{trans_doc_id:h.trans_doc_id,page_num:h.page_num,status:h.status,has_content:!!h.trans_page_content,error:h.error}),o.onPageTranslationResponse?((S=(v=o.logger)==null?void 0:v.log)==null||S.call(v,"[chat-sdk][ChatProvider] Invoking onPageTranslationResponse callback from config"),o.onPageTranslationResponse(h),(k=(m=o.logger)==null?void 0:m.log)==null||k.call(m,"[chat-sdk][ChatProvider] onPageTranslationResponse callback completed")):(U=(C=o.logger)==null?void 0:C.log)==null||U.call(C,"[chat-sdk][ChatProvider] No onPageTranslationResponse callback in config")}),I=l.on("bulk-translation-response",h=>{var p,w,v,S,m,k,C,U;(w=(p=o.logger)==null?void 0:p.log)==null||w.call(p,"[chat-sdk][ChatProvider] Received bulk-translation-response event:",{trans_doc_id:h.trans_doc_id,status:h.status,completed_pages:h.completed_pages,total_pages:h.total_pages,current_page:h.current_page,error:h.error}),o.onBulkTranslationResponse?((S=(v=o.logger)==null?void 0:v.log)==null||S.call(v,"[chat-sdk][ChatProvider] Invoking onBulkTranslationResponse callback from config"),o.onBulkTranslationResponse(h),(k=(m=o.logger)==null?void 0:m.log)==null||k.call(m,"[chat-sdk][ChatProvider] onBulkTranslationResponse callback completed")):(U=(C=o.logger)==null?void 0:C.log)==null||U.call(C,"[chat-sdk][ChatProvider] No onBulkTranslationResponse callback in config")}),P=l.on("rule-learned",h=>{var p,w;(w=(p=o.logger)==null?void 0:p.log)==null||w.call(p,"[chat-sdk][ChatProvider] Received rule-learned event:",{trans_doc_id:h.trans_doc_id,instruction_id:h.instruction_id,rule_summary:h.rule_summary}),i(v=>({...v,messages:[...v.messages,{id:N(),type:"rule-learned",content:h.message||"Rule learned",timestamp:new Date,instructionId:h.instruction_id,ruleSummary:h.rule_summary}]})),o.onRuleLearned&&o.onRuleLearned(h)}),q=l.on("learned-rules-response",h=>{var p,w;(w=(p=o.logger)==null?void 0:p.log)==null||w.call(p,"[chat-sdk][ChatProvider] Received learned-rules-response event:",{trans_doc_id:h.trans_doc_id,has_rules:h.has_rules,status:h.status}),o.onLearnedRulesResponse&&o.onLearnedRulesResponse(h)});return l.connect().then(()=>{const h=o.contextProvider();if(h)return l.requestChatHistory(h)}).catch(h=>{var p,w;return(w=(p=o.logger)==null?void 0:p.warn)==null?void 0:w.call(p,"chat-sdk connect failed",h)}),()=>{u(),f(),g(),y(),b(),x(),I(),P(),q(),l.disconnect()}},[o]);const a=T.useMemo(()=>({async submitInstruction(l){const u=t.current;if(!u)throw new Error("SDK not ready");const f=o.contextProvider();if(!f)throw new Error("contextProvider returned null");i(g=>{var y;return{...g,isSubmitting:!0,messages:[...g.messages,{id:N(),type:"user",content:l,timestamp:new Date,pageNum:f.page_num,contextText:(y=f.highlighted_region)==null?void 0:y.text},{id:N(),type:"loading",content:"Processing your instruction...",timestamp:new Date,isStreaming:!0}]}}),await u.submitInstruction(l,f)},async submitInstructionWithContext(l,u){const f=t.current;if(!f)throw new Error("SDK not ready");i(g=>{var y;return{...g,isSubmitting:!0,messages:[...g.messages,{id:N(),type:"user",content:l,timestamp:new Date,pageNum:u.page_num,contextText:(y=u.highlighted_region)==null?void 0:y.text},{id:N(),type:"loading",content:"Processing your instruction...",timestamp:new Date,isStreaming:!0}]}}),await f.submitInstruction(l,u)},async requestChatHistory(){const l=t.current;if(!l)throw new Error("SDK not ready");const u=o.contextProvider();if(!u)throw new Error("contextProvider returned null");await l.requestChatHistory(u)},async sendPatchDecision(l,u,f,g,y){var x,I,P,q;const b=t.current;if(!b)throw new Error("SDK not ready");(I=(x=o.logger)==null?void 0:x.log)==null||I.call(x,"[chat-sdk][ChatProvider] sendPatchDecision called:",{trans_doc_id:l,page_num:u,instruction_id:f,decision:g,remember_this:y}),await b.sendPatchDecision({trans_doc_id:l,page_num:u,instruction_id:f,decision:g,remember_this:y}),(q=(P=o.logger)==null?void 0:P.log)==null||q.call(P,"[chat-sdk][ChatProvider] sendPatchDecision completed"),i(h=>({...h,latestPatchOffer:null}))},async requestPageTranslation(l,u){var g,y,b,x;const f=t.current;if(!f)throw new Error("SDK not ready");return(y=(g=o.logger)==null?void 0:g.log)==null||y.call(g,"[chat-sdk][ChatProvider] requestPageTranslation called:",{trans_doc_id:l,page_num:u}),await f.requestPageTranslation({trans_doc_id:l,page_num:u}),(x=(b=o.logger)==null?void 0:b.log)==null||x.call(b,"[chat-sdk][ChatProvider] requestPageTranslation request sent"),!0},async requestBulkTranslation(l,u){var g,y,b,x;const f=t.current;if(!f)throw new Error("SDK not ready");return(y=(g=o.logger)==null?void 0:g.log)==null||y.call(g,"[chat-sdk][ChatProvider] requestBulkTranslation called:",{trans_doc_id:l,page_list:u}),await f.requestBulkTranslation({trans_doc_id:l,page_list:u}),(x=(b=o.logger)==null?void 0:b.log)==null||x.call(b,"[chat-sdk][ChatProvider] requestBulkTranslation request sent"),!0},async cancelBulkTranslation(l){var f,g,y,b;const u=t.current;if(!u)throw new Error("SDK not ready");return(g=(f=o.logger)==null?void 0:f.log)==null||g.call(f,"[chat-sdk][ChatProvider] cancelBulkTranslation called:",{trans_doc_id:l}),await u.cancelBulkTranslation(l),(b=(y=o.logger)==null?void 0:y.log)==null||b.call(y,"[chat-sdk][ChatProvider] cancelBulkTranslation request sent"),!0},async requestLearnedRules(l){var f,g,y,b;const u=t.current;if(!u)throw new Error("SDK not ready");(g=(f=o.logger)==null?void 0:f.log)==null||g.call(f,"[chat-sdk][ChatProvider] requestLearnedRules called:",{trans_doc_id:l}),await u.requestLearnedRules(l),(b=(y=o.logger)==null?void 0:y.log)==null||b.call(y,"[chat-sdk][ChatProvider] requestLearnedRules request sent")},async updateRules(l,u){var g,y,b,x;const f=t.current;if(!f)throw new Error("SDK not ready");(y=(g=o.logger)==null?void 0:g.log)==null||y.call(g,"[chat-sdk][ChatProvider] updateRules called:",{trans_doc_id:l,rules_text_length:u.length}),await f.updateRules(l,u),(x=(b=o.logger)==null?void 0:b.log)==null||x.call(b,"[chat-sdk][ChatProvider] updateRules request sent")},clearMessages(){i(l=>({...l,messages:[]}))},clearSelection(){var l;(l=o.onClearSelection)==null||l.call(o)}}),[o]),d=T.useMemo(()=>({...r,...a}),[r,a]);return c.jsx(Pe.Provider,{value:d,children:e})}function Ut(){const n=T.useContext(Pe);if(!n)throw new Error("useChat must be used within ChatProvider");return n}function Le(){return Ut()}const Be=T.forwardRef(({title:n="AI Assistance",placeholder:e="Ask anything...",height:t="500px",onClose:s},r)=>{const{messages:i,connection:o,submitInstruction:a,submitInstructionWithContext:d,isSubmitting:l,clearSelection:u}=Le(),[f,g]=T.useState(""),[y,b]=T.useState(null),[x,I]=T.useState(null),P=T.useRef(null),q=T.useRef(null),h=!o.connected||l;T.useImperativeHandle(r,()=>({setContext:({text:m,context:k})=>{I(m),b(k),setTimeout(()=>{var C;(C=q.current)==null||C.focus()},100)},focusInput:()=>{var m;(m=q.current)==null||m.focus()}}),[]);const p=T.useMemo(()=>[...i].sort((m,k)=>m.timestamp.getTime()-k.timestamp.getTime()),[i]);T.useEffect(()=>{P.current&&(P.current.scrollTop=P.current.scrollHeight)},[p]);const w=async m=>{m.preventDefault();const k=f.trim();k&&(y?(await d(k,y),b(null),I(null)):await a(k),g(""))},v=m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),w(m))},S=()=>{b(null),I(null),u()};return c.jsxs("div",{className:"chat-sdk",style:{height:t},children:[c.jsxs("div",{className:"chat-sdk__header",children:[c.jsx("div",{className:"chat-sdk__title",children:n}),s&&c.jsx("button",{type:"button",onClick:s,className:"chat-sdk__close-btn",children:c.jsx(Ft,{})})]}),c.jsx("div",{className:"chat-sdk__messages",ref:P,children:p.length===0?c.jsx("div",{className:"chat-sdk__empty",children:"Welcome! Ask anything about the translation."}):p.map(m=>c.jsx(Mt,{message:m},m.id))}),c.jsxs("div",{className:"chat-sdk__composer",children:[c.jsxs("form",{className:"chat-sdk__input-bar",onSubmit:w,children:[x&&c.jsx("div",{className:"chat-sdk__input-context",children:c.jsxs("div",{className:"chat-sdk__context-chip",children:[c.jsx("span",{className:"chat-sdk__context-text",children:x.length>40?`${x.slice(0,40)}…`:x}),c.jsx("button",{type:"button",onClick:S,className:"chat-sdk__context-clear",children:c.jsx(zt,{})})]})}),c.jsx("textarea",{ref:q,className:"chat-sdk__input",placeholder:x?"What would you like to change?":e,value:f,onChange:m=>g(m.target.value),onKeyDown:v,disabled:h,rows:1}),c.jsx("div",{className:"chat-sdk__actions",children:c.jsx("button",{className:"chat-sdk__send",type:"submit",disabled:!f.trim()||h,children:c.jsx(Kt,{})})})]}),o.error&&c.jsxs("div",{className:"chat-sdk__error",children:["⚠️ ",o.error]})]})]})});Be.displayName="ChatWidget";function Mt({message:n}){var i;const e=n.type==="user",t=n.type==="loading",s=n.type==="ai-patch",r=n.type==="rule-learned";if(e)return c.jsxs("div",{className:"chat-sdk__user-container",children:[n.contextText&&c.jsx("div",{className:"chat-sdk__user-context",children:c.jsx("div",{className:"chat-sdk__context-chip",children:c.jsx("span",{className:"chat-sdk__context-text",children:n.contextText.length>40?`${n.contextText.slice(0,40)}…`:n.contextText})})}),c.jsx("div",{className:"chat-sdk__bubble user",children:c.jsx("div",{className:"chat-sdk__bubble-body",children:n.content})}),c.jsxs("div",{className:"chat-sdk__bubble-meta",children:[n.pageNum!==void 0&&c.jsxs("span",{children:["Page ",n.pageNum]}),n.pageNum!==void 0&&c.jsx("span",{className:"chat-sdk__meta-dot",children:"•"}),c.jsx("span",{children:De(n.timestamp)})]})]});if(r){const o=n.ruleSummary||n.content,a=o.charAt(0).toUpperCase()+o.slice(1);return c.jsxs("div",{className:"chat-sdk__rule-learned-container",children:[c.jsxs("div",{className:"chat-sdk__rule-learned",children:[c.jsx("div",{className:"chat-sdk__rule-learned-icon",children:c.jsx(Ht,{})}),c.jsxs("div",{className:"chat-sdk__rule-learned-body",children:[c.jsx("span",{className:"chat-sdk__rule-learned-title",children:"Memory updated"}),c.jsx("span",{className:"chat-sdk__rule-learned-text",children:a})]})]}),c.jsx("div",{className:"chat-sdk__rule-learned-meta",children:De(n.timestamp)})]})}return c.jsx("div",{className:`chat-sdk__bubble ${s?"ai-patch":"ai"}`,children:c.jsxs("div",{className:`chat-sdk__bubble-body ${n.isStreaming?"streaming":""}`,children:[s&&c.jsx("div",{className:"chat-sdk__suggestion-text",children:c.jsx(Vt,{instructionId:n.instructionId})}),s&&((i=n.patchData)!=null&&i.originalText)?c.jsxs("div",{className:"chat-sdk__patch",children:[c.jsx("div",{className:"chat-sdk__patch-label chat-sdk__patch-label--original",children:"Original"}),c.jsx("div",{className:"chat-sdk__patch-block chat-sdk__patch-block--original",children:n.patchData.originalText}),c.jsx("div",{className:"chat-sdk__patch-label chat-sdk__patch-label--improved",children:"Suggested"}),c.jsxs("div",{className:"chat-sdk__patch-block chat-sdk__patch-block--improved",children:[n.patchData.improvedText,n.isStreaming&&c.jsx(fe,{})]})]}):c.jsxs(c.Fragment,{children:[c.jsx("div",{children:n.content}),t&&c.jsx(fe,{}),n.isStreaming&&!t&&c.jsx(fe,{})]})]})})}function Ft(){return c.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("path",{d:"m15 9-6 6"}),c.jsx("path",{d:"m9 9 6 6"})]})}function Ht(){return c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),c.jsx("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"}),c.jsx("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),c.jsx("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),c.jsx("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),c.jsx("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),c.jsx("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),c.jsx("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),c.jsx("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]})}function De(n){const e=new Date,t=new Date(e.getFullYear(),e.getMonth(),e.getDate()),s=new Date(t.getTime()-24*60*60*1e3),r=new Date(n.getFullYear(),n.getMonth(),n.getDate()),i=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1});if(r.getTime()===t.getTime())return i;if(r.getTime()===s.getTime())return`Yesterday, ${i}`;{const o=n.getDate(),d=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][n.getMonth()];return`${o} ${d}, ${i}`}}const G=["I have a suggestion for you","Here is something you might like","How about this?"];function Vt({instructionId:n}){const e=T.useMemo(()=>{if(n){let t=0;for(let s=0;s<n.length;s++)t=(t*31+n.charCodeAt(s))%G.length;return Math.abs(t)%G.length}return Math.floor(Math.random()*G.length)},[n]);return c.jsx(c.Fragment,{children:G[e]})}function Kt(){return c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"5"}),c.jsx("polyline",{points:"5 12 12 5 19 12"})]})}function zt(){return c.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function fe(){return c.jsxs("span",{className:"chat-sdk__stream",children:[c.jsx("span",{}),c.jsx("span",{}),c.jsx("span",{})]})}const $t=".chat-sdk{--radius-full: 9999px;--radius-large: 20px;--radius-medium: 12px;--spacing-1: 8px;--spacing-2: 16px;--space-20: 20px;--background-primary: #ffffff;--background-secondary: #f5f5f5;--background-tertiary: #f0f0f0;--surface-secondary: #ffffff;--content-primary: #141414;--content-secondary: #666666;--content-tertiary: #999999;--border-secondary: #e6e6e6;--background-brand1-primary: #e8effc;--content-brand1-secondary: #212191;--background-black: #141414;display:flex;flex-direction:column;background:var(--background-primary);border:1px solid var(--border-secondary);border-radius:var(--radius-large);box-shadow:0 8px 30px #0000000f;font-family:Matter,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;overflow:hidden}.chat-sdk__header{padding:14px 20px;display:flex;align-items:center;justify-content:space-between;background:var(--surface-secondary);border-bottom:1px solid var(--border-secondary)}.chat-sdk__title{font-weight:600;font-size:16px;color:var(--content-primary)}.chat-sdk__close-btn{display:flex;align-items:center;justify-content:center;width:20px;height:20px;padding:0;background:transparent;border:none;color:#131313;cursor:pointer;transition:opacity .15s}.chat-sdk__close-btn:hover{opacity:.7}.chat-sdk__messages{flex:1;padding:var(--space-20) 24px;display:flex;flex-direction:column;gap:24px;overflow-y:auto}.chat-sdk__empty{text-align:center;color:var(--content-secondary);font-size:14px;padding:16px}.chat-sdk__user-container{display:flex;flex-direction:column;align-items:flex-end;gap:8px}.chat-sdk__user-context{display:flex;justify-content:flex-end}.chat-sdk__context-chip{background:var(--background-tertiary);padding:8px 12px;border-radius:var(--radius-full);display:inline-flex;align-items:center;gap:8px;max-width:100%}.chat-sdk__context-text{font-size:14px;line-height:1.45;color:var(--content-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:280px}.chat-sdk__bubble.user{background:var(--background-brand1-primary);padding:10px;border-radius:var(--radius-medium);max-width:85%;border:none;color:var(--content-brand1-secondary)}.chat-sdk__bubble-meta{display:flex;align-items:center;justify-content:flex-end;gap:5px;font-size:12px;color:var(--content-tertiary);margin-top:4px}.chat-sdk__meta-dot{font-size:6px}.chat-sdk__bubble.user .chat-sdk__bubble-body{color:var(--content-brand1-secondary);font-size:15px;line-height:1.45;white-space:pre-wrap;overflow-wrap:break-word}.chat-sdk__bubble.ai,.chat-sdk__bubble.ai-patch{align-self:flex-start;max-width:90%;min-width:0;display:flex;flex-direction:column}.chat-sdk__bubble-body{display:flex;flex-direction:column;gap:8px;font-size:15px;color:var(--content-primary);line-height:1.5;overflow-wrap:break-word;word-break:break-word}.chat-sdk__suggestion-text{font-size:13px;color:var(--content-secondary);margin-bottom:0}.chat-sdk__patch{display:flex;flex-direction:column;gap:8px;margin-top:4px}.chat-sdk__patch-label{font-size:12px;color:var(--content-tertiary);font-weight:600}.chat-sdk__patch-block{background:#f3f4f6;border-radius:10px;padding:12px;border:1px solid #e5e7eb;font-size:14px;line-height:1.5;color:var(--content-primary);overflow-wrap:break-word;word-break:break-word;white-space:pre-wrap}.chat-sdk__patch-label--original{color:#b81514}.chat-sdk__patch-label--improved{color:#2d6a1e}.chat-sdk__patch-block--original{background:#fef2f2;border-color:#fde7e2}.chat-sdk__patch-block--improved{background:#f0fdf4;border-color:#dcfce7}.chat-sdk__composer{padding:var(--spacing-1);background:var(--background-primary)}.chat-sdk__input-bar{display:flex;flex-direction:column;background:#fff;border:1px solid var(--border-secondary);border-radius:var(--radius-large);padding:8px;overflow:hidden}.chat-sdk__input-context{padding:0 4px 8px}.chat-sdk__input-context .chat-sdk__context-chip{background:var(--background-tertiary);padding:8px 12px;border-radius:var(--radius-full);display:inline-flex;align-items:center;gap:8px}.chat-sdk__input-context .chat-sdk__context-text{font-size:14px;line-height:1.45;color:var(--content-primary)}.chat-sdk__context-clear{display:flex;align-items:center;justify-content:center;width:16px;height:16px;padding:0;background:transparent;border:none;color:var(--content-secondary);cursor:pointer;transition:color .15s}.chat-sdk__context-clear:hover{color:var(--content-primary)}.chat-sdk__input{width:100%;border:none;background:transparent;resize:none;min-height:72px;max-height:120px;font-size:15px;font-family:inherit;color:var(--content-primary);outline:none;line-height:1.45;padding:4px 8px}.chat-sdk__input::placeholder{color:var(--content-tertiary)}.chat-sdk__actions{display:flex;align-items:center;justify-content:flex-end}.chat-sdk__send{display:flex;align-items:center;justify-content:center;width:28px;height:28px;min-width:28px;min-height:28px;background:var(--background-black);color:#fff;border:none;border-radius:50%;cursor:pointer;transition:opacity .2s}.chat-sdk__send:disabled{opacity:.3;cursor:not-allowed}.chat-sdk__send:not(:disabled):hover{opacity:.8}.chat-sdk__error{font-size:12px;color:#dc2626;padding:4px 8px}.chat-sdk__stream{display:inline-flex;gap:4px;vertical-align:middle}.chat-sdk__stream span{width:4px;height:4px;background:currentColor;border-radius:50%;animation:chat-sdk-pulse 1.4s infinite ease-in-out both}.chat-sdk__stream span:nth-child(1){animation-delay:-.32s}.chat-sdk__stream span:nth-child(2){animation-delay:-.16s}@keyframes chat-sdk-pulse{0%,80%,to{transform:scale(0)}40%{transform:scale(1)}}.chat-sdk__rule-learned-container{display:flex;flex-direction:column;width:100%;animation:chat-sdk-rule-fade-in .5s ease-out}@keyframes chat-sdk-rule-fade-in{0%{opacity:0;transform:translateY(8px) scale(.97)}to{opacity:1;transform:translateY(0) scale(1)}}.chat-sdk__rule-learned{display:flex;align-items:flex-start;gap:6px;padding:8px 12px;background:#9370db2e;border:1px solid rgba(147,112,219,.5);border-radius:var(--radius-medium);width:100%}.chat-sdk__rule-learned-meta{font-size:12px;color:var(--content-tertiary);margin-top:4px;text-align:right}.chat-sdk__rule-learned-icon{flex-shrink:0;color:#9370db;display:flex;align-items:center;height:18px}.chat-sdk__rule-learned-body{display:flex;flex-direction:column;gap:2px;flex:1;min-width:0}.chat-sdk__rule-learned-title{font-size:13px;font-weight:600;color:#7b5cb8;white-space:nowrap;line-height:18px}.chat-sdk__rule-learned-text{font-size:13px;color:var(--content-primary);line-height:1.4;word-wrap:break-word}";R.ChatProvider=qt,R.ChatWidget=Be,R.style=$t,R.useChat=Le,Object.defineProperty(R,Symbol.toStringTag,{value:"Module"})});
2
2
  //# sourceMappingURL=translation-chat-sdk.umd.js.map