translation-chat-sdk 0.1.8 → 0.2.0

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