translation-chat-sdk 0.2.2 → 0.2.4

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/style.css CHANGED
@@ -1 +1 @@
1
- .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:var(--spacing-2) var(--space-20);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__status{display:flex;align-items:center;gap:6px;color:var(--content-tertiary);font-size:12px}.chat-sdk__status-dot{width:8px;height:8px;border-radius:50%;background:#ef4444}.chat-sdk__status-dot.connected{background:#10b981}.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.user .chat-sdk__bubble-body{color:var(--content-brand1-secondary);font-size:15px;line-height:1.45;white-space:pre-wrap}.chat-sdk__bubble.ai,.chat-sdk__bubble.ai-patch{align-self:flex-start;max-width:90%;display:flex;flex-direction:column}.chat-sdk__bubble-body{display:flex;flex-direction:column;gap:8px;font-size:15px;color:var(--content-primary);line-height:1.5}.chat-sdk__suggestion-text{font-size:13px;color:var(--content-secondary);margin-bottom:0}.chat-sdk__patch{display:flex;flex-direction:column;gap:8px;margin-top:4px}.chat-sdk__patch-label{font-size:12px;color:var(--content-tertiary);font-weight:600}.chat-sdk__patch-block{background:#f3f4f6;border-radius:10px;padding:12px;border:1px solid #e5e7eb;font-size:14px;line-height:1.5;color:var(--content-secondary)}.chat-sdk__composer{padding:var(--spacing-1);background:var(--background-primary)}.chat-sdk__input-bar{display:flex;flex-direction:column;background:#fff;border:1px solid var(--border-secondary);border-radius:var(--radius-large);padding:8px;overflow:hidden}.chat-sdk__input-context{padding:0 4px 8px}.chat-sdk__input-context .chat-sdk__context-chip{background:var(--background-tertiary);padding:8px 12px;border-radius:var(--radius-full);display:inline-flex;align-items:center;gap:8px}.chat-sdk__input-context .chat-sdk__context-text{font-size:14px;line-height:1.45;color:var(--content-primary)}.chat-sdk__context-clear{display:flex;align-items:center;justify-content:center;width:16px;height:16px;padding:0;background:transparent;border:none;color:var(--content-secondary);cursor:pointer;transition:color .15s}.chat-sdk__context-clear:hover{color:var(--content-primary)}.chat-sdk__input{width:100%;border:none;background:transparent;resize:none;min-height:72px;max-height:120px;font-size:15px;font-family:inherit;color:var(--content-primary);outline:none;line-height:1.45;padding:4px 8px}.chat-sdk__input::placeholder{color:var(--content-tertiary)}.chat-sdk__actions{display:flex;align-items:center;justify-content:space-between}.chat-sdk__actions-left{display:flex;align-items:center}.chat-sdk__add-btn{display:flex;align-items:center;justify-content:center;width:28px;height:28px;padding:0;background:transparent;border:none;border-radius:50%;color:var(--content-secondary);cursor:pointer;transition:background .15s,color .15s}.chat-sdk__add-btn:hover:not(:disabled){background:var(--background-tertiary);color:var(--content-primary)}.chat-sdk__add-btn:disabled{opacity:.4;cursor:not-allowed}.chat-sdk__send{display:flex;align-items:center;justify-content:center;width:28px;height:28px;min-width:28px;min-height:28px;background:var(--background-black);color:#fff;border:none;border-radius:50%;cursor:pointer;transition:opacity .2s}.chat-sdk__send:disabled{opacity:.3;cursor:not-allowed}.chat-sdk__send:not(:disabled):hover{opacity:.8}.chat-sdk__error{font-size:12px;color:#dc2626;padding:4px 8px}.chat-sdk__stream{display:inline-flex;gap:4px;vertical-align:middle}.chat-sdk__stream span{width:4px;height:4px;background:currentColor;border-radius:50%;animation:chat-sdk-pulse 1.4s infinite ease-in-out both}.chat-sdk__stream span:nth-child(1){animation-delay:-.32s}.chat-sdk__stream span:nth-child(2){animation-delay:-.16s}@keyframes chat-sdk-pulse{0%,80%,to{transform:scale(0)}40%{transform:scale(1)}}
1
+ .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__status{display:flex;align-items:center;gap:6px;color:var(--content-tertiary);font-size:12px}.chat-sdk__status-dot{width:8px;height:8px;border-radius:50%;background:#ef4444}.chat-sdk__status-dot.connected{background:#10b981}.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.user .chat-sdk__bubble-body{color:var(--content-brand1-secondary);font-size:15px;line-height:1.45;white-space:pre-wrap}.chat-sdk__bubble.ai,.chat-sdk__bubble.ai-patch{align-self:flex-start;max-width:90%;display:flex;flex-direction:column}.chat-sdk__bubble-body{display:flex;flex-direction:column;gap:8px;font-size:15px;color:var(--content-primary);line-height:1.5}.chat-sdk__suggestion-text{font-size:13px;color:var(--content-secondary);margin-bottom:0}.chat-sdk__patch{display:flex;flex-direction:column;gap:8px;margin-top:4px}.chat-sdk__patch-label{font-size:12px;color:var(--content-tertiary);font-weight:600}.chat-sdk__patch-block{background:#f3f4f6;border-radius:10px;padding:12px;border:1px solid #e5e7eb;font-size:14px;line-height:1.5;color:var(--content-secondary)}.chat-sdk__composer{padding:var(--spacing-1);background:var(--background-primary)}.chat-sdk__input-bar{display:flex;flex-direction:column;background:#fff;border:1px solid var(--border-secondary);border-radius:var(--radius-large);padding:8px;overflow:hidden}.chat-sdk__input-context{padding:0 4px 8px}.chat-sdk__input-context .chat-sdk__context-chip{background:var(--background-tertiary);padding:8px 12px;border-radius:var(--radius-full);display:inline-flex;align-items:center;gap:8px}.chat-sdk__input-context .chat-sdk__context-text{font-size:14px;line-height:1.45;color:var(--content-primary)}.chat-sdk__context-clear{display:flex;align-items:center;justify-content:center;width:16px;height:16px;padding:0;background:transparent;border:none;color:var(--content-secondary);cursor:pointer;transition:color .15s}.chat-sdk__context-clear:hover{color:var(--content-primary)}.chat-sdk__input{width:100%;border:none;background:transparent;resize:none;min-height:72px;max-height:120px;font-size:15px;font-family:inherit;color:var(--content-primary);outline:none;line-height:1.45;padding:4px 8px}.chat-sdk__input::placeholder{color:var(--content-tertiary)}.chat-sdk__actions{display:flex;align-items:center;justify-content:space-between}.chat-sdk__actions-left{display:flex;align-items:center}.chat-sdk__add-btn{display:flex;align-items:center;justify-content:center;width:28px;height:28px;padding:0;background:transparent;border:none;border-radius:50%;color:var(--content-secondary);cursor:pointer;transition:background .15s,color .15s}.chat-sdk__add-btn:hover:not(:disabled){background:var(--background-tertiary);color:var(--content-primary)}.chat-sdk__add-btn:disabled{opacity:.4;cursor:not-allowed}.chat-sdk__send{display:flex;align-items:center;justify-content:center;width:28px;height:28px;min-width:28px;min-height:28px;background:var(--background-black);color:#fff;border:none;border-radius:50%;cursor:pointer;transition:opacity .2s}.chat-sdk__send:disabled{opacity:.3;cursor:not-allowed}.chat-sdk__send:not(:disabled):hover{opacity:.8}.chat-sdk__error{font-size:12px;color:#dc2626;padding:4px 8px}.chat-sdk__stream{display:inline-flex;gap:4px;vertical-align:middle}.chat-sdk__stream span{width:4px;height:4px;background:currentColor;border-radius:50%;animation:chat-sdk-pulse 1.4s infinite ease-in-out both}.chat-sdk__stream span:nth-child(1){animation-delay:-.32s}.chat-sdk__stream span:nth-child(2){animation-delay:-.16s}@keyframes chat-sdk-pulse{0%,80%,to{transform:scale(0)}40%{transform:scale(1)}}
@@ -19,5 +19,5 @@
19
19
  <%s {...props} />
20
20
  React keys must be passed directly to JSX without using spread:
21
21
  let props = %s;
22
- <%s key={someKey} {...props} />`,C,N,V,N),Oe[N+C]=!0)}if(N=null,T!==void 0&&(t(T),N=""+T),o(k)&&(t(k.key),N=""+k.key),"key"in k){T={};for(var he in k)he!=="key"&&(T[he]=k[he])}else T=k;return N&&c(T,typeof a=="function"?a.displayName||a.name||"Unknown":a),l(a,N,T,r(),Q,ce)}function p(a){m(a)?a._store&&(a._store.validated=1):typeof a=="object"&&a!==null&&a.$$typeof===L&&(a._payload.status==="fulfilled"?m(a._payload.value)&&a._payload.value._store&&(a._payload.value._store.validated=1):a._store&&(a._store.validated=1))}function m(a){return typeof a=="object"&&a!==null&&a.$$typeof===w}var b=R,w=Symbol.for("react.transitional.element"),P=Symbol.for("react.portal"),q=Symbol.for("react.fragment"),h=Symbol.for("react.strict_mode"),_=Symbol.for("react.profiler"),v=Symbol.for("react.consumer"),E=Symbol.for("react.context"),A=Symbol.for("react.forward_ref"),y=Symbol.for("react.suspense"),x=Symbol.for("react.suspense_list"),O=Symbol.for("react.memo"),L=Symbol.for("react.lazy"),z=Symbol.for("react.activity"),F=Symbol.for("react.client.reference"),oe=b.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Re=Object.prototype.hasOwnProperty,tt=Array.isArray,ae=console.createTask?console.createTask:function(){return null};b={react_stack_bottom_frame:function(a){return a()}};var Se,Ae={},Ce=b.react_stack_bottom_frame.bind(b,i)(),Ne=ae(n(i)),Oe={};W.Fragment=q,W.jsx=function(a,k,T){var C=1e4>oe.recentlyCreatedOwnerStacks++;return f(a,k,T,!1,C?Error("react-stack-top-frame"):Ce,C?ae(n(a)):Ne)},W.jsxs=function(a,k,T){var C=1e4>oe.recentlyCreatedOwnerStacks++;return f(a,k,T,!0,C?Error("react-stack-top-frame"):Ce,C?ae(n(a)):Ne)}}()),W}process.env.NODE_ENV==="production"?pe.exports=st():pe.exports=rt();var u=pe.exports;const j=Object.create(null);j.open="0";j.close="1";j.ping="2";j.pong="3";j.message="4";j.upgrade="5";j.noop="6";const Z=Object.create(null);Object.keys(j).forEach(s=>{Z[j[s]]=s});const ge={type:"error",data:"parser error"},qe=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Ue=typeof ArrayBuffer=="function",Me=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,xe=({type:s,data:e},t,n)=>qe&&e instanceof Blob?t?n(e):Le(e,n):Ue&&(e instanceof ArrayBuffer||Me(e))?t?n(e):Le(new Blob([e]),n):n(j[s]+(e||"")),Le=(s,e)=>{const t=new FileReader;return t.onload=function(){const n=t.result.split(",")[1];e("b"+(n||""))},t.readAsDataURL(s)};function Ie(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}let le;function it(s,e){if(qe&&s.data instanceof Blob)return s.data.arrayBuffer().then(Ie).then(e);if(Ue&&(s.data instanceof ArrayBuffer||Me(s.data)))return e(Ie(s.data));xe(s,!1,t=>{le||(le=new TextEncoder),e(le.encode(t))})}const De="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",K=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<De.length;s++)K[De.charCodeAt(s)]=s;const ot=s=>{let e=s.length*.75,t=s.length,n,r=0,i,o,c,d;s[s.length-1]==="="&&(e--,s[s.length-2]==="="&&e--);const l=new ArrayBuffer(e),f=new Uint8Array(l);for(n=0;n<t;n+=4)i=K[s.charCodeAt(n)],o=K[s.charCodeAt(n+1)],c=K[s.charCodeAt(n+2)],d=K[s.charCodeAt(n+3)],f[r++]=i<<2|o>>4,f[r++]=(o&15)<<4|c>>2,f[r++]=(c&3)<<6|d&63;return l},at=typeof ArrayBuffer=="function",ve=(s,e)=>{if(typeof s!="string")return{type:"message",data:Fe(s,e)};const t=s.charAt(0);return t==="b"?{type:"message",data:ct(s.substring(1),e)}:Z[t]?s.length>1?{type:Z[t],data:s.substring(1)}:{type:Z[t]}:ge},ct=(s,e)=>{if(at){const t=ot(s);return Fe(t,e)}else return{base64:!0,data:s}},Fe=(s,e)=>{switch(e){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}},Ve="",ht=(s,e)=>{const t=s.length,n=new Array(t);let r=0;s.forEach((i,o)=>{xe(i,!1,c=>{n[o]=c,++r===t&&e(n.join(Ve))})})},lt=(s,e)=>{const t=s.split(Ve),n=[];for(let r=0;r<t.length;r++){const i=ve(t[r],e);if(n.push(i),i.type==="error")break}return n};function ut(){return new TransformStream({transform(s,e){it(s,t=>{const n=t.length;let r;if(n<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,n);else if(n<65536){r=new Uint8Array(3);const i=new DataView(r.buffer);i.setUint8(0,126),i.setUint16(1,n)}else{r=new Uint8Array(9);const i=new DataView(r.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(n))}s.data&&typeof s.data!="string"&&(r[0]|=128),e.enqueue(r),e.enqueue(t)})}})}let ue;function J(s){return s.reduce((e,t)=>e+t.length,0)}function X(s,e){if(s[0].length===e)return s.shift();const t=new Uint8Array(e);let n=0;for(let r=0;r<e;r++)t[r]=s[0][n++],n===s[0].length&&(s.shift(),n=0);return s.length&&n<s[0].length&&(s[0]=s[0].slice(n)),t}function dt(s,e){ue||(ue=new TextDecoder);const t=[];let n=0,r=-1,i=!1;return new TransformStream({transform(o,c){for(t.push(o);;){if(n===0){if(J(t)<1)break;const d=X(t,1);i=(d[0]&128)===128,r=d[0]&127,r<126?n=3:r===126?n=1:n=2}else if(n===1){if(J(t)<2)break;const d=X(t,2);r=new DataView(d.buffer,d.byteOffset,d.length).getUint16(0),n=3}else if(n===2){if(J(t)<8)break;const d=X(t,8),l=new DataView(d.buffer,d.byteOffset,d.length),f=l.getUint32(0);if(f>Math.pow(2,21)-1){c.enqueue(ge);break}r=f*Math.pow(2,32)+l.getUint32(4),n=3}else{if(J(t)<r)break;const d=X(t,r);c.enqueue(ve(i?d:ue.decode(d),e)),n=0}if(r===0||r>s){c.enqueue(ge);break}}}})}const $e=4;function S(s){if(s)return ft(s)}function ft(s){for(var e in S.prototype)s[e]=S.prototype[e];return s}S.prototype.on=S.prototype.addEventListener=function(s,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+s]=this._callbacks["$"+s]||[]).push(e),this};S.prototype.once=function(s,e){function t(){this.off(s,t),e.apply(this,arguments)}return t.fn=e,this.on(s,t),this};S.prototype.off=S.prototype.removeListener=S.prototype.removeAllListeners=S.prototype.removeEventListener=function(s,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+s];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+s],this;for(var n,r=0;r<t.length;r++)if(n=t[r],n===e||n.fn===e){t.splice(r,1);break}return t.length===0&&delete this._callbacks["$"+s],this};S.prototype.emit=function(s){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+s],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,r=t.length;n<r;++n)t[n].apply(this,e)}return this};S.prototype.emitReserved=S.prototype.emit;S.prototype.listeners=function(s){return this._callbacks=this._callbacks||{},this._callbacks["$"+s]||[]};S.prototype.hasListeners=function(s){return!!this.listeners(s).length};const re=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),B=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),pt="arraybuffer";function He(s,...e){return e.reduce((t,n)=>(s.hasOwnProperty(n)&&(t[n]=s[n]),t),{})}const gt=B.setTimeout,_t=B.clearTimeout;function ie(s,e){e.useNativeTimers?(s.setTimeoutFn=gt.bind(B),s.clearTimeoutFn=_t.bind(B)):(s.setTimeoutFn=B.setTimeout.bind(B),s.clearTimeoutFn=B.clearTimeout.bind(B))}const mt=1.33;function yt(s){return typeof s=="string"?kt(s):Math.ceil((s.byteLength||s.size)*mt)}function kt(s){let e=0,t=0;for(let n=0,r=s.length;n<r;n++)e=s.charCodeAt(n),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(n++,t+=4);return t}function We(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function bt(s){let e="";for(let t in s)s.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(s[t]));return e}function xt(s){let e={},t=s.split("&");for(let n=0,r=t.length;n<r;n++){let i=t[n].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}class vt extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class we extends S{constructor(e){super(),this.writable=!1,ie(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new vt(e,t,n)),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=ve(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=bt(e);return t.length?"?"+t:""}}class wt extends we{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 n=0;this._polling&&(n++,this.once("pollComplete",function(){--n||t()})),this.writable||(n++,this.once("drain",function(){--n||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};lt(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,ht(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]=We()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let Ye=!1;try{Ye=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Et=Ye;function Tt(){}class Rt extends wt{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(r,i)=>{this.onError("xhr post error",r,i)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}}class D extends S{constructor(e,t,n){super(),this.createRequest=e,ie(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var e;const t=He(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&n.setRequestHeader(r,this._opts.extraHeaders[r])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var r;n.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},n.send(this._data)}catch(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=D.requestsCount++,D.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Tt,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete D.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}D.requestsCount=0;D.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",je);else if(typeof addEventListener=="function"){const s="onpagehide"in B?"pagehide":"unload";addEventListener(s,je,!1)}}function je(){for(let s in D.requests)D.requests.hasOwnProperty(s)&&D.requests[s].abort()}const St=function(){const s=Ke({xdomain:!1});return s&&s.responseType!==null}();class At extends Rt{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=St&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new D(Ke,this.uri(),e)}}function Ke(s){const e=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Et))return new XMLHttpRequest}catch{}if(!e)try{return new B[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const ze=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Ct extends we{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=ze?{}:He(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(r){return this.emitReserved("error",r)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;xe(n,this.supportsBinary,i=>{try{this.doWrite(n,i)}catch{}r&&re(()=>{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]=We()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const de=B.WebSocket||B.MozWebSocket;class Nt extends Ct{createSocket(e,t,n){return ze?new de(e,t,n):t?new de(e,t):new de(e)}doWrite(e,t){this.ws.send(t)}}class Ot extends we{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=dt(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=ut();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();const i=()=>{n.read().then(({done:c,value:d})=>{c||(this.onPacket(d),i())}).catch(c=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&re(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const Pt={websocket:Nt,webtransport:Ot,polling:At},Bt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Lt=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function _e(s){if(s.length>8e3)throw"URI too long";const e=s,t=s.indexOf("["),n=s.indexOf("]");t!=-1&&n!=-1&&(s=s.substring(0,t)+s.substring(t,n).replace(/:/g,";")+s.substring(n,s.length));let r=Bt.exec(s||""),i={},o=14;for(;o--;)i[Lt[o]]=r[o]||"";return t!=-1&&n!=-1&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=It(i,i.path),i.queryKey=Dt(i,i.query),i}function It(s,e){const t=/\/{2,9}/g,n=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&n.splice(0,1),e.slice(-1)=="/"&&n.splice(n.length-1,1),n}function Dt(s,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,r,i){r&&(t[r]=i)}),t}const me=typeof addEventListener=="function"&&typeof removeEventListener=="function",ee=[];me&&addEventListener("offline",()=>{ee.forEach(s=>s())},!1);class M extends S{constructor(e,t){if(super(),this.binaryType=pt,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 n=_e(e);t.hostname=n.host,t.secure=n.protocol==="https"||n.protocol==="wss",t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=_e(t.host).host);ie(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(n=>{const r=n.prototype.name;this.transports.push(r),this._transportsByName[r]=n}),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=xt(this.opts.query)),me&&(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"})},ee.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=$e,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&M.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",M.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 n=0;n<this.writeBuffer.length;n++){const r=this.writeBuffer[n].data;if(r&&(t+=yt(r)),n>0&&t>this._maxPayload)return this.writeBuffer.slice(0,n);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,re(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,r){if(typeof t=="function"&&(r=t,t=void 0),typeof n=="function"&&(r=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const i={type:e,data:t,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{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?n():e()}):this.upgrading?n():e()),this}_onError(e){if(M.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(),me&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=ee.indexOf(this._offlineEventListener);n!==-1&&ee.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}M.protocol=$e;class jt extends M{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),n=!1;M.priorWebsocketSuccess=!1;const r=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",p=>{if(!n)if(p.type==="pong"&&p.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;M.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(f(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const m=new Error("probe error");m.transport=t.name,this.emitReserved("upgradeError",m)}}))};function i(){n||(n=!0,f(),t.close(),t=null)}const o=p=>{const m=new Error("probe error: "+p);m.transport=t.name,i(),this.emitReserved("upgradeError",m)};function c(){o("transport closed")}function d(){o("socket closed")}function l(p){t&&p.name!==t.name&&i()}const f=()=>{t.removeListener("open",r),t.removeListener("error",o),t.removeListener("close",c),this.off("close",d),this.off("upgrading",l)};t.once("open",r),t.once("error",o),t.once("close",c),this.once("close",d),this.once("upgrading",l),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}let qt=class extends jt{constructor(e,t={}){const n=typeof e=="object"?e:t;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(r=>Pt[r]).filter(r=>!!r)),super(e,n)}};function Ut(s,e="",t){let n=s;t=t||typeof location<"u"&&location,s==null&&(s=t.protocol+"//"+t.host),typeof s=="string"&&(s.charAt(0)==="/"&&(s.charAt(1)==="/"?s=t.protocol+s:s=t.host+s),/^(https?|wss?):\/\//.test(s)||(typeof t<"u"?s=t.protocol+"//"+s:s="https://"+s),n=_e(s)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+e,n.href=n.protocol+"://"+i+(t&&t.port===n.port?"":":"+n.port),n}const Mt=typeof ArrayBuffer=="function",Ft=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,Qe=Object.prototype.toString,Vt=typeof Blob=="function"||typeof Blob<"u"&&Qe.call(Blob)==="[object BlobConstructor]",$t=typeof File=="function"||typeof File<"u"&&Qe.call(File)==="[object FileConstructor]";function Ee(s){return Mt&&(s instanceof ArrayBuffer||Ft(s))||Vt&&s instanceof Blob||$t&&s instanceof File}function te(s,e){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let t=0,n=s.length;t<n;t++)if(te(s[t]))return!0;return!1}if(Ee(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return te(s.toJSON(),!0);for(const t in s)if(Object.prototype.hasOwnProperty.call(s,t)&&te(s[t]))return!0;return!1}function Ht(s){const e=[],t=s.data,n=s;return n.data=ye(t,e),n.attachments=e.length,{packet:n,buffers:e}}function ye(s,e){if(!s)return s;if(Ee(s)){const t={_placeholder:!0,num:e.length};return e.push(s),t}else if(Array.isArray(s)){const t=new Array(s.length);for(let n=0;n<s.length;n++)t[n]=ye(s[n],e);return t}else if(typeof s=="object"&&!(s instanceof Date)){const t={};for(const n in s)Object.prototype.hasOwnProperty.call(s,n)&&(t[n]=ye(s[n],e));return t}return s}function Wt(s,e){return s.data=ke(s.data,e),delete s.attachments,s}function ke(s,e){if(!s)return s;if(s&&s._placeholder===!0){if(typeof s.num=="number"&&s.num>=0&&s.num<e.length)return e[s.num];throw new Error("illegal attachments")}else if(Array.isArray(s))for(let t=0;t<s.length;t++)s[t]=ke(s[t],e);else if(typeof s=="object")for(const t in s)Object.prototype.hasOwnProperty.call(s,t)&&(s[t]=ke(s[t],e));return s}const Je=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],Yt=5;var g;(function(s){s[s.CONNECT=0]="CONNECT",s[s.DISCONNECT=1]="DISCONNECT",s[s.EVENT=2]="EVENT",s[s.ACK=3]="ACK",s[s.CONNECT_ERROR=4]="CONNECT_ERROR",s[s.BINARY_EVENT=5]="BINARY_EVENT",s[s.BINARY_ACK=6]="BINARY_ACK"})(g||(g={}));class Kt{constructor(e){this.replacer=e}encode(e){return(e.type===g.EVENT||e.type===g.ACK)&&te(e)?this.encodeAsBinary({type:e.type===g.EVENT?g.BINARY_EVENT:g.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===g.BINARY_EVENT||e.type===g.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=Ht(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}}class Te extends S{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 n=t.type===g.BINARY_EVENT;n||t.type===g.BINARY_ACK?(t.type=n?g.EVENT:g.ACK,this.reconstructor=new zt(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(Ee(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 n={type:Number(e.charAt(0))};if(g[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===g.BINARY_EVENT||n.type===g.BINARY_ACK){const i=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const o=e.substring(i,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");n.attachments=Number(o)}if(e.charAt(t+1)==="/"){const i=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););n.nsp=e.substring(i,t)}else n.nsp="/";const r=e.charAt(t+1);if(r!==""&&Number(r)==r){const i=t+1;for(;++t;){const o=e.charAt(t);if(o==null||Number(o)!=o){--t;break}if(t===e.length)break}n.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(Te.isPayloadValid(n.type,i))n.data=i;else throw new Error("invalid payload")}return n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case g.CONNECT:return se(t);case g.DISCONNECT:return t===void 0;case g.CONNECT_ERROR:return typeof t=="string"||se(t);case g.EVENT:case g.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Je.indexOf(t[0])===-1);case g.ACK:case g.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class zt{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=Wt(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function Qt(s){return typeof s=="string"}const Jt=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s};function Xt(s){return s===void 0||Jt(s)}function se(s){return Object.prototype.toString.call(s)==="[object Object]"}function Gt(s,e){switch(s){case g.CONNECT:return e===void 0||se(e);case g.DISCONNECT:return e===void 0;case g.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Je.indexOf(e[0])===-1);case g.ACK:return Array.isArray(e);case g.CONNECT_ERROR:return typeof e=="string"||se(e);default:return!1}}function Zt(s){return Qt(s.nsp)&&Xt(s.id)&&Gt(s.type,s.data)}const en=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Te,Encoder:Kt,get PacketType(){return g},isPacketValid:Zt,protocol:Yt},Symbol.toStringTag,{value:"Module"}));function I(s,e,t){return s.on(e,t),function(){s.off(e,t)}}const tn=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Xe extends S{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[I(e,"open",this.onopen.bind(this)),I(e,"packet",this.onpacket.bind(this)),I(e,"error",this.onerror.bind(this)),I(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 n,r,i;if(tn.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:g.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const f=this.ids++,p=t.pop();this._registerAckCallback(f,p),o.id=f}const c=(r=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||r===void 0?void 0:r.writable,d=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!c||(d?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var n;const r=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(r===void 0){this.acks[e]=t;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===e&&this.sendBuffer.splice(c,1);t.call(this,new Error("operation has timed out"))},r),o=(...c)=>{this.io.clearTimeoutFn(i),t.apply(this,c)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((n,r)=>{const i=(o,c)=>o?r(o):n(c);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((r,...i)=>(this._queue[0],r!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(r)):(this._queue.shift(),t&&t(null,...i)),n.pending=!1,this._drainQueue())),this._queue.push(n),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:g.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(n=>String(n.id)===e)){const n=this.acks[e];delete this.acks[e],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case g.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 g.EVENT:case g.BINARY_EVENT:this.onevent(e);break;case g.ACK:case g.BINARY_ACK:this.onack(e);break;case g.DISCONNECT:this.ondisconnect();break;case g.CONNECT_ERROR:this.destroy();const n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);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 n of t)n.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 n=!1;return function(...r){n||(n=!0,t.packet({type:g.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:g.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function $(s){s=s||{},this.ms=s.min||100,this.max=s.max||1e4,this.factor=s.factor||2,this.jitter=s.jitter>0&&s.jitter<=1?s.jitter:0,this.attempts=0}$.prototype.duration=function(){var s=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*s);s=Math.floor(e*10)&1?s+t:s-t}return Math.min(s,this.max)|0};$.prototype.reset=function(){this.attempts=0};$.prototype.setMin=function(s){this.ms=s};$.prototype.setMax=function(s){this.max=s};$.prototype.setJitter=function(s){this.jitter=s};class be extends S{constructor(e,t){var n;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,ie(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((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new $({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||en;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new qt(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=I(t,"open",function(){n.onopen(),e&&e()}),i=c=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},o=I(t,"error",i);if(this._timeout!==!1){const c=this._timeout,d=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),t.close()},c);this.opts.autoUnref&&d.unref(),this.subs.push(()=>{this.clearTimeoutFn(d)})}return this.subs.push(r),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(I(e,"ping",this.onping.bind(this)),I(e,"data",this.ondata.bind(this)),I(e,"error",this.onerror.bind(this)),I(e,"close",this.onclose.bind(this)),I(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){re(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new Xe(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const n of t)if(this.nsps[n].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(r=>{r?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",r)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const Y={};function ne(s,e){typeof s=="object"&&(e=s,s=void 0),e=e||{};const t=Ut(s,e.path||"/socket.io"),n=t.source,r=t.id,i=t.path,o=Y[r]&&i in Y[r].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let d;return c?d=new be(n,e):(Y[r]||(Y[r]=new be(n,e)),d=Y[r]),t.query&&!e.query&&(e.query=t.queryKey),d.socket(t.path,e)}Object.assign(ne,{Manager:be,Socket:Xe,io:ne,connect:ne});function U(){return`${Date.now().toString(36)}-${Math.random().toString(16).slice(2,8)}`}class nn{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 n;return(n=this.listeners.get(e))==null?void 0:n.delete(t)}}emit(e,t){var n;(n=this.listeners.get(e))==null||n.forEach(r=>{var i,o;try{r(t)}catch(c){(o=(i=this.config.logger)==null?void 0:i.error)==null||o.call(i,`chat-sdk listener error for ${e}`,c)}})}setConnection(e){var t,n;this.emit("connection",e),(n=(t=this.config).onConnectionChange)==null||n.call(t,e)}async getToken(){var t,n;const{tokenProvider:e}=this.config;if(!e)return null;try{return(typeof e=="function"?await e():e)||null}catch(r){return(n=(t=this.config.logger)==null?void 0:t.warn)==null||n.call(t,"chat-sdk token provider failed",r),null}}async connect(){var i;if((i=this.socket)!=null&&i.connected)return;const e=new URL(this.config.websocketUrl),t=e.pathname==="/"?"/socket.io":e.pathname,n=e.origin,r=await this.getToken();return this.socket=ne(n,{path:t,transports:["websocket","polling"],autoConnect:!1,reconnection:!1,auth:r?{token:r}:void 0}),this.registerSocketEvents(),this.setConnection({connected:!1,connecting:!0}),new Promise((o,c)=>{const d=setTimeout(()=>{c(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(),c(l)}),this.socket.connect()})}disconnect(){var e;(e=this.socket)==null||e.disconnect(),this.socket=null,this.setConnection({connected:!1,connecting:!1})}async submitInstruction(e,t){var i,o;if(!((i=this.socket)!=null&&i.connected))throw new Error("Not connected");this.lastContext=t;const n=await this.getToken(),r={trans_doc_id:t.trans_doc_id,page_num:t.page_num,instruction:e,modification_level:"page",access_token:n||void 0,region_coordinates:t.highlighted_region?{start_offset:t.highlighted_region.start_offset,end_offset:t.highlighted_region.end_offset}:void 0,region_text:(o=t.highlighted_region)==null?void 0:o.text,selection_id:t.selection_id};this.socket.emit("INSTR_SUBMIT",r)}async requestChatHistory(e){var n;if(!((n=this.socket)!=null&&n.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 n;if(!((n=this.socket)!=null&&n.connected))throw new Error("Not connected");const t=await this.getToken();this.socket.emit("PATCH_DECISION",{...e,access_token:t||void 0})}async requestPageTranslation(e){var r,i,o,c,d;if(!((r=this.socket)!=null&&r.connected))throw new Error("Not connected");const t=await this.getToken(),n={...e,access_token:t||void 0};(o=(i=this.config.logger)==null?void 0:i.log)==null||o.call(i,"[chat-sdk] Sending PAGE_TRANSLATION_REQUEST:",{trans_doc_id:e.trans_doc_id,page_num:e.page_num,has_access_token:!!t}),this.socket.emit("PAGE_TRANSLATION_REQUEST",n),(d=(c=this.config.logger)==null?void 0:c.log)==null||d.call(c,"[chat-sdk] PAGE_TRANSLATION_REQUEST emitted successfully")}async requestBulkTranslation(e){var r,i,o,c,d;if(!((r=this.socket)!=null&&r.connected))throw new Error("Not connected");const t=await this.getToken(),n={...e,access_token:t||void 0};(o=(i=this.config.logger)==null?void 0:i.log)==null||o.call(i,"[chat-sdk] Sending BULK_TRANSLATION_REQUEST:",{trans_doc_id:e.trans_doc_id,page_list:e.page_list,has_access_token:!!t}),this.socket.emit("BULK_TRANSLATION_REQUEST",n),(d=(c=this.config.logger)==null?void 0:c.log)==null||d.call(c,"[chat-sdk] BULK_TRANSLATION_REQUEST emitted successfully")}async cancelBulkTranslation(e){var n,r,i,o,c;if(!((n=this.socket)!=null&&n.connected))throw new Error("Not connected");const t=await this.getToken();(i=(r=this.config.logger)==null?void 0:r.log)==null||i.call(r,"[chat-sdk] Sending CANCEL_BULK_TRANSLATION_REQUEST:",{trans_doc_id:e,has_access_token:!!t}),this.socket.emit("CANCEL_BULK_TRANSLATION_REQUEST",{trans_doc_id:e,access_token:t||void 0}),(c=(o=this.config.logger)==null?void 0:o.log)==null||c.call(o,"[chat-sdk] CANCEL_BULK_TRANSLATION_REQUEST emitted successfully")}registerSocketEvents(){this.socket&&(this.socket.on("disconnect",()=>{this.setConnection({connected:!1,connecting:!1}),this.handleReconnect()}),this.socket.on("connect_error",e=>{this.setConnection({connected:!1,connecting:!1,error:e.message}),this.handleReconnect()}),this.socket.on("CHAT_RESPONSE",e=>{this.emit("chat-response",e)}),this.socket.on("PATCH_OFFER",e=>{this.emit("patch-offer",e)}),this.socket.on("CHAT_HISTORY_RESPONSE",e=>{this.emit("chat-history-response",e)}),this.socket.on("INSTRUCTION_ERROR",e=>{this.emit("instruction-error",e)}),this.socket.on("PAGE_TRANSLATION_RESPONSE",e=>{var t,n,r,i,o,c,d,l,f,p,m;(r=(t=this.config.logger)==null?void 0:t.log)==null||r.call(t,"[chat-sdk] Received PAGE_TRANSLATION_RESPONSE from socket:",{trans_doc_id:e.trans_doc_id,page_num:e.page_num,status:e.status,has_content:!!e.trans_page_content,content_length:(n=e.trans_page_content)==null?void 0:n.length,error:e.error,error_type:e.error_type,updated_at:e.updated_at}),this.emit("page-translation-response",e),(o=(i=this.config.logger)==null?void 0:i.log)==null||o.call(i,"[chat-sdk] Emitted page-translation-response internally"),this.config.onPageTranslationResponse?((d=(c=this.config.logger)==null?void 0:c.log)==null||d.call(c,"[chat-sdk] Calling onPageTranslationResponse callback"),this.config.onPageTranslationResponse(e),(f=(l=this.config.logger)==null?void 0:l.log)==null||f.call(l,"[chat-sdk] onPageTranslationResponse callback completed")):(m=(p=this.config.logger)==null?void 0:p.log)==null||m.call(p,"[chat-sdk] No onPageTranslationResponse callback configured")}),this.socket.on("BULK_TRANSLATION_RESPONSE",e=>{var t,n,r,i,o,c,d,l,f,p;(n=(t=this.config.logger)==null?void 0:t.log)==null||n.call(t,"[chat-sdk] Received BULK_TRANSLATION_RESPONSE from socket:",{trans_doc_id:e.trans_doc_id,status:e.status,completed_pages:e.completed_pages,total_pages:e.total_pages,current_page:e.current_page,error:e.error,error_type:e.error_type}),this.emit("bulk-translation-response",e),(i=(r=this.config.logger)==null?void 0:r.log)==null||i.call(r,"[chat-sdk] Emitted bulk-translation-response internally"),this.config.onBulkTranslationResponse?((c=(o=this.config.logger)==null?void 0:o.log)==null||c.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")):(p=(f=this.config.logger)==null?void 0:f.log)==null||p.call(f,"[chat-sdk] No onBulkTranslationResponse callback configured")}),this.socket.on("connected",()=>{this.lastContext&&this.requestChatHistory(this.lastContext).catch(e=>{var t,n;return(n=(t=this.config.logger)==null?void 0:t.warn)==null?void 0:n.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(n=>{var r,i;return(i=(r=this.config.logger)==null?void 0:r.error)==null?void 0:i.call(r,"chat-sdk reconnect failed",n)})},this.config.reconnectDelayMs)}}function sn(s){return s.map(e=>{const t={id:U(),instructionId:e.instruction_id,pageNum:e.page_num,timestamp:new Date(e.timestamp)},n={...t,type:"user",content:e.instruction,contextText:e.region_text},r=[];return e.response_content&&e.response_type==="chat"&&r.push({...t,type:"ai-chat",content:e.response_content}),e.response_content&&e.response_type==="patch"&&r.push({...t,type:"ai-patch",content:e.response_content,patchData:{originalText:e.region_text,improvedText:e.response_content,regionText:e.region_text,isComplete:!0}}),[n,...r]}).flat().sort((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())}const Ge=R.createContext(null),rn={connected:!1,connecting:!1};function on({config:s,children:e}){const t=R.useRef(null),n=R.useRef(new Map),[r,i]=R.useState({messages:[],connection:rn,latestPatchOffer:null,isSubmitting:!1}),o=R.useMemo(()=>({reconnectAttempts:5,reconnectDelayMs:1500,...s}),[s]);R.useEffect(()=>{const l=new nn(o);t.current=l;const f=l.on("connection",h=>{i(_=>({..._,connection:h}))}),p=l.on("chat-response",h=>{i(_=>{const v=[..._.messages];let E=v.find(x=>x.instructionId===h.instruction_id&&x.type==="ai-chat");E||(E={id:U(),type:"ai-chat",content:"",timestamp:new Date,instructionId:h.instruction_id,pageNum:h.page_num,isStreaming:!0},v.push(E));const A={...E,content:(E.content||"")+(h.chunk_text||""),isStreaming:!h.is_final},y=v.map(x=>x.id===E.id?A:x);return{..._,messages:y,isSubmitting:h.is_final?!1:_.isSubmitting}})}),m=l.on("patch-offer",h=>{var E;const _=`${h.trans_doc_id}-${h.instruction_id}`,v=n.current.get(_)??{trans_doc_id:h.trans_doc_id,page_num:h.page_num,instruction_id:h.instruction_id,original_text:h.region_original_text||"",highlighted_region:h.region_coordinates,new_suggestion:"",is_page_level:!h.region_coordinates,selection_id:h.selection_id};if(v.new_suggestion+=h.region_replacement_text_chunk||"",h.selection_id&&!v.selection_id&&(v.selection_id=h.selection_id),n.current.set(_,v),i(A=>{var z;const y=[...A.messages];let x=y.find(F=>F.instructionId===h.instruction_id&&F.type==="ai-patch");x||(x={id:U(),type:"ai-patch",content:"",timestamp:new Date,instructionId:h.instruction_id,pageNum:h.page_num,isStreaming:!0,patchData:{originalText:h.region_original_text,improvedText:"",regionText:h.region_original_text,isComplete:!1}},y.push(x));const O={...x,content:(x.content||"")+(h.region_replacement_text_chunk||""),isStreaming:!h.is_final,patchData:{...x.patchData,improvedText:(((z=x.patchData)==null?void 0:z.improvedText)||"")+(h.region_replacement_text_chunk||""),regionText:h.region_original_text,isComplete:h.is_final}},L=y.map(F=>F.id===x.id?O:F);return{...A,messages:L,isSubmitting:h.is_final?!1:A.isSubmitting}}),h.is_final){const A=n.current.get(_);A&&((E=o.onPatchOffer)==null||E.call(o,A),i(y=>({...y,latestPatchOffer:A}))),n.current.delete(_)}}),b=l.on("chat-history-response",h=>{if(h.status==="success"){const _=sn(h.messages);i(v=>({...v,messages:_}))}else i(_=>({..._,messages:[..._.messages,{id:U(),type:"system",content:h.error||"Failed to load chat history",timestamp:new Date}]}))}),w=l.on("instruction-error",h=>{i(_=>({..._,isSubmitting:!1,messages:[..._.messages,{id:U(),type:"error",content:h.error,timestamp:new Date}]}))}),P=l.on("page-translation-response",h=>{var _,v,E,A,y,x,O,L;(v=(_=o.logger)==null?void 0:_.log)==null||v.call(_,"[chat-sdk][ChatProvider] Received page-translation-response event:",{trans_doc_id:h.trans_doc_id,page_num:h.page_num,status:h.status,has_content:!!h.trans_page_content,error:h.error}),o.onPageTranslationResponse?((A=(E=o.logger)==null?void 0:E.log)==null||A.call(E,"[chat-sdk][ChatProvider] Invoking onPageTranslationResponse callback from config"),o.onPageTranslationResponse(h),(x=(y=o.logger)==null?void 0:y.log)==null||x.call(y,"[chat-sdk][ChatProvider] onPageTranslationResponse callback completed")):(L=(O=o.logger)==null?void 0:O.log)==null||L.call(O,"[chat-sdk][ChatProvider] No onPageTranslationResponse callback in config")}),q=l.on("bulk-translation-response",h=>{var _,v,E,A,y,x,O,L;(v=(_=o.logger)==null?void 0:_.log)==null||v.call(_,"[chat-sdk][ChatProvider] Received bulk-translation-response event:",{trans_doc_id:h.trans_doc_id,status:h.status,completed_pages:h.completed_pages,total_pages:h.total_pages,current_page:h.current_page,error:h.error}),o.onBulkTranslationResponse?((A=(E=o.logger)==null?void 0:E.log)==null||A.call(E,"[chat-sdk][ChatProvider] Invoking onBulkTranslationResponse callback from config"),o.onBulkTranslationResponse(h),(x=(y=o.logger)==null?void 0:y.log)==null||x.call(y,"[chat-sdk][ChatProvider] onBulkTranslationResponse callback completed")):(L=(O=o.logger)==null?void 0:O.log)==null||L.call(O,"[chat-sdk][ChatProvider] No onBulkTranslationResponse callback in config")});return l.connect().then(()=>{const h=o.contextProvider();if(h)return l.requestChatHistory(h)}).catch(h=>{var _,v;return(v=(_=o.logger)==null?void 0:_.warn)==null?void 0:v.call(_,"chat-sdk connect failed",h)}),()=>{f(),p(),m(),b(),w(),P(),q(),l.disconnect()}},[o]);const c=R.useMemo(()=>({async submitInstruction(l){const f=t.current;if(!f)throw new Error("SDK not ready");const p=o.contextProvider();if(!p)throw new Error("contextProvider returned null");i(m=>{var b;return{...m,isSubmitting:!0,messages:[...m.messages,{id:U(),type:"user",content:l,timestamp:new Date,contextText:(b=p.highlighted_region)==null?void 0:b.text},{id:U(),type:"loading",content:"Processing your instruction...",timestamp:new Date,isStreaming:!0}]}}),await f.submitInstruction(l,p)},async submitInstructionWithContext(l,f){const p=t.current;if(!p)throw new Error("SDK not ready");i(m=>{var b;return{...m,isSubmitting:!0,messages:[...m.messages,{id:U(),type:"user",content:l,timestamp:new Date,contextText:(b=f.highlighted_region)==null?void 0:b.text},{id:U(),type:"loading",content:"Processing your instruction...",timestamp:new Date,isStreaming:!0}]}}),await p.submitInstruction(l,f)},async requestChatHistory(){const l=t.current;if(!l)throw new Error("SDK not ready");const f=o.contextProvider();if(!f)throw new Error("contextProvider returned null");await l.requestChatHistory(f)},async sendPatchDecision(l,f,p,m){const b=t.current;if(!b)throw new Error("SDK not ready");await b.sendPatchDecision({trans_doc_id:l,page_num:f,instruction_id:p,decision:m}),i(w=>({...w,latestPatchOffer:null}))},async requestPageTranslation(l,f){var m,b,w,P;const p=t.current;if(!p)throw new Error("SDK not ready");return(b=(m=o.logger)==null?void 0:m.log)==null||b.call(m,"[chat-sdk][ChatProvider] requestPageTranslation called:",{trans_doc_id:l,page_num:f}),await p.requestPageTranslation({trans_doc_id:l,page_num:f}),(P=(w=o.logger)==null?void 0:w.log)==null||P.call(w,"[chat-sdk][ChatProvider] requestPageTranslation request sent"),!0},async requestBulkTranslation(l,f){var m,b,w,P;const p=t.current;if(!p)throw new Error("SDK not ready");return(b=(m=o.logger)==null?void 0:m.log)==null||b.call(m,"[chat-sdk][ChatProvider] requestBulkTranslation called:",{trans_doc_id:l,page_list:f}),await p.requestBulkTranslation({trans_doc_id:l,page_list:f}),(P=(w=o.logger)==null?void 0:w.log)==null||P.call(w,"[chat-sdk][ChatProvider] requestBulkTranslation request sent"),!0},async cancelBulkTranslation(l){var p,m,b,w;const f=t.current;if(!f)throw new Error("SDK not ready");return(m=(p=o.logger)==null?void 0:p.log)==null||m.call(p,"[chat-sdk][ChatProvider] cancelBulkTranslation called:",{trans_doc_id:l}),await f.cancelBulkTranslation(l),(w=(b=o.logger)==null?void 0:b.log)==null||w.call(b,"[chat-sdk][ChatProvider] cancelBulkTranslation request sent"),!0},clearMessages(){i(l=>({...l,messages:[]}))}}),[o]),d=R.useMemo(()=>({...r,...c}),[r,c]);return u.jsx(Ge.Provider,{value:d,children:e})}function an(){const s=R.useContext(Ge);if(!s)throw new Error("useChat must be used within ChatProvider");return s}function Ze(){return an()}const et=R.forwardRef(({title:s="AI Assistance",placeholder:e="Ask anything...",height:t="500px"},n)=>{const{messages:r,connection:i,submitInstruction:o,submitInstructionWithContext:c,isSubmitting:d}=Ze(),[l,f]=R.useState(""),[p,m]=R.useState(null),[b,w]=R.useState(null),P=R.useRef(null),q=R.useRef(null),h=!i.connected||d;R.useImperativeHandle(n,()=>({setContext:({text:y,context:x})=>{w(y),m(x),setTimeout(()=>{var O;(O=q.current)==null||O.focus()},100)},focusInput:()=>{var y;(y=q.current)==null||y.focus()}}),[]);const _=R.useMemo(()=>[...r].sort((y,x)=>y.timestamp.getTime()-x.timestamp.getTime()),[r]);R.useEffect(()=>{P.current&&(P.current.scrollTop=P.current.scrollHeight)},[_]);const v=async y=>{y.preventDefault();const x=l.trim();x&&(p?(await c(x,p),m(null),w(null)):await o(x),f(""))},E=y=>{y.key==="Enter"&&!y.shiftKey&&(y.preventDefault(),v(y))},A=()=>{m(null),w(null)};return u.jsxs("div",{className:"chat-sdk",style:{height:t},children:[u.jsxs("div",{className:"chat-sdk__header",children:[u.jsx("div",{className:"chat-sdk__title",children:s}),u.jsxs("div",{className:"chat-sdk__status",children:[u.jsx("span",{className:`chat-sdk__status-dot ${i.connected?"connected":"disconnected"}`}),i.connected?"Connected":i.connecting?"Connecting...":"Disconnected"]})]}),u.jsx("div",{className:"chat-sdk__messages",ref:P,children:_.length===0?u.jsx("div",{className:"chat-sdk__empty",children:"Welcome! Ask anything about the translation."}):_.map(y=>u.jsx(cn,{message:y},y.id))}),u.jsxs("div",{className:"chat-sdk__composer",children:[u.jsxs("form",{className:"chat-sdk__input-bar",onSubmit:v,children:[b&&u.jsx("div",{className:"chat-sdk__input-context",children:u.jsxs("div",{className:"chat-sdk__context-chip",children:[u.jsx("span",{className:"chat-sdk__context-text",children:b.length>40?`${b.slice(0,40)}…`:b}),u.jsx("button",{type:"button",onClick:A,className:"chat-sdk__context-clear",children:u.jsx(dn,{})})]})}),u.jsx("textarea",{ref:q,className:"chat-sdk__input",placeholder:b?"What would you like to change?":e,value:l,onChange:y=>f(y.target.value),onKeyDown:E,disabled:h,rows:1}),u.jsxs("div",{className:"chat-sdk__actions",children:[u.jsx("div",{className:"chat-sdk__actions-left",children:u.jsx("button",{type:"button",className:"chat-sdk__add-btn",disabled:h,children:u.jsx(un,{})})}),u.jsx("button",{className:"chat-sdk__send",type:"submit",disabled:!l.trim()||h,children:u.jsx(ln,{})})]})]}),i.error&&u.jsxs("div",{className:"chat-sdk__error",children:["⚠️ ",i.error]})]})]})});et.displayName="ChatWidget";function cn({message:s}){var r;const e=s.type==="user",t=s.type==="loading",n=s.type==="ai-patch";return e?u.jsxs("div",{className:"chat-sdk__user-container",children:[s.contextText&&u.jsx("div",{className:"chat-sdk__user-context",children:u.jsx("div",{className:"chat-sdk__context-chip",children:u.jsx("span",{className:"chat-sdk__context-text",children:s.contextText.length>40?`${s.contextText.slice(0,40)}…`:s.contextText})})}),u.jsx("div",{className:"chat-sdk__bubble user",children:u.jsx("div",{className:"chat-sdk__bubble-body",children:s.content})})]}):u.jsx("div",{className:`chat-sdk__bubble ${n?"ai-patch":"ai"}`,children:u.jsxs("div",{className:`chat-sdk__bubble-body ${s.isStreaming?"streaming":""}`,children:[n&&u.jsx("div",{className:"chat-sdk__suggestion-text",children:u.jsx(hn,{instructionId:s.instructionId})}),n&&((r=s.patchData)!=null&&r.originalText)?u.jsxs("div",{className:"chat-sdk__patch",children:[u.jsx("div",{className:"chat-sdk__patch-label",children:"Original"}),u.jsx("div",{className:"chat-sdk__patch-block",children:s.patchData.originalText}),u.jsx("div",{className:"chat-sdk__patch-label",children:"Improved"}),u.jsxs("div",{className:"chat-sdk__patch-block",children:[s.patchData.improvedText,s.isStreaming&&u.jsx(fe,{})]})]}):u.jsxs(u.Fragment,{children:[u.jsx("div",{children:s.content}),t&&u.jsx(fe,{}),s.isStreaming&&!t&&u.jsx(fe,{})]})]})})}const G=["I have a suggestion for you","Here is something you might like","How about this?"];function hn({instructionId:s}){const e=R.useMemo(()=>{if(s){let t=0;for(let n=0;n<s.length;n++)t=(t*31+s.charCodeAt(n))%G.length;return Math.abs(t)%G.length}return Math.floor(Math.random()*G.length)},[s]);return u.jsx(u.Fragment,{children:G[e]})}function ln(){return u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"5"}),u.jsx("polyline",{points:"5 12 12 5 19 12"})]})}function un(){return u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),u.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function dn(){return u.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),u.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function fe(){return u.jsxs("span",{className:"chat-sdk__stream",children:[u.jsx("span",{}),u.jsx("span",{}),u.jsx("span",{})]})}const fn=".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:var(--spacing-2) var(--space-20);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__status{display:flex;align-items:center;gap:6px;color:var(--content-tertiary);font-size:12px}.chat-sdk__status-dot{width:8px;height:8px;border-radius:50%;background:#ef4444}.chat-sdk__status-dot.connected{background:#10b981}.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.user .chat-sdk__bubble-body{color:var(--content-brand1-secondary);font-size:15px;line-height:1.45;white-space:pre-wrap}.chat-sdk__bubble.ai,.chat-sdk__bubble.ai-patch{align-self:flex-start;max-width:90%;display:flex;flex-direction:column}.chat-sdk__bubble-body{display:flex;flex-direction:column;gap:8px;font-size:15px;color:var(--content-primary);line-height:1.5}.chat-sdk__suggestion-text{font-size:13px;color:var(--content-secondary);margin-bottom:0}.chat-sdk__patch{display:flex;flex-direction:column;gap:8px;margin-top:4px}.chat-sdk__patch-label{font-size:12px;color:var(--content-tertiary);font-weight:600}.chat-sdk__patch-block{background:#f3f4f6;border-radius:10px;padding:12px;border:1px solid #e5e7eb;font-size:14px;line-height:1.5;color:var(--content-secondary)}.chat-sdk__composer{padding:var(--spacing-1);background:var(--background-primary)}.chat-sdk__input-bar{display:flex;flex-direction:column;background:#fff;border:1px solid var(--border-secondary);border-radius:var(--radius-large);padding:8px;overflow:hidden}.chat-sdk__input-context{padding:0 4px 8px}.chat-sdk__input-context .chat-sdk__context-chip{background:var(--background-tertiary);padding:8px 12px;border-radius:var(--radius-full);display:inline-flex;align-items:center;gap:8px}.chat-sdk__input-context .chat-sdk__context-text{font-size:14px;line-height:1.45;color:var(--content-primary)}.chat-sdk__context-clear{display:flex;align-items:center;justify-content:center;width:16px;height:16px;padding:0;background:transparent;border:none;color:var(--content-secondary);cursor:pointer;transition:color .15s}.chat-sdk__context-clear:hover{color:var(--content-primary)}.chat-sdk__input{width:100%;border:none;background:transparent;resize:none;min-height:72px;max-height:120px;font-size:15px;font-family:inherit;color:var(--content-primary);outline:none;line-height:1.45;padding:4px 8px}.chat-sdk__input::placeholder{color:var(--content-tertiary)}.chat-sdk__actions{display:flex;align-items:center;justify-content:space-between}.chat-sdk__actions-left{display:flex;align-items:center}.chat-sdk__add-btn{display:flex;align-items:center;justify-content:center;width:28px;height:28px;padding:0;background:transparent;border:none;border-radius:50%;color:var(--content-secondary);cursor:pointer;transition:background .15s,color .15s}.chat-sdk__add-btn:hover:not(:disabled){background:var(--background-tertiary);color:var(--content-primary)}.chat-sdk__add-btn:disabled{opacity:.4;cursor:not-allowed}.chat-sdk__send{display:flex;align-items:center;justify-content:center;width:28px;height:28px;min-width:28px;min-height:28px;background:var(--background-black);color:#fff;border:none;border-radius:50%;cursor:pointer;transition:opacity .2s}.chat-sdk__send:disabled{opacity:.3;cursor:not-allowed}.chat-sdk__send:not(:disabled):hover{opacity:.8}.chat-sdk__error{font-size:12px;color:#dc2626;padding:4px 8px}.chat-sdk__stream{display:inline-flex;gap:4px;vertical-align:middle}.chat-sdk__stream span{width:4px;height:4px;background:currentColor;border-radius:50%;animation:chat-sdk-pulse 1.4s infinite ease-in-out both}.chat-sdk__stream span:nth-child(1){animation-delay:-.32s}.chat-sdk__stream span:nth-child(2){animation-delay:-.16s}@keyframes chat-sdk-pulse{0%,80%,to{transform:scale(0)}40%{transform:scale(1)}}";exports.ChatProvider=on;exports.ChatWidget=et;exports.style=fn;exports.useChat=Ze;
22
+ <%s key={someKey} {...props} />`,C,N,V,N),Oe[N+C]=!0)}if(N=null,T!==void 0&&(t(T),N=""+T),o(k)&&(t(k.key),N=""+k.key),"key"in k){T={};for(var he in k)he!=="key"&&(T[he]=k[he])}else T=k;return N&&c(T,typeof a=="function"?a.displayName||a.name||"Unknown":a),l(a,N,T,r(),Q,ce)}function p(a){m(a)?a._store&&(a._store.validated=1):typeof a=="object"&&a!==null&&a.$$typeof===L&&(a._payload.status==="fulfilled"?m(a._payload.value)&&a._payload.value._store&&(a._payload.value._store.validated=1):a._store&&(a._store.validated=1))}function m(a){return typeof a=="object"&&a!==null&&a.$$typeof===w}var b=R,w=Symbol.for("react.transitional.element"),P=Symbol.for("react.portal"),q=Symbol.for("react.fragment"),h=Symbol.for("react.strict_mode"),_=Symbol.for("react.profiler"),v=Symbol.for("react.consumer"),E=Symbol.for("react.context"),A=Symbol.for("react.forward_ref"),y=Symbol.for("react.suspense"),x=Symbol.for("react.suspense_list"),O=Symbol.for("react.memo"),L=Symbol.for("react.lazy"),z=Symbol.for("react.activity"),F=Symbol.for("react.client.reference"),oe=b.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Re=Object.prototype.hasOwnProperty,tt=Array.isArray,ae=console.createTask?console.createTask:function(){return null};b={react_stack_bottom_frame:function(a){return a()}};var Se,Ae={},Ce=b.react_stack_bottom_frame.bind(b,i)(),Ne=ae(n(i)),Oe={};W.Fragment=q,W.jsx=function(a,k,T){var C=1e4>oe.recentlyCreatedOwnerStacks++;return f(a,k,T,!1,C?Error("react-stack-top-frame"):Ce,C?ae(n(a)):Ne)},W.jsxs=function(a,k,T){var C=1e4>oe.recentlyCreatedOwnerStacks++;return f(a,k,T,!0,C?Error("react-stack-top-frame"):Ce,C?ae(n(a)):Ne)}}()),W}process.env.NODE_ENV==="production"?pe.exports=st():pe.exports=rt();var u=pe.exports;const j=Object.create(null);j.open="0";j.close="1";j.ping="2";j.pong="3";j.message="4";j.upgrade="5";j.noop="6";const Z=Object.create(null);Object.keys(j).forEach(s=>{Z[j[s]]=s});const ge={type:"error",data:"parser error"},qe=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Ue=typeof ArrayBuffer=="function",Me=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,xe=({type:s,data:e},t,n)=>qe&&e instanceof Blob?t?n(e):Le(e,n):Ue&&(e instanceof ArrayBuffer||Me(e))?t?n(e):Le(new Blob([e]),n):n(j[s]+(e||"")),Le=(s,e)=>{const t=new FileReader;return t.onload=function(){const n=t.result.split(",")[1];e("b"+(n||""))},t.readAsDataURL(s)};function Ie(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}let le;function it(s,e){if(qe&&s.data instanceof Blob)return s.data.arrayBuffer().then(Ie).then(e);if(Ue&&(s.data instanceof ArrayBuffer||Me(s.data)))return e(Ie(s.data));xe(s,!1,t=>{le||(le=new TextEncoder),e(le.encode(t))})}const De="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",K=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<De.length;s++)K[De.charCodeAt(s)]=s;const ot=s=>{let e=s.length*.75,t=s.length,n,r=0,i,o,c,d;s[s.length-1]==="="&&(e--,s[s.length-2]==="="&&e--);const l=new ArrayBuffer(e),f=new Uint8Array(l);for(n=0;n<t;n+=4)i=K[s.charCodeAt(n)],o=K[s.charCodeAt(n+1)],c=K[s.charCodeAt(n+2)],d=K[s.charCodeAt(n+3)],f[r++]=i<<2|o>>4,f[r++]=(o&15)<<4|c>>2,f[r++]=(c&3)<<6|d&63;return l},at=typeof ArrayBuffer=="function",ve=(s,e)=>{if(typeof s!="string")return{type:"message",data:Fe(s,e)};const t=s.charAt(0);return t==="b"?{type:"message",data:ct(s.substring(1),e)}:Z[t]?s.length>1?{type:Z[t],data:s.substring(1)}:{type:Z[t]}:ge},ct=(s,e)=>{if(at){const t=ot(s);return Fe(t,e)}else return{base64:!0,data:s}},Fe=(s,e)=>{switch(e){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}},Ve="",ht=(s,e)=>{const t=s.length,n=new Array(t);let r=0;s.forEach((i,o)=>{xe(i,!1,c=>{n[o]=c,++r===t&&e(n.join(Ve))})})},lt=(s,e)=>{const t=s.split(Ve),n=[];for(let r=0;r<t.length;r++){const i=ve(t[r],e);if(n.push(i),i.type==="error")break}return n};function ut(){return new TransformStream({transform(s,e){it(s,t=>{const n=t.length;let r;if(n<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,n);else if(n<65536){r=new Uint8Array(3);const i=new DataView(r.buffer);i.setUint8(0,126),i.setUint16(1,n)}else{r=new Uint8Array(9);const i=new DataView(r.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(n))}s.data&&typeof s.data!="string"&&(r[0]|=128),e.enqueue(r),e.enqueue(t)})}})}let ue;function J(s){return s.reduce((e,t)=>e+t.length,0)}function X(s,e){if(s[0].length===e)return s.shift();const t=new Uint8Array(e);let n=0;for(let r=0;r<e;r++)t[r]=s[0][n++],n===s[0].length&&(s.shift(),n=0);return s.length&&n<s[0].length&&(s[0]=s[0].slice(n)),t}function dt(s,e){ue||(ue=new TextDecoder);const t=[];let n=0,r=-1,i=!1;return new TransformStream({transform(o,c){for(t.push(o);;){if(n===0){if(J(t)<1)break;const d=X(t,1);i=(d[0]&128)===128,r=d[0]&127,r<126?n=3:r===126?n=1:n=2}else if(n===1){if(J(t)<2)break;const d=X(t,2);r=new DataView(d.buffer,d.byteOffset,d.length).getUint16(0),n=3}else if(n===2){if(J(t)<8)break;const d=X(t,8),l=new DataView(d.buffer,d.byteOffset,d.length),f=l.getUint32(0);if(f>Math.pow(2,21)-1){c.enqueue(ge);break}r=f*Math.pow(2,32)+l.getUint32(4),n=3}else{if(J(t)<r)break;const d=X(t,r);c.enqueue(ve(i?d:ue.decode(d),e)),n=0}if(r===0||r>s){c.enqueue(ge);break}}}})}const $e=4;function S(s){if(s)return ft(s)}function ft(s){for(var e in S.prototype)s[e]=S.prototype[e];return s}S.prototype.on=S.prototype.addEventListener=function(s,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+s]=this._callbacks["$"+s]||[]).push(e),this};S.prototype.once=function(s,e){function t(){this.off(s,t),e.apply(this,arguments)}return t.fn=e,this.on(s,t),this};S.prototype.off=S.prototype.removeListener=S.prototype.removeAllListeners=S.prototype.removeEventListener=function(s,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+s];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+s],this;for(var n,r=0;r<t.length;r++)if(n=t[r],n===e||n.fn===e){t.splice(r,1);break}return t.length===0&&delete this._callbacks["$"+s],this};S.prototype.emit=function(s){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+s],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,r=t.length;n<r;++n)t[n].apply(this,e)}return this};S.prototype.emitReserved=S.prototype.emit;S.prototype.listeners=function(s){return this._callbacks=this._callbacks||{},this._callbacks["$"+s]||[]};S.prototype.hasListeners=function(s){return!!this.listeners(s).length};const re=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),B=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),pt="arraybuffer";function He(s,...e){return e.reduce((t,n)=>(s.hasOwnProperty(n)&&(t[n]=s[n]),t),{})}const gt=B.setTimeout,_t=B.clearTimeout;function ie(s,e){e.useNativeTimers?(s.setTimeoutFn=gt.bind(B),s.clearTimeoutFn=_t.bind(B)):(s.setTimeoutFn=B.setTimeout.bind(B),s.clearTimeoutFn=B.clearTimeout.bind(B))}const mt=1.33;function yt(s){return typeof s=="string"?kt(s):Math.ceil((s.byteLength||s.size)*mt)}function kt(s){let e=0,t=0;for(let n=0,r=s.length;n<r;n++)e=s.charCodeAt(n),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(n++,t+=4);return t}function We(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function bt(s){let e="";for(let t in s)s.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(s[t]));return e}function xt(s){let e={},t=s.split("&");for(let n=0,r=t.length;n<r;n++){let i=t[n].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}class vt extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class we extends S{constructor(e){super(),this.writable=!1,ie(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new vt(e,t,n)),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=ve(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=bt(e);return t.length?"?"+t:""}}class wt extends we{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 n=0;this._polling&&(n++,this.once("pollComplete",function(){--n||t()})),this.writable||(n++,this.once("drain",function(){--n||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};lt(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,ht(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]=We()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let Ye=!1;try{Ye=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Et=Ye;function Tt(){}class Rt extends wt{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(r,i)=>{this.onError("xhr post error",r,i)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}}class D extends S{constructor(e,t,n){super(),this.createRequest=e,ie(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var e;const t=He(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&n.setRequestHeader(r,this._opts.extraHeaders[r])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var r;n.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},n.send(this._data)}catch(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=D.requestsCount++,D.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Tt,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete D.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}D.requestsCount=0;D.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",je);else if(typeof addEventListener=="function"){const s="onpagehide"in B?"pagehide":"unload";addEventListener(s,je,!1)}}function je(){for(let s in D.requests)D.requests.hasOwnProperty(s)&&D.requests[s].abort()}const St=function(){const s=Ke({xdomain:!1});return s&&s.responseType!==null}();class At extends Rt{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=St&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new D(Ke,this.uri(),e)}}function Ke(s){const e=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Et))return new XMLHttpRequest}catch{}if(!e)try{return new B[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const ze=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Ct extends we{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=ze?{}:He(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(r){return this.emitReserved("error",r)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;xe(n,this.supportsBinary,i=>{try{this.doWrite(n,i)}catch{}r&&re(()=>{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]=We()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const de=B.WebSocket||B.MozWebSocket;class Nt extends Ct{createSocket(e,t,n){return ze?new de(e,t,n):t?new de(e,t):new de(e)}doWrite(e,t){this.ws.send(t)}}class Ot extends we{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=dt(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=ut();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();const i=()=>{n.read().then(({done:c,value:d})=>{c||(this.onPacket(d),i())}).catch(c=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&re(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const Pt={websocket:Nt,webtransport:Ot,polling:At},Bt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Lt=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function _e(s){if(s.length>8e3)throw"URI too long";const e=s,t=s.indexOf("["),n=s.indexOf("]");t!=-1&&n!=-1&&(s=s.substring(0,t)+s.substring(t,n).replace(/:/g,";")+s.substring(n,s.length));let r=Bt.exec(s||""),i={},o=14;for(;o--;)i[Lt[o]]=r[o]||"";return t!=-1&&n!=-1&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=It(i,i.path),i.queryKey=Dt(i,i.query),i}function It(s,e){const t=/\/{2,9}/g,n=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&n.splice(0,1),e.slice(-1)=="/"&&n.splice(n.length-1,1),n}function Dt(s,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,r,i){r&&(t[r]=i)}),t}const me=typeof addEventListener=="function"&&typeof removeEventListener=="function",ee=[];me&&addEventListener("offline",()=>{ee.forEach(s=>s())},!1);class M extends S{constructor(e,t){if(super(),this.binaryType=pt,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 n=_e(e);t.hostname=n.host,t.secure=n.protocol==="https"||n.protocol==="wss",t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=_e(t.host).host);ie(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(n=>{const r=n.prototype.name;this.transports.push(r),this._transportsByName[r]=n}),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=xt(this.opts.query)),me&&(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"})},ee.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=$e,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&M.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",M.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 n=0;n<this.writeBuffer.length;n++){const r=this.writeBuffer[n].data;if(r&&(t+=yt(r)),n>0&&t>this._maxPayload)return this.writeBuffer.slice(0,n);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,re(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,r){if(typeof t=="function"&&(r=t,t=void 0),typeof n=="function"&&(r=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const i={type:e,data:t,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{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?n():e()}):this.upgrading?n():e()),this}_onError(e){if(M.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(),me&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=ee.indexOf(this._offlineEventListener);n!==-1&&ee.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}M.protocol=$e;class jt extends M{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),n=!1;M.priorWebsocketSuccess=!1;const r=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",p=>{if(!n)if(p.type==="pong"&&p.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;M.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(f(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const m=new Error("probe error");m.transport=t.name,this.emitReserved("upgradeError",m)}}))};function i(){n||(n=!0,f(),t.close(),t=null)}const o=p=>{const m=new Error("probe error: "+p);m.transport=t.name,i(),this.emitReserved("upgradeError",m)};function c(){o("transport closed")}function d(){o("socket closed")}function l(p){t&&p.name!==t.name&&i()}const f=()=>{t.removeListener("open",r),t.removeListener("error",o),t.removeListener("close",c),this.off("close",d),this.off("upgrading",l)};t.once("open",r),t.once("error",o),t.once("close",c),this.once("close",d),this.once("upgrading",l),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}let qt=class extends jt{constructor(e,t={}){const n=typeof e=="object"?e:t;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(r=>Pt[r]).filter(r=>!!r)),super(e,n)}};function Ut(s,e="",t){let n=s;t=t||typeof location<"u"&&location,s==null&&(s=t.protocol+"//"+t.host),typeof s=="string"&&(s.charAt(0)==="/"&&(s.charAt(1)==="/"?s=t.protocol+s:s=t.host+s),/^(https?|wss?):\/\//.test(s)||(typeof t<"u"?s=t.protocol+"//"+s:s="https://"+s),n=_e(s)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+e,n.href=n.protocol+"://"+i+(t&&t.port===n.port?"":":"+n.port),n}const Mt=typeof ArrayBuffer=="function",Ft=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,Qe=Object.prototype.toString,Vt=typeof Blob=="function"||typeof Blob<"u"&&Qe.call(Blob)==="[object BlobConstructor]",$t=typeof File=="function"||typeof File<"u"&&Qe.call(File)==="[object FileConstructor]";function Ee(s){return Mt&&(s instanceof ArrayBuffer||Ft(s))||Vt&&s instanceof Blob||$t&&s instanceof File}function te(s,e){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let t=0,n=s.length;t<n;t++)if(te(s[t]))return!0;return!1}if(Ee(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return te(s.toJSON(),!0);for(const t in s)if(Object.prototype.hasOwnProperty.call(s,t)&&te(s[t]))return!0;return!1}function Ht(s){const e=[],t=s.data,n=s;return n.data=ye(t,e),n.attachments=e.length,{packet:n,buffers:e}}function ye(s,e){if(!s)return s;if(Ee(s)){const t={_placeholder:!0,num:e.length};return e.push(s),t}else if(Array.isArray(s)){const t=new Array(s.length);for(let n=0;n<s.length;n++)t[n]=ye(s[n],e);return t}else if(typeof s=="object"&&!(s instanceof Date)){const t={};for(const n in s)Object.prototype.hasOwnProperty.call(s,n)&&(t[n]=ye(s[n],e));return t}return s}function Wt(s,e){return s.data=ke(s.data,e),delete s.attachments,s}function ke(s,e){if(!s)return s;if(s&&s._placeholder===!0){if(typeof s.num=="number"&&s.num>=0&&s.num<e.length)return e[s.num];throw new Error("illegal attachments")}else if(Array.isArray(s))for(let t=0;t<s.length;t++)s[t]=ke(s[t],e);else if(typeof s=="object")for(const t in s)Object.prototype.hasOwnProperty.call(s,t)&&(s[t]=ke(s[t],e));return s}const Je=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],Yt=5;var g;(function(s){s[s.CONNECT=0]="CONNECT",s[s.DISCONNECT=1]="DISCONNECT",s[s.EVENT=2]="EVENT",s[s.ACK=3]="ACK",s[s.CONNECT_ERROR=4]="CONNECT_ERROR",s[s.BINARY_EVENT=5]="BINARY_EVENT",s[s.BINARY_ACK=6]="BINARY_ACK"})(g||(g={}));class Kt{constructor(e){this.replacer=e}encode(e){return(e.type===g.EVENT||e.type===g.ACK)&&te(e)?this.encodeAsBinary({type:e.type===g.EVENT?g.BINARY_EVENT:g.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===g.BINARY_EVENT||e.type===g.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=Ht(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}}class Te extends S{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 n=t.type===g.BINARY_EVENT;n||t.type===g.BINARY_ACK?(t.type=n?g.EVENT:g.ACK,this.reconstructor=new zt(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(Ee(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 n={type:Number(e.charAt(0))};if(g[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===g.BINARY_EVENT||n.type===g.BINARY_ACK){const i=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const o=e.substring(i,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");n.attachments=Number(o)}if(e.charAt(t+1)==="/"){const i=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););n.nsp=e.substring(i,t)}else n.nsp="/";const r=e.charAt(t+1);if(r!==""&&Number(r)==r){const i=t+1;for(;++t;){const o=e.charAt(t);if(o==null||Number(o)!=o){--t;break}if(t===e.length)break}n.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(Te.isPayloadValid(n.type,i))n.data=i;else throw new Error("invalid payload")}return n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case g.CONNECT:return se(t);case g.DISCONNECT:return t===void 0;case g.CONNECT_ERROR:return typeof t=="string"||se(t);case g.EVENT:case g.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Je.indexOf(t[0])===-1);case g.ACK:case g.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class zt{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=Wt(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function Qt(s){return typeof s=="string"}const Jt=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s};function Xt(s){return s===void 0||Jt(s)}function se(s){return Object.prototype.toString.call(s)==="[object Object]"}function Gt(s,e){switch(s){case g.CONNECT:return e===void 0||se(e);case g.DISCONNECT:return e===void 0;case g.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Je.indexOf(e[0])===-1);case g.ACK:return Array.isArray(e);case g.CONNECT_ERROR:return typeof e=="string"||se(e);default:return!1}}function Zt(s){return Qt(s.nsp)&&Xt(s.id)&&Gt(s.type,s.data)}const en=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Te,Encoder:Kt,get PacketType(){return g},isPacketValid:Zt,protocol:Yt},Symbol.toStringTag,{value:"Module"}));function I(s,e,t){return s.on(e,t),function(){s.off(e,t)}}const tn=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Xe extends S{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[I(e,"open",this.onopen.bind(this)),I(e,"packet",this.onpacket.bind(this)),I(e,"error",this.onerror.bind(this)),I(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 n,r,i;if(tn.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:g.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const f=this.ids++,p=t.pop();this._registerAckCallback(f,p),o.id=f}const c=(r=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||r===void 0?void 0:r.writable,d=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!c||(d?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var n;const r=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(r===void 0){this.acks[e]=t;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===e&&this.sendBuffer.splice(c,1);t.call(this,new Error("operation has timed out"))},r),o=(...c)=>{this.io.clearTimeoutFn(i),t.apply(this,c)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((n,r)=>{const i=(o,c)=>o?r(o):n(c);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((r,...i)=>(this._queue[0],r!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(r)):(this._queue.shift(),t&&t(null,...i)),n.pending=!1,this._drainQueue())),this._queue.push(n),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:g.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(n=>String(n.id)===e)){const n=this.acks[e];delete this.acks[e],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case g.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 g.EVENT:case g.BINARY_EVENT:this.onevent(e);break;case g.ACK:case g.BINARY_ACK:this.onack(e);break;case g.DISCONNECT:this.ondisconnect();break;case g.CONNECT_ERROR:this.destroy();const n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);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 n of t)n.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 n=!1;return function(...r){n||(n=!0,t.packet({type:g.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:g.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function $(s){s=s||{},this.ms=s.min||100,this.max=s.max||1e4,this.factor=s.factor||2,this.jitter=s.jitter>0&&s.jitter<=1?s.jitter:0,this.attempts=0}$.prototype.duration=function(){var s=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*s);s=Math.floor(e*10)&1?s+t:s-t}return Math.min(s,this.max)|0};$.prototype.reset=function(){this.attempts=0};$.prototype.setMin=function(s){this.ms=s};$.prototype.setMax=function(s){this.max=s};$.prototype.setJitter=function(s){this.jitter=s};class be extends S{constructor(e,t){var n;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,ie(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((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new $({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||en;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new qt(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=I(t,"open",function(){n.onopen(),e&&e()}),i=c=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",c),e?e(c):this.maybeReconnectOnOpen()},o=I(t,"error",i);if(this._timeout!==!1){const c=this._timeout,d=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),t.close()},c);this.opts.autoUnref&&d.unref(),this.subs.push(()=>{this.clearTimeoutFn(d)})}return this.subs.push(r),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(I(e,"ping",this.onping.bind(this)),I(e,"data",this.ondata.bind(this)),I(e,"error",this.onerror.bind(this)),I(e,"close",this.onclose.bind(this)),I(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){re(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new Xe(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const n of t)if(this.nsps[n].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(r=>{r?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",r)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const Y={};function ne(s,e){typeof s=="object"&&(e=s,s=void 0),e=e||{};const t=Ut(s,e.path||"/socket.io"),n=t.source,r=t.id,i=t.path,o=Y[r]&&i in Y[r].nsps,c=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let d;return c?d=new be(n,e):(Y[r]||(Y[r]=new be(n,e)),d=Y[r]),t.query&&!e.query&&(e.query=t.queryKey),d.socket(t.path,e)}Object.assign(ne,{Manager:be,Socket:Xe,io:ne,connect:ne});function U(){return`${Date.now().toString(36)}-${Math.random().toString(16).slice(2,8)}`}class nn{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 n;return(n=this.listeners.get(e))==null?void 0:n.delete(t)}}emit(e,t){var n;(n=this.listeners.get(e))==null||n.forEach(r=>{var i,o;try{r(t)}catch(c){(o=(i=this.config.logger)==null?void 0:i.error)==null||o.call(i,`chat-sdk listener error for ${e}`,c)}})}setConnection(e){var t,n;this.emit("connection",e),(n=(t=this.config).onConnectionChange)==null||n.call(t,e)}async getToken(){var t,n;const{tokenProvider:e}=this.config;if(!e)return null;try{return(typeof e=="function"?await e():e)||null}catch(r){return(n=(t=this.config.logger)==null?void 0:t.warn)==null||n.call(t,"chat-sdk token provider failed",r),null}}async connect(){var i;if((i=this.socket)!=null&&i.connected)return;const e=new URL(this.config.websocketUrl),t=e.pathname==="/"?"/socket.io":e.pathname,n=e.origin,r=await this.getToken();return this.socket=ne(n,{path:t,transports:["websocket","polling"],autoConnect:!1,reconnection:!1,auth:r?{token:r}:void 0,withCredentials:!0}),this.registerSocketEvents(),this.setConnection({connected:!1,connecting:!0}),new Promise((o,c)=>{const d=setTimeout(()=>{c(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(),c(l)}),this.socket.connect()})}disconnect(){var e;(e=this.socket)==null||e.disconnect(),this.socket=null,this.setConnection({connected:!1,connecting:!1})}async submitInstruction(e,t){var i,o;if(!((i=this.socket)!=null&&i.connected))throw new Error("Not connected");this.lastContext=t;const n=await this.getToken(),r={trans_doc_id:t.trans_doc_id,page_num:t.page_num,instruction:e,modification_level:"page",access_token:n||void 0,region_coordinates:t.highlighted_region?{start_offset:t.highlighted_region.start_offset,end_offset:t.highlighted_region.end_offset}:void 0,region_text:(o=t.highlighted_region)==null?void 0:o.text,selection_id:t.selection_id};this.socket.emit("INSTR_SUBMIT",r)}async requestChatHistory(e){var n;if(!((n=this.socket)!=null&&n.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 n;if(!((n=this.socket)!=null&&n.connected))throw new Error("Not connected");const t=await this.getToken();this.socket.emit("PATCH_DECISION",{...e,access_token:t||void 0})}async requestPageTranslation(e){var r,i,o,c,d;if(!((r=this.socket)!=null&&r.connected))throw new Error("Not connected");const t=await this.getToken(),n={...e,access_token:t||void 0};(o=(i=this.config.logger)==null?void 0:i.log)==null||o.call(i,"[chat-sdk] Sending PAGE_TRANSLATION_REQUEST:",{trans_doc_id:e.trans_doc_id,page_num:e.page_num,has_access_token:!!t}),this.socket.emit("PAGE_TRANSLATION_REQUEST",n),(d=(c=this.config.logger)==null?void 0:c.log)==null||d.call(c,"[chat-sdk] PAGE_TRANSLATION_REQUEST emitted successfully")}async requestBulkTranslation(e){var r,i,o,c,d;if(!((r=this.socket)!=null&&r.connected))throw new Error("Not connected");const t=await this.getToken(),n={...e,access_token:t||void 0};(o=(i=this.config.logger)==null?void 0:i.log)==null||o.call(i,"[chat-sdk] Sending BULK_TRANSLATION_REQUEST:",{trans_doc_id:e.trans_doc_id,page_list:e.page_list,has_access_token:!!t}),this.socket.emit("BULK_TRANSLATION_REQUEST",n),(d=(c=this.config.logger)==null?void 0:c.log)==null||d.call(c,"[chat-sdk] BULK_TRANSLATION_REQUEST emitted successfully")}async cancelBulkTranslation(e){var n,r,i,o,c;if(!((n=this.socket)!=null&&n.connected))throw new Error("Not connected");const t=await this.getToken();(i=(r=this.config.logger)==null?void 0:r.log)==null||i.call(r,"[chat-sdk] Sending CANCEL_BULK_TRANSLATION_REQUEST:",{trans_doc_id:e,has_access_token:!!t}),this.socket.emit("CANCEL_BULK_TRANSLATION_REQUEST",{trans_doc_id:e,access_token:t||void 0}),(c=(o=this.config.logger)==null?void 0:o.log)==null||c.call(o,"[chat-sdk] CANCEL_BULK_TRANSLATION_REQUEST emitted successfully")}registerSocketEvents(){this.socket&&(this.socket.on("disconnect",()=>{this.setConnection({connected:!1,connecting:!1}),this.handleReconnect()}),this.socket.on("connect_error",e=>{this.setConnection({connected:!1,connecting:!1,error:e.message}),this.handleReconnect()}),this.socket.on("CHAT_RESPONSE",e=>{this.emit("chat-response",e)}),this.socket.on("PATCH_OFFER",e=>{this.emit("patch-offer",e)}),this.socket.on("CHAT_HISTORY_RESPONSE",e=>{this.emit("chat-history-response",e)}),this.socket.on("INSTRUCTION_ERROR",e=>{this.emit("instruction-error",e)}),this.socket.on("PAGE_TRANSLATION_RESPONSE",e=>{var t,n,r,i,o,c,d,l,f,p,m;(r=(t=this.config.logger)==null?void 0:t.log)==null||r.call(t,"[chat-sdk] Received PAGE_TRANSLATION_RESPONSE from socket:",{trans_doc_id:e.trans_doc_id,page_num:e.page_num,status:e.status,has_content:!!e.trans_page_content,content_length:(n=e.trans_page_content)==null?void 0:n.length,error:e.error,error_type:e.error_type,updated_at:e.updated_at}),this.emit("page-translation-response",e),(o=(i=this.config.logger)==null?void 0:i.log)==null||o.call(i,"[chat-sdk] Emitted page-translation-response internally"),this.config.onPageTranslationResponse?((d=(c=this.config.logger)==null?void 0:c.log)==null||d.call(c,"[chat-sdk] Calling onPageTranslationResponse callback"),this.config.onPageTranslationResponse(e),(f=(l=this.config.logger)==null?void 0:l.log)==null||f.call(l,"[chat-sdk] onPageTranslationResponse callback completed")):(m=(p=this.config.logger)==null?void 0:p.log)==null||m.call(p,"[chat-sdk] No onPageTranslationResponse callback configured")}),this.socket.on("BULK_TRANSLATION_RESPONSE",e=>{var t,n,r,i,o,c,d,l,f,p;(n=(t=this.config.logger)==null?void 0:t.log)==null||n.call(t,"[chat-sdk] Received BULK_TRANSLATION_RESPONSE from socket:",{trans_doc_id:e.trans_doc_id,status:e.status,completed_pages:e.completed_pages,total_pages:e.total_pages,current_page:e.current_page,error:e.error,error_type:e.error_type}),this.emit("bulk-translation-response",e),(i=(r=this.config.logger)==null?void 0:r.log)==null||i.call(r,"[chat-sdk] Emitted bulk-translation-response internally"),this.config.onBulkTranslationResponse?((c=(o=this.config.logger)==null?void 0:o.log)==null||c.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")):(p=(f=this.config.logger)==null?void 0:f.log)==null||p.call(f,"[chat-sdk] No onBulkTranslationResponse callback configured")}),this.socket.on("connected",()=>{this.lastContext&&this.requestChatHistory(this.lastContext).catch(e=>{var t,n;return(n=(t=this.config.logger)==null?void 0:t.warn)==null?void 0:n.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(n=>{var r,i;return(i=(r=this.config.logger)==null?void 0:r.error)==null?void 0:i.call(r,"chat-sdk reconnect failed",n)})},this.config.reconnectDelayMs)}}function sn(s){return s.map(e=>{const t={id:U(),instructionId:e.instruction_id,pageNum:e.page_num,timestamp:new Date(e.timestamp)},n={...t,type:"user",content:e.instruction,contextText:e.region_text},r=[];return e.response_content&&e.response_type==="chat"&&r.push({...t,type:"ai-chat",content:e.response_content}),e.response_content&&e.response_type==="patch"&&r.push({...t,type:"ai-patch",content:e.response_content,patchData:{originalText:e.region_text,improvedText:e.response_content,regionText:e.region_text,isComplete:!0}}),[n,...r]}).flat().sort((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())}const Ge=R.createContext(null),rn={connected:!1,connecting:!1};function on({config:s,children:e}){const t=R.useRef(null),n=R.useRef(new Map),[r,i]=R.useState({messages:[],connection:rn,latestPatchOffer:null,isSubmitting:!1}),o=R.useMemo(()=>({reconnectAttempts:5,reconnectDelayMs:1500,...s}),[s]);R.useEffect(()=>{const l=new nn(o);t.current=l;const f=l.on("connection",h=>{i(_=>({..._,connection:h}))}),p=l.on("chat-response",h=>{i(_=>{const v=[..._.messages];let E=v.find(x=>x.instructionId===h.instruction_id&&x.type==="ai-chat");E||(E={id:U(),type:"ai-chat",content:"",timestamp:new Date,instructionId:h.instruction_id,pageNum:h.page_num,isStreaming:!0},v.push(E));const A={...E,content:(E.content||"")+(h.chunk_text||""),isStreaming:!h.is_final},y=v.map(x=>x.id===E.id?A:x);return{..._,messages:y,isSubmitting:h.is_final?!1:_.isSubmitting}})}),m=l.on("patch-offer",h=>{var E;const _=`${h.trans_doc_id}-${h.instruction_id}`,v=n.current.get(_)??{trans_doc_id:h.trans_doc_id,page_num:h.page_num,instruction_id:h.instruction_id,original_text:h.region_original_text||"",highlighted_region:h.region_coordinates,new_suggestion:"",is_page_level:!h.region_coordinates,selection_id:h.selection_id};if(v.new_suggestion+=h.region_replacement_text_chunk||"",h.selection_id&&!v.selection_id&&(v.selection_id=h.selection_id),n.current.set(_,v),i(A=>{var z;const y=[...A.messages];let x=y.find(F=>F.instructionId===h.instruction_id&&F.type==="ai-patch");x||(x={id:U(),type:"ai-patch",content:"",timestamp:new Date,instructionId:h.instruction_id,pageNum:h.page_num,isStreaming:!0,patchData:{originalText:h.region_original_text,improvedText:"",regionText:h.region_original_text,isComplete:!1}},y.push(x));const O={...x,content:(x.content||"")+(h.region_replacement_text_chunk||""),isStreaming:!h.is_final,patchData:{...x.patchData,improvedText:(((z=x.patchData)==null?void 0:z.improvedText)||"")+(h.region_replacement_text_chunk||""),regionText:h.region_original_text,isComplete:h.is_final}},L=y.map(F=>F.id===x.id?O:F);return{...A,messages:L,isSubmitting:h.is_final?!1:A.isSubmitting}}),h.is_final){const A=n.current.get(_);A&&((E=o.onPatchOffer)==null||E.call(o,A),i(y=>({...y,latestPatchOffer:A}))),n.current.delete(_)}}),b=l.on("chat-history-response",h=>{if(h.status==="success"){const _=sn(h.messages);i(v=>({...v,messages:_}))}else i(_=>({..._,messages:[..._.messages,{id:U(),type:"system",content:h.error||"Failed to load chat history",timestamp:new Date}]}))}),w=l.on("instruction-error",h=>{i(_=>({..._,isSubmitting:!1,messages:[..._.messages,{id:U(),type:"error",content:h.error,timestamp:new Date}]}))}),P=l.on("page-translation-response",h=>{var _,v,E,A,y,x,O,L;(v=(_=o.logger)==null?void 0:_.log)==null||v.call(_,"[chat-sdk][ChatProvider] Received page-translation-response event:",{trans_doc_id:h.trans_doc_id,page_num:h.page_num,status:h.status,has_content:!!h.trans_page_content,error:h.error}),o.onPageTranslationResponse?((A=(E=o.logger)==null?void 0:E.log)==null||A.call(E,"[chat-sdk][ChatProvider] Invoking onPageTranslationResponse callback from config"),o.onPageTranslationResponse(h),(x=(y=o.logger)==null?void 0:y.log)==null||x.call(y,"[chat-sdk][ChatProvider] onPageTranslationResponse callback completed")):(L=(O=o.logger)==null?void 0:O.log)==null||L.call(O,"[chat-sdk][ChatProvider] No onPageTranslationResponse callback in config")}),q=l.on("bulk-translation-response",h=>{var _,v,E,A,y,x,O,L;(v=(_=o.logger)==null?void 0:_.log)==null||v.call(_,"[chat-sdk][ChatProvider] Received bulk-translation-response event:",{trans_doc_id:h.trans_doc_id,status:h.status,completed_pages:h.completed_pages,total_pages:h.total_pages,current_page:h.current_page,error:h.error}),o.onBulkTranslationResponse?((A=(E=o.logger)==null?void 0:E.log)==null||A.call(E,"[chat-sdk][ChatProvider] Invoking onBulkTranslationResponse callback from config"),o.onBulkTranslationResponse(h),(x=(y=o.logger)==null?void 0:y.log)==null||x.call(y,"[chat-sdk][ChatProvider] onBulkTranslationResponse callback completed")):(L=(O=o.logger)==null?void 0:O.log)==null||L.call(O,"[chat-sdk][ChatProvider] No onBulkTranslationResponse callback in config")});return l.connect().then(()=>{const h=o.contextProvider();if(h)return l.requestChatHistory(h)}).catch(h=>{var _,v;return(v=(_=o.logger)==null?void 0:_.warn)==null?void 0:v.call(_,"chat-sdk connect failed",h)}),()=>{f(),p(),m(),b(),w(),P(),q(),l.disconnect()}},[o]);const c=R.useMemo(()=>({async submitInstruction(l){const f=t.current;if(!f)throw new Error("SDK not ready");const p=o.contextProvider();if(!p)throw new Error("contextProvider returned null");i(m=>{var b;return{...m,isSubmitting:!0,messages:[...m.messages,{id:U(),type:"user",content:l,timestamp:new Date,contextText:(b=p.highlighted_region)==null?void 0:b.text},{id:U(),type:"loading",content:"Processing your instruction...",timestamp:new Date,isStreaming:!0}]}}),await f.submitInstruction(l,p)},async submitInstructionWithContext(l,f){const p=t.current;if(!p)throw new Error("SDK not ready");i(m=>{var b;return{...m,isSubmitting:!0,messages:[...m.messages,{id:U(),type:"user",content:l,timestamp:new Date,contextText:(b=f.highlighted_region)==null?void 0:b.text},{id:U(),type:"loading",content:"Processing your instruction...",timestamp:new Date,isStreaming:!0}]}}),await p.submitInstruction(l,f)},async requestChatHistory(){const l=t.current;if(!l)throw new Error("SDK not ready");const f=o.contextProvider();if(!f)throw new Error("contextProvider returned null");await l.requestChatHistory(f)},async sendPatchDecision(l,f,p,m){const b=t.current;if(!b)throw new Error("SDK not ready");await b.sendPatchDecision({trans_doc_id:l,page_num:f,instruction_id:p,decision:m}),i(w=>({...w,latestPatchOffer:null}))},async requestPageTranslation(l,f){var m,b,w,P;const p=t.current;if(!p)throw new Error("SDK not ready");return(b=(m=o.logger)==null?void 0:m.log)==null||b.call(m,"[chat-sdk][ChatProvider] requestPageTranslation called:",{trans_doc_id:l,page_num:f}),await p.requestPageTranslation({trans_doc_id:l,page_num:f}),(P=(w=o.logger)==null?void 0:w.log)==null||P.call(w,"[chat-sdk][ChatProvider] requestPageTranslation request sent"),!0},async requestBulkTranslation(l,f){var m,b,w,P;const p=t.current;if(!p)throw new Error("SDK not ready");return(b=(m=o.logger)==null?void 0:m.log)==null||b.call(m,"[chat-sdk][ChatProvider] requestBulkTranslation called:",{trans_doc_id:l,page_list:f}),await p.requestBulkTranslation({trans_doc_id:l,page_list:f}),(P=(w=o.logger)==null?void 0:w.log)==null||P.call(w,"[chat-sdk][ChatProvider] requestBulkTranslation request sent"),!0},async cancelBulkTranslation(l){var p,m,b,w;const f=t.current;if(!f)throw new Error("SDK not ready");return(m=(p=o.logger)==null?void 0:p.log)==null||m.call(p,"[chat-sdk][ChatProvider] cancelBulkTranslation called:",{trans_doc_id:l}),await f.cancelBulkTranslation(l),(w=(b=o.logger)==null?void 0:b.log)==null||w.call(b,"[chat-sdk][ChatProvider] cancelBulkTranslation request sent"),!0},clearMessages(){i(l=>({...l,messages:[]}))}}),[o]),d=R.useMemo(()=>({...r,...c}),[r,c]);return u.jsx(Ge.Provider,{value:d,children:e})}function an(){const s=R.useContext(Ge);if(!s)throw new Error("useChat must be used within ChatProvider");return s}function Ze(){return an()}const et=R.forwardRef(({title:s="AI Assistance",placeholder:e="Ask anything...",height:t="500px"},n)=>{const{messages:r,connection:i,submitInstruction:o,submitInstructionWithContext:c,isSubmitting:d}=Ze(),[l,f]=R.useState(""),[p,m]=R.useState(null),[b,w]=R.useState(null),P=R.useRef(null),q=R.useRef(null),h=!i.connected||d;R.useImperativeHandle(n,()=>({setContext:({text:y,context:x})=>{w(y),m(x),setTimeout(()=>{var O;(O=q.current)==null||O.focus()},100)},focusInput:()=>{var y;(y=q.current)==null||y.focus()}}),[]);const _=R.useMemo(()=>[...r].sort((y,x)=>y.timestamp.getTime()-x.timestamp.getTime()),[r]);R.useEffect(()=>{P.current&&(P.current.scrollTop=P.current.scrollHeight)},[_]);const v=async y=>{y.preventDefault();const x=l.trim();x&&(p?(await c(x,p),m(null),w(null)):await o(x),f(""))},E=y=>{y.key==="Enter"&&!y.shiftKey&&(y.preventDefault(),v(y))},A=()=>{m(null),w(null)};return u.jsxs("div",{className:"chat-sdk",style:{height:t},children:[u.jsxs("div",{className:"chat-sdk__header",children:[u.jsx("div",{className:"chat-sdk__title",children:s}),u.jsxs("div",{className:"chat-sdk__status",children:[u.jsx("span",{className:`chat-sdk__status-dot ${i.connected?"connected":"disconnected"}`}),i.connected?"Connected":i.connecting?"Connecting...":"Disconnected"]})]}),u.jsx("div",{className:"chat-sdk__messages",ref:P,children:_.length===0?u.jsx("div",{className:"chat-sdk__empty",children:"Welcome! Ask anything about the translation."}):_.map(y=>u.jsx(cn,{message:y},y.id))}),u.jsxs("div",{className:"chat-sdk__composer",children:[u.jsxs("form",{className:"chat-sdk__input-bar",onSubmit:v,children:[b&&u.jsx("div",{className:"chat-sdk__input-context",children:u.jsxs("div",{className:"chat-sdk__context-chip",children:[u.jsx("span",{className:"chat-sdk__context-text",children:b.length>40?`${b.slice(0,40)}…`:b}),u.jsx("button",{type:"button",onClick:A,className:"chat-sdk__context-clear",children:u.jsx(dn,{})})]})}),u.jsx("textarea",{ref:q,className:"chat-sdk__input",placeholder:b?"What would you like to change?":e,value:l,onChange:y=>f(y.target.value),onKeyDown:E,disabled:h,rows:1}),u.jsxs("div",{className:"chat-sdk__actions",children:[u.jsx("div",{className:"chat-sdk__actions-left",children:u.jsx("button",{type:"button",className:"chat-sdk__add-btn",disabled:h,children:u.jsx(un,{})})}),u.jsx("button",{className:"chat-sdk__send",type:"submit",disabled:!l.trim()||h,children:u.jsx(ln,{})})]})]}),i.error&&u.jsxs("div",{className:"chat-sdk__error",children:["⚠️ ",i.error]})]})]})});et.displayName="ChatWidget";function cn({message:s}){var r;const e=s.type==="user",t=s.type==="loading",n=s.type==="ai-patch";return e?u.jsxs("div",{className:"chat-sdk__user-container",children:[s.contextText&&u.jsx("div",{className:"chat-sdk__user-context",children:u.jsx("div",{className:"chat-sdk__context-chip",children:u.jsx("span",{className:"chat-sdk__context-text",children:s.contextText.length>40?`${s.contextText.slice(0,40)}…`:s.contextText})})}),u.jsx("div",{className:"chat-sdk__bubble user",children:u.jsx("div",{className:"chat-sdk__bubble-body",children:s.content})})]}):u.jsx("div",{className:`chat-sdk__bubble ${n?"ai-patch":"ai"}`,children:u.jsxs("div",{className:`chat-sdk__bubble-body ${s.isStreaming?"streaming":""}`,children:[n&&u.jsx("div",{className:"chat-sdk__suggestion-text",children:u.jsx(hn,{instructionId:s.instructionId})}),n&&((r=s.patchData)!=null&&r.originalText)?u.jsxs("div",{className:"chat-sdk__patch",children:[u.jsx("div",{className:"chat-sdk__patch-label",children:"Original"}),u.jsx("div",{className:"chat-sdk__patch-block",children:s.patchData.originalText}),u.jsx("div",{className:"chat-sdk__patch-label",children:"Improved"}),u.jsxs("div",{className:"chat-sdk__patch-block",children:[s.patchData.improvedText,s.isStreaming&&u.jsx(fe,{})]})]}):u.jsxs(u.Fragment,{children:[u.jsx("div",{children:s.content}),t&&u.jsx(fe,{}),s.isStreaming&&!t&&u.jsx(fe,{})]})]})})}const G=["I have a suggestion for you","Here is something you might like","How about this?"];function hn({instructionId:s}){const e=R.useMemo(()=>{if(s){let t=0;for(let n=0;n<s.length;n++)t=(t*31+s.charCodeAt(n))%G.length;return Math.abs(t)%G.length}return Math.floor(Math.random()*G.length)},[s]);return u.jsx(u.Fragment,{children:G[e]})}function ln(){return u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"5"}),u.jsx("polyline",{points:"5 12 12 5 19 12"})]})}function un(){return u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),u.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function dn(){return u.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),u.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function fe(){return u.jsxs("span",{className:"chat-sdk__stream",children:[u.jsx("span",{}),u.jsx("span",{}),u.jsx("span",{})]})}const fn=".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__status{display:flex;align-items:center;gap:6px;color:var(--content-tertiary);font-size:12px}.chat-sdk__status-dot{width:8px;height:8px;border-radius:50%;background:#ef4444}.chat-sdk__status-dot.connected{background:#10b981}.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.user .chat-sdk__bubble-body{color:var(--content-brand1-secondary);font-size:15px;line-height:1.45;white-space:pre-wrap}.chat-sdk__bubble.ai,.chat-sdk__bubble.ai-patch{align-self:flex-start;max-width:90%;display:flex;flex-direction:column}.chat-sdk__bubble-body{display:flex;flex-direction:column;gap:8px;font-size:15px;color:var(--content-primary);line-height:1.5}.chat-sdk__suggestion-text{font-size:13px;color:var(--content-secondary);margin-bottom:0}.chat-sdk__patch{display:flex;flex-direction:column;gap:8px;margin-top:4px}.chat-sdk__patch-label{font-size:12px;color:var(--content-tertiary);font-weight:600}.chat-sdk__patch-block{background:#f3f4f6;border-radius:10px;padding:12px;border:1px solid #e5e7eb;font-size:14px;line-height:1.5;color:var(--content-secondary)}.chat-sdk__composer{padding:var(--spacing-1);background:var(--background-primary)}.chat-sdk__input-bar{display:flex;flex-direction:column;background:#fff;border:1px solid var(--border-secondary);border-radius:var(--radius-large);padding:8px;overflow:hidden}.chat-sdk__input-context{padding:0 4px 8px}.chat-sdk__input-context .chat-sdk__context-chip{background:var(--background-tertiary);padding:8px 12px;border-radius:var(--radius-full);display:inline-flex;align-items:center;gap:8px}.chat-sdk__input-context .chat-sdk__context-text{font-size:14px;line-height:1.45;color:var(--content-primary)}.chat-sdk__context-clear{display:flex;align-items:center;justify-content:center;width:16px;height:16px;padding:0;background:transparent;border:none;color:var(--content-secondary);cursor:pointer;transition:color .15s}.chat-sdk__context-clear:hover{color:var(--content-primary)}.chat-sdk__input{width:100%;border:none;background:transparent;resize:none;min-height:72px;max-height:120px;font-size:15px;font-family:inherit;color:var(--content-primary);outline:none;line-height:1.45;padding:4px 8px}.chat-sdk__input::placeholder{color:var(--content-tertiary)}.chat-sdk__actions{display:flex;align-items:center;justify-content:space-between}.chat-sdk__actions-left{display:flex;align-items:center}.chat-sdk__add-btn{display:flex;align-items:center;justify-content:center;width:28px;height:28px;padding:0;background:transparent;border:none;border-radius:50%;color:var(--content-secondary);cursor:pointer;transition:background .15s,color .15s}.chat-sdk__add-btn:hover:not(:disabled){background:var(--background-tertiary);color:var(--content-primary)}.chat-sdk__add-btn:disabled{opacity:.4;cursor:not-allowed}.chat-sdk__send{display:flex;align-items:center;justify-content:center;width:28px;height:28px;min-width:28px;min-height:28px;background:var(--background-black);color:#fff;border:none;border-radius:50%;cursor:pointer;transition:opacity .2s}.chat-sdk__send:disabled{opacity:.3;cursor:not-allowed}.chat-sdk__send:not(:disabled):hover{opacity:.8}.chat-sdk__error{font-size:12px;color:#dc2626;padding:4px 8px}.chat-sdk__stream{display:inline-flex;gap:4px;vertical-align:middle}.chat-sdk__stream span{width:4px;height:4px;background:currentColor;border-radius:50%;animation:chat-sdk-pulse 1.4s infinite ease-in-out both}.chat-sdk__stream span:nth-child(1){animation-delay:-.32s}.chat-sdk__stream span:nth-child(2){animation-delay:-.16s}@keyframes chat-sdk-pulse{0%,80%,to{transform:scale(0)}40%{transform:scale(1)}}";exports.ChatProvider=on;exports.ChatWidget=et;exports.style=fn;exports.useChat=Ze;
23
23
  //# sourceMappingURL=translation-chat-sdk.cjs.js.map