teodor-new-chat-ui 4.3.621 → 4.3.623

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/index.umd.js CHANGED
@@ -1,9 +1,9 @@
1
- (function(ne,Pt){typeof exports=="object"&&typeof module<"u"?Pt(exports,require("clsx"),require("tailwind-merge"),require("react"),require("@radix-ui/react-slot"),require("class-variance-authority"),require("react-dom"),require("lucide-react")):typeof define=="function"&&define.amd?define(["exports","clsx","tailwind-merge","react","@radix-ui/react-slot","class-variance-authority","react-dom","lucide-react"],Pt):(ne=typeof globalThis<"u"?globalThis:ne||self,Pt(ne.NewChatUI={},ne.clsx,ne.tailwindMerge,ne.React,ne.reactSlot,ne.classVarianceAuthority,ne.ReactDOM,ne.LucideReact))})(this,function(ne,Pt,Bn,x,sr,Ya,Ls,pe){"use strict";var yC=Object.defineProperty;var SC=(ne,Pt,Bn)=>Pt in ne?yC(ne,Pt,{enumerable:!0,configurable:!0,writable:!0,value:Bn}):ne[Pt]=Bn;var Ga=(ne,Pt,Bn)=>SC(ne,typeof Pt!="symbol"?Pt+"":Pt,Bn);function Xa(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const w=Xa(x),Ja=Xa(Ls);function mp(...e){return Bn.twMerge(Pt.clsx(e))}function Za(e,t){return function(){return e.apply(t,arguments)}}const{toString:gp}=Object.prototype,{getPrototypeOf:$s}=Object,{iterator:bo,toStringTag:Qa}=Symbol,wo=(e=>t=>{const n=gp.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),en=e=>(e=e.toLowerCase(),t=>wo(t)===e),vo=e=>t=>typeof t===e,{isArray:ir}=Array,ar=vo("undefined");function jr(e){return e!==null&&!ar(e)&&e.constructor!==null&&!ar(e.constructor)&&Ot(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const el=en("ArrayBuffer");function xp(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&el(e.buffer),t}const bp=vo("string"),Ot=vo("function"),tl=vo("number"),Pr=e=>e!==null&&typeof e=="object",wp=e=>e===!0||e===!1,yo=e=>{if(wo(e)!=="object")return!1;const t=$s(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Qa in e)&&!(bo in e)},vp=e=>{if(!Pr(e)||jr(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},yp=en("Date"),Sp=en("File"),Cp=en("Blob"),kp=en("FileList"),Tp=e=>Pr(e)&&Ot(e.pipe),Ep=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Ot(e.append)&&((t=wo(e))==="formdata"||t==="object"&&Ot(e.toString)&&e.toString()==="[object FormData]"))},Ip=en("URLSearchParams"),[Ap,Np,_p,jp]=["ReadableStream","Request","Response","Headers"].map(en),Pp=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Or(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),ir(e))for(r=0,o=e.length;r<o;r++)t.call(null,e[r],r,e);else{if(jr(e))return;const s=n?Object.getOwnPropertyNames(e):Object.keys(e),i=s.length;let a;for(r=0;r<i;r++)a=s[r],t.call(null,e[a],a,e)}}function nl(e,t){if(jr(e))return null;t=t.toLowerCase();const n=Object.keys(e);let r=n.length,o;for(;r-- >0;)if(o=n[r],t===o.toLowerCase())return o;return null}const Hn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,rl=e=>!ar(e)&&e!==Hn;function Fs(){const{caseless:e,skipUndefined:t}=rl(this)&&this||{},n={},r=(o,s)=>{const i=e&&nl(n,s)||s;yo(n[i])&&yo(o)?n[i]=Fs(n[i],o):yo(o)?n[i]=Fs({},o):ir(o)?n[i]=o.slice():(!t||!ar(o))&&(n[i]=o)};for(let o=0,s=arguments.length;o<s;o++)arguments[o]&&Or(arguments[o],r);return n}const Op=(e,t,n,{allOwnKeys:r}={})=>(Or(t,(o,s)=>{n&&Ot(o)?e[s]=Za(o,n):e[s]=o},{allOwnKeys:r}),e),Rp=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),Mp=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},Dp=(e,t,n,r)=>{let o,s,i;const a={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),s=o.length;s-- >0;)i=o[s],(!r||r(i,e,t))&&!a[i]&&(t[i]=e[i],a[i]=!0);e=n!==!1&&$s(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},Lp=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},$p=e=>{if(!e)return null;if(ir(e))return e;let t=e.length;if(!tl(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},Fp=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&$s(Uint8Array)),zp=(e,t)=>{const r=(e&&e[bo]).call(e);let o;for(;(o=r.next())&&!o.done;){const s=o.value;t.call(e,s[0],s[1])}},Bp=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},Hp=en("HTMLFormElement"),Up=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),ol=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),Wp=en("RegExp"),sl=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Or(n,(o,s)=>{let i;(i=t(o,s,e))!==!1&&(r[s]=i||o)}),Object.defineProperties(e,r)},Vp=e=>{sl(e,(t,n)=>{if(Ot(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Ot(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},Kp=(e,t)=>{const n={},r=o=>{o.forEach(s=>{n[s]=!0})};return ir(e)?r(e):r(String(e).split(t)),n},qp=()=>{},Gp=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function Yp(e){return!!(e&&Ot(e.append)&&e[Qa]==="FormData"&&e[bo])}const Xp=e=>{const t=new Array(10),n=(r,o)=>{if(Pr(r)){if(t.indexOf(r)>=0)return;if(jr(r))return r;if(!("toJSON"in r)){t[o]=r;const s=ir(r)?[]:{};return Or(r,(i,a)=>{const c=n(i,o+1);!ar(c)&&(s[a]=c)}),t[o]=void 0,s}}return r};return n(e,0)},Jp=en("AsyncFunction"),Zp=e=>e&&(Pr(e)||Ot(e))&&Ot(e.then)&&Ot(e.catch),il=((e,t)=>e?setImmediate:t?((n,r)=>(Hn.addEventListener("message",({source:o,data:s})=>{o===Hn&&s===n&&r.length&&r.shift()()},!1),o=>{r.push(o),Hn.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",Ot(Hn.postMessage)),Qp=typeof queueMicrotask<"u"?queueMicrotask.bind(Hn):typeof process<"u"&&process.nextTick||il,B={isArray:ir,isArrayBuffer:el,isBuffer:jr,isFormData:Ep,isArrayBufferView:xp,isString:bp,isNumber:tl,isBoolean:wp,isObject:Pr,isPlainObject:yo,isEmptyObject:vp,isReadableStream:Ap,isRequest:Np,isResponse:_p,isHeaders:jp,isUndefined:ar,isDate:yp,isFile:Sp,isBlob:Cp,isRegExp:Wp,isFunction:Ot,isStream:Tp,isURLSearchParams:Ip,isTypedArray:Fp,isFileList:kp,forEach:Or,merge:Fs,extend:Op,trim:Pp,stripBOM:Rp,inherits:Mp,toFlatObject:Dp,kindOf:wo,kindOfTest:en,endsWith:Lp,toArray:$p,forEachEntry:zp,matchAll:Bp,isHTMLForm:Hp,hasOwnProperty:ol,hasOwnProp:ol,reduceDescriptors:sl,freezeMethods:Vp,toObjectSet:Kp,toCamelCase:Up,noop:qp,toFiniteNumber:Gp,findKey:nl,global:Hn,isContextDefined:rl,isSpecCompliantForm:Yp,toJSONObject:Xp,isAsyncFn:Jp,isThenable:Zp,setImmediate:il,asap:Qp,isIterable:e=>e!=null&&Ot(e[bo])};function Ie(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o,this.status=o.status?o.status:null)}B.inherits(Ie,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:B.toJSONObject(this.config),code:this.code,status:this.status}}});const al=Ie.prototype,ll={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{ll[e]={value:e}}),Object.defineProperties(Ie,ll),Object.defineProperty(al,"isAxiosError",{value:!0}),Ie.from=(e,t,n,r,o,s)=>{const i=Object.create(al);B.toFlatObject(e,i,function(u){return u!==Error.prototype},l=>l!=="isAxiosError");const a=e&&e.message?e.message:"Error",c=t==null&&e?e.code:t;return Ie.call(i,a,c,n,r,o),e&&i.cause==null&&Object.defineProperty(i,"cause",{value:e,configurable:!0}),i.name=e&&e.name||"Error",s&&Object.assign(i,s),i};const em=null;function zs(e){return B.isPlainObject(e)||B.isArray(e)}function cl(e){return B.endsWith(e,"[]")?e.slice(0,-2):e}function ul(e,t,n){return e?e.concat(t).map(function(o,s){return o=cl(o),!n&&s?"["+o+"]":o}).join(n?".":""):t}function tm(e){return B.isArray(e)&&!e.some(zs)}const nm=B.toFlatObject(B,{},null,function(t){return/^is[A-Z]/.test(t)});function So(e,t,n){if(!B.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=B.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(g,b){return!B.isUndefined(b[g])});const r=n.metaTokens,o=n.visitor||u,s=n.dots,i=n.indexes,c=(n.Blob||typeof Blob<"u"&&Blob)&&B.isSpecCompliantForm(t);if(!B.isFunction(o))throw new TypeError("visitor must be a function");function l(m){if(m===null)return"";if(B.isDate(m))return m.toISOString();if(B.isBoolean(m))return m.toString();if(!c&&B.isBlob(m))throw new Ie("Blob is not supported. Use a Buffer instead.");return B.isArrayBuffer(m)||B.isTypedArray(m)?c&&typeof Blob=="function"?new Blob([m]):Buffer.from(m):m}function u(m,g,b){let v=m;if(m&&!b&&typeof m=="object"){if(B.endsWith(g,"{}"))g=r?g:g.slice(0,-2),m=JSON.stringify(m);else if(B.isArray(m)&&tm(m)||(B.isFileList(m)||B.endsWith(g,"[]"))&&(v=B.toArray(m)))return g=cl(g),v.forEach(function(T,I){!(B.isUndefined(T)||T===null)&&t.append(i===!0?ul([g],I,s):i===null?g:g+"[]",l(T))}),!1}return zs(m)?!0:(t.append(ul(b,g,s),l(m)),!1)}const f=[],h=Object.assign(nm,{defaultVisitor:u,convertValue:l,isVisitable:zs});function p(m,g){if(!B.isUndefined(m)){if(f.indexOf(m)!==-1)throw Error("Circular reference detected in "+g.join("."));f.push(m),B.forEach(m,function(v,y){(!(B.isUndefined(v)||v===null)&&o.call(t,v,B.isString(y)?y.trim():y,g,h))===!0&&p(v,g?g.concat(y):[y])}),f.pop()}}if(!B.isObject(e))throw new TypeError("data must be an object");return p(e),t}function dl(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function Bs(e,t){this._pairs=[],e&&So(e,this,t)}const fl=Bs.prototype;fl.append=function(t,n){this._pairs.push([t,n])},fl.toString=function(t){const n=t?function(r){return t.call(this,r,dl)}:dl;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function rm(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function hl(e,t,n){if(!t)return e;const r=n&&n.encode||rm;B.isFunction(n)&&(n={serialize:n});const o=n&&n.serialize;let s;if(o?s=o(t,n):s=B.isURLSearchParams(t)?t.toString():new Bs(t,n).toString(r),s){const i=e.indexOf("#");i!==-1&&(e=e.slice(0,i)),e+=(e.indexOf("?")===-1?"?":"&")+s}return e}class pl{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){B.forEach(this.handlers,function(r){r!==null&&t(r)})}}const ml={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},om={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:Bs,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},Hs=typeof window<"u"&&typeof document<"u",Us=typeof navigator=="object"&&navigator||void 0,sm=Hs&&(!Us||["ReactNative","NativeScript","NS"].indexOf(Us.product)<0),im=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",am=Hs&&window.location.href||"http://localhost",wt={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Hs,hasStandardBrowserEnv:sm,hasStandardBrowserWebWorkerEnv:im,navigator:Us,origin:am},Symbol.toStringTag,{value:"Module"})),...om};function lm(e,t){return So(e,new wt.classes.URLSearchParams,{visitor:function(n,r,o,s){return wt.isNode&&B.isBuffer(n)?(this.append(r,n.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)},...t})}function cm(e){return B.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function um(e){const t={},n=Object.keys(e);let r;const o=n.length;let s;for(r=0;r<o;r++)s=n[r],t[s]=e[s];return t}function gl(e){function t(n,r,o,s){let i=n[s++];if(i==="__proto__")return!0;const a=Number.isFinite(+i),c=s>=n.length;return i=!i&&B.isArray(o)?o.length:i,c?(B.hasOwnProp(o,i)?o[i]=[o[i],r]:o[i]=r,!a):((!o[i]||!B.isObject(o[i]))&&(o[i]=[]),t(n,r,o[i],s)&&B.isArray(o[i])&&(o[i]=um(o[i])),!a)}if(B.isFormData(e)&&B.isFunction(e.entries)){const n={};return B.forEachEntry(e,(r,o)=>{t(cm(r),o,n,0)}),n}return null}function dm(e,t,n){if(B.isString(e))try{return(t||JSON.parse)(e),B.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const Rr={transitional:ml,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,s=B.isObject(t);if(s&&B.isHTMLForm(t)&&(t=new FormData(t)),B.isFormData(t))return o?JSON.stringify(gl(t)):t;if(B.isArrayBuffer(t)||B.isBuffer(t)||B.isStream(t)||B.isFile(t)||B.isBlob(t)||B.isReadableStream(t))return t;if(B.isArrayBufferView(t))return t.buffer;if(B.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let a;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return lm(t,this.formSerializer).toString();if((a=B.isFileList(t))||r.indexOf("multipart/form-data")>-1){const c=this.env&&this.env.FormData;return So(a?{"files[]":t}:t,c&&new c,this.formSerializer)}}return s||o?(n.setContentType("application/json",!1),dm(t)):t}],transformResponse:[function(t){const n=this.transitional||Rr.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(B.isResponse(t)||B.isReadableStream(t))return t;if(t&&B.isString(t)&&(r&&!this.responseType||o)){const i=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t,this.parseReviver)}catch(a){if(i)throw a.name==="SyntaxError"?Ie.from(a,Ie.ERR_BAD_RESPONSE,this,null,this.response):a}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:wt.classes.FormData,Blob:wt.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};B.forEach(["delete","get","head","post","put","patch"],e=>{Rr.headers[e]={}});const fm=B.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),hm=e=>{const t={};let n,r,o;return e&&e.split(`
2
- `).forEach(function(i){o=i.indexOf(":"),n=i.substring(0,o).trim().toLowerCase(),r=i.substring(o+1).trim(),!(!n||t[n]&&fm[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},xl=Symbol("internals");function Mr(e){return e&&String(e).trim().toLowerCase()}function Co(e){return e===!1||e==null?e:B.isArray(e)?e.map(Co):String(e)}function pm(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const mm=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Ws(e,t,n,r,o){if(B.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!B.isString(t)){if(B.isString(r))return t.indexOf(r)!==-1;if(B.isRegExp(r))return r.test(t)}}function gm(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function xm(e,t){const n=B.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,s,i){return this[r].call(this,t,o,s,i)},configurable:!0})})}let Rt=class{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function s(a,c,l){const u=Mr(c);if(!u)throw new Error("header name must be a non-empty string");const f=B.findKey(o,u);(!f||o[f]===void 0||l===!0||l===void 0&&o[f]!==!1)&&(o[f||c]=Co(a))}const i=(a,c)=>B.forEach(a,(l,u)=>s(l,u,c));if(B.isPlainObject(t)||t instanceof this.constructor)i(t,n);else if(B.isString(t)&&(t=t.trim())&&!mm(t))i(hm(t),n);else if(B.isObject(t)&&B.isIterable(t)){let a={},c,l;for(const u of t){if(!B.isArray(u))throw TypeError("Object iterator must return a key-value pair");a[l=u[0]]=(c=a[l])?B.isArray(c)?[...c,u[1]]:[c,u[1]]:u[1]}i(a,n)}else t!=null&&s(n,t,r);return this}get(t,n){if(t=Mr(t),t){const r=B.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return pm(o);if(B.isFunction(n))return n.call(this,o,r);if(B.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=Mr(t),t){const r=B.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||Ws(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function s(i){if(i=Mr(i),i){const a=B.findKey(r,i);a&&(!n||Ws(r,r[a],a,n))&&(delete r[a],o=!0)}}return B.isArray(t)?t.forEach(s):s(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const s=n[r];(!t||Ws(this,this[s],s,t,!0))&&(delete this[s],o=!0)}return o}normalize(t){const n=this,r={};return B.forEach(this,(o,s)=>{const i=B.findKey(r,s);if(i){n[i]=Co(o),delete n[s];return}const a=t?gm(s):String(s).trim();a!==s&&delete n[s],n[a]=Co(o),r[a]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return B.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&B.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(`
3
- `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[xl]=this[xl]={accessors:{}}).accessors,o=this.prototype;function s(i){const a=Mr(i);r[a]||(xm(o,i),r[a]=!0)}return B.isArray(t)?t.forEach(s):s(t),this}};Rt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),B.reduceDescriptors(Rt.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}}),B.freezeMethods(Rt);function Vs(e,t){const n=this||Rr,r=t||n,o=Rt.from(r.headers);let s=r.data;return B.forEach(e,function(a){s=a.call(n,s,o.normalize(),t?t.status:void 0)}),o.normalize(),s}function bl(e){return!!(e&&e.__CANCEL__)}function lr(e,t,n){Ie.call(this,e??"canceled",Ie.ERR_CANCELED,t,n),this.name="CanceledError"}B.inherits(lr,Ie,{__CANCEL__:!0});function wl(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new Ie("Request failed with status code "+n.status,[Ie.ERR_BAD_REQUEST,Ie.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function bm(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function wm(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,s=0,i;return t=t!==void 0?t:1e3,function(c){const l=Date.now(),u=r[s];i||(i=l),n[o]=c,r[o]=l;let f=s,h=0;for(;f!==o;)h+=n[f++],f=f%e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),l-i<t)return;const p=u&&l-u;return p?Math.round(h*1e3/p):void 0}}function vm(e,t){let n=0,r=1e3/t,o,s;const i=(l,u=Date.now())=>{n=u,o=null,s&&(clearTimeout(s),s=null),e(...l)};return[(...l)=>{const u=Date.now(),f=u-n;f>=r?i(l,u):(o=l,s||(s=setTimeout(()=>{s=null,i(o)},r-f)))},()=>o&&i(o)]}const ko=(e,t,n=3)=>{let r=0;const o=wm(50,250);return vm(s=>{const i=s.loaded,a=s.lengthComputable?s.total:void 0,c=i-r,l=o(c),u=i<=a;r=i;const f={loaded:i,total:a,progress:a?i/a:void 0,bytes:c,rate:l||void 0,estimated:l&&a&&u?(a-i)/l:void 0,event:s,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(f)},n)},vl=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},yl=e=>(...t)=>B.asap(()=>e(...t)),ym=wt.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,wt.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(wt.origin),wt.navigator&&/(msie|trident)/i.test(wt.navigator.userAgent)):()=>!0,Sm=wt.hasStandardBrowserEnv?{write(e,t,n,r,o,s){const i=[e+"="+encodeURIComponent(t)];B.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),B.isString(r)&&i.push("path="+r),B.isString(o)&&i.push("domain="+o),s===!0&&i.push("secure"),document.cookie=i.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Cm(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function km(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Sl(e,t,n){let r=!Cm(t);return e&&(r||n==!1)?km(e,t):t}const Cl=e=>e instanceof Rt?{...e}:e;function Un(e,t){t=t||{};const n={};function r(l,u,f,h){return B.isPlainObject(l)&&B.isPlainObject(u)?B.merge.call({caseless:h},l,u):B.isPlainObject(u)?B.merge({},u):B.isArray(u)?u.slice():u}function o(l,u,f,h){if(B.isUndefined(u)){if(!B.isUndefined(l))return r(void 0,l,f,h)}else return r(l,u,f,h)}function s(l,u){if(!B.isUndefined(u))return r(void 0,u)}function i(l,u){if(B.isUndefined(u)){if(!B.isUndefined(l))return r(void 0,l)}else return r(void 0,u)}function a(l,u,f){if(f in t)return r(l,u);if(f in e)return r(void 0,l)}const c={url:s,method:s,data:s,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:a,headers:(l,u,f)=>o(Cl(l),Cl(u),f,!0)};return B.forEach(Object.keys({...e,...t}),function(u){const f=c[u]||o,h=f(e[u],t[u],u);B.isUndefined(h)&&f!==a||(n[u]=h)}),n}const kl=e=>{const t=Un({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:i,auth:a}=t;if(t.headers=i=Rt.from(i),t.url=hl(Sl(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),B.isFormData(n)){if(wt.hasStandardBrowserEnv||wt.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(B.isFunction(n.getHeaders)){const c=n.getHeaders(),l=["content-type","content-length"];Object.entries(c).forEach(([u,f])=>{l.includes(u.toLowerCase())&&i.set(u,f)})}}if(wt.hasStandardBrowserEnv&&(r&&B.isFunction(r)&&(r=r(t)),r||r!==!1&&ym(t.url))){const c=o&&s&&Sm.read(s);c&&i.set(o,c)}return t},Tm=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(n,r){const o=kl(e);let s=o.data;const i=Rt.from(o.headers).normalize();let{responseType:a,onUploadProgress:c,onDownloadProgress:l}=o,u,f,h,p,m;function g(){p&&p(),m&&m(),o.cancelToken&&o.cancelToken.unsubscribe(u),o.signal&&o.signal.removeEventListener("abort",u)}let b=new XMLHttpRequest;b.open(o.method.toUpperCase(),o.url,!0),b.timeout=o.timeout;function v(){if(!b)return;const T=Rt.from("getAllResponseHeaders"in b&&b.getAllResponseHeaders()),k={data:!a||a==="text"||a==="json"?b.responseText:b.response,status:b.status,statusText:b.statusText,headers:T,config:e,request:b};wl(function(E){n(E),g()},function(E){r(E),g()},k),b=null}"onloadend"in b?b.onloadend=v:b.onreadystatechange=function(){!b||b.readyState!==4||b.status===0&&!(b.responseURL&&b.responseURL.indexOf("file:")===0)||setTimeout(v)},b.onabort=function(){b&&(r(new Ie("Request aborted",Ie.ECONNABORTED,e,b)),b=null)},b.onerror=function(I){const k=I&&I.message?I.message:"Network Error",S=new Ie(k,Ie.ERR_NETWORK,e,b);S.event=I||null,r(S),b=null},b.ontimeout=function(){let I=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const k=o.transitional||ml;o.timeoutErrorMessage&&(I=o.timeoutErrorMessage),r(new Ie(I,k.clarifyTimeoutError?Ie.ETIMEDOUT:Ie.ECONNABORTED,e,b)),b=null},s===void 0&&i.setContentType(null),"setRequestHeader"in b&&B.forEach(i.toJSON(),function(I,k){b.setRequestHeader(k,I)}),B.isUndefined(o.withCredentials)||(b.withCredentials=!!o.withCredentials),a&&a!=="json"&&(b.responseType=o.responseType),l&&([h,m]=ko(l,!0),b.addEventListener("progress",h)),c&&b.upload&&([f,p]=ko(c),b.upload.addEventListener("progress",f),b.upload.addEventListener("loadend",p)),(o.cancelToken||o.signal)&&(u=T=>{b&&(r(!T||T.type?new lr(null,e,b):T),b.abort(),b=null)},o.cancelToken&&o.cancelToken.subscribe(u),o.signal&&(o.signal.aborted?u():o.signal.addEventListener("abort",u)));const y=bm(o.url);if(y&&wt.protocols.indexOf(y)===-1){r(new Ie("Unsupported protocol "+y+":",Ie.ERR_BAD_REQUEST,e));return}b.send(s||null)})},Em=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,o;const s=function(l){if(!o){o=!0,a();const u=l instanceof Error?l:this.reason;r.abort(u instanceof Ie?u:new lr(u instanceof Error?u.message:u))}};let i=t&&setTimeout(()=>{i=null,s(new Ie(`timeout ${t} of ms exceeded`,Ie.ETIMEDOUT))},t);const a=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(l=>{l.unsubscribe?l.unsubscribe(s):l.removeEventListener("abort",s)}),e=null)};e.forEach(l=>l.addEventListener("abort",s));const{signal:c}=r;return c.unsubscribe=()=>B.asap(a),c}},Im=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let r=0,o;for(;r<n;)o=r+t,yield e.slice(r,o),r=o},Am=async function*(e,t){for await(const n of Nm(e))yield*Im(n,t)},Nm=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},Tl=(e,t,n,r)=>{const o=Am(e,t);let s=0,i,a=c=>{i||(i=!0,r&&r(c))};return new ReadableStream({async pull(c){try{const{done:l,value:u}=await o.next();if(l){a(),c.close();return}let f=u.byteLength;if(n){let h=s+=f;n(h)}c.enqueue(new Uint8Array(u))}catch(l){throw a(l),l}},cancel(c){return a(c),o.return()}},{highWaterMark:2})},El=64*1024,{isFunction:To}=B,_m=(({Request:e,Response:t})=>({Request:e,Response:t}))(B.global),{ReadableStream:Il,TextEncoder:Al}=B.global,Nl=(e,...t)=>{try{return!!e(...t)}catch{return!1}},jm=e=>{e=B.merge.call({skipUndefined:!0},_m,e);const{fetch:t,Request:n,Response:r}=e,o=t?To(t):typeof fetch=="function",s=To(n),i=To(r);if(!o)return!1;const a=o&&To(Il),c=o&&(typeof Al=="function"?(m=>g=>m.encode(g))(new Al):async m=>new Uint8Array(await new n(m).arrayBuffer())),l=s&&a&&Nl(()=>{let m=!1;const g=new n(wt.origin,{body:new Il,method:"POST",get duplex(){return m=!0,"half"}}).headers.has("Content-Type");return m&&!g}),u=i&&a&&Nl(()=>B.isReadableStream(new r("").body)),f={stream:u&&(m=>m.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(m=>{!f[m]&&(f[m]=(g,b)=>{let v=g&&g[m];if(v)return v.call(g);throw new Ie(`Response type '${m}' is not supported`,Ie.ERR_NOT_SUPPORT,b)})});const h=async m=>{if(m==null)return 0;if(B.isBlob(m))return m.size;if(B.isSpecCompliantForm(m))return(await new n(wt.origin,{method:"POST",body:m}).arrayBuffer()).byteLength;if(B.isArrayBufferView(m)||B.isArrayBuffer(m))return m.byteLength;if(B.isURLSearchParams(m)&&(m=m+""),B.isString(m))return(await c(m)).byteLength},p=async(m,g)=>{const b=B.toFiniteNumber(m.getContentLength());return b??h(g)};return async m=>{let{url:g,method:b,data:v,signal:y,cancelToken:T,timeout:I,onDownloadProgress:k,onUploadProgress:S,responseType:E,headers:j,withCredentials:_="same-origin",fetchOptions:D}=kl(m),L=t||fetch;E=E?(E+"").toLowerCase():"text";let W=Em([y,T&&T.toAbortSignal()],I),V=null;const $=W&&W.unsubscribe&&(()=>{W.unsubscribe()});let Z;try{if(S&&l&&b!=="get"&&b!=="head"&&(Z=await p(j,v))!==0){let H=new n(g,{method:"POST",body:v,duplex:"half"}),A;if(B.isFormData(v)&&(A=H.headers.get("content-type"))&&j.setContentType(A),H.body){const[N,R]=vl(Z,ko(yl(S)));v=Tl(H.body,El,N,R)}}B.isString(_)||(_=_?"include":"omit");const X=s&&"credentials"in n.prototype,oe={...D,signal:W,method:b.toUpperCase(),headers:j.normalize().toJSON(),body:v,duplex:"half",credentials:X?_:void 0};V=s&&new n(g,oe);let U=await(s?L(V,D):L(g,oe));const F=u&&(E==="stream"||E==="response");if(u&&(k||F&&$)){const H={};["status","statusText","headers"].forEach(M=>{H[M]=U[M]});const A=B.toFiniteNumber(U.headers.get("content-length")),[N,R]=k&&vl(A,ko(yl(k),!0))||[];U=new r(Tl(U.body,El,N,()=>{R&&R(),$&&$()}),H)}E=E||"text";let G=await f[B.findKey(f,E)||"text"](U,m);return!F&&$&&$(),await new Promise((H,A)=>{wl(H,A,{data:G,headers:Rt.from(U.headers),status:U.status,statusText:U.statusText,config:m,request:V})})}catch(X){throw $&&$(),X&&X.name==="TypeError"&&/Load failed|fetch/i.test(X.message)?Object.assign(new Ie("Network Error",Ie.ERR_NETWORK,m,V),{cause:X.cause||X}):Ie.from(X,X&&X.code,m,V)}}},Pm=new Map,_l=e=>{let t=e?e.env:{};const{fetch:n,Request:r,Response:o}=t,s=[r,o,n];let i=s.length,a=i,c,l,u=Pm;for(;a--;)c=s[a],l=u.get(c),l===void 0&&u.set(c,l=a?new Map:jm(t)),u=l;return l};_l();const Ks={http:em,xhr:Tm,fetch:{get:_l}};B.forEach(Ks,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const jl=e=>`- ${e}`,Om=e=>B.isFunction(e)||e===null||e===!1,Pl={getAdapter:(e,t)=>{e=B.isArray(e)?e:[e];const{length:n}=e;let r,o;const s={};for(let i=0;i<n;i++){r=e[i];let a;if(o=r,!Om(r)&&(o=Ks[(a=String(r)).toLowerCase()],o===void 0))throw new Ie(`Unknown adapter '${a}'`);if(o&&(B.isFunction(o)||(o=o.get(t))))break;s[a||"#"+i]=o}if(!o){const i=Object.entries(s).map(([c,l])=>`adapter ${c} `+(l===!1?"is not supported by the environment":"is not available in the build"));let a=n?i.length>1?`since :
1
+ (function(ne,Pt){typeof exports=="object"&&typeof module<"u"?Pt(exports,require("clsx"),require("tailwind-merge"),require("react"),require("@radix-ui/react-slot"),require("class-variance-authority"),require("react-dom"),require("lucide-react")):typeof define=="function"&&define.amd?define(["exports","clsx","tailwind-merge","react","@radix-ui/react-slot","class-variance-authority","react-dom","lucide-react"],Pt):(ne=typeof globalThis<"u"?globalThis:ne||self,Pt(ne.NewChatUI={},ne.clsx,ne.tailwindMerge,ne.React,ne.reactSlot,ne.classVarianceAuthority,ne.ReactDOM,ne.LucideReact))})(this,function(ne,Pt,Bn,x,sr,Ya,Ls,pe){"use strict";var yC=Object.defineProperty;var SC=(ne,Pt,Bn)=>Pt in ne?yC(ne,Pt,{enumerable:!0,configurable:!0,writable:!0,value:Bn}):ne[Pt]=Bn;var Ga=(ne,Pt,Bn)=>SC(ne,typeof Pt!="symbol"?Pt+"":Pt,Bn);function Xa(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const w=Xa(x),Ja=Xa(Ls);function pp(...e){return Bn.twMerge(Pt.clsx(e))}function Za(e,t){return function(){return e.apply(t,arguments)}}const{toString:mp}=Object.prototype,{getPrototypeOf:$s}=Object,{iterator:bo,toStringTag:Qa}=Symbol,wo=(e=>t=>{const n=mp.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),en=e=>(e=e.toLowerCase(),t=>wo(t)===e),vo=e=>t=>typeof t===e,{isArray:ir}=Array,ar=vo("undefined");function jr(e){return e!==null&&!ar(e)&&e.constructor!==null&&!ar(e.constructor)&&Ot(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const el=en("ArrayBuffer");function gp(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&el(e.buffer),t}const xp=vo("string"),Ot=vo("function"),tl=vo("number"),Pr=e=>e!==null&&typeof e=="object",bp=e=>e===!0||e===!1,yo=e=>{if(wo(e)!=="object")return!1;const t=$s(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Qa in e)&&!(bo in e)},wp=e=>{if(!Pr(e)||jr(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},vp=en("Date"),yp=en("File"),Sp=en("Blob"),Cp=en("FileList"),kp=e=>Pr(e)&&Ot(e.pipe),Tp=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Ot(e.append)&&((t=wo(e))==="formdata"||t==="object"&&Ot(e.toString)&&e.toString()==="[object FormData]"))},Ep=en("URLSearchParams"),[Ip,Ap,Np,_p]=["ReadableStream","Request","Response","Headers"].map(en),jp=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Or(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),ir(e))for(r=0,o=e.length;r<o;r++)t.call(null,e[r],r,e);else{if(jr(e))return;const s=n?Object.getOwnPropertyNames(e):Object.keys(e),i=s.length;let a;for(r=0;r<i;r++)a=s[r],t.call(null,e[a],a,e)}}function nl(e,t){if(jr(e))return null;t=t.toLowerCase();const n=Object.keys(e);let r=n.length,o;for(;r-- >0;)if(o=n[r],t===o.toLowerCase())return o;return null}const Hn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,rl=e=>!ar(e)&&e!==Hn;function Fs(){const{caseless:e,skipUndefined:t}=rl(this)&&this||{},n={},r=(o,s)=>{const i=e&&nl(n,s)||s;yo(n[i])&&yo(o)?n[i]=Fs(n[i],o):yo(o)?n[i]=Fs({},o):ir(o)?n[i]=o.slice():(!t||!ar(o))&&(n[i]=o)};for(let o=0,s=arguments.length;o<s;o++)arguments[o]&&Or(arguments[o],r);return n}const Pp=(e,t,n,{allOwnKeys:r}={})=>(Or(t,(o,s)=>{n&&Ot(o)?e[s]=Za(o,n):e[s]=o},{allOwnKeys:r}),e),Op=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),Rp=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},Mp=(e,t,n,r)=>{let o,s,i;const a={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),s=o.length;s-- >0;)i=o[s],(!r||r(i,e,t))&&!a[i]&&(t[i]=e[i],a[i]=!0);e=n!==!1&&$s(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},Dp=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},Lp=e=>{if(!e)return null;if(ir(e))return e;let t=e.length;if(!tl(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},$p=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&$s(Uint8Array)),Fp=(e,t)=>{const r=(e&&e[bo]).call(e);let o;for(;(o=r.next())&&!o.done;){const s=o.value;t.call(e,s[0],s[1])}},zp=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},Bp=en("HTMLFormElement"),Hp=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),ol=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),Up=en("RegExp"),sl=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Or(n,(o,s)=>{let i;(i=t(o,s,e))!==!1&&(r[s]=i||o)}),Object.defineProperties(e,r)},Wp=e=>{sl(e,(t,n)=>{if(Ot(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Ot(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},Vp=(e,t)=>{const n={},r=o=>{o.forEach(s=>{n[s]=!0})};return ir(e)?r(e):r(String(e).split(t)),n},Kp=()=>{},qp=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function Gp(e){return!!(e&&Ot(e.append)&&e[Qa]==="FormData"&&e[bo])}const Yp=e=>{const t=new Array(10),n=(r,o)=>{if(Pr(r)){if(t.indexOf(r)>=0)return;if(jr(r))return r;if(!("toJSON"in r)){t[o]=r;const s=ir(r)?[]:{};return Or(r,(i,a)=>{const c=n(i,o+1);!ar(c)&&(s[a]=c)}),t[o]=void 0,s}}return r};return n(e,0)},Xp=en("AsyncFunction"),Jp=e=>e&&(Pr(e)||Ot(e))&&Ot(e.then)&&Ot(e.catch),il=((e,t)=>e?setImmediate:t?((n,r)=>(Hn.addEventListener("message",({source:o,data:s})=>{o===Hn&&s===n&&r.length&&r.shift()()},!1),o=>{r.push(o),Hn.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",Ot(Hn.postMessage)),Zp=typeof queueMicrotask<"u"?queueMicrotask.bind(Hn):typeof process<"u"&&process.nextTick||il,B={isArray:ir,isArrayBuffer:el,isBuffer:jr,isFormData:Tp,isArrayBufferView:gp,isString:xp,isNumber:tl,isBoolean:bp,isObject:Pr,isPlainObject:yo,isEmptyObject:wp,isReadableStream:Ip,isRequest:Ap,isResponse:Np,isHeaders:_p,isUndefined:ar,isDate:vp,isFile:yp,isBlob:Sp,isRegExp:Up,isFunction:Ot,isStream:kp,isURLSearchParams:Ep,isTypedArray:$p,isFileList:Cp,forEach:Or,merge:Fs,extend:Pp,trim:jp,stripBOM:Op,inherits:Rp,toFlatObject:Mp,kindOf:wo,kindOfTest:en,endsWith:Dp,toArray:Lp,forEachEntry:Fp,matchAll:zp,isHTMLForm:Bp,hasOwnProperty:ol,hasOwnProp:ol,reduceDescriptors:sl,freezeMethods:Wp,toObjectSet:Vp,toCamelCase:Hp,noop:Kp,toFiniteNumber:qp,findKey:nl,global:Hn,isContextDefined:rl,isSpecCompliantForm:Gp,toJSONObject:Yp,isAsyncFn:Xp,isThenable:Jp,setImmediate:il,asap:Zp,isIterable:e=>e!=null&&Ot(e[bo])};function Ie(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o,this.status=o.status?o.status:null)}B.inherits(Ie,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:B.toJSONObject(this.config),code:this.code,status:this.status}}});const al=Ie.prototype,ll={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{ll[e]={value:e}}),Object.defineProperties(Ie,ll),Object.defineProperty(al,"isAxiosError",{value:!0}),Ie.from=(e,t,n,r,o,s)=>{const i=Object.create(al);B.toFlatObject(e,i,function(u){return u!==Error.prototype},l=>l!=="isAxiosError");const a=e&&e.message?e.message:"Error",c=t==null&&e?e.code:t;return Ie.call(i,a,c,n,r,o),e&&i.cause==null&&Object.defineProperty(i,"cause",{value:e,configurable:!0}),i.name=e&&e.name||"Error",s&&Object.assign(i,s),i};const Qp=null;function zs(e){return B.isPlainObject(e)||B.isArray(e)}function cl(e){return B.endsWith(e,"[]")?e.slice(0,-2):e}function ul(e,t,n){return e?e.concat(t).map(function(o,s){return o=cl(o),!n&&s?"["+o+"]":o}).join(n?".":""):t}function em(e){return B.isArray(e)&&!e.some(zs)}const tm=B.toFlatObject(B,{},null,function(t){return/^is[A-Z]/.test(t)});function So(e,t,n){if(!B.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=B.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(g,b){return!B.isUndefined(b[g])});const r=n.metaTokens,o=n.visitor||u,s=n.dots,i=n.indexes,c=(n.Blob||typeof Blob<"u"&&Blob)&&B.isSpecCompliantForm(t);if(!B.isFunction(o))throw new TypeError("visitor must be a function");function l(m){if(m===null)return"";if(B.isDate(m))return m.toISOString();if(B.isBoolean(m))return m.toString();if(!c&&B.isBlob(m))throw new Ie("Blob is not supported. Use a Buffer instead.");return B.isArrayBuffer(m)||B.isTypedArray(m)?c&&typeof Blob=="function"?new Blob([m]):Buffer.from(m):m}function u(m,g,b){let v=m;if(m&&!b&&typeof m=="object"){if(B.endsWith(g,"{}"))g=r?g:g.slice(0,-2),m=JSON.stringify(m);else if(B.isArray(m)&&em(m)||(B.isFileList(m)||B.endsWith(g,"[]"))&&(v=B.toArray(m)))return g=cl(g),v.forEach(function(T,I){!(B.isUndefined(T)||T===null)&&t.append(i===!0?ul([g],I,s):i===null?g:g+"[]",l(T))}),!1}return zs(m)?!0:(t.append(ul(b,g,s),l(m)),!1)}const f=[],h=Object.assign(tm,{defaultVisitor:u,convertValue:l,isVisitable:zs});function p(m,g){if(!B.isUndefined(m)){if(f.indexOf(m)!==-1)throw Error("Circular reference detected in "+g.join("."));f.push(m),B.forEach(m,function(v,y){(!(B.isUndefined(v)||v===null)&&o.call(t,v,B.isString(y)?y.trim():y,g,h))===!0&&p(v,g?g.concat(y):[y])}),f.pop()}}if(!B.isObject(e))throw new TypeError("data must be an object");return p(e),t}function dl(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function Bs(e,t){this._pairs=[],e&&So(e,this,t)}const fl=Bs.prototype;fl.append=function(t,n){this._pairs.push([t,n])},fl.toString=function(t){const n=t?function(r){return t.call(this,r,dl)}:dl;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function nm(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function hl(e,t,n){if(!t)return e;const r=n&&n.encode||nm;B.isFunction(n)&&(n={serialize:n});const o=n&&n.serialize;let s;if(o?s=o(t,n):s=B.isURLSearchParams(t)?t.toString():new Bs(t,n).toString(r),s){const i=e.indexOf("#");i!==-1&&(e=e.slice(0,i)),e+=(e.indexOf("?")===-1?"?":"&")+s}return e}class pl{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){B.forEach(this.handlers,function(r){r!==null&&t(r)})}}const ml={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},rm={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:Bs,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},Hs=typeof window<"u"&&typeof document<"u",Us=typeof navigator=="object"&&navigator||void 0,om=Hs&&(!Us||["ReactNative","NativeScript","NS"].indexOf(Us.product)<0),sm=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",im=Hs&&window.location.href||"http://localhost",wt={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Hs,hasStandardBrowserEnv:om,hasStandardBrowserWebWorkerEnv:sm,navigator:Us,origin:im},Symbol.toStringTag,{value:"Module"})),...rm};function am(e,t){return So(e,new wt.classes.URLSearchParams,{visitor:function(n,r,o,s){return wt.isNode&&B.isBuffer(n)?(this.append(r,n.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)},...t})}function lm(e){return B.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function cm(e){const t={},n=Object.keys(e);let r;const o=n.length;let s;for(r=0;r<o;r++)s=n[r],t[s]=e[s];return t}function gl(e){function t(n,r,o,s){let i=n[s++];if(i==="__proto__")return!0;const a=Number.isFinite(+i),c=s>=n.length;return i=!i&&B.isArray(o)?o.length:i,c?(B.hasOwnProp(o,i)?o[i]=[o[i],r]:o[i]=r,!a):((!o[i]||!B.isObject(o[i]))&&(o[i]=[]),t(n,r,o[i],s)&&B.isArray(o[i])&&(o[i]=cm(o[i])),!a)}if(B.isFormData(e)&&B.isFunction(e.entries)){const n={};return B.forEachEntry(e,(r,o)=>{t(lm(r),o,n,0)}),n}return null}function um(e,t,n){if(B.isString(e))try{return(t||JSON.parse)(e),B.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const Rr={transitional:ml,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,s=B.isObject(t);if(s&&B.isHTMLForm(t)&&(t=new FormData(t)),B.isFormData(t))return o?JSON.stringify(gl(t)):t;if(B.isArrayBuffer(t)||B.isBuffer(t)||B.isStream(t)||B.isFile(t)||B.isBlob(t)||B.isReadableStream(t))return t;if(B.isArrayBufferView(t))return t.buffer;if(B.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let a;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return am(t,this.formSerializer).toString();if((a=B.isFileList(t))||r.indexOf("multipart/form-data")>-1){const c=this.env&&this.env.FormData;return So(a?{"files[]":t}:t,c&&new c,this.formSerializer)}}return s||o?(n.setContentType("application/json",!1),um(t)):t}],transformResponse:[function(t){const n=this.transitional||Rr.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(B.isResponse(t)||B.isReadableStream(t))return t;if(t&&B.isString(t)&&(r&&!this.responseType||o)){const i=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t,this.parseReviver)}catch(a){if(i)throw a.name==="SyntaxError"?Ie.from(a,Ie.ERR_BAD_RESPONSE,this,null,this.response):a}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:wt.classes.FormData,Blob:wt.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};B.forEach(["delete","get","head","post","put","patch"],e=>{Rr.headers[e]={}});const dm=B.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),fm=e=>{const t={};let n,r,o;return e&&e.split(`
2
+ `).forEach(function(i){o=i.indexOf(":"),n=i.substring(0,o).trim().toLowerCase(),r=i.substring(o+1).trim(),!(!n||t[n]&&dm[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},xl=Symbol("internals");function Mr(e){return e&&String(e).trim().toLowerCase()}function Co(e){return e===!1||e==null?e:B.isArray(e)?e.map(Co):String(e)}function hm(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const pm=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Ws(e,t,n,r,o){if(B.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!B.isString(t)){if(B.isString(r))return t.indexOf(r)!==-1;if(B.isRegExp(r))return r.test(t)}}function mm(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function gm(e,t){const n=B.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,s,i){return this[r].call(this,t,o,s,i)},configurable:!0})})}let Rt=class{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function s(a,c,l){const u=Mr(c);if(!u)throw new Error("header name must be a non-empty string");const f=B.findKey(o,u);(!f||o[f]===void 0||l===!0||l===void 0&&o[f]!==!1)&&(o[f||c]=Co(a))}const i=(a,c)=>B.forEach(a,(l,u)=>s(l,u,c));if(B.isPlainObject(t)||t instanceof this.constructor)i(t,n);else if(B.isString(t)&&(t=t.trim())&&!pm(t))i(fm(t),n);else if(B.isObject(t)&&B.isIterable(t)){let a={},c,l;for(const u of t){if(!B.isArray(u))throw TypeError("Object iterator must return a key-value pair");a[l=u[0]]=(c=a[l])?B.isArray(c)?[...c,u[1]]:[c,u[1]]:u[1]}i(a,n)}else t!=null&&s(n,t,r);return this}get(t,n){if(t=Mr(t),t){const r=B.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return hm(o);if(B.isFunction(n))return n.call(this,o,r);if(B.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=Mr(t),t){const r=B.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||Ws(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function s(i){if(i=Mr(i),i){const a=B.findKey(r,i);a&&(!n||Ws(r,r[a],a,n))&&(delete r[a],o=!0)}}return B.isArray(t)?t.forEach(s):s(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const s=n[r];(!t||Ws(this,this[s],s,t,!0))&&(delete this[s],o=!0)}return o}normalize(t){const n=this,r={};return B.forEach(this,(o,s)=>{const i=B.findKey(r,s);if(i){n[i]=Co(o),delete n[s];return}const a=t?mm(s):String(s).trim();a!==s&&delete n[s],n[a]=Co(o),r[a]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return B.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&B.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(`
3
+ `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[xl]=this[xl]={accessors:{}}).accessors,o=this.prototype;function s(i){const a=Mr(i);r[a]||(gm(o,i),r[a]=!0)}return B.isArray(t)?t.forEach(s):s(t),this}};Rt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),B.reduceDescriptors(Rt.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}}),B.freezeMethods(Rt);function Vs(e,t){const n=this||Rr,r=t||n,o=Rt.from(r.headers);let s=r.data;return B.forEach(e,function(a){s=a.call(n,s,o.normalize(),t?t.status:void 0)}),o.normalize(),s}function bl(e){return!!(e&&e.__CANCEL__)}function lr(e,t,n){Ie.call(this,e??"canceled",Ie.ERR_CANCELED,t,n),this.name="CanceledError"}B.inherits(lr,Ie,{__CANCEL__:!0});function wl(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new Ie("Request failed with status code "+n.status,[Ie.ERR_BAD_REQUEST,Ie.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function xm(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function bm(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,s=0,i;return t=t!==void 0?t:1e3,function(c){const l=Date.now(),u=r[s];i||(i=l),n[o]=c,r[o]=l;let f=s,h=0;for(;f!==o;)h+=n[f++],f=f%e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),l-i<t)return;const p=u&&l-u;return p?Math.round(h*1e3/p):void 0}}function wm(e,t){let n=0,r=1e3/t,o,s;const i=(l,u=Date.now())=>{n=u,o=null,s&&(clearTimeout(s),s=null),e(...l)};return[(...l)=>{const u=Date.now(),f=u-n;f>=r?i(l,u):(o=l,s||(s=setTimeout(()=>{s=null,i(o)},r-f)))},()=>o&&i(o)]}const ko=(e,t,n=3)=>{let r=0;const o=bm(50,250);return wm(s=>{const i=s.loaded,a=s.lengthComputable?s.total:void 0,c=i-r,l=o(c),u=i<=a;r=i;const f={loaded:i,total:a,progress:a?i/a:void 0,bytes:c,rate:l||void 0,estimated:l&&a&&u?(a-i)/l:void 0,event:s,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(f)},n)},vl=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},yl=e=>(...t)=>B.asap(()=>e(...t)),vm=wt.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,wt.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(wt.origin),wt.navigator&&/(msie|trident)/i.test(wt.navigator.userAgent)):()=>!0,ym=wt.hasStandardBrowserEnv?{write(e,t,n,r,o,s){const i=[e+"="+encodeURIComponent(t)];B.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),B.isString(r)&&i.push("path="+r),B.isString(o)&&i.push("domain="+o),s===!0&&i.push("secure"),document.cookie=i.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Sm(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Cm(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Sl(e,t,n){let r=!Sm(t);return e&&(r||n==!1)?Cm(e,t):t}const Cl=e=>e instanceof Rt?{...e}:e;function Un(e,t){t=t||{};const n={};function r(l,u,f,h){return B.isPlainObject(l)&&B.isPlainObject(u)?B.merge.call({caseless:h},l,u):B.isPlainObject(u)?B.merge({},u):B.isArray(u)?u.slice():u}function o(l,u,f,h){if(B.isUndefined(u)){if(!B.isUndefined(l))return r(void 0,l,f,h)}else return r(l,u,f,h)}function s(l,u){if(!B.isUndefined(u))return r(void 0,u)}function i(l,u){if(B.isUndefined(u)){if(!B.isUndefined(l))return r(void 0,l)}else return r(void 0,u)}function a(l,u,f){if(f in t)return r(l,u);if(f in e)return r(void 0,l)}const c={url:s,method:s,data:s,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:a,headers:(l,u,f)=>o(Cl(l),Cl(u),f,!0)};return B.forEach(Object.keys({...e,...t}),function(u){const f=c[u]||o,h=f(e[u],t[u],u);B.isUndefined(h)&&f!==a||(n[u]=h)}),n}const kl=e=>{const t=Un({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:i,auth:a}=t;if(t.headers=i=Rt.from(i),t.url=hl(Sl(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),B.isFormData(n)){if(wt.hasStandardBrowserEnv||wt.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(B.isFunction(n.getHeaders)){const c=n.getHeaders(),l=["content-type","content-length"];Object.entries(c).forEach(([u,f])=>{l.includes(u.toLowerCase())&&i.set(u,f)})}}if(wt.hasStandardBrowserEnv&&(r&&B.isFunction(r)&&(r=r(t)),r||r!==!1&&vm(t.url))){const c=o&&s&&ym.read(s);c&&i.set(o,c)}return t},km=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(n,r){const o=kl(e);let s=o.data;const i=Rt.from(o.headers).normalize();let{responseType:a,onUploadProgress:c,onDownloadProgress:l}=o,u,f,h,p,m;function g(){p&&p(),m&&m(),o.cancelToken&&o.cancelToken.unsubscribe(u),o.signal&&o.signal.removeEventListener("abort",u)}let b=new XMLHttpRequest;b.open(o.method.toUpperCase(),o.url,!0),b.timeout=o.timeout;function v(){if(!b)return;const T=Rt.from("getAllResponseHeaders"in b&&b.getAllResponseHeaders()),k={data:!a||a==="text"||a==="json"?b.responseText:b.response,status:b.status,statusText:b.statusText,headers:T,config:e,request:b};wl(function(E){n(E),g()},function(E){r(E),g()},k),b=null}"onloadend"in b?b.onloadend=v:b.onreadystatechange=function(){!b||b.readyState!==4||b.status===0&&!(b.responseURL&&b.responseURL.indexOf("file:")===0)||setTimeout(v)},b.onabort=function(){b&&(r(new Ie("Request aborted",Ie.ECONNABORTED,e,b)),b=null)},b.onerror=function(I){const k=I&&I.message?I.message:"Network Error",S=new Ie(k,Ie.ERR_NETWORK,e,b);S.event=I||null,r(S),b=null},b.ontimeout=function(){let I=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const k=o.transitional||ml;o.timeoutErrorMessage&&(I=o.timeoutErrorMessage),r(new Ie(I,k.clarifyTimeoutError?Ie.ETIMEDOUT:Ie.ECONNABORTED,e,b)),b=null},s===void 0&&i.setContentType(null),"setRequestHeader"in b&&B.forEach(i.toJSON(),function(I,k){b.setRequestHeader(k,I)}),B.isUndefined(o.withCredentials)||(b.withCredentials=!!o.withCredentials),a&&a!=="json"&&(b.responseType=o.responseType),l&&([h,m]=ko(l,!0),b.addEventListener("progress",h)),c&&b.upload&&([f,p]=ko(c),b.upload.addEventListener("progress",f),b.upload.addEventListener("loadend",p)),(o.cancelToken||o.signal)&&(u=T=>{b&&(r(!T||T.type?new lr(null,e,b):T),b.abort(),b=null)},o.cancelToken&&o.cancelToken.subscribe(u),o.signal&&(o.signal.aborted?u():o.signal.addEventListener("abort",u)));const y=xm(o.url);if(y&&wt.protocols.indexOf(y)===-1){r(new Ie("Unsupported protocol "+y+":",Ie.ERR_BAD_REQUEST,e));return}b.send(s||null)})},Tm=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,o;const s=function(l){if(!o){o=!0,a();const u=l instanceof Error?l:this.reason;r.abort(u instanceof Ie?u:new lr(u instanceof Error?u.message:u))}};let i=t&&setTimeout(()=>{i=null,s(new Ie(`timeout ${t} of ms exceeded`,Ie.ETIMEDOUT))},t);const a=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(l=>{l.unsubscribe?l.unsubscribe(s):l.removeEventListener("abort",s)}),e=null)};e.forEach(l=>l.addEventListener("abort",s));const{signal:c}=r;return c.unsubscribe=()=>B.asap(a),c}},Em=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let r=0,o;for(;r<n;)o=r+t,yield e.slice(r,o),r=o},Im=async function*(e,t){for await(const n of Am(e))yield*Em(n,t)},Am=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},Tl=(e,t,n,r)=>{const o=Im(e,t);let s=0,i,a=c=>{i||(i=!0,r&&r(c))};return new ReadableStream({async pull(c){try{const{done:l,value:u}=await o.next();if(l){a(),c.close();return}let f=u.byteLength;if(n){let h=s+=f;n(h)}c.enqueue(new Uint8Array(u))}catch(l){throw a(l),l}},cancel(c){return a(c),o.return()}},{highWaterMark:2})},El=64*1024,{isFunction:To}=B,Nm=(({Request:e,Response:t})=>({Request:e,Response:t}))(B.global),{ReadableStream:Il,TextEncoder:Al}=B.global,Nl=(e,...t)=>{try{return!!e(...t)}catch{return!1}},_m=e=>{e=B.merge.call({skipUndefined:!0},Nm,e);const{fetch:t,Request:n,Response:r}=e,o=t?To(t):typeof fetch=="function",s=To(n),i=To(r);if(!o)return!1;const a=o&&To(Il),c=o&&(typeof Al=="function"?(m=>g=>m.encode(g))(new Al):async m=>new Uint8Array(await new n(m).arrayBuffer())),l=s&&a&&Nl(()=>{let m=!1;const g=new n(wt.origin,{body:new Il,method:"POST",get duplex(){return m=!0,"half"}}).headers.has("Content-Type");return m&&!g}),u=i&&a&&Nl(()=>B.isReadableStream(new r("").body)),f={stream:u&&(m=>m.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(m=>{!f[m]&&(f[m]=(g,b)=>{let v=g&&g[m];if(v)return v.call(g);throw new Ie(`Response type '${m}' is not supported`,Ie.ERR_NOT_SUPPORT,b)})});const h=async m=>{if(m==null)return 0;if(B.isBlob(m))return m.size;if(B.isSpecCompliantForm(m))return(await new n(wt.origin,{method:"POST",body:m}).arrayBuffer()).byteLength;if(B.isArrayBufferView(m)||B.isArrayBuffer(m))return m.byteLength;if(B.isURLSearchParams(m)&&(m=m+""),B.isString(m))return(await c(m)).byteLength},p=async(m,g)=>{const b=B.toFiniteNumber(m.getContentLength());return b??h(g)};return async m=>{let{url:g,method:b,data:v,signal:y,cancelToken:T,timeout:I,onDownloadProgress:k,onUploadProgress:S,responseType:E,headers:j,withCredentials:_="same-origin",fetchOptions:D}=kl(m),L=t||fetch;E=E?(E+"").toLowerCase():"text";let W=Tm([y,T&&T.toAbortSignal()],I),V=null;const $=W&&W.unsubscribe&&(()=>{W.unsubscribe()});let Z;try{if(S&&l&&b!=="get"&&b!=="head"&&(Z=await p(j,v))!==0){let H=new n(g,{method:"POST",body:v,duplex:"half"}),A;if(B.isFormData(v)&&(A=H.headers.get("content-type"))&&j.setContentType(A),H.body){const[N,R]=vl(Z,ko(yl(S)));v=Tl(H.body,El,N,R)}}B.isString(_)||(_=_?"include":"omit");const X=s&&"credentials"in n.prototype,oe={...D,signal:W,method:b.toUpperCase(),headers:j.normalize().toJSON(),body:v,duplex:"half",credentials:X?_:void 0};V=s&&new n(g,oe);let U=await(s?L(V,D):L(g,oe));const F=u&&(E==="stream"||E==="response");if(u&&(k||F&&$)){const H={};["status","statusText","headers"].forEach(M=>{H[M]=U[M]});const A=B.toFiniteNumber(U.headers.get("content-length")),[N,R]=k&&vl(A,ko(yl(k),!0))||[];U=new r(Tl(U.body,El,N,()=>{R&&R(),$&&$()}),H)}E=E||"text";let G=await f[B.findKey(f,E)||"text"](U,m);return!F&&$&&$(),await new Promise((H,A)=>{wl(H,A,{data:G,headers:Rt.from(U.headers),status:U.status,statusText:U.statusText,config:m,request:V})})}catch(X){throw $&&$(),X&&X.name==="TypeError"&&/Load failed|fetch/i.test(X.message)?Object.assign(new Ie("Network Error",Ie.ERR_NETWORK,m,V),{cause:X.cause||X}):Ie.from(X,X&&X.code,m,V)}}},jm=new Map,_l=e=>{let t=e?e.env:{};const{fetch:n,Request:r,Response:o}=t,s=[r,o,n];let i=s.length,a=i,c,l,u=jm;for(;a--;)c=s[a],l=u.get(c),l===void 0&&u.set(c,l=a?new Map:_m(t)),u=l;return l};_l();const Ks={http:Qp,xhr:km,fetch:{get:_l}};B.forEach(Ks,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const jl=e=>`- ${e}`,Pm=e=>B.isFunction(e)||e===null||e===!1,Pl={getAdapter:(e,t)=>{e=B.isArray(e)?e:[e];const{length:n}=e;let r,o;const s={};for(let i=0;i<n;i++){r=e[i];let a;if(o=r,!Pm(r)&&(o=Ks[(a=String(r)).toLowerCase()],o===void 0))throw new Ie(`Unknown adapter '${a}'`);if(o&&(B.isFunction(o)||(o=o.get(t))))break;s[a||"#"+i]=o}if(!o){const i=Object.entries(s).map(([c,l])=>`adapter ${c} `+(l===!1?"is not supported by the environment":"is not available in the build"));let a=n?i.length>1?`since :
4
4
  `+i.map(jl).join(`
5
- `):" "+jl(i[0]):"as no adapter specified";throw new Ie("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return o},adapters:Ks};function qs(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new lr(null,e)}function Ol(e){return qs(e),e.headers=Rt.from(e.headers),e.data=Vs.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Pl.getAdapter(e.adapter||Rr.adapter,e)(e).then(function(r){return qs(e),r.data=Vs.call(e,e.transformResponse,r),r.headers=Rt.from(r.headers),r},function(r){return bl(r)||(qs(e),r&&r.response&&(r.response.data=Vs.call(e,e.transformResponse,r.response),r.response.headers=Rt.from(r.response.headers))),Promise.reject(r)})}const Rl="1.12.2",Eo={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Eo[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Ml={};Eo.transitional=function(t,n,r){function o(s,i){return"[Axios v"+Rl+"] Transitional option '"+s+"'"+i+(r?". "+r:"")}return(s,i,a)=>{if(t===!1)throw new Ie(o(i," has been removed"+(n?" in "+n:"")),Ie.ERR_DEPRECATED);return n&&!Ml[i]&&(Ml[i]=!0,console.warn(o(i," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(s,i,a):!0}},Eo.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function Rm(e,t,n){if(typeof e!="object")throw new Ie("options must be an object",Ie.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const s=r[o],i=t[s];if(i){const a=e[s],c=a===void 0||i(a,s,e);if(c!==!0)throw new Ie("option "+s+" must be "+c,Ie.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Ie("Unknown option "+s,Ie.ERR_BAD_OPTION)}}const Io={assertOptions:Rm,validators:Eo},cn=Io.validators;let Wn=class{constructor(t){this.defaults=t||{},this.interceptors={request:new pl,response:new pl}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=`
6
- `+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Un(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&Io.assertOptions(r,{silentJSONParsing:cn.transitional(cn.boolean),forcedJSONParsing:cn.transitional(cn.boolean),clarifyTimeoutError:cn.transitional(cn.boolean)},!1),o!=null&&(B.isFunction(o)?n.paramsSerializer={serialize:o}:Io.assertOptions(o,{encode:cn.function,serialize:cn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Io.assertOptions(n,{baseUrl:cn.spelling("baseURL"),withXsrfToken:cn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&B.merge(s.common,s[n.method]);s&&B.forEach(["delete","get","head","post","put","patch","common"],m=>{delete s[m]}),n.headers=Rt.concat(i,s);const a=[];let c=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(n)===!1||(c=c&&g.synchronous,a.unshift(g.fulfilled,g.rejected))});const l=[];this.interceptors.response.forEach(function(g){l.push(g.fulfilled,g.rejected)});let u,f=0,h;if(!c){const m=[Ol.bind(this),void 0];for(m.unshift(...a),m.push(...l),h=m.length,u=Promise.resolve(n);f<h;)u=u.then(m[f++],m[f++]);return u}h=a.length;let p=n;for(;f<h;){const m=a[f++],g=a[f++];try{p=m(p)}catch(b){g.call(this,b);break}}try{u=Ol.call(this,p)}catch(m){return Promise.reject(m)}for(f=0,h=l.length;f<h;)u=u.then(l[f++],l[f++]);return u}getUri(t){t=Un(this.defaults,t);const n=Sl(t.baseURL,t.url,t.allowAbsoluteUrls);return hl(n,t.params,t.paramsSerializer)}};B.forEach(["delete","get","head","options"],function(t){Wn.prototype[t]=function(n,r){return this.request(Un(r||{},{method:t,url:n,data:(r||{}).data}))}}),B.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(Un(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Wn.prototype[t]=n(),Wn.prototype[t+"Form"]=n(!0)});let Mm=class pp{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(o=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{r.subscribe(a),s=a}).then(o);return i.cancel=function(){r.unsubscribe(s)},i},t(function(s,i,a){r.reason||(r.reason=new lr(s,i,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new pp(function(o){t=o}),cancel:t}}};function Dm(e){return function(n){return e.apply(null,n)}}function Lm(e){return B.isObject(e)&&e.isAxiosError===!0}const Gs={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Gs).forEach(([e,t])=>{Gs[t]=e});function Dl(e){const t=new Wn(e),n=Za(Wn.prototype.request,t);return B.extend(n,Wn.prototype,t,{allOwnKeys:!0}),B.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Dl(Un(e,o))},n}const at=Dl(Rr);at.Axios=Wn,at.CanceledError=lr,at.CancelToken=Mm,at.isCancel=bl,at.VERSION=Rl,at.toFormData=So,at.AxiosError=Ie,at.Cancel=at.CanceledError,at.all=function(t){return Promise.all(t)},at.spread=Dm,at.isAxiosError=Lm,at.mergeConfig=Un,at.AxiosHeaders=Rt,at.formToJSON=e=>gl(B.isHTMLForm(e)?new FormData(e):e),at.getAdapter=Pl.getAdapter,at.HttpStatusCode=Gs,at.default=at;const{Axios:NC,AxiosError:_C,CanceledError:jC,isCancel:Ll,CancelToken:PC,VERSION:OC,all:RC,Cancel:MC,isAxiosError:DC,spread:LC,toFormData:$C,AxiosHeaders:FC,HttpStatusCode:zC,formToJSON:BC,getAdapter:HC,mergeConfig:UC}=at,En={authToken:"authToken",authTokenExpiresAt:"authTokenExpiresAt",authSessionId:"authSessionId",chatSettings:"chat-settings",threadManagerView:"thread-manager-view",playgroundSettings:"new-chat-ui-chat-settings",debugLogs:"app:debugLogs"};function Ao(e){return`draft:${e}`}let No=null;const Ys=new Set;function Xs(){return No}function In(e){No=e,Ys.forEach(t=>t(e))}function Js(e){return Ys.add(e),()=>Ys.delete(e)}const $l=3e4,Fl=9e4,It=at.create({timeout:$l,withCredentials:!0});It.interceptors.request.use(e=>(No&&(e.headers.Authorization=`Bearer ${No}`),e)),It.interceptors.response.use(e=>{if(typeof window<"u"&&(e!=null&&e.data))try{const t=e.data,n=t.data||{},r=typeof t.token=="string"&&t.token||typeof n.token=="string"&&n.token||null,o=typeof t.expires_at=="number"&&t.expires_at||typeof n.expires_at=="number"&&n.expires_at||typeof t.expiresAt=="number"&&t.expiresAt||typeof n.expiresAt=="number"&&n.expiresAt||null;r&&(localStorage.setItem(En.authToken,r),In(r)),o&&localStorage.setItem(En.authTokenExpiresAt,o.toString()),(r||o)&&window.dispatchEvent(new CustomEvent("smartorg:chat-token-updated",{detail:{token:r,expiresAt:o}}))}catch(t){console.warn("[chat-api] Error storing token:",t)}return e},e=>Promise.reject(e));async function Mt(e,t){return It.defaults.baseURL?(await It.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function Dr(e,t,n){return It.defaults.baseURL?(await It.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function zl(e,t,n){return It.defaults.baseURL?(await It.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Zs(e,t){return It.defaults.baseURL?(await It.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function At(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class Bl{get baseUrl(){return It.defaults.baseURL||""}updateConfig(t){if(t.chatBaseUrl)It.defaults.baseURL=t.chatBaseUrl;else if(t.baseUrl){const n=t.baseUrl.replace(/\/+$/,"");n.endsWith("/chat")?It.defaults.baseURL=n:It.defaults.baseURL=`${n}/chat`}t.apiKey!==void 0?In(t.apiKey):t.getToken&&In(t.getToken())}getAuthToken(){return Xs()}setAuthToken(t){In(t)}onTokenChange(t){return Js(t)}async listThreads(){const t=await Mt("/threads"),n=At(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async listSharedThreads(){const t=await Mt("/threads/shared"),n=At(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t,n){const r={};t&&(r.title=t),n&&(r.project=n);const o=await Dr("/threads",Object.keys(r).length?r:void 0);return At(o)}async updateThread(t,n){const r=await zl(`/threads/${t}`,{title:n});return At(r)}async deleteThread(t){const n=await Zs(`/threads/${t}`);return At(n)}async shareThread(t,n){const r=await Dr(`/threads/${t}/share`,{shared_with_user_id:n});return At(r)}async threadInfo(t){const n=await Mt(`/threads/${t}/info`);return At(n)}async listAgents(){const t=await Mt("/agents"),n=At(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await Mt(`/agents/${t}`);return At(n)}async getAgentSchema(t){const n=await Mt(`/agents/${t}/schema`);return At(n)}async getState(t){const n=await Mt(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return At(n)}async getStateHistory(t){const n=await Mt(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:Fl,signal:t.signal});return At(n)}async cancelRun(t){const n=await Dr("/stream/cancel",{threadId:t});return At(n)}async unshareThread(t,n){const r=await Zs(`/threads/${t}/share/${n}`);return At(r)}}const An=new Bl;class Hl{async fetchFileBlob(t,n){return await Mt(t,{responseType:"blob",onDownloadProgress:o=>{try{if(n&&o.lengthComputable){const s=o.loaded/o.total;n(s)}}catch{}},maxBodyLength:1/0})}async viewFileById(t,n){const r=await this.fetchFileBlob(`/files/${t}/view`,n),o=URL.createObjectURL(r);window.open(o,"_blank"),setTimeout(()=>URL.revokeObjectURL(o),6e4)}async getFileBlob(t,n){return await this.fetchFileBlob(`/files/${t}/view`,n)}async getFileContent(t,n){return await(await this.fetchFileBlob(`/files/${t}/view`,n)).text()}async downloadFileById(t,n){const r=await this.fetchFileBlob(`/files/${t}/download`,n),o=URL.createObjectURL(r);let s=`file_${t}`;try{const a=await Mt(`/files/${t}`);s=(a==null?void 0:a.filename)??s}catch{}const i=document.createElement("a");i.href=o,i.download=s,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(o),6e4)}async getFileInfo(t){return await Mt(`/files/${t}`)}async listFiles(t,n=50,r=0){const o={limit:n,offset:r};return t&&(o.thread_id=t),await Mt("/files",{params:o})}async uploadFile(t,n,r){const o=new FormData;return o.append("file",t),n&&o.append("thread_id",n),await Dr("/files/upload-form",o,{onUploadProgress:s=>{try{if(r&&s.lengthComputable){const i=s.loaded/s.total;r(i)}}catch{}}})}}const Qs=new Hl;var ei={exports:{}},Lr={};/**
5
+ `):" "+jl(i[0]):"as no adapter specified";throw new Ie("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return o},adapters:Ks};function qs(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new lr(null,e)}function Ol(e){return qs(e),e.headers=Rt.from(e.headers),e.data=Vs.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Pl.getAdapter(e.adapter||Rr.adapter,e)(e).then(function(r){return qs(e),r.data=Vs.call(e,e.transformResponse,r),r.headers=Rt.from(r.headers),r},function(r){return bl(r)||(qs(e),r&&r.response&&(r.response.data=Vs.call(e,e.transformResponse,r.response),r.response.headers=Rt.from(r.response.headers))),Promise.reject(r)})}const Rl="1.12.2",Eo={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Eo[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Ml={};Eo.transitional=function(t,n,r){function o(s,i){return"[Axios v"+Rl+"] Transitional option '"+s+"'"+i+(r?". "+r:"")}return(s,i,a)=>{if(t===!1)throw new Ie(o(i," has been removed"+(n?" in "+n:"")),Ie.ERR_DEPRECATED);return n&&!Ml[i]&&(Ml[i]=!0,console.warn(o(i," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(s,i,a):!0}},Eo.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function Om(e,t,n){if(typeof e!="object")throw new Ie("options must be an object",Ie.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const s=r[o],i=t[s];if(i){const a=e[s],c=a===void 0||i(a,s,e);if(c!==!0)throw new Ie("option "+s+" must be "+c,Ie.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Ie("Unknown option "+s,Ie.ERR_BAD_OPTION)}}const Io={assertOptions:Om,validators:Eo},cn=Io.validators;let Wn=class{constructor(t){this.defaults=t||{},this.interceptors={request:new pl,response:new pl}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=`
6
+ `+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Un(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&Io.assertOptions(r,{silentJSONParsing:cn.transitional(cn.boolean),forcedJSONParsing:cn.transitional(cn.boolean),clarifyTimeoutError:cn.transitional(cn.boolean)},!1),o!=null&&(B.isFunction(o)?n.paramsSerializer={serialize:o}:Io.assertOptions(o,{encode:cn.function,serialize:cn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Io.assertOptions(n,{baseUrl:cn.spelling("baseURL"),withXsrfToken:cn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&B.merge(s.common,s[n.method]);s&&B.forEach(["delete","get","head","post","put","patch","common"],m=>{delete s[m]}),n.headers=Rt.concat(i,s);const a=[];let c=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(n)===!1||(c=c&&g.synchronous,a.unshift(g.fulfilled,g.rejected))});const l=[];this.interceptors.response.forEach(function(g){l.push(g.fulfilled,g.rejected)});let u,f=0,h;if(!c){const m=[Ol.bind(this),void 0];for(m.unshift(...a),m.push(...l),h=m.length,u=Promise.resolve(n);f<h;)u=u.then(m[f++],m[f++]);return u}h=a.length;let p=n;for(;f<h;){const m=a[f++],g=a[f++];try{p=m(p)}catch(b){g.call(this,b);break}}try{u=Ol.call(this,p)}catch(m){return Promise.reject(m)}for(f=0,h=l.length;f<h;)u=u.then(l[f++],l[f++]);return u}getUri(t){t=Un(this.defaults,t);const n=Sl(t.baseURL,t.url,t.allowAbsoluteUrls);return hl(n,t.params,t.paramsSerializer)}};B.forEach(["delete","get","head","options"],function(t){Wn.prototype[t]=function(n,r){return this.request(Un(r||{},{method:t,url:n,data:(r||{}).data}))}}),B.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(Un(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Wn.prototype[t]=n(),Wn.prototype[t+"Form"]=n(!0)});let Rm=class hp{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(o=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{r.subscribe(a),s=a}).then(o);return i.cancel=function(){r.unsubscribe(s)},i},t(function(s,i,a){r.reason||(r.reason=new lr(s,i,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new hp(function(o){t=o}),cancel:t}}};function Mm(e){return function(n){return e.apply(null,n)}}function Dm(e){return B.isObject(e)&&e.isAxiosError===!0}const Gs={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Gs).forEach(([e,t])=>{Gs[t]=e});function Dl(e){const t=new Wn(e),n=Za(Wn.prototype.request,t);return B.extend(n,Wn.prototype,t,{allOwnKeys:!0}),B.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Dl(Un(e,o))},n}const at=Dl(Rr);at.Axios=Wn,at.CanceledError=lr,at.CancelToken=Rm,at.isCancel=bl,at.VERSION=Rl,at.toFormData=So,at.AxiosError=Ie,at.Cancel=at.CanceledError,at.all=function(t){return Promise.all(t)},at.spread=Mm,at.isAxiosError=Dm,at.mergeConfig=Un,at.AxiosHeaders=Rt,at.formToJSON=e=>gl(B.isHTMLForm(e)?new FormData(e):e),at.getAdapter=Pl.getAdapter,at.HttpStatusCode=Gs,at.default=at;const{Axios:NC,AxiosError:_C,CanceledError:jC,isCancel:Ll,CancelToken:PC,VERSION:OC,all:RC,Cancel:MC,isAxiosError:DC,spread:LC,toFormData:$C,AxiosHeaders:FC,HttpStatusCode:zC,formToJSON:BC,getAdapter:HC,mergeConfig:UC}=at,En={authToken:"authToken",authTokenExpiresAt:"authTokenExpiresAt",authSessionId:"authSessionId",chatSettings:"chat-settings",threadManagerView:"thread-manager-view",playgroundSettings:"new-chat-ui-chat-settings",debugLogs:"app:debugLogs"};function Ao(e){return`draft:${e}`}let No=null;const Ys=new Set;function Xs(){return No}function In(e){No=e,Ys.forEach(t=>t(e))}function Js(e){return Ys.add(e),()=>Ys.delete(e)}const $l=3e4,Fl=9e4,It=at.create({timeout:$l,withCredentials:!0});It.interceptors.request.use(e=>(No&&(e.headers.Authorization=`Bearer ${No}`),e)),It.interceptors.response.use(e=>{if(typeof window<"u"&&(e!=null&&e.data))try{const t=e.data,n=t.data||{},r=typeof t.token=="string"&&t.token||typeof n.token=="string"&&n.token||null,o=typeof t.expires_at=="number"&&t.expires_at||typeof n.expires_at=="number"&&n.expires_at||typeof t.expiresAt=="number"&&t.expiresAt||typeof n.expiresAt=="number"&&n.expiresAt||null;r&&(localStorage.setItem(En.authToken,r),In(r)),o&&localStorage.setItem(En.authTokenExpiresAt,o.toString()),(r||o)&&window.dispatchEvent(new CustomEvent("smartorg:chat-token-updated",{detail:{token:r,expiresAt:o}}))}catch(t){console.warn("[chat-api] Error storing token:",t)}return e},e=>Promise.reject(e));async function Mt(e,t){return It.defaults.baseURL?(await It.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function Dr(e,t,n){return It.defaults.baseURL?(await It.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function zl(e,t,n){return It.defaults.baseURL?(await It.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Zs(e,t){return It.defaults.baseURL?(await It.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function At(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class Bl{get baseUrl(){return It.defaults.baseURL||""}updateConfig(t){if(t.chatBaseUrl)It.defaults.baseURL=t.chatBaseUrl;else if(t.baseUrl){const n=t.baseUrl.replace(/\/+$/,"");n.endsWith("/chat")?It.defaults.baseURL=n:It.defaults.baseURL=`${n}/chat`}t.apiKey!==void 0?In(t.apiKey):t.getToken&&In(t.getToken())}getAuthToken(){return Xs()}setAuthToken(t){In(t)}onTokenChange(t){return Js(t)}async listThreads(){const t=await Mt("/threads"),n=At(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async listSharedThreads(){const t=await Mt("/threads/shared"),n=At(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t,n){const r={};t&&(r.title=t),n&&(r.project=n);const o=await Dr("/threads",Object.keys(r).length?r:void 0);return At(o)}async updateThread(t,n){const r=await zl(`/threads/${t}`,{title:n});return At(r)}async deleteThread(t){const n=await Zs(`/threads/${t}`);return At(n)}async shareThread(t,n){const r=await Dr(`/threads/${t}/share`,{shared_with_user_id:n});return At(r)}async threadInfo(t){const n=await Mt(`/threads/${t}/info`);return At(n)}async listAgents(){const t=await Mt("/agents"),n=At(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await Mt(`/agents/${t}`);return At(n)}async getAgentSchema(t){const n=await Mt(`/agents/${t}/schema`);return At(n)}async getState(t){const n=await Mt(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return At(n)}async getStateHistory(t){const n=await Mt(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:Fl,signal:t.signal});return At(n)}async cancelRun(t){const n=await Dr("/stream/cancel",{threadId:t});return At(n)}async unshareThread(t,n){const r=await Zs(`/threads/${t}/share/${n}`);return At(r)}}const An=new Bl;class Hl{async fetchFileBlob(t,n){return await Mt(t,{responseType:"blob",onDownloadProgress:o=>{try{if(n&&o.lengthComputable){const s=o.loaded/o.total;n(s)}}catch{}},maxBodyLength:1/0})}async viewFileById(t,n){const r=await this.fetchFileBlob(`/files/${t}/view`,n),o=URL.createObjectURL(r);window.open(o,"_blank"),setTimeout(()=>URL.revokeObjectURL(o),6e4)}async getFileBlob(t,n){return await this.fetchFileBlob(`/files/${t}/view`,n)}async getFileContent(t,n){return await(await this.fetchFileBlob(`/files/${t}/view`,n)).text()}async downloadFileById(t,n){const r=await this.fetchFileBlob(`/files/${t}/download`,n),o=URL.createObjectURL(r);let s=`file_${t}`;try{const a=await Mt(`/files/${t}`);s=(a==null?void 0:a.filename)??s}catch{}const i=document.createElement("a");i.href=o,i.download=s,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(o),6e4)}async getFileInfo(t){return await Mt(`/files/${t}`)}async listFiles(t,n=50,r=0){const o={limit:n,offset:r};return t&&(o.thread_id=t),await Mt("/files",{params:o})}async uploadFile(t,n,r){const o=new FormData;return o.append("file",t),n&&o.append("thread_id",n),await Dr("/files/upload-form",o,{onUploadProgress:s=>{try{if(r&&s.lengthComputable){const i=s.loaded/s.total;r(i)}}catch{}}})}}const Qs=new Hl;var ei={exports:{}},Lr={};/**
7
7
  * @license React
8
8
  * react-jsx-runtime.production.min.js
9
9
  *
@@ -11,7 +11,7 @@
11
11
  *
12
12
  * This source code is licensed under the MIT license found in the
13
13
  * LICENSE file in the root directory of this source tree.
14
- */var Ul;function $m(){if(Ul)return Lr;Ul=1;var e=x,t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function i(a,c,l){var u,f={},h=null,p=null;l!==void 0&&(h=""+l),c.key!==void 0&&(h=""+c.key),c.ref!==void 0&&(p=c.ref);for(u in c)r.call(c,u)&&!s.hasOwnProperty(u)&&(f[u]=c[u]);if(a&&a.defaultProps)for(u in c=a.defaultProps,c)f[u]===void 0&&(f[u]=c[u]);return{$$typeof:t,type:a,key:h,ref:p,props:f,_owner:o.current}}return Lr.Fragment=n,Lr.jsx=i,Lr.jsxs=i,Lr}var $r={};/**
14
+ */var Ul;function Lm(){if(Ul)return Lr;Ul=1;var e=x,t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function i(a,c,l){var u,f={},h=null,p=null;l!==void 0&&(h=""+l),c.key!==void 0&&(h=""+c.key),c.ref!==void 0&&(p=c.ref);for(u in c)r.call(c,u)&&!s.hasOwnProperty(u)&&(f[u]=c[u]);if(a&&a.defaultProps)for(u in c=a.defaultProps,c)f[u]===void 0&&(f[u]=c[u]);return{$$typeof:t,type:a,key:h,ref:p,props:f,_owner:o.current}}return Lr.Fragment=n,Lr.jsx=i,Lr.jsxs=i,Lr}var $r={};/**
15
15
  * @license React
16
16
  * react-jsx-runtime.development.js
17
17
  *
@@ -19,7 +19,7 @@
19
19
  *
20
20
  * This source code is licensed under the MIT license found in the
21
21
  * LICENSE file in the root directory of this source tree.
22
- */var Wl;function Fm(){return Wl||(Wl=1,process.env.NODE_ENV!=="production"&&function(){var e=x,t=Symbol.for("react.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),i=Symbol.for("react.provider"),a=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),l=Symbol.for("react.suspense"),u=Symbol.for("react.suspense_list"),f=Symbol.for("react.memo"),h=Symbol.for("react.lazy"),p=Symbol.for("react.offscreen"),m=Symbol.iterator,g="@@iterator";function b(C){if(C===null||typeof C!="object")return null;var O=m&&C[m]||C[g];return typeof O=="function"?O:null}var v=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function y(C){{for(var O=arguments.length,z=new Array(O>1?O-1:0),se=1;se<O;se++)z[se-1]=arguments[se];T("error",C,z)}}function T(C,O,z){{var se=v.ReactDebugCurrentFrame,ie=se.getStackAddendum();ie!==""&&(O+="%s",z=z.concat([ie]));var Ce=z.map(function(Te){return String(Te)});Ce.unshift("Warning: "+O),Function.prototype.apply.call(console[C],console,Ce)}}var I=!1,k=!1,S=!1,E=!1,j=!1,_;_=Symbol.for("react.module.reference");function D(C){return!!(typeof C=="string"||typeof C=="function"||C===r||C===s||j||C===o||C===l||C===u||E||C===p||I||k||S||typeof C=="object"&&C!==null&&(C.$$typeof===h||C.$$typeof===f||C.$$typeof===i||C.$$typeof===a||C.$$typeof===c||C.$$typeof===_||C.getModuleId!==void 0))}function L(C,O,z){var se=C.displayName;if(se)return se;var ie=O.displayName||O.name||"";return ie!==""?z+"("+ie+")":z}function W(C){return C.displayName||"Context"}function V(C){if(C==null)return null;if(typeof C.tag=="number"&&y("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof C=="function")return C.displayName||C.name||null;if(typeof C=="string")return C;switch(C){case r:return"Fragment";case n:return"Portal";case s:return"Profiler";case o:return"StrictMode";case l:return"Suspense";case u:return"SuspenseList"}if(typeof C=="object")switch(C.$$typeof){case a:var O=C;return W(O)+".Consumer";case i:var z=C;return W(z._context)+".Provider";case c:return L(C,C.render,"ForwardRef");case f:var se=C.displayName||null;return se!==null?se:V(C.type)||"Memo";case h:{var ie=C,Ce=ie._payload,Te=ie._init;try{return V(Te(Ce))}catch{return null}}}return null}var $=Object.assign,Z=0,X,oe,U,F,G,H,A;function N(){}N.__reactDisabledLog=!0;function R(){{if(Z===0){X=console.log,oe=console.info,U=console.warn,F=console.error,G=console.group,H=console.groupCollapsed,A=console.groupEnd;var C={configurable:!0,enumerable:!0,value:N,writable:!0};Object.defineProperties(console,{info:C,log:C,warn:C,error:C,group:C,groupCollapsed:C,groupEnd:C})}Z++}}function M(){{if(Z--,Z===0){var C={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:$({},C,{value:X}),info:$({},C,{value:oe}),warn:$({},C,{value:U}),error:$({},C,{value:F}),group:$({},C,{value:G}),groupCollapsed:$({},C,{value:H}),groupEnd:$({},C,{value:A})})}Z<0&&y("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var q=v.ReactCurrentDispatcher,J;function P(C,O,z){{if(J===void 0)try{throw Error()}catch(ie){var se=ie.stack.trim().match(/\n( *(at )?)/);J=se&&se[1]||""}return`
22
+ */var Wl;function $m(){return Wl||(Wl=1,process.env.NODE_ENV!=="production"&&function(){var e=x,t=Symbol.for("react.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),i=Symbol.for("react.provider"),a=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),l=Symbol.for("react.suspense"),u=Symbol.for("react.suspense_list"),f=Symbol.for("react.memo"),h=Symbol.for("react.lazy"),p=Symbol.for("react.offscreen"),m=Symbol.iterator,g="@@iterator";function b(C){if(C===null||typeof C!="object")return null;var O=m&&C[m]||C[g];return typeof O=="function"?O:null}var v=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function y(C){{for(var O=arguments.length,z=new Array(O>1?O-1:0),se=1;se<O;se++)z[se-1]=arguments[se];T("error",C,z)}}function T(C,O,z){{var se=v.ReactDebugCurrentFrame,ie=se.getStackAddendum();ie!==""&&(O+="%s",z=z.concat([ie]));var Ce=z.map(function(Te){return String(Te)});Ce.unshift("Warning: "+O),Function.prototype.apply.call(console[C],console,Ce)}}var I=!1,k=!1,S=!1,E=!1,j=!1,_;_=Symbol.for("react.module.reference");function D(C){return!!(typeof C=="string"||typeof C=="function"||C===r||C===s||j||C===o||C===l||C===u||E||C===p||I||k||S||typeof C=="object"&&C!==null&&(C.$$typeof===h||C.$$typeof===f||C.$$typeof===i||C.$$typeof===a||C.$$typeof===c||C.$$typeof===_||C.getModuleId!==void 0))}function L(C,O,z){var se=C.displayName;if(se)return se;var ie=O.displayName||O.name||"";return ie!==""?z+"("+ie+")":z}function W(C){return C.displayName||"Context"}function V(C){if(C==null)return null;if(typeof C.tag=="number"&&y("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof C=="function")return C.displayName||C.name||null;if(typeof C=="string")return C;switch(C){case r:return"Fragment";case n:return"Portal";case s:return"Profiler";case o:return"StrictMode";case l:return"Suspense";case u:return"SuspenseList"}if(typeof C=="object")switch(C.$$typeof){case a:var O=C;return W(O)+".Consumer";case i:var z=C;return W(z._context)+".Provider";case c:return L(C,C.render,"ForwardRef");case f:var se=C.displayName||null;return se!==null?se:V(C.type)||"Memo";case h:{var ie=C,Ce=ie._payload,Te=ie._init;try{return V(Te(Ce))}catch{return null}}}return null}var $=Object.assign,Z=0,X,oe,U,F,G,H,A;function N(){}N.__reactDisabledLog=!0;function R(){{if(Z===0){X=console.log,oe=console.info,U=console.warn,F=console.error,G=console.group,H=console.groupCollapsed,A=console.groupEnd;var C={configurable:!0,enumerable:!0,value:N,writable:!0};Object.defineProperties(console,{info:C,log:C,warn:C,error:C,group:C,groupCollapsed:C,groupEnd:C})}Z++}}function M(){{if(Z--,Z===0){var C={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:$({},C,{value:X}),info:$({},C,{value:oe}),warn:$({},C,{value:U}),error:$({},C,{value:F}),group:$({},C,{value:G}),groupCollapsed:$({},C,{value:H}),groupEnd:$({},C,{value:A})})}Z<0&&y("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var q=v.ReactCurrentDispatcher,J;function P(C,O,z){{if(J===void 0)try{throw Error()}catch(ie){var se=ie.stack.trim().match(/\n( *(at )?)/);J=se&&se[1]||""}return`
23
23
  `+J+C}}var K=!1,te;{var le=typeof WeakMap=="function"?WeakMap:Map;te=new le}function he(C,O){if(!C||K)return"";{var z=te.get(C);if(z!==void 0)return z}var se;K=!0;var ie=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var Ce;Ce=q.current,q.current=null,R();try{if(O){var Te=function(){throw Error()};if(Object.defineProperty(Te.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Te,[])}catch(Bt){se=Bt}Reflect.construct(C,[],Te)}else{try{Te.call()}catch(Bt){se=Bt}C.call(Te.prototype)}}else{try{throw Error()}catch(Bt){se=Bt}C()}}catch(Bt){if(Bt&&se&&typeof Bt.stack=="string"){for(var _e=Bt.stack.split(`
24
24
  `),nt=se.stack.split(`
25
25
  `),Ye=_e.length-1,it=nt.length-1;Ye>=1&&it>=0&&_e[Ye]!==nt[it];)it--;for(;Ye>=1&&it>=0;Ye--,it--)if(_e[Ye]!==nt[it]){if(Ye!==1||it!==1)do if(Ye--,it--,it<0||_e[Ye]!==nt[it]){var Qt=`
@@ -32,11 +32,11 @@ Check the top-level render call using <`+z+">.")}return O}}function Ft(C,O){{if(
32
32
  <%s {...props} />
33
33
  React keys must be passed directly to JSX without using spread:
34
34
  let props = %s;
35
- <%s key={someKey} {...props} />`,qa,or,wC,or),Gt[or+qa]=!0}}return C===r?Tn(it):kn(it),it}}function ln(C,O,z){return vn(C,O,z,!0)}function Y(C,O,z){return vn(C,O,z,!1)}var fe=Y,Q=ln;$r.Fragment=r,$r.jsx=fe,$r.jsxs=Q}()),$r}process.env.NODE_ENV==="production"?ei.exports=$m():ei.exports=Fm();var d=ei.exports;class zm{constructor(){Ga(this,"_authBaseUrl","")}get baseUrl(){return this._authBaseUrl}updateConfig(t){if(t.authBaseUrl)this._authBaseUrl=t.authBaseUrl;else if(t.baseUrl){const n=t.baseUrl.replace(/\/+$/,"");this._authBaseUrl=`${n}/auth`}t.apiKey!==void 0?In(t.apiKey):t.getToken&&In(t.getToken())}getAuthToken(){return Xs()}setAuthToken(t){In(t)}onTokenChange(t){return Js(t)}async listUsers(){const t=await Mt("/users",{baseURL:this.baseUrl});return(t==null?void 0:t.users)??[]}}const Bm=new zm,Vl=x.createContext(null);function Kl({children:e,apiConfig:t}){const n=An,r=Bm;if(t){const s=n.baseUrl,i=r.baseUrl,a=n.getAuthToken();(t.baseUrl||t.chatBaseUrl)&&(t.chatBaseUrl&&t.chatBaseUrl!==s||t.baseUrl&&!s.startsWith(t.baseUrl))&&n.updateConfig(t),(t.baseUrl||t.authBaseUrl)&&(t.authBaseUrl&&t.authBaseUrl!==i||t.baseUrl&&!i.startsWith(t.baseUrl))&&r.updateConfig(t),t.apiKey!==void 0&&t.apiKey!==a&&(n.updateConfig({apiKey:t.apiKey}),r.updateConfig({apiKey:t.apiKey}))}const o={token:n.getAuthToken(),setToken:s=>{n.setAuthToken(s),r.setAuthToken(s)},chatApi:n,authApi:r,fileApi:Qs,baseUrl:n.baseUrl};return d.jsx(Vl.Provider,{value:o,children:e})}async function ql(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const o=r.result,s=new Uint8Array(o);let i="";const a=s.byteLength;for(let c=0;c<a;c++)i+=String.fromCharCode(s[c]);t(btoa(i))}catch(o){n(o)}},r.onerror=o=>n(o),r.readAsArrayBuffer(e)})}async function Gl(e=[]){const t=[],n=[];for(const r of e)try{const o=await ql(r),s=r.type||"application/octet-stream";n.push({filename:r.name,data:o,mime_type:s}),s.startsWith("image/")?t.push({type:"image_url",url:`data:${s};base64,${o}`,mimeType:s,alt:r.name}):t.push({type:"file",url:`data:${s};base64,${o}`,mimeType:s,name:r.name,size:r.size,sourceType:"base64"})}catch{}return{contentParts:t,filesInfo:n}}function Vn(){const e=x.useContext(Vl);if(!e)throw new Error("useApi must be used within ApiProvider");return e}function Hm(e,t,n){const r=typeof t=="string"?[{type:"text",text:t}]:t;return{id:`msg-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,role:e,content:r,createdAt:new Date().toISOString(),...n}}function Yl(e,t="user"){return typeof e=="string"?Hm(t,e):e}function Kn(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function Fr(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}}function Um(e,t){if(!e)return null;for(const n of t){const r=e[n];if(typeof r=="number"&&Number.isFinite(r))return r}return null}function Xl(e){const t=Kn(e);if(t)return Kn(t.configurable)??t}function cr(e){const r=[...(Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[]).map((s,i)=>Wm(s,i)).filter(s=>!!s)].sort((s,i)=>Jl(i.createdAt)-Jl(s.createdAt)),o=r[0]??null;return{threadId:(e==null?void 0:e.threadId)??"",latest:o,checkpoints:r,interrupt:(o==null?void 0:o.interrupt)??null}}function Wm(e,t){var k,S,E,j;if(!e)return null;const n=((k=e.values)==null?void 0:k.active_agent)??((S=e.values)==null?void 0:S.activeAgent)??null,r=(E=e.values)==null?void 0:E.messages,s=(Array.isArray(r)?r:[]).map(_=>Vm(_,n)).filter(_=>!!_),i=Kn(e.metadata)??{},a=Xl(e.config),c=Kn(e.parent_config??e.parentConfig),l=Xl(c),u=Fr(a,["checkpoint_id","checkpointId"]),f=Fr(a,["checkpoint_ns","checkpointNs"]),h=Fr(l,["checkpoint_id","checkpointId"]),p=Kn(e.config),m=Array.isArray(e.tasks)?e.tasks.map(_=>({..._})):e.tasks??null,g=Array.isArray(e.next)?[...e.next]:e.next??null,b=typeof e.created_at=="string"&&e.created_at.trim()?e.created_at:typeof e.createdAt=="string"&&e.createdAt.trim()?e.createdAt:new Date(Date.now()-t).toISOString(),v={...i,step:Um(i,["step"])??0,source:Fr(i,["source"])??null},y=s.map(_=>({..._,checkpointId:u??null})),T=(j=e.values)==null?void 0:j.interrupts,I=Array.isArray(e.interrupts)?e.interrupts:Array.isArray(T)?T:[];return{checkpointId:u??null,checkpointNs:f??null,createdAt:b,parentId:h??null,messages:y,interrupt:Ym(s,I,t,u??null),metadata:v,config:p??null,parentConfig:c??null,next:g,tasks:m,values:e.values??{}}}function Vm(e,t){var l,u,f;if(!e||typeof e!="object")return null;const n=Km(e);if(!n)return null;const r=Gm(e==null?void 0:e.content);if(!r.length)return null;const o=typeof e.createdAt=="string"?e.createdAt:typeof((l=e.additional_kwargs)==null?void 0:l.created_at)=="string"?(u=e.additional_kwargs)==null?void 0:u.created_at:new Date().toISOString(),s=typeof e.id=="string"&&e.id.trim()?e.id:`msg-${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`,i=typeof e.name=="string"?e.name:void 0,a=typeof e.model=="string"?e.model:((f=e.additional_kwargs)==null?void 0:f.model)??void 0;return{id:s,role:n,name:i??a??(n==="assistant"?t??void 0:void 0),model:a,createdAt:o,content:r,toolCallId:e.toolCallId??e.tool_call_id??void 0,tool_calls:e.tool_calls??e.toolCalls??void 0,additionalKwargs:e.additional_kwargs??void 0,responseMetadata:e.response_metadata??void 0,artifact:e.artifact??void 0,threadId:e.threadId??e.thread_id}}function Km(e){const t=typeof e.role=="string"?e.role:void 0;if(t&&qm(t))return t;const n=typeof e.type=="string"?e.type:void 0;if(!n)return null;switch(n){case"human":return"user";case"ai":return"assistant";case"tool":return"tool";case"system":return"system";default:return null}}function qm(e){return e==="assistant"||e==="user"||e==="system"||e==="tool"||e==="default_message"}function Gm(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>!!(t&&typeof t=="object"&&typeof t.type=="string")):[]}function Ym(e,t,n,r){const o=t.length,s=Xm(e,n);if(s)return s;for(let i=o-1;i>=0;i-=1){const a=t[i];if(!a||typeof a!="object")continue;const c=a,l=c.value??a;if(l==null)continue;return{id:typeof c.id=="string"&&c.id.trim()?c.id:`interrupt-${r??n}-${i}`,value:l}}return null}function Xm(e,t){var n;for(let r=e.length-1;r>=0;r--){const o=((n=e[r])==null?void 0:n.content)??[];for(let s=o.length-1;s>=0;s--){const i=o[s];if((i==null?void 0:i.type)==="interrupt"){const a=i;return{id:typeof a.id=="string"&&a.id.trim()?a.id:`interrupt-${t}-${r}-${s}`,value:a.value}}}}return null}function Jl(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Zl(e){return!!e&&typeof e=="object"&&"data"in e}function Jm(e={}){const t=e.baseUrl||"",n=e.streamPath??"/stream",[r,o]=x.useState(e.token??null),s=x.useRef(e.headers??{}),i=e.credentials??"include",[a,c]=x.useState(!1),[l,u]=x.useState(null),[f,h]=x.useState(""),[p,m]=x.useState(null),[g,b]=x.useState(0),[v,y]=x.useState(!1),[T,I]=x.useState({}),[k,S]=x.useState(null),[E,j]=x.useState({}),_=x.useRef(null),D=x.useRef(!0),L=x.useRef(0),W=x.useRef(null),V=x.useRef(null),$=x.useRef(null),Z=x.useRef(null),X=x.useRef({messageId:null,lastSeq:null,lastText:""}),oe=x.useCallback(H=>{o(H)},[]),U=x.useCallback(()=>{h(""),m(null),u(null),V.current=null,$.current=null,Z.current=null,I({}),S(null),j({}),X.current={messageId:null,lastSeq:null,lastText:""}},[]),F=x.useCallback(()=>{var R;console.debug("[use-chat] stop() invoked - aborting stream");const H=(R=W.current)==null?void 0:R.threadId,A=()=>{var M;(M=_.current)==null||M.abort(),_.current=null,W.current=null,c(!1),y(!1),L.current=0,b(0)};(H?An.cancelRun(H).catch(M=>{console.warn("[use-chat] cancel run failed:",M)}):Promise.resolve()).finally(A)},[]),G=x.useCallback((H,A,N)=>{_.current&&(_.current.abort(),_.current=null),c(!0),u(null),e.autoAppendAssistant!==!1&&h(""),m(null),V.current=null,$.current=null,Z.current=null,I({}),S(null),j({}),X.current={messageId:null,lastSeq:null,lastText:""};const R=new AbortController;_.current=R;let M=null,q=null,J=!1;return W.current={threadId:H.threadId??null,headers:{},isStreaming:!0},(async()=>{var P,K,te,le,he,ue,ge,be,Be,Le,je,Fe,tt,mt,ot,ze,Me,Ze;try{let rt={};try{if(r)rt={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const Ee=window.__AUTH_TOKEN__,Ve=((P=window.localStorage)==null?void 0:P.getItem(En.authToken))||null;let dt=null;try{const Ft=(K=window.localStorage)==null?void 0:K.getItem(En.chatSettings);Ft&&(dt=((te=JSON.parse(Ft))==null?void 0:te.apiKey)||null)}catch{}const Et=Ee||Ve||dt||null;Et&&(rt={Authorization:`Bearer ${Et}`})}}catch{}console.debug("[use-chat] POST",t+n);let qe={};if(typeof window<"u")try{const $e=(le=window.localStorage)==null?void 0:le.getItem(En.authSessionId);$e&&(qe={"X-Session-Id":$e})}catch{}const ht={...rt,...qe,...s.current},xt={"Content-Type":"application/json",Accept:"text/event-stream",...ht},He=await fetch(t+n,{method:"POST",headers:xt,body:JSON.stringify(H),signal:R.signal,credentials:i});if(W.current&&(W.current.headers=ht),!He.ok||!He.body){const $e=await He.text().catch(()=>"");console.debug("[use-chat] non-OK response",He.status,$e==null?void 0:$e.slice(0,500));const Ee=`stream ${He.status}${$e?": "+$e:""}`;throw(he=N==null?void 0:N.onConnectionError)==null||he.call(N,Ee),J=!0,M="error",q=Ee,new Error(Ee)}y(!0);const st=He.body.getReader(),an=new TextDecoder;let jt="",ct=[];L.current=0,b(0);let kt=0,Tt=null;const bt=()=>{if(ct.length){const $e=ct.join("");ct=[],D.current&&h(Ee=>Ee+$e)}Tt=null},Ge=()=>{typeof window<"u"&&Tt==null&&(Tt=requestAnimationFrame(bt))};let gt=Date.now();const ut=setInterval(()=>{var $e;if(Date.now()-gt>18e5){const Ee="Stream idle timeout";u(Ee),M="error",q=Ee,R.abort(),($e=N==null?void 0:N.onError)==null||$e.call(N,Ee)}},5e3),$t=1024*1024;try{const $e=He.headers.get("X-Thread-Id")||He.headers.get("x-thread-id"),Ee=He.headers.get("X-Thread-Created")||He.headers.get("x-thread-created"),Ve=$e??null,dt=String(Ee??"").toLowerCase()==="true";for(W.current&&!W.current.threadId&&(W.current={...W.current,threadId:Ve}),(ue=N==null?void 0:N.onOpen)==null||ue.call(N,{threadId:Ve,created:dt});;){const{value:Et,done:Ft}=await st.read();if(Ft)break;jt+=an.decode(Et,{stream:!0}),jt.length>$t&&(jt="",console.warn("Stream buffer reset: exceeded 1MB"));let zt;for(;(zt=jt.indexOf(`
35
+ <%s key={someKey} {...props} />`,qa,or,wC,or),Gt[or+qa]=!0}}return C===r?Tn(it):kn(it),it}}function ln(C,O,z){return vn(C,O,z,!0)}function Y(C,O,z){return vn(C,O,z,!1)}var fe=Y,Q=ln;$r.Fragment=r,$r.jsx=fe,$r.jsxs=Q}()),$r}process.env.NODE_ENV==="production"?ei.exports=Lm():ei.exports=$m();var d=ei.exports;class Fm{constructor(){Ga(this,"_authBaseUrl","")}get baseUrl(){return this._authBaseUrl}updateConfig(t){if(t.authBaseUrl)this._authBaseUrl=t.authBaseUrl;else if(t.baseUrl){const n=t.baseUrl.replace(/\/+$/,"");this._authBaseUrl=`${n}/auth`}t.apiKey!==void 0?In(t.apiKey):t.getToken&&In(t.getToken())}getAuthToken(){return Xs()}setAuthToken(t){In(t)}onTokenChange(t){return Js(t)}async listUsers(){const t=await Mt("/users",{baseURL:this.baseUrl});return(t==null?void 0:t.users)??[]}}const zm=new Fm,Vl=x.createContext(null);function Kl({children:e,apiConfig:t}){const n=An,r=zm;if(t){const s=n.baseUrl,i=r.baseUrl,a=n.getAuthToken();(t.baseUrl||t.chatBaseUrl)&&(t.chatBaseUrl&&t.chatBaseUrl!==s||t.baseUrl&&!s.startsWith(t.baseUrl))&&n.updateConfig(t),(t.baseUrl||t.authBaseUrl)&&(t.authBaseUrl&&t.authBaseUrl!==i||t.baseUrl&&!i.startsWith(t.baseUrl))&&r.updateConfig(t),t.apiKey!==void 0&&t.apiKey!==a&&(n.updateConfig({apiKey:t.apiKey}),r.updateConfig({apiKey:t.apiKey}))}const o={token:n.getAuthToken(),setToken:s=>{n.setAuthToken(s),r.setAuthToken(s)},chatApi:n,authApi:r,fileApi:Qs,baseUrl:n.baseUrl};return d.jsx(Vl.Provider,{value:o,children:e})}async function ql(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const o=r.result,s=new Uint8Array(o);let i="";const a=s.byteLength;for(let c=0;c<a;c++)i+=String.fromCharCode(s[c]);t(btoa(i))}catch(o){n(o)}},r.onerror=o=>n(o),r.readAsArrayBuffer(e)})}async function Gl(e=[]){const t=[],n=[];for(const r of e)try{const o=await ql(r),s=r.type||"application/octet-stream";n.push({filename:r.name,data:o,mime_type:s}),s.startsWith("image/")?t.push({type:"image_url",url:`data:${s};base64,${o}`,mimeType:s,alt:r.name}):t.push({type:"file",url:`data:${s};base64,${o}`,mimeType:s,name:r.name,size:r.size,sourceType:"base64"})}catch{}return{contentParts:t,filesInfo:n}}function Vn(){const e=x.useContext(Vl);if(!e)throw new Error("useApi must be used within ApiProvider");return e}function Bm(e,t,n){const r=typeof t=="string"?[{type:"text",text:t}]:t;return{id:`msg-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,role:e,content:r,createdAt:new Date().toISOString(),...n}}function Yl(e,t="user"){return typeof e=="string"?Bm(t,e):e}function Kn(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function Fr(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}}function Hm(e,t){if(!e)return null;for(const n of t){const r=e[n];if(typeof r=="number"&&Number.isFinite(r))return r}return null}function Xl(e){const t=Kn(e);if(t)return Kn(t.configurable)??t}function cr(e){const r=[...(Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[]).map((s,i)=>Um(s,i)).filter(s=>!!s)].sort((s,i)=>Jl(i.createdAt)-Jl(s.createdAt)),o=r[0]??null;return{threadId:(e==null?void 0:e.threadId)??"",latest:o,checkpoints:r,interrupt:(o==null?void 0:o.interrupt)??null}}function Um(e,t){var k,S,E,j;if(!e)return null;const n=((k=e.values)==null?void 0:k.active_agent)??((S=e.values)==null?void 0:S.activeAgent)??null,r=(E=e.values)==null?void 0:E.messages,s=(Array.isArray(r)?r:[]).map(_=>Wm(_,n)).filter(_=>!!_),i=Kn(e.metadata)??{},a=Xl(e.config),c=Kn(e.parent_config??e.parentConfig),l=Xl(c),u=Fr(a,["checkpoint_id","checkpointId"]),f=Fr(a,["checkpoint_ns","checkpointNs"]),h=Fr(l,["checkpoint_id","checkpointId"]),p=Kn(e.config),m=Array.isArray(e.tasks)?e.tasks.map(_=>({..._})):e.tasks??null,g=Array.isArray(e.next)?[...e.next]:e.next??null,b=typeof e.created_at=="string"&&e.created_at.trim()?e.created_at:typeof e.createdAt=="string"&&e.createdAt.trim()?e.createdAt:new Date(Date.now()-t).toISOString(),v={...i,step:Hm(i,["step"])??0,source:Fr(i,["source"])??null},y=s.map(_=>({..._,checkpointId:u??null})),T=(j=e.values)==null?void 0:j.interrupts,I=Array.isArray(e.interrupts)?e.interrupts:Array.isArray(T)?T:[];return{checkpointId:u??null,checkpointNs:f??null,createdAt:b,parentId:h??null,messages:y,interrupt:Gm(s,I,t,u??null),metadata:v,config:p??null,parentConfig:c??null,next:g,tasks:m,values:e.values??{}}}function Wm(e,t){var l,u,f,h,p;if(!e||typeof e!="object")return null;const n=Vm(e);if(!n)return null;const r=qm(e==null?void 0:e.content);if(!r.length)return null;const o=typeof e.createdAt=="string"?e.createdAt:typeof((l=e.additional_kwargs)==null?void 0:l.created_at)=="string"?(u=e.additional_kwargs)==null?void 0:u.created_at:new Date().toISOString(),s=typeof e.id=="string"&&e.id.trim()?e.id:`msg-${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`,i=typeof e.name=="string"?e.name:void 0,a=typeof e.model=="string"?e.model:((f=e.additional_kwargs)==null?void 0:f.model)??void 0;return{id:s,role:n,name:i??a??(n==="assistant"?t??void 0:void 0),model:a,createdAt:o,content:r,toolCallId:e.toolCallId??e.tool_call_id??((h=e.additional_kwargs)==null?void 0:h.tool_call_id)??void 0,tool_calls:e.tool_calls??e.toolCalls??((p=e.additional_kwargs)==null?void 0:p.tool_calls)??void 0,additionalKwargs:e.additional_kwargs??void 0,responseMetadata:e.response_metadata??void 0,artifact:e.artifact??void 0,threadId:e.threadId??e.thread_id}}function Vm(e){const t=typeof e.role=="string"?e.role:void 0;if(t&&Km(t))return t;const n=typeof e.type=="string"?e.type:void 0;if(!n)return null;switch(n){case"human":return"user";case"ai":return"assistant";case"tool":return"tool";case"system":return"system";default:return null}}function Km(e){return e==="assistant"||e==="user"||e==="system"||e==="tool"||e==="default_message"}function qm(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e.filter(t=>!!(t&&typeof t=="object"&&typeof t.type=="string")):[]}function Gm(e,t,n,r){const o=t.length,s=Ym(e,n);if(s)return s;for(let i=o-1;i>=0;i-=1){const a=t[i];if(!a||typeof a!="object")continue;const c=a,l=c.value??a;if(l==null)continue;return{id:typeof c.id=="string"&&c.id.trim()?c.id:`interrupt-${r??n}-${i}`,value:l}}return null}function Ym(e,t){var n;for(let r=e.length-1;r>=0;r--){const o=((n=e[r])==null?void 0:n.content)??[];for(let s=o.length-1;s>=0;s--){const i=o[s];if((i==null?void 0:i.type)==="interrupt"){const a=i;return{id:typeof a.id=="string"&&a.id.trim()?a.id:`interrupt-${t}-${r}-${s}`,value:a.value}}}}return null}function Jl(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Zl(e){return!!e&&typeof e=="object"&&"data"in e}function Xm(e={}){const t=e.baseUrl||"",n=e.streamPath??"/stream",[r,o]=x.useState(e.token??null),s=x.useRef(e.headers??{}),i=e.credentials??"include",[a,c]=x.useState(!1),[l,u]=x.useState(null),[f,h]=x.useState(""),[p,m]=x.useState(null),[g,b]=x.useState(0),[v,y]=x.useState(!1),[T,I]=x.useState({}),[k,S]=x.useState(null),[E,j]=x.useState({}),_=x.useRef(null),D=x.useRef(!0),L=x.useRef(0),W=x.useRef(null),V=x.useRef(null),$=x.useRef(null),Z=x.useRef(null),X=x.useRef({messageId:null,lastSeq:null,lastText:""}),oe=x.useCallback(H=>{o(H)},[]),U=x.useCallback(()=>{h(""),m(null),u(null),V.current=null,$.current=null,Z.current=null,I({}),S(null),j({}),X.current={messageId:null,lastSeq:null,lastText:""}},[]),F=x.useCallback(()=>{var R;console.debug("[use-chat] stop() invoked - aborting stream");const H=(R=W.current)==null?void 0:R.threadId,A=()=>{var M;(M=_.current)==null||M.abort(),_.current=null,W.current=null,c(!1),y(!1),L.current=0,b(0)};(H?An.cancelRun(H).catch(M=>{console.warn("[use-chat] cancel run failed:",M)}):Promise.resolve()).finally(A)},[]),G=x.useCallback((H,A,N)=>{_.current&&(_.current.abort(),_.current=null),c(!0),u(null),e.autoAppendAssistant!==!1&&h(""),m(null),V.current=null,$.current=null,Z.current=null,I({}),S(null),j({}),X.current={messageId:null,lastSeq:null,lastText:""};const R=new AbortController;_.current=R;let M=null,q=null,J=!1;return W.current={threadId:H.threadId??null,headers:{},isStreaming:!0},(async()=>{var P,K,te,le,he,ue,ge,be,Be,Le,je,Fe,tt,mt,ot,ze,Me,Ze;try{let rt={};try{if(r)rt={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const Ee=window.__AUTH_TOKEN__,Ve=((P=window.localStorage)==null?void 0:P.getItem(En.authToken))||null;let dt=null;try{const Ft=(K=window.localStorage)==null?void 0:K.getItem(En.chatSettings);Ft&&(dt=((te=JSON.parse(Ft))==null?void 0:te.apiKey)||null)}catch{}const Et=Ee||Ve||dt||null;Et&&(rt={Authorization:`Bearer ${Et}`})}}catch{}console.debug("[use-chat] POST",t+n);let qe={};if(typeof window<"u")try{const $e=(le=window.localStorage)==null?void 0:le.getItem(En.authSessionId);$e&&(qe={"X-Session-Id":$e})}catch{}const ht={...rt,...qe,...s.current},xt={"Content-Type":"application/json",Accept:"text/event-stream",...ht},He=await fetch(t+n,{method:"POST",headers:xt,body:JSON.stringify(H),signal:R.signal,credentials:i});if(W.current&&(W.current.headers=ht),!He.ok||!He.body){const $e=await He.text().catch(()=>"");console.debug("[use-chat] non-OK response",He.status,$e==null?void 0:$e.slice(0,500));const Ee=`stream ${He.status}${$e?": "+$e:""}`;throw(he=N==null?void 0:N.onConnectionError)==null||he.call(N,Ee),J=!0,M="error",q=Ee,new Error(Ee)}y(!0);const st=He.body.getReader(),an=new TextDecoder;let jt="",ct=[];L.current=0,b(0);let kt=0,Tt=null;const bt=()=>{if(ct.length){const $e=ct.join("");ct=[],D.current&&h(Ee=>Ee+$e)}Tt=null},Ge=()=>{typeof window<"u"&&Tt==null&&(Tt=requestAnimationFrame(bt))};let gt=Date.now();const ut=setInterval(()=>{var $e;if(Date.now()-gt>18e5){const Ee="Stream idle timeout";u(Ee),M="error",q=Ee,R.abort(),($e=N==null?void 0:N.onError)==null||$e.call(N,Ee)}},5e3),$t=1024*1024;try{const $e=He.headers.get("X-Thread-Id")||He.headers.get("x-thread-id"),Ee=He.headers.get("X-Thread-Created")||He.headers.get("x-thread-created"),Ve=$e??null,dt=String(Ee??"").toLowerCase()==="true";for(W.current&&!W.current.threadId&&(W.current={...W.current,threadId:Ve}),(ue=N==null?void 0:N.onOpen)==null||ue.call(N,{threadId:Ve,created:dt});;){const{value:Et,done:Ft}=await st.read();if(Ft)break;jt+=an.decode(Et,{stream:!0}),jt.length>$t&&(jt="",console.warn("Stream buffer reset: exceeded 1MB"));let zt;for(;(zt=jt.indexOf(`
36
36
 
37
37
  `))>=0;){const kn=jt.slice(0,zt);jt=jt.slice(zt+2);const Tn=kn.split(/\r?\n/),Gt=[];let vn=null;for(const O of Tn){if(O.startsWith(":")){O.startsWith(": heartbeat")&&console.debug("[use-chat] SSE heartbeat comment received");continue}if(O){if(O.startsWith("event:")){const z=O.slice(6).trim();z&&(vn=z);continue}if(O.startsWith("data:")){const z=O.slice(5);Gt.push(z.startsWith(" ")?z.slice(1):z)}}}const ln=Gt.join(`
38
- `);if(!ln)continue;let Y;try{Y=JSON.parse(ln)}catch{console.debug("[use-chat] malformed SSE:",ln.slice(0,200));continue}vn&&typeof Y=="object"&&Y!==null&&!("type"in Y)&&(Y.type=vn);const fe=Zl(Y)?Y.data:Y;if(!fe){console.warn("[use-chat] dropped envelope event without payload",Y);continue}const Q=fe;gt=Date.now(),Q.type==="values"&&(Q.type="state_history"),Q.type==="metadata"&&(Q.title||Q.createdAt)&&(Q.type="thread_info");const C=Q.seq;if(C!==void 0){if(C<=kt){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:C,lastProcessedSeq:kt,type:Q.type});continue}kt>0&&C>kt+1&&((ge=N==null?void 0:N.onGap)==null||ge.call(N,{from:kt,to:C})),kt=C,L.current=C,b(C)}if(Q.type==="checkpoint")V.current=Q.checkpointId??null,$.current=Q.checkpointNs??null,m(Q.checkpointId??null);else if(Q.type==="state_history"){Z.current=Q;try{const z=cr(Q).latest;z&&(V.current=z.checkpointId??null,$.current=z.checkpointNs??null,m(z.checkpointId??null),j(z.values??{}))}catch(O){console.warn("[use-chat] Failed to hydrate state_history payload",O)}}try{A==null||A(Q)}catch(O){console.error("[use-chat] Error in onEvent callback:",O,"for event:",Q.type)}try{Q.type==="tool.start"&&(N!=null&&N.onToolStart)?N.onToolStart(Q):Q.type==="tool.end"&&(N!=null&&N.onToolEnd)?N.onToolEnd(Q):Q.type==="token"&&(N!=null&&N.onToken)?N.onToken(Q.token):Q.type==="thread_info"&&(N!=null&&N.onThreadInfo)&&N.onThreadInfo(Q)}catch(O){console.warn("[use-chat] Typed callback error:",O)}if(Q.type==="messages/partial"){const z=Q.messages;if(Array.isArray(z)&&z.length>0){const se=z.find(ie=>ie.type==="ai");if(se){const ie=se.id,Ce=se.content??"",Te=se.response_metadata??{};if(X.current.messageId!==ie){const nt=Te.model_name??Te.model_provider??"assistant";X.current={messageId:ie,lastSeq:null,lastText:""};const Ye={id:ie,role:"assistant",name:nt,model:nt,createdAt:new Date().toISOString(),content:[{type:"text",text:Ce}]};I(it=>({...it,[ie]:Ye})),S(ie)}else I(nt=>{const Ye=nt[ie];return Ye?{...nt,[ie]:{...Ye,content:[{type:"text",text:Ce}]}}:nt});const _e=X.current.lastText||"";if(Ce.length>_e.length){const nt=Ce.slice(_e.length);X.current.lastText=Ce,e.autoAppendAssistant!==!1&&(ct.push(nt),Ge())}}}}else if(Q.type==="updates"){const O=Q;if(O.tools){const z=O.tools;if(z.status==="start"){const se={type:"tool.start",id:z.id,name:z.name,args:z.args,seq:O.seq,call_id:z.id};try{A==null||A(se)}catch(ie){console.error("[use-chat] Error in onEvent (tool.start polyfill):",ie)}}else if(z.status==="end"){const se={type:"tool.end",id:z.id,name:z.name,output:z.output,artifact:z.artifact,seq:O.seq,call_id:z.id};try{A==null||A(se)}catch(ie){console.error("[use-chat] Error in onEvent (tool.end polyfill):",ie)}}}continue}else if(Q.type==="heartbeat"){console.debug("[use-chat] heartbeat received");try{(be=N==null?void 0:N.onHeartbeat)==null||be.call(N,Q)}catch(O){console.warn("[use-chat] heartbeat callback failed",O)}}else if(Tt!==null&&cancelAnimationFrame(Tt),bt(),Q.type==="checkpoint")m(Q.checkpointId??null);else if(Q.type==="error"){const O=Q;if(u(O.message),M="error",q=O.message,O.error_type==="auth_error"||O.code==="TOKEN_EXPIRED"||((Be=O.message)==null?void 0:Be.includes("token"))||((Le=O.message)==null?void 0:Le.includes("401"))||((je=O.message)==null?void 0:je.includes("unauthorized"))||((Fe=O.message)==null?void 0:Fe.includes("Unauthorized"))){console.error("[use-chat] Auth error detected:",O.message);try{(tt=N==null?void 0:N.onAuthError)==null||tt.call(N,O.message)}catch(se){console.warn("[use-chat] onAuthError handler failed",se)}R.abort()}}}}bt(),M===null&&!R.signal.aborted&&(M="complete")}catch($e){if($e.name==="AbortError")M=M??"aborted";else{const Ee=$e.message||String($e);M="error",q=Ee,u(Ee),(mt=N==null?void 0:N.onError)==null||mt.call(N,Ee)}}finally{try{await st.cancel()}catch{}finally{(ot=st.releaseLock)==null||ot.call(st)}Tt!==null&&typeof window<"u"&&window.cancelAnimationFrame(Tt),clearInterval(ut)}}catch(rt){if(rt.name==="AbortError")M=M??"aborted";else{const qe=rt.message||String(rt);M="error",q=qe,u(qe),(ze=N==null?void 0:N.onError)==null||ze.call(N,qe),J||((Me=N==null?void 0:N.onConnectionError)==null||Me.call(N,qe),J=!0)}}finally{const rt=L.current,qe=V.current,ht=$.current,xt=Z.current,He=M??(R.signal.aborted?"aborted":q?"error":"complete");try{(Ze=N==null?void 0:N.onClosed)==null||Ze.call(N,{reason:He,lastSeq:rt,lastCheckpointId:qe,lastCheckpointNs:ht,lastStateHistory:xt,error:q})}catch(st){console.warn("[use-chat] onClosed callback failed",st)}c(!1),y(!1),_.current=null,L.current=0,b(0),W.current=null}})(),{close:()=>R.abort()}},[t,n,r,e.autoAppendAssistant]);return x.useEffect(()=>()=>{var H;D.current=!1,(H=_.current)==null||H.abort()},[]),{isStreaming:a,error:l,assistantText:f,activeMessageId:k,streamedMessages:T,lastCheckpointId:p,lastSeq:g,connected:v,stream:G,stop:F,clear:U,setToken:oe,values:E,interrupt:()=>Promise.resolve(),resume:()=>Promise.resolve(),goto:()=>Promise.resolve()}}const Zm=["detail","message","error","description","title"];function _o(e){if(!e)return null;if(typeof e=="string"){const t=e.trim();return t.length?t:null}if(Array.isArray(e)){for(const t of e){const n=_o(t);if(n)return n}return null}if(typeof e=="object"){const t=e;for(const n of Zm){const r=_o(t[n]);if(r)return r}if("errors"in t){const n=_o(t.errors);if(n)return n}}return null}function Qm(e){if(!e)return"Request failed";const t=e.response,n=_o(t==null?void 0:t.data);if(n)return n;if(t!=null&&t.statusText)return t.statusText;if(e instanceof Error&&e.message)return e.message;if(typeof e=="string"){const r=e.trim();if(r.length)return r}return t!=null&&t.status?`Request failed with status code ${t.status}`:"Request failed"}function Ql({api:e,initialThreadId:t=null,onError:n,onThreadChange:r,onCurrentThreadDeleted:o}){const[s,i]=x.useState([]),[a,c]=x.useState(t),[l,u]=x.useState(!1),[f,h]=x.useState(null),[p,m]=x.useState([]),[g,b]=x.useState(!1),[,v]=x.useState(null),[y,T]=x.useState(null),[I,k]=x.useState(!1),S=x.useRef(a),E=x.useRef(new Map);x.useEffect(()=>{S.current=a},[a]),x.useEffect(()=>{t!==void 0&&t!==S.current&&c(t)},[t]);const j=x.useCallback(async()=>{u(!0),h(null);try{const U=await e.listThreads();i(U??[])}catch(U){const F=String(U);h(F),n==null||n(F)}finally{u(!1)}},[e,n]),_=x.useCallback(async()=>{b(!0),v(null);try{const U=await e.listSharedThreads();m(U??[])}catch(U){const F=String(U);v(F),n==null||n(F)}finally{b(!1)}},[e,n]);x.useEffect(()=>{j()},[j]),x.useEffect(()=>{_()},[_]),x.useEffect(()=>{r==null||r(a)},[a,r]);const D=x.useCallback(async(U,F)=>{try{const G=F&&typeof F=="object"?{id:F.id,name:F.name??""}:void 0,H=await e.createThread(U,G);return c(H.threadId),await j(),H.threadId}catch(G){const H=String(G);return n==null||n(H),null}},[e,n,j]),L=x.useCallback(async U=>{const F=s;i(H=>H.filter(A=>A.threadId!==U));const G=new AbortController;E.current.set(U,G);try{await e.deleteThread(U),S.current===U&&(c(null),o==null||o())}catch(H){i(F);const A=String(H);n==null||n(A)}finally{E.current.delete(U)}},[e,o,n,s]),W=x.useCallback(async(U,F)=>{try{await e.updateThread(U,F),await j()}catch(G){n==null||n(String(G))}},[e,n,j]),V=x.useCallback(async(U,F)=>{k(!0),T("Sharing thread…");try{await e.shareThread(U,F),await _(),T("Shared successfully")}catch(G){const H=Qm(G);throw n==null||n(H),T(`Failed to share: ${H}`),new Error(H)}finally{k(!1)}},[e,n,_]),$=x.useCallback(async(U,F)=>{try{await e.unshareThread(U,F),await _()}catch(G){const H=String(G);throw n==null||n(H),G}},[e,n,_]),Z=x.useMemo(()=>({createThread:D,deleteThread:L,renameThread:W,refreshThreads:j,refreshSharedThreads:_,shareThread:V,unshareThread:$}),[D,L,W,j,_,V,$]),X=x.useCallback(U=>{if(!(U!=null&&U.threadId))return;const F={threadId:U.threadId,title:U.title||`Thread ${U.threadId.slice(0,8)}`,project:U.project,createdAt:U.createdAt||new Date().toISOString(),updatedAt:U.updatedAt||new Date().toISOString(),messageCount:U.messageCount??1};i(G=>{let H=!1;const A=G.map(N=>N.threadId===F.threadId?(H=!0,console.debug("[useThreadsState] thread_info: updating existing thread",F.threadId),{...N,title:F.title??N.title,project:F.project??N.project,updatedAt:F.updatedAt??N.updatedAt,messageCount:F.messageCount??N.messageCount}):N);return H?A:(console.debug("[useThreadsState] thread_info: adding thread to list",F.threadId),[F,...G])})},[]),oe=x.useCallback(()=>T(null),[]);return{threads:s,currentThreadId:a,currentThreadIdRef:S,setCurrentThreadId:c,isLoadingThreads:l,threadsError:f,sharedThreads:p,isLoadingSharedThreads:g,actions:Z,addThreadFromEvent:X,shareInFlight:I,shareStatus:y,clearShareStatus:oe}}const ec=x.createContext(null);function tc({children:e,initialThreadId:t=null,onError:n,onThreadChange:r}){const{chatApi:o}=Vn(),{threads:s,currentThreadId:i,setCurrentThreadId:a,currentThreadIdRef:c,isLoadingThreads:l,threadsError:u,sharedThreads:f,isLoadingSharedThreads:h,actions:p,addThreadFromEvent:m,shareInFlight:g,shareStatus:b,clearShareStatus:v}=Ql({api:o,initialThreadId:t,onError:n,onThreadChange:r}),y=x.useMemo(()=>({threads:s,currentThreadId:i,setCurrentThreadId:a,currentThreadIdRef:c,isLoading:l,error:u,sharedThreads:f,isLoadingSharedThreads:h,actions:p,shareInFlight:g,shareStatus:b,clearShareStatus:v,addThreadFromEvent:m}),[s,i,a,c,l,u,f,h,p,g,b,v,m]);return d.jsx(ec.Provider,{value:y,children:e})}function ur(){const e=x.useContext(ec);if(!e)throw new Error("useThreads must be used within a ThreadsProvider");return e}function dr(e){const t=e==null?void 0:e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return null;try{return JSON.parse(t)}catch{const n=eg(t);if(n)try{return JSON.parse(n)}catch{return null}return null}}function eg(e){let t=!1,n="";for(const o of e){if(o==="\\"){n+=o,t=!t;continue}if(o==="'"&&!t){n+='"';continue}n+=o,t=!1}return n.replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false").replace(/\bNone\b/g,"null")}function ti(e){return!!(e&&typeof e=="object"&&(e.type==="file"||e.mimeType||e.filename||e.sourceType==="base64"))}function zr(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){if(Array.isArray(e)){const n=e.map(zr).filter(r=>r!==void 0);if(!n.length){console.debug("[message-utils] sanitizeForDisplay - array emptied -> returning undefined",{originalLength:e.length});return}return n}if(ti(e)){try{console.debug("[message-utils] sanitizeForDisplay - dropping file-like object",{sampleFilename:e&&(e.filename||e.name)?e.filename||e.name:void 0,keys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - dropped file-like (unable to inspect)",{err:String(n)})}return}const t={};for(const n of Object.keys(e)){const r=e[n];if(n==="data"&&typeof r=="string"&&r.length>100)t[n]=`[base64 ${r.length} chars omitted]`;else{const o=zr(r);o!==void 0&&(t[n]=o)}}if(Object.keys(t).length)return t;try{console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined",{originalKeys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined (inspect failed)",{err:String(n)})}return}return e}function fr(e){if(typeof e=="string")return e;if(ti(e))return"";try{const t=zr(e);return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}catch{return""}}function nc(e){return typeof e!="string"?!1:/^[\s\n]*[-*]\s|^[\s\n]*#+\s|```|^\s*\[.*\]\(|^>\s/.test(e)}function tg(e){const t=fr(e);return typeof e=="string"&&nc(e)?{content:e,isMarkdown:!0}:{content:t,isMarkdown:!1}}function Br(e){if(e==null)return e;if(typeof e=="string"){const t=e.trim();if(t.startsWith("{")||t.startsWith("[")){const n=dr(t);if(n!==null)return Br(n)}return e}return typeof e=="object"&&!Array.isArray(e)&&e.content!==void 0?Br(e.content):e}function rc(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}function jo(e){return{toolCallId:(e.toolCallId||e.tool_call_id)??void 0,name:e.name??void 0}}function oc(e){if(e==null)return null;const t=String(e).trim();return t.length>0?t:null}function ng(e){const t=r=>{try{const o=zr(r);return typeof o=="string"?o:JSON.stringify(o??"")}catch{return""}},n=e.filter(r=>r.type==="text");return n.length?t(n.map(r=>r.text).join(`
39
- `)):t(e)}function rg(e){var n;if(e.name&&e.name.trim())return e.name;const t=(n=e.additionalKwargs)==null?void 0:n.agent_name;return typeof t=="string"&&t.trim()?t:e.model&&e.model.includes("/")?e.model.split("/").pop()||null:e.model||null}function sc(e){const t=e.updatedAt??e.createdAt??"",n=Array.isArray(e.content)?e.content.map(i=>{switch(i.type){case"text":return`t:${i.text.length}`;case"image":return"img";case"interrupt":return"interrupt";default:return"unknown"}}).join("|"):"",r="checkpointId"in e&&e.checkpointId?`cp:${e.checkpointId}`:"",o="checkpointNs"in e&&e.checkpointNs?`ns:${e.checkpointNs}`:"",s=[r,o].filter(Boolean).join("|");return`${e.id}:${t}:${n}${s?`:${s}`:""}`}function ni(e){var n;const t=(n=e.additionalKwargs)==null?void 0:n.toolProgress;return Array.isArray(t)?t:[]}function ic(e){if(e.role!=="assistant")return!1;const t=Array.isArray(e.content)?e.content:Array.isArray(e.parts)?e.parts:[],n=t.some(s=>s.type==="text"&&s.text&&s.text.trim().length>0),r=t.some(s=>s.type==="image"||s.type==="image_url"||s.type==="file"),o=!!e.artifact;return!n&&!r&&!o}function og(e){return e.role==="tool"?!0:e.role==="assistant"?ic(e):!1}function sg(e,t){const n=[],r=e.findIndex(c=>c.id===t);if(r===-1)return n;const o=new Map;let s=0;for(let c=r;c>=0;c--){const l=e[c];if(c<r&&l.role==="assistant"&&!ic(l))break;if(l.role==="assistant"){const u=Array.isArray(l.content)?l.content:Array.isArray(l.parts)?l.parts:[];if(l.tool_calls)for(const f of l.tool_calls)f.id&&f.name&&!o.has(f.id)&&o.set(f.id,{name:f.name,timestamp:l.createdAt,order:s++});for(const f of u)if(f.type==="tool_call"){const h=f;h.id&&h.name&&!o.has(h.id)&&o.set(h.id,{name:h.name,timestamp:l.createdAt,order:s++})}}}if(o.size===0)return n;const i=new Map;for(let c=r+1;c<e.length;c++){const l=e[c];if(l.role==="tool"){const f=jo(l).toolCallId;if(console.log("[buildToolExecutionTimeline] Tool message at index",c,{toolCallId:f,name:l.name,hasMatch:o.has(f||""),toolCallMapKeys:Array.from(o.keys())}),f&&o.has(f)){const h=Array.isArray(l.content)?l.content:Array.isArray(l.parts)?l.parts:[],p=rc(h.filter(m=>m.type==="text"));i.set(f,{content:p||`Finished ${l.name||"tool"}`,artifact:l.artifact,timestamp:l.createdAt})}}}const a=Array.from(o.entries()).sort((c,l)=>c[1].order-l[1].order);for(const[c,l]of a){const u=i.get(c);u?(n.push({type:"tool.start",toolName:l.name,toolCallId:c,content:`Starting ${l.name}...`,timestamp:l.timestamp}),n.push({type:"tool.end",toolName:l.name,toolCallId:c,content:u.content,timestamp:u.timestamp,output:u.content,artifact:u.artifact})):n.push({type:"tool.start",toolName:l.name,toolCallId:c,content:`Starting ${l.name}...`,timestamp:l.timestamp})}return n}function hr(e){if(e==null)return e;if(typeof e=="string"){const t=e.trim(),n=dr(t);return n!==null?hr(n):t}if(Array.isArray(e))return e.map(t=>hr(t));if(typeof e=="object"){const t=e.value;if(t!==void 0)return hr(t)}return e}function ac(e){const t=hr(e.value);return t===e.value?e:{...e,value:t}}function Po(e){const t=e.artifact;return!t||typeof t!="object"?null:"metadata"in t&&t.metadata?t.metadata:{id:t.id??e.id??`artifact-${Date.now()}`,type:t.type??"unknown",created_at:e.createdAt??new Date().toISOString(),status:t.status??"completed",progress:t.progress??void 0}}function ig(e){if(!e||typeof e!="object")return!1;const t=Po({artifact:e});return!!(t&&t.status==="in_progress"&&(t.progress??0)<100)}function ag(e,t){const n=Po(e);if(!n)return e;const r={...n,...t,updated_at:new Date().toISOString()};return{...e,artifact:{...typeof e.artifact=="object"&&e.artifact?e.artifact:{},metadata:r}}}function lg(e,t){return e.find(n=>{const r=Po(n);return(r==null?void 0:r.id)===t})??null}function Oo(e){return e.filter(t=>{var c;if(t.role!=="assistant")return!0;const n=t.content,r=typeof n=="string"?n.trim().length>0:Array.isArray(n)&&n.some(l=>{var u;return l&&l.type==="text"&&((u=l.text)==null?void 0:u.trim())}),o=Array.isArray(n)&&n.some(l=>l&&l.type==="image"),s=t.artifact!==null&&t.artifact!==void 0,i=((c=t.tool_calls)==null?void 0:c.length)>0,a=Array.isArray(n)&&n.some(l=>l&&["file","tool_call","interrupt"].includes(l.type));return!!(r||o||s||i||a)})}function Hr(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function cg(e){let t=!1;const n=e.map(r=>{var s;const o=(r.content??[]).filter(i=>i.type!=="interrupt");return o.length!==((s=r.parts)==null?void 0:s.length)?(t=!0,{...r,content:o}):r});return t?n:e}function ug(e,t,n){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const s={...e[r],checkpointId:t,checkpointNs:n??void 0};return Hr(e,r,s)}return e}function dg(e){const t=new Map,n=[];return e.slice().sort((r,o)=>{const s=r.createdAt?Date.parse(r.createdAt):0,i=o.createdAt?Date.parse(o.createdAt):0;return s-i}).forEach(r=>{const o=Array.isArray(r.messages)?r.messages:[];for(const s of o)!(s!=null&&s.id)||t.has(s.id)||(t.set(s.id,s),n.push(s))}),n.sort((r,o)=>{const s=r.createdAt?Date.parse(r.createdAt):0,i=o.createdAt?Date.parse(o.createdAt):0;return s-i}),n}const fg={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,messagesStreamMeta:{},pendingInterrupt:null,values:{}};function hg(e,t){var n;switch(t.type){case"reset":return{messages:Oo(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,pendingInterrupt:null,messagesStreamMeta:{},values:{}};case"user_message":{const{message:r,editingMessageId:o}=t.payload;if(o){const s=e.messages.findIndex(i=>i.id===o);if(s>=0){const i=e.messages.slice(0,s);return{...e,messages:[...i,r],assemblingId:null}}}return{...e,messages:[...e.messages,r],assemblingId:null}}case"seed":{const r=Oo(t.payload.messages),o={...e,messages:r,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(o.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(o.lastCheckpointNs=t.payload.checkpointNs??null),o}case"prepend":{const r=Oo(t.payload.messages);if(!r.length)return e;const o=new Set(e.messages.map(a=>a.id)),s=r.filter(a=>!o.has(a.id));if(!s.length)return e;const i=[...s,...e.messages];return{...e,messages:i}}case"event":return lc(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>lc(o,s),e):e}default:return e}}function pg(e=[]){const[t,n]=x.useReducer(hg,{...fg,messages:e}),r=x.useRef([]),o=x.useRef(null),s=x.useRef(null),i=x.useCallback(()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),o.current=null,s.current=null;const u=r.current;u.length&&(r.current=[],n({type:"batch",payload:{events:u}}))},[]),a=x.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o.current===null&&(o.current=window.requestAnimationFrame(()=>i())):s.current===null&&(s.current=setTimeout(i,8))},[i]),c=x.useCallback(u=>{r.current.push(u),a()},[a]);x.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const l=x.useMemo(()=>({reset:u=>n({type:"reset",payload:{messages:u}}),seed:(u,f)=>n({type:"seed",payload:{messages:u,...f??{}}}),prepend:u=>n({type:"prepend",payload:{messages:u}}),pushUser:(u,f)=>n({type:"user_message",payload:{message:u,editingMessageId:f}}),onEvent:c}),[c]);return{state:t,dispatch:n,...l}}function lc(e,t){if(t.type==="tool.start")return gg(e,t);if(t.type==="tool.progress")return xg(e,t);if(t.type==="tool.end")return bg(e,t);if(t.type==="artifact.update")return wg(e,t);if(t.type==="checkpoint"){const n=t.checkpointNs??e.lastCheckpointNs??null,r=ug(e.messages,t.checkpointId,n);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:n,messages:r}}if(t.type==="error"){const n={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,n]}}if(t.type==="state_history"){const n=cr(t),r=n.interrupt,o=n.latest,s=dg(n.checkpoints);let i=s.length?s:o==null?void 0:o.messages;if(i){if(e.assemblingId&&!i.some(a=>a.id===e.assemblingId)){const a=e.messages.find(c=>c.id===e.assemblingId);a&&(i=[...i,a])}i=Oo(i)}else i=r===null?cg(e.messages):e.messages;return{...e,messages:i,pendingInterrupt:r,lastCheckpointId:(o==null?void 0:o.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(o==null?void 0:o.checkpointNs)??e.lastCheckpointNs,values:(o==null?void 0:o.values)??e.values}}return t.type==="thread_info",e}function ri(e){return e.call_id??e.id??null}function cc(e){return e.id??e.call_id??`tool-${Date.now()}-${Math.random().toString(16).slice(2)}`}function uc(e,t,n,r){const o=t??`call-${Date.now()}-${Math.random().toString(16).slice(2)}`;return{id:e,role:"tool",name:n??void 0,toolCallId:o,content:[{type:"tool_call",id:o,name:n??"tool",args:r??{}}],createdAt:new Date().toISOString(),additionalKwargs:{toolName:n??void 0,toolStreaming:!0,toolProgress:[]}}}function oi(e,t){if(!t)return-1;for(let n=0;n<e.length;n+=1){const r=e[n];if(r.role!=="tool")continue;const o=r.toolCallId;if(typeof o=="string"&&o===t)return n;const s=r.additionalKwargs??{};if(typeof s.toolCallId=="string"&&s.toolCallId===t||jo(r).toolCallId===t)return n}return-1}function mg(e){if(e==null)return[];const t=Br(e);if(typeof t=="string"&&t.trim())return[{type:"text",text:t}];const n=fr(t??e);return n?[{type:"text",text:n}]:[]}function si(e,t){const n=e.additionalKwargs??{},r=Array.isArray(n.toolProgress)?[...n.toolProgress]:[],o={...n,toolProgress:[...r,t]};return{...e,additionalKwargs:o}}function gg(e,t){const n=ri(t),r=oi(e.messages,n),o=t.name??t.tool??void 0,s=cc(t),i={type:t.type,content:`Starting ${o??"tool"}...`,seq:t.seq??null,timestamp:new Date().toISOString()};if(r>=0){const l=e.messages[r],f={...l.additionalKwargs??{},toolStreaming:!0,toolProgress:[i]},h={...l,name:o??l.name,additionalKwargs:f};return{...e,messages:Hr(e.messages,r,h)}}const a=uc(s,n,o,t.args),c=si(a,i);return{...e,messages:[...e.messages,c]}}function xg(e,t){var u,f,h,p,m;const n=t.id??t.call_id??((u=t.data)==null?void 0:u.id)??ri(t);if(!n)return e;const r=oi(e.messages,n);if(r===-1)return e;const o=t.status??t.step??t.type??((f=t.data)==null?void 0:f.type)??"progress",s=t.content??((h=t.data)==null?void 0:h.content)??(typeof t.data=="string"?t.data:void 0),i={type:o,content:s,seq:t.seq??null,timestamp:new Date().toISOString()},a=t.metadata??((p=t.data)==null?void 0:p.metadata);a&&(i.metadata=a);const c=t.idx??((m=t.data)==null?void 0:m.idx);typeof c=="number"&&(i.idx=c);const l=si(e.messages[r],i);return{...e,messages:Hr(e.messages,r,l)}}function bg(e,t){const n=ri(t),r=cc(t);let o=e.messages,s=oi(o,n);if(s===-1){const m=t.name??t.tool??void 0;o=[...o,uc(r,n,m,{})],s=o.length-1}const i=o[s],a=t.output??t.error??null,c=mg(a),l=[...i.content,...c],u={type:t.type,content:typeof t.output=="string"?t.output:void 0,seq:t.seq??null,timestamp:new Date().toISOString()};t.artifact&&(u.artifact=t.artifact);const f=si(i,u),h=t.artifact??i.artifact,p={...f,name:t.name??t.tool??i.name,content:l,artifact:h,additionalKwargs:{...f.additionalKwargs??{},toolStreaming:!1}};return{...e,messages:Hr(o,s,p)}}function wg(e,t){const n=lg(e.messages,t.artifact_id);if(!n){const s={id:`artifact-${t.artifact_id}`,role:"tool",name:"artifact_updater",content:[],createdAt:new Date().toISOString(),artifact:{type:"unknown",metadata:{id:t.artifact_id,type:"unknown",created_at:new Date().toISOString(),status:t.status,progress:t.progress},...t.partial_data}};return{...e,messages:[...e.messages,s]}}const r=e.messages.indexOf(n),o=ag(n,{status:t.status,progress:t.progress,error:t.error});return t.partial_data&&o.artifact&&(o.artifact={...o.artifact,...t.partial_data}),{...e,messages:Hr(e.messages,r,o)}}const dc=120;function vg(e){if(!Array.isArray(e))return"";const t=e.filter(r=>!!(r&&r.type==="text")).map(r=>(r.text??"").trim()).filter(Boolean);if(!t.length)return"";const n=t.join(" ").replace(/\s+/g," ").trim();return n?n.length>dc?`${n.slice(0,dc-3)}…`:n:""}function yg(e){return vg(e.content)||""}function Sg(e){const t=new Map,n=[],r=new Map,o=[];for(let l=0;l<e.length;l++){const u=e[l],f=u.checkpointId,h=f??`cp-${l}`,p=u.metadata??{},m=typeof p.step=="number"?p.step:null,g=typeof p.source=="string"?p.source:null;let b=null,v=null;const y=Array.isArray(u.messages)?u.messages:[];for(const S of y)S.role==="user"&&(v||(v=S),S.id&&(b=S.id));const T=u.next&&u.next.length>0?String(u.next[0]):null,I=u.parentConfig??null,k={id:h,step:m,source:g,createdAt:u.createdAt??null,namespace:u.checkpointNs??null,parentId:u.parentId??null,next:T,parentConfig:I,userMessageId:b};if(o.push(k),f&&t.set(f,k),f&&v){const S=yg(v);S&&r.set(f,S)}n.push({id:h,messageId:b,step:m,source:g,createdAt:u.createdAt??null,next:T,parentConfig:I})}const s=new Map;for(const l of o){if(!l.userMessageId)continue;const u=s.get(l.userMessageId)??[];u.push(l),s.set(l.userMessageId,u)}for(const l of s.values()){if(!l.length)continue;l.sort((f,h)=>{const p=f.createdAt?Date.parse(f.createdAt):0;return(h.createdAt?Date.parse(h.createdAt):0)-p});const u=l.length;for(let f=0;f<l.length;f++){const h=l[f];h.attemptCount=u,h.attemptIndex=f,h.isLatestAttempt=f===0}}return{checkpoints:e,checkpointMetaByCheckpointId:t,timeline:n,messagePreviews:r,getLatest:()=>{const l=n[0];if(l)return t.get(l.id)},getCheckpoint:l=>t.get(l),getMessageAttempts:l=>{const u=[];for(const f of t.values())f.userMessageId===l&&u.push(f);return u.length?(u.sort((f,h)=>{const p=typeof f.attemptIndex=="number"?f.attemptIndex:Number.MAX_SAFE_INTEGER,m=typeof h.attemptIndex=="number"?h.attemptIndex:Number.MAX_SAFE_INTEGER;return p-m}),u):[]}}}function Cg(e,t,n){if(!e)return{attemptCount:1,attemptIndex:0,attempts:[]};const r=n.getMessageAttempts(e);if(!r.length)return{attemptCount:1,attemptIndex:0,attempts:[]};let o=0;if(t){const s=r.findIndex(i=>i.id===t);s>=0&&(o=s)}return{attemptCount:r.length,attemptIndex:o,attempts:r}}function kg(e){return x.useMemo(()=>Sg(e),[e])}function fc({api:e,seed:t,onError:n,currentThreadId:r,initialThreadId:o=null,initialCheckpointId:s=null,initialCheckpointNs:i=null,autoLoadInitial:a=!0,isStreaming:c,getMessages:l}){const[u,f]=x.useState(null),p=x.useMemo(()=>cr(u),[u]).checkpoints,m=kg(p),g=m.timeline,[b,v]=x.useState(!1),[y,T]=x.useState(!1),[I,k]=x.useState(null),S=x.useRef(r),E=x.useRef(null),j=x.useRef(null),_=x.useRef(null),D=x.useRef(null),L=x.useRef(null),W=x.useRef(new Map),V=x.useRef(null);x.useEffect(()=>{S.current=r},[r]);const $=x.useCallback(async R=>{var q,J;if(!R.threadId)return;const M=R.threadId;(q=R.onStart)==null||q.call(R),R.setLoading(!0);try{await R.action(M)}catch(P){if(!Ll(P)&&S.current===M){const te=String(P);(J=R.handleError)==null||J.call(R,te),n==null||n(te)}throw P}finally{R.setLoading(!1)}},[n]),Z=x.useCallback(async(R,M)=>{var te;if(!R)return;const q=`${R}:${M??"latest"}`,J=W.current.get(q);if(J)return J;(te=V.current)==null||te.abort();const P=new AbortController;V.current=P;const K=$({threadId:R,setLoading:v,onStart:()=>k(null),handleError:le=>k(le),action:async le=>{const he=await e.getStateHistory({threadId:le,checkpointId:M??void 0,signal:P.signal});if(S.current!==le){console.log(`[useThreadHistoryState] Thread changed during load (was ${le}, now ${S.current}), discarding stale data`);return}const{checkpoints:ue,latest:ge}=cr(he),be=M?ue.find(Be=>Be.checkpointId===M)??ge:ge;t((be==null?void 0:be.messages)??[],{checkpointId:(be==null?void 0:be.checkpointId)??null,checkpointNs:(be==null?void 0:be.checkpointNs)??null,pendingInterrupt:(be==null?void 0:be.interrupt)??null}),f(he)}});W.current.set(q,K);try{await K}finally{W.current.delete(q),V.current===P&&(V.current=null)}return S.current===R&&(L.current=q),K},[e,t,$]),X=x.useCallback(async(R,M)=>{D.current=R;try{await Z(R,M)}catch(q){if(!Ll(q))throw q}finally{D.current===R&&(D.current=null)}},[Z]),oe=x.useCallback(R=>{j.current=R},[]),U=x.useCallback(R=>{_.current=R},[]),F=x.useCallback(R=>{const M=R.threadId??S.current;if(!M||S.current&&S.current!==M)return;const{checkpoints:q,latest:J}=cr(R);if(!q.length)return;const P=J,K=_.current===M;!c&&!K&&t((P==null?void 0:P.messages)??[],{checkpointId:(P==null?void 0:P.checkpointId)??null,checkpointNs:(P==null?void 0:P.checkpointNs)??null,pendingInterrupt:(P==null?void 0:P.interrupt)??null}),f(R),L.current=`${M}:latest`,j.current=null,_.current===M&&(_.current=null)},[t,c]),G=x.useCallback(async(R,M)=>{const q=S.current;await $({threadId:q,setLoading:T,action:async J=>{const P=await e.getStateHistory({threadId:J,checkpointId:R,checkpointNs:M??void 0});if(S.current!==J)return;const{checkpoints:K}=cr(P),te=K.find(le=>le.checkpointId===R&&(M?le.checkpointNs===M:!0));if(!te){console.warn("[useThreadHistoryState] Requested checkpoint not found:",{checkpointId:R,checkpointNs:M});return}f(P),t(te.messages??[],{checkpointId:te.checkpointId??null,checkpointNs:te.checkpointNs??null})}}).catch(()=>{})},[e,t,$]),H=x.useCallback((R,M)=>{t(l(),{checkpointId:R??null,checkpointNs:M??null})},[l,t]),A=x.useCallback(async()=>{S.current&&await X(S.current)},[X]);x.useEffect(()=>{if(!a||!r||b||c)return;if(j.current===r){j.current=null,E.current=r;return}if(_.current===r){E.current=r;return}if(D.current===r){D.current=null,E.current=r;return}if(E.current===r)return;E.current=r;let R;const M=`${r}:latest`;L.current!==M&&X(r,R)},[a,r,s,i,o,b,c,X]);const N=x.useCallback(()=>{f(null),v(!1),T(!1),k(null),j.current=null,_.current=null,E.current=null,L.current=null,D.current=null},[]);return{threadCheckpoints:p,threadTimeline:g,checkpointIndex:m,isLoadingThread:b,isLoadingCheckpoint:y,threadStateError:I,loadThread:X,navigateToCheckpoint:G,setCurrentCheckpointId:H,returnToLatest:A,handleStateHistoryEvent:F,markSkipNextLoad:oe,markStreamPendingThread:U,resetHistoryState:N,clearState:N}}const hc=x.createContext(null),pc=x.createContext(null);function Ur(){const e=x.useContext(hc);if(!e)throw new Error("useThreadState must be used within a ThreadStateProvider");return e}function mc(){const e=x.useContext(pc);if(!e)throw new Error("useThreadStateUpdater must be used within a ThreadStateProvider");return e}function gc({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:o=!0,isStreaming:s,onError:i}){const{chatApi:a}=Vn(),{currentThreadId:c}=ur(),{state:l,seed:u,onEvent:f,dispatch:h}=pg(),{threadCheckpoints:p,threadTimeline:m,checkpointIndex:g,isLoadingThread:b,isLoadingCheckpoint:v,threadStateError:y,loadThread:T,navigateToCheckpoint:I,setCurrentCheckpointId:k,returnToLatest:S,handleStateHistoryEvent:E,markSkipNextLoad:j,markStreamPendingThread:_,resetHistoryState:D}=fc({api:a,seed:u,onError:i,currentThreadId:c,initialThreadId:t,initialCheckpointId:n,initialCheckpointNs:r,autoLoadInitial:o,isStreaming:s,getMessages:x.useCallback(()=>l.messages,[l.messages])});x.useEffect(()=>{c||(u([],{}),D())},[c,u,D]);const L=x.useRef(null),W=x.useCallback(G=>{L.current=G},[]),V=x.useRef(null),$=x.useCallback(G=>{V.current=G},[]),Z=x.useMemo(()=>({assemblingMessageId:l.assemblingId??null}),[l.assemblingId]),X=x.useCallback((G,H)=>{const A=Yl(G,"user");return h({type:"user_message",payload:{message:A,editingMessageId:H==null?void 0:H.editingMessageId}}),A},[h]),oe=x.useCallback(async()=>{L.current?await L.current():(u([],{}),D())},[u,D]),U=x.useMemo(()=>({threadId:c,messages:l.messages,interrupt:l.pendingInterrupt,checkpoint:{id:l.lastCheckpointId??null,namespace:l.lastCheckpointNs??null},checkpoints:p,checkpointIndex:g,timelineCheckpoints:m,metadata:Z,values:l.values??{},isLoading:b,isLoadingCheckpoint:v,error:y,loadOlder:async()=>{},seedFromSnapshot:G=>{u(G.messages,{checkpointId:G.checkpointId,checkpointNs:G.checkpointNs,pendingInterrupt:G.interrupt})},clearState:oe,navigateToCheckpoint:I,setCurrentCheckpointId:k,returnToLatest:S,loadThread:async(G,H,A)=>{await T(G,H,{clearProgress:!1})},clearThread:oe,respondToInterrupt:async(G,H,A)=>{V.current&&await V.current(G,H,A)},messagePreviews:g.messagePreviews,handleStateHistoryEvent:E,markSkipNextLoad:j,markStreamPendingThread:_,resetHistoryState:D,pushUser:X,onEvent:f}),[c,l.messages,l.pendingInterrupt,l.lastCheckpointId,l.lastCheckpointNs,l.values,p,m,g,Z,b,v,y,u,oe,I,k,S,T,E,j,_,X,f]),F=x.useMemo(()=>({registerClearThread:W,registerRespondToInterrupt:$}),[W,$]);return d.jsx(pc.Provider,{value:F,children:d.jsx(hc.Provider,{value:U,children:e})})}function xc(e,t){if(!e)return null;const n=Kn(e);if(!n)return null;const r=Kn(n.configurable)??n;return Fr(r,t)??null}function Tg(e){const t=xc(e,["checkpoint_id","checkpointId"]);if(!t)return null;const n=xc(e,["checkpoint_ns","checkpointNs"]);return{checkpointId:t,checkpointNs:n}}function Eg(e,t){const n=typeof e.step=="number"?e.step:Number.POSITIVE_INFINITY,r=typeof t.step=="number"?t.step:Number.POSITIVE_INFINITY;if(n!==r)return n-r;const o=e.createdAt?Date.parse(e.createdAt):0,s=t.createdAt?Date.parse(t.createdAt):0;return o-s}function Ig(e,t){const n=[...e].sort(Eg);for(const r of n){if(r.messageId!==t)continue;const o=Tg(r.parentConfig);if(!o)throw new Error(`Parent checkpoint info missing for message ${t}`);return o}throw new Error(`Message ${t} not found in timeline`)}const bc=x.createContext(null),wc=x.createContext(!1);function Ag({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:o=!0,onError:s,onAuthError:i,onThreadChange:a,onConnectionError:c,onToolEnd:l}){const{chatApi:u,baseUrl:f}=Vn(),h=f,{stream:p,stop:m,clear:g,isStreaming:b,error:v,connected:y}=Jm({baseUrl:h}),[T,I]=x.useState(!1);return x.useEffect(()=>{I(b)},[b]),d.jsx(tc,{initialThreadId:t,onError:s,onThreadChange:a,children:d.jsx(gc,{initialThreadId:t,initialCheckpointId:n,initialCheckpointNs:r,autoLoadInitial:o,onError:s,isStreaming:T,children:d.jsx(wc.Provider,{value:!0,children:d.jsx(Ng,{api:u,streamApi:{stream:p,stop:m,clear:g,isStreaming:b,error:v,connected:y},onError:s,onAuthError:i,onConnectionError:c,onToolEnd:l,children:e})})})})}function Ng({children:e,api:t,streamApi:n,onError:r,onAuthError:o,onConnectionError:s,onToolEnd:i}){const{stream:a,stop:c,clear:l,isStreaming:u,error:f,connected:h}=n,{setCurrentThreadId:p,currentThreadIdRef:m,addThreadFromEvent:g,currentThreadId:b}=ur();x.useEffect(()=>{b!==void 0&&l()},[b,l]);const{interrupt:v,checkpoint:y,timelineCheckpoints:T,handleStateHistoryEvent:I,markSkipNextLoad:k,markStreamPendingThread:S,resetHistoryState:E,pushUser:j,onEvent:_,messages:D}=Ur(),{registerClearThread:L,registerRespondToInterrupt:W}=mc(),V=x.useCallback(H=>{g(H),m.current!==H.threadId&&((H.created??!m.current)&&k(H.threadId),S(H.threadId),p(H.threadId))},[g,k,S,p,m]),$=x.useCallback(H=>{H.type==="thread_info"?V(H):H.type==="state_history"?I(H):H.type==="tool.end"?(_(H),i==null||i(H)):_(H)},[V,I,_,i]),Z=x.useCallback((H,A)=>{a(H,N=>{$(N),A==null||A(N)},{onError:N=>{console.error("[StreamingProvider] Stream error:",N),r==null||r(N)},onAuthError:N=>{console.error("[StreamingProvider] Auth error:",N),o==null||o(N)},onConnectionError:N=>{console.error("[StreamingProvider] Connection error:",N),s==null||s(N)}})},[a,$,r,o,s]),X=x.useRef(y);x.useEffect(()=>{X.current=y},[y]);const oe=x.useCallback(async(H,A,N)=>{const R=m.current;if(!R)throw new Error("No active thread to handle interrupt");const M=H?A??!0:!1,q=X.current,J={threadId:R,checkpointId:q.id??void 0,checkpointNs:q.namespace??void 0,command:{kind:"resume",value:M},payload:N==null?void 0:N.payload};Z(J)},[m,Z]);x.useEffect(()=>{W(oe)},[oe,W]);const U=x.useCallback(async()=>{c(),l(),E(),p(null)},[l,E,p,c]);x.useEffect(()=>{L(U)},[U,L]);const F=x.useCallback(async(H,A)=>{u&&c();let N=m.current;const R=(H==null?void 0:H.text)??"",M=(H==null?void 0:H.attachments)??[],q=(R==null?void 0:R.trim())??"",J={...(H==null?void 0:H.payload)??{}},P=Array.isArray(J.messages)?J.messages:void 0;P&&delete J.messages;const K=!!(P&&P.length),te=!!(H.contentParts&&H.contentParts.length>0);if(!N&&!q&&M.length===0&&!K&&!te)return;if(!N){const Me=Math.floor(Date.now()/1e3).toString(16).padStart(8,"0"),Ze=Array.from({length:4},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("").slice(0,16);N=`${Me}${Ze}`,k(N),p(N)}let le=null;H.contentParts&&H.contentParts.length>0&&(le=H.contentParts);const{contentParts:he,filesInfo:ue}=le?{contentParts:le,filesInfo:[]}:await Gl(M),ge=[...he];q&&ge.push({type:"text",text:R});const be=A==null?void 0:A.originalMessageId,Be=!!(A!=null&&A.edit&&be),Le=!K&&ge.length>0;let je=null;if(Le){const Me=Be?be:`msg-${Date.now()}`;je=Yl({id:Me,role:"user",content:ge,createdAt:new Date().toISOString()},"user"),Be?j(je,{editingMessageId:be}):j(je)}const Fe=K?P:je?[je]:[],tt={...J,...ue.length?{files_info:ue}:{}};Fe.length?tt.messages=Fe:"messages"in tt||(tt.messages=[]);let mt=(A==null?void 0:A.checkpointId)??y.id??void 0,ot=(A==null?void 0:A.checkpointNs)??y.namespace??void 0;if(Be&&be){const Me=Ig(T,be);mt=Me.checkpointId,ot=Me.checkpointNs??void 0}const ze={threadId:N,payload:tt,checkpointId:mt,checkpointNs:ot,config:A==null?void 0:A.config,edit:!!(A!=null&&A.edit)};Z(ze,A==null?void 0:A.onEvent)},[y,m,u,k,j,Z,c,T]),G=x.useMemo(()=>({isStreaming:u,error:f,connectionState:f?"error":u?h?"connected":"connecting":"idle",messages:D,submit:F,stop:c,interrupt:v,resume:()=>Promise.resolve(),goto:(H,A)=>Promise.resolve(),clearError:()=>{}}),[u,f,F,c,v,h,D]);return d.jsx(bc.Provider,{value:G,children:e})}function ii(){const e=x.useContext(bc);if(!e)throw new Error("useStream must be used within StreamingProvider");return e}function _g(){return x.useContext(wc)}function vc(e){return typeof e=="object"&&e!==null}function jg(e,t){if(Object.is(e,t))return!0;if(!vc(e)||!vc(t))return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n)if(!Object.prototype.hasOwnProperty.call(t,o)||!Object.is(e[o],t[o]))return!1;return!0}function yc(e){const t=x.useRef(e),n=x.useRef(e);return jg(t.current,e)||(t.current=e,n.current=e),n.current}function Wr({children:e,apiConfig:t,initialThreadId:n=null,initialCheckpointId:r=null,initialCheckpointNs:o=null,autoLoadInitial:s=!0,onConnectionError:i,onError:a,onAuthError:c,onThreadChange:l,onToolEnd:u}){const f=yc(t),h=Vr(a),p=Vr(c),m=Vr(i),g=Vr(l),b=Vr(u),v=x.useMemo(()=>({initialThreadId:n,initialCheckpointId:r,initialCheckpointNs:o,autoLoadInitial:s,onError:h,onAuthError:p,onConnectionError:m,onThreadChange:g,onToolEnd:b}),[n,r,o,s,h,p,m,g,b]);return d.jsx(Kl,{apiConfig:f,children:d.jsx(Ag,{...v,children:e})})}function Vr(e){const t=x.useRef(e);return x.useEffect(()=>{t.current=e},[e]),x.useCallback((...n)=>{const r=t.current;if(r)return r(...n)},[])}function pr(e){if(!(typeof globalThis>"u"))return globalThis[e]}function Sc(){const e=[pr("__API_BASE_URL__"),pr("__CHAT_API_BASE_URL__"),pr("__CHAT_API_URL__")];for(const t of e)if(typeof t=="string"&&t.trim())return t.trim().replace(/\/+$/,"")}function Cc(){const e=[pr("__API_AUTH_TOKEN__"),pr("__CHAT_API_KEY__"),pr("__CHAT_AUTH_TOKEN__")];for(const t of e)if(typeof t=="string"&&t.trim())return t.trim()}function kc(...e){for(const t of e)if(typeof t=="string"&&t.trim())return t.trim().replace(/\/+$/,"");return""}function Tc(){const e={},t=Sc(),n=Cc();return t&&(e.baseUrl=t),n&&(e.apiKey=n),e}function Ec(){const e=Tc(),t=An.getAuthToken(),n=Sc();return{apiBaseUrl:kc(e.baseUrl,n),apiKey:t||e.apiKey||Cc()||"",model:"gpt-4",temperature:.7,maxTokens:4096,layoutSize:"desktop",showThreads:!0,autoScrollMessages:!0,darkMode:!1,enableSound:!1,messageHistory:100}}const ai=En.chatSettings;function Ic(){try{const e=localStorage.getItem(ai);return e?JSON.parse(e):{}}catch(e){return console.error("Failed to parse stored settings:",e),{}}}function Ac(e){try{const t={...e,apiBaseUrl:e.apiBaseUrl.trim().replace(/\/+$/,"")};localStorage.setItem(ai,JSON.stringify(t)),t.apiKey&&An.setAuthToken(t.apiKey)}catch(t){console.error("Failed to save settings:",t)}}function Pg(){const e=Ec(),t=Ic(),n=An.getAuthToken(),r=typeof t.apiBaseUrl=="string"?t.apiBaseUrl:void 0;return{...e,...t,apiKey:n||t.apiKey||e.apiKey,apiBaseUrl:kc(An.baseUrl,r,e.apiBaseUrl)}}function Og(e){An.updateConfig({baseUrl:e.apiBaseUrl,apiKey:e.apiKey??void 0}),Ac(e)}function ae(...e){return Bn.twMerge(Pt.clsx(e))}const Rg=Ya.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),Ke=w.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?sr.Slot:"button";return d.jsx(i,{className:ae(Rg({variant:t,size:n,className:e})),ref:s,...o})});Ke.displayName="Button";const Ro=0,Nn=1,mr=2,Nc=4;function _c(e){return()=>e}function Mg(e){e()}function jc(e,t){return n=>e(t(n))}function Pc(e,t){return()=>e(t)}function Dg(e,t){return n=>e(t,n)}function li(e){return e!==void 0}function Lg(...e){return()=>{e.map(Mg)}}function gr(){}function Mo(e,t){return t(e),e}function $g(e,t){return t(e)}function Xe(...e){return e}function De(e,t){return e(Nn,t)}function Ae(e,t){e(Ro,t)}function ci(e){e(mr)}function lt(e){return e(Nc)}function me(e,t){return De(e,Dg(t,Ro))}function tn(e,t){const n=e(Nn,r=>{n(),t(r)});return n}function Oc(e){let t,n;return r=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{r(t)},e)}}function Rc(e,t){return e===t}function Je(e=Rc){let t;return n=>r=>{e(t,r)||(t=r,n(r))}}function ye(e){return t=>n=>{e(n)&&t(n)}}function ce(e){return t=>jc(t,e)}function un(e){return t=>()=>{t(e)}}function ee(e,...t){const n=Fg(...t);return(r,o)=>{switch(r){case mr:ci(e);return;case Nn:return De(e,n(o))}}}function dn(e,t){return n=>r=>{n(t=e(t,r))}}function qn(e){return t=>n=>{e>0?e--:t(n)}}function yn(e){let t=null,n;return r=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,r(t)},e))}}function Ne(...e){const t=new Array(e.length);let n=0,r=null;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);De(s,c=>{const l=n;n=n|a,t[i]=c,l!==o&&n===o&&r&&(r(),r=null)})}),s=>i=>{const a=()=>{s([i].concat(t))};n===o?a():r=a}}function Fg(...e){return t=>e.reduceRight($g,t)}function zg(e){let t,n;const r=()=>t==null?void 0:t();return function(o,s){switch(o){case Nn:return s?n===s?void 0:(r(),n=s,t=De(e,s),t):(r(),gr);case mr:r(),n=null;return}}}function re(e){let t=e;const n=Oe();return(r,o)=>{switch(r){case Ro:t=o;break;case Nn:{o(t);break}case Nc:return t}return n(r,o)}}function vt(e,t){return Mo(re(t),n=>me(e,n))}function Oe(){const e=[];return(t,n)=>{switch(t){case Ro:e.slice().forEach(r=>{r(n)});return;case mr:e.splice(0,e.length);return;case Nn:return e.push(n),()=>{const r=e.indexOf(n);r>-1&&e.splice(r,1)}}}}function Ht(e){return Mo(Oe(),t=>me(e,t))}function Re(e,t=[],{singleton:n}={singleton:!0}){return{constructor:e,dependencies:t,id:Bg(),singleton:n}}const Bg=()=>Symbol();function Hg(e){const t=new Map,n=({constructor:r,dependencies:o,id:s,singleton:i})=>{if(i&&t.has(s))return t.get(s);const a=r(o.map(c=>n(c)));return i&&t.set(s,a),a};return n(e)}function ft(...e){const t=Oe(),n=new Array(e.length);let r=0;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);De(s,c=>{n[i]=c,r=r|a,r===o&&Ae(t,n)})}),function(s,i){switch(s){case mr:{ci(t);return}case Nn:return r===o&&i(n),De(t,i)}}}function ve(e,t=Rc){return ee(e,Je(t))}function ui(...e){return function(t,n){switch(t){case mr:return;case Nn:return Lg(...e.map(r=>De(r,n)))}}}var Dt=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(Dt||{});const Ug={0:"debug",3:"error",1:"log",2:"warn"},Wg=()=>typeof globalThis>"u"?window:globalThis,_n=Re(()=>{const e=re(3);return{log:re((t,n,r=1)=>{var o;const s=(o=Wg().VIRTUOSO_LOG_LEVEL)!=null?o:lt(e);r>=s&&console[Ug[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function Gn(e,t,n){return di(e,t,n).callbackRef}function di(e,t,n){const r=x.useRef(null);let o=i=>{};const s=x.useMemo(()=>typeof ResizeObserver<"u"?new ResizeObserver(i=>{const a=()=>{const c=i[0].target;c.offsetParent!==null&&e(c)};n?a():requestAnimationFrame(a)}):null,[e,n]);return o=i=>{i&&t?(s==null||s.observe(i),r.current=i):(r.current&&(s==null||s.unobserve(r.current)),r.current=null)},{callbackRef:o,ref:r}}function Vg(e,t,n,r,o,s,i,a,c){const l=x.useCallback(u=>{const f=Kg(u.children,t,a?"offsetWidth":"offsetHeight",o);let h=u.parentElement;for(;!h.dataset.virtuosoScroller;)h=h.parentElement;const p=h.lastElementChild.dataset.viewportType==="window";let m;p&&(m=h.ownerDocument.defaultView);const g=i?a?i.scrollLeft:i.scrollTop:p?a?m.scrollX||m.document.documentElement.scrollLeft:m.scrollY||m.document.documentElement.scrollTop:a?h.scrollLeft:h.scrollTop,b=i?a?i.scrollWidth:i.scrollHeight:p?a?m.document.documentElement.scrollWidth:m.document.documentElement.scrollHeight:a?h.scrollWidth:h.scrollHeight,v=i?a?i.offsetWidth:i.offsetHeight:p?a?m.innerWidth:m.innerHeight:a?h.offsetWidth:h.offsetHeight;r({scrollHeight:b,scrollTop:Math.max(g,0),viewportHeight:v}),s==null||s(a?Mc("column-gap",getComputedStyle(u).columnGap,o):Mc("row-gap",getComputedStyle(u).rowGap,o)),f!==null&&e(f)},[e,t,o,s,i,r,a]);return di(l,n,c)}function Kg(e,t,n,r){const o=e.length;if(o===0)return null;const s=[];for(let i=0;i<o;i++){const a=e.item(i);if(a.dataset.index===void 0)continue;const c=parseInt(a.dataset.index),l=parseFloat(a.dataset.knownSize),u=t(a,n);if(u===0&&r("Zero-sized element, this should not happen",{child:a},Dt.ERROR),u===l)continue;const f=s[s.length-1];s.length===0||f.size!==u||f.endIndex!==c-1?s.push({endIndex:c,size:u,startIndex:c}):s[s.length-1].endIndex++}return s}function Mc(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,Dt.WARN),t==="normal"?0:parseInt(t??"0",10)}function Dc(e,t,n){const r=x.useRef(null),o=x.useCallback(c=>{if(!(c!=null&&c.offsetParent))return;const l=c.getBoundingClientRect(),u=l.width;let f,h;if(t){const p=t.getBoundingClientRect(),m=l.top-p.top;h=p.height-Math.max(0,m),f=m+t.scrollTop}else{const p=i.current.ownerDocument.defaultView;h=p.innerHeight-Math.max(0,l.top),f=l.top+p.scrollY}r.current={offsetTop:f,visibleHeight:h,visibleWidth:u},e(r.current)},[e,t]),{callbackRef:s,ref:i}=di(o,!0,n),a=x.useCallback(()=>{o(i.current)},[o,i]);return x.useEffect(()=>{var c;if(t){t.addEventListener("scroll",a);const l=new ResizeObserver(()=>{requestAnimationFrame(a)});return l.observe(t),()=>{t.removeEventListener("scroll",a),l.unobserve(t)}}else{const l=(c=i.current)==null?void 0:c.ownerDocument.defaultView;return l==null||l.addEventListener("scroll",a),l==null||l.addEventListener("resize",a),()=>{l==null||l.removeEventListener("scroll",a),l==null||l.removeEventListener("resize",a)}}},[a,t,i]),s}const Nt=Re(()=>{const e=Oe(),t=Oe(),n=re(0),r=Oe(),o=re(0),s=Oe(),i=Oe(),a=re(0),c=re(0),l=re(0),u=re(0),f=Oe(),h=Oe(),p=re(!1),m=re(!1),g=re(!1);return me(ee(e,ce(({scrollTop:b})=>b)),t),me(ee(e,ce(({scrollHeight:b})=>b)),i),me(t,o),{deviation:n,fixedFooterHeight:l,fixedHeaderHeight:c,footerHeight:u,headerHeight:a,horizontalDirection:m,scrollBy:h,scrollContainerState:e,scrollHeight:i,scrollingInProgress:p,scrollTo:f,scrollTop:t,skipAnimationFrameInResizeObserver:g,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:s}},[],{singleton:!0}),Kr={lvl:0};function Lc(e,t){const n=e.length;if(n===0)return[];let{index:r,value:o}=t(e[0]);const s=[];for(let i=1;i<n;i++){const{index:a,value:c}=t(e[i]);s.push({end:a-1,start:r,value:o}),r=a,o=c}return s.push({end:1/0,start:r,value:o}),s}function Ue(e){return e===Kr}function qr(e,t){if(!Ue(e))return t===e.k?e.v:t<e.k?qr(e.l,t):qr(e.r,t)}function nn(e,t,n="k"){if(Ue(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const r=nn(e.r,t,n);return r[0]===-1/0?[e.k,e.v]:r}return nn(e.l,t,n)}function Ut(e,t,n){return Ue(e)?zc(t,n,1):t===e.k?pt(e,{k:t,v:n}):t<e.k?Bc(pt(e,{l:Ut(e.l,t,n)})):Bc(pt(e,{r:Ut(e.r,t,n)}))}function xr(){return Kr}function Do(e,t,n){if(Ue(e))return[];const r=nn(e,t)[0];return qg(hi(e,r,n))}function fi(e,t){if(Ue(e))return Kr;const{k:n,l:r,r:o}=e;if(t===n){if(Ue(r))return o;if(Ue(o))return r;{const[s,i]=Fc(r);return Lo(pt(e,{k:s,l:$c(r),v:i}))}}else return t<n?Lo(pt(e,{l:fi(r,t)})):Lo(pt(e,{r:fi(o,t)}))}function Yn(e){return Ue(e)?[]:[...Yn(e.l),{k:e.k,v:e.v},...Yn(e.r)]}function hi(e,t,n){if(Ue(e))return[];const{k:r,l:o,r:s,v:i}=e;let a=[];return r>t&&(a=a.concat(hi(o,t,n))),r>=t&&r<=n&&a.push({k:r,v:i}),r<=n&&(a=a.concat(hi(s,t,n))),a}function Lo(e){const{l:t,lvl:n,r}=e;if(r.lvl>=n-1&&t.lvl>=n-1)return e;if(n>r.lvl+1){if(pi(t))return Hc(pt(e,{lvl:n-1}));if(!Ue(t)&&!Ue(t.r))return pt(t.r,{l:pt(t,{r:t.r.l}),lvl:n,r:pt(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}else{if(pi(e))return mi(pt(e,{lvl:n-1}));if(!Ue(r)&&!Ue(r.l)){const o=r.l,s=pi(o)?r.lvl-1:r.lvl;return pt(o,{l:pt(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:mi(pt(r,{l:o.r,lvl:s}))})}else throw new Error("Unexpected empty nodes")}}function pt(e,t){return zc(t.k!==void 0?t.k:e.k,t.v!==void 0?t.v:e.v,t.lvl!==void 0?t.lvl:e.lvl,t.l!==void 0?t.l:e.l,t.r!==void 0?t.r:e.r)}function $c(e){return Ue(e.r)?e.l:Lo(pt(e,{r:$c(e.r)}))}function pi(e){return Ue(e)||e.lvl>e.r.lvl}function Fc(e){return Ue(e.r)?[e.k,e.v]:Fc(e.r)}function zc(e,t,n,r=Kr,o=Kr){return{k:e,l:r,lvl:n,r:o,v:t}}function Bc(e){return mi(Hc(e))}function Hc(e){const{l:t}=e;return!Ue(t)&&t.lvl===e.lvl?pt(t,{r:pt(e,{l:t.r})}):e}function mi(e){const{lvl:t,r:n}=e;return!Ue(n)&&!Ue(n.r)&&n.lvl===t&&n.r.lvl===t?pt(n,{l:pt(e,{r:n.l}),lvl:t+1}):e}function qg(e){return Lc(e,({k:t,v:n})=>({index:t,value:n}))}function Uc(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}function Gr(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}const gi=Re(()=>({recalcInProgress:re(!1)}),[],{singleton:!0});function Wc(e,t,n){return e[$o(e,t,n)]}function $o(e,t,n,r=0){let o=e.length-1;for(;r<=o;){const s=Math.floor((r+o)/2),i=e[s],a=n(i,t);if(a===0)return s;if(a===-1){if(o-r<2)return s-1;o=s-1}else{if(o===r)return s;r=s+1}}throw new Error(`Failed binary finding record in array - ${e.join(",")}, searched for ${t}`)}function Gg(e,t,n,r){const o=$o(e,t,r),s=$o(e,n,r,o);return e.slice(o,s+1)}function jn(e,t){return Math.round(e.getBoundingClientRect()[t])}function Fo(e){return!Ue(e.groupOffsetTree)}function xi({index:e},t){return t===e?0:t<e?-1:1}function Yg(){return{groupIndices:[],groupOffsetTree:xr(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:xr()}}function Xg(e,t){let n=Ue(e)?0:1/0;for(const r of t){const{endIndex:o,size:s,startIndex:i}=r;if(n=Math.min(n,i),Ue(e)){e=Ut(e,0,s);continue}const a=Do(e,i-1,o+1);if(a.some(rx(r)))continue;let c=!1,l=!1;for(const{end:u,start:f,value:h}of a)c?(o>=f||s===h)&&(e=fi(e,f)):(l=h!==s,c=!0),u>o&&o>=f&&h!==s&&(e=Ut(e,o+1,h));l&&(e=Ut(e,i,s))}return[e,n]}function Jg(e){return typeof e.groupIndex<"u"}function Zg({offset:e},t){return t===e?0:t<e?-1:1}function Yr(e,t,n){if(t.length===0)return 0;const{index:r,offset:o,size:s}=Wc(t,e,xi),i=e-r,a=s*i+(i-1)*n+o;return a>0?a+n:a}function Vc(e,t){if(!Fo(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function Kc(e,t,n){if(Jg(e))return t.groupIndices[e.groupIndex]+1;{const r=e.index==="LAST"?n:e.index;let o=Vc(r,t);return o=Math.max(0,o,Math.min(n,o)),o}}function Qg(e,t,n,r=0){return r>0&&(t=Math.max(t,Wc(e,r,xi).offset)),Lc(Gg(e,t,n,Zg),nx)}function ex(e,[t,n,r,o]){t.length>0&&r("received item sizes",t,Dt.DEBUG);const s=e.sizeTree;let i=s,a=0;if(n.length>0&&Ue(s)&&t.length===2){const h=t[0].size,p=t[1].size;i=n.reduce((m,g)=>Ut(Ut(m,g,h),g+1,p),i)}else[i,a]=Xg(i,t);if(i===s)return e;const{lastIndex:c,lastOffset:l,lastSize:u,offsetTree:f}=bi(e.offsetTree,a,i,o);return{groupIndices:n,groupOffsetTree:n.reduce((h,p)=>Ut(h,p,Yr(p,f,o)),xr()),lastIndex:c,lastOffset:l,lastSize:u,offsetTree:f,sizeTree:i}}function tx(e){return Yn(e).map(({k:t,v:n},r,o)=>{const s=o[r+1];return{endIndex:s?s.k-1:1/0,size:n,startIndex:t}})}function qc(e,t){let n=0,r=0;for(;n<e;)n+=t[r+1]-t[r]-1,r++;return r-(n===e?0:1)}function bi(e,t,n,r){let o=e,s=0,i=0,a=0,c=0;if(t!==0){c=$o(o,t-1,xi),a=o[c].offset;const l=nn(n,t-1);s=l[0],i=l[1],o.length&&o[c].size===nn(n,t)[1]&&(c-=1),o=o.slice(0,c+1)}else o=[];for(const{start:l,value:u}of Do(n,t,1/0)){const f=l-s,h=f*i+a+f*r;o.push({index:l,offset:h,size:u}),s=l,a=h,i=u}return{lastIndex:s,lastOffset:a,lastSize:i,offsetTree:o}}function nx(e){return{index:e.index,value:e}}function rx(e){const{endIndex:t,size:n,startIndex:r}=e;return o=>o.start===r&&(o.end===t||o.end===1/0)&&o.value===n}const ox={offsetHeight:"height",offsetWidth:"width"},fn=Re(([{log:e},{recalcInProgress:t}])=>{const n=Oe(),r=Oe(),o=vt(r,0),s=Oe(),i=Oe(),a=re(0),c=re([]),l=re(void 0),u=re(void 0),f=re((k,S)=>jn(k,ox[S])),h=re(void 0),p=re(0),m=Yg(),g=vt(ee(n,Ne(c,e,p),dn(ex,m),Je()),m),b=vt(ee(c,Je(),dn((k,S)=>({current:S,prev:k.current}),{current:[],prev:[]}),ce(({prev:k})=>k)),[]);me(ee(c,ye(k=>k.length>0),Ne(g,p),ce(([k,S,E])=>{const j=k.reduce((_,D,L)=>Ut(_,D,Yr(D,S.offsetTree,E)||L),xr());return{...S,groupIndices:k,groupOffsetTree:j}})),g),me(ee(r,Ne(g),ye(([k,{lastIndex:S}])=>k<S),ce(([k,{lastIndex:S,lastSize:E}])=>[{endIndex:S,size:E,startIndex:k}])),n),me(l,u);const v=vt(ee(l,ce(k=>k===void 0)),!0);me(ee(u,ye(k=>k!==void 0&&Ue(lt(g).sizeTree)),ce(k=>[{endIndex:0,size:k,startIndex:0}])),n);const y=Ht(ee(n,Ne(g),dn(({sizes:k},[S,E])=>({changed:E!==k,sizes:E}),{changed:!1,sizes:m}),ce(k=>k.changed)));De(ee(a,dn((k,S)=>({diff:k.prev-S,prev:S}),{diff:0,prev:0}),ce(k=>k.diff)),k=>{const{groupIndices:S}=lt(g);if(k>0)Ae(t,!0),Ae(s,k+qc(k,S));else if(k<0){const E=lt(b);E.length>0&&(k-=qc(-k,E)),Ae(i,k)}}),De(ee(a,Ne(e)),([k,S])=>{k<0&&S("`firstItemIndex` prop should not be set to less than zero. If you don't know the total count, just use a very high value",{firstItemIndex:a},Dt.ERROR)});const T=Ht(s);me(ee(s,Ne(g),ce(([k,S])=>{const E=S.groupIndices.length>0,j=[],_=S.lastSize;if(E){const D=qr(S.sizeTree,0);let L=0,W=0;for(;L<k;){const $=S.groupIndices[W],Z=S.groupIndices.length===W+1?1/0:S.groupIndices[W+1]-$-1;j.push({endIndex:$,size:D,startIndex:$}),j.push({endIndex:$+1+Z-1,size:_,startIndex:$+1}),W++,L+=Z+1}const V=Yn(S.sizeTree);return L!==k&&V.shift(),V.reduce(($,{k:Z,v:X})=>{let oe=$.ranges;return $.prevSize!==0&&(oe=[...$.ranges,{endIndex:Z+k-1,size:$.prevSize,startIndex:$.prevIndex}]),{prevIndex:Z+k,prevSize:X,ranges:oe}},{prevIndex:k,prevSize:0,ranges:j}).ranges}return Yn(S.sizeTree).reduce((D,{k:L,v:W})=>({prevIndex:L+k,prevSize:W,ranges:[...D.ranges,{endIndex:L+k-1,size:D.prevSize,startIndex:D.prevIndex}]}),{prevIndex:0,prevSize:_,ranges:[]}).ranges})),n);const I=Ht(ee(i,Ne(g,p),ce(([k,{offsetTree:S},E])=>{const j=-k;return Yr(j,S,E)})));return me(ee(i,Ne(g,p),ce(([k,S,E])=>{if(S.groupIndices.length>0){if(Ue(S.sizeTree))return S;let j=xr();const _=lt(b);let D=0,L=0,W=0;for(;D<-k;){W=_[L];const V=_[L+1]-W-1;L++,D+=V+1}if(j=Yn(S.sizeTree).reduce((V,{k:$,v:Z})=>Ut(V,Math.max(0,$+k),Z),j),D!==-k){const V=qr(S.sizeTree,W);j=Ut(j,0,V);const $=nn(S.sizeTree,-k+1)[1];j=Ut(j,1,$)}return{...S,sizeTree:j,...bi(S.offsetTree,0,j,E)}}else{const j=Yn(S.sizeTree).reduce((_,{k:D,v:L})=>Ut(_,Math.max(0,D+k),L),xr());return{...S,sizeTree:j,...bi(S.offsetTree,0,j,E)}}})),g),{beforeUnshiftWith:T,data:h,defaultItemSize:u,firstItemIndex:a,fixedItemSize:l,gap:p,groupIndices:c,itemSize:f,listRefresh:y,shiftWith:i,shiftWithOffset:I,sizeRanges:n,sizes:g,statefulTotalCount:o,totalCount:r,trackItemSizes:v,unshiftWith:s}},Xe(_n,gi),{singleton:!0});function sx(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const Gc=Re(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:r,scrollTop:o}])=>{const s=Oe(),i=Oe(),a=Ht(ee(s,ce(sx)));return me(ee(a,ce(c=>c.totalCount)),n),me(ee(a,ce(c=>c.groupIndices)),e),me(ee(ft(o,t,r),ye(([c,l])=>Fo(l)),ce(([c,l,u])=>nn(l.groupOffsetTree,Math.max(c-u,0),"v")[0]),Je(),ce(c=>[c])),i),{groupCounts:s,topItemsIndexes:i}},Xe(fn,Nt)),Pn=Re(([{log:e}])=>{const t=re(!1),n=Ht(ee(t,ye(r=>r),Je()));return De(t,r=>{r&&lt(e)("props updated",{},Dt.DEBUG)}),{didMount:n,propsReady:t}},Xe(_n),{singleton:!0}),ix=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function Yc(e){const t=typeof e=="number"?{index:e}:e;return t.align||(t.align="start"),(!t.behavior||!ix)&&(t.behavior="auto"),t.offset||(t.offset=0),t}const Xr=Re(([{gap:e,listRefresh:t,sizes:n,totalCount:r},{fixedFooterHeight:o,fixedHeaderHeight:s,footerHeight:i,headerHeight:a,scrollingInProgress:c,scrollTo:l,smoothScrollTargetReached:u,viewportHeight:f},{log:h}])=>{const p=Oe(),m=Oe(),g=re(0);let b=null,v=null,y=null;function T(){b&&(b(),b=null),y&&(y(),y=null),v&&(clearTimeout(v),v=null),Ae(c,!1)}return me(ee(p,Ne(n,f,r,g,a,i,h),Ne(e,s,o),ce(([[I,k,S,E,j,_,D,L],W,V,$])=>{const Z=Yc(I),{align:X,behavior:oe,offset:U}=Z,F=E-1,G=Kc(Z,k,F);let H=Yr(G,k.offsetTree,W)+_;X==="end"?(H+=V+nn(k.sizeTree,G)[1]-S+$,G===F&&(H+=D)):X==="center"?H+=(V+nn(k.sizeTree,G)[1]-S+$)/2:H-=j,U&&(H+=U);const A=N=>{T(),N?(L("retrying to scroll to",{location:I},Dt.DEBUG),Ae(p,I)):(Ae(m,!0),L("list did not change, scroll successful",{},Dt.DEBUG))};if(T(),oe==="smooth"){let N=!1;y=De(t,R=>{N=N||R}),b=tn(u,()=>{A(N)})}else b=tn(ee(t,ax(150)),A);return v=setTimeout(()=>{T()},1200),Ae(c,!0),L("scrolling from index to",{behavior:oe,index:G,top:H},Dt.DEBUG),{behavior:oe,top:H}})),l),{scrollTargetReached:m,scrollToIndex:p,topListHeight:g}},Xe(fn,Nt,_n),{singleton:!0});function ax(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return r=>{r&&(t(!0),clearTimeout(n))}}}function wi(e,t){e==0?t():requestAnimationFrame(()=>{wi(e-1,t)})}function vi(e,t){const n=t-1;return typeof e=="number"?e:e.index==="LAST"?n:e.index}const Jr=Re(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:r},{scrollTargetReached:o,scrollToIndex:s},{didMount:i}])=>{const a=re(!0),c=re(0),l=re(!0);return me(ee(i,Ne(c),ye(([u,f])=>!!f),un(!1)),a),me(ee(i,Ne(c),ye(([u,f])=>!!f),un(!1)),l),De(ee(ft(t,i),Ne(a,n,e,l),ye(([[,u],f,{sizeTree:h},p,m])=>u&&(!Ue(h)||li(p))&&!f&&!m),Ne(c)),([,u])=>{tn(o,()=>{Ae(l,!0)}),wi(4,()=>{tn(r,()=>{Ae(a,!0)}),Ae(s,u)})}),{initialItemFinalLocationReached:l,initialTopMostItemIndex:c,scrolledToInitialItem:a}},Xe(fn,Nt,Xr,Pn),{singleton:!0});function Xc(e,t){return Math.abs(e-t)<1.01}const Zr="up",Qr="down",lx="none",cx={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},ux=0,eo=Re(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:r,scrollTop:o,viewportHeight:s}])=>{const i=re(!1),a=re(!0),c=Oe(),l=Oe(),u=re(4),f=re(ux),h=vt(ee(ui(ee(ve(o),qn(1),un(!0)),ee(ve(o),qn(1),un(!1),Oc(100))),Je()),!1),p=vt(ee(ui(ee(n,un(!0)),ee(n,un(!1),Oc(200))),Je()),!1);me(ee(ft(ve(o),ve(f)),ce(([y,T])=>y<=T),Je()),a),me(ee(a,yn(50)),l);const m=Ht(ee(ft(r,ve(s),ve(t),ve(e),ve(u)),dn((y,[{scrollHeight:T,scrollTop:I},k,S,E,j])=>{const _=I+k-T>-j,D={scrollHeight:T,scrollTop:I,viewportHeight:k};if(_){let W,V;return I>y.state.scrollTop?(W="SCROLLED_DOWN",V=y.state.scrollTop-I):(W="SIZE_DECREASED",V=y.state.scrollTop-I||y.scrollTopDelta),{atBottom:!0,atBottomBecause:W,scrollTopDelta:V,state:D}}let L;return D.scrollHeight>y.state.scrollHeight?L="SIZE_INCREASED":k<y.state.viewportHeight?L="VIEWPORT_HEIGHT_DECREASING":I<y.state.scrollTop?L="SCROLLING_UPWARDS":L="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:L,state:D}},cx),Je((y,T)=>y&&y.atBottom===T.atBottom))),g=vt(ee(r,dn((y,{scrollHeight:T,scrollTop:I,viewportHeight:k})=>{if(Xc(y.scrollHeight,T))return{changed:!1,jump:0,scrollHeight:T,scrollTop:I};{const S=T-(I+k)<1;return y.scrollTop!==I&&S?{changed:!0,jump:y.scrollTop-I,scrollHeight:T,scrollTop:I}:{changed:!0,jump:0,scrollHeight:T,scrollTop:I}}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),ye(y=>y.changed),ce(y=>y.jump)),0);me(ee(m,ce(y=>y.atBottom)),i),me(ee(i,yn(50)),c);const b=re(Qr);me(ee(r,ce(({scrollTop:y})=>y),Je(),dn((y,T)=>lt(p)?{direction:y.direction,prevScrollTop:T}:{direction:T<y.prevScrollTop?Zr:Qr,prevScrollTop:T},{direction:Qr,prevScrollTop:0}),ce(y=>y.direction)),b),me(ee(r,yn(50),un(lx)),b);const v=re(0);return me(ee(h,ye(y=>!y),un(0)),v),me(ee(o,yn(100),Ne(h),ye(([y,T])=>!!T),dn(([y,T],[I])=>[T,I],[0,0]),ce(([y,T])=>T-y)),v),{atBottomState:m,atBottomStateChange:c,atBottomThreshold:u,atTopStateChange:l,atTopThreshold:f,isAtBottom:i,isAtTop:a,isScrolling:h,lastJumpDueToItemResize:g,scrollDirection:b,scrollVelocity:v}},Xe(Nt)),zo="top",Bo="bottom",Jc="none";function Zc(e,t,n){return typeof e=="number"?n===Zr&&t===zo||n===Qr&&t===Bo?e:0:n===Zr?t===zo?e.main:e.reverse:t===Bo?e.main:e.reverse}function Qc(e,t){var n;return typeof e=="number"?e:(n=e[t])!=null?n:0}const yi=Re(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:r,viewportHeight:o}])=>{const s=Oe(),i=re(0),a=re(0),c=re(0),l=vt(ee(ft(ve(r),ve(o),ve(n),ve(s,Gr),ve(c),ve(i),ve(t),ve(e),ve(a)),ce(([u,f,h,[p,m],g,b,v,y,T])=>{const I=u-y,k=b+v,S=Math.max(h-I,0);let E=Jc;const j=Qc(T,zo),_=Qc(T,Bo);return p-=y,p+=h+v,m+=h+v,m-=y,p>u+k-j&&(E=Zr),m<u-S+f+_&&(E=Qr),E!==Jc?[Math.max(I-h-Zc(g,zo,E)-j,0),I-S-v+f+Zc(g,Bo,E)+_]:null}),ye(u=>u!=null),Je(Gr)),[0,0]);return{increaseViewportBy:a,listBoundary:s,overscan:c,topListHeight:i,visibleRange:l}},Xe(Nt),{singleton:!0});function dx(e,t,n){if(Fo(t)){const r=Vc(e,t);return[{index:nn(t.groupOffsetTree,r)[0],offset:0,size:0},{data:n==null?void 0:n[0],index:r,offset:0,size:0}]}return[{data:n==null?void 0:n[0],index:e,offset:0,size:0}]}const Si={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function Ho(e,t,n,r,o,s){const{lastIndex:i,lastOffset:a,lastSize:c}=o;let l=0,u=0;if(e.length>0){l=e[0].offset;const g=e[e.length-1];u=g.offset+g.size}const f=n-i,h=a+f*c+(f-1)*r,p=l,m=h-u;return{bottom:u,firstItemIndex:s,items:tu(e,o,s),offsetBottom:m,offsetTop:l,top:p,topItems:tu(t,o,s),topListHeight:t.reduce((g,b)=>b.size+g,0),totalCount:n}}function eu(e,t,n,r,o,s){let i=0;if(n.groupIndices.length>0)for(const u of n.groupIndices){if(u-i>=e)break;i++}const a=e+i,c=vi(t,a),l=Array.from({length:a}).map((u,f)=>({data:s[f+c],index:f+c,offset:0,size:0}));return Ho(l,[],a,o,n,r)}function tu(e,t,n){if(e.length===0)return[];if(!Fo(t))return e.map(l=>({...l,index:l.index+n,originalIndex:l.index}));const r=e[0].index,o=e[e.length-1].index,s=[],i=Do(t.groupOffsetTree,r,o);let a,c=0;for(const l of e){(!a||a.end<l.index)&&(a=i.shift(),c=t.groupIndices.indexOf(a.start));let u;l.index===a.start?u={index:c,type:"group"}:u={groupIndex:c,index:l.index-(c+1)+n},s.push({...u,data:l.data,offset:l.offset,originalIndex:l.index,size:l.size})}return s}const Xn=Re(([{data:e,firstItemIndex:t,gap:n,sizes:r,totalCount:o},s,{listBoundary:i,topListHeight:a,visibleRange:c},{initialTopMostItemIndex:l,scrolledToInitialItem:u},{topListHeight:f},h,{didMount:p},{recalcInProgress:m}])=>{const g=re([]),b=re(0),v=Oe();me(s.topItemsIndexes,g);const y=vt(ee(ft(p,m,ve(c,Gr),ve(o),ve(r),ve(l),u,ve(g),ve(t),ve(n),e),ye(([S,E,,j,,,,,,,_])=>{const D=_&&_.length!==j;return S&&!E&&!D}),ce(([,,[S,E],j,_,D,L,W,V,$,Z])=>{const X=_,{offsetTree:oe,sizeTree:U}=X,F=lt(b);if(j===0)return{...Si,totalCount:j};if(S===0&&E===0)return F===0?{...Si,totalCount:j}:eu(F,D,_,V,$,Z||[]);if(Ue(U))return F>0?null:Ho(dx(vi(D,j),X,Z),[],j,$,X,V);const G=[];if(W.length>0){const M=W[0],q=W[W.length-1];let J=0;for(const P of Do(U,M,q)){const K=P.value,te=Math.max(P.start,M),le=Math.min(P.end,q);for(let he=te;he<=le;he++)G.push({data:Z==null?void 0:Z[he],index:he,offset:J,size:K}),J+=K}}if(!L)return Ho([],G,j,$,X,V);const H=W.length>0?W[W.length-1]+1:0,A=Qg(oe,S,E,H);if(A.length===0)return null;const N=j-1,R=Mo([],M=>{for(const q of A){const J=q.value;let P=J.offset,K=q.start;const te=J.size;if(J.offset<S){K+=Math.floor((S-J.offset+$)/(te+$));const he=K-q.start;P+=he*te+he*$}K<H&&(P+=(H-K)*te,K=H);const le=Math.min(q.end,N);for(let he=K;he<=le&&!(P>=E);he++)M.push({data:Z==null?void 0:Z[he],index:he,offset:P,size:te}),P+=te+$}});return Ho(R,G,j,$,X,V)}),ye(S=>S!==null),Je()),Si);me(ee(e,ye(li),ce(S=>S==null?void 0:S.length)),o),me(ee(y,ce(S=>S.topListHeight)),f),me(f,a),me(ee(y,ce(S=>[S.top,S.bottom])),i),me(ee(y,ce(S=>S.items)),v);const T=Ht(ee(y,ye(({items:S})=>S.length>0),Ne(o,e),ye(([{items:S},E])=>S[S.length-1].originalIndex===E-1),ce(([,S,E])=>[S-1,E]),Je(Gr),ce(([S])=>S))),I=Ht(ee(y,yn(200),ye(({items:S,topItems:E})=>S.length>0&&S[0].originalIndex===E.length),ce(({items:S})=>S[0].index),Je())),k=Ht(ee(y,ye(({items:S})=>S.length>0),ce(({items:S})=>{let E=0,j=S.length-1;for(;S[E].type==="group"&&E<j;)E++;for(;S[j].type==="group"&&j>E;)j--;return{endIndex:S[j].index,startIndex:S[E].index}}),Je(Uc)));return{endReached:T,initialItemCount:b,itemsRendered:v,listState:y,rangeChanged:k,startReached:I,topItemsIndexes:g,...h}},Xe(fn,Gc,yi,Jr,Xr,eo,Pn,gi),{singleton:!0}),nu=Re(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:r},{listState:o}])=>{const s=Oe(),i=vt(ee(ft(n,e,r,t,o),ce(([a,c,l,u,f])=>a+c+l+u+f.offsetBottom+f.bottom)),0);return me(ve(i),s),{totalListHeight:i,totalListHeightChanged:s}},Xe(Nt,Xn),{singleton:!0}),fx=Re(([{viewportHeight:e},{totalListHeight:t}])=>{const n=re(!1),r=vt(ee(ft(n,e,t),ye(([o])=>o),ce(([,o,s])=>Math.max(0,o-s)),yn(0),Je()),0);return{alignToBottom:n,paddingTopAddition:r}},Xe(Nt,nu),{singleton:!0}),ru=Re(()=>({context:re(null)})),hx=({itemBottom:e,itemTop:t,locationParams:{align:n,behavior:r,...o},viewportBottom:s,viewportTop:i})=>t<i?{...o,align:n??"start",behavior:r}:e>s?{...o,align:n??"end",behavior:r}:null,ou=Re(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:s,scrollingInProgress:i,scrollTop:a,viewportHeight:c},{scrollToIndex:l}])=>{const u=Oe();return me(ee(u,Ne(t,c,n,s,o,r,a),Ne(e),ce(([[f,h,p,m,g,b,v,y],T])=>{const{align:I,behavior:k,calculateViewLocation:S=hx,done:E,...j}=f,_=Kc(f,h,m-1),D=Yr(_,h.offsetTree,T)+g+b,L=D+nn(h.sizeTree,_)[1],W=y+b,V=y+p-v,$=S({itemBottom:L,itemTop:D,locationParams:{align:I,behavior:k,...j},viewportBottom:V,viewportTop:W});return $?E&&tn(ee(i,ye(Z=>!Z),qn(lt(i)?1:2)),E):E&&E(),$}),ye(f=>f!==null)),l),{scrollIntoView:u}},Xe(fn,Nt,Xr,Xn,_n),{singleton:!0});function su(e){return e?e==="smooth"?"smooth":"auto":!1}const px=(e,t)=>typeof e=="function"?su(e(t)):t&&su(e),mx=Re(([{listRefresh:e,totalCount:t,fixedItemSize:n,data:r},{atBottomState:o,isAtBottom:s},{scrollToIndex:i},{scrolledToInitialItem:a},{didMount:c,propsReady:l},{log:u},{scrollingInProgress:f},{context:h},{scrollIntoView:p}])=>{const m=re(!1),g=Oe();let b=null;function v(k){Ae(i,{align:"end",behavior:k,index:"LAST"})}De(ee(ft(ee(ve(t),qn(1)),c),Ne(ve(m),s,a,f),ce(([[k,S],E,j,_,D])=>{let L=S&&_,W="auto";return L&&(W=px(E,j||D),L=L&&!!W),{followOutputBehavior:W,shouldFollow:L,totalCount:k}}),ye(({shouldFollow:k})=>k)),({followOutputBehavior:k,totalCount:S})=>{b&&(b(),b=null),lt(n)?requestAnimationFrame(()=>{lt(u)("following output to ",{totalCount:S},Dt.DEBUG),v(k)}):b=tn(e,()=>{lt(u)("following output to ",{totalCount:S},Dt.DEBUG),v(k),b=null})});function y(k){const S=tn(o,E=>{k&&!E.atBottom&&E.notAtBottomBecause==="SIZE_INCREASED"&&!b&&(lt(u)("scrolling to bottom due to increased size",{},Dt.DEBUG),v("auto"))});setTimeout(S,100)}De(ee(ft(ve(m),t,l),ye(([k,,S])=>k&&S),dn(({value:k},[,S])=>({refreshed:k===S,value:S}),{refreshed:!1,value:0}),ye(({refreshed:k})=>k),Ne(m,t)),([,k])=>{lt(a)&&y(k!==!1)}),De(g,()=>{y(lt(m)!==!1)}),De(ft(ve(m),o),([k,S])=>{k&&!S.atBottom&&S.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&v("auto")});const T=re(null),I=Oe();return me(ui(ee(ve(r),ce(k=>{var S;return(S=k==null?void 0:k.length)!=null?S:0})),ee(ve(t))),I),De(ee(ft(ee(I,qn(1)),c),Ne(ve(T),a,f,h),ce(([[k,S],E,j,_,D])=>S&&j&&(E==null?void 0:E({context:D,totalCount:k,scrollingInProgress:_}))),ye(k=>!!k),yn(0)),k=>{b&&(b(),b=null),lt(n)?requestAnimationFrame(()=>{lt(u)("scrolling into view",{}),Ae(p,k)}):b=tn(e,()=>{lt(u)("scrolling into view",{}),Ae(p,k),b=null})}),{autoscrollToBottom:g,followOutput:m,scrollIntoViewOnChange:T}},Xe(fn,eo,Xr,Jr,Pn,_n,Nt,ru,ou)),gx=Re(([{data:e,firstItemIndex:t,gap:n,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:s,listState:i},{didMount:a}])=>(me(ee(a,Ne(s),ye(([,c])=>c!==0),Ne(o,r,t,n,e),ce(([[,c],l,u,f,h,p=[]])=>eu(c,l,u,f,h,p))),i),{}),Xe(fn,Jr,Xn,Pn),{singleton:!0}),xx=Re(([{didMount:e},{scrollTo:t},{listState:n}])=>{const r=re(0);return De(ee(e,Ne(r),ye(([,o])=>o!==0),ce(([,o])=>({top:o}))),o=>{tn(ee(n,qn(1),ye(s=>s.items.length>1)),()=>{requestAnimationFrame(()=>{Ae(t,o)})})}),{initialScrollTop:r}},Xe(Pn,Nt,Xn),{singleton:!0}),iu=Re(([{scrollVelocity:e}])=>{const t=re(!1),n=Oe(),r=re(!1);return me(ee(e,Ne(r,t,n),ye(([o,s])=>!!s),ce(([o,s,i,a])=>{const{enter:c,exit:l}=s;if(i){if(l(o,a))return!1}else if(c(o,a))return!0;return i}),Je()),t),De(ee(ft(t,e,n),Ne(r)),([[o,s,i],a])=>{o&&a&&a.change&&a.change(s,i)}),{isSeeking:t,scrollSeekConfiguration:r,scrollSeekRangeChanged:n,scrollVelocity:e}},Xe(eo),{singleton:!0}),Ci=Re(([{scrollContainerState:e,scrollTo:t}])=>{const n=Oe(),r=Oe(),o=Oe(),s=re(!1),i=re(void 0);return me(ee(ft(n,r),ce(([{scrollHeight:a,scrollTop:c,viewportHeight:l},{offsetTop:u}])=>({scrollHeight:a,scrollTop:Math.max(0,c-u),viewportHeight:l}))),e),me(ee(t,Ne(r),ce(([a,{offsetTop:c}])=>({...a,top:a.top+c}))),o),{customScrollParent:i,useWindowScroll:s,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:r}},Xe(Nt)),bx=Re(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:r},{initialTopMostItemIndex:o},{didMount:s},{useWindowScroll:i,windowScrollContainerState:a,windowViewportRect:c}])=>{const l=Oe(),u=re(void 0),f=re(null),h=re(null);return me(a,f),me(c,h),De(ee(l,Ne(t,r,i,f,h,n)),([p,m,g,b,v,y,T])=>{const I=tx(m.sizeTree);b&&v!==null&&y!==null&&(g=v.scrollTop-y.offsetTop),g-=T,p({ranges:I,scrollTop:g})}),me(ee(u,ye(li),ce(wx)),o),me(ee(s,Ne(u),ye(([,p])=>p!==void 0),Je(),ce(([,p])=>p.ranges)),e),{getState:l,restoreStateFrom:u}},Xe(fn,Nt,Jr,Pn,Ci));function wx(e){return{align:"start",index:0,offset:e.scrollTop}}const vx=Re(([{topItemsIndexes:e}])=>{const t=re(0);return me(ee(t,ye(n=>n>=0),ce(n=>Array.from({length:n}).map((r,o)=>o))),e),{topItemCount:t}},Xe(Xn));function au(e){let t=!1,n;return()=>(t||(t=!0,n=e()),n)}const yx=au(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),Sx=Re(([{deviation:e,scrollBy:t,scrollingInProgress:n,scrollTop:r},{isAtBottom:o,isScrolling:s,lastJumpDueToItemResize:i,scrollDirection:a},{listState:c},{beforeUnshiftWith:l,gap:u,shiftWithOffset:f,sizes:h},{log:p},{recalcInProgress:m}])=>{const g=Ht(ee(c,Ne(i),dn(([,v,y,T],[{bottom:I,items:k,offsetBottom:S,totalCount:E},j])=>{const _=I+S;let D=0;return y===E&&v.length>0&&k.length>0&&(k[0].originalIndex===0&&v[0].originalIndex===0||(D=_-T,D!==0&&(D+=j))),[D,k,E,_]},[0,[],0,0]),ye(([v])=>v!==0),Ne(r,a,n,o,p,m),ye(([,v,y,T,,,I])=>!I&&!T&&v!==0&&y===Zr),ce(([[v],,,,,y])=>(y("Upward scrolling compensation",{amount:v},Dt.DEBUG),v))));function b(v){v>0?(Ae(t,{behavior:"auto",top:-v}),Ae(e,0)):(Ae(e,0),Ae(t,{behavior:"auto",top:-v}))}return De(ee(g,Ne(e,s)),([v,y,T])=>{T&&yx()?Ae(e,y-v):b(-v)}),De(ee(ft(vt(s,!1),e,m),ye(([v,y,T])=>!v&&!T&&y!==0),ce(([v,y])=>y),yn(1)),b),me(ee(f,ce(v=>({top:-v}))),t),De(ee(l,Ne(h,u),ce(([v,{groupIndices:y,lastSize:T,sizeTree:I},k])=>{function S(E){return E*(T+k)}if(y.length===0)return S(v);{let E=0;const j=qr(I,0);let _=0,D=0;for(;_<v;){_++,E+=j;let L=y.length===D+1?1/0:y[D+1]-y[D]-1;_+L>v&&(E-=j,L=v-_+1),_+=L,E+=S(L),D++}return E}})),v=>{Ae(e,v),requestAnimationFrame(()=>{Ae(t,{top:v}),requestAnimationFrame(()=>{Ae(e,0),Ae(m,!1)})})}),{deviation:e}},Xe(Nt,eo,Xn,fn,_n,gi)),Cx=Re(([e,t,n,r,o,s,i,a,c,l,u])=>({...e,...t,...n,...r,...o,...s,...i,...a,...c,...l,...u}),Xe(yi,gx,Pn,iu,nu,xx,fx,Ci,ou,_n,ru)),lu=Re(([{data:e,defaultItemSize:t,firstItemIndex:n,fixedItemSize:r,gap:o,groupIndices:s,itemSize:i,sizeRanges:a,sizes:c,statefulTotalCount:l,totalCount:u,trackItemSizes:f},{initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:m},g,b,v,{listState:y,topItemsIndexes:T,...I},{scrollToIndex:k},S,{topItemCount:E},{groupCounts:j},_])=>(me(I.rangeChanged,_.scrollSeekRangeChanged),me(ee(_.windowViewportRect,ce(D=>D.visibleHeight)),g.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:r,gap:o,groupCounts:j,initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:m,sizeRanges:a,topItemCount:E,topItemsIndexes:T,totalCount:u,...v,groupIndices:s,itemSize:i,listState:y,scrollToIndex:k,statefulTotalCount:l,trackItemSizes:f,...I,..._,...g,sizes:c,...b}),Xe(fn,Jr,Nt,bx,mx,Xn,Xr,Sx,vx,Gc,Cx));function kx(e,t){const n={},r={};let o=0;const s=e.length;for(;o<s;)r[e[o]]=1,o+=1;for(const i in t)Object.hasOwn(r,i)||(n[i]=t[i]);return n}const Uo=typeof document<"u"?x.useLayoutEffect:x.useEffect;function cu(e,t,n){const r=Object.keys(t.required||{}),o=Object.keys(t.optional||{}),s=Object.keys(t.methods||{}),i=Object.keys(t.events||{}),a=x.createContext({});function c(b,v){b.propsReady&&Ae(b.propsReady,!1);for(const y of r){const T=b[t.required[y]];Ae(T,v[y])}for(const y of o)if(y in v){const T=b[t.optional[y]];Ae(T,v[y])}b.propsReady&&Ae(b.propsReady,!0)}function l(b){return s.reduce((v,y)=>(v[y]=T=>{const I=b[t.methods[y]];Ae(I,T)},v),{})}function u(b){return i.reduce((v,y)=>(v[y]=zg(b[t.events[y]]),v),{})}const f=x.forwardRef((b,v)=>{const{children:y,...T}=b,[I]=x.useState(()=>Mo(Hg(e),E=>{c(E,T)})),[k]=x.useState(Pc(u,I));Uo(()=>{for(const E of i)E in T&&De(k[E],T[E]);return()=>{Object.values(k).map(ci)}},[T,k,I]),Uo(()=>{c(I,T)}),x.useImperativeHandle(v,_c(l(I)));const S=n;return d.jsx(a.Provider,{value:I,children:n?d.jsx(S,{...kx([...r,...o,...i],T),children:y}):y})}),h=b=>{const v=x.useContext(a);return x.useCallback(y=>{Ae(v[b],y)},[v,b])},p=b=>{const v=x.useContext(a)[b],y=x.useCallback(T=>De(v,T),[v]);return x.useSyncExternalStore(y,()=>lt(v),()=>lt(v))},m=b=>{const v=x.useContext(a)[b],[y,T]=x.useState(Pc(lt,v));return Uo(()=>De(v,I=>{I!==y&&T(_c(I))}),[v,y]),y},g=x.version.startsWith("18")?p:m;return{Component:f,useEmitter:(b,v)=>{const y=x.useContext(a)[b];Uo(()=>De(y,v),[v,y])},useEmitterValue:g,usePublisher:h}}const uu=x.createContext(void 0),du=x.createContext(void 0),fu=typeof document<"u"?x.useLayoutEffect:x.useEffect;function ki(e){return"self"in e}function Tx(e){return"body"in e}function hu(e,t,n,r=gr,o,s){const i=x.useRef(null),a=x.useRef(null),c=x.useRef(null),l=x.useCallback(h=>{let p,m,g;const b=h.target;if(Tx(b)||ki(b)){const y=ki(b)?b:b.defaultView;g=s?y.scrollX:y.scrollY,p=s?y.document.documentElement.scrollWidth:y.document.documentElement.scrollHeight,m=s?y.innerWidth:y.innerHeight}else g=s?b.scrollLeft:b.scrollTop,p=s?b.scrollWidth:b.scrollHeight,m=s?b.offsetWidth:b.offsetHeight;const v=()=>{e({scrollHeight:p,scrollTop:Math.max(g,0),viewportHeight:m})};h.suppressFlushSync?v():Ls.flushSync(v),a.current!==null&&(g===a.current||g<=0||g===p-m)&&(a.current=null,t(!0),c.current&&(clearTimeout(c.current),c.current=null))},[e,t,s]);x.useEffect(()=>{const h=o||i.current;return r(o||i.current),l({suppressFlushSync:!0,target:h}),h.addEventListener("scroll",l,{passive:!0}),()=>{r(null),h.removeEventListener("scroll",l)}},[i,l,n,r,o]);function u(h){const p=i.current;if(!p||(s?"offsetWidth"in p&&p.offsetWidth===0:"offsetHeight"in p&&p.offsetHeight===0))return;const m=h.behavior==="smooth";let g,b,v;ki(p)?(b=Math.max(jn(p.document.documentElement,s?"width":"height"),s?p.document.documentElement.scrollWidth:p.document.documentElement.scrollHeight),g=s?p.innerWidth:p.innerHeight,v=s?window.scrollX:window.scrollY):(b=p[s?"scrollWidth":"scrollHeight"],g=jn(p,s?"width":"height"),v=p[s?"scrollLeft":"scrollTop"]);const y=b-g;if(h.top=Math.ceil(Math.max(Math.min(y,h.top),0)),Xc(g,b)||h.top===v){e({scrollHeight:b,scrollTop:v,viewportHeight:g}),m&&t(!0);return}m?(a.current=h.top,c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{c.current=null,a.current=null,t(!0)},1e3)):a.current=null,s&&(h={behavior:h.behavior,left:h.top}),p.scrollTo(h)}function f(h){s&&(h={behavior:h.behavior,left:h.top}),i.current.scrollBy(h)}return{scrollByCallback:f,scrollerRef:i,scrollToCallback:u}}const Ti="-webkit-sticky",pu="sticky",Ei=au(()=>{if(typeof document>"u")return pu;const e=document.createElement("div");return e.style.position=Ti,e.style.position===Ti?Ti:pu});function Ii(e){return e}const Ex=Re(()=>{const e=re(a=>`Item ${a}`),t=re(a=>`Group ${a}`),n=re({}),r=re(Ii),o=re("div"),s=re(gr),i=(a,c=null)=>vt(ee(n,ce(l=>l[a]),Je()),c);return{components:n,computeItemKey:r,EmptyPlaceholder:i("EmptyPlaceholder"),FooterComponent:i("Footer"),GroupComponent:i("Group","div"),groupContent:t,HeaderComponent:i("Header"),HeaderFooterTag:o,ItemComponent:i("Item","div"),itemContent:e,ListComponent:i("List","div"),ScrollerComponent:i("Scroller","div"),scrollerRef:s,ScrollSeekPlaceholder:i("ScrollSeekPlaceholder"),TopItemListComponent:i("TopItemList")}}),Ix=Re(([e,t])=>({...e,...t}),Xe(lu,Ex)),Ax=({height:e})=>d.jsx("div",{style:{height:e}}),Nx={overflowAnchor:"none",position:Ei(),zIndex:1},mu={overflowAnchor:"none"},_x={...mu,display:"inline-block",height:"100%"},gu=x.memo(function({showTopList:e=!1}){const t=ke("listState"),n=Yt("sizeRanges"),r=ke("useWindowScroll"),o=ke("customScrollParent"),s=Yt("windowScrollContainerState"),i=Yt("scrollContainerState"),a=o||r?s:i,c=ke("itemContent"),l=ke("context"),u=ke("groupContent"),f=ke("trackItemSizes"),h=ke("itemSize"),p=ke("log"),m=Yt("gap"),g=ke("horizontalDirection"),{callbackRef:b}=Vg(n,h,f,e?gr:a,p,m,o,g,ke("skipAnimationFrameInResizeObserver")),[v,y]=x.useState(0);Ai("deviation",$=>{v!==$&&y($)});const T=ke("EmptyPlaceholder"),I=ke("ScrollSeekPlaceholder")||Ax,k=ke("ListComponent"),S=ke("ItemComponent"),E=ke("GroupComponent"),j=ke("computeItemKey"),_=ke("isSeeking"),D=ke("groupIndices").length>0,L=ke("alignToBottom"),W=ke("initialItemFinalLocationReached"),V=e?{}:{boxSizing:"border-box",...g?{display:"inline-block",height:"100%",marginLeft:v!==0?v:L?"auto":0,paddingLeft:t.offsetTop,paddingRight:t.offsetBottom,whiteSpace:"nowrap"}:{marginTop:v!==0?v:L?"auto":0,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...W?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&T?d.jsx(T,{...yt(T,l)}):d.jsx(k,{...yt(k,l),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:b,style:V,children:(e?t.topItems:t.items).map($=>{const Z=$.originalIndex,X=j(Z+t.firstItemIndex,$.data,l);return _?x.createElement(I,{...yt(I,l),height:$.size,index:$.index,key:X,type:$.type||"item",...$.type==="group"?{}:{groupIndex:$.groupIndex}}):$.type==="group"?x.createElement(E,{...yt(E,l),"data-index":Z,"data-item-index":$.index,"data-known-size":$.size,key:X,style:Nx},u($.index,l)):x.createElement(S,{...yt(S,l),...Rx(S,$.data),"data-index":Z,"data-item-group-index":$.groupIndex,"data-item-index":$.index,"data-known-size":$.size,key:X,style:g?_x:mu},D?c($.index,$.groupIndex,$.data,l):c($.index,$.data,l))})})}),jx={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},Px={outline:"none",overflowX:"auto",position:"relative"},Wo=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:{}}),Ox={position:Ei(),top:0,width:"100%",zIndex:1};function yt(e,t){if(typeof e!="string")return{context:t}}function Rx(e,t){return{item:typeof e=="string"?void 0:t}}const Mx=x.memo(function(){const e=ke("HeaderComponent"),t=Yt("headerHeight"),n=ke("HeaderFooterTag"),r=Gn(x.useMemo(()=>s=>{t(jn(s,"height"))},[t]),!0,ke("skipAnimationFrameInResizeObserver")),o=ke("context");return e?d.jsx(n,{ref:r,children:d.jsx(e,{...yt(e,o)})}):null}),Dx=x.memo(function(){const e=ke("FooterComponent"),t=Yt("footerHeight"),n=ke("HeaderFooterTag"),r=Gn(x.useMemo(()=>s=>{t(jn(s,"height"))},[t]),!0,ke("skipAnimationFrameInResizeObserver")),o=ke("context");return e?d.jsx(n,{ref:r,children:d.jsx(e,{...yt(e,o)})}):null});function xu({useEmitter:e,useEmitterValue:t,usePublisher:n}){return x.memo(function({children:r,style:o,context:s,...i}){const a=n("scrollContainerState"),c=t("ScrollerComponent"),l=n("smoothScrollTargetReached"),u=t("scrollerRef"),f=t("horizontalDirection")||!1,{scrollByCallback:h,scrollerRef:p,scrollToCallback:m}=hu(a,l,c,u,void 0,f);return e("scrollTo",m),e("scrollBy",h),d.jsx(c,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:p,style:{...f?Px:jx,...o},tabIndex:0,...i,...yt(c,s),children:r})})}function bu({useEmitter:e,useEmitterValue:t,usePublisher:n}){return x.memo(function({children:r,style:o,context:s,...i}){const a=n("windowScrollContainerState"),c=t("ScrollerComponent"),l=n("smoothScrollTargetReached"),u=t("totalListHeight"),f=t("deviation"),h=t("customScrollParent"),p=x.useRef(null),m=t("scrollerRef"),{scrollByCallback:g,scrollerRef:b,scrollToCallback:v}=hu(a,l,c,m,h);return fu(()=>{var y;return b.current=h||((y=p.current)==null?void 0:y.ownerDocument.defaultView),()=>{b.current=null}},[b,h]),e("windowScrollTo",v),e("scrollBy",g),d.jsx(c,{ref:p,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...u!==0?{height:u+f}:{}},...i,...yt(c,s),children:r})})}const Lx=({children:e})=>{const t=x.useContext(uu),n=Yt("viewportHeight"),r=Yt("fixedItemHeight"),o=ke("alignToBottom"),s=ke("horizontalDirection"),i=x.useMemo(()=>jc(n,c=>jn(c,s?"width":"height")),[n,s]),a=Gn(i,!0,ke("skipAnimationFrameInResizeObserver"));return x.useEffect(()=>{t&&(n(t.viewportHeight),r(t.itemHeight))},[t,n,r]),d.jsx("div",{"data-viewport-type":"element",ref:a,style:Wo(o),children:e})},$x=({children:e})=>{const t=x.useContext(uu),n=Yt("windowViewportRect"),r=Yt("fixedItemHeight"),o=ke("customScrollParent"),s=Dc(n,o,ke("skipAnimationFrameInResizeObserver")),i=ke("alignToBottom");return x.useEffect(()=>{t&&(r(t.itemHeight),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:100}))},[t,n,r]),d.jsx("div",{"data-viewport-type":"window",ref:s,style:Wo(i),children:e})},Fx=({children:e})=>{const t=ke("TopItemListComponent")||"div",n=ke("headerHeight"),r={...Ox,marginTop:`${n}px`},o=ke("context");return d.jsx(t,{style:r,...yt(t,o),children:e})},zx=x.memo(function(e){const t=ke("useWindowScroll"),n=ke("topItemsIndexes").length>0,r=ke("customScrollParent"),o=ke("context");return d.jsxs(r||t?Ux:Hx,{...e,context:o,children:[n&&d.jsx(Fx,{children:d.jsx(gu,{showTopList:!0})}),d.jsxs(r||t?$x:Lx,{children:[d.jsx(Mx,{}),d.jsx(gu,{}),d.jsx(Dx,{})]})]})}),{Component:Bx,useEmitter:Ai,useEmitterValue:ke,usePublisher:Yt}=cu(Ix,{required:{},optional:{restoreStateFrom:"restoreStateFrom",context:"context",followOutput:"followOutput",scrollIntoViewOnChange:"scrollIntoViewOnChange",itemContent:"itemContent",groupContent:"groupContent",overscan:"overscan",increaseViewportBy:"increaseViewportBy",totalCount:"totalCount",groupCounts:"groupCounts",topItemCount:"topItemCount",firstItemIndex:"firstItemIndex",initialTopMostItemIndex:"initialTopMostItemIndex",components:"components",atBottomThreshold:"atBottomThreshold",atTopThreshold:"atTopThreshold",computeItemKey:"computeItemKey",defaultItemHeight:"defaultItemHeight",fixedItemHeight:"fixedItemHeight",itemSize:"itemSize",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"HeaderFooterTag",data:"data",initialItemCount:"initialItemCount",initialScrollTop:"initialScrollTop",alignToBottom:"alignToBottom",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",horizontalDirection:"horizontalDirection",skipAnimationFrameInResizeObserver:"skipAnimationFrameInResizeObserver"},methods:{scrollToIndex:"scrollToIndex",scrollIntoView:"scrollIntoView",scrollTo:"scrollTo",scrollBy:"scrollBy",autoscrollToBottom:"autoscrollToBottom",getState:"getState"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",totalListHeightChanged:"totalListHeightChanged",itemsRendered:"itemsRendered",groupIndices:"groupIndices"}},zx),Hx=xu({useEmitter:Ai,useEmitterValue:ke,usePublisher:Yt}),Ux=bu({useEmitter:Ai,useEmitterValue:ke,usePublisher:Yt}),Wx=Bx;Xe(lu,Re(()=>{const e=re(l=>d.jsxs("td",{children:["Item $",l]})),t=re(null),n=re(l=>d.jsxs("td",{colSpan:1e3,children:["Group ",l]})),r=re(null),o=re(null),s=re({}),i=re(Ii),a=re(gr),c=(l,u=null)=>vt(ee(s,ce(f=>f[l]),Je()),u);return{components:s,computeItemKey:i,context:t,EmptyPlaceholder:c("EmptyPlaceholder"),FillerRow:c("FillerRow"),fixedFooterContent:o,fixedHeaderContent:r,itemContent:e,groupContent:n,ScrollerComponent:c("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:c("ScrollSeekPlaceholder"),TableBodyComponent:c("TableBody","tbody"),TableComponent:c("Table","table"),TableFooterComponent:c("TableFoot","tfoot"),TableHeadComponent:c("TableHead","thead"),TableRowComponent:c("TableRow","tr"),GroupComponent:c("Group","tr")}})),Ei();const wu={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},Vx={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:vu,floor:Vo,max:to,min:Ni,round:yu}=Math;function Su(e,t,n){return Array.from({length:t-e+1}).map((r,o)=>({data:n===null?null:n[o+e],index:o+e}))}function Kx(e){return{...Vx,items:e}}function Ko(e,t){return e&&e.width===t.width&&e.height===t.height}function qx(e,t){return e&&e.column===t.column&&e.row===t.row}const Gx=Re(([{increaseViewportBy:e,listBoundary:t,overscan:n,visibleRange:r},{footerHeight:o,headerHeight:s,scrollBy:i,scrollContainerState:a,scrollTo:c,scrollTop:l,smoothScrollTargetReached:u,viewportHeight:f},h,p,{didMount:m,propsReady:g},{customScrollParent:b,useWindowScroll:v,windowScrollContainerState:y,windowScrollTo:T,windowViewportRect:I},k])=>{const S=re(0),E=re(0),j=re(wu),_=re({height:0,width:0}),D=re({height:0,width:0}),L=Oe(),W=Oe(),V=re(0),$=re(null),Z=re({column:0,row:0}),X=Oe(),oe=Oe(),U=re(!1),F=re(0),G=re(!0),H=re(!1),A=re(!1);De(ee(m,Ne(F),ye(([P,K])=>!!K)),()=>{Ae(G,!1)}),De(ee(ft(m,G,D,_,F,H),ye(([P,K,te,le,,he])=>P&&!K&&te.height!==0&&le.height!==0&&!he)),([,,,,P])=>{Ae(H,!0),wi(1,()=>{Ae(L,P)}),tn(ee(l),()=>{Ae(t,[0,0]),Ae(G,!0)})}),me(ee(oe,ye(P=>P!=null&&P.scrollTop>0),un(0)),E),De(ee(m,Ne(oe),ye(([,P])=>P!=null)),([,P])=>{P&&(Ae(_,P.viewport),Ae(D,P.item),Ae(Z,P.gap),P.scrollTop>0&&(Ae(U,!0),tn(ee(l,qn(1)),K=>{Ae(U,!1)}),Ae(c,{top:P.scrollTop})))}),me(ee(_,ce(({height:P})=>P)),f),me(ee(ft(ve(_,Ko),ve(D,Ko),ve(Z,(P,K)=>P&&P.column===K.column&&P.row===K.row),ve(l)),ce(([P,K,te,le])=>({gap:te,item:K,scrollTop:le,viewport:P}))),X),me(ee(ft(ve(S),r,ve(Z,qx),ve(D,Ko),ve(_,Ko),ve($),ve(E),ve(U),ve(G),ve(F)),ye(([,,,,,,,P])=>!P),ce(([P,[K,te],le,he,ue,ge,be,,Be,Le])=>{const{column:je,row:Fe}=le,{height:tt,width:mt}=he,{width:ot}=ue;if(be===0&&(P===0||ot===0))return wu;if(mt===0){const st=vi(Le,P),an=st+Math.max(be-1,0);return Kx(Su(st,an,ge))}const ze=Cu(ot,mt,je);let Me,Ze;Be?K===0&&te===0&&be>0?(Me=0,Ze=be-1):(Me=ze*Vo((K+Fe)/(tt+Fe)),Ze=ze*vu((te+Fe)/(tt+Fe))-1,Ze=Ni(P-1,to(Ze,ze-1)),Me=Ni(Ze,to(0,Me))):(Me=0,Ze=-1);const rt=Su(Me,Ze,ge),{bottom:qe,top:ht}=ku(ue,le,he,rt),xt=vu(P/ze),He=xt*tt+(xt-1)*Fe-qe;return{bottom:qe,itemHeight:tt,items:rt,itemWidth:mt,offsetBottom:He,offsetTop:ht,top:ht}})),j),me(ee($,ye(P=>P!==null),ce(P=>P.length)),S),me(ee(ft(_,D,j,Z),ye(([P,K,{items:te}])=>te.length>0&&K.height!==0&&P.height!==0),ce(([P,K,{items:te},le])=>{const{bottom:he,top:ue}=ku(P,le,K,te);return[ue,he]}),Je(Gr)),t);const N=re(!1);me(ee(l,Ne(N),ce(([P,K])=>K||P!==0)),N);const R=Ht(ee(ft(j,S),ye(([{items:P}])=>P.length>0),Ne(N),ye(([[P,K],te])=>{const le=P.items[P.items.length-1].index===K-1;return(te||P.bottom>0&&P.itemHeight>0&&P.offsetBottom===0&&P.items.length===K)&&le}),ce(([[,P]])=>P-1),Je())),M=Ht(ee(ve(j),ye(({items:P})=>P.length>0&&P[0].index===0),un(0),Je())),q=Ht(ee(ve(j),Ne(U),ye(([{items:P},K])=>P.length>0&&!K),ce(([{items:P}])=>({endIndex:P[P.length-1].index,startIndex:P[0].index})),Je(Uc),yn(0)));me(q,p.scrollSeekRangeChanged),me(ee(L,Ne(_,D,S,Z),ce(([P,K,te,le,he])=>{const ue=Yc(P),{align:ge,behavior:be,offset:Be}=ue;let Le=ue.index;Le==="LAST"&&(Le=le-1),Le=to(0,Le,Ni(le-1,Le));let je=_i(K,he,te,Le);return ge==="end"?je=yu(je-K.height+te.height):ge==="center"&&(je=yu(je-K.height/2+te.height/2)),Be&&(je+=Be),{behavior:be,top:je}})),c);const J=vt(ee(j,ce(P=>P.offsetBottom+P.bottom)),0);return me(ee(I,ce(P=>({height:P.visibleHeight,width:P.visibleWidth}))),_),{customScrollParent:b,data:$,deviation:V,footerHeight:o,gap:Z,headerHeight:s,increaseViewportBy:e,initialItemCount:E,itemDimensions:D,overscan:n,restoreStateFrom:oe,scrollBy:i,scrollContainerState:a,scrollHeight:W,scrollTo:c,scrollToIndex:L,scrollTop:l,smoothScrollTargetReached:u,totalCount:S,useWindowScroll:v,viewportDimensions:_,windowScrollContainerState:y,windowScrollTo:T,windowViewportRect:I,...p,gridState:j,horizontalDirection:A,initialTopMostItemIndex:F,totalListHeight:J,...h,endReached:R,propsReady:g,rangeChanged:q,startReached:M,stateChanged:X,stateRestoreInProgress:U,...k}},Xe(yi,Nt,eo,iu,Pn,Ci,_n));function Cu(e,t,n){return to(1,Vo((e+n)/(Vo(t)+n)))}function ku(e,t,n,r){const{height:o}=n;if(o===void 0||r.length===0)return{bottom:0,top:0};const s=_i(e,t,n,r[0].index);return{bottom:_i(e,t,n,r[r.length-1].index)+o,top:s}}function _i(e,t,n,r){const o=Cu(e.width,n.width,t.column),s=Vo(r/o),i=s*n.height+to(0,s-1)*t.row;return i>0?i+t.row:i}const Yx=Re(()=>{const e=re(f=>`Item ${f}`),t=re({}),n=re(null),r=re("virtuoso-grid-item"),o=re("virtuoso-grid-list"),s=re(Ii),i=re("div"),a=re(gr),c=(f,h=null)=>vt(ee(t,ce(p=>p[f]),Je()),h),l=re(!1),u=re(!1);return me(ve(u),l),{components:t,computeItemKey:s,context:n,FooterComponent:c("Footer"),HeaderComponent:c("Header"),headerFooterTag:i,itemClassName:r,ItemComponent:c("Item","div"),itemContent:e,listClassName:o,ListComponent:c("List","div"),readyStateChanged:l,reportReadyState:u,ScrollerComponent:c("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:c("ScrollSeekPlaceholder","div")}}),Xx=Re(([e,t])=>({...e,...t}),Xe(Gx,Yx)),Jx=x.memo(function(){const e=Qe("gridState"),t=Qe("listClassName"),n=Qe("itemClassName"),r=Qe("itemContent"),o=Qe("computeItemKey"),s=Qe("isSeeking"),i=Xt("scrollHeight"),a=Qe("ItemComponent"),c=Qe("ListComponent"),l=Qe("ScrollSeekPlaceholder"),u=Qe("context"),f=Xt("itemDimensions"),h=Xt("gap"),p=Qe("log"),m=Qe("stateRestoreInProgress"),g=Xt("reportReadyState"),b=Gn(x.useMemo(()=>v=>{const y=v.parentElement.parentElement.scrollHeight;i(y);const T=v.firstChild;if(T){const{height:I,width:k}=T.getBoundingClientRect();f({height:I,width:k})}h({column:Eu("column-gap",getComputedStyle(v).columnGap,p),row:Eu("row-gap",getComputedStyle(v).rowGap,p)})},[i,f,h,p]),!0,!1);return fu(()=>{e.itemHeight>0&&e.itemWidth>0&&g(!0)},[e]),m?null:d.jsx(c,{className:t,ref:b,...yt(c,u),"data-testid":"virtuoso-item-list",style:{paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},children:e.items.map(v=>{const y=o(v.index,v.data,u);return s?d.jsx(l,{...yt(l,u),height:e.itemHeight,index:v.index,width:e.itemWidth},y):x.createElement(a,{...yt(a,u),className:n,"data-index":v.index,key:y},r(v.index,v.data,u))})})}),Zx=x.memo(function(){const e=Qe("HeaderComponent"),t=Xt("headerHeight"),n=Qe("headerFooterTag"),r=Gn(x.useMemo(()=>s=>{t(jn(s,"height"))},[t]),!0,!1),o=Qe("context");return e?d.jsx(n,{ref:r,children:d.jsx(e,{...yt(e,o)})}):null}),Qx=x.memo(function(){const e=Qe("FooterComponent"),t=Xt("footerHeight"),n=Qe("headerFooterTag"),r=Gn(x.useMemo(()=>s=>{t(jn(s,"height"))},[t]),!0,!1),o=Qe("context");return e?d.jsx(n,{ref:r,children:d.jsx(e,{...yt(e,o)})}):null}),eb=({children:e})=>{const t=x.useContext(du),n=Xt("itemDimensions"),r=Xt("viewportDimensions"),o=Gn(x.useMemo(()=>s=>{r(s.getBoundingClientRect())},[r]),!0,!1);return x.useEffect(()=>{t&&(r({height:t.viewportHeight,width:t.viewportWidth}),n({height:t.itemHeight,width:t.itemWidth}))},[t,r,n]),d.jsx("div",{ref:o,style:Wo(!1),children:e})},tb=({children:e})=>{const t=x.useContext(du),n=Xt("windowViewportRect"),r=Xt("itemDimensions"),o=Qe("customScrollParent"),s=Dc(n,o,!1);return x.useEffect(()=>{t&&(r({height:t.itemHeight,width:t.itemWidth}),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:t.viewportWidth}))},[t,n,r]),d.jsx("div",{ref:s,style:Wo(!1),children:e})},nb=x.memo(function({...e}){const t=Qe("useWindowScroll"),n=Qe("customScrollParent"),r=n||t?ob:rb,o=n||t?tb:eb,s=Qe("context");return d.jsx(r,{...e,...yt(r,s),children:d.jsxs(o,{children:[d.jsx(Zx,{}),d.jsx(Jx,{}),d.jsx(Qx,{})]})})}),{useEmitter:Tu,useEmitterValue:Qe,usePublisher:Xt}=cu(Xx,{optional:{context:"context",totalCount:"totalCount",overscan:"overscan",itemContent:"itemContent",components:"components",computeItemKey:"computeItemKey",data:"data",initialItemCount:"initialItemCount",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"headerFooterTag",listClassName:"listClassName",itemClassName:"itemClassName",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",restoreStateFrom:"restoreStateFrom",initialTopMostItemIndex:"initialTopMostItemIndex",increaseViewportBy:"increaseViewportBy"},methods:{scrollTo:"scrollTo",scrollBy:"scrollBy",scrollToIndex:"scrollToIndex"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",stateChanged:"stateChanged",readyStateChanged:"readyStateChanged"}},nb),rb=xu({useEmitter:Tu,useEmitterValue:Qe,usePublisher:Xt}),ob=bu({useEmitter:Tu,useEmitterValue:Qe,usePublisher:Xt});function Eu(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,Dt.WARN),t==="normal"?0:parseInt(t??"0",10)}function Se(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function Iu(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function On(...e){return t=>{let n=!1;const r=e.map(o=>{const s=Iu(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():Iu(e[o],null)}}}}function et(...e){return w.useCallback(On(...e),e)}function sb(e,t){const n=w.createContext(t),r=s=>{const{children:i,...a}=s,c=w.useMemo(()=>a,Object.values(a));return d.jsx(n.Provider,{value:c,children:i})};r.displayName=e+"Provider";function o(s){const i=w.useContext(n);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function Rn(e,t=[]){let n=[];function r(s,i){const a=w.createContext(i),c=n.length;n=[...n,i];const l=f=>{var v;const{scope:h,children:p,...m}=f,g=((v=h==null?void 0:h[e])==null?void 0:v[c])||a,b=w.useMemo(()=>m,Object.values(m));return d.jsx(g.Provider,{value:b,children:p})};l.displayName=s+"Provider";function u(f,h){var g;const p=((g=h==null?void 0:h[e])==null?void 0:g[c])||a,m=w.useContext(p);if(m)return m;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[l,u]}const o=()=>{const s=n.map(i=>w.createContext(i));return function(a){const c=(a==null?void 0:a[e])||s;return w.useMemo(()=>({[`__scope${e}`]:{...a,[e]:c}}),[a,c])}};return o.scopeName=e,[r,ib(o,...t)]}function ib(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:c,scopeName:l})=>{const f=c(s)[`__scope${l}`];return{...a,...f}},{});return w.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var hn=globalThis!=null&&globalThis.document?w.useLayoutEffect:()=>{},ab=w[" useId ".trim().toString()]||(()=>{}),lb=0;function Wt(e){const[t,n]=w.useState(ab());return hn(()=>{n(r=>r??String(lb++))},[e]),e||(t?`radix-${t}`:"")}var cb=w[" useInsertionEffect ".trim().toString()]||hn;function qo({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=ub({defaultProp:t,onChange:n}),a=e!==void 0,c=a?e:o;{const u=w.useRef(e!==void 0);w.useEffect(()=>{const f=u.current;f!==a&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=a},[a,r])}const l=w.useCallback(u=>{var f;if(a){const h=db(u)?u(e):u;h!==e&&((f=i.current)==null||f.call(i,h))}else s(u)},[a,e,s,i]);return[c,l]}function ub({defaultProp:e,onChange:t}){const[n,r]=w.useState(e),o=w.useRef(n),s=w.useRef(t);return cb(()=>{s.current=t},[t]),w.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function db(e){return typeof e=="function"}var fb=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Pe=fb.reduce((e,t)=>{const n=sr.createSlot(`Primitive.${t}`),r=w.forwardRef((o,s)=>{const{asChild:i,...a}=o,c=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),d.jsx(c,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Au(e,t){e&&Ja.flushSync(()=>e.dispatchEvent(t))}function St(e){const t=w.useRef(e);return w.useEffect(()=>{t.current=e}),w.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function hb(e,t=globalThis==null?void 0:globalThis.document){const n=St(e);w.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var pb="DismissableLayer",ji="dismissableLayer.update",mb="dismissableLayer.pointerDownOutside",gb="dismissableLayer.focusOutside",Nu,_u=w.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Pi=w.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...c}=e,l=w.useContext(_u),[u,f]=w.useState(null),h=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=w.useState({}),m=et(t,E=>f(E)),g=Array.from(l.layers),[b]=[...l.layersWithOutsidePointerEventsDisabled].slice(-1),v=g.indexOf(b),y=u?g.indexOf(u):-1,T=l.layersWithOutsidePointerEventsDisabled.size>0,I=y>=v,k=wb(E=>{const j=E.target,_=[...l.branches].some(D=>D.contains(j));!I||_||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},h),S=vb(E=>{const j=E.target;[...l.branches].some(D=>D.contains(j))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},h);return hb(E=>{y===l.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},h),w.useEffect(()=>{if(u)return n&&(l.layersWithOutsidePointerEventsDisabled.size===0&&(Nu=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),l.layersWithOutsidePointerEventsDisabled.add(u)),l.layers.add(u),ju(),()=>{n&&l.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=Nu)}},[u,h,n,l]),w.useEffect(()=>()=>{u&&(l.layers.delete(u),l.layersWithOutsidePointerEventsDisabled.delete(u),ju())},[u,l]),w.useEffect(()=>{const E=()=>p({});return document.addEventListener(ji,E),()=>document.removeEventListener(ji,E)},[]),d.jsx(Pe.div,{...c,ref:m,style:{pointerEvents:T?I?"auto":"none":void 0,...e.style},onFocusCapture:Se(e.onFocusCapture,S.onFocusCapture),onBlurCapture:Se(e.onBlurCapture,S.onBlurCapture),onPointerDownCapture:Se(e.onPointerDownCapture,k.onPointerDownCapture)})});Pi.displayName=pb;var xb="DismissableLayerBranch",bb=w.forwardRef((e,t)=>{const n=w.useContext(_u),r=w.useRef(null),o=et(t,r);return w.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),d.jsx(Pe.div,{...e,ref:o})});bb.displayName=xb;function wb(e,t=globalThis==null?void 0:globalThis.document){const n=St(e),r=w.useRef(!1),o=w.useRef(()=>{});return w.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let c=function(){Pu(mb,n,l,{discrete:!0})};const l={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=c,t.addEventListener("click",o.current,{once:!0})):c()}else t.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function vb(e,t=globalThis==null?void 0:globalThis.document){const n=St(e),r=w.useRef(!1);return w.useEffect(()=>{const o=s=>{s.target&&!r.current&&Pu(gb,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function ju(){const e=new CustomEvent(ji);document.dispatchEvent(e)}function Pu(e,t,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?Au(o,s):o.dispatchEvent(s)}var Oi="focusScope.autoFocusOnMount",Ri="focusScope.autoFocusOnUnmount",Ou={bubbles:!1,cancelable:!0},yb="FocusScope",Mi=w.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,c]=w.useState(null),l=St(o),u=St(s),f=w.useRef(null),h=et(t,g=>c(g)),p=w.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;w.useEffect(()=>{if(r){let g=function(T){if(p.paused||!a)return;const I=T.target;a.contains(I)?f.current=I:Mn(f.current,{select:!0})},b=function(T){if(p.paused||!a)return;const I=T.relatedTarget;I!==null&&(a.contains(I)||Mn(f.current,{select:!0}))},v=function(T){if(document.activeElement===document.body)for(const k of T)k.removedNodes.length>0&&Mn(a)};document.addEventListener("focusin",g),document.addEventListener("focusout",b);const y=new MutationObserver(v);return a&&y.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",b),y.disconnect()}}},[r,a,p.paused]),w.useEffect(()=>{if(a){Du.add(p);const g=document.activeElement;if(!a.contains(g)){const v=new CustomEvent(Oi,Ou);a.addEventListener(Oi,l),a.dispatchEvent(v),v.defaultPrevented||(Sb(Ib(Ru(a)),{select:!0}),document.activeElement===g&&Mn(a))}return()=>{a.removeEventListener(Oi,l),setTimeout(()=>{const v=new CustomEvent(Ri,Ou);a.addEventListener(Ri,u),a.dispatchEvent(v),v.defaultPrevented||Mn(g??document.body,{select:!0}),a.removeEventListener(Ri,u),Du.remove(p)},0)}}},[a,l,u,p]);const m=w.useCallback(g=>{if(!n&&!r||p.paused)return;const b=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,v=document.activeElement;if(b&&v){const y=g.currentTarget,[T,I]=Cb(y);T&&I?!g.shiftKey&&v===I?(g.preventDefault(),n&&Mn(T,{select:!0})):g.shiftKey&&v===T&&(g.preventDefault(),n&&Mn(I,{select:!0})):v===y&&g.preventDefault()}},[n,r,p.paused]);return d.jsx(Pe.div,{tabIndex:-1,...i,ref:h,onKeyDown:m})});Mi.displayName=yb;function Sb(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Mn(r,{select:t}),document.activeElement!==n)return}function Cb(e){const t=Ru(e),n=Mu(t,e),r=Mu(t.reverse(),e);return[n,r]}function Ru(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Mu(e,t){for(const n of e)if(!kb(n,{upTo:t}))return n}function kb(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function Tb(e){return e instanceof HTMLInputElement&&"select"in e}function Mn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Tb(e)&&t&&e.select()}}var Du=Eb();function Eb(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Lu(e,t),e.unshift(t)},remove(t){var n;e=Lu(e,t),(n=e[0])==null||n.resume()}}}function Lu(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function Ib(e){return e.filter(t=>t.tagName!=="A")}var Ab="Portal",Di=w.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=w.useState(!1);hn(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Ls.createPortal(d.jsx(Pe.div,{...r,ref:t}),i):null});Di.displayName=Ab;function Nb(e,t){return w.useReducer((n,r)=>t[n][r]??n,e)}var Vt=e=>{const{present:t,children:n}=e,r=_b(t),o=typeof n=="function"?n({present:r.isPresent}):w.Children.only(n),s=et(r.ref,jb(o));return typeof n=="function"||r.isPresent?w.cloneElement(o,{ref:s}):null};Vt.displayName="Presence";function _b(e){const[t,n]=w.useState(),r=w.useRef(null),o=w.useRef(e),s=w.useRef("none"),i=e?"mounted":"unmounted",[a,c]=Nb(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return w.useEffect(()=>{const l=Go(r.current);s.current=a==="mounted"?l:"none"},[a]),hn(()=>{const l=r.current,u=o.current;if(u!==e){const h=s.current,p=Go(l);e?c("MOUNT"):p==="none"||(l==null?void 0:l.display)==="none"?c("UNMOUNT"):c(u&&h!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,c]),hn(()=>{if(t){let l;const u=t.ownerDocument.defaultView??window,f=p=>{const g=Go(r.current).includes(CSS.escape(p.animationName));if(p.target===t&&g&&(c("ANIMATION_END"),!o.current)){const b=t.style.animationFillMode;t.style.animationFillMode="forwards",l=u.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=b)})}},h=p=>{p.target===t&&(s.current=Go(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{u.clearTimeout(l),t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:w.useCallback(l=>{r.current=l?getComputedStyle(l):null,n(l)},[])}}function Go(e){return(e==null?void 0:e.animationName)||"none"}function jb(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Li=0;function $u(){w.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Fu()),document.body.insertAdjacentElement("beforeend",e[1]??Fu()),Li++,()=>{Li===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Li--}},[])}function Fu(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var pn=function(){return pn=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},pn.apply(this,arguments)};function zu(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function Pb(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}typeof SuppressedError=="function"&&SuppressedError;var Yo="right-scroll-bar-position",Xo="width-before-scroll-bar",Ob="with-scroll-bars-hidden",Rb="--removed-body-scroll-bar-size";function $i(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function Mb(e,t){var n=x.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var Db=typeof window<"u"?w.useLayoutEffect:w.useEffect,Bu=new WeakMap;function Lb(e,t){var n=Mb(null,function(r){return e.forEach(function(o){return $i(o,r)})});return Db(function(){var r=Bu.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||$i(a,null)}),s.forEach(function(a){o.has(a)||$i(a,i)})}Bu.set(n,e)},[e]),n}function $b(e){return e}function Fb(e,t){t===void 0&&(t=$b);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(s){var i=t(s,r);return n.push(i),function(){n=n.filter(function(a){return a!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var a=n;n=[],a.forEach(s),i=n}var c=function(){var u=i;i=[],u.forEach(s)},l=function(){return Promise.resolve().then(c)};l(),n={push:function(u){i.push(u),l()},filter:function(u){return i=i.filter(u),n}}}};return o}function zb(e){e===void 0&&(e={});var t=Fb(null);return t.options=pn({async:!0,ssr:!1},e),t}var Hu=function(e){var t=e.sideCar,n=zu(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return w.createElement(r,pn({},n))};Hu.isSideCarExport=!0;function Bb(e,t){return e.useMedium(t),Hu}var Uu=zb(),Fi=function(){},Jo=w.forwardRef(function(e,t){var n=w.useRef(null),r=w.useState({onScrollCapture:Fi,onWheelCapture:Fi,onTouchMoveCapture:Fi}),o=r[0],s=r[1],i=e.forwardProps,a=e.children,c=e.className,l=e.removeScrollBar,u=e.enabled,f=e.shards,h=e.sideCar,p=e.noRelative,m=e.noIsolation,g=e.inert,b=e.allowPinchZoom,v=e.as,y=v===void 0?"div":v,T=e.gapMode,I=zu(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=h,S=Lb([n,t]),E=pn(pn({},I),o);return w.createElement(w.Fragment,null,u&&w.createElement(k,{sideCar:Uu,removeScrollBar:l,shards:f,noRelative:p,noIsolation:m,inert:g,setCallbacks:s,allowPinchZoom:!!b,lockRef:n,gapMode:T}),i?w.cloneElement(w.Children.only(a),pn(pn({},E),{ref:S})):w.createElement(y,pn({},E,{className:c,ref:S}),a))});Jo.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},Jo.classNames={fullWidth:Xo,zeroRight:Yo};var Hb=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Ub(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Hb();return t&&e.setAttribute("nonce",t),e}function Wb(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Vb(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Kb=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Ub())&&(Wb(t,n),Vb(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},qb=function(){var e=Kb();return function(t,n){w.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Wu=function(){var e=qb(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Gb={left:0,top:0,right:0,gap:0},zi=function(e){return parseInt(e||"",10)||0},Yb=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[zi(n),zi(r),zi(o)]},Xb=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Gb;var t=Yb(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},Jb=Wu(),br="data-scroll-locked",Zb=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
38
+ `);if(!ln)continue;let Y;try{Y=JSON.parse(ln)}catch{console.debug("[use-chat] malformed SSE:",ln.slice(0,200));continue}vn&&typeof Y=="object"&&Y!==null&&!("type"in Y)&&(Y.type=vn);const fe=Zl(Y)?Y.data:Y;if(!fe){console.warn("[use-chat] dropped envelope event without payload",Y);continue}const Q=fe;gt=Date.now(),Q.type==="values"&&(Q.type="state_history"),Q.type==="metadata"&&(Q.title||Q.createdAt)&&(Q.type="thread_info");const C=Q.seq;if(C!==void 0){if(C<=kt){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:C,lastProcessedSeq:kt,type:Q.type});continue}kt>0&&C>kt+1&&((ge=N==null?void 0:N.onGap)==null||ge.call(N,{from:kt,to:C})),kt=C,L.current=C,b(C)}if(Q.type==="checkpoint")V.current=Q.checkpointId??null,$.current=Q.checkpointNs??null,m(Q.checkpointId??null);else if(Q.type==="state_history"){Z.current=Q;try{const z=cr(Q).latest;z&&(V.current=z.checkpointId??null,$.current=z.checkpointNs??null,m(z.checkpointId??null),j(z.values??{}))}catch(O){console.warn("[use-chat] Failed to hydrate state_history payload",O)}}try{A==null||A(Q)}catch(O){console.error("[use-chat] Error in onEvent callback:",O,"for event:",Q.type)}try{Q.type==="tool.start"&&(N!=null&&N.onToolStart)?N.onToolStart(Q):Q.type==="tool.end"&&(N!=null&&N.onToolEnd)?N.onToolEnd(Q):Q.type==="token"&&(N!=null&&N.onToken)?N.onToken(Q.token):Q.type==="thread_info"&&(N!=null&&N.onThreadInfo)&&N.onThreadInfo(Q)}catch(O){console.warn("[use-chat] Typed callback error:",O)}if(Q.type==="messages/partial"){const z=Q.messages;if(Array.isArray(z)&&z.length>0){const se=z.find(ie=>ie.type==="ai");if(se){const ie=se.id,Ce=se.content??"",Te=se.response_metadata??{};if(X.current.messageId!==ie){const nt=Te.model_name??Te.model_provider??"assistant";X.current={messageId:ie,lastSeq:null,lastText:""};const Ye={id:ie,role:"assistant",name:nt,model:nt,createdAt:new Date().toISOString(),content:[{type:"text",text:Ce}]};I(it=>({...it,[ie]:Ye})),S(ie)}else I(nt=>{const Ye=nt[ie];return Ye?{...nt,[ie]:{...Ye,content:[{type:"text",text:Ce}]}}:nt});const _e=X.current.lastText||"";if(Ce.length>_e.length){const nt=Ce.slice(_e.length);X.current.lastText=Ce,e.autoAppendAssistant!==!1&&(ct.push(nt),Ge())}}}}else if(Q.type==="updates"){const O=Q;if(O.tools){const z=O.tools;if(z.status==="start"){const se={type:"tool.start",id:z.id,name:z.name,args:z.args,seq:O.seq,call_id:z.id};try{A==null||A(se)}catch(ie){console.error("[use-chat] Error in onEvent (tool.start polyfill):",ie)}}else if(z.status==="end"){const se={type:"tool.end",id:z.id,name:z.name,output:z.output,artifact:z.artifact,seq:O.seq,call_id:z.id};try{A==null||A(se)}catch(ie){console.error("[use-chat] Error in onEvent (tool.end polyfill):",ie)}}}continue}else if(Q.type==="heartbeat"){console.debug("[use-chat] heartbeat received");try{(be=N==null?void 0:N.onHeartbeat)==null||be.call(N,Q)}catch(O){console.warn("[use-chat] heartbeat callback failed",O)}}else if(Tt!==null&&cancelAnimationFrame(Tt),bt(),Q.type==="checkpoint")m(Q.checkpointId??null);else if(Q.type==="error"){const O=Q;if(u(O.message),M="error",q=O.message,O.error_type==="auth_error"||O.code==="TOKEN_EXPIRED"||((Be=O.message)==null?void 0:Be.includes("token"))||((Le=O.message)==null?void 0:Le.includes("401"))||((je=O.message)==null?void 0:je.includes("unauthorized"))||((Fe=O.message)==null?void 0:Fe.includes("Unauthorized"))){console.error("[use-chat] Auth error detected:",O.message);try{(tt=N==null?void 0:N.onAuthError)==null||tt.call(N,O.message)}catch(se){console.warn("[use-chat] onAuthError handler failed",se)}R.abort()}}}}bt(),M===null&&!R.signal.aborted&&(M="complete")}catch($e){if($e.name==="AbortError")M=M??"aborted";else{const Ee=$e.message||String($e);M="error",q=Ee,u(Ee),(mt=N==null?void 0:N.onError)==null||mt.call(N,Ee)}}finally{try{await st.cancel()}catch{}finally{(ot=st.releaseLock)==null||ot.call(st)}Tt!==null&&typeof window<"u"&&window.cancelAnimationFrame(Tt),clearInterval(ut)}}catch(rt){if(rt.name==="AbortError")M=M??"aborted";else{const qe=rt.message||String(rt);M="error",q=qe,u(qe),(ze=N==null?void 0:N.onError)==null||ze.call(N,qe),J||((Me=N==null?void 0:N.onConnectionError)==null||Me.call(N,qe),J=!0)}}finally{const rt=L.current,qe=V.current,ht=$.current,xt=Z.current,He=M??(R.signal.aborted?"aborted":q?"error":"complete");try{(Ze=N==null?void 0:N.onClosed)==null||Ze.call(N,{reason:He,lastSeq:rt,lastCheckpointId:qe,lastCheckpointNs:ht,lastStateHistory:xt,error:q})}catch(st){console.warn("[use-chat] onClosed callback failed",st)}c(!1),y(!1),_.current=null,L.current=0,b(0),W.current=null}})(),{close:()=>R.abort()}},[t,n,r,e.autoAppendAssistant]);return x.useEffect(()=>()=>{var H;D.current=!1,(H=_.current)==null||H.abort()},[]),{isStreaming:a,error:l,assistantText:f,activeMessageId:k,streamedMessages:T,lastCheckpointId:p,lastSeq:g,connected:v,stream:G,stop:F,clear:U,setToken:oe,values:E,interrupt:()=>Promise.resolve(),resume:()=>Promise.resolve(),goto:()=>Promise.resolve()}}const Jm=["detail","message","error","description","title"];function _o(e){if(!e)return null;if(typeof e=="string"){const t=e.trim();return t.length?t:null}if(Array.isArray(e)){for(const t of e){const n=_o(t);if(n)return n}return null}if(typeof e=="object"){const t=e;for(const n of Jm){const r=_o(t[n]);if(r)return r}if("errors"in t){const n=_o(t.errors);if(n)return n}}return null}function Zm(e){if(!e)return"Request failed";const t=e.response,n=_o(t==null?void 0:t.data);if(n)return n;if(t!=null&&t.statusText)return t.statusText;if(e instanceof Error&&e.message)return e.message;if(typeof e=="string"){const r=e.trim();if(r.length)return r}return t!=null&&t.status?`Request failed with status code ${t.status}`:"Request failed"}function Ql({api:e,initialThreadId:t=null,onError:n,onThreadChange:r,onCurrentThreadDeleted:o}){const[s,i]=x.useState([]),[a,c]=x.useState(t),[l,u]=x.useState(!1),[f,h]=x.useState(null),[p,m]=x.useState([]),[g,b]=x.useState(!1),[,v]=x.useState(null),[y,T]=x.useState(null),[I,k]=x.useState(!1),S=x.useRef(a),E=x.useRef(new Map);x.useEffect(()=>{S.current=a},[a]),x.useEffect(()=>{t!==void 0&&t!==S.current&&c(t)},[t]);const j=x.useCallback(async()=>{u(!0),h(null);try{const U=await e.listThreads();i(U??[])}catch(U){const F=String(U);h(F),n==null||n(F)}finally{u(!1)}},[e,n]),_=x.useCallback(async()=>{b(!0),v(null);try{const U=await e.listSharedThreads();m(U??[])}catch(U){const F=String(U);v(F),n==null||n(F)}finally{b(!1)}},[e,n]);x.useEffect(()=>{j()},[j]),x.useEffect(()=>{_()},[_]),x.useEffect(()=>{r==null||r(a)},[a,r]);const D=x.useCallback(async(U,F)=>{try{const G=F&&typeof F=="object"?{id:F.id,name:F.name??""}:void 0,H=await e.createThread(U,G);return c(H.threadId),await j(),H.threadId}catch(G){const H=String(G);return n==null||n(H),null}},[e,n,j]),L=x.useCallback(async U=>{const F=s;i(H=>H.filter(A=>A.threadId!==U));const G=new AbortController;E.current.set(U,G);try{await e.deleteThread(U),S.current===U&&(c(null),o==null||o())}catch(H){i(F);const A=String(H);n==null||n(A)}finally{E.current.delete(U)}},[e,o,n,s]),W=x.useCallback(async(U,F)=>{try{await e.updateThread(U,F),await j()}catch(G){n==null||n(String(G))}},[e,n,j]),V=x.useCallback(async(U,F)=>{k(!0),T("Sharing thread…");try{await e.shareThread(U,F),await _(),T("Shared successfully")}catch(G){const H=Zm(G);throw n==null||n(H),T(`Failed to share: ${H}`),new Error(H)}finally{k(!1)}},[e,n,_]),$=x.useCallback(async(U,F)=>{try{await e.unshareThread(U,F),await _()}catch(G){const H=String(G);throw n==null||n(H),G}},[e,n,_]),Z=x.useMemo(()=>({createThread:D,deleteThread:L,renameThread:W,refreshThreads:j,refreshSharedThreads:_,shareThread:V,unshareThread:$}),[D,L,W,j,_,V,$]),X=x.useCallback(U=>{if(!(U!=null&&U.threadId))return;const F={threadId:U.threadId,title:U.title||`Thread ${U.threadId.slice(0,8)}`,project:U.project,createdAt:U.createdAt||new Date().toISOString(),updatedAt:U.updatedAt||new Date().toISOString(),messageCount:U.messageCount??1};i(G=>{let H=!1;const A=G.map(N=>N.threadId===F.threadId?(H=!0,console.debug("[useThreadsState] thread_info: updating existing thread",F.threadId),{...N,title:F.title??N.title,project:F.project??N.project,updatedAt:F.updatedAt??N.updatedAt,messageCount:F.messageCount??N.messageCount}):N);return H?A:(console.debug("[useThreadsState] thread_info: adding thread to list",F.threadId),[F,...G])})},[]),oe=x.useCallback(()=>T(null),[]);return{threads:s,currentThreadId:a,currentThreadIdRef:S,setCurrentThreadId:c,isLoadingThreads:l,threadsError:f,sharedThreads:p,isLoadingSharedThreads:g,actions:Z,addThreadFromEvent:X,shareInFlight:I,shareStatus:y,clearShareStatus:oe}}const ec=x.createContext(null);function tc({children:e,initialThreadId:t=null,onError:n,onThreadChange:r}){const{chatApi:o}=Vn(),{threads:s,currentThreadId:i,setCurrentThreadId:a,currentThreadIdRef:c,isLoadingThreads:l,threadsError:u,sharedThreads:f,isLoadingSharedThreads:h,actions:p,addThreadFromEvent:m,shareInFlight:g,shareStatus:b,clearShareStatus:v}=Ql({api:o,initialThreadId:t,onError:n,onThreadChange:r}),y=x.useMemo(()=>({threads:s,currentThreadId:i,setCurrentThreadId:a,currentThreadIdRef:c,isLoading:l,error:u,sharedThreads:f,isLoadingSharedThreads:h,actions:p,shareInFlight:g,shareStatus:b,clearShareStatus:v,addThreadFromEvent:m}),[s,i,a,c,l,u,f,h,p,g,b,v,m]);return d.jsx(ec.Provider,{value:y,children:e})}function ur(){const e=x.useContext(ec);if(!e)throw new Error("useThreads must be used within a ThreadsProvider");return e}function dr(e){const t=e==null?void 0:e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return null;try{return JSON.parse(t)}catch{const n=Qm(t);if(n)try{return JSON.parse(n)}catch{return null}return null}}function Qm(e){let t=!1,n="";for(const o of e){if(o==="\\"){n+=o,t=!t;continue}if(o==="'"&&!t){n+='"';continue}n+=o,t=!1}return n.replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false").replace(/\bNone\b/g,"null")}function ti(e){return!!(e&&typeof e=="object"&&(e.type==="file"||e.mimeType||e.filename||e.sourceType==="base64"))}function zr(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){if(Array.isArray(e)){const n=e.map(zr).filter(r=>r!==void 0);if(!n.length){console.debug("[message-utils] sanitizeForDisplay - array emptied -> returning undefined",{originalLength:e.length});return}return n}if(ti(e)){try{console.debug("[message-utils] sanitizeForDisplay - dropping file-like object",{sampleFilename:e&&(e.filename||e.name)?e.filename||e.name:void 0,keys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - dropped file-like (unable to inspect)",{err:String(n)})}return}const t={};for(const n of Object.keys(e)){const r=e[n];if(n==="data"&&typeof r=="string"&&r.length>100)t[n]=`[base64 ${r.length} chars omitted]`;else{const o=zr(r);o!==void 0&&(t[n]=o)}}if(Object.keys(t).length)return t;try{console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined",{originalKeys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined (inspect failed)",{err:String(n)})}return}return e}function fr(e){if(typeof e=="string")return e;if(ti(e))return"";try{const t=zr(e);return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}catch{return""}}function nc(e){return typeof e!="string"?!1:/^[\s\n]*[-*]\s|^[\s\n]*#+\s|```|^\s*\[.*\]\(|^>\s/.test(e)}function eg(e){const t=fr(e);return typeof e=="string"&&nc(e)?{content:e,isMarkdown:!0}:{content:t,isMarkdown:!1}}function Br(e){if(e==null)return e;if(typeof e=="string"){const t=e.trim();if(t.startsWith("{")||t.startsWith("[")){const n=dr(t);if(n!==null)return Br(n)}return e}return typeof e=="object"&&!Array.isArray(e)&&e.content!==void 0?Br(e.content):e}function rc(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}function jo(e){return{toolCallId:(e.toolCallId||e.tool_call_id)??void 0,name:e.name??void 0}}function oc(e){if(e==null)return null;const t=String(e).trim();return t.length>0?t:null}function tg(e){const t=r=>{try{const o=zr(r);return typeof o=="string"?o:JSON.stringify(o??"")}catch{return""}},n=e.filter(r=>r.type==="text");return n.length?t(n.map(r=>r.text).join(`
39
+ `)):t(e)}function ng(e){var n;if(e.name&&e.name.trim())return e.name;const t=(n=e.additionalKwargs)==null?void 0:n.agent_name;return typeof t=="string"&&t.trim()?t:e.model&&e.model.includes("/")?e.model.split("/").pop()||null:e.model||null}function sc(e){const t=e.updatedAt??e.createdAt??"",n=Array.isArray(e.content)?e.content.map(i=>{switch(i.type){case"text":return`t:${i.text.length}`;case"image":return"img";case"interrupt":return"interrupt";default:return"unknown"}}).join("|"):"",r="checkpointId"in e&&e.checkpointId?`cp:${e.checkpointId}`:"",o="checkpointNs"in e&&e.checkpointNs?`ns:${e.checkpointNs}`:"",s=[r,o].filter(Boolean).join("|");return`${e.id}:${t}:${n}${s?`:${s}`:""}`}function ni(e){var n;const t=(n=e.additionalKwargs)==null?void 0:n.toolProgress;return Array.isArray(t)?t:[]}function rg(e){if(e.role!=="assistant")return!1;const t=Array.isArray(e.content)?e.content:Array.isArray(e.parts)?e.parts:[],n=t.some(s=>s.type==="text"&&s.text&&s.text.trim().length>0),r=t.some(s=>s.type==="image"||s.type==="image_url"||s.type==="file"),o=!!e.artifact;return!n&&!r&&!o}function og(e){return e.role==="tool"?!0:e.role==="assistant"?rg(e):!1}function sg(e,t){const n=[],r=e.findIndex(c=>c.id===t);if(r===-1)return n;const o=new Map;let s=0;for(let c=r;c>=0;c--){const l=e[c];if(l.role==="user")break;if(l.role==="assistant"){const u=Array.isArray(l.content)?l.content:Array.isArray(l.parts)?l.parts:[];if(l.tool_calls)for(const f of l.tool_calls)f.id&&f.name&&!o.has(f.id)&&o.set(f.id,{name:f.name,timestamp:l.createdAt,order:s++});for(const f of u)if(f.type==="tool_call"){const h=f;h.id&&h.name&&!o.has(h.id)&&o.set(h.id,{name:h.name,timestamp:l.createdAt,order:s++})}}}if(o.size===0)return n;const i=new Map;for(let c=r+1;c<e.length;c++){const l=e[c];if(l.role==="tool"){const f=jo(l).toolCallId;if(console.log("[buildToolExecutionTimeline] Tool message at index",c,{toolCallId:f,name:l.name,hasMatch:o.has(f||""),toolCallMapKeys:Array.from(o.keys())}),f&&o.has(f)){const h=Array.isArray(l.content)?l.content:Array.isArray(l.parts)?l.parts:[],p=rc(h.filter(m=>m.type==="text"));i.set(f,{content:p||`Finished ${l.name||"tool"}`,artifact:l.artifact,timestamp:l.createdAt})}}}const a=Array.from(o.entries()).sort((c,l)=>c[1].order-l[1].order);for(const[c,l]of a){const u=i.get(c);u?(n.push({type:"tool.start",toolName:l.name,toolCallId:c,content:`Starting ${l.name}...`,timestamp:l.timestamp}),n.push({type:"tool.end",toolName:l.name,toolCallId:c,content:u.content,timestamp:u.timestamp,output:u.content,artifact:u.artifact})):n.push({type:"tool.start",toolName:l.name,toolCallId:c,content:`Starting ${l.name}...`,timestamp:l.timestamp})}return n}function hr(e){if(e==null)return e;if(typeof e=="string"){const t=e.trim(),n=dr(t);return n!==null?hr(n):t}if(Array.isArray(e))return e.map(t=>hr(t));if(typeof e=="object"){const t=e.value;if(t!==void 0)return hr(t)}return e}function ic(e){const t=hr(e.value);return t===e.value?e:{...e,value:t}}function Po(e){const t=e.artifact;return!t||typeof t!="object"?null:"metadata"in t&&t.metadata?t.metadata:{id:t.id??e.id??`artifact-${Date.now()}`,type:t.type??"unknown",created_at:e.createdAt??new Date().toISOString(),status:t.status??"completed",progress:t.progress??void 0}}function ig(e){if(!e||typeof e!="object")return!1;const t=Po({artifact:e});return!!(t&&t.status==="in_progress"&&(t.progress??0)<100)}function ag(e,t){const n=Po(e);if(!n)return e;const r={...n,...t,updated_at:new Date().toISOString()};return{...e,artifact:{...typeof e.artifact=="object"&&e.artifact?e.artifact:{},metadata:r}}}function lg(e,t){return e.find(n=>{const r=Po(n);return(r==null?void 0:r.id)===t})??null}function Oo(e){return e.filter(t=>{var c;if(t.role!=="assistant")return!0;const n=t.content,r=typeof n=="string"?n.trim().length>0:Array.isArray(n)&&n.some(l=>{var u;return l&&l.type==="text"&&((u=l.text)==null?void 0:u.trim())}),o=Array.isArray(n)&&n.some(l=>l&&l.type==="image"),s=t.artifact!==null&&t.artifact!==void 0,i=((c=t.tool_calls)==null?void 0:c.length)>0,a=Array.isArray(n)&&n.some(l=>l&&["file","tool_call","interrupt"].includes(l.type));return!!(r||o||s||i||a)})}function Hr(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function cg(e){let t=!1;const n=e.map(r=>{var s;const o=(r.content??[]).filter(i=>i.type!=="interrupt");return o.length!==((s=r.parts)==null?void 0:s.length)?(t=!0,{...r,content:o}):r});return t?n:e}function ug(e,t,n){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const s={...e[r],checkpointId:t,checkpointNs:n??void 0};return Hr(e,r,s)}return e}function dg(e){const t=new Map,n=[];return e.slice().sort((r,o)=>{const s=r.createdAt?Date.parse(r.createdAt):0,i=o.createdAt?Date.parse(o.createdAt):0;return s-i}).forEach(r=>{const o=Array.isArray(r.messages)?r.messages:[];for(const s of o)!(s!=null&&s.id)||t.has(s.id)||(t.set(s.id,s),n.push(s))}),n.sort((r,o)=>{const s=r.createdAt?Date.parse(r.createdAt):0,i=o.createdAt?Date.parse(o.createdAt):0;return s-i}),n}const fg={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,messagesStreamMeta:{},pendingInterrupt:null,values:{}};function hg(e,t){var n;switch(t.type){case"reset":return{messages:Oo(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,pendingInterrupt:null,messagesStreamMeta:{},values:{}};case"user_message":{const{message:r,editingMessageId:o}=t.payload;if(o){const s=e.messages.findIndex(i=>i.id===o);if(s>=0){const i=e.messages.slice(0,s);return{...e,messages:[...i,r],assemblingId:null}}}return{...e,messages:[...e.messages,r],assemblingId:null}}case"seed":{const r=Oo(t.payload.messages),o={...e,messages:r,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(o.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(o.lastCheckpointNs=t.payload.checkpointNs??null),o}case"prepend":{const r=Oo(t.payload.messages);if(!r.length)return e;const o=new Set(e.messages.map(a=>a.id)),s=r.filter(a=>!o.has(a.id));if(!s.length)return e;const i=[...s,...e.messages];return{...e,messages:i}}case"event":return ac(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>ac(o,s),e):e}default:return e}}function pg(e=[]){const[t,n]=x.useReducer(hg,{...fg,messages:e}),r=x.useRef([]),o=x.useRef(null),s=x.useRef(null),i=x.useCallback(()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),o.current=null,s.current=null;const u=r.current;u.length&&(r.current=[],n({type:"batch",payload:{events:u}}))},[]),a=x.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o.current===null&&(o.current=window.requestAnimationFrame(()=>i())):s.current===null&&(s.current=setTimeout(i,8))},[i]),c=x.useCallback(u=>{r.current.push(u),a()},[a]);x.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const l=x.useMemo(()=>({reset:u=>n({type:"reset",payload:{messages:u}}),seed:(u,f)=>n({type:"seed",payload:{messages:u,...f??{}}}),prepend:u=>n({type:"prepend",payload:{messages:u}}),pushUser:(u,f)=>n({type:"user_message",payload:{message:u,editingMessageId:f}}),onEvent:c}),[c]);return{state:t,dispatch:n,...l}}function ac(e,t){if(t.type==="tool.start")return gg(e,t);if(t.type==="tool.progress")return xg(e,t);if(t.type==="tool.end")return bg(e,t);if(t.type==="artifact.update")return wg(e,t);if(t.type==="checkpoint"){const n=t.checkpointNs??e.lastCheckpointNs??null,r=ug(e.messages,t.checkpointId,n);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:n,messages:r}}if(t.type==="error"){const n={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,n]}}if(t.type==="state_history"){const n=cr(t),r=n.interrupt,o=n.latest,s=dg(n.checkpoints);let i=s.length?s:o==null?void 0:o.messages;if(i){if(e.assemblingId&&!i.some(a=>a.id===e.assemblingId)){const a=e.messages.find(c=>c.id===e.assemblingId);a&&(i=[...i,a])}i=Oo(i)}else i=r===null?cg(e.messages):e.messages;return{...e,messages:i,pendingInterrupt:r,lastCheckpointId:(o==null?void 0:o.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(o==null?void 0:o.checkpointNs)??e.lastCheckpointNs,values:(o==null?void 0:o.values)??e.values}}return t.type==="thread_info",e}function ri(e){return e.call_id??e.id??null}function lc(e){return e.id??e.call_id??`tool-${Date.now()}-${Math.random().toString(16).slice(2)}`}function cc(e,t,n,r){const o=t??`call-${Date.now()}-${Math.random().toString(16).slice(2)}`;return{id:e,role:"tool",name:n??void 0,toolCallId:o,content:[{type:"tool_call",id:o,name:n??"tool",args:r??{}}],createdAt:new Date().toISOString(),additionalKwargs:{toolName:n??void 0,toolStreaming:!0,toolProgress:[]}}}function oi(e,t){if(!t)return-1;for(let n=0;n<e.length;n+=1){const r=e[n];if(r.role!=="tool")continue;const o=r.toolCallId;if(typeof o=="string"&&o===t)return n;const s=r.additionalKwargs??{};if(typeof s.toolCallId=="string"&&s.toolCallId===t||jo(r).toolCallId===t)return n}return-1}function mg(e){if(e==null)return[];const t=Br(e);if(typeof t=="string"&&t.trim())return[{type:"text",text:t}];const n=fr(t??e);return n?[{type:"text",text:n}]:[]}function si(e,t){const n=e.additionalKwargs??{},r=Array.isArray(n.toolProgress)?[...n.toolProgress]:[],o={...n,toolProgress:[...r,t]};return{...e,additionalKwargs:o}}function gg(e,t){const n=ri(t),r=oi(e.messages,n),o=t.name??t.tool??void 0,s=lc(t),i={type:t.type,content:`Starting ${o??"tool"}...`,seq:t.seq??null,timestamp:new Date().toISOString()};if(r>=0){const l=e.messages[r],f={...l.additionalKwargs??{},toolStreaming:!0,toolProgress:[i]},h={...l,name:o??l.name,additionalKwargs:f};return{...e,messages:Hr(e.messages,r,h)}}const a=cc(s,n,o,t.args),c=si(a,i);return{...e,messages:[...e.messages,c]}}function xg(e,t){var u,f,h,p,m;const n=t.id??t.call_id??((u=t.data)==null?void 0:u.id)??ri(t);if(!n)return e;const r=oi(e.messages,n);if(r===-1)return e;const o=t.status??t.step??t.type??((f=t.data)==null?void 0:f.type)??"progress",s=t.content??((h=t.data)==null?void 0:h.content)??(typeof t.data=="string"?t.data:void 0),i={type:o,content:s,seq:t.seq??null,timestamp:new Date().toISOString()},a=t.metadata??((p=t.data)==null?void 0:p.metadata);a&&(i.metadata=a);const c=t.idx??((m=t.data)==null?void 0:m.idx);typeof c=="number"&&(i.idx=c);const l=si(e.messages[r],i);return{...e,messages:Hr(e.messages,r,l)}}function bg(e,t){const n=ri(t),r=lc(t);let o=e.messages,s=oi(o,n);if(s===-1){const m=t.name??t.tool??void 0;o=[...o,cc(r,n,m,{})],s=o.length-1}const i=o[s],a=t.output??t.error??null,c=mg(a),l=[...i.content,...c],u={type:t.type,content:typeof t.output=="string"?t.output:void 0,seq:t.seq??null,timestamp:new Date().toISOString()};t.artifact&&(u.artifact=t.artifact);const f=si(i,u),h=t.artifact??i.artifact,p={...f,name:t.name??t.tool??i.name,content:l,artifact:h,additionalKwargs:{...f.additionalKwargs??{},toolStreaming:!1}};return{...e,messages:Hr(o,s,p)}}function wg(e,t){const n=lg(e.messages,t.artifact_id);if(!n){const s={id:`artifact-${t.artifact_id}`,role:"tool",name:"artifact_updater",content:[],createdAt:new Date().toISOString(),artifact:{type:"unknown",metadata:{id:t.artifact_id,type:"unknown",created_at:new Date().toISOString(),status:t.status,progress:t.progress},...t.partial_data}};return{...e,messages:[...e.messages,s]}}const r=e.messages.indexOf(n),o=ag(n,{status:t.status,progress:t.progress,error:t.error});return t.partial_data&&o.artifact&&(o.artifact={...o.artifact,...t.partial_data}),{...e,messages:Hr(e.messages,r,o)}}const uc=120;function vg(e){if(!Array.isArray(e))return"";const t=e.filter(r=>!!(r&&r.type==="text")).map(r=>(r.text??"").trim()).filter(Boolean);if(!t.length)return"";const n=t.join(" ").replace(/\s+/g," ").trim();return n?n.length>uc?`${n.slice(0,uc-3)}…`:n:""}function yg(e){return vg(e.content)||""}function Sg(e){const t=new Map,n=[],r=new Map,o=[];for(let l=0;l<e.length;l++){const u=e[l],f=u.checkpointId,h=f??`cp-${l}`,p=u.metadata??{},m=typeof p.step=="number"?p.step:null,g=typeof p.source=="string"?p.source:null;let b=null,v=null;const y=Array.isArray(u.messages)?u.messages:[];for(const S of y)S.role==="user"&&(v||(v=S),S.id&&(b=S.id));const T=u.next&&u.next.length>0?String(u.next[0]):null,I=u.parentConfig??null,k={id:h,step:m,source:g,createdAt:u.createdAt??null,namespace:u.checkpointNs??null,parentId:u.parentId??null,next:T,parentConfig:I,userMessageId:b};if(o.push(k),f&&t.set(f,k),f&&v){const S=yg(v);S&&r.set(f,S)}n.push({id:h,messageId:b,step:m,source:g,createdAt:u.createdAt??null,next:T,parentConfig:I})}const s=new Map;for(const l of o){if(!l.userMessageId)continue;const u=s.get(l.userMessageId)??[];u.push(l),s.set(l.userMessageId,u)}for(const l of s.values()){if(!l.length)continue;l.sort((f,h)=>{const p=f.createdAt?Date.parse(f.createdAt):0;return(h.createdAt?Date.parse(h.createdAt):0)-p});const u=l.length;for(let f=0;f<l.length;f++){const h=l[f];h.attemptCount=u,h.attemptIndex=f,h.isLatestAttempt=f===0}}return{checkpoints:e,checkpointMetaByCheckpointId:t,timeline:n,messagePreviews:r,getLatest:()=>{const l=n[0];if(l)return t.get(l.id)},getCheckpoint:l=>t.get(l),getMessageAttempts:l=>{const u=[];for(const f of t.values())f.userMessageId===l&&u.push(f);return u.length?(u.sort((f,h)=>{const p=typeof f.attemptIndex=="number"?f.attemptIndex:Number.MAX_SAFE_INTEGER,m=typeof h.attemptIndex=="number"?h.attemptIndex:Number.MAX_SAFE_INTEGER;return p-m}),u):[]}}}function Cg(e,t,n){if(!e)return{attemptCount:1,attemptIndex:0,attempts:[]};const r=n.getMessageAttempts(e);if(!r.length)return{attemptCount:1,attemptIndex:0,attempts:[]};let o=0;if(t){const s=r.findIndex(i=>i.id===t);s>=0&&(o=s)}return{attemptCount:r.length,attemptIndex:o,attempts:r}}function kg(e){return x.useMemo(()=>Sg(e),[e])}function dc({api:e,seed:t,onError:n,currentThreadId:r,initialThreadId:o=null,initialCheckpointId:s=null,initialCheckpointNs:i=null,autoLoadInitial:a=!0,isStreaming:c,getMessages:l}){const[u,f]=x.useState(null),p=x.useMemo(()=>cr(u),[u]).checkpoints,m=kg(p),g=m.timeline,[b,v]=x.useState(!1),[y,T]=x.useState(!1),[I,k]=x.useState(null),S=x.useRef(r),E=x.useRef(null),j=x.useRef(null),_=x.useRef(null),D=x.useRef(null),L=x.useRef(null),W=x.useRef(new Map),V=x.useRef(null);x.useEffect(()=>{S.current=r},[r]);const $=x.useCallback(async R=>{var q,J;if(!R.threadId)return;const M=R.threadId;(q=R.onStart)==null||q.call(R),R.setLoading(!0);try{await R.action(M)}catch(P){if(!Ll(P)&&S.current===M){const te=String(P);(J=R.handleError)==null||J.call(R,te),n==null||n(te)}throw P}finally{R.setLoading(!1)}},[n]),Z=x.useCallback(async(R,M)=>{var te;if(!R)return;const q=`${R}:${M??"latest"}`,J=W.current.get(q);if(J)return J;(te=V.current)==null||te.abort();const P=new AbortController;V.current=P;const K=$({threadId:R,setLoading:v,onStart:()=>k(null),handleError:le=>k(le),action:async le=>{const he=await e.getStateHistory({threadId:le,checkpointId:M??void 0,signal:P.signal});if(S.current!==le){console.log(`[useThreadHistoryState] Thread changed during load (was ${le}, now ${S.current}), discarding stale data`);return}const{checkpoints:ue,latest:ge}=cr(he),be=M?ue.find(Be=>Be.checkpointId===M)??ge:ge;t((be==null?void 0:be.messages)??[],{checkpointId:(be==null?void 0:be.checkpointId)??null,checkpointNs:(be==null?void 0:be.checkpointNs)??null,pendingInterrupt:(be==null?void 0:be.interrupt)??null}),f(he)}});W.current.set(q,K);try{await K}finally{W.current.delete(q),V.current===P&&(V.current=null)}return S.current===R&&(L.current=q),K},[e,t,$]),X=x.useCallback(async(R,M)=>{D.current=R;try{await Z(R,M)}catch(q){if(!Ll(q))throw q}finally{D.current===R&&(D.current=null)}},[Z]),oe=x.useCallback(R=>{j.current=R},[]),U=x.useCallback(R=>{_.current=R},[]),F=x.useCallback(R=>{const M=R.threadId??S.current;if(!M||S.current&&S.current!==M)return;const{checkpoints:q,latest:J}=cr(R);if(!q.length)return;const P=J,K=_.current===M;!c&&!K&&t((P==null?void 0:P.messages)??[],{checkpointId:(P==null?void 0:P.checkpointId)??null,checkpointNs:(P==null?void 0:P.checkpointNs)??null,pendingInterrupt:(P==null?void 0:P.interrupt)??null}),f(R),L.current=`${M}:latest`,j.current=null,_.current===M&&(_.current=null)},[t,c]),G=x.useCallback(async(R,M)=>{const q=S.current;await $({threadId:q,setLoading:T,action:async J=>{const P=await e.getStateHistory({threadId:J,checkpointId:R,checkpointNs:M??void 0});if(S.current!==J)return;const{checkpoints:K}=cr(P),te=K.find(le=>le.checkpointId===R&&(M?le.checkpointNs===M:!0));if(!te){console.warn("[useThreadHistoryState] Requested checkpoint not found:",{checkpointId:R,checkpointNs:M});return}f(P),t(te.messages??[],{checkpointId:te.checkpointId??null,checkpointNs:te.checkpointNs??null})}}).catch(()=>{})},[e,t,$]),H=x.useCallback((R,M)=>{t(l(),{checkpointId:R??null,checkpointNs:M??null})},[l,t]),A=x.useCallback(async()=>{S.current&&await X(S.current)},[X]);x.useEffect(()=>{if(!a||!r||b||c)return;if(j.current===r){j.current=null,E.current=r;return}if(_.current===r){E.current=r;return}if(D.current===r){D.current=null,E.current=r;return}if(E.current===r)return;E.current=r;let R;const M=`${r}:latest`;L.current!==M&&X(r,R)},[a,r,s,i,o,b,c,X]);const N=x.useCallback(()=>{f(null),v(!1),T(!1),k(null),j.current=null,_.current=null,E.current=null,L.current=null,D.current=null},[]);return{threadCheckpoints:p,threadTimeline:g,checkpointIndex:m,isLoadingThread:b,isLoadingCheckpoint:y,threadStateError:I,loadThread:X,navigateToCheckpoint:G,setCurrentCheckpointId:H,returnToLatest:A,handleStateHistoryEvent:F,markSkipNextLoad:oe,markStreamPendingThread:U,resetHistoryState:N,clearState:N}}const fc=x.createContext(null),hc=x.createContext(null);function Ur(){const e=x.useContext(fc);if(!e)throw new Error("useThreadState must be used within a ThreadStateProvider");return e}function pc(){const e=x.useContext(hc);if(!e)throw new Error("useThreadStateUpdater must be used within a ThreadStateProvider");return e}function mc({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:o=!0,isStreaming:s,onError:i}){const{chatApi:a}=Vn(),{currentThreadId:c}=ur(),{state:l,seed:u,onEvent:f,dispatch:h}=pg(),{threadCheckpoints:p,threadTimeline:m,checkpointIndex:g,isLoadingThread:b,isLoadingCheckpoint:v,threadStateError:y,loadThread:T,navigateToCheckpoint:I,setCurrentCheckpointId:k,returnToLatest:S,handleStateHistoryEvent:E,markSkipNextLoad:j,markStreamPendingThread:_,resetHistoryState:D}=dc({api:a,seed:u,onError:i,currentThreadId:c,initialThreadId:t,initialCheckpointId:n,initialCheckpointNs:r,autoLoadInitial:o,isStreaming:s,getMessages:x.useCallback(()=>l.messages,[l.messages])});x.useEffect(()=>{c||(u([],{}),D())},[c,u,D]);const L=x.useRef(null),W=x.useCallback(G=>{L.current=G},[]),V=x.useRef(null),$=x.useCallback(G=>{V.current=G},[]),Z=x.useMemo(()=>({assemblingMessageId:l.assemblingId??null}),[l.assemblingId]),X=x.useCallback((G,H)=>{const A=Yl(G,"user");return h({type:"user_message",payload:{message:A,editingMessageId:H==null?void 0:H.editingMessageId}}),A},[h]),oe=x.useCallback(async()=>{L.current?await L.current():(u([],{}),D())},[u,D]),U=x.useMemo(()=>({threadId:c,messages:l.messages,interrupt:l.pendingInterrupt,checkpoint:{id:l.lastCheckpointId??null,namespace:l.lastCheckpointNs??null},checkpoints:p,checkpointIndex:g,timelineCheckpoints:m,metadata:Z,values:l.values??{},isLoading:b,isLoadingCheckpoint:v,error:y,loadOlder:async()=>{},seedFromSnapshot:G=>{u(G.messages,{checkpointId:G.checkpointId,checkpointNs:G.checkpointNs,pendingInterrupt:G.interrupt})},clearState:oe,navigateToCheckpoint:I,setCurrentCheckpointId:k,returnToLatest:S,loadThread:async(G,H,A)=>{await T(G,H,{clearProgress:!1})},clearThread:oe,respondToInterrupt:async(G,H,A)=>{V.current&&await V.current(G,H,A)},messagePreviews:g.messagePreviews,handleStateHistoryEvent:E,markSkipNextLoad:j,markStreamPendingThread:_,resetHistoryState:D,pushUser:X,onEvent:f}),[c,l.messages,l.pendingInterrupt,l.lastCheckpointId,l.lastCheckpointNs,l.values,p,m,g,Z,b,v,y,u,oe,I,k,S,T,E,j,_,X,f]),F=x.useMemo(()=>({registerClearThread:W,registerRespondToInterrupt:$}),[W,$]);return d.jsx(hc.Provider,{value:F,children:d.jsx(fc.Provider,{value:U,children:e})})}function gc(e,t){if(!e)return null;const n=Kn(e);if(!n)return null;const r=Kn(n.configurable)??n;return Fr(r,t)??null}function Tg(e){const t=gc(e,["checkpoint_id","checkpointId"]);if(!t)return null;const n=gc(e,["checkpoint_ns","checkpointNs"]);return{checkpointId:t,checkpointNs:n}}function Eg(e,t){const n=typeof e.step=="number"?e.step:Number.POSITIVE_INFINITY,r=typeof t.step=="number"?t.step:Number.POSITIVE_INFINITY;if(n!==r)return n-r;const o=e.createdAt?Date.parse(e.createdAt):0,s=t.createdAt?Date.parse(t.createdAt):0;return o-s}function Ig(e,t){const n=[...e].sort(Eg);for(const r of n){if(r.messageId!==t)continue;const o=Tg(r.parentConfig);if(!o)throw new Error(`Parent checkpoint info missing for message ${t}`);return o}throw new Error(`Message ${t} not found in timeline`)}const xc=x.createContext(null),bc=x.createContext(!1);function Ag({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:o=!0,onError:s,onAuthError:i,onThreadChange:a,onConnectionError:c,onToolEnd:l}){const{chatApi:u,baseUrl:f}=Vn(),h=f,{stream:p,stop:m,clear:g,isStreaming:b,error:v,connected:y}=Xm({baseUrl:h}),[T,I]=x.useState(!1);return x.useEffect(()=>{I(b)},[b]),d.jsx(tc,{initialThreadId:t,onError:s,onThreadChange:a,children:d.jsx(mc,{initialThreadId:t,initialCheckpointId:n,initialCheckpointNs:r,autoLoadInitial:o,onError:s,isStreaming:T,children:d.jsx(bc.Provider,{value:!0,children:d.jsx(Ng,{api:u,streamApi:{stream:p,stop:m,clear:g,isStreaming:b,error:v,connected:y},onError:s,onAuthError:i,onConnectionError:c,onToolEnd:l,children:e})})})})}function Ng({children:e,api:t,streamApi:n,onError:r,onAuthError:o,onConnectionError:s,onToolEnd:i}){const{stream:a,stop:c,clear:l,isStreaming:u,error:f,connected:h}=n,{setCurrentThreadId:p,currentThreadIdRef:m,addThreadFromEvent:g,currentThreadId:b}=ur();x.useEffect(()=>{b!==void 0&&l()},[b,l]);const{interrupt:v,checkpoint:y,timelineCheckpoints:T,handleStateHistoryEvent:I,markSkipNextLoad:k,markStreamPendingThread:S,resetHistoryState:E,pushUser:j,onEvent:_,messages:D}=Ur(),{registerClearThread:L,registerRespondToInterrupt:W}=pc(),V=x.useCallback(H=>{g(H),m.current!==H.threadId&&((H.created??!m.current)&&k(H.threadId),S(H.threadId),p(H.threadId))},[g,k,S,p,m]),$=x.useCallback(H=>{H.type==="thread_info"?V(H):H.type==="state_history"?I(H):H.type==="tool.end"?(_(H),i==null||i(H)):_(H)},[V,I,_,i]),Z=x.useCallback((H,A)=>{a(H,N=>{$(N),A==null||A(N)},{onError:N=>{console.error("[StreamingProvider] Stream error:",N),r==null||r(N)},onAuthError:N=>{console.error("[StreamingProvider] Auth error:",N),o==null||o(N)},onConnectionError:N=>{console.error("[StreamingProvider] Connection error:",N),s==null||s(N)}})},[a,$,r,o,s]),X=x.useRef(y);x.useEffect(()=>{X.current=y},[y]);const oe=x.useCallback(async(H,A,N)=>{const R=m.current;if(!R)throw new Error("No active thread to handle interrupt");const M=H?A??!0:!1,q=X.current,J={threadId:R,checkpointId:q.id??void 0,checkpointNs:q.namespace??void 0,command:{kind:"resume",value:M},payload:N==null?void 0:N.payload};Z(J)},[m,Z]);x.useEffect(()=>{W(oe)},[oe,W]);const U=x.useCallback(async()=>{c(),l(),E(),p(null)},[l,E,p,c]);x.useEffect(()=>{L(U)},[U,L]);const F=x.useCallback(async(H,A)=>{u&&c();let N=m.current;const R=(H==null?void 0:H.text)??"",M=(H==null?void 0:H.attachments)??[],q=(R==null?void 0:R.trim())??"",J={...(H==null?void 0:H.payload)??{}},P=Array.isArray(J.messages)?J.messages:void 0;P&&delete J.messages;const K=!!(P&&P.length),te=!!(H.contentParts&&H.contentParts.length>0);if(!N&&!q&&M.length===0&&!K&&!te)return;if(!N){const Me=Math.floor(Date.now()/1e3).toString(16).padStart(8,"0"),Ze=Array.from({length:4},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("").slice(0,16);N=`${Me}${Ze}`,k(N),p(N)}let le=null;H.contentParts&&H.contentParts.length>0&&(le=H.contentParts);const{contentParts:he,filesInfo:ue}=le?{contentParts:le,filesInfo:[]}:await Gl(M),ge=[...he];q&&ge.push({type:"text",text:R});const be=A==null?void 0:A.originalMessageId,Be=!!(A!=null&&A.edit&&be),Le=!K&&ge.length>0;let je=null;if(Le){const Me=Be?be:`msg-${Date.now()}`;je=Yl({id:Me,role:"user",content:ge,createdAt:new Date().toISOString()},"user"),Be?j(je,{editingMessageId:be}):j(je)}const Fe=K?P:je?[je]:[],tt={...J,...ue.length?{files_info:ue}:{}};Fe.length?tt.messages=Fe:"messages"in tt||(tt.messages=[]);let mt=(A==null?void 0:A.checkpointId)??y.id??void 0,ot=(A==null?void 0:A.checkpointNs)??y.namespace??void 0;if(Be&&be){const Me=Ig(T,be);mt=Me.checkpointId,ot=Me.checkpointNs??void 0}const ze={threadId:N,payload:tt,checkpointId:mt,checkpointNs:ot,config:A==null?void 0:A.config,edit:!!(A!=null&&A.edit)};Z(ze,A==null?void 0:A.onEvent)},[y,m,u,k,j,Z,c,T]),G=x.useMemo(()=>({isStreaming:u,error:f,connectionState:f?"error":u?h?"connected":"connecting":"idle",messages:D,submit:F,stop:c,interrupt:v,resume:()=>Promise.resolve(),goto:(H,A)=>Promise.resolve(),clearError:()=>{}}),[u,f,F,c,v,h,D]);return d.jsx(xc.Provider,{value:G,children:e})}function ii(){const e=x.useContext(xc);if(!e)throw new Error("useStream must be used within StreamingProvider");return e}function _g(){return x.useContext(bc)}function wc(e){return typeof e=="object"&&e!==null}function jg(e,t){if(Object.is(e,t))return!0;if(!wc(e)||!wc(t))return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n)if(!Object.prototype.hasOwnProperty.call(t,o)||!Object.is(e[o],t[o]))return!1;return!0}function vc(e){const t=x.useRef(e),n=x.useRef(e);return jg(t.current,e)||(t.current=e,n.current=e),n.current}function Wr({children:e,apiConfig:t,initialThreadId:n=null,initialCheckpointId:r=null,initialCheckpointNs:o=null,autoLoadInitial:s=!0,onConnectionError:i,onError:a,onAuthError:c,onThreadChange:l,onToolEnd:u}){const f=vc(t),h=Vr(a),p=Vr(c),m=Vr(i),g=Vr(l),b=Vr(u),v=x.useMemo(()=>({initialThreadId:n,initialCheckpointId:r,initialCheckpointNs:o,autoLoadInitial:s,onError:h,onAuthError:p,onConnectionError:m,onThreadChange:g,onToolEnd:b}),[n,r,o,s,h,p,m,g,b]);return d.jsx(Kl,{apiConfig:f,children:d.jsx(Ag,{...v,children:e})})}function Vr(e){const t=x.useRef(e);return x.useEffect(()=>{t.current=e},[e]),x.useCallback((...n)=>{const r=t.current;if(r)return r(...n)},[])}function pr(e){if(!(typeof globalThis>"u"))return globalThis[e]}function yc(){const e=[pr("__API_BASE_URL__"),pr("__CHAT_API_BASE_URL__"),pr("__CHAT_API_URL__")];for(const t of e)if(typeof t=="string"&&t.trim())return t.trim().replace(/\/+$/,"")}function Sc(){const e=[pr("__API_AUTH_TOKEN__"),pr("__CHAT_API_KEY__"),pr("__CHAT_AUTH_TOKEN__")];for(const t of e)if(typeof t=="string"&&t.trim())return t.trim()}function Cc(...e){for(const t of e)if(typeof t=="string"&&t.trim())return t.trim().replace(/\/+$/,"");return""}function kc(){const e={},t=yc(),n=Sc();return t&&(e.baseUrl=t),n&&(e.apiKey=n),e}function Tc(){const e=kc(),t=An.getAuthToken(),n=yc();return{apiBaseUrl:Cc(e.baseUrl,n),apiKey:t||e.apiKey||Sc()||"",model:"gpt-4",temperature:.7,maxTokens:4096,layoutSize:"desktop",showThreads:!0,autoScrollMessages:!0,darkMode:!1,enableSound:!1,messageHistory:100}}const ai=En.chatSettings;function Ec(){try{const e=localStorage.getItem(ai);return e?JSON.parse(e):{}}catch(e){return console.error("Failed to parse stored settings:",e),{}}}function Ic(e){try{const t={...e,apiBaseUrl:e.apiBaseUrl.trim().replace(/\/+$/,"")};localStorage.setItem(ai,JSON.stringify(t)),t.apiKey&&An.setAuthToken(t.apiKey)}catch(t){console.error("Failed to save settings:",t)}}function Pg(){const e=Tc(),t=Ec(),n=An.getAuthToken(),r=typeof t.apiBaseUrl=="string"?t.apiBaseUrl:void 0;return{...e,...t,apiKey:n||t.apiKey||e.apiKey,apiBaseUrl:Cc(An.baseUrl,r,e.apiBaseUrl)}}function Og(e){An.updateConfig({baseUrl:e.apiBaseUrl,apiKey:e.apiKey??void 0}),Ic(e)}function ae(...e){return Bn.twMerge(Pt.clsx(e))}const Rg=Ya.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),Ke=w.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?sr.Slot:"button";return d.jsx(i,{className:ae(Rg({variant:t,size:n,className:e})),ref:s,...o})});Ke.displayName="Button";const Ro=0,Nn=1,mr=2,Ac=4;function Nc(e){return()=>e}function Mg(e){e()}function _c(e,t){return n=>e(t(n))}function jc(e,t){return()=>e(t)}function Dg(e,t){return n=>e(t,n)}function li(e){return e!==void 0}function Lg(...e){return()=>{e.map(Mg)}}function gr(){}function Mo(e,t){return t(e),e}function $g(e,t){return t(e)}function Xe(...e){return e}function De(e,t){return e(Nn,t)}function Ae(e,t){e(Ro,t)}function ci(e){e(mr)}function lt(e){return e(Ac)}function me(e,t){return De(e,Dg(t,Ro))}function tn(e,t){const n=e(Nn,r=>{n(),t(r)});return n}function Pc(e){let t,n;return r=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{r(t)},e)}}function Oc(e,t){return e===t}function Je(e=Oc){let t;return n=>r=>{e(t,r)||(t=r,n(r))}}function ye(e){return t=>n=>{e(n)&&t(n)}}function ce(e){return t=>_c(t,e)}function un(e){return t=>()=>{t(e)}}function ee(e,...t){const n=Fg(...t);return(r,o)=>{switch(r){case mr:ci(e);return;case Nn:return De(e,n(o))}}}function dn(e,t){return n=>r=>{n(t=e(t,r))}}function qn(e){return t=>n=>{e>0?e--:t(n)}}function yn(e){let t=null,n;return r=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,r(t)},e))}}function Ne(...e){const t=new Array(e.length);let n=0,r=null;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);De(s,c=>{const l=n;n=n|a,t[i]=c,l!==o&&n===o&&r&&(r(),r=null)})}),s=>i=>{const a=()=>{s([i].concat(t))};n===o?a():r=a}}function Fg(...e){return t=>e.reduceRight($g,t)}function zg(e){let t,n;const r=()=>t==null?void 0:t();return function(o,s){switch(o){case Nn:return s?n===s?void 0:(r(),n=s,t=De(e,s),t):(r(),gr);case mr:r(),n=null;return}}}function re(e){let t=e;const n=Oe();return(r,o)=>{switch(r){case Ro:t=o;break;case Nn:{o(t);break}case Ac:return t}return n(r,o)}}function vt(e,t){return Mo(re(t),n=>me(e,n))}function Oe(){const e=[];return(t,n)=>{switch(t){case Ro:e.slice().forEach(r=>{r(n)});return;case mr:e.splice(0,e.length);return;case Nn:return e.push(n),()=>{const r=e.indexOf(n);r>-1&&e.splice(r,1)}}}}function Ht(e){return Mo(Oe(),t=>me(e,t))}function Re(e,t=[],{singleton:n}={singleton:!0}){return{constructor:e,dependencies:t,id:Bg(),singleton:n}}const Bg=()=>Symbol();function Hg(e){const t=new Map,n=({constructor:r,dependencies:o,id:s,singleton:i})=>{if(i&&t.has(s))return t.get(s);const a=r(o.map(c=>n(c)));return i&&t.set(s,a),a};return n(e)}function ft(...e){const t=Oe(),n=new Array(e.length);let r=0;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);De(s,c=>{n[i]=c,r=r|a,r===o&&Ae(t,n)})}),function(s,i){switch(s){case mr:{ci(t);return}case Nn:return r===o&&i(n),De(t,i)}}}function ve(e,t=Oc){return ee(e,Je(t))}function ui(...e){return function(t,n){switch(t){case mr:return;case Nn:return Lg(...e.map(r=>De(r,n)))}}}var Dt=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(Dt||{});const Ug={0:"debug",3:"error",1:"log",2:"warn"},Wg=()=>typeof globalThis>"u"?window:globalThis,_n=Re(()=>{const e=re(3);return{log:re((t,n,r=1)=>{var o;const s=(o=Wg().VIRTUOSO_LOG_LEVEL)!=null?o:lt(e);r>=s&&console[Ug[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function Gn(e,t,n){return di(e,t,n).callbackRef}function di(e,t,n){const r=x.useRef(null);let o=i=>{};const s=x.useMemo(()=>typeof ResizeObserver<"u"?new ResizeObserver(i=>{const a=()=>{const c=i[0].target;c.offsetParent!==null&&e(c)};n?a():requestAnimationFrame(a)}):null,[e,n]);return o=i=>{i&&t?(s==null||s.observe(i),r.current=i):(r.current&&(s==null||s.unobserve(r.current)),r.current=null)},{callbackRef:o,ref:r}}function Vg(e,t,n,r,o,s,i,a,c){const l=x.useCallback(u=>{const f=Kg(u.children,t,a?"offsetWidth":"offsetHeight",o);let h=u.parentElement;for(;!h.dataset.virtuosoScroller;)h=h.parentElement;const p=h.lastElementChild.dataset.viewportType==="window";let m;p&&(m=h.ownerDocument.defaultView);const g=i?a?i.scrollLeft:i.scrollTop:p?a?m.scrollX||m.document.documentElement.scrollLeft:m.scrollY||m.document.documentElement.scrollTop:a?h.scrollLeft:h.scrollTop,b=i?a?i.scrollWidth:i.scrollHeight:p?a?m.document.documentElement.scrollWidth:m.document.documentElement.scrollHeight:a?h.scrollWidth:h.scrollHeight,v=i?a?i.offsetWidth:i.offsetHeight:p?a?m.innerWidth:m.innerHeight:a?h.offsetWidth:h.offsetHeight;r({scrollHeight:b,scrollTop:Math.max(g,0),viewportHeight:v}),s==null||s(a?Rc("column-gap",getComputedStyle(u).columnGap,o):Rc("row-gap",getComputedStyle(u).rowGap,o)),f!==null&&e(f)},[e,t,o,s,i,r,a]);return di(l,n,c)}function Kg(e,t,n,r){const o=e.length;if(o===0)return null;const s=[];for(let i=0;i<o;i++){const a=e.item(i);if(a.dataset.index===void 0)continue;const c=parseInt(a.dataset.index),l=parseFloat(a.dataset.knownSize),u=t(a,n);if(u===0&&r("Zero-sized element, this should not happen",{child:a},Dt.ERROR),u===l)continue;const f=s[s.length-1];s.length===0||f.size!==u||f.endIndex!==c-1?s.push({endIndex:c,size:u,startIndex:c}):s[s.length-1].endIndex++}return s}function Rc(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,Dt.WARN),t==="normal"?0:parseInt(t??"0",10)}function Mc(e,t,n){const r=x.useRef(null),o=x.useCallback(c=>{if(!(c!=null&&c.offsetParent))return;const l=c.getBoundingClientRect(),u=l.width;let f,h;if(t){const p=t.getBoundingClientRect(),m=l.top-p.top;h=p.height-Math.max(0,m),f=m+t.scrollTop}else{const p=i.current.ownerDocument.defaultView;h=p.innerHeight-Math.max(0,l.top),f=l.top+p.scrollY}r.current={offsetTop:f,visibleHeight:h,visibleWidth:u},e(r.current)},[e,t]),{callbackRef:s,ref:i}=di(o,!0,n),a=x.useCallback(()=>{o(i.current)},[o,i]);return x.useEffect(()=>{var c;if(t){t.addEventListener("scroll",a);const l=new ResizeObserver(()=>{requestAnimationFrame(a)});return l.observe(t),()=>{t.removeEventListener("scroll",a),l.unobserve(t)}}else{const l=(c=i.current)==null?void 0:c.ownerDocument.defaultView;return l==null||l.addEventListener("scroll",a),l==null||l.addEventListener("resize",a),()=>{l==null||l.removeEventListener("scroll",a),l==null||l.removeEventListener("resize",a)}}},[a,t,i]),s}const Nt=Re(()=>{const e=Oe(),t=Oe(),n=re(0),r=Oe(),o=re(0),s=Oe(),i=Oe(),a=re(0),c=re(0),l=re(0),u=re(0),f=Oe(),h=Oe(),p=re(!1),m=re(!1),g=re(!1);return me(ee(e,ce(({scrollTop:b})=>b)),t),me(ee(e,ce(({scrollHeight:b})=>b)),i),me(t,o),{deviation:n,fixedFooterHeight:l,fixedHeaderHeight:c,footerHeight:u,headerHeight:a,horizontalDirection:m,scrollBy:h,scrollContainerState:e,scrollHeight:i,scrollingInProgress:p,scrollTo:f,scrollTop:t,skipAnimationFrameInResizeObserver:g,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:s}},[],{singleton:!0}),Kr={lvl:0};function Dc(e,t){const n=e.length;if(n===0)return[];let{index:r,value:o}=t(e[0]);const s=[];for(let i=1;i<n;i++){const{index:a,value:c}=t(e[i]);s.push({end:a-1,start:r,value:o}),r=a,o=c}return s.push({end:1/0,start:r,value:o}),s}function Ue(e){return e===Kr}function qr(e,t){if(!Ue(e))return t===e.k?e.v:t<e.k?qr(e.l,t):qr(e.r,t)}function nn(e,t,n="k"){if(Ue(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const r=nn(e.r,t,n);return r[0]===-1/0?[e.k,e.v]:r}return nn(e.l,t,n)}function Ut(e,t,n){return Ue(e)?Fc(t,n,1):t===e.k?pt(e,{k:t,v:n}):t<e.k?zc(pt(e,{l:Ut(e.l,t,n)})):zc(pt(e,{r:Ut(e.r,t,n)}))}function xr(){return Kr}function Do(e,t,n){if(Ue(e))return[];const r=nn(e,t)[0];return qg(hi(e,r,n))}function fi(e,t){if(Ue(e))return Kr;const{k:n,l:r,r:o}=e;if(t===n){if(Ue(r))return o;if(Ue(o))return r;{const[s,i]=$c(r);return Lo(pt(e,{k:s,l:Lc(r),v:i}))}}else return t<n?Lo(pt(e,{l:fi(r,t)})):Lo(pt(e,{r:fi(o,t)}))}function Yn(e){return Ue(e)?[]:[...Yn(e.l),{k:e.k,v:e.v},...Yn(e.r)]}function hi(e,t,n){if(Ue(e))return[];const{k:r,l:o,r:s,v:i}=e;let a=[];return r>t&&(a=a.concat(hi(o,t,n))),r>=t&&r<=n&&a.push({k:r,v:i}),r<=n&&(a=a.concat(hi(s,t,n))),a}function Lo(e){const{l:t,lvl:n,r}=e;if(r.lvl>=n-1&&t.lvl>=n-1)return e;if(n>r.lvl+1){if(pi(t))return Bc(pt(e,{lvl:n-1}));if(!Ue(t)&&!Ue(t.r))return pt(t.r,{l:pt(t,{r:t.r.l}),lvl:n,r:pt(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}else{if(pi(e))return mi(pt(e,{lvl:n-1}));if(!Ue(r)&&!Ue(r.l)){const o=r.l,s=pi(o)?r.lvl-1:r.lvl;return pt(o,{l:pt(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:mi(pt(r,{l:o.r,lvl:s}))})}else throw new Error("Unexpected empty nodes")}}function pt(e,t){return Fc(t.k!==void 0?t.k:e.k,t.v!==void 0?t.v:e.v,t.lvl!==void 0?t.lvl:e.lvl,t.l!==void 0?t.l:e.l,t.r!==void 0?t.r:e.r)}function Lc(e){return Ue(e.r)?e.l:Lo(pt(e,{r:Lc(e.r)}))}function pi(e){return Ue(e)||e.lvl>e.r.lvl}function $c(e){return Ue(e.r)?[e.k,e.v]:$c(e.r)}function Fc(e,t,n,r=Kr,o=Kr){return{k:e,l:r,lvl:n,r:o,v:t}}function zc(e){return mi(Bc(e))}function Bc(e){const{l:t}=e;return!Ue(t)&&t.lvl===e.lvl?pt(t,{r:pt(e,{l:t.r})}):e}function mi(e){const{lvl:t,r:n}=e;return!Ue(n)&&!Ue(n.r)&&n.lvl===t&&n.r.lvl===t?pt(n,{l:pt(e,{r:n.l}),lvl:t+1}):e}function qg(e){return Dc(e,({k:t,v:n})=>({index:t,value:n}))}function Hc(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}function Gr(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}const gi=Re(()=>({recalcInProgress:re(!1)}),[],{singleton:!0});function Uc(e,t,n){return e[$o(e,t,n)]}function $o(e,t,n,r=0){let o=e.length-1;for(;r<=o;){const s=Math.floor((r+o)/2),i=e[s],a=n(i,t);if(a===0)return s;if(a===-1){if(o-r<2)return s-1;o=s-1}else{if(o===r)return s;r=s+1}}throw new Error(`Failed binary finding record in array - ${e.join(",")}, searched for ${t}`)}function Gg(e,t,n,r){const o=$o(e,t,r),s=$o(e,n,r,o);return e.slice(o,s+1)}function jn(e,t){return Math.round(e.getBoundingClientRect()[t])}function Fo(e){return!Ue(e.groupOffsetTree)}function xi({index:e},t){return t===e?0:t<e?-1:1}function Yg(){return{groupIndices:[],groupOffsetTree:xr(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:xr()}}function Xg(e,t){let n=Ue(e)?0:1/0;for(const r of t){const{endIndex:o,size:s,startIndex:i}=r;if(n=Math.min(n,i),Ue(e)){e=Ut(e,0,s);continue}const a=Do(e,i-1,o+1);if(a.some(rx(r)))continue;let c=!1,l=!1;for(const{end:u,start:f,value:h}of a)c?(o>=f||s===h)&&(e=fi(e,f)):(l=h!==s,c=!0),u>o&&o>=f&&h!==s&&(e=Ut(e,o+1,h));l&&(e=Ut(e,i,s))}return[e,n]}function Jg(e){return typeof e.groupIndex<"u"}function Zg({offset:e},t){return t===e?0:t<e?-1:1}function Yr(e,t,n){if(t.length===0)return 0;const{index:r,offset:o,size:s}=Uc(t,e,xi),i=e-r,a=s*i+(i-1)*n+o;return a>0?a+n:a}function Wc(e,t){if(!Fo(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function Vc(e,t,n){if(Jg(e))return t.groupIndices[e.groupIndex]+1;{const r=e.index==="LAST"?n:e.index;let o=Wc(r,t);return o=Math.max(0,o,Math.min(n,o)),o}}function Qg(e,t,n,r=0){return r>0&&(t=Math.max(t,Uc(e,r,xi).offset)),Dc(Gg(e,t,n,Zg),nx)}function ex(e,[t,n,r,o]){t.length>0&&r("received item sizes",t,Dt.DEBUG);const s=e.sizeTree;let i=s,a=0;if(n.length>0&&Ue(s)&&t.length===2){const h=t[0].size,p=t[1].size;i=n.reduce((m,g)=>Ut(Ut(m,g,h),g+1,p),i)}else[i,a]=Xg(i,t);if(i===s)return e;const{lastIndex:c,lastOffset:l,lastSize:u,offsetTree:f}=bi(e.offsetTree,a,i,o);return{groupIndices:n,groupOffsetTree:n.reduce((h,p)=>Ut(h,p,Yr(p,f,o)),xr()),lastIndex:c,lastOffset:l,lastSize:u,offsetTree:f,sizeTree:i}}function tx(e){return Yn(e).map(({k:t,v:n},r,o)=>{const s=o[r+1];return{endIndex:s?s.k-1:1/0,size:n,startIndex:t}})}function Kc(e,t){let n=0,r=0;for(;n<e;)n+=t[r+1]-t[r]-1,r++;return r-(n===e?0:1)}function bi(e,t,n,r){let o=e,s=0,i=0,a=0,c=0;if(t!==0){c=$o(o,t-1,xi),a=o[c].offset;const l=nn(n,t-1);s=l[0],i=l[1],o.length&&o[c].size===nn(n,t)[1]&&(c-=1),o=o.slice(0,c+1)}else o=[];for(const{start:l,value:u}of Do(n,t,1/0)){const f=l-s,h=f*i+a+f*r;o.push({index:l,offset:h,size:u}),s=l,a=h,i=u}return{lastIndex:s,lastOffset:a,lastSize:i,offsetTree:o}}function nx(e){return{index:e.index,value:e}}function rx(e){const{endIndex:t,size:n,startIndex:r}=e;return o=>o.start===r&&(o.end===t||o.end===1/0)&&o.value===n}const ox={offsetHeight:"height",offsetWidth:"width"},fn=Re(([{log:e},{recalcInProgress:t}])=>{const n=Oe(),r=Oe(),o=vt(r,0),s=Oe(),i=Oe(),a=re(0),c=re([]),l=re(void 0),u=re(void 0),f=re((k,S)=>jn(k,ox[S])),h=re(void 0),p=re(0),m=Yg(),g=vt(ee(n,Ne(c,e,p),dn(ex,m),Je()),m),b=vt(ee(c,Je(),dn((k,S)=>({current:S,prev:k.current}),{current:[],prev:[]}),ce(({prev:k})=>k)),[]);me(ee(c,ye(k=>k.length>0),Ne(g,p),ce(([k,S,E])=>{const j=k.reduce((_,D,L)=>Ut(_,D,Yr(D,S.offsetTree,E)||L),xr());return{...S,groupIndices:k,groupOffsetTree:j}})),g),me(ee(r,Ne(g),ye(([k,{lastIndex:S}])=>k<S),ce(([k,{lastIndex:S,lastSize:E}])=>[{endIndex:S,size:E,startIndex:k}])),n),me(l,u);const v=vt(ee(l,ce(k=>k===void 0)),!0);me(ee(u,ye(k=>k!==void 0&&Ue(lt(g).sizeTree)),ce(k=>[{endIndex:0,size:k,startIndex:0}])),n);const y=Ht(ee(n,Ne(g),dn(({sizes:k},[S,E])=>({changed:E!==k,sizes:E}),{changed:!1,sizes:m}),ce(k=>k.changed)));De(ee(a,dn((k,S)=>({diff:k.prev-S,prev:S}),{diff:0,prev:0}),ce(k=>k.diff)),k=>{const{groupIndices:S}=lt(g);if(k>0)Ae(t,!0),Ae(s,k+Kc(k,S));else if(k<0){const E=lt(b);E.length>0&&(k-=Kc(-k,E)),Ae(i,k)}}),De(ee(a,Ne(e)),([k,S])=>{k<0&&S("`firstItemIndex` prop should not be set to less than zero. If you don't know the total count, just use a very high value",{firstItemIndex:a},Dt.ERROR)});const T=Ht(s);me(ee(s,Ne(g),ce(([k,S])=>{const E=S.groupIndices.length>0,j=[],_=S.lastSize;if(E){const D=qr(S.sizeTree,0);let L=0,W=0;for(;L<k;){const $=S.groupIndices[W],Z=S.groupIndices.length===W+1?1/0:S.groupIndices[W+1]-$-1;j.push({endIndex:$,size:D,startIndex:$}),j.push({endIndex:$+1+Z-1,size:_,startIndex:$+1}),W++,L+=Z+1}const V=Yn(S.sizeTree);return L!==k&&V.shift(),V.reduce(($,{k:Z,v:X})=>{let oe=$.ranges;return $.prevSize!==0&&(oe=[...$.ranges,{endIndex:Z+k-1,size:$.prevSize,startIndex:$.prevIndex}]),{prevIndex:Z+k,prevSize:X,ranges:oe}},{prevIndex:k,prevSize:0,ranges:j}).ranges}return Yn(S.sizeTree).reduce((D,{k:L,v:W})=>({prevIndex:L+k,prevSize:W,ranges:[...D.ranges,{endIndex:L+k-1,size:D.prevSize,startIndex:D.prevIndex}]}),{prevIndex:0,prevSize:_,ranges:[]}).ranges})),n);const I=Ht(ee(i,Ne(g,p),ce(([k,{offsetTree:S},E])=>{const j=-k;return Yr(j,S,E)})));return me(ee(i,Ne(g,p),ce(([k,S,E])=>{if(S.groupIndices.length>0){if(Ue(S.sizeTree))return S;let j=xr();const _=lt(b);let D=0,L=0,W=0;for(;D<-k;){W=_[L];const V=_[L+1]-W-1;L++,D+=V+1}if(j=Yn(S.sizeTree).reduce((V,{k:$,v:Z})=>Ut(V,Math.max(0,$+k),Z),j),D!==-k){const V=qr(S.sizeTree,W);j=Ut(j,0,V);const $=nn(S.sizeTree,-k+1)[1];j=Ut(j,1,$)}return{...S,sizeTree:j,...bi(S.offsetTree,0,j,E)}}else{const j=Yn(S.sizeTree).reduce((_,{k:D,v:L})=>Ut(_,Math.max(0,D+k),L),xr());return{...S,sizeTree:j,...bi(S.offsetTree,0,j,E)}}})),g),{beforeUnshiftWith:T,data:h,defaultItemSize:u,firstItemIndex:a,fixedItemSize:l,gap:p,groupIndices:c,itemSize:f,listRefresh:y,shiftWith:i,shiftWithOffset:I,sizeRanges:n,sizes:g,statefulTotalCount:o,totalCount:r,trackItemSizes:v,unshiftWith:s}},Xe(_n,gi),{singleton:!0});function sx(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const qc=Re(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:r,scrollTop:o}])=>{const s=Oe(),i=Oe(),a=Ht(ee(s,ce(sx)));return me(ee(a,ce(c=>c.totalCount)),n),me(ee(a,ce(c=>c.groupIndices)),e),me(ee(ft(o,t,r),ye(([c,l])=>Fo(l)),ce(([c,l,u])=>nn(l.groupOffsetTree,Math.max(c-u,0),"v")[0]),Je(),ce(c=>[c])),i),{groupCounts:s,topItemsIndexes:i}},Xe(fn,Nt)),Pn=Re(([{log:e}])=>{const t=re(!1),n=Ht(ee(t,ye(r=>r),Je()));return De(t,r=>{r&&lt(e)("props updated",{},Dt.DEBUG)}),{didMount:n,propsReady:t}},Xe(_n),{singleton:!0}),ix=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function Gc(e){const t=typeof e=="number"?{index:e}:e;return t.align||(t.align="start"),(!t.behavior||!ix)&&(t.behavior="auto"),t.offset||(t.offset=0),t}const Xr=Re(([{gap:e,listRefresh:t,sizes:n,totalCount:r},{fixedFooterHeight:o,fixedHeaderHeight:s,footerHeight:i,headerHeight:a,scrollingInProgress:c,scrollTo:l,smoothScrollTargetReached:u,viewportHeight:f},{log:h}])=>{const p=Oe(),m=Oe(),g=re(0);let b=null,v=null,y=null;function T(){b&&(b(),b=null),y&&(y(),y=null),v&&(clearTimeout(v),v=null),Ae(c,!1)}return me(ee(p,Ne(n,f,r,g,a,i,h),Ne(e,s,o),ce(([[I,k,S,E,j,_,D,L],W,V,$])=>{const Z=Gc(I),{align:X,behavior:oe,offset:U}=Z,F=E-1,G=Vc(Z,k,F);let H=Yr(G,k.offsetTree,W)+_;X==="end"?(H+=V+nn(k.sizeTree,G)[1]-S+$,G===F&&(H+=D)):X==="center"?H+=(V+nn(k.sizeTree,G)[1]-S+$)/2:H-=j,U&&(H+=U);const A=N=>{T(),N?(L("retrying to scroll to",{location:I},Dt.DEBUG),Ae(p,I)):(Ae(m,!0),L("list did not change, scroll successful",{},Dt.DEBUG))};if(T(),oe==="smooth"){let N=!1;y=De(t,R=>{N=N||R}),b=tn(u,()=>{A(N)})}else b=tn(ee(t,ax(150)),A);return v=setTimeout(()=>{T()},1200),Ae(c,!0),L("scrolling from index to",{behavior:oe,index:G,top:H},Dt.DEBUG),{behavior:oe,top:H}})),l),{scrollTargetReached:m,scrollToIndex:p,topListHeight:g}},Xe(fn,Nt,_n),{singleton:!0});function ax(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return r=>{r&&(t(!0),clearTimeout(n))}}}function wi(e,t){e==0?t():requestAnimationFrame(()=>{wi(e-1,t)})}function vi(e,t){const n=t-1;return typeof e=="number"?e:e.index==="LAST"?n:e.index}const Jr=Re(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:r},{scrollTargetReached:o,scrollToIndex:s},{didMount:i}])=>{const a=re(!0),c=re(0),l=re(!0);return me(ee(i,Ne(c),ye(([u,f])=>!!f),un(!1)),a),me(ee(i,Ne(c),ye(([u,f])=>!!f),un(!1)),l),De(ee(ft(t,i),Ne(a,n,e,l),ye(([[,u],f,{sizeTree:h},p,m])=>u&&(!Ue(h)||li(p))&&!f&&!m),Ne(c)),([,u])=>{tn(o,()=>{Ae(l,!0)}),wi(4,()=>{tn(r,()=>{Ae(a,!0)}),Ae(s,u)})}),{initialItemFinalLocationReached:l,initialTopMostItemIndex:c,scrolledToInitialItem:a}},Xe(fn,Nt,Xr,Pn),{singleton:!0});function Yc(e,t){return Math.abs(e-t)<1.01}const Zr="up",Qr="down",lx="none",cx={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},ux=0,eo=Re(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:r,scrollTop:o,viewportHeight:s}])=>{const i=re(!1),a=re(!0),c=Oe(),l=Oe(),u=re(4),f=re(ux),h=vt(ee(ui(ee(ve(o),qn(1),un(!0)),ee(ve(o),qn(1),un(!1),Pc(100))),Je()),!1),p=vt(ee(ui(ee(n,un(!0)),ee(n,un(!1),Pc(200))),Je()),!1);me(ee(ft(ve(o),ve(f)),ce(([y,T])=>y<=T),Je()),a),me(ee(a,yn(50)),l);const m=Ht(ee(ft(r,ve(s),ve(t),ve(e),ve(u)),dn((y,[{scrollHeight:T,scrollTop:I},k,S,E,j])=>{const _=I+k-T>-j,D={scrollHeight:T,scrollTop:I,viewportHeight:k};if(_){let W,V;return I>y.state.scrollTop?(W="SCROLLED_DOWN",V=y.state.scrollTop-I):(W="SIZE_DECREASED",V=y.state.scrollTop-I||y.scrollTopDelta),{atBottom:!0,atBottomBecause:W,scrollTopDelta:V,state:D}}let L;return D.scrollHeight>y.state.scrollHeight?L="SIZE_INCREASED":k<y.state.viewportHeight?L="VIEWPORT_HEIGHT_DECREASING":I<y.state.scrollTop?L="SCROLLING_UPWARDS":L="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:L,state:D}},cx),Je((y,T)=>y&&y.atBottom===T.atBottom))),g=vt(ee(r,dn((y,{scrollHeight:T,scrollTop:I,viewportHeight:k})=>{if(Yc(y.scrollHeight,T))return{changed:!1,jump:0,scrollHeight:T,scrollTop:I};{const S=T-(I+k)<1;return y.scrollTop!==I&&S?{changed:!0,jump:y.scrollTop-I,scrollHeight:T,scrollTop:I}:{changed:!0,jump:0,scrollHeight:T,scrollTop:I}}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),ye(y=>y.changed),ce(y=>y.jump)),0);me(ee(m,ce(y=>y.atBottom)),i),me(ee(i,yn(50)),c);const b=re(Qr);me(ee(r,ce(({scrollTop:y})=>y),Je(),dn((y,T)=>lt(p)?{direction:y.direction,prevScrollTop:T}:{direction:T<y.prevScrollTop?Zr:Qr,prevScrollTop:T},{direction:Qr,prevScrollTop:0}),ce(y=>y.direction)),b),me(ee(r,yn(50),un(lx)),b);const v=re(0);return me(ee(h,ye(y=>!y),un(0)),v),me(ee(o,yn(100),Ne(h),ye(([y,T])=>!!T),dn(([y,T],[I])=>[T,I],[0,0]),ce(([y,T])=>T-y)),v),{atBottomState:m,atBottomStateChange:c,atBottomThreshold:u,atTopStateChange:l,atTopThreshold:f,isAtBottom:i,isAtTop:a,isScrolling:h,lastJumpDueToItemResize:g,scrollDirection:b,scrollVelocity:v}},Xe(Nt)),zo="top",Bo="bottom",Xc="none";function Jc(e,t,n){return typeof e=="number"?n===Zr&&t===zo||n===Qr&&t===Bo?e:0:n===Zr?t===zo?e.main:e.reverse:t===Bo?e.main:e.reverse}function Zc(e,t){var n;return typeof e=="number"?e:(n=e[t])!=null?n:0}const yi=Re(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:r,viewportHeight:o}])=>{const s=Oe(),i=re(0),a=re(0),c=re(0),l=vt(ee(ft(ve(r),ve(o),ve(n),ve(s,Gr),ve(c),ve(i),ve(t),ve(e),ve(a)),ce(([u,f,h,[p,m],g,b,v,y,T])=>{const I=u-y,k=b+v,S=Math.max(h-I,0);let E=Xc;const j=Zc(T,zo),_=Zc(T,Bo);return p-=y,p+=h+v,m+=h+v,m-=y,p>u+k-j&&(E=Zr),m<u-S+f+_&&(E=Qr),E!==Xc?[Math.max(I-h-Jc(g,zo,E)-j,0),I-S-v+f+Jc(g,Bo,E)+_]:null}),ye(u=>u!=null),Je(Gr)),[0,0]);return{increaseViewportBy:a,listBoundary:s,overscan:c,topListHeight:i,visibleRange:l}},Xe(Nt),{singleton:!0});function dx(e,t,n){if(Fo(t)){const r=Wc(e,t);return[{index:nn(t.groupOffsetTree,r)[0],offset:0,size:0},{data:n==null?void 0:n[0],index:r,offset:0,size:0}]}return[{data:n==null?void 0:n[0],index:e,offset:0,size:0}]}const Si={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function Ho(e,t,n,r,o,s){const{lastIndex:i,lastOffset:a,lastSize:c}=o;let l=0,u=0;if(e.length>0){l=e[0].offset;const g=e[e.length-1];u=g.offset+g.size}const f=n-i,h=a+f*c+(f-1)*r,p=l,m=h-u;return{bottom:u,firstItemIndex:s,items:eu(e,o,s),offsetBottom:m,offsetTop:l,top:p,topItems:eu(t,o,s),topListHeight:t.reduce((g,b)=>b.size+g,0),totalCount:n}}function Qc(e,t,n,r,o,s){let i=0;if(n.groupIndices.length>0)for(const u of n.groupIndices){if(u-i>=e)break;i++}const a=e+i,c=vi(t,a),l=Array.from({length:a}).map((u,f)=>({data:s[f+c],index:f+c,offset:0,size:0}));return Ho(l,[],a,o,n,r)}function eu(e,t,n){if(e.length===0)return[];if(!Fo(t))return e.map(l=>({...l,index:l.index+n,originalIndex:l.index}));const r=e[0].index,o=e[e.length-1].index,s=[],i=Do(t.groupOffsetTree,r,o);let a,c=0;for(const l of e){(!a||a.end<l.index)&&(a=i.shift(),c=t.groupIndices.indexOf(a.start));let u;l.index===a.start?u={index:c,type:"group"}:u={groupIndex:c,index:l.index-(c+1)+n},s.push({...u,data:l.data,offset:l.offset,originalIndex:l.index,size:l.size})}return s}const Xn=Re(([{data:e,firstItemIndex:t,gap:n,sizes:r,totalCount:o},s,{listBoundary:i,topListHeight:a,visibleRange:c},{initialTopMostItemIndex:l,scrolledToInitialItem:u},{topListHeight:f},h,{didMount:p},{recalcInProgress:m}])=>{const g=re([]),b=re(0),v=Oe();me(s.topItemsIndexes,g);const y=vt(ee(ft(p,m,ve(c,Gr),ve(o),ve(r),ve(l),u,ve(g),ve(t),ve(n),e),ye(([S,E,,j,,,,,,,_])=>{const D=_&&_.length!==j;return S&&!E&&!D}),ce(([,,[S,E],j,_,D,L,W,V,$,Z])=>{const X=_,{offsetTree:oe,sizeTree:U}=X,F=lt(b);if(j===0)return{...Si,totalCount:j};if(S===0&&E===0)return F===0?{...Si,totalCount:j}:Qc(F,D,_,V,$,Z||[]);if(Ue(U))return F>0?null:Ho(dx(vi(D,j),X,Z),[],j,$,X,V);const G=[];if(W.length>0){const M=W[0],q=W[W.length-1];let J=0;for(const P of Do(U,M,q)){const K=P.value,te=Math.max(P.start,M),le=Math.min(P.end,q);for(let he=te;he<=le;he++)G.push({data:Z==null?void 0:Z[he],index:he,offset:J,size:K}),J+=K}}if(!L)return Ho([],G,j,$,X,V);const H=W.length>0?W[W.length-1]+1:0,A=Qg(oe,S,E,H);if(A.length===0)return null;const N=j-1,R=Mo([],M=>{for(const q of A){const J=q.value;let P=J.offset,K=q.start;const te=J.size;if(J.offset<S){K+=Math.floor((S-J.offset+$)/(te+$));const he=K-q.start;P+=he*te+he*$}K<H&&(P+=(H-K)*te,K=H);const le=Math.min(q.end,N);for(let he=K;he<=le&&!(P>=E);he++)M.push({data:Z==null?void 0:Z[he],index:he,offset:P,size:te}),P+=te+$}});return Ho(R,G,j,$,X,V)}),ye(S=>S!==null),Je()),Si);me(ee(e,ye(li),ce(S=>S==null?void 0:S.length)),o),me(ee(y,ce(S=>S.topListHeight)),f),me(f,a),me(ee(y,ce(S=>[S.top,S.bottom])),i),me(ee(y,ce(S=>S.items)),v);const T=Ht(ee(y,ye(({items:S})=>S.length>0),Ne(o,e),ye(([{items:S},E])=>S[S.length-1].originalIndex===E-1),ce(([,S,E])=>[S-1,E]),Je(Gr),ce(([S])=>S))),I=Ht(ee(y,yn(200),ye(({items:S,topItems:E})=>S.length>0&&S[0].originalIndex===E.length),ce(({items:S})=>S[0].index),Je())),k=Ht(ee(y,ye(({items:S})=>S.length>0),ce(({items:S})=>{let E=0,j=S.length-1;for(;S[E].type==="group"&&E<j;)E++;for(;S[j].type==="group"&&j>E;)j--;return{endIndex:S[j].index,startIndex:S[E].index}}),Je(Hc)));return{endReached:T,initialItemCount:b,itemsRendered:v,listState:y,rangeChanged:k,startReached:I,topItemsIndexes:g,...h}},Xe(fn,qc,yi,Jr,Xr,eo,Pn,gi),{singleton:!0}),tu=Re(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:r},{listState:o}])=>{const s=Oe(),i=vt(ee(ft(n,e,r,t,o),ce(([a,c,l,u,f])=>a+c+l+u+f.offsetBottom+f.bottom)),0);return me(ve(i),s),{totalListHeight:i,totalListHeightChanged:s}},Xe(Nt,Xn),{singleton:!0}),fx=Re(([{viewportHeight:e},{totalListHeight:t}])=>{const n=re(!1),r=vt(ee(ft(n,e,t),ye(([o])=>o),ce(([,o,s])=>Math.max(0,o-s)),yn(0),Je()),0);return{alignToBottom:n,paddingTopAddition:r}},Xe(Nt,tu),{singleton:!0}),nu=Re(()=>({context:re(null)})),hx=({itemBottom:e,itemTop:t,locationParams:{align:n,behavior:r,...o},viewportBottom:s,viewportTop:i})=>t<i?{...o,align:n??"start",behavior:r}:e>s?{...o,align:n??"end",behavior:r}:null,ru=Re(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:s,scrollingInProgress:i,scrollTop:a,viewportHeight:c},{scrollToIndex:l}])=>{const u=Oe();return me(ee(u,Ne(t,c,n,s,o,r,a),Ne(e),ce(([[f,h,p,m,g,b,v,y],T])=>{const{align:I,behavior:k,calculateViewLocation:S=hx,done:E,...j}=f,_=Vc(f,h,m-1),D=Yr(_,h.offsetTree,T)+g+b,L=D+nn(h.sizeTree,_)[1],W=y+b,V=y+p-v,$=S({itemBottom:L,itemTop:D,locationParams:{align:I,behavior:k,...j},viewportBottom:V,viewportTop:W});return $?E&&tn(ee(i,ye(Z=>!Z),qn(lt(i)?1:2)),E):E&&E(),$}),ye(f=>f!==null)),l),{scrollIntoView:u}},Xe(fn,Nt,Xr,Xn,_n),{singleton:!0});function ou(e){return e?e==="smooth"?"smooth":"auto":!1}const px=(e,t)=>typeof e=="function"?ou(e(t)):t&&ou(e),mx=Re(([{listRefresh:e,totalCount:t,fixedItemSize:n,data:r},{atBottomState:o,isAtBottom:s},{scrollToIndex:i},{scrolledToInitialItem:a},{didMount:c,propsReady:l},{log:u},{scrollingInProgress:f},{context:h},{scrollIntoView:p}])=>{const m=re(!1),g=Oe();let b=null;function v(k){Ae(i,{align:"end",behavior:k,index:"LAST"})}De(ee(ft(ee(ve(t),qn(1)),c),Ne(ve(m),s,a,f),ce(([[k,S],E,j,_,D])=>{let L=S&&_,W="auto";return L&&(W=px(E,j||D),L=L&&!!W),{followOutputBehavior:W,shouldFollow:L,totalCount:k}}),ye(({shouldFollow:k})=>k)),({followOutputBehavior:k,totalCount:S})=>{b&&(b(),b=null),lt(n)?requestAnimationFrame(()=>{lt(u)("following output to ",{totalCount:S},Dt.DEBUG),v(k)}):b=tn(e,()=>{lt(u)("following output to ",{totalCount:S},Dt.DEBUG),v(k),b=null})});function y(k){const S=tn(o,E=>{k&&!E.atBottom&&E.notAtBottomBecause==="SIZE_INCREASED"&&!b&&(lt(u)("scrolling to bottom due to increased size",{},Dt.DEBUG),v("auto"))});setTimeout(S,100)}De(ee(ft(ve(m),t,l),ye(([k,,S])=>k&&S),dn(({value:k},[,S])=>({refreshed:k===S,value:S}),{refreshed:!1,value:0}),ye(({refreshed:k})=>k),Ne(m,t)),([,k])=>{lt(a)&&y(k!==!1)}),De(g,()=>{y(lt(m)!==!1)}),De(ft(ve(m),o),([k,S])=>{k&&!S.atBottom&&S.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&v("auto")});const T=re(null),I=Oe();return me(ui(ee(ve(r),ce(k=>{var S;return(S=k==null?void 0:k.length)!=null?S:0})),ee(ve(t))),I),De(ee(ft(ee(I,qn(1)),c),Ne(ve(T),a,f,h),ce(([[k,S],E,j,_,D])=>S&&j&&(E==null?void 0:E({context:D,totalCount:k,scrollingInProgress:_}))),ye(k=>!!k),yn(0)),k=>{b&&(b(),b=null),lt(n)?requestAnimationFrame(()=>{lt(u)("scrolling into view",{}),Ae(p,k)}):b=tn(e,()=>{lt(u)("scrolling into view",{}),Ae(p,k),b=null})}),{autoscrollToBottom:g,followOutput:m,scrollIntoViewOnChange:T}},Xe(fn,eo,Xr,Jr,Pn,_n,Nt,nu,ru)),gx=Re(([{data:e,firstItemIndex:t,gap:n,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:s,listState:i},{didMount:a}])=>(me(ee(a,Ne(s),ye(([,c])=>c!==0),Ne(o,r,t,n,e),ce(([[,c],l,u,f,h,p=[]])=>Qc(c,l,u,f,h,p))),i),{}),Xe(fn,Jr,Xn,Pn),{singleton:!0}),xx=Re(([{didMount:e},{scrollTo:t},{listState:n}])=>{const r=re(0);return De(ee(e,Ne(r),ye(([,o])=>o!==0),ce(([,o])=>({top:o}))),o=>{tn(ee(n,qn(1),ye(s=>s.items.length>1)),()=>{requestAnimationFrame(()=>{Ae(t,o)})})}),{initialScrollTop:r}},Xe(Pn,Nt,Xn),{singleton:!0}),su=Re(([{scrollVelocity:e}])=>{const t=re(!1),n=Oe(),r=re(!1);return me(ee(e,Ne(r,t,n),ye(([o,s])=>!!s),ce(([o,s,i,a])=>{const{enter:c,exit:l}=s;if(i){if(l(o,a))return!1}else if(c(o,a))return!0;return i}),Je()),t),De(ee(ft(t,e,n),Ne(r)),([[o,s,i],a])=>{o&&a&&a.change&&a.change(s,i)}),{isSeeking:t,scrollSeekConfiguration:r,scrollSeekRangeChanged:n,scrollVelocity:e}},Xe(eo),{singleton:!0}),Ci=Re(([{scrollContainerState:e,scrollTo:t}])=>{const n=Oe(),r=Oe(),o=Oe(),s=re(!1),i=re(void 0);return me(ee(ft(n,r),ce(([{scrollHeight:a,scrollTop:c,viewportHeight:l},{offsetTop:u}])=>({scrollHeight:a,scrollTop:Math.max(0,c-u),viewportHeight:l}))),e),me(ee(t,Ne(r),ce(([a,{offsetTop:c}])=>({...a,top:a.top+c}))),o),{customScrollParent:i,useWindowScroll:s,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:r}},Xe(Nt)),bx=Re(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:r},{initialTopMostItemIndex:o},{didMount:s},{useWindowScroll:i,windowScrollContainerState:a,windowViewportRect:c}])=>{const l=Oe(),u=re(void 0),f=re(null),h=re(null);return me(a,f),me(c,h),De(ee(l,Ne(t,r,i,f,h,n)),([p,m,g,b,v,y,T])=>{const I=tx(m.sizeTree);b&&v!==null&&y!==null&&(g=v.scrollTop-y.offsetTop),g-=T,p({ranges:I,scrollTop:g})}),me(ee(u,ye(li),ce(wx)),o),me(ee(s,Ne(u),ye(([,p])=>p!==void 0),Je(),ce(([,p])=>p.ranges)),e),{getState:l,restoreStateFrom:u}},Xe(fn,Nt,Jr,Pn,Ci));function wx(e){return{align:"start",index:0,offset:e.scrollTop}}const vx=Re(([{topItemsIndexes:e}])=>{const t=re(0);return me(ee(t,ye(n=>n>=0),ce(n=>Array.from({length:n}).map((r,o)=>o))),e),{topItemCount:t}},Xe(Xn));function iu(e){let t=!1,n;return()=>(t||(t=!0,n=e()),n)}const yx=iu(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),Sx=Re(([{deviation:e,scrollBy:t,scrollingInProgress:n,scrollTop:r},{isAtBottom:o,isScrolling:s,lastJumpDueToItemResize:i,scrollDirection:a},{listState:c},{beforeUnshiftWith:l,gap:u,shiftWithOffset:f,sizes:h},{log:p},{recalcInProgress:m}])=>{const g=Ht(ee(c,Ne(i),dn(([,v,y,T],[{bottom:I,items:k,offsetBottom:S,totalCount:E},j])=>{const _=I+S;let D=0;return y===E&&v.length>0&&k.length>0&&(k[0].originalIndex===0&&v[0].originalIndex===0||(D=_-T,D!==0&&(D+=j))),[D,k,E,_]},[0,[],0,0]),ye(([v])=>v!==0),Ne(r,a,n,o,p,m),ye(([,v,y,T,,,I])=>!I&&!T&&v!==0&&y===Zr),ce(([[v],,,,,y])=>(y("Upward scrolling compensation",{amount:v},Dt.DEBUG),v))));function b(v){v>0?(Ae(t,{behavior:"auto",top:-v}),Ae(e,0)):(Ae(e,0),Ae(t,{behavior:"auto",top:-v}))}return De(ee(g,Ne(e,s)),([v,y,T])=>{T&&yx()?Ae(e,y-v):b(-v)}),De(ee(ft(vt(s,!1),e,m),ye(([v,y,T])=>!v&&!T&&y!==0),ce(([v,y])=>y),yn(1)),b),me(ee(f,ce(v=>({top:-v}))),t),De(ee(l,Ne(h,u),ce(([v,{groupIndices:y,lastSize:T,sizeTree:I},k])=>{function S(E){return E*(T+k)}if(y.length===0)return S(v);{let E=0;const j=qr(I,0);let _=0,D=0;for(;_<v;){_++,E+=j;let L=y.length===D+1?1/0:y[D+1]-y[D]-1;_+L>v&&(E-=j,L=v-_+1),_+=L,E+=S(L),D++}return E}})),v=>{Ae(e,v),requestAnimationFrame(()=>{Ae(t,{top:v}),requestAnimationFrame(()=>{Ae(e,0),Ae(m,!1)})})}),{deviation:e}},Xe(Nt,eo,Xn,fn,_n,gi)),Cx=Re(([e,t,n,r,o,s,i,a,c,l,u])=>({...e,...t,...n,...r,...o,...s,...i,...a,...c,...l,...u}),Xe(yi,gx,Pn,su,tu,xx,fx,Ci,ru,_n,nu)),au=Re(([{data:e,defaultItemSize:t,firstItemIndex:n,fixedItemSize:r,gap:o,groupIndices:s,itemSize:i,sizeRanges:a,sizes:c,statefulTotalCount:l,totalCount:u,trackItemSizes:f},{initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:m},g,b,v,{listState:y,topItemsIndexes:T,...I},{scrollToIndex:k},S,{topItemCount:E},{groupCounts:j},_])=>(me(I.rangeChanged,_.scrollSeekRangeChanged),me(ee(_.windowViewportRect,ce(D=>D.visibleHeight)),g.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:r,gap:o,groupCounts:j,initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:m,sizeRanges:a,topItemCount:E,topItemsIndexes:T,totalCount:u,...v,groupIndices:s,itemSize:i,listState:y,scrollToIndex:k,statefulTotalCount:l,trackItemSizes:f,...I,..._,...g,sizes:c,...b}),Xe(fn,Jr,Nt,bx,mx,Xn,Xr,Sx,vx,qc,Cx));function kx(e,t){const n={},r={};let o=0;const s=e.length;for(;o<s;)r[e[o]]=1,o+=1;for(const i in t)Object.hasOwn(r,i)||(n[i]=t[i]);return n}const Uo=typeof document<"u"?x.useLayoutEffect:x.useEffect;function lu(e,t,n){const r=Object.keys(t.required||{}),o=Object.keys(t.optional||{}),s=Object.keys(t.methods||{}),i=Object.keys(t.events||{}),a=x.createContext({});function c(b,v){b.propsReady&&Ae(b.propsReady,!1);for(const y of r){const T=b[t.required[y]];Ae(T,v[y])}for(const y of o)if(y in v){const T=b[t.optional[y]];Ae(T,v[y])}b.propsReady&&Ae(b.propsReady,!0)}function l(b){return s.reduce((v,y)=>(v[y]=T=>{const I=b[t.methods[y]];Ae(I,T)},v),{})}function u(b){return i.reduce((v,y)=>(v[y]=zg(b[t.events[y]]),v),{})}const f=x.forwardRef((b,v)=>{const{children:y,...T}=b,[I]=x.useState(()=>Mo(Hg(e),E=>{c(E,T)})),[k]=x.useState(jc(u,I));Uo(()=>{for(const E of i)E in T&&De(k[E],T[E]);return()=>{Object.values(k).map(ci)}},[T,k,I]),Uo(()=>{c(I,T)}),x.useImperativeHandle(v,Nc(l(I)));const S=n;return d.jsx(a.Provider,{value:I,children:n?d.jsx(S,{...kx([...r,...o,...i],T),children:y}):y})}),h=b=>{const v=x.useContext(a);return x.useCallback(y=>{Ae(v[b],y)},[v,b])},p=b=>{const v=x.useContext(a)[b],y=x.useCallback(T=>De(v,T),[v]);return x.useSyncExternalStore(y,()=>lt(v),()=>lt(v))},m=b=>{const v=x.useContext(a)[b],[y,T]=x.useState(jc(lt,v));return Uo(()=>De(v,I=>{I!==y&&T(Nc(I))}),[v,y]),y},g=x.version.startsWith("18")?p:m;return{Component:f,useEmitter:(b,v)=>{const y=x.useContext(a)[b];Uo(()=>De(y,v),[v,y])},useEmitterValue:g,usePublisher:h}}const cu=x.createContext(void 0),uu=x.createContext(void 0),du=typeof document<"u"?x.useLayoutEffect:x.useEffect;function ki(e){return"self"in e}function Tx(e){return"body"in e}function fu(e,t,n,r=gr,o,s){const i=x.useRef(null),a=x.useRef(null),c=x.useRef(null),l=x.useCallback(h=>{let p,m,g;const b=h.target;if(Tx(b)||ki(b)){const y=ki(b)?b:b.defaultView;g=s?y.scrollX:y.scrollY,p=s?y.document.documentElement.scrollWidth:y.document.documentElement.scrollHeight,m=s?y.innerWidth:y.innerHeight}else g=s?b.scrollLeft:b.scrollTop,p=s?b.scrollWidth:b.scrollHeight,m=s?b.offsetWidth:b.offsetHeight;const v=()=>{e({scrollHeight:p,scrollTop:Math.max(g,0),viewportHeight:m})};h.suppressFlushSync?v():Ls.flushSync(v),a.current!==null&&(g===a.current||g<=0||g===p-m)&&(a.current=null,t(!0),c.current&&(clearTimeout(c.current),c.current=null))},[e,t,s]);x.useEffect(()=>{const h=o||i.current;return r(o||i.current),l({suppressFlushSync:!0,target:h}),h.addEventListener("scroll",l,{passive:!0}),()=>{r(null),h.removeEventListener("scroll",l)}},[i,l,n,r,o]);function u(h){const p=i.current;if(!p||(s?"offsetWidth"in p&&p.offsetWidth===0:"offsetHeight"in p&&p.offsetHeight===0))return;const m=h.behavior==="smooth";let g,b,v;ki(p)?(b=Math.max(jn(p.document.documentElement,s?"width":"height"),s?p.document.documentElement.scrollWidth:p.document.documentElement.scrollHeight),g=s?p.innerWidth:p.innerHeight,v=s?window.scrollX:window.scrollY):(b=p[s?"scrollWidth":"scrollHeight"],g=jn(p,s?"width":"height"),v=p[s?"scrollLeft":"scrollTop"]);const y=b-g;if(h.top=Math.ceil(Math.max(Math.min(y,h.top),0)),Yc(g,b)||h.top===v){e({scrollHeight:b,scrollTop:v,viewportHeight:g}),m&&t(!0);return}m?(a.current=h.top,c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{c.current=null,a.current=null,t(!0)},1e3)):a.current=null,s&&(h={behavior:h.behavior,left:h.top}),p.scrollTo(h)}function f(h){s&&(h={behavior:h.behavior,left:h.top}),i.current.scrollBy(h)}return{scrollByCallback:f,scrollerRef:i,scrollToCallback:u}}const Ti="-webkit-sticky",hu="sticky",Ei=iu(()=>{if(typeof document>"u")return hu;const e=document.createElement("div");return e.style.position=Ti,e.style.position===Ti?Ti:hu});function Ii(e){return e}const Ex=Re(()=>{const e=re(a=>`Item ${a}`),t=re(a=>`Group ${a}`),n=re({}),r=re(Ii),o=re("div"),s=re(gr),i=(a,c=null)=>vt(ee(n,ce(l=>l[a]),Je()),c);return{components:n,computeItemKey:r,EmptyPlaceholder:i("EmptyPlaceholder"),FooterComponent:i("Footer"),GroupComponent:i("Group","div"),groupContent:t,HeaderComponent:i("Header"),HeaderFooterTag:o,ItemComponent:i("Item","div"),itemContent:e,ListComponent:i("List","div"),ScrollerComponent:i("Scroller","div"),scrollerRef:s,ScrollSeekPlaceholder:i("ScrollSeekPlaceholder"),TopItemListComponent:i("TopItemList")}}),Ix=Re(([e,t])=>({...e,...t}),Xe(au,Ex)),Ax=({height:e})=>d.jsx("div",{style:{height:e}}),Nx={overflowAnchor:"none",position:Ei(),zIndex:1},pu={overflowAnchor:"none"},_x={...pu,display:"inline-block",height:"100%"},mu=x.memo(function({showTopList:e=!1}){const t=ke("listState"),n=Yt("sizeRanges"),r=ke("useWindowScroll"),o=ke("customScrollParent"),s=Yt("windowScrollContainerState"),i=Yt("scrollContainerState"),a=o||r?s:i,c=ke("itemContent"),l=ke("context"),u=ke("groupContent"),f=ke("trackItemSizes"),h=ke("itemSize"),p=ke("log"),m=Yt("gap"),g=ke("horizontalDirection"),{callbackRef:b}=Vg(n,h,f,e?gr:a,p,m,o,g,ke("skipAnimationFrameInResizeObserver")),[v,y]=x.useState(0);Ai("deviation",$=>{v!==$&&y($)});const T=ke("EmptyPlaceholder"),I=ke("ScrollSeekPlaceholder")||Ax,k=ke("ListComponent"),S=ke("ItemComponent"),E=ke("GroupComponent"),j=ke("computeItemKey"),_=ke("isSeeking"),D=ke("groupIndices").length>0,L=ke("alignToBottom"),W=ke("initialItemFinalLocationReached"),V=e?{}:{boxSizing:"border-box",...g?{display:"inline-block",height:"100%",marginLeft:v!==0?v:L?"auto":0,paddingLeft:t.offsetTop,paddingRight:t.offsetBottom,whiteSpace:"nowrap"}:{marginTop:v!==0?v:L?"auto":0,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...W?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&T?d.jsx(T,{...yt(T,l)}):d.jsx(k,{...yt(k,l),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:b,style:V,children:(e?t.topItems:t.items).map($=>{const Z=$.originalIndex,X=j(Z+t.firstItemIndex,$.data,l);return _?x.createElement(I,{...yt(I,l),height:$.size,index:$.index,key:X,type:$.type||"item",...$.type==="group"?{}:{groupIndex:$.groupIndex}}):$.type==="group"?x.createElement(E,{...yt(E,l),"data-index":Z,"data-item-index":$.index,"data-known-size":$.size,key:X,style:Nx},u($.index,l)):x.createElement(S,{...yt(S,l),...Rx(S,$.data),"data-index":Z,"data-item-group-index":$.groupIndex,"data-item-index":$.index,"data-known-size":$.size,key:X,style:g?_x:pu},D?c($.index,$.groupIndex,$.data,l):c($.index,$.data,l))})})}),jx={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},Px={outline:"none",overflowX:"auto",position:"relative"},Wo=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:{}}),Ox={position:Ei(),top:0,width:"100%",zIndex:1};function yt(e,t){if(typeof e!="string")return{context:t}}function Rx(e,t){return{item:typeof e=="string"?void 0:t}}const Mx=x.memo(function(){const e=ke("HeaderComponent"),t=Yt("headerHeight"),n=ke("HeaderFooterTag"),r=Gn(x.useMemo(()=>s=>{t(jn(s,"height"))},[t]),!0,ke("skipAnimationFrameInResizeObserver")),o=ke("context");return e?d.jsx(n,{ref:r,children:d.jsx(e,{...yt(e,o)})}):null}),Dx=x.memo(function(){const e=ke("FooterComponent"),t=Yt("footerHeight"),n=ke("HeaderFooterTag"),r=Gn(x.useMemo(()=>s=>{t(jn(s,"height"))},[t]),!0,ke("skipAnimationFrameInResizeObserver")),o=ke("context");return e?d.jsx(n,{ref:r,children:d.jsx(e,{...yt(e,o)})}):null});function gu({useEmitter:e,useEmitterValue:t,usePublisher:n}){return x.memo(function({children:r,style:o,context:s,...i}){const a=n("scrollContainerState"),c=t("ScrollerComponent"),l=n("smoothScrollTargetReached"),u=t("scrollerRef"),f=t("horizontalDirection")||!1,{scrollByCallback:h,scrollerRef:p,scrollToCallback:m}=fu(a,l,c,u,void 0,f);return e("scrollTo",m),e("scrollBy",h),d.jsx(c,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:p,style:{...f?Px:jx,...o},tabIndex:0,...i,...yt(c,s),children:r})})}function xu({useEmitter:e,useEmitterValue:t,usePublisher:n}){return x.memo(function({children:r,style:o,context:s,...i}){const a=n("windowScrollContainerState"),c=t("ScrollerComponent"),l=n("smoothScrollTargetReached"),u=t("totalListHeight"),f=t("deviation"),h=t("customScrollParent"),p=x.useRef(null),m=t("scrollerRef"),{scrollByCallback:g,scrollerRef:b,scrollToCallback:v}=fu(a,l,c,m,h);return du(()=>{var y;return b.current=h||((y=p.current)==null?void 0:y.ownerDocument.defaultView),()=>{b.current=null}},[b,h]),e("windowScrollTo",v),e("scrollBy",g),d.jsx(c,{ref:p,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...u!==0?{height:u+f}:{}},...i,...yt(c,s),children:r})})}const Lx=({children:e})=>{const t=x.useContext(cu),n=Yt("viewportHeight"),r=Yt("fixedItemHeight"),o=ke("alignToBottom"),s=ke("horizontalDirection"),i=x.useMemo(()=>_c(n,c=>jn(c,s?"width":"height")),[n,s]),a=Gn(i,!0,ke("skipAnimationFrameInResizeObserver"));return x.useEffect(()=>{t&&(n(t.viewportHeight),r(t.itemHeight))},[t,n,r]),d.jsx("div",{"data-viewport-type":"element",ref:a,style:Wo(o),children:e})},$x=({children:e})=>{const t=x.useContext(cu),n=Yt("windowViewportRect"),r=Yt("fixedItemHeight"),o=ke("customScrollParent"),s=Mc(n,o,ke("skipAnimationFrameInResizeObserver")),i=ke("alignToBottom");return x.useEffect(()=>{t&&(r(t.itemHeight),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:100}))},[t,n,r]),d.jsx("div",{"data-viewport-type":"window",ref:s,style:Wo(i),children:e})},Fx=({children:e})=>{const t=ke("TopItemListComponent")||"div",n=ke("headerHeight"),r={...Ox,marginTop:`${n}px`},o=ke("context");return d.jsx(t,{style:r,...yt(t,o),children:e})},zx=x.memo(function(e){const t=ke("useWindowScroll"),n=ke("topItemsIndexes").length>0,r=ke("customScrollParent"),o=ke("context");return d.jsxs(r||t?Ux:Hx,{...e,context:o,children:[n&&d.jsx(Fx,{children:d.jsx(mu,{showTopList:!0})}),d.jsxs(r||t?$x:Lx,{children:[d.jsx(Mx,{}),d.jsx(mu,{}),d.jsx(Dx,{})]})]})}),{Component:Bx,useEmitter:Ai,useEmitterValue:ke,usePublisher:Yt}=lu(Ix,{required:{},optional:{restoreStateFrom:"restoreStateFrom",context:"context",followOutput:"followOutput",scrollIntoViewOnChange:"scrollIntoViewOnChange",itemContent:"itemContent",groupContent:"groupContent",overscan:"overscan",increaseViewportBy:"increaseViewportBy",totalCount:"totalCount",groupCounts:"groupCounts",topItemCount:"topItemCount",firstItemIndex:"firstItemIndex",initialTopMostItemIndex:"initialTopMostItemIndex",components:"components",atBottomThreshold:"atBottomThreshold",atTopThreshold:"atTopThreshold",computeItemKey:"computeItemKey",defaultItemHeight:"defaultItemHeight",fixedItemHeight:"fixedItemHeight",itemSize:"itemSize",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"HeaderFooterTag",data:"data",initialItemCount:"initialItemCount",initialScrollTop:"initialScrollTop",alignToBottom:"alignToBottom",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",horizontalDirection:"horizontalDirection",skipAnimationFrameInResizeObserver:"skipAnimationFrameInResizeObserver"},methods:{scrollToIndex:"scrollToIndex",scrollIntoView:"scrollIntoView",scrollTo:"scrollTo",scrollBy:"scrollBy",autoscrollToBottom:"autoscrollToBottom",getState:"getState"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",totalListHeightChanged:"totalListHeightChanged",itemsRendered:"itemsRendered",groupIndices:"groupIndices"}},zx),Hx=gu({useEmitter:Ai,useEmitterValue:ke,usePublisher:Yt}),Ux=xu({useEmitter:Ai,useEmitterValue:ke,usePublisher:Yt}),Wx=Bx;Xe(au,Re(()=>{const e=re(l=>d.jsxs("td",{children:["Item $",l]})),t=re(null),n=re(l=>d.jsxs("td",{colSpan:1e3,children:["Group ",l]})),r=re(null),o=re(null),s=re({}),i=re(Ii),a=re(gr),c=(l,u=null)=>vt(ee(s,ce(f=>f[l]),Je()),u);return{components:s,computeItemKey:i,context:t,EmptyPlaceholder:c("EmptyPlaceholder"),FillerRow:c("FillerRow"),fixedFooterContent:o,fixedHeaderContent:r,itemContent:e,groupContent:n,ScrollerComponent:c("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:c("ScrollSeekPlaceholder"),TableBodyComponent:c("TableBody","tbody"),TableComponent:c("Table","table"),TableFooterComponent:c("TableFoot","tfoot"),TableHeadComponent:c("TableHead","thead"),TableRowComponent:c("TableRow","tr"),GroupComponent:c("Group","tr")}})),Ei();const bu={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},Vx={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:wu,floor:Vo,max:to,min:Ni,round:vu}=Math;function yu(e,t,n){return Array.from({length:t-e+1}).map((r,o)=>({data:n===null?null:n[o+e],index:o+e}))}function Kx(e){return{...Vx,items:e}}function Ko(e,t){return e&&e.width===t.width&&e.height===t.height}function qx(e,t){return e&&e.column===t.column&&e.row===t.row}const Gx=Re(([{increaseViewportBy:e,listBoundary:t,overscan:n,visibleRange:r},{footerHeight:o,headerHeight:s,scrollBy:i,scrollContainerState:a,scrollTo:c,scrollTop:l,smoothScrollTargetReached:u,viewportHeight:f},h,p,{didMount:m,propsReady:g},{customScrollParent:b,useWindowScroll:v,windowScrollContainerState:y,windowScrollTo:T,windowViewportRect:I},k])=>{const S=re(0),E=re(0),j=re(bu),_=re({height:0,width:0}),D=re({height:0,width:0}),L=Oe(),W=Oe(),V=re(0),$=re(null),Z=re({column:0,row:0}),X=Oe(),oe=Oe(),U=re(!1),F=re(0),G=re(!0),H=re(!1),A=re(!1);De(ee(m,Ne(F),ye(([P,K])=>!!K)),()=>{Ae(G,!1)}),De(ee(ft(m,G,D,_,F,H),ye(([P,K,te,le,,he])=>P&&!K&&te.height!==0&&le.height!==0&&!he)),([,,,,P])=>{Ae(H,!0),wi(1,()=>{Ae(L,P)}),tn(ee(l),()=>{Ae(t,[0,0]),Ae(G,!0)})}),me(ee(oe,ye(P=>P!=null&&P.scrollTop>0),un(0)),E),De(ee(m,Ne(oe),ye(([,P])=>P!=null)),([,P])=>{P&&(Ae(_,P.viewport),Ae(D,P.item),Ae(Z,P.gap),P.scrollTop>0&&(Ae(U,!0),tn(ee(l,qn(1)),K=>{Ae(U,!1)}),Ae(c,{top:P.scrollTop})))}),me(ee(_,ce(({height:P})=>P)),f),me(ee(ft(ve(_,Ko),ve(D,Ko),ve(Z,(P,K)=>P&&P.column===K.column&&P.row===K.row),ve(l)),ce(([P,K,te,le])=>({gap:te,item:K,scrollTop:le,viewport:P}))),X),me(ee(ft(ve(S),r,ve(Z,qx),ve(D,Ko),ve(_,Ko),ve($),ve(E),ve(U),ve(G),ve(F)),ye(([,,,,,,,P])=>!P),ce(([P,[K,te],le,he,ue,ge,be,,Be,Le])=>{const{column:je,row:Fe}=le,{height:tt,width:mt}=he,{width:ot}=ue;if(be===0&&(P===0||ot===0))return bu;if(mt===0){const st=vi(Le,P),an=st+Math.max(be-1,0);return Kx(yu(st,an,ge))}const ze=Su(ot,mt,je);let Me,Ze;Be?K===0&&te===0&&be>0?(Me=0,Ze=be-1):(Me=ze*Vo((K+Fe)/(tt+Fe)),Ze=ze*wu((te+Fe)/(tt+Fe))-1,Ze=Ni(P-1,to(Ze,ze-1)),Me=Ni(Ze,to(0,Me))):(Me=0,Ze=-1);const rt=yu(Me,Ze,ge),{bottom:qe,top:ht}=Cu(ue,le,he,rt),xt=wu(P/ze),He=xt*tt+(xt-1)*Fe-qe;return{bottom:qe,itemHeight:tt,items:rt,itemWidth:mt,offsetBottom:He,offsetTop:ht,top:ht}})),j),me(ee($,ye(P=>P!==null),ce(P=>P.length)),S),me(ee(ft(_,D,j,Z),ye(([P,K,{items:te}])=>te.length>0&&K.height!==0&&P.height!==0),ce(([P,K,{items:te},le])=>{const{bottom:he,top:ue}=Cu(P,le,K,te);return[ue,he]}),Je(Gr)),t);const N=re(!1);me(ee(l,Ne(N),ce(([P,K])=>K||P!==0)),N);const R=Ht(ee(ft(j,S),ye(([{items:P}])=>P.length>0),Ne(N),ye(([[P,K],te])=>{const le=P.items[P.items.length-1].index===K-1;return(te||P.bottom>0&&P.itemHeight>0&&P.offsetBottom===0&&P.items.length===K)&&le}),ce(([[,P]])=>P-1),Je())),M=Ht(ee(ve(j),ye(({items:P})=>P.length>0&&P[0].index===0),un(0),Je())),q=Ht(ee(ve(j),Ne(U),ye(([{items:P},K])=>P.length>0&&!K),ce(([{items:P}])=>({endIndex:P[P.length-1].index,startIndex:P[0].index})),Je(Hc),yn(0)));me(q,p.scrollSeekRangeChanged),me(ee(L,Ne(_,D,S,Z),ce(([P,K,te,le,he])=>{const ue=Gc(P),{align:ge,behavior:be,offset:Be}=ue;let Le=ue.index;Le==="LAST"&&(Le=le-1),Le=to(0,Le,Ni(le-1,Le));let je=_i(K,he,te,Le);return ge==="end"?je=vu(je-K.height+te.height):ge==="center"&&(je=vu(je-K.height/2+te.height/2)),Be&&(je+=Be),{behavior:be,top:je}})),c);const J=vt(ee(j,ce(P=>P.offsetBottom+P.bottom)),0);return me(ee(I,ce(P=>({height:P.visibleHeight,width:P.visibleWidth}))),_),{customScrollParent:b,data:$,deviation:V,footerHeight:o,gap:Z,headerHeight:s,increaseViewportBy:e,initialItemCount:E,itemDimensions:D,overscan:n,restoreStateFrom:oe,scrollBy:i,scrollContainerState:a,scrollHeight:W,scrollTo:c,scrollToIndex:L,scrollTop:l,smoothScrollTargetReached:u,totalCount:S,useWindowScroll:v,viewportDimensions:_,windowScrollContainerState:y,windowScrollTo:T,windowViewportRect:I,...p,gridState:j,horizontalDirection:A,initialTopMostItemIndex:F,totalListHeight:J,...h,endReached:R,propsReady:g,rangeChanged:q,startReached:M,stateChanged:X,stateRestoreInProgress:U,...k}},Xe(yi,Nt,eo,su,Pn,Ci,_n));function Su(e,t,n){return to(1,Vo((e+n)/(Vo(t)+n)))}function Cu(e,t,n,r){const{height:o}=n;if(o===void 0||r.length===0)return{bottom:0,top:0};const s=_i(e,t,n,r[0].index);return{bottom:_i(e,t,n,r[r.length-1].index)+o,top:s}}function _i(e,t,n,r){const o=Su(e.width,n.width,t.column),s=Vo(r/o),i=s*n.height+to(0,s-1)*t.row;return i>0?i+t.row:i}const Yx=Re(()=>{const e=re(f=>`Item ${f}`),t=re({}),n=re(null),r=re("virtuoso-grid-item"),o=re("virtuoso-grid-list"),s=re(Ii),i=re("div"),a=re(gr),c=(f,h=null)=>vt(ee(t,ce(p=>p[f]),Je()),h),l=re(!1),u=re(!1);return me(ve(u),l),{components:t,computeItemKey:s,context:n,FooterComponent:c("Footer"),HeaderComponent:c("Header"),headerFooterTag:i,itemClassName:r,ItemComponent:c("Item","div"),itemContent:e,listClassName:o,ListComponent:c("List","div"),readyStateChanged:l,reportReadyState:u,ScrollerComponent:c("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:c("ScrollSeekPlaceholder","div")}}),Xx=Re(([e,t])=>({...e,...t}),Xe(Gx,Yx)),Jx=x.memo(function(){const e=Qe("gridState"),t=Qe("listClassName"),n=Qe("itemClassName"),r=Qe("itemContent"),o=Qe("computeItemKey"),s=Qe("isSeeking"),i=Xt("scrollHeight"),a=Qe("ItemComponent"),c=Qe("ListComponent"),l=Qe("ScrollSeekPlaceholder"),u=Qe("context"),f=Xt("itemDimensions"),h=Xt("gap"),p=Qe("log"),m=Qe("stateRestoreInProgress"),g=Xt("reportReadyState"),b=Gn(x.useMemo(()=>v=>{const y=v.parentElement.parentElement.scrollHeight;i(y);const T=v.firstChild;if(T){const{height:I,width:k}=T.getBoundingClientRect();f({height:I,width:k})}h({column:Tu("column-gap",getComputedStyle(v).columnGap,p),row:Tu("row-gap",getComputedStyle(v).rowGap,p)})},[i,f,h,p]),!0,!1);return du(()=>{e.itemHeight>0&&e.itemWidth>0&&g(!0)},[e]),m?null:d.jsx(c,{className:t,ref:b,...yt(c,u),"data-testid":"virtuoso-item-list",style:{paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},children:e.items.map(v=>{const y=o(v.index,v.data,u);return s?d.jsx(l,{...yt(l,u),height:e.itemHeight,index:v.index,width:e.itemWidth},y):x.createElement(a,{...yt(a,u),className:n,"data-index":v.index,key:y},r(v.index,v.data,u))})})}),Zx=x.memo(function(){const e=Qe("HeaderComponent"),t=Xt("headerHeight"),n=Qe("headerFooterTag"),r=Gn(x.useMemo(()=>s=>{t(jn(s,"height"))},[t]),!0,!1),o=Qe("context");return e?d.jsx(n,{ref:r,children:d.jsx(e,{...yt(e,o)})}):null}),Qx=x.memo(function(){const e=Qe("FooterComponent"),t=Xt("footerHeight"),n=Qe("headerFooterTag"),r=Gn(x.useMemo(()=>s=>{t(jn(s,"height"))},[t]),!0,!1),o=Qe("context");return e?d.jsx(n,{ref:r,children:d.jsx(e,{...yt(e,o)})}):null}),eb=({children:e})=>{const t=x.useContext(uu),n=Xt("itemDimensions"),r=Xt("viewportDimensions"),o=Gn(x.useMemo(()=>s=>{r(s.getBoundingClientRect())},[r]),!0,!1);return x.useEffect(()=>{t&&(r({height:t.viewportHeight,width:t.viewportWidth}),n({height:t.itemHeight,width:t.itemWidth}))},[t,r,n]),d.jsx("div",{ref:o,style:Wo(!1),children:e})},tb=({children:e})=>{const t=x.useContext(uu),n=Xt("windowViewportRect"),r=Xt("itemDimensions"),o=Qe("customScrollParent"),s=Mc(n,o,!1);return x.useEffect(()=>{t&&(r({height:t.itemHeight,width:t.itemWidth}),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:t.viewportWidth}))},[t,n,r]),d.jsx("div",{ref:s,style:Wo(!1),children:e})},nb=x.memo(function({...e}){const t=Qe("useWindowScroll"),n=Qe("customScrollParent"),r=n||t?ob:rb,o=n||t?tb:eb,s=Qe("context");return d.jsx(r,{...e,...yt(r,s),children:d.jsxs(o,{children:[d.jsx(Zx,{}),d.jsx(Jx,{}),d.jsx(Qx,{})]})})}),{useEmitter:ku,useEmitterValue:Qe,usePublisher:Xt}=lu(Xx,{optional:{context:"context",totalCount:"totalCount",overscan:"overscan",itemContent:"itemContent",components:"components",computeItemKey:"computeItemKey",data:"data",initialItemCount:"initialItemCount",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"headerFooterTag",listClassName:"listClassName",itemClassName:"itemClassName",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",restoreStateFrom:"restoreStateFrom",initialTopMostItemIndex:"initialTopMostItemIndex",increaseViewportBy:"increaseViewportBy"},methods:{scrollTo:"scrollTo",scrollBy:"scrollBy",scrollToIndex:"scrollToIndex"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",stateChanged:"stateChanged",readyStateChanged:"readyStateChanged"}},nb),rb=gu({useEmitter:ku,useEmitterValue:Qe,usePublisher:Xt}),ob=xu({useEmitter:ku,useEmitterValue:Qe,usePublisher:Xt});function Tu(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,Dt.WARN),t==="normal"?0:parseInt(t??"0",10)}function Se(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function Eu(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function On(...e){return t=>{let n=!1;const r=e.map(o=>{const s=Eu(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():Eu(e[o],null)}}}}function et(...e){return w.useCallback(On(...e),e)}function sb(e,t){const n=w.createContext(t),r=s=>{const{children:i,...a}=s,c=w.useMemo(()=>a,Object.values(a));return d.jsx(n.Provider,{value:c,children:i})};r.displayName=e+"Provider";function o(s){const i=w.useContext(n);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function Rn(e,t=[]){let n=[];function r(s,i){const a=w.createContext(i),c=n.length;n=[...n,i];const l=f=>{var v;const{scope:h,children:p,...m}=f,g=((v=h==null?void 0:h[e])==null?void 0:v[c])||a,b=w.useMemo(()=>m,Object.values(m));return d.jsx(g.Provider,{value:b,children:p})};l.displayName=s+"Provider";function u(f,h){var g;const p=((g=h==null?void 0:h[e])==null?void 0:g[c])||a,m=w.useContext(p);if(m)return m;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[l,u]}const o=()=>{const s=n.map(i=>w.createContext(i));return function(a){const c=(a==null?void 0:a[e])||s;return w.useMemo(()=>({[`__scope${e}`]:{...a,[e]:c}}),[a,c])}};return o.scopeName=e,[r,ib(o,...t)]}function ib(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:c,scopeName:l})=>{const f=c(s)[`__scope${l}`];return{...a,...f}},{});return w.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var hn=globalThis!=null&&globalThis.document?w.useLayoutEffect:()=>{},ab=w[" useId ".trim().toString()]||(()=>{}),lb=0;function Wt(e){const[t,n]=w.useState(ab());return hn(()=>{n(r=>r??String(lb++))},[e]),e||(t?`radix-${t}`:"")}var cb=w[" useInsertionEffect ".trim().toString()]||hn;function qo({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=ub({defaultProp:t,onChange:n}),a=e!==void 0,c=a?e:o;{const u=w.useRef(e!==void 0);w.useEffect(()=>{const f=u.current;f!==a&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=a},[a,r])}const l=w.useCallback(u=>{var f;if(a){const h=db(u)?u(e):u;h!==e&&((f=i.current)==null||f.call(i,h))}else s(u)},[a,e,s,i]);return[c,l]}function ub({defaultProp:e,onChange:t}){const[n,r]=w.useState(e),o=w.useRef(n),s=w.useRef(t);return cb(()=>{s.current=t},[t]),w.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function db(e){return typeof e=="function"}var fb=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Pe=fb.reduce((e,t)=>{const n=sr.createSlot(`Primitive.${t}`),r=w.forwardRef((o,s)=>{const{asChild:i,...a}=o,c=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),d.jsx(c,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Iu(e,t){e&&Ja.flushSync(()=>e.dispatchEvent(t))}function St(e){const t=w.useRef(e);return w.useEffect(()=>{t.current=e}),w.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function hb(e,t=globalThis==null?void 0:globalThis.document){const n=St(e);w.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var pb="DismissableLayer",ji="dismissableLayer.update",mb="dismissableLayer.pointerDownOutside",gb="dismissableLayer.focusOutside",Au,Nu=w.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Pi=w.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...c}=e,l=w.useContext(Nu),[u,f]=w.useState(null),h=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=w.useState({}),m=et(t,E=>f(E)),g=Array.from(l.layers),[b]=[...l.layersWithOutsidePointerEventsDisabled].slice(-1),v=g.indexOf(b),y=u?g.indexOf(u):-1,T=l.layersWithOutsidePointerEventsDisabled.size>0,I=y>=v,k=wb(E=>{const j=E.target,_=[...l.branches].some(D=>D.contains(j));!I||_||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},h),S=vb(E=>{const j=E.target;[...l.branches].some(D=>D.contains(j))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},h);return hb(E=>{y===l.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},h),w.useEffect(()=>{if(u)return n&&(l.layersWithOutsidePointerEventsDisabled.size===0&&(Au=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),l.layersWithOutsidePointerEventsDisabled.add(u)),l.layers.add(u),_u(),()=>{n&&l.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=Au)}},[u,h,n,l]),w.useEffect(()=>()=>{u&&(l.layers.delete(u),l.layersWithOutsidePointerEventsDisabled.delete(u),_u())},[u,l]),w.useEffect(()=>{const E=()=>p({});return document.addEventListener(ji,E),()=>document.removeEventListener(ji,E)},[]),d.jsx(Pe.div,{...c,ref:m,style:{pointerEvents:T?I?"auto":"none":void 0,...e.style},onFocusCapture:Se(e.onFocusCapture,S.onFocusCapture),onBlurCapture:Se(e.onBlurCapture,S.onBlurCapture),onPointerDownCapture:Se(e.onPointerDownCapture,k.onPointerDownCapture)})});Pi.displayName=pb;var xb="DismissableLayerBranch",bb=w.forwardRef((e,t)=>{const n=w.useContext(Nu),r=w.useRef(null),o=et(t,r);return w.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),d.jsx(Pe.div,{...e,ref:o})});bb.displayName=xb;function wb(e,t=globalThis==null?void 0:globalThis.document){const n=St(e),r=w.useRef(!1),o=w.useRef(()=>{});return w.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let c=function(){ju(mb,n,l,{discrete:!0})};const l={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=c,t.addEventListener("click",o.current,{once:!0})):c()}else t.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function vb(e,t=globalThis==null?void 0:globalThis.document){const n=St(e),r=w.useRef(!1);return w.useEffect(()=>{const o=s=>{s.target&&!r.current&&ju(gb,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function _u(){const e=new CustomEvent(ji);document.dispatchEvent(e)}function ju(e,t,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?Iu(o,s):o.dispatchEvent(s)}var Oi="focusScope.autoFocusOnMount",Ri="focusScope.autoFocusOnUnmount",Pu={bubbles:!1,cancelable:!0},yb="FocusScope",Mi=w.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,c]=w.useState(null),l=St(o),u=St(s),f=w.useRef(null),h=et(t,g=>c(g)),p=w.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;w.useEffect(()=>{if(r){let g=function(T){if(p.paused||!a)return;const I=T.target;a.contains(I)?f.current=I:Mn(f.current,{select:!0})},b=function(T){if(p.paused||!a)return;const I=T.relatedTarget;I!==null&&(a.contains(I)||Mn(f.current,{select:!0}))},v=function(T){if(document.activeElement===document.body)for(const k of T)k.removedNodes.length>0&&Mn(a)};document.addEventListener("focusin",g),document.addEventListener("focusout",b);const y=new MutationObserver(v);return a&&y.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",b),y.disconnect()}}},[r,a,p.paused]),w.useEffect(()=>{if(a){Mu.add(p);const g=document.activeElement;if(!a.contains(g)){const v=new CustomEvent(Oi,Pu);a.addEventListener(Oi,l),a.dispatchEvent(v),v.defaultPrevented||(Sb(Ib(Ou(a)),{select:!0}),document.activeElement===g&&Mn(a))}return()=>{a.removeEventListener(Oi,l),setTimeout(()=>{const v=new CustomEvent(Ri,Pu);a.addEventListener(Ri,u),a.dispatchEvent(v),v.defaultPrevented||Mn(g??document.body,{select:!0}),a.removeEventListener(Ri,u),Mu.remove(p)},0)}}},[a,l,u,p]);const m=w.useCallback(g=>{if(!n&&!r||p.paused)return;const b=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,v=document.activeElement;if(b&&v){const y=g.currentTarget,[T,I]=Cb(y);T&&I?!g.shiftKey&&v===I?(g.preventDefault(),n&&Mn(T,{select:!0})):g.shiftKey&&v===T&&(g.preventDefault(),n&&Mn(I,{select:!0})):v===y&&g.preventDefault()}},[n,r,p.paused]);return d.jsx(Pe.div,{tabIndex:-1,...i,ref:h,onKeyDown:m})});Mi.displayName=yb;function Sb(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Mn(r,{select:t}),document.activeElement!==n)return}function Cb(e){const t=Ou(e),n=Ru(t,e),r=Ru(t.reverse(),e);return[n,r]}function Ou(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Ru(e,t){for(const n of e)if(!kb(n,{upTo:t}))return n}function kb(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function Tb(e){return e instanceof HTMLInputElement&&"select"in e}function Mn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Tb(e)&&t&&e.select()}}var Mu=Eb();function Eb(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Du(e,t),e.unshift(t)},remove(t){var n;e=Du(e,t),(n=e[0])==null||n.resume()}}}function Du(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function Ib(e){return e.filter(t=>t.tagName!=="A")}var Ab="Portal",Di=w.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=w.useState(!1);hn(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Ls.createPortal(d.jsx(Pe.div,{...r,ref:t}),i):null});Di.displayName=Ab;function Nb(e,t){return w.useReducer((n,r)=>t[n][r]??n,e)}var Vt=e=>{const{present:t,children:n}=e,r=_b(t),o=typeof n=="function"?n({present:r.isPresent}):w.Children.only(n),s=et(r.ref,jb(o));return typeof n=="function"||r.isPresent?w.cloneElement(o,{ref:s}):null};Vt.displayName="Presence";function _b(e){const[t,n]=w.useState(),r=w.useRef(null),o=w.useRef(e),s=w.useRef("none"),i=e?"mounted":"unmounted",[a,c]=Nb(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return w.useEffect(()=>{const l=Go(r.current);s.current=a==="mounted"?l:"none"},[a]),hn(()=>{const l=r.current,u=o.current;if(u!==e){const h=s.current,p=Go(l);e?c("MOUNT"):p==="none"||(l==null?void 0:l.display)==="none"?c("UNMOUNT"):c(u&&h!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,c]),hn(()=>{if(t){let l;const u=t.ownerDocument.defaultView??window,f=p=>{const g=Go(r.current).includes(CSS.escape(p.animationName));if(p.target===t&&g&&(c("ANIMATION_END"),!o.current)){const b=t.style.animationFillMode;t.style.animationFillMode="forwards",l=u.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=b)})}},h=p=>{p.target===t&&(s.current=Go(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{u.clearTimeout(l),t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:w.useCallback(l=>{r.current=l?getComputedStyle(l):null,n(l)},[])}}function Go(e){return(e==null?void 0:e.animationName)||"none"}function jb(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Li=0;function Lu(){w.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??$u()),document.body.insertAdjacentElement("beforeend",e[1]??$u()),Li++,()=>{Li===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Li--}},[])}function $u(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var pn=function(){return pn=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},pn.apply(this,arguments)};function Fu(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function Pb(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}typeof SuppressedError=="function"&&SuppressedError;var Yo="right-scroll-bar-position",Xo="width-before-scroll-bar",Ob="with-scroll-bars-hidden",Rb="--removed-body-scroll-bar-size";function $i(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function Mb(e,t){var n=x.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var Db=typeof window<"u"?w.useLayoutEffect:w.useEffect,zu=new WeakMap;function Lb(e,t){var n=Mb(null,function(r){return e.forEach(function(o){return $i(o,r)})});return Db(function(){var r=zu.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||$i(a,null)}),s.forEach(function(a){o.has(a)||$i(a,i)})}zu.set(n,e)},[e]),n}function $b(e){return e}function Fb(e,t){t===void 0&&(t=$b);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(s){var i=t(s,r);return n.push(i),function(){n=n.filter(function(a){return a!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var a=n;n=[],a.forEach(s),i=n}var c=function(){var u=i;i=[],u.forEach(s)},l=function(){return Promise.resolve().then(c)};l(),n={push:function(u){i.push(u),l()},filter:function(u){return i=i.filter(u),n}}}};return o}function zb(e){e===void 0&&(e={});var t=Fb(null);return t.options=pn({async:!0,ssr:!1},e),t}var Bu=function(e){var t=e.sideCar,n=Fu(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return w.createElement(r,pn({},n))};Bu.isSideCarExport=!0;function Bb(e,t){return e.useMedium(t),Bu}var Hu=zb(),Fi=function(){},Jo=w.forwardRef(function(e,t){var n=w.useRef(null),r=w.useState({onScrollCapture:Fi,onWheelCapture:Fi,onTouchMoveCapture:Fi}),o=r[0],s=r[1],i=e.forwardProps,a=e.children,c=e.className,l=e.removeScrollBar,u=e.enabled,f=e.shards,h=e.sideCar,p=e.noRelative,m=e.noIsolation,g=e.inert,b=e.allowPinchZoom,v=e.as,y=v===void 0?"div":v,T=e.gapMode,I=Fu(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=h,S=Lb([n,t]),E=pn(pn({},I),o);return w.createElement(w.Fragment,null,u&&w.createElement(k,{sideCar:Hu,removeScrollBar:l,shards:f,noRelative:p,noIsolation:m,inert:g,setCallbacks:s,allowPinchZoom:!!b,lockRef:n,gapMode:T}),i?w.cloneElement(w.Children.only(a),pn(pn({},E),{ref:S})):w.createElement(y,pn({},E,{className:c,ref:S}),a))});Jo.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},Jo.classNames={fullWidth:Xo,zeroRight:Yo};var Hb=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Ub(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Hb();return t&&e.setAttribute("nonce",t),e}function Wb(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Vb(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Kb=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Ub())&&(Wb(t,n),Vb(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},qb=function(){var e=Kb();return function(t,n){w.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Uu=function(){var e=qb(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Gb={left:0,top:0,right:0,gap:0},zi=function(e){return parseInt(e||"",10)||0},Yb=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[zi(n),zi(r),zi(o)]},Xb=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Gb;var t=Yb(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},Jb=Uu(),br="data-scroll-locked",Zb=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
40
40
  .`.concat(Ob,` {
41
41
  overflow: hidden `).concat(r,`;
42
42
  padding-right: `).concat(a,"px ").concat(r,`;
@@ -73,14 +73,14 @@ React keys must be passed directly to JSX without using spread:
73
73
  body[`).concat(br,`] {
74
74
  `).concat(Rb,": ").concat(a,`px;
75
75
  }
76
- `)},Vu=function(){var e=parseInt(document.body.getAttribute(br)||"0",10);return isFinite(e)?e:0},Qb=function(){w.useEffect(function(){return document.body.setAttribute(br,(Vu()+1).toString()),function(){var e=Vu()-1;e<=0?document.body.removeAttribute(br):document.body.setAttribute(br,e.toString())}},[])},ew=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r;Qb();var s=w.useMemo(function(){return Xb(o)},[o]);return w.createElement(Jb,{styles:Zb(s,!t,o,n?"":"!important")})},Bi=!1;if(typeof window<"u")try{var Zo=Object.defineProperty({},"passive",{get:function(){return Bi=!0,!0}});window.addEventListener("test",Zo,Zo),window.removeEventListener("test",Zo,Zo)}catch{Bi=!1}var wr=Bi?{passive:!1}:!1,tw=function(e){return e.tagName==="TEXTAREA"},Ku=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!tw(e)&&n[t]==="visible")},nw=function(e){return Ku(e,"overflowY")},rw=function(e){return Ku(e,"overflowX")},qu=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var o=Gu(e,r);if(o){var s=Yu(e,r),i=s[1],a=s[2];if(i>a)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},ow=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},sw=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},Gu=function(e,t){return e==="v"?nw(t):rw(t)},Yu=function(e,t){return e==="v"?ow(t):sw(t)},iw=function(e,t){return e==="h"&&t==="rtl"?-1:1},aw=function(e,t,n,r,o){var s=iw(e,window.getComputedStyle(t).direction),i=s*r,a=n.target,c=t.contains(a),l=!1,u=i>0,f=0,h=0;do{if(!a)break;var p=Yu(e,a),m=p[0],g=p[1],b=p[2],v=g-b-s*m;(m||v)&&Gu(e,a)&&(f+=v,h+=m);var y=a.parentNode;a=y&&y.nodeType===Node.DOCUMENT_FRAGMENT_NODE?y.host:y}while(!c&&a!==document.body||c&&(t.contains(a)||t===a));return(u&&Math.abs(f)<1||!u&&Math.abs(h)<1)&&(l=!0),l},Qo=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Xu=function(e){return[e.deltaX,e.deltaY]},Ju=function(e){return e&&"current"in e?e.current:e},lw=function(e,t){return e[0]===t[0]&&e[1]===t[1]},cw=function(e){return`
76
+ `)},Wu=function(){var e=parseInt(document.body.getAttribute(br)||"0",10);return isFinite(e)?e:0},Qb=function(){w.useEffect(function(){return document.body.setAttribute(br,(Wu()+1).toString()),function(){var e=Wu()-1;e<=0?document.body.removeAttribute(br):document.body.setAttribute(br,e.toString())}},[])},ew=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r;Qb();var s=w.useMemo(function(){return Xb(o)},[o]);return w.createElement(Jb,{styles:Zb(s,!t,o,n?"":"!important")})},Bi=!1;if(typeof window<"u")try{var Zo=Object.defineProperty({},"passive",{get:function(){return Bi=!0,!0}});window.addEventListener("test",Zo,Zo),window.removeEventListener("test",Zo,Zo)}catch{Bi=!1}var wr=Bi?{passive:!1}:!1,tw=function(e){return e.tagName==="TEXTAREA"},Vu=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!tw(e)&&n[t]==="visible")},nw=function(e){return Vu(e,"overflowY")},rw=function(e){return Vu(e,"overflowX")},Ku=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var o=qu(e,r);if(o){var s=Gu(e,r),i=s[1],a=s[2];if(i>a)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},ow=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},sw=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},qu=function(e,t){return e==="v"?nw(t):rw(t)},Gu=function(e,t){return e==="v"?ow(t):sw(t)},iw=function(e,t){return e==="h"&&t==="rtl"?-1:1},aw=function(e,t,n,r,o){var s=iw(e,window.getComputedStyle(t).direction),i=s*r,a=n.target,c=t.contains(a),l=!1,u=i>0,f=0,h=0;do{if(!a)break;var p=Gu(e,a),m=p[0],g=p[1],b=p[2],v=g-b-s*m;(m||v)&&qu(e,a)&&(f+=v,h+=m);var y=a.parentNode;a=y&&y.nodeType===Node.DOCUMENT_FRAGMENT_NODE?y.host:y}while(!c&&a!==document.body||c&&(t.contains(a)||t===a));return(u&&Math.abs(f)<1||!u&&Math.abs(h)<1)&&(l=!0),l},Qo=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Yu=function(e){return[e.deltaX,e.deltaY]},Xu=function(e){return e&&"current"in e?e.current:e},lw=function(e,t){return e[0]===t[0]&&e[1]===t[1]},cw=function(e){return`
77
77
  .block-interactivity-`.concat(e,` {pointer-events: none;}
78
78
  .allow-interactivity-`).concat(e,` {pointer-events: all;}
79
- `)},uw=0,vr=[];function dw(e){var t=w.useRef([]),n=w.useRef([0,0]),r=w.useRef(),o=w.useState(uw++)[0],s=w.useState(Wu)[0],i=w.useRef(e);w.useEffect(function(){i.current=e},[e]),w.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var g=Pb([e.lockRef.current],(e.shards||[]).map(Ju),!0).filter(Boolean);return g.forEach(function(b){return b.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),g.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var a=w.useCallback(function(g,b){if("touches"in g&&g.touches.length===2||g.type==="wheel"&&g.ctrlKey)return!i.current.allowPinchZoom;var v=Qo(g),y=n.current,T="deltaX"in g?g.deltaX:y[0]-v[0],I="deltaY"in g?g.deltaY:y[1]-v[1],k,S=g.target,E=Math.abs(T)>Math.abs(I)?"h":"v";if("touches"in g&&E==="h"&&S.type==="range")return!1;var j=qu(E,S);if(!j)return!0;if(j?k=E:(k=E==="v"?"h":"v",j=qu(E,S)),!j)return!1;if(!r.current&&"changedTouches"in g&&(T||I)&&(r.current=k),!k)return!0;var _=r.current||k;return aw(_,b,g,_==="h"?T:I)},[]),c=w.useCallback(function(g){var b=g;if(!(!vr.length||vr[vr.length-1]!==s)){var v="deltaY"in b?Xu(b):Qo(b),y=t.current.filter(function(k){return k.name===b.type&&(k.target===b.target||b.target===k.shadowParent)&&lw(k.delta,v)})[0];if(y&&y.should){b.cancelable&&b.preventDefault();return}if(!y){var T=(i.current.shards||[]).map(Ju).filter(Boolean).filter(function(k){return k.contains(b.target)}),I=T.length>0?a(b,T[0]):!i.current.noIsolation;I&&b.cancelable&&b.preventDefault()}}},[]),l=w.useCallback(function(g,b,v,y){var T={name:g,delta:b,target:v,should:y,shadowParent:fw(v)};t.current.push(T),setTimeout(function(){t.current=t.current.filter(function(I){return I!==T})},1)},[]),u=w.useCallback(function(g){n.current=Qo(g),r.current=void 0},[]),f=w.useCallback(function(g){l(g.type,Xu(g),g.target,a(g,e.lockRef.current))},[]),h=w.useCallback(function(g){l(g.type,Qo(g),g.target,a(g,e.lockRef.current))},[]);w.useEffect(function(){return vr.push(s),e.setCallbacks({onScrollCapture:f,onWheelCapture:f,onTouchMoveCapture:h}),document.addEventListener("wheel",c,wr),document.addEventListener("touchmove",c,wr),document.addEventListener("touchstart",u,wr),function(){vr=vr.filter(function(g){return g!==s}),document.removeEventListener("wheel",c,wr),document.removeEventListener("touchmove",c,wr),document.removeEventListener("touchstart",u,wr)}},[]);var p=e.removeScrollBar,m=e.inert;return w.createElement(w.Fragment,null,m?w.createElement(s,{styles:cw(o)}):null,p?w.createElement(ew,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function fw(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const hw=Bb(Uu,dw);var Hi=w.forwardRef(function(e,t){return w.createElement(Jo,pn({},e,{ref:t,sideCar:hw}))});Hi.classNames=Jo.classNames;var pw=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},yr=new WeakMap,es=new WeakMap,ts={},Ui=0,Zu=function(e){return e&&(e.host||Zu(e.parentNode))},mw=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=Zu(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},gw=function(e,t,n,r){var o=mw(t,Array.isArray(e)?e:[e]);ts[n]||(ts[n]=new WeakMap);var s=ts[n],i=[],a=new Set,c=new Set(o),l=function(f){!f||a.has(f)||(a.add(f),l(f.parentNode))};o.forEach(l);var u=function(f){!f||c.has(f)||Array.prototype.forEach.call(f.children,function(h){if(a.has(h))u(h);else try{var p=h.getAttribute(r),m=p!==null&&p!=="false",g=(yr.get(h)||0)+1,b=(s.get(h)||0)+1;yr.set(h,g),s.set(h,b),i.push(h),g===1&&m&&es.set(h,!0),b===1&&h.setAttribute(n,"true"),m||h.setAttribute(r,"true")}catch(v){console.error("aria-hidden: cannot operate on ",h,v)}})};return u(t),a.clear(),Ui++,function(){i.forEach(function(f){var h=yr.get(f)-1,p=s.get(f)-1;yr.set(f,h),s.set(f,p),h||(es.has(f)||f.removeAttribute(r),es.delete(f)),p||f.removeAttribute(n)}),Ui--,Ui||(yr=new WeakMap,yr=new WeakMap,es=new WeakMap,ts={})}},Qu=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=pw(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),gw(r,o,n,"aria-hidden")):function(){return null}},ns="Dialog",[ed,VC]=Rn(ns),[xw,rn]=ed(ns),td=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:s,modal:i=!0}=e,a=w.useRef(null),c=w.useRef(null),[l,u]=qo({prop:r,defaultProp:o??!1,onChange:s,caller:ns});return d.jsx(xw,{scope:t,triggerRef:a,contentRef:c,contentId:Wt(),titleId:Wt(),descriptionId:Wt(),open:l,onOpenChange:u,onOpenToggle:w.useCallback(()=>u(f=>!f),[u]),modal:i,children:n})};td.displayName=ns;var nd="DialogTrigger",bw=w.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=rn(nd,n),s=et(t,o.triggerRef);return d.jsx(Pe.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Ki(o.open),...r,ref:s,onClick:Se(e.onClick,o.onOpenToggle)})});bw.displayName=nd;var Wi="DialogPortal",[ww,rd]=ed(Wi,{forceMount:void 0}),od=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,s=rn(Wi,t);return d.jsx(ww,{scope:t,forceMount:n,children:w.Children.map(r,i=>d.jsx(Vt,{present:n||s.open,children:d.jsx(Di,{asChild:!0,container:o,children:i})}))})};od.displayName=Wi;var rs="DialogOverlay",sd=w.forwardRef((e,t)=>{const n=rd(rs,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=rn(rs,e.__scopeDialog);return s.modal?d.jsx(Vt,{present:r||s.open,children:d.jsx(yw,{...o,ref:t})}):null});sd.displayName=rs;var vw=sr.createSlot("DialogOverlay.RemoveScroll"),yw=w.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=rn(rs,n);return d.jsx(Hi,{as:vw,allowPinchZoom:!0,shards:[o.contentRef],children:d.jsx(Pe.div,{"data-state":Ki(o.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),Jn="DialogContent",id=w.forwardRef((e,t)=>{const n=rd(Jn,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=rn(Jn,e.__scopeDialog);return d.jsx(Vt,{present:r||s.open,children:s.modal?d.jsx(Sw,{...o,ref:t}):d.jsx(Cw,{...o,ref:t})})});id.displayName=Jn;var Sw=w.forwardRef((e,t)=>{const n=rn(Jn,e.__scopeDialog),r=w.useRef(null),o=et(t,n.contentRef,r);return w.useEffect(()=>{const s=r.current;if(s)return Qu(s)},[]),d.jsx(ad,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Se(e.onCloseAutoFocus,s=>{var i;s.preventDefault(),(i=n.triggerRef.current)==null||i.focus()}),onPointerDownOutside:Se(e.onPointerDownOutside,s=>{const i=s.detail.originalEvent,a=i.button===0&&i.ctrlKey===!0;(i.button===2||a)&&s.preventDefault()}),onFocusOutside:Se(e.onFocusOutside,s=>s.preventDefault())})}),Cw=w.forwardRef((e,t)=>{const n=rn(Jn,e.__scopeDialog),r=w.useRef(!1),o=w.useRef(!1);return d.jsx(ad,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var i,a;(i=e.onCloseAutoFocus)==null||i.call(e,s),s.defaultPrevented||(r.current||(a=n.triggerRef.current)==null||a.focus(),s.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:s=>{var c,l;(c=e.onInteractOutside)==null||c.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const i=s.target;((l=n.triggerRef.current)==null?void 0:l.contains(i))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})}),ad=w.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:s,...i}=e,a=rn(Jn,n),c=w.useRef(null),l=et(t,c);return $u(),d.jsxs(d.Fragment,{children:[d.jsx(Mi,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:s,children:d.jsx(Pi,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":Ki(a.open),...i,ref:l,onDismiss:()=>a.onOpenChange(!1)})}),d.jsxs(d.Fragment,{children:[d.jsx(kw,{titleId:a.titleId}),d.jsx(Ew,{contentRef:c,descriptionId:a.descriptionId})]})]})}),Vi="DialogTitle",ld=w.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=rn(Vi,n);return d.jsx(Pe.h2,{id:o.titleId,...r,ref:t})});ld.displayName=Vi;var cd="DialogDescription",ud=w.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=rn(cd,n);return d.jsx(Pe.p,{id:o.descriptionId,...r,ref:t})});ud.displayName=cd;var dd="DialogClose",fd=w.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=rn(dd,n);return d.jsx(Pe.button,{type:"button",...r,ref:t,onClick:Se(e.onClick,()=>o.onOpenChange(!1))})});fd.displayName=dd;function Ki(e){return e?"open":"closed"}var hd="DialogTitleWarning",[KC,pd]=sb(hd,{contentName:Jn,titleName:Vi,docsSlug:"dialog"}),kw=({titleId:e})=>{const t=pd(hd),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
79
+ `)},uw=0,vr=[];function dw(e){var t=w.useRef([]),n=w.useRef([0,0]),r=w.useRef(),o=w.useState(uw++)[0],s=w.useState(Uu)[0],i=w.useRef(e);w.useEffect(function(){i.current=e},[e]),w.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var g=Pb([e.lockRef.current],(e.shards||[]).map(Xu),!0).filter(Boolean);return g.forEach(function(b){return b.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),g.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var a=w.useCallback(function(g,b){if("touches"in g&&g.touches.length===2||g.type==="wheel"&&g.ctrlKey)return!i.current.allowPinchZoom;var v=Qo(g),y=n.current,T="deltaX"in g?g.deltaX:y[0]-v[0],I="deltaY"in g?g.deltaY:y[1]-v[1],k,S=g.target,E=Math.abs(T)>Math.abs(I)?"h":"v";if("touches"in g&&E==="h"&&S.type==="range")return!1;var j=Ku(E,S);if(!j)return!0;if(j?k=E:(k=E==="v"?"h":"v",j=Ku(E,S)),!j)return!1;if(!r.current&&"changedTouches"in g&&(T||I)&&(r.current=k),!k)return!0;var _=r.current||k;return aw(_,b,g,_==="h"?T:I)},[]),c=w.useCallback(function(g){var b=g;if(!(!vr.length||vr[vr.length-1]!==s)){var v="deltaY"in b?Yu(b):Qo(b),y=t.current.filter(function(k){return k.name===b.type&&(k.target===b.target||b.target===k.shadowParent)&&lw(k.delta,v)})[0];if(y&&y.should){b.cancelable&&b.preventDefault();return}if(!y){var T=(i.current.shards||[]).map(Xu).filter(Boolean).filter(function(k){return k.contains(b.target)}),I=T.length>0?a(b,T[0]):!i.current.noIsolation;I&&b.cancelable&&b.preventDefault()}}},[]),l=w.useCallback(function(g,b,v,y){var T={name:g,delta:b,target:v,should:y,shadowParent:fw(v)};t.current.push(T),setTimeout(function(){t.current=t.current.filter(function(I){return I!==T})},1)},[]),u=w.useCallback(function(g){n.current=Qo(g),r.current=void 0},[]),f=w.useCallback(function(g){l(g.type,Yu(g),g.target,a(g,e.lockRef.current))},[]),h=w.useCallback(function(g){l(g.type,Qo(g),g.target,a(g,e.lockRef.current))},[]);w.useEffect(function(){return vr.push(s),e.setCallbacks({onScrollCapture:f,onWheelCapture:f,onTouchMoveCapture:h}),document.addEventListener("wheel",c,wr),document.addEventListener("touchmove",c,wr),document.addEventListener("touchstart",u,wr),function(){vr=vr.filter(function(g){return g!==s}),document.removeEventListener("wheel",c,wr),document.removeEventListener("touchmove",c,wr),document.removeEventListener("touchstart",u,wr)}},[]);var p=e.removeScrollBar,m=e.inert;return w.createElement(w.Fragment,null,m?w.createElement(s,{styles:cw(o)}):null,p?w.createElement(ew,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function fw(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const hw=Bb(Hu,dw);var Hi=w.forwardRef(function(e,t){return w.createElement(Jo,pn({},e,{ref:t,sideCar:hw}))});Hi.classNames=Jo.classNames;var pw=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},yr=new WeakMap,es=new WeakMap,ts={},Ui=0,Ju=function(e){return e&&(e.host||Ju(e.parentNode))},mw=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=Ju(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},gw=function(e,t,n,r){var o=mw(t,Array.isArray(e)?e:[e]);ts[n]||(ts[n]=new WeakMap);var s=ts[n],i=[],a=new Set,c=new Set(o),l=function(f){!f||a.has(f)||(a.add(f),l(f.parentNode))};o.forEach(l);var u=function(f){!f||c.has(f)||Array.prototype.forEach.call(f.children,function(h){if(a.has(h))u(h);else try{var p=h.getAttribute(r),m=p!==null&&p!=="false",g=(yr.get(h)||0)+1,b=(s.get(h)||0)+1;yr.set(h,g),s.set(h,b),i.push(h),g===1&&m&&es.set(h,!0),b===1&&h.setAttribute(n,"true"),m||h.setAttribute(r,"true")}catch(v){console.error("aria-hidden: cannot operate on ",h,v)}})};return u(t),a.clear(),Ui++,function(){i.forEach(function(f){var h=yr.get(f)-1,p=s.get(f)-1;yr.set(f,h),s.set(f,p),h||(es.has(f)||f.removeAttribute(r),es.delete(f)),p||f.removeAttribute(n)}),Ui--,Ui||(yr=new WeakMap,yr=new WeakMap,es=new WeakMap,ts={})}},Zu=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=pw(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),gw(r,o,n,"aria-hidden")):function(){return null}},ns="Dialog",[Qu,VC]=Rn(ns),[xw,rn]=Qu(ns),ed=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:s,modal:i=!0}=e,a=w.useRef(null),c=w.useRef(null),[l,u]=qo({prop:r,defaultProp:o??!1,onChange:s,caller:ns});return d.jsx(xw,{scope:t,triggerRef:a,contentRef:c,contentId:Wt(),titleId:Wt(),descriptionId:Wt(),open:l,onOpenChange:u,onOpenToggle:w.useCallback(()=>u(f=>!f),[u]),modal:i,children:n})};ed.displayName=ns;var td="DialogTrigger",bw=w.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=rn(td,n),s=et(t,o.triggerRef);return d.jsx(Pe.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Ki(o.open),...r,ref:s,onClick:Se(e.onClick,o.onOpenToggle)})});bw.displayName=td;var Wi="DialogPortal",[ww,nd]=Qu(Wi,{forceMount:void 0}),rd=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,s=rn(Wi,t);return d.jsx(ww,{scope:t,forceMount:n,children:w.Children.map(r,i=>d.jsx(Vt,{present:n||s.open,children:d.jsx(Di,{asChild:!0,container:o,children:i})}))})};rd.displayName=Wi;var rs="DialogOverlay",od=w.forwardRef((e,t)=>{const n=nd(rs,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=rn(rs,e.__scopeDialog);return s.modal?d.jsx(Vt,{present:r||s.open,children:d.jsx(yw,{...o,ref:t})}):null});od.displayName=rs;var vw=sr.createSlot("DialogOverlay.RemoveScroll"),yw=w.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=rn(rs,n);return d.jsx(Hi,{as:vw,allowPinchZoom:!0,shards:[o.contentRef],children:d.jsx(Pe.div,{"data-state":Ki(o.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),Jn="DialogContent",sd=w.forwardRef((e,t)=>{const n=nd(Jn,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=rn(Jn,e.__scopeDialog);return d.jsx(Vt,{present:r||s.open,children:s.modal?d.jsx(Sw,{...o,ref:t}):d.jsx(Cw,{...o,ref:t})})});sd.displayName=Jn;var Sw=w.forwardRef((e,t)=>{const n=rn(Jn,e.__scopeDialog),r=w.useRef(null),o=et(t,n.contentRef,r);return w.useEffect(()=>{const s=r.current;if(s)return Zu(s)},[]),d.jsx(id,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Se(e.onCloseAutoFocus,s=>{var i;s.preventDefault(),(i=n.triggerRef.current)==null||i.focus()}),onPointerDownOutside:Se(e.onPointerDownOutside,s=>{const i=s.detail.originalEvent,a=i.button===0&&i.ctrlKey===!0;(i.button===2||a)&&s.preventDefault()}),onFocusOutside:Se(e.onFocusOutside,s=>s.preventDefault())})}),Cw=w.forwardRef((e,t)=>{const n=rn(Jn,e.__scopeDialog),r=w.useRef(!1),o=w.useRef(!1);return d.jsx(id,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var i,a;(i=e.onCloseAutoFocus)==null||i.call(e,s),s.defaultPrevented||(r.current||(a=n.triggerRef.current)==null||a.focus(),s.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:s=>{var c,l;(c=e.onInteractOutside)==null||c.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const i=s.target;((l=n.triggerRef.current)==null?void 0:l.contains(i))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})}),id=w.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:s,...i}=e,a=rn(Jn,n),c=w.useRef(null),l=et(t,c);return Lu(),d.jsxs(d.Fragment,{children:[d.jsx(Mi,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:s,children:d.jsx(Pi,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":Ki(a.open),...i,ref:l,onDismiss:()=>a.onOpenChange(!1)})}),d.jsxs(d.Fragment,{children:[d.jsx(kw,{titleId:a.titleId}),d.jsx(Ew,{contentRef:c,descriptionId:a.descriptionId})]})]})}),Vi="DialogTitle",ad=w.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=rn(Vi,n);return d.jsx(Pe.h2,{id:o.titleId,...r,ref:t})});ad.displayName=Vi;var ld="DialogDescription",cd=w.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=rn(ld,n);return d.jsx(Pe.p,{id:o.descriptionId,...r,ref:t})});cd.displayName=ld;var ud="DialogClose",dd=w.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=rn(ud,n);return d.jsx(Pe.button,{type:"button",...r,ref:t,onClick:Se(e.onClick,()=>o.onOpenChange(!1))})});dd.displayName=ud;function Ki(e){return e?"open":"closed"}var fd="DialogTitleWarning",[KC,hd]=sb(fd,{contentName:Jn,titleName:Vi,docsSlug:"dialog"}),kw=({titleId:e})=>{const t=hd(fd),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
80
80
 
81
81
  If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
82
82
 
83
- For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return w.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},Tw="DialogDescriptionWarning",Ew=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${pd(Tw).contentName}}.`;return w.useEffect(()=>{var s;const o=(s=e.current)==null?void 0:s.getAttribute("aria-describedby");t&&o&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},md=td,gd=od,qi=sd,Gi=id,no=ld,xd=ud,Iw=fd;const bd=md,Aw=gd,wd=w.forwardRef(({className:e,...t},n)=>d.jsx(qi,{ref:n,className:ae("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));wd.displayName=qi.displayName;const Yi=w.forwardRef(({className:e,children:t,...n},r)=>{const o=w.useMemo(()=>{let s=!1;function i(a){w.Children.forEach(a,c=>{if(s||!w.isValidElement(c))return;const l=c.type;if(l===no||(l==null?void 0:l.displayName)===no.displayName||(l==null?void 0:l.name)==="DialogTitle"){s=!0;return}c.props&&c.props.children&&i(c.props.children)})}return i(t),s},[t]);return d.jsxs(Aw,{children:[d.jsx(wd,{}),d.jsxs(Gi,{ref:r,className:ae("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...n,children:[!o&&d.jsx(no,{className:"sr-only",children:"Dialog"}),t,d.jsxs(Iw,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[d.jsx(pe.X,{className:"h-4 w-4"}),d.jsx("span",{className:"sr-only",children:"Close"})]})]})]})});Yi.displayName=Gi.displayName;const vd=({className:e,...t})=>d.jsx("div",{className:ae("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});vd.displayName="DialogHeader";const yd=w.forwardRef(({className:e,...t},n)=>d.jsx(no,{ref:n,className:ae("text-lg font-semibold leading-none tracking-tight",e),...t}));yd.displayName=no.displayName;const Nw=w.forwardRef(({className:e,...t},n)=>d.jsx(xd,{ref:n,className:ae("text-sm text-muted-foreground",e),...t}));Nw.displayName=xd.displayName;function _w(e,t){return t==="application/octet-stream"&&e.toLowerCase().endsWith(".pdf")?"application/pdf":t}function jw({isOpen:e,onClose:t,fileId:n,fileName:r,mimeType:o}){const{chatApi:s}=Vn(),i=s.getAuthToken();if(!e||!n)return null;const a=`${s.baseUrl}/files/${n}/view?token=${i}`,l=_w(r,o).startsWith("image/");return d.jsx(bd,{open:e,onOpenChange:t,children:d.jsx(Yi,{className:"max-w-6xl w-[95vw] h-[90vh] p-0 overflow-hidden border-none bg-background/95 backdrop-blur-md shadow-2xl",children:d.jsxs("div",{className:"w-full h-full flex flex-col relative group",children:[d.jsx("div",{className:"flex-1 min-h-0 w-full h-full bg-background/50 overflow-hidden",children:l?d.jsx("div",{className:"w-full h-full flex items-center justify-center p-8",children:d.jsx("img",{src:a,alt:r,className:"max-w-full max-h-full object-contain drop-shadow-2xl rounded-sm",loading:"lazy"})}):d.jsx("iframe",{src:a,className:"w-full h-full border-none",title:r,loading:"lazy"})}),d.jsx("div",{className:"absolute top-4 left-4 bg-background/80 backdrop-blur-md px-3 py-1.5 rounded-full border border-border text-xs font-medium text-muted-foreground opacity-100 group-hover:opacity-0 transition-opacity pointer-events-none shadow-sm",children:r})]})})})}function Pw({artifact:e,showPartialData:t=!1}){if(!e||typeof e!="object")return null;const n=Po({artifact:e});if(!n)return null;const r=ig(e),o=n.progress??0,s=n.status??"completed";if(s==="completed"&&!t)return null;const i=()=>{switch(s){case"pending":case"in_progress":return d.jsx(pe.Loader2,{className:"h-4 w-4 animate-spin text-blue-500"});case"completed":return d.jsx(pe.CheckCircle2,{className:"h-4 w-4 text-green-500"});case"failed":return d.jsx(pe.XCircle,{className:"h-4 w-4 text-red-500"});default:return null}},a=()=>{switch(s){case"pending":return"Preparing...";case"in_progress":return o>0?`${o}% complete`:"Processing...";case"completed":return"Complete";case"failed":return n.error??"Failed";default:return""}};return d.jsxs("div",{className:"rounded-md border border-border/40 bg-muted/30 p-3 space-y-2",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[i(),d.jsx("span",{className:"text-sm font-medium capitalize",children:n.type.replace(/_/g," ")})]}),d.jsx("span",{className:"text-xs text-muted-foreground",children:a()})]}),r&&o>0&&d.jsx("div",{className:"w-full bg-muted rounded-full h-1.5",children:d.jsx("div",{className:"bg-blue-500 h-1.5 rounded-full transition-all duration-300 ease-out",style:{width:`${o}%`}})}),s==="failed"&&n.error&&d.jsx("div",{className:"text-xs text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-950/20 p-2 rounded",children:n.error}),t&&s==="in_progress"&&e.partial_data&&d.jsxs("div",{className:"text-xs text-muted-foreground",children:[d.jsx("div",{className:"font-medium mb-1",children:"Preview:"}),d.jsx("pre",{className:"bg-background/50 rounded p-2 overflow-auto max-h-32",children:JSON.stringify(e.partial_data,null,2)})]})]})}const Ow="prose prose-sm max-w-none break-words dark:prose-invert prose-headings:break-words prose-p:break-words prose-li:break-words prose-td:break-words prose-th:break-words prose-a:break-all prose-code:break-words prose-blockquote:break-words";function Rw({data:e}){return Array.isArray(e)?e.every(n=>n===null||["string","number","boolean"].includes(typeof n))?d.jsx("div",{className:Ow,children:d.jsx("ul",{className:"list-disc pl-5",children:e.map((n,r)=>d.jsx("li",{children:String(n)},r))})}):d.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:fr(e)}):d.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:fr(e)})}function Sd(e,t){return x.useMemo(()=>{const n=new Map,r=ni(e);r.length>0?r.forEach((i,a)=>{const c=i.toolCallId||`streaming-${a}`;n.set(c,{toolCallId:c,toolName:i.step||i.toolName||"tool",status:i.type==="tool.end"?"completed":"running",content:i.content,artifact:i.artifact,output:i.output})}):t&&e.role==="assistant"&&sg(t,e.id).forEach(a=>{const c=n.get(a.toolCallId);a.type==="tool.start"?n.set(a.toolCallId,{toolCallId:a.toolCallId,toolName:a.toolName,status:"running",content:a.content,timestamp:a.timestamp,...c}):n.set(a.toolCallId,{...c,toolCallId:a.toolCallId,toolName:a.toolName,status:"completed",output:a.output,artifact:a.artifact,content:a.content||(c==null?void 0:c.content),timestamp:a.timestamp||(c==null?void 0:c.timestamp)})});const o=Array.from(n.values()),s=o.filter(i=>i.artifact).map(i=>i.artifact);return{steps:o,artifacts:s,hasToolExecution:o.length>0}},[e,t])}function Mw({message:e,allMessages:t}){const n=e.name??"tool",{steps:r}=Sd(e,t);return r.length===0?null:d.jsx("div",{className:"space-y-1 py-1",children:r.map((o,s)=>{const i=o.status==="running",a=o.toolName||n;return d.jsxs("div",{className:"group/step flex items-start gap-3 px-2 py-1.5 rounded-md hover:bg-muted/30 transition-colors",children:[d.jsx("div",{className:"shrink-0 flex items-center justify-center h-4 mt-0.5",children:d.jsx("span",{className:"text-[10px] font-mono font-medium text-muted-foreground/40 group-hover/step:text-muted-foreground/60 transition-colors",children:(s+1).toString().padStart(2,"0")})}),d.jsxs("div",{className:"flex-1 min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted-foreground/70 group-hover/step:text-foreground/80 transition-colors truncate",children:a}),i?d.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[d.jsx("span",{className:"flex h-1.5 w-1.5 rounded-full bg-blue-500 animate-pulse"}),d.jsx("span",{className:"text-[9px] text-blue-500 font-medium lowercase",children:"running"})]}):d.jsx("div",{className:"flex items-center gap-1 shrink-0 opacity-0 group-hover/step:opacity-100 transition-opacity",children:d.jsx("span",{className:"text-[9px] text-muted-foreground/50 font-medium lowercase",children:"completed"})}),!!o.artifact&&d.jsx("span",{className:"shrink-0 text-[8px] px-1 py-0 rounded bg-primary/10 text-primary/70 font-semibold border border-primary/20 leading-none",children:"Artifact"})]}),o.content&&d.jsx("p",{className:"text-[10px] text-muted-foreground/60 truncate group-hover/step:text-muted-foreground/80 transition-colors",children:o.content})]})]},o.toolCallId||s)})})}const Cd=w.forwardRef(({className:e,...t},n)=>d.jsx("div",{ref:n,className:ae("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));Cd.displayName="Card";const kd=w.forwardRef(({className:e,...t},n)=>d.jsx("div",{ref:n,className:ae("flex flex-col space-y-1.5 p-6",e),...t}));kd.displayName="CardHeader";const Td=w.forwardRef(({className:e,...t},n)=>d.jsx("h3",{ref:n,className:ae("text-2xl font-semibold leading-none tracking-tight",e),...t}));Td.displayName="CardTitle";const Ed=w.forwardRef(({className:e,...t},n)=>d.jsx("p",{ref:n,className:ae("text-sm text-muted-foreground",e),...t}));Ed.displayName="CardDescription";const Xi=w.forwardRef(({className:e,...t},n)=>d.jsx("div",{ref:n,className:ae("p-6 pt-0",e),...t}));Xi.displayName="CardContent";const Id=w.forwardRef(({className:e,...t},n)=>d.jsx("div",{ref:n,className:ae("flex items-center p-6 pt-0",e),...t}));Id.displayName="CardFooter";const Dw=e=>!!e&&typeof e=="object"&&e.type==="user_choice"&&typeof e.question=="string"&&Array.isArray(e.alternatives);function Ad({interruptPart:e,onApprove:t,onReject:n,onSelectAlternative:r,disabled:o,isActive:s,payload:i}){const a=Dw(i)?i:null,c=(a==null?void 0:a.question)??e.title??"Approve the result?",l=a?s?"Select one of the alternatives to continue.":"Waiting for approval from another participant.":s?"Please approve or reject this action to resume the workflow.":"Waiting for approval from another participant.";let u=null;if(!a&&i!==void 0&&i!==null)if(typeof i=="string")u=d.jsx("p",{className:"text-sm leading-relaxed text-blue-800/90 dark:text-blue-200/90 whitespace-pre-wrap",children:i});else{const f=fr(i);u=d.jsx("pre",{className:"max-h-48 overflow-auto rounded bg-blue-100/60 p-2 text-xs text-blue-900/90 dark:bg-blue-900/40 dark:text-blue-100/80",children:f})}return d.jsxs(Cd,{className:ae("border-blue-200 dark:border-blue-800 bg-blue-50/50 dark:bg-blue-950/10 transition-shadow",s?"shadow-md ring-1 ring-blue-300 dark:ring-blue-500/70":"opacity-80"),children:[d.jsxs(kd,{className:"pb-3",children:[d.jsx(Td,{className:"text-blue-900 dark:text-blue-100 text-base",children:c}),d.jsx(Ed,{className:"text-blue-700 dark:text-blue-300 text-sm",children:l})]}),a?d.jsx(Xi,{className:"pt-0 pb-3",children:d.jsx("div",{className:"space-y-2",children:a.alternatives.map(f=>d.jsx(Ke,{size:"sm",variant:"outline",onClick:()=>r==null?void 0:r(e,f),className:"w-full justify-start text-left",disabled:o||!s,children:d.jsxs("div",{className:"flex flex-col items-start gap-1",children:[d.jsx("span",{className:"font-semibold",children:f.label}),f.description?d.jsx("span",{className:"text-xs text-muted-foreground leading-snug",children:f.description}):null]})},f.id))})}):u&&d.jsx(Xi,{className:"pt-0 pb-3",children:u}),!a&&d.jsx(Id,{className:"pt-0",children:d.jsxs("div",{className:"flex gap-2 ml-auto",children:[d.jsx(Ke,{size:"sm",variant:"outline",onClick:()=>n(e),className:"border-red-300 text-red-700 hover:bg-red-50 dark:border-red-700 dark:text-red-300 dark:hover:bg-red-950/50",disabled:o||!s,children:"Reject"}),d.jsx(Ke,{size:"sm",onClick:()=>t(e),className:"bg-blue-600 hover:bg-blue-700 text-white",disabled:o||!s,children:"Approve"})]})})]})}function Lw({className:e}){const t=x.useRef(null);return x.useEffect(()=>{let n=0;const r=()=>{if(n=(n+1)%4,t.current){const s=".".repeat(n);t.current.textContent=`Is thinking${s}`}};r();const o=setInterval(r,500);return()=>clearInterval(o)},[]),d.jsx("span",{ref:t,"aria-live":"polite",className:ae("inline-block text-xs opacity-70 ml-1",e),children:"Is thinking"})}function Nd(){return{async:!1,baseUrl:null,breaks:!1,extensions:null,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,hooks:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1}}let Zn=Nd();function $w(e){Zn=e}const _d=/[&<>"']/,Fw=new RegExp(_d.source,"g"),jd=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,zw=new RegExp(jd.source,"g"),Bw={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Pd=e=>Bw[e];function Ct(e,t){if(t){if(_d.test(e))return e.replace(Fw,Pd)}else if(jd.test(e))return e.replace(zw,Pd);return e}const Hw=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function Od(e){return e.replace(Hw,(t,n)=>(n=n.toLowerCase(),n==="colon"?":":n.charAt(0)==="#"?n.charAt(1)==="x"?String.fromCharCode(parseInt(n.substring(2),16)):String.fromCharCode(+n.substring(1)):""))}const Uw=/(^|[^\[])\^/g;function We(e,t){e=typeof e=="string"?e:e.source,t=t||"";const n={replace:(r,o)=>(o=o.source||o,o=o.replace(Uw,"$1"),e=e.replace(r,o),n),getRegex:()=>new RegExp(e,t)};return n}const Ww=/[^\w:]/g,Vw=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function Rd(e,t,n){if(e){let r;try{r=decodeURIComponent(Od(n)).replace(Ww,"").toLowerCase()}catch{return null}if(r.indexOf("javascript:")===0||r.indexOf("vbscript:")===0||r.indexOf("data:")===0)return null}t&&!Vw.test(n)&&(n=Yw(t,n));try{n=encodeURI(n).replace(/%25/g,"%")}catch{return null}return n}const os={},Kw=/^[^:]+:\/*[^/]*$/,qw=/^([^:]+:)[\s\S]*$/,Gw=/^([^:]+:\/*[^/]*)[\s\S]*$/;function Yw(e,t){os[" "+e]||(Kw.test(e)?os[" "+e]=e+"/":os[" "+e]=is(e,"/",!0)),e=os[" "+e];const n=e.indexOf(":")===-1;return t.substring(0,2)==="//"?n?t:e.replace(qw,"$1")+t:t.charAt(0)==="/"?n?t:e.replace(Gw,"$1")+t:e+t}const ss={exec:function(){}};function Md(e,t){const n=e.replace(/\|/g,(s,i,a)=>{let c=!1,l=i;for(;--l>=0&&a[l]==="\\";)c=!c;return c?"|":" |"}),r=n.split(/ \|/);let o=0;if(r[0].trim()||r.shift(),r.length>0&&!r[r.length-1].trim()&&r.pop(),r.length>t)r.splice(t);else for(;r.length<t;)r.push("");for(;o<r.length;o++)r[o]=r[o].trim().replace(/\\\|/g,"|");return r}function is(e,t,n){const r=e.length;if(r===0)return"";let o=0;for(;o<r;){const s=e.charAt(r-o-1);if(s===t&&!n)o++;else if(s!==t&&n)o++;else break}return e.slice(0,r-o)}function Xw(e,t){if(e.indexOf(t[1])===-1)return-1;const n=e.length;let r=0,o=0;for(;o<n;o++)if(e[o]==="\\")o++;else if(e[o]===t[0])r++;else if(e[o]===t[1]&&(r--,r<0))return o;return-1}function Jw(e){e&&e.sanitize&&!e.silent&&console.warn("marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options")}function Dd(e,t){if(t<1)return"";let n="";for(;t>1;)t&1&&(n+=e),t>>=1,e+=e;return n+e}function Ld(e,t,n,r){const o=t.href,s=t.title?Ct(t.title):null,i=e[1].replace(/\\([\[\]])/g,"$1");if(e[0].charAt(0)!=="!"){r.state.inLink=!0;const a={type:"link",raw:n,href:o,title:s,text:i,tokens:r.inlineTokens(i)};return r.state.inLink=!1,a}return{type:"image",raw:n,href:o,title:s,text:Ct(i)}}function Zw(e,t){const n=e.match(/^(\s+)(?:```)/);if(n===null)return t;const r=n[1];return t.split(`
83
+ For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return w.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},Tw="DialogDescriptionWarning",Ew=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${hd(Tw).contentName}}.`;return w.useEffect(()=>{var s;const o=(s=e.current)==null?void 0:s.getAttribute("aria-describedby");t&&o&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},pd=ed,md=rd,qi=od,Gi=sd,no=ad,gd=cd,Iw=dd;const xd=pd,Aw=md,bd=w.forwardRef(({className:e,...t},n)=>d.jsx(qi,{ref:n,className:ae("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));bd.displayName=qi.displayName;const Yi=w.forwardRef(({className:e,children:t,...n},r)=>{const o=w.useMemo(()=>{let s=!1;function i(a){w.Children.forEach(a,c=>{if(s||!w.isValidElement(c))return;const l=c.type;if(l===no||(l==null?void 0:l.displayName)===no.displayName||(l==null?void 0:l.name)==="DialogTitle"){s=!0;return}c.props&&c.props.children&&i(c.props.children)})}return i(t),s},[t]);return d.jsxs(Aw,{children:[d.jsx(bd,{}),d.jsxs(Gi,{ref:r,className:ae("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...n,children:[!o&&d.jsx(no,{className:"sr-only",children:"Dialog"}),t,d.jsxs(Iw,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[d.jsx(pe.X,{className:"h-4 w-4"}),d.jsx("span",{className:"sr-only",children:"Close"})]})]})]})});Yi.displayName=Gi.displayName;const wd=({className:e,...t})=>d.jsx("div",{className:ae("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});wd.displayName="DialogHeader";const vd=w.forwardRef(({className:e,...t},n)=>d.jsx(no,{ref:n,className:ae("text-lg font-semibold leading-none tracking-tight",e),...t}));vd.displayName=no.displayName;const Nw=w.forwardRef(({className:e,...t},n)=>d.jsx(gd,{ref:n,className:ae("text-sm text-muted-foreground",e),...t}));Nw.displayName=gd.displayName;function _w(e,t){return t==="application/octet-stream"&&e.toLowerCase().endsWith(".pdf")?"application/pdf":t}function jw({isOpen:e,onClose:t,fileId:n,fileName:r,mimeType:o}){const{chatApi:s}=Vn(),i=s.getAuthToken();if(!e||!n)return null;const a=`${s.baseUrl}/files/${n}/view?token=${i}`,l=_w(r,o).startsWith("image/");return d.jsx(xd,{open:e,onOpenChange:t,children:d.jsx(Yi,{className:"max-w-6xl w-[95vw] h-[90vh] p-0 overflow-hidden border-none bg-background/95 backdrop-blur-md shadow-2xl",children:d.jsxs("div",{className:"w-full h-full flex flex-col relative group",children:[d.jsx("div",{className:"flex-1 min-h-0 w-full h-full bg-background/50 overflow-hidden",children:l?d.jsx("div",{className:"w-full h-full flex items-center justify-center p-8",children:d.jsx("img",{src:a,alt:r,className:"max-w-full max-h-full object-contain drop-shadow-2xl rounded-sm",loading:"lazy"})}):d.jsx("iframe",{src:a,className:"w-full h-full border-none",title:r,loading:"lazy"})}),d.jsx("div",{className:"absolute top-4 left-4 bg-background/80 backdrop-blur-md px-3 py-1.5 rounded-full border border-border text-xs font-medium text-muted-foreground opacity-100 group-hover:opacity-0 transition-opacity pointer-events-none shadow-sm",children:r})]})})})}function Pw({artifact:e,showPartialData:t=!1}){if(!e||typeof e!="object")return null;const n=Po({artifact:e});if(!n)return null;const r=ig(e),o=n.progress??0,s=n.status??"completed";if(s==="completed"&&!t)return null;const i=()=>{switch(s){case"pending":case"in_progress":return d.jsx(pe.Loader2,{className:"h-4 w-4 animate-spin text-blue-500"});case"completed":return d.jsx(pe.CheckCircle2,{className:"h-4 w-4 text-green-500"});case"failed":return d.jsx(pe.XCircle,{className:"h-4 w-4 text-red-500"});default:return null}},a=()=>{switch(s){case"pending":return"Preparing...";case"in_progress":return o>0?`${o}% complete`:"Processing...";case"completed":return"Complete";case"failed":return n.error??"Failed";default:return""}};return d.jsxs("div",{className:"rounded-md border border-border/40 bg-muted/30 p-3 space-y-2",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[i(),d.jsx("span",{className:"text-sm font-medium capitalize",children:n.type.replace(/_/g," ")})]}),d.jsx("span",{className:"text-xs text-muted-foreground",children:a()})]}),r&&o>0&&d.jsx("div",{className:"w-full bg-muted rounded-full h-1.5",children:d.jsx("div",{className:"bg-blue-500 h-1.5 rounded-full transition-all duration-300 ease-out",style:{width:`${o}%`}})}),s==="failed"&&n.error&&d.jsx("div",{className:"text-xs text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-950/20 p-2 rounded",children:n.error}),t&&s==="in_progress"&&e.partial_data&&d.jsxs("div",{className:"text-xs text-muted-foreground",children:[d.jsx("div",{className:"font-medium mb-1",children:"Preview:"}),d.jsx("pre",{className:"bg-background/50 rounded p-2 overflow-auto max-h-32",children:JSON.stringify(e.partial_data,null,2)})]})]})}const Ow="prose prose-sm max-w-none break-words dark:prose-invert prose-headings:break-words prose-p:break-words prose-li:break-words prose-td:break-words prose-th:break-words prose-a:break-all prose-code:break-words prose-blockquote:break-words";function Rw({data:e}){return Array.isArray(e)?e.every(n=>n===null||["string","number","boolean"].includes(typeof n))?d.jsx("div",{className:Ow,children:d.jsx("ul",{className:"list-disc pl-5",children:e.map((n,r)=>d.jsx("li",{children:String(n)},r))})}):d.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:fr(e)}):d.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:fr(e)})}function yd(e,t){return x.useMemo(()=>{const n=new Map,r=ni(e);r.length>0?r.forEach((i,a)=>{const c=i.toolCallId||`streaming-${a}`;n.set(c,{toolCallId:c,toolName:i.step||i.toolName||"tool",status:i.type==="tool.end"?"completed":"running",content:i.content,artifact:i.artifact,output:i.output})}):t&&e.role==="assistant"&&sg(t,e.id).forEach(a=>{const c=n.get(a.toolCallId);a.type==="tool.start"?n.set(a.toolCallId,{toolCallId:a.toolCallId,toolName:a.toolName,status:"running",content:a.content,timestamp:a.timestamp,...c}):n.set(a.toolCallId,{...c,toolCallId:a.toolCallId,toolName:a.toolName,status:"completed",output:a.output,artifact:a.artifact,content:a.content||(c==null?void 0:c.content),timestamp:a.timestamp||(c==null?void 0:c.timestamp)})});const o=Array.from(n.values()),s=o.filter(i=>i.artifact).map(i=>i.artifact);return{steps:o,artifacts:s,hasToolExecution:o.length>0}},[e,t])}function Mw({message:e,allMessages:t}){const n=e.name??"tool",{steps:r}=yd(e,t);return r.length===0?null:d.jsx("div",{className:"space-y-1 py-1",children:r.map((o,s)=>{const i=o.status==="running",a=o.toolName||n;return d.jsxs("div",{className:"group/step flex items-start gap-3 px-2 py-1.5 rounded-md hover:bg-muted/30 transition-colors",children:[d.jsx("div",{className:"shrink-0 flex items-center justify-center h-4 mt-0.5",children:d.jsx("span",{className:"text-[10px] font-mono font-medium text-muted-foreground/40 group-hover/step:text-muted-foreground/60 transition-colors",children:(s+1).toString().padStart(2,"0")})}),d.jsxs("div",{className:"flex-1 min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted-foreground/70 group-hover/step:text-foreground/80 transition-colors truncate",children:a}),i?d.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[d.jsx("span",{className:"flex h-1.5 w-1.5 rounded-full bg-blue-500 animate-pulse"}),d.jsx("span",{className:"text-[9px] text-blue-500 font-medium lowercase",children:"running"})]}):d.jsx("div",{className:"flex items-center gap-1 shrink-0 opacity-0 group-hover/step:opacity-100 transition-opacity",children:d.jsx("span",{className:"text-[9px] text-muted-foreground/50 font-medium lowercase",children:"completed"})}),!!o.artifact&&d.jsx("span",{className:"shrink-0 text-[8px] px-1 py-0 rounded bg-primary/10 text-primary/70 font-semibold border border-primary/20 leading-none",children:"Artifact"})]}),o.content&&d.jsx("p",{className:"text-[10px] text-muted-foreground/60 truncate group-hover/step:text-muted-foreground/80 transition-colors",children:o.content})]})]},o.toolCallId||s)})})}const Sd=w.forwardRef(({className:e,...t},n)=>d.jsx("div",{ref:n,className:ae("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));Sd.displayName="Card";const Cd=w.forwardRef(({className:e,...t},n)=>d.jsx("div",{ref:n,className:ae("flex flex-col space-y-1.5 p-6",e),...t}));Cd.displayName="CardHeader";const kd=w.forwardRef(({className:e,...t},n)=>d.jsx("h3",{ref:n,className:ae("text-2xl font-semibold leading-none tracking-tight",e),...t}));kd.displayName="CardTitle";const Td=w.forwardRef(({className:e,...t},n)=>d.jsx("p",{ref:n,className:ae("text-sm text-muted-foreground",e),...t}));Td.displayName="CardDescription";const Xi=w.forwardRef(({className:e,...t},n)=>d.jsx("div",{ref:n,className:ae("p-6 pt-0",e),...t}));Xi.displayName="CardContent";const Ed=w.forwardRef(({className:e,...t},n)=>d.jsx("div",{ref:n,className:ae("flex items-center p-6 pt-0",e),...t}));Ed.displayName="CardFooter";const Dw=e=>!!e&&typeof e=="object"&&e.type==="user_choice"&&typeof e.question=="string"&&Array.isArray(e.alternatives);function Id({interruptPart:e,onApprove:t,onReject:n,onSelectAlternative:r,disabled:o,isActive:s,payload:i}){const a=Dw(i)?i:null,c=(a==null?void 0:a.question)??e.title??"Approve the result?",l=a?s?"Select one of the alternatives to continue.":"Waiting for approval from another participant.":s?"Please approve or reject this action to resume the workflow.":"Waiting for approval from another participant.";let u=null;if(!a&&i!==void 0&&i!==null)if(typeof i=="string")u=d.jsx("p",{className:"text-sm leading-relaxed text-blue-800/90 dark:text-blue-200/90 whitespace-pre-wrap",children:i});else{const f=fr(i);u=d.jsx("pre",{className:"max-h-48 overflow-auto rounded bg-blue-100/60 p-2 text-xs text-blue-900/90 dark:bg-blue-900/40 dark:text-blue-100/80",children:f})}return d.jsxs(Sd,{className:ae("border-blue-200 dark:border-blue-800 bg-blue-50/50 dark:bg-blue-950/10 transition-shadow",s?"shadow-md ring-1 ring-blue-300 dark:ring-blue-500/70":"opacity-80"),children:[d.jsxs(Cd,{className:"pb-3",children:[d.jsx(kd,{className:"text-blue-900 dark:text-blue-100 text-base",children:c}),d.jsx(Td,{className:"text-blue-700 dark:text-blue-300 text-sm",children:l})]}),a?d.jsx(Xi,{className:"pt-0 pb-3",children:d.jsx("div",{className:"space-y-2",children:a.alternatives.map(f=>d.jsx(Ke,{size:"sm",variant:"outline",onClick:()=>r==null?void 0:r(e,f),className:"w-full justify-start text-left",disabled:o||!s,children:d.jsxs("div",{className:"flex flex-col items-start gap-1",children:[d.jsx("span",{className:"font-semibold",children:f.label}),f.description?d.jsx("span",{className:"text-xs text-muted-foreground leading-snug",children:f.description}):null]})},f.id))})}):u&&d.jsx(Xi,{className:"pt-0 pb-3",children:u}),!a&&d.jsx(Ed,{className:"pt-0",children:d.jsxs("div",{className:"flex gap-2 ml-auto",children:[d.jsx(Ke,{size:"sm",variant:"outline",onClick:()=>n(e),className:"border-red-300 text-red-700 hover:bg-red-50 dark:border-red-700 dark:text-red-300 dark:hover:bg-red-950/50",disabled:o||!s,children:"Reject"}),d.jsx(Ke,{size:"sm",onClick:()=>t(e),className:"bg-blue-600 hover:bg-blue-700 text-white",disabled:o||!s,children:"Approve"})]})})]})}function Lw({className:e}){const t=x.useRef(null);return x.useEffect(()=>{let n=0;const r=()=>{if(n=(n+1)%4,t.current){const s=".".repeat(n);t.current.textContent=`Is thinking${s}`}};r();const o=setInterval(r,500);return()=>clearInterval(o)},[]),d.jsx("span",{ref:t,"aria-live":"polite",className:ae("inline-block text-xs opacity-70 ml-1",e),children:"Is thinking"})}function Ad(){return{async:!1,baseUrl:null,breaks:!1,extensions:null,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,hooks:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1}}let Zn=Ad();function $w(e){Zn=e}const Nd=/[&<>"']/,Fw=new RegExp(Nd.source,"g"),_d=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,zw=new RegExp(_d.source,"g"),Bw={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},jd=e=>Bw[e];function Ct(e,t){if(t){if(Nd.test(e))return e.replace(Fw,jd)}else if(_d.test(e))return e.replace(zw,jd);return e}const Hw=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function Pd(e){return e.replace(Hw,(t,n)=>(n=n.toLowerCase(),n==="colon"?":":n.charAt(0)==="#"?n.charAt(1)==="x"?String.fromCharCode(parseInt(n.substring(2),16)):String.fromCharCode(+n.substring(1)):""))}const Uw=/(^|[^\[])\^/g;function We(e,t){e=typeof e=="string"?e:e.source,t=t||"";const n={replace:(r,o)=>(o=o.source||o,o=o.replace(Uw,"$1"),e=e.replace(r,o),n),getRegex:()=>new RegExp(e,t)};return n}const Ww=/[^\w:]/g,Vw=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function Od(e,t,n){if(e){let r;try{r=decodeURIComponent(Pd(n)).replace(Ww,"").toLowerCase()}catch{return null}if(r.indexOf("javascript:")===0||r.indexOf("vbscript:")===0||r.indexOf("data:")===0)return null}t&&!Vw.test(n)&&(n=Yw(t,n));try{n=encodeURI(n).replace(/%25/g,"%")}catch{return null}return n}const os={},Kw=/^[^:]+:\/*[^/]*$/,qw=/^([^:]+:)[\s\S]*$/,Gw=/^([^:]+:\/*[^/]*)[\s\S]*$/;function Yw(e,t){os[" "+e]||(Kw.test(e)?os[" "+e]=e+"/":os[" "+e]=is(e,"/",!0)),e=os[" "+e];const n=e.indexOf(":")===-1;return t.substring(0,2)==="//"?n?t:e.replace(qw,"$1")+t:t.charAt(0)==="/"?n?t:e.replace(Gw,"$1")+t:e+t}const ss={exec:function(){}};function Rd(e,t){const n=e.replace(/\|/g,(s,i,a)=>{let c=!1,l=i;for(;--l>=0&&a[l]==="\\";)c=!c;return c?"|":" |"}),r=n.split(/ \|/);let o=0;if(r[0].trim()||r.shift(),r.length>0&&!r[r.length-1].trim()&&r.pop(),r.length>t)r.splice(t);else for(;r.length<t;)r.push("");for(;o<r.length;o++)r[o]=r[o].trim().replace(/\\\|/g,"|");return r}function is(e,t,n){const r=e.length;if(r===0)return"";let o=0;for(;o<r;){const s=e.charAt(r-o-1);if(s===t&&!n)o++;else if(s!==t&&n)o++;else break}return e.slice(0,r-o)}function Xw(e,t){if(e.indexOf(t[1])===-1)return-1;const n=e.length;let r=0,o=0;for(;o<n;o++)if(e[o]==="\\")o++;else if(e[o]===t[0])r++;else if(e[o]===t[1]&&(r--,r<0))return o;return-1}function Jw(e){e&&e.sanitize&&!e.silent&&console.warn("marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options")}function Md(e,t){if(t<1)return"";let n="";for(;t>1;)t&1&&(n+=e),t>>=1,e+=e;return n+e}function Dd(e,t,n,r){const o=t.href,s=t.title?Ct(t.title):null,i=e[1].replace(/\\([\[\]])/g,"$1");if(e[0].charAt(0)!=="!"){r.state.inLink=!0;const a={type:"link",raw:n,href:o,title:s,text:i,tokens:r.inlineTokens(i)};return r.state.inLink=!1,a}return{type:"image",raw:n,href:o,title:s,text:Ct(i)}}function Zw(e,t){const n=e.match(/^(\s+)(?:```)/);if(n===null)return t;const r=n[1];return t.split(`
84
84
  `).map(o=>{const s=o.match(/^\s+/);if(s===null)return o;const[i]=s;return i.length>=r.length?o.slice(r.length):o}).join(`
85
85
  `)}class Ji{constructor(t){this.options=t||Zn}space(t){const n=this.rules.block.newline.exec(t);if(n&&n[0].length>0)return{type:"space",raw:n[0]}}code(t){const n=this.rules.block.code.exec(t);if(n){const r=n[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:n[0],codeBlockStyle:"indented",text:this.options.pedantic?r:is(r,`
86
86
  `)}}}fences(t){const n=this.rules.block.fences.exec(t);if(n){const r=n[0],o=Zw(r,n[3]||"");return{type:"code",raw:r,lang:n[2]?n[2].trim().replace(this.rules.inline._escapes,"$1"):n[2],text:o}}}heading(t){const n=this.rules.block.heading.exec(t);if(n){let r=n[2].trim();if(/#$/.test(r)){const o=is(r,"#");(this.options.pedantic||!o||/ $/.test(o))&&(r=o.trim())}return{type:"heading",raw:n[0],depth:n[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(t){const n=this.rules.block.hr.exec(t);if(n)return{type:"hr",raw:n[0]}}blockquote(t){const n=this.rules.block.blockquote.exec(t);if(n){const r=n[0].replace(/^ *>[ \t]?/gm,""),o=this.lexer.state.top;this.lexer.state.top=!0;const s=this.lexer.blockTokens(r);return this.lexer.state.top=o,{type:"blockquote",raw:n[0],tokens:s,text:r}}}list(t){let n=this.rules.block.list.exec(t);if(n){let r,o,s,i,a,c,l,u,f,h,p,m,g=n[1].trim();const b=g.length>1,v={type:"list",raw:"",ordered:b,start:b?+g.slice(0,-1):"",loose:!1,items:[]};g=b?`\\d{1,9}\\${g.slice(-1)}`:`\\${g}`,this.options.pedantic&&(g=b?g:"[*+-]");const y=new RegExp(`^( {0,3}${g})((?:[ ][^\\n]*)?(?:\\n|$))`);for(;t&&(m=!1,!(!(n=y.exec(t))||this.rules.block.hr.test(t)));){if(r=n[0],t=t.substring(r.length),u=n[2].split(`
@@ -90,10 +90,10 @@ For more information, see https://radix-ui.com/primitives/docs/components/${t.do
90
90
  `,1)[0],f=h,this.options.pedantic&&(f=f.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),!(S.test(f)||E.test(f)||I.test(f)||k.test(t)));){if(f.search(/[^ ]/)>=i||!f.trim())p+=`
91
91
  `+f.slice(i);else{if(c||u.search(/[^ ]/)>=4||S.test(u)||E.test(u)||k.test(u))break;p+=`
92
92
  `+f}!c&&!f.trim()&&(c=!0),r+=h+`
93
- `,t=t.substring(h.length+1),u=f.slice(i)}}v.loose||(l?v.loose=!0:/\n *\n *$/.test(r)&&(l=!0)),this.options.gfm&&(o=/^\[[ xX]\] /.exec(p),o&&(s=o[0]!=="[ ] ",p=p.replace(/^\[[ xX]\] +/,""))),v.items.push({type:"list_item",raw:r,task:!!o,checked:s,loose:!1,text:p}),v.raw+=r}v.items[v.items.length-1].raw=r.trimRight(),v.items[v.items.length-1].text=p.trimRight(),v.raw=v.raw.trimRight();const T=v.items.length;for(a=0;a<T;a++)if(this.lexer.state.top=!1,v.items[a].tokens=this.lexer.blockTokens(v.items[a].text,[]),!v.loose){const I=v.items[a].tokens.filter(S=>S.type==="space"),k=I.length>0&&I.some(S=>/\n.*\n/.test(S.raw));v.loose=k}if(v.loose)for(a=0;a<T;a++)v.items[a].loose=!0;return v}}html(t){const n=this.rules.block.html.exec(t);if(n){const r={type:"html",raw:n[0],pre:!this.options.sanitizer&&(n[1]==="pre"||n[1]==="script"||n[1]==="style"),text:n[0]};if(this.options.sanitize){const o=this.options.sanitizer?this.options.sanitizer(n[0]):Ct(n[0]);r.type="paragraph",r.text=o,r.tokens=this.lexer.inline(o)}return r}}def(t){const n=this.rules.block.def.exec(t);if(n){const r=n[1].toLowerCase().replace(/\s+/g," "),o=n[2]?n[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline._escapes,"$1"):"",s=n[3]?n[3].substring(1,n[3].length-1).replace(this.rules.inline._escapes,"$1"):n[3];return{type:"def",tag:r,raw:n[0],href:o,title:s}}}table(t){const n=this.rules.block.table.exec(t);if(n){const r={type:"table",header:Md(n[1]).map(o=>({text:o})),align:n[2].replace(/^ *|\| *$/g,"").split(/ *\| */),rows:n[3]&&n[3].trim()?n[3].replace(/\n[ \t]*$/,"").split(`
94
- `):[]};if(r.header.length===r.align.length){r.raw=n[0];let o=r.align.length,s,i,a,c;for(s=0;s<o;s++)/^ *-+: *$/.test(r.align[s])?r.align[s]="right":/^ *:-+: *$/.test(r.align[s])?r.align[s]="center":/^ *:-+ *$/.test(r.align[s])?r.align[s]="left":r.align[s]=null;for(o=r.rows.length,s=0;s<o;s++)r.rows[s]=Md(r.rows[s],r.header.length).map(l=>({text:l}));for(o=r.header.length,i=0;i<o;i++)r.header[i].tokens=this.lexer.inline(r.header[i].text);for(o=r.rows.length,i=0;i<o;i++)for(c=r.rows[i],a=0;a<c.length;a++)c[a].tokens=this.lexer.inline(c[a].text);return r}}}lheading(t){const n=this.rules.block.lheading.exec(t);if(n)return{type:"heading",raw:n[0],depth:n[2].charAt(0)==="="?1:2,text:n[1],tokens:this.lexer.inline(n[1])}}paragraph(t){const n=this.rules.block.paragraph.exec(t);if(n){const r=n[1].charAt(n[1].length-1)===`
95
- `?n[1].slice(0,-1):n[1];return{type:"paragraph",raw:n[0],text:r,tokens:this.lexer.inline(r)}}}text(t){const n=this.rules.block.text.exec(t);if(n)return{type:"text",raw:n[0],text:n[0],tokens:this.lexer.inline(n[0])}}escape(t){const n=this.rules.inline.escape.exec(t);if(n)return{type:"escape",raw:n[0],text:Ct(n[1])}}tag(t){const n=this.rules.inline.tag.exec(t);if(n)return!this.lexer.state.inLink&&/^<a /i.test(n[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(n[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(n[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(n[0])&&(this.lexer.state.inRawBlock=!1),{type:this.options.sanitize?"text":"html",raw:n[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,text:this.options.sanitize?this.options.sanitizer?this.options.sanitizer(n[0]):Ct(n[0]):n[0]}}link(t){const n=this.rules.inline.link.exec(t);if(n){const r=n[2].trim();if(!this.options.pedantic&&/^</.test(r)){if(!/>$/.test(r))return;const i=is(r.slice(0,-1),"\\");if((r.length-i.length)%2===0)return}else{const i=Xw(n[2],"()");if(i>-1){const c=(n[0].indexOf("!")===0?5:4)+n[1].length+i;n[2]=n[2].substring(0,i),n[0]=n[0].substring(0,c).trim(),n[3]=""}}let o=n[2],s="";if(this.options.pedantic){const i=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(o);i&&(o=i[1],s=i[3])}else s=n[3]?n[3].slice(1,-1):"";return o=o.trim(),/^</.test(o)&&(this.options.pedantic&&!/>$/.test(r)?o=o.slice(1):o=o.slice(1,-1)),Ld(n,{href:o&&o.replace(this.rules.inline._escapes,"$1"),title:s&&s.replace(this.rules.inline._escapes,"$1")},n[0],this.lexer)}}reflink(t,n){let r;if((r=this.rules.inline.reflink.exec(t))||(r=this.rules.inline.nolink.exec(t))){let o=(r[2]||r[1]).replace(/\s+/g," ");if(o=n[o.toLowerCase()],!o){const s=r[0].charAt(0);return{type:"text",raw:s,text:s}}return Ld(r,o,r[0],this.lexer)}}emStrong(t,n,r=""){let o=this.rules.inline.emStrong.lDelim.exec(t);if(!o||o[3]&&r.match(/[\p{L}\p{N}]/u))return;const s=o[1]||o[2]||"";if(!s||s&&(r===""||this.rules.inline.punctuation.exec(r))){const i=o[0].length-1;let a,c,l=i,u=0;const f=o[0][0]==="*"?this.rules.inline.emStrong.rDelimAst:this.rules.inline.emStrong.rDelimUnd;for(f.lastIndex=0,n=n.slice(-1*t.length+i);(o=f.exec(n))!=null;){if(a=o[1]||o[2]||o[3]||o[4]||o[5]||o[6],!a)continue;if(c=a.length,o[3]||o[4]){l+=c;continue}else if((o[5]||o[6])&&i%3&&!((i+c)%3)){u+=c;continue}if(l-=c,l>0)continue;c=Math.min(c,c+l+u);const h=t.slice(0,i+o.index+(o[0].length-a.length)+c);if(Math.min(i,c)%2){const m=h.slice(1,-1);return{type:"em",raw:h,text:m,tokens:this.lexer.inlineTokens(m)}}const p=h.slice(2,-2);return{type:"strong",raw:h,text:p,tokens:this.lexer.inlineTokens(p)}}}}codespan(t){const n=this.rules.inline.code.exec(t);if(n){let r=n[2].replace(/\n/g," ");const o=/[^ ]/.test(r),s=/^ /.test(r)&&/ $/.test(r);return o&&s&&(r=r.substring(1,r.length-1)),r=Ct(r,!0),{type:"codespan",raw:n[0],text:r}}}br(t){const n=this.rules.inline.br.exec(t);if(n)return{type:"br",raw:n[0]}}del(t){const n=this.rules.inline.del.exec(t);if(n)return{type:"del",raw:n[0],text:n[2],tokens:this.lexer.inlineTokens(n[2])}}autolink(t,n){const r=this.rules.inline.autolink.exec(t);if(r){let o,s;return r[2]==="@"?(o=Ct(this.options.mangle?n(r[1]):r[1]),s="mailto:"+o):(o=Ct(r[1]),s=o),{type:"link",raw:r[0],text:o,href:s,tokens:[{type:"text",raw:o,text:o}]}}}url(t,n){let r;if(r=this.rules.inline.url.exec(t)){let o,s;if(r[2]==="@")o=Ct(this.options.mangle?n(r[0]):r[0]),s="mailto:"+o;else{let i;do i=r[0],r[0]=this.rules.inline._backpedal.exec(r[0])[0];while(i!==r[0]);o=Ct(r[0]),r[1]==="www."?s="http://"+r[0]:s=r[0]}return{type:"link",raw:r[0],text:o,href:s,tokens:[{type:"text",raw:o,text:o}]}}}inlineText(t,n){const r=this.rules.inline.text.exec(t);if(r){let o;return this.lexer.state.inRawBlock?o=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(r[0]):Ct(r[0]):r[0]:o=Ct(this.options.smartypants?n(r[0]):r[0]),{type:"text",raw:r[0],text:o}}}}const we={newline:/^(?: *(?:\n|$))+/,code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hr:/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/,html:"^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))",def:/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/,table:ss,lheading:/^((?:.|\n(?!\n))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,_paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,text:/^[^\n]+/};we._label=/(?!\s*\])(?:\\.|[^\[\]\\])+/,we._title=/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/,we.def=We(we.def).replace("label",we._label).replace("title",we._title).getRegex(),we.bullet=/(?:[*+-]|\d{1,9}[.)])/,we.listItemStart=We(/^( *)(bull) */).replace("bull",we.bullet).getRegex(),we.list=We(we.list).replace(/bull/g,we.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+we.def.source+")").getRegex(),we._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",we._comment=/<!--(?!-?>)[\s\S]*?(?:-->|$)/,we.html=We(we.html,"i").replace("comment",we._comment).replace("tag",we._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),we.paragraph=We(we._paragraph).replace("hr",we.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",we._tag).getRegex(),we.blockquote=We(we.blockquote).replace("paragraph",we.paragraph).getRegex(),we.normal={...we},we.gfm={...we.normal,table:"^ *([^\\n ].*\\|.*)\\n {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)(?:\\| *)?(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"},we.gfm.table=We(we.gfm.table).replace("hr",we.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",we._tag).getRegex(),we.gfm.paragraph=We(we._paragraph).replace("hr",we.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("table",we.gfm.table).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",we._tag).getRegex(),we.pedantic={...we.normal,html:We(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",we._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:ss,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:We(we.normal._paragraph).replace("hr",we.hr).replace("heading",` *#{1,6} *[^
96
- ]`).replace("lheading",we.lheading).replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").getRegex()};const de={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:ss,tag:"^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>",link:/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(ref)\]/,nolink:/^!?\[(ref)\](?:\[\])?/,reflinkSearch:"reflink|nolink(?!\\()",emStrong:{lDelim:/^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/,rDelimAst:/^(?:[^_*\\]|\\.)*?\_\_(?:[^_*\\]|\\.)*?\*(?:[^_*\\]|\\.)*?(?=\_\_)|(?:[^*\\]|\\.)+(?=[^*])|[punct_](\*+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|(?:[^punct*_\s\\]|\\.)(\*+)(?=[^punct*_\s])/,rDelimUnd:/^(?:[^_*\\]|\\.)*?\*\*(?:[^_*\\]|\\.)*?\_(?:[^_*\\]|\\.)*?(?=\*\*)|(?:[^_\\]|\\.)+(?=[^_])|[punct*](\_+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/},code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:ss,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,punctuation:/^([\spunctuation])/};de._punctuation="!\"#$%&'()+\\-.,/:;<=>?@\\[\\]`^{|}~",de.punctuation=We(de.punctuation).replace(/punctuation/g,de._punctuation).getRegex(),de.blockSkip=/\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g,de.escapedEmSt=/(?:^|[^\\])(?:\\\\)*\\[*_]/g,de._comment=We(we._comment).replace("(?:-->|$)","-->").getRegex(),de.emStrong.lDelim=We(de.emStrong.lDelim).replace(/punct/g,de._punctuation).getRegex(),de.emStrong.rDelimAst=We(de.emStrong.rDelimAst,"g").replace(/punct/g,de._punctuation).getRegex(),de.emStrong.rDelimUnd=We(de.emStrong.rDelimUnd,"g").replace(/punct/g,de._punctuation).getRegex(),de._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g,de._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/,de._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/,de.autolink=We(de.autolink).replace("scheme",de._scheme).replace("email",de._email).getRegex(),de._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/,de.tag=We(de.tag).replace("comment",de._comment).replace("attribute",de._attribute).getRegex(),de._label=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,de._href=/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/,de._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/,de.link=We(de.link).replace("label",de._label).replace("href",de._href).replace("title",de._title).getRegex(),de.reflink=We(de.reflink).replace("label",de._label).replace("ref",we._label).getRegex(),de.nolink=We(de.nolink).replace("ref",we._label).getRegex(),de.reflinkSearch=We(de.reflinkSearch,"g").replace("reflink",de.reflink).replace("nolink",de.nolink).getRegex(),de.normal={...de},de.pedantic={...de.normal,strong:{start:/^__|\*\*/,middle:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,endAst:/\*\*(?!\*)/g,endUnd:/__(?!_)/g},em:{start:/^_|\*/,middle:/^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,endAst:/\*(?!\*)/g,endUnd:/_(?!_)/g},link:We(/^!?\[(label)\]\((.*?)\)/).replace("label",de._label).getRegex(),reflink:We(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",de._label).getRegex()},de.gfm={...de.normal,escape:We(de.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},de.gfm.url=We(de.gfm.url,"i").replace("email",de.gfm._extended_email).getRegex(),de.breaks={...de.gfm,br:We(de.br).replace("{2,}","*").getRegex(),text:We(de.gfm.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()};function Qw(e){return e.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…")}function $d(e){let t="",n,r;const o=e.length;for(n=0;n<o;n++)r=e.charCodeAt(n),Math.random()>.5&&(r="x"+r.toString(16)),t+="&#"+r+";";return t}class Dn{constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Zn,this.options.tokenizer=this.options.tokenizer||new Ji,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const n={block:we.normal,inline:de.normal};this.options.pedantic?(n.block=we.pedantic,n.inline=de.pedantic):this.options.gfm&&(n.block=we.gfm,this.options.breaks?n.inline=de.breaks:n.inline=de.gfm),this.tokenizer.rules=n}static get rules(){return{block:we,inline:de}}static lex(t,n){return new Dn(n).lex(t)}static lexInline(t,n){return new Dn(n).inlineTokens(t)}lex(t){t=t.replace(/\r\n|\r/g,`
93
+ `,t=t.substring(h.length+1),u=f.slice(i)}}v.loose||(l?v.loose=!0:/\n *\n *$/.test(r)&&(l=!0)),this.options.gfm&&(o=/^\[[ xX]\] /.exec(p),o&&(s=o[0]!=="[ ] ",p=p.replace(/^\[[ xX]\] +/,""))),v.items.push({type:"list_item",raw:r,task:!!o,checked:s,loose:!1,text:p}),v.raw+=r}v.items[v.items.length-1].raw=r.trimRight(),v.items[v.items.length-1].text=p.trimRight(),v.raw=v.raw.trimRight();const T=v.items.length;for(a=0;a<T;a++)if(this.lexer.state.top=!1,v.items[a].tokens=this.lexer.blockTokens(v.items[a].text,[]),!v.loose){const I=v.items[a].tokens.filter(S=>S.type==="space"),k=I.length>0&&I.some(S=>/\n.*\n/.test(S.raw));v.loose=k}if(v.loose)for(a=0;a<T;a++)v.items[a].loose=!0;return v}}html(t){const n=this.rules.block.html.exec(t);if(n){const r={type:"html",raw:n[0],pre:!this.options.sanitizer&&(n[1]==="pre"||n[1]==="script"||n[1]==="style"),text:n[0]};if(this.options.sanitize){const o=this.options.sanitizer?this.options.sanitizer(n[0]):Ct(n[0]);r.type="paragraph",r.text=o,r.tokens=this.lexer.inline(o)}return r}}def(t){const n=this.rules.block.def.exec(t);if(n){const r=n[1].toLowerCase().replace(/\s+/g," "),o=n[2]?n[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline._escapes,"$1"):"",s=n[3]?n[3].substring(1,n[3].length-1).replace(this.rules.inline._escapes,"$1"):n[3];return{type:"def",tag:r,raw:n[0],href:o,title:s}}}table(t){const n=this.rules.block.table.exec(t);if(n){const r={type:"table",header:Rd(n[1]).map(o=>({text:o})),align:n[2].replace(/^ *|\| *$/g,"").split(/ *\| */),rows:n[3]&&n[3].trim()?n[3].replace(/\n[ \t]*$/,"").split(`
94
+ `):[]};if(r.header.length===r.align.length){r.raw=n[0];let o=r.align.length,s,i,a,c;for(s=0;s<o;s++)/^ *-+: *$/.test(r.align[s])?r.align[s]="right":/^ *:-+: *$/.test(r.align[s])?r.align[s]="center":/^ *:-+ *$/.test(r.align[s])?r.align[s]="left":r.align[s]=null;for(o=r.rows.length,s=0;s<o;s++)r.rows[s]=Rd(r.rows[s],r.header.length).map(l=>({text:l}));for(o=r.header.length,i=0;i<o;i++)r.header[i].tokens=this.lexer.inline(r.header[i].text);for(o=r.rows.length,i=0;i<o;i++)for(c=r.rows[i],a=0;a<c.length;a++)c[a].tokens=this.lexer.inline(c[a].text);return r}}}lheading(t){const n=this.rules.block.lheading.exec(t);if(n)return{type:"heading",raw:n[0],depth:n[2].charAt(0)==="="?1:2,text:n[1],tokens:this.lexer.inline(n[1])}}paragraph(t){const n=this.rules.block.paragraph.exec(t);if(n){const r=n[1].charAt(n[1].length-1)===`
95
+ `?n[1].slice(0,-1):n[1];return{type:"paragraph",raw:n[0],text:r,tokens:this.lexer.inline(r)}}}text(t){const n=this.rules.block.text.exec(t);if(n)return{type:"text",raw:n[0],text:n[0],tokens:this.lexer.inline(n[0])}}escape(t){const n=this.rules.inline.escape.exec(t);if(n)return{type:"escape",raw:n[0],text:Ct(n[1])}}tag(t){const n=this.rules.inline.tag.exec(t);if(n)return!this.lexer.state.inLink&&/^<a /i.test(n[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(n[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(n[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(n[0])&&(this.lexer.state.inRawBlock=!1),{type:this.options.sanitize?"text":"html",raw:n[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,text:this.options.sanitize?this.options.sanitizer?this.options.sanitizer(n[0]):Ct(n[0]):n[0]}}link(t){const n=this.rules.inline.link.exec(t);if(n){const r=n[2].trim();if(!this.options.pedantic&&/^</.test(r)){if(!/>$/.test(r))return;const i=is(r.slice(0,-1),"\\");if((r.length-i.length)%2===0)return}else{const i=Xw(n[2],"()");if(i>-1){const c=(n[0].indexOf("!")===0?5:4)+n[1].length+i;n[2]=n[2].substring(0,i),n[0]=n[0].substring(0,c).trim(),n[3]=""}}let o=n[2],s="";if(this.options.pedantic){const i=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(o);i&&(o=i[1],s=i[3])}else s=n[3]?n[3].slice(1,-1):"";return o=o.trim(),/^</.test(o)&&(this.options.pedantic&&!/>$/.test(r)?o=o.slice(1):o=o.slice(1,-1)),Dd(n,{href:o&&o.replace(this.rules.inline._escapes,"$1"),title:s&&s.replace(this.rules.inline._escapes,"$1")},n[0],this.lexer)}}reflink(t,n){let r;if((r=this.rules.inline.reflink.exec(t))||(r=this.rules.inline.nolink.exec(t))){let o=(r[2]||r[1]).replace(/\s+/g," ");if(o=n[o.toLowerCase()],!o){const s=r[0].charAt(0);return{type:"text",raw:s,text:s}}return Dd(r,o,r[0],this.lexer)}}emStrong(t,n,r=""){let o=this.rules.inline.emStrong.lDelim.exec(t);if(!o||o[3]&&r.match(/[\p{L}\p{N}]/u))return;const s=o[1]||o[2]||"";if(!s||s&&(r===""||this.rules.inline.punctuation.exec(r))){const i=o[0].length-1;let a,c,l=i,u=0;const f=o[0][0]==="*"?this.rules.inline.emStrong.rDelimAst:this.rules.inline.emStrong.rDelimUnd;for(f.lastIndex=0,n=n.slice(-1*t.length+i);(o=f.exec(n))!=null;){if(a=o[1]||o[2]||o[3]||o[4]||o[5]||o[6],!a)continue;if(c=a.length,o[3]||o[4]){l+=c;continue}else if((o[5]||o[6])&&i%3&&!((i+c)%3)){u+=c;continue}if(l-=c,l>0)continue;c=Math.min(c,c+l+u);const h=t.slice(0,i+o.index+(o[0].length-a.length)+c);if(Math.min(i,c)%2){const m=h.slice(1,-1);return{type:"em",raw:h,text:m,tokens:this.lexer.inlineTokens(m)}}const p=h.slice(2,-2);return{type:"strong",raw:h,text:p,tokens:this.lexer.inlineTokens(p)}}}}codespan(t){const n=this.rules.inline.code.exec(t);if(n){let r=n[2].replace(/\n/g," ");const o=/[^ ]/.test(r),s=/^ /.test(r)&&/ $/.test(r);return o&&s&&(r=r.substring(1,r.length-1)),r=Ct(r,!0),{type:"codespan",raw:n[0],text:r}}}br(t){const n=this.rules.inline.br.exec(t);if(n)return{type:"br",raw:n[0]}}del(t){const n=this.rules.inline.del.exec(t);if(n)return{type:"del",raw:n[0],text:n[2],tokens:this.lexer.inlineTokens(n[2])}}autolink(t,n){const r=this.rules.inline.autolink.exec(t);if(r){let o,s;return r[2]==="@"?(o=Ct(this.options.mangle?n(r[1]):r[1]),s="mailto:"+o):(o=Ct(r[1]),s=o),{type:"link",raw:r[0],text:o,href:s,tokens:[{type:"text",raw:o,text:o}]}}}url(t,n){let r;if(r=this.rules.inline.url.exec(t)){let o,s;if(r[2]==="@")o=Ct(this.options.mangle?n(r[0]):r[0]),s="mailto:"+o;else{let i;do i=r[0],r[0]=this.rules.inline._backpedal.exec(r[0])[0];while(i!==r[0]);o=Ct(r[0]),r[1]==="www."?s="http://"+r[0]:s=r[0]}return{type:"link",raw:r[0],text:o,href:s,tokens:[{type:"text",raw:o,text:o}]}}}inlineText(t,n){const r=this.rules.inline.text.exec(t);if(r){let o;return this.lexer.state.inRawBlock?o=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(r[0]):Ct(r[0]):r[0]:o=Ct(this.options.smartypants?n(r[0]):r[0]),{type:"text",raw:r[0],text:o}}}}const we={newline:/^(?: *(?:\n|$))+/,code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hr:/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/,html:"^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))",def:/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/,table:ss,lheading:/^((?:.|\n(?!\n))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,_paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,text:/^[^\n]+/};we._label=/(?!\s*\])(?:\\.|[^\[\]\\])+/,we._title=/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/,we.def=We(we.def).replace("label",we._label).replace("title",we._title).getRegex(),we.bullet=/(?:[*+-]|\d{1,9}[.)])/,we.listItemStart=We(/^( *)(bull) */).replace("bull",we.bullet).getRegex(),we.list=We(we.list).replace(/bull/g,we.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+we.def.source+")").getRegex(),we._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",we._comment=/<!--(?!-?>)[\s\S]*?(?:-->|$)/,we.html=We(we.html,"i").replace("comment",we._comment).replace("tag",we._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),we.paragraph=We(we._paragraph).replace("hr",we.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",we._tag).getRegex(),we.blockquote=We(we.blockquote).replace("paragraph",we.paragraph).getRegex(),we.normal={...we},we.gfm={...we.normal,table:"^ *([^\\n ].*\\|.*)\\n {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)(?:\\| *)?(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"},we.gfm.table=We(we.gfm.table).replace("hr",we.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",we._tag).getRegex(),we.gfm.paragraph=We(we._paragraph).replace("hr",we.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("table",we.gfm.table).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",we._tag).getRegex(),we.pedantic={...we.normal,html:We(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",we._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:ss,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:We(we.normal._paragraph).replace("hr",we.hr).replace("heading",` *#{1,6} *[^
96
+ ]`).replace("lheading",we.lheading).replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").getRegex()};const de={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:ss,tag:"^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>",link:/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(ref)\]/,nolink:/^!?\[(ref)\](?:\[\])?/,reflinkSearch:"reflink|nolink(?!\\()",emStrong:{lDelim:/^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/,rDelimAst:/^(?:[^_*\\]|\\.)*?\_\_(?:[^_*\\]|\\.)*?\*(?:[^_*\\]|\\.)*?(?=\_\_)|(?:[^*\\]|\\.)+(?=[^*])|[punct_](\*+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|(?:[^punct*_\s\\]|\\.)(\*+)(?=[^punct*_\s])/,rDelimUnd:/^(?:[^_*\\]|\\.)*?\*\*(?:[^_*\\]|\\.)*?\_(?:[^_*\\]|\\.)*?(?=\*\*)|(?:[^_\\]|\\.)+(?=[^_])|[punct*](\_+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/},code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:ss,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,punctuation:/^([\spunctuation])/};de._punctuation="!\"#$%&'()+\\-.,/:;<=>?@\\[\\]`^{|}~",de.punctuation=We(de.punctuation).replace(/punctuation/g,de._punctuation).getRegex(),de.blockSkip=/\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g,de.escapedEmSt=/(?:^|[^\\])(?:\\\\)*\\[*_]/g,de._comment=We(we._comment).replace("(?:-->|$)","-->").getRegex(),de.emStrong.lDelim=We(de.emStrong.lDelim).replace(/punct/g,de._punctuation).getRegex(),de.emStrong.rDelimAst=We(de.emStrong.rDelimAst,"g").replace(/punct/g,de._punctuation).getRegex(),de.emStrong.rDelimUnd=We(de.emStrong.rDelimUnd,"g").replace(/punct/g,de._punctuation).getRegex(),de._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g,de._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/,de._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/,de.autolink=We(de.autolink).replace("scheme",de._scheme).replace("email",de._email).getRegex(),de._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/,de.tag=We(de.tag).replace("comment",de._comment).replace("attribute",de._attribute).getRegex(),de._label=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,de._href=/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/,de._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/,de.link=We(de.link).replace("label",de._label).replace("href",de._href).replace("title",de._title).getRegex(),de.reflink=We(de.reflink).replace("label",de._label).replace("ref",we._label).getRegex(),de.nolink=We(de.nolink).replace("ref",we._label).getRegex(),de.reflinkSearch=We(de.reflinkSearch,"g").replace("reflink",de.reflink).replace("nolink",de.nolink).getRegex(),de.normal={...de},de.pedantic={...de.normal,strong:{start:/^__|\*\*/,middle:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,endAst:/\*\*(?!\*)/g,endUnd:/__(?!_)/g},em:{start:/^_|\*/,middle:/^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,endAst:/\*(?!\*)/g,endUnd:/_(?!_)/g},link:We(/^!?\[(label)\]\((.*?)\)/).replace("label",de._label).getRegex(),reflink:We(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",de._label).getRegex()},de.gfm={...de.normal,escape:We(de.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},de.gfm.url=We(de.gfm.url,"i").replace("email",de.gfm._extended_email).getRegex(),de.breaks={...de.gfm,br:We(de.br).replace("{2,}","*").getRegex(),text:We(de.gfm.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()};function Qw(e){return e.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…")}function Ld(e){let t="",n,r;const o=e.length;for(n=0;n<o;n++)r=e.charCodeAt(n),Math.random()>.5&&(r="x"+r.toString(16)),t+="&#"+r+";";return t}class Dn{constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Zn,this.options.tokenizer=this.options.tokenizer||new Ji,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const n={block:we.normal,inline:de.normal};this.options.pedantic?(n.block=we.pedantic,n.inline=de.pedantic):this.options.gfm&&(n.block=we.gfm,this.options.breaks?n.inline=de.breaks:n.inline=de.gfm),this.tokenizer.rules=n}static get rules(){return{block:we,inline:de}}static lex(t,n){return new Dn(n).lex(t)}static lexInline(t,n){return new Dn(n).inlineTokens(t)}lex(t){t=t.replace(/\r\n|\r/g,`
97
97
  `),this.blockTokens(t,this.tokens);let n;for(;n=this.inlineQueue.shift();)this.inlineTokens(n.src,n.tokens);return this.tokens}blockTokens(t,n=[]){this.options.pedantic?t=t.replace(/\t/g," ").replace(/^ +$/gm,""):t=t.replace(/^( *)(\t+)/gm,(a,c,l)=>c+" ".repeat(l.length));let r,o,s,i;for(;t;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(a=>(r=a.call({lexer:this},t,n))?(t=t.substring(r.raw.length),n.push(r),!0):!1))){if(r=this.tokenizer.space(t)){t=t.substring(r.raw.length),r.raw.length===1&&n.length>0?n[n.length-1].raw+=`
98
98
  `:n.push(r);continue}if(r=this.tokenizer.code(t)){t=t.substring(r.raw.length),o=n[n.length-1],o&&(o.type==="paragraph"||o.type==="text")?(o.raw+=`
99
99
  `+r.raw,o.text+=`
@@ -103,7 +103,7 @@ For more information, see https://radix-ui.com/primitives/docs/components/${t.do
103
103
  `+r.raw,o.text+=`
104
104
  `+r.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):n.push(r),i=s.length!==t.length,t=t.substring(r.raw.length);continue}if(r=this.tokenizer.text(t)){t=t.substring(r.raw.length),o=n[n.length-1],o&&o.type==="text"?(o.raw+=`
105
105
  `+r.raw,o.text+=`
106
- `+r.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):n.push(r);continue}if(t){const a="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(a);break}else throw new Error(a)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){let r,o,s,i=t,a,c,l;if(this.tokens.links){const u=Object.keys(this.tokens.links);if(u.length>0)for(;(a=this.tokenizer.rules.inline.reflinkSearch.exec(i))!=null;)u.includes(a[0].slice(a[0].lastIndexOf("[")+1,-1))&&(i=i.slice(0,a.index)+"["+Dd("a",a[0].length-2)+"]"+i.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(a=this.tokenizer.rules.inline.blockSkip.exec(i))!=null;)i=i.slice(0,a.index)+"["+Dd("a",a[0].length-2)+"]"+i.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(a=this.tokenizer.rules.inline.escapedEmSt.exec(i))!=null;)i=i.slice(0,a.index+a[0].length-2)+"++"+i.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex),this.tokenizer.rules.inline.escapedEmSt.lastIndex--;for(;t;)if(c||(l=""),c=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some(u=>(r=u.call({lexer:this},t,n))?(t=t.substring(r.raw.length),n.push(r),!0):!1))){if(r=this.tokenizer.escape(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.tag(t)){t=t.substring(r.raw.length),o=n[n.length-1],o&&r.type==="text"&&o.type==="text"?(o.raw+=r.raw,o.text+=r.text):n.push(r);continue}if(r=this.tokenizer.link(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(r.raw.length),o=n[n.length-1],o&&r.type==="text"&&o.type==="text"?(o.raw+=r.raw,o.text+=r.text):n.push(r);continue}if(r=this.tokenizer.emStrong(t,i,l)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.codespan(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.br(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.del(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.autolink(t,$d)){t=t.substring(r.raw.length),n.push(r);continue}if(!this.state.inLink&&(r=this.tokenizer.url(t,$d))){t=t.substring(r.raw.length),n.push(r);continue}if(s=t,this.options.extensions&&this.options.extensions.startInline){let u=1/0;const f=t.slice(1);let h;this.options.extensions.startInline.forEach(function(p){h=p.call({lexer:this},f),typeof h=="number"&&h>=0&&(u=Math.min(u,h))}),u<1/0&&u>=0&&(s=t.substring(0,u+1))}if(r=this.tokenizer.inlineText(s,Qw)){t=t.substring(r.raw.length),r.raw.slice(-1)!=="_"&&(l=r.raw.slice(-1)),c=!0,o=n[n.length-1],o&&o.type==="text"?(o.raw+=r.raw,o.text+=r.text):n.push(r);continue}if(t){const u="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(u);break}else throw new Error(u)}}return n}}class Zi{constructor(t){this.options=t||Zn}code(t,n,r){const o=(n||"").match(/\S*/)[0];if(this.options.highlight){const s=this.options.highlight(t,o);s!=null&&s!==t&&(r=!0,t=s)}return t=t.replace(/\n$/,"")+`
106
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):n.push(r);continue}if(t){const a="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(a);break}else throw new Error(a)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){let r,o,s,i=t,a,c,l;if(this.tokens.links){const u=Object.keys(this.tokens.links);if(u.length>0)for(;(a=this.tokenizer.rules.inline.reflinkSearch.exec(i))!=null;)u.includes(a[0].slice(a[0].lastIndexOf("[")+1,-1))&&(i=i.slice(0,a.index)+"["+Md("a",a[0].length-2)+"]"+i.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(a=this.tokenizer.rules.inline.blockSkip.exec(i))!=null;)i=i.slice(0,a.index)+"["+Md("a",a[0].length-2)+"]"+i.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(a=this.tokenizer.rules.inline.escapedEmSt.exec(i))!=null;)i=i.slice(0,a.index+a[0].length-2)+"++"+i.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex),this.tokenizer.rules.inline.escapedEmSt.lastIndex--;for(;t;)if(c||(l=""),c=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some(u=>(r=u.call({lexer:this},t,n))?(t=t.substring(r.raw.length),n.push(r),!0):!1))){if(r=this.tokenizer.escape(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.tag(t)){t=t.substring(r.raw.length),o=n[n.length-1],o&&r.type==="text"&&o.type==="text"?(o.raw+=r.raw,o.text+=r.text):n.push(r);continue}if(r=this.tokenizer.link(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(r.raw.length),o=n[n.length-1],o&&r.type==="text"&&o.type==="text"?(o.raw+=r.raw,o.text+=r.text):n.push(r);continue}if(r=this.tokenizer.emStrong(t,i,l)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.codespan(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.br(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.del(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.autolink(t,Ld)){t=t.substring(r.raw.length),n.push(r);continue}if(!this.state.inLink&&(r=this.tokenizer.url(t,Ld))){t=t.substring(r.raw.length),n.push(r);continue}if(s=t,this.options.extensions&&this.options.extensions.startInline){let u=1/0;const f=t.slice(1);let h;this.options.extensions.startInline.forEach(function(p){h=p.call({lexer:this},f),typeof h=="number"&&h>=0&&(u=Math.min(u,h))}),u<1/0&&u>=0&&(s=t.substring(0,u+1))}if(r=this.tokenizer.inlineText(s,Qw)){t=t.substring(r.raw.length),r.raw.slice(-1)!=="_"&&(l=r.raw.slice(-1)),c=!0,o=n[n.length-1],o&&o.type==="text"?(o.raw+=r.raw,o.text+=r.text):n.push(r);continue}if(t){const u="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(u);break}else throw new Error(u)}}return n}}class Zi{constructor(t){this.options=t||Zn}code(t,n,r){const o=(n||"").match(/\S*/)[0];if(this.options.highlight){const s=this.options.highlight(t,o);s!=null&&s!==t&&(r=!0,t=s)}return t=t.replace(/\n$/,"")+`
107
107
  `,o?'<pre><code class="'+this.options.langPrefix+Ct(o)+'">'+(r?t:Ct(t,!0))+`</code></pre>
108
108
  `:"<pre><code>"+(r?t:Ct(t,!0))+`</code></pre>
109
109
  `}blockquote(t){return`<blockquote>
@@ -123,9 +123,9 @@ ${t}</blockquote>
123
123
  `}tablerow(t){return`<tr>
124
124
  ${t}</tr>
125
125
  `}tablecell(t,n){const r=n.header?"th":"td";return(n.align?`<${r} align="${n.align}">`:`<${r}>`)+t+`</${r}>
126
- `}strong(t){return`<strong>${t}</strong>`}em(t){return`<em>${t}</em>`}codespan(t){return`<code>${t}</code>`}br(){return this.options.xhtml?"<br/>":"<br>"}del(t){return`<del>${t}</del>`}link(t,n,r){if(t=Rd(this.options.sanitize,this.options.baseUrl,t),t===null)return r;let o='<a href="'+t+'"';return n&&(o+=' title="'+n+'"'),o+=">"+r+"</a>",o}image(t,n,r){if(t=Rd(this.options.sanitize,this.options.baseUrl,t),t===null)return r;let o=`<img src="${t}" alt="${r}"`;return n&&(o+=` title="${n}"`),o+=this.options.xhtml?"/>":">",o}text(t){return t}}class Fd{strong(t){return t}em(t){return t}codespan(t){return t}del(t){return t}html(t){return t}text(t){return t}link(t,n,r){return""+r}image(t,n,r){return""+r}br(){return""}}class zd{constructor(){this.seen={}}serialize(t){return t.toLowerCase().trim().replace(/<[!\/a-z].*?>/ig,"").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,"").replace(/\s/g,"-")}getNextSafeSlug(t,n){let r=t,o=0;if(this.seen.hasOwnProperty(r)){o=this.seen[t];do o++,r=t+"-"+o;while(this.seen.hasOwnProperty(r))}return n||(this.seen[t]=o,this.seen[r]=0),r}slug(t,n={}){const r=this.serialize(t);return this.getNextSafeSlug(r,n.dryrun)}}class Ln{constructor(t){this.options=t||Zn,this.options.renderer=this.options.renderer||new Zi,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new Fd,this.slugger=new zd}static parse(t,n){return new Ln(n).parse(t)}static parseInline(t,n){return new Ln(n).parseInline(t)}parse(t,n=!0){let r="",o,s,i,a,c,l,u,f,h,p,m,g,b,v,y,T,I,k,S;const E=t.length;for(o=0;o<E;o++){if(p=t[o],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[p.type]&&(S=this.options.extensions.renderers[p.type].call({parser:this},p),S!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(p.type))){r+=S||"";continue}switch(p.type){case"space":continue;case"hr":{r+=this.renderer.hr();continue}case"heading":{r+=this.renderer.heading(this.parseInline(p.tokens),p.depth,Od(this.parseInline(p.tokens,this.textRenderer)),this.slugger);continue}case"code":{r+=this.renderer.code(p.text,p.lang,p.escaped);continue}case"table":{for(f="",u="",a=p.header.length,s=0;s<a;s++)u+=this.renderer.tablecell(this.parseInline(p.header[s].tokens),{header:!0,align:p.align[s]});for(f+=this.renderer.tablerow(u),h="",a=p.rows.length,s=0;s<a;s++){for(l=p.rows[s],u="",c=l.length,i=0;i<c;i++)u+=this.renderer.tablecell(this.parseInline(l[i].tokens),{header:!1,align:p.align[i]});h+=this.renderer.tablerow(u)}r+=this.renderer.table(f,h);continue}case"blockquote":{h=this.parse(p.tokens),r+=this.renderer.blockquote(h);continue}case"list":{for(m=p.ordered,g=p.start,b=p.loose,a=p.items.length,h="",s=0;s<a;s++)y=p.items[s],T=y.checked,I=y.task,v="",y.task&&(k=this.renderer.checkbox(T),b?y.tokens.length>0&&y.tokens[0].type==="paragraph"?(y.tokens[0].text=k+" "+y.tokens[0].text,y.tokens[0].tokens&&y.tokens[0].tokens.length>0&&y.tokens[0].tokens[0].type==="text"&&(y.tokens[0].tokens[0].text=k+" "+y.tokens[0].tokens[0].text)):y.tokens.unshift({type:"text",text:k}):v+=k),v+=this.parse(y.tokens,b),h+=this.renderer.listitem(v,I,T);r+=this.renderer.list(h,m,g);continue}case"html":{r+=this.renderer.html(p.text);continue}case"paragraph":{r+=this.renderer.paragraph(this.parseInline(p.tokens));continue}case"text":{for(h=p.tokens?this.parseInline(p.tokens):p.text;o+1<E&&t[o+1].type==="text";)p=t[++o],h+=`
126
+ `}strong(t){return`<strong>${t}</strong>`}em(t){return`<em>${t}</em>`}codespan(t){return`<code>${t}</code>`}br(){return this.options.xhtml?"<br/>":"<br>"}del(t){return`<del>${t}</del>`}link(t,n,r){if(t=Od(this.options.sanitize,this.options.baseUrl,t),t===null)return r;let o='<a href="'+t+'"';return n&&(o+=' title="'+n+'"'),o+=">"+r+"</a>",o}image(t,n,r){if(t=Od(this.options.sanitize,this.options.baseUrl,t),t===null)return r;let o=`<img src="${t}" alt="${r}"`;return n&&(o+=` title="${n}"`),o+=this.options.xhtml?"/>":">",o}text(t){return t}}class $d{strong(t){return t}em(t){return t}codespan(t){return t}del(t){return t}html(t){return t}text(t){return t}link(t,n,r){return""+r}image(t,n,r){return""+r}br(){return""}}class Fd{constructor(){this.seen={}}serialize(t){return t.toLowerCase().trim().replace(/<[!\/a-z].*?>/ig,"").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,"").replace(/\s/g,"-")}getNextSafeSlug(t,n){let r=t,o=0;if(this.seen.hasOwnProperty(r)){o=this.seen[t];do o++,r=t+"-"+o;while(this.seen.hasOwnProperty(r))}return n||(this.seen[t]=o,this.seen[r]=0),r}slug(t,n={}){const r=this.serialize(t);return this.getNextSafeSlug(r,n.dryrun)}}class Ln{constructor(t){this.options=t||Zn,this.options.renderer=this.options.renderer||new Zi,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new $d,this.slugger=new Fd}static parse(t,n){return new Ln(n).parse(t)}static parseInline(t,n){return new Ln(n).parseInline(t)}parse(t,n=!0){let r="",o,s,i,a,c,l,u,f,h,p,m,g,b,v,y,T,I,k,S;const E=t.length;for(o=0;o<E;o++){if(p=t[o],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[p.type]&&(S=this.options.extensions.renderers[p.type].call({parser:this},p),S!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(p.type))){r+=S||"";continue}switch(p.type){case"space":continue;case"hr":{r+=this.renderer.hr();continue}case"heading":{r+=this.renderer.heading(this.parseInline(p.tokens),p.depth,Pd(this.parseInline(p.tokens,this.textRenderer)),this.slugger);continue}case"code":{r+=this.renderer.code(p.text,p.lang,p.escaped);continue}case"table":{for(f="",u="",a=p.header.length,s=0;s<a;s++)u+=this.renderer.tablecell(this.parseInline(p.header[s].tokens),{header:!0,align:p.align[s]});for(f+=this.renderer.tablerow(u),h="",a=p.rows.length,s=0;s<a;s++){for(l=p.rows[s],u="",c=l.length,i=0;i<c;i++)u+=this.renderer.tablecell(this.parseInline(l[i].tokens),{header:!1,align:p.align[i]});h+=this.renderer.tablerow(u)}r+=this.renderer.table(f,h);continue}case"blockquote":{h=this.parse(p.tokens),r+=this.renderer.blockquote(h);continue}case"list":{for(m=p.ordered,g=p.start,b=p.loose,a=p.items.length,h="",s=0;s<a;s++)y=p.items[s],T=y.checked,I=y.task,v="",y.task&&(k=this.renderer.checkbox(T),b?y.tokens.length>0&&y.tokens[0].type==="paragraph"?(y.tokens[0].text=k+" "+y.tokens[0].text,y.tokens[0].tokens&&y.tokens[0].tokens.length>0&&y.tokens[0].tokens[0].type==="text"&&(y.tokens[0].tokens[0].text=k+" "+y.tokens[0].tokens[0].text)):y.tokens.unshift({type:"text",text:k}):v+=k),v+=this.parse(y.tokens,b),h+=this.renderer.listitem(v,I,T);r+=this.renderer.list(h,m,g);continue}case"html":{r+=this.renderer.html(p.text);continue}case"paragraph":{r+=this.renderer.paragraph(this.parseInline(p.tokens));continue}case"text":{for(h=p.tokens?this.parseInline(p.tokens):p.text;o+1<E&&t[o+1].type==="text";)p=t[++o],h+=`
127
127
  `+(p.tokens?this.parseInline(p.tokens):p.text);r+=n?this.renderer.paragraph(h):h;continue}default:{const j='Token with "'+p.type+'" type was not found.';if(this.options.silent){console.error(j);return}else throw new Error(j)}}}return r}parseInline(t,n){n=n||this.renderer;let r="",o,s,i;const a=t.length;for(o=0;o<a;o++){if(s=t[o],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]&&(i=this.options.extensions.renderers[s.type].call({parser:this},s),i!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type))){r+=i||"";continue}switch(s.type){case"escape":{r+=n.text(s.text);break}case"html":{r+=n.html(s.text);break}case"link":{r+=n.link(s.href,s.title,this.parseInline(s.tokens,n));break}case"image":{r+=n.image(s.href,s.title,s.text);break}case"strong":{r+=n.strong(this.parseInline(s.tokens,n));break}case"em":{r+=n.em(this.parseInline(s.tokens,n));break}case"codespan":{r+=n.codespan(s.text);break}case"br":{r+=n.br();break}case"del":{r+=n.del(this.parseInline(s.tokens,n));break}case"text":{r+=n.text(s.text);break}default:{const c='Token with "'+s.type+'" type was not found.';if(this.options.silent){console.error(c);return}else throw new Error(c)}}}return r}}class as{constructor(t){this.options=t||Zn}preprocess(t){return t}postprocess(t){return t}}Ga(as,"passThroughHooks",new Set(["preprocess","postprocess"]));function ev(e,t,n){return r=>{if(r.message+=`
128
- Please report this to https://github.com/markedjs/marked.`,e){const o="<p>An error occurred:</p><pre>"+Ct(r.message+"",!0)+"</pre>";if(t)return Promise.resolve(o);if(n){n(null,o);return}return o}if(t)return Promise.reject(r);if(n){n(r);return}throw r}}function Bd(e,t){return(n,r,o)=>{typeof r=="function"&&(o=r,r=null);const s={...r};r={...xe.defaults,...s};const i=ev(r.silent,r.async,o);if(typeof n>"u"||n===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(Jw(r),r.hooks&&(r.hooks.options=r),o){const a=r.highlight;let c;try{r.hooks&&(n=r.hooks.preprocess(n)),c=e(n,r)}catch(f){return i(f)}const l=function(f){let h;if(!f)try{r.walkTokens&&xe.walkTokens(c,r.walkTokens),h=t(c,r),r.hooks&&(h=r.hooks.postprocess(h))}catch(p){f=p}return r.highlight=a,f?i(f):o(null,h)};if(!a||a.length<3||(delete r.highlight,!c.length))return l();let u=0;xe.walkTokens(c,function(f){f.type==="code"&&(u++,setTimeout(()=>{a(f.text,f.lang,function(h,p){if(h)return l(h);p!=null&&p!==f.text&&(f.text=p,f.escaped=!0),u--,u===0&&l()})},0))}),u===0&&l();return}if(r.async)return Promise.resolve(r.hooks?r.hooks.preprocess(n):n).then(a=>e(a,r)).then(a=>r.walkTokens?Promise.all(xe.walkTokens(a,r.walkTokens)).then(()=>a):a).then(a=>t(a,r)).then(a=>r.hooks?r.hooks.postprocess(a):a).catch(i);try{r.hooks&&(n=r.hooks.preprocess(n));const a=e(n,r);r.walkTokens&&xe.walkTokens(a,r.walkTokens);let c=t(a,r);return r.hooks&&(c=r.hooks.postprocess(c)),c}catch(a){return i(a)}}}function xe(e,t,n){return Bd(Dn.lex,Ln.parse)(e,t,n)}xe.options=xe.setOptions=function(e){return xe.defaults={...xe.defaults,...e},$w(xe.defaults),xe},xe.getDefaults=Nd,xe.defaults=Zn,xe.use=function(...e){const t=xe.defaults.extensions||{renderers:{},childTokens:{}};e.forEach(n=>{const r={...n};if(r.async=xe.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if(o.renderer){const s=t.renderers[o.name];s?t.renderers[o.name]=function(...i){let a=o.renderer.apply(this,i);return a===!1&&(a=s.apply(this,i)),a}:t.renderers[o.name]=o.renderer}if(o.tokenizer){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");t[o.level]?t[o.level].unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),r.extensions=t),n.renderer){const o=xe.defaults.renderer||new Zi;for(const s in n.renderer){const i=o[s];o[s]=(...a)=>{let c=n.renderer[s].apply(o,a);return c===!1&&(c=i.apply(o,a)),c}}r.renderer=o}if(n.tokenizer){const o=xe.defaults.tokenizer||new Ji;for(const s in n.tokenizer){const i=o[s];o[s]=(...a)=>{let c=n.tokenizer[s].apply(o,a);return c===!1&&(c=i.apply(o,a)),c}}r.tokenizer=o}if(n.hooks){const o=xe.defaults.hooks||new as;for(const s in n.hooks){const i=o[s];as.passThroughHooks.has(s)?o[s]=a=>{if(xe.defaults.async)return Promise.resolve(n.hooks[s].call(o,a)).then(l=>i.call(o,l));const c=n.hooks[s].call(o,a);return i.call(o,c)}:o[s]=(...a)=>{let c=n.hooks[s].apply(o,a);return c===!1&&(c=i.apply(o,a)),c}}r.hooks=o}if(n.walkTokens){const o=xe.defaults.walkTokens;r.walkTokens=function(s){let i=[];return i.push(n.walkTokens.call(this,s)),o&&(i=i.concat(o.call(this,s))),i}}xe.setOptions(r)})},xe.walkTokens=function(e,t){let n=[];for(const r of e)switch(n=n.concat(t.call(xe,r)),r.type){case"table":{for(const o of r.header)n=n.concat(xe.walkTokens(o.tokens,t));for(const o of r.rows)for(const s of o)n=n.concat(xe.walkTokens(s.tokens,t));break}case"list":{n=n.concat(xe.walkTokens(r.items,t));break}default:xe.defaults.extensions&&xe.defaults.extensions.childTokens&&xe.defaults.extensions.childTokens[r.type]?xe.defaults.extensions.childTokens[r.type].forEach(function(o){n=n.concat(xe.walkTokens(r[o],t))}):r.tokens&&(n=n.concat(xe.walkTokens(r.tokens,t)))}return n},xe.parseInline=Bd(Dn.lexInline,Ln.parseInline),xe.Parser=Ln,xe.parser=Ln.parse,xe.Renderer=Zi,xe.TextRenderer=Fd,xe.Lexer=Dn,xe.lexer=Dn.lex,xe.Tokenizer=Ji,xe.Slugger=zd,xe.Hooks=as,xe.parse=xe,xe.options,xe.setOptions,xe.use,xe.walkTokens,xe.parseInline,Ln.parse,Dn.lex;function ro({content:e,className:t="",allowHtml:n=!1,style:r}){const o=x.useMemo(()=>{if(!e||typeof e!="string"||e.trim().length===0)return"";try{if(!n){const i=e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");return typeof xe.parse=="function"?xe.parse(i):xe(i)}return typeof xe.parse=="function"?xe.parse(e):xe(e)}catch(i){return console.error("[MarkdownContent] parse error",i),`<pre class="font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words">Error rendering markdown: ${String(i)}</pre>`}},[e,n]),s=x.useMemo(()=>{const i={color:"currentColor",...r};if(r&&r.color){const a=r.color;return{...i,"--tw-prose-body":a,"--tw-prose-headings":a,"--tw-prose-links":a,"--tw-prose-bold":a,"--tw-prose-counters":a,"--tw-prose-bullets":a,"--tw-prose-hr":a,"--tw-prose-quotes":a,"--tw-prose-quote-borders":a,"--tw-prose-captions":a,"--tw-prose-code":a,"--tw-prose-pre-code":a,"--tw-prose-pre-bg":"inherit","--tw-prose-th-borders":a,"--tw-prose-td-borders":a}}return i},[r]);return d.jsx("div",{className:ae("markdown prose prose-sm max-w-none break-words","dark:prose-invert","text-current","prose-headings:text-current prose-p:text-current prose-li:text-current prose-a:text-current prose-strong:text-current","prose-em:text-current prose-blockquote:text-current prose-table:text-current prose-td:text-current prose-th:text-current","prose-pre:font-mono prose-pre:text-xs prose-pre:bg-background/50 prose-pre:border prose-pre:rounded prose-pre:p-3 prose-pre:whitespace-pre prose-pre:overflow-x-auto","prose-code:font-mono prose-code:text-sm prose-code:bg-background/50 prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-current",t),style:s,dangerouslySetInnerHTML:{__html:o}})}function tv({text:e,expanded:t,onExpandedChange:n,previewLength:r,isCompact:o}){const s=Math.max(e.length-r,0),i=e.substring(0,r);return d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("div",{className:ae("text-sm text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:t?d.jsx(ro,{content:e,allowHtml:!1}):d.jsxs("pre",{className:ae("font-sans whitespace-pre-wrap break-words bg-transparent p-0 m-0 text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:[i,"..."]})}),d.jsx(Ke,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-xs !text-[hsl(var(--chat-bubble-user-text))]",onClick:()=>n(!t),children:t?d.jsxs(d.Fragment,{children:[d.jsx(pe.ChevronUp,{className:"h-3 w-3 mr-1"})," Show less"]}):d.jsxs(d.Fragment,{children:[d.jsx(pe.ChevronDown,{className:"h-3 w-3 mr-1"})," Show more (",s," chars)"]})})]})}function nv(e,t,n){const[r,o]=x.useState(e),s=x.useRef(e),i=x.useRef(null);return x.useEffect(()=>{s.current=e;const a=()=>{o(s.current),i.current&&(clearTimeout(i.current),i.current=null)};if(!t||n<=0){a();return}return i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{a()},n),()=>{i.current&&(clearTimeout(i.current),i.current=null)}},[e,t,n]),r}function Hd({message:e,allMessages:t,isToolMessage:n,showToolMessages:r,isToolStreaming:o,contentParts:s,textContent:i,imageParts:a,fileParts:c,interruptPart:l,isStreamingMessage:u,streamingDebounceMs:f,enableStreamingMarkdownBuffer:h,renderStreamingMarkdown:p,handleFileClick:m,uploadingFiles:g,messageRole:b,truncateUserMessages:v,userMessagePreviewLength:y,isUserExpanded:T,setIsUserExpanded:I,isCompactLayout:k,iconForeground:S,toolConfig:E,handleInterruptApprove:j,handleInterruptReject:_,handleInterruptAlternative:D,disableInterruptActions:L,renderArtifactsInline:W=!0}){const V=x.useCallback(()=>d.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted/30 rounded",children:[d.jsx(pe.Loader,{className:"h-4 w-4 text-muted-foreground"}),d.jsx("span",{className:"text-sm text-muted-foreground",children:"File upload"})]}),[]),Z=nv(s,(h??!0)&&u,f??0),X=x.useMemo(()=>Z.filter(P=>P.type==="text"),[Z]),oe=x.useMemo(()=>X.map(P=>P.text??"").join(""),[X]),{artifacts:U}=Sd(e,t),F=x.useMemo(()=>{if(!p)return null;const P=ov(oe);return{stablePart:oe.slice(0,P),tailPart:oe.slice(P)}},[oe,p]),G=x.useMemo(()=>{if(!F)return null;const{stablePart:P,tailPart:K}=F;return!P&&!K?null:d.jsxs("div",{className:"space-y-2",children:[P?d.jsx(ro,{content:P,allowHtml:!1}):null,K?d.jsx(ro,{content:K,allowHtml:!1}):null]})},[F]),H=x.useMemo(()=>{if(!p)return Z;const P=[];let K=!1;for(const te of Z){if(te.type==="text"){K||(P.push({type:"text",text:"",__streamingMarkdownAggregate:!0}),K=!0);continue}P.push(te)}return P},[Z,p]),N=(p?H:Z).filter(P=>P.type!=="interrupt"&&P.type!=="image_url"),R=()=>!a||a.length===0?null:d.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:a.map((P,K)=>{const te=P;return d.jsx("div",{className:"relative group",children:d.jsx("img",{src:te.url,alt:te.alt??"Image",loading:"lazy",onClick:()=>window.open(te.url,"_blank"),className:"h-20 w-20 object-cover rounded-md border border-border/50 cursor-pointer hover:opacity-90 transition-opacity"})},K)})}),M=x.useCallback(({part:P,i:K})=>{if(P.type==="text"){if(p)return null;const te=P.text??"",le=te.trim(),he=dr(le);return he&&b!=="tool"?d.jsx(Rw,{data:he},K):b==="user"&&v&&le.length>y?d.jsx(tv,{text:le,expanded:T,onExpandedChange:I,previewLength:y,isCompact:k},K):d.jsx(ro,{content:te,allowHtml:!1},K)}if(P.type==="image_url")return null;if(P.type==="file"){const te=P,le=te.name||"file";return d.jsxs("a",{href:te.url,onClick:he=>m(he,te,K),className:`inline-flex items-center gap-2 rounded px-2 py-1 text-xs bg-gray-100 border hover:bg-gray-200
129
- dark:bg-background/10 dark:border-border/30 dark:hover:bg-background/20`,children:[g[K]?d.jsx(pe.Loader,{className:"h-4 w-4 animate-spin"}):null,d.jsxs("span",{className:"truncate max-w-[180px]",children:[le,g[K]?" (processing)":""]})]},K)}return null},[m,k,T,b,v,g,y,p,I]),q=i.trim().length>0||a.length>0||c.length>0||N.length>0||!!e.artifact;if(!n&&c.length>0&&!u&&!i&&a.length===0)return V();if(!n&&!q&&!u)return null;if(l){const P=l.value,K=!L,te=j??(()=>{}),le=_??(()=>{});return d.jsx(Ad,{interruptPart:l,payload:P,onApprove:te,onReject:le,onSelectAlternative:D,disabled:L,isActive:K})}const J=d.jsxs("div",{className:"space-y-2",children:[b==="assistant"&&r&&d.jsx(Mw,{message:e,allMessages:t,isStreaming:u,toolConfig:E}),N.map((P,K)=>p&&sv(P)?G?d.jsx("div",{className:"space-y-2",children:G},`streaming-md-${K}`):null:d.jsx(M,{part:P,i:K},K)),R(),W&&(U.length>0||!!e.artifact)&&d.jsxs("div",{className:"mt-4 pt-4 border-t border-border/40 space-y-4",children:[!!e.artifact&&d.jsx(Ka,{message:e,viewMode:"expanded",toolConfig:E}),U.map((P,K)=>d.jsx(Ka,{message:{...e,artifact:P},viewMode:"expanded",toolConfig:E},`timeline-art-${K}`))]})]});if(u){const P=i.trim().length>0||a.length>0;return d.jsxs("div",{"aria-busy":"true",role:"status",children:[J,P?d.jsx("span",{className:"inline-block w-2 h-4 ml-0.5 bg-current opacity-70 animate-pulse align-middle","aria-hidden":"true"}):d.jsx(Lw,{className:S})]})}return J}function rv(e){return e?!(oo(e,/```/g)||oo(e,/`/g)||oo(e,/\*\*/g)||oo(e,/__/g)||oo(e,/~~/g)||/[^\\]\[[^\]]*$/.test(e)||/\[[^\]]*\]\([^)]*$/.test(e)):!0}function oo(e,t){const n=e.match(t);return((n==null?void 0:n.length)??0)%2!==0}function ov(e){if(!e)return 0;for(let t=e.length;t>=0;t-=1)if(rv(e.slice(0,t)))return t;return 0}function sv(e){return e.type==="text"&&!!e.__streamingMarkdownAggregate}const iv=Ya.cva("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function av({className:e,variant:t,...n}){return d.jsx("div",{className:ae(iv({variant:t}),e),...n})}function lv({showTimestamp:e,showAgentName:t,isToolMessage:n,isInterruptMessage:r=!1,iconForeground:o,agentName:s,messageIcon:i,customHeaderClass:a,customActionsClass:c,isCompactLayout:l,showActions:u,isEditing:f,messageRole:h,onCopy:p,onEdit:m,onRegenerate:g,showCheckpointControls:b,attemptCount:v,attemptIndex:y,handleOlderAttemptSelect:T,handleNewerAttemptSelect:I,messageCreatedAt:k,copied:S}){return!e&&!t&&!n&&!r?null:d.jsxs("div",{className:ae("flex items-center justify-between mb-2 pb-2",h!=="assistant"&&"border-b border-current/10",l&&"mb-1 pb-1",o,a),children:[d.jsxs("div",{className:"flex items-center gap-2",children:[i,t&&s&&d.jsx("span",{className:ae("font-medium",l?"text-xs":"text-sm"),children:s}),n&&!r&&d.jsx(av,{variant:"outline",className:ae("text-xs flex items-center gap-1",o,"border border-current/40",l&&"text-xs h-4"),children:d.jsx("span",{children:"Tool Output"})}),r&&d.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Interrupt"})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[b&&v>1&&d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("button",{type:"button",className:ae("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",y<v-1?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{y>=v-1||T()},"aria-label":"Older attempt (back in time)",disabled:y>=v-1,children:d.jsx(pe.ChevronLeft,{className:"h-3 w-3"})}),d.jsx("div",{className:"flex items-center gap-2",children:d.jsxs("span",{className:"whitespace-nowrap",children:[v-y," / ",v]})}),d.jsx("button",{type:"button",className:ae("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",y>0?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{y<=0||I()},"aria-label":"Newer attempt (forward in time)",disabled:y<=0,children:d.jsx(pe.ChevronRight,{className:"h-3 w-3"})})]}),e&&k&&d.jsx("time",{className:ae("text-xs opacity-60",o,l&&"text-xs"),dateTime:new Date(k.endsWith("Z")||k.includes("+")?k:`${k}Z`).toISOString(),title:new Date(k.endsWith("Z")||k.includes("+")?k:`${k}Z`).toLocaleString(),children:new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(new Date(k.endsWith("Z")||k.includes("+")?k:`${k}Z`))}),u&&!f&&d.jsxs("div",{className:ae("opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",c),children:[d.jsx("div",{className:"relative",children:d.jsx(Ke,{variant:"ghost",size:"sm",onClick:p,className:ae("h-6 w-6 p-0 hover:bg-foreground/10",o,l&&"h-5 w-5"),"aria-label":"Copy message",title:"Copy message",children:d.jsx(pe.Copy,{className:ae(S?"text-success":o,l?"h-3 w-3":"h-4 w-4")})})}),h==="user"&&m&&d.jsx(Ke,{variant:"ghost",size:"sm",onClick:m,className:ae("h-6 w-6 p-0 hover:bg-foreground/10",o,l&&"h-5 w-5"),"aria-label":"Edit message",children:d.jsx(pe.Edit,{className:ae(o,l?"h-3 w-3":"h-4 w-4")})}),h==="assistant"&&g&&d.jsx(Ke,{variant:"ghost",size:"sm",onClick:g,className:ae("h-6 w-6 p-0 hover:bg-foreground/10",o,l&&"h-5 w-5"),"aria-label":"Regenerate response",children:d.jsx(pe.RotateCcw,{className:ae(o,l?"h-3 w-3":"h-4 w-4")})})]})]})]})}const cv=1,uv=1e6;let Qi=0;function dv(){return Qi=(Qi+1)%Number.MAX_SAFE_INTEGER,Qi.toString()}const ea=new Map,Ud=e=>{if(ea.has(e))return;const t=setTimeout(()=>{ea.delete(e),so({type:"REMOVE_TOAST",toastId:e})},uv);ea.set(e,t)},fv=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,cv)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?Ud(n):e.toasts.forEach(r=>{Ud(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},ls=[];let cs={toasts:[]};function so(e){cs=fv(cs,e),ls.forEach(t=>{t(cs)})}function hv({...e}){const t=dv(),n=o=>so({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>so({type:"DISMISS_TOAST",toastId:t});return so({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function pv(){const[e,t]=w.useState(cs);return w.useEffect(()=>(ls.push(t),()=>{const n=ls.indexOf(t);n>-1&&ls.splice(n,1)}),[e]),{...e,toast:hv,dismiss:n=>so({type:"DISMISS_TOAST",toastId:n})}}function mv(e){const{allowFileOpen:t,currentThreadId:n}=e,{fileApi:r}=Vn(),{toast:o}=pv(),[s,i]=x.useState({}),[a,c]=x.useState(null),[l,u]=x.useState(!1),f=x.useCallback(()=>{u(!1),c(null)},[]),h=x.useCallback(m=>{c(m),u(!0)},[]),p=x.useCallback(async(m,g,b)=>{var v,y;if(!t){m.preventDefault();return}if(s[b]){m.preventDefault();return}try{const T=String(g.url??""),I=T.match(/\/chat\/files\/([^/]+)(?:\/(view|download))?/);if(I){m.preventDefault();const k=I[1],S=g.name||`file_${k}`,E=g.mimeType||"application/octet-stream";h({id:k,name:S,mimeType:E});return}if(T.startsWith("data:")){m.preventDefault(),i(S=>({...S,[b]:!0}));const k=o({title:"Fetching file...",description:"",open:!0});try{const S=await r.listFiles(n??void 0);if(!S||!Array.isArray(S))throw new Error("Invalid file list response");const E=S.find(j=>!j||typeof j!="object"||!((j.filename??"")===(g.name??""))?!1:typeof g.size=="number"&&typeof j.size=="number"?j.size===g.size:!0);if(!(E!=null&&E.id))throw new Error(`File "${g.name}" is not yet available on the server`);if(!E.id||!E.filename)throw new Error("Invalid file data received from server");h({id:E.id,name:g.name||E.filename||`file_${E.id}`,mimeType:g.mimeType||E.mime_type||"application/octet-stream"}),(v=k.update)==null||v.call(k,{id:k.id,title:"Success",description:`Opened ${g.name}`,open:!0})}catch(S){console.error("Failed to fetch server file:",S);const E=S instanceof Error?S.message:"Unknown error occurred";(y=k.update)==null||y.call(k,{id:k.id,title:"Failed",description:E}),o({title:"Failed to fetch file",description:E,open:!0})}finally{i(S=>({...S,[b]:!1}))}}}catch(T){console.error("File click error:",T),i(I=>({...I,[b]:!1}))}},[t,s,o,n,h]);return{uploadingFiles:s,handleFileClick:p,fileViewerOpen:l,currentFileInfo:a,closeFileViewer:f}}function gv(e){return x.useMemo(()=>{const t=e;let n=Array.isArray(t.content)?t.content:[];typeof t.content=="string"&&(n=[{type:"text",text:t.content}]);const r=t.additionalKwargs??{};return{contentParts:n,textContent:rc(n),toolMeta:jo(t),imageParts:n.filter(o=>o.type==="image_url"),fileParts:n.filter(o=>o.type==="file"),interruptParts:n.filter(o=>o.type==="interrupt"),toolRaw:ng(n),isToolStreaming:!!r.toolStreaming}},[e])}const Wd="data:";function xv(e){if(!e)return[];const t=[],n=e.split(/\r?\n/);for(const r of n){const o=r.trim();if(!o||!o.startsWith(Wd))continue;const s=o.slice(Wd.length).trim();if(!s||s.toLowerCase()==="[done]")continue;const i=dr(s);i&&typeof i=="object"&&t.push(i)}return t}function bv(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n&&typeof n=="object"&&n.type==="tool.end")return n}return null}function wv(e){return x.useMemo(()=>{const t=e.content.filter(l=>l.type==="text");if(!t.length)return null;let r=t.flatMap(l=>xv(l.text??""));if(!r.length){const l=t.map(f=>f.text??"").join(`
130
- `),u=dr(l);u&&typeof u=="object"&&(r=[u])}if(!r.length)return null;const s=bv(r)??r[r.length-1];if(!s)return null;const i=s.output??s.payload??s,a=hr(i),c=Br(a);return c&&typeof c=="object"&&!Array.isArray(c)?{kind:"dict",value:c,data:c,event:s}:{kind:"generic",value:c,event:s}},[e])}const ta=x.memo(function({message:t,messageIndex:n,allMessages:r,isStreamingMessage:o=!1,isEditing:s=!1,showActions:i=!0,showTimestamp:a=!0,showAgentName:c=!0,layoutSize:l="desktop",truncateUserMessages:u=!0,userMessagePreviewLength:f=500,showToolMessages:h=!0,toolConfig:p,customStyles:m={},streamingDebounceMs:g=300,renderStreamingMarkdown:b=!0,enableStreamingMarkdownBuffer:v,onEdit:y,onRegenerate:T,onCopy:I,getInterruptOptions:k,attemptCount:S=1,attemptIndex:E=0,onSelectCheckpoint:j,attemptMetas:_=[],renderArtifactsInline:D=!0}){const[L,W]=x.useState(!1),[V,$]=x.useState(!1),{currentThreadId:Z}=ur(),{respondToInterrupt:X}=Ur(),[oe,U]=x.useState(!1),F=l==="phone"||l==="half-screen",G=t.role,H=G==="interrupt",A=G==="tool"||H,{toolRenderers:N,toolArtifactRenderers:R,getToolExpandable:M}=p??{},q=!(o&&G!=="user"),{uploadingFiles:J,handleFileClick:P,fileViewerOpen:K,currentFileInfo:te,closeFileViewer:le}=mv({allowFileOpen:q,currentThreadId:Z}),he=x.useMemo(()=>{switch(G){case"user":return"text-[hsl(var(--chat-bubble-user-text))]";case"assistant":return"text-[hsl(var(--chat-bubble-ai-text))]";case"interrupt":return"text-[hsl(var(--chat-bubble-ai-text))]";case"tool":return"text-secondary-foreground";case"system":return"text-muted-foreground";default:return"text-[hsl(var(--chat-bubble-ai-text))]"}},[G]),ue=gv(t),{contentParts:ge,imageParts:be,fileParts:Be,textContent:Le,toolRaw:je,isToolStreaming:Fe,interruptParts:tt}=ue,mt=v??g!==0,ot=x.useMemo(()=>tt.length?tt[0]:null,[tt]),ze=x.useCallback(async()=>{const Ee=A?je:Le;async function Ve(dt){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(dt);return}if(navigator.clipboard&&typeof navigator.clipboard.write=="function"&&typeof ClipboardItem<"u"){const Et=new Blob([dt],{type:"text/plain"});await navigator.clipboard.write([new ClipboardItem({"text/plain":Et})]);return}throw new Error("Clipboard API not supported in this context.")}try{await Ve(Ee),W(!0),setTimeout(()=>W(!1),2e3),I==null||I(Ee)}catch(dt){console.error("Failed to copy:",dt)}},[A,je,Le,I]),Me=x.useCallback(async(Ee,Ve)=>{if(!ot)return;if(!oc(ot.id)){console.warn("Interrupt part missing id",ot);return}U(!0);try{const Et=k==null?void 0:k(t);await X(Ee,Ve,Et)}catch(Et){console.error("Failed to respond to interrupt:",Et)}finally{U(!1)}},[ot,X]),Ze=x.useCallback(()=>Me(!0),[Me]),rt=x.useCallback(()=>Me(!1),[Me]),qe=x.useCallback((Ee,Ve)=>{if(!Ve)return;const dt={alternativeId:Ve.id??Ve.label??void 0,alternativeLabel:Ve.label};Me(!0,dt)},[Me]),ht=x.useCallback(()=>{if(!y||!t.id)return;const Ee=(A?je:Le)??"",Ve="type"in t&&t.type==="default_message"?void 0:{checkpointId:t.checkpointId??null,checkpointNs:t.checkpointNs??null};y(t.id,Ee,Ve)},[y,A,je,Le,t]),xt=x.useCallback(()=>{T==null||T(n)},[T,n]),He=x.useCallback(()=>{const Ve=ae(F?"h-3 w-3":"h-4 w-4","opacity-60 flex-shrink-0",he);switch(G){case"user":return d.jsx(pe.User,{className:Ve});case"assistant":return d.jsx(pe.Bot,{className:Ve});case"tool":return d.jsx(pe.Wrench,{className:Ve});case"interrupt":return d.jsx(pe.Bot,{className:Ve});default:return d.jsx(pe.Bot,{className:Ve})}},[F,he,G]),st=x.useCallback(()=>{const Ee="group relative mb-4 flex w-full";switch(G){case"user":return ae(Ee,"justify-end");case"assistant":case"tool":case"system":case"interrupt":return ae(Ee,"justify-start");default:return Ee}},[G]),an=x.useCallback(()=>{const Ee=ae("rounded-lg px-4 py-3 relative min-w-0 max-w-full break-words",F&&"px-3 py-2 text-sm");switch(G){case"user":return ae(Ee,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-user))] text-[hsl(var(--chat-bubble-user-text))]","border border-transparent");case"assistant":return ae(Ee,"w-full md:max-w-[95%]","bg-transparent text-[hsl(var(--chat-bubble-ai-text))]","border-none");case"tool":case"interrupt":return ae(Ee,"w-full md:max-w-[95%] bg-secondary/50 text-secondary-foreground border border-dashed");case"system":return ae(Ee,"w-full md:max-w-[85%] bg-accent/40 text-muted-foreground border");default:return ae(Ee,"w-full md:max-w-[95%]","bg-transparent text-[hsl(var(--chat-bubble-ai-text))]","border-none")}},[F,G]),jt=h||H,ct=d.jsx(Hd,{message:t,allMessages:r,isToolMessage:A,showToolMessages:jt,toolConfig:{toolRenderers:N,toolArtifactRenderers:R,getToolExpandable:M},isToolStreaming:Fe,contentParts:ge,textContent:Le,imageParts:be,fileParts:Be,isStreamingMessage:o,enableStreamingMarkdownBuffer:mt,renderStreamingMarkdown:b,streamingDebounceMs:g,handleFileClick:P,uploadingFiles:J,messageRole:G,truncateUserMessages:u,userMessagePreviewLength:f,isUserExpanded:V,setIsUserExpanded:$,isCompactLayout:F,iconForeground:he,interruptPart:ot,handleInterruptApprove:Ze,handleInterruptReject:rt,handleInterruptAlternative:qe,disableInterruptActions:oe,renderArtifactsInline:D}),kt=x.useMemo(()=>rg(t),[t]),Tt=He(),bt=G==="user"&&(S??1)>1&&typeof j=="function",Ge=(_==null?void 0:_.length)??0,gt=Ge>0&&E<Ge-1?_[E+1]:void 0,ut=Ge>0&&E>0?_[E-1]:void 0,$t=x.useCallback(()=>{!gt||!j||j(gt.id,void 0,!!gt.isLatestAttempt)},[gt,j]),$e=x.useCallback(()=>{!ut||!j||j(ut.id,void 0,!!ut.isLatestAttempt)},[ut,j]);return A&&!h?null:d.jsxs(d.Fragment,{children:[d.jsx("div",{className:ae(st(),m.container),children:d.jsxs("div",{className:ae(an(),m.content),children:[d.jsx(lv,{showTimestamp:a,showAgentName:c,isToolMessage:A,iconForeground:he,agentName:kt,messageIcon:Tt,customHeaderClass:m.header,customActionsClass:m.actions,isCompactLayout:F,showActions:i,isEditing:s,messageRole:G,isInterruptMessage:H,onCopy:ze,onEdit:ht,onRegenerate:xt,showCheckpointControls:bt,attemptCount:S,attemptIndex:E,handleOlderAttemptSelect:$t,handleNewerAttemptSelect:$e,messageCreatedAt:t.createdAt,copied:L}),d.jsx("div",{className:"relative",children:ct}),!(a||c||A)&&i&&!s&&d.jsxs("div",{className:ae("absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",m.actions),children:[d.jsx(Ke,{variant:"ghost",size:"sm",onClick:()=>ze(),className:ae("h-6 w-6 p-0 hover:bg-background/50 text-current",F&&"h-5 w-5"),children:d.jsx(pe.Copy,{className:ae(L?"text-success":"text-current",F?"h-3 w-3":"h-4 w-4")})}),G==="user"&&y&&d.jsx(Ke,{variant:"ghost",size:"sm",onClick:ht,className:ae("h-6 w-6 p-0 hover:bg-background/50 text-current",F&&"h-5 w-5"),children:d.jsx(pe.Edit,{className:ae("text-current",F?"h-3 w-3":"h-4 w-4")})}),G==="assistant"&&T&&d.jsx(Ke,{variant:"ghost",size:"sm",onClick:xt,className:ae("h-6 w-6 p-0 hover:bg-background/50 text-current",F&&"h-5 w-5"),children:d.jsx(pe.RotateCcw,{className:ae("text-current",F?"h-3 w-3":"h-4 w-4")})})]})]})}),te&&d.jsx(jw,{isOpen:K,onClose:le,fileId:te.id,fileName:te.name,mimeType:te.mimeType})]})},(e,t)=>{var c,l,u,f,h,p,m,g;if(t.isStreamingMessage||e.isStreamingMessage||!(e.message.id===t.message.id&&sc(e.message)===sc(t.message)))return!1;const o=["isEditing","showActions","layoutSize","showTimestamp","showAgentName","truncateUserMessages","userMessagePreviewLength","showToolMessages","toolConfig"].every(b=>e[b]===t[b]),s=((c=e.customStyles)==null?void 0:c.container)===((l=t.customStyles)==null?void 0:l.container)&&((u=e.customStyles)==null?void 0:u.content)===((f=t.customStyles)==null?void 0:f.content)&&((h=e.customStyles)==null?void 0:h.actions)===((p=t.customStyles)==null?void 0:p.actions)&&((m=e.customStyles)==null?void 0:m.header)===((g=t.customStyles)==null?void 0:g.header);if(!o||!s)return!1;const i=ni(e.message),a=ni(t.message);return i.length===a.length});ta.displayName="MessageComponent";const vv={checkpoints:[],checkpointMetaByCheckpointId:new Map,timeline:[],messagePreviews:new Map,getLatest:()=>{},getCheckpoint:()=>{},getMessageAttempts:()=>[]},na=(e,t)=>(e==null?void 0:e.id)??`message-${t}`,ra=x.memo(function({message:t,index:n,allMessages:r,streamingAssistantId:o,streamingDebounceMs:s=0,layoutSize:i,enableMessageEditing:a,editingMessageId:c,onEdit:l,onRegenerate:u,onCancelEdit:f,showToolMessages:h,checkpointIndex:p,onSelectCheckpoint:m,getMessageCustomStyles:g,getInterruptOptions:b,toolConfig:v,renderArtifactsInline:y=!0}){const T=na(t,n),S=!!t.__syntheticStreaming||o===t.id&&t.role==="assistant",E=p??vv,j=t.checkpointId??null,{attemptCount:_,attemptIndex:D,attempts:L}=x.useMemo(()=>Cg(t.id,j,E),[t.id,j,E]),W=g==null?void 0:g(t);return d.jsx("div",{className:"relative mb-4 last:mb-0 w-full max-w-full min-w-0","data-message-id":T,style:{minHeight:"60px",containIntrinsicSize:"auto 120px"},children:d.jsx(ta,{message:t,messageIndex:n,allMessages:r,isStreamingMessage:S,renderStreamingMarkdown:S,streamingDebounceMs:s,isEditing:c===t.id,showActions:a,showTimestamp:!1,showAgentName:!0,layoutSize:i,onEdit:l,onRegenerate:()=>u(n),onCancelEdit:f,getInterruptOptions:b,showToolMessages:h,attemptCount:_,attemptIndex:D,attemptMetas:L,onSelectCheckpoint:m,customStyles:W,toolConfig:v,renderArtifactsInline:y})})});ra.displayName="MessageRow";const yv=Object.freeze({}),us=x.forwardRef(({messages:e=[],isStreaming:t,streamingAssistantId:n,streamingDebounceMs:r=0,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onStartReached:a,onEdit:c,onRegenerate:l,onCancelEdit:u,className:f,style:h,emptyMessage:p,followNewMessages:m=!0,isNavigatingCheckpoint:g=!1,onScrollAway:b,onAtBottom:v,showToolMessages:y=!0,toolConfig:T,checkpointIndex:I,activeCheckpointId:k,onSelectCheckpoint:S,showThinkingIndicator:E=!0,getMessageCustomStyles:j,getInterruptOptions:_,pendingInterrupt:D,renderArtifactsInline:L=!0},W)=>{const V=x.useRef(null),$=x.useRef(null),Z=x.useRef(!1),X=x.useRef(!1),[oe,U]=x.useState(!1),F=x.useRef(null);x.useEffect(()=>{if(!D){F.current=null;return}F.current!==D.id&&(U(!1),F.current=D.id)},[D]),x.useEffect(()=>{t&&U(!0)},[t]);const G=x.useMemo(()=>{if(!D)return null;const ue=D.value,ge={interruptId:D.id,type:"user_choice",question:ue==null?void 0:ue.question,alternatives:ue==null?void 0:ue.alternatives};return{id:`interrupt-${D.id}`,role:"interrupt",content:[{type:"interrupt",id:D.id,value:ge}],createdAt:new Date().toISOString(),checkpointId:k??null,checkpointNs:null,expandable:!0}},[D,k]),H=x.useMemo(()=>!G||oe||e.some(ue=>ue.id===G.id)?e:[...e,G],[e,G,oe]),A=x.useMemo(()=>!t||!E||n&&H.some(ge=>ge.id===n)?H:[...H,{id:"thinking-assistant",role:"assistant",content:[{type:"text",text:""}],createdAt:new Date().toISOString(),__syntheticStreaming:!0}],[H,n,E,t]),N=x.useMemo(()=>A.filter(ue=>!og(ue)),[A]),R=x.useMemo(()=>T??yv,[T]),M=x.useCallback(ue=>{b&&b(!ue),v&&v(ue)},[b,v]),q=x.useMemo(()=>{if(a)return async()=>{if(!Z.current){Z.current=!0;try{await a()}finally{Z.current=!1}}}},[a]),J=x.useMemo(()=>!m||g?!1:"auto",[m,g]),P=N.length===0&&p,K=["flex h-full flex-col md:flex-row",f].filter(Boolean).join(" "),te=()=>P?d.jsx("div",{className:"h-full w-full",children:p}):d.jsx("div",{className:"flex h-full items-center justify-center py-8 text-center text-muted-foreground",children:"No messages yet. Start a conversation!"}),le=N.length,he=le>0;return x.useEffect(()=>{var ue,ge;if(le===0){X.current=!1;return}if(!X.current)if(X.current=!0,V.current&&N.length>0){const be=N.length-1;(ge=(ue=V.current).scrollToIndex)==null||ge.call(ue,{index:be,align:"end",behavior:"auto"})}else $.current&&($.current.scrollTop=$.current.scrollHeight)},[le,N.length]),x.useImperativeHandle(W,()=>({scrollToLatest:()=>{var ue,ge;if(V.current&&N.length>0){const be=N.length-1;(ge=(ue=V.current).scrollToIndex)==null||ge.call(ue,{index:be,align:"end",behavior:"auto"})}else $.current&&($.current.scrollTop=$.current.scrollHeight)},scrollToTop:()=>{var ue,ge;V.current&&N.length>0?(ge=(ue=V.current).scrollToIndex)==null||ge.call(ue,{index:0,align:"start",behavior:"auto"}):$.current&&($.current.scrollTop=0)}}),[N]),d.jsx("div",{className:K,style:h,children:d.jsx("div",{className:"relative flex-1 min-h-0 min-w-0",children:he?d.jsx(Wx,{ref:ue=>{V.current=ue},scrollerRef:ue=>{$.current=ue instanceof HTMLDivElement?ue:null},data:N,followOutput:J,overscan:200,increaseViewportBy:{top:100,bottom:200},defaultItemHeight:80,atBottomThreshold:50,startReached:()=>{q&&q()},atBottomStateChange:M,style:{height:"100%",overscrollBehavior:"contain"},computeItemKey:(ue,ge)=>na(ge,ue),itemContent:(ue,ge)=>d.jsx(ra,{message:ge,index:ue,allMessages:e,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onEdit:c,onRegenerate:l,onCancelEdit:u,showToolMessages:y,toolConfig:R,checkpointIndex:I,activeCheckpointId:k,onSelectCheckpoint:S,getMessageCustomStyles:j,getInterruptOptions:_,renderArtifactsInline:L})}):te()})})});us.displayName="MessageList";function Vd(e){const t=e+"CollectionProvider",[n,r]=Rn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=g=>{const{scope:b,children:v}=g,y=x.useRef(null),T=x.useRef(new Map).current;return d.jsx(o,{scope:b,itemMap:T,collectionRef:y,children:v})};i.displayName=t;const a=e+"CollectionSlot",c=sr.createSlot(a),l=x.forwardRef((g,b)=>{const{scope:v,children:y}=g,T=s(a,v),I=et(b,T.collectionRef);return d.jsx(c,{ref:I,children:y})});l.displayName=a;const u=e+"CollectionItemSlot",f="data-radix-collection-item",h=sr.createSlot(u),p=x.forwardRef((g,b)=>{const{scope:v,children:y,...T}=g,I=x.useRef(null),k=et(b,I),S=s(u,v);return x.useEffect(()=>(S.itemMap.set(I,{ref:I,...T}),()=>void S.itemMap.delete(I))),d.jsx(h,{[f]:"",ref:k,children:y})});p.displayName=u;function m(g){const b=s(e+"CollectionConsumer",g);return x.useCallback(()=>{const y=b.collectionRef.current;if(!y)return[];const T=Array.from(y.querySelectorAll(`[${f}]`));return Array.from(b.itemMap.values()).sort((S,E)=>T.indexOf(S.ref.current)-T.indexOf(E.ref.current))},[b.collectionRef,b.itemMap])}return[{Provider:i,Slot:l,ItemSlot:p},m,r]}var Sv=w.createContext(void 0);function oa(e){const t=w.useContext(Sv);return e||t||"ltr"}const Cv=["top","right","bottom","left"],$n=Math.min,Kt=Math.max,ds=Math.round,fs=Math.floor,mn=e=>({x:e,y:e}),kv={left:"right",right:"left",bottom:"top",top:"bottom"},Tv={start:"end",end:"start"};function sa(e,t,n){return Kt(e,$n(t,n))}function Sn(e,t){return typeof e=="function"?e(t):e}function Cn(e){return e.split("-")[0]}function Sr(e){return e.split("-")[1]}function ia(e){return e==="x"?"y":"x"}function aa(e){return e==="y"?"height":"width"}const Ev=new Set(["top","bottom"]);function gn(e){return Ev.has(Cn(e))?"y":"x"}function la(e){return ia(gn(e))}function Iv(e,t,n){n===void 0&&(n=!1);const r=Sr(e),o=la(e),s=aa(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=hs(i)),[i,hs(i)]}function Av(e){const t=hs(e);return[ca(e),t,ca(t)]}function ca(e){return e.replace(/start|end/g,t=>Tv[t])}const Kd=["left","right"],qd=["right","left"],Nv=["top","bottom"],_v=["bottom","top"];function jv(e,t,n){switch(e){case"top":case"bottom":return n?t?qd:Kd:t?Kd:qd;case"left":case"right":return t?Nv:_v;default:return[]}}function Pv(e,t,n,r){const o=Sr(e);let s=jv(Cn(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(ca)))),s}function hs(e){return e.replace(/left|right|bottom|top/g,t=>kv[t])}function Ov(e){return{top:0,right:0,bottom:0,left:0,...e}}function Gd(e){return typeof e!="number"?Ov(e):{top:e,right:e,bottom:e,left:e}}function ps(e){const{x:t,y:n,width:r,height:o}=e;return{width:r,height:o,top:n,left:t,right:t+r,bottom:n+o,x:t,y:n}}function Yd(e,t,n){let{reference:r,floating:o}=e;const s=gn(t),i=la(t),a=aa(i),c=Cn(t),l=s==="y",u=r.x+r.width/2-o.width/2,f=r.y+r.height/2-o.height/2,h=r[a]/2-o[a]/2;let p;switch(c){case"top":p={x:u,y:r.y-o.height};break;case"bottom":p={x:u,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:f};break;case"left":p={x:r.x-o.width,y:f};break;default:p={x:r.x,y:r.y}}switch(Sr(t)){case"start":p[i]-=h*(n&&l?-1:1);break;case"end":p[i]+=h*(n&&l?-1:1);break}return p}const Rv=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,a=s.filter(Boolean),c=await(i.isRTL==null?void 0:i.isRTL(t));let l=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:u,y:f}=Yd(l,r,c),h=r,p={},m=0;for(let g=0;g<a.length;g++){const{name:b,fn:v}=a[g],{x:y,y:T,data:I,reset:k}=await v({x:u,y:f,initialPlacement:r,placement:h,strategy:o,middlewareData:p,rects:l,platform:i,elements:{reference:e,floating:t}});u=y??u,f=T??f,p={...p,[b]:{...p[b],...I}},k&&m<=50&&(m++,typeof k=="object"&&(k.placement&&(h=k.placement),k.rects&&(l=k.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):k.rects),{x:u,y:f}=Yd(l,h,c)),g=-1)}return{x:u,y:f,placement:h,strategy:o,middlewareData:p}};async function io(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:c}=e,{boundary:l="clippingAncestors",rootBoundary:u="viewport",elementContext:f="floating",altBoundary:h=!1,padding:p=0}=Sn(t,e),m=Gd(p),b=a[h?f==="floating"?"reference":"floating":f],v=ps(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(b)))==null||n?b:b.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:l,rootBoundary:u,strategy:c})),y=f==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.reference,T=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),I=await(s.isElement==null?void 0:s.isElement(T))?await(s.getScale==null?void 0:s.getScale(T))||{x:1,y:1}:{x:1,y:1},k=ps(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:y,offsetParent:T,strategy:c}):y);return{top:(v.top-k.top+m.top)/I.y,bottom:(k.bottom-v.bottom+m.bottom)/I.y,left:(v.left-k.left+m.left)/I.x,right:(k.right-v.right+m.right)/I.x}}const Mv=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:s,platform:i,elements:a,middlewareData:c}=t,{element:l,padding:u=0}=Sn(e,t)||{};if(l==null)return{};const f=Gd(u),h={x:n,y:r},p=la(o),m=aa(p),g=await i.getDimensions(l),b=p==="y",v=b?"top":"left",y=b?"bottom":"right",T=b?"clientHeight":"clientWidth",I=s.reference[m]+s.reference[p]-h[p]-s.floating[m],k=h[p]-s.reference[p],S=await(i.getOffsetParent==null?void 0:i.getOffsetParent(l));let E=S?S[T]:0;(!E||!await(i.isElement==null?void 0:i.isElement(S)))&&(E=a.floating[T]||s.floating[m]);const j=I/2-k/2,_=E/2-g[m]/2-1,D=$n(f[v],_),L=$n(f[y],_),W=D,V=E-g[m]-L,$=E/2-g[m]/2+j,Z=sa(W,$,V),X=!c.arrow&&Sr(o)!=null&&$!==Z&&s.reference[m]/2-($<W?D:L)-g[m]/2<0,oe=X?$<W?$-W:$-V:0;return{[p]:h[p]+oe,data:{[p]:Z,centerOffset:$-Z-oe,...X&&{alignmentOffset:oe}},reset:X}}}),Dv=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:s,rects:i,initialPlacement:a,platform:c,elements:l}=t,{mainAxis:u=!0,crossAxis:f=!0,fallbackPlacements:h,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:m="none",flipAlignment:g=!0,...b}=Sn(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const v=Cn(o),y=gn(a),T=Cn(a)===a,I=await(c.isRTL==null?void 0:c.isRTL(l.floating)),k=h||(T||!g?[hs(a)]:Av(a)),S=m!=="none";!h&&S&&k.push(...Pv(a,g,m,I));const E=[a,...k],j=await io(t,b),_=[];let D=((r=s.flip)==null?void 0:r.overflows)||[];if(u&&_.push(j[v]),f){const $=Iv(o,i,I);_.push(j[$[0]],j[$[1]])}if(D=[...D,{placement:o,overflows:_}],!_.every($=>$<=0)){var L,W;const $=(((L=s.flip)==null?void 0:L.index)||0)+1,Z=E[$];if(Z&&(!(f==="alignment"?y!==gn(Z):!1)||D.every(U=>gn(U.placement)===y?U.overflows[0]>0:!0)))return{data:{index:$,overflows:D},reset:{placement:Z}};let X=(W=D.filter(oe=>oe.overflows[0]<=0).sort((oe,U)=>oe.overflows[1]-U.overflows[1])[0])==null?void 0:W.placement;if(!X)switch(p){case"bestFit":{var V;const oe=(V=D.filter(U=>{if(S){const F=gn(U.placement);return F===y||F==="y"}return!0}).map(U=>[U.placement,U.overflows.filter(F=>F>0).reduce((F,G)=>F+G,0)]).sort((U,F)=>U[1]-F[1])[0])==null?void 0:V[0];oe&&(X=oe);break}case"initialPlacement":X=a;break}if(o!==X)return{reset:{placement:X}}}return{}}}};function Xd(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Jd(e){return Cv.some(t=>e[t]>=0)}const Lv=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=Sn(e,t);switch(r){case"referenceHidden":{const s=await io(t,{...o,elementContext:"reference"}),i=Xd(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Jd(i)}}}case"escaped":{const s=await io(t,{...o,altBoundary:!0}),i=Xd(s,n.floating);return{data:{escapedOffsets:i,escaped:Jd(i)}}}default:return{}}}}},Zd=new Set(["left","top"]);async function $v(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=Cn(n),a=Sr(n),c=gn(n)==="y",l=Zd.has(i)?-1:1,u=s&&c?-1:1,f=Sn(t,e);let{mainAxis:h,crossAxis:p,alignmentAxis:m}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof m=="number"&&(p=a==="end"?m*-1:m),c?{x:p*u,y:h*l}:{x:h*l,y:p*u}}const Fv=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:s,placement:i,middlewareData:a}=t,c=await $v(t,e);return i===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+c.x,y:s+c.y,data:{...c,placement:i}}}}},zv=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:s=!0,crossAxis:i=!1,limiter:a={fn:b=>{let{x:v,y}=b;return{x:v,y}}},...c}=Sn(e,t),l={x:n,y:r},u=await io(t,c),f=gn(Cn(o)),h=ia(f);let p=l[h],m=l[f];if(s){const b=h==="y"?"top":"left",v=h==="y"?"bottom":"right",y=p+u[b],T=p-u[v];p=sa(y,p,T)}if(i){const b=f==="y"?"top":"left",v=f==="y"?"bottom":"right",y=m+u[b],T=m-u[v];m=sa(y,m,T)}const g=a.fn({...t,[h]:p,[f]:m});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[h]:s,[f]:i}}}}}},Bv=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:s,middlewareData:i}=t,{offset:a=0,mainAxis:c=!0,crossAxis:l=!0}=Sn(e,t),u={x:n,y:r},f=gn(o),h=ia(f);let p=u[h],m=u[f];const g=Sn(a,t),b=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(c){const T=h==="y"?"height":"width",I=s.reference[h]-s.floating[T]+b.mainAxis,k=s.reference[h]+s.reference[T]-b.mainAxis;p<I?p=I:p>k&&(p=k)}if(l){var v,y;const T=h==="y"?"width":"height",I=Zd.has(Cn(o)),k=s.reference[f]-s.floating[T]+(I&&((v=i.offset)==null?void 0:v[f])||0)+(I?0:b.crossAxis),S=s.reference[f]+s.reference[T]+(I?0:((y=i.offset)==null?void 0:y[f])||0)-(I?b.crossAxis:0);m<k?m=k:m>S&&(m=S)}return{[h]:p,[f]:m}}}},Hv=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:s,platform:i,elements:a}=t,{apply:c=()=>{},...l}=Sn(e,t),u=await io(t,l),f=Cn(o),h=Sr(o),p=gn(o)==="y",{width:m,height:g}=s.floating;let b,v;f==="top"||f==="bottom"?(b=f,v=h===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(v=f,b=h==="end"?"top":"bottom");const y=g-u.top-u.bottom,T=m-u.left-u.right,I=$n(g-u[b],y),k=$n(m-u[v],T),S=!t.middlewareData.shift;let E=I,j=k;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(j=T),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(E=y),S&&!h){const D=Kt(u.left,0),L=Kt(u.right,0),W=Kt(u.top,0),V=Kt(u.bottom,0);p?j=m-2*(D!==0||L!==0?D+L:Kt(u.left,u.right)):E=g-2*(W!==0||V!==0?W+V:Kt(u.top,u.bottom))}await c({...t,availableWidth:j,availableHeight:E});const _=await i.getDimensions(a.floating);return m!==_.width||g!==_.height?{reset:{rects:!0}}:{}}}};function ms(){return typeof window<"u"}function Cr(e){return Qd(e)?(e.nodeName||"").toLowerCase():"#document"}function qt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function xn(e){var t;return(t=(Qd(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Qd(e){return ms()?e instanceof Node||e instanceof qt(e).Node:!1}function on(e){return ms()?e instanceof Element||e instanceof qt(e).Element:!1}function bn(e){return ms()?e instanceof HTMLElement||e instanceof qt(e).HTMLElement:!1}function ef(e){return!ms()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof qt(e).ShadowRoot}const Uv=new Set(["inline","contents"]);function ao(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=sn(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!Uv.has(o)}const Wv=new Set(["table","td","th"]);function Vv(e){return Wv.has(Cr(e))}const Kv=[":popover-open",":modal"];function gs(e){return Kv.some(t=>{try{return e.matches(t)}catch{return!1}})}const qv=["transform","translate","scale","rotate","perspective"],Gv=["transform","translate","scale","rotate","perspective","filter"],Yv=["paint","layout","strict","content"];function ua(e){const t=da(),n=on(e)?sn(e):e;return qv.some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||Gv.some(r=>(n.willChange||"").includes(r))||Yv.some(r=>(n.contain||"").includes(r))}function Xv(e){let t=Fn(e);for(;bn(t)&&!kr(t);){if(ua(t))return t;if(gs(t))return null;t=Fn(t)}return null}function da(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const Jv=new Set(["html","body","#document"]);function kr(e){return Jv.has(Cr(e))}function sn(e){return qt(e).getComputedStyle(e)}function xs(e){return on(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Fn(e){if(Cr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||ef(e)&&e.host||xn(e);return ef(t)?t.host:t}function tf(e){const t=Fn(e);return kr(t)?e.ownerDocument?e.ownerDocument.body:e.body:bn(t)&&ao(t)?t:tf(t)}function lo(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=tf(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=qt(o);if(s){const a=fa(i);return t.concat(i,i.visualViewport||[],ao(o)?o:[],a&&n?lo(a):[])}return t.concat(o,lo(o,[],n))}function fa(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function nf(e){const t=sn(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=bn(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=ds(n)!==s||ds(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function ha(e){return on(e)?e:e.contextElement}function Tr(e){const t=ha(e);if(!bn(t))return mn(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=nf(t);let i=(s?ds(n.width):n.width)/r,a=(s?ds(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const Zv=mn(0);function rf(e){const t=qt(e);return!da()||!t.visualViewport?Zv:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Qv(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==qt(e)?!1:t}function Qn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=ha(e);let i=mn(1);t&&(r?on(r)&&(i=Tr(r)):i=Tr(e));const a=Qv(s,n,r)?rf(s):mn(0);let c=(o.left+a.x)/i.x,l=(o.top+a.y)/i.y,u=o.width/i.x,f=o.height/i.y;if(s){const h=qt(s),p=r&&on(r)?qt(r):r;let m=h,g=fa(m);for(;g&&r&&p!==m;){const b=Tr(g),v=g.getBoundingClientRect(),y=sn(g),T=v.left+(g.clientLeft+parseFloat(y.paddingLeft))*b.x,I=v.top+(g.clientTop+parseFloat(y.paddingTop))*b.y;c*=b.x,l*=b.y,u*=b.x,f*=b.y,c+=T,l+=I,m=qt(g),g=fa(m)}}return ps({width:u,height:f,x:c,y:l})}function bs(e,t){const n=xs(e).scrollLeft;return t?t.left+n:Qn(xn(e)).left+n}function of(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-bs(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function ey(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=xn(r),a=t?gs(t.floating):!1;if(r===i||a&&s)return n;let c={scrollLeft:0,scrollTop:0},l=mn(1);const u=mn(0),f=bn(r);if((f||!f&&!s)&&((Cr(r)!=="body"||ao(i))&&(c=xs(r)),bn(r))){const p=Qn(r);l=Tr(r),u.x=p.x+r.clientLeft,u.y=p.y+r.clientTop}const h=i&&!f&&!s?of(i,c):mn(0);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+u.x+h.x,y:n.y*l.y-c.scrollTop*l.y+u.y+h.y}}function ty(e){return Array.from(e.getClientRects())}function ny(e){const t=xn(e),n=xs(e),r=e.ownerDocument.body,o=Kt(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Kt(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+bs(e);const a=-n.scrollTop;return sn(r).direction==="rtl"&&(i+=Kt(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const sf=25;function ry(e,t){const n=qt(e),r=xn(e),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,a=0,c=0;if(o){s=o.width,i=o.height;const u=da();(!u||u&&t==="fixed")&&(a=o.offsetLeft,c=o.offsetTop)}const l=bs(r);if(l<=0){const u=r.ownerDocument,f=u.body,h=getComputedStyle(f),p=u.compatMode==="CSS1Compat"&&parseFloat(h.marginLeft)+parseFloat(h.marginRight)||0,m=Math.abs(r.clientWidth-f.clientWidth-p);m<=sf&&(s-=m)}else l<=sf&&(s+=l);return{width:s,height:i,x:a,y:c}}const oy=new Set(["absolute","fixed"]);function sy(e,t){const n=Qn(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=bn(e)?Tr(e):mn(1),i=e.clientWidth*s.x,a=e.clientHeight*s.y,c=o*s.x,l=r*s.y;return{width:i,height:a,x:c,y:l}}function af(e,t,n){let r;if(t==="viewport")r=ry(e,n);else if(t==="document")r=ny(xn(e));else if(on(t))r=sy(t,n);else{const o=rf(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return ps(r)}function lf(e,t){const n=Fn(e);return n===t||!on(n)||kr(n)?!1:sn(n).position==="fixed"||lf(n,t)}function iy(e,t){const n=t.get(e);if(n)return n;let r=lo(e,[],!1).filter(a=>on(a)&&Cr(a)!=="body"),o=null;const s=sn(e).position==="fixed";let i=s?Fn(e):e;for(;on(i)&&!kr(i);){const a=sn(i),c=ua(i);!c&&a.position==="fixed"&&(o=null),(s?!c&&!o:!c&&a.position==="static"&&!!o&&oy.has(o.position)||ao(i)&&!c&&lf(e,i))?r=r.filter(u=>u!==i):o=a,i=Fn(i)}return t.set(e,r),r}function ay(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?gs(t)?[]:iy(t,this._c):[].concat(n),r],a=i[0],c=i.reduce((l,u)=>{const f=af(t,u,o);return l.top=Kt(f.top,l.top),l.right=$n(f.right,l.right),l.bottom=$n(f.bottom,l.bottom),l.left=Kt(f.left,l.left),l},af(t,a,o));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function ly(e){const{width:t,height:n}=nf(e);return{width:t,height:n}}function cy(e,t,n){const r=bn(t),o=xn(t),s=n==="fixed",i=Qn(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const c=mn(0);function l(){c.x=bs(o)}if(r||!r&&!s)if((Cr(t)!=="body"||ao(o))&&(a=xs(t)),r){const p=Qn(t,!0,s,t);c.x=p.x+t.clientLeft,c.y=p.y+t.clientTop}else o&&l();s&&!r&&o&&l();const u=o&&!r&&!s?of(o,a):mn(0),f=i.left+a.scrollLeft-c.x-u.x,h=i.top+a.scrollTop-c.y-u.y;return{x:f,y:h,width:i.width,height:i.height}}function pa(e){return sn(e).position==="static"}function cf(e,t){if(!bn(e)||sn(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return xn(e)===n&&(n=n.ownerDocument.body),n}function uf(e,t){const n=qt(e);if(gs(e))return n;if(!bn(e)){let o=Fn(e);for(;o&&!kr(o);){if(on(o)&&!pa(o))return o;o=Fn(o)}return n}let r=cf(e,t);for(;r&&Vv(r)&&pa(r);)r=cf(r,t);return r&&kr(r)&&pa(r)&&!ua(r)?n:r||Xv(e)||n}const uy=async function(e){const t=this.getOffsetParent||uf,n=this.getDimensions,r=await n(e.floating);return{reference:cy(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function dy(e){return sn(e).direction==="rtl"}const fy={convertOffsetParentRelativeRectToViewportRelativeRect:ey,getDocumentElement:xn,getClippingRect:ay,getOffsetParent:uf,getElementRects:uy,getClientRects:ty,getDimensions:ly,getScale:Tr,isElement:on,isRTL:dy};function df(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function hy(e,t){let n=null,r;const o=xn(e);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function i(a,c){a===void 0&&(a=!1),c===void 0&&(c=1),s();const l=e.getBoundingClientRect(),{left:u,top:f,width:h,height:p}=l;if(a||t(),!h||!p)return;const m=fs(f),g=fs(o.clientWidth-(u+h)),b=fs(o.clientHeight-(f+p)),v=fs(u),T={rootMargin:-m+"px "+-g+"px "+-b+"px "+-v+"px",threshold:Kt(0,$n(1,c))||1};let I=!0;function k(S){const E=S[0].intersectionRatio;if(E!==c){if(!I)return i();E?i(!1,E):r=setTimeout(()=>{i(!1,1e-7)},1e3)}E===1&&!df(l,e.getBoundingClientRect())&&i(),I=!1}try{n=new IntersectionObserver(k,{...T,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,T)}n.observe(e)}return i(!0),s}function py(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:c=!1}=r,l=ha(e),u=o||s?[...l?lo(l):[],...lo(t)]:[];u.forEach(v=>{o&&v.addEventListener("scroll",n,{passive:!0}),s&&v.addEventListener("resize",n)});const f=l&&a?hy(l,n):null;let h=-1,p=null;i&&(p=new ResizeObserver(v=>{let[y]=v;y&&y.target===l&&p&&(p.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var T;(T=p)==null||T.observe(t)})),n()}),l&&!c&&p.observe(l),p.observe(t));let m,g=c?Qn(e):null;c&&b();function b(){const v=Qn(e);g&&!df(g,v)&&n(),g=v,m=requestAnimationFrame(b)}return n(),()=>{var v;u.forEach(y=>{o&&y.removeEventListener("scroll",n),s&&y.removeEventListener("resize",n)}),f==null||f(),(v=p)==null||v.disconnect(),p=null,c&&cancelAnimationFrame(m)}}const my=Fv,gy=zv,xy=Dv,by=Hv,wy=Lv,ff=Mv,vy=Bv,yy=(e,t,n)=>{const r=new Map,o={platform:fy,...n},s={...o.platform,_c:r};return Rv(e,t,{...o,platform:s})};var Sy=typeof document<"u",Cy=function(){},ws=Sy?x.useLayoutEffect:Cy;function vs(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!vs(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const s=o[r];if(!(s==="_owner"&&e.$$typeof)&&!vs(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function hf(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function pf(e,t){const n=hf(e);return Math.round(t*n)/n}function ma(e){const t=w.useRef(e);return ws(()=>{t.current=e}),t}function ky(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:s,floating:i}={},transform:a=!0,whileElementsMounted:c,open:l}=e,[u,f]=w.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[h,p]=w.useState(r);vs(h,r)||p(r);const[m,g]=w.useState(null),[b,v]=w.useState(null),y=w.useCallback(U=>{U!==S.current&&(S.current=U,g(U))},[]),T=w.useCallback(U=>{U!==E.current&&(E.current=U,v(U))},[]),I=s||m,k=i||b,S=w.useRef(null),E=w.useRef(null),j=w.useRef(u),_=c!=null,D=ma(c),L=ma(o),W=ma(l),V=w.useCallback(()=>{if(!S.current||!E.current)return;const U={placement:t,strategy:n,middleware:h};L.current&&(U.platform=L.current),yy(S.current,E.current,U).then(F=>{const G={...F,isPositioned:W.current!==!1};$.current&&!vs(j.current,G)&&(j.current=G,Ja.flushSync(()=>{f(G)}))})},[h,t,n,L,W]);ws(()=>{l===!1&&j.current.isPositioned&&(j.current.isPositioned=!1,f(U=>({...U,isPositioned:!1})))},[l]);const $=w.useRef(!1);ws(()=>($.current=!0,()=>{$.current=!1}),[]),ws(()=>{if(I&&(S.current=I),k&&(E.current=k),I&&k){if(D.current)return D.current(I,k,V);V()}},[I,k,V,D,_]);const Z=w.useMemo(()=>({reference:S,floating:E,setReference:y,setFloating:T}),[y,T]),X=w.useMemo(()=>({reference:I,floating:k}),[I,k]),oe=w.useMemo(()=>{const U={position:n,left:0,top:0};if(!X.floating)return U;const F=pf(X.floating,u.x),G=pf(X.floating,u.y);return a?{...U,transform:"translate("+F+"px, "+G+"px)",...hf(X.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:F,top:G}},[n,a,X.floating,u.x,u.y]);return w.useMemo(()=>({...u,update:V,refs:Z,elements:X,floatingStyles:oe}),[u,V,Z,X,oe])}const Ty=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?ff({element:r.current,padding:o}).fn(n):{}:r?ff({element:r,padding:o}).fn(n):{}}}},Ey=(e,t)=>({...my(e),options:[e,t]}),Iy=(e,t)=>({...gy(e),options:[e,t]}),Ay=(e,t)=>({...vy(e),options:[e,t]}),Ny=(e,t)=>({...xy(e),options:[e,t]}),_y=(e,t)=>({...by(e),options:[e,t]}),jy=(e,t)=>({...wy(e),options:[e,t]}),Py=(e,t)=>({...Ty(e),options:[e,t]});var Oy="Arrow",mf=w.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return d.jsx(Pe.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:d.jsx("polygon",{points:"0,0 30,0 15,10"})})});mf.displayName=Oy;var Ry=mf;function My(e){const[t,n]=w.useState(void 0);return hn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let i,a;if("borderBoxSize"in s){const c=s.borderBoxSize,l=Array.isArray(c)?c[0]:c;i=l.inlineSize,a=l.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var ga="Popper",[gf,xf]=Rn(ga),[Dy,bf]=gf(ga),wf=e=>{const{__scopePopper:t,children:n}=e,[r,o]=w.useState(null);return d.jsx(Dy,{scope:t,anchor:r,onAnchorChange:o,children:n})};wf.displayName=ga;var vf="PopperAnchor",yf=w.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=bf(vf,n),i=w.useRef(null),a=et(t,i),c=w.useRef(null);return w.useEffect(()=>{const l=c.current;c.current=(r==null?void 0:r.current)||i.current,l!==c.current&&s.onAnchorChange(c.current)}),r?null:d.jsx(Pe.div,{...o,ref:a})});yf.displayName=vf;var xa="PopperContent",[Ly,$y]=gf(xa),Sf=w.forwardRef((e,t)=>{var J,P,K,te,le,he;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:c=!0,collisionBoundary:l=[],collisionPadding:u=0,sticky:f="partial",hideWhenDetached:h=!1,updatePositionStrategy:p="optimized",onPlaced:m,...g}=e,b=bf(xa,n),[v,y]=w.useState(null),T=et(t,ue=>y(ue)),[I,k]=w.useState(null),S=My(I),E=(S==null?void 0:S.width)??0,j=(S==null?void 0:S.height)??0,_=r+(s!=="center"?"-"+s:""),D=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},L=Array.isArray(l)?l:[l],W=L.length>0,V={padding:D,boundary:L.filter(zy),altBoundary:W},{refs:$,floatingStyles:Z,placement:X,isPositioned:oe,middlewareData:U}=ky({strategy:"fixed",placement:_,whileElementsMounted:(...ue)=>py(...ue,{animationFrame:p==="always"}),elements:{reference:b.anchor},middleware:[Ey({mainAxis:o+j,alignmentAxis:i}),c&&Iy({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?Ay():void 0,...V}),c&&Ny({...V}),_y({...V,apply:({elements:ue,rects:ge,availableWidth:be,availableHeight:Be})=>{const{width:Le,height:je}=ge.reference,Fe=ue.floating.style;Fe.setProperty("--radix-popper-available-width",`${be}px`),Fe.setProperty("--radix-popper-available-height",`${Be}px`),Fe.setProperty("--radix-popper-anchor-width",`${Le}px`),Fe.setProperty("--radix-popper-anchor-height",`${je}px`)}}),I&&Py({element:I,padding:a}),By({arrowWidth:E,arrowHeight:j}),h&&jy({strategy:"referenceHidden",...V})]}),[F,G]=Tf(X),H=St(m);hn(()=>{oe&&(H==null||H())},[oe,H]);const A=(J=U.arrow)==null?void 0:J.x,N=(P=U.arrow)==null?void 0:P.y,R=((K=U.arrow)==null?void 0:K.centerOffset)!==0,[M,q]=w.useState();return hn(()=>{v&&q(window.getComputedStyle(v).zIndex)},[v]),d.jsx("div",{ref:$.setFloating,"data-radix-popper-content-wrapper":"",style:{...Z,transform:oe?Z.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:M,"--radix-popper-transform-origin":[(te=U.transformOrigin)==null?void 0:te.x,(le=U.transformOrigin)==null?void 0:le.y].join(" "),...((he=U.hide)==null?void 0:he.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:d.jsx(Ly,{scope:n,placedSide:F,onArrowChange:k,arrowX:A,arrowY:N,shouldHideArrow:R,children:d.jsx(Pe.div,{"data-side":F,"data-align":G,...g,ref:T,style:{...g.style,animation:oe?void 0:"none"}})})})});Sf.displayName=xa;var Cf="PopperArrow",Fy={top:"bottom",right:"left",bottom:"top",left:"right"},kf=w.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=$y(Cf,r),i=Fy[s.placedSide];return d.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:d.jsx(Ry,{...o,ref:n,style:{...o.style,display:"block"}})})});kf.displayName=Cf;function zy(e){return e!==null}var By=e=>({name:"transformOrigin",options:e,fn(t){var b,v,y;const{placement:n,rects:r,middlewareData:o}=t,i=((b=o.arrow)==null?void 0:b.centerOffset)!==0,a=i?0:e.arrowWidth,c=i?0:e.arrowHeight,[l,u]=Tf(n),f={start:"0%",center:"50%",end:"100%"}[u],h=(((v=o.arrow)==null?void 0:v.x)??0)+a/2,p=(((y=o.arrow)==null?void 0:y.y)??0)+c/2;let m="",g="";return l==="bottom"?(m=i?f:`${h}px`,g=`${-c}px`):l==="top"?(m=i?f:`${h}px`,g=`${r.floating.height+c}px`):l==="right"?(m=`${-c}px`,g=i?f:`${p}px`):l==="left"&&(m=`${r.floating.width+c}px`,g=i?f:`${p}px`),{data:{x:m,y:g}}}});function Tf(e){const[t,n="center"]=e.split("-");return[t,n]}var Hy=wf,Uy=yf,Wy=Sf,Vy=kf,ba="rovingFocusGroup.onEntryFocus",Ky={bubbles:!1,cancelable:!0},co="RovingFocusGroup",[wa,Ef,qy]=Vd(co),[Gy,If]=Rn(co,[qy]),[Yy,Xy]=Gy(co),Af=w.forwardRef((e,t)=>d.jsx(wa.Provider,{scope:e.__scopeRovingFocusGroup,children:d.jsx(wa.Slot,{scope:e.__scopeRovingFocusGroup,children:d.jsx(Jy,{...e,ref:t})})}));Af.displayName=co;var Jy=w.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:c,onEntryFocus:l,preventScrollOnEntryFocus:u=!1,...f}=e,h=w.useRef(null),p=et(t,h),m=oa(s),[g,b]=qo({prop:i,defaultProp:a??null,onChange:c,caller:co}),[v,y]=w.useState(!1),T=St(l),I=Ef(n),k=w.useRef(!1),[S,E]=w.useState(0);return w.useEffect(()=>{const j=h.current;if(j)return j.addEventListener(ba,T),()=>j.removeEventListener(ba,T)},[T]),d.jsx(Yy,{scope:n,orientation:r,dir:m,loop:o,currentTabStopId:g,onItemFocus:w.useCallback(j=>b(j),[b]),onItemShiftTab:w.useCallback(()=>y(!0),[]),onFocusableItemAdd:w.useCallback(()=>E(j=>j+1),[]),onFocusableItemRemove:w.useCallback(()=>E(j=>j-1),[]),children:d.jsx(Pe.div,{tabIndex:v||S===0?-1:0,"data-orientation":r,...f,ref:p,style:{outline:"none",...e.style},onMouseDown:Se(e.onMouseDown,()=>{k.current=!0}),onFocus:Se(e.onFocus,j=>{const _=!k.current;if(j.target===j.currentTarget&&_&&!v){const D=new CustomEvent(ba,Ky);if(j.currentTarget.dispatchEvent(D),!D.defaultPrevented){const L=I().filter(X=>X.focusable),W=L.find(X=>X.active),V=L.find(X=>X.id===g),Z=[W,V,...L].filter(Boolean).map(X=>X.ref.current);jf(Z,u)}}k.current=!1}),onBlur:Se(e.onBlur,()=>y(!1))})})}),Nf="RovingFocusGroupItem",_f=w.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,c=Wt(),l=s||c,u=Xy(Nf,n),f=u.currentTabStopId===l,h=Ef(n),{onFocusableItemAdd:p,onFocusableItemRemove:m,currentTabStopId:g}=u;return w.useEffect(()=>{if(r)return p(),()=>m()},[r,p,m]),d.jsx(wa.ItemSlot,{scope:n,id:l,focusable:r,active:o,children:d.jsx(Pe.span,{tabIndex:f?0:-1,"data-orientation":u.orientation,...a,ref:t,onMouseDown:Se(e.onMouseDown,b=>{r?u.onItemFocus(l):b.preventDefault()}),onFocus:Se(e.onFocus,()=>u.onItemFocus(l)),onKeyDown:Se(e.onKeyDown,b=>{if(b.key==="Tab"&&b.shiftKey){u.onItemShiftTab();return}if(b.target!==b.currentTarget)return;const v=e0(b,u.orientation,u.dir);if(v!==void 0){if(b.metaKey||b.ctrlKey||b.altKey||b.shiftKey)return;b.preventDefault();let T=h().filter(I=>I.focusable).map(I=>I.ref.current);if(v==="last")T.reverse();else if(v==="prev"||v==="next"){v==="prev"&&T.reverse();const I=T.indexOf(b.currentTarget);T=u.loop?t0(T,I+1):T.slice(I+1)}setTimeout(()=>jf(T))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:g!=null}):i})})});_f.displayName=Nf;var Zy={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Qy(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function e0(e,t,n){const r=Qy(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Zy[r]}function jf(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function t0(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var n0=Af,r0=_f,va=["Enter"," "],o0=["ArrowDown","PageUp","Home"],Pf=["ArrowUp","PageDown","End"],s0=[...o0,...Pf],i0={ltr:[...va,"ArrowRight"],rtl:[...va,"ArrowLeft"]},a0={ltr:["ArrowLeft"],rtl:["ArrowRight"]},uo="Menu",[fo,l0,c0]=Vd(uo),[er,Of]=Rn(uo,[c0,xf,If]),ys=xf(),Rf=If(),[u0,tr]=er(uo),[d0,ho]=er(uo),Mf=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:s,modal:i=!0}=e,a=ys(t),[c,l]=w.useState(null),u=w.useRef(!1),f=St(s),h=oa(o);return w.useEffect(()=>{const p=()=>{u.current=!0,document.addEventListener("pointerdown",m,{capture:!0,once:!0}),document.addEventListener("pointermove",m,{capture:!0,once:!0})},m=()=>u.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",m,{capture:!0}),document.removeEventListener("pointermove",m,{capture:!0})}},[]),d.jsx(Hy,{...a,children:d.jsx(u0,{scope:t,open:n,onOpenChange:f,content:c,onContentChange:l,children:d.jsx(d0,{scope:t,onClose:w.useCallback(()=>f(!1),[f]),isUsingKeyboardRef:u,dir:h,modal:i,children:r})})})};Mf.displayName=uo;var f0="MenuAnchor",ya=w.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=ys(n);return d.jsx(Uy,{...o,...r,ref:t})});ya.displayName=f0;var Sa="MenuPortal",[h0,Df]=er(Sa,{forceMount:void 0}),Lf=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,s=tr(Sa,t);return d.jsx(h0,{scope:t,forceMount:n,children:d.jsx(Vt,{present:n||s.open,children:d.jsx(Di,{asChild:!0,container:o,children:r})})})};Lf.displayName=Sa;var Jt="MenuContent",[p0,Ca]=er(Jt),$f=w.forwardRef((e,t)=>{const n=Df(Jt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=tr(Jt,e.__scopeMenu),i=ho(Jt,e.__scopeMenu);return d.jsx(fo.Provider,{scope:e.__scopeMenu,children:d.jsx(Vt,{present:r||s.open,children:d.jsx(fo.Slot,{scope:e.__scopeMenu,children:i.modal?d.jsx(m0,{...o,ref:t}):d.jsx(g0,{...o,ref:t})})})})}),m0=w.forwardRef((e,t)=>{const n=tr(Jt,e.__scopeMenu),r=w.useRef(null),o=et(t,r);return w.useEffect(()=>{const s=r.current;if(s)return Qu(s)},[]),d.jsx(ka,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Se(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),g0=w.forwardRef((e,t)=>{const n=tr(Jt,e.__scopeMenu);return d.jsx(ka,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),x0=sr.createSlot("MenuContent.ScrollLock"),ka=w.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:s,onCloseAutoFocus:i,disableOutsidePointerEvents:a,onEntryFocus:c,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onInteractOutside:h,onDismiss:p,disableOutsideScroll:m,...g}=e,b=tr(Jt,n),v=ho(Jt,n),y=ys(n),T=Rf(n),I=l0(n),[k,S]=w.useState(null),E=w.useRef(null),j=et(t,E,b.onContentChange),_=w.useRef(0),D=w.useRef(""),L=w.useRef(0),W=w.useRef(null),V=w.useRef("right"),$=w.useRef(0),Z=m?Hi:w.Fragment,X=m?{as:x0,allowPinchZoom:!0}:void 0,oe=F=>{var J,P;const G=D.current+F,H=I().filter(K=>!K.disabled),A=document.activeElement,N=(J=H.find(K=>K.ref.current===A))==null?void 0:J.textValue,R=H.map(K=>K.textValue),M=N0(R,G,N),q=(P=H.find(K=>K.textValue===M))==null?void 0:P.ref.current;(function K(te){D.current=te,window.clearTimeout(_.current),te!==""&&(_.current=window.setTimeout(()=>K(""),1e3))})(G),q&&setTimeout(()=>q.focus())};w.useEffect(()=>()=>window.clearTimeout(_.current),[]),$u();const U=w.useCallback(F=>{var H,A;return V.current===((H=W.current)==null?void 0:H.side)&&j0(F,(A=W.current)==null?void 0:A.area)},[]);return d.jsx(p0,{scope:n,searchRef:D,onItemEnter:w.useCallback(F=>{U(F)&&F.preventDefault()},[U]),onItemLeave:w.useCallback(F=>{var G;U(F)||((G=E.current)==null||G.focus(),S(null))},[U]),onTriggerLeave:w.useCallback(F=>{U(F)&&F.preventDefault()},[U]),pointerGraceTimerRef:L,onPointerGraceIntentChange:w.useCallback(F=>{W.current=F},[]),children:d.jsx(Z,{...X,children:d.jsx(Mi,{asChild:!0,trapped:o,onMountAutoFocus:Se(s,F=>{var G;F.preventDefault(),(G=E.current)==null||G.focus({preventScroll:!0})}),onUnmountAutoFocus:i,children:d.jsx(Pi,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onInteractOutside:h,onDismiss:p,children:d.jsx(n0,{asChild:!0,...T,dir:v.dir,orientation:"vertical",loop:r,currentTabStopId:k,onCurrentTabStopIdChange:S,onEntryFocus:Se(c,F=>{v.isUsingKeyboardRef.current||F.preventDefault()}),preventScrollOnEntryFocus:!0,children:d.jsx(Wy,{role:"menu","aria-orientation":"vertical","data-state":th(b.open),"data-radix-menu-content":"",dir:v.dir,...y,...g,ref:j,style:{outline:"none",...g.style},onKeyDown:Se(g.onKeyDown,F=>{const H=F.target.closest("[data-radix-menu-content]")===F.currentTarget,A=F.ctrlKey||F.altKey||F.metaKey,N=F.key.length===1;H&&(F.key==="Tab"&&F.preventDefault(),!A&&N&&oe(F.key));const R=E.current;if(F.target!==R||!s0.includes(F.key))return;F.preventDefault();const q=I().filter(J=>!J.disabled).map(J=>J.ref.current);Pf.includes(F.key)&&q.reverse(),I0(q)}),onBlur:Se(e.onBlur,F=>{F.currentTarget.contains(F.target)||(window.clearTimeout(_.current),D.current="")}),onPointerMove:Se(e.onPointerMove,mo(F=>{const G=F.target,H=$.current!==F.clientX;if(F.currentTarget.contains(G)&&H){const A=F.clientX>$.current?"right":"left";V.current=A,$.current=F.clientX}}))})})})})})})});$f.displayName=Jt;var b0="MenuGroup",Ta=w.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.jsx(Pe.div,{role:"group",...r,ref:t})});Ta.displayName=b0;var w0="MenuLabel",Ff=w.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.jsx(Pe.div,{...r,ref:t})});Ff.displayName=w0;var Ss="MenuItem",zf="menu.itemSelect",Cs=w.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,s=w.useRef(null),i=ho(Ss,e.__scopeMenu),a=Ca(Ss,e.__scopeMenu),c=et(t,s),l=w.useRef(!1),u=()=>{const f=s.current;if(!n&&f){const h=new CustomEvent(zf,{bubbles:!0,cancelable:!0});f.addEventListener(zf,p=>r==null?void 0:r(p),{once:!0}),Au(f,h),h.defaultPrevented?l.current=!1:i.onClose()}};return d.jsx(Bf,{...o,ref:c,disabled:n,onClick:Se(e.onClick,u),onPointerDown:f=>{var h;(h=e.onPointerDown)==null||h.call(e,f),l.current=!0},onPointerUp:Se(e.onPointerUp,f=>{var h;l.current||(h=f.currentTarget)==null||h.click()}),onKeyDown:Se(e.onKeyDown,f=>{const h=a.searchRef.current!=="";n||h&&f.key===" "||va.includes(f.key)&&(f.currentTarget.click(),f.preventDefault())})})});Cs.displayName=Ss;var Bf=w.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...s}=e,i=Ca(Ss,n),a=Rf(n),c=w.useRef(null),l=et(t,c),[u,f]=w.useState(!1),[h,p]=w.useState("");return w.useEffect(()=>{const m=c.current;m&&p((m.textContent??"").trim())},[s.children]),d.jsx(fo.ItemSlot,{scope:n,disabled:r,textValue:o??h,children:d.jsx(r0,{asChild:!0,...a,focusable:!r,children:d.jsx(Pe.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:l,onPointerMove:Se(e.onPointerMove,mo(m=>{r?i.onItemLeave(m):(i.onItemEnter(m),m.defaultPrevented||m.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Se(e.onPointerLeave,mo(m=>i.onItemLeave(m))),onFocus:Se(e.onFocus,()=>f(!0)),onBlur:Se(e.onBlur,()=>f(!1))})})})}),v0="MenuCheckboxItem",Hf=w.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return d.jsx(qf,{scope:e.__scopeMenu,checked:n,children:d.jsx(Cs,{role:"menuitemcheckbox","aria-checked":ks(n)?"mixed":n,...o,ref:t,"data-state":Ia(n),onSelect:Se(o.onSelect,()=>r==null?void 0:r(ks(n)?!0:!n),{checkForDefaultPrevented:!1})})})});Hf.displayName=v0;var Uf="MenuRadioGroup",[y0,S0]=er(Uf,{value:void 0,onValueChange:()=>{}}),Wf=w.forwardRef((e,t)=>{const{value:n,onValueChange:r,...o}=e,s=St(r);return d.jsx(y0,{scope:e.__scopeMenu,value:n,onValueChange:s,children:d.jsx(Ta,{...o,ref:t})})});Wf.displayName=Uf;var Vf="MenuRadioItem",Kf=w.forwardRef((e,t)=>{const{value:n,...r}=e,o=S0(Vf,e.__scopeMenu),s=n===o.value;return d.jsx(qf,{scope:e.__scopeMenu,checked:s,children:d.jsx(Cs,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":Ia(s),onSelect:Se(r.onSelect,()=>{var i;return(i=o.onValueChange)==null?void 0:i.call(o,n)},{checkForDefaultPrevented:!1})})})});Kf.displayName=Vf;var Ea="MenuItemIndicator",[qf,C0]=er(Ea,{checked:!1}),Gf=w.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,s=C0(Ea,n);return d.jsx(Vt,{present:r||ks(s.checked)||s.checked===!0,children:d.jsx(Pe.span,{...o,ref:t,"data-state":Ia(s.checked)})})});Gf.displayName=Ea;var k0="MenuSeparator",Yf=w.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.jsx(Pe.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});Yf.displayName=k0;var T0="MenuArrow",Xf=w.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=ys(n);return d.jsx(Vy,{...o,...r,ref:t})});Xf.displayName=T0;var E0="MenuSub",[qC,Jf]=er(E0),po="MenuSubTrigger",Zf=w.forwardRef((e,t)=>{const n=tr(po,e.__scopeMenu),r=ho(po,e.__scopeMenu),o=Jf(po,e.__scopeMenu),s=Ca(po,e.__scopeMenu),i=w.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:c}=s,l={__scopeMenu:e.__scopeMenu},u=w.useCallback(()=>{i.current&&window.clearTimeout(i.current),i.current=null},[]);return w.useEffect(()=>u,[u]),w.useEffect(()=>{const f=a.current;return()=>{window.clearTimeout(f),c(null)}},[a,c]),d.jsx(ya,{asChild:!0,...l,children:d.jsx(Bf,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":th(n.open),...e,ref:On(t,o.onTriggerChange),onClick:f=>{var h;(h=e.onClick)==null||h.call(e,f),!(e.disabled||f.defaultPrevented)&&(f.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Se(e.onPointerMove,mo(f=>{s.onItemEnter(f),!f.defaultPrevented&&!e.disabled&&!n.open&&!i.current&&(s.onPointerGraceIntentChange(null),i.current=window.setTimeout(()=>{n.onOpenChange(!0),u()},100))})),onPointerLeave:Se(e.onPointerLeave,mo(f=>{var p,m;u();const h=(p=n.content)==null?void 0:p.getBoundingClientRect();if(h){const g=(m=n.content)==null?void 0:m.dataset.side,b=g==="right",v=b?-5:5,y=h[b?"left":"right"],T=h[b?"right":"left"];s.onPointerGraceIntentChange({area:[{x:f.clientX+v,y:f.clientY},{x:y,y:h.top},{x:T,y:h.top},{x:T,y:h.bottom},{x:y,y:h.bottom}],side:g}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(f),f.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:Se(e.onKeyDown,f=>{var p;const h=s.searchRef.current!=="";e.disabled||h&&f.key===" "||i0[r.dir].includes(f.key)&&(n.onOpenChange(!0),(p=n.content)==null||p.focus(),f.preventDefault())})})})});Zf.displayName=po;var Qf="MenuSubContent",eh=w.forwardRef((e,t)=>{const n=Df(Jt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=tr(Jt,e.__scopeMenu),i=ho(Jt,e.__scopeMenu),a=Jf(Qf,e.__scopeMenu),c=w.useRef(null),l=et(t,c);return d.jsx(fo.Provider,{scope:e.__scopeMenu,children:d.jsx(Vt,{present:r||s.open,children:d.jsx(fo.Slot,{scope:e.__scopeMenu,children:d.jsx(ka,{id:a.contentId,"aria-labelledby":a.triggerId,...o,ref:l,align:"start",side:i.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:u=>{var f;i.isUsingKeyboardRef.current&&((f=c.current)==null||f.focus()),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:Se(e.onFocusOutside,u=>{u.target!==a.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:Se(e.onEscapeKeyDown,u=>{i.onClose(),u.preventDefault()}),onKeyDown:Se(e.onKeyDown,u=>{var p;const f=u.currentTarget.contains(u.target),h=a0[i.dir].includes(u.key);f&&h&&(s.onOpenChange(!1),(p=a.trigger)==null||p.focus(),u.preventDefault())})})})})})});eh.displayName=Qf;function th(e){return e?"open":"closed"}function ks(e){return e==="indeterminate"}function Ia(e){return ks(e)?"indeterminate":e?"checked":"unchecked"}function I0(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function A0(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function N0(e,t,n){const o=t.length>1&&Array.from(t).every(l=>l===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=A0(e,Math.max(s,0));o.length===1&&(i=i.filter(l=>l!==n));const c=i.find(l=>l.toLowerCase().startsWith(o.toLowerCase()));return c!==n?c:void 0}function _0(e,t){const{x:n,y:r}=e;let o=!1;for(let s=0,i=t.length-1;s<t.length;i=s++){const a=t[s],c=t[i],l=a.x,u=a.y,f=c.x,h=c.y;u>r!=h>r&&n<(f-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function j0(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return _0(n,t)}function mo(e){return t=>t.pointerType==="mouse"?e(t):void 0}var P0=Mf,O0=ya,R0=Lf,M0=$f,D0=Ta,L0=Ff,$0=Cs,F0=Hf,z0=Wf,B0=Kf,H0=Gf,U0=Yf,W0=Xf,V0=Zf,K0=eh,Ts="DropdownMenu",[q0,GC]=Rn(Ts,[Of]),_t=Of(),[G0,nh]=q0(Ts),rh=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:s,onOpenChange:i,modal:a=!0}=e,c=_t(t),l=w.useRef(null),[u,f]=qo({prop:o,defaultProp:s??!1,onChange:i,caller:Ts});return d.jsx(G0,{scope:t,triggerId:Wt(),triggerRef:l,contentId:Wt(),open:u,onOpenChange:f,onOpenToggle:w.useCallback(()=>f(h=>!h),[f]),modal:a,children:d.jsx(P0,{...c,open:u,onOpenChange:f,dir:r,modal:a,children:n})})};rh.displayName=Ts;var oh="DropdownMenuTrigger",sh=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,s=nh(oh,n),i=_t(n);return d.jsx(O0,{asChild:!0,...i,children:d.jsx(Pe.button,{type:"button",id:s.triggerId,"aria-haspopup":"menu","aria-expanded":s.open,"aria-controls":s.open?s.contentId:void 0,"data-state":s.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...o,ref:On(t,s.triggerRef),onPointerDown:Se(e.onPointerDown,a=>{!r&&a.button===0&&a.ctrlKey===!1&&(s.onOpenToggle(),s.open||a.preventDefault())}),onKeyDown:Se(e.onKeyDown,a=>{r||(["Enter"," "].includes(a.key)&&s.onOpenToggle(),a.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});sh.displayName=oh;var Y0="DropdownMenuPortal",ih=e=>{const{__scopeDropdownMenu:t,...n}=e,r=_t(t);return d.jsx(R0,{...r,...n})};ih.displayName=Y0;var ah="DropdownMenuContent",lh=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=nh(ah,n),s=_t(n),i=w.useRef(!1);return d.jsx(M0,{id:o.contentId,"aria-labelledby":o.triggerId,...s,...r,ref:t,onCloseAutoFocus:Se(e.onCloseAutoFocus,a=>{var c;i.current||(c=o.triggerRef.current)==null||c.focus(),i.current=!1,a.preventDefault()}),onInteractOutside:Se(e.onInteractOutside,a=>{const c=a.detail.originalEvent,l=c.button===0&&c.ctrlKey===!0,u=c.button===2||l;(!o.modal||u)&&(i.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});lh.displayName=ah;var X0="DropdownMenuGroup",J0=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx(D0,{...o,...r,ref:t})});J0.displayName=X0;var Z0="DropdownMenuLabel",ch=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx(L0,{...o,...r,ref:t})});ch.displayName=Z0;var Q0="DropdownMenuItem",uh=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx($0,{...o,...r,ref:t})});uh.displayName=Q0;var eS="DropdownMenuCheckboxItem",dh=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx(F0,{...o,...r,ref:t})});dh.displayName=eS;var tS="DropdownMenuRadioGroup",nS=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx(z0,{...o,...r,ref:t})});nS.displayName=tS;var rS="DropdownMenuRadioItem",fh=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx(B0,{...o,...r,ref:t})});fh.displayName=rS;var oS="DropdownMenuItemIndicator",hh=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx(H0,{...o,...r,ref:t})});hh.displayName=oS;var sS="DropdownMenuSeparator",ph=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx(U0,{...o,...r,ref:t})});ph.displayName=sS;var iS="DropdownMenuArrow",aS=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx(W0,{...o,...r,ref:t})});aS.displayName=iS;var lS="DropdownMenuSubTrigger",mh=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx(V0,{...o,...r,ref:t})});mh.displayName=lS;var cS="DropdownMenuSubContent",gh=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx(K0,{...o,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});gh.displayName=cS;var uS=rh,dS=sh,fS=ih,xh=lh,bh=ch,wh=uh,vh=dh,yh=fh,Sh=hh,Ch=ph,kh=mh,Th=gh;const Aa=uS,Na=dS,hS=w.forwardRef(({className:e,inset:t,children:n,...r},o)=>d.jsxs(kh,{ref:o,className:ae("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",e),...r,children:[n,d.jsx(pe.ChevronRight,{className:"ml-auto h-4 w-4"})]}));hS.displayName=kh.displayName;const pS=w.forwardRef(({className:e,...t},n)=>d.jsx(Th,{ref:n,className:ae("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));pS.displayName=Th.displayName;const Es=w.forwardRef(({className:e,sideOffset:t=4,...n},r)=>d.jsx(fS,{children:d.jsx(xh,{ref:r,sideOffset:t,className:ae("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})}));Es.displayName=xh.displayName;const nr=w.forwardRef(({className:e,inset:t,...n},r)=>d.jsx(wh,{ref:r,className:ae("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));nr.displayName=wh.displayName;const mS=w.forwardRef(({className:e,children:t,checked:n,...r},o)=>d.jsxs(vh,{ref:o,className:ae("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[d.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:d.jsx(Sh,{children:d.jsx(pe.Check,{className:"h-4 w-4"})})}),t]}));mS.displayName=vh.displayName;const gS=w.forwardRef(({className:e,children:t,...n},r)=>d.jsxs(yh,{ref:r,className:ae("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[d.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:d.jsx(Sh,{children:d.jsx(pe.Circle,{className:"h-2 w-2 fill-current"})})}),t]}));gS.displayName=yh.displayName;const xS=w.forwardRef(({className:e,inset:t,...n},r)=>d.jsx(bh,{ref:r,className:ae("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));xS.displayName=bh.displayName;const bS=w.forwardRef(({className:e,...t},n)=>d.jsx(Ch,{ref:n,className:ae("-mx-1 my-1 h-px bg-muted",e),...t}));bS.displayName=Ch.displayName;const Eh=w.forwardRef(({className:e,...t},n)=>d.jsx("textarea",{className:ae("flex min-h-[40px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));Eh.displayName="Textarea";const wS=1e4;function _a({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=wS,value:i,onValueChange:a,onSend:c,onCancelEdit:l,onStop:u,className:f="",textareaClassName:h="",allowEmptySend:p=!1,sendButtonClassName:m,validate:g,onValidationError:b}){const v=i!==void 0,[y,T]=x.useState(e),I=(v?i:y)??"",[k,S]=x.useTransition(),E=x.useRef(null),j=x.useRef(0),_=x.useRef(null),D=x.useRef("");x.useEffect(()=>{if(!v&&(T(e??""),_.current=null,E.current)){const R=!e||e.trim()==="",M=44;R?E.current.style.height=`${M}px`:(E.current.style.height="auto",E.current.style.height=`${Math.max(E.current.scrollHeight,M)}px`)}},[e,t,v]);const[L,W]=x.useState(null),V=x.useCallback(R=>R.length>s?`Message too long (${R.length}/${s} characters)`:null,[s]),$=x.useMemo(()=>g??V,[g,V]),Z=x.useCallback(R=>{const M=$(R);return W(M),b==null||b(M),D.current=R,M},[$,b]),X=x.useCallback(()=>{const R=E.current;if(!R)return;const M=!R.value||R.value.trim()==="",q=44;if(M){R.style.height=`${q}px`;return}R.style.height="auto";const J=Math.max(R.scrollHeight,q);R.style.height=`${J}px`},[]);x.useEffect(()=>{X()},[X,I]),x.useEffect(()=>{if(!L)return;const R=(I??"").trim();D.current!==R&&Z(R)},[I,L,Z]);const oe=x.useCallback((R,{fromUser:M})=>{v||T(R),M&&(a==null||a(R))},[v,a]),U=x.useCallback(async R=>{R&&R.preventDefault();const M=(I??"").trim();if(!M&&!p||Z(M))return;const q=++j.current;_.current={id:q,shouldClear:!0},S(()=>{var J,P,K;try{const te=c(M);te&&typeof te.then=="function"?te.then(()=>{var le,he;((le=_.current)==null?void 0:le.id)===q&&_.current.shouldClear&&(v||(T(""),E.current&&(E.current.style.height="auto"),a==null||a(""))),((he=_.current)==null?void 0:he.id)===q&&(_.current=null)}).catch(()=>{var le;((le=_.current)==null?void 0:le.id)===q&&(_.current=null)}):(((J=_.current)==null?void 0:J.id)===q&&_.current.shouldClear&&(v||(T(""),E.current&&(E.current.style.height="auto"),a==null||a(""))),((P=_.current)==null?void 0:P.id)===q&&(_.current=null))}catch{((K=_.current)==null?void 0:K.id)===q&&(_.current=null)}})},[I,c,p,v,a,Z]),F=x.useCallback(R=>{const M=R.target.value;oe(M,{fromUser:!0}),_.current&&(_.current.shouldClear=!1),E.current&&(E.current.style.height="auto",E.current.style.height=`${E.current.scrollHeight}px`),L&&Z(M.trim())},[oe,Z,L]),G=x.useCallback(R=>{R.key==="Enter"&&!R.shiftKey?(R.preventDefault(),U()):R.key==="Escape"&&t&&(R.preventDefault(),l==null||l())},[U,t,l]),N=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${t?"border-[hsl(var(--ring))] bg-[hsl(var(--card))] text-[hsl(var(--card-foreground))] dark:bg-[hsl(var(--card))] dark:text-[hsl(var(--card-foreground))]":""} ${h}`;return d.jsx("div",{className:`w-full ${f}`,children:d.jsxs("div",{className:"flex items-end gap-2",children:[d.jsxs("div",{className:"flex-1",children:[d.jsx(Eh,{ref:E,value:I,onChange:F,onKeyDown:G,placeholder:t?"Edit your message...":n,className:N,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"}),L&&d.jsx("p",{className:"mt-1 text-xs text-destructive font-medium",children:L})]}),d.jsx("div",{children:r?d.jsx(Ke,{type:"button",onClick:()=>{u==null||u()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!u,children:d.jsx(pe.Square,{size:16})}):d.jsx(Ke,{type:"button",onClick:R=>void U(R),size:"icon",className:`shrink-0 ${m??""}`,title:t?"Save changes":"Send message",disabled:o||!I.trim()&&!p||k||r,children:d.jsx(pe.Send,{size:16})})})]})})}const vS=x.memo(_a);function ja({composerValue:e,onComposerChange:t,onSend:n,onCancelEdit:r,onStop:o,editingMessageId:s=null,editingInitialValue:i="",placeholder:a="Type your message...",isStreaming:c=!1,disabled:l=!1,textareaClassName:u="",customStyles:f={},enableFileUpload:h=!1,enableExcelUpload:p=!1,onExcelUpload:m,onFilesChange:g,onError:b,allowEmptySend:v=!1,inputError:y=null}){const[T,I]=x.useState([]),k=x.useRef(null),S=x.useRef(null),[E,j]=x.useState(0),[_,D]=x.useState(0),[L,W]=x.useState(!1),[V,$]=x.useState(null),[Z,X]=x.useState(null),oe=x.useCallback(()=>{k.current&&(k.current.value=""),S.current&&(S.current.value=""),j(M=>M+1),D(M=>M+1)},[]),U=x.useCallback(M=>{I(q=>{const J=[...q,...M];return g==null||g(J),J})},[g]),F=x.useCallback(M=>{const q=Array.from(M.target.files||[]);U(q),M.target.value=""},[U]),G=x.useCallback(M=>{I(q=>{const J=q.filter((P,K)=>K!==M);return J.length===0&&oe(),g==null||g(J),J})},[g,oe]),H=x.useCallback(async M=>{const q=(M.target.files||[])[0];if(q&&($(null),X(null),!!m)){W(!0);try{await m(q),$(`Uploaded ${q.name} - processing through chat stream`)}catch(J){const P=J instanceof Error?J.message:"Failed to upload Excel file";X(P),b==null||b(P)}finally{W(!1),M.target.value="",oe()}}},[m,b,oe]),A=x.useMemo(()=>v||T.length>0,[v,T]),N=x.useCallback(async M=>{const J=await n(M,T);return T.length>0&&(I([]),g==null||g([]),oe()),J},[n,oe,T]),R=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${s?"border-blue-400 bg-blue-50 text-blue-900 dark:border-blue-500 dark:bg-blue-950/60 dark:text-blue-50":""} ${y?"border-red-400":""} ${f.textarea||""} ${u}`;return d.jsxs(d.Fragment,{children:[(h||p)&&d.jsxs("div",{className:"mb-3 space-y-3",children:[h&&d.jsxs(d.Fragment,{children:[d.jsx("input",{ref:k,type:"file",multiple:!0,onChange:F,className:"hidden"},E),T.length>0&&d.jsx("div",{className:"flex flex-wrap gap-2",children:T.map((M,q)=>d.jsxs("div",{className:"flex items-center gap-2 bg-gray-100 dark:bg-gray-800 rounded-lg px-3 py-2 text-sm text-gray-900 dark:text-gray-100",children:[d.jsx(pe.Paperclip,{size:14}),d.jsx("span",{className:"truncate max-w-[150px]",children:M.name}),d.jsx(Ke,{variant:"ghost",size:"sm",onClick:()=>G(q),className:"h-4 w-4 p-0 text-gray-500 dark:text-gray-400 hover:text-red-500 dark:hover:text-red-400","aria-label":`Remove ${M.name}`,children:d.jsx(pe.X,{size:12})})]},q))})]}),p&&d.jsxs(d.Fragment,{children:[d.jsx("input",{ref:S,type:"file",accept:".xls,.xlsx,.xlsm",onChange:H,className:"hidden"},_),L&&d.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[d.jsx(pe.Loader2,{className:"h-4 w-4 animate-spin"})," Uploading Excel file..."]}),V&&!L&&d.jsx("div",{className:"text-sm rounded border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-700",children:V}),Z&&!L&&d.jsx("div",{className:"text-sm rounded border border-red-200 bg-red-50 px-3 py-2 text-red-600",children:Z})]})]}),d.jsxs("div",{className:"flex items-end gap-2",children:[(h||p)&&d.jsxs(Aa,{children:[d.jsx(Na,{asChild:!0,children:d.jsx(Ke,{type:"button",size:"icon",variant:"outline",disabled:c||l,title:"More input actions",className:f.moreButton||"",children:d.jsx(pe.Plus,{size:16})})}),d.jsxs(Es,{align:"start",sideOffset:6,className:"w-52",children:[h&&d.jsxs(nr,{onClick:()=>{var M;return(M=k.current)==null?void 0:M.click()},className:"cursor-pointer",children:[d.jsx(pe.Paperclip,{className:"h-4 w-4 mr-2"})," Attach files or images"]}),p&&d.jsxs(nr,{onClick:()=>{var M;L||(M=S.current)==null||M.click()},className:`cursor-pointer ${L?"opacity-60 pointer-events-none":""}`,children:[d.jsx(pe.FileSpreadsheet,{className:"h-4 w-4 mr-2"})," Upload Excel file"]})]})]}),d.jsx("div",{className:"flex-1",children:d.jsx(vS,{initialValue:i,editingMessageId:s,value:e,onValueChange:t,placeholder:s?"Edit your message...":a,isStreaming:c,disabled:l,onSend:N,onCancelEdit:r,onStop:o,allowEmptySend:A,textareaClassName:R,sendButtonClassName:f.sendButton})})]})]})}const yS=x.memo(ja),Ih={value:""};function Er({className:e="",placeholder:t="Type your message...",maxHeight:n=void 0,streamingDebounceMs:r=500,followNewMessages:o=!0,enableFileUpload:s=!0,enableExcelUpload:i=!1,enableMessageEditing:a=!0,showToolMessages:c=!0,toolConfig:l,toolRenderers:u,toolArtifactRenderers:f,payloadExtras:h={},customStyles:p={},messageCustomStyles:m,onMessageSent:g,onExcelUploadSuccess:b,onError:v,renderArtifactsInline:y=!0,emptyMessage:T}){const{currentThreadId:I}=ur(),{threadId:k,messages:S,isLoading:E,navigateToCheckpoint:j,returnToLatest:_,checkpoint:D,checkpoints:L,interrupt:W,metadata:V,checkpointIndex:$,respondToInterrupt:Z}=Ur(),{isStreaming:X,error:oe,connectionState:U,submit:F,stop:G,messages:H}=ii(),A=k??I??null,N=(D==null?void 0:D.id)??null,R=(D==null?void 0:D.namespace)??null,M=(V==null?void 0:V.assemblingMessageId)??null;x.useEffect(()=>{console.log("[ChatInterface] streamingAssistantId changed:",{streamingAssistantId:M,isStreaming:X,assemblingMessageId:V==null?void 0:V.assemblingMessageId})},[M,X,V==null?void 0:V.assemblingMessageId]);const q=W,J=q?oc(q.id):null,P=J!==null?{type:"interrupt",id:J}:null,[K,te]=x.useState(!1),[le,he]=x.useState(!1);x.useEffect(()=>{q||te(!1)},[q]);const ue=x.useCallback(()=>{te(!0)},[]),ge=x.useCallback(()=>{te(!1)},[]),be=x.useCallback(Q=>{},[]),Be=x.useCallback(Q=>Q.name!=="ask_user_choice",[]),Le=l??{toolRenderers:u,toolArtifactRenderers:f,getToolExpandable:Be},je=x.useCallback(async(Q,C,O)=>{try{ue(),await Z(Q,C,O)}catch(z){console.error("Failed to respond to interrupt:",z)}finally{ge()}},[ge,ue,Z]),Fe=x.useCallback(()=>je(!0),[je]),tt=x.useCallback(()=>je(!1),[je]),mt=x.useCallback((Q,C)=>je(!0,C),[je]),ot=!!q||K,[ze,Me]=x.useState(null),[Ze,rt]=x.useState(""),[qe,ht]=x.useState(null),[xt,He]=x.useState(null),[st,an]=x.useState(!1),jt=x.useRef(!1),[ct,kt]=x.useState(()=>Ih.value),Tt=x.useRef(ct),bt=x.useRef(null),Ge=x.useCallback(Q=>{Ih.value=Q,kt(Q)},[]),[gt,ut]=x.useState(!1),$t=x.useRef(null),$e=x.useCallback(Q=>{Ge(Q)},[Ge]);x.useEffect(()=>{X||he(!1)},[X]),x.useEffect(()=>{V!=null&&V.assemblingMessageId&&he(!1)},[V==null?void 0:V.assemblingMessageId]);const[Ee,Ve]=x.useState("desktop");x.useEffect(()=>{const Q=()=>{const C=window.innerWidth;Ve(C<640?"phone":C<1024?"tablet":"desktop")};return Q(),window.addEventListener("resize",Q),()=>window.removeEventListener("resize",Q)},[]),x.useEffect(()=>{jt.current=!1},[A]),x.useEffect(()=>{Tt.current=ct},[ct]),x.useEffect(()=>{if(!ze){bt.current=null;return}bt.current===null&&(bt.current=Tt.current),Ge(Ze??"")},[Ze,ze,Ge]),x.useEffect(()=>{oe&&!st&&(v==null||v(oe))},[oe,st,v]);const dt=async(Q,C)=>{const O=Q.trim();if(!(!O&&C.length===0))try{const z=ze?(qe==null?void 0:qe.checkpointId)??N??void 0:N??void 0,se=ze?(qe==null?void 0:qe.checkpointNs)??R??void 0:R??void 0;await F({text:O||"",attachments:C,payload:h},{checkpointId:z,checkpointNs:se,edit:!!ze,originalMessageId:ze??void 0}),g==null||g(O),he(!0),Ge(""),He(null),Me(null),rt(""),ht(null)}catch(z){const se=(z==null?void 0:z.message)||"Failed to send message";He(se),v==null||v(se),he(!1)}},Et=x.useCallback(async Q=>{await F({attachments:[Q],payload:h},{checkpointId:N??void 0,checkpointNs:R??void 0}),b==null||b({file:Q})},[N,R,h,b,F]),Ft=x.useCallback((Q,C,O)=>{a&&(bt.current=ct,Me(Q),rt(C),Ge(C),He(null),ht({checkpointId:(O==null?void 0:O.checkpointId)??null,checkpointNs:(O==null?void 0:O.checkpointNs)??null}))},[ct,a,Ge]),zt=x.useCallback(()=>{Me(null),rt(""),ht(null),He(null),Ge(bt.current??ct),bt.current=null},[ct,Ge]),kn=x.useCallback((Q,C,O)=>{Ft(Q,C,O)},[Ft]),Tn=x.useCallback(Q=>{let C=null;for(let ie=Q-1;ie>=0;ie--)if(S[ie].role==="user"){C=S[ie];break}if(!C)return;const O=Array.isArray(C.content)?C.content:[],se=O.filter(ie=>(ie==null?void 0:ie.type)==="text").map(ie=>ie.text).join("")||(()=>{try{return JSON.stringify(O,null,2)}catch{return String(O)}})();se&&F({text:se,payload:h},{checkpointId:N??void 0,checkpointNs:R??void 0,edit:!0,originalMessageId:C.id})},[S,F,N,R,h]),Gt=x.useCallback(async Q=>{if(I){ut(!0);try{if(!Q){await _(),requestAnimationFrame(()=>{var z;(z=$t.current)==null||z.scrollToLatest()});return}const C=L.find(z=>z.checkpointId===Q),O=(C==null?void 0:C.checkpointNs)??null;await j(Q,O),requestAnimationFrame(()=>{var z;(z=$t.current)==null||z.scrollToTop()})}finally{ut(!1)}}},[L,I,$t,j,_]),vn=x.useCallback(async(Q,C,O)=>{await Gt(O?null:Q)},[Gt]),ln=`flex flex-1 w-full flex-col min-h-0 min-w-0 max-h-full overflow-hidden bg-transparent ${e} ${p.container||""}`,Y=`flex-1 min-h-0 min-w-0 max-h-full w-full overflow-hidden overscroll-contain break-words break-anywhere p-4 ${q?"pb-32":""} bg-transparent ${p.messagesArea||""}`,fe=`relative flex-shrink-0 w-full border-t p-4 bg-transparent ${p.inputArea||""}`;return d.jsxs("div",{className:ln,children:[!!oe&&!st&&d.jsxs("div",{className:"flex-shrink-0 bg-red-50 border border-red-200 text-red-800 px-4 py-2 text-sm flex items-center justify-between",children:[d.jsx("span",{children:oe}),d.jsx(Ke,{variant:"ghost",size:"sm",onClick:()=>an(!0),className:"text-red-800 hover:bg-red-100","aria-label":"Dismiss error",children:d.jsx(pe.X,{size:16})})]}),d.jsxs("div",{className:`relative ${Y}`,style:n?{maxHeight:n}:void 0,children:[d.jsx(us,{ref:$t,className:"h-full",style:{height:"100%"},messages:H??S,isStreaming:X,streamingAssistantId:M,streamingDebounceMs:r,followNewMessages:o,layoutSize:Ee,enableMessageEditing:a,editingMessageId:ze,onEdit:kn,onRegenerate:Tn,onCancelEdit:zt,emptyMessage:T,isNavigatingCheckpoint:gt,showToolMessages:c,toolConfig:Le,checkpointIndex:$,activeCheckpointId:N,onSelectCheckpoint:vn,showThinkingIndicator:X||le,getMessageCustomStyles:m,getInterruptOptions:be,renderArtifactsInline:y}),(U==="reconnecting"||U==="connecting")&&d.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-muted/80 px-3 py-1 text-xs font-medium text-foreground shadow-sm backdrop-blur-sm dark:bg-muted/60",children:d.jsxs("span",{className:"flex items-center gap-2",children:[d.jsx(pe.Loader2,{className:"h-3 w-3 animate-spin"}),U==="reconnecting"?"Reconnecting…":"Connecting…"]})}),U==="error"&&d.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-destructive/10 px-3 py-1 text-xs font-semibold text-destructive shadow-sm",children:"Connection lost"}),E&&d.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-background/80 backdrop-blur-sm text-muted-foreground",children:[d.jsx(pe.Loader2,{className:"h-6 w-6 animate-spin"}),d.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading messages…"})]}),gt&&d.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-background/80 backdrop-blur-sm text-muted-foreground",children:[d.jsx(pe.Loader2,{className:"h-6 w-6 animate-spin"}),d.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading checkpoint…"})]}),q&&P&&d.jsx("div",{className:"pointer-events-auto absolute inset-x-0 bottom-6 z-30 flex justify-center px-4",children:d.jsx("div",{className:"w-full max-w-3xl",children:d.jsx(Ad,{interruptPart:P,onApprove:Fe,onReject:tt,onSelectAlternative:mt,disabled:K,isActive:!0,payload:q.value})})})]}),d.jsxs("div",{className:fe,children:[ze&&d.jsx("div",{className:"mb-3 p-3 bg-blue-50 border border-blue-200 rounded-lg",children:d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx(pe.Edit3,{size:16,className:"text-blue-600"}),d.jsx("span",{className:"text-sm font-medium text-blue-800",children:"Editing message"})]}),d.jsx(Ke,{variant:"ghost",size:"sm",onClick:zt,className:"text-blue-600 hover:bg-blue-100",children:d.jsx(pe.X,{size:16})})]})}),xt&&d.jsx("div",{className:"mb-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2",children:xt}),d.jsx(yS,{composerValue:ct,onComposerChange:$e,onSend:dt,onCancelEdit:zt,onStop:G,editingMessageId:ze,editingInitialValue:Ze,placeholder:ze?"Edit your message...":t,isStreaming:X,disabled:ot,enableFileUpload:s,enableExcelUpload:i,onExcelUpload:Et,onError:v,customStyles:p,textareaClassName:p.textarea||"",allowEmptySend:!1,inputError:xt})]})]})}var Ah=1,SS=.9,CS=.8,kS=.17,Pa=.1,Oa=.999,TS=.9999,ES=.99,IS=/[\\\/_+.#"@\[\(\{&]/,AS=/[\\\/_+.#"@\[\(\{&]/g,NS=/[\s-]/,Nh=/[\s-]/g;function Ra(e,t,n,r,o,s,i){if(s===t.length)return o===e.length?Ah:ES;var a=`${o},${s}`;if(i[a]!==void 0)return i[a];for(var c=r.charAt(s),l=n.indexOf(c,o),u=0,f,h,p,m;l>=0;)f=Ra(e,t,n,r,l+1,s+1,i),f>u&&(l===o?f*=Ah:IS.test(e.charAt(l-1))?(f*=CS,p=e.slice(o,l-1).match(AS),p&&o>0&&(f*=Math.pow(Oa,p.length))):NS.test(e.charAt(l-1))?(f*=SS,m=e.slice(o,l-1).match(Nh),m&&o>0&&(f*=Math.pow(Oa,m.length))):(f*=kS,o>0&&(f*=Math.pow(Oa,l-o))),e.charAt(l)!==t.charAt(s)&&(f*=TS)),(f<Pa&&n.charAt(l-1)===r.charAt(s+1)||r.charAt(s+1)===r.charAt(s)&&n.charAt(l-1)!==r.charAt(s))&&(h=Ra(e,t,n,r,l+1,s+2,i),h*Pa>f&&(f=h*Pa)),f>u&&(u=f),l=n.indexOf(c,l+1);return i[a]=u,u}function _h(e){return e.toLowerCase().replace(Nh," ")}function _S(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Ra(e,t,_h(e),_h(t),0,0,{})}var go='[cmdk-group=""]',Ma='[cmdk-group-items=""]',jS='[cmdk-group-heading=""]',jh='[cmdk-item=""]',Ph=`${jh}:not([aria-disabled="true"])`,Da="cmdk-item-select",Ir="data-value",PS=(e,t,n)=>_S(e,t,n),Oh=w.createContext(void 0),xo=()=>w.useContext(Oh),Rh=w.createContext(void 0),La=()=>w.useContext(Rh),Mh=w.createContext(void 0),Dh=w.forwardRef((e,t)=>{let n=Ar(()=>{var A,N;return{search:"",value:(N=(A=e.value)!=null?A:e.defaultValue)!=null?N:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=Ar(()=>new Set),o=Ar(()=>new Map),s=Ar(()=>new Map),i=Ar(()=>new Set),a=Lh(e),{label:c,children:l,value:u,onValueChange:f,filter:h,shouldFilter:p,loop:m,disablePointerSelection:g=!1,vimBindings:b=!0,...v}=e,y=Wt(),T=Wt(),I=Wt(),k=w.useRef(null),S=US();rr(()=>{if(u!==void 0){let A=u.trim();n.current.value=A,E.emit()}},[u]),rr(()=>{S(6,V)},[]);let E=w.useMemo(()=>({subscribe:A=>(i.current.add(A),()=>i.current.delete(A)),snapshot:()=>n.current,setState:(A,N,R)=>{var M,q,J,P;if(!Object.is(n.current[A],N)){if(n.current[A]=N,A==="search")W(),D(),S(1,L);else if(A==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let K=document.getElementById(I);K?K.focus():(M=document.getElementById(y))==null||M.focus()}if(S(7,()=>{var K;n.current.selectedItemId=(K=$())==null?void 0:K.id,E.emit()}),R||S(5,V),((q=a.current)==null?void 0:q.value)!==void 0){let K=N??"";(P=(J=a.current).onValueChange)==null||P.call(J,K);return}}E.emit()}},emit:()=>{i.current.forEach(A=>A())}}),[]),j=w.useMemo(()=>({value:(A,N,R)=>{var M;N!==((M=s.current.get(A))==null?void 0:M.value)&&(s.current.set(A,{value:N,keywords:R}),n.current.filtered.items.set(A,_(N,R)),S(2,()=>{D(),E.emit()}))},item:(A,N)=>(r.current.add(A),N&&(o.current.has(N)?o.current.get(N).add(A):o.current.set(N,new Set([A]))),S(3,()=>{W(),D(),n.current.value||L(),E.emit()}),()=>{s.current.delete(A),r.current.delete(A),n.current.filtered.items.delete(A);let R=$();S(4,()=>{W(),(R==null?void 0:R.getAttribute("id"))===A&&L(),E.emit()})}),group:A=>(o.current.has(A)||o.current.set(A,new Set),()=>{s.current.delete(A),o.current.delete(A)}),filter:()=>a.current.shouldFilter,label:c||e["aria-label"],getDisablePointerSelection:()=>a.current.disablePointerSelection,listId:y,inputId:I,labelId:T,listInnerRef:k}),[]);function _(A,N){var R,M;let q=(M=(R=a.current)==null?void 0:R.filter)!=null?M:PS;return A?q(A,n.current.search,N):0}function D(){if(!n.current.search||a.current.shouldFilter===!1)return;let A=n.current.filtered.items,N=[];n.current.filtered.groups.forEach(M=>{let q=o.current.get(M),J=0;q.forEach(P=>{let K=A.get(P);J=Math.max(K,J)}),N.push([M,J])});let R=k.current;Z().sort((M,q)=>{var J,P;let K=M.getAttribute("id"),te=q.getAttribute("id");return((J=A.get(te))!=null?J:0)-((P=A.get(K))!=null?P:0)}).forEach(M=>{let q=M.closest(Ma);q?q.appendChild(M.parentElement===q?M:M.closest(`${Ma} > *`)):R.appendChild(M.parentElement===R?M:M.closest(`${Ma} > *`))}),N.sort((M,q)=>q[1]-M[1]).forEach(M=>{var q;let J=(q=k.current)==null?void 0:q.querySelector(`${go}[${Ir}="${encodeURIComponent(M[0])}"]`);J==null||J.parentElement.appendChild(J)})}function L(){let A=Z().find(R=>R.getAttribute("aria-disabled")!=="true"),N=A==null?void 0:A.getAttribute(Ir);E.setState("value",N||void 0)}function W(){var A,N,R,M;if(!n.current.search||a.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let q=0;for(let J of r.current){let P=(N=(A=s.current.get(J))==null?void 0:A.value)!=null?N:"",K=(M=(R=s.current.get(J))==null?void 0:R.keywords)!=null?M:[],te=_(P,K);n.current.filtered.items.set(J,te),te>0&&q++}for(let[J,P]of o.current)for(let K of P)if(n.current.filtered.items.get(K)>0){n.current.filtered.groups.add(J);break}n.current.filtered.count=q}function V(){var A,N,R;let M=$();M&&(((A=M.parentElement)==null?void 0:A.firstChild)===M&&((R=(N=M.closest(go))==null?void 0:N.querySelector(jS))==null||R.scrollIntoView({block:"nearest"})),M.scrollIntoView({block:"nearest"}))}function $(){var A;return(A=k.current)==null?void 0:A.querySelector(`${jh}[aria-selected="true"]`)}function Z(){var A;return Array.from(((A=k.current)==null?void 0:A.querySelectorAll(Ph))||[])}function X(A){let N=Z()[A];N&&E.setState("value",N.getAttribute(Ir))}function oe(A){var N;let R=$(),M=Z(),q=M.findIndex(P=>P===R),J=M[q+A];(N=a.current)!=null&&N.loop&&(J=q+A<0?M[M.length-1]:q+A===M.length?M[0]:M[q+A]),J&&E.setState("value",J.getAttribute(Ir))}function U(A){let N=$(),R=N==null?void 0:N.closest(go),M;for(;R&&!M;)R=A>0?BS(R,go):HS(R,go),M=R==null?void 0:R.querySelector(Ph);M?E.setState("value",M.getAttribute(Ir)):oe(A)}let F=()=>X(Z().length-1),G=A=>{A.preventDefault(),A.metaKey?F():A.altKey?U(1):oe(1)},H=A=>{A.preventDefault(),A.metaKey?X(0):A.altKey?U(-1):oe(-1)};return w.createElement(Pe.div,{ref:t,tabIndex:-1,...v,"cmdk-root":"",onKeyDown:A=>{var N;(N=v.onKeyDown)==null||N.call(v,A);let R=A.nativeEvent.isComposing||A.keyCode===229;if(!(A.defaultPrevented||R))switch(A.key){case"n":case"j":{b&&A.ctrlKey&&G(A);break}case"ArrowDown":{G(A);break}case"p":case"k":{b&&A.ctrlKey&&H(A);break}case"ArrowUp":{H(A);break}case"Home":{A.preventDefault(),X(0);break}case"End":{A.preventDefault(),F();break}case"Enter":{A.preventDefault();let M=$();if(M){let q=new Event(Da);M.dispatchEvent(q)}}}}},w.createElement("label",{"cmdk-label":"",htmlFor:j.inputId,id:j.labelId,style:VS},c),Is(e,A=>w.createElement(Rh.Provider,{value:E},w.createElement(Oh.Provider,{value:j},A))))}),OS=w.forwardRef((e,t)=>{var n,r;let o=Wt(),s=w.useRef(null),i=w.useContext(Mh),a=xo(),c=Lh(e),l=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:i==null?void 0:i.forceMount;rr(()=>{if(!l)return a.item(o,i==null?void 0:i.id)},[l]);let u=$h(o,s,[e.value,e.children,s],e.keywords),f=La(),h=zn(S=>S.value&&S.value===u.current),p=zn(S=>l||a.filter()===!1?!0:S.search?S.filtered.items.get(o)>0:!0);w.useEffect(()=>{let S=s.current;if(!(!S||e.disabled))return S.addEventListener(Da,m),()=>S.removeEventListener(Da,m)},[p,e.onSelect,e.disabled]);function m(){var S,E;g(),(E=(S=c.current).onSelect)==null||E.call(S,u.current)}function g(){f.setState("value",u.current,!0)}if(!p)return null;let{disabled:b,value:v,onSelect:y,forceMount:T,keywords:I,...k}=e;return w.createElement(Pe.div,{ref:On(s,t),...k,id:o,"cmdk-item":"",role:"option","aria-disabled":!!b,"aria-selected":!!h,"data-disabled":!!b,"data-selected":!!h,onPointerMove:b||a.getDisablePointerSelection()?void 0:g,onClick:b?void 0:m},e.children)}),RS=w.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:o,...s}=e,i=Wt(),a=w.useRef(null),c=w.useRef(null),l=Wt(),u=xo(),f=zn(p=>o||u.filter()===!1?!0:p.search?p.filtered.groups.has(i):!0);rr(()=>u.group(i),[]),$h(i,a,[e.value,e.heading,c]);let h=w.useMemo(()=>({id:i,forceMount:o}),[o]);return w.createElement(Pe.div,{ref:On(a,t),...s,"cmdk-group":"",role:"presentation",hidden:f?void 0:!0},n&&w.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:l},n),Is(e,p=>w.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?l:void 0},w.createElement(Mh.Provider,{value:h},p))))}),MS=w.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,o=w.useRef(null),s=zn(i=>!i.search);return!n&&!s?null:w.createElement(Pe.div,{ref:On(o,t),...r,"cmdk-separator":"",role:"separator"})}),DS=w.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,o=e.value!=null,s=La(),i=zn(l=>l.search),a=zn(l=>l.selectedItemId),c=xo();return w.useEffect(()=>{e.value!=null&&s.setState("search",e.value)},[e.value]),w.createElement(Pe.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":a,id:c.inputId,type:"text",value:o?e.value:i,onChange:l=>{o||s.setState("search",l.target.value),n==null||n(l.target.value)}})}),LS=w.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...o}=e,s=w.useRef(null),i=w.useRef(null),a=zn(l=>l.selectedItemId),c=xo();return w.useEffect(()=>{if(i.current&&s.current){let l=i.current,u=s.current,f,h=new ResizeObserver(()=>{f=requestAnimationFrame(()=>{let p=l.offsetHeight;u.style.setProperty("--cmdk-list-height",p.toFixed(1)+"px")})});return h.observe(l),()=>{cancelAnimationFrame(f),h.unobserve(l)}}},[]),w.createElement(Pe.div,{ref:On(s,t),...o,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":a,"aria-label":r,id:c.listId},Is(e,l=>w.createElement("div",{ref:On(i,c.listInnerRef),"cmdk-list-sizer":""},l)))}),$S=w.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:o,contentClassName:s,container:i,...a}=e;return w.createElement(md,{open:n,onOpenChange:r},w.createElement(gd,{container:i},w.createElement(qi,{"cmdk-overlay":"",className:o}),w.createElement(Gi,{"aria-label":e.label,"cmdk-dialog":"",className:s},w.createElement(Dh,{ref:t,...a}))))}),FS=w.forwardRef((e,t)=>zn(n=>n.filtered.count===0)?w.createElement(Pe.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),zS=w.forwardRef((e,t)=>{let{progress:n,children:r,label:o="Loading...",...s}=e;return w.createElement(Pe.div,{ref:t,...s,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":o},Is(e,i=>w.createElement("div",{"aria-hidden":!0},i)))}),Lt=Object.assign(Dh,{List:LS,Item:OS,Input:DS,Group:RS,Separator:MS,Dialog:$S,Empty:FS,Loading:zS});function BS(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function HS(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function Lh(e){let t=w.useRef(e);return rr(()=>{t.current=e}),t}var rr=typeof window>"u"?w.useEffect:w.useLayoutEffect;function Ar(e){let t=w.useRef();return t.current===void 0&&(t.current=e()),t}function zn(e){let t=La(),n=()=>e(t.snapshot());return w.useSyncExternalStore(t.subscribe,n,n)}function $h(e,t,n,r=[]){let o=w.useRef(),s=xo();return rr(()=>{var i;let a=(()=>{var l;for(let u of n){if(typeof u=="string")return u.trim();if(typeof u=="object"&&"current"in u)return u.current?(l=u.current.textContent)==null?void 0:l.trim():o.current}})(),c=r.map(l=>l.trim());s.value(e,a,c),(i=t.current)==null||i.setAttribute(Ir,a),o.current=a}),o}var US=()=>{let[e,t]=w.useState(),n=Ar(()=>new Map);return rr(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,o)=>{n.current.set(r,o),t({})}};function WS(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Is({asChild:e,children:t},n){return e&&w.isValidElement(t)?w.cloneElement(WS(t),{ref:t.ref},n(t.props.children)):n(t)}var VS={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const Fh=w.forwardRef(({className:e,...t},n)=>d.jsx(Lt,{ref:n,className:ae("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t}));Fh.displayName=Lt.displayName;const zh=w.forwardRef(({className:e,...t},n)=>d.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[d.jsx(pe.Search,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),d.jsx(Lt.Input,{ref:n,className:ae("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));zh.displayName=Lt.Input.displayName;const Bh=w.forwardRef(({className:e,...t},n)=>d.jsx(Lt.List,{ref:n,className:ae("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));Bh.displayName=Lt.List.displayName;const Hh=w.forwardRef((e,t)=>d.jsx(Lt.Empty,{ref:t,className:"py-6 text-center text-sm",...e}));Hh.displayName=Lt.Empty.displayName;const Uh=w.forwardRef(({className:e,...t},n)=>d.jsx(Lt.Group,{ref:n,className:ae("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t}));Uh.displayName=Lt.Group.displayName;const KS=w.forwardRef(({className:e,...t},n)=>d.jsx(Lt.Separator,{ref:n,className:ae("-mx-1 h-px bg-border",e),...t}));KS.displayName=Lt.Separator.displayName;const Wh=w.forwardRef(({className:e,...t},n)=>d.jsx(Lt.Item,{ref:n,className:ae("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",e),...t}));Wh.displayName=Lt.Item.displayName;function qS(e,[t,n]){return Math.min(n,Math.max(t,e))}function GS(e,t){return w.useReducer((n,r)=>t[n][r]??n,e)}var $a="ScrollArea",[Vh,YC]=Rn($a),[YS,Zt]=Vh($a),Kh=w.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:s=600,...i}=e,[a,c]=w.useState(null),[l,u]=w.useState(null),[f,h]=w.useState(null),[p,m]=w.useState(null),[g,b]=w.useState(null),[v,y]=w.useState(0),[T,I]=w.useState(0),[k,S]=w.useState(!1),[E,j]=w.useState(!1),_=et(t,L=>c(L)),D=oa(o);return d.jsx(YS,{scope:n,type:r,dir:D,scrollHideDelay:s,scrollArea:a,viewport:l,onViewportChange:u,content:f,onContentChange:h,scrollbarX:p,onScrollbarXChange:m,scrollbarXEnabled:k,onScrollbarXEnabledChange:S,scrollbarY:g,onScrollbarYChange:b,scrollbarYEnabled:E,onScrollbarYEnabledChange:j,onCornerWidthChange:y,onCornerHeightChange:I,children:d.jsx(Pe.div,{dir:D,...i,ref:_,style:{position:"relative","--radix-scroll-area-corner-width":v+"px","--radix-scroll-area-corner-height":T+"px",...e.style}})})});Kh.displayName=$a;var qh="ScrollAreaViewport",Gh=w.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...s}=e,i=Zt(qh,n),a=w.useRef(null),c=et(t,a,i.onViewportChange);return d.jsxs(d.Fragment,{children:[d.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:o}),d.jsx(Pe.div,{"data-radix-scroll-area-viewport":"",...s,ref:c,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style},children:d.jsx("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});Gh.displayName=qh;var wn="ScrollAreaScrollbar",Fa=w.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Zt(wn,e.__scopeScrollArea),{onScrollbarXEnabledChange:s,onScrollbarYEnabledChange:i}=o,a=e.orientation==="horizontal";return w.useEffect(()=>(a?s(!0):i(!0),()=>{a?s(!1):i(!1)}),[a,s,i]),o.type==="hover"?d.jsx(XS,{...r,ref:t,forceMount:n}):o.type==="scroll"?d.jsx(JS,{...r,ref:t,forceMount:n}):o.type==="auto"?d.jsx(Yh,{...r,ref:t,forceMount:n}):o.type==="always"?d.jsx(za,{...r,ref:t}):null});Fa.displayName=wn;var XS=w.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Zt(wn,e.__scopeScrollArea),[s,i]=w.useState(!1);return w.useEffect(()=>{const a=o.scrollArea;let c=0;if(a){const l=()=>{window.clearTimeout(c),i(!0)},u=()=>{c=window.setTimeout(()=>i(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",l),a.addEventListener("pointerleave",u),()=>{window.clearTimeout(c),a.removeEventListener("pointerenter",l),a.removeEventListener("pointerleave",u)}}},[o.scrollArea,o.scrollHideDelay]),d.jsx(Vt,{present:n||s,children:d.jsx(Yh,{"data-state":s?"visible":"hidden",...r,ref:t})})}),JS=w.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Zt(wn,e.__scopeScrollArea),s=e.orientation==="horizontal",i=js(()=>c("SCROLL_END"),100),[a,c]=GS("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return w.useEffect(()=>{if(a==="idle"){const l=window.setTimeout(()=>c("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(l)}},[a,o.scrollHideDelay,c]),w.useEffect(()=>{const l=o.viewport,u=s?"scrollLeft":"scrollTop";if(l){let f=l[u];const h=()=>{const p=l[u];f!==p&&(c("SCROLL"),i()),f=p};return l.addEventListener("scroll",h),()=>l.removeEventListener("scroll",h)}},[o.viewport,s,c,i]),d.jsx(Vt,{present:n||a!=="hidden",children:d.jsx(za,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:Se(e.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:Se(e.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),Yh=w.forwardRef((e,t)=>{const n=Zt(wn,e.__scopeScrollArea),{forceMount:r,...o}=e,[s,i]=w.useState(!1),a=e.orientation==="horizontal",c=js(()=>{if(n.viewport){const l=n.viewport.offsetWidth<n.viewport.scrollWidth,u=n.viewport.offsetHeight<n.viewport.scrollHeight;i(a?l:u)}},10);return Nr(n.viewport,c),Nr(n.content,c),d.jsx(Vt,{present:r||s,children:d.jsx(za,{"data-state":s?"visible":"hidden",...o,ref:t})})}),za=w.forwardRef((e,t)=>{const{orientation:n="vertical",...r}=e,o=Zt(wn,e.__scopeScrollArea),s=w.useRef(null),i=w.useRef(0),[a,c]=w.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),l=ep(a.viewport,a.content),u={...r,sizes:a,onSizesChange:c,hasThumb:l>0&&l<1,onThumbChange:h=>s.current=h,onThumbPointerUp:()=>i.current=0,onThumbPointerDown:h=>i.current=h};function f(h,p){return rC(h,i.current,a,p)}return n==="horizontal"?d.jsx(ZS,{...u,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollLeft,p=tp(h,a,o.dir);s.current.style.transform=`translate3d(${p}px, 0, 0)`}},onWheelScroll:h=>{o.viewport&&(o.viewport.scrollLeft=h)},onDragScroll:h=>{o.viewport&&(o.viewport.scrollLeft=f(h,o.dir))}}):n==="vertical"?d.jsx(QS,{...u,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollTop,p=tp(h,a);s.current.style.transform=`translate3d(0, ${p}px, 0)`}},onWheelScroll:h=>{o.viewport&&(o.viewport.scrollTop=h)},onDragScroll:h=>{o.viewport&&(o.viewport.scrollTop=f(h))}}):null}),ZS=w.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=Zt(wn,e.__scopeScrollArea),[i,a]=w.useState(),c=w.useRef(null),l=et(t,c,s.onScrollbarXChange);return w.useEffect(()=>{c.current&&a(getComputedStyle(c.current))},[c]),d.jsx(Jh,{"data-orientation":"horizontal",...o,ref:l,sizes:n,style:{bottom:0,left:s.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:s.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":_s(n)+"px",...e.style},onThumbPointerDown:u=>e.onThumbPointerDown(u.x),onDragScroll:u=>e.onDragScroll(u.x),onWheelScroll:(u,f)=>{if(s.viewport){const h=s.viewport.scrollLeft+u.deltaX;e.onWheelScroll(h),rp(h,f)&&u.preventDefault()}},onResize:()=>{c.current&&s.viewport&&i&&r({content:s.viewport.scrollWidth,viewport:s.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:Ns(i.paddingLeft),paddingEnd:Ns(i.paddingRight)}})}})}),QS=w.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=Zt(wn,e.__scopeScrollArea),[i,a]=w.useState(),c=w.useRef(null),l=et(t,c,s.onScrollbarYChange);return w.useEffect(()=>{c.current&&a(getComputedStyle(c.current))},[c]),d.jsx(Jh,{"data-orientation":"vertical",...o,ref:l,sizes:n,style:{top:0,right:s.dir==="ltr"?0:void 0,left:s.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":_s(n)+"px",...e.style},onThumbPointerDown:u=>e.onThumbPointerDown(u.y),onDragScroll:u=>e.onDragScroll(u.y),onWheelScroll:(u,f)=>{if(s.viewport){const h=s.viewport.scrollTop+u.deltaY;e.onWheelScroll(h),rp(h,f)&&u.preventDefault()}},onResize:()=>{c.current&&s.viewport&&i&&r({content:s.viewport.scrollHeight,viewport:s.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:Ns(i.paddingTop),paddingEnd:Ns(i.paddingBottom)}})}})}),[eC,Xh]=Vh(wn),Jh=w.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:s,onThumbPointerUp:i,onThumbPointerDown:a,onThumbPositionChange:c,onDragScroll:l,onWheelScroll:u,onResize:f,...h}=e,p=Zt(wn,n),[m,g]=w.useState(null),b=et(t,_=>g(_)),v=w.useRef(null),y=w.useRef(""),T=p.viewport,I=r.content-r.viewport,k=St(u),S=St(c),E=js(f,10);function j(_){if(v.current){const D=_.clientX-v.current.left,L=_.clientY-v.current.top;l({x:D,y:L})}}return w.useEffect(()=>{const _=D=>{const L=D.target;(m==null?void 0:m.contains(L))&&k(D,I)};return document.addEventListener("wheel",_,{passive:!1}),()=>document.removeEventListener("wheel",_,{passive:!1})},[T,m,I,k]),w.useEffect(S,[r,S]),Nr(m,E),Nr(p.content,E),d.jsx(eC,{scope:n,scrollbar:m,hasThumb:o,onThumbChange:St(s),onThumbPointerUp:St(i),onThumbPositionChange:S,onThumbPointerDown:St(a),children:d.jsx(Pe.div,{...h,ref:b,style:{position:"absolute",...h.style},onPointerDown:Se(e.onPointerDown,_=>{_.button===0&&(_.target.setPointerCapture(_.pointerId),v.current=m.getBoundingClientRect(),y.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",p.viewport&&(p.viewport.style.scrollBehavior="auto"),j(_))}),onPointerMove:Se(e.onPointerMove,j),onPointerUp:Se(e.onPointerUp,_=>{const D=_.target;D.hasPointerCapture(_.pointerId)&&D.releasePointerCapture(_.pointerId),document.body.style.webkitUserSelect=y.current,p.viewport&&(p.viewport.style.scrollBehavior=""),v.current=null})})})}),As="ScrollAreaThumb",Zh=w.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Xh(As,e.__scopeScrollArea);return d.jsx(Vt,{present:n||o.hasThumb,children:d.jsx(tC,{ref:t,...r})})}),tC=w.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,s=Zt(As,n),i=Xh(As,n),{onThumbPositionChange:a}=i,c=et(t,f=>i.onThumbChange(f)),l=w.useRef(void 0),u=js(()=>{l.current&&(l.current(),l.current=void 0)},100);return w.useEffect(()=>{const f=s.viewport;if(f){const h=()=>{if(u(),!l.current){const p=oC(f,a);l.current=p,a()}};return a(),f.addEventListener("scroll",h),()=>f.removeEventListener("scroll",h)}},[s.viewport,u,a]),d.jsx(Pe.div,{"data-state":i.hasThumb?"visible":"hidden",...o,ref:c,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:Se(e.onPointerDownCapture,f=>{const p=f.target.getBoundingClientRect(),m=f.clientX-p.left,g=f.clientY-p.top;i.onThumbPointerDown({x:m,y:g})}),onPointerUp:Se(e.onPointerUp,i.onThumbPointerUp)})});Zh.displayName=As;var Ba="ScrollAreaCorner",Qh=w.forwardRef((e,t)=>{const n=Zt(Ba,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?d.jsx(nC,{...e,ref:t}):null});Qh.displayName=Ba;var nC=w.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=Zt(Ba,n),[s,i]=w.useState(0),[a,c]=w.useState(0),l=!!(s&&a);return Nr(o.scrollbarX,()=>{var f;const u=((f=o.scrollbarX)==null?void 0:f.offsetHeight)||0;o.onCornerHeightChange(u),c(u)}),Nr(o.scrollbarY,()=>{var f;const u=((f=o.scrollbarY)==null?void 0:f.offsetWidth)||0;o.onCornerWidthChange(u),i(u)}),l?d.jsx(Pe.div,{...r,ref:t,style:{width:s,height:a,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function Ns(e){return e?parseInt(e,10):0}function ep(e,t){const n=e/t;return isNaN(n)?0:n}function _s(e){const t=ep(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function rC(e,t,n,r="ltr"){const o=_s(n),s=o/2,i=t||s,a=o-i,c=n.scrollbar.paddingStart+i,l=n.scrollbar.size-n.scrollbar.paddingEnd-a,u=n.content-n.viewport,f=r==="ltr"?[0,u]:[u*-1,0];return np([c,l],f)(e)}function tp(e,t,n="ltr"){const r=_s(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,s=t.scrollbar.size-o,i=t.content-t.viewport,a=s-r,c=n==="ltr"?[0,i]:[i*-1,0],l=qS(e,c);return np([0,i],[0,a])(l)}function np(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function rp(e,t){return e>0&&e<t}var oC=(e,t=()=>{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const s={left:e.scrollLeft,top:e.scrollTop},i=n.left!==s.left,a=n.top!==s.top;(i||a)&&t(),n=s,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function js(e,t){const n=St(e),r=w.useRef(0);return w.useEffect(()=>()=>window.clearTimeout(r.current),[]),w.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function Nr(e,t){const n=St(t);hn(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}var op=Kh,sC=Gh,iC=Qh;const sp=w.forwardRef(({className:e,children:t,...n},r)=>d.jsxs(op,{ref:r,className:ae("relative overflow-hidden",e),...n,children:[d.jsx(sC,{className:"h-full w-full rounded-[inherit] overflow-auto",children:t}),d.jsx(ip,{}),d.jsx(iC,{})]}));sp.displayName=op.displayName;const ip=w.forwardRef(({className:e,orientation:t="vertical",...n},r)=>d.jsx(Fa,{ref:r,orientation:t,className:ae("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:d.jsx(Zh,{className:"relative flex-1 rounded-full bg-border"})}));ip.displayName=Fa.displayName;function Ha({thread:e,isActive:t=!1,editingThreadId:n,editingTitle:r="",onSelect:o,onStartEditing:s,onEditingTitleChange:i,onSaveEditing:a,onCancelEditing:c,onShare:l,onDelete:u,showEditTitle:f=!0,showDeleteButton:h=!0,formatDate:p,getDisplayThreadTitle:m,itemClassName:g,activeItemClassName:b,secondaryLine:v}){const y=n===e.threadId,T=x.useMemo(()=>(m==null?void 0:m(e))??e.title??e.threadId,[m,e]),I=()=>o==null?void 0:o(e.threadId),k=S=>s==null?void 0:s(e,S);return d.jsxs("div",{className:ae("flex items-center justify-between rounded px-2 py-1 text-sm hover:bg-muted cursor-pointer",g,t&&(b??"bg-muted/70")),onClick:I,children:[d.jsxs("div",{className:"flex flex-col min-w-0",children:[y?d.jsx("input",{className:"text-sm px-2 py-1 border rounded",value:r,onChange:S=>i==null?void 0:i(S.target.value)}):d.jsx("span",{className:"font-medium truncate",children:T}),v&&d.jsx("span",{className:"text-xs text-muted-foreground truncate",children:v}),p&&e.updatedAt&&d.jsx("span",{className:"text-[10px] text-muted-foreground",children:p(e.updatedAt)})]}),d.jsx("div",{className:"flex items-center gap-1",children:y?d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx(Ke,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:S=>{S.stopPropagation(),a==null||a(e)},children:"Save"}),d.jsx(Ke,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:S=>{S.stopPropagation(),c==null||c(e)},children:"Cancel"})]}):d.jsxs(Aa,{children:[d.jsx(Na,{asChild:!0,children:d.jsxs(Ke,{size:"sm",variant:"ghost",className:"h-8 w-8 p-0 opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100 transition-opacity",onClick:S=>S.stopPropagation(),children:[d.jsx(pe.MoreVertical,{className:"h-4 w-4"}),d.jsx("span",{className:"sr-only",children:"Open menu"})]})}),d.jsxs(Es,{align:"end",children:[f&&d.jsxs(nr,{onClick:S=>{S.stopPropagation(),k(S)},children:[d.jsx(pe.Edit3,{className:"mr-2 h-4 w-4"}),d.jsx("span",{children:"Rename"})]}),l&&d.jsxs(nr,{onClick:S=>{S.stopPropagation(),l(e)},children:[d.jsx(pe.Share2,{className:"mr-2 h-4 w-4"}),d.jsx("span",{children:"Share"})]}),h&&d.jsxs(nr,{onClick:S=>{S.stopPropagation(),u==null||u(e)},className:"text-destructive focus:text-destructive",children:[d.jsx(pe.Trash2,{className:"mr-2 h-4 w-4"}),d.jsx("span",{children:"Delete"})]})]})]})})]})}var Ps="Collapsible",[aC,XC]=Rn(Ps),[lC,Ua]=aC(Ps),ap=w.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:o,disabled:s,onOpenChange:i,...a}=e,[c,l]=qo({prop:r,defaultProp:o??!1,onChange:i,caller:Ps});return d.jsx(lC,{scope:n,disabled:s,contentId:Wt(),open:c,onOpenToggle:w.useCallback(()=>l(u=>!u),[l]),children:d.jsx(Pe.div,{"data-state":Va(c),"data-disabled":s?"":void 0,...a,ref:t})})});ap.displayName=Ps;var lp="CollapsibleTrigger",cp=w.forwardRef((e,t)=>{const{__scopeCollapsible:n,...r}=e,o=Ua(lp,n);return d.jsx(Pe.button,{type:"button","aria-controls":o.contentId,"aria-expanded":o.open||!1,"data-state":Va(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...r,ref:t,onClick:Se(e.onClick,o.onOpenToggle)})});cp.displayName=lp;var Wa="CollapsibleContent",up=w.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Ua(Wa,e.__scopeCollapsible);return d.jsx(Vt,{present:n||o.open,children:({present:s})=>d.jsx(cC,{...r,ref:t,present:s})})});up.displayName=Wa;var cC=w.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:r,children:o,...s}=e,i=Ua(Wa,n),[a,c]=w.useState(r),l=w.useRef(null),u=et(t,l),f=w.useRef(0),h=f.current,p=w.useRef(0),m=p.current,g=i.open||a,b=w.useRef(g),v=w.useRef(void 0);return w.useEffect(()=>{const y=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(y)},[]),hn(()=>{const y=l.current;if(y){v.current=v.current||{transitionDuration:y.style.transitionDuration,animationName:y.style.animationName},y.style.transitionDuration="0s",y.style.animationName="none";const T=y.getBoundingClientRect();f.current=T.height,p.current=T.width,b.current||(y.style.transitionDuration=v.current.transitionDuration,y.style.animationName=v.current.animationName),c(r)}},[i.open,r]),d.jsx(Pe.div,{"data-state":Va(i.open),"data-disabled":i.disabled?"":void 0,id:i.contentId,hidden:!g,...s,ref:u,style:{"--radix-collapsible-content-height":h?`${h}px`:void 0,"--radix-collapsible-content-width":m?`${m}px`:void 0,...e.style},children:g&&o})});function Va(e){return e?"open":"closed"}var uC=ap;const Os=uC,Rs=cp,Ms=up,dp=25,fp=En.threadManagerView,dC=e=>e==="default"||e==="shared",fC=()=>{if(typeof window>"u")return null;try{const e=window.localStorage.getItem(fp);if(dC(e))return e}catch{}return null};function hp({defaultView:e}={}){const[t,n]=x.useState(()=>fC()??e??"default");x.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(fp,t)}catch{}},[t]);const r=x.useCallback(o=>{n(o)},[]);return{view:t,setView:r}}const hC=[{key:"default",label:"My chats"},{key:"shared",label:"Shared with you"}];function Ds({className:e="",showCreateButton:t=!0,showDeleteButton:n=!0,showEditTitle:r=!0,maxHeight:o="400px",customStyles:s={},currentThreadId:i=null,navigateToThread:a,onThreadSelect:c,onThreadCreate:l,onThreadDelete:u,view:f,defaultView:h,onViewChange:p,viewOptions:m,viewState:g,showHeader:b=!0,shareTargets:v,isLoadingShareTargets:y,shareTargetFilter:T,groupBy:I,menuItem:k}){const{chatApi:S,authApi:E}=Vn(),{threads:j,sharedThreads:_,currentThreadId:D,setCurrentThreadId:L,isLoading:W,isLoadingSharedThreads:V,actions:$,shareInFlight:Z,shareStatus:X,clearShareStatus:oe}=ur(),{createThread:U,deleteThread:F,renameThread:G,shareThread:H}=$,{loadThread:A}=Ur(),N=i??D,[R,M]=x.useState(Array.isArray(j)?j:[]),q=x.useRef(R.length>0),J=x.useRef(null),P=x.useRef(0),[K,te]=x.useState(null),[le,he]=x.useState(""),[ue,ge]=x.useState(!1),[be,Be]=x.useState(!1),[Le,je]=x.useState(null),[Fe,tt]=x.useState(""),[mt,ot]=x.useState([]),[ze,Me]=x.useState(!1),Ze=x.useCallback(Y=>he(Y),[]);x.useEffect(()=>{be&&!v&&mt.length===0&&!ze&&(async()=>{Me(!0);try{const Q=(await E.listUsers()).filter(C=>C.id||C.user_id).map(C=>({type:"user",value:C.user_id||C.id||"",id:C.user_id||C.id||"",label:C.name||C.username||C.email||"Unknown User",secondaryLabel:C.name||C.username?C.email:void 0}));ot(Q)}catch(fe){console.error("Failed to load users for sharing:",fe)}finally{Me(!1)}})()},[be,v,mt.length,ze,S]);const rt=v??mt,qe=y??ze,ht=m&&m.length>0?m:hC,xt=hp({defaultView:h}),He=g??xt,st=f??He.view,an=x.useCallback(Y=>{f||He.setView(Y),p==null||p(Y)},[f,p,He]),jt=ht.find(Y=>Y.key===st)??ht[0],ct=Y=>{je(Y),tt(""),Be(!0)},kt=()=>{Be(!1),je(null),tt(""),oe()},Tt=x.useCallback(async Y=>{if(!(!Le||Z)&&Y.id)try{await H(Le,Y.id),setTimeout(()=>kt(),600)}catch(fe){console.error("Failed to share thread:",fe)}},[kt,Z,Le,H]),bt=x.useMemo(()=>{const Y=rt,fe=Fe.trim().toLowerCase();return fe?T?Y.filter(Q=>T(Q,fe)):Y.filter(Q=>`${Q.label} ${Q.secondaryLabel??""}`.toLowerCase().includes(fe)):Y},[v,Fe,T]),Ge=st==="shared",gt=Ge?_:R,ut=x.useMemo(()=>{if(!I||Ge)return null;const Y="Default",fe=C=>{if(!C)return"Older";try{const O=C.endsWith("Z")||C.includes("+")?C:`${C}Z`,z=new Date(O),se=new Date,ie=new Date(se.getFullYear(),se.getMonth(),se.getDate()),Ce=new Date(z.getFullYear(),z.getMonth(),z.getDate()),Te=Math.floor((ie.getTime()-Ce.getTime())/(1e3*60*60*24));return Te===0?"Today":Te===1?"Yesterday":Te<=7?"Last 7 Days":"Older"}catch{return"Older"}};if(I==="project"){const C={};return gt.forEach(O=>{var Ce,Te;const z=((Ce=O.project)==null?void 0:Ce.name)||((Te=O.project)==null?void 0:Te.id)||Y,se=O.menuItem||k||"Default",ie=fe(O.updatedAt);C[z]||(C[z]={}),C[z][se]||(C[z][se]={}),C[z][se][ie]||(C[z][se][ie]=[]),C[z][se][ie].push(O)}),Object.values(C).forEach(O=>{Object.values(O).forEach(z=>{Object.values(z).forEach(se=>{se.sort((ie,Ce)=>new Date(Ce.updatedAt||Ce.createdAt||"").getTime()-new Date(ie.updatedAt||ie.createdAt||"").getTime())})})}),{kind:"project-menu-date",groups:C}}const Q={};return gt.forEach(C=>{let O=Y;I in C&&(O=C[I]||Y),Q[O]||(Q[O]=[]),Q[O].push(C)}),Object.keys(Q).forEach(C=>{Q[C].sort((O,z)=>new Date(z.updatedAt||z.createdAt||"").getTime()-new Date(O.updatedAt||O.createdAt||"").getTime())}),{kind:"flat",groups:Q}},[gt,I,Ge]),$t=Ge?V:W,$e=Ge?"No shared conversations yet":"No conversations yet",Ee=Y=>{const fe=Y.sharedAt?` • ${Gt(Y.sharedAt)}`:"";return`Shared by ${Y.sharedByUserId}${fe}`},Ve=Y=>"sharedByUserId"in Y;x.useEffect(()=>{const Y=Array.isArray(j)?j:[];if(Y.length>0){q.current=!0,M(Y);return}W||(q.current=!1,M(Y))},[j,W]),x.useEffect(()=>{if(!J.current)return;const Y=J.current.querySelector("[data-radix-scroll-area-viewport]");if(!Y)return;let fe=null,Q=null;return fe=requestAnimationFrame(()=>{Q=requestAnimationFrame(()=>{Y.scrollTop=P.current})}),()=>{fe!==null&&cancelAnimationFrame(fe),Q!==null&&cancelAnimationFrame(Q)}},[R]);const dt=async Y=>{try{L(Y),await A(Y),a==null||a(Y),c==null||c(Y)}catch(fe){console.error("Failed to select thread:",fe)}},Et=async()=>{try{ge(!0);const Y=await U();Y&&(l==null||l(Y),a==null||a(Y))}catch(Y){console.error("Failed to create thread:",Y)}finally{ge(!1)}},Ft=async(Y,fe)=>{const Q=Y.threadId;if(confirm("Delete this thread?")){if(J.current){const C=J.current.querySelector("[data-radix-scroll-area-viewport]");C&&(P.current=C.scrollTop)}try{await F(Q),u==null||u(Q)}catch(C){console.error("Failed to delete thread:",C)}}},zt=(Y,fe)=>{fe==null||fe.stopPropagation(),te(Y.threadId),he(Y.title||`Thread ${Y.threadId.slice(0,8)}`)},kn=async Y=>{const fe=typeof Y=="string"?Y:Y.threadId;if(le.trim())try{await G(fe,le.trim()),te(null),he("")}catch(Q){console.error("Failed to update title:",Q)}},Tn=Y=>{te(null),he("")},Gt=Y=>{if(!Y)return"";try{const fe=Y.endsWith("Z")||Y.includes("+")?Y:`${Y}Z`,Q=new Date(fe),O=new Date().getTime()-Q.getTime(),z=Math.floor(O/(1e3*60*60*24));return z===0?Q.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):z===1?"Yesterday":z<7?`${z} days ago`:Q.toLocaleDateString()}catch{return""}},vn=Y=>Y.title||`Thread ${Y.threadId.slice(0,8)}`,ln=Y=>{const fe=vn(Y);return fe.length<=dp?fe:`${fe.slice(0,dp)}...`};return d.jsxs("div",{className:`thread-manager-root flex flex-col h-full ${e} ${s.container||""}`,children:[b&&d.jsxs("div",{className:s.header||"flex flex-col gap-2 px-1 py-0 border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-900 shadow-sm",children:[t&&d.jsx("div",{className:"flex justify-end",children:d.jsxs(Ke,{onClick:Et,disabled:ue||W,className:s.createButton||"px-3 py-2 gap-1",size:"sm",variant:"ghost",title:ue?"Creating...":"New Chat",children:[d.jsx(pe.Edit3,{size:16}),d.jsx("span",{children:"New chat"})]})}),d.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-slate-700 dark:text-slate-200 uppercase tracking-wide leading-tight",children:[d.jsx("span",{children:"Current View"}),d.jsxs(Aa,{children:[d.jsx(Na,{asChild:!0,children:d.jsx(Ke,{variant:"outline",size:"sm",className:"text-[11px] text-slate-700 dark:text-slate-200 border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-900 hover:bg-slate-50 dark:hover:bg-slate-800 px-2 py-0",children:jt.label})}),d.jsx(Es,{align:"start",sideOffset:6,className:"w-40",children:ht.map(Y=>d.jsxs(nr,{className:"justify-between text-[12px]",onClick:fe=>{fe.preventDefault(),an(Y.key)},children:[d.jsx("span",{children:Y.label}),st===Y.key&&d.jsx(pe.Check,{className:"h-3 w-3"})]},Y.key))})]})]})]}),d.jsx(sp,{ref:J,className:`flex-1 min-h-0 ${s.threadList||""}`,style:o?{maxHeight:o}:void 0,children:d.jsx("div",{className:"p-2 space-y-1 pb-4",children:$t?d.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-8 text-slate-400",children:[d.jsx(pe.Loader2,{className:"h-5 w-5 animate-spin"}),d.jsx("span",{className:"text-sm",children:"Loading threads…"})]}):gt.length===0?d.jsxs("div",{className:"text-center py-8 text-slate-400",children:[d.jsx(pe.MessageSquare,{className:"w-8 h-8 mx-auto mb-2 opacity-40 text-slate-500"}),d.jsx("p",{className:"text-sm text-slate-500",children:$e})]}):ut?ut.kind==="project-menu-date"?Object.entries(ut.groups).sort(([Y],[fe])=>{const Q="Default";return Y===Q?1:fe===Q?-1:Y.localeCompare(fe)}).map(([Y,fe])=>d.jsxs(Os,{defaultOpen:!0,className:"group/collapsible",children:[d.jsxs(Rs,{className:"flex items-center w-full px-2 py-1 text-xs font-semibold text-slate-600 hover:text-slate-900 dark:hover:text-slate-200",children:[d.jsx(pe.ChevronRight,{className:"w-3 h-3 mr-1 transition-transform group-data-[state=open]/collapsible:rotate-90"}),Y,d.jsx("span",{className:"ml-auto text-[10px] text-slate-400",children:Object.values(fe).reduce((Q,C)=>Q+Object.values(C).reduce((O,z)=>O+z.length,0),0)})]}),d.jsx(Ms,{children:d.jsx("div",{className:"pl-2 border-l border-slate-100 dark:border-slate-800 ml-1.5 my-1 space-y-1",children:Object.entries(fe).sort(([Q],[C])=>Q.localeCompare(C)).map(([Q,C])=>d.jsxs(Os,{defaultOpen:!0,className:"group/collapsible",children:[d.jsxs(Rs,{className:"flex items-center w-full px-2 py-1 text-[11px] font-medium text-slate-500 hover:text-slate-800 dark:hover:text-slate-200",children:[d.jsx(pe.ChevronRight,{className:"w-3 h-3 mr-1 transition-transform group-data-[state=open]/collapsible:rotate-90"}),Q,d.jsx("span",{className:"ml-auto text-[10px] text-slate-400",children:Object.values(C).reduce((O,z)=>O+z.length,0)})]}),d.jsx(Ms,{children:d.jsx("div",{className:"pl-2 border-l border-slate-100 dark:border-slate-800 ml-1.5 my-1 space-y-1",children:Object.entries(C).sort(([O],[z])=>{const se=["Today","Yesterday","Last 7 Days","Older"],ie=se.indexOf(O),Ce=se.indexOf(z);return ie!==-1||Ce!==-1?(ie===-1?se.length:ie)-(Ce===-1?se.length:Ce):O.localeCompare(z)}).map(([O,z])=>d.jsxs(Os,{defaultOpen:!0,className:"group/collapsible",children:[d.jsxs(Rs,{className:"flex items-center w-full px-2 py-1 text-[10px] font-medium text-slate-400 hover:text-slate-600 dark:hover:text-slate-300",children:[d.jsx(pe.ChevronRight,{className:"w-3 h-3 mr-1 transition-transform group-data-[state=open]/collapsible:rotate-90"}),O,d.jsx("span",{className:"ml-auto text-[10px] text-slate-400",children:z.length})]}),d.jsx(Ms,{children:d.jsx("div",{className:"pl-2 border-l border-slate-100 dark:border-slate-800 ml-1.5 my-1 space-y-1",children:z.map(se=>d.jsx(Ha,{thread:se,isActive:N===se.threadId,editingThreadId:K,editingTitle:le,onSelect:dt,onStartEditing:zt,onEditingTitleChange:Ze,onSaveEditing:ie=>void kn(ie),onCancelEditing:ie=>Tn(),onShare:ie=>ct(ie.threadId),onDelete:ie=>Ft(ie),showEditTitle:r,showDeleteButton:n,formatDate:Gt,getDisplayThreadTitle:ln,itemClassName:s.threadItem,activeItemClassName:s.activeThread},se.threadId))})})]},`${Y}-${Q}-${O}`))})})]},`${Y}-${Q}`))})})]},Y)):Object.entries(ut.groups).sort(([Y],[fe])=>{const Q="Default";return Y===Q?1:fe===Q?-1:Y.localeCompare(fe)}).map(([Y,fe])=>d.jsxs(Os,{defaultOpen:!0,className:"group/collapsible",children:[d.jsxs(Rs,{className:"flex items-center w-full px-2 py-1 text-xs font-medium text-slate-500 hover:text-slate-800 dark:hover:text-slate-200",children:[d.jsx(pe.ChevronRight,{className:"w-3 h-3 mr-1 transition-transform group-data-[state=open]/collapsible:rotate-90"}),Y,d.jsx("span",{className:"ml-auto text-[10px] text-slate-400",children:fe.length})]}),d.jsx(Ms,{children:d.jsx("div",{className:"pl-2 border-l border-slate-100 dark:border-slate-800 ml-1.5 my-1 space-y-1",children:fe.map(Q=>d.jsx(Ha,{thread:Q,isActive:N===Q.threadId,editingThreadId:K,editingTitle:le,onSelect:dt,onStartEditing:zt,onEditingTitleChange:Ze,onSaveEditing:C=>void kn(C),onCancelEditing:C=>Tn(),onShare:C=>ct(C.threadId),onDelete:C=>Ft(C),showEditTitle:r,showDeleteButton:n,formatDate:Gt,getDisplayThreadTitle:ln,itemClassName:s.threadItem,activeItemClassName:s.activeThread},Q.threadId))})})]},Y)):gt.slice().sort((Y,fe)=>new Date(fe.updatedAt||fe.createdAt||"").getTime()-new Date(Y.updatedAt||Y.createdAt||"").getTime()).map(Y=>d.jsx(Ha,{thread:Y,isActive:N===Y.threadId,editingThreadId:K,editingTitle:le,onSelect:dt,onStartEditing:zt,onEditingTitleChange:Ze,onSaveEditing:fe=>void kn(fe),onCancelEditing:fe=>Tn(),onShare:fe=>ct(fe.threadId),onDelete:fe=>Ft(fe),showEditTitle:r,showDeleteButton:n,formatDate:Gt,getDisplayThreadTitle:ln,secondaryLine:Ge&&Ve(Y)?Ee(Y):void 0,itemClassName:s.threadItem,activeItemClassName:s.activeThread},Y.threadId))})}),d.jsx(bd,{open:be,onOpenChange:Y=>!Y&&kt(),children:d.jsxs(Yi,{className:"max-w-md p-0",children:[d.jsx(vd,{children:d.jsx(yd,{children:"Share thread"})}),d.jsxs(Fh,{children:[d.jsx(zh,{autoFocus:!0,value:Fe,onValueChange:Y=>tt(Y),placeholder:"Search for recipients..."}),d.jsxs(Bh,{children:[X&&d.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 text-xs text-muted-foreground",children:[Z&&d.jsx(pe.Loader2,{className:"h-3 w-3 animate-spin"}),d.jsx("span",{className:X.startsWith("Failed")?"text-red-500":X.startsWith("Shared")?"text-emerald-500":"text-slate-600 dark:text-slate-400",children:X})]}),d.jsx(Hh,{children:qe?d.jsxs("span",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[d.jsx(pe.Loader2,{className:"h-4 w-4 animate-spin"}),"Loading recipients…"]}):"No matching recipients found"}),bt.length>0&&d.jsx(Uh,{heading:"Recipients",children:bt.map(Y=>d.jsx(Wh,{onSelect:()=>Tt(Y),children:d.jsxs("div",{className:"flex flex-col items-start text-sm",children:[d.jsx("span",{className:"font-medium",children:Y.label}),Y.secondaryLabel&&d.jsx("span",{className:"text-xs text-muted-foreground",children:Y.secondaryLabel})]})},Y.id))})]})]})]})})]})}function pC({layout:e="sidebar",layoutSize:t="desktop",showThreads:n=!0,className:r="",customStyles:o={},payloadExtras:s={},...i}){const a=u=>{const f="h-full";switch(u){case"phone":return`${f} max-w-none`;case"tablet":return`${f} max-w-4xl mx-auto`;case"half-screen":return`${f} max-w-2xl`;case"desktop":default:return`${f} max-w-7xl mx-auto`}},c=u=>({"--chat-sidebar-width":u==="phone"?"100%":u==="tablet"?"280px":u==="half-screen"?"240px":"320px","--chat-message-max-width":u==="phone"?"95%":u==="tablet"?"90%":u==="half-screen"?"85%":"80%","--chat-input-height":u==="phone"?"120px":"100px"}),l=x.useCallback(u=>{var f;(f=i.onThreadChange)==null||f.call(i,u)},[i]);return e==="fullscreen"?d.jsx(Wr,{...i,onThreadChange:l,children:d.jsx("div",{className:`${a(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:c(t),children:d.jsx(Er,{className:"flex-1",onError:i.onError,enableFileUpload:!0,payloadExtras:s})})}):e==="tabs"?d.jsx(Wr,{...i,onThreadChange:l,children:d.jsx("div",{className:`${a(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:c(t),children:d.jsxs("div",{className:"flex-1 flex min-h-0 overflow-hidden",children:[n&&d.jsx("div",{className:`w-80 border-r flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:d.jsx(Ds,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),d.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:d.jsx(Er,{onError:i.onError,enableFileUpload:!0,payloadExtras:s})})]})})}):d.jsx(Wr,{...i,onThreadChange:l,children:d.jsxs("div",{className:`${a(t)} flex overflow-hidden ${r} ${o.container||""}`,style:c(t),children:[n&&d.jsx("div",{className:`w-80 border-r bg-gray-50 flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:d.jsx(Ds,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),d.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:d.jsx(Er,{onError:i.onError,enableFileUpload:!0,payloadExtras:s})})]})})}function mC({placeholder:e,onMessageSent:t}){const[n,r]=x.useState("chat");return d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsxs("div",{className:"flex border-b border-gray-200 bg-gray-50",children:[d.jsx("button",{onClick:()=>r("chat"),className:`flex-1 px-3 py-2 text-sm font-medium transition-colors ${n==="chat"?"border-b-2 border-slate-800 text-slate-800 bg-white":"text-gray-600 hover:text-gray-800"}`,children:d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx(pe.MessageSquare,{size:14}),"Chat"]})}),d.jsx("button",{onClick:()=>r("threads"),className:`flex-1 px-3 py-2 text-sm font-medium transition-colors ${n==="threads"?"border-b-2 border-slate-800 text-slate-800 bg-white":"text-gray-600 hover:text-gray-800"}`,children:d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx(pe.History,{size:14}),"History"]})})]}),d.jsx("div",{className:"flex-1 min-h-0",children:n==="chat"?d.jsx(Er,{placeholder:e??"Ask Serti AI anything...",className:"h-full",onMessageSent:t}):d.jsx(Ds,{showCreateButton:!0,className:"h-full",onThreadSelect:()=>r("chat")})})]})}function gC({className:e="",placeholder:t,isAuthenticated:n=!0,onMessageSent:r,widgetTitle:o="Serti AI Navigator",widgetSubtitle:s="AI-Powered Assistant",...i}){const[a,c]=x.useState(!1);return n?d.jsx(Wr,{...i,children:d.jsx("div",{className:`fixed bottom-6 right-6 z-[9999] transition-all duration-300 ${e}`,children:d.jsxs("div",{className:`w-96 bg-white rounded-xl shadow-2xl border border-gray-200 overflow-hidden relative ${a?"scale-75":"scale-100"}`,children:[d.jsx("div",{className:"bg-slate-800 text-white p-4 flex-shrink-0",children:d.jsxs("div",{className:"flex items-center justify-between gap-3",children:[d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsxs("div",{className:"relative h-10 w-10 rounded-full bg-gradient-to-br from-slate-500 to-slate-700 border border-white/30 flex items-center justify-center text-white text-sm font-bold",children:["S",d.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-3 w-3 rounded-full border-2 border-slate-800 bg-emerald-400"})]}),d.jsxs("div",{className:"flex flex-col",children:[d.jsx("h3",{className:"text-lg font-semibold leading-tight",children:o}),d.jsx("p",{className:"text-xs text-white/70",children:s})]}),d.jsx("span",{className:"ml-2 inline-flex items-center justify-center rounded-full bg-red-500 px-2 py-0.5 text-[11px] font-semibold leading-none text-white",children:"1"})]}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx(Ke,{variant:"ghost",size:"sm",className:"text-white hover:bg-white/10 h-8 w-8 p-0",title:"Options",children:d.jsx(pe.MoreHorizontal,{size:16})}),d.jsx(Ke,{variant:"ghost",size:"sm",className:"text-white hover:bg-white/10 h-8 w-8 p-0",title:"Compose",children:d.jsx(pe.Edit3,{size:16})}),d.jsx(Ke,{variant:"ghost",size:"sm",onClick:l=>{l.stopPropagation(),c(u=>!u)},className:"text-white hover:bg-white/10 h-8 w-8 p-0",title:a?"Maximize":"Minimize",children:a?d.jsx(pe.Maximize2,{size:14}):d.jsx(pe.Minimize2,{size:14})})]})]})}),!a&&d.jsx("div",{className:"h-96 flex flex-col",children:d.jsx(mC,{placeholder:t,onMessageSent:r})})]})})}):null}function xC({label:e="New chat",children:t,className:n,variant:r="ghost",size:o="sm",...s}){return d.jsxs(Ke,{variant:r,size:o,className:ae("gap-2 rounded-full px-3 font-semibold transition-all hover:scale-[1.01]",n),...s,children:[d.jsx(pe.Edit3,{size:16}),t??e]})}function Ka({message:e,viewMode:t,isStreaming:n=!1,toolConfig:r,expandable:o=!1}){const{toolRenderers:s,toolArtifactRenderers:i}=r??{},a=jo(e),c=e.artifact??null,l=wv(e),f=(l?ac(l):null)??l,h=e.content.find(L=>L.type!=="tool_call"),p=L=>{if(L==null)return null;const W=typeof L=="string"?L:(()=>{try{return JSON.stringify(L,null,2)}catch{return String(L)}})();return d.jsx("pre",{className:"whitespace-pre-wrap break-words font-sans text-xs text-muted-foreground/80 bg-muted/30 p-2 rounded border border-border/50",children:W})},m=L=>p(L),g=()=>{if((f==null?void 0:f.kind)==="generic")return m(f.value);if(!h)return null;if(h.type==="text"){const L=h.text??"";return L?m(L):null}return m(h)},b=()=>(f==null?void 0:f.kind)==="dict"?m(f.data):g(),y=(()=>{if(!s)return;if(a.name){const W=s[a.name];if(W)return W}const L=(f==null?void 0:f.kind)??(l==null?void 0:l.kind);if(L){const W=s[L];if(W)return W}return s.default})(),T=b(),I=!o||t==="expanded",k=(I?y==null?void 0:y({message:e,toolMeta:a,toolPayload:f,viewMode:t,isStreaming:n}):null)??null,E=(()=>{if(!i)return;const L=c==null?void 0:c.type;if(typeof L=="string"){const W=i[L];if(W)return W}return i.default})(),j=E?E({artifact:c,message:e,toolPayload:f,isStreaming:n}):null,_=k??T,D=E?j:null;return d.jsxs("div",{className:"space-y-2",children:[n&&d.jsx(Pw,{artifact:c,showPartialData:!1}),c&&D,I?_:null]})}function bC({submit:e,chatRequest:t,lastCheckpointId:n,lastCheckpointNs:r,onMessageSent:o,onExcelUploadSuccess:s,onError:i,enableMessageEditing:a,messages:c,setPendingAssistantResponse:l,project:u,onEvent:f,activeThreadId:h,ensureValidToken:p}){const{messages:m}=ii(),[g,b]=x.useState(null),[v,y]=x.useState(""),[T,I]=x.useState(null),[k,S]=x.useState(null),[E,j]=x.useState(!1),[_,D]=x.useState(""),L=x.useRef(_),W=x.useRef(null);x.useEffect(()=>{if(!g)if(h){const A=localStorage.getItem(Ao(h));D(A||"")}else D("")},[h,g]);const V=x.useCallback(A=>{D(A),!g&&h&&localStorage.setItem(Ao(h),A)},[h,g]);x.useEffect(()=>{L.current=_},[_]),x.useEffect(()=>{if(!g){W.current=null;return}W.current===null&&(W.current=L.current),V(v??"")},[v,g,V]);const $=x.useCallback(A=>{V(A)},[V]),Z=async(A,N)=>{const R=Array.isArray(N)?{files:N}:N??{},M=R.files??[],q=R.contentParts??[],J=A.trim();if(!(!J&&M.length===0&&q.length===0))try{p&&await p();const P=M.map(async ge=>{try{const be=await Qs.uploadFile(ge);return{file:ge,record:be}}catch(be){throw console.error("Failed to upload file",ge.name,be),new Error(`Failed to upload ${ge.name}`)}}),te=(await Promise.all(P)).map(({record:ge})=>{const be=ge.mime_type;return be.startsWith("image/")?{type:"image_url",url:ge.content_url,mimeType:be,alt:ge.filename}:{type:"file",url:ge.content_url,mimeType:be,name:ge.filename,size:ge.size}}),le=[...q,...te],he=g?(T==null?void 0:T.checkpointId)??n??void 0:n??void 0,ue=g?(T==null?void 0:T.checkpointNs)??r??void 0:r??void 0;await e({text:J||"",contentParts:le,attachments:[],payload:t.payload},{checkpointId:he,checkpointNs:ue,project:u??void 0,edit:!!g,originalMessageId:g??void 0,config:t.config,onEvent:f}),o==null||o(J),l(!0),h&&localStorage.removeItem(Ao(h)),V(""),S(null),b(null),y(""),I(null)}catch(P){const K=(P==null?void 0:P.message)||"Failed to send message";S(K),i==null||i(K),l(!1)}},X=(A,N)=>{N||Z(A,{files:[]})},oe=x.useCallback(async A=>{await e({attachments:[A],payload:t.payload},{checkpointId:n??void 0,checkpointNs:r??void 0,project:u??void 0,config:t.config,onEvent:f}),s==null||s({file:A})},[n,r,t,s,e]),U=x.useCallback((A,N,R)=>{a&&(W.current=_,b(A),y(N),I({checkpointId:(R==null?void 0:R.checkpointId)??null,checkpointNs:(R==null?void 0:R.checkpointNs)??null}),S(null))},[_,a]),F=x.useCallback(()=>{b(null),y(""),I(null),S(null);const A=W.current;A!==null&&D(A),W.current=null},[]),G=x.useCallback(A=>{let N=null;for(let J=A-1;J>=0;J--)if(c[J].role==="user"){N=c[J];break}if(!N)return;const R=Array.isArray(N.content)?N.content:[],q=R.filter(J=>(J==null?void 0:J.type)==="text").map(J=>J.text).join("")||(()=>{try{return JSON.stringify(R,null,2)}catch{return String(R)}})();q&&e({text:q,payload:t.payload},{checkpointId:n??void 0,checkpointNs:r??void 0,edit:!0,originalMessageId:N.id,config:t.config,onEvent:f})},[c,e,n,r,t]);return{editingMessageId:g,editingInitialValue:v,inputError:k,setInputError:S,dismissError:E,setDismissError:j,composerValue:_,handleComposerChange:$,handleSendMessage:Z,handleQuickPrompt:X,handleExcelUpload:oe,startEditing:U,cancelEditing:F,handleRegenerateCb:G,displayMessages:m}}ne.ApiProvider=Kl,ne.ChatApi=Bl,ne.ChatApp=pC,ne.ChatContainer=Er,ne.ChatInput=_a,ne.ChatInputArea=ja,ne.ChatInputRow=ja,ne.ChatInterface=Er,ne.ChatMessagesArea=us,ne.ChatProviders=Wr,ne.ChatWidget=gC,ne.Composer=_a,ne.DEFAULT_TIMEOUT_MS=$l,ne.FileApi=Hl,ne.HISTORY_TIMEOUT_MS=Fl,ne.MarkdownContent=ro,ne.MessageComponent=ta,ne.MessageContent=Hd,ne.MessageList=us,ne.MessageRow=ra,ne.NewChatButton=xC,ne.SETTINGS_STORAGE_KEY=ai,ne.STORAGE_KEYS=En,ne.ThreadManager=Ds,ne.ThreadStateProvider=gc,ne.ThreadsProvider=tc,ne.ToolContent=Ka,ne.applySettings=Og,ne.chatApiClient=An,ne.cn=mp,ne.del=Zs,ne.draftKey=Ao,ne.extractToolContent=Br,ne.fileApiClient=Qs,ne.fileToBase64=ql,ne.formatToolOutput=tg,ne.get=Mt,ne.getChatToken=Xs,ne.getCurrentSettings=Pg,ne.getDefaultApiConfig=Tc,ne.getDefaultChatSettings=Ec,ne.getMessageDomKey=na,ne.httpClient=It,ne.isEnvelope=Zl,ne.isFileLike=ti,ne.loadStoredSettings=Ic,ne.looksLikeMarkdown=nc,ne.normalizeToolPayload=ac,ne.normalizeToolPayloadValue=hr,ne.onChatTokenChanged=Js,ne.parseJsonSafe=dr,ne.post=Dr,ne.pretty=fr,ne.processAttachments=Gl,ne.put=zl,ne.sanitizeForDisplay=zr,ne.saveSettings=Ac,ne.setChatToken=In,ne.unwrap=At,ne.useApi=Vn,ne.useChatController=bC,ne.useHasChatSession=_g,ne.useShallowStableValue=yc,ne.useStream=ii,ne.useThreadHistoryState=fc,ne.useThreadManagerViewState=hp,ne.useThreadState=Ur,ne.useThreadStateUpdater=mc,ne.useThreads=ur,ne.useThreadsState=Ql,Object.defineProperty(ne,Symbol.toStringTag,{value:"Module"})});
128
+ Please report this to https://github.com/markedjs/marked.`,e){const o="<p>An error occurred:</p><pre>"+Ct(r.message+"",!0)+"</pre>";if(t)return Promise.resolve(o);if(n){n(null,o);return}return o}if(t)return Promise.reject(r);if(n){n(r);return}throw r}}function zd(e,t){return(n,r,o)=>{typeof r=="function"&&(o=r,r=null);const s={...r};r={...xe.defaults,...s};const i=ev(r.silent,r.async,o);if(typeof n>"u"||n===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(Jw(r),r.hooks&&(r.hooks.options=r),o){const a=r.highlight;let c;try{r.hooks&&(n=r.hooks.preprocess(n)),c=e(n,r)}catch(f){return i(f)}const l=function(f){let h;if(!f)try{r.walkTokens&&xe.walkTokens(c,r.walkTokens),h=t(c,r),r.hooks&&(h=r.hooks.postprocess(h))}catch(p){f=p}return r.highlight=a,f?i(f):o(null,h)};if(!a||a.length<3||(delete r.highlight,!c.length))return l();let u=0;xe.walkTokens(c,function(f){f.type==="code"&&(u++,setTimeout(()=>{a(f.text,f.lang,function(h,p){if(h)return l(h);p!=null&&p!==f.text&&(f.text=p,f.escaped=!0),u--,u===0&&l()})},0))}),u===0&&l();return}if(r.async)return Promise.resolve(r.hooks?r.hooks.preprocess(n):n).then(a=>e(a,r)).then(a=>r.walkTokens?Promise.all(xe.walkTokens(a,r.walkTokens)).then(()=>a):a).then(a=>t(a,r)).then(a=>r.hooks?r.hooks.postprocess(a):a).catch(i);try{r.hooks&&(n=r.hooks.preprocess(n));const a=e(n,r);r.walkTokens&&xe.walkTokens(a,r.walkTokens);let c=t(a,r);return r.hooks&&(c=r.hooks.postprocess(c)),c}catch(a){return i(a)}}}function xe(e,t,n){return zd(Dn.lex,Ln.parse)(e,t,n)}xe.options=xe.setOptions=function(e){return xe.defaults={...xe.defaults,...e},$w(xe.defaults),xe},xe.getDefaults=Ad,xe.defaults=Zn,xe.use=function(...e){const t=xe.defaults.extensions||{renderers:{},childTokens:{}};e.forEach(n=>{const r={...n};if(r.async=xe.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if(o.renderer){const s=t.renderers[o.name];s?t.renderers[o.name]=function(...i){let a=o.renderer.apply(this,i);return a===!1&&(a=s.apply(this,i)),a}:t.renderers[o.name]=o.renderer}if(o.tokenizer){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");t[o.level]?t[o.level].unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),r.extensions=t),n.renderer){const o=xe.defaults.renderer||new Zi;for(const s in n.renderer){const i=o[s];o[s]=(...a)=>{let c=n.renderer[s].apply(o,a);return c===!1&&(c=i.apply(o,a)),c}}r.renderer=o}if(n.tokenizer){const o=xe.defaults.tokenizer||new Ji;for(const s in n.tokenizer){const i=o[s];o[s]=(...a)=>{let c=n.tokenizer[s].apply(o,a);return c===!1&&(c=i.apply(o,a)),c}}r.tokenizer=o}if(n.hooks){const o=xe.defaults.hooks||new as;for(const s in n.hooks){const i=o[s];as.passThroughHooks.has(s)?o[s]=a=>{if(xe.defaults.async)return Promise.resolve(n.hooks[s].call(o,a)).then(l=>i.call(o,l));const c=n.hooks[s].call(o,a);return i.call(o,c)}:o[s]=(...a)=>{let c=n.hooks[s].apply(o,a);return c===!1&&(c=i.apply(o,a)),c}}r.hooks=o}if(n.walkTokens){const o=xe.defaults.walkTokens;r.walkTokens=function(s){let i=[];return i.push(n.walkTokens.call(this,s)),o&&(i=i.concat(o.call(this,s))),i}}xe.setOptions(r)})},xe.walkTokens=function(e,t){let n=[];for(const r of e)switch(n=n.concat(t.call(xe,r)),r.type){case"table":{for(const o of r.header)n=n.concat(xe.walkTokens(o.tokens,t));for(const o of r.rows)for(const s of o)n=n.concat(xe.walkTokens(s.tokens,t));break}case"list":{n=n.concat(xe.walkTokens(r.items,t));break}default:xe.defaults.extensions&&xe.defaults.extensions.childTokens&&xe.defaults.extensions.childTokens[r.type]?xe.defaults.extensions.childTokens[r.type].forEach(function(o){n=n.concat(xe.walkTokens(r[o],t))}):r.tokens&&(n=n.concat(xe.walkTokens(r.tokens,t)))}return n},xe.parseInline=zd(Dn.lexInline,Ln.parseInline),xe.Parser=Ln,xe.parser=Ln.parse,xe.Renderer=Zi,xe.TextRenderer=$d,xe.Lexer=Dn,xe.lexer=Dn.lex,xe.Tokenizer=Ji,xe.Slugger=Fd,xe.Hooks=as,xe.parse=xe,xe.options,xe.setOptions,xe.use,xe.walkTokens,xe.parseInline,Ln.parse,Dn.lex;function ro({content:e,className:t="",allowHtml:n=!1,style:r}){const o=x.useMemo(()=>{if(!e||typeof e!="string"||e.trim().length===0)return"";try{if(!n){const i=e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");return typeof xe.parse=="function"?xe.parse(i):xe(i)}return typeof xe.parse=="function"?xe.parse(e):xe(e)}catch(i){return console.error("[MarkdownContent] parse error",i),`<pre class="font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words">Error rendering markdown: ${String(i)}</pre>`}},[e,n]),s=x.useMemo(()=>{const i={color:"currentColor",...r};if(r&&r.color){const a=r.color;return{...i,"--tw-prose-body":a,"--tw-prose-headings":a,"--tw-prose-links":a,"--tw-prose-bold":a,"--tw-prose-counters":a,"--tw-prose-bullets":a,"--tw-prose-hr":a,"--tw-prose-quotes":a,"--tw-prose-quote-borders":a,"--tw-prose-captions":a,"--tw-prose-code":a,"--tw-prose-pre-code":a,"--tw-prose-pre-bg":"inherit","--tw-prose-th-borders":a,"--tw-prose-td-borders":a}}return i},[r]);return d.jsx("div",{className:ae("markdown prose prose-sm max-w-none break-words","dark:prose-invert","text-current","prose-headings:text-current prose-p:text-current prose-li:text-current prose-a:text-current prose-strong:text-current","prose-em:text-current prose-blockquote:text-current prose-table:text-current prose-td:text-current prose-th:text-current","prose-pre:font-mono prose-pre:text-xs prose-pre:bg-background/50 prose-pre:border prose-pre:rounded prose-pre:p-3 prose-pre:whitespace-pre prose-pre:overflow-x-auto","prose-code:font-mono prose-code:text-sm prose-code:bg-background/50 prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-current",t),style:s,dangerouslySetInnerHTML:{__html:o}})}function tv({text:e,expanded:t,onExpandedChange:n,previewLength:r,isCompact:o}){const s=Math.max(e.length-r,0),i=e.substring(0,r);return d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("div",{className:ae("text-sm text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:t?d.jsx(ro,{content:e,allowHtml:!1}):d.jsxs("pre",{className:ae("font-sans whitespace-pre-wrap break-words bg-transparent p-0 m-0 text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:[i,"..."]})}),d.jsx(Ke,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-xs !text-[hsl(var(--chat-bubble-user-text))]",onClick:()=>n(!t),children:t?d.jsxs(d.Fragment,{children:[d.jsx(pe.ChevronUp,{className:"h-3 w-3 mr-1"})," Show less"]}):d.jsxs(d.Fragment,{children:[d.jsx(pe.ChevronDown,{className:"h-3 w-3 mr-1"})," Show more (",s," chars)"]})})]})}function nv(e,t,n){const[r,o]=x.useState(e),s=x.useRef(e),i=x.useRef(null);return x.useEffect(()=>{s.current=e;const a=()=>{o(s.current),i.current&&(clearTimeout(i.current),i.current=null)};if(!t||n<=0){a();return}return i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{a()},n),()=>{i.current&&(clearTimeout(i.current),i.current=null)}},[e,t,n]),r}function Bd({message:e,allMessages:t,isToolMessage:n,showToolMessages:r,isToolStreaming:o,contentParts:s,textContent:i,imageParts:a,fileParts:c,interruptPart:l,isStreamingMessage:u,streamingDebounceMs:f,enableStreamingMarkdownBuffer:h,renderStreamingMarkdown:p,handleFileClick:m,uploadingFiles:g,messageRole:b,truncateUserMessages:v,userMessagePreviewLength:y,isUserExpanded:T,setIsUserExpanded:I,isCompactLayout:k,iconForeground:S,toolConfig:E,handleInterruptApprove:j,handleInterruptReject:_,handleInterruptAlternative:D,disableInterruptActions:L,renderArtifactsInline:W=!0}){const V=x.useCallback(()=>d.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted/30 rounded",children:[d.jsx(pe.Loader,{className:"h-4 w-4 text-muted-foreground"}),d.jsx("span",{className:"text-sm text-muted-foreground",children:"File upload"})]}),[]),Z=nv(s,(h??!0)&&u,f??0),X=x.useMemo(()=>Z.filter(P=>P.type==="text"),[Z]),oe=x.useMemo(()=>X.map(P=>P.text??"").join(""),[X]),{artifacts:U}=yd(e,t),F=x.useMemo(()=>{if(!p)return null;const P=ov(oe);return{stablePart:oe.slice(0,P),tailPart:oe.slice(P)}},[oe,p]),G=x.useMemo(()=>{if(!F)return null;const{stablePart:P,tailPart:K}=F;return!P&&!K?null:d.jsxs("div",{className:"space-y-2",children:[P?d.jsx(ro,{content:P,allowHtml:!1}):null,K?d.jsx(ro,{content:K,allowHtml:!1}):null]})},[F]),H=x.useMemo(()=>{if(!p)return Z;const P=[];let K=!1;for(const te of Z){if(te.type==="text"){K||(P.push({type:"text",text:"",__streamingMarkdownAggregate:!0}),K=!0);continue}P.push(te)}return P},[Z,p]),N=(p?H:Z).filter(P=>P.type!=="interrupt"&&P.type!=="image_url"),R=()=>!a||a.length===0?null:d.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:a.map((P,K)=>{const te=P;return d.jsx("div",{className:"relative group",children:d.jsx("img",{src:te.url,alt:te.alt??"Image",loading:"lazy",onClick:()=>window.open(te.url,"_blank"),className:"h-20 w-20 object-cover rounded-md border border-border/50 cursor-pointer hover:opacity-90 transition-opacity"})},K)})}),M=x.useCallback(({part:P,i:K})=>{if(P.type==="text"){if(p)return null;const te=P.text??"",le=te.trim(),he=dr(le);return he&&b!=="tool"?d.jsx(Rw,{data:he},K):b==="user"&&v&&le.length>y?d.jsx(tv,{text:le,expanded:T,onExpandedChange:I,previewLength:y,isCompact:k},K):d.jsx(ro,{content:te,allowHtml:!1},K)}if(P.type==="image_url")return null;if(P.type==="file"){const te=P,le=te.name||"file";return d.jsxs("a",{href:te.url,onClick:he=>m(he,te,K),className:`inline-flex items-center gap-2 rounded px-2 py-1 text-xs bg-gray-100 border hover:bg-gray-200
129
+ dark:bg-background/10 dark:border-border/30 dark:hover:bg-background/20`,children:[g[K]?d.jsx(pe.Loader,{className:"h-4 w-4 animate-spin"}):null,d.jsxs("span",{className:"truncate max-w-[180px]",children:[le,g[K]?" (processing)":""]})]},K)}return null},[m,k,T,b,v,g,y,p,I]),q=i.trim().length>0||a.length>0||c.length>0||N.length>0||!!e.artifact;if(!n&&c.length>0&&!u&&!i&&a.length===0)return V();if(!n&&!q&&!u)return null;if(l){const P=l.value,K=!L,te=j??(()=>{}),le=_??(()=>{});return d.jsx(Id,{interruptPart:l,payload:P,onApprove:te,onReject:le,onSelectAlternative:D,disabled:L,isActive:K})}const J=d.jsxs("div",{className:"space-y-2",children:[b==="assistant"&&r&&d.jsx(Mw,{message:e,allMessages:t,isStreaming:u,toolConfig:E}),N.map((P,K)=>p&&sv(P)?G?d.jsx("div",{className:"space-y-2",children:G},`streaming-md-${K}`):null:d.jsx(M,{part:P,i:K},K)),R(),W&&(U.length>0||!!e.artifact)&&d.jsxs("div",{className:"mt-4 pt-4 border-t border-border/40 space-y-4",children:[!!e.artifact&&d.jsx(Ka,{message:e,viewMode:"expanded",toolConfig:E}),U.map((P,K)=>d.jsx(Ka,{message:{...e,artifact:P},viewMode:"expanded",toolConfig:E},`timeline-art-${K}`))]})]});if(u){const P=i.trim().length>0||a.length>0;return d.jsxs("div",{"aria-busy":"true",role:"status",children:[J,P?d.jsx("span",{className:"inline-block w-2 h-4 ml-0.5 bg-current opacity-70 animate-pulse align-middle","aria-hidden":"true"}):d.jsx(Lw,{className:S})]})}return J}function rv(e){return e?!(oo(e,/```/g)||oo(e,/`/g)||oo(e,/\*\*/g)||oo(e,/__/g)||oo(e,/~~/g)||/[^\\]\[[^\]]*$/.test(e)||/\[[^\]]*\]\([^)]*$/.test(e)):!0}function oo(e,t){const n=e.match(t);return((n==null?void 0:n.length)??0)%2!==0}function ov(e){if(!e)return 0;for(let t=e.length;t>=0;t-=1)if(rv(e.slice(0,t)))return t;return 0}function sv(e){return e.type==="text"&&!!e.__streamingMarkdownAggregate}const iv=Ya.cva("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function av({className:e,variant:t,...n}){return d.jsx("div",{className:ae(iv({variant:t}),e),...n})}function lv({showTimestamp:e,showAgentName:t,isToolMessage:n,isInterruptMessage:r=!1,iconForeground:o,agentName:s,messageIcon:i,customHeaderClass:a,customActionsClass:c,isCompactLayout:l,showActions:u,isEditing:f,messageRole:h,onCopy:p,onEdit:m,onRegenerate:g,showCheckpointControls:b,attemptCount:v,attemptIndex:y,handleOlderAttemptSelect:T,handleNewerAttemptSelect:I,messageCreatedAt:k,copied:S}){return!e&&!t&&!n&&!r?null:d.jsxs("div",{className:ae("flex items-center justify-between mb-2 pb-2",h!=="assistant"&&"border-b border-current/10",l&&"mb-1 pb-1",o,a),children:[d.jsxs("div",{className:"flex items-center gap-2",children:[i,t&&s&&d.jsx("span",{className:ae("font-medium",l?"text-xs":"text-sm"),children:s}),n&&!r&&d.jsx(av,{variant:"outline",className:ae("text-xs flex items-center gap-1",o,"border border-current/40",l&&"text-xs h-4"),children:d.jsx("span",{children:"Tool Output"})}),r&&d.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Interrupt"})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[b&&v>1&&d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("button",{type:"button",className:ae("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",y<v-1?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{y>=v-1||T()},"aria-label":"Older attempt (back in time)",disabled:y>=v-1,children:d.jsx(pe.ChevronLeft,{className:"h-3 w-3"})}),d.jsx("div",{className:"flex items-center gap-2",children:d.jsxs("span",{className:"whitespace-nowrap",children:[v-y," / ",v]})}),d.jsx("button",{type:"button",className:ae("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",y>0?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{y<=0||I()},"aria-label":"Newer attempt (forward in time)",disabled:y<=0,children:d.jsx(pe.ChevronRight,{className:"h-3 w-3"})})]}),e&&k&&d.jsx("time",{className:ae("text-xs opacity-60",o,l&&"text-xs"),dateTime:new Date(k.endsWith("Z")||k.includes("+")?k:`${k}Z`).toISOString(),title:new Date(k.endsWith("Z")||k.includes("+")?k:`${k}Z`).toLocaleString(),children:new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(new Date(k.endsWith("Z")||k.includes("+")?k:`${k}Z`))}),u&&!f&&d.jsxs("div",{className:ae("opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",c),children:[d.jsx("div",{className:"relative",children:d.jsx(Ke,{variant:"ghost",size:"sm",onClick:p,className:ae("h-6 w-6 p-0 hover:bg-foreground/10",o,l&&"h-5 w-5"),"aria-label":"Copy message",title:"Copy message",children:d.jsx(pe.Copy,{className:ae(S?"text-success":o,l?"h-3 w-3":"h-4 w-4")})})}),h==="user"&&m&&d.jsx(Ke,{variant:"ghost",size:"sm",onClick:m,className:ae("h-6 w-6 p-0 hover:bg-foreground/10",o,l&&"h-5 w-5"),"aria-label":"Edit message",children:d.jsx(pe.Edit,{className:ae(o,l?"h-3 w-3":"h-4 w-4")})}),h==="assistant"&&g&&d.jsx(Ke,{variant:"ghost",size:"sm",onClick:g,className:ae("h-6 w-6 p-0 hover:bg-foreground/10",o,l&&"h-5 w-5"),"aria-label":"Regenerate response",children:d.jsx(pe.RotateCcw,{className:ae(o,l?"h-3 w-3":"h-4 w-4")})})]})]})]})}const cv=1,uv=1e6;let Qi=0;function dv(){return Qi=(Qi+1)%Number.MAX_SAFE_INTEGER,Qi.toString()}const ea=new Map,Hd=e=>{if(ea.has(e))return;const t=setTimeout(()=>{ea.delete(e),so({type:"REMOVE_TOAST",toastId:e})},uv);ea.set(e,t)},fv=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,cv)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?Hd(n):e.toasts.forEach(r=>{Hd(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},ls=[];let cs={toasts:[]};function so(e){cs=fv(cs,e),ls.forEach(t=>{t(cs)})}function hv({...e}){const t=dv(),n=o=>so({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>so({type:"DISMISS_TOAST",toastId:t});return so({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function pv(){const[e,t]=w.useState(cs);return w.useEffect(()=>(ls.push(t),()=>{const n=ls.indexOf(t);n>-1&&ls.splice(n,1)}),[e]),{...e,toast:hv,dismiss:n=>so({type:"DISMISS_TOAST",toastId:n})}}function mv(e){const{allowFileOpen:t,currentThreadId:n}=e,{fileApi:r}=Vn(),{toast:o}=pv(),[s,i]=x.useState({}),[a,c]=x.useState(null),[l,u]=x.useState(!1),f=x.useCallback(()=>{u(!1),c(null)},[]),h=x.useCallback(m=>{c(m),u(!0)},[]),p=x.useCallback(async(m,g,b)=>{var v,y;if(!t){m.preventDefault();return}if(s[b]){m.preventDefault();return}try{const T=String(g.url??""),I=T.match(/\/chat\/files\/([^/]+)(?:\/(view|download))?/);if(I){m.preventDefault();const k=I[1],S=g.name||`file_${k}`,E=g.mimeType||"application/octet-stream";h({id:k,name:S,mimeType:E});return}if(T.startsWith("data:")){m.preventDefault(),i(S=>({...S,[b]:!0}));const k=o({title:"Fetching file...",description:"",open:!0});try{const S=await r.listFiles(n??void 0);if(!S||!Array.isArray(S))throw new Error("Invalid file list response");const E=S.find(j=>!j||typeof j!="object"||!((j.filename??"")===(g.name??""))?!1:typeof g.size=="number"&&typeof j.size=="number"?j.size===g.size:!0);if(!(E!=null&&E.id))throw new Error(`File "${g.name}" is not yet available on the server`);if(!E.id||!E.filename)throw new Error("Invalid file data received from server");h({id:E.id,name:g.name||E.filename||`file_${E.id}`,mimeType:g.mimeType||E.mime_type||"application/octet-stream"}),(v=k.update)==null||v.call(k,{id:k.id,title:"Success",description:`Opened ${g.name}`,open:!0})}catch(S){console.error("Failed to fetch server file:",S);const E=S instanceof Error?S.message:"Unknown error occurred";(y=k.update)==null||y.call(k,{id:k.id,title:"Failed",description:E}),o({title:"Failed to fetch file",description:E,open:!0})}finally{i(S=>({...S,[b]:!1}))}}}catch(T){console.error("File click error:",T),i(I=>({...I,[b]:!1}))}},[t,s,o,n,h]);return{uploadingFiles:s,handleFileClick:p,fileViewerOpen:l,currentFileInfo:a,closeFileViewer:f}}function gv(e){return x.useMemo(()=>{const t=e;let n=Array.isArray(t.content)?t.content:[];typeof t.content=="string"&&(n=[{type:"text",text:t.content}]);const r=t.additionalKwargs??{};return{contentParts:n,textContent:rc(n),toolMeta:jo(t),imageParts:n.filter(o=>o.type==="image_url"),fileParts:n.filter(o=>o.type==="file"),interruptParts:n.filter(o=>o.type==="interrupt"),toolRaw:tg(n),isToolStreaming:!!r.toolStreaming}},[e])}const Ud="data:";function xv(e){if(!e)return[];const t=[],n=e.split(/\r?\n/);for(const r of n){const o=r.trim();if(!o||!o.startsWith(Ud))continue;const s=o.slice(Ud.length).trim();if(!s||s.toLowerCase()==="[done]")continue;const i=dr(s);i&&typeof i=="object"&&t.push(i)}return t}function bv(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n&&typeof n=="object"&&n.type==="tool.end")return n}return null}function wv(e){return x.useMemo(()=>{const t=e.content.filter(l=>l.type==="text");if(!t.length)return null;let r=t.flatMap(l=>xv(l.text??""));if(!r.length){const l=t.map(f=>f.text??"").join(`
130
+ `),u=dr(l);u&&typeof u=="object"&&(r=[u])}if(!r.length)return null;const s=bv(r)??r[r.length-1];if(!s)return null;const i=s.output??s.payload??s,a=hr(i),c=Br(a);return c&&typeof c=="object"&&!Array.isArray(c)?{kind:"dict",value:c,data:c,event:s}:{kind:"generic",value:c,event:s}},[e])}const ta=x.memo(function({message:t,messageIndex:n,allMessages:r,isStreamingMessage:o=!1,isEditing:s=!1,showActions:i=!0,showTimestamp:a=!0,showAgentName:c=!0,layoutSize:l="desktop",truncateUserMessages:u=!0,userMessagePreviewLength:f=500,showToolMessages:h=!0,toolConfig:p,customStyles:m={},streamingDebounceMs:g=300,renderStreamingMarkdown:b=!0,enableStreamingMarkdownBuffer:v,onEdit:y,onRegenerate:T,onCopy:I,getInterruptOptions:k,attemptCount:S=1,attemptIndex:E=0,onSelectCheckpoint:j,attemptMetas:_=[],renderArtifactsInline:D=!0}){const[L,W]=x.useState(!1),[V,$]=x.useState(!1),{currentThreadId:Z}=ur(),{respondToInterrupt:X}=Ur(),[oe,U]=x.useState(!1),F=l==="phone"||l==="half-screen",G=t.role,H=G==="interrupt",A=G==="tool"||H,{toolRenderers:N,toolArtifactRenderers:R,getToolExpandable:M}=p??{},q=!(o&&G!=="user"),{uploadingFiles:J,handleFileClick:P,fileViewerOpen:K,currentFileInfo:te,closeFileViewer:le}=mv({allowFileOpen:q,currentThreadId:Z}),he=x.useMemo(()=>{switch(G){case"user":return"text-[hsl(var(--chat-bubble-user-text))]";case"assistant":return"text-[hsl(var(--chat-bubble-ai-text))]";case"interrupt":return"text-[hsl(var(--chat-bubble-ai-text))]";case"tool":return"text-secondary-foreground";case"system":return"text-muted-foreground";default:return"text-[hsl(var(--chat-bubble-ai-text))]"}},[G]),ue=gv(t),{contentParts:ge,imageParts:be,fileParts:Be,textContent:Le,toolRaw:je,isToolStreaming:Fe,interruptParts:tt}=ue,mt=v??g!==0,ot=x.useMemo(()=>tt.length?tt[0]:null,[tt]),ze=x.useCallback(async()=>{const Ee=A?je:Le;async function Ve(dt){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(dt);return}if(navigator.clipboard&&typeof navigator.clipboard.write=="function"&&typeof ClipboardItem<"u"){const Et=new Blob([dt],{type:"text/plain"});await navigator.clipboard.write([new ClipboardItem({"text/plain":Et})]);return}throw new Error("Clipboard API not supported in this context.")}try{await Ve(Ee),W(!0),setTimeout(()=>W(!1),2e3),I==null||I(Ee)}catch(dt){console.error("Failed to copy:",dt)}},[A,je,Le,I]),Me=x.useCallback(async(Ee,Ve)=>{if(!ot)return;if(!oc(ot.id)){console.warn("Interrupt part missing id",ot);return}U(!0);try{const Et=k==null?void 0:k(t);await X(Ee,Ve,Et)}catch(Et){console.error("Failed to respond to interrupt:",Et)}finally{U(!1)}},[ot,X]),Ze=x.useCallback(()=>Me(!0),[Me]),rt=x.useCallback(()=>Me(!1),[Me]),qe=x.useCallback((Ee,Ve)=>{if(!Ve)return;const dt={alternativeId:Ve.id??Ve.label??void 0,alternativeLabel:Ve.label};Me(!0,dt)},[Me]),ht=x.useCallback(()=>{if(!y||!t.id)return;const Ee=(A?je:Le)??"",Ve="type"in t&&t.type==="default_message"?void 0:{checkpointId:t.checkpointId??null,checkpointNs:t.checkpointNs??null};y(t.id,Ee,Ve)},[y,A,je,Le,t]),xt=x.useCallback(()=>{T==null||T(n)},[T,n]),He=x.useCallback(()=>{const Ve=ae(F?"h-3 w-3":"h-4 w-4","opacity-60 flex-shrink-0",he);switch(G){case"user":return d.jsx(pe.User,{className:Ve});case"assistant":return d.jsx(pe.Bot,{className:Ve});case"tool":return d.jsx(pe.Wrench,{className:Ve});case"interrupt":return d.jsx(pe.Bot,{className:Ve});default:return d.jsx(pe.Bot,{className:Ve})}},[F,he,G]),st=x.useCallback(()=>{const Ee="group relative mb-4 flex w-full";switch(G){case"user":return ae(Ee,"justify-end");case"assistant":case"tool":case"system":case"interrupt":return ae(Ee,"justify-start");default:return Ee}},[G]),an=x.useCallback(()=>{const Ee=ae("rounded-lg px-4 py-3 relative min-w-0 max-w-full break-words",F&&"px-3 py-2 text-sm");switch(G){case"user":return ae(Ee,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-user))] text-[hsl(var(--chat-bubble-user-text))]","border border-transparent");case"assistant":return ae(Ee,"w-full md:max-w-[95%]","bg-transparent text-[hsl(var(--chat-bubble-ai-text))]","border-none");case"tool":case"interrupt":return ae(Ee,"w-full md:max-w-[95%] bg-secondary/50 text-secondary-foreground border border-dashed");case"system":return ae(Ee,"w-full md:max-w-[85%] bg-accent/40 text-muted-foreground border");default:return ae(Ee,"w-full md:max-w-[95%]","bg-transparent text-[hsl(var(--chat-bubble-ai-text))]","border-none")}},[F,G]),jt=h||H,ct=d.jsx(Bd,{message:t,allMessages:r,isToolMessage:A,showToolMessages:jt,toolConfig:{toolRenderers:N,toolArtifactRenderers:R,getToolExpandable:M},isToolStreaming:Fe,contentParts:ge,textContent:Le,imageParts:be,fileParts:Be,isStreamingMessage:o,enableStreamingMarkdownBuffer:mt,renderStreamingMarkdown:b,streamingDebounceMs:g,handleFileClick:P,uploadingFiles:J,messageRole:G,truncateUserMessages:u,userMessagePreviewLength:f,isUserExpanded:V,setIsUserExpanded:$,isCompactLayout:F,iconForeground:he,interruptPart:ot,handleInterruptApprove:Ze,handleInterruptReject:rt,handleInterruptAlternative:qe,disableInterruptActions:oe,renderArtifactsInline:D}),kt=x.useMemo(()=>ng(t),[t]),Tt=He(),bt=G==="user"&&(S??1)>1&&typeof j=="function",Ge=(_==null?void 0:_.length)??0,gt=Ge>0&&E<Ge-1?_[E+1]:void 0,ut=Ge>0&&E>0?_[E-1]:void 0,$t=x.useCallback(()=>{!gt||!j||j(gt.id,void 0,!!gt.isLatestAttempt)},[gt,j]),$e=x.useCallback(()=>{!ut||!j||j(ut.id,void 0,!!ut.isLatestAttempt)},[ut,j]);return A&&!h?null:d.jsxs(d.Fragment,{children:[d.jsx("div",{className:ae(st(),m.container),children:d.jsxs("div",{className:ae(an(),m.content),children:[d.jsx(lv,{showTimestamp:a,showAgentName:c,isToolMessage:A,iconForeground:he,agentName:kt,messageIcon:Tt,customHeaderClass:m.header,customActionsClass:m.actions,isCompactLayout:F,showActions:i,isEditing:s,messageRole:G,isInterruptMessage:H,onCopy:ze,onEdit:ht,onRegenerate:xt,showCheckpointControls:bt,attemptCount:S,attemptIndex:E,handleOlderAttemptSelect:$t,handleNewerAttemptSelect:$e,messageCreatedAt:t.createdAt,copied:L}),d.jsx("div",{className:"relative",children:ct}),!(a||c||A)&&i&&!s&&d.jsxs("div",{className:ae("absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",m.actions),children:[d.jsx(Ke,{variant:"ghost",size:"sm",onClick:()=>ze(),className:ae("h-6 w-6 p-0 hover:bg-background/50 text-current",F&&"h-5 w-5"),children:d.jsx(pe.Copy,{className:ae(L?"text-success":"text-current",F?"h-3 w-3":"h-4 w-4")})}),G==="user"&&y&&d.jsx(Ke,{variant:"ghost",size:"sm",onClick:ht,className:ae("h-6 w-6 p-0 hover:bg-background/50 text-current",F&&"h-5 w-5"),children:d.jsx(pe.Edit,{className:ae("text-current",F?"h-3 w-3":"h-4 w-4")})}),G==="assistant"&&T&&d.jsx(Ke,{variant:"ghost",size:"sm",onClick:xt,className:ae("h-6 w-6 p-0 hover:bg-background/50 text-current",F&&"h-5 w-5"),children:d.jsx(pe.RotateCcw,{className:ae("text-current",F?"h-3 w-3":"h-4 w-4")})})]})]})}),te&&d.jsx(jw,{isOpen:K,onClose:le,fileId:te.id,fileName:te.name,mimeType:te.mimeType})]})},(e,t)=>{var c,l,u,f,h,p,m,g;if(t.isStreamingMessage||e.isStreamingMessage||!(e.message.id===t.message.id&&sc(e.message)===sc(t.message)))return!1;const o=["isEditing","showActions","layoutSize","showTimestamp","showAgentName","truncateUserMessages","userMessagePreviewLength","showToolMessages","toolConfig"].every(b=>e[b]===t[b]),s=((c=e.customStyles)==null?void 0:c.container)===((l=t.customStyles)==null?void 0:l.container)&&((u=e.customStyles)==null?void 0:u.content)===((f=t.customStyles)==null?void 0:f.content)&&((h=e.customStyles)==null?void 0:h.actions)===((p=t.customStyles)==null?void 0:p.actions)&&((m=e.customStyles)==null?void 0:m.header)===((g=t.customStyles)==null?void 0:g.header);if(!o||!s)return!1;const i=ni(e.message),a=ni(t.message);return i.length===a.length});ta.displayName="MessageComponent";const vv={checkpoints:[],checkpointMetaByCheckpointId:new Map,timeline:[],messagePreviews:new Map,getLatest:()=>{},getCheckpoint:()=>{},getMessageAttempts:()=>[]},na=(e,t)=>(e==null?void 0:e.id)??`message-${t}`,ra=x.memo(function({message:t,index:n,allMessages:r,streamingAssistantId:o,streamingDebounceMs:s=0,layoutSize:i,enableMessageEditing:a,editingMessageId:c,onEdit:l,onRegenerate:u,onCancelEdit:f,showToolMessages:h,checkpointIndex:p,onSelectCheckpoint:m,getMessageCustomStyles:g,getInterruptOptions:b,toolConfig:v,renderArtifactsInline:y=!0}){const T=na(t,n),S=!!t.__syntheticStreaming||o===t.id&&t.role==="assistant",E=p??vv,j=t.checkpointId??null,{attemptCount:_,attemptIndex:D,attempts:L}=x.useMemo(()=>Cg(t.id,j,E),[t.id,j,E]),W=g==null?void 0:g(t);return d.jsx("div",{className:"relative mb-4 last:mb-0 w-full max-w-full min-w-0","data-message-id":T,style:{minHeight:"60px",containIntrinsicSize:"auto 120px"},children:d.jsx(ta,{message:t,messageIndex:n,allMessages:r,isStreamingMessage:S,renderStreamingMarkdown:S,streamingDebounceMs:s,isEditing:c===t.id,showActions:a,showTimestamp:!1,showAgentName:!0,layoutSize:i,onEdit:l,onRegenerate:()=>u(n),onCancelEdit:f,getInterruptOptions:b,showToolMessages:h,attemptCount:_,attemptIndex:D,attemptMetas:L,onSelectCheckpoint:m,customStyles:W,toolConfig:v,renderArtifactsInline:y})})});ra.displayName="MessageRow";const yv=Object.freeze({}),us=x.forwardRef(({messages:e=[],isStreaming:t,streamingAssistantId:n,streamingDebounceMs:r=0,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onStartReached:a,onEdit:c,onRegenerate:l,onCancelEdit:u,className:f,style:h,emptyMessage:p,followNewMessages:m=!0,isNavigatingCheckpoint:g=!1,onScrollAway:b,onAtBottom:v,showToolMessages:y=!0,toolConfig:T,checkpointIndex:I,activeCheckpointId:k,onSelectCheckpoint:S,showThinkingIndicator:E=!0,getMessageCustomStyles:j,getInterruptOptions:_,pendingInterrupt:D,renderArtifactsInline:L=!0},W)=>{const V=x.useRef(null),$=x.useRef(null),Z=x.useRef(!1),X=x.useRef(!1),[oe,U]=x.useState(!1),F=x.useRef(null);x.useEffect(()=>{if(!D){F.current=null;return}F.current!==D.id&&(U(!1),F.current=D.id)},[D]),x.useEffect(()=>{t&&U(!0)},[t]);const G=x.useMemo(()=>{if(!D)return null;const ue=D.value,ge={interruptId:D.id,type:"user_choice",question:ue==null?void 0:ue.question,alternatives:ue==null?void 0:ue.alternatives};return{id:`interrupt-${D.id}`,role:"interrupt",content:[{type:"interrupt",id:D.id,value:ge}],createdAt:new Date().toISOString(),checkpointId:k??null,checkpointNs:null,expandable:!0}},[D,k]),H=x.useMemo(()=>!G||oe||e.some(ue=>ue.id===G.id)?e:[...e,G],[e,G,oe]),A=x.useMemo(()=>!t||!E||n&&H.some(ge=>ge.id===n)?H:[...H,{id:"thinking-assistant",role:"assistant",content:[{type:"text",text:""}],createdAt:new Date().toISOString(),__syntheticStreaming:!0}],[H,n,E,t]),N=x.useMemo(()=>A.filter(ue=>!og(ue)),[A]),R=x.useMemo(()=>T??yv,[T]),M=x.useCallback(ue=>{b&&b(!ue),v&&v(ue)},[b,v]),q=x.useMemo(()=>{if(a)return async()=>{if(!Z.current){Z.current=!0;try{await a()}finally{Z.current=!1}}}},[a]),J=x.useMemo(()=>!m||g?!1:"auto",[m,g]),P=N.length===0&&p,K=["flex h-full flex-col md:flex-row",f].filter(Boolean).join(" "),te=()=>P?d.jsx("div",{className:"h-full w-full",children:p}):d.jsx("div",{className:"flex h-full items-center justify-center py-8 text-center text-muted-foreground",children:"No messages yet. Start a conversation!"}),le=N.length,he=le>0;return x.useEffect(()=>{var ue,ge;if(le===0){X.current=!1;return}if(!X.current)if(X.current=!0,V.current&&N.length>0){const be=N.length-1;(ge=(ue=V.current).scrollToIndex)==null||ge.call(ue,{index:be,align:"end",behavior:"auto"})}else $.current&&($.current.scrollTop=$.current.scrollHeight)},[le,N.length]),x.useImperativeHandle(W,()=>({scrollToLatest:()=>{var ue,ge;if(V.current&&N.length>0){const be=N.length-1;(ge=(ue=V.current).scrollToIndex)==null||ge.call(ue,{index:be,align:"end",behavior:"auto"})}else $.current&&($.current.scrollTop=$.current.scrollHeight)},scrollToTop:()=>{var ue,ge;V.current&&N.length>0?(ge=(ue=V.current).scrollToIndex)==null||ge.call(ue,{index:0,align:"start",behavior:"auto"}):$.current&&($.current.scrollTop=0)}}),[N]),d.jsx("div",{className:K,style:h,children:d.jsx("div",{className:"relative flex-1 min-h-0 min-w-0",children:he?d.jsx(Wx,{ref:ue=>{V.current=ue},scrollerRef:ue=>{$.current=ue instanceof HTMLDivElement?ue:null},data:N,followOutput:J,overscan:200,increaseViewportBy:{top:100,bottom:200},defaultItemHeight:80,atBottomThreshold:50,startReached:()=>{q&&q()},atBottomStateChange:M,style:{height:"100%",overscrollBehavior:"contain"},computeItemKey:(ue,ge)=>na(ge,ue),itemContent:(ue,ge)=>d.jsx(ra,{message:ge,index:ue,allMessages:e,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onEdit:c,onRegenerate:l,onCancelEdit:u,showToolMessages:y,toolConfig:R,checkpointIndex:I,activeCheckpointId:k,onSelectCheckpoint:S,getMessageCustomStyles:j,getInterruptOptions:_,renderArtifactsInline:L})}):te()})})});us.displayName="MessageList";function Wd(e){const t=e+"CollectionProvider",[n,r]=Rn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=g=>{const{scope:b,children:v}=g,y=x.useRef(null),T=x.useRef(new Map).current;return d.jsx(o,{scope:b,itemMap:T,collectionRef:y,children:v})};i.displayName=t;const a=e+"CollectionSlot",c=sr.createSlot(a),l=x.forwardRef((g,b)=>{const{scope:v,children:y}=g,T=s(a,v),I=et(b,T.collectionRef);return d.jsx(c,{ref:I,children:y})});l.displayName=a;const u=e+"CollectionItemSlot",f="data-radix-collection-item",h=sr.createSlot(u),p=x.forwardRef((g,b)=>{const{scope:v,children:y,...T}=g,I=x.useRef(null),k=et(b,I),S=s(u,v);return x.useEffect(()=>(S.itemMap.set(I,{ref:I,...T}),()=>void S.itemMap.delete(I))),d.jsx(h,{[f]:"",ref:k,children:y})});p.displayName=u;function m(g){const b=s(e+"CollectionConsumer",g);return x.useCallback(()=>{const y=b.collectionRef.current;if(!y)return[];const T=Array.from(y.querySelectorAll(`[${f}]`));return Array.from(b.itemMap.values()).sort((S,E)=>T.indexOf(S.ref.current)-T.indexOf(E.ref.current))},[b.collectionRef,b.itemMap])}return[{Provider:i,Slot:l,ItemSlot:p},m,r]}var Sv=w.createContext(void 0);function oa(e){const t=w.useContext(Sv);return e||t||"ltr"}const Cv=["top","right","bottom","left"],$n=Math.min,Kt=Math.max,ds=Math.round,fs=Math.floor,mn=e=>({x:e,y:e}),kv={left:"right",right:"left",bottom:"top",top:"bottom"},Tv={start:"end",end:"start"};function sa(e,t,n){return Kt(e,$n(t,n))}function Sn(e,t){return typeof e=="function"?e(t):e}function Cn(e){return e.split("-")[0]}function Sr(e){return e.split("-")[1]}function ia(e){return e==="x"?"y":"x"}function aa(e){return e==="y"?"height":"width"}const Ev=new Set(["top","bottom"]);function gn(e){return Ev.has(Cn(e))?"y":"x"}function la(e){return ia(gn(e))}function Iv(e,t,n){n===void 0&&(n=!1);const r=Sr(e),o=la(e),s=aa(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=hs(i)),[i,hs(i)]}function Av(e){const t=hs(e);return[ca(e),t,ca(t)]}function ca(e){return e.replace(/start|end/g,t=>Tv[t])}const Vd=["left","right"],Kd=["right","left"],Nv=["top","bottom"],_v=["bottom","top"];function jv(e,t,n){switch(e){case"top":case"bottom":return n?t?Kd:Vd:t?Vd:Kd;case"left":case"right":return t?Nv:_v;default:return[]}}function Pv(e,t,n,r){const o=Sr(e);let s=jv(Cn(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(ca)))),s}function hs(e){return e.replace(/left|right|bottom|top/g,t=>kv[t])}function Ov(e){return{top:0,right:0,bottom:0,left:0,...e}}function qd(e){return typeof e!="number"?Ov(e):{top:e,right:e,bottom:e,left:e}}function ps(e){const{x:t,y:n,width:r,height:o}=e;return{width:r,height:o,top:n,left:t,right:t+r,bottom:n+o,x:t,y:n}}function Gd(e,t,n){let{reference:r,floating:o}=e;const s=gn(t),i=la(t),a=aa(i),c=Cn(t),l=s==="y",u=r.x+r.width/2-o.width/2,f=r.y+r.height/2-o.height/2,h=r[a]/2-o[a]/2;let p;switch(c){case"top":p={x:u,y:r.y-o.height};break;case"bottom":p={x:u,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:f};break;case"left":p={x:r.x-o.width,y:f};break;default:p={x:r.x,y:r.y}}switch(Sr(t)){case"start":p[i]-=h*(n&&l?-1:1);break;case"end":p[i]+=h*(n&&l?-1:1);break}return p}const Rv=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,a=s.filter(Boolean),c=await(i.isRTL==null?void 0:i.isRTL(t));let l=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:u,y:f}=Gd(l,r,c),h=r,p={},m=0;for(let g=0;g<a.length;g++){const{name:b,fn:v}=a[g],{x:y,y:T,data:I,reset:k}=await v({x:u,y:f,initialPlacement:r,placement:h,strategy:o,middlewareData:p,rects:l,platform:i,elements:{reference:e,floating:t}});u=y??u,f=T??f,p={...p,[b]:{...p[b],...I}},k&&m<=50&&(m++,typeof k=="object"&&(k.placement&&(h=k.placement),k.rects&&(l=k.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):k.rects),{x:u,y:f}=Gd(l,h,c)),g=-1)}return{x:u,y:f,placement:h,strategy:o,middlewareData:p}};async function io(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:c}=e,{boundary:l="clippingAncestors",rootBoundary:u="viewport",elementContext:f="floating",altBoundary:h=!1,padding:p=0}=Sn(t,e),m=qd(p),b=a[h?f==="floating"?"reference":"floating":f],v=ps(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(b)))==null||n?b:b.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:l,rootBoundary:u,strategy:c})),y=f==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.reference,T=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),I=await(s.isElement==null?void 0:s.isElement(T))?await(s.getScale==null?void 0:s.getScale(T))||{x:1,y:1}:{x:1,y:1},k=ps(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:y,offsetParent:T,strategy:c}):y);return{top:(v.top-k.top+m.top)/I.y,bottom:(k.bottom-v.bottom+m.bottom)/I.y,left:(v.left-k.left+m.left)/I.x,right:(k.right-v.right+m.right)/I.x}}const Mv=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:s,platform:i,elements:a,middlewareData:c}=t,{element:l,padding:u=0}=Sn(e,t)||{};if(l==null)return{};const f=qd(u),h={x:n,y:r},p=la(o),m=aa(p),g=await i.getDimensions(l),b=p==="y",v=b?"top":"left",y=b?"bottom":"right",T=b?"clientHeight":"clientWidth",I=s.reference[m]+s.reference[p]-h[p]-s.floating[m],k=h[p]-s.reference[p],S=await(i.getOffsetParent==null?void 0:i.getOffsetParent(l));let E=S?S[T]:0;(!E||!await(i.isElement==null?void 0:i.isElement(S)))&&(E=a.floating[T]||s.floating[m]);const j=I/2-k/2,_=E/2-g[m]/2-1,D=$n(f[v],_),L=$n(f[y],_),W=D,V=E-g[m]-L,$=E/2-g[m]/2+j,Z=sa(W,$,V),X=!c.arrow&&Sr(o)!=null&&$!==Z&&s.reference[m]/2-($<W?D:L)-g[m]/2<0,oe=X?$<W?$-W:$-V:0;return{[p]:h[p]+oe,data:{[p]:Z,centerOffset:$-Z-oe,...X&&{alignmentOffset:oe}},reset:X}}}),Dv=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:s,rects:i,initialPlacement:a,platform:c,elements:l}=t,{mainAxis:u=!0,crossAxis:f=!0,fallbackPlacements:h,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:m="none",flipAlignment:g=!0,...b}=Sn(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const v=Cn(o),y=gn(a),T=Cn(a)===a,I=await(c.isRTL==null?void 0:c.isRTL(l.floating)),k=h||(T||!g?[hs(a)]:Av(a)),S=m!=="none";!h&&S&&k.push(...Pv(a,g,m,I));const E=[a,...k],j=await io(t,b),_=[];let D=((r=s.flip)==null?void 0:r.overflows)||[];if(u&&_.push(j[v]),f){const $=Iv(o,i,I);_.push(j[$[0]],j[$[1]])}if(D=[...D,{placement:o,overflows:_}],!_.every($=>$<=0)){var L,W;const $=(((L=s.flip)==null?void 0:L.index)||0)+1,Z=E[$];if(Z&&(!(f==="alignment"?y!==gn(Z):!1)||D.every(U=>gn(U.placement)===y?U.overflows[0]>0:!0)))return{data:{index:$,overflows:D},reset:{placement:Z}};let X=(W=D.filter(oe=>oe.overflows[0]<=0).sort((oe,U)=>oe.overflows[1]-U.overflows[1])[0])==null?void 0:W.placement;if(!X)switch(p){case"bestFit":{var V;const oe=(V=D.filter(U=>{if(S){const F=gn(U.placement);return F===y||F==="y"}return!0}).map(U=>[U.placement,U.overflows.filter(F=>F>0).reduce((F,G)=>F+G,0)]).sort((U,F)=>U[1]-F[1])[0])==null?void 0:V[0];oe&&(X=oe);break}case"initialPlacement":X=a;break}if(o!==X)return{reset:{placement:X}}}return{}}}};function Yd(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Xd(e){return Cv.some(t=>e[t]>=0)}const Lv=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=Sn(e,t);switch(r){case"referenceHidden":{const s=await io(t,{...o,elementContext:"reference"}),i=Yd(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Xd(i)}}}case"escaped":{const s=await io(t,{...o,altBoundary:!0}),i=Yd(s,n.floating);return{data:{escapedOffsets:i,escaped:Xd(i)}}}default:return{}}}}},Jd=new Set(["left","top"]);async function $v(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=Cn(n),a=Sr(n),c=gn(n)==="y",l=Jd.has(i)?-1:1,u=s&&c?-1:1,f=Sn(t,e);let{mainAxis:h,crossAxis:p,alignmentAxis:m}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof m=="number"&&(p=a==="end"?m*-1:m),c?{x:p*u,y:h*l}:{x:h*l,y:p*u}}const Fv=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:s,placement:i,middlewareData:a}=t,c=await $v(t,e);return i===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+c.x,y:s+c.y,data:{...c,placement:i}}}}},zv=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:s=!0,crossAxis:i=!1,limiter:a={fn:b=>{let{x:v,y}=b;return{x:v,y}}},...c}=Sn(e,t),l={x:n,y:r},u=await io(t,c),f=gn(Cn(o)),h=ia(f);let p=l[h],m=l[f];if(s){const b=h==="y"?"top":"left",v=h==="y"?"bottom":"right",y=p+u[b],T=p-u[v];p=sa(y,p,T)}if(i){const b=f==="y"?"top":"left",v=f==="y"?"bottom":"right",y=m+u[b],T=m-u[v];m=sa(y,m,T)}const g=a.fn({...t,[h]:p,[f]:m});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[h]:s,[f]:i}}}}}},Bv=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:s,middlewareData:i}=t,{offset:a=0,mainAxis:c=!0,crossAxis:l=!0}=Sn(e,t),u={x:n,y:r},f=gn(o),h=ia(f);let p=u[h],m=u[f];const g=Sn(a,t),b=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(c){const T=h==="y"?"height":"width",I=s.reference[h]-s.floating[T]+b.mainAxis,k=s.reference[h]+s.reference[T]-b.mainAxis;p<I?p=I:p>k&&(p=k)}if(l){var v,y;const T=h==="y"?"width":"height",I=Jd.has(Cn(o)),k=s.reference[f]-s.floating[T]+(I&&((v=i.offset)==null?void 0:v[f])||0)+(I?0:b.crossAxis),S=s.reference[f]+s.reference[T]+(I?0:((y=i.offset)==null?void 0:y[f])||0)-(I?b.crossAxis:0);m<k?m=k:m>S&&(m=S)}return{[h]:p,[f]:m}}}},Hv=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:s,platform:i,elements:a}=t,{apply:c=()=>{},...l}=Sn(e,t),u=await io(t,l),f=Cn(o),h=Sr(o),p=gn(o)==="y",{width:m,height:g}=s.floating;let b,v;f==="top"||f==="bottom"?(b=f,v=h===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(v=f,b=h==="end"?"top":"bottom");const y=g-u.top-u.bottom,T=m-u.left-u.right,I=$n(g-u[b],y),k=$n(m-u[v],T),S=!t.middlewareData.shift;let E=I,j=k;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(j=T),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(E=y),S&&!h){const D=Kt(u.left,0),L=Kt(u.right,0),W=Kt(u.top,0),V=Kt(u.bottom,0);p?j=m-2*(D!==0||L!==0?D+L:Kt(u.left,u.right)):E=g-2*(W!==0||V!==0?W+V:Kt(u.top,u.bottom))}await c({...t,availableWidth:j,availableHeight:E});const _=await i.getDimensions(a.floating);return m!==_.width||g!==_.height?{reset:{rects:!0}}:{}}}};function ms(){return typeof window<"u"}function Cr(e){return Zd(e)?(e.nodeName||"").toLowerCase():"#document"}function qt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function xn(e){var t;return(t=(Zd(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Zd(e){return ms()?e instanceof Node||e instanceof qt(e).Node:!1}function on(e){return ms()?e instanceof Element||e instanceof qt(e).Element:!1}function bn(e){return ms()?e instanceof HTMLElement||e instanceof qt(e).HTMLElement:!1}function Qd(e){return!ms()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof qt(e).ShadowRoot}const Uv=new Set(["inline","contents"]);function ao(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=sn(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!Uv.has(o)}const Wv=new Set(["table","td","th"]);function Vv(e){return Wv.has(Cr(e))}const Kv=[":popover-open",":modal"];function gs(e){return Kv.some(t=>{try{return e.matches(t)}catch{return!1}})}const qv=["transform","translate","scale","rotate","perspective"],Gv=["transform","translate","scale","rotate","perspective","filter"],Yv=["paint","layout","strict","content"];function ua(e){const t=da(),n=on(e)?sn(e):e;return qv.some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||Gv.some(r=>(n.willChange||"").includes(r))||Yv.some(r=>(n.contain||"").includes(r))}function Xv(e){let t=Fn(e);for(;bn(t)&&!kr(t);){if(ua(t))return t;if(gs(t))return null;t=Fn(t)}return null}function da(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const Jv=new Set(["html","body","#document"]);function kr(e){return Jv.has(Cr(e))}function sn(e){return qt(e).getComputedStyle(e)}function xs(e){return on(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Fn(e){if(Cr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Qd(e)&&e.host||xn(e);return Qd(t)?t.host:t}function ef(e){const t=Fn(e);return kr(t)?e.ownerDocument?e.ownerDocument.body:e.body:bn(t)&&ao(t)?t:ef(t)}function lo(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=ef(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=qt(o);if(s){const a=fa(i);return t.concat(i,i.visualViewport||[],ao(o)?o:[],a&&n?lo(a):[])}return t.concat(o,lo(o,[],n))}function fa(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function tf(e){const t=sn(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=bn(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=ds(n)!==s||ds(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function ha(e){return on(e)?e:e.contextElement}function Tr(e){const t=ha(e);if(!bn(t))return mn(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=tf(t);let i=(s?ds(n.width):n.width)/r,a=(s?ds(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const Zv=mn(0);function nf(e){const t=qt(e);return!da()||!t.visualViewport?Zv:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Qv(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==qt(e)?!1:t}function Qn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=ha(e);let i=mn(1);t&&(r?on(r)&&(i=Tr(r)):i=Tr(e));const a=Qv(s,n,r)?nf(s):mn(0);let c=(o.left+a.x)/i.x,l=(o.top+a.y)/i.y,u=o.width/i.x,f=o.height/i.y;if(s){const h=qt(s),p=r&&on(r)?qt(r):r;let m=h,g=fa(m);for(;g&&r&&p!==m;){const b=Tr(g),v=g.getBoundingClientRect(),y=sn(g),T=v.left+(g.clientLeft+parseFloat(y.paddingLeft))*b.x,I=v.top+(g.clientTop+parseFloat(y.paddingTop))*b.y;c*=b.x,l*=b.y,u*=b.x,f*=b.y,c+=T,l+=I,m=qt(g),g=fa(m)}}return ps({width:u,height:f,x:c,y:l})}function bs(e,t){const n=xs(e).scrollLeft;return t?t.left+n:Qn(xn(e)).left+n}function rf(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-bs(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function ey(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=xn(r),a=t?gs(t.floating):!1;if(r===i||a&&s)return n;let c={scrollLeft:0,scrollTop:0},l=mn(1);const u=mn(0),f=bn(r);if((f||!f&&!s)&&((Cr(r)!=="body"||ao(i))&&(c=xs(r)),bn(r))){const p=Qn(r);l=Tr(r),u.x=p.x+r.clientLeft,u.y=p.y+r.clientTop}const h=i&&!f&&!s?rf(i,c):mn(0);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+u.x+h.x,y:n.y*l.y-c.scrollTop*l.y+u.y+h.y}}function ty(e){return Array.from(e.getClientRects())}function ny(e){const t=xn(e),n=xs(e),r=e.ownerDocument.body,o=Kt(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Kt(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+bs(e);const a=-n.scrollTop;return sn(r).direction==="rtl"&&(i+=Kt(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const of=25;function ry(e,t){const n=qt(e),r=xn(e),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,a=0,c=0;if(o){s=o.width,i=o.height;const u=da();(!u||u&&t==="fixed")&&(a=o.offsetLeft,c=o.offsetTop)}const l=bs(r);if(l<=0){const u=r.ownerDocument,f=u.body,h=getComputedStyle(f),p=u.compatMode==="CSS1Compat"&&parseFloat(h.marginLeft)+parseFloat(h.marginRight)||0,m=Math.abs(r.clientWidth-f.clientWidth-p);m<=of&&(s-=m)}else l<=of&&(s+=l);return{width:s,height:i,x:a,y:c}}const oy=new Set(["absolute","fixed"]);function sy(e,t){const n=Qn(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=bn(e)?Tr(e):mn(1),i=e.clientWidth*s.x,a=e.clientHeight*s.y,c=o*s.x,l=r*s.y;return{width:i,height:a,x:c,y:l}}function sf(e,t,n){let r;if(t==="viewport")r=ry(e,n);else if(t==="document")r=ny(xn(e));else if(on(t))r=sy(t,n);else{const o=nf(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return ps(r)}function af(e,t){const n=Fn(e);return n===t||!on(n)||kr(n)?!1:sn(n).position==="fixed"||af(n,t)}function iy(e,t){const n=t.get(e);if(n)return n;let r=lo(e,[],!1).filter(a=>on(a)&&Cr(a)!=="body"),o=null;const s=sn(e).position==="fixed";let i=s?Fn(e):e;for(;on(i)&&!kr(i);){const a=sn(i),c=ua(i);!c&&a.position==="fixed"&&(o=null),(s?!c&&!o:!c&&a.position==="static"&&!!o&&oy.has(o.position)||ao(i)&&!c&&af(e,i))?r=r.filter(u=>u!==i):o=a,i=Fn(i)}return t.set(e,r),r}function ay(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?gs(t)?[]:iy(t,this._c):[].concat(n),r],a=i[0],c=i.reduce((l,u)=>{const f=sf(t,u,o);return l.top=Kt(f.top,l.top),l.right=$n(f.right,l.right),l.bottom=$n(f.bottom,l.bottom),l.left=Kt(f.left,l.left),l},sf(t,a,o));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function ly(e){const{width:t,height:n}=tf(e);return{width:t,height:n}}function cy(e,t,n){const r=bn(t),o=xn(t),s=n==="fixed",i=Qn(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const c=mn(0);function l(){c.x=bs(o)}if(r||!r&&!s)if((Cr(t)!=="body"||ao(o))&&(a=xs(t)),r){const p=Qn(t,!0,s,t);c.x=p.x+t.clientLeft,c.y=p.y+t.clientTop}else o&&l();s&&!r&&o&&l();const u=o&&!r&&!s?rf(o,a):mn(0),f=i.left+a.scrollLeft-c.x-u.x,h=i.top+a.scrollTop-c.y-u.y;return{x:f,y:h,width:i.width,height:i.height}}function pa(e){return sn(e).position==="static"}function lf(e,t){if(!bn(e)||sn(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return xn(e)===n&&(n=n.ownerDocument.body),n}function cf(e,t){const n=qt(e);if(gs(e))return n;if(!bn(e)){let o=Fn(e);for(;o&&!kr(o);){if(on(o)&&!pa(o))return o;o=Fn(o)}return n}let r=lf(e,t);for(;r&&Vv(r)&&pa(r);)r=lf(r,t);return r&&kr(r)&&pa(r)&&!ua(r)?n:r||Xv(e)||n}const uy=async function(e){const t=this.getOffsetParent||cf,n=this.getDimensions,r=await n(e.floating);return{reference:cy(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function dy(e){return sn(e).direction==="rtl"}const fy={convertOffsetParentRelativeRectToViewportRelativeRect:ey,getDocumentElement:xn,getClippingRect:ay,getOffsetParent:cf,getElementRects:uy,getClientRects:ty,getDimensions:ly,getScale:Tr,isElement:on,isRTL:dy};function uf(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function hy(e,t){let n=null,r;const o=xn(e);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function i(a,c){a===void 0&&(a=!1),c===void 0&&(c=1),s();const l=e.getBoundingClientRect(),{left:u,top:f,width:h,height:p}=l;if(a||t(),!h||!p)return;const m=fs(f),g=fs(o.clientWidth-(u+h)),b=fs(o.clientHeight-(f+p)),v=fs(u),T={rootMargin:-m+"px "+-g+"px "+-b+"px "+-v+"px",threshold:Kt(0,$n(1,c))||1};let I=!0;function k(S){const E=S[0].intersectionRatio;if(E!==c){if(!I)return i();E?i(!1,E):r=setTimeout(()=>{i(!1,1e-7)},1e3)}E===1&&!uf(l,e.getBoundingClientRect())&&i(),I=!1}try{n=new IntersectionObserver(k,{...T,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,T)}n.observe(e)}return i(!0),s}function py(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:c=!1}=r,l=ha(e),u=o||s?[...l?lo(l):[],...lo(t)]:[];u.forEach(v=>{o&&v.addEventListener("scroll",n,{passive:!0}),s&&v.addEventListener("resize",n)});const f=l&&a?hy(l,n):null;let h=-1,p=null;i&&(p=new ResizeObserver(v=>{let[y]=v;y&&y.target===l&&p&&(p.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var T;(T=p)==null||T.observe(t)})),n()}),l&&!c&&p.observe(l),p.observe(t));let m,g=c?Qn(e):null;c&&b();function b(){const v=Qn(e);g&&!uf(g,v)&&n(),g=v,m=requestAnimationFrame(b)}return n(),()=>{var v;u.forEach(y=>{o&&y.removeEventListener("scroll",n),s&&y.removeEventListener("resize",n)}),f==null||f(),(v=p)==null||v.disconnect(),p=null,c&&cancelAnimationFrame(m)}}const my=Fv,gy=zv,xy=Dv,by=Hv,wy=Lv,df=Mv,vy=Bv,yy=(e,t,n)=>{const r=new Map,o={platform:fy,...n},s={...o.platform,_c:r};return Rv(e,t,{...o,platform:s})};var Sy=typeof document<"u",Cy=function(){},ws=Sy?x.useLayoutEffect:Cy;function vs(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!vs(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const s=o[r];if(!(s==="_owner"&&e.$$typeof)&&!vs(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function ff(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function hf(e,t){const n=ff(e);return Math.round(t*n)/n}function ma(e){const t=w.useRef(e);return ws(()=>{t.current=e}),t}function ky(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:s,floating:i}={},transform:a=!0,whileElementsMounted:c,open:l}=e,[u,f]=w.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[h,p]=w.useState(r);vs(h,r)||p(r);const[m,g]=w.useState(null),[b,v]=w.useState(null),y=w.useCallback(U=>{U!==S.current&&(S.current=U,g(U))},[]),T=w.useCallback(U=>{U!==E.current&&(E.current=U,v(U))},[]),I=s||m,k=i||b,S=w.useRef(null),E=w.useRef(null),j=w.useRef(u),_=c!=null,D=ma(c),L=ma(o),W=ma(l),V=w.useCallback(()=>{if(!S.current||!E.current)return;const U={placement:t,strategy:n,middleware:h};L.current&&(U.platform=L.current),yy(S.current,E.current,U).then(F=>{const G={...F,isPositioned:W.current!==!1};$.current&&!vs(j.current,G)&&(j.current=G,Ja.flushSync(()=>{f(G)}))})},[h,t,n,L,W]);ws(()=>{l===!1&&j.current.isPositioned&&(j.current.isPositioned=!1,f(U=>({...U,isPositioned:!1})))},[l]);const $=w.useRef(!1);ws(()=>($.current=!0,()=>{$.current=!1}),[]),ws(()=>{if(I&&(S.current=I),k&&(E.current=k),I&&k){if(D.current)return D.current(I,k,V);V()}},[I,k,V,D,_]);const Z=w.useMemo(()=>({reference:S,floating:E,setReference:y,setFloating:T}),[y,T]),X=w.useMemo(()=>({reference:I,floating:k}),[I,k]),oe=w.useMemo(()=>{const U={position:n,left:0,top:0};if(!X.floating)return U;const F=hf(X.floating,u.x),G=hf(X.floating,u.y);return a?{...U,transform:"translate("+F+"px, "+G+"px)",...ff(X.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:F,top:G}},[n,a,X.floating,u.x,u.y]);return w.useMemo(()=>({...u,update:V,refs:Z,elements:X,floatingStyles:oe}),[u,V,Z,X,oe])}const Ty=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?df({element:r.current,padding:o}).fn(n):{}:r?df({element:r,padding:o}).fn(n):{}}}},Ey=(e,t)=>({...my(e),options:[e,t]}),Iy=(e,t)=>({...gy(e),options:[e,t]}),Ay=(e,t)=>({...vy(e),options:[e,t]}),Ny=(e,t)=>({...xy(e),options:[e,t]}),_y=(e,t)=>({...by(e),options:[e,t]}),jy=(e,t)=>({...wy(e),options:[e,t]}),Py=(e,t)=>({...Ty(e),options:[e,t]});var Oy="Arrow",pf=w.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return d.jsx(Pe.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:d.jsx("polygon",{points:"0,0 30,0 15,10"})})});pf.displayName=Oy;var Ry=pf;function My(e){const[t,n]=w.useState(void 0);return hn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let i,a;if("borderBoxSize"in s){const c=s.borderBoxSize,l=Array.isArray(c)?c[0]:c;i=l.inlineSize,a=l.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var ga="Popper",[mf,gf]=Rn(ga),[Dy,xf]=mf(ga),bf=e=>{const{__scopePopper:t,children:n}=e,[r,o]=w.useState(null);return d.jsx(Dy,{scope:t,anchor:r,onAnchorChange:o,children:n})};bf.displayName=ga;var wf="PopperAnchor",vf=w.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=xf(wf,n),i=w.useRef(null),a=et(t,i),c=w.useRef(null);return w.useEffect(()=>{const l=c.current;c.current=(r==null?void 0:r.current)||i.current,l!==c.current&&s.onAnchorChange(c.current)}),r?null:d.jsx(Pe.div,{...o,ref:a})});vf.displayName=wf;var xa="PopperContent",[Ly,$y]=mf(xa),yf=w.forwardRef((e,t)=>{var J,P,K,te,le,he;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:c=!0,collisionBoundary:l=[],collisionPadding:u=0,sticky:f="partial",hideWhenDetached:h=!1,updatePositionStrategy:p="optimized",onPlaced:m,...g}=e,b=xf(xa,n),[v,y]=w.useState(null),T=et(t,ue=>y(ue)),[I,k]=w.useState(null),S=My(I),E=(S==null?void 0:S.width)??0,j=(S==null?void 0:S.height)??0,_=r+(s!=="center"?"-"+s:""),D=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},L=Array.isArray(l)?l:[l],W=L.length>0,V={padding:D,boundary:L.filter(zy),altBoundary:W},{refs:$,floatingStyles:Z,placement:X,isPositioned:oe,middlewareData:U}=ky({strategy:"fixed",placement:_,whileElementsMounted:(...ue)=>py(...ue,{animationFrame:p==="always"}),elements:{reference:b.anchor},middleware:[Ey({mainAxis:o+j,alignmentAxis:i}),c&&Iy({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?Ay():void 0,...V}),c&&Ny({...V}),_y({...V,apply:({elements:ue,rects:ge,availableWidth:be,availableHeight:Be})=>{const{width:Le,height:je}=ge.reference,Fe=ue.floating.style;Fe.setProperty("--radix-popper-available-width",`${be}px`),Fe.setProperty("--radix-popper-available-height",`${Be}px`),Fe.setProperty("--radix-popper-anchor-width",`${Le}px`),Fe.setProperty("--radix-popper-anchor-height",`${je}px`)}}),I&&Py({element:I,padding:a}),By({arrowWidth:E,arrowHeight:j}),h&&jy({strategy:"referenceHidden",...V})]}),[F,G]=kf(X),H=St(m);hn(()=>{oe&&(H==null||H())},[oe,H]);const A=(J=U.arrow)==null?void 0:J.x,N=(P=U.arrow)==null?void 0:P.y,R=((K=U.arrow)==null?void 0:K.centerOffset)!==0,[M,q]=w.useState();return hn(()=>{v&&q(window.getComputedStyle(v).zIndex)},[v]),d.jsx("div",{ref:$.setFloating,"data-radix-popper-content-wrapper":"",style:{...Z,transform:oe?Z.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:M,"--radix-popper-transform-origin":[(te=U.transformOrigin)==null?void 0:te.x,(le=U.transformOrigin)==null?void 0:le.y].join(" "),...((he=U.hide)==null?void 0:he.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:d.jsx(Ly,{scope:n,placedSide:F,onArrowChange:k,arrowX:A,arrowY:N,shouldHideArrow:R,children:d.jsx(Pe.div,{"data-side":F,"data-align":G,...g,ref:T,style:{...g.style,animation:oe?void 0:"none"}})})})});yf.displayName=xa;var Sf="PopperArrow",Fy={top:"bottom",right:"left",bottom:"top",left:"right"},Cf=w.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=$y(Sf,r),i=Fy[s.placedSide];return d.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:d.jsx(Ry,{...o,ref:n,style:{...o.style,display:"block"}})})});Cf.displayName=Sf;function zy(e){return e!==null}var By=e=>({name:"transformOrigin",options:e,fn(t){var b,v,y;const{placement:n,rects:r,middlewareData:o}=t,i=((b=o.arrow)==null?void 0:b.centerOffset)!==0,a=i?0:e.arrowWidth,c=i?0:e.arrowHeight,[l,u]=kf(n),f={start:"0%",center:"50%",end:"100%"}[u],h=(((v=o.arrow)==null?void 0:v.x)??0)+a/2,p=(((y=o.arrow)==null?void 0:y.y)??0)+c/2;let m="",g="";return l==="bottom"?(m=i?f:`${h}px`,g=`${-c}px`):l==="top"?(m=i?f:`${h}px`,g=`${r.floating.height+c}px`):l==="right"?(m=`${-c}px`,g=i?f:`${p}px`):l==="left"&&(m=`${r.floating.width+c}px`,g=i?f:`${p}px`),{data:{x:m,y:g}}}});function kf(e){const[t,n="center"]=e.split("-");return[t,n]}var Hy=bf,Uy=vf,Wy=yf,Vy=Cf,ba="rovingFocusGroup.onEntryFocus",Ky={bubbles:!1,cancelable:!0},co="RovingFocusGroup",[wa,Tf,qy]=Wd(co),[Gy,Ef]=Rn(co,[qy]),[Yy,Xy]=Gy(co),If=w.forwardRef((e,t)=>d.jsx(wa.Provider,{scope:e.__scopeRovingFocusGroup,children:d.jsx(wa.Slot,{scope:e.__scopeRovingFocusGroup,children:d.jsx(Jy,{...e,ref:t})})}));If.displayName=co;var Jy=w.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:c,onEntryFocus:l,preventScrollOnEntryFocus:u=!1,...f}=e,h=w.useRef(null),p=et(t,h),m=oa(s),[g,b]=qo({prop:i,defaultProp:a??null,onChange:c,caller:co}),[v,y]=w.useState(!1),T=St(l),I=Tf(n),k=w.useRef(!1),[S,E]=w.useState(0);return w.useEffect(()=>{const j=h.current;if(j)return j.addEventListener(ba,T),()=>j.removeEventListener(ba,T)},[T]),d.jsx(Yy,{scope:n,orientation:r,dir:m,loop:o,currentTabStopId:g,onItemFocus:w.useCallback(j=>b(j),[b]),onItemShiftTab:w.useCallback(()=>y(!0),[]),onFocusableItemAdd:w.useCallback(()=>E(j=>j+1),[]),onFocusableItemRemove:w.useCallback(()=>E(j=>j-1),[]),children:d.jsx(Pe.div,{tabIndex:v||S===0?-1:0,"data-orientation":r,...f,ref:p,style:{outline:"none",...e.style},onMouseDown:Se(e.onMouseDown,()=>{k.current=!0}),onFocus:Se(e.onFocus,j=>{const _=!k.current;if(j.target===j.currentTarget&&_&&!v){const D=new CustomEvent(ba,Ky);if(j.currentTarget.dispatchEvent(D),!D.defaultPrevented){const L=I().filter(X=>X.focusable),W=L.find(X=>X.active),V=L.find(X=>X.id===g),Z=[W,V,...L].filter(Boolean).map(X=>X.ref.current);_f(Z,u)}}k.current=!1}),onBlur:Se(e.onBlur,()=>y(!1))})})}),Af="RovingFocusGroupItem",Nf=w.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,c=Wt(),l=s||c,u=Xy(Af,n),f=u.currentTabStopId===l,h=Tf(n),{onFocusableItemAdd:p,onFocusableItemRemove:m,currentTabStopId:g}=u;return w.useEffect(()=>{if(r)return p(),()=>m()},[r,p,m]),d.jsx(wa.ItemSlot,{scope:n,id:l,focusable:r,active:o,children:d.jsx(Pe.span,{tabIndex:f?0:-1,"data-orientation":u.orientation,...a,ref:t,onMouseDown:Se(e.onMouseDown,b=>{r?u.onItemFocus(l):b.preventDefault()}),onFocus:Se(e.onFocus,()=>u.onItemFocus(l)),onKeyDown:Se(e.onKeyDown,b=>{if(b.key==="Tab"&&b.shiftKey){u.onItemShiftTab();return}if(b.target!==b.currentTarget)return;const v=e0(b,u.orientation,u.dir);if(v!==void 0){if(b.metaKey||b.ctrlKey||b.altKey||b.shiftKey)return;b.preventDefault();let T=h().filter(I=>I.focusable).map(I=>I.ref.current);if(v==="last")T.reverse();else if(v==="prev"||v==="next"){v==="prev"&&T.reverse();const I=T.indexOf(b.currentTarget);T=u.loop?t0(T,I+1):T.slice(I+1)}setTimeout(()=>_f(T))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:g!=null}):i})})});Nf.displayName=Af;var Zy={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Qy(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function e0(e,t,n){const r=Qy(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Zy[r]}function _f(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function t0(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var n0=If,r0=Nf,va=["Enter"," "],o0=["ArrowDown","PageUp","Home"],jf=["ArrowUp","PageDown","End"],s0=[...o0,...jf],i0={ltr:[...va,"ArrowRight"],rtl:[...va,"ArrowLeft"]},a0={ltr:["ArrowLeft"],rtl:["ArrowRight"]},uo="Menu",[fo,l0,c0]=Wd(uo),[er,Pf]=Rn(uo,[c0,gf,Ef]),ys=gf(),Of=Ef(),[u0,tr]=er(uo),[d0,ho]=er(uo),Rf=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:s,modal:i=!0}=e,a=ys(t),[c,l]=w.useState(null),u=w.useRef(!1),f=St(s),h=oa(o);return w.useEffect(()=>{const p=()=>{u.current=!0,document.addEventListener("pointerdown",m,{capture:!0,once:!0}),document.addEventListener("pointermove",m,{capture:!0,once:!0})},m=()=>u.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",m,{capture:!0}),document.removeEventListener("pointermove",m,{capture:!0})}},[]),d.jsx(Hy,{...a,children:d.jsx(u0,{scope:t,open:n,onOpenChange:f,content:c,onContentChange:l,children:d.jsx(d0,{scope:t,onClose:w.useCallback(()=>f(!1),[f]),isUsingKeyboardRef:u,dir:h,modal:i,children:r})})})};Rf.displayName=uo;var f0="MenuAnchor",ya=w.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=ys(n);return d.jsx(Uy,{...o,...r,ref:t})});ya.displayName=f0;var Sa="MenuPortal",[h0,Mf]=er(Sa,{forceMount:void 0}),Df=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,s=tr(Sa,t);return d.jsx(h0,{scope:t,forceMount:n,children:d.jsx(Vt,{present:n||s.open,children:d.jsx(Di,{asChild:!0,container:o,children:r})})})};Df.displayName=Sa;var Jt="MenuContent",[p0,Ca]=er(Jt),Lf=w.forwardRef((e,t)=>{const n=Mf(Jt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=tr(Jt,e.__scopeMenu),i=ho(Jt,e.__scopeMenu);return d.jsx(fo.Provider,{scope:e.__scopeMenu,children:d.jsx(Vt,{present:r||s.open,children:d.jsx(fo.Slot,{scope:e.__scopeMenu,children:i.modal?d.jsx(m0,{...o,ref:t}):d.jsx(g0,{...o,ref:t})})})})}),m0=w.forwardRef((e,t)=>{const n=tr(Jt,e.__scopeMenu),r=w.useRef(null),o=et(t,r);return w.useEffect(()=>{const s=r.current;if(s)return Zu(s)},[]),d.jsx(ka,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Se(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),g0=w.forwardRef((e,t)=>{const n=tr(Jt,e.__scopeMenu);return d.jsx(ka,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),x0=sr.createSlot("MenuContent.ScrollLock"),ka=w.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:s,onCloseAutoFocus:i,disableOutsidePointerEvents:a,onEntryFocus:c,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onInteractOutside:h,onDismiss:p,disableOutsideScroll:m,...g}=e,b=tr(Jt,n),v=ho(Jt,n),y=ys(n),T=Of(n),I=l0(n),[k,S]=w.useState(null),E=w.useRef(null),j=et(t,E,b.onContentChange),_=w.useRef(0),D=w.useRef(""),L=w.useRef(0),W=w.useRef(null),V=w.useRef("right"),$=w.useRef(0),Z=m?Hi:w.Fragment,X=m?{as:x0,allowPinchZoom:!0}:void 0,oe=F=>{var J,P;const G=D.current+F,H=I().filter(K=>!K.disabled),A=document.activeElement,N=(J=H.find(K=>K.ref.current===A))==null?void 0:J.textValue,R=H.map(K=>K.textValue),M=N0(R,G,N),q=(P=H.find(K=>K.textValue===M))==null?void 0:P.ref.current;(function K(te){D.current=te,window.clearTimeout(_.current),te!==""&&(_.current=window.setTimeout(()=>K(""),1e3))})(G),q&&setTimeout(()=>q.focus())};w.useEffect(()=>()=>window.clearTimeout(_.current),[]),Lu();const U=w.useCallback(F=>{var H,A;return V.current===((H=W.current)==null?void 0:H.side)&&j0(F,(A=W.current)==null?void 0:A.area)},[]);return d.jsx(p0,{scope:n,searchRef:D,onItemEnter:w.useCallback(F=>{U(F)&&F.preventDefault()},[U]),onItemLeave:w.useCallback(F=>{var G;U(F)||((G=E.current)==null||G.focus(),S(null))},[U]),onTriggerLeave:w.useCallback(F=>{U(F)&&F.preventDefault()},[U]),pointerGraceTimerRef:L,onPointerGraceIntentChange:w.useCallback(F=>{W.current=F},[]),children:d.jsx(Z,{...X,children:d.jsx(Mi,{asChild:!0,trapped:o,onMountAutoFocus:Se(s,F=>{var G;F.preventDefault(),(G=E.current)==null||G.focus({preventScroll:!0})}),onUnmountAutoFocus:i,children:d.jsx(Pi,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onInteractOutside:h,onDismiss:p,children:d.jsx(n0,{asChild:!0,...T,dir:v.dir,orientation:"vertical",loop:r,currentTabStopId:k,onCurrentTabStopIdChange:S,onEntryFocus:Se(c,F=>{v.isUsingKeyboardRef.current||F.preventDefault()}),preventScrollOnEntryFocus:!0,children:d.jsx(Wy,{role:"menu","aria-orientation":"vertical","data-state":eh(b.open),"data-radix-menu-content":"",dir:v.dir,...y,...g,ref:j,style:{outline:"none",...g.style},onKeyDown:Se(g.onKeyDown,F=>{const H=F.target.closest("[data-radix-menu-content]")===F.currentTarget,A=F.ctrlKey||F.altKey||F.metaKey,N=F.key.length===1;H&&(F.key==="Tab"&&F.preventDefault(),!A&&N&&oe(F.key));const R=E.current;if(F.target!==R||!s0.includes(F.key))return;F.preventDefault();const q=I().filter(J=>!J.disabled).map(J=>J.ref.current);jf.includes(F.key)&&q.reverse(),I0(q)}),onBlur:Se(e.onBlur,F=>{F.currentTarget.contains(F.target)||(window.clearTimeout(_.current),D.current="")}),onPointerMove:Se(e.onPointerMove,mo(F=>{const G=F.target,H=$.current!==F.clientX;if(F.currentTarget.contains(G)&&H){const A=F.clientX>$.current?"right":"left";V.current=A,$.current=F.clientX}}))})})})})})})});Lf.displayName=Jt;var b0="MenuGroup",Ta=w.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.jsx(Pe.div,{role:"group",...r,ref:t})});Ta.displayName=b0;var w0="MenuLabel",$f=w.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.jsx(Pe.div,{...r,ref:t})});$f.displayName=w0;var Ss="MenuItem",Ff="menu.itemSelect",Cs=w.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,s=w.useRef(null),i=ho(Ss,e.__scopeMenu),a=Ca(Ss,e.__scopeMenu),c=et(t,s),l=w.useRef(!1),u=()=>{const f=s.current;if(!n&&f){const h=new CustomEvent(Ff,{bubbles:!0,cancelable:!0});f.addEventListener(Ff,p=>r==null?void 0:r(p),{once:!0}),Iu(f,h),h.defaultPrevented?l.current=!1:i.onClose()}};return d.jsx(zf,{...o,ref:c,disabled:n,onClick:Se(e.onClick,u),onPointerDown:f=>{var h;(h=e.onPointerDown)==null||h.call(e,f),l.current=!0},onPointerUp:Se(e.onPointerUp,f=>{var h;l.current||(h=f.currentTarget)==null||h.click()}),onKeyDown:Se(e.onKeyDown,f=>{const h=a.searchRef.current!=="";n||h&&f.key===" "||va.includes(f.key)&&(f.currentTarget.click(),f.preventDefault())})})});Cs.displayName=Ss;var zf=w.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...s}=e,i=Ca(Ss,n),a=Of(n),c=w.useRef(null),l=et(t,c),[u,f]=w.useState(!1),[h,p]=w.useState("");return w.useEffect(()=>{const m=c.current;m&&p((m.textContent??"").trim())},[s.children]),d.jsx(fo.ItemSlot,{scope:n,disabled:r,textValue:o??h,children:d.jsx(r0,{asChild:!0,...a,focusable:!r,children:d.jsx(Pe.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:l,onPointerMove:Se(e.onPointerMove,mo(m=>{r?i.onItemLeave(m):(i.onItemEnter(m),m.defaultPrevented||m.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Se(e.onPointerLeave,mo(m=>i.onItemLeave(m))),onFocus:Se(e.onFocus,()=>f(!0)),onBlur:Se(e.onBlur,()=>f(!1))})})})}),v0="MenuCheckboxItem",Bf=w.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return d.jsx(Kf,{scope:e.__scopeMenu,checked:n,children:d.jsx(Cs,{role:"menuitemcheckbox","aria-checked":ks(n)?"mixed":n,...o,ref:t,"data-state":Ia(n),onSelect:Se(o.onSelect,()=>r==null?void 0:r(ks(n)?!0:!n),{checkForDefaultPrevented:!1})})})});Bf.displayName=v0;var Hf="MenuRadioGroup",[y0,S0]=er(Hf,{value:void 0,onValueChange:()=>{}}),Uf=w.forwardRef((e,t)=>{const{value:n,onValueChange:r,...o}=e,s=St(r);return d.jsx(y0,{scope:e.__scopeMenu,value:n,onValueChange:s,children:d.jsx(Ta,{...o,ref:t})})});Uf.displayName=Hf;var Wf="MenuRadioItem",Vf=w.forwardRef((e,t)=>{const{value:n,...r}=e,o=S0(Wf,e.__scopeMenu),s=n===o.value;return d.jsx(Kf,{scope:e.__scopeMenu,checked:s,children:d.jsx(Cs,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":Ia(s),onSelect:Se(r.onSelect,()=>{var i;return(i=o.onValueChange)==null?void 0:i.call(o,n)},{checkForDefaultPrevented:!1})})})});Vf.displayName=Wf;var Ea="MenuItemIndicator",[Kf,C0]=er(Ea,{checked:!1}),qf=w.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,s=C0(Ea,n);return d.jsx(Vt,{present:r||ks(s.checked)||s.checked===!0,children:d.jsx(Pe.span,{...o,ref:t,"data-state":Ia(s.checked)})})});qf.displayName=Ea;var k0="MenuSeparator",Gf=w.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.jsx(Pe.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});Gf.displayName=k0;var T0="MenuArrow",Yf=w.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=ys(n);return d.jsx(Vy,{...o,...r,ref:t})});Yf.displayName=T0;var E0="MenuSub",[qC,Xf]=er(E0),po="MenuSubTrigger",Jf=w.forwardRef((e,t)=>{const n=tr(po,e.__scopeMenu),r=ho(po,e.__scopeMenu),o=Xf(po,e.__scopeMenu),s=Ca(po,e.__scopeMenu),i=w.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:c}=s,l={__scopeMenu:e.__scopeMenu},u=w.useCallback(()=>{i.current&&window.clearTimeout(i.current),i.current=null},[]);return w.useEffect(()=>u,[u]),w.useEffect(()=>{const f=a.current;return()=>{window.clearTimeout(f),c(null)}},[a,c]),d.jsx(ya,{asChild:!0,...l,children:d.jsx(zf,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":eh(n.open),...e,ref:On(t,o.onTriggerChange),onClick:f=>{var h;(h=e.onClick)==null||h.call(e,f),!(e.disabled||f.defaultPrevented)&&(f.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Se(e.onPointerMove,mo(f=>{s.onItemEnter(f),!f.defaultPrevented&&!e.disabled&&!n.open&&!i.current&&(s.onPointerGraceIntentChange(null),i.current=window.setTimeout(()=>{n.onOpenChange(!0),u()},100))})),onPointerLeave:Se(e.onPointerLeave,mo(f=>{var p,m;u();const h=(p=n.content)==null?void 0:p.getBoundingClientRect();if(h){const g=(m=n.content)==null?void 0:m.dataset.side,b=g==="right",v=b?-5:5,y=h[b?"left":"right"],T=h[b?"right":"left"];s.onPointerGraceIntentChange({area:[{x:f.clientX+v,y:f.clientY},{x:y,y:h.top},{x:T,y:h.top},{x:T,y:h.bottom},{x:y,y:h.bottom}],side:g}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(f),f.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:Se(e.onKeyDown,f=>{var p;const h=s.searchRef.current!=="";e.disabled||h&&f.key===" "||i0[r.dir].includes(f.key)&&(n.onOpenChange(!0),(p=n.content)==null||p.focus(),f.preventDefault())})})})});Jf.displayName=po;var Zf="MenuSubContent",Qf=w.forwardRef((e,t)=>{const n=Mf(Jt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=tr(Jt,e.__scopeMenu),i=ho(Jt,e.__scopeMenu),a=Xf(Zf,e.__scopeMenu),c=w.useRef(null),l=et(t,c);return d.jsx(fo.Provider,{scope:e.__scopeMenu,children:d.jsx(Vt,{present:r||s.open,children:d.jsx(fo.Slot,{scope:e.__scopeMenu,children:d.jsx(ka,{id:a.contentId,"aria-labelledby":a.triggerId,...o,ref:l,align:"start",side:i.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:u=>{var f;i.isUsingKeyboardRef.current&&((f=c.current)==null||f.focus()),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:Se(e.onFocusOutside,u=>{u.target!==a.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:Se(e.onEscapeKeyDown,u=>{i.onClose(),u.preventDefault()}),onKeyDown:Se(e.onKeyDown,u=>{var p;const f=u.currentTarget.contains(u.target),h=a0[i.dir].includes(u.key);f&&h&&(s.onOpenChange(!1),(p=a.trigger)==null||p.focus(),u.preventDefault())})})})})})});Qf.displayName=Zf;function eh(e){return e?"open":"closed"}function ks(e){return e==="indeterminate"}function Ia(e){return ks(e)?"indeterminate":e?"checked":"unchecked"}function I0(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function A0(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function N0(e,t,n){const o=t.length>1&&Array.from(t).every(l=>l===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=A0(e,Math.max(s,0));o.length===1&&(i=i.filter(l=>l!==n));const c=i.find(l=>l.toLowerCase().startsWith(o.toLowerCase()));return c!==n?c:void 0}function _0(e,t){const{x:n,y:r}=e;let o=!1;for(let s=0,i=t.length-1;s<t.length;i=s++){const a=t[s],c=t[i],l=a.x,u=a.y,f=c.x,h=c.y;u>r!=h>r&&n<(f-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function j0(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return _0(n,t)}function mo(e){return t=>t.pointerType==="mouse"?e(t):void 0}var P0=Rf,O0=ya,R0=Df,M0=Lf,D0=Ta,L0=$f,$0=Cs,F0=Bf,z0=Uf,B0=Vf,H0=qf,U0=Gf,W0=Yf,V0=Jf,K0=Qf,Ts="DropdownMenu",[q0,GC]=Rn(Ts,[Pf]),_t=Pf(),[G0,th]=q0(Ts),nh=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:s,onOpenChange:i,modal:a=!0}=e,c=_t(t),l=w.useRef(null),[u,f]=qo({prop:o,defaultProp:s??!1,onChange:i,caller:Ts});return d.jsx(G0,{scope:t,triggerId:Wt(),triggerRef:l,contentId:Wt(),open:u,onOpenChange:f,onOpenToggle:w.useCallback(()=>f(h=>!h),[f]),modal:a,children:d.jsx(P0,{...c,open:u,onOpenChange:f,dir:r,modal:a,children:n})})};nh.displayName=Ts;var rh="DropdownMenuTrigger",oh=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,s=th(rh,n),i=_t(n);return d.jsx(O0,{asChild:!0,...i,children:d.jsx(Pe.button,{type:"button",id:s.triggerId,"aria-haspopup":"menu","aria-expanded":s.open,"aria-controls":s.open?s.contentId:void 0,"data-state":s.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...o,ref:On(t,s.triggerRef),onPointerDown:Se(e.onPointerDown,a=>{!r&&a.button===0&&a.ctrlKey===!1&&(s.onOpenToggle(),s.open||a.preventDefault())}),onKeyDown:Se(e.onKeyDown,a=>{r||(["Enter"," "].includes(a.key)&&s.onOpenToggle(),a.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});oh.displayName=rh;var Y0="DropdownMenuPortal",sh=e=>{const{__scopeDropdownMenu:t,...n}=e,r=_t(t);return d.jsx(R0,{...r,...n})};sh.displayName=Y0;var ih="DropdownMenuContent",ah=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=th(ih,n),s=_t(n),i=w.useRef(!1);return d.jsx(M0,{id:o.contentId,"aria-labelledby":o.triggerId,...s,...r,ref:t,onCloseAutoFocus:Se(e.onCloseAutoFocus,a=>{var c;i.current||(c=o.triggerRef.current)==null||c.focus(),i.current=!1,a.preventDefault()}),onInteractOutside:Se(e.onInteractOutside,a=>{const c=a.detail.originalEvent,l=c.button===0&&c.ctrlKey===!0,u=c.button===2||l;(!o.modal||u)&&(i.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});ah.displayName=ih;var X0="DropdownMenuGroup",J0=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx(D0,{...o,...r,ref:t})});J0.displayName=X0;var Z0="DropdownMenuLabel",lh=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx(L0,{...o,...r,ref:t})});lh.displayName=Z0;var Q0="DropdownMenuItem",ch=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx($0,{...o,...r,ref:t})});ch.displayName=Q0;var eS="DropdownMenuCheckboxItem",uh=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx(F0,{...o,...r,ref:t})});uh.displayName=eS;var tS="DropdownMenuRadioGroup",nS=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx(z0,{...o,...r,ref:t})});nS.displayName=tS;var rS="DropdownMenuRadioItem",dh=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx(B0,{...o,...r,ref:t})});dh.displayName=rS;var oS="DropdownMenuItemIndicator",fh=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx(H0,{...o,...r,ref:t})});fh.displayName=oS;var sS="DropdownMenuSeparator",hh=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx(U0,{...o,...r,ref:t})});hh.displayName=sS;var iS="DropdownMenuArrow",aS=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx(W0,{...o,...r,ref:t})});aS.displayName=iS;var lS="DropdownMenuSubTrigger",ph=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx(V0,{...o,...r,ref:t})});ph.displayName=lS;var cS="DropdownMenuSubContent",mh=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_t(n);return d.jsx(K0,{...o,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});mh.displayName=cS;var uS=nh,dS=oh,fS=sh,gh=ah,xh=lh,bh=ch,wh=uh,vh=dh,yh=fh,Sh=hh,Ch=ph,kh=mh;const Aa=uS,Na=dS,hS=w.forwardRef(({className:e,inset:t,children:n,...r},o)=>d.jsxs(Ch,{ref:o,className:ae("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",e),...r,children:[n,d.jsx(pe.ChevronRight,{className:"ml-auto h-4 w-4"})]}));hS.displayName=Ch.displayName;const pS=w.forwardRef(({className:e,...t},n)=>d.jsx(kh,{ref:n,className:ae("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));pS.displayName=kh.displayName;const Es=w.forwardRef(({className:e,sideOffset:t=4,...n},r)=>d.jsx(fS,{children:d.jsx(gh,{ref:r,sideOffset:t,className:ae("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})}));Es.displayName=gh.displayName;const nr=w.forwardRef(({className:e,inset:t,...n},r)=>d.jsx(bh,{ref:r,className:ae("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));nr.displayName=bh.displayName;const mS=w.forwardRef(({className:e,children:t,checked:n,...r},o)=>d.jsxs(wh,{ref:o,className:ae("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[d.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:d.jsx(yh,{children:d.jsx(pe.Check,{className:"h-4 w-4"})})}),t]}));mS.displayName=wh.displayName;const gS=w.forwardRef(({className:e,children:t,...n},r)=>d.jsxs(vh,{ref:r,className:ae("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[d.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:d.jsx(yh,{children:d.jsx(pe.Circle,{className:"h-2 w-2 fill-current"})})}),t]}));gS.displayName=vh.displayName;const xS=w.forwardRef(({className:e,inset:t,...n},r)=>d.jsx(xh,{ref:r,className:ae("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));xS.displayName=xh.displayName;const bS=w.forwardRef(({className:e,...t},n)=>d.jsx(Sh,{ref:n,className:ae("-mx-1 my-1 h-px bg-muted",e),...t}));bS.displayName=Sh.displayName;const Th=w.forwardRef(({className:e,...t},n)=>d.jsx("textarea",{className:ae("flex min-h-[40px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));Th.displayName="Textarea";const wS=1e4;function _a({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=wS,value:i,onValueChange:a,onSend:c,onCancelEdit:l,onStop:u,className:f="",textareaClassName:h="",allowEmptySend:p=!1,sendButtonClassName:m,validate:g,onValidationError:b}){const v=i!==void 0,[y,T]=x.useState(e),I=(v?i:y)??"",[k,S]=x.useTransition(),E=x.useRef(null),j=x.useRef(0),_=x.useRef(null),D=x.useRef("");x.useEffect(()=>{if(!v&&(T(e??""),_.current=null,E.current)){const R=!e||e.trim()==="",M=44;R?E.current.style.height=`${M}px`:(E.current.style.height="auto",E.current.style.height=`${Math.max(E.current.scrollHeight,M)}px`)}},[e,t,v]);const[L,W]=x.useState(null),V=x.useCallback(R=>R.length>s?`Message too long (${R.length}/${s} characters)`:null,[s]),$=x.useMemo(()=>g??V,[g,V]),Z=x.useCallback(R=>{const M=$(R);return W(M),b==null||b(M),D.current=R,M},[$,b]),X=x.useCallback(()=>{const R=E.current;if(!R)return;const M=!R.value||R.value.trim()==="",q=44;if(M){R.style.height=`${q}px`;return}R.style.height="auto";const J=Math.max(R.scrollHeight,q);R.style.height=`${J}px`},[]);x.useEffect(()=>{X()},[X,I]),x.useEffect(()=>{if(!L)return;const R=(I??"").trim();D.current!==R&&Z(R)},[I,L,Z]);const oe=x.useCallback((R,{fromUser:M})=>{v||T(R),M&&(a==null||a(R))},[v,a]),U=x.useCallback(async R=>{R&&R.preventDefault();const M=(I??"").trim();if(!M&&!p||Z(M))return;const q=++j.current;_.current={id:q,shouldClear:!0},S(()=>{var J,P,K;try{const te=c(M);te&&typeof te.then=="function"?te.then(()=>{var le,he;((le=_.current)==null?void 0:le.id)===q&&_.current.shouldClear&&(v||(T(""),E.current&&(E.current.style.height="auto"),a==null||a(""))),((he=_.current)==null?void 0:he.id)===q&&(_.current=null)}).catch(()=>{var le;((le=_.current)==null?void 0:le.id)===q&&(_.current=null)}):(((J=_.current)==null?void 0:J.id)===q&&_.current.shouldClear&&(v||(T(""),E.current&&(E.current.style.height="auto"),a==null||a(""))),((P=_.current)==null?void 0:P.id)===q&&(_.current=null))}catch{((K=_.current)==null?void 0:K.id)===q&&(_.current=null)}})},[I,c,p,v,a,Z]),F=x.useCallback(R=>{const M=R.target.value;oe(M,{fromUser:!0}),_.current&&(_.current.shouldClear=!1),E.current&&(E.current.style.height="auto",E.current.style.height=`${E.current.scrollHeight}px`),L&&Z(M.trim())},[oe,Z,L]),G=x.useCallback(R=>{R.key==="Enter"&&!R.shiftKey?(R.preventDefault(),U()):R.key==="Escape"&&t&&(R.preventDefault(),l==null||l())},[U,t,l]),N=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${t?"border-[hsl(var(--ring))] bg-[hsl(var(--card))] text-[hsl(var(--card-foreground))] dark:bg-[hsl(var(--card))] dark:text-[hsl(var(--card-foreground))]":""} ${h}`;return d.jsx("div",{className:`w-full ${f}`,children:d.jsxs("div",{className:"flex items-end gap-2",children:[d.jsxs("div",{className:"flex-1",children:[d.jsx(Th,{ref:E,value:I,onChange:F,onKeyDown:G,placeholder:t?"Edit your message...":n,className:N,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"}),L&&d.jsx("p",{className:"mt-1 text-xs text-destructive font-medium",children:L})]}),d.jsx("div",{children:r?d.jsx(Ke,{type:"button",onClick:()=>{u==null||u()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!u,children:d.jsx(pe.Square,{size:16})}):d.jsx(Ke,{type:"button",onClick:R=>void U(R),size:"icon",className:`shrink-0 ${m??""}`,title:t?"Save changes":"Send message",disabled:o||!I.trim()&&!p||k||r,children:d.jsx(pe.Send,{size:16})})})]})})}const vS=x.memo(_a);function ja({composerValue:e,onComposerChange:t,onSend:n,onCancelEdit:r,onStop:o,editingMessageId:s=null,editingInitialValue:i="",placeholder:a="Type your message...",isStreaming:c=!1,disabled:l=!1,textareaClassName:u="",customStyles:f={},enableFileUpload:h=!1,enableExcelUpload:p=!1,onExcelUpload:m,onFilesChange:g,onError:b,allowEmptySend:v=!1,inputError:y=null}){const[T,I]=x.useState([]),k=x.useRef(null),S=x.useRef(null),[E,j]=x.useState(0),[_,D]=x.useState(0),[L,W]=x.useState(!1),[V,$]=x.useState(null),[Z,X]=x.useState(null),oe=x.useCallback(()=>{k.current&&(k.current.value=""),S.current&&(S.current.value=""),j(M=>M+1),D(M=>M+1)},[]),U=x.useCallback(M=>{I(q=>{const J=[...q,...M];return g==null||g(J),J})},[g]),F=x.useCallback(M=>{const q=Array.from(M.target.files||[]);U(q),M.target.value=""},[U]),G=x.useCallback(M=>{I(q=>{const J=q.filter((P,K)=>K!==M);return J.length===0&&oe(),g==null||g(J),J})},[g,oe]),H=x.useCallback(async M=>{const q=(M.target.files||[])[0];if(q&&($(null),X(null),!!m)){W(!0);try{await m(q),$(`Uploaded ${q.name} - processing through chat stream`)}catch(J){const P=J instanceof Error?J.message:"Failed to upload Excel file";X(P),b==null||b(P)}finally{W(!1),M.target.value="",oe()}}},[m,b,oe]),A=x.useMemo(()=>v||T.length>0,[v,T]),N=x.useCallback(async M=>{const J=await n(M,T);return T.length>0&&(I([]),g==null||g([]),oe()),J},[n,oe,T]),R=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${s?"border-blue-400 bg-blue-50 text-blue-900 dark:border-blue-500 dark:bg-blue-950/60 dark:text-blue-50":""} ${y?"border-red-400":""} ${f.textarea||""} ${u}`;return d.jsxs(d.Fragment,{children:[(h||p)&&d.jsxs("div",{className:"mb-3 space-y-3",children:[h&&d.jsxs(d.Fragment,{children:[d.jsx("input",{ref:k,type:"file",multiple:!0,onChange:F,className:"hidden"},E),T.length>0&&d.jsx("div",{className:"flex flex-wrap gap-2",children:T.map((M,q)=>d.jsxs("div",{className:"flex items-center gap-2 bg-gray-100 dark:bg-gray-800 rounded-lg px-3 py-2 text-sm text-gray-900 dark:text-gray-100",children:[d.jsx(pe.Paperclip,{size:14}),d.jsx("span",{className:"truncate max-w-[150px]",children:M.name}),d.jsx(Ke,{variant:"ghost",size:"sm",onClick:()=>G(q),className:"h-4 w-4 p-0 text-gray-500 dark:text-gray-400 hover:text-red-500 dark:hover:text-red-400","aria-label":`Remove ${M.name}`,children:d.jsx(pe.X,{size:12})})]},q))})]}),p&&d.jsxs(d.Fragment,{children:[d.jsx("input",{ref:S,type:"file",accept:".xls,.xlsx,.xlsm",onChange:H,className:"hidden"},_),L&&d.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[d.jsx(pe.Loader2,{className:"h-4 w-4 animate-spin"})," Uploading Excel file..."]}),V&&!L&&d.jsx("div",{className:"text-sm rounded border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-700",children:V}),Z&&!L&&d.jsx("div",{className:"text-sm rounded border border-red-200 bg-red-50 px-3 py-2 text-red-600",children:Z})]})]}),d.jsxs("div",{className:"flex items-end gap-2",children:[(h||p)&&d.jsxs(Aa,{children:[d.jsx(Na,{asChild:!0,children:d.jsx(Ke,{type:"button",size:"icon",variant:"outline",disabled:c||l,title:"More input actions",className:f.moreButton||"",children:d.jsx(pe.Plus,{size:16})})}),d.jsxs(Es,{align:"start",sideOffset:6,className:"w-52",children:[h&&d.jsxs(nr,{onClick:()=>{var M;return(M=k.current)==null?void 0:M.click()},className:"cursor-pointer",children:[d.jsx(pe.Paperclip,{className:"h-4 w-4 mr-2"})," Attach files or images"]}),p&&d.jsxs(nr,{onClick:()=>{var M;L||(M=S.current)==null||M.click()},className:`cursor-pointer ${L?"opacity-60 pointer-events-none":""}`,children:[d.jsx(pe.FileSpreadsheet,{className:"h-4 w-4 mr-2"})," Upload Excel file"]})]})]}),d.jsx("div",{className:"flex-1",children:d.jsx(vS,{initialValue:i,editingMessageId:s,value:e,onValueChange:t,placeholder:s?"Edit your message...":a,isStreaming:c,disabled:l,onSend:N,onCancelEdit:r,onStop:o,allowEmptySend:A,textareaClassName:R,sendButtonClassName:f.sendButton})})]})]})}const yS=x.memo(ja),Eh={value:""};function Er({className:e="",placeholder:t="Type your message...",maxHeight:n=void 0,streamingDebounceMs:r=500,followNewMessages:o=!0,enableFileUpload:s=!0,enableExcelUpload:i=!1,enableMessageEditing:a=!0,showToolMessages:c=!0,toolConfig:l,toolRenderers:u,toolArtifactRenderers:f,payloadExtras:h={},customStyles:p={},messageCustomStyles:m,onMessageSent:g,onExcelUploadSuccess:b,onError:v,renderArtifactsInline:y=!0,emptyMessage:T}){const{currentThreadId:I}=ur(),{threadId:k,messages:S,isLoading:E,navigateToCheckpoint:j,returnToLatest:_,checkpoint:D,checkpoints:L,interrupt:W,metadata:V,checkpointIndex:$,respondToInterrupt:Z}=Ur(),{isStreaming:X,error:oe,connectionState:U,submit:F,stop:G,messages:H}=ii(),A=k??I??null,N=(D==null?void 0:D.id)??null,R=(D==null?void 0:D.namespace)??null,M=(V==null?void 0:V.assemblingMessageId)??null;x.useEffect(()=>{console.log("[ChatInterface] streamingAssistantId changed:",{streamingAssistantId:M,isStreaming:X,assemblingMessageId:V==null?void 0:V.assemblingMessageId})},[M,X,V==null?void 0:V.assemblingMessageId]);const q=W,J=q?oc(q.id):null,P=J!==null?{type:"interrupt",id:J}:null,[K,te]=x.useState(!1),[le,he]=x.useState(!1);x.useEffect(()=>{q||te(!1)},[q]);const ue=x.useCallback(()=>{te(!0)},[]),ge=x.useCallback(()=>{te(!1)},[]),be=x.useCallback(Q=>{},[]),Be=x.useCallback(Q=>Q.name!=="ask_user_choice",[]),Le=l??{toolRenderers:u,toolArtifactRenderers:f,getToolExpandable:Be},je=x.useCallback(async(Q,C,O)=>{try{ue(),await Z(Q,C,O)}catch(z){console.error("Failed to respond to interrupt:",z)}finally{ge()}},[ge,ue,Z]),Fe=x.useCallback(()=>je(!0),[je]),tt=x.useCallback(()=>je(!1),[je]),mt=x.useCallback((Q,C)=>je(!0,C),[je]),ot=!!q||K,[ze,Me]=x.useState(null),[Ze,rt]=x.useState(""),[qe,ht]=x.useState(null),[xt,He]=x.useState(null),[st,an]=x.useState(!1),jt=x.useRef(!1),[ct,kt]=x.useState(()=>Eh.value),Tt=x.useRef(ct),bt=x.useRef(null),Ge=x.useCallback(Q=>{Eh.value=Q,kt(Q)},[]),[gt,ut]=x.useState(!1),$t=x.useRef(null),$e=x.useCallback(Q=>{Ge(Q)},[Ge]);x.useEffect(()=>{X||he(!1)},[X]),x.useEffect(()=>{V!=null&&V.assemblingMessageId&&he(!1)},[V==null?void 0:V.assemblingMessageId]);const[Ee,Ve]=x.useState("desktop");x.useEffect(()=>{const Q=()=>{const C=window.innerWidth;Ve(C<640?"phone":C<1024?"tablet":"desktop")};return Q(),window.addEventListener("resize",Q),()=>window.removeEventListener("resize",Q)},[]),x.useEffect(()=>{jt.current=!1},[A]),x.useEffect(()=>{Tt.current=ct},[ct]),x.useEffect(()=>{if(!ze){bt.current=null;return}bt.current===null&&(bt.current=Tt.current),Ge(Ze??"")},[Ze,ze,Ge]),x.useEffect(()=>{oe&&!st&&(v==null||v(oe))},[oe,st,v]);const dt=async(Q,C)=>{const O=Q.trim();if(!(!O&&C.length===0))try{const z=ze?(qe==null?void 0:qe.checkpointId)??N??void 0:N??void 0,se=ze?(qe==null?void 0:qe.checkpointNs)??R??void 0:R??void 0;await F({text:O||"",attachments:C,payload:h},{checkpointId:z,checkpointNs:se,edit:!!ze,originalMessageId:ze??void 0}),g==null||g(O),he(!0),Ge(""),He(null),Me(null),rt(""),ht(null)}catch(z){const se=(z==null?void 0:z.message)||"Failed to send message";He(se),v==null||v(se),he(!1)}},Et=x.useCallback(async Q=>{await F({attachments:[Q],payload:h},{checkpointId:N??void 0,checkpointNs:R??void 0}),b==null||b({file:Q})},[N,R,h,b,F]),Ft=x.useCallback((Q,C,O)=>{a&&(bt.current=ct,Me(Q),rt(C),Ge(C),He(null),ht({checkpointId:(O==null?void 0:O.checkpointId)??null,checkpointNs:(O==null?void 0:O.checkpointNs)??null}))},[ct,a,Ge]),zt=x.useCallback(()=>{Me(null),rt(""),ht(null),He(null),Ge(bt.current??ct),bt.current=null},[ct,Ge]),kn=x.useCallback((Q,C,O)=>{Ft(Q,C,O)},[Ft]),Tn=x.useCallback(Q=>{let C=null;for(let ie=Q-1;ie>=0;ie--)if(S[ie].role==="user"){C=S[ie];break}if(!C)return;const O=Array.isArray(C.content)?C.content:[],se=O.filter(ie=>(ie==null?void 0:ie.type)==="text").map(ie=>ie.text).join("")||(()=>{try{return JSON.stringify(O,null,2)}catch{return String(O)}})();se&&F({text:se,payload:h},{checkpointId:N??void 0,checkpointNs:R??void 0,edit:!0,originalMessageId:C.id})},[S,F,N,R,h]),Gt=x.useCallback(async Q=>{if(I){ut(!0);try{if(!Q){await _(),requestAnimationFrame(()=>{var z;(z=$t.current)==null||z.scrollToLatest()});return}const C=L.find(z=>z.checkpointId===Q),O=(C==null?void 0:C.checkpointNs)??null;await j(Q,O),requestAnimationFrame(()=>{var z;(z=$t.current)==null||z.scrollToTop()})}finally{ut(!1)}}},[L,I,$t,j,_]),vn=x.useCallback(async(Q,C,O)=>{await Gt(O?null:Q)},[Gt]),ln=`flex flex-1 w-full flex-col min-h-0 min-w-0 max-h-full overflow-hidden bg-transparent ${e} ${p.container||""}`,Y=`flex-1 min-h-0 min-w-0 max-h-full w-full overflow-hidden overscroll-contain break-words break-anywhere p-4 ${q?"pb-32":""} bg-transparent ${p.messagesArea||""}`,fe=`relative flex-shrink-0 w-full border-t p-4 bg-transparent ${p.inputArea||""}`;return d.jsxs("div",{className:ln,children:[!!oe&&!st&&d.jsxs("div",{className:"flex-shrink-0 bg-red-50 border border-red-200 text-red-800 px-4 py-2 text-sm flex items-center justify-between",children:[d.jsx("span",{children:oe}),d.jsx(Ke,{variant:"ghost",size:"sm",onClick:()=>an(!0),className:"text-red-800 hover:bg-red-100","aria-label":"Dismiss error",children:d.jsx(pe.X,{size:16})})]}),d.jsxs("div",{className:`relative ${Y}`,style:n?{maxHeight:n}:void 0,children:[d.jsx(us,{ref:$t,className:"h-full",style:{height:"100%"},messages:H??S,isStreaming:X,streamingAssistantId:M,streamingDebounceMs:r,followNewMessages:o,layoutSize:Ee,enableMessageEditing:a,editingMessageId:ze,onEdit:kn,onRegenerate:Tn,onCancelEdit:zt,emptyMessage:T,isNavigatingCheckpoint:gt,showToolMessages:c,toolConfig:Le,checkpointIndex:$,activeCheckpointId:N,onSelectCheckpoint:vn,showThinkingIndicator:X||le,getMessageCustomStyles:m,getInterruptOptions:be,renderArtifactsInline:y}),(U==="reconnecting"||U==="connecting")&&d.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-muted/80 px-3 py-1 text-xs font-medium text-foreground shadow-sm backdrop-blur-sm dark:bg-muted/60",children:d.jsxs("span",{className:"flex items-center gap-2",children:[d.jsx(pe.Loader2,{className:"h-3 w-3 animate-spin"}),U==="reconnecting"?"Reconnecting…":"Connecting…"]})}),U==="error"&&d.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-destructive/10 px-3 py-1 text-xs font-semibold text-destructive shadow-sm",children:"Connection lost"}),E&&d.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-background/80 backdrop-blur-sm text-muted-foreground",children:[d.jsx(pe.Loader2,{className:"h-6 w-6 animate-spin"}),d.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading messages…"})]}),gt&&d.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-background/80 backdrop-blur-sm text-muted-foreground",children:[d.jsx(pe.Loader2,{className:"h-6 w-6 animate-spin"}),d.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading checkpoint…"})]}),q&&P&&d.jsx("div",{className:"pointer-events-auto absolute inset-x-0 bottom-6 z-30 flex justify-center px-4",children:d.jsx("div",{className:"w-full max-w-3xl",children:d.jsx(Id,{interruptPart:P,onApprove:Fe,onReject:tt,onSelectAlternative:mt,disabled:K,isActive:!0,payload:q.value})})})]}),d.jsxs("div",{className:fe,children:[ze&&d.jsx("div",{className:"mb-3 p-3 bg-blue-50 border border-blue-200 rounded-lg",children:d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx(pe.Edit3,{size:16,className:"text-blue-600"}),d.jsx("span",{className:"text-sm font-medium text-blue-800",children:"Editing message"})]}),d.jsx(Ke,{variant:"ghost",size:"sm",onClick:zt,className:"text-blue-600 hover:bg-blue-100",children:d.jsx(pe.X,{size:16})})]})}),xt&&d.jsx("div",{className:"mb-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2",children:xt}),d.jsx(yS,{composerValue:ct,onComposerChange:$e,onSend:dt,onCancelEdit:zt,onStop:G,editingMessageId:ze,editingInitialValue:Ze,placeholder:ze?"Edit your message...":t,isStreaming:X,disabled:ot,enableFileUpload:s,enableExcelUpload:i,onExcelUpload:Et,onError:v,customStyles:p,textareaClassName:p.textarea||"",allowEmptySend:!1,inputError:xt})]})]})}var Ih=1,SS=.9,CS=.8,kS=.17,Pa=.1,Oa=.999,TS=.9999,ES=.99,IS=/[\\\/_+.#"@\[\(\{&]/,AS=/[\\\/_+.#"@\[\(\{&]/g,NS=/[\s-]/,Ah=/[\s-]/g;function Ra(e,t,n,r,o,s,i){if(s===t.length)return o===e.length?Ih:ES;var a=`${o},${s}`;if(i[a]!==void 0)return i[a];for(var c=r.charAt(s),l=n.indexOf(c,o),u=0,f,h,p,m;l>=0;)f=Ra(e,t,n,r,l+1,s+1,i),f>u&&(l===o?f*=Ih:IS.test(e.charAt(l-1))?(f*=CS,p=e.slice(o,l-1).match(AS),p&&o>0&&(f*=Math.pow(Oa,p.length))):NS.test(e.charAt(l-1))?(f*=SS,m=e.slice(o,l-1).match(Ah),m&&o>0&&(f*=Math.pow(Oa,m.length))):(f*=kS,o>0&&(f*=Math.pow(Oa,l-o))),e.charAt(l)!==t.charAt(s)&&(f*=TS)),(f<Pa&&n.charAt(l-1)===r.charAt(s+1)||r.charAt(s+1)===r.charAt(s)&&n.charAt(l-1)!==r.charAt(s))&&(h=Ra(e,t,n,r,l+1,s+2,i),h*Pa>f&&(f=h*Pa)),f>u&&(u=f),l=n.indexOf(c,l+1);return i[a]=u,u}function Nh(e){return e.toLowerCase().replace(Ah," ")}function _S(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Ra(e,t,Nh(e),Nh(t),0,0,{})}var go='[cmdk-group=""]',Ma='[cmdk-group-items=""]',jS='[cmdk-group-heading=""]',_h='[cmdk-item=""]',jh=`${_h}:not([aria-disabled="true"])`,Da="cmdk-item-select",Ir="data-value",PS=(e,t,n)=>_S(e,t,n),Ph=w.createContext(void 0),xo=()=>w.useContext(Ph),Oh=w.createContext(void 0),La=()=>w.useContext(Oh),Rh=w.createContext(void 0),Mh=w.forwardRef((e,t)=>{let n=Ar(()=>{var A,N;return{search:"",value:(N=(A=e.value)!=null?A:e.defaultValue)!=null?N:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=Ar(()=>new Set),o=Ar(()=>new Map),s=Ar(()=>new Map),i=Ar(()=>new Set),a=Dh(e),{label:c,children:l,value:u,onValueChange:f,filter:h,shouldFilter:p,loop:m,disablePointerSelection:g=!1,vimBindings:b=!0,...v}=e,y=Wt(),T=Wt(),I=Wt(),k=w.useRef(null),S=US();rr(()=>{if(u!==void 0){let A=u.trim();n.current.value=A,E.emit()}},[u]),rr(()=>{S(6,V)},[]);let E=w.useMemo(()=>({subscribe:A=>(i.current.add(A),()=>i.current.delete(A)),snapshot:()=>n.current,setState:(A,N,R)=>{var M,q,J,P;if(!Object.is(n.current[A],N)){if(n.current[A]=N,A==="search")W(),D(),S(1,L);else if(A==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let K=document.getElementById(I);K?K.focus():(M=document.getElementById(y))==null||M.focus()}if(S(7,()=>{var K;n.current.selectedItemId=(K=$())==null?void 0:K.id,E.emit()}),R||S(5,V),((q=a.current)==null?void 0:q.value)!==void 0){let K=N??"";(P=(J=a.current).onValueChange)==null||P.call(J,K);return}}E.emit()}},emit:()=>{i.current.forEach(A=>A())}}),[]),j=w.useMemo(()=>({value:(A,N,R)=>{var M;N!==((M=s.current.get(A))==null?void 0:M.value)&&(s.current.set(A,{value:N,keywords:R}),n.current.filtered.items.set(A,_(N,R)),S(2,()=>{D(),E.emit()}))},item:(A,N)=>(r.current.add(A),N&&(o.current.has(N)?o.current.get(N).add(A):o.current.set(N,new Set([A]))),S(3,()=>{W(),D(),n.current.value||L(),E.emit()}),()=>{s.current.delete(A),r.current.delete(A),n.current.filtered.items.delete(A);let R=$();S(4,()=>{W(),(R==null?void 0:R.getAttribute("id"))===A&&L(),E.emit()})}),group:A=>(o.current.has(A)||o.current.set(A,new Set),()=>{s.current.delete(A),o.current.delete(A)}),filter:()=>a.current.shouldFilter,label:c||e["aria-label"],getDisablePointerSelection:()=>a.current.disablePointerSelection,listId:y,inputId:I,labelId:T,listInnerRef:k}),[]);function _(A,N){var R,M;let q=(M=(R=a.current)==null?void 0:R.filter)!=null?M:PS;return A?q(A,n.current.search,N):0}function D(){if(!n.current.search||a.current.shouldFilter===!1)return;let A=n.current.filtered.items,N=[];n.current.filtered.groups.forEach(M=>{let q=o.current.get(M),J=0;q.forEach(P=>{let K=A.get(P);J=Math.max(K,J)}),N.push([M,J])});let R=k.current;Z().sort((M,q)=>{var J,P;let K=M.getAttribute("id"),te=q.getAttribute("id");return((J=A.get(te))!=null?J:0)-((P=A.get(K))!=null?P:0)}).forEach(M=>{let q=M.closest(Ma);q?q.appendChild(M.parentElement===q?M:M.closest(`${Ma} > *`)):R.appendChild(M.parentElement===R?M:M.closest(`${Ma} > *`))}),N.sort((M,q)=>q[1]-M[1]).forEach(M=>{var q;let J=(q=k.current)==null?void 0:q.querySelector(`${go}[${Ir}="${encodeURIComponent(M[0])}"]`);J==null||J.parentElement.appendChild(J)})}function L(){let A=Z().find(R=>R.getAttribute("aria-disabled")!=="true"),N=A==null?void 0:A.getAttribute(Ir);E.setState("value",N||void 0)}function W(){var A,N,R,M;if(!n.current.search||a.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let q=0;for(let J of r.current){let P=(N=(A=s.current.get(J))==null?void 0:A.value)!=null?N:"",K=(M=(R=s.current.get(J))==null?void 0:R.keywords)!=null?M:[],te=_(P,K);n.current.filtered.items.set(J,te),te>0&&q++}for(let[J,P]of o.current)for(let K of P)if(n.current.filtered.items.get(K)>0){n.current.filtered.groups.add(J);break}n.current.filtered.count=q}function V(){var A,N,R;let M=$();M&&(((A=M.parentElement)==null?void 0:A.firstChild)===M&&((R=(N=M.closest(go))==null?void 0:N.querySelector(jS))==null||R.scrollIntoView({block:"nearest"})),M.scrollIntoView({block:"nearest"}))}function $(){var A;return(A=k.current)==null?void 0:A.querySelector(`${_h}[aria-selected="true"]`)}function Z(){var A;return Array.from(((A=k.current)==null?void 0:A.querySelectorAll(jh))||[])}function X(A){let N=Z()[A];N&&E.setState("value",N.getAttribute(Ir))}function oe(A){var N;let R=$(),M=Z(),q=M.findIndex(P=>P===R),J=M[q+A];(N=a.current)!=null&&N.loop&&(J=q+A<0?M[M.length-1]:q+A===M.length?M[0]:M[q+A]),J&&E.setState("value",J.getAttribute(Ir))}function U(A){let N=$(),R=N==null?void 0:N.closest(go),M;for(;R&&!M;)R=A>0?BS(R,go):HS(R,go),M=R==null?void 0:R.querySelector(jh);M?E.setState("value",M.getAttribute(Ir)):oe(A)}let F=()=>X(Z().length-1),G=A=>{A.preventDefault(),A.metaKey?F():A.altKey?U(1):oe(1)},H=A=>{A.preventDefault(),A.metaKey?X(0):A.altKey?U(-1):oe(-1)};return w.createElement(Pe.div,{ref:t,tabIndex:-1,...v,"cmdk-root":"",onKeyDown:A=>{var N;(N=v.onKeyDown)==null||N.call(v,A);let R=A.nativeEvent.isComposing||A.keyCode===229;if(!(A.defaultPrevented||R))switch(A.key){case"n":case"j":{b&&A.ctrlKey&&G(A);break}case"ArrowDown":{G(A);break}case"p":case"k":{b&&A.ctrlKey&&H(A);break}case"ArrowUp":{H(A);break}case"Home":{A.preventDefault(),X(0);break}case"End":{A.preventDefault(),F();break}case"Enter":{A.preventDefault();let M=$();if(M){let q=new Event(Da);M.dispatchEvent(q)}}}}},w.createElement("label",{"cmdk-label":"",htmlFor:j.inputId,id:j.labelId,style:VS},c),Is(e,A=>w.createElement(Oh.Provider,{value:E},w.createElement(Ph.Provider,{value:j},A))))}),OS=w.forwardRef((e,t)=>{var n,r;let o=Wt(),s=w.useRef(null),i=w.useContext(Rh),a=xo(),c=Dh(e),l=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:i==null?void 0:i.forceMount;rr(()=>{if(!l)return a.item(o,i==null?void 0:i.id)},[l]);let u=Lh(o,s,[e.value,e.children,s],e.keywords),f=La(),h=zn(S=>S.value&&S.value===u.current),p=zn(S=>l||a.filter()===!1?!0:S.search?S.filtered.items.get(o)>0:!0);w.useEffect(()=>{let S=s.current;if(!(!S||e.disabled))return S.addEventListener(Da,m),()=>S.removeEventListener(Da,m)},[p,e.onSelect,e.disabled]);function m(){var S,E;g(),(E=(S=c.current).onSelect)==null||E.call(S,u.current)}function g(){f.setState("value",u.current,!0)}if(!p)return null;let{disabled:b,value:v,onSelect:y,forceMount:T,keywords:I,...k}=e;return w.createElement(Pe.div,{ref:On(s,t),...k,id:o,"cmdk-item":"",role:"option","aria-disabled":!!b,"aria-selected":!!h,"data-disabled":!!b,"data-selected":!!h,onPointerMove:b||a.getDisablePointerSelection()?void 0:g,onClick:b?void 0:m},e.children)}),RS=w.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:o,...s}=e,i=Wt(),a=w.useRef(null),c=w.useRef(null),l=Wt(),u=xo(),f=zn(p=>o||u.filter()===!1?!0:p.search?p.filtered.groups.has(i):!0);rr(()=>u.group(i),[]),Lh(i,a,[e.value,e.heading,c]);let h=w.useMemo(()=>({id:i,forceMount:o}),[o]);return w.createElement(Pe.div,{ref:On(a,t),...s,"cmdk-group":"",role:"presentation",hidden:f?void 0:!0},n&&w.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:l},n),Is(e,p=>w.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?l:void 0},w.createElement(Rh.Provider,{value:h},p))))}),MS=w.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,o=w.useRef(null),s=zn(i=>!i.search);return!n&&!s?null:w.createElement(Pe.div,{ref:On(o,t),...r,"cmdk-separator":"",role:"separator"})}),DS=w.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,o=e.value!=null,s=La(),i=zn(l=>l.search),a=zn(l=>l.selectedItemId),c=xo();return w.useEffect(()=>{e.value!=null&&s.setState("search",e.value)},[e.value]),w.createElement(Pe.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":a,id:c.inputId,type:"text",value:o?e.value:i,onChange:l=>{o||s.setState("search",l.target.value),n==null||n(l.target.value)}})}),LS=w.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...o}=e,s=w.useRef(null),i=w.useRef(null),a=zn(l=>l.selectedItemId),c=xo();return w.useEffect(()=>{if(i.current&&s.current){let l=i.current,u=s.current,f,h=new ResizeObserver(()=>{f=requestAnimationFrame(()=>{let p=l.offsetHeight;u.style.setProperty("--cmdk-list-height",p.toFixed(1)+"px")})});return h.observe(l),()=>{cancelAnimationFrame(f),h.unobserve(l)}}},[]),w.createElement(Pe.div,{ref:On(s,t),...o,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":a,"aria-label":r,id:c.listId},Is(e,l=>w.createElement("div",{ref:On(i,c.listInnerRef),"cmdk-list-sizer":""},l)))}),$S=w.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:o,contentClassName:s,container:i,...a}=e;return w.createElement(pd,{open:n,onOpenChange:r},w.createElement(md,{container:i},w.createElement(qi,{"cmdk-overlay":"",className:o}),w.createElement(Gi,{"aria-label":e.label,"cmdk-dialog":"",className:s},w.createElement(Mh,{ref:t,...a}))))}),FS=w.forwardRef((e,t)=>zn(n=>n.filtered.count===0)?w.createElement(Pe.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),zS=w.forwardRef((e,t)=>{let{progress:n,children:r,label:o="Loading...",...s}=e;return w.createElement(Pe.div,{ref:t,...s,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":o},Is(e,i=>w.createElement("div",{"aria-hidden":!0},i)))}),Lt=Object.assign(Mh,{List:LS,Item:OS,Input:DS,Group:RS,Separator:MS,Dialog:$S,Empty:FS,Loading:zS});function BS(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function HS(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function Dh(e){let t=w.useRef(e);return rr(()=>{t.current=e}),t}var rr=typeof window>"u"?w.useEffect:w.useLayoutEffect;function Ar(e){let t=w.useRef();return t.current===void 0&&(t.current=e()),t}function zn(e){let t=La(),n=()=>e(t.snapshot());return w.useSyncExternalStore(t.subscribe,n,n)}function Lh(e,t,n,r=[]){let o=w.useRef(),s=xo();return rr(()=>{var i;let a=(()=>{var l;for(let u of n){if(typeof u=="string")return u.trim();if(typeof u=="object"&&"current"in u)return u.current?(l=u.current.textContent)==null?void 0:l.trim():o.current}})(),c=r.map(l=>l.trim());s.value(e,a,c),(i=t.current)==null||i.setAttribute(Ir,a),o.current=a}),o}var US=()=>{let[e,t]=w.useState(),n=Ar(()=>new Map);return rr(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,o)=>{n.current.set(r,o),t({})}};function WS(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Is({asChild:e,children:t},n){return e&&w.isValidElement(t)?w.cloneElement(WS(t),{ref:t.ref},n(t.props.children)):n(t)}var VS={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const $h=w.forwardRef(({className:e,...t},n)=>d.jsx(Lt,{ref:n,className:ae("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t}));$h.displayName=Lt.displayName;const Fh=w.forwardRef(({className:e,...t},n)=>d.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[d.jsx(pe.Search,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),d.jsx(Lt.Input,{ref:n,className:ae("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));Fh.displayName=Lt.Input.displayName;const zh=w.forwardRef(({className:e,...t},n)=>d.jsx(Lt.List,{ref:n,className:ae("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));zh.displayName=Lt.List.displayName;const Bh=w.forwardRef((e,t)=>d.jsx(Lt.Empty,{ref:t,className:"py-6 text-center text-sm",...e}));Bh.displayName=Lt.Empty.displayName;const Hh=w.forwardRef(({className:e,...t},n)=>d.jsx(Lt.Group,{ref:n,className:ae("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t}));Hh.displayName=Lt.Group.displayName;const KS=w.forwardRef(({className:e,...t},n)=>d.jsx(Lt.Separator,{ref:n,className:ae("-mx-1 h-px bg-border",e),...t}));KS.displayName=Lt.Separator.displayName;const Uh=w.forwardRef(({className:e,...t},n)=>d.jsx(Lt.Item,{ref:n,className:ae("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",e),...t}));Uh.displayName=Lt.Item.displayName;function qS(e,[t,n]){return Math.min(n,Math.max(t,e))}function GS(e,t){return w.useReducer((n,r)=>t[n][r]??n,e)}var $a="ScrollArea",[Wh,YC]=Rn($a),[YS,Zt]=Wh($a),Vh=w.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:s=600,...i}=e,[a,c]=w.useState(null),[l,u]=w.useState(null),[f,h]=w.useState(null),[p,m]=w.useState(null),[g,b]=w.useState(null),[v,y]=w.useState(0),[T,I]=w.useState(0),[k,S]=w.useState(!1),[E,j]=w.useState(!1),_=et(t,L=>c(L)),D=oa(o);return d.jsx(YS,{scope:n,type:r,dir:D,scrollHideDelay:s,scrollArea:a,viewport:l,onViewportChange:u,content:f,onContentChange:h,scrollbarX:p,onScrollbarXChange:m,scrollbarXEnabled:k,onScrollbarXEnabledChange:S,scrollbarY:g,onScrollbarYChange:b,scrollbarYEnabled:E,onScrollbarYEnabledChange:j,onCornerWidthChange:y,onCornerHeightChange:I,children:d.jsx(Pe.div,{dir:D,...i,ref:_,style:{position:"relative","--radix-scroll-area-corner-width":v+"px","--radix-scroll-area-corner-height":T+"px",...e.style}})})});Vh.displayName=$a;var Kh="ScrollAreaViewport",qh=w.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...s}=e,i=Zt(Kh,n),a=w.useRef(null),c=et(t,a,i.onViewportChange);return d.jsxs(d.Fragment,{children:[d.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:o}),d.jsx(Pe.div,{"data-radix-scroll-area-viewport":"",...s,ref:c,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style},children:d.jsx("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});qh.displayName=Kh;var wn="ScrollAreaScrollbar",Fa=w.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Zt(wn,e.__scopeScrollArea),{onScrollbarXEnabledChange:s,onScrollbarYEnabledChange:i}=o,a=e.orientation==="horizontal";return w.useEffect(()=>(a?s(!0):i(!0),()=>{a?s(!1):i(!1)}),[a,s,i]),o.type==="hover"?d.jsx(XS,{...r,ref:t,forceMount:n}):o.type==="scroll"?d.jsx(JS,{...r,ref:t,forceMount:n}):o.type==="auto"?d.jsx(Gh,{...r,ref:t,forceMount:n}):o.type==="always"?d.jsx(za,{...r,ref:t}):null});Fa.displayName=wn;var XS=w.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Zt(wn,e.__scopeScrollArea),[s,i]=w.useState(!1);return w.useEffect(()=>{const a=o.scrollArea;let c=0;if(a){const l=()=>{window.clearTimeout(c),i(!0)},u=()=>{c=window.setTimeout(()=>i(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",l),a.addEventListener("pointerleave",u),()=>{window.clearTimeout(c),a.removeEventListener("pointerenter",l),a.removeEventListener("pointerleave",u)}}},[o.scrollArea,o.scrollHideDelay]),d.jsx(Vt,{present:n||s,children:d.jsx(Gh,{"data-state":s?"visible":"hidden",...r,ref:t})})}),JS=w.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Zt(wn,e.__scopeScrollArea),s=e.orientation==="horizontal",i=js(()=>c("SCROLL_END"),100),[a,c]=GS("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return w.useEffect(()=>{if(a==="idle"){const l=window.setTimeout(()=>c("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(l)}},[a,o.scrollHideDelay,c]),w.useEffect(()=>{const l=o.viewport,u=s?"scrollLeft":"scrollTop";if(l){let f=l[u];const h=()=>{const p=l[u];f!==p&&(c("SCROLL"),i()),f=p};return l.addEventListener("scroll",h),()=>l.removeEventListener("scroll",h)}},[o.viewport,s,c,i]),d.jsx(Vt,{present:n||a!=="hidden",children:d.jsx(za,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:Se(e.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:Se(e.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),Gh=w.forwardRef((e,t)=>{const n=Zt(wn,e.__scopeScrollArea),{forceMount:r,...o}=e,[s,i]=w.useState(!1),a=e.orientation==="horizontal",c=js(()=>{if(n.viewport){const l=n.viewport.offsetWidth<n.viewport.scrollWidth,u=n.viewport.offsetHeight<n.viewport.scrollHeight;i(a?l:u)}},10);return Nr(n.viewport,c),Nr(n.content,c),d.jsx(Vt,{present:r||s,children:d.jsx(za,{"data-state":s?"visible":"hidden",...o,ref:t})})}),za=w.forwardRef((e,t)=>{const{orientation:n="vertical",...r}=e,o=Zt(wn,e.__scopeScrollArea),s=w.useRef(null),i=w.useRef(0),[a,c]=w.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),l=Qh(a.viewport,a.content),u={...r,sizes:a,onSizesChange:c,hasThumb:l>0&&l<1,onThumbChange:h=>s.current=h,onThumbPointerUp:()=>i.current=0,onThumbPointerDown:h=>i.current=h};function f(h,p){return rC(h,i.current,a,p)}return n==="horizontal"?d.jsx(ZS,{...u,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollLeft,p=ep(h,a,o.dir);s.current.style.transform=`translate3d(${p}px, 0, 0)`}},onWheelScroll:h=>{o.viewport&&(o.viewport.scrollLeft=h)},onDragScroll:h=>{o.viewport&&(o.viewport.scrollLeft=f(h,o.dir))}}):n==="vertical"?d.jsx(QS,{...u,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollTop,p=ep(h,a);s.current.style.transform=`translate3d(0, ${p}px, 0)`}},onWheelScroll:h=>{o.viewport&&(o.viewport.scrollTop=h)},onDragScroll:h=>{o.viewport&&(o.viewport.scrollTop=f(h))}}):null}),ZS=w.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=Zt(wn,e.__scopeScrollArea),[i,a]=w.useState(),c=w.useRef(null),l=et(t,c,s.onScrollbarXChange);return w.useEffect(()=>{c.current&&a(getComputedStyle(c.current))},[c]),d.jsx(Xh,{"data-orientation":"horizontal",...o,ref:l,sizes:n,style:{bottom:0,left:s.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:s.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":_s(n)+"px",...e.style},onThumbPointerDown:u=>e.onThumbPointerDown(u.x),onDragScroll:u=>e.onDragScroll(u.x),onWheelScroll:(u,f)=>{if(s.viewport){const h=s.viewport.scrollLeft+u.deltaX;e.onWheelScroll(h),np(h,f)&&u.preventDefault()}},onResize:()=>{c.current&&s.viewport&&i&&r({content:s.viewport.scrollWidth,viewport:s.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:Ns(i.paddingLeft),paddingEnd:Ns(i.paddingRight)}})}})}),QS=w.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=Zt(wn,e.__scopeScrollArea),[i,a]=w.useState(),c=w.useRef(null),l=et(t,c,s.onScrollbarYChange);return w.useEffect(()=>{c.current&&a(getComputedStyle(c.current))},[c]),d.jsx(Xh,{"data-orientation":"vertical",...o,ref:l,sizes:n,style:{top:0,right:s.dir==="ltr"?0:void 0,left:s.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":_s(n)+"px",...e.style},onThumbPointerDown:u=>e.onThumbPointerDown(u.y),onDragScroll:u=>e.onDragScroll(u.y),onWheelScroll:(u,f)=>{if(s.viewport){const h=s.viewport.scrollTop+u.deltaY;e.onWheelScroll(h),np(h,f)&&u.preventDefault()}},onResize:()=>{c.current&&s.viewport&&i&&r({content:s.viewport.scrollHeight,viewport:s.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:Ns(i.paddingTop),paddingEnd:Ns(i.paddingBottom)}})}})}),[eC,Yh]=Wh(wn),Xh=w.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:s,onThumbPointerUp:i,onThumbPointerDown:a,onThumbPositionChange:c,onDragScroll:l,onWheelScroll:u,onResize:f,...h}=e,p=Zt(wn,n),[m,g]=w.useState(null),b=et(t,_=>g(_)),v=w.useRef(null),y=w.useRef(""),T=p.viewport,I=r.content-r.viewport,k=St(u),S=St(c),E=js(f,10);function j(_){if(v.current){const D=_.clientX-v.current.left,L=_.clientY-v.current.top;l({x:D,y:L})}}return w.useEffect(()=>{const _=D=>{const L=D.target;(m==null?void 0:m.contains(L))&&k(D,I)};return document.addEventListener("wheel",_,{passive:!1}),()=>document.removeEventListener("wheel",_,{passive:!1})},[T,m,I,k]),w.useEffect(S,[r,S]),Nr(m,E),Nr(p.content,E),d.jsx(eC,{scope:n,scrollbar:m,hasThumb:o,onThumbChange:St(s),onThumbPointerUp:St(i),onThumbPositionChange:S,onThumbPointerDown:St(a),children:d.jsx(Pe.div,{...h,ref:b,style:{position:"absolute",...h.style},onPointerDown:Se(e.onPointerDown,_=>{_.button===0&&(_.target.setPointerCapture(_.pointerId),v.current=m.getBoundingClientRect(),y.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",p.viewport&&(p.viewport.style.scrollBehavior="auto"),j(_))}),onPointerMove:Se(e.onPointerMove,j),onPointerUp:Se(e.onPointerUp,_=>{const D=_.target;D.hasPointerCapture(_.pointerId)&&D.releasePointerCapture(_.pointerId),document.body.style.webkitUserSelect=y.current,p.viewport&&(p.viewport.style.scrollBehavior=""),v.current=null})})})}),As="ScrollAreaThumb",Jh=w.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Yh(As,e.__scopeScrollArea);return d.jsx(Vt,{present:n||o.hasThumb,children:d.jsx(tC,{ref:t,...r})})}),tC=w.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,s=Zt(As,n),i=Yh(As,n),{onThumbPositionChange:a}=i,c=et(t,f=>i.onThumbChange(f)),l=w.useRef(void 0),u=js(()=>{l.current&&(l.current(),l.current=void 0)},100);return w.useEffect(()=>{const f=s.viewport;if(f){const h=()=>{if(u(),!l.current){const p=oC(f,a);l.current=p,a()}};return a(),f.addEventListener("scroll",h),()=>f.removeEventListener("scroll",h)}},[s.viewport,u,a]),d.jsx(Pe.div,{"data-state":i.hasThumb?"visible":"hidden",...o,ref:c,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:Se(e.onPointerDownCapture,f=>{const p=f.target.getBoundingClientRect(),m=f.clientX-p.left,g=f.clientY-p.top;i.onThumbPointerDown({x:m,y:g})}),onPointerUp:Se(e.onPointerUp,i.onThumbPointerUp)})});Jh.displayName=As;var Ba="ScrollAreaCorner",Zh=w.forwardRef((e,t)=>{const n=Zt(Ba,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?d.jsx(nC,{...e,ref:t}):null});Zh.displayName=Ba;var nC=w.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=Zt(Ba,n),[s,i]=w.useState(0),[a,c]=w.useState(0),l=!!(s&&a);return Nr(o.scrollbarX,()=>{var f;const u=((f=o.scrollbarX)==null?void 0:f.offsetHeight)||0;o.onCornerHeightChange(u),c(u)}),Nr(o.scrollbarY,()=>{var f;const u=((f=o.scrollbarY)==null?void 0:f.offsetWidth)||0;o.onCornerWidthChange(u),i(u)}),l?d.jsx(Pe.div,{...r,ref:t,style:{width:s,height:a,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function Ns(e){return e?parseInt(e,10):0}function Qh(e,t){const n=e/t;return isNaN(n)?0:n}function _s(e){const t=Qh(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function rC(e,t,n,r="ltr"){const o=_s(n),s=o/2,i=t||s,a=o-i,c=n.scrollbar.paddingStart+i,l=n.scrollbar.size-n.scrollbar.paddingEnd-a,u=n.content-n.viewport,f=r==="ltr"?[0,u]:[u*-1,0];return tp([c,l],f)(e)}function ep(e,t,n="ltr"){const r=_s(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,s=t.scrollbar.size-o,i=t.content-t.viewport,a=s-r,c=n==="ltr"?[0,i]:[i*-1,0],l=qS(e,c);return tp([0,i],[0,a])(l)}function tp(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function np(e,t){return e>0&&e<t}var oC=(e,t=()=>{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const s={left:e.scrollLeft,top:e.scrollTop},i=n.left!==s.left,a=n.top!==s.top;(i||a)&&t(),n=s,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function js(e,t){const n=St(e),r=w.useRef(0);return w.useEffect(()=>()=>window.clearTimeout(r.current),[]),w.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function Nr(e,t){const n=St(t);hn(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}var rp=Vh,sC=qh,iC=Zh;const op=w.forwardRef(({className:e,children:t,...n},r)=>d.jsxs(rp,{ref:r,className:ae("relative overflow-hidden",e),...n,children:[d.jsx(sC,{className:"h-full w-full rounded-[inherit] overflow-auto",children:t}),d.jsx(sp,{}),d.jsx(iC,{})]}));op.displayName=rp.displayName;const sp=w.forwardRef(({className:e,orientation:t="vertical",...n},r)=>d.jsx(Fa,{ref:r,orientation:t,className:ae("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:d.jsx(Jh,{className:"relative flex-1 rounded-full bg-border"})}));sp.displayName=Fa.displayName;function Ha({thread:e,isActive:t=!1,editingThreadId:n,editingTitle:r="",onSelect:o,onStartEditing:s,onEditingTitleChange:i,onSaveEditing:a,onCancelEditing:c,onShare:l,onDelete:u,showEditTitle:f=!0,showDeleteButton:h=!0,formatDate:p,getDisplayThreadTitle:m,itemClassName:g,activeItemClassName:b,secondaryLine:v}){const y=n===e.threadId,T=x.useMemo(()=>(m==null?void 0:m(e))??e.title??e.threadId,[m,e]),I=()=>o==null?void 0:o(e.threadId),k=S=>s==null?void 0:s(e,S);return d.jsxs("div",{className:ae("flex items-center justify-between rounded px-2 py-1 text-sm hover:bg-muted cursor-pointer",g,t&&(b??"bg-muted/70")),onClick:I,children:[d.jsxs("div",{className:"flex flex-col min-w-0",children:[y?d.jsx("input",{className:"text-sm px-2 py-1 border rounded",value:r,onChange:S=>i==null?void 0:i(S.target.value)}):d.jsx("span",{className:"font-medium truncate",children:T}),v&&d.jsx("span",{className:"text-xs text-muted-foreground truncate",children:v}),p&&e.updatedAt&&d.jsx("span",{className:"text-[10px] text-muted-foreground",children:p(e.updatedAt)})]}),d.jsx("div",{className:"flex items-center gap-1",children:y?d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx(Ke,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:S=>{S.stopPropagation(),a==null||a(e)},children:"Save"}),d.jsx(Ke,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:S=>{S.stopPropagation(),c==null||c(e)},children:"Cancel"})]}):d.jsxs(Aa,{children:[d.jsx(Na,{asChild:!0,children:d.jsxs(Ke,{size:"sm",variant:"ghost",className:"h-8 w-8 p-0 opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100 transition-opacity",onClick:S=>S.stopPropagation(),children:[d.jsx(pe.MoreVertical,{className:"h-4 w-4"}),d.jsx("span",{className:"sr-only",children:"Open menu"})]})}),d.jsxs(Es,{align:"end",children:[f&&d.jsxs(nr,{onClick:S=>{S.stopPropagation(),k(S)},children:[d.jsx(pe.Edit3,{className:"mr-2 h-4 w-4"}),d.jsx("span",{children:"Rename"})]}),l&&d.jsxs(nr,{onClick:S=>{S.stopPropagation(),l(e)},children:[d.jsx(pe.Share2,{className:"mr-2 h-4 w-4"}),d.jsx("span",{children:"Share"})]}),h&&d.jsxs(nr,{onClick:S=>{S.stopPropagation(),u==null||u(e)},className:"text-destructive focus:text-destructive",children:[d.jsx(pe.Trash2,{className:"mr-2 h-4 w-4"}),d.jsx("span",{children:"Delete"})]})]})]})})]})}var Ps="Collapsible",[aC,XC]=Rn(Ps),[lC,Ua]=aC(Ps),ip=w.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:o,disabled:s,onOpenChange:i,...a}=e,[c,l]=qo({prop:r,defaultProp:o??!1,onChange:i,caller:Ps});return d.jsx(lC,{scope:n,disabled:s,contentId:Wt(),open:c,onOpenToggle:w.useCallback(()=>l(u=>!u),[l]),children:d.jsx(Pe.div,{"data-state":Va(c),"data-disabled":s?"":void 0,...a,ref:t})})});ip.displayName=Ps;var ap="CollapsibleTrigger",lp=w.forwardRef((e,t)=>{const{__scopeCollapsible:n,...r}=e,o=Ua(ap,n);return d.jsx(Pe.button,{type:"button","aria-controls":o.contentId,"aria-expanded":o.open||!1,"data-state":Va(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...r,ref:t,onClick:Se(e.onClick,o.onOpenToggle)})});lp.displayName=ap;var Wa="CollapsibleContent",cp=w.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Ua(Wa,e.__scopeCollapsible);return d.jsx(Vt,{present:n||o.open,children:({present:s})=>d.jsx(cC,{...r,ref:t,present:s})})});cp.displayName=Wa;var cC=w.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:r,children:o,...s}=e,i=Ua(Wa,n),[a,c]=w.useState(r),l=w.useRef(null),u=et(t,l),f=w.useRef(0),h=f.current,p=w.useRef(0),m=p.current,g=i.open||a,b=w.useRef(g),v=w.useRef(void 0);return w.useEffect(()=>{const y=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(y)},[]),hn(()=>{const y=l.current;if(y){v.current=v.current||{transitionDuration:y.style.transitionDuration,animationName:y.style.animationName},y.style.transitionDuration="0s",y.style.animationName="none";const T=y.getBoundingClientRect();f.current=T.height,p.current=T.width,b.current||(y.style.transitionDuration=v.current.transitionDuration,y.style.animationName=v.current.animationName),c(r)}},[i.open,r]),d.jsx(Pe.div,{"data-state":Va(i.open),"data-disabled":i.disabled?"":void 0,id:i.contentId,hidden:!g,...s,ref:u,style:{"--radix-collapsible-content-height":h?`${h}px`:void 0,"--radix-collapsible-content-width":m?`${m}px`:void 0,...e.style},children:g&&o})});function Va(e){return e?"open":"closed"}var uC=ip;const Os=uC,Rs=lp,Ms=cp,up=25,dp=En.threadManagerView,dC=e=>e==="default"||e==="shared",fC=()=>{if(typeof window>"u")return null;try{const e=window.localStorage.getItem(dp);if(dC(e))return e}catch{}return null};function fp({defaultView:e}={}){const[t,n]=x.useState(()=>fC()??e??"default");x.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(dp,t)}catch{}},[t]);const r=x.useCallback(o=>{n(o)},[]);return{view:t,setView:r}}const hC=[{key:"default",label:"My chats"},{key:"shared",label:"Shared with you"}];function Ds({className:e="",showCreateButton:t=!0,showDeleteButton:n=!0,showEditTitle:r=!0,maxHeight:o="400px",customStyles:s={},currentThreadId:i=null,navigateToThread:a,onThreadSelect:c,onThreadCreate:l,onThreadDelete:u,view:f,defaultView:h,onViewChange:p,viewOptions:m,viewState:g,showHeader:b=!0,shareTargets:v,isLoadingShareTargets:y,shareTargetFilter:T,groupBy:I,menuItem:k}){const{chatApi:S,authApi:E}=Vn(),{threads:j,sharedThreads:_,currentThreadId:D,setCurrentThreadId:L,isLoading:W,isLoadingSharedThreads:V,actions:$,shareInFlight:Z,shareStatus:X,clearShareStatus:oe}=ur(),{createThread:U,deleteThread:F,renameThread:G,shareThread:H}=$,{loadThread:A}=Ur(),N=i??D,[R,M]=x.useState(Array.isArray(j)?j:[]),q=x.useRef(R.length>0),J=x.useRef(null),P=x.useRef(0),[K,te]=x.useState(null),[le,he]=x.useState(""),[ue,ge]=x.useState(!1),[be,Be]=x.useState(!1),[Le,je]=x.useState(null),[Fe,tt]=x.useState(""),[mt,ot]=x.useState([]),[ze,Me]=x.useState(!1),Ze=x.useCallback(Y=>he(Y),[]);x.useEffect(()=>{be&&!v&&mt.length===0&&!ze&&(async()=>{Me(!0);try{const Q=(await E.listUsers()).filter(C=>C.id||C.user_id).map(C=>({type:"user",value:C.user_id||C.id||"",id:C.user_id||C.id||"",label:C.name||C.username||C.email||"Unknown User",secondaryLabel:C.name||C.username?C.email:void 0}));ot(Q)}catch(fe){console.error("Failed to load users for sharing:",fe)}finally{Me(!1)}})()},[be,v,mt.length,ze,S]);const rt=v??mt,qe=y??ze,ht=m&&m.length>0?m:hC,xt=fp({defaultView:h}),He=g??xt,st=f??He.view,an=x.useCallback(Y=>{f||He.setView(Y),p==null||p(Y)},[f,p,He]),jt=ht.find(Y=>Y.key===st)??ht[0],ct=Y=>{je(Y),tt(""),Be(!0)},kt=()=>{Be(!1),je(null),tt(""),oe()},Tt=x.useCallback(async Y=>{if(!(!Le||Z)&&Y.id)try{await H(Le,Y.id),setTimeout(()=>kt(),600)}catch(fe){console.error("Failed to share thread:",fe)}},[kt,Z,Le,H]),bt=x.useMemo(()=>{const Y=rt,fe=Fe.trim().toLowerCase();return fe?T?Y.filter(Q=>T(Q,fe)):Y.filter(Q=>`${Q.label} ${Q.secondaryLabel??""}`.toLowerCase().includes(fe)):Y},[v,Fe,T]),Ge=st==="shared",gt=Ge?_:R,ut=x.useMemo(()=>{if(!I||Ge)return null;const Y="Default",fe=C=>{if(!C)return"Older";try{const O=C.endsWith("Z")||C.includes("+")?C:`${C}Z`,z=new Date(O),se=new Date,ie=new Date(se.getFullYear(),se.getMonth(),se.getDate()),Ce=new Date(z.getFullYear(),z.getMonth(),z.getDate()),Te=Math.floor((ie.getTime()-Ce.getTime())/(1e3*60*60*24));return Te===0?"Today":Te===1?"Yesterday":Te<=7?"Last 7 Days":"Older"}catch{return"Older"}};if(I==="project"){const C={};return gt.forEach(O=>{var Ce,Te;const z=((Ce=O.project)==null?void 0:Ce.name)||((Te=O.project)==null?void 0:Te.id)||Y,se=O.menuItem||k||"Default",ie=fe(O.updatedAt);C[z]||(C[z]={}),C[z][se]||(C[z][se]={}),C[z][se][ie]||(C[z][se][ie]=[]),C[z][se][ie].push(O)}),Object.values(C).forEach(O=>{Object.values(O).forEach(z=>{Object.values(z).forEach(se=>{se.sort((ie,Ce)=>new Date(Ce.updatedAt||Ce.createdAt||"").getTime()-new Date(ie.updatedAt||ie.createdAt||"").getTime())})})}),{kind:"project-menu-date",groups:C}}const Q={};return gt.forEach(C=>{let O=Y;I in C&&(O=C[I]||Y),Q[O]||(Q[O]=[]),Q[O].push(C)}),Object.keys(Q).forEach(C=>{Q[C].sort((O,z)=>new Date(z.updatedAt||z.createdAt||"").getTime()-new Date(O.updatedAt||O.createdAt||"").getTime())}),{kind:"flat",groups:Q}},[gt,I,Ge]),$t=Ge?V:W,$e=Ge?"No shared conversations yet":"No conversations yet",Ee=Y=>{const fe=Y.sharedAt?` • ${Gt(Y.sharedAt)}`:"";return`Shared by ${Y.sharedByUserId}${fe}`},Ve=Y=>"sharedByUserId"in Y;x.useEffect(()=>{const Y=Array.isArray(j)?j:[];if(Y.length>0){q.current=!0,M(Y);return}W||(q.current=!1,M(Y))},[j,W]),x.useEffect(()=>{if(!J.current)return;const Y=J.current.querySelector("[data-radix-scroll-area-viewport]");if(!Y)return;let fe=null,Q=null;return fe=requestAnimationFrame(()=>{Q=requestAnimationFrame(()=>{Y.scrollTop=P.current})}),()=>{fe!==null&&cancelAnimationFrame(fe),Q!==null&&cancelAnimationFrame(Q)}},[R]);const dt=async Y=>{try{L(Y),await A(Y),a==null||a(Y),c==null||c(Y)}catch(fe){console.error("Failed to select thread:",fe)}},Et=async()=>{try{ge(!0);const Y=await U();Y&&(l==null||l(Y),a==null||a(Y))}catch(Y){console.error("Failed to create thread:",Y)}finally{ge(!1)}},Ft=async(Y,fe)=>{const Q=Y.threadId;if(confirm("Delete this thread?")){if(J.current){const C=J.current.querySelector("[data-radix-scroll-area-viewport]");C&&(P.current=C.scrollTop)}try{await F(Q),u==null||u(Q)}catch(C){console.error("Failed to delete thread:",C)}}},zt=(Y,fe)=>{fe==null||fe.stopPropagation(),te(Y.threadId),he(Y.title||`Thread ${Y.threadId.slice(0,8)}`)},kn=async Y=>{const fe=typeof Y=="string"?Y:Y.threadId;if(le.trim())try{await G(fe,le.trim()),te(null),he("")}catch(Q){console.error("Failed to update title:",Q)}},Tn=Y=>{te(null),he("")},Gt=Y=>{if(!Y)return"";try{const fe=Y.endsWith("Z")||Y.includes("+")?Y:`${Y}Z`,Q=new Date(fe),O=new Date().getTime()-Q.getTime(),z=Math.floor(O/(1e3*60*60*24));return z===0?Q.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):z===1?"Yesterday":z<7?`${z} days ago`:Q.toLocaleDateString()}catch{return""}},vn=Y=>Y.title||`Thread ${Y.threadId.slice(0,8)}`,ln=Y=>{const fe=vn(Y);return fe.length<=up?fe:`${fe.slice(0,up)}...`};return d.jsxs("div",{className:`thread-manager-root flex flex-col h-full ${e} ${s.container||""}`,children:[b&&d.jsxs("div",{className:s.header||"flex flex-col gap-2 px-1 py-0 border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-900 shadow-sm",children:[t&&d.jsx("div",{className:"flex justify-end",children:d.jsxs(Ke,{onClick:Et,disabled:ue||W,className:s.createButton||"px-3 py-2 gap-1",size:"sm",variant:"ghost",title:ue?"Creating...":"New Chat",children:[d.jsx(pe.Edit3,{size:16}),d.jsx("span",{children:"New chat"})]})}),d.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-slate-700 dark:text-slate-200 uppercase tracking-wide leading-tight",children:[d.jsx("span",{children:"Current View"}),d.jsxs(Aa,{children:[d.jsx(Na,{asChild:!0,children:d.jsx(Ke,{variant:"outline",size:"sm",className:"text-[11px] text-slate-700 dark:text-slate-200 border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-900 hover:bg-slate-50 dark:hover:bg-slate-800 px-2 py-0",children:jt.label})}),d.jsx(Es,{align:"start",sideOffset:6,className:"w-40",children:ht.map(Y=>d.jsxs(nr,{className:"justify-between text-[12px]",onClick:fe=>{fe.preventDefault(),an(Y.key)},children:[d.jsx("span",{children:Y.label}),st===Y.key&&d.jsx(pe.Check,{className:"h-3 w-3"})]},Y.key))})]})]})]}),d.jsx(op,{ref:J,className:`flex-1 min-h-0 ${s.threadList||""}`,style:o?{maxHeight:o}:void 0,children:d.jsx("div",{className:"p-2 space-y-1 pb-4",children:$t?d.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-8 text-slate-400",children:[d.jsx(pe.Loader2,{className:"h-5 w-5 animate-spin"}),d.jsx("span",{className:"text-sm",children:"Loading threads…"})]}):gt.length===0?d.jsxs("div",{className:"text-center py-8 text-slate-400",children:[d.jsx(pe.MessageSquare,{className:"w-8 h-8 mx-auto mb-2 opacity-40 text-slate-500"}),d.jsx("p",{className:"text-sm text-slate-500",children:$e})]}):ut?ut.kind==="project-menu-date"?Object.entries(ut.groups).sort(([Y],[fe])=>{const Q="Default";return Y===Q?1:fe===Q?-1:Y.localeCompare(fe)}).map(([Y,fe])=>d.jsxs(Os,{defaultOpen:!0,className:"group/collapsible",children:[d.jsxs(Rs,{className:"flex items-center w-full px-2 py-1 text-xs font-semibold text-slate-600 hover:text-slate-900 dark:hover:text-slate-200",children:[d.jsx(pe.ChevronRight,{className:"w-3 h-3 mr-1 transition-transform group-data-[state=open]/collapsible:rotate-90"}),Y,d.jsx("span",{className:"ml-auto text-[10px] text-slate-400",children:Object.values(fe).reduce((Q,C)=>Q+Object.values(C).reduce((O,z)=>O+z.length,0),0)})]}),d.jsx(Ms,{children:d.jsx("div",{className:"pl-2 border-l border-slate-100 dark:border-slate-800 ml-1.5 my-1 space-y-1",children:Object.entries(fe).sort(([Q],[C])=>Q.localeCompare(C)).map(([Q,C])=>d.jsxs(Os,{defaultOpen:!0,className:"group/collapsible",children:[d.jsxs(Rs,{className:"flex items-center w-full px-2 py-1 text-[11px] font-medium text-slate-500 hover:text-slate-800 dark:hover:text-slate-200",children:[d.jsx(pe.ChevronRight,{className:"w-3 h-3 mr-1 transition-transform group-data-[state=open]/collapsible:rotate-90"}),Q,d.jsx("span",{className:"ml-auto text-[10px] text-slate-400",children:Object.values(C).reduce((O,z)=>O+z.length,0)})]}),d.jsx(Ms,{children:d.jsx("div",{className:"pl-2 border-l border-slate-100 dark:border-slate-800 ml-1.5 my-1 space-y-1",children:Object.entries(C).sort(([O],[z])=>{const se=["Today","Yesterday","Last 7 Days","Older"],ie=se.indexOf(O),Ce=se.indexOf(z);return ie!==-1||Ce!==-1?(ie===-1?se.length:ie)-(Ce===-1?se.length:Ce):O.localeCompare(z)}).map(([O,z])=>d.jsxs(Os,{defaultOpen:!0,className:"group/collapsible",children:[d.jsxs(Rs,{className:"flex items-center w-full px-2 py-1 text-[10px] font-medium text-slate-400 hover:text-slate-600 dark:hover:text-slate-300",children:[d.jsx(pe.ChevronRight,{className:"w-3 h-3 mr-1 transition-transform group-data-[state=open]/collapsible:rotate-90"}),O,d.jsx("span",{className:"ml-auto text-[10px] text-slate-400",children:z.length})]}),d.jsx(Ms,{children:d.jsx("div",{className:"pl-2 border-l border-slate-100 dark:border-slate-800 ml-1.5 my-1 space-y-1",children:z.map(se=>d.jsx(Ha,{thread:se,isActive:N===se.threadId,editingThreadId:K,editingTitle:le,onSelect:dt,onStartEditing:zt,onEditingTitleChange:Ze,onSaveEditing:ie=>void kn(ie),onCancelEditing:ie=>Tn(),onShare:ie=>ct(ie.threadId),onDelete:ie=>Ft(ie),showEditTitle:r,showDeleteButton:n,formatDate:Gt,getDisplayThreadTitle:ln,itemClassName:s.threadItem,activeItemClassName:s.activeThread},se.threadId))})})]},`${Y}-${Q}-${O}`))})})]},`${Y}-${Q}`))})})]},Y)):Object.entries(ut.groups).sort(([Y],[fe])=>{const Q="Default";return Y===Q?1:fe===Q?-1:Y.localeCompare(fe)}).map(([Y,fe])=>d.jsxs(Os,{defaultOpen:!0,className:"group/collapsible",children:[d.jsxs(Rs,{className:"flex items-center w-full px-2 py-1 text-xs font-medium text-slate-500 hover:text-slate-800 dark:hover:text-slate-200",children:[d.jsx(pe.ChevronRight,{className:"w-3 h-3 mr-1 transition-transform group-data-[state=open]/collapsible:rotate-90"}),Y,d.jsx("span",{className:"ml-auto text-[10px] text-slate-400",children:fe.length})]}),d.jsx(Ms,{children:d.jsx("div",{className:"pl-2 border-l border-slate-100 dark:border-slate-800 ml-1.5 my-1 space-y-1",children:fe.map(Q=>d.jsx(Ha,{thread:Q,isActive:N===Q.threadId,editingThreadId:K,editingTitle:le,onSelect:dt,onStartEditing:zt,onEditingTitleChange:Ze,onSaveEditing:C=>void kn(C),onCancelEditing:C=>Tn(),onShare:C=>ct(C.threadId),onDelete:C=>Ft(C),showEditTitle:r,showDeleteButton:n,formatDate:Gt,getDisplayThreadTitle:ln,itemClassName:s.threadItem,activeItemClassName:s.activeThread},Q.threadId))})})]},Y)):gt.slice().sort((Y,fe)=>new Date(fe.updatedAt||fe.createdAt||"").getTime()-new Date(Y.updatedAt||Y.createdAt||"").getTime()).map(Y=>d.jsx(Ha,{thread:Y,isActive:N===Y.threadId,editingThreadId:K,editingTitle:le,onSelect:dt,onStartEditing:zt,onEditingTitleChange:Ze,onSaveEditing:fe=>void kn(fe),onCancelEditing:fe=>Tn(),onShare:fe=>ct(fe.threadId),onDelete:fe=>Ft(fe),showEditTitle:r,showDeleteButton:n,formatDate:Gt,getDisplayThreadTitle:ln,secondaryLine:Ge&&Ve(Y)?Ee(Y):void 0,itemClassName:s.threadItem,activeItemClassName:s.activeThread},Y.threadId))})}),d.jsx(xd,{open:be,onOpenChange:Y=>!Y&&kt(),children:d.jsxs(Yi,{className:"max-w-md p-0",children:[d.jsx(wd,{children:d.jsx(vd,{children:"Share thread"})}),d.jsxs($h,{children:[d.jsx(Fh,{autoFocus:!0,value:Fe,onValueChange:Y=>tt(Y),placeholder:"Search for recipients..."}),d.jsxs(zh,{children:[X&&d.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 text-xs text-muted-foreground",children:[Z&&d.jsx(pe.Loader2,{className:"h-3 w-3 animate-spin"}),d.jsx("span",{className:X.startsWith("Failed")?"text-red-500":X.startsWith("Shared")?"text-emerald-500":"text-slate-600 dark:text-slate-400",children:X})]}),d.jsx(Bh,{children:qe?d.jsxs("span",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[d.jsx(pe.Loader2,{className:"h-4 w-4 animate-spin"}),"Loading recipients…"]}):"No matching recipients found"}),bt.length>0&&d.jsx(Hh,{heading:"Recipients",children:bt.map(Y=>d.jsx(Uh,{onSelect:()=>Tt(Y),children:d.jsxs("div",{className:"flex flex-col items-start text-sm",children:[d.jsx("span",{className:"font-medium",children:Y.label}),Y.secondaryLabel&&d.jsx("span",{className:"text-xs text-muted-foreground",children:Y.secondaryLabel})]})},Y.id))})]})]})]})})]})}function pC({layout:e="sidebar",layoutSize:t="desktop",showThreads:n=!0,className:r="",customStyles:o={},payloadExtras:s={},...i}){const a=u=>{const f="h-full";switch(u){case"phone":return`${f} max-w-none`;case"tablet":return`${f} max-w-4xl mx-auto`;case"half-screen":return`${f} max-w-2xl`;case"desktop":default:return`${f} max-w-7xl mx-auto`}},c=u=>({"--chat-sidebar-width":u==="phone"?"100%":u==="tablet"?"280px":u==="half-screen"?"240px":"320px","--chat-message-max-width":u==="phone"?"95%":u==="tablet"?"90%":u==="half-screen"?"85%":"80%","--chat-input-height":u==="phone"?"120px":"100px"}),l=x.useCallback(u=>{var f;(f=i.onThreadChange)==null||f.call(i,u)},[i]);return e==="fullscreen"?d.jsx(Wr,{...i,onThreadChange:l,children:d.jsx("div",{className:`${a(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:c(t),children:d.jsx(Er,{className:"flex-1",onError:i.onError,enableFileUpload:!0,payloadExtras:s})})}):e==="tabs"?d.jsx(Wr,{...i,onThreadChange:l,children:d.jsx("div",{className:`${a(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:c(t),children:d.jsxs("div",{className:"flex-1 flex min-h-0 overflow-hidden",children:[n&&d.jsx("div",{className:`w-80 border-r flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:d.jsx(Ds,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),d.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:d.jsx(Er,{onError:i.onError,enableFileUpload:!0,payloadExtras:s})})]})})}):d.jsx(Wr,{...i,onThreadChange:l,children:d.jsxs("div",{className:`${a(t)} flex overflow-hidden ${r} ${o.container||""}`,style:c(t),children:[n&&d.jsx("div",{className:`w-80 border-r bg-gray-50 flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:d.jsx(Ds,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),d.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:d.jsx(Er,{onError:i.onError,enableFileUpload:!0,payloadExtras:s})})]})})}function mC({placeholder:e,onMessageSent:t}){const[n,r]=x.useState("chat");return d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsxs("div",{className:"flex border-b border-gray-200 bg-gray-50",children:[d.jsx("button",{onClick:()=>r("chat"),className:`flex-1 px-3 py-2 text-sm font-medium transition-colors ${n==="chat"?"border-b-2 border-slate-800 text-slate-800 bg-white":"text-gray-600 hover:text-gray-800"}`,children:d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx(pe.MessageSquare,{size:14}),"Chat"]})}),d.jsx("button",{onClick:()=>r("threads"),className:`flex-1 px-3 py-2 text-sm font-medium transition-colors ${n==="threads"?"border-b-2 border-slate-800 text-slate-800 bg-white":"text-gray-600 hover:text-gray-800"}`,children:d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx(pe.History,{size:14}),"History"]})})]}),d.jsx("div",{className:"flex-1 min-h-0",children:n==="chat"?d.jsx(Er,{placeholder:e??"Ask Serti AI anything...",className:"h-full",onMessageSent:t}):d.jsx(Ds,{showCreateButton:!0,className:"h-full",onThreadSelect:()=>r("chat")})})]})}function gC({className:e="",placeholder:t,isAuthenticated:n=!0,onMessageSent:r,widgetTitle:o="Serti AI Navigator",widgetSubtitle:s="AI-Powered Assistant",...i}){const[a,c]=x.useState(!1);return n?d.jsx(Wr,{...i,children:d.jsx("div",{className:`fixed bottom-6 right-6 z-[9999] transition-all duration-300 ${e}`,children:d.jsxs("div",{className:`w-96 bg-white rounded-xl shadow-2xl border border-gray-200 overflow-hidden relative ${a?"scale-75":"scale-100"}`,children:[d.jsx("div",{className:"bg-slate-800 text-white p-4 flex-shrink-0",children:d.jsxs("div",{className:"flex items-center justify-between gap-3",children:[d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsxs("div",{className:"relative h-10 w-10 rounded-full bg-gradient-to-br from-slate-500 to-slate-700 border border-white/30 flex items-center justify-center text-white text-sm font-bold",children:["S",d.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-3 w-3 rounded-full border-2 border-slate-800 bg-emerald-400"})]}),d.jsxs("div",{className:"flex flex-col",children:[d.jsx("h3",{className:"text-lg font-semibold leading-tight",children:o}),d.jsx("p",{className:"text-xs text-white/70",children:s})]}),d.jsx("span",{className:"ml-2 inline-flex items-center justify-center rounded-full bg-red-500 px-2 py-0.5 text-[11px] font-semibold leading-none text-white",children:"1"})]}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx(Ke,{variant:"ghost",size:"sm",className:"text-white hover:bg-white/10 h-8 w-8 p-0",title:"Options",children:d.jsx(pe.MoreHorizontal,{size:16})}),d.jsx(Ke,{variant:"ghost",size:"sm",className:"text-white hover:bg-white/10 h-8 w-8 p-0",title:"Compose",children:d.jsx(pe.Edit3,{size:16})}),d.jsx(Ke,{variant:"ghost",size:"sm",onClick:l=>{l.stopPropagation(),c(u=>!u)},className:"text-white hover:bg-white/10 h-8 w-8 p-0",title:a?"Maximize":"Minimize",children:a?d.jsx(pe.Maximize2,{size:14}):d.jsx(pe.Minimize2,{size:14})})]})]})}),!a&&d.jsx("div",{className:"h-96 flex flex-col",children:d.jsx(mC,{placeholder:t,onMessageSent:r})})]})})}):null}function xC({label:e="New chat",children:t,className:n,variant:r="ghost",size:o="sm",...s}){return d.jsxs(Ke,{variant:r,size:o,className:ae("gap-2 rounded-full px-3 font-semibold transition-all hover:scale-[1.01]",n),...s,children:[d.jsx(pe.Edit3,{size:16}),t??e]})}function Ka({message:e,viewMode:t,isStreaming:n=!1,toolConfig:r,expandable:o=!1}){const{toolRenderers:s,toolArtifactRenderers:i}=r??{},a=jo(e),c=e.artifact??null,l=wv(e),f=(l?ic(l):null)??l,h=e.content.find(L=>L.type!=="tool_call"),p=L=>{if(L==null)return null;const W=typeof L=="string"?L:(()=>{try{return JSON.stringify(L,null,2)}catch{return String(L)}})();return d.jsx("pre",{className:"whitespace-pre-wrap break-words font-sans text-xs text-muted-foreground/80 bg-muted/30 p-2 rounded border border-border/50",children:W})},m=L=>p(L),g=()=>{if((f==null?void 0:f.kind)==="generic")return m(f.value);if(!h)return null;if(h.type==="text"){const L=h.text??"";return L?m(L):null}return m(h)},b=()=>(f==null?void 0:f.kind)==="dict"?m(f.data):g(),y=(()=>{if(!s)return;if(a.name){const W=s[a.name];if(W)return W}const L=(f==null?void 0:f.kind)??(l==null?void 0:l.kind);if(L){const W=s[L];if(W)return W}return s.default})(),T=b(),I=!o||t==="expanded",k=(I?y==null?void 0:y({message:e,toolMeta:a,toolPayload:f,viewMode:t,isStreaming:n}):null)??null,E=(()=>{if(!i)return;const L=c==null?void 0:c.type;if(typeof L=="string"){const W=i[L];if(W)return W}return i.default})(),j=E?E({artifact:c,message:e,toolPayload:f,isStreaming:n}):null,_=k??T,D=E?j:null;return d.jsxs("div",{className:"space-y-2",children:[n&&d.jsx(Pw,{artifact:c,showPartialData:!1}),c&&D,I?_:null]})}function bC({submit:e,chatRequest:t,lastCheckpointId:n,lastCheckpointNs:r,onMessageSent:o,onExcelUploadSuccess:s,onError:i,enableMessageEditing:a,messages:c,setPendingAssistantResponse:l,project:u,onEvent:f,activeThreadId:h,ensureValidToken:p}){const{messages:m}=ii(),[g,b]=x.useState(null),[v,y]=x.useState(""),[T,I]=x.useState(null),[k,S]=x.useState(null),[E,j]=x.useState(!1),[_,D]=x.useState(""),L=x.useRef(_),W=x.useRef(null);x.useEffect(()=>{if(!g)if(h){const A=localStorage.getItem(Ao(h));D(A||"")}else D("")},[h,g]);const V=x.useCallback(A=>{D(A),!g&&h&&localStorage.setItem(Ao(h),A)},[h,g]);x.useEffect(()=>{L.current=_},[_]),x.useEffect(()=>{if(!g){W.current=null;return}W.current===null&&(W.current=L.current),V(v??"")},[v,g,V]);const $=x.useCallback(A=>{V(A)},[V]),Z=async(A,N)=>{const R=Array.isArray(N)?{files:N}:N??{},M=R.files??[],q=R.contentParts??[],J=A.trim();if(!(!J&&M.length===0&&q.length===0))try{p&&await p();const P=M.map(async ge=>{try{const be=await Qs.uploadFile(ge);return{file:ge,record:be}}catch(be){throw console.error("Failed to upload file",ge.name,be),new Error(`Failed to upload ${ge.name}`)}}),te=(await Promise.all(P)).map(({record:ge})=>{const be=ge.mime_type;return be.startsWith("image/")?{type:"image_url",url:ge.content_url,mimeType:be,alt:ge.filename}:{type:"file",url:ge.content_url,mimeType:be,name:ge.filename,size:ge.size}}),le=[...q,...te],he=g?(T==null?void 0:T.checkpointId)??n??void 0:n??void 0,ue=g?(T==null?void 0:T.checkpointNs)??r??void 0:r??void 0;await e({text:J||"",contentParts:le,attachments:[],payload:t.payload},{checkpointId:he,checkpointNs:ue,project:u??void 0,edit:!!g,originalMessageId:g??void 0,config:t.config,onEvent:f}),o==null||o(J),l(!0),h&&localStorage.removeItem(Ao(h)),V(""),S(null),b(null),y(""),I(null)}catch(P){const K=(P==null?void 0:P.message)||"Failed to send message";S(K),i==null||i(K),l(!1)}},X=(A,N)=>{N||Z(A,{files:[]})},oe=x.useCallback(async A=>{await e({attachments:[A],payload:t.payload},{checkpointId:n??void 0,checkpointNs:r??void 0,project:u??void 0,config:t.config,onEvent:f}),s==null||s({file:A})},[n,r,t,s,e]),U=x.useCallback((A,N,R)=>{a&&(W.current=_,b(A),y(N),I({checkpointId:(R==null?void 0:R.checkpointId)??null,checkpointNs:(R==null?void 0:R.checkpointNs)??null}),S(null))},[_,a]),F=x.useCallback(()=>{b(null),y(""),I(null),S(null);const A=W.current;A!==null&&D(A),W.current=null},[]),G=x.useCallback(A=>{let N=null;for(let J=A-1;J>=0;J--)if(c[J].role==="user"){N=c[J];break}if(!N)return;const R=Array.isArray(N.content)?N.content:[],q=R.filter(J=>(J==null?void 0:J.type)==="text").map(J=>J.text).join("")||(()=>{try{return JSON.stringify(R,null,2)}catch{return String(R)}})();q&&e({text:q,payload:t.payload},{checkpointId:n??void 0,checkpointNs:r??void 0,edit:!0,originalMessageId:N.id,config:t.config,onEvent:f})},[c,e,n,r,t]);return{editingMessageId:g,editingInitialValue:v,inputError:k,setInputError:S,dismissError:E,setDismissError:j,composerValue:_,handleComposerChange:$,handleSendMessage:Z,handleQuickPrompt:X,handleExcelUpload:oe,startEditing:U,cancelEditing:F,handleRegenerateCb:G,displayMessages:m}}ne.ApiProvider=Kl,ne.ChatApi=Bl,ne.ChatApp=pC,ne.ChatContainer=Er,ne.ChatInput=_a,ne.ChatInputArea=ja,ne.ChatInputRow=ja,ne.ChatInterface=Er,ne.ChatMessagesArea=us,ne.ChatProviders=Wr,ne.ChatWidget=gC,ne.Composer=_a,ne.DEFAULT_TIMEOUT_MS=$l,ne.FileApi=Hl,ne.HISTORY_TIMEOUT_MS=Fl,ne.MarkdownContent=ro,ne.MessageComponent=ta,ne.MessageContent=Bd,ne.MessageList=us,ne.MessageRow=ra,ne.NewChatButton=xC,ne.SETTINGS_STORAGE_KEY=ai,ne.STORAGE_KEYS=En,ne.ThreadManager=Ds,ne.ThreadStateProvider=mc,ne.ThreadsProvider=tc,ne.ToolContent=Ka,ne.applySettings=Og,ne.chatApiClient=An,ne.cn=pp,ne.del=Zs,ne.draftKey=Ao,ne.extractToolContent=Br,ne.fileApiClient=Qs,ne.fileToBase64=ql,ne.formatToolOutput=eg,ne.get=Mt,ne.getChatToken=Xs,ne.getCurrentSettings=Pg,ne.getDefaultApiConfig=kc,ne.getDefaultChatSettings=Tc,ne.getMessageDomKey=na,ne.httpClient=It,ne.isEnvelope=Zl,ne.isFileLike=ti,ne.loadStoredSettings=Ec,ne.looksLikeMarkdown=nc,ne.normalizeToolPayload=ic,ne.normalizeToolPayloadValue=hr,ne.onChatTokenChanged=Js,ne.parseJsonSafe=dr,ne.post=Dr,ne.pretty=fr,ne.processAttachments=Gl,ne.put=zl,ne.sanitizeForDisplay=zr,ne.saveSettings=Ic,ne.setChatToken=In,ne.unwrap=At,ne.useApi=Vn,ne.useChatController=bC,ne.useHasChatSession=_g,ne.useShallowStableValue=vc,ne.useStream=ii,ne.useThreadHistoryState=dc,ne.useThreadManagerViewState=fp,ne.useThreadState=Ur,ne.useThreadStateUpdater=pc,ne.useThreads=ur,ne.useThreadsState=Ql,Object.defineProperty(ne,Symbol.toStringTag,{value:"Module"})});
131
131
  //# sourceMappingURL=index.umd.js.map