translation-chat-sdk 0.3.11 → 0.3.12
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.
- package/dist/services/socketClient.d.ts +4 -1
- package/dist/translation-chat-sdk.cjs.js +1 -1
- package/dist/translation-chat-sdk.cjs.js.map +1 -1
- package/dist/translation-chat-sdk.es.js +528 -507
- package/dist/translation-chat-sdk.es.js.map +1 -1
- package/dist/translation-chat-sdk.umd.js +1 -1
- package/dist/translation-chat-sdk.umd.js.map +1 -1
- package/dist/types.d.ts +13 -0
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ChatSDKConfig, ConnectionState, HistoryMessage, InstructionContext, PageTranslationResponseEventDetail, BulkTranslationResponseEventDetail, RuleLearnedEventDetail, LearnedRulesResponseEventDetail, UpdateRulesResponseEventDetail } from '../types';
|
|
1
|
+
import { ChatSDKConfig, ConnectionState, HistoryMessage, InstructionContext, PageTranslationResponseEventDetail, BulkTranslationResponseEventDetail, RuleLearnedEventDetail, LearnedRulesResponseEventDetail, UpdateRulesResponseEventDetail, PresenceUpdateEventDetail } from '../types';
|
|
2
2
|
type EventMap = {
|
|
3
3
|
connection: ConnectionState;
|
|
4
4
|
'chat-response': {
|
|
@@ -56,6 +56,7 @@ type EventMap = {
|
|
|
56
56
|
'rule-learned': RuleLearnedEventDetail;
|
|
57
57
|
'learned-rules-response': LearnedRulesResponseEventDetail;
|
|
58
58
|
'update-rules-response': UpdateRulesResponseEventDetail;
|
|
59
|
+
'presence-update': PresenceUpdateEventDetail;
|
|
59
60
|
'auth-error': {
|
|
60
61
|
message: string;
|
|
61
62
|
};
|
|
@@ -95,6 +96,8 @@ export declare class ChatSocketClient {
|
|
|
95
96
|
cancelBulkTranslation(trans_doc_id: string): Promise<void>;
|
|
96
97
|
requestLearnedRules(trans_doc_id: string): Promise<void>;
|
|
97
98
|
updateRules(trans_doc_id: string, rules_text: string): Promise<void>;
|
|
99
|
+
joinTranslation(trans_doc_id: string): void;
|
|
100
|
+
leaveTranslation(): void;
|
|
98
101
|
private registerSocketEvents;
|
|
99
102
|
private handleReconnect;
|
|
100
103
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("react/jsx-runtime"),R=require("react"),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 $=Object.create(null);Object.keys(L).forEach(n=>{$[L[n]]=n});const ne={type:"error",data:"parser error"},be=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",xe=typeof ArrayBuffer=="function",we=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,he=({type:n,data:e},t,s)=>be&&e instanceof Blob?t?s(e):ge(e,s):xe&&(e instanceof ArrayBuffer||we(e))?t?s(e):ge(new Blob([e]),s):s(L[n]+(e||"")),ge=(n,e)=>{const t=new FileReader;return t.onload=function(){const s=t.result.split(",")[1];e("b"+(s||""))},t.readAsDataURL(n)};function _e(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let Z;function Ue(n,e){if(be&&n.data instanceof Blob)return n.data.arrayBuffer().then(_e).then(e);if(xe&&(n.data instanceof ArrayBuffer||we(n.data)))return e(_e(n.data));he(n,!1,t=>{Z||(Z=new TextEncoder),e(Z.encode(t))})}const me="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",H=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n<me.length;n++)H[me.charCodeAt(n)]=n;const qe=n=>{let e=n.length*.75,t=n.length,s,i=0,r,o,h,u;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);const l=new ArrayBuffer(e),d=new Uint8Array(l);for(s=0;s<t;s+=4)r=H[n.charCodeAt(s)],o=H[n.charCodeAt(s+1)],h=H[n.charCodeAt(s+2)],u=H[n.charCodeAt(s+3)],d[i++]=r<<2|o>>4,d[i++]=(o&15)<<4|h>>2,d[i++]=(h&3)<<6|u&63;return l},je=typeof ArrayBuffer=="function",le=(n,e)=>{if(typeof n!="string")return{type:"message",data:ve(n,e)};const t=n.charAt(0);return t==="b"?{type:"message",data:Me(n.substring(1),e)}:$[t]?n.length>1?{type:$[t],data:n.substring(1)}:{type:$[t]}:ne},Me=(n,e)=>{if(je){const t=qe(n);return ve(t,e)}else return{base64:!0,data:n}},ve=(n,e)=>{switch(e){case"blob":return n instanceof Blob?n:new Blob([n]);case"arraybuffer":default:return n instanceof ArrayBuffer?n:n.buffer}},Ee="",Fe=(n,e)=>{const t=n.length,s=new Array(t);let i=0;n.forEach((r,o)=>{he(r,!1,h=>{s[o]=h,++i===t&&e(s.join(Ee))})})},He=(n,e)=>{const t=n.split(Ee),s=[];for(let i=0;i<t.length;i++){const r=le(t[i],e);if(s.push(r),r.type==="error")break}return s};function Ve(){return new TransformStream({transform(n,e){Ue(n,t=>{const s=t.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const r=new DataView(i.buffer);r.setUint8(0,126),r.setUint16(1,s)}else{i=new Uint8Array(9);const r=new DataView(i.buffer);r.setUint8(0,127),r.setBigUint64(1,BigInt(s))}n.data&&typeof n.data!="string"&&(i[0]|=128),e.enqueue(i),e.enqueue(t)})}})}let ee;function V(n){return n.reduce((e,t)=>e+t.length,0)}function K(n,e){if(n[0].length===e)return n.shift();const t=new Uint8Array(e);let s=0;for(let i=0;i<e;i++)t[i]=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 Ke(n,e){ee||(ee=new TextDecoder);const t=[];let s=0,i=-1,r=!1;return new TransformStream({transform(o,h){for(t.push(o);;){if(s===0){if(V(t)<1)break;const u=K(t,1);r=(u[0]&128)===128,i=u[0]&127,i<126?s=3:i===126?s=1:s=2}else if(s===1){if(V(t)<2)break;const u=K(t,2);i=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),s=3}else if(s===2){if(V(t)<8)break;const u=K(t,8),l=new DataView(u.buffer,u.byteOffset,u.length),d=l.getUint32(0);if(d>Math.pow(2,21)-1){h.enqueue(ne);break}i=d*Math.pow(2,32)+l.getUint32(4),s=3}else{if(V(t)<i)break;const u=K(t,i);h.enqueue(le(r?u:ee.decode(u),e)),s=0}if(i===0||i>n){h.enqueue(ne);break}}}})}const Te=4;function T(n){if(n)return ze(n)}function ze(n){for(var e in T.prototype)n[e]=T.prototype[e];return n}T.prototype.on=T.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};T.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};T.prototype.off=T.prototype.removeListener=T.prototype.removeAllListeners=T.prototype.removeEventListener=function(n,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+n];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;for(var s,i=0;i<t.length;i++)if(s=t[i],s===e||s.fn===e){t.splice(i,1);break}return t.length===0&&delete this._callbacks["$"+n],this};T.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,i=t.length;s<i;++s)t[s].apply(this,e)}return this};T.prototype.emitReserved=T.prototype.emit;T.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};T.prototype.hasListeners=function(n){return!!this.listeners(n).length};const X=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),N=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),$e="arraybuffer";function Re(n,...e){return e.reduce((t,s)=>(n.hasOwnProperty(s)&&(t[s]=n[s]),t),{})}const We=N.setTimeout,Qe=N.clearTimeout;function G(n,e){e.useNativeTimers?(n.setTimeoutFn=We.bind(N),n.clearTimeoutFn=Qe.bind(N)):(n.setTimeoutFn=N.setTimeout.bind(N),n.clearTimeoutFn=N.clearTimeout.bind(N))}const Ye=1.33;function Je(n){return typeof n=="string"?Xe(n):Math.ceil((n.byteLength||n.size)*Ye)}function Xe(n){let e=0,t=0;for(let s=0,i=n.length;s<i;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 Se(){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,i=t.length;s<i;s++){let r=t[s].split("=");e[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return e}class et extends Error{constructor(e,t,s){super(e),this.description=t,this.context=s,this.type="TransportError"}}class ue extends T{constructor(e){super(),this.writable=!1,G(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=le(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 ue{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)};He(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,Fe(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]=Se()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let Ne=!1;try{Ne=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const st=Ne;function nt(){}class it 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",(i,r)=>{this.onError("xhr post error",i,r)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,s)=>{this.onError("xhr poll error",t,s)}),this.pollXhr=e}}class P extends T{constructor(e,t,s){super(),this.createRequest=e,G(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=Re(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(t);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&s.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var i;s.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=P.requestsCount++,P.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 P.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()}}P.requestsCount=0;P.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",ye);else if(typeof addEventListener=="function"){const n="onpagehide"in N?"pagehide":"unload";addEventListener(n,ye,!1)}}function ye(){for(let n in P.requests)P.requests.hasOwnProperty(n)&&P.requests[n].abort()}const rt=function(){const n=Ce({xdomain:!1});return n&&n.responseType!==null}();class ot extends it{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=rt&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new P(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 N[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Ae=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class ct extends ue{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=Ae?{}:Re(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,s)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],i=t===e.length-1;he(s,this.supportsBinary,r=>{try{this.doWrite(s,r)}catch{}i&&X(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=Se()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const te=N.WebSocket||N.MozWebSocket;class at extends ct{createSocket(e,t,s){return Ae?new te(e,t,s):t?new te(e,t):new te(e)}doWrite(e,t){this.ws.send(t)}}class ht extends ue{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=Ke(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=e.readable.pipeThrough(t).getReader(),i=Ve();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const r=()=>{s.read().then(({done:h,value:u})=>{h||(this.onPacket(u),r())}).catch(h=>{})};r();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],i=t===e.length-1;this._writer.write(s).then(()=>{i&&X(()=>{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},ut=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,dt=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function ie(n){if(n.length>8e3)throw"URI too long";const e=n,t=n.indexOf("["),s=n.indexOf("]");t!=-1&&s!=-1&&(n=n.substring(0,t)+n.substring(t,s).replace(/:/g,";")+n.substring(s,n.length));let i=ut.exec(n||""),r={},o=14;for(;o--;)r[dt[o]]=i[o]||"";return t!=-1&&s!=-1&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=ft(r,r.path),r.queryKey=pt(r,r.query),r}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,i,r){i&&(t[i]=r)}),t}const re=typeof addEventListener=="function"&&typeof removeEventListener=="function",W=[];re&&addEventListener("offline",()=>{W.forEach(n=>n())},!1);class I extends T{constructor(e,t){if(super(),this.binaryType=$e,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=ie(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=ie(t.host).host);G(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(s=>{const i=s.prototype.name;this.transports.push(i),this._transportsByName[i]=s}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Ze(this.opts.query)),re&&(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"})},W.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=Te,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&&I.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",I.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 i=this.writeBuffer[s].data;if(i&&(t+=Je(i)),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,X(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,s){return this._sendPacket("message",e,t,s),this}send(e,t,s){return this._sendPacket("message",e,t,s),this}_sendPacket(e,t,s,i){if(typeof t=="function"&&(i=t,t=void 0),typeof s=="function"&&(i=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const r={type:e,data:t,options:s};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},s=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():e()}):this.upgrading?s():e()),this}_onError(e){if(I.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(),re&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=W.indexOf(this._offlineEventListener);s!==-1&&W.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}I.protocol=Te;class gt extends I{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;I.priorWebsocketSuccess=!1;const i=()=>{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;I.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(d(),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 r(){s||(s=!0,d(),t.close(),t=null)}const o=f=>{const g=new Error("probe error: "+f);g.transport=t.name,r(),this.emitReserved("upgradeError",g)};function h(){o("transport closed")}function u(){o("socket closed")}function l(f){t&&f.name!==t.name&&r()}const d=()=>{t.removeListener("open",i),t.removeListener("error",o),t.removeListener("close",h),this.off("close",u),this.off("upgrading",l)};t.once("open",i),t.once("error",o),t.once("close",h),this.once("close",u),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(i=>lt[i]).filter(i=>!!i)),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=ie(n)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const r=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+r+":"+s.port+e,s.href=s.protocol+"://"+r+(t&&t.port===s.port?"":":"+s.port),s}const yt=typeof ArrayBuffer=="function",kt=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,Oe=Object.prototype.toString,bt=typeof Blob=="function"||typeof Blob<"u"&&Oe.call(Blob)==="[object BlobConstructor]",xt=typeof File=="function"||typeof File<"u"&&Oe.call(File)==="[object FileConstructor]";function de(n){return yt&&(n instanceof ArrayBuffer||kt(n))||bt&&n instanceof Blob||xt&&n instanceof File}function Q(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,s=n.length;t<s;t++)if(Q(n[t]))return!0;return!1}if(de(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return Q(n.toJSON(),!0);for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&Q(n[t]))return!0;return!1}function wt(n){const e=[],t=n.data,s=n;return s.data=oe(t,e),s.attachments=e.length,{packet:s,buffers:e}}function oe(n,e){if(!n)return n;if(de(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]=oe(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]=oe(n[s],e));return t}return n}function vt(n,e){return n.data=ce(n.data,e),delete n.attachments,n}function ce(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]=ce(n[t],e);else if(typeof n=="object")for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=ce(n[t],e));return n}const Pe=["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)&&Q(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=wt(e),s=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(s),i}}class fe extends T{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 Rt(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(de(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 r=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const o=e.substring(r,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");s.attachments=Number(o)}if(e.charAt(t+1)==="/"){const r=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););s.nsp=e.substring(r,t)}else s.nsp="/";const i=e.charAt(t+1);if(i!==""&&Number(i)==i){const r=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(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(fe.isPayloadValid(s.type,r))s.data=r;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"&&Pe.indexOf(t[0])===-1);case _.ACK:case _.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Rt{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=vt(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function St(n){return typeof n=="string"}const Nt=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n};function Ct(n){return n===void 0||Nt(n)}function J(n){return Object.prototype.toString.call(n)==="[object Object]"}function At(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"&&Pe.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 St(n.nsp)&&Ct(n.id)&&At(n.type,n.data)}const Pt=Object.freeze(Object.defineProperty({__proto__:null,Decoder:fe,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 Le extends T{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,i,r;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 d=this.ids++,f=t.pop();this._registerAckCallback(d,f),o.id=d}const h=(i=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||i===void 0?void 0:i.writable,u=this.connected&&!(!((r=this.io.engine)===null||r===void 0)&&r._hasPingExpired());return this.flags.volatile&&!h||(u?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var s;const i=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(i===void 0){this.acks[e]=t;return}const r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let h=0;h<this.sendBuffer.length;h++)this.sendBuffer[h].id===e&&this.sendBuffer.splice(h,1);t.call(this,new Error("operation has timed out"))},i),o=(...h)=>{this.io.clearTimeoutFn(r),t.apply(this,h)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((s,i)=>{const r=(o,h)=>o?i(o):s(h);r.withError=!0,t.push(r),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...r)=>(this._queue[0],i!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(i)):(this._queue.shift(),t&&t(null,...r)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:_.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(...i){s||(s=!0,t.packet({type:_.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._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 M(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}M.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};M.prototype.reset=function(){this.attempts=0};M.prototype.setMin=function(n){this.ms=n};M.prototype.setMax=function(n){this.max=n};M.prototype.setJitter=function(n){this.jitter=n};class ae extends T{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,G(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 M({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||Pt;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new _t(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const i=O(t,"open",function(){s.onopen(),e&&e()}),r=h=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",h),e?e(h):this.maybeReconnectOnOpen()},o=O(t,"error",r);if(this._timeout!==!1){const h=this._timeout,u=this.setTimeoutFn(()=>{i(),r(new Error("timeout")),t.close()},h);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(i),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(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){X(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let s=this.nsps[e];return s?this._autoConnect&&!s.active&&s.connect():(s=new Le(this,e,t),this.nsps[e]=s),s}_destroy(e){const t=Object.keys(this.nsps);for(const s of t)if(this.nsps[s].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let s=0;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(i=>{i?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):e.onreconnect()}))},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const F={};function Y(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};const t=mt(n,e.path||"/socket.io"),s=t.source,i=t.id,r=t.path,o=F[i]&&r in F[i].nsps,h=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let u;return h?u=new ae(s,e):(F[i]||(F[i]=new ae(s,e)),u=F[i]),t.query&&!e.query&&(e.query=t.queryKey),u.socket(t.path,e)}Object.assign(Y,{Manager:ae,Socket:Le,io:Y,connect:Y});function S(){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(i=>{var r,o;try{i(t)}catch(h){(o=(r=this.config.logger)==null?void 0:r.error)==null||o.call(r,`chat-sdk listener error for ${e}`,h)}})}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(i){return(s=(t=this.config.logger)==null?void 0:t.warn)==null||s.call(t,"chat-sdk token provider failed",i),null}}async connect(){var r;if((r=this.socket)!=null&&r.connected)return;const e=new URL(this.config.websocketUrl),t=e.pathname==="/"?"/socket.io":e.pathname,s=e.origin,i=await this.getToken();return this.socket=Y(s,{path:t,transports:["websocket","polling"],autoConnect:!1,reconnection:!1,auth:i?{token:i}:void 0,withCredentials:!0}),this.registerSocketEvents(),this.setConnection({connected:!1,connecting:!0}),new Promise((o,h)=>{const u=setTimeout(()=>{h(new Error("connection timeout"))},1e4);this.socket.once("connect",()=>{clearTimeout(u),this.reconnectAttempts=0,this.setConnection({connected:!0,connecting:!1}),o()}),this.socket.once("connect_error",l=>{clearTimeout(u),this.setConnection({connected:!1,connecting:!1,error:l.message}),this.handleReconnect(),h(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 r,o;if(!((r=this.socket)!=null&&r.connected))throw new Error("Not connected");this.lastContext=t;const s=await this.getToken(),i={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("INSTRUCTION_SUBMIT",i)}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,i,r,o,h;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();(r=(i=this.config.logger)==null?void 0:i.log)==null||r.call(i,"[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}),(h=(o=this.config.logger)==null?void 0:o.log)==null||h.call(o,"[chat-sdk] PATCH_DECISION emitted successfully")}async requestPageTranslation(e){var i,r,o,h,u;if(!((i=this.socket)!=null&&i.connected))throw new Error("Not connected");const t=await this.getToken(),s={...e,access_token:t||void 0};(o=(r=this.config.logger)==null?void 0:r.log)==null||o.call(r,"[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),(u=(h=this.config.logger)==null?void 0:h.log)==null||u.call(h,"[chat-sdk] PAGE_TRANSLATION_REQUEST emitted successfully")}async requestBulkTranslation(e){var i,r,o,h,u;if(!((i=this.socket)!=null&&i.connected))throw new Error("Not connected");const t=await this.getToken(),s={...e,access_token:t||void 0};(o=(r=this.config.logger)==null?void 0:r.log)==null||o.call(r,"[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),(u=(h=this.config.logger)==null?void 0:h.log)==null||u.call(h,"[chat-sdk] BULK_TRANSLATION_REQUEST emitted successfully")}async cancelBulkTranslation(e){var s,i,r,o,h;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();(r=(i=this.config.logger)==null?void 0:i.log)==null||r.call(i,"[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}),(h=(o=this.config.logger)==null?void 0:o.log)==null||h.call(o,"[chat-sdk] CANCEL_BULK_TRANSLATION_REQUEST emitted successfully")}async requestLearnedRules(e){var s,i,r,o,h;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();(r=(i=this.config.logger)==null?void 0:i.log)==null||r.call(i,"[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}),(h=(o=this.config.logger)==null?void 0:o.log)==null||h.call(o,"[chat-sdk] LEARNED_RULES_REQUEST emitted successfully")}async updateRules(e,t){var i,r,o,h,u;if(!((i=this.socket)!=null&&i.connected))throw new Error("Not connected");const s=await this.getToken();(o=(r=this.config.logger)==null?void 0:r.log)==null||o.call(r,"[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}),(u=(h=this.config.logger)==null?void 0:h.log)==null||u.call(h,"[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_RESPONSE",e=>{var t,s;(s=(t=this.config.logger)==null?void 0:t.log)==null||s.call(t,"[chat-sdk] Received INSTRUCTION_RESPONSE:",{instruction_id:e.instruction_id,status:e.status,response_type:e.response_type}),this.emit("instruction-response",e)}),this.socket.on("INSTRUCTION_ERROR",e=>{this.emit("instruction-error",e)}),this.socket.on("PAGE_TRANSLATION_RESPONSE",e=>{var t,s,i,r,o,h,u,l,d,f,g;(i=(t=this.config.logger)==null?void 0:t.log)==null||i.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=(r=this.config.logger)==null?void 0:r.log)==null||o.call(r,"[chat-sdk] Emitted page-translation-response internally"),this.config.onPageTranslationResponse?((u=(h=this.config.logger)==null?void 0:h.log)==null||u.call(h,"[chat-sdk] Calling onPageTranslationResponse callback"),this.config.onPageTranslationResponse(e),(d=(l=this.config.logger)==null?void 0:l.log)==null||d.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,i,r,o,h,u,l,d,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),(r=(i=this.config.logger)==null?void 0:i.log)==null||r.call(i,"[chat-sdk] Emitted bulk-translation-response internally"),this.config.onBulkTranslationResponse?((h=(o=this.config.logger)==null?void 0:o.log)==null||h.call(o,"[chat-sdk] Calling onBulkTranslationResponse callback"),this.config.onBulkTranslationResponse(e),(l=(u=this.config.logger)==null?void 0:u.log)==null||l.call(u,"[chat-sdk] onBulkTranslationResponse callback completed")):(f=(d=this.config.logger)==null?void 0:d.log)==null||f.call(d,"[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 i,r;return(r=(i=this.config.logger)==null?void 0:i.error)==null?void 0:r.call(i,"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:S(),type:"rule-learned",content:e.response_content||"Rule learned",ruleSummary:e.rule_summary??void 0}];const s={...t,id:S(),type:"user",content:e.instruction,contextText:e.region_text??void 0},i=[];return e.response_content&&e.response_type==="chat"&&i.push({...t,id:S(),type:"ai-chat",content:e.response_content}),e.response_content&&e.response_type==="patch"&&i.push({...t,id:S(),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,...i]}).flat().sort((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())}const Be=R.createContext(null),It={connected:!1,connecting:!1};function Ut({config:n,children:e}){const t=R.useRef(null),s=R.useRef(new Map),[i,r]=R.useState({messages:[],connection:It,latestPatchOffer:null,isSubmitting:!1}),o=R.useMemo(()=>({reconnectAttempts:5,reconnectDelayMs:1500,...n}),[n]);R.useEffect(()=>{const l=new Bt(o);t.current=l;const d=l.on("connection",c=>{r(p=>({...p,connection:c}))}),f=l.on("chat-response",c=>{r(p=>{const m=p.messages.filter(v=>v.type!=="loading");let b=m.find(v=>v.instructionId===c.instruction_id&&v.type==="ai-chat");b||(b={id:S(),type:"ai-chat",content:"",timestamp:new Date,instructionId:c.instruction_id,pageNum:c.page_num,isStreaming:!0},m.push(b));const y={...b,content:(b.content||"")+(c.chunk_text||""),isStreaming:!c.is_final},w=m.map(v=>v.id===b.id?y:v);return{...p,messages:w,isSubmitting:c.is_final?!1:p.isSubmitting}})}),g=l.on("patch-offer",c=>{var b;const p=`${c.trans_doc_id}-${c.instruction_id}`,m=s.current.get(p)??{trans_doc_id:c.trans_doc_id,page_num:c.page_num,instruction_id:c.instruction_id,original_text:c.region_original_text||"",highlighted_region:c.region_coordinates,new_suggestion:"",is_page_level:!c.region_coordinates,selection_id:c.selection_id};if(m.new_suggestion+=c.region_replacement_text_chunk||"",c.selection_id&&!m.selection_id&&(m.selection_id=c.selection_id),s.current.set(p,m),r(y=>{var pe;const w=y.messages.filter(q=>q.type!=="loading");let v=w.find(q=>q.instructionId===c.instruction_id&&q.type==="ai-patch");v||(v={id:S(),type:"ai-patch",content:"",timestamp:new Date,instructionId:c.instruction_id,pageNum:c.page_num,isStreaming:!0,patchData:{originalText:c.region_original_text,improvedText:"",regionText:c.region_original_text,isComplete:!1}},w.push(v));const A={...v,content:(v.content||"")+(c.region_replacement_text_chunk||""),isStreaming:!c.is_final,patchData:{...v.patchData,improvedText:(((pe=v.patchData)==null?void 0:pe.improvedText)||"")+(c.region_replacement_text_chunk||""),regionText:c.region_original_text,isComplete:c.is_final}},U=w.map(q=>q.id===v.id?A:q);return{...y,messages:U,isSubmitting:c.is_final?!1:y.isSubmitting}}),c.is_final){const y=s.current.get(p);y&&((b=o.onPatchOffer)==null||b.call(o,y),r(w=>({...w,latestPatchOffer:y}))),s.current.delete(p)}}),k=l.on("chat-history-response",c=>{if(c.status==="success"){const p=Dt(c.messages);r(m=>({...m,messages:p}))}else r(p=>({...p,messages:[...p.messages,{id:S(),type:"system",content:c.error||"Failed to load chat history",timestamp:new Date}]}))}),x=l.on("instruction-response",c=>{var p;if(c.status==="error"){r(m=>({...m,isSubmitting:!1,messages:[...m.messages.filter(b=>b.type!=="loading"),{id:S(),type:"error",content:c.error||"Instruction processing failed",timestamp:new Date,instructionId:c.instruction_id}]}));return}if(c.response_type==="patch"){const m={trans_doc_id:c.trans_doc_id,page_num:c.page_num??0,instruction_id:c.instruction_id,original_text:c.region_text||"",highlighted_region:c.region_coordinates,new_suggestion:(c.response_content||"").trim(),is_page_level:!c.region_coordinates,selection_id:c.selection_id};r(b=>({...b,isSubmitting:!1,latestPatchOffer:m,messages:[...b.messages.filter(y=>y.type!=="loading"),{id:S(),type:"ai-patch",content:c.response_content||"",timestamp:new Date,instructionId:c.instruction_id,pageNum:c.page_num??void 0,isStreaming:!1,patchData:{originalText:c.region_text??void 0,improvedText:c.response_content||"",regionText:c.region_text??void 0,isComplete:!0}}]})),(p=o.onPatchOffer)==null||p.call(o,m)}else r(m=>({...m,isSubmitting:!1,messages:[...m.messages.filter(b=>b.type!=="loading"),{id:S(),type:"ai-chat",content:c.response_content||"",timestamp:new Date,instructionId:c.instruction_id,pageNum:c.page_num??void 0,isStreaming:!1}]}))}),E=l.on("instruction-error",c=>{r(p=>({...p,isSubmitting:!1,messages:[...p.messages,{id:S(),type:"error",content:c.error,timestamp:new Date}]}))}),B=l.on("page-translation-response",c=>{var p,m,b,y,w,v,A,U;(m=(p=o.logger)==null?void 0:p.log)==null||m.call(p,"[chat-sdk][ChatProvider] Received page-translation-response event:",{trans_doc_id:c.trans_doc_id,page_num:c.page_num,status:c.status,has_content:!!c.trans_page_content,error:c.error}),o.onPageTranslationResponse?((y=(b=o.logger)==null?void 0:b.log)==null||y.call(b,"[chat-sdk][ChatProvider] Invoking onPageTranslationResponse callback from config"),o.onPageTranslationResponse(c),(v=(w=o.logger)==null?void 0:w.log)==null||v.call(w,"[chat-sdk][ChatProvider] onPageTranslationResponse callback completed")):(U=(A=o.logger)==null?void 0:A.log)==null||U.call(A,"[chat-sdk][ChatProvider] No onPageTranslationResponse callback in config")}),C=l.on("bulk-translation-response",c=>{var p,m,b,y,w,v,A,U;(m=(p=o.logger)==null?void 0:p.log)==null||m.call(p,"[chat-sdk][ChatProvider] Received bulk-translation-response event:",{trans_doc_id:c.trans_doc_id,status:c.status,completed_pages:c.completed_pages,total_pages:c.total_pages,current_page:c.current_page,error:c.error}),o.onBulkTranslationResponse?((y=(b=o.logger)==null?void 0:b.log)==null||y.call(b,"[chat-sdk][ChatProvider] Invoking onBulkTranslationResponse callback from config"),o.onBulkTranslationResponse(c),(v=(w=o.logger)==null?void 0:w.log)==null||v.call(w,"[chat-sdk][ChatProvider] onBulkTranslationResponse callback completed")):(U=(A=o.logger)==null?void 0:A.log)==null||U.call(A,"[chat-sdk][ChatProvider] No onBulkTranslationResponse callback in config")}),D=l.on("rule-learned",c=>{var p,m;(m=(p=o.logger)==null?void 0:p.log)==null||m.call(p,"[chat-sdk][ChatProvider] Received rule-learned event:",{trans_doc_id:c.trans_doc_id,instruction_id:c.instruction_id,rule_summary:c.rule_summary}),r(b=>({...b,messages:[...b.messages,{id:S(),type:"rule-learned",content:c.message||"Rule learned",timestamp:new Date,instructionId:c.instruction_id,ruleSummary:c.rule_summary}]})),o.onRuleLearned&&o.onRuleLearned(c)}),j=l.on("learned-rules-response",c=>{var p,m;(m=(p=o.logger)==null?void 0:p.log)==null||m.call(p,"[chat-sdk][ChatProvider] Received learned-rules-response event:",{trans_doc_id:c.trans_doc_id,has_rules:c.has_rules,status:c.status}),o.onLearnedRulesResponse&&o.onLearnedRulesResponse(c)});return l.connect().then(()=>{const c=o.contextProvider();if(c)return l.requestChatHistory(c)}).catch(c=>{var p,m;return(m=(p=o.logger)==null?void 0:p.warn)==null?void 0:m.call(p,"chat-sdk connect failed",c)}),()=>{d(),f(),g(),k(),x(),E(),B(),C(),D(),j(),l.disconnect()}},[o]);const h=R.useMemo(()=>({async submitInstruction(l){const d=t.current;if(!d)throw new Error("SDK not ready");const f=o.contextProvider();if(!f)throw new Error("contextProvider returned null");r(g=>{var k;return{...g,isSubmitting:!0,messages:[...g.messages,{id:S(),type:"user",content:l,timestamp:new Date,pageNum:f.page_num,contextText:(k=f.highlighted_region)==null?void 0:k.text},{id:S(),type:"loading",content:"Processing your instruction...",timestamp:new Date,isStreaming:!0}]}}),await d.submitInstruction(l,f)},async submitInstructionWithContext(l,d){const f=t.current;if(!f)throw new Error("SDK not ready");r(g=>{var k;return{...g,isSubmitting:!0,messages:[...g.messages,{id:S(),type:"user",content:l,timestamp:new Date,pageNum:d.page_num,contextText:(k=d.highlighted_region)==null?void 0:k.text},{id:S(),type:"loading",content:"Processing your instruction...",timestamp:new Date,isStreaming:!0}]}}),await f.submitInstruction(l,d)},async requestChatHistory(){const l=t.current;if(!l)throw new Error("SDK not ready");const d=o.contextProvider();if(!d)throw new Error("contextProvider returned null");await l.requestChatHistory(d)},async sendPatchDecision(l,d,f,g,k){var E,B,C,D;const x=t.current;if(!x)throw new Error("SDK not ready");(B=(E=o.logger)==null?void 0:E.log)==null||B.call(E,"[chat-sdk][ChatProvider] sendPatchDecision called:",{trans_doc_id:l,page_num:d,instruction_id:f,decision:g,remember_this:k}),await x.sendPatchDecision({trans_doc_id:l,page_num:d,instruction_id:f,decision:g,remember_this:k}),(D=(C=o.logger)==null?void 0:C.log)==null||D.call(C,"[chat-sdk][ChatProvider] sendPatchDecision completed"),r(j=>({...j,latestPatchOffer:null}))},async requestPageTranslation(l,d){var g,k,x,E;const f=t.current;if(!f)throw new Error("SDK not ready");return(k=(g=o.logger)==null?void 0:g.log)==null||k.call(g,"[chat-sdk][ChatProvider] requestPageTranslation called:",{trans_doc_id:l,page_num:d}),await f.requestPageTranslation({trans_doc_id:l,page_num:d}),(E=(x=o.logger)==null?void 0:x.log)==null||E.call(x,"[chat-sdk][ChatProvider] requestPageTranslation request sent"),!0},async requestBulkTranslation(l,d){var g,k,x,E;const f=t.current;if(!f)throw new Error("SDK not ready");return(k=(g=o.logger)==null?void 0:g.log)==null||k.call(g,"[chat-sdk][ChatProvider] requestBulkTranslation called:",{trans_doc_id:l,page_list:d}),await f.requestBulkTranslation({trans_doc_id:l,page_list:d}),(E=(x=o.logger)==null?void 0:x.log)==null||E.call(x,"[chat-sdk][ChatProvider] requestBulkTranslation request sent"),!0},async cancelBulkTranslation(l){var f,g,k,x;const d=t.current;if(!d)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 d.cancelBulkTranslation(l),(x=(k=o.logger)==null?void 0:k.log)==null||x.call(k,"[chat-sdk][ChatProvider] cancelBulkTranslation request sent"),!0},async requestLearnedRules(l){var f,g,k,x;const d=t.current;if(!d)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 d.requestLearnedRules(l),(x=(k=o.logger)==null?void 0:k.log)==null||x.call(k,"[chat-sdk][ChatProvider] requestLearnedRules request sent")},async updateRules(l,d){var g,k,x,E;const f=t.current;if(!f)throw new Error("SDK not ready");(k=(g=o.logger)==null?void 0:g.log)==null||k.call(g,"[chat-sdk][ChatProvider] updateRules called:",{trans_doc_id:l,rules_text_length:d.length}),await f.updateRules(l,d),(E=(x=o.logger)==null?void 0:x.log)==null||E.call(x,"[chat-sdk][ChatProvider] updateRules request sent")},clearMessages(){r(l=>({...l,messages:[]}))},clearSelection(){var l;(l=o.onClearSelection)==null||l.call(o)}}),[o]),u=R.useMemo(()=>({...i,...h}),[i,h]);return a.jsx(Be.Provider,{value:u,children:e})}function qt(){const n=R.useContext(Be);if(!n)throw new Error("useChat must be used within ChatProvider");return n}function De(){return qt()}const Ie=R.forwardRef(({title:n="AI Assistance",placeholder:e="Ask anything...",height:t="500px",onClose:s},i)=>{const{messages:r,connection:o,submitInstruction:h,submitInstructionWithContext:u,isSubmitting:l,clearSelection:d}=De(),[f,g]=R.useState(""),[k,x]=R.useState(null),[E,B]=R.useState(null),C=R.useRef(null),D=R.useRef(null),j=!o.connected||l;R.useImperativeHandle(i,()=>({setContext:({text:y,context:w})=>{B(y),x(w),setTimeout(()=>{var v;(v=D.current)==null||v.focus()},100)},focusInput:()=>{var y;(y=D.current)==null||y.focus()}}),[]);const c=R.useMemo(()=>[...r].sort((y,w)=>y.timestamp.getTime()-w.timestamp.getTime()),[r]);R.useEffect(()=>{C.current&&(C.current.scrollTop=C.current.scrollHeight)},[c]);const p=async y=>{y.preventDefault();const w=f.trim();w&&(k?(await u(w,k),x(null),B(null)):await h(w),g(""))},m=y=>{y.key==="Enter"&&!y.shiftKey&&(y.preventDefault(),p(y))},b=()=>{x(null),B(null),d()};return a.jsxs("div",{className:"chat-sdk",style:{height:t},children:[a.jsxs("div",{className:"chat-sdk__header",children:[a.jsx("div",{className:"chat-sdk__title",children:n}),s&&a.jsx("button",{type:"button",onClick:s,className:"chat-sdk__close-btn",children:a.jsx(Mt,{})})]}),a.jsx("div",{className:"chat-sdk__messages",ref:C,children:c.length===0?a.jsx("div",{className:"chat-sdk__empty",children:"Welcome! Ask anything about the translation."}):c.map(y=>a.jsx(jt,{message:y},y.id))}),a.jsxs("div",{className:"chat-sdk__composer",children:[a.jsxs("form",{className:"chat-sdk__input-bar",onSubmit:p,children:[E&&a.jsx("div",{className:"chat-sdk__input-context",children:a.jsxs("div",{className:"chat-sdk__context-chip",children:[a.jsx("span",{className:"chat-sdk__context-text",children:E.length>40?`${E.slice(0,40)}…`:E}),a.jsx("button",{type:"button",onClick:b,className:"chat-sdk__context-clear",children:a.jsx(Kt,{})})]})}),a.jsx("textarea",{ref:D,className:"chat-sdk__input",placeholder:E?"What would you like to change?":e,value:f,onChange:y=>g(y.target.value),onKeyDown:m,disabled:j,rows:1}),a.jsx("div",{className:"chat-sdk__actions",children:a.jsx("button",{className:"chat-sdk__send",type:"submit",disabled:!f.trim()||j,children:a.jsx(Vt,{})})})]}),o.error&&a.jsxs("div",{className:"chat-sdk__error",children:["⚠️ ",o.error]})]})]})});Ie.displayName="ChatWidget";function jt({message:n}){var r;const e=n.type==="user",t=n.type==="loading",s=n.type==="ai-patch",i=n.type==="rule-learned";if(e)return a.jsxs("div",{className:"chat-sdk__user-container",children:[n.contextText&&a.jsx("div",{className:"chat-sdk__user-context",children:a.jsx("div",{className:"chat-sdk__context-chip",children:a.jsx("span",{className:"chat-sdk__context-text",children:n.contextText.length>40?`${n.contextText.slice(0,40)}…`:n.contextText})})}),a.jsx("div",{className:"chat-sdk__bubble user",children:a.jsx("div",{className:"chat-sdk__bubble-body",children:n.content})}),a.jsxs("div",{className:"chat-sdk__bubble-meta",children:[n.pageNum!==void 0&&a.jsxs("span",{children:["Page ",n.pageNum]}),n.pageNum!==void 0&&a.jsx("span",{className:"chat-sdk__meta-dot",children:"•"}),a.jsx("span",{children:ke(n.timestamp)})]})]});if(i){const o=n.ruleSummary||n.content,h=o.charAt(0).toUpperCase()+o.slice(1);return a.jsxs("div",{className:"chat-sdk__rule-learned-container",children:[a.jsxs("div",{className:"chat-sdk__rule-learned",children:[a.jsx("div",{className:"chat-sdk__rule-learned-icon",children:a.jsx(Ft,{})}),a.jsxs("div",{className:"chat-sdk__rule-learned-body",children:[a.jsx("span",{className:"chat-sdk__rule-learned-title",children:"Memory updated"}),a.jsx("span",{className:"chat-sdk__rule-learned-text",children:h})]})]}),a.jsx("div",{className:"chat-sdk__rule-learned-meta",children:ke(n.timestamp)})]})}return a.jsx("div",{className:`chat-sdk__bubble ${s?"ai-patch":"ai"}`,children:a.jsxs("div",{className:`chat-sdk__bubble-body ${n.isStreaming?"streaming":""}`,children:[s&&a.jsx("div",{className:"chat-sdk__suggestion-text",children:a.jsx(Ht,{instructionId:n.instructionId})}),s&&((r=n.patchData)!=null&&r.originalText)?a.jsxs("div",{className:"chat-sdk__patch",children:[a.jsx("div",{className:"chat-sdk__patch-label chat-sdk__patch-label--original",children:"Original"}),a.jsx("div",{className:"chat-sdk__patch-block chat-sdk__patch-block--original",children:n.patchData.originalText}),a.jsx("div",{className:"chat-sdk__patch-label chat-sdk__patch-label--improved",children:"Suggested"}),a.jsxs("div",{className:"chat-sdk__patch-block chat-sdk__patch-block--improved",children:[n.patchData.improvedText,n.isStreaming&&a.jsx(se,{})]})]}):a.jsxs(a.Fragment,{children:[a.jsx("div",{children:n.content}),t&&a.jsx(se,{}),n.isStreaming&&!t&&a.jsx(se,{})]})]})})}function Mt(){return a.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("circle",{cx:"12",cy:"12",r:"10"}),a.jsx("path",{d:"m15 9-6 6"}),a.jsx("path",{d:"m9 9 6 6"})]})}function Ft(){return a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a.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"}),a.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"}),a.jsx("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),a.jsx("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),a.jsx("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),a.jsx("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),a.jsx("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),a.jsx("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),a.jsx("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]})}function ke(n){const e=new Date,t=new Date(e.getFullYear(),e.getMonth(),e.getDate()),s=new Date(t.getTime()-24*60*60*1e3),i=new Date(n.getFullYear(),n.getMonth(),n.getDate()),r=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1});if(i.getTime()===t.getTime())return r;if(i.getTime()===s.getTime())return`Yesterday, ${r}`;{const o=n.getDate(),u=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][n.getMonth()];return`${o} ${u}, ${r}`}}const z=["I have a suggestion for you","Here is something you might like","How about this?"];function Ht({instructionId:n}){const e=R.useMemo(()=>{if(n){let t=0;for(let s=0;s<n.length;s++)t=(t*31+n.charCodeAt(s))%z.length;return Math.abs(t)%z.length}return Math.floor(Math.random()*z.length)},[n]);return a.jsx(a.Fragment,{children:z[e]})}function Vt(){return a.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"5"}),a.jsx("polyline",{points:"5 12 12 5 19 12"})]})}function Kt(){return a.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function se(){return a.jsxs("span",{className:"chat-sdk__stream",children:[a.jsx("span",{}),a.jsx("span",{}),a.jsx("span",{})]})}const zt=".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}";exports.ChatProvider=Ut;exports.ChatWidget=Ie;exports.style=zt;exports.useChat=De;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("react/jsx-runtime"),R=require("react"),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 W=Object.create(null);Object.keys(L).forEach(n=>{W[L[n]]=n});const ie={type:"error",data:"parser error"},xe=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",we=typeof ArrayBuffer=="function",ve=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n&&n.buffer instanceof ArrayBuffer,le=({type:n,data:e},t,s)=>xe&&e instanceof Blob?t?s(e):_e(e,s):we&&(e instanceof ArrayBuffer||ve(e))?t?s(e):_e(new Blob([e]),s):s(L[n]+(e||"")),_e=(n,e)=>{const t=new FileReader;return t.onload=function(){const s=t.result.split(",")[1];e("b"+(s||""))},t.readAsDataURL(n)};function me(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let ee;function qe(n,e){if(xe&&n.data instanceof Blob)return n.data.arrayBuffer().then(me).then(e);if(we&&(n.data instanceof ArrayBuffer||ve(n.data)))return e(me(n.data));le(n,!1,t=>{ee||(ee=new TextEncoder),e(ee.encode(t))})}const ye="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",H=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let n=0;n<ye.length;n++)H[ye.charCodeAt(n)]=n;const je=n=>{let e=n.length*.75,t=n.length,s,i=0,r,o,h,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)r=H[n.charCodeAt(s)],o=H[n.charCodeAt(s+1)],h=H[n.charCodeAt(s+2)],d=H[n.charCodeAt(s+3)],u[i++]=r<<2|o>>4,u[i++]=(o&15)<<4|h>>2,u[i++]=(h&3)<<6|d&63;return l},Me=typeof ArrayBuffer=="function",ue=(n,e)=>{if(typeof n!="string")return{type:"message",data:Ee(n,e)};const t=n.charAt(0);return t==="b"?{type:"message",data:Fe(n.substring(1),e)}:W[t]?n.length>1?{type:W[t],data:n.substring(1)}:{type:W[t]}:ie},Fe=(n,e)=>{if(Me){const t=je(n);return Ee(t,e)}else return{base64:!0,data:n}},Ee=(n,e)=>{switch(e){case"blob":return n instanceof Blob?n:new Blob([n]);case"arraybuffer":default:return n instanceof ArrayBuffer?n:n.buffer}},Te="",Ve=(n,e)=>{const t=n.length,s=new Array(t);let i=0;n.forEach((r,o)=>{le(r,!1,h=>{s[o]=h,++i===t&&e(s.join(Te))})})},He=(n,e)=>{const t=n.split(Te),s=[];for(let i=0;i<t.length;i++){const r=ue(t[i],e);if(s.push(r),r.type==="error")break}return s};function Ke(){return new TransformStream({transform(n,e){qe(n,t=>{const s=t.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const r=new DataView(i.buffer);r.setUint8(0,126),r.setUint16(1,s)}else{i=new Uint8Array(9);const r=new DataView(i.buffer);r.setUint8(0,127),r.setBigUint64(1,BigInt(s))}n.data&&typeof n.data!="string"&&(i[0]|=128),e.enqueue(i),e.enqueue(t)})}})}let te;function K(n){return n.reduce((e,t)=>e+t.length,0)}function z(n,e){if(n[0].length===e)return n.shift();const t=new Uint8Array(e);let s=0;for(let i=0;i<e;i++)t[i]=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){te||(te=new TextDecoder);const t=[];let s=0,i=-1,r=!1;return new TransformStream({transform(o,h){for(t.push(o);;){if(s===0){if(K(t)<1)break;const d=z(t,1);r=(d[0]&128)===128,i=d[0]&127,i<126?s=3:i===126?s=1:s=2}else if(s===1){if(K(t)<2)break;const d=z(t,2);i=new DataView(d.buffer,d.byteOffset,d.length).getUint16(0),s=3}else if(s===2){if(K(t)<8)break;const d=z(t,8),l=new DataView(d.buffer,d.byteOffset,d.length),u=l.getUint32(0);if(u>Math.pow(2,21)-1){h.enqueue(ie);break}i=u*Math.pow(2,32)+l.getUint32(4),s=3}else{if(K(t)<i)break;const d=z(t,i);h.enqueue(ue(r?d:te.decode(d),e)),s=0}if(i===0||i>n){h.enqueue(ie);break}}}})}const Re=4;function T(n){if(n)return $e(n)}function $e(n){for(var e in T.prototype)n[e]=T.prototype[e];return n}T.prototype.on=T.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};T.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};T.prototype.off=T.prototype.removeListener=T.prototype.removeAllListeners=T.prototype.removeEventListener=function(n,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+n];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;for(var s,i=0;i<t.length;i++)if(s=t[i],s===e||s.fn===e){t.splice(i,1);break}return t.length===0&&delete this._callbacks["$"+n],this};T.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,i=t.length;s<i;++s)t[s].apply(this,e)}return this};T.prototype.emitReserved=T.prototype.emit;T.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};T.prototype.hasListeners=function(n){return!!this.listeners(n).length};const G=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),N=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),We="arraybuffer";function Se(n,...e){return e.reduce((t,s)=>(n.hasOwnProperty(s)&&(t[s]=n[s]),t),{})}const Qe=N.setTimeout,Ye=N.clearTimeout;function Z(n,e){e.useNativeTimers?(n.setTimeoutFn=Qe.bind(N),n.clearTimeoutFn=Ye.bind(N)):(n.setTimeoutFn=N.setTimeout.bind(N),n.clearTimeoutFn=N.clearTimeout.bind(N))}const Je=1.33;function Xe(n){return typeof n=="string"?Ge(n):Math.ceil((n.byteLength||n.size)*Je)}function Ge(n){let e=0,t=0;for(let s=0,i=n.length;s<i;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 Ne(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Ze(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function et(n){let e={},t=n.split("&");for(let s=0,i=t.length;s<i;s++){let r=t[s].split("=");e[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return e}class tt extends Error{constructor(e,t,s){super(e),this.description=t,this.context=s,this.type="TransportError"}}class de extends T{constructor(e){super(),this.writable=!1,Z(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 tt(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=ue(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=Ze(e);return t.length?"?"+t:""}}class st extends de{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)};He(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,Ve(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]=Ne()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let Ce=!1;try{Ce=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const nt=Ce;function it(){}class rt extends st{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let s=location.port;s||(s=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||s!==e.port}}doWrite(e,t){const s=this.request({method:"POST",data:e});s.on("success",t),s.on("error",(i,r)=>{this.onError("xhr post error",i,r)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,s)=>{this.onError("xhr poll error",t,s)}),this.pollXhr=e}}class P extends T{constructor(e,t,s){super(),this.createRequest=e,Z(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=Se(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(t);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&s.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var i;s.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=P.requestsCount++,P.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=it,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete P.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()}}P.requestsCount=0;P.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",ke);else if(typeof addEventListener=="function"){const n="onpagehide"in N?"pagehide":"unload";addEventListener(n,ke,!1)}}function ke(){for(let n in P.requests)P.requests.hasOwnProperty(n)&&P.requests[n].abort()}const ot=function(){const n=Ae({xdomain:!1});return n&&n.responseType!==null}();class ct extends rt{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=ot&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new P(Ae,this.uri(),e)}}function Ae(n){const e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||nt))return new XMLHttpRequest}catch{}if(!e)try{return new N[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Oe=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class at extends de{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,s=Oe?{}:Se(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,s)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],i=t===e.length-1;le(s,this.supportsBinary,r=>{try{this.doWrite(s,r)}catch{}i&&G(()=>{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]=Ne()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const se=N.WebSocket||N.MozWebSocket;class ht extends at{createSocket(e,t,s){return Oe?new se(e,t,s):t?new se(e,t):new se(e)}doWrite(e,t){this.ws.send(t)}}class lt extends de{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(),i=Ke();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const r=()=>{s.read().then(({done:h,value:d})=>{h||(this.onPacket(d),r())}).catch(h=>{})};r();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const s=e[t],i=t===e.length-1;this._writer.write(s).then(()=>{i&&G(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const ut={websocket:ht,webtransport:lt,polling:ct},dt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ft=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function re(n){if(n.length>8e3)throw"URI too long";const e=n,t=n.indexOf("["),s=n.indexOf("]");t!=-1&&s!=-1&&(n=n.substring(0,t)+n.substring(t,s).replace(/:/g,";")+n.substring(s,n.length));let i=dt.exec(n||""),r={},o=14;for(;o--;)r[ft[o]]=i[o]||"";return t!=-1&&s!=-1&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=pt(r,r.path),r.queryKey=gt(r,r.query),r}function pt(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 gt(n,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,i,r){i&&(t[i]=r)}),t}const oe=typeof addEventListener=="function"&&typeof removeEventListener=="function",Q=[];oe&&addEventListener("offline",()=>{Q.forEach(n=>n())},!1);class I extends T{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=re(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=re(t.host).host);Z(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(s=>{const i=s.prototype.name;this.transports.push(i),this._transportsByName[i]=s}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=et(this.opts.query)),oe&&(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"})},Q.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=Re,t.transport=e,this.id&&(t.sid=this.id);const s=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](s)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&I.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",I.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 i=this.writeBuffer[s].data;if(i&&(t+=Xe(i)),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,G(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,s){return this._sendPacket("message",e,t,s),this}send(e,t,s){return this._sendPacket("message",e,t,s),this}_sendPacket(e,t,s,i){if(typeof t=="function"&&(i=t,t=void 0),typeof s=="function"&&(i=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const r={type:e,data:t,options:s};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},s=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():e()}):this.upgrading?s():e()),this}_onError(e){if(I.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(),oe&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=Q.indexOf(this._offlineEventListener);s!==-1&&Q.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}I.protocol=Re;class _t extends I{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;I.priorWebsocketSuccess=!1;const i=()=>{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;I.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 _=new Error("probe error");_.transport=t.name,this.emitReserved("upgradeError",_)}}))};function r(){s||(s=!0,u(),t.close(),t=null)}const o=f=>{const _=new Error("probe error: "+f);_.transport=t.name,r(),this.emitReserved("upgradeError",_)};function h(){o("transport closed")}function d(){o("socket closed")}function l(f){t&&f.name!==t.name&&r()}const u=()=>{t.removeListener("open",i),t.removeListener("error",o),t.removeListener("close",h),this.off("close",d),this.off("upgrading",l)};t.once("open",i),t.once("error",o),t.once("close",h),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 mt=class extends _t{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(i=>ut[i]).filter(i=>!!i)),super(e,s)}};function yt(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=re(n)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const r=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+r+":"+s.port+e,s.href=s.protocol+"://"+r+(t&&t.port===s.port?"":":"+s.port),s}const kt=typeof ArrayBuffer=="function",bt=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,Pe=Object.prototype.toString,xt=typeof Blob=="function"||typeof Blob<"u"&&Pe.call(Blob)==="[object BlobConstructor]",wt=typeof File=="function"||typeof File<"u"&&Pe.call(File)==="[object FileConstructor]";function fe(n){return kt&&(n instanceof ArrayBuffer||bt(n))||xt&&n instanceof Blob||wt&&n instanceof File}function Y(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,s=n.length;t<s;t++)if(Y(n[t]))return!0;return!1}if(fe(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return Y(n.toJSON(),!0);for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&Y(n[t]))return!0;return!1}function vt(n){const e=[],t=n.data,s=n;return s.data=ce(t,e),s.attachments=e.length,{packet:s,buffers:e}}function ce(n,e){if(!n)return n;if(fe(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]=ce(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]=ce(n[s],e));return t}return n}function Et(n,e){return n.data=ae(n.data,e),delete n.attachments,n}function ae(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]=ae(n[t],e);else if(typeof n=="object")for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=ae(n[t],e));return n}const Le=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],Tt=5;var m;(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"})(m||(m={}));class Rt{constructor(e){this.replacer=e}encode(e){return(e.type===m.EVENT||e.type===m.ACK)&&Y(e)?this.encodeAsBinary({type:e.type===m.EVENT?m.BINARY_EVENT:m.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===m.BINARY_EVENT||e.type===m.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),i=t.buffers;return i.unshift(s),i}}class pe extends T{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===m.BINARY_EVENT;s||t.type===m.BINARY_ACK?(t.type=s?m.EVENT:m.ACK,this.reconstructor=new St(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(fe(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(m[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===m.BINARY_EVENT||s.type===m.BINARY_ACK){const r=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const o=e.substring(r,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");s.attachments=Number(o)}if(e.charAt(t+1)==="/"){const r=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););s.nsp=e.substring(r,t)}else s.nsp="/";const i=e.charAt(t+1);if(i!==""&&Number(i)==i){const r=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(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(pe.isPayloadValid(s.type,r))s.data=r;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 m.CONNECT:return X(t);case m.DISCONNECT:return t===void 0;case m.CONNECT_ERROR:return typeof t=="string"||X(t);case m.EVENT:case m.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Le.indexOf(t[0])===-1);case m.ACK:case m.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=Et(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 X(n){return Object.prototype.toString.call(n)==="[object Object]"}function Ot(n,e){switch(n){case m.CONNECT:return e===void 0||X(e);case m.DISCONNECT:return e===void 0;case m.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Le.indexOf(e[0])===-1);case m.ACK:return Array.isArray(e);case m.CONNECT_ERROR:return typeof e=="string"||X(e);default:return!1}}function Pt(n){return Nt(n.nsp)&&At(n.id)&&Ot(n.type,n.data)}const Lt=Object.freeze(Object.defineProperty({__proto__:null,Decoder:pe,Encoder:Rt,get PacketType(){return m},isPacketValid:Pt,protocol:Tt},Symbol.toStringTag,{value:"Module"}));function O(n,e,t){return n.on(e,t),function(){n.off(e,t)}}const Bt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Be extends T{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,i,r;if(Bt.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:m.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 h=(i=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||i===void 0?void 0:i.writable,d=this.connected&&!(!((r=this.io.engine)===null||r===void 0)&&r._hasPingExpired());return this.flags.volatile&&!h||(d?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var s;const i=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(i===void 0){this.acks[e]=t;return}const r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let h=0;h<this.sendBuffer.length;h++)this.sendBuffer[h].id===e&&this.sendBuffer.splice(h,1);t.call(this,new Error("operation has timed out"))},i),o=(...h)=>{this.io.clearTimeoutFn(r),t.apply(this,h)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((s,i)=>{const r=(o,h)=>o?i(o):s(h);r.withError=!0,t.push(r),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...r)=>(this._queue[0],i!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(i)):(this._queue.shift(),t&&t(null,...r)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:m.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 m.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 m.EVENT:case m.BINARY_EVENT:this.onevent(e);break;case m.ACK:case m.BINARY_ACK:this.onack(e);break;case m.DISCONNECT:this.ondisconnect();break;case m.CONNECT_ERROR:this.destroy();const s=new Error(e.data.message);s.data=e.data.data,this.emitReserved("connect_error",s);break}}onevent(e){const t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const s of t)s.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let s=!1;return function(...i){s||(s=!0,t.packet({type:m.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._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:m.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 M(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}M.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};M.prototype.reset=function(){this.attempts=0};M.prototype.setMin=function(n){this.ms=n};M.prototype.setMax=function(n){this.max=n};M.prototype.setJitter=function(n){this.jitter=n};class he extends T{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,Z(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 M({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||Lt;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new mt(this.uri,this.opts);const t=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const i=O(t,"open",function(){s.onopen(),e&&e()}),r=h=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",h),e?e(h):this.maybeReconnectOnOpen()},o=O(t,"error",r);if(this._timeout!==!1){const h=this._timeout,d=this.setTimeoutFn(()=>{i(),r(new Error("timeout")),t.close()},h);this.opts.autoUnref&&d.unref(),this.subs.push(()=>{this.clearTimeoutFn(d)})}return this.subs.push(i),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(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){G(()=>{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 Be(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(i=>{i?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):e.onreconnect()}))},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const V={};function J(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};const t=yt(n,e.path||"/socket.io"),s=t.source,i=t.id,r=t.path,o=V[i]&&r in V[i].nsps,h=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let d;return h?d=new he(s,e):(V[i]||(V[i]=new he(s,e)),d=V[i]),t.query&&!e.query&&(e.query=t.queryKey),d.socket(t.path,e)}Object.assign(J,{Manager:he,Socket:Be,io:J,connect:J});function S(){return`${Date.now().toString(36)}-${Math.random().toString(16).slice(2,8)}`}class Dt{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(i=>{var r,o;try{i(t)}catch(h){(o=(r=this.config.logger)==null?void 0:r.error)==null||o.call(r,`chat-sdk listener error for ${e}`,h)}})}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(i){return(s=(t=this.config.logger)==null?void 0:t.warn)==null||s.call(t,"chat-sdk token provider failed",i),null}}async connect(){var r;if((r=this.socket)!=null&&r.connected)return;const e=new URL(this.config.websocketUrl),t=e.pathname==="/"?"/socket.io":e.pathname,s=e.origin,i=await this.getToken();return this.socket=J(s,{path:t,transports:["websocket","polling"],autoConnect:!1,reconnection:!1,auth:i?{token:i}:void 0,withCredentials:!0}),this.registerSocketEvents(),this.setConnection({connected:!1,connecting:!0}),new Promise((o,h)=>{const d=setTimeout(()=>{h(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(),h(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 r,o;if(!((r=this.socket)!=null&&r.connected))throw new Error("Not connected");this.lastContext=t;const s=await this.getToken(),i={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("INSTRUCTION_SUBMIT",i)}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,i,r,o,h;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();(r=(i=this.config.logger)==null?void 0:i.log)==null||r.call(i,"[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}),(h=(o=this.config.logger)==null?void 0:o.log)==null||h.call(o,"[chat-sdk] PATCH_DECISION emitted successfully")}async requestPageTranslation(e){var i,r,o,h,d;if(!((i=this.socket)!=null&&i.connected))throw new Error("Not connected");const t=await this.getToken(),s={...e,access_token:t||void 0};(o=(r=this.config.logger)==null?void 0:r.log)==null||o.call(r,"[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=(h=this.config.logger)==null?void 0:h.log)==null||d.call(h,"[chat-sdk] PAGE_TRANSLATION_REQUEST emitted successfully")}async requestBulkTranslation(e){var i,r,o,h,d;if(!((i=this.socket)!=null&&i.connected))throw new Error("Not connected");const t=await this.getToken(),s={...e,access_token:t||void 0};(o=(r=this.config.logger)==null?void 0:r.log)==null||o.call(r,"[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=(h=this.config.logger)==null?void 0:h.log)==null||d.call(h,"[chat-sdk] BULK_TRANSLATION_REQUEST emitted successfully")}async cancelBulkTranslation(e){var s,i,r,o,h;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();(r=(i=this.config.logger)==null?void 0:i.log)==null||r.call(i,"[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}),(h=(o=this.config.logger)==null?void 0:o.log)==null||h.call(o,"[chat-sdk] CANCEL_BULK_TRANSLATION_REQUEST emitted successfully")}async requestLearnedRules(e){var s,i,r,o,h;if(!((s=this.socket)!=null&&s.connected))throw new Error("Not connected");const t=await this.getToken();(r=(i=this.config.logger)==null?void 0:i.log)==null||r.call(i,"[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}),(h=(o=this.config.logger)==null?void 0:o.log)==null||h.call(o,"[chat-sdk] LEARNED_RULES_REQUEST emitted successfully")}async updateRules(e,t){var i,r,o,h,d;if(!((i=this.socket)!=null&&i.connected))throw new Error("Not connected");const s=await this.getToken();(o=(r=this.config.logger)==null?void 0:r.log)==null||o.call(r,"[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=(h=this.config.logger)==null?void 0:h.log)==null||d.call(h,"[chat-sdk] UPDATE_RULES_REQUEST emitted successfully")}joinTranslation(e){var t;(t=this.socket)!=null&&t.connected&&this.socket.emit("JOIN_TRANSLATION",{trans_doc_id:e})}leaveTranslation(){var e;(e=this.socket)!=null&&e.connected&&this.socket.emit("LEAVE_TRANSLATION",{})}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_RESPONSE",e=>{var t,s;(s=(t=this.config.logger)==null?void 0:t.log)==null||s.call(t,"[chat-sdk] Received INSTRUCTION_RESPONSE:",{instruction_id:e.instruction_id,status:e.status,response_type:e.response_type}),this.emit("instruction-response",e)}),this.socket.on("INSTRUCTION_ERROR",e=>{this.emit("instruction-error",e)}),this.socket.on("PAGE_TRANSLATION_RESPONSE",e=>{var t,s,i,r,o,h,d,l,u,f,_;(i=(t=this.config.logger)==null?void 0:t.log)==null||i.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=(r=this.config.logger)==null?void 0:r.log)==null||o.call(r,"[chat-sdk] Emitted page-translation-response internally"),this.config.onPageTranslationResponse?((d=(h=this.config.logger)==null?void 0:h.log)==null||d.call(h,"[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")):(_=(f=this.config.logger)==null?void 0:f.log)==null||_.call(f,"[chat-sdk] No onPageTranslationResponse callback configured")}),this.socket.on("BULK_TRANSLATION_RESPONSE",e=>{var t,s,i,r,o,h,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),(r=(i=this.config.logger)==null?void 0:i.log)==null||r.call(i,"[chat-sdk] Emitted bulk-translation-response internally"),this.config.onBulkTranslationResponse?((h=(o=this.config.logger)==null?void 0:o.log)==null||h.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("PRESENCE_UPDATE",e=>{this.emit("presence-update",e),this.config.onPresenceUpdate&&this.config.onPresenceUpdate(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 i,r;return(r=(i=this.config.logger)==null?void 0:i.error)==null?void 0:r.call(i,"chat-sdk reconnect failed",s)})},this.config.reconnectDelayMs)}}function It(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:S(),type:"rule-learned",content:e.response_content||"Rule learned",ruleSummary:e.rule_summary??void 0}];const s={...t,id:S(),type:"user",content:e.instruction,contextText:e.region_text??void 0},i=[];return e.response_content&&e.response_type==="chat"&&i.push({...t,id:S(),type:"ai-chat",content:e.response_content}),e.response_content&&e.response_type==="patch"&&i.push({...t,id:S(),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,...i]}).flat().sort((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())}const De=R.createContext(null),Ut={connected:!1,connecting:!1};function qt({config:n,children:e}){const t=R.useRef(null),s=R.useRef(new Map),[i,r]=R.useState({messages:[],connection:Ut,latestPatchOffer:null,isSubmitting:!1,activeUsers:[]}),o=R.useMemo(()=>({reconnectAttempts:5,reconnectDelayMs:1500,...n}),[n]);R.useEffect(()=>{const l=new Dt(o);t.current=l;const u=l.on("connection",c=>{r(p=>({...p,connection:c}))}),f=l.on("chat-response",c=>{r(p=>{const y=p.messages.filter(w=>w.type!=="loading");let g=y.find(w=>w.instructionId===c.instruction_id&&w.type==="ai-chat");g||(g={id:S(),type:"ai-chat",content:"",timestamp:new Date,instructionId:c.instruction_id,pageNum:c.page_num,isStreaming:!0},y.push(g));const x={...g,content:(g.content||"")+(c.chunk_text||""),isStreaming:!c.is_final},E=y.map(w=>w.id===g.id?x:w);return{...p,messages:E,isSubmitting:c.is_final?!1:p.isSubmitting}})}),_=l.on("patch-offer",c=>{var g;const p=`${c.trans_doc_id}-${c.instruction_id}`,y=s.current.get(p)??{trans_doc_id:c.trans_doc_id,page_num:c.page_num,instruction_id:c.instruction_id,original_text:c.region_original_text||"",highlighted_region:c.region_coordinates,new_suggestion:"",is_page_level:!c.region_coordinates,selection_id:c.selection_id};if(y.new_suggestion+=c.region_replacement_text_chunk||"",c.selection_id&&!y.selection_id&&(y.selection_id=c.selection_id),s.current.set(p,y),r(x=>{var ge;const E=x.messages.filter(q=>q.type!=="loading");let w=E.find(q=>q.instructionId===c.instruction_id&&q.type==="ai-patch");w||(w={id:S(),type:"ai-patch",content:"",timestamp:new Date,instructionId:c.instruction_id,pageNum:c.page_num,isStreaming:!0,patchData:{originalText:c.region_original_text,improvedText:"",regionText:c.region_original_text,isComplete:!1}},E.push(w));const A={...w,content:(w.content||"")+(c.region_replacement_text_chunk||""),isStreaming:!c.is_final,patchData:{...w.patchData,improvedText:(((ge=w.patchData)==null?void 0:ge.improvedText)||"")+(c.region_replacement_text_chunk||""),regionText:c.region_original_text,isComplete:c.is_final}},U=E.map(q=>q.id===w.id?A:q);return{...x,messages:U,isSubmitting:c.is_final?!1:x.isSubmitting}}),c.is_final){const x=s.current.get(p);x&&((g=o.onPatchOffer)==null||g.call(o,x),r(E=>({...E,latestPatchOffer:x}))),s.current.delete(p)}}),k=l.on("chat-history-response",c=>{if(c.status==="success"){const p=It(c.messages);r(y=>({...y,messages:p}))}else r(p=>({...p,messages:[...p.messages,{id:S(),type:"system",content:c.error||"Failed to load chat history",timestamp:new Date}]}))}),b=l.on("instruction-response",c=>{var p;if(c.status==="error"){r(y=>({...y,isSubmitting:!1,messages:[...y.messages.filter(g=>g.type!=="loading"),{id:S(),type:"error",content:c.error||"Instruction processing failed",timestamp:new Date,instructionId:c.instruction_id}]}));return}if(c.response_type==="patch"){const y={trans_doc_id:c.trans_doc_id,page_num:c.page_num??0,instruction_id:c.instruction_id,original_text:c.region_text||"",highlighted_region:c.region_coordinates,new_suggestion:(c.response_content||"").trim(),is_page_level:!c.region_coordinates,selection_id:c.selection_id};r(g=>({...g,isSubmitting:!1,latestPatchOffer:y,messages:[...g.messages.filter(x=>x.type!=="loading"),{id:S(),type:"ai-patch",content:c.response_content||"",timestamp:new Date,instructionId:c.instruction_id,pageNum:c.page_num??void 0,isStreaming:!1,patchData:{originalText:c.region_text??void 0,improvedText:c.response_content||"",regionText:c.region_text??void 0,isComplete:!0}}]})),(p=o.onPatchOffer)==null||p.call(o,y)}else r(y=>({...y,isSubmitting:!1,messages:[...y.messages.filter(g=>g.type!=="loading"),{id:S(),type:"ai-chat",content:c.response_content||"",timestamp:new Date,instructionId:c.instruction_id,pageNum:c.page_num??void 0,isStreaming:!1}]}))}),v=l.on("instruction-error",c=>{r(p=>({...p,isSubmitting:!1,messages:[...p.messages,{id:S(),type:"error",content:c.error,timestamp:new Date}]}))}),B=l.on("page-translation-response",c=>{var p,y,g,x,E,w,A,U;(y=(p=o.logger)==null?void 0:p.log)==null||y.call(p,"[chat-sdk][ChatProvider] Received page-translation-response event:",{trans_doc_id:c.trans_doc_id,page_num:c.page_num,status:c.status,has_content:!!c.trans_page_content,error:c.error}),o.onPageTranslationResponse?((x=(g=o.logger)==null?void 0:g.log)==null||x.call(g,"[chat-sdk][ChatProvider] Invoking onPageTranslationResponse callback from config"),o.onPageTranslationResponse(c),(w=(E=o.logger)==null?void 0:E.log)==null||w.call(E,"[chat-sdk][ChatProvider] onPageTranslationResponse callback completed")):(U=(A=o.logger)==null?void 0:A.log)==null||U.call(A,"[chat-sdk][ChatProvider] No onPageTranslationResponse callback in config")}),C=l.on("bulk-translation-response",c=>{var p,y,g,x,E,w,A,U;(y=(p=o.logger)==null?void 0:p.log)==null||y.call(p,"[chat-sdk][ChatProvider] Received bulk-translation-response event:",{trans_doc_id:c.trans_doc_id,status:c.status,completed_pages:c.completed_pages,total_pages:c.total_pages,current_page:c.current_page,error:c.error}),o.onBulkTranslationResponse?((x=(g=o.logger)==null?void 0:g.log)==null||x.call(g,"[chat-sdk][ChatProvider] Invoking onBulkTranslationResponse callback from config"),o.onBulkTranslationResponse(c),(w=(E=o.logger)==null?void 0:E.log)==null||w.call(E,"[chat-sdk][ChatProvider] onBulkTranslationResponse callback completed")):(U=(A=o.logger)==null?void 0:A.log)==null||U.call(A,"[chat-sdk][ChatProvider] No onBulkTranslationResponse callback in config")}),D=l.on("rule-learned",c=>{var p,y;(y=(p=o.logger)==null?void 0:p.log)==null||y.call(p,"[chat-sdk][ChatProvider] Received rule-learned event:",{trans_doc_id:c.trans_doc_id,instruction_id:c.instruction_id,rule_summary:c.rule_summary}),r(g=>({...g,messages:[...g.messages,{id:S(),type:"rule-learned",content:c.message||"Rule learned",timestamp:new Date,instructionId:c.instruction_id,ruleSummary:c.rule_summary}]})),o.onRuleLearned&&o.onRuleLearned(c)}),j=l.on("learned-rules-response",c=>{var p,y;(y=(p=o.logger)==null?void 0:p.log)==null||y.call(p,"[chat-sdk][ChatProvider] Received learned-rules-response event:",{trans_doc_id:c.trans_doc_id,has_rules:c.has_rules,status:c.status}),o.onLearnedRulesResponse&&o.onLearnedRulesResponse(c)}),F=l.on("presence-update",c=>{r(p=>({...p,activeUsers:c.users}))});return l.connect().then(()=>{const c=o.contextProvider();if(c)return l.requestChatHistory(c)}).catch(c=>{var p,y;return(y=(p=o.logger)==null?void 0:p.warn)==null?void 0:y.call(p,"chat-sdk connect failed",c)}),()=>{u(),f(),_(),k(),b(),v(),B(),C(),D(),j(),F(),l.disconnect()}},[o]);const h=R.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");r(_=>{var k;return{..._,isSubmitting:!0,messages:[..._.messages,{id:S(),type:"user",content:l,timestamp:new Date,pageNum:f.page_num,contextText:(k=f.highlighted_region)==null?void 0:k.text},{id:S(),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");r(_=>{var k;return{..._,isSubmitting:!0,messages:[..._.messages,{id:S(),type:"user",content:l,timestamp:new Date,pageNum:u.page_num,contextText:(k=u.highlighted_region)==null?void 0:k.text},{id:S(),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,_,k){var v,B,C,D;const b=t.current;if(!b)throw new Error("SDK not ready");(B=(v=o.logger)==null?void 0:v.log)==null||B.call(v,"[chat-sdk][ChatProvider] sendPatchDecision called:",{trans_doc_id:l,page_num:u,instruction_id:f,decision:_,remember_this:k}),await b.sendPatchDecision({trans_doc_id:l,page_num:u,instruction_id:f,decision:_,remember_this:k}),(D=(C=o.logger)==null?void 0:C.log)==null||D.call(C,"[chat-sdk][ChatProvider] sendPatchDecision completed"),r(j=>({...j,latestPatchOffer:null}))},async requestPageTranslation(l,u){var _,k,b,v;const f=t.current;if(!f)throw new Error("SDK not ready");return(k=(_=o.logger)==null?void 0:_.log)==null||k.call(_,"[chat-sdk][ChatProvider] requestPageTranslation called:",{trans_doc_id:l,page_num:u}),await f.requestPageTranslation({trans_doc_id:l,page_num:u}),(v=(b=o.logger)==null?void 0:b.log)==null||v.call(b,"[chat-sdk][ChatProvider] requestPageTranslation request sent"),!0},async requestBulkTranslation(l,u){var _,k,b,v;const f=t.current;if(!f)throw new Error("SDK not ready");return(k=(_=o.logger)==null?void 0:_.log)==null||k.call(_,"[chat-sdk][ChatProvider] requestBulkTranslation called:",{trans_doc_id:l,page_list:u}),await f.requestBulkTranslation({trans_doc_id:l,page_list:u}),(v=(b=o.logger)==null?void 0:b.log)==null||v.call(b,"[chat-sdk][ChatProvider] requestBulkTranslation request sent"),!0},async cancelBulkTranslation(l){var f,_,k,b;const u=t.current;if(!u)throw new Error("SDK not ready");return(_=(f=o.logger)==null?void 0:f.log)==null||_.call(f,"[chat-sdk][ChatProvider] cancelBulkTranslation called:",{trans_doc_id:l}),await u.cancelBulkTranslation(l),(b=(k=o.logger)==null?void 0:k.log)==null||b.call(k,"[chat-sdk][ChatProvider] cancelBulkTranslation request sent"),!0},async requestLearnedRules(l){var f,_,k,b;const u=t.current;if(!u)throw new Error("SDK not ready");(_=(f=o.logger)==null?void 0:f.log)==null||_.call(f,"[chat-sdk][ChatProvider] requestLearnedRules called:",{trans_doc_id:l}),await u.requestLearnedRules(l),(b=(k=o.logger)==null?void 0:k.log)==null||b.call(k,"[chat-sdk][ChatProvider] requestLearnedRules request sent")},async updateRules(l,u){var _,k,b,v;const f=t.current;if(!f)throw new Error("SDK not ready");(k=(_=o.logger)==null?void 0:_.log)==null||k.call(_,"[chat-sdk][ChatProvider] updateRules called:",{trans_doc_id:l,rules_text_length:u.length}),await f.updateRules(l,u),(v=(b=o.logger)==null?void 0:b.log)==null||v.call(b,"[chat-sdk][ChatProvider] updateRules request sent")},joinTranslation(l){var u;(u=t.current)==null||u.joinTranslation(l)},leaveTranslation(){var l;(l=t.current)==null||l.leaveTranslation(),r(u=>({...u,activeUsers:[]}))},clearMessages(){r(l=>({...l,messages:[]}))},clearSelection(){var l;(l=o.onClearSelection)==null||l.call(o)}}),[o]),d=R.useMemo(()=>({...i,...h}),[i,h]);return a.jsx(De.Provider,{value:d,children:e})}function jt(){const n=R.useContext(De);if(!n)throw new Error("useChat must be used within ChatProvider");return n}function Ie(){return jt()}const Ue=R.forwardRef(({title:n="AI Assistance",placeholder:e="Ask anything...",height:t="500px",onClose:s},i)=>{const{messages:r,connection:o,submitInstruction:h,submitInstructionWithContext:d,isSubmitting:l,clearSelection:u}=Ie(),[f,_]=R.useState(""),[k,b]=R.useState(null),[v,B]=R.useState(null),C=R.useRef(null),D=R.useRef(null),j=!o.connected||l;R.useImperativeHandle(i,()=>({setContext:({text:g,context:x})=>{B(g),b(x),setTimeout(()=>{var E;(E=D.current)==null||E.focus()},100)},focusInput:()=>{var g;(g=D.current)==null||g.focus()}}),[]);const F=R.useMemo(()=>[...r].sort((g,x)=>g.timestamp.getTime()-x.timestamp.getTime()),[r]);R.useEffect(()=>{C.current&&(C.current.scrollTop=C.current.scrollHeight)},[F]);const c=async g=>{g.preventDefault();const x=f.trim();x&&(k?(await d(x,k),b(null),B(null)):await h(x),_(""))},p=g=>{g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),c(g))},y=()=>{b(null),B(null),u()};return a.jsxs("div",{className:"chat-sdk",style:{height:t},children:[a.jsxs("div",{className:"chat-sdk__header",children:[a.jsx("div",{className:"chat-sdk__title",children:n}),s&&a.jsx("button",{type:"button",onClick:s,className:"chat-sdk__close-btn",children:a.jsx(Ft,{})})]}),a.jsx("div",{className:"chat-sdk__messages",ref:C,children:F.length===0?a.jsx("div",{className:"chat-sdk__empty",children:"Welcome! Ask anything about the translation."}):F.map(g=>a.jsx(Mt,{message:g},g.id))}),a.jsxs("div",{className:"chat-sdk__composer",children:[a.jsxs("form",{className:"chat-sdk__input-bar",onSubmit:c,children:[v&&a.jsx("div",{className:"chat-sdk__input-context",children:a.jsxs("div",{className:"chat-sdk__context-chip",children:[a.jsx("span",{className:"chat-sdk__context-text",children:v.length>40?`${v.slice(0,40)}…`:v}),a.jsx("button",{type:"button",onClick:y,className:"chat-sdk__context-clear",children:a.jsx(zt,{})})]})}),a.jsx("textarea",{ref:D,className:"chat-sdk__input",placeholder:v?"What would you like to change?":e,value:f,onChange:g=>_(g.target.value),onKeyDown:p,disabled:j,rows:1}),a.jsx("div",{className:"chat-sdk__actions",children:a.jsx("button",{className:"chat-sdk__send",type:"submit",disabled:!f.trim()||j,children:a.jsx(Kt,{})})})]}),o.error&&a.jsxs("div",{className:"chat-sdk__error",children:["⚠️ ",o.error]})]})]})});Ue.displayName="ChatWidget";function Mt({message:n}){var r;const e=n.type==="user",t=n.type==="loading",s=n.type==="ai-patch",i=n.type==="rule-learned";if(e)return a.jsxs("div",{className:"chat-sdk__user-container",children:[n.contextText&&a.jsx("div",{className:"chat-sdk__user-context",children:a.jsx("div",{className:"chat-sdk__context-chip",children:a.jsx("span",{className:"chat-sdk__context-text",children:n.contextText.length>40?`${n.contextText.slice(0,40)}…`:n.contextText})})}),a.jsx("div",{className:"chat-sdk__bubble user",children:a.jsx("div",{className:"chat-sdk__bubble-body",children:n.content})}),a.jsxs("div",{className:"chat-sdk__bubble-meta",children:[n.pageNum!==void 0&&a.jsxs("span",{children:["Page ",n.pageNum]}),n.pageNum!==void 0&&a.jsx("span",{className:"chat-sdk__meta-dot",children:"•"}),a.jsx("span",{children:be(n.timestamp)})]})]});if(i){const o=n.ruleSummary||n.content,h=o.charAt(0).toUpperCase()+o.slice(1);return a.jsxs("div",{className:"chat-sdk__rule-learned-container",children:[a.jsxs("div",{className:"chat-sdk__rule-learned",children:[a.jsx("div",{className:"chat-sdk__rule-learned-icon",children:a.jsx(Vt,{})}),a.jsxs("div",{className:"chat-sdk__rule-learned-body",children:[a.jsx("span",{className:"chat-sdk__rule-learned-title",children:"Memory updated"}),a.jsx("span",{className:"chat-sdk__rule-learned-text",children:h})]})]}),a.jsx("div",{className:"chat-sdk__rule-learned-meta",children:be(n.timestamp)})]})}return a.jsx("div",{className:`chat-sdk__bubble ${s?"ai-patch":"ai"}`,children:a.jsxs("div",{className:`chat-sdk__bubble-body ${n.isStreaming?"streaming":""}`,children:[s&&a.jsx("div",{className:"chat-sdk__suggestion-text",children:a.jsx(Ht,{instructionId:n.instructionId})}),s&&((r=n.patchData)!=null&&r.originalText)?a.jsxs("div",{className:"chat-sdk__patch",children:[a.jsx("div",{className:"chat-sdk__patch-label chat-sdk__patch-label--original",children:"Original"}),a.jsx("div",{className:"chat-sdk__patch-block chat-sdk__patch-block--original",children:n.patchData.originalText}),a.jsx("div",{className:"chat-sdk__patch-label chat-sdk__patch-label--improved",children:"Suggested"}),a.jsxs("div",{className:"chat-sdk__patch-block chat-sdk__patch-block--improved",children:[n.patchData.improvedText,n.isStreaming&&a.jsx(ne,{})]})]}):a.jsxs(a.Fragment,{children:[a.jsx("div",{children:n.content}),t&&a.jsx(ne,{}),n.isStreaming&&!t&&a.jsx(ne,{})]})]})})}function Ft(){return a.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("circle",{cx:"12",cy:"12",r:"10"}),a.jsx("path",{d:"m15 9-6 6"}),a.jsx("path",{d:"m9 9 6 6"})]})}function Vt(){return a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a.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"}),a.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"}),a.jsx("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),a.jsx("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),a.jsx("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),a.jsx("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),a.jsx("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),a.jsx("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),a.jsx("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]})}function be(n){const e=new Date,t=new Date(e.getFullYear(),e.getMonth(),e.getDate()),s=new Date(t.getTime()-24*60*60*1e3),i=new Date(n.getFullYear(),n.getMonth(),n.getDate()),r=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1});if(i.getTime()===t.getTime())return r;if(i.getTime()===s.getTime())return`Yesterday, ${r}`;{const o=n.getDate(),d=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][n.getMonth()];return`${o} ${d}, ${r}`}}const $=["I have a suggestion for you","Here is something you might like","How about this?"];function Ht({instructionId:n}){const e=R.useMemo(()=>{if(n){let t=0;for(let s=0;s<n.length;s++)t=(t*31+n.charCodeAt(s))%$.length;return Math.abs(t)%$.length}return Math.floor(Math.random()*$.length)},[n]);return a.jsx(a.Fragment,{children:$[e]})}function Kt(){return a.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"5"}),a.jsx("polyline",{points:"5 12 12 5 19 12"})]})}function zt(){return a.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function ne(){return a.jsxs("span",{className:"chat-sdk__stream",children:[a.jsx("span",{}),a.jsx("span",{}),a.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}";exports.ChatProvider=qt;exports.ChatWidget=Ue;exports.style=$t;exports.useChat=Ie;
|
|
2
2
|
//# sourceMappingURL=translation-chat-sdk.cjs.js.map
|