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